ScriptContext.cpp 220 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeBasePch.h"
  6. // Parser Includes
  7. #include "RegexCommon.h"
  8. #include "DebugWriter.h"
  9. #include "RegexStats.h"
  10. #include "ByteCode/ByteCodeApi.h"
  11. #include "Library/ProfileString.h"
  12. #include "Debug/DiagHelperMethodWrapper.h"
  13. #include "BackendApi.h"
  14. #if PROFILE_DICTIONARY
  15. #include "DictionaryStats.h"
  16. #endif
  17. #include "Base/ScriptContextProfiler.h"
  18. #include "Base/EtwTrace.h"
  19. #include "Language/InterpreterStackFrame.h"
  20. #include "Language/SourceDynamicProfileManager.h"
  21. #include "Language/JavascriptStackWalker.h"
  22. #include "Language/AsmJsTypes.h"
  23. #include "Language/AsmJsModule.h"
  24. #ifdef ASMJS_PLAT
  25. #include "Language/AsmJsEncoder.h"
  26. #include "Language/AsmJsCodeGenerator.h"
  27. #endif
  28. #ifdef ENABLE_BASIC_TELEMETRY
  29. #include "ScriptContextTelemetry.h"
  30. #endif
  31. namespace Js
  32. {
  33. ScriptContext * ScriptContext::New(ThreadContext * threadContext)
  34. {
  35. AutoPtr<ScriptContext> scriptContext(HeapNew(ScriptContext, threadContext));
  36. scriptContext->InitializeAllocations();
  37. return scriptContext.Detach();
  38. }
  39. void ScriptContext::Delete(ScriptContext* scriptContext)
  40. {
  41. HeapDelete(scriptContext);
  42. }
  43. ScriptContext::ScriptContext(ThreadContext* threadContext) :
  44. ScriptContextBase(),
  45. interpreterArena(nullptr),
  46. moduleSrcInfoCount(0),
  47. // Regex globals
  48. #if ENABLE_REGEX_CONFIG_OPTIONS
  49. regexStatsDatabase(0),
  50. regexDebugWriter(0),
  51. #endif
  52. trigramAlphabet(nullptr),
  53. regexStacks(nullptr),
  54. arrayMatchInit(false),
  55. config(threadContext->GetConfig(), threadContext->IsOptimizedForManyInstances()),
  56. #if ENABLE_BACKGROUND_PARSING
  57. backgroundParser(nullptr),
  58. #endif
  59. #if ENABLE_NATIVE_CODEGEN
  60. nativeCodeGen(nullptr),
  61. m_domFastPathHelperMap(nullptr),
  62. #endif
  63. threadContext(threadContext),
  64. scriptStartEventHandler(nullptr),
  65. scriptEndEventHandler(nullptr),
  66. #ifdef FAULT_INJECTION
  67. disposeScriptByFaultInjectionEventHandler(nullptr),
  68. #endif
  69. integerStringMap(this->GeneralAllocator()),
  70. guestArena(nullptr),
  71. raiseMessageToDebuggerFunctionType(nullptr),
  72. transitionToDebugModeIfFirstSourceFn(nullptr),
  73. sourceSize(0),
  74. deferredBody(false),
  75. isScriptContextActuallyClosed(false),
  76. isFinalized(false),
  77. isInvalidatedForHostObjects(false),
  78. fastDOMenabled(false),
  79. directHostTypeId(TypeIds_GlobalObject),
  80. isPerformingNonreentrantWork(false),
  81. isDiagnosticsScriptContext(false),
  82. m_enumerateNonUserFunctionsOnly(false),
  83. recycler(threadContext->EnsureRecycler()),
  84. CurrentThunk(DefaultEntryThunk),
  85. CurrentCrossSiteThunk(CrossSite::DefaultThunk),
  86. DeferredParsingThunk(DefaultDeferredParsingThunk),
  87. DeferredDeserializationThunk(DefaultDeferredDeserializeThunk),
  88. DispatchDefaultInvoke(nullptr),
  89. DispatchProfileInvoke(nullptr),
  90. m_pBuiltinFunctionIdMap(nullptr),
  91. diagnosticArena(nullptr),
  92. hostScriptContext(nullptr),
  93. scriptEngineHaltCallback(nullptr),
  94. #if DYNAMIC_INTERPRETER_THUNK
  95. interpreterThunkEmitter(nullptr),
  96. #endif
  97. #ifdef ASMJS_PLAT
  98. asmJsInterpreterThunkEmitter(nullptr),
  99. asmJsCodeGenerator(nullptr),
  100. #endif
  101. generalAllocator(_u("SC-General"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  102. #ifdef ENABLE_BASIC_TELEMETRY
  103. telemetryAllocator(_u("SC-Telemetry"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  104. #endif
  105. dynamicProfileInfoAllocator(_u("SC-DynProfileInfo"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  106. #ifdef SEPARATE_ARENA
  107. sourceCodeAllocator(_u("SC-Code"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  108. regexAllocator(_u("SC-Regex"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  109. #endif
  110. #ifdef NEED_MISC_ALLOCATOR
  111. miscAllocator(_u("GC-Misc"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  112. #endif
  113. inlineCacheAllocator(_u("SC-InlineCache"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  114. isInstInlineCacheAllocator(_u("SC-IsInstInlineCache"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  115. hasUsedInlineCache(false),
  116. hasProtoOrStoreFieldInlineCache(false),
  117. hasIsInstInlineCache(false),
  118. registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(nullptr),
  119. cache(nullptr),
  120. firstInterpreterFrameReturnAddress(nullptr),
  121. builtInLibraryFunctions(nullptr),
  122. m_remoteScriptContextAddr(0),
  123. isWeakReferenceDictionaryListCleared(false)
  124. #if ENABLE_PROFILE_INFO
  125. , referencesSharedDynamicSourceContextInfo(false)
  126. #endif
  127. #if DBG
  128. , isInitialized(false)
  129. , isCloningGlobal(false)
  130. , bindRef(MiscAllocator())
  131. #endif
  132. #if ENABLE_TTD
  133. , TTDHostCallbackFunctor()
  134. , TTDMode(TTD::TTDMode::Invalid)
  135. , ScriptContextLogTag(TTD_INVALID_LOG_PTR_ID)
  136. , TTDRootNestingCount(0)
  137. , TTDWellKnownInfo(nullptr)
  138. , TTDContextInfo(nullptr)
  139. #endif
  140. #ifdef REJIT_STATS
  141. , rejitStatsMap(nullptr)
  142. #endif
  143. #ifdef ENABLE_BASIC_TELEMETRY
  144. , telemetry(nullptr)
  145. #endif
  146. #ifdef INLINE_CACHE_STATS
  147. , cacheDataMap(nullptr)
  148. #endif
  149. #ifdef FIELD_ACCESS_STATS
  150. , fieldAccessStatsByFunctionNumber(nullptr)
  151. #endif
  152. , webWorkerId(Js::Constants::NonWebWorkerContextId)
  153. , url(_u(""))
  154. , startupComplete(false)
  155. , isEnumeratingRecyclerObjects(false)
  156. #ifdef EDIT_AND_CONTINUE
  157. , activeScriptEditQuery(nullptr)
  158. #endif
  159. #ifdef ENABLE_SCRIPT_PROFILING
  160. , heapEnum(nullptr)
  161. #endif
  162. #ifdef RECYCLER_PERF_COUNTERS
  163. , bindReferenceCount(0)
  164. #endif
  165. , nextPendingClose(nullptr)
  166. #ifdef ENABLE_SCRIPT_PROFILING
  167. , m_fTraceDomCall(FALSE)
  168. #endif
  169. , intConstPropsOnGlobalObject(nullptr)
  170. , intConstPropsOnGlobalUserObject(nullptr)
  171. #ifdef PROFILE_STRINGS
  172. , stringProfiler(nullptr)
  173. #endif
  174. #ifdef PROFILE_BAILOUT_RECORD_MEMORY
  175. , codeSize(0)
  176. , bailOutRecordBytes(0)
  177. , bailOutOffsetBytes(0)
  178. #endif
  179. , debugContext(nullptr)
  180. {
  181. // This may allocate memory and cause exception, but it is ok, as we all we have done so far
  182. // are field init and those dtor will be called if exception occurs
  183. threadContext->EnsureDebugManager();
  184. // Don't use throwing memory allocation in ctor, as exception in ctor doesn't cause the dtor to be called
  185. // potentially causing memory leaks
  186. BEGIN_NO_EXCEPTION;
  187. #ifdef RUNTIME_DATA_COLLECTION
  188. createTime = time(nullptr);
  189. #endif
  190. #ifdef BGJIT_STATS
  191. interpretedCount = maxFuncInterpret = funcJITCount = bytecodeJITCount = interpretedCallsHighPri = jitCodeUsed = funcJitCodeUsed = loopJITCount = speculativeJitCount = 0;
  192. #endif
  193. #ifdef PROFILE_TYPES
  194. convertNullToSimpleCount = 0;
  195. convertNullToSimpleDictionaryCount = 0;
  196. convertNullToDictionaryCount = 0;
  197. convertDeferredToDictionaryCount = 0;
  198. convertDeferredToSimpleDictionaryCount = 0;
  199. convertSimpleToDictionaryCount = 0;
  200. convertSimpleToSimpleDictionaryCount = 0;
  201. convertPathToDictionaryCount1 = 0;
  202. convertPathToDictionaryCount2 = 0;
  203. convertPathToDictionaryCount3 = 0;
  204. convertPathToDictionaryCount4 = 0;
  205. convertPathToSimpleDictionaryCount = 0;
  206. convertSimplePathToPathCount = 0;
  207. convertSimpleDictionaryToDictionaryCount = 0;
  208. convertSimpleSharedDictionaryToNonSharedCount = 0;
  209. convertSimpleSharedToNonSharedCount = 0;
  210. simplePathTypeHandlerCount = 0;
  211. pathTypeHandlerCount = 0;
  212. promoteCount = 0;
  213. cacheCount = 0;
  214. branchCount = 0;
  215. maxPathLength = 0;
  216. memset(typeCount, 0, sizeof(typeCount));
  217. memset(instanceCount, 0, sizeof(instanceCount));
  218. #endif
  219. #ifdef PROFILE_OBJECT_LITERALS
  220. objectLiteralInstanceCount = 0;
  221. objectLiteralPathCount = 0;
  222. memset(objectLiteralCount, 0, sizeof(objectLiteralCount));
  223. objectLiteralSimpleDictionaryCount = 0;
  224. objectLiteralMaxLength = 0;
  225. objectLiteralPromoteCount = 0;
  226. objectLiteralCacheCount = 0;
  227. objectLiteralBranchCount = 0;
  228. #endif
  229. #if DBG_DUMP
  230. byteCodeDataSize = 0;
  231. byteCodeAuxiliaryDataSize = 0;
  232. byteCodeAuxiliaryContextDataSize = 0;
  233. memset(byteCodeHistogram, 0, sizeof(byteCodeHistogram));
  234. #endif
  235. memset(propertyStrings, 0, sizeof(PropertyStringMap*)* 80);
  236. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  237. this->allocId = threadContext->GetUnreleasedScriptContextCount();
  238. #endif
  239. #if DBG
  240. this->hadProfiled = false;
  241. #endif
  242. #if DBG_DUMP
  243. forinCache = 0;
  244. forinNoCache = 0;
  245. #endif
  246. callCount = 0;
  247. threadContext->GetHiResTimer()->Reset();
  248. #ifdef PROFILE_EXEC
  249. profiler = nullptr;
  250. isProfilerCreated = false;
  251. disableProfiler = false;
  252. ensureParentInfo = false;
  253. #endif
  254. #ifdef PROFILE_MEM
  255. profileMemoryDump = true;
  256. #endif
  257. #ifdef ENABLE_SCRIPT_PROFILING
  258. m_pProfileCallback = nullptr;
  259. m_pProfileCallback2 = nullptr;
  260. m_inProfileCallback = FALSE;
  261. CleanupDocumentContext = nullptr;
  262. #endif
  263. // Do this after all operations that may cause potential exceptions
  264. threadContext->RegisterScriptContext(this);
  265. numberAllocator.Initialize(this->GetRecycler());
  266. #if DEBUG
  267. m_iProfileSession = -1;
  268. #endif
  269. #ifdef LEAK_REPORT
  270. this->urlRecord = nullptr;
  271. this->isRootTrackerScriptContext = false;
  272. #endif
  273. PERF_COUNTER_INC(Basic, ScriptContext);
  274. PERF_COUNTER_INC(Basic, ScriptContextActive);
  275. END_NO_EXCEPTION;
  276. }
  277. void ScriptContext::InitializeAllocations()
  278. {
  279. this->charClassifier = Anew(GeneralAllocator(), CharClassifier, this);
  280. this->valueOfInlineCache = AllocatorNewZ(InlineCacheAllocator, GetInlineCacheAllocator(), InlineCache);
  281. this->toStringInlineCache = AllocatorNewZ(InlineCacheAllocator, GetInlineCacheAllocator(), InlineCache);
  282. #ifdef REJIT_STATS
  283. if (PHASE_STATS1(Js::ReJITPhase))
  284. {
  285. rejitReasonCounts = AnewArrayZ(GeneralAllocator(), uint, NumRejitReasons);
  286. bailoutReasonCounts = Anew(GeneralAllocator(), BailoutStatsMap, GeneralAllocator());
  287. }
  288. #endif
  289. #ifdef ENABLE_BASIC_TELEMETRY
  290. this->telemetry = Anew(this->TelemetryAllocator(), ScriptContextTelemetry, *this);
  291. #endif
  292. #ifdef PROFILE_STRINGS
  293. if (Js::Configuration::Global.flags.ProfileStrings)
  294. {
  295. stringProfiler = Anew(MiscAllocator(), StringProfiler, threadContext->GetPageAllocator());
  296. }
  297. #endif
  298. intConstPropsOnGlobalObject = Anew(GeneralAllocator(), PropIdSetForConstProp, GeneralAllocator());
  299. intConstPropsOnGlobalUserObject = Anew(GeneralAllocator(), PropIdSetForConstProp, GeneralAllocator());
  300. #if ENABLE_NATIVE_CODEGEN
  301. m_domFastPathHelperMap = HeapNew(JITDOMFastPathHelperMap, &HeapAllocator::Instance, 17);
  302. #endif
  303. this->debugContext = HeapNew(DebugContext, this);
  304. }
  305. void ScriptContext::EnsureClearDebugDocument()
  306. {
  307. if (this->sourceList)
  308. {
  309. this->sourceList->Map([=](uint i, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef) {
  310. Js::Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
  311. if (sourceInfo)
  312. {
  313. sourceInfo->ClearDebugDocument();
  314. }
  315. });
  316. }
  317. }
  318. void ScriptContext::ShutdownClearSourceLists()
  319. {
  320. if (this->sourceList)
  321. {
  322. // In the unclean shutdown case, we might not have destroyed the script context when
  323. // this is called- in which case, skip doing this work and simply release the source list
  324. // so that it doesn't show up as a leak. Since we're doing unclean shutdown, it's ok to
  325. // skip cleanup here for expediency.
  326. if (this->isClosed)
  327. {
  328. this->MapFunction([this](Js::FunctionBody* functionBody) {
  329. Assert(functionBody->GetScriptContext() == this);
  330. functionBody->CleanupSourceInfo(true);
  331. });
  332. }
  333. EnsureClearDebugDocument();
  334. // Don't need the source list any more so ok to release
  335. this->sourceList.Unroot(this->GetRecycler());
  336. }
  337. if (this->calleeUtf8SourceInfoList)
  338. {
  339. this->calleeUtf8SourceInfoList.Unroot(this->GetRecycler());
  340. }
  341. }
  342. ScriptContext::~ScriptContext()
  343. {
  344. // Take etw rundown lock on this thread context. We are going to change/destroy this scriptContext.
  345. AutoCriticalSection autocs(GetThreadContext()->GetEtwRundownCriticalSection());
  346. #if ENABLE_NATIVE_CODEGEN
  347. if (m_domFastPathHelperMap != nullptr)
  348. {
  349. HeapDelete(m_domFastPathHelperMap);
  350. }
  351. if (m_remoteScriptContextAddr != 0)
  352. {
  353. Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
  354. JITManager::GetJITManager()->CleanupScriptContext(m_remoteScriptContextAddr);
  355. m_remoteScriptContextAddr = 0;
  356. }
  357. #endif
  358. // TODO: Can we move this on Close()?
  359. ClearHostScriptContext();
  360. if (this->hasProtoOrStoreFieldInlineCache)
  361. {
  362. // TODO (PersistentInlineCaches): It really isn't necessary to clear inline caches in all script contexts.
  363. // Since this script context is being destroyed, the inline cache arena will also go away and release its
  364. // memory back to the page allocator. Thus, we cannot leave this script context's inline caches on the
  365. // thread context's invalidation lists. However, it should suffice to remove this script context's caches
  366. // without touching other script contexts' caches. We could call some form of RemoveInlineCachesFromInvalidationLists()
  367. // on the inline cache allocator, which would walk all inline caches and zap values pointed to by strongRef.
  368. // clear out all inline caches to remove our proto inline caches from the thread context
  369. threadContext->ClearInlineCaches();
  370. ClearInlineCaches();
  371. Assert(!this->hasProtoOrStoreFieldInlineCache);
  372. }
  373. if (this->hasIsInstInlineCache)
  374. {
  375. // clear out all inline caches to remove our proto inline caches from the thread context
  376. threadContext->ClearIsInstInlineCaches();
  377. ClearIsInstInlineCaches();
  378. Assert(!this->hasIsInstInlineCache);
  379. }
  380. // Only call RemoveFromPendingClose if we are in a pending close state.
  381. if (isClosed && !isScriptContextActuallyClosed)
  382. {
  383. threadContext->RemoveFromPendingClose(this);
  384. }
  385. SetIsClosed();
  386. bool closed = Close(true);
  387. // JIT may access number allocator. Need to close the script context first,
  388. // which will close the native code generator and abort any current job on this generator.
  389. numberAllocator.Uninitialize();
  390. ShutdownClearSourceLists();
  391. if (regexStacks)
  392. {
  393. Adelete(RegexAllocator(), regexStacks);
  394. regexStacks = nullptr;
  395. }
  396. if (javascriptLibrary != nullptr)
  397. {
  398. javascriptLibrary->scriptContext = nullptr;
  399. javascriptLibrary = nullptr;
  400. if (closed)
  401. {
  402. // if we just closed, we haven't unpin the object yet.
  403. // We need to null out the script context in the global object first
  404. // before we unpin the global object so that script context dtor doesn't get called twice
  405. #if ENABLE_NATIVE_CODEGEN
  406. Assert(this->IsClosedNativeCodeGenerator());
  407. #endif
  408. if (!GetThreadContext()->IsJSRT())
  409. {
  410. this->recycler->RootRelease(globalObject);
  411. }
  412. }
  413. }
  414. #if ENABLE_BACKGROUND_PARSING
  415. if (this->backgroundParser != nullptr)
  416. {
  417. BackgroundParser::Delete(this->backgroundParser);
  418. this->backgroundParser = nullptr;
  419. }
  420. #endif
  421. #if ENABLE_NATIVE_CODEGEN
  422. if (this->nativeCodeGen != nullptr)
  423. {
  424. DeleteNativeCodeGenerator(this->nativeCodeGen);
  425. nativeCodeGen = NULL;
  426. }
  427. #endif
  428. #if DYNAMIC_INTERPRETER_THUNK
  429. if (this->interpreterThunkEmitter != nullptr)
  430. {
  431. HeapDelete(interpreterThunkEmitter);
  432. this->interpreterThunkEmitter = NULL;
  433. }
  434. #endif
  435. #ifdef ASMJS_PLAT
  436. if (this->asmJsInterpreterThunkEmitter != nullptr)
  437. {
  438. HeapDelete(asmJsInterpreterThunkEmitter);
  439. this->asmJsInterpreterThunkEmitter = nullptr;
  440. }
  441. if (this->asmJsCodeGenerator != nullptr)
  442. {
  443. HeapDelete(asmJsCodeGenerator);
  444. this->asmJsCodeGenerator = NULL;
  445. }
  446. #endif
  447. // In case there is something added to the list between close and dtor, just reset the list again
  448. this->weakReferenceDictionaryList.Reset();
  449. PERF_COUNTER_DEC(Basic, ScriptContext);
  450. }
  451. void ScriptContext::SetUrl(BSTR bstrUrl)
  452. {
  453. // Assumption: this method is never called multiple times
  454. Assert(this->url != nullptr && wcslen(this->url) == 0);
  455. charcount_t length = SysStringLen(bstrUrl) + 1; // Add 1 for the NULL.
  456. char16* urlCopy = AnewArray(this->GeneralAllocator(), char16, length);
  457. js_memcpy_s(urlCopy, (length - 1) * sizeof(char16), bstrUrl, (length - 1) * sizeof(char16));
  458. urlCopy[length - 1] = _u('\0');
  459. this->url = urlCopy;
  460. #ifdef LEAK_REPORT
  461. if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
  462. {
  463. this->urlRecord = LeakReport::LogUrl(urlCopy, this->globalObject);
  464. }
  465. #endif
  466. }
  467. uint ScriptContext::GetNextSourceContextId()
  468. {
  469. Assert(this->cache);
  470. Assert(this->cache->sourceContextInfoMap ||
  471. this->cache->dynamicSourceContextInfoMap);
  472. uint nextSourceContextId = 0;
  473. if (this->cache->sourceContextInfoMap)
  474. {
  475. nextSourceContextId = this->cache->sourceContextInfoMap->Count();
  476. }
  477. if (this->cache->dynamicSourceContextInfoMap)
  478. {
  479. nextSourceContextId += this->cache->dynamicSourceContextInfoMap->Count();
  480. }
  481. return nextSourceContextId + 1;
  482. }
  483. // Do most of the Close() work except the final release which could delete the scriptContext.
  484. void ScriptContext::InternalClose()
  485. {
  486. this->PrintStats();
  487. isScriptContextActuallyClosed = true;
  488. PERF_COUNTER_DEC(Basic, ScriptContextActive);
  489. #if DBG_DUMP
  490. if (Js::Configuration::Global.flags.TraceWin8Allocations)
  491. {
  492. Output::Print(_u("MemoryTrace: ScriptContext Close\n"));
  493. Output::Flush();
  494. }
  495. #endif
  496. #ifdef ENABLE_JS_ETW
  497. EventWriteJSCRIPT_HOST_SCRIPT_CONTEXT_CLOSE(this);
  498. #endif
  499. #if ENABLE_TTD
  500. if(this->TTDWellKnownInfo != nullptr)
  501. {
  502. TT_HEAP_DELETE(TTD::RuntimeContextInfo, this->TTDWellKnownInfo);
  503. this->TTDWellKnownInfo = nullptr;
  504. }
  505. if(this->TTDContextInfo != nullptr)
  506. {
  507. TT_HEAP_DELETE(TTD::ScriptContextTTD, this->TTDContextInfo);
  508. this->TTDContextInfo = nullptr;
  509. }
  510. #endif
  511. #if ENABLE_PROFILE_INFO
  512. HRESULT hr = S_OK;
  513. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  514. {
  515. DynamicProfileInfo::Save(this);
  516. }
  517. END_TRANSLATE_OOM_TO_HRESULT(hr);
  518. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  519. this->ClearDynamicProfileList();
  520. #endif
  521. #endif
  522. #if ENABLE_NATIVE_CODEGEN
  523. if (nativeCodeGen != nullptr)
  524. {
  525. Assert(!isInitialized || this->globalObject != nullptr);
  526. CloseNativeCodeGenerator(this->nativeCodeGen);
  527. }
  528. #endif
  529. if (this->fakeGlobalFuncForUndefer)
  530. {
  531. this->fakeGlobalFuncForUndefer->Cleanup(true);
  532. this->fakeGlobalFuncForUndefer.Unroot(this->GetRecycler());
  533. }
  534. if (this->sourceList)
  535. {
  536. bool hasFunctions = false;
  537. this->sourceList->MapUntil([&hasFunctions](int, RecyclerWeakReference<Utf8SourceInfo>* sourceInfoWeakRef) -> bool
  538. {
  539. Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
  540. if (sourceInfo)
  541. {
  542. hasFunctions = sourceInfo->HasFunctions();
  543. }
  544. return hasFunctions;
  545. });
  546. if (hasFunctions)
  547. {
  548. // We still need to walk through all the function bodies and call cleanup
  549. // because otherwise ETW events might not get fired if a GC doesn't happen
  550. // and the thread context isn't shut down cleanly (process detach case)
  551. this->MapFunction([this](Js::FunctionBody* functionBody) {
  552. Assert(functionBody->GetScriptContext() == nullptr || functionBody->GetScriptContext() == this);
  553. functionBody->Cleanup(/* isScriptContextClosing */ true);
  554. });
  555. }
  556. }
  557. JS_ETW(EtwTrace::LogSourceUnloadEvents(this));
  558. this->GetThreadContext()->SubSourceSize(this->GetSourceSize());
  559. #if DYNAMIC_INTERPRETER_THUNK
  560. if (this->interpreterThunkEmitter != nullptr)
  561. {
  562. this->interpreterThunkEmitter->Close();
  563. }
  564. #endif
  565. #ifdef ASMJS_PLAT
  566. if (this->asmJsInterpreterThunkEmitter != nullptr)
  567. {
  568. this->asmJsInterpreterThunkEmitter->Close();
  569. }
  570. #endif
  571. #ifdef ENABLE_SCRIPT_PROFILING
  572. // Stop profiling if present
  573. DeRegisterProfileProbe(S_OK, nullptr);
  574. #endif
  575. if (this->diagnosticArena != nullptr)
  576. {
  577. HeapDelete(this->diagnosticArena);
  578. this->diagnosticArena = nullptr;
  579. }
  580. if (this->debugContext != nullptr)
  581. {
  582. // Guard the closing and deleting of DebugContext as in meantime PDM might
  583. // call OnBreakFlagChange
  584. AutoCriticalSection autoDebugContextCloseCS(&debugContextCloseCS);
  585. this->debugContext->Close();
  586. HeapDelete(this->debugContext);
  587. this->debugContext = nullptr;
  588. }
  589. // Need to print this out before the native code gen is deleted
  590. // which will delete the codegenProfiler
  591. #ifdef PROFILE_EXEC
  592. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  593. {
  594. if (isProfilerCreated)
  595. {
  596. this->ProfilePrint();
  597. }
  598. if (profiler != nullptr)
  599. {
  600. profiler->Release();
  601. profiler = nullptr;
  602. }
  603. }
  604. #endif
  605. #if ENABLE_PROFILE_INFO
  606. // Release this only after native code gen is shut down, as there may be
  607. // profile info allocated from the SourceDynamicProfileManager arena.
  608. // The first condition might not be true if the dynamic functions have already been freed by the time
  609. // ScriptContext closes
  610. if (referencesSharedDynamicSourceContextInfo)
  611. {
  612. // For the host provided dynamic code, we may not have added any dynamic context to the dynamicSourceContextInfoMap
  613. Assert(this->GetDynamicSourceContextInfoMap() != nullptr);
  614. this->GetThreadContext()->ReleaseSourceDynamicProfileManagers(this->GetUrl());
  615. }
  616. #endif
  617. RECYCLER_PERF_COUNTER_SUB(BindReference, bindReferenceCount);
  618. if (this->interpreterArena)
  619. {
  620. ReleaseInterpreterArena();
  621. interpreterArena = nullptr;
  622. }
  623. if (this->guestArena)
  624. {
  625. ReleaseGuestArena();
  626. guestArena = nullptr;
  627. }
  628. cache = nullptr;
  629. builtInLibraryFunctions = nullptr;
  630. pActiveScriptDirect = nullptr;
  631. isWeakReferenceDictionaryListCleared = true;
  632. this->weakReferenceDictionaryList.Clear(this->GeneralAllocator());
  633. // This can be null if the script context initialization threw
  634. // and InternalClose gets called in the destructor code path
  635. if (javascriptLibrary != nullptr)
  636. {
  637. javascriptLibrary->CleanupForClose();
  638. javascriptLibrary->Uninitialize();
  639. }
  640. if (registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext != nullptr)
  641. {
  642. // UnregisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext may throw, set up the correct state first
  643. ScriptContext ** registeredScriptContext = registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext;
  644. ClearPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesCaches();
  645. Assert(registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext == nullptr);
  646. threadContext->UnregisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(registeredScriptContext);
  647. }
  648. threadContext->ReleaseDebugManager();
  649. }
  650. bool ScriptContext::Close(bool inDestructor)
  651. {
  652. if (isScriptContextActuallyClosed)
  653. return false;
  654. // Limit the lock scope. We require the same lock in ~ScriptContext(), which may be called next.
  655. {
  656. // Take etw rundown lock on this thread context. We are going to change this scriptContext.
  657. AutoCriticalSection autocs(GetThreadContext()->GetEtwRundownCriticalSection());
  658. InternalClose();
  659. }
  660. if (!inDestructor && globalObject != nullptr)
  661. {
  662. //A side effect of releasing globalObject that this script context could be deleted, so the release call here
  663. //must be the last thing in close.
  664. #if ENABLE_NATIVE_CODEGEN
  665. Assert(this->IsClosedNativeCodeGenerator());
  666. #endif
  667. if (!GetThreadContext()->IsJSRT())
  668. {
  669. GetRecycler()->RootRelease(globalObject);
  670. }
  671. }
  672. // A script context closing is a signal to the thread context that it
  673. // needs to do an idle GC independent of what the heuristics are
  674. this->threadContext->SetForceOneIdleCollection();
  675. return true;
  676. }
  677. PropertyString* ScriptContext::GetPropertyString2(char16 ch1, char16 ch2)
  678. {
  679. if (ch1 < '0' || ch1 > 'z' || ch2 < '0' || ch2 > 'z')
  680. {
  681. return NULL;
  682. }
  683. const uint i = PropertyStringMap::PStrMapIndex(ch1);
  684. if (propertyStrings[i] == NULL)
  685. {
  686. return NULL;
  687. }
  688. const uint j = PropertyStringMap::PStrMapIndex(ch2);
  689. return propertyStrings[i]->strLen2[j];
  690. }
  691. void ScriptContext::FindPropertyRecord(JavascriptString *pstName, PropertyRecord const ** propertyRecord)
  692. {
  693. threadContext->FindPropertyRecord(pstName, propertyRecord);
  694. }
  695. void ScriptContext::FindPropertyRecord(__in LPCWSTR propertyName, __in int propertyNameLength, PropertyRecord const ** propertyRecord)
  696. {
  697. threadContext->FindPropertyRecord(propertyName, propertyNameLength, propertyRecord);
  698. }
  699. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>* ScriptContext::FindPropertyIdNoCase(__in LPCWSTR propertyName, __in int propertyNameLength)
  700. {
  701. return threadContext->FindPropertyIdNoCase(this, propertyName, propertyNameLength);
  702. }
  703. PropertyId ScriptContext::GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName)
  704. {
  705. Js::PropertyRecord const * propertyRecord;
  706. threadContext->GetOrAddPropertyId(propName, &propertyRecord);
  707. this->TrackPid(propertyRecord);
  708. return propertyRecord->GetPropertyId();
  709. }
  710. void ScriptContext::GetOrAddPropertyRecord(JsUtil::CharacterBuffer<WCHAR> const& propertyName, PropertyRecord const ** propertyRecord)
  711. {
  712. threadContext->GetOrAddPropertyId(propertyName, propertyRecord);
  713. }
  714. PropertyId ScriptContext::GetOrAddPropertyIdTracked(__in_ecount(propertyNameLength) LPCWSTR propertyName, __in int propertyNameLength)
  715. {
  716. Js::PropertyRecord const * propertyRecord;
  717. threadContext->GetOrAddPropertyId(propertyName, propertyNameLength, &propertyRecord);
  718. if (propertyNameLength == 2)
  719. {
  720. CachePropertyString2(propertyRecord);
  721. }
  722. this->TrackPid(propertyRecord);
  723. return propertyRecord->GetPropertyId();
  724. }
  725. void ScriptContext::GetOrAddPropertyRecord(__in_ecount(propertyNameLength) LPCWSTR propertyName, __in int propertyNameLength, PropertyRecord const ** propertyRecord)
  726. {
  727. threadContext->GetOrAddPropertyId(propertyName, propertyNameLength, propertyRecord);
  728. if (propertyNameLength == 2)
  729. {
  730. CachePropertyString2(*propertyRecord);
  731. }
  732. }
  733. BOOL ScriptContext::IsNumericPropertyId(PropertyId propertyId, uint32* value)
  734. {
  735. BOOL isNumericPropertyId = threadContext->IsNumericPropertyId(propertyId, value);
  736. #if DEBUG
  737. PropertyRecord const * name = this->GetPropertyName(propertyId);
  738. if (name != nullptr)
  739. {
  740. // Symbol properties are not numeric - description should not be used.
  741. if (name->IsSymbol())
  742. {
  743. return false;
  744. }
  745. uint32 index;
  746. BOOL isIndex = JavascriptArray::GetIndex(name->GetBuffer(), &index);
  747. if (isNumericPropertyId != isIndex)
  748. {
  749. // WOOB 1137798: JavascriptArray::GetIndex does not handle embedded NULLs. So if we have a property
  750. // name "1234\0", JavascriptArray::GetIndex would incorrectly accepts it as an array index property
  751. // name.
  752. Assert((size_t)(name->GetLength()) != wcslen(name->GetBuffer()));
  753. }
  754. else if (isNumericPropertyId)
  755. {
  756. Assert((uint32)*value == index);
  757. }
  758. }
  759. #endif
  760. return isNumericPropertyId;
  761. }
  762. void ScriptContext::RegisterWeakReferenceDictionary(JsUtil::IWeakReferenceDictionary* weakReferenceDictionary)
  763. {
  764. this->weakReferenceDictionaryList.Prepend(this->GeneralAllocator(), weakReferenceDictionary);
  765. }
  766. RecyclableObject *ScriptContext::GetMissingPropertyResult()
  767. {
  768. return GetLibrary()->GetUndefined();
  769. }
  770. RecyclableObject *ScriptContext::GetMissingItemResult()
  771. {
  772. return GetLibrary()->GetUndefined();
  773. }
  774. SRCINFO *ScriptContext::AddHostSrcInfo(SRCINFO const *pSrcInfo)
  775. {
  776. Assert(pSrcInfo != nullptr);
  777. return RecyclerNewZ(this->GetRecycler(), SRCINFO, *pSrcInfo);
  778. }
  779. #ifdef PROFILE_TYPES
  780. void ScriptContext::ProfileTypes()
  781. {
  782. Output::Print(_u("===============================================================================\n"));
  783. Output::Print(_u("Types Profile\n"));
  784. Output::Print(_u("-------------------------------------------------------------------------------\n"));
  785. Output::Print(_u("Dynamic Type Conversions:\n"));
  786. Output::Print(_u(" Null to Simple %8d\n"), convertNullToSimpleCount);
  787. Output::Print(_u(" Deferred to SimpleMap %8d\n"), convertDeferredToSimpleDictionaryCount);
  788. Output::Print(_u(" Simple to Map %8d\n"), convertSimpleToDictionaryCount);
  789. Output::Print(_u(" Simple to SimpleMap %8d\n"), convertSimpleToSimpleDictionaryCount);
  790. Output::Print(_u(" Path to SimpleMap (set) %8d\n"), convertPathToDictionaryCount1);
  791. Output::Print(_u(" Path to SimpleMap (delete) %8d\n"), convertPathToDictionaryCount2);
  792. Output::Print(_u(" Path to SimpleMap (attribute) %8d\n"), convertPathToDictionaryCount3);
  793. Output::Print(_u(" Path to SimpleMap %8d\n"), convertPathToSimpleDictionaryCount);
  794. Output::Print(_u(" SimplePath to Path %8d\n"), convertSimplePathToPathCount);
  795. Output::Print(_u(" Shared SimpleMap to non-shared %8d\n"), convertSimpleSharedDictionaryToNonSharedCount);
  796. Output::Print(_u(" Deferred to Map %8d\n"), convertDeferredToDictionaryCount);
  797. Output::Print(_u(" Path to Map (accessor) %8d\n"), convertPathToDictionaryCount4);
  798. Output::Print(_u(" SimpleMap to Map %8d\n"), convertSimpleDictionaryToDictionaryCount);
  799. Output::Print(_u(" Path Cache Hits %8d\n"), cacheCount);
  800. Output::Print(_u(" Path Branches %8d\n"), branchCount);
  801. Output::Print(_u(" Path Promotions %8d\n"), promoteCount);
  802. Output::Print(_u(" Path Length (max) %8d\n"), maxPathLength);
  803. Output::Print(_u(" SimplePathTypeHandlers %8d\n"), simplePathTypeHandlerCount);
  804. Output::Print(_u(" PathTypeHandlers %8d\n"), pathTypeHandlerCount);
  805. Output::Print(_u("\n"));
  806. Output::Print(_u("Type Statistics: %8s %8s\n"), _u("Types"), _u("Instances"));
  807. Output::Print(_u(" Undefined %8d %8d\n"), typeCount[TypeIds_Undefined], instanceCount[TypeIds_Undefined]);
  808. Output::Print(_u(" Null %8d %8d\n"), typeCount[TypeIds_Null], instanceCount[TypeIds_Null]);
  809. Output::Print(_u(" Boolean %8d %8d\n"), typeCount[TypeIds_Boolean], instanceCount[TypeIds_Boolean]);
  810. Output::Print(_u(" Integer %8d %8d\n"), typeCount[TypeIds_Integer], instanceCount[TypeIds_Integer]);
  811. Output::Print(_u(" Number %8d %8d\n"), typeCount[TypeIds_Number], instanceCount[TypeIds_Number]);
  812. Output::Print(_u(" String %8d %8d\n"), typeCount[TypeIds_String], instanceCount[TypeIds_String]);
  813. Output::Print(_u(" Object %8d %8d\n"), typeCount[TypeIds_Object], instanceCount[TypeIds_Object]);
  814. Output::Print(_u(" Function %8d %8d\n"), typeCount[TypeIds_Function], instanceCount[TypeIds_Function]);
  815. Output::Print(_u(" Array %8d %8d\n"), typeCount[TypeIds_Array], instanceCount[TypeIds_Array]);
  816. Output::Print(_u(" Date %8d %8d\n"), typeCount[TypeIds_Date], instanceCount[TypeIds_Date] + instanceCount[TypeIds_WinRTDate]);
  817. Output::Print(_u(" Symbol %8d %8d\n"), typeCount[TypeIds_Symbol], instanceCount[TypeIds_Symbol]);
  818. Output::Print(_u(" RegEx %8d %8d\n"), typeCount[TypeIds_RegEx], instanceCount[TypeIds_RegEx]);
  819. Output::Print(_u(" Error %8d %8d\n"), typeCount[TypeIds_Error], instanceCount[TypeIds_Error]);
  820. Output::Print(_u(" Proxy %8d %8d\n"), typeCount[TypeIds_Proxy], instanceCount[TypeIds_Proxy]);
  821. Output::Print(_u(" BooleanObject %8d %8d\n"), typeCount[TypeIds_BooleanObject], instanceCount[TypeIds_BooleanObject]);
  822. Output::Print(_u(" NumberObject %8d %8d\n"), typeCount[TypeIds_NumberObject], instanceCount[TypeIds_NumberObject]);
  823. Output::Print(_u(" StringObject %8d %8d\n"), typeCount[TypeIds_StringObject], instanceCount[TypeIds_StringObject]);
  824. Output::Print(_u(" SymbolObject %8d %8d\n"), typeCount[TypeIds_SymbolObject], instanceCount[TypeIds_SymbolObject]);
  825. Output::Print(_u(" GlobalObject %8d %8d\n"), typeCount[TypeIds_GlobalObject], instanceCount[TypeIds_GlobalObject]);
  826. Output::Print(_u(" Enumerator %8d %8d\n"), typeCount[TypeIds_Enumerator], instanceCount[TypeIds_Enumerator]);
  827. Output::Print(_u(" Int8Array %8d %8d\n"), typeCount[TypeIds_Int8Array], instanceCount[TypeIds_Int8Array]);
  828. Output::Print(_u(" Uint8Array %8d %8d\n"), typeCount[TypeIds_Uint8Array], instanceCount[TypeIds_Uint8Array]);
  829. Output::Print(_u(" Uint8ClampedArray %8d %8d\n"), typeCount[TypeIds_Uint8ClampedArray], instanceCount[TypeIds_Uint8ClampedArray]);
  830. Output::Print(_u(" Int16Array %8d %8d\n"), typeCount[TypeIds_Int16Array], instanceCount[TypeIds_Int16Array]);
  831. Output::Print(_u(" Int16Array %8d %8d\n"), typeCount[TypeIds_Uint16Array], instanceCount[TypeIds_Uint16Array]);
  832. Output::Print(_u(" Int32Array %8d %8d\n"), typeCount[TypeIds_Int32Array], instanceCount[TypeIds_Int32Array]);
  833. Output::Print(_u(" Uint32Array %8d %8d\n"), typeCount[TypeIds_Uint32Array], instanceCount[TypeIds_Uint32Array]);
  834. Output::Print(_u(" Float32Array %8d %8d\n"), typeCount[TypeIds_Float32Array], instanceCount[TypeIds_Float32Array]);
  835. Output::Print(_u(" Float64Array %8d %8d\n"), typeCount[TypeIds_Float64Array], instanceCount[TypeIds_Float64Array]);
  836. Output::Print(_u(" DataView %8d %8d\n"), typeCount[TypeIds_DataView], instanceCount[TypeIds_DataView]);
  837. Output::Print(_u(" ModuleRoot %8d %8d\n"), typeCount[TypeIds_ModuleRoot], instanceCount[TypeIds_ModuleRoot]);
  838. Output::Print(_u(" HostObject %8d %8d\n"), typeCount[TypeIds_HostObject], instanceCount[TypeIds_HostObject]);
  839. Output::Print(_u(" VariantDate %8d %8d\n"), typeCount[TypeIds_VariantDate], instanceCount[TypeIds_VariantDate]);
  840. Output::Print(_u(" HostDispatch %8d %8d\n"), typeCount[TypeIds_HostDispatch], instanceCount[TypeIds_HostDispatch]);
  841. Output::Print(_u(" Arguments %8d %8d\n"), typeCount[TypeIds_Arguments], instanceCount[TypeIds_Arguments]);
  842. Output::Print(_u(" ActivationObject %8d %8d\n"), typeCount[TypeIds_ActivationObject], instanceCount[TypeIds_ActivationObject]);
  843. Output::Print(_u(" Map %8d %8d\n"), typeCount[TypeIds_Map], instanceCount[TypeIds_Map]);
  844. Output::Print(_u(" Set %8d %8d\n"), typeCount[TypeIds_Set], instanceCount[TypeIds_Set]);
  845. Output::Print(_u(" WeakMap %8d %8d\n"), typeCount[TypeIds_WeakMap], instanceCount[TypeIds_WeakMap]);
  846. Output::Print(_u(" WeakSet %8d %8d\n"), typeCount[TypeIds_WeakSet], instanceCount[TypeIds_WeakSet]);
  847. Output::Print(_u(" ArrayIterator %8d %8d\n"), typeCount[TypeIds_ArrayIterator], instanceCount[TypeIds_ArrayIterator]);
  848. Output::Print(_u(" MapIterator %8d %8d\n"), typeCount[TypeIds_MapIterator], instanceCount[TypeIds_MapIterator]);
  849. Output::Print(_u(" SetIterator %8d %8d\n"), typeCount[TypeIds_SetIterator], instanceCount[TypeIds_SetIterator]);
  850. Output::Print(_u(" StringIterator %8d %8d\n"), typeCount[TypeIds_StringIterator], instanceCount[TypeIds_StringIterator]);
  851. Output::Print(_u(" Generator %8d %8d\n"), typeCount[TypeIds_Generator], instanceCount[TypeIds_Generator]);
  852. #if !DBG
  853. Output::Print(_u(" ** Instance statistics only available on debug builds...\n"));
  854. #endif
  855. Output::Flush();
  856. }
  857. #endif
  858. #ifdef PROFILE_OBJECT_LITERALS
  859. void ScriptContext::ProfileObjectLiteral()
  860. {
  861. Output::Print(_u("===============================================================================\n"));
  862. Output::Print(_u(" Object Lit Instances created.. %d\n"), objectLiteralInstanceCount);
  863. Output::Print(_u(" Object Lit Path Types......... %d\n"), objectLiteralPathCount);
  864. Output::Print(_u(" Object Lit Simple Map......... %d\n"), objectLiteralSimpleDictionaryCount);
  865. Output::Print(_u(" Object Lit Max # of properties %d\n"), objectLiteralMaxLength);
  866. Output::Print(_u(" Object Lit Promote count...... %d\n"), objectLiteralPromoteCount);
  867. Output::Print(_u(" Object Lit Cache Hits......... %d\n"), objectLiteralCacheCount);
  868. Output::Print(_u(" Object Lit Branch count....... %d\n"), objectLiteralBranchCount);
  869. for (int i = 0; i < TypePath::MaxPathTypeHandlerLength; i++)
  870. {
  871. if (objectLiteralCount[i] != 0)
  872. {
  873. Output::Print(_u(" Object Lit properties [ %2d] .. %d\n"), i, objectLiteralCount[i]);
  874. }
  875. }
  876. Output::Flush();
  877. }
  878. #endif
  879. //
  880. // Regex helpers
  881. //
  882. #if ENABLE_REGEX_CONFIG_OPTIONS
  883. UnifiedRegex::RegexStatsDatabase* ScriptContext::GetRegexStatsDatabase()
  884. {
  885. if (regexStatsDatabase == 0)
  886. {
  887. ArenaAllocator* allocator = MiscAllocator();
  888. regexStatsDatabase = Anew(allocator, UnifiedRegex::RegexStatsDatabase, allocator);
  889. }
  890. return regexStatsDatabase;
  891. }
  892. UnifiedRegex::DebugWriter* ScriptContext::GetRegexDebugWriter()
  893. {
  894. if (regexDebugWriter == 0)
  895. {
  896. ArenaAllocator* allocator = MiscAllocator();
  897. regexDebugWriter = Anew(allocator, UnifiedRegex::DebugWriter);
  898. }
  899. return regexDebugWriter;
  900. }
  901. #endif
  902. bool ScriptContext::DoUndeferGlobalFunctions() const
  903. {
  904. return CONFIG_FLAG(DeferTopLevelTillFirstCall) && !AutoSystemInfo::Data.IsLowMemoryProcess();
  905. }
  906. RegexPatternMruMap* ScriptContext::GetDynamicRegexMap() const
  907. {
  908. Assert(!isScriptContextActuallyClosed);
  909. Assert(cache);
  910. Assert(cache->dynamicRegexMap);
  911. return cache->dynamicRegexMap;
  912. }
  913. void ScriptContext::SetTrigramAlphabet(UnifiedRegex::TrigramAlphabet * trigramAlphabet)
  914. {
  915. this->trigramAlphabet = trigramAlphabet;
  916. }
  917. UnifiedRegex::RegexStacks *ScriptContext::RegexStacks()
  918. {
  919. UnifiedRegex::RegexStacks * stacks = regexStacks;
  920. if (stacks)
  921. {
  922. return stacks;
  923. }
  924. return AllocRegexStacks();
  925. }
  926. UnifiedRegex::RegexStacks * ScriptContext::AllocRegexStacks()
  927. {
  928. Assert(this->regexStacks == nullptr);
  929. UnifiedRegex::RegexStacks * stacks = Anew(RegexAllocator(), UnifiedRegex::RegexStacks, threadContext->GetPageAllocator());
  930. this->regexStacks = stacks;
  931. return stacks;
  932. }
  933. UnifiedRegex::RegexStacks *ScriptContext::SaveRegexStacks()
  934. {
  935. Assert(regexStacks);
  936. const auto saved = regexStacks;
  937. regexStacks = nullptr;
  938. return saved;
  939. }
  940. void ScriptContext::RestoreRegexStacks(UnifiedRegex::RegexStacks *const stacks)
  941. {
  942. Assert(stacks);
  943. Assert(stacks != regexStacks);
  944. if (regexStacks)
  945. {
  946. Adelete(RegexAllocator(), regexStacks);
  947. }
  948. regexStacks = stacks;
  949. }
  950. Js::TempArenaAllocatorObject* ScriptContext::GetTemporaryAllocator(LPCWSTR name)
  951. {
  952. return this->threadContext->GetTemporaryAllocator(name);
  953. }
  954. void ScriptContext::ReleaseTemporaryAllocator(Js::TempArenaAllocatorObject* tempAllocator)
  955. {
  956. AssertMsg(tempAllocator != nullptr, "tempAllocator should not be null");
  957. this->threadContext->ReleaseTemporaryAllocator(tempAllocator);
  958. }
  959. Js::TempGuestArenaAllocatorObject* ScriptContext::GetTemporaryGuestAllocator(LPCWSTR name)
  960. {
  961. return this->threadContext->GetTemporaryGuestAllocator(name);
  962. }
  963. void ScriptContext::ReleaseTemporaryGuestAllocator(Js::TempGuestArenaAllocatorObject* tempGuestAllocator)
  964. {
  965. AssertMsg(tempGuestAllocator != nullptr, "tempAllocator should not be null");
  966. this->threadContext->ReleaseTemporaryGuestAllocator(tempGuestAllocator);
  967. }
  968. void ScriptContext::InitializeCache()
  969. {
  970. this->cache = RecyclerNewFinalized(recycler, Cache);
  971. this->javascriptLibrary->scriptContextCache = this->cache;
  972. this->cache->dynamicRegexMap =
  973. RegexPatternMruMap::New(
  974. recycler,
  975. REGEX_CONFIG_FLAG(DynamicRegexMruListSize) <= 0 ? 16 : REGEX_CONFIG_FLAG(DynamicRegexMruListSize));
  976. SourceContextInfo* sourceContextInfo = RecyclerNewStructZ(this->GetRecycler(), SourceContextInfo);
  977. sourceContextInfo->dwHostSourceContext = Js::Constants::NoHostSourceContext;
  978. sourceContextInfo->isHostDynamicDocument = false;
  979. sourceContextInfo->sourceContextId = Js::Constants::NoSourceContext;
  980. this->cache->noContextSourceContextInfo = sourceContextInfo;
  981. SRCINFO* srcInfo = RecyclerNewStructZ(this->GetRecycler(), SRCINFO);
  982. srcInfo->sourceContextInfo = this->cache->noContextSourceContextInfo;
  983. srcInfo->moduleID = kmodGlobal;
  984. this->cache->noContextGlobalSourceInfo = srcInfo;
  985. }
  986. void ScriptContext::InitializePreGlobal()
  987. {
  988. this->guestArena = this->GetRecycler()->CreateGuestArena(_u("Guest"), Throw::OutOfMemory);
  989. #if ENABLE_PROFILE_INFO
  990. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  991. if (DynamicProfileInfo::NeedProfileInfoList())
  992. {
  993. this->profileInfoList.Root(RecyclerNew(this->GetRecycler(), SListBase<DynamicProfileInfo *>), recycler);
  994. }
  995. #endif
  996. #endif
  997. #if ENABLE_BACKGROUND_PARSING
  998. if (PHASE_ON1(Js::ParallelParsePhase))
  999. {
  1000. this->backgroundParser = BackgroundParser::New(this);
  1001. }
  1002. #endif
  1003. #if ENABLE_NATIVE_CODEGEN
  1004. // Create the native code gen before the profiler
  1005. this->nativeCodeGen = NewNativeCodeGenerator(this);
  1006. #endif
  1007. #ifdef PROFILE_EXEC
  1008. this->CreateProfiler();
  1009. #endif
  1010. this->operationStack = Anew(GeneralAllocator(), JsUtil::Stack<Var>, GeneralAllocator());
  1011. Tick::InitType();
  1012. }
  1013. void ScriptContext::Initialize()
  1014. {
  1015. SmartFPUControl defaultControl;
  1016. InitializePreGlobal();
  1017. InitializeGlobalObject();
  1018. InitializePostGlobal();
  1019. }
  1020. void ScriptContext::InitializePostGlobal()
  1021. {
  1022. this->GetDebugContext()->Initialize();
  1023. this->GetDebugContext()->GetProbeContainer()->Initialize(this);
  1024. AssertMsg(this->CurrentThunk == DefaultEntryThunk, "Creating non default thunk while initializing");
  1025. AssertMsg(this->DeferredParsingThunk == DefaultDeferredParsingThunk, "Creating non default thunk while initializing");
  1026. AssertMsg(this->DeferredDeserializationThunk == DefaultDeferredDeserializeThunk, "Creating non default thunk while initializing");
  1027. #ifdef FIELD_ACCESS_STATS
  1028. this->fieldAccessStatsByFunctionNumber = RecyclerNew(this->recycler, FieldAccessStatsByFunctionNumberMap, recycler);
  1029. BindReference(this->fieldAccessStatsByFunctionNumber);
  1030. #endif
  1031. if (!sourceList)
  1032. {
  1033. AutoCriticalSection critSec(threadContext->GetEtwRundownCriticalSection());
  1034. sourceList.Root(RecyclerNew(this->GetRecycler(), SourceList, this->GetRecycler()), this->GetRecycler());
  1035. }
  1036. #if DYNAMIC_INTERPRETER_THUNK
  1037. interpreterThunkEmitter = HeapNew(InterpreterThunkEmitter, SourceCodeAllocator(), this->GetThreadContext()->GetThunkPageAllocators());
  1038. #endif
  1039. #ifdef ASMJS_PLAT
  1040. asmJsInterpreterThunkEmitter = HeapNew(InterpreterThunkEmitter, SourceCodeAllocator(), this->GetThreadContext()->GetThunkPageAllocators(),
  1041. true);
  1042. #endif
  1043. JS_ETW(EtwTrace::LogScriptContextLoadEvent(this));
  1044. JS_ETW(EventWriteJSCRIPT_HOST_SCRIPT_CONTEXT_START(this));
  1045. #ifdef PROFILE_EXEC
  1046. if (profiler != nullptr)
  1047. {
  1048. this->threadContext->GetRecycler()->SetProfiler(profiler->GetProfiler(), profiler->GetBackgroundRecyclerProfiler());
  1049. }
  1050. #endif
  1051. #if DBG
  1052. this->javascriptLibrary->DumpLibraryByteCode();
  1053. isInitialized = TRUE;
  1054. #endif
  1055. }
  1056. #ifdef ASMJS_PLAT
  1057. AsmJsCodeGenerator* ScriptContext::InitAsmJsCodeGenerator()
  1058. {
  1059. if( !asmJsCodeGenerator )
  1060. {
  1061. asmJsCodeGenerator = HeapNew( AsmJsCodeGenerator, this );
  1062. }
  1063. return asmJsCodeGenerator;
  1064. }
  1065. #endif
  1066. void ScriptContext::MarkForClose()
  1067. {
  1068. SaveStartupProfileAndRelease(true);
  1069. SetIsClosed();
  1070. #ifdef LEAK_REPORT
  1071. if (this->isRootTrackerScriptContext)
  1072. {
  1073. this->GetThreadContext()->ClearRootTrackerScriptContext(this);
  1074. }
  1075. #endif
  1076. if (!threadContext->IsInScript())
  1077. {
  1078. Close(FALSE);
  1079. }
  1080. else
  1081. {
  1082. threadContext->AddToPendingScriptContextCloseList(this);
  1083. }
  1084. }
  1085. void ScriptContext::SetIsClosed()
  1086. {
  1087. this->isClosed = true;
  1088. #if ENABLE_NATIVE_CODEGEN
  1089. if (m_remoteScriptContextAddr)
  1090. {
  1091. JITManager::GetJITManager()->CloseScriptContext(m_remoteScriptContextAddr);
  1092. }
  1093. #endif
  1094. }
  1095. void ScriptContext::InitializeGlobalObject()
  1096. {
  1097. GlobalObject * localGlobalObject = GlobalObject::New(this);
  1098. GetRecycler()->RootAddRef(localGlobalObject);
  1099. // Assigned the global Object after we have successfully AddRef (in case of OOM)
  1100. globalObject = localGlobalObject;
  1101. globalObject->Initialize(this);
  1102. }
  1103. ArenaAllocator* ScriptContext::AllocatorForDiagnostics()
  1104. {
  1105. if (this->diagnosticArena == nullptr)
  1106. {
  1107. this->diagnosticArena = HeapNew(ArenaAllocator, _u("Diagnostic"), this->GetThreadContext()->GetDebugManager()->GetDiagnosticPageAllocator(), Throw::OutOfMemory);
  1108. }
  1109. Assert(this->diagnosticArena != nullptr);
  1110. return this->diagnosticArena;
  1111. }
  1112. void ScriptContext::PushObject(Var object)
  1113. {
  1114. operationStack->Push(object);
  1115. }
  1116. Var ScriptContext::PopObject()
  1117. {
  1118. return operationStack->Pop();
  1119. }
  1120. BOOL ScriptContext::CheckObject(Var object)
  1121. {
  1122. return operationStack->Contains(object);
  1123. }
  1124. void ScriptContext::SetHostScriptContext(HostScriptContext * hostScriptContext)
  1125. {
  1126. Assert(this->hostScriptContext == nullptr);
  1127. this->hostScriptContext = hostScriptContext;
  1128. #ifdef PROFILE_EXEC
  1129. this->ensureParentInfo = true;
  1130. #endif
  1131. }
  1132. //
  1133. // Enables chakradiag to get the HaltCallBack pointer that is implemented by
  1134. // the ScriptEngine.
  1135. //
  1136. void ScriptContext::SetScriptEngineHaltCallback(HaltCallback* scriptEngine)
  1137. {
  1138. Assert(this->scriptEngineHaltCallback == NULL);
  1139. Assert(scriptEngine != NULL);
  1140. this->scriptEngineHaltCallback = scriptEngine;
  1141. }
  1142. void ScriptContext::ClearHostScriptContext()
  1143. {
  1144. if (this->hostScriptContext != nullptr)
  1145. {
  1146. this->hostScriptContext->Delete();
  1147. #ifdef PROFILE_EXEC
  1148. this->ensureParentInfo = false;
  1149. #endif
  1150. }
  1151. }
  1152. IActiveScriptProfilerHeapEnum* ScriptContext::GetHeapEnum()
  1153. {
  1154. Assert(this->GetThreadContext());
  1155. return this->GetThreadContext()->GetHeapEnum();
  1156. }
  1157. void ScriptContext::SetHeapEnum(IActiveScriptProfilerHeapEnum* newHeapEnum)
  1158. {
  1159. Assert(this->GetThreadContext());
  1160. this->GetThreadContext()->SetHeapEnum(newHeapEnum);
  1161. }
  1162. void ScriptContext::ClearHeapEnum()
  1163. {
  1164. Assert(this->GetThreadContext());
  1165. this->GetThreadContext()->ClearHeapEnum();
  1166. }
  1167. BOOL ScriptContext::VerifyAlive(BOOL isJSFunction, ScriptContext* requestScriptContext)
  1168. {
  1169. if (isClosed)
  1170. {
  1171. if (!requestScriptContext)
  1172. {
  1173. requestScriptContext = this;
  1174. }
  1175. #if ENABLE_PROFILE_INFO
  1176. if (!GetThreadContext()->RecordImplicitException())
  1177. {
  1178. return FALSE;
  1179. }
  1180. #endif
  1181. if (isJSFunction)
  1182. {
  1183. Js::JavascriptError::MapAndThrowError(requestScriptContext, JSERR_CantExecute);
  1184. }
  1185. else
  1186. {
  1187. Js::JavascriptError::MapAndThrowError(requestScriptContext, E_ACCESSDENIED);
  1188. }
  1189. }
  1190. return TRUE;
  1191. }
  1192. void ScriptContext::VerifyAliveWithHostContext(BOOL isJSFunction, HostScriptContext* requestHostScriptContext)
  1193. {
  1194. if (requestHostScriptContext)
  1195. {
  1196. VerifyAlive(isJSFunction, requestHostScriptContext->GetScriptContext());
  1197. }
  1198. else
  1199. {
  1200. Assert(GetThreadContext()->IsJSRT() || !GetHostScriptContext()->HasCaller());
  1201. VerifyAlive(isJSFunction, NULL);
  1202. }
  1203. }
  1204. PropertyRecord const * ScriptContext::GetPropertyName(PropertyId propertyId)
  1205. {
  1206. return threadContext->GetPropertyName(propertyId);
  1207. }
  1208. PropertyRecord const * ScriptContext::GetPropertyNameLocked(PropertyId propertyId)
  1209. {
  1210. return threadContext->GetPropertyNameLocked(propertyId);
  1211. }
  1212. void ScriptContext::InitPropertyStringMap(int i)
  1213. {
  1214. propertyStrings[i] = AnewStruct(GeneralAllocator(), PropertyStringMap);
  1215. memset(propertyStrings[i]->strLen2, 0, sizeof(PropertyString*)* 80);
  1216. }
  1217. void ScriptContext::TrackPid(const PropertyRecord* propertyRecord)
  1218. {
  1219. if (IsBuiltInPropertyId(propertyRecord->GetPropertyId()) || propertyRecord->IsBound())
  1220. {
  1221. return;
  1222. }
  1223. if (-1 != this->GetLibrary()->EnsureReferencedPropertyRecordList()->AddNew(propertyRecord))
  1224. {
  1225. RECYCLER_PERF_COUNTER_INC(PropertyRecordBindReference);
  1226. }
  1227. }
  1228. void ScriptContext::TrackPid(PropertyId propertyId)
  1229. {
  1230. if (IsBuiltInPropertyId(propertyId))
  1231. {
  1232. return;
  1233. }
  1234. const PropertyRecord* propertyRecord = this->GetPropertyName(propertyId);
  1235. Assert(propertyRecord != nullptr);
  1236. this->TrackPid(propertyRecord);
  1237. }
  1238. bool ScriptContext::IsTrackedPropertyId(Js::PropertyId propertyId)
  1239. {
  1240. if (IsBuiltInPropertyId(propertyId))
  1241. {
  1242. return true;
  1243. }
  1244. const PropertyRecord* propertyRecord = this->GetPropertyName(propertyId);
  1245. Assert(propertyRecord != nullptr);
  1246. if (propertyRecord->IsBound())
  1247. {
  1248. return true;
  1249. }
  1250. JavascriptLibrary::ReferencedPropertyRecordHashSet * referencedPropertyRecords
  1251. = this->GetLibrary()->GetReferencedPropertyRecordList();
  1252. return referencedPropertyRecords && referencedPropertyRecords->Contains(propertyRecord);
  1253. }
  1254. PropertyString* ScriptContext::AddPropertyString2(const Js::PropertyRecord* propString)
  1255. {
  1256. const char16* buf = propString->GetBuffer();
  1257. const uint i = PropertyStringMap::PStrMapIndex(buf[0]);
  1258. if (propertyStrings[i] == NULL)
  1259. {
  1260. InitPropertyStringMap(i);
  1261. }
  1262. const uint j = PropertyStringMap::PStrMapIndex(buf[1]);
  1263. if (propertyStrings[i]->strLen2[j] == NULL && !isClosed)
  1264. {
  1265. propertyStrings[i]->strLen2[j] = GetLibrary()->CreatePropertyString(propString, this->GeneralAllocator());
  1266. this->TrackPid(propString);
  1267. }
  1268. return propertyStrings[i]->strLen2[j];
  1269. }
  1270. PropertyString* ScriptContext::CachePropertyString2(const PropertyRecord* propString)
  1271. {
  1272. Assert(propString->GetLength() == 2);
  1273. const char16* propertyName = propString->GetBuffer();
  1274. if ((propertyName[0] <= 'z') && (propertyName[1] <= 'z') && (propertyName[0] >= '0') && (propertyName[1] >= '0') && ((propertyName[0] > '9') || (propertyName[1] > '9')))
  1275. {
  1276. return AddPropertyString2(propString);
  1277. }
  1278. return NULL;
  1279. }
  1280. PropertyString* ScriptContext::TryGetPropertyString(PropertyId propertyId)
  1281. {
  1282. PropertyStringCacheMap* propertyStringMap = this->GetLibrary()->EnsurePropertyStringMap();
  1283. RecyclerWeakReference<PropertyString>* stringReference;
  1284. if (propertyStringMap->TryGetValue(propertyId, &stringReference))
  1285. {
  1286. PropertyString *string = stringReference->Get();
  1287. if (string != nullptr)
  1288. {
  1289. return string;
  1290. }
  1291. }
  1292. return nullptr;
  1293. }
  1294. PropertyString* ScriptContext::GetPropertyString(PropertyId propertyId)
  1295. {
  1296. PropertyString *string = TryGetPropertyString(propertyId);
  1297. if (string != nullptr)
  1298. {
  1299. return string;
  1300. }
  1301. PropertyStringCacheMap* propertyStringMap = this->GetLibrary()->EnsurePropertyStringMap();
  1302. const Js::PropertyRecord* propertyName = this->GetPropertyName(propertyId);
  1303. string = this->GetLibrary()->CreatePropertyString(propertyName);
  1304. propertyStringMap->Item(propertyId, recycler->CreateWeakReferenceHandle(string));
  1305. return string;
  1306. }
  1307. void ScriptContext::InvalidatePropertyStringCache(PropertyId propertyId, Type* type)
  1308. {
  1309. Assert(!isFinalized);
  1310. PropertyStringCacheMap* propertyStringMap = this->javascriptLibrary->GetPropertyStringMap();
  1311. if (propertyStringMap != nullptr)
  1312. {
  1313. PropertyString *string = nullptr;
  1314. RecyclerWeakReference<PropertyString>* stringReference;
  1315. if (propertyStringMap->TryGetValue(propertyId, &stringReference))
  1316. {
  1317. string = stringReference->Get();
  1318. }
  1319. if (string)
  1320. {
  1321. PropertyCache const* cache = string->GetPropertyCache();
  1322. if (cache->type == type)
  1323. {
  1324. string->ClearPropertyCache();
  1325. }
  1326. }
  1327. }
  1328. }
  1329. void ScriptContext::CleanupWeakReferenceDictionaries()
  1330. {
  1331. if (!isWeakReferenceDictionaryListCleared)
  1332. {
  1333. SListBase<JsUtil::IWeakReferenceDictionary*>::Iterator iter(&this->weakReferenceDictionaryList);
  1334. while (iter.Next())
  1335. {
  1336. JsUtil::IWeakReferenceDictionary* weakReferenceDictionary = iter.Data();
  1337. weakReferenceDictionary->Cleanup();
  1338. }
  1339. }
  1340. }
  1341. JavascriptString* ScriptContext::GetIntegerString(Var aValue)
  1342. {
  1343. return this->GetIntegerString(TaggedInt::ToInt32(aValue));
  1344. }
  1345. JavascriptString* ScriptContext::GetIntegerString(uint value)
  1346. {
  1347. if (value <= INT_MAX)
  1348. {
  1349. return this->GetIntegerString((int)value);
  1350. }
  1351. return TaggedInt::ToString(value, this);
  1352. }
  1353. JavascriptString* ScriptContext::GetIntegerString(int value)
  1354. {
  1355. // Optimize for 0-9
  1356. if (0 <= value && value <= 9)
  1357. {
  1358. return GetLibrary()->GetCharStringCache().GetStringForCharA('0' + static_cast<char>(value));
  1359. }
  1360. JavascriptString *string;
  1361. if (!this->integerStringMap.TryGetValue(value, &string))
  1362. {
  1363. // Add the string to hash table cache
  1364. // Don't add if table is getting too full. We'll be holding on to
  1365. // too many strings, and table lookup will become too slow.
  1366. if (this->integerStringMap.Count() > 1024)
  1367. {
  1368. // Use recycler memory
  1369. string = TaggedInt::ToString(value, this);
  1370. }
  1371. else
  1372. {
  1373. char16 stringBuffer[20];
  1374. TaggedInt::ToBuffer(value, stringBuffer, _countof(stringBuffer));
  1375. string = JavascriptString::NewCopySzFromArena(stringBuffer, this, this->GeneralAllocator());
  1376. this->integerStringMap.AddNew(value, string);
  1377. }
  1378. }
  1379. return string;
  1380. }
  1381. void ScriptContext::CheckEvalRestriction()
  1382. {
  1383. HRESULT hr = S_OK;
  1384. Var domError = nullptr;
  1385. HostScriptContext* hostScriptContext = this->GetHostScriptContext();
  1386. BEGIN_LEAVE_SCRIPT(this)
  1387. {
  1388. if (!FAILED(hr = hostScriptContext->CheckEvalRestriction()))
  1389. {
  1390. return;
  1391. }
  1392. hr = hostScriptContext->HostExceptionFromHRESULT(hr, &domError);
  1393. }
  1394. END_LEAVE_SCRIPT(this);
  1395. if (FAILED(hr))
  1396. {
  1397. Js::JavascriptError::MapAndThrowError(this, hr);
  1398. }
  1399. if (domError != nullptr)
  1400. {
  1401. JavascriptExceptionOperators::Throw(domError, this);
  1402. }
  1403. AssertMsg(false, "We should have thrown by now.");
  1404. Js::JavascriptError::MapAndThrowError(this, E_FAIL);
  1405. }
  1406. ParseNode* ScriptContext::ParseScript(Parser* parser,
  1407. const byte* script,
  1408. size_t cb,
  1409. SRCINFO const * pSrcInfo,
  1410. CompileScriptException * pse,
  1411. Utf8SourceInfo** ppSourceInfo,
  1412. const char16 *rootDisplayName,
  1413. LoadScriptFlag loadScriptFlag,
  1414. uint* sourceIndex)
  1415. {
  1416. if (pSrcInfo == nullptr)
  1417. {
  1418. pSrcInfo = this->cache->noContextGlobalSourceInfo;
  1419. }
  1420. LPUTF8 utf8Script = nullptr;
  1421. size_t length = cb;
  1422. size_t cbNeeded = 0;
  1423. bool isLibraryCode = ((loadScriptFlag & LoadScriptFlag_LibraryCode) == LoadScriptFlag_LibraryCode);
  1424. if ((loadScriptFlag & LoadScriptFlag_Utf8Source) != LoadScriptFlag_Utf8Source)
  1425. {
  1426. // Convert to UTF8 and then load that
  1427. length = cb / sizeof(char16);
  1428. if (!IsValidCharCount(length))
  1429. {
  1430. Js::Throw::OutOfMemory();
  1431. }
  1432. Assert(length < MAXLONG);
  1433. // Allocate memory for the UTF8 output buffer.
  1434. // We need at most 3 bytes for each Unicode code point.
  1435. // The + 1 is to include the terminating NUL.
  1436. // Nit: Technically, we know that the NUL only needs 1 byte instead of
  1437. // 3, but that's difficult to express in a SAL annotation for "EncodeInto".
  1438. size_t cbUtf8Buffer = AllocSizeMath::Mul(AllocSizeMath::Add(length, 1), 3);
  1439. utf8Script = RecyclerNewArrayLeafTrace(this->GetRecycler(), utf8char_t, cbUtf8Buffer);
  1440. cbNeeded = utf8::EncodeIntoAndNullTerminate(utf8Script, (const char16*)script, static_cast<charcount_t>(length));
  1441. #if DBG_DUMP && defined(PROFILE_MEM)
  1442. if(Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::ParsePhase) && Configuration::Global.flags.Verbose)
  1443. {
  1444. Output::Print(_u("Loading script.\n")
  1445. _u(" Unicode (in bytes) %u\n")
  1446. _u(" UTF-8 size (in bytes) %u\n")
  1447. _u(" Expected savings %d\n"), length * sizeof(char16), cbNeeded, length * sizeof(char16) - cbNeeded);
  1448. }
  1449. #endif
  1450. // Free unused bytes
  1451. Assert(cbNeeded + 1 <= cbUtf8Buffer);
  1452. *ppSourceInfo = Utf8SourceInfo::New(this, utf8Script, (int)length, cbNeeded, pSrcInfo, isLibraryCode);
  1453. }
  1454. else
  1455. {
  1456. // We do not own the memory passed into DefaultLoadScriptUtf8. We need to save it so we copy the memory.
  1457. if(*ppSourceInfo == nullptr)
  1458. {
  1459. // the 'length' here is not correct - we will get the length from the parser - however parser hasn't done yet.
  1460. // Once the parser is done we will update the utf8sourceinfo's lenght correctly with parser's
  1461. *ppSourceInfo = Utf8SourceInfo::New(this, script, (int)length, cb, pSrcInfo, isLibraryCode);
  1462. }
  1463. }
  1464. //
  1465. // Parse and the JavaScript code
  1466. //
  1467. HRESULT hr;
  1468. SourceContextInfo * sourceContextInfo = pSrcInfo->sourceContextInfo;
  1469. // Invoke the parser, passing in the global function name, which we will then run to execute
  1470. // the script.
  1471. // TODO: yongqu handle non-global code.
  1472. ULONG grfscr = fscrGlobalCode | ((loadScriptFlag & LoadScriptFlag_Expression) == LoadScriptFlag_Expression ? fscrReturnExpression : 0);
  1473. if(((loadScriptFlag & LoadScriptFlag_disableDeferredParse) != LoadScriptFlag_disableDeferredParse) &&
  1474. (length > Parser::GetDeferralThreshold(sourceContextInfo->IsSourceProfileLoaded())))
  1475. {
  1476. grfscr |= fscrDeferFncParse;
  1477. }
  1478. if((loadScriptFlag & LoadScriptFlag_disableAsmJs) == LoadScriptFlag_disableAsmJs)
  1479. {
  1480. grfscr |= fscrNoAsmJs;
  1481. }
  1482. if(PHASE_FORCE1(Js::EvalCompilePhase))
  1483. {
  1484. // pretend it is eval
  1485. grfscr |= (fscrEval | fscrEvalCode);
  1486. }
  1487. if((loadScriptFlag & LoadScriptFlag_isByteCodeBufferForLibrary) == LoadScriptFlag_isByteCodeBufferForLibrary)
  1488. {
  1489. grfscr |= fscrNoPreJit;
  1490. }
  1491. if(((loadScriptFlag & LoadScriptFlag_Module) == LoadScriptFlag_Module) &&
  1492. GetConfig()->IsES6ModuleEnabled())
  1493. {
  1494. grfscr |= fscrIsModuleCode;
  1495. }
  1496. if (isLibraryCode)
  1497. {
  1498. grfscr |= fscrIsLibraryCode;
  1499. }
  1500. ParseNodePtr parseTree;
  1501. if((loadScriptFlag & LoadScriptFlag_Utf8Source) == LoadScriptFlag_Utf8Source)
  1502. {
  1503. hr = parser->ParseUtf8Source(&parseTree, script, cb, grfscr, pse, &sourceContextInfo->nextLocalFunctionId, sourceContextInfo);
  1504. }
  1505. else
  1506. {
  1507. hr = parser->ParseCesu8Source(&parseTree, utf8Script, cbNeeded, grfscr, pse, &sourceContextInfo->nextLocalFunctionId, sourceContextInfo);
  1508. }
  1509. if(FAILED(hr) || parseTree == nullptr)
  1510. {
  1511. return nullptr;
  1512. }
  1513. (*ppSourceInfo)->SetParseFlags(grfscr);
  1514. //Make sure we have the body and text information available
  1515. if ((loadScriptFlag & LoadScriptFlag_Utf8Source) != LoadScriptFlag_Utf8Source)
  1516. {
  1517. *sourceIndex = this->SaveSourceNoCopy(*ppSourceInfo, static_cast<charcount_t>((*ppSourceInfo)->GetCchLength()), /*isCesu8*/ true);
  1518. }
  1519. else
  1520. {
  1521. // Update the length.
  1522. (*ppSourceInfo)->SetCchLength(parser->GetSourceIchLim());
  1523. *sourceIndex = this->SaveSourceNoCopy(*ppSourceInfo, parser->GetSourceIchLim(), /* isCesu8*/ false);
  1524. }
  1525. return parseTree;
  1526. }
  1527. JavascriptFunction* ScriptContext::LoadScript(const byte* script, size_t cb, SRCINFO const * pSrcInfo, CompileScriptException * pse, Utf8SourceInfo** ppSourceInfo, const char16 *rootDisplayName, LoadScriptFlag loadScriptFlag)
  1528. {
  1529. Assert(!this->threadContext->IsScriptActive());
  1530. Assert(pse != nullptr);
  1531. try
  1532. {
  1533. AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));
  1534. Js::AutoDynamicCodeReference dynamicFunctionReference(this);
  1535. Parser parser(this);
  1536. uint sourceIndex;
  1537. JavascriptFunction * pFunction = nullptr;
  1538. ParseNodePtr parseTree = ParseScript(&parser, script, cb, pSrcInfo, pse, ppSourceInfo, rootDisplayName, loadScriptFlag, &sourceIndex);
  1539. if (parseTree != nullptr)
  1540. {
  1541. pFunction = GenerateRootFunction(parseTree, sourceIndex, &parser, (*ppSourceInfo)->GetParseFlags(), pse, rootDisplayName);
  1542. }
  1543. if (pse->ei.scode == JSERR_AsmJsCompileError)
  1544. {
  1545. Assert((loadScriptFlag & LoadScriptFlag_disableAsmJs) != LoadScriptFlag_disableAsmJs);
  1546. pse->Clear();
  1547. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_disableAsmJs);
  1548. return LoadScript(script, cb, pSrcInfo, pse, ppSourceInfo, rootDisplayName, loadScriptFlag);
  1549. }
  1550. #ifdef ENABLE_SCRIPT_PROFILING
  1551. if (pFunction != nullptr && this->IsProfiling())
  1552. {
  1553. RegisterScript(pFunction->GetFunctionProxy());
  1554. }
  1555. #else
  1556. Assert(!this->IsProfiling());
  1557. #endif
  1558. return pFunction;
  1559. }
  1560. catch (Js::OutOfMemoryException)
  1561. {
  1562. pse->ProcessError(nullptr, E_OUTOFMEMORY, nullptr);
  1563. return nullptr;
  1564. }
  1565. catch (Js::StackOverflowException)
  1566. {
  1567. pse->ProcessError(nullptr, VBSERR_OutOfStack, nullptr);
  1568. return nullptr;
  1569. }
  1570. }
  1571. JavascriptFunction* ScriptContext::GenerateRootFunction(ParseNodePtr parseTree, uint sourceIndex, Parser* parser, uint32 grfscr, CompileScriptException * pse, const char16 *rootDisplayName)
  1572. {
  1573. HRESULT hr;
  1574. // Get the source code to keep it alive during the bytecode generation process
  1575. LPCUTF8 source = this->GetSource(sourceIndex)->GetSource(_u("ScriptContext::GenerateRootFunction"));
  1576. Assert(source != nullptr); // Source should not have been reclaimed by now
  1577. // Generate bytecode and native code
  1578. ParseableFunctionInfo* body = NULL;
  1579. hr = GenerateByteCode(parseTree, grfscr, this, &body, sourceIndex, false, parser, pse);
  1580. this->GetSource(sourceIndex)->SetByteCodeGenerationFlags(grfscr);
  1581. if(FAILED(hr))
  1582. {
  1583. return nullptr;
  1584. }
  1585. body->SetDisplayName(rootDisplayName);
  1586. body->SetIsTopLevel(true);
  1587. JavascriptFunction* rootFunction = javascriptLibrary->CreateScriptFunction(body);
  1588. return rootFunction;
  1589. }
  1590. BOOL ScriptContext::ReserveStaticTypeIds(__in int first, __in int last)
  1591. {
  1592. return threadContext->ReserveStaticTypeIds(first, last);
  1593. }
  1594. TypeId ScriptContext::ReserveTypeIds(int count)
  1595. {
  1596. return threadContext->ReserveTypeIds(count);
  1597. }
  1598. TypeId ScriptContext::CreateTypeId()
  1599. {
  1600. return threadContext->CreateTypeId();
  1601. }
  1602. void ScriptContext::OnScriptStart(bool isRoot, bool isScript)
  1603. {
  1604. const bool isForcedEnter = this->GetDebugContext() != nullptr ? this->GetDebugContext()->GetProbeContainer()->isForcedToEnterScriptStart : false;
  1605. if (this->scriptStartEventHandler != nullptr && ((isRoot && threadContext->GetCallRootLevel() == 1) || isForcedEnter))
  1606. {
  1607. if (this->GetDebugContext() != nullptr)
  1608. {
  1609. this->GetDebugContext()->GetProbeContainer()->isForcedToEnterScriptStart = false;
  1610. }
  1611. this->scriptStartEventHandler(this);
  1612. }
  1613. #if ENABLE_NATIVE_CODEGEN
  1614. //Blue 5491: Only start codegen if isScript. Avoid it if we are not really starting script and called from risky region such as catch handler.
  1615. if (isScript)
  1616. {
  1617. NativeCodeGenEnterScriptStart(this->GetNativeCodeGenerator());
  1618. }
  1619. #endif
  1620. }
  1621. void ScriptContext::OnScriptEnd(bool isRoot, bool isForcedEnd)
  1622. {
  1623. if ((isRoot && threadContext->GetCallRootLevel() == 1) || isForcedEnd)
  1624. {
  1625. if (this->scriptEndEventHandler != nullptr)
  1626. {
  1627. this->scriptEndEventHandler(this);
  1628. }
  1629. }
  1630. }
  1631. #ifdef FAULT_INJECTION
  1632. void ScriptContext::DisposeScriptContextByFaultInjection() {
  1633. if (this->disposeScriptByFaultInjectionEventHandler != nullptr)
  1634. {
  1635. this->disposeScriptByFaultInjectionEventHandler(this);
  1636. }
  1637. }
  1638. #endif
  1639. template <bool stackProbe, bool leaveForHost>
  1640. bool ScriptContext::LeaveScriptStart(void * frameAddress)
  1641. {
  1642. ThreadContext * threadContext = this->threadContext;
  1643. if (!threadContext->IsScriptActive())
  1644. {
  1645. // we should have enter always.
  1646. AssertMsg(FALSE, "Leaving ScriptStart while script is not active.");
  1647. return false;
  1648. }
  1649. // Make sure the host function will have at least 32k of stack available.
  1650. if (stackProbe)
  1651. {
  1652. threadContext->ProbeStack(Js::Constants::MinStackCallout, this);
  1653. }
  1654. else
  1655. {
  1656. AssertMsg(ExceptionCheck::HasStackProbe(), "missing stack probe");
  1657. }
  1658. threadContext->LeaveScriptStart<leaveForHost>(frameAddress);
  1659. return true;
  1660. }
  1661. template <bool leaveForHost>
  1662. void ScriptContext::LeaveScriptEnd(void * frameAddress)
  1663. {
  1664. this->threadContext->LeaveScriptEnd<leaveForHost>(frameAddress);
  1665. }
  1666. // explicit instantiations
  1667. template bool ScriptContext::LeaveScriptStart<true, true>(void * frameAddress);
  1668. template bool ScriptContext::LeaveScriptStart<true, false>(void * frameAddress);
  1669. template bool ScriptContext::LeaveScriptStart<false, true>(void * frameAddress);
  1670. template void ScriptContext::LeaveScriptEnd<true>(void * frameAddress);
  1671. template void ScriptContext::LeaveScriptEnd<false>(void * frameAddress);
  1672. bool ScriptContext::EnsureInterpreterArena(ArenaAllocator **ppAlloc)
  1673. {
  1674. bool fNew = false;
  1675. if (this->interpreterArena == nullptr)
  1676. {
  1677. this->interpreterArena = this->GetRecycler()->CreateGuestArena(_u("Interpreter"), Throw::OutOfMemory);
  1678. fNew = true;
  1679. }
  1680. *ppAlloc = this->interpreterArena;
  1681. return fNew;
  1682. }
  1683. void ScriptContext::ReleaseInterpreterArena()
  1684. {
  1685. AssertMsg(this->interpreterArena, "No interpreter arena to release");
  1686. if (this->interpreterArena)
  1687. {
  1688. this->GetRecycler()->DeleteGuestArena(this->interpreterArena);
  1689. this->interpreterArena = nullptr;
  1690. }
  1691. }
  1692. void ScriptContext::ReleaseGuestArena()
  1693. {
  1694. AssertMsg(this->guestArena, "No guest arena to release");
  1695. if (this->guestArena)
  1696. {
  1697. this->GetRecycler()->DeleteGuestArena(this->guestArena);
  1698. this->guestArena = nullptr;
  1699. }
  1700. }
  1701. void ScriptContext::SetScriptStartEventHandler(ScriptContext::EventHandler eventHandler)
  1702. {
  1703. AssertMsg(this->scriptStartEventHandler == nullptr, "Do not support multi-cast yet");
  1704. this->scriptStartEventHandler = eventHandler;
  1705. }
  1706. void ScriptContext::SetScriptEndEventHandler(ScriptContext::EventHandler eventHandler)
  1707. {
  1708. AssertMsg(this->scriptEndEventHandler == nullptr, "Do not support multi-cast yet");
  1709. this->scriptEndEventHandler = eventHandler;
  1710. }
  1711. #ifdef FAULT_INJECTION
  1712. void ScriptContext::SetDisposeDisposeByFaultInjectionEventHandler(ScriptContext::EventHandler eventHandler)
  1713. {
  1714. AssertMsg(this->disposeScriptByFaultInjectionEventHandler == nullptr, "Do not support multi-cast yet");
  1715. this->disposeScriptByFaultInjectionEventHandler = eventHandler;
  1716. }
  1717. #endif
  1718. bool ScriptContext::SaveSourceCopy(Utf8SourceInfo* const sourceInfo, int cchLength, bool isCesu8, uint * index)
  1719. {
  1720. HRESULT hr = S_OK;
  1721. BEGIN_TRANSLATE_OOM_TO_HRESULT
  1722. {
  1723. *index = this->SaveSourceCopy(sourceInfo, cchLength, isCesu8);
  1724. }
  1725. END_TRANSLATE_OOM_TO_HRESULT(hr);
  1726. return hr == S_OK;
  1727. }
  1728. uint ScriptContext::SaveSourceCopy(Utf8SourceInfo* sourceInfo, int cchLength, bool isCesu8)
  1729. {
  1730. Utf8SourceInfo* newSource = Utf8SourceInfo::Clone(this, sourceInfo);
  1731. return SaveSourceNoCopy(newSource, cchLength, isCesu8);
  1732. }
  1733. uint ScriptContext::SaveSourceNoCopy(Utf8SourceInfo* sourceInfo, int cchLength, bool isCesu8)
  1734. {
  1735. Assert(sourceInfo->GetScriptContext() == this);
  1736. if (this->IsScriptContextInDebugMode() && !sourceInfo->GetIsLibraryCode() && !sourceInfo->IsInDebugMode())
  1737. {
  1738. sourceInfo->SetInDebugMode(true);
  1739. }
  1740. RecyclerWeakReference<Utf8SourceInfo>* sourceWeakRef = this->GetRecycler()->CreateWeakReferenceHandle<Utf8SourceInfo>(sourceInfo);
  1741. sourceInfo->SetIsCesu8(isCesu8);
  1742. {
  1743. // We can be compiling new source code while rundown thread is reading from the list, causing AV on the reader thread
  1744. // lock the list during write as well.
  1745. AutoCriticalSection autocs(GetThreadContext()->GetEtwRundownCriticalSection());
  1746. return sourceList->SetAtFirstFreeSpot(sourceWeakRef);
  1747. }
  1748. }
  1749. void ScriptContext::CloneSources(ScriptContext* sourceContext)
  1750. {
  1751. sourceContext->sourceList->Map([=](int index, RecyclerWeakReference<Utf8SourceInfo>* sourceInfo)
  1752. {
  1753. Utf8SourceInfo* info = sourceInfo->Get();
  1754. if (info)
  1755. {
  1756. CloneSource(info);
  1757. }
  1758. });
  1759. }
  1760. uint ScriptContext::CloneSource(Utf8SourceInfo* info)
  1761. {
  1762. return this->SaveSourceCopy(info, info->GetCchLength(), info->GetIsCesu8());
  1763. }
  1764. Utf8SourceInfo* ScriptContext::GetSource(uint index)
  1765. {
  1766. Assert(this->sourceList->IsItemValid(index)); // This assert should be a subset of info != null- if info was null, in the last collect, we'd have invalidated the item
  1767. Utf8SourceInfo* info = this->sourceList->Item(index)->Get();
  1768. Assert(info != nullptr); // Should still be alive if this method is being called
  1769. return info;
  1770. }
  1771. bool ScriptContext::IsItemValidInSourceList(int index)
  1772. {
  1773. return (index < this->sourceList->Count()) && this->sourceList->IsItemValid(index);
  1774. }
  1775. void ScriptContext::RecordException(JavascriptExceptionObject * exceptionObject, bool propagateToDebugger)
  1776. {
  1777. Assert(this->threadContext->GetRecordedException() == nullptr || GetThreadContext()->HasUnhandledException());
  1778. this->threadContext->SetRecordedException(exceptionObject, propagateToDebugger);
  1779. #if DBG && ENABLE_DEBUG_STACK_BACK_TRACE
  1780. exceptionObject->FillStackBackTrace();
  1781. #endif
  1782. }
  1783. void ScriptContext::RethrowRecordedException(JavascriptExceptionObject::HostWrapperCreateFuncType hostWrapperCreateFunc)
  1784. {
  1785. bool considerPassingToDebugger = false;
  1786. JavascriptExceptionObject * exceptionObject = this->GetAndClearRecordedException(&considerPassingToDebugger);
  1787. if (hostWrapperCreateFunc)
  1788. {
  1789. exceptionObject->SetHostWrapperCreateFunc(exceptionObject->GetScriptContext() != this ? hostWrapperCreateFunc : nullptr);
  1790. }
  1791. JavascriptExceptionOperators::RethrowExceptionObject(exceptionObject, this, considerPassingToDebugger);
  1792. }
  1793. Js::JavascriptExceptionObject * ScriptContext::GetAndClearRecordedException(bool *considerPassingToDebugger)
  1794. {
  1795. JavascriptExceptionObject * exceptionObject = this->threadContext->GetRecordedException();
  1796. Assert(exceptionObject != nullptr);
  1797. if (considerPassingToDebugger)
  1798. {
  1799. *considerPassingToDebugger = this->threadContext->GetPropagateException();
  1800. }
  1801. exceptionObject = exceptionObject->CloneIfStaticExceptionObject(this);
  1802. this->threadContext->SetRecordedException(nullptr);
  1803. return exceptionObject;
  1804. }
  1805. bool ScriptContext::IsInEvalMap(FastEvalMapString const& key, BOOL isIndirect, ScriptFunction **ppFuncScript)
  1806. {
  1807. EvalCacheDictionary *dict = isIndirect ? this->cache->indirectEvalCacheDictionary : this->cache->evalCacheDictionary;
  1808. if (dict == nullptr)
  1809. {
  1810. return false;
  1811. }
  1812. #ifdef PROFILE_EVALMAP
  1813. if (Configuration::Global.flags.ProfileEvalMap)
  1814. {
  1815. charcount_t len = key.str.GetLength();
  1816. if (dict->TryGetValue(key, ppFuncScript))
  1817. {
  1818. Output::Print(_u("EvalMap cache hit:\t source size = %d\n"), len);
  1819. }
  1820. else
  1821. {
  1822. Output::Print(_u("EvalMap cache miss:\t source size = %d\n"), len);
  1823. }
  1824. }
  1825. #endif
  1826. // If eval map cleanup is false, to preserve existing behavior, add it to the eval map MRU list
  1827. bool success = dict->TryGetValue(key, ppFuncScript);
  1828. if (success)
  1829. {
  1830. dict->NotifyAdd(key);
  1831. #ifdef VERBOSE_EVAL_MAP
  1832. #if DBG
  1833. dict->DumpKeepAlives();
  1834. #endif
  1835. #endif
  1836. }
  1837. return success;
  1838. }
  1839. void ScriptContext::AddToEvalMap(FastEvalMapString const& key, BOOL isIndirect, ScriptFunction *pFuncScript)
  1840. {
  1841. EvalCacheDictionary *dict = isIndirect ? this->cache->indirectEvalCacheDictionary : this->cache->evalCacheDictionary;
  1842. if (dict == nullptr)
  1843. {
  1844. EvalCacheTopLevelDictionary* evalTopDictionary = RecyclerNew(this->recycler, EvalCacheTopLevelDictionary, this->recycler);
  1845. dict = RecyclerNew(this->recycler, EvalCacheDictionary, evalTopDictionary, recycler);
  1846. if (isIndirect)
  1847. {
  1848. this->cache->indirectEvalCacheDictionary = dict;
  1849. }
  1850. else
  1851. {
  1852. this->cache->evalCacheDictionary = dict;
  1853. }
  1854. }
  1855. dict->Add(key, pFuncScript);
  1856. }
  1857. bool ScriptContext::IsInNewFunctionMap(EvalMapString const& key, ParseableFunctionInfo **ppFuncBody)
  1858. {
  1859. if (this->cache->newFunctionCache == nullptr)
  1860. {
  1861. return false;
  1862. }
  1863. // If eval map cleanup is false, to preserve existing behavior, add it to the eval map MRU list
  1864. bool success = this->cache->newFunctionCache->TryGetValue(key, ppFuncBody);
  1865. if (success)
  1866. {
  1867. this->cache->newFunctionCache->NotifyAdd(key);
  1868. #ifdef VERBOSE_EVAL_MAP
  1869. #if DBG
  1870. this->cache->newFunctionCache->DumpKeepAlives();
  1871. #endif
  1872. #endif
  1873. }
  1874. return success;
  1875. }
  1876. void ScriptContext::AddToNewFunctionMap(EvalMapString const& key, ParseableFunctionInfo *pFuncBody)
  1877. {
  1878. if (this->cache->newFunctionCache == nullptr)
  1879. {
  1880. this->cache->newFunctionCache = RecyclerNew(this->recycler, NewFunctionCache, this->recycler);
  1881. }
  1882. this->cache->newFunctionCache->Add(key, pFuncBody);
  1883. }
  1884. void ScriptContext::EnsureSourceContextInfoMap()
  1885. {
  1886. if (this->cache->sourceContextInfoMap == nullptr)
  1887. {
  1888. this->cache->sourceContextInfoMap = RecyclerNew(this->GetRecycler(), SourceContextInfoMap, this->GetRecycler());
  1889. }
  1890. }
  1891. void ScriptContext::EnsureDynamicSourceContextInfoMap()
  1892. {
  1893. if (this->cache->dynamicSourceContextInfoMap == nullptr)
  1894. {
  1895. this->cache->dynamicSourceContextInfoMap = RecyclerNew(this->GetRecycler(), DynamicSourceContextInfoMap, this->GetRecycler());
  1896. }
  1897. }
  1898. SourceContextInfo* ScriptContext::GetSourceContextInfo(uint hash)
  1899. {
  1900. SourceContextInfo * sourceContextInfo;
  1901. if (this->cache->dynamicSourceContextInfoMap && this->cache->dynamicSourceContextInfoMap->TryGetValue(hash, &sourceContextInfo))
  1902. {
  1903. return sourceContextInfo;
  1904. }
  1905. return nullptr;
  1906. }
  1907. SourceContextInfo* ScriptContext::CreateSourceContextInfo(uint hash, DWORD_PTR hostSourceContext)
  1908. {
  1909. EnsureDynamicSourceContextInfoMap();
  1910. if (this->GetSourceContextInfo(hash) != nullptr)
  1911. {
  1912. return const_cast<SourceContextInfo*>(this->cache->noContextSourceContextInfo);
  1913. }
  1914. if (this->cache->dynamicSourceContextInfoMap->Count() > INMEMORY_CACHE_MAX_PROFILE_MANAGER)
  1915. {
  1916. OUTPUT_TRACE(Js::DynamicProfilePhase, _u("Max of dynamic script profile info reached.\n"));
  1917. return const_cast<SourceContextInfo*>(this->cache->noContextSourceContextInfo);
  1918. }
  1919. // This is capped so we can continue allocating in the arena
  1920. SourceContextInfo * sourceContextInfo = RecyclerNewStructZ(this->GetRecycler(), SourceContextInfo);
  1921. sourceContextInfo->sourceContextId = this->GetNextSourceContextId();
  1922. sourceContextInfo->dwHostSourceContext = hostSourceContext;
  1923. sourceContextInfo->isHostDynamicDocument = true;
  1924. sourceContextInfo->hash = hash;
  1925. #if ENABLE_PROFILE_INFO
  1926. sourceContextInfo->sourceDynamicProfileManager = this->threadContext->GetSourceDynamicProfileManager(this->GetUrl(), hash, &referencesSharedDynamicSourceContextInfo);
  1927. #endif
  1928. // For the host provided dynamic code (if hostSourceContext is not NoHostSourceContext), do not add to dynamicSourceContextInfoMap
  1929. if (hostSourceContext == Js::Constants::NoHostSourceContext)
  1930. {
  1931. this->cache->dynamicSourceContextInfoMap->Add(hash, sourceContextInfo);
  1932. }
  1933. return sourceContextInfo;
  1934. }
  1935. //
  1936. // Makes a copy of the URL to be stored in the map.
  1937. //
  1938. SourceContextInfo * ScriptContext::CreateSourceContextInfo(DWORD_PTR sourceContext, char16 const * url, size_t len,
  1939. IActiveScriptDataCache* profileDataCache, char16 const * sourceMapUrl /*= NULL*/, size_t sourceMapUrlLen /*= 0*/)
  1940. {
  1941. // Take etw rundown lock on this thread context. We are going to init/add to sourceContextInfoMap.
  1942. AutoCriticalSection autocs(GetThreadContext()->GetEtwRundownCriticalSection());
  1943. EnsureSourceContextInfoMap();
  1944. Assert(this->GetSourceContextInfo(sourceContext, profileDataCache) == nullptr);
  1945. SourceContextInfo * sourceContextInfo = RecyclerNewStructZ(this->GetRecycler(), SourceContextInfo);
  1946. sourceContextInfo->sourceContextId = this->GetNextSourceContextId();
  1947. sourceContextInfo->dwHostSourceContext = sourceContext;
  1948. sourceContextInfo->isHostDynamicDocument = false;
  1949. #if ENABLE_PROFILE_INFO
  1950. sourceContextInfo->sourceDynamicProfileManager = nullptr;
  1951. #endif
  1952. if (url != nullptr)
  1953. {
  1954. sourceContextInfo->url = CopyString(url, len, this->SourceCodeAllocator());
  1955. JS_ETW(EtwTrace::LogSourceModuleLoadEvent(this, sourceContext, url));
  1956. }
  1957. if (sourceMapUrl != nullptr && sourceMapUrlLen != 0)
  1958. {
  1959. sourceContextInfo->sourceMapUrl = CopyString(sourceMapUrl, sourceMapUrlLen, this->SourceCodeAllocator());
  1960. }
  1961. #if ENABLE_PROFILE_INFO
  1962. if (!this->startupComplete)
  1963. {
  1964. sourceContextInfo->sourceDynamicProfileManager = SourceDynamicProfileManager::LoadFromDynamicProfileStorage(sourceContextInfo, this, profileDataCache);
  1965. Assert(sourceContextInfo->sourceDynamicProfileManager != NULL);
  1966. }
  1967. this->cache->sourceContextInfoMap->Add(sourceContext, sourceContextInfo);
  1968. #endif
  1969. return sourceContextInfo;
  1970. }
  1971. // static
  1972. const char16* ScriptContext::CopyString(const char16* str, size_t charCount, ArenaAllocator* alloc)
  1973. {
  1974. size_t length = charCount + 1; // Add 1 for the NULL.
  1975. char16* copy = AnewArray(alloc, char16, length);
  1976. js_wmemcpy_s(copy, length, str, charCount);
  1977. copy[length - 1] = _u('\0');
  1978. return copy;
  1979. }
  1980. SourceContextInfo * ScriptContext::GetSourceContextInfo(DWORD_PTR sourceContext, IActiveScriptDataCache* profileDataCache)
  1981. {
  1982. if (sourceContext == Js::Constants::NoHostSourceContext)
  1983. {
  1984. return const_cast<SourceContextInfo*>(this->cache->noContextSourceContextInfo);
  1985. }
  1986. // We only init sourceContextInfoMap, don't need to lock.
  1987. EnsureSourceContextInfoMap();
  1988. SourceContextInfo * sourceContextInfo;
  1989. if (this->cache->sourceContextInfoMap->TryGetValue(sourceContext, &sourceContextInfo))
  1990. {
  1991. #if ENABLE_PROFILE_INFO
  1992. if (profileDataCache &&
  1993. sourceContextInfo->sourceDynamicProfileManager != nullptr &&
  1994. !sourceContextInfo->sourceDynamicProfileManager->IsProfileLoadedFromWinInet() &&
  1995. !this->startupComplete)
  1996. {
  1997. bool profileLoaded = sourceContextInfo->sourceDynamicProfileManager->LoadFromProfileCache(profileDataCache, sourceContextInfo->url);
  1998. if (profileLoaded)
  1999. {
  2000. JS_ETW(EventWriteJSCRIPT_PROFILE_LOAD(sourceContextInfo->dwHostSourceContext, this));
  2001. }
  2002. }
  2003. #endif
  2004. return sourceContextInfo;
  2005. }
  2006. return nullptr;
  2007. }
  2008. SRCINFO const *
  2009. ScriptContext::GetModuleSrcInfo(Js::ModuleID moduleID)
  2010. {
  2011. if (moduleSrcInfoCount <= moduleID)
  2012. {
  2013. uint newCount = moduleID + 4; // Preallocate 4 more slots, moduleID don't usually grow much
  2014. SRCINFO const ** newModuleSrcInfo = RecyclerNewArrayZ(this->GetRecycler(), SRCINFO const*, newCount);
  2015. memcpy(newModuleSrcInfo, cache->moduleSrcInfo, sizeof(SRCINFO const *)* moduleSrcInfoCount);
  2016. cache->moduleSrcInfo = newModuleSrcInfo;
  2017. moduleSrcInfoCount = newCount;
  2018. cache->moduleSrcInfo[0] = this->cache->noContextGlobalSourceInfo;
  2019. }
  2020. SRCINFO const * si = cache->moduleSrcInfo[moduleID];
  2021. if (si == nullptr)
  2022. {
  2023. SRCINFO * newSrcInfo = RecyclerNewStructZ(this->GetRecycler(), SRCINFO);
  2024. newSrcInfo->sourceContextInfo = this->cache->noContextSourceContextInfo;
  2025. newSrcInfo->moduleID = moduleID;
  2026. cache->moduleSrcInfo[moduleID] = newSrcInfo;
  2027. si = newSrcInfo;
  2028. }
  2029. return si;
  2030. }
  2031. #if ENABLE_TTD
  2032. void ScriptContext::InitializeCoreImage_TTD()
  2033. {
  2034. AssertMsg(this->TTDWellKnownInfo == nullptr, "This should only happen once!!!");
  2035. this->TTDWellKnownInfo = TT_HEAP_NEW(TTD::RuntimeContextInfo);
  2036. bool hasCaller = this->GetHostScriptContext() ? !!this->GetHostScriptContext()->HasCaller() : false;
  2037. BEGIN_JS_RUNTIME_CALLROOT_EX(this, hasCaller)
  2038. {
  2039. this->TTDWellKnownInfo->GatherKnownObjectToPathMap(this);
  2040. }
  2041. END_JS_RUNTIME_CALL(this);
  2042. }
  2043. void ScriptContext::InitializeRecordingActionsAsNeeded_TTD()
  2044. {
  2045. this->TTDContextInfo = TT_HEAP_NEW(TTD::ScriptContextTTD, this);
  2046. this->TTDContextInfo->AddTrackedRoot(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(this->GetLibrary()->GetGlobalObject()), this->GetLibrary()->GetGlobalObject());
  2047. this->ScriptContextLogTag = TTD_CONVERT_OBJ_TO_LOG_PTR_ID(this->GetLibrary()->GetGlobalObject());
  2048. this->TTDContextInfo->AddTrackedRoot(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(this->GetLibrary()->GetUndefined()), this->GetLibrary()->GetUndefined());
  2049. this->TTDContextInfo->AddTrackedRoot(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(this->GetLibrary()->GetNull()), this->GetLibrary()->GetNull());
  2050. this->TTDContextInfo->AddTrackedRoot(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(this->GetLibrary()->GetTrue()), this->GetLibrary()->GetTrue());
  2051. this->TTDContextInfo->AddTrackedRoot(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(this->GetLibrary()->GetFalse()), this->GetLibrary()->GetFalse());
  2052. #if ENABLE_TTD_STACK_STMTS
  2053. this->ForceNoNative();
  2054. #endif
  2055. }
  2056. void ScriptContext::InitializeDebuggingActionsAsNeeded_TTD()
  2057. {
  2058. this->ForceNoNative();
  2059. }
  2060. #endif
  2061. #ifdef PROFILE_EXEC
  2062. void
  2063. ScriptContext::DisableProfiler()
  2064. {
  2065. disableProfiler = true;
  2066. }
  2067. Profiler *
  2068. ScriptContext::CreateProfiler()
  2069. {
  2070. Assert(profiler == nullptr);
  2071. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  2072. {
  2073. this->profiler = NoCheckHeapNew(ScriptContextProfiler);
  2074. this->profiler->Initialize(GetThreadContext()->GetPageAllocator(), threadContext->GetRecycler());
  2075. #if ENABLE_NATIVE_CODEGEN
  2076. CreateProfilerNativeCodeGen(this->nativeCodeGen, this->profiler);
  2077. #endif
  2078. this->isProfilerCreated = true;
  2079. Profiler * oldProfiler = this->threadContext->GetRecycler()->GetProfiler();
  2080. this->threadContext->GetRecycler()->SetProfiler(this->profiler->GetProfiler(), this->profiler->GetBackgroundRecyclerProfiler());
  2081. return oldProfiler;
  2082. }
  2083. return nullptr;
  2084. }
  2085. void
  2086. ScriptContext::SetRecyclerProfiler()
  2087. {
  2088. Assert(Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag));
  2089. AssertMsg(this->profiler != nullptr, "Profiler tag is supplied but the profiler pointer is NULL");
  2090. if (this->ensureParentInfo)
  2091. {
  2092. this->hostScriptContext->EnsureParentInfo();
  2093. this->ensureParentInfo = false;
  2094. }
  2095. this->GetRecycler()->SetProfiler(this->profiler->GetProfiler(), this->profiler->GetBackgroundRecyclerProfiler());
  2096. }
  2097. void
  2098. ScriptContext::SetProfilerFromScriptContext(ScriptContext * scriptContext)
  2099. {
  2100. // this function needs to be called before any code gen happens so
  2101. // that access to codegenProfiler won't have concurrency issues
  2102. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  2103. {
  2104. Assert(this->profiler != nullptr);
  2105. Assert(this->isProfilerCreated);
  2106. Assert(scriptContext->profiler != nullptr);
  2107. Assert(scriptContext->isProfilerCreated);
  2108. scriptContext->profiler->ProfileMerge(this->profiler);
  2109. this->profiler->Release();
  2110. this->profiler = scriptContext->profiler;
  2111. this->profiler->AddRef();
  2112. this->isProfilerCreated = false;
  2113. #if ENABLE_NATIVE_CODEGEN
  2114. SetProfilerFromNativeCodeGen(this->nativeCodeGen, scriptContext->GetNativeCodeGenerator());
  2115. #endif
  2116. this->threadContext->GetRecycler()->SetProfiler(this->profiler->GetProfiler(), this->profiler->GetBackgroundRecyclerProfiler());
  2117. }
  2118. }
  2119. void
  2120. ScriptContext::ProfileBegin(Js::Phase phase)
  2121. {
  2122. AssertMsg((this->profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  2123. "Profiler tag is supplied but the profiler pointer is NULL");
  2124. if (this->profiler)
  2125. {
  2126. if (this->ensureParentInfo)
  2127. {
  2128. this->hostScriptContext->EnsureParentInfo();
  2129. this->ensureParentInfo = false;
  2130. }
  2131. this->profiler->ProfileBegin(phase);
  2132. }
  2133. }
  2134. void
  2135. ScriptContext::ProfileEnd(Js::Phase phase)
  2136. {
  2137. AssertMsg((this->profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  2138. "Profiler tag is supplied but the profiler pointer is NULL");
  2139. if (this->profiler)
  2140. {
  2141. this->profiler->ProfileEnd(phase);
  2142. }
  2143. }
  2144. void
  2145. ScriptContext::ProfileSuspend(Js::Phase phase, Js::Profiler::SuspendRecord * suspendRecord)
  2146. {
  2147. AssertMsg((this->profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  2148. "Profiler tag is supplied but the profiler pointer is NULL");
  2149. if (this->profiler)
  2150. {
  2151. this->profiler->ProfileSuspend(phase, suspendRecord);
  2152. }
  2153. }
  2154. void
  2155. ScriptContext::ProfileResume(Js::Profiler::SuspendRecord * suspendRecord)
  2156. {
  2157. AssertMsg((this->profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  2158. "Profiler tag is supplied but the profiler pointer is NULL");
  2159. if (this->profiler)
  2160. {
  2161. this->profiler->ProfileResume(suspendRecord);
  2162. }
  2163. }
  2164. void
  2165. ScriptContext::ProfilePrint()
  2166. {
  2167. if (disableProfiler)
  2168. {
  2169. return;
  2170. }
  2171. Assert(profiler != nullptr);
  2172. recycler->EnsureNotCollecting();
  2173. profiler->ProfilePrint(Js::Configuration::Global.flags.Profile.GetFirstPhase());
  2174. #if ENABLE_NATIVE_CODEGEN
  2175. ProfilePrintNativeCodeGen(this->nativeCodeGen);
  2176. #endif
  2177. }
  2178. #endif
  2179. #ifdef ENABLE_SCRIPT_PROFILING
  2180. inline void ScriptContext::CoreSetProfileEventMask(DWORD dwEventMask)
  2181. {
  2182. AssertMsg(m_pProfileCallback != NULL, "Assigning the event mask when there is no callback");
  2183. m_dwEventMask = dwEventMask;
  2184. m_fTraceFunctionCall = (dwEventMask & PROFILER_EVENT_MASK_TRACE_SCRIPT_FUNCTION_CALL);
  2185. m_fTraceNativeFunctionCall = (dwEventMask & PROFILER_EVENT_MASK_TRACE_NATIVE_FUNCTION_CALL);
  2186. m_fTraceDomCall = (dwEventMask & PROFILER_EVENT_MASK_TRACE_DOM_FUNCTION_CALL);
  2187. }
  2188. HRESULT ScriptContext::RegisterProfileProbe(IActiveScriptProfilerCallback *pProfileCallback, DWORD dwEventMask, DWORD dwContext, RegisterExternalLibraryType RegisterExternalLibrary, JavascriptMethod dispatchInvoke)
  2189. {
  2190. if (m_pProfileCallback != NULL)
  2191. {
  2192. return ACTIVPROF_E_PROFILER_PRESENT;
  2193. }
  2194. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterProfileProbe\n"));
  2195. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("Info\nThunks Address :\n"));
  2196. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("DefaultEntryThunk : 0x%08X, CrossSite::DefaultThunk : 0x%08X, DefaultDeferredParsingThunk : 0x%08X\n"), DefaultEntryThunk, CrossSite::DefaultThunk, DefaultDeferredParsingThunk);
  2197. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ProfileEntryThunk : 0x%08X, CrossSite::ProfileThunk : 0x%08X, ProfileDeferredParsingThunk : 0x%08X, ProfileDeferredDeserializeThunk : 0x%08X,\n"), ProfileEntryThunk, CrossSite::ProfileThunk, ProfileDeferredParsingThunk, ProfileDeferredDeserializeThunk);
  2198. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptType :\n"));
  2199. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("PROFILER_SCRIPT_TYPE_USER : 0, PROFILER_SCRIPT_TYPE_DYNAMIC : 1, PROFILER_SCRIPT_TYPE_NATIVE : 2, PROFILER_SCRIPT_TYPE_DOM : 3\n"));
  2200. HRESULT hr = pProfileCallback->Initialize(dwContext);
  2201. if (SUCCEEDED(hr))
  2202. {
  2203. m_pProfileCallback = pProfileCallback;
  2204. pProfileCallback->AddRef();
  2205. CoreSetProfileEventMask(dwEventMask);
  2206. if (m_fTraceDomCall)
  2207. {
  2208. if (FAILED(pProfileCallback->QueryInterface(&m_pProfileCallback2)))
  2209. {
  2210. m_fTraceDomCall = FALSE;
  2211. }
  2212. }
  2213. if (webWorkerId != Js::Constants::NonWebWorkerContextId)
  2214. {
  2215. IActiveScriptProfilerCallback3 * pProfilerCallback3;
  2216. if (SUCCEEDED(pProfileCallback->QueryInterface(&pProfilerCallback3)))
  2217. {
  2218. pProfilerCallback3->SetWebWorkerId(webWorkerId);
  2219. pProfilerCallback3->Release();
  2220. // Omitting the HRESULT since it is up to the callback to make use of the webWorker information.
  2221. }
  2222. }
  2223. #if DEBUG
  2224. StartNewProfileSession();
  2225. #endif
  2226. #if ENABLE_NATIVE_CODEGEN
  2227. NativeCodeGenerator *pNativeCodeGen = this->GetNativeCodeGenerator();
  2228. AutoOptionalCriticalSection autoAcquireCodeGenQueue(GetNativeCodeGenCriticalSection(pNativeCodeGen));
  2229. #endif
  2230. this->SetProfileMode(TRUE);
  2231. #if ENABLE_NATIVE_CODEGEN
  2232. SetProfileModeNativeCodeGen(pNativeCodeGen, TRUE);
  2233. #endif
  2234. // Register builtin functions
  2235. if (m_fTraceNativeFunctionCall)
  2236. {
  2237. hr = this->RegisterBuiltinFunctions(RegisterExternalLibrary);
  2238. if (FAILED(hr))
  2239. {
  2240. return hr;
  2241. }
  2242. }
  2243. this->RegisterAllScripts();
  2244. // Set the dispatch profiler:
  2245. this->SetDispatchProfile(TRUE, dispatchInvoke);
  2246. // Update the function objects currently present in there.
  2247. this->SetFunctionInRecyclerToProfileMode();
  2248. }
  2249. return hr;
  2250. }
  2251. HRESULT ScriptContext::SetProfileEventMask(DWORD dwEventMask)
  2252. {
  2253. if (m_pProfileCallback == NULL)
  2254. {
  2255. return ACTIVPROF_E_PROFILER_ABSENT;
  2256. }
  2257. return ACTIVPROF_E_UNABLE_TO_APPLY_ACTION;
  2258. }
  2259. HRESULT ScriptContext::DeRegisterProfileProbe(HRESULT hrReason, JavascriptMethod dispatchInvoke)
  2260. {
  2261. if (m_pProfileCallback == NULL)
  2262. {
  2263. return ACTIVPROF_E_PROFILER_ABSENT;
  2264. }
  2265. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::DeRegisterProfileProbe\n"));
  2266. #if ENABLE_NATIVE_CODEGEN
  2267. // Acquire the code gen working queue - we are going to change the thunks
  2268. NativeCodeGenerator *pNativeCodeGen = this->GetNativeCodeGenerator();
  2269. Assert(pNativeCodeGen);
  2270. {
  2271. AutoOptionalCriticalSection lock(GetNativeCodeGenCriticalSection(pNativeCodeGen));
  2272. this->SetProfileMode(FALSE);
  2273. SetProfileModeNativeCodeGen(pNativeCodeGen, FALSE);
  2274. // DisableJIT-TODO: Does need to happen even with JIT disabled?
  2275. // Unset the dispatch profiler:
  2276. if (dispatchInvoke != nullptr)
  2277. {
  2278. this->SetDispatchProfile(FALSE, dispatchInvoke);
  2279. }
  2280. }
  2281. #endif
  2282. m_inProfileCallback = TRUE;
  2283. HRESULT hr = m_pProfileCallback->Shutdown(hrReason);
  2284. m_inProfileCallback = FALSE;
  2285. m_pProfileCallback->Release();
  2286. m_pProfileCallback = NULL;
  2287. if (m_pProfileCallback2 != NULL)
  2288. {
  2289. m_pProfileCallback2->Release();
  2290. m_pProfileCallback2 = NULL;
  2291. }
  2292. #if DEBUG
  2293. StopProfileSession();
  2294. #endif
  2295. return hr;
  2296. }
  2297. void ScriptContext::SetProfileMode(BOOL fSet)
  2298. {
  2299. #ifdef ENABLE_SCRIPT_PROFILING
  2300. if (fSet)
  2301. {
  2302. AssertMsg(m_pProfileCallback != NULL, "In profile mode when there is no call back");
  2303. this->CurrentThunk = ProfileEntryThunk;
  2304. this->CurrentCrossSiteThunk = CrossSite::ProfileThunk;
  2305. this->DeferredParsingThunk = ProfileDeferredParsingThunk;
  2306. this->DeferredDeserializationThunk = ProfileDeferredDeserializeThunk;
  2307. this->globalObject->EvalHelper = &Js::GlobalObject::ProfileModeEvalHelper;
  2308. #if DBG
  2309. this->hadProfiled = true;
  2310. #endif
  2311. }
  2312. else
  2313. #endif
  2314. {
  2315. Assert(!fSet);
  2316. this->CurrentThunk = DefaultEntryThunk;
  2317. this->CurrentCrossSiteThunk = CrossSite::DefaultThunk;
  2318. this->DeferredParsingThunk = DefaultDeferredParsingThunk;
  2319. this->globalObject->EvalHelper = &Js::GlobalObject::DefaultEvalHelper;
  2320. // In Debug mode/Fast F12 library is still needed for built-in wrappers.
  2321. if (!(this->IsScriptContextInDebugMode() && this->IsExceptionWrapperForBuiltInsEnabled()))
  2322. {
  2323. this->javascriptLibrary->SetProfileMode(FALSE);
  2324. }
  2325. }
  2326. }
  2327. HRESULT ScriptContext::RegisterScript(Js::FunctionProxy * proxy, BOOL fRegisterScript /*default TRUE*/)
  2328. {
  2329. if (m_pProfileCallback == nullptr)
  2330. {
  2331. return ACTIVPROF_E_PROFILER_ABSENT;
  2332. }
  2333. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterScript, fRegisterScript : %s, IsFunctionDefer : %s\n"), IsTrueOrFalse(fRegisterScript), IsTrueOrFalse(proxy->IsDeferred()));
  2334. AssertMsg(proxy != nullptr, "Function body cannot be null when calling reporting");
  2335. AssertMsg(proxy->GetScriptContext() == this, "wrong script context while reporting the function?");
  2336. if (fRegisterScript)
  2337. {
  2338. // Register the script to the callback.
  2339. // REVIEW: do we really need to undefer everything?
  2340. HRESULT hr = proxy->EnsureDeserialized()->Parse()->ReportScriptCompiled();
  2341. if (FAILED(hr))
  2342. {
  2343. return hr;
  2344. }
  2345. }
  2346. return !proxy->IsDeferred() ? proxy->GetFunctionBody()->RegisterFunction(false) : S_OK;
  2347. }
  2348. HRESULT ScriptContext::RegisterAllScripts()
  2349. {
  2350. AssertMsg(m_pProfileCallback != nullptr, "Called register scripts when we don't have profile callback");
  2351. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterAllScripts started\n"));
  2352. // Future Work: Once Utf8SourceInfo can generate the debug document text without requiring a function body,
  2353. // this code can be considerably simplified to doing the following:
  2354. // - scriptContext->MapScript() : Fire script compiled for each script
  2355. // - scriptContext->MapFunction(): Fire function compiled for each function
  2356. this->MapScript([](Utf8SourceInfo* sourceInfo)
  2357. {
  2358. FunctionBody* functionBody = sourceInfo->GetAnyParsedFunction();
  2359. if (functionBody)
  2360. {
  2361. functionBody->ReportScriptCompiled();
  2362. }
  2363. });
  2364. // FunctionCompiled events for all functions.
  2365. this->MapFunction([](Js::FunctionBody* pFuncBody)
  2366. {
  2367. if (!pFuncBody->GetIsTopLevel() && pFuncBody->GetIsGlobalFunc())
  2368. {
  2369. // This must be the dummy function, generated due to the deferred parsing.
  2370. return;
  2371. }
  2372. pFuncBody->RegisterFunction(TRUE, TRUE); // Ignore potential failure (worst case is not profiling).
  2373. });
  2374. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterAllScripts ended\n"));
  2375. return S_OK;
  2376. }
  2377. #endif // ENABLE_SCRIPT_PROFILING
  2378. // Shuts down and recreates the native code generator. This is used when
  2379. // attaching and detaching the debugger in order to clear the list of work
  2380. // items that are pending in the JIT job queue.
  2381. // Alloc first and then free so that the native code generator is at a different address
  2382. #if ENABLE_NATIVE_CODEGEN
  2383. HRESULT ScriptContext::RecreateNativeCodeGenerator()
  2384. {
  2385. NativeCodeGenerator* oldCodeGen = this->nativeCodeGen;
  2386. HRESULT hr = S_OK;
  2387. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  2388. this->nativeCodeGen = NewNativeCodeGenerator(this);
  2389. SetProfileModeNativeCodeGen(this->GetNativeCodeGenerator(), this->IsProfiling());
  2390. END_TRANSLATE_OOM_TO_HRESULT(hr);
  2391. // Delete the native code generator and recreate so that all jobs get cleared properly
  2392. // and re-jitted.
  2393. CloseNativeCodeGenerator(oldCodeGen);
  2394. DeleteNativeCodeGenerator(oldCodeGen);
  2395. return hr;
  2396. }
  2397. #endif
  2398. HRESULT ScriptContext::OnDebuggerAttached()
  2399. {
  2400. OUTPUT_TRACE(Js::DebuggerPhase, _u("ScriptContext::OnDebuggerAttached: start 0x%p\n"), this);
  2401. Js::StepController* stepController = &this->GetThreadContext()->GetDebugManager()->stepController;
  2402. if (stepController->IsActive())
  2403. {
  2404. AssertMsg(stepController->GetActivatedContext() == nullptr, "StepController should not be active when we attach.");
  2405. stepController->Deactivate(); // Defense in depth
  2406. }
  2407. bool shouldPerformSourceRundown = false;
  2408. if (this->IsScriptContextInNonDebugMode())
  2409. {
  2410. // Today we do source rundown as a part of attach to support VS attaching without
  2411. // first calling PerformSourceRundown. PerformSourceRundown will be called once
  2412. // by debugger host prior to attaching.
  2413. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::SourceRundown);
  2414. // Need to perform rundown only once.
  2415. shouldPerformSourceRundown = true;
  2416. }
  2417. // Rundown on all existing functions and change their thunks so that they will go to debug mode once they are called.
  2418. HRESULT hr = OnDebuggerAttachedDetached(/*attach*/ true);
  2419. // Debugger attach/detach failure is catastrophic, take down the process
  2420. DEBUGGER_ATTACHDETACH_FATAL_ERROR_IF_FAILED(hr);
  2421. // Disable QC while functions are re-parsed as this can be time consuming
  2422. AutoDisableInterrupt autoDisableInterrupt(this->threadContext->GetInterruptPoller(), true);
  2423. hr = this->GetDebugContext()->RundownSourcesAndReparse(shouldPerformSourceRundown, /*shouldReparseFunctions*/ true);
  2424. if (this->IsClosed())
  2425. {
  2426. return hr;
  2427. }
  2428. // Debugger attach/detach failure is catastrophic, take down the process
  2429. DEBUGGER_ATTACHDETACH_FATAL_ERROR_IF_FAILED(hr);
  2430. HRESULT hrEntryPointUpdate = S_OK;
  2431. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  2432. #ifdef ASMJS_PLAT
  2433. TempArenaAllocatorObject* tmpAlloc = GetTemporaryAllocator(_u("DebuggerTransition"));
  2434. debugTransitionAlloc = tmpAlloc->GetAllocator();
  2435. asmJsEnvironmentMap = Anew(debugTransitionAlloc, AsmFunctionMap, debugTransitionAlloc);
  2436. #endif
  2437. // Still do the pass on the function's entrypoint to reflect its state with the functionbody's entrypoint.
  2438. this->UpdateRecyclerFunctionEntryPointsForDebugger();
  2439. #ifdef ASMJS_PLAT
  2440. auto asmEnvIter = asmJsEnvironmentMap->GetIterator();
  2441. while (asmEnvIter.IsValid())
  2442. {
  2443. // we are attaching, change frame setup for asm.js frame to javascript frame
  2444. SList<AsmJsScriptFunction *> * funcList = asmEnvIter.CurrentValue();
  2445. Assert(!funcList->Empty());
  2446. void* newEnv = AsmJsModuleInfo::ConvertFrameForJavascript(asmEnvIter.CurrentKey(), funcList->Head());
  2447. funcList->Iterate([&](AsmJsScriptFunction * func)
  2448. {
  2449. func->GetEnvironment()->SetItem(0, newEnv);
  2450. });
  2451. asmEnvIter.MoveNext();
  2452. }
  2453. // walk through and clean up the asm.js fields as a discrete step, because module might be multiply linked
  2454. auto asmCleanupIter = asmJsEnvironmentMap->GetIterator();
  2455. while (asmCleanupIter.IsValid())
  2456. {
  2457. SList<AsmJsScriptFunction *> * funcList = asmCleanupIter.CurrentValue();
  2458. Assert(!funcList->Empty());
  2459. funcList->Iterate([](AsmJsScriptFunction * func)
  2460. {
  2461. func->SetModuleMemory(nullptr);
  2462. func->GetFunctionBody()->ResetAsmJsInfo();
  2463. });
  2464. asmCleanupIter.MoveNext();
  2465. }
  2466. ReleaseTemporaryAllocator(tmpAlloc);
  2467. #endif
  2468. END_TRANSLATE_OOM_TO_HRESULT(hrEntryPointUpdate);
  2469. if (hrEntryPointUpdate != S_OK)
  2470. {
  2471. // should only be here for OOM
  2472. Assert(hrEntryPointUpdate == E_OUTOFMEMORY);
  2473. return hrEntryPointUpdate;
  2474. }
  2475. OUTPUT_TRACE(Js::DebuggerPhase, _u("ScriptContext::OnDebuggerAttached: done 0x%p, hr = 0x%X\n"), this, hr);
  2476. return hr;
  2477. }
  2478. // Reverts the script context state back to the state before debugging began.
  2479. HRESULT ScriptContext::OnDebuggerDetached()
  2480. {
  2481. OUTPUT_TRACE(Js::DebuggerPhase, _u("ScriptContext::OnDebuggerDetached: start 0x%p\n"), this);
  2482. Js::StepController* stepController = &this->GetThreadContext()->GetDebugManager()->stepController;
  2483. if (stepController->IsActive())
  2484. {
  2485. // Normally step controller is deactivated on start of dispatch (step, async break, exception, etc),
  2486. // and in the beginning of interpreter loop we check for step complete (can cause check whether current bytecode belong to stmt).
  2487. // But since it holds to functionBody/statementMaps, we have to deactivate it as func bodies are going away/reparsed.
  2488. stepController->Deactivate();
  2489. }
  2490. // Go through all existing functions and change their thunks back to using non-debug mode versions when called
  2491. // and notify the script context that the debugger has detached to allow it to revert the runtime to the proper
  2492. // state (JIT enabled).
  2493. HRESULT hr = OnDebuggerAttachedDetached(/*attach*/ false);
  2494. // Debugger attach/detach failure is catastrophic, take down the process
  2495. DEBUGGER_ATTACHDETACH_FATAL_ERROR_IF_FAILED(hr);
  2496. // Move the debugger into source rundown mode.
  2497. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::SourceRundown);
  2498. // Disable QC while functions are re-parsed as this can be time consuming
  2499. AutoDisableInterrupt autoDisableInterrupt(this->threadContext->GetInterruptPoller(), true);
  2500. // Force a reparse so that indirect function caches are updated.
  2501. hr = this->GetDebugContext()->RundownSourcesAndReparse(/*shouldPerformSourceRundown*/ false, /*shouldReparseFunctions*/ true);
  2502. if (this->IsClosed())
  2503. {
  2504. return hr;
  2505. }
  2506. // Debugger attach/detach failure is catastrophic, take down the process
  2507. DEBUGGER_ATTACHDETACH_FATAL_ERROR_IF_FAILED(hr);
  2508. // Still do the pass on the function's entrypoint to reflect its state with the functionbody's entrypoint.
  2509. this->UpdateRecyclerFunctionEntryPointsForDebugger();
  2510. OUTPUT_TRACE(Js::DebuggerPhase, _u("ScriptContext::OnDebuggerDetached: done 0x%p, hr = 0x%X\n"), this, hr);
  2511. return hr;
  2512. }
  2513. HRESULT ScriptContext::OnDebuggerAttachedDetached(bool attach)
  2514. {
  2515. // notify threadContext that debugger is attaching so do not do expire
  2516. struct AutoRestore
  2517. {
  2518. AutoRestore(ThreadContext* threadContext)
  2519. :threadContext(threadContext)
  2520. {
  2521. this->threadContext->GetDebugManager()->SetDebuggerAttaching(true);
  2522. }
  2523. ~AutoRestore()
  2524. {
  2525. this->threadContext->GetDebugManager()->SetDebuggerAttaching(false);
  2526. }
  2527. private:
  2528. ThreadContext* threadContext;
  2529. } autoRestore(this->GetThreadContext());
  2530. if (!Js::Configuration::Global.EnableJitInDebugMode())
  2531. {
  2532. if (attach)
  2533. {
  2534. // Now force nonative, so the job will not be put in jit queue.
  2535. ForceNoNative();
  2536. }
  2537. else
  2538. {
  2539. // Take the runtime out of interpreted mode so the JIT
  2540. // queue can be exercised.
  2541. this->ForceNative();
  2542. }
  2543. }
  2544. // Invalidate all the caches.
  2545. this->threadContext->InvalidateAllProtoInlineCaches();
  2546. this->threadContext->InvalidateAllStoreFieldInlineCaches();
  2547. this->threadContext->InvalidateAllIsInstInlineCaches();
  2548. if (!attach)
  2549. {
  2550. this->UnRegisterDebugThunk();
  2551. // Remove all breakpoint probes
  2552. this->GetDebugContext()->GetProbeContainer()->RemoveAllProbes();
  2553. }
  2554. HRESULT hr = S_OK;
  2555. if (!CONFIG_FLAG(ForceDiagnosticsMode))
  2556. {
  2557. #if ENABLE_NATIVE_CODEGEN
  2558. // Recreate the native code generator so that all pending
  2559. // JIT work items will be cleared.
  2560. hr = RecreateNativeCodeGenerator();
  2561. if (FAILED(hr))
  2562. {
  2563. return hr;
  2564. }
  2565. #endif
  2566. if (attach)
  2567. {
  2568. // We need to transition to debug mode after the NativeCodeGenerator is cleared/closed. Since the NativeCodeGenerator will be working on a different thread - it may
  2569. // be checking on the DebuggerState (from ScriptContext) while emitting code.
  2570. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::Debugging);
  2571. #if ENABLE_NATIVE_CODEGEN
  2572. UpdateNativeCodeGeneratorForDebugMode(this->nativeCodeGen);
  2573. #endif
  2574. }
  2575. }
  2576. else if (attach)
  2577. {
  2578. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::Debugging);
  2579. }
  2580. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  2581. {
  2582. // Remap all the function entry point thunks.
  2583. this->sourceList->Map([=](uint i, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef) {
  2584. Js::Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
  2585. if (sourceInfo != nullptr)
  2586. {
  2587. if (!sourceInfo->GetIsLibraryCode())
  2588. {
  2589. sourceInfo->SetInDebugMode(attach);
  2590. sourceInfo->MapFunction([](Js::FunctionBody* functionBody) {
  2591. functionBody->SetEntryToDeferParseForDebugger();
  2592. });
  2593. }
  2594. else
  2595. {
  2596. sourceInfo->MapFunction([](Js::FunctionBody* functionBody) {
  2597. functionBody->ResetEntryPoint();
  2598. });
  2599. }
  2600. }
  2601. });
  2602. }
  2603. END_TRANSLATE_OOM_TO_HRESULT(hr);
  2604. if (FAILED(hr))
  2605. {
  2606. return hr;
  2607. }
  2608. if (attach)
  2609. {
  2610. this->RegisterDebugThunk();
  2611. }
  2612. #if ENABLE_PROFILE_INFO
  2613. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  2614. // Reset the dynamic profile list
  2615. if (this->profileInfoList)
  2616. {
  2617. this->profileInfoList->Reset();
  2618. }
  2619. #endif
  2620. #endif
  2621. return hr;
  2622. }
  2623. // We use ProfileThunk under debugger.
  2624. void ScriptContext::RegisterDebugThunk(bool calledDuringAttach /*= true*/)
  2625. {
  2626. if (this->IsExceptionWrapperForBuiltInsEnabled())
  2627. {
  2628. #ifdef ENABLE_SCRIPT_PROFILING
  2629. this->CurrentThunk = ProfileEntryThunk;
  2630. this->CurrentCrossSiteThunk = CrossSite::ProfileThunk;
  2631. #if ENABLE_NATIVE_CODEGEN
  2632. SetProfileModeNativeCodeGen(this->GetNativeCodeGenerator(), TRUE);
  2633. #endif
  2634. // Set library to profile mode so that for built-ins all new instances of functions
  2635. // are created with entry point set to the ProfileThunk.
  2636. this->javascriptLibrary->SetProfileMode(true);
  2637. this->javascriptLibrary->SetDispatchProfile(true, DispatchProfileInvoke);
  2638. if (!calledDuringAttach)
  2639. {
  2640. #ifdef ENABLE_SCRIPT_PROFILING
  2641. m_fTraceDomCall = TRUE; // This flag is always needed in DebugMode to wrap external functions with DebugProfileThunk
  2642. #endif
  2643. // Update the function objects currently present in there.
  2644. this->SetFunctionInRecyclerToProfileMode(true/*enumerateNonUserFunctionsOnly*/);
  2645. }
  2646. #else
  2647. AssertMsg(false, "Profiling needs to be enabled to call RegisterDebugThunk");
  2648. #endif
  2649. }
  2650. }
  2651. void ScriptContext::UnRegisterDebugThunk()
  2652. {
  2653. if (!this->IsProfiling() && this->IsExceptionWrapperForBuiltInsEnabled())
  2654. {
  2655. this->CurrentThunk = DefaultEntryThunk;
  2656. this->CurrentCrossSiteThunk = CrossSite::DefaultThunk;
  2657. #if ENABLE_NATIVE_CODEGEN
  2658. SetProfileModeNativeCodeGen(this->GetNativeCodeGenerator(), FALSE);
  2659. #endif
  2660. if (!this->IsProfiling())
  2661. {
  2662. this->javascriptLibrary->SetProfileMode(false);
  2663. this->javascriptLibrary->SetDispatchProfile(false, DispatchDefaultInvoke);
  2664. }
  2665. }
  2666. }
  2667. #ifdef ENABLE_SCRIPT_PROFILING
  2668. HRESULT ScriptContext::RegisterBuiltinFunctions(RegisterExternalLibraryType RegisterExternalLibrary)
  2669. {
  2670. Assert(m_pProfileCallback != NULL);
  2671. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterBuiltinFunctions\n"));
  2672. HRESULT hr = S_OK;
  2673. // Consider creating ProfileArena allocator instead of General allocator
  2674. if (m_pBuiltinFunctionIdMap == NULL)
  2675. {
  2676. // Anew throws if it OOMs, so the caller into this function needs to handle that exception
  2677. m_pBuiltinFunctionIdMap = Anew(GeneralAllocator(), BuiltinFunctionIdDictionary,
  2678. GeneralAllocator(), 17);
  2679. }
  2680. this->javascriptLibrary->SetProfileMode(TRUE);
  2681. if (FAILED(hr = OnScriptCompiled(BuiltInFunctionsScriptId, PROFILER_SCRIPT_TYPE_NATIVE, NULL)))
  2682. {
  2683. return hr;
  2684. }
  2685. if (FAILED(hr = this->javascriptLibrary->ProfilerRegisterBuiltIns()))
  2686. {
  2687. return hr;
  2688. }
  2689. // External Library
  2690. if (RegisterExternalLibrary != NULL)
  2691. {
  2692. (*RegisterExternalLibrary)(this);
  2693. }
  2694. return hr;
  2695. }
  2696. void ScriptContext::SetFunctionInRecyclerToProfileMode(bool enumerateNonUserFunctionsOnly/* = false*/)
  2697. {
  2698. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::SetFunctionInRecyclerToProfileMode started (m_fTraceDomCall : %s)\n"), IsTrueOrFalse(m_fTraceDomCall));
  2699. // Mark this script context isEnumeratingRecyclerObjects
  2700. AutoEnumeratingRecyclerObjects enumeratingRecyclerObjects(this);
  2701. m_enumerateNonUserFunctionsOnly = enumerateNonUserFunctionsOnly;
  2702. this->recycler->EnumerateObjects(JavascriptLibrary::EnumFunctionClass, &ScriptContext::RecyclerEnumClassEnumeratorCallback);
  2703. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::SetFunctionInRecyclerToProfileMode ended\n"));
  2704. }
  2705. #endif // ENABLE_SCRIPT_PROFILING
  2706. void ScriptContext::UpdateRecyclerFunctionEntryPointsForDebugger()
  2707. {
  2708. // Mark this script context isEnumeratingRecyclerObjects
  2709. AutoEnumeratingRecyclerObjects enumeratingRecyclerObjects(this);
  2710. this->recycler->EnumerateObjects(JavascriptLibrary::EnumFunctionClass, &ScriptContext::RecyclerFunctionCallbackForDebugger);
  2711. }
  2712. #ifdef ASMJS_PLAT
  2713. void ScriptContext::TransitionEnvironmentForDebugger(ScriptFunction * scriptFunction)
  2714. {
  2715. if (scriptFunction->GetScriptContext()->IsScriptContextInDebugMode() &&
  2716. scriptFunction->GetFunctionBody()->IsInDebugMode() &&
  2717. scriptFunction->GetFunctionBody()->GetAsmJsFunctionInfo() != nullptr &&
  2718. scriptFunction->GetFunctionBody()->GetAsmJsFunctionInfo()->GetModuleFunctionBody() != nullptr)
  2719. {
  2720. void* env = scriptFunction->GetEnvironment()->GetItem(0);
  2721. SList<AsmJsScriptFunction*> * funcList = nullptr;
  2722. if (asmJsEnvironmentMap->TryGetValue(env, &funcList))
  2723. {
  2724. funcList->Push((AsmJsScriptFunction*)scriptFunction);
  2725. }
  2726. else
  2727. {
  2728. SList<AsmJsScriptFunction*> * newList = Anew(debugTransitionAlloc, SList<AsmJsScriptFunction*>, debugTransitionAlloc);
  2729. asmJsEnvironmentMap->AddNew(env, newList);
  2730. newList->Push((AsmJsScriptFunction*)scriptFunction);
  2731. }
  2732. }
  2733. }
  2734. #endif
  2735. /*static*/
  2736. void ScriptContext::RecyclerFunctionCallbackForDebugger(void *address, size_t size)
  2737. {
  2738. JavascriptFunction *pFunction = (JavascriptFunction *)address;
  2739. ScriptContext* scriptContext = pFunction->GetScriptContext();
  2740. if (scriptContext == nullptr || scriptContext->IsClosed())
  2741. {
  2742. // Can't enumerate from closed scriptcontext
  2743. return;
  2744. }
  2745. if (!scriptContext->IsEnumeratingRecyclerObjects())
  2746. {
  2747. return; // function not from enumerating script context
  2748. }
  2749. // Wrapped function are not allocated with the EnumClass bit
  2750. Assert(pFunction->GetFunctionInfo() != &JavascriptExternalFunction::EntryInfo::WrappedFunctionThunk);
  2751. JavascriptMethod entryPoint = pFunction->GetEntryPoint();
  2752. FunctionInfo * info = pFunction->GetFunctionInfo();
  2753. FunctionProxy * proxy = info->GetFunctionProxy();
  2754. if (proxy != info)
  2755. {
  2756. #ifdef ENABLE_SCRIPT_PROFILING
  2757. // Not a script function or, the thunk can deal with moving to the function body
  2758. Assert(proxy == nullptr || entryPoint == DefaultDeferredParsingThunk
  2759. || entryPoint == ProfileDeferredParsingThunk
  2760. || entryPoint == ProfileDeferredDeserializeThunk
  2761. || entryPoint == CrossSite::ProfileThunk
  2762. || entryPoint == DefaultDeferredDeserializeThunk
  2763. || entryPoint == CrossSite::DefaultThunk);
  2764. #else
  2765. // Not a script function or, the thunk can deal with moving to the function body
  2766. Assert(proxy == nullptr || entryPoint == DefaultDeferredParsingThunk
  2767. || entryPoint == DefaultDeferredDeserializeThunk
  2768. || entryPoint == CrossSite::DefaultThunk);
  2769. #endif
  2770. // Replace entry points for built-ins/external/winrt functions so that we can wrap them with try-catch for "continue after exception".
  2771. if (!pFunction->IsScriptFunction() && IsExceptionWrapperForBuiltInsEnabled(scriptContext))
  2772. {
  2773. #ifdef ENABLE_SCRIPT_PROFILING
  2774. if (scriptContext->IsScriptContextInDebugMode())
  2775. {
  2776. // We are attaching.
  2777. // For built-ins, WinRT and DOM functions which are already in recycler, change entry points to route to debug/profile thunk.
  2778. ScriptContext::SetEntryPointToProfileThunk(pFunction);
  2779. }
  2780. else
  2781. {
  2782. // We are detaching.
  2783. // For built-ins, WinRT and DOM functions which are already in recycler, restore entry points to original.
  2784. if (!scriptContext->IsProfiling())
  2785. {
  2786. ScriptContext::RestoreEntryPointFromProfileThunk(pFunction);
  2787. }
  2788. // If we are profiling, don't change anything.
  2789. }
  2790. #else
  2791. AssertMsg(false, "Profiling needs to be enabled to change thunks for debugging");
  2792. #endif
  2793. }
  2794. return;
  2795. }
  2796. if (!proxy->IsFunctionBody())
  2797. {
  2798. // REVIEW: why we still have function that is still deferred?
  2799. return;
  2800. }
  2801. Assert(pFunction->IsScriptFunction());
  2802. // Excluding the internal library code, which is not debuggable already
  2803. if (!proxy->GetUtf8SourceInfo()->GetIsLibraryCode())
  2804. {
  2805. // Reset the constructor cache to default, so that it will not pick up the cached type, created before debugging.
  2806. // Look bug: 301517
  2807. pFunction->ResetConstructorCacheToDefault();
  2808. }
  2809. if (ScriptFunctionWithInlineCache::Is(pFunction))
  2810. {
  2811. ScriptFunctionWithInlineCache::FromVar(pFunction)->ClearInlineCacheOnFunctionObject();
  2812. }
  2813. // We should have force parsed the function, and have a function body
  2814. FunctionBody * pBody = proxy->GetFunctionBody();
  2815. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2816. if (scriptContext->IsScriptContextInDebugMode() && !proxy->GetUtf8SourceInfo()->GetIsLibraryCode() && !pBody->IsInDebugMode())
  2817. {
  2818. // Identifying if any function escaped for not being in debug mode. (This can be removed as a part of TFS : 935011)
  2819. Throw::FatalInternalError();
  2820. }
  2821. #endif
  2822. ScriptFunction * scriptFunction = ScriptFunction::FromVar(pFunction);
  2823. #ifdef ASMJS_PLAT
  2824. scriptContext->TransitionEnvironmentForDebugger(scriptFunction);
  2825. #endif
  2826. JavascriptMethod newEntryPoint;
  2827. if (CrossSite::IsThunk(entryPoint))
  2828. {
  2829. // Can't change from cross-site to non-cross-site, but still need to update the e.p.info on ScriptFunctionType.
  2830. newEntryPoint = entryPoint;
  2831. }
  2832. else
  2833. {
  2834. newEntryPoint = pBody->GetDirectEntryPoint(pBody->GetDefaultFunctionEntryPointInfo());
  2835. }
  2836. scriptFunction->ChangeEntryPoint(pBody->GetDefaultFunctionEntryPointInfo(), newEntryPoint);
  2837. }
  2838. #ifdef ENABLE_SCRIPT_PROFILING
  2839. void ScriptContext::RecyclerEnumClassEnumeratorCallback(void *address, size_t size)
  2840. {
  2841. // TODO: we are assuming its function because for now we are enumerating only on functions
  2842. // In future if the RecyclerNewEnumClass is used of Recyclable objects or Dynamic object, we would need a check if it is function
  2843. JavascriptFunction *pFunction = (JavascriptFunction *)address;
  2844. ScriptContext* scriptContext = pFunction->GetScriptContext();
  2845. if (scriptContext == nullptr || scriptContext->IsClosed())
  2846. {
  2847. // Can't enumerate from closed scriptcontext
  2848. return;
  2849. }
  2850. if (!scriptContext->IsEnumeratingRecyclerObjects())
  2851. {
  2852. return; // function not from enumerating script context
  2853. }
  2854. if (!scriptContext->IsTraceDomCall() && (pFunction->IsExternalFunction() || pFunction->IsWinRTFunction()))
  2855. {
  2856. return;
  2857. }
  2858. if (scriptContext->IsEnumerateNonUserFunctionsOnly() && pFunction->IsScriptFunction())
  2859. {
  2860. return;
  2861. }
  2862. // Wrapped function are not allocated with the EnumClass bit
  2863. Assert(pFunction->GetFunctionInfo() != &JavascriptExternalFunction::EntryInfo::WrappedFunctionThunk);
  2864. JavascriptMethod entryPoint = pFunction->GetEntryPoint();
  2865. FunctionProxy *proxy = pFunction->GetFunctionProxy();
  2866. if (proxy != NULL)
  2867. {
  2868. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2869. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2870. #endif
  2871. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RecyclerEnumClassEnumeratorCallback\n"));
  2872. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\tFunctionProxy : 0x%08X, FunctionNumber : %s, DeferredParseAttributes : %d, EntryPoint : 0x%08X"),
  2873. (DWORD_PTR)proxy, proxy->GetDebugNumberSet(debugStringBuffer), proxy->GetAttributes(), (DWORD_PTR)entryPoint);
  2874. #if ENABLE_NATIVE_CODEGEN
  2875. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u(" (IsIntermediateCodeGenThunk : %s, isNative : %s)\n"),
  2876. IsTrueOrFalse(IsIntermediateCodeGenThunk(entryPoint)), IsTrueOrFalse(scriptContext->IsNativeAddress(entryPoint)));
  2877. #endif
  2878. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\n"));
  2879. FunctionInfo * info = pFunction->GetFunctionInfo();
  2880. if (proxy != info)
  2881. {
  2882. // The thunk can deal with moving to the function body
  2883. #ifdef ENABLE_SCRIPT_PROFILING
  2884. Assert(entryPoint == DefaultDeferredParsingThunk || entryPoint == ProfileDeferredParsingThunk
  2885. || entryPoint == DefaultDeferredDeserializeThunk || entryPoint == ProfileDeferredDeserializeThunk
  2886. || entryPoint == CrossSite::DefaultThunk || entryPoint == CrossSite::ProfileThunk);
  2887. #else
  2888. Assert(entryPoint == DefaultDeferredParsingThunk
  2889. || entryPoint == DefaultDeferredDeserializeThunk
  2890. || entryPoint == CrossSite::DefaultThunk);
  2891. #endif
  2892. Assert(!proxy->IsDeferred());
  2893. Assert(proxy->GetFunctionBody()->GetProfileSession() == proxy->GetScriptContext()->GetProfileSession());
  2894. return;
  2895. }
  2896. #if ENABLE_NATIVE_CODEGEN
  2897. if (!IsIntermediateCodeGenThunk(entryPoint) && entryPoint != DynamicProfileInfo::EnsureDynamicProfileInfoThunk)
  2898. #endif
  2899. {
  2900. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\t\tJs::ScriptContext::GetProfileModeThunk : 0x%08X\n"), (DWORD_PTR)Js::ScriptContext::GetProfileModeThunk(entryPoint));
  2901. ScriptFunction * scriptFunction = ScriptFunction::FromVar(pFunction);
  2902. scriptFunction->ChangeEntryPoint(proxy->GetDefaultEntryPointInfo(), Js::ScriptContext::GetProfileModeThunk(entryPoint));
  2903. #if ENABLE_NATIVE_CODEGEN
  2904. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\tUpdated entrypoint : 0x%08X (isNative : %s)\n"), (DWORD_PTR)pFunction->GetEntryPoint(), IsTrueOrFalse(scriptContext->IsNativeAddress(entryPoint)));
  2905. #endif
  2906. }
  2907. }
  2908. else
  2909. {
  2910. ScriptContext::SetEntryPointToProfileThunk(pFunction);
  2911. }
  2912. }
  2913. // static
  2914. void ScriptContext::SetEntryPointToProfileThunk(JavascriptFunction* function)
  2915. {
  2916. JavascriptMethod entryPoint = function->GetEntryPoint();
  2917. if (entryPoint == Js::CrossSite::DefaultThunk)
  2918. {
  2919. function->SetEntryPoint(Js::CrossSite::ProfileThunk);
  2920. }
  2921. else if (entryPoint != Js::CrossSite::ProfileThunk && entryPoint != ProfileEntryThunk)
  2922. {
  2923. function->SetEntryPoint(ProfileEntryThunk);
  2924. }
  2925. }
  2926. // static
  2927. void ScriptContext::RestoreEntryPointFromProfileThunk(JavascriptFunction* function)
  2928. {
  2929. JavascriptMethod entryPoint = function->GetEntryPoint();
  2930. if (entryPoint == Js::CrossSite::ProfileThunk)
  2931. {
  2932. function->SetEntryPoint(Js::CrossSite::DefaultThunk);
  2933. }
  2934. else if (entryPoint == ProfileEntryThunk)
  2935. {
  2936. function->SetEntryPoint(function->GetFunctionInfo()->GetOriginalEntryPoint());
  2937. }
  2938. }
  2939. JavascriptMethod ScriptContext::GetProfileModeThunk(JavascriptMethod entryPoint)
  2940. {
  2941. #if ENABLE_NATIVE_CODEGEN
  2942. Assert(!IsIntermediateCodeGenThunk(entryPoint));
  2943. #endif
  2944. if (entryPoint == DefaultDeferredParsingThunk || entryPoint == ProfileDeferredParsingThunk)
  2945. {
  2946. return ProfileDeferredParsingThunk;
  2947. }
  2948. if (entryPoint == DefaultDeferredDeserializeThunk || entryPoint == ProfileDeferredDeserializeThunk)
  2949. {
  2950. return ProfileDeferredDeserializeThunk;
  2951. }
  2952. if (CrossSite::IsThunk(entryPoint))
  2953. {
  2954. return CrossSite::ProfileThunk;
  2955. }
  2956. return ProfileEntryThunk;
  2957. }
  2958. #endif // ENABLE_SCRIPT_PROFILING
  2959. #if _M_IX86
  2960. __declspec(naked)
  2961. Var ScriptContext::ProfileModeDeferredParsingThunk(RecyclableObject* function, CallInfo callInfo, ...)
  2962. {
  2963. // Register functions
  2964. __asm
  2965. {
  2966. push ebp
  2967. mov ebp, esp
  2968. lea eax, [esp + 8]
  2969. push eax
  2970. call ScriptContext::ProfileModeDeferredParse
  2971. #ifdef _CONTROL_FLOW_GUARD
  2972. // verify that the call target is valid
  2973. mov ecx, eax
  2974. call[__guard_check_icall_fptr]
  2975. mov eax, ecx
  2976. #endif
  2977. pop ebp
  2978. // Although we don't restore ESP here on WinCE, this is fine because script profiler is not shipped for WinCE.
  2979. jmp eax
  2980. }
  2981. }
  2982. #elif defined(_M_X64) || defined(_M_ARM32_OR_ARM64)
  2983. // Do nothing: the implementation of ScriptContext::ProfileModeDeferredParsingThunk is declared (appropriately decorated) in
  2984. // Language\amd64\amd64_Thunks.asm and Language\arm\arm_Thunks.asm and Language\arm64\arm64_Thunks.asm respectively.
  2985. #else
  2986. Var ScriptContext::ProfileModeDeferredParsingThunk(RecyclableObject* function, CallInfo callInfo, ...)
  2987. {
  2988. Js::Throw::NotImplemented();
  2989. return nullptr;
  2990. }
  2991. #endif
  2992. Js::JavascriptMethod ScriptContext::ProfileModeDeferredParse(ScriptFunction ** functionRef)
  2993. {
  2994. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2995. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2996. #endif
  2997. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::ProfileModeDeferredParse FunctionNumber : %s, startEntrypoint : 0x%08X\n"), (*functionRef)->GetFunctionProxy()->GetDebugNumberSet(debugStringBuffer), (*functionRef)->GetEntryPoint());
  2998. BOOL fParsed = FALSE;
  2999. JavascriptMethod entryPoint = Js::JavascriptFunction::DeferredParseCore(functionRef, fParsed);
  3000. #ifdef ENABLE_SCRIPT_PROFILING
  3001. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\t\tIsParsed : %s, updatedEntrypoint : 0x%08X\n"), IsTrueOrFalse(fParsed), entryPoint);
  3002. //To get the scriptContext we only need the functionProxy
  3003. FunctionProxy *pRootBody = (*functionRef)->GetFunctionProxy();
  3004. ScriptContext *pScriptContext = pRootBody->GetScriptContext();
  3005. if (pScriptContext->IsProfiling() && !pRootBody->GetFunctionBody()->HasFunctionCompiledSent())
  3006. {
  3007. pScriptContext->RegisterScript(pRootBody, FALSE /*fRegisterScript*/);
  3008. }
  3009. // We can come to this function even though we have stopped profiling.
  3010. Assert(!pScriptContext->IsProfiling() || (*functionRef)->GetFunctionBody()->GetProfileSession() == pScriptContext->GetProfileSession());
  3011. #endif
  3012. return entryPoint;
  3013. }
  3014. #if _M_IX86
  3015. __declspec(naked)
  3016. Var ScriptContext::ProfileModeDeferredDeserializeThunk(RecyclableObject* function, CallInfo callInfo, ...)
  3017. {
  3018. // Register functions
  3019. __asm
  3020. {
  3021. push ebp
  3022. mov ebp, esp
  3023. push[esp + 8]
  3024. call ScriptContext::ProfileModeDeferredDeserialize
  3025. #ifdef _CONTROL_FLOW_GUARD
  3026. // verify that the call target is valid
  3027. mov ecx, eax
  3028. call[__guard_check_icall_fptr]
  3029. mov eax, ecx
  3030. #endif
  3031. pop ebp
  3032. // Although we don't restore ESP here on WinCE, this is fine because script profiler is not shipped for WinCE.
  3033. jmp eax
  3034. }
  3035. }
  3036. #elif defined(_M_X64) || defined(_M_ARM32_OR_ARM64)
  3037. // Do nothing: the implementation of ScriptContext::ProfileModeDeferredDeserializeThunk is declared (appropriately decorated) in
  3038. // Language\amd64\amd64_Thunks.asm and Language\arm\arm_Thunks.asm respectively.
  3039. #endif
  3040. Js::JavascriptMethod ScriptContext::ProfileModeDeferredDeserialize(ScriptFunction *function)
  3041. {
  3042. #if ENABLE_DEBUG_CONFIG_OPTIONS
  3043. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3044. #endif
  3045. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::ProfileModeDeferredDeserialize FunctionNumber : %s\n"), function->GetFunctionProxy()->GetDebugNumberSet(debugStringBuffer));
  3046. JavascriptMethod entryPoint = Js::JavascriptFunction::DeferredDeserialize(function);
  3047. #ifdef ENABLE_SCRIPT_PROFILING
  3048. //To get the scriptContext; we only need the FunctionProxy
  3049. FunctionProxy *pRootBody = function->GetFunctionProxy();
  3050. ScriptContext *pScriptContext = pRootBody->GetScriptContext();
  3051. if (pScriptContext->IsProfiling() && !pRootBody->GetFunctionBody()->HasFunctionCompiledSent())
  3052. {
  3053. pScriptContext->RegisterScript(pRootBody, FALSE /*fRegisterScript*/);
  3054. }
  3055. // We can come to this function even though we have stopped profiling.
  3056. Assert(!pScriptContext->IsProfiling() || function->GetFunctionBody()->GetProfileSession() == pScriptContext->GetProfileSession());
  3057. #endif
  3058. return entryPoint;
  3059. }
  3060. #ifdef ENABLE_SCRIPT_PROFILING
  3061. BOOL ScriptContext::GetProfileInfo(
  3062. JavascriptFunction* function,
  3063. PROFILER_TOKEN &scriptId,
  3064. PROFILER_TOKEN &functionId)
  3065. {
  3066. BOOL fCanProfile = (m_pProfileCallback != nullptr && m_fTraceFunctionCall);
  3067. if (!fCanProfile)
  3068. {
  3069. return FALSE;
  3070. }
  3071. Js::FunctionInfo* functionInfo = function->GetFunctionInfo();
  3072. if (functionInfo->GetAttributes() & FunctionInfo::DoNotProfile)
  3073. {
  3074. return FALSE;
  3075. }
  3076. Js::FunctionBody * functionBody = functionInfo->GetFunctionBody();
  3077. if (functionBody == nullptr)
  3078. {
  3079. functionId = GetFunctionNumber(functionInfo->GetOriginalEntryPoint());
  3080. if (functionId == -1)
  3081. {
  3082. // Dom Call
  3083. return m_fTraceDomCall && (m_pProfileCallback2 != nullptr);
  3084. }
  3085. else
  3086. {
  3087. // Builtin function
  3088. scriptId = BuiltInFunctionsScriptId;
  3089. return m_fTraceNativeFunctionCall;
  3090. }
  3091. }
  3092. else if (!functionBody->GetUtf8SourceInfo()->GetIsLibraryCode() || functionBody->IsPublicLibraryCode()) // user script or public library code
  3093. {
  3094. scriptId = (PROFILER_TOKEN)functionBody->GetUtf8SourceInfo()->GetSourceInfoId();
  3095. functionId = functionBody->GetFunctionNumber();
  3096. return TRUE;
  3097. }
  3098. return FALSE;
  3099. }
  3100. #endif // ENABLE_SCRIPT_PROFILING
  3101. bool ScriptContext::IsForceNoNative()
  3102. {
  3103. bool forceNoNative = false;
  3104. if (this->IsScriptContextInSourceRundownOrDebugMode())
  3105. {
  3106. forceNoNative = this->IsInterpreted();
  3107. }
  3108. else if (!Js::Configuration::Global.EnableJitInDebugMode())
  3109. {
  3110. forceNoNative = true;
  3111. this->ForceNoNative();
  3112. }
  3113. return forceNoNative;
  3114. }
  3115. void ScriptContext::InitializeDebugging()
  3116. {
  3117. if (!this->IsScriptContextInDebugMode()) // If we already in debug mode, we would have done below changes already.
  3118. {
  3119. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::Debugging);
  3120. if (this->IsScriptContextInDebugMode())
  3121. {
  3122. // Note: for this we need final IsInDebugMode and NativeCodeGen initialized,
  3123. // and inside EnsureScriptContext, which seems appropriate as well,
  3124. // it's too early as debugger manager is not registered, thus IsDebuggerEnvironmentAvailable is false.
  3125. this->RegisterDebugThunk(false/*calledDuringAttach*/);
  3126. // TODO: for launch scenario for external and WinRT functions it might be too late to register debug thunk here,
  3127. // as we need the thunk registered before FunctionInfo's for built-ins, that may throw, are created.
  3128. // Need to verify. If that's the case, one way would be to enumerate and fix all external/winRT thunks here.
  3129. }
  3130. }
  3131. }
  3132. // Combined profile/debug wrapper thunk.
  3133. // - used when we profile to send profile events
  3134. // - used when we debug, only used for built-in functions
  3135. // - used when we profile and debug
  3136. Var ScriptContext::DebugProfileProbeThunk(RecyclableObject* callable, CallInfo callInfo, ...)
  3137. {
  3138. #if defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  3139. RUNTIME_ARGUMENTS(args, callInfo);
  3140. JavascriptFunction* function = JavascriptFunction::FromVar(callable);
  3141. ScriptContext* scriptContext = function->GetScriptContext();
  3142. PROFILER_TOKEN scriptId = -1;
  3143. PROFILER_TOKEN functionId = -1;
  3144. bool functionEnterEventSent = false;
  3145. const bool isProfilingUserCode = scriptContext->GetThreadContext()->IsProfilingUserCode();
  3146. const bool isUserCode = !function->IsLibraryCode();
  3147. char16 *pwszExtractedFunctionName = NULL;
  3148. const char16 *pwszFunctionName = NULL;
  3149. HRESULT hrOfEnterEvent = S_OK;
  3150. // We can come here when profiling is not on
  3151. // e.g. User starts profiling, we update all thinks and then stop profiling - we don't update thunk
  3152. // So we still get this call
  3153. const bool fProfile = (isUserCode || isProfilingUserCode) // Only report user code or entry library code
  3154. && scriptContext->GetProfileInfo(function, scriptId, functionId);
  3155. if (fProfile)
  3156. {
  3157. Js::FunctionBody *pBody = function->GetFunctionBody();
  3158. if (pBody != nullptr && !pBody->HasFunctionCompiledSent())
  3159. {
  3160. pBody->RegisterFunction(false/*changeThunk*/);
  3161. }
  3162. #if DEBUG
  3163. { // scope
  3164. Assert(scriptContext->IsProfiling());
  3165. if (pBody && pBody->GetProfileSession() != pBody->GetScriptContext()->GetProfileSession())
  3166. {
  3167. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3168. OUTPUT_TRACE_DEBUGONLY(Js::ScriptProfilerPhase, _u("ScriptContext::ProfileProbeThunk, ProfileSession does not match (%d != %d), functionNumber : %s, functionName : %s\n"),
  3169. pBody->GetProfileSession(), pBody->GetScriptContext()->GetProfileSession(), pBody->GetDebugNumberSet(debugStringBuffer), pBody->GetDisplayName());
  3170. }
  3171. AssertMsg(pBody == NULL || pBody->GetProfileSession() == pBody->GetScriptContext()->GetProfileSession(), "Function info wasn't reported for this profile session");
  3172. }
  3173. #endif
  3174. if (functionId == -1)
  3175. {
  3176. Var sourceString = function->GetSourceString();
  3177. // SourceString will be null for the Js::BoundFunction, don't throw Enter/Exit notification in that case.
  3178. if (sourceString != NULL)
  3179. {
  3180. if (TaggedInt::Is(sourceString))
  3181. {
  3182. PropertyId nameId = TaggedInt::ToInt32(sourceString);
  3183. pwszFunctionName = scriptContext->GetPropertyString(nameId)->GetSz();
  3184. }
  3185. else
  3186. {
  3187. // it is string because user had called in toString extract name from it
  3188. Assert(JavascriptString::Is(sourceString));
  3189. const char16 *pwszToString = ((JavascriptString *)sourceString)->GetSz();
  3190. const char16 *pwszNameStart = wcsstr(pwszToString, _u(" "));
  3191. const char16 *pwszNameEnd = wcsstr(pwszToString, _u("("));
  3192. if (pwszNameStart == nullptr || pwszNameEnd == nullptr || ((int)(pwszNameEnd - pwszNameStart) <= 0))
  3193. {
  3194. int len = ((JavascriptString *)sourceString)->GetLength() + 1;
  3195. pwszExtractedFunctionName = new char16[len];
  3196. wcsncpy_s(pwszExtractedFunctionName, len, pwszToString, _TRUNCATE);
  3197. }
  3198. else
  3199. {
  3200. int len = (int)(pwszNameEnd - pwszNameStart);
  3201. AssertMsg(len > 0, "Allocating array with zero or negative length?");
  3202. pwszExtractedFunctionName = new char16[len];
  3203. wcsncpy_s(pwszExtractedFunctionName, len, pwszNameStart + 1, _TRUNCATE);
  3204. }
  3205. pwszFunctionName = pwszExtractedFunctionName;
  3206. }
  3207. functionEnterEventSent = true;
  3208. Assert(pwszFunctionName != NULL);
  3209. hrOfEnterEvent = scriptContext->OnDispatchFunctionEnter(pwszFunctionName);
  3210. }
  3211. }
  3212. else
  3213. {
  3214. hrOfEnterEvent = scriptContext->OnFunctionEnter(scriptId, functionId);
  3215. }
  3216. scriptContext->GetThreadContext()->SetIsProfilingUserCode(isUserCode); // Update IsProfilingUserCode state
  3217. }
  3218. Var aReturn = NULL;
  3219. JavascriptMethod origEntryPoint = function->GetFunctionInfo()->GetOriginalEntryPoint();
  3220. __try
  3221. {
  3222. Assert(!function->IsScriptFunction() || function->GetFunctionProxy());
  3223. // No need to wrap script functions, also can't if the wrapper is already on the stack.
  3224. // Treat "library code" script functions, such as Intl, as built-ins:
  3225. // use the wrapper when calling them, and do not reset the wrapper when calling them.
  3226. bool isDebugWrapperEnabled = scriptContext->IsScriptContextInDebugMode() && IsExceptionWrapperForBuiltInsEnabled(scriptContext);
  3227. bool useDebugWrapper =
  3228. isDebugWrapperEnabled &&
  3229. function->IsLibraryCode() &&
  3230. !AutoRegisterIgnoreExceptionWrapper::IsRegistered(scriptContext->GetThreadContext());
  3231. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("DebugProfileProbeThunk: calling function: %s isWrapperRegistered=%d useDebugWrapper=%d\n"),
  3232. function->GetFunctionInfo()->HasBody() ? function->GetFunctionBody()->GetDisplayName() : _u("built-in/library"), AutoRegisterIgnoreExceptionWrapper::IsRegistered(scriptContext->GetThreadContext()), useDebugWrapper);
  3233. if (scriptContext->IsScriptContextInDebugMode())
  3234. {
  3235. scriptContext->GetDebugContext()->GetProbeContainer()->StartRecordingCall();
  3236. }
  3237. if (useDebugWrapper)
  3238. {
  3239. // For native use wrapper and bail out on to ignore exception.
  3240. // Extract try-catch out of hot path in normal profile mode (presence of try-catch in a function is bad for perf).
  3241. aReturn = ProfileModeThunk_DebugModeWrapper(function, scriptContext, origEntryPoint, args);
  3242. }
  3243. else
  3244. {
  3245. if (isDebugWrapperEnabled && !function->IsLibraryCode())
  3246. {
  3247. // We want to ignore exception and continue into closest user/script function down on the stack.
  3248. // Thus, if needed, reset the wrapper for the time of this call,
  3249. // so that if there is library/helper call after script function, it will use try-catch.
  3250. // Can't use smart/destructor object here because of __try__finally.
  3251. ThreadContext* threadContext = scriptContext->GetThreadContext();
  3252. bool isOrigWrapperPresent = threadContext->GetDebugManager()->GetDebuggingFlags()->IsBuiltInWrapperPresent();
  3253. if (isOrigWrapperPresent)
  3254. {
  3255. threadContext->GetDebugManager()->GetDebuggingFlags()->SetIsBuiltInWrapperPresent(false);
  3256. }
  3257. __try
  3258. {
  3259. aReturn = JavascriptFunction::CallFunction<true>(function, origEntryPoint, args);
  3260. }
  3261. __finally
  3262. {
  3263. threadContext->GetDebugManager()->GetDebuggingFlags()->SetIsBuiltInWrapperPresent(isOrigWrapperPresent);
  3264. }
  3265. }
  3266. else
  3267. {
  3268. // Can we update return address to a thunk that sends Exit event and then jmp to entry instead of Calling it.
  3269. // Saves stack space and it might be something we would be doing anyway for handling profile.Start/stop
  3270. // which can come anywhere on the stack.
  3271. aReturn = JavascriptFunction::CallFunction<true>(function, origEntryPoint, args);
  3272. }
  3273. }
  3274. }
  3275. __finally
  3276. {
  3277. if (fProfile)
  3278. {
  3279. if (hrOfEnterEvent != ACTIVPROF_E_PROFILER_ABSENT)
  3280. {
  3281. if (functionId == -1)
  3282. {
  3283. // Check whether we have sent the Enter event or not.
  3284. if (functionEnterEventSent)
  3285. {
  3286. scriptContext->OnDispatchFunctionExit(pwszFunctionName);
  3287. if (pwszExtractedFunctionName != NULL)
  3288. {
  3289. delete[]pwszExtractedFunctionName;
  3290. }
  3291. }
  3292. }
  3293. else
  3294. {
  3295. scriptContext->OnFunctionExit(scriptId, functionId);
  3296. }
  3297. }
  3298. scriptContext->GetThreadContext()->SetIsProfilingUserCode(isProfilingUserCode); // Restore IsProfilingUserCode state
  3299. }
  3300. if (scriptContext->IsScriptContextInDebugMode())
  3301. {
  3302. scriptContext->GetDebugContext()->GetProbeContainer()->EndRecordingCall(aReturn, function);
  3303. }
  3304. }
  3305. return aReturn;
  3306. #else
  3307. return nullptr;
  3308. #endif // defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  3309. }
  3310. #ifdef ENABLE_SCRIPT_PROFILING
  3311. // Part of ProfileModeThunk which is called in debug mode (debug or debug & profile).
  3312. Var ScriptContext::ProfileModeThunk_DebugModeWrapper(JavascriptFunction* function, ScriptContext* scriptContext, JavascriptMethod entryPoint, Arguments& args)
  3313. {
  3314. AutoRegisterIgnoreExceptionWrapper autoWrapper(scriptContext->GetThreadContext());
  3315. Var aReturn = HelperOrLibraryMethodWrapper<true>(scriptContext, [=] {
  3316. return JavascriptFunction::CallFunction<true>(function, entryPoint, args);
  3317. });
  3318. return aReturn;
  3319. }
  3320. HRESULT ScriptContext::OnScriptCompiled(PROFILER_TOKEN scriptId, PROFILER_SCRIPT_TYPE type, IUnknown *pIDebugDocumentContext)
  3321. {
  3322. // TODO : can we do a delay send of these events or can we send an event before doing all this stuff that could calculate overhead?
  3323. Assert(m_pProfileCallback != NULL);
  3324. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::OnScriptCompiled scriptId : %d, ScriptType : %d\n"), scriptId, type);
  3325. HRESULT hr = S_OK;
  3326. if ((type == PROFILER_SCRIPT_TYPE_NATIVE && m_fTraceNativeFunctionCall) ||
  3327. (type != PROFILER_SCRIPT_TYPE_NATIVE && m_fTraceFunctionCall))
  3328. {
  3329. m_inProfileCallback = TRUE;
  3330. hr = m_pProfileCallback->ScriptCompiled(scriptId, type, pIDebugDocumentContext);
  3331. m_inProfileCallback = FALSE;
  3332. }
  3333. return hr;
  3334. }
  3335. HRESULT ScriptContext::OnFunctionCompiled(
  3336. PROFILER_TOKEN functionId,
  3337. PROFILER_TOKEN scriptId,
  3338. const WCHAR *pwszFunctionName,
  3339. const WCHAR *pwszFunctionNameHint,
  3340. IUnknown *pIDebugDocumentContext)
  3341. {
  3342. Assert(m_pProfileCallback != NULL);
  3343. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3344. if (scriptId != BuiltInFunctionsScriptId || Js::Configuration::Global.flags.Verbose)
  3345. {
  3346. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::OnFunctionCompiled scriptId : %d, functionId : %d, FunctionName : %s, FunctionNameHint : %s\n"), scriptId, functionId, pwszFunctionName, pwszFunctionNameHint);
  3347. }
  3348. #endif
  3349. HRESULT hr = S_OK;
  3350. if ((scriptId == BuiltInFunctionsScriptId && m_fTraceNativeFunctionCall) ||
  3351. (scriptId != BuiltInFunctionsScriptId && m_fTraceFunctionCall))
  3352. {
  3353. m_inProfileCallback = TRUE;
  3354. hr = m_pProfileCallback->FunctionCompiled(functionId, scriptId, pwszFunctionName, pwszFunctionNameHint, pIDebugDocumentContext);
  3355. m_inProfileCallback = FALSE;
  3356. }
  3357. return hr;
  3358. }
  3359. HRESULT ScriptContext::OnFunctionEnter(PROFILER_TOKEN scriptId, PROFILER_TOKEN functionId)
  3360. {
  3361. if (m_pProfileCallback == NULL)
  3362. {
  3363. return ACTIVPROF_E_PROFILER_ABSENT;
  3364. }
  3365. OUTPUT_VERBOSE_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::OnFunctionEnter scriptId : %d, functionId : %d\n"), scriptId, functionId);
  3366. HRESULT hr = S_OK;
  3367. if ((scriptId == BuiltInFunctionsScriptId && m_fTraceNativeFunctionCall) ||
  3368. (scriptId != BuiltInFunctionsScriptId && m_fTraceFunctionCall))
  3369. {
  3370. m_inProfileCallback = TRUE;
  3371. hr = m_pProfileCallback->OnFunctionEnter(scriptId, functionId);
  3372. m_inProfileCallback = FALSE;
  3373. }
  3374. return hr;
  3375. }
  3376. HRESULT ScriptContext::OnFunctionExit(PROFILER_TOKEN scriptId, PROFILER_TOKEN functionId)
  3377. {
  3378. if (m_pProfileCallback == NULL)
  3379. {
  3380. return ACTIVPROF_E_PROFILER_ABSENT;
  3381. }
  3382. OUTPUT_VERBOSE_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::OnFunctionExit scriptId : %d, functionId : %d\n"), scriptId, functionId);
  3383. HRESULT hr = S_OK;
  3384. if ((scriptId == BuiltInFunctionsScriptId && m_fTraceNativeFunctionCall) ||
  3385. (scriptId != BuiltInFunctionsScriptId && m_fTraceFunctionCall))
  3386. {
  3387. m_inProfileCallback = TRUE;
  3388. hr = m_pProfileCallback->OnFunctionExit(scriptId, functionId);
  3389. m_inProfileCallback = FALSE;
  3390. }
  3391. return hr;
  3392. }
  3393. HRESULT ScriptContext::FunctionExitSenderThunk(PROFILER_TOKEN functionId, PROFILER_TOKEN scriptId, ScriptContext *pScriptContext)
  3394. {
  3395. return pScriptContext->OnFunctionExit(scriptId, functionId);
  3396. }
  3397. HRESULT ScriptContext::FunctionExitByNameSenderThunk(const char16 *pwszFunctionName, ScriptContext *pScriptContext)
  3398. {
  3399. return pScriptContext->OnDispatchFunctionExit(pwszFunctionName);
  3400. }
  3401. #endif // ENABLE_SCRIPT_PROFILING
  3402. Js::PropertyId ScriptContext::GetFunctionNumber(JavascriptMethod entryPoint)
  3403. {
  3404. return (m_pBuiltinFunctionIdMap == NULL) ? -1 : m_pBuiltinFunctionIdMap->Lookup(entryPoint, -1);
  3405. }
  3406. HRESULT ScriptContext::RegisterLibraryFunction(const char16 *pwszObjectName, const char16 *pwszFunctionName, Js::PropertyId functionPropertyId, JavascriptMethod entryPoint)
  3407. {
  3408. #ifdef ENABLE_SCRIPT_PROFILING
  3409. #if DEBUG
  3410. const char16 *pwszObjectNameFromProperty = const_cast<char16 *>(GetPropertyName(functionPropertyId)->GetBuffer());
  3411. if (GetPropertyName(functionPropertyId)->IsSymbol())
  3412. {
  3413. // The spec names functions whose property is a well known symbol as the description from the symbol
  3414. // wrapped in square brackets, so verify by skipping past first bracket
  3415. Assert(!wcsncmp(pwszFunctionName + 1, pwszObjectNameFromProperty, wcslen(pwszObjectNameFromProperty)));
  3416. Assert(wcslen(pwszFunctionName) == wcslen(pwszObjectNameFromProperty) + 2);
  3417. }
  3418. else
  3419. {
  3420. Assert(!wcscmp(pwszFunctionName, pwszObjectNameFromProperty));
  3421. }
  3422. Assert(m_pBuiltinFunctionIdMap != NULL);
  3423. #endif
  3424. // Create the propertyId as object.functionName if it is not global function
  3425. // the global functions would be recognized by just functionName
  3426. // e.g. with functionName, toString, depending on objectName, it could be Object.toString, or Date.toString
  3427. char16 szTempName[70];
  3428. if (pwszObjectName != NULL)
  3429. {
  3430. // Create name as "object.function"
  3431. swprintf_s(szTempName, 70, _u("%s.%s"), pwszObjectName, pwszFunctionName);
  3432. functionPropertyId = GetOrAddPropertyIdTracked(szTempName, (uint)wcslen(szTempName));
  3433. }
  3434. Js::PropertyId cachedFunctionId;
  3435. bool keyFound = m_pBuiltinFunctionIdMap->TryGetValue(entryPoint, &cachedFunctionId);
  3436. if (keyFound)
  3437. {
  3438. // Entry point is already in the map
  3439. if (cachedFunctionId != functionPropertyId)
  3440. {
  3441. // This is the scenario where we could be using same function for multiple builtin functions
  3442. // e.g. Error.toString, WinRTError.toString etc.
  3443. // We would ignore these extra entrypoints because while profiling, identifying which object's toString is too costly for its worth
  3444. return S_OK;
  3445. }
  3446. // else is the scenario where map was created by earlier profiling session and we are yet to send function compiled for this session
  3447. }
  3448. else
  3449. {
  3450. #if DBG
  3451. m_pBuiltinFunctionIdMap->MapUntil([&](JavascriptMethod, Js::PropertyId propertyId) -> bool
  3452. {
  3453. if (functionPropertyId == propertyId)
  3454. {
  3455. Assert(false);
  3456. return true;
  3457. }
  3458. return false;
  3459. });
  3460. #endif
  3461. // throws, this must always be in a function that handles OOM
  3462. m_pBuiltinFunctionIdMap->Add(entryPoint, functionPropertyId);
  3463. }
  3464. // Use name with "Object." if its not a global function
  3465. if (pwszObjectName != NULL)
  3466. {
  3467. return OnFunctionCompiled(functionPropertyId, BuiltInFunctionsScriptId, szTempName, NULL, NULL);
  3468. }
  3469. else
  3470. {
  3471. return OnFunctionCompiled(functionPropertyId, BuiltInFunctionsScriptId, pwszFunctionName, NULL, NULL);
  3472. }
  3473. #else
  3474. return S_OK;
  3475. #endif // ENABLE_SCRIPT_PROFILING
  3476. }
  3477. void ScriptContext::BindReference(void * addr)
  3478. {
  3479. Assert(!this->isClosed);
  3480. Assert(this->guestArena);
  3481. Assert(recycler->IsValidObject(addr));
  3482. #if DBG
  3483. Assert(!bindRef.ContainsKey(addr)); // Make sure we don't bind the same pointer twice
  3484. bindRef.AddNew(addr);
  3485. #endif
  3486. javascriptLibrary->BindReference(addr);
  3487. #ifdef RECYCLER_PERF_COUNTERS
  3488. this->bindReferenceCount++;
  3489. RECYCLER_PERF_COUNTER_INC(BindReference);
  3490. #endif
  3491. }
  3492. #ifdef PROFILE_STRINGS
  3493. StringProfiler* ScriptContext::GetStringProfiler()
  3494. {
  3495. return stringProfiler;
  3496. }
  3497. #endif
  3498. void ScriptContext::FreeFunctionEntryPoint(Js::JavascriptMethod method)
  3499. {
  3500. #if ENABLE_NATIVE_CODEGEN
  3501. FreeNativeCodeGenAllocation(this, method);
  3502. #endif
  3503. }
  3504. void ScriptContext::RegisterProtoInlineCache(InlineCache *pCache, PropertyId propId)
  3505. {
  3506. hasProtoOrStoreFieldInlineCache = true;
  3507. threadContext->RegisterProtoInlineCache(pCache, propId);
  3508. }
  3509. void ScriptContext::InvalidateProtoCaches(const PropertyId propertyId)
  3510. {
  3511. threadContext->InvalidateProtoInlineCaches(propertyId);
  3512. // Because setter inline caches get registered in the store field chain, we must invalidate that
  3513. // chain whenever we invalidate the proto chain.
  3514. threadContext->InvalidateStoreFieldInlineCaches(propertyId);
  3515. #if ENABLE_NATIVE_CODEGEN
  3516. threadContext->InvalidatePropertyGuards(propertyId);
  3517. #endif
  3518. threadContext->InvalidateProtoTypePropertyCaches(propertyId);
  3519. }
  3520. void ScriptContext::InvalidateAllProtoCaches()
  3521. {
  3522. threadContext->InvalidateAllProtoInlineCaches();
  3523. // Because setter inline caches get registered in the store field chain, we must invalidate that
  3524. // chain whenever we invalidate the proto chain.
  3525. threadContext->InvalidateAllStoreFieldInlineCaches();
  3526. #if ENABLE_NATIVE_CODEGEN
  3527. threadContext->InvalidateAllPropertyGuards();
  3528. #endif
  3529. threadContext->InvalidateAllProtoTypePropertyCaches();
  3530. }
  3531. void ScriptContext::RegisterStoreFieldInlineCache(InlineCache *pCache, PropertyId propId)
  3532. {
  3533. hasProtoOrStoreFieldInlineCache = true;
  3534. threadContext->RegisterStoreFieldInlineCache(pCache, propId);
  3535. }
  3536. void ScriptContext::InvalidateStoreFieldCaches(const PropertyId propertyId)
  3537. {
  3538. threadContext->InvalidateStoreFieldInlineCaches(propertyId);
  3539. #if ENABLE_NATIVE_CODEGEN
  3540. threadContext->InvalidatePropertyGuards(propertyId);
  3541. #endif
  3542. }
  3543. void ScriptContext::InvalidateAllStoreFieldCaches()
  3544. {
  3545. threadContext->InvalidateAllStoreFieldInlineCaches();
  3546. }
  3547. void ScriptContext::RegisterIsInstInlineCache(Js::IsInstInlineCache * cache, Js::Var function)
  3548. {
  3549. Assert(JavascriptFunction::FromVar(function)->GetScriptContext() == this);
  3550. hasIsInstInlineCache = true;
  3551. threadContext->RegisterIsInstInlineCache(cache, function);
  3552. }
  3553. #if DBG
  3554. bool ScriptContext::IsIsInstInlineCacheRegistered(Js::IsInstInlineCache * cache, Js::Var function)
  3555. {
  3556. return threadContext->IsIsInstInlineCacheRegistered(cache, function);
  3557. }
  3558. #endif
  3559. void ScriptContext::CleanSourceListInternal(bool calledDuringMark)
  3560. {
  3561. bool fCleanupDocRequired = false;
  3562. for (int i = 0; i < sourceList->Count(); i++)
  3563. {
  3564. if (this->sourceList->IsItemValid(i))
  3565. {
  3566. RecyclerWeakReference<Utf8SourceInfo>* sourceInfoWeakRef = this->sourceList->Item(i);
  3567. Utf8SourceInfo* strongRef = nullptr;
  3568. if (calledDuringMark)
  3569. {
  3570. strongRef = sourceInfoWeakRef->FastGet();
  3571. }
  3572. else
  3573. {
  3574. strongRef = sourceInfoWeakRef->Get();
  3575. }
  3576. if (strongRef == nullptr)
  3577. {
  3578. this->sourceList->RemoveAt(i);
  3579. fCleanupDocRequired = true;
  3580. }
  3581. }
  3582. }
  3583. #ifdef ENABLE_SCRIPT_PROFILING
  3584. // If the sourceList got changed, in we need to refresh the nondebug document list in the profiler mode.
  3585. if (fCleanupDocRequired && m_pProfileCallback != NULL)
  3586. {
  3587. Assert(CleanupDocumentContext != NULL);
  3588. CleanupDocumentContext(this);
  3589. }
  3590. #endif // ENABLE_SCRIPT_PROFILING
  3591. }
  3592. void ScriptContext::ClearScriptContextCaches()
  3593. {
  3594. // Prevent reentrancy for the following work, which is not required to be done on every call to this function including
  3595. // reentrant calls
  3596. if (this->isPerformingNonreentrantWork || !this->hasUsedInlineCache)
  3597. {
  3598. return;
  3599. }
  3600. class AutoCleanup
  3601. {
  3602. private:
  3603. ScriptContext *const scriptContext;
  3604. public:
  3605. AutoCleanup(ScriptContext *const scriptContext) : scriptContext(scriptContext)
  3606. {
  3607. scriptContext->isPerformingNonreentrantWork = true;
  3608. }
  3609. ~AutoCleanup()
  3610. {
  3611. scriptContext->isPerformingNonreentrantWork = false;
  3612. }
  3613. } autoCleanup(this);
  3614. if (this->isScriptContextActuallyClosed)
  3615. {
  3616. return;
  3617. }
  3618. Assert(this->guestArena);
  3619. Assert(this->cache);
  3620. if (EnableEvalMapCleanup())
  3621. {
  3622. // The eval map is not re-entrant, so make sure it's not in the middle of adding an entry
  3623. // Also, don't clean the eval map if the debugger is attached
  3624. if (!this->IsScriptContextInDebugMode())
  3625. {
  3626. if (this->cache->evalCacheDictionary != nullptr)
  3627. {
  3628. this->CleanDynamicFunctionCache<Js::EvalCacheTopLevelDictionary>(this->cache->evalCacheDictionary->GetDictionary());
  3629. }
  3630. if (this->cache->indirectEvalCacheDictionary != nullptr)
  3631. {
  3632. this->CleanDynamicFunctionCache<Js::EvalCacheTopLevelDictionary>(this->cache->indirectEvalCacheDictionary->GetDictionary());
  3633. }
  3634. if (this->cache->newFunctionCache != nullptr)
  3635. {
  3636. this->CleanDynamicFunctionCache<Js::NewFunctionCache>(this->cache->newFunctionCache);
  3637. }
  3638. if (this->hostScriptContext != nullptr)
  3639. {
  3640. this->hostScriptContext->CleanDynamicCodeCache();
  3641. }
  3642. }
  3643. }
  3644. if (REGEX_CONFIG_FLAG(DynamicRegexMruListSize) > 0)
  3645. {
  3646. GetDynamicRegexMap()->RemoveRecentlyUnusedItems();
  3647. }
  3648. CleanSourceListInternal(true);
  3649. }
  3650. void ScriptContext::ClearInlineCaches()
  3651. {
  3652. if (this->hasUsedInlineCache)
  3653. {
  3654. GetInlineCacheAllocator()->ZeroAll();
  3655. this->hasUsedInlineCache = false;
  3656. this->hasProtoOrStoreFieldInlineCache = false;
  3657. }
  3658. Assert(GetInlineCacheAllocator()->IsAllZero());
  3659. }
  3660. void ScriptContext::ClearIsInstInlineCaches()
  3661. {
  3662. if (this->hasIsInstInlineCache)
  3663. {
  3664. GetIsInstInlineCacheAllocator()->ZeroAll();
  3665. this->hasIsInstInlineCache = false;
  3666. }
  3667. Assert(GetIsInstInlineCacheAllocator()->IsAllZero());
  3668. }
  3669. #ifdef PERSISTENT_INLINE_CACHES
  3670. void ScriptContext::ClearInlineCachesWithDeadWeakRefs()
  3671. {
  3672. if (this->hasUsedInlineCache)
  3673. {
  3674. GetInlineCacheAllocator()->ClearCachesWithDeadWeakRefs(this->recycler);
  3675. Assert(GetInlineCacheAllocator()->HasNoDeadWeakRefs(this->recycler));
  3676. }
  3677. }
  3678. #endif
  3679. #if ENABLE_NATIVE_CODEGEN
  3680. void ScriptContext::RegisterConstructorCache(Js::PropertyId propertyId, Js::ConstructorCache* cache)
  3681. {
  3682. this->threadContext->RegisterConstructorCache(propertyId, cache);
  3683. }
  3684. #endif
  3685. void ScriptContext::RegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext()
  3686. {
  3687. Assert(!IsClosed());
  3688. if (registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext == nullptr)
  3689. {
  3690. DoRegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext();
  3691. }
  3692. }
  3693. void ScriptContext::DoRegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext()
  3694. {
  3695. Assert(!IsClosed());
  3696. Assert(registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext == nullptr);
  3697. // this call may throw OOM
  3698. registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext = threadContext->RegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(this);
  3699. }
  3700. void ScriptContext::ClearPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesCaches()
  3701. {
  3702. Assert(registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext != nullptr);
  3703. if (!isFinalized)
  3704. {
  3705. javascriptLibrary->NoPrototypeChainsAreEnsuredToHaveOnlyWritableDataProperties();
  3706. }
  3707. // Caller will unregister the script context from the thread context
  3708. registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext = nullptr;
  3709. }
  3710. JavascriptString * ScriptContext::GetLastNumberToStringRadix10(double value)
  3711. {
  3712. if (value == lastNumberToStringRadix10)
  3713. {
  3714. return cache->lastNumberToStringRadix10String;
  3715. }
  3716. return nullptr;
  3717. }
  3718. void
  3719. ScriptContext::SetLastNumberToStringRadix10(double value, JavascriptString * str)
  3720. {
  3721. lastNumberToStringRadix10 = value;
  3722. cache->lastNumberToStringRadix10String = str;
  3723. }
  3724. bool ScriptContext::GetLastUtcTimeFromStr(JavascriptString * str, double& dbl)
  3725. {
  3726. Assert(str != nullptr);
  3727. if (str != cache->lastUtcTimeFromStrString)
  3728. {
  3729. if (cache->lastUtcTimeFromStrString == nullptr
  3730. || !JavascriptString::Equals(str, cache->lastUtcTimeFromStrString))
  3731. {
  3732. return false;
  3733. }
  3734. }
  3735. dbl = lastUtcTimeFromStr;
  3736. return true;
  3737. }
  3738. void
  3739. ScriptContext::SetLastUtcTimeFromStr(JavascriptString * str, double value)
  3740. {
  3741. lastUtcTimeFromStr = value;
  3742. cache->lastUtcTimeFromStrString = str;
  3743. }
  3744. #if ENABLE_NATIVE_CODEGEN
  3745. BOOL ScriptContext::IsNativeAddress(void * codeAddr)
  3746. {
  3747. return this->GetThreadContext()->IsNativeAddress(codeAddr);
  3748. }
  3749. #endif
  3750. bool ScriptContext::SetDispatchProfile(bool fSet, JavascriptMethod dispatchInvoke)
  3751. {
  3752. if (!fSet)
  3753. {
  3754. this->javascriptLibrary->SetDispatchProfile(false, dispatchInvoke);
  3755. return true;
  3756. }
  3757. #ifdef ENABLE_SCRIPT_PROFILING
  3758. else if (m_fTraceDomCall)
  3759. {
  3760. this->javascriptLibrary->SetDispatchProfile(true, dispatchInvoke);
  3761. return true;
  3762. }
  3763. #endif // ENABLE_SCRIPT_PROFILING
  3764. return false;
  3765. }
  3766. #ifdef ENABLE_SCRIPT_PROFILING
  3767. HRESULT ScriptContext::OnDispatchFunctionEnter(const WCHAR *pwszFunctionName)
  3768. {
  3769. if (m_pProfileCallback2 == NULL)
  3770. {
  3771. return ACTIVPROF_E_PROFILER_ABSENT;
  3772. }
  3773. HRESULT hr = S_OK;
  3774. if (m_fTraceDomCall)
  3775. {
  3776. m_inProfileCallback = TRUE;
  3777. hr = m_pProfileCallback2->OnFunctionEnterByName(pwszFunctionName, PROFILER_SCRIPT_TYPE_DOM);
  3778. m_inProfileCallback = FALSE;
  3779. }
  3780. return hr;
  3781. }
  3782. HRESULT ScriptContext::OnDispatchFunctionExit(const WCHAR *pwszFunctionName)
  3783. {
  3784. if (m_pProfileCallback2 == NULL)
  3785. {
  3786. return ACTIVPROF_E_PROFILER_ABSENT;
  3787. }
  3788. HRESULT hr = S_OK;
  3789. if (m_fTraceDomCall)
  3790. {
  3791. m_inProfileCallback = TRUE;
  3792. hr = m_pProfileCallback2->OnFunctionExitByName(pwszFunctionName, PROFILER_SCRIPT_TYPE_DOM);
  3793. m_inProfileCallback = FALSE;
  3794. }
  3795. return hr;
  3796. }
  3797. #endif // ENABLE_SCRIPT_PROFILING
  3798. void ScriptContext::SetBuiltInLibraryFunction(JavascriptMethod entryPoint, JavascriptFunction* function)
  3799. {
  3800. if (!isClosed)
  3801. {
  3802. if (builtInLibraryFunctions == NULL)
  3803. {
  3804. Assert(this->recycler);
  3805. builtInLibraryFunctions = RecyclerNew(this->recycler, BuiltInLibraryFunctionMap, this->recycler);
  3806. cache->builtInLibraryFunctions = builtInLibraryFunctions;
  3807. }
  3808. builtInLibraryFunctions->Item(entryPoint, function);
  3809. }
  3810. }
  3811. #if ENABLE_NATIVE_CODEGEN
  3812. void ScriptContext::InitializeRemoteScriptContext()
  3813. {
  3814. Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
  3815. ScriptContextDataIDL contextData;
  3816. contextData.nullAddr = (intptr_t)GetLibrary()->GetNull();
  3817. contextData.undefinedAddr = (intptr_t)GetLibrary()->GetUndefined();
  3818. contextData.trueAddr = (intptr_t)GetLibrary()->GetTrue();
  3819. contextData.falseAddr = (intptr_t)GetLibrary()->GetFalse();
  3820. contextData.undeclBlockVarAddr = (intptr_t)GetLibrary()->GetUndeclBlockVar();
  3821. contextData.scriptContextAddr = (intptr_t)this;
  3822. contextData.emptyStringAddr = (intptr_t)GetLibrary()->GetEmptyString();
  3823. contextData.negativeZeroAddr = (intptr_t)GetLibrary()->GetNegativeZero();
  3824. contextData.numberTypeStaticAddr = (intptr_t)GetLibrary()->GetNumberTypeStatic();
  3825. contextData.stringTypeStaticAddr = (intptr_t)GetLibrary()->GetStringTypeStatic();
  3826. contextData.objectTypeAddr = (intptr_t)GetLibrary()->GetObjectType();
  3827. contextData.objectHeaderInlinedTypeAddr = (intptr_t)GetLibrary()->GetObjectHeaderInlinedType();
  3828. contextData.regexTypeAddr = (intptr_t)GetLibrary()->GetRegexType();
  3829. contextData.arrayConstructorAddr = (intptr_t)GetLibrary()->GetArrayConstructor();
  3830. contextData.arrayTypeAddr = (intptr_t)GetLibrary()->GetArrayType();
  3831. contextData.nativeIntArrayTypeAddr = (intptr_t)GetLibrary()->GetNativeIntArrayType();
  3832. contextData.nativeFloatArrayTypeAddr = (intptr_t)GetLibrary()->GetNativeFloatArrayType();
  3833. contextData.charStringCacheAddr = (intptr_t)&GetLibrary()->GetCharStringCache();
  3834. contextData.libraryAddr = (intptr_t)GetLibrary();
  3835. contextData.globalObjectAddr = (intptr_t)GetLibrary()->GetGlobalObject();
  3836. contextData.globalObjectThisAddr = (intptr_t)GetLibrary()->GetGlobalObject()->ToThis();
  3837. contextData.builtinFunctionsBaseAddr = (intptr_t)GetLibrary()->GetBuiltinFunctions();
  3838. contextData.sideEffectsAddr = optimizationOverrides.GetAddressOfSideEffects();
  3839. contextData.arraySetElementFastPathVtableAddr = (intptr_t)optimizationOverrides.GetAddressOfArraySetElementFastPathVtable();
  3840. contextData.intArraySetElementFastPathVtableAddr = (intptr_t)optimizationOverrides.GetAddressOfIntArraySetElementFastPathVtable();
  3841. contextData.floatArraySetElementFastPathVtableAddr = (intptr_t)optimizationOverrides.GetAddressOfFloatArraySetElementFastPathVtable();
  3842. contextData.recyclerAddr = (intptr_t)GetRecycler();
  3843. contextData.recyclerAllowNativeCodeBumpAllocation = GetRecycler()->AllowNativeCodeBumpAllocation();
  3844. contextData.numberAllocatorAddr = (intptr_t)GetNumberAllocator();
  3845. #ifdef RECYCLER_MEMORY_VERIFY
  3846. contextData.isRecyclerVerifyEnabled = (boolean)recycler->VerifyEnabled();
  3847. contextData.recyclerVerifyPad = recycler->GetVerifyPad();
  3848. #else
  3849. // TODO: OOP JIT, figure out how to have this only in debug build
  3850. contextData.isRecyclerVerifyEnabled = FALSE;
  3851. contextData.recyclerVerifyPad = 0;
  3852. #endif
  3853. contextData.numberAllocatorAddr = (intptr_t)GetNumberAllocator();
  3854. contextData.isSIMDEnabled = GetConfig()->IsSimdjsEnabled();
  3855. CompileAssert(VTableValue::Count == VTABLE_COUNT); // need to update idl when this changes
  3856. auto vtblAddresses = GetLibrary()->GetVTableAddresses();
  3857. for (unsigned int i = 0; i < VTableValue::Count; i++)
  3858. {
  3859. contextData.vtableAddresses[i] = vtblAddresses[i];
  3860. }
  3861. JITManager::GetJITManager()->InitializeScriptContext(&contextData, &m_remoteScriptContextAddr);
  3862. }
  3863. #endif
  3864. intptr_t ScriptContext::GetNullAddr() const
  3865. {
  3866. return (intptr_t)GetLibrary()->GetNull();
  3867. }
  3868. intptr_t ScriptContext::GetUndefinedAddr() const
  3869. {
  3870. return (intptr_t)GetLibrary()->GetUndefined();
  3871. }
  3872. intptr_t ScriptContext::GetTrueAddr() const
  3873. {
  3874. return (intptr_t)GetLibrary()->GetTrue();
  3875. }
  3876. intptr_t ScriptContext::GetFalseAddr() const
  3877. {
  3878. return (intptr_t)GetLibrary()->GetFalse();
  3879. }
  3880. intptr_t ScriptContext::GetUndeclBlockVarAddr() const
  3881. {
  3882. return (intptr_t)GetLibrary()->GetUndeclBlockVar();
  3883. }
  3884. intptr_t ScriptContext::GetEmptyStringAddr() const
  3885. {
  3886. return (intptr_t)GetLibrary()->GetEmptyString();
  3887. }
  3888. intptr_t ScriptContext::GetNegativeZeroAddr() const
  3889. {
  3890. return (intptr_t)GetLibrary()->GetNegativeZero();
  3891. }
  3892. intptr_t ScriptContext::GetNumberTypeStaticAddr() const
  3893. {
  3894. return (intptr_t)GetLibrary()->GetNumberTypeStatic();
  3895. }
  3896. intptr_t ScriptContext::GetStringTypeStaticAddr() const
  3897. {
  3898. return (intptr_t)GetLibrary()->GetStringTypeStatic();
  3899. }
  3900. intptr_t ScriptContext::GetObjectTypeAddr() const
  3901. {
  3902. return (intptr_t)GetLibrary()->GetObjectType();
  3903. }
  3904. intptr_t ScriptContext::GetObjectHeaderInlinedTypeAddr() const
  3905. {
  3906. return (intptr_t)GetLibrary()->GetObjectHeaderInlinedType();
  3907. }
  3908. intptr_t ScriptContext::GetRegexTypeAddr() const
  3909. {
  3910. return (intptr_t)GetLibrary()->GetRegexType();
  3911. }
  3912. intptr_t ScriptContext::GetArrayTypeAddr() const
  3913. {
  3914. return (intptr_t)GetLibrary()->GetArrayType();
  3915. }
  3916. intptr_t ScriptContext::GetNativeIntArrayTypeAddr() const
  3917. {
  3918. return (intptr_t)GetLibrary()->GetNativeIntArrayType();
  3919. }
  3920. intptr_t ScriptContext::GetNativeFloatArrayTypeAddr() const
  3921. {
  3922. return (intptr_t)GetLibrary()->GetNativeFloatArrayType();
  3923. }
  3924. intptr_t ScriptContext::GetArrayConstructorAddr() const
  3925. {
  3926. return (intptr_t)GetLibrary()->GetArrayConstructor();
  3927. }
  3928. intptr_t ScriptContext::GetCharStringCacheAddr() const
  3929. {
  3930. return (intptr_t)&GetLibrary()->GetCharStringCache();
  3931. }
  3932. intptr_t ScriptContext::GetSideEffectsAddr() const
  3933. {
  3934. return optimizationOverrides.GetAddressOfSideEffects();
  3935. }
  3936. intptr_t ScriptContext::GetArraySetElementFastPathVtableAddr() const
  3937. {
  3938. return optimizationOverrides.GetArraySetElementFastPathVtableAddr();
  3939. }
  3940. intptr_t ScriptContext::GetIntArraySetElementFastPathVtableAddr() const
  3941. {
  3942. return optimizationOverrides.GetIntArraySetElementFastPathVtableAddr();
  3943. }
  3944. intptr_t ScriptContext::GetFloatArraySetElementFastPathVtableAddr() const
  3945. {
  3946. return optimizationOverrides.GetFloatArraySetElementFastPathVtableAddr();
  3947. }
  3948. intptr_t ScriptContext::GetBuiltinFunctionsBaseAddr() const
  3949. {
  3950. return (intptr_t)GetLibrary()->GetBuiltinFunctions();
  3951. }
  3952. intptr_t ScriptContext::GetLibraryAddr() const
  3953. {
  3954. return (intptr_t)GetLibrary();
  3955. }
  3956. intptr_t ScriptContext::GetGlobalObjectAddr() const
  3957. {
  3958. return (intptr_t)GetLibrary()->GetGlobalObject();
  3959. }
  3960. intptr_t ScriptContext::GetGlobalObjectThisAddr() const
  3961. {
  3962. return (intptr_t)GetLibrary()->GetGlobalObject()->ToThis();
  3963. }
  3964. intptr_t ScriptContext::GetNumberAllocatorAddr() const
  3965. {
  3966. return (intptr_t)&numberAllocator;
  3967. }
  3968. intptr_t ScriptContext::GetRecyclerAddr() const
  3969. {
  3970. return (intptr_t)GetRecycler();
  3971. }
  3972. bool ScriptContext::GetRecyclerAllowNativeCodeBumpAllocation() const
  3973. {
  3974. return GetRecycler()->AllowNativeCodeBumpAllocation();
  3975. }
  3976. bool ScriptContext::IsSIMDEnabled() const
  3977. {
  3978. return GetConfig()->IsSimdjsEnabled();
  3979. }
  3980. bool ScriptContext::IsPRNGSeeded() const
  3981. {
  3982. return GetLibrary()->IsPRNGSeeded();
  3983. }
  3984. intptr_t ScriptContext::GetAddr() const
  3985. {
  3986. return (intptr_t)this;
  3987. }
  3988. #if ENABLE_NATIVE_CODEGEN
  3989. void ScriptContext::AddToDOMFastPathHelperMap(intptr_t funcInfoAddr, IR::JnHelperMethod helper)
  3990. {
  3991. m_domFastPathHelperMap->Add(funcInfoAddr, helper);
  3992. }
  3993. IR::JnHelperMethod ScriptContext::GetDOMFastPathHelper(intptr_t funcInfoAddr)
  3994. {
  3995. IR::JnHelperMethod helper;
  3996. m_domFastPathHelperMap->LockResize();
  3997. bool found = m_domFastPathHelperMap->TryGetValue(funcInfoAddr, &helper);
  3998. m_domFastPathHelperMap->UnlockResize();
  3999. Assert(found);
  4000. return helper;
  4001. }
  4002. #endif
  4003. intptr_t ScriptContext::GetVTableAddress(VTableValue vtableType) const
  4004. {
  4005. Assert(vtableType < VTableValue::Count);
  4006. return GetLibrary()->GetVTableAddresses()[vtableType];
  4007. }
  4008. bool ScriptContext::IsRecyclerVerifyEnabled() const
  4009. {
  4010. #ifdef RECYCLER_MEMORY_VERIFY
  4011. return recycler->VerifyEnabled() != FALSE;
  4012. #else
  4013. return false;
  4014. #endif
  4015. }
  4016. uint ScriptContext::GetRecyclerVerifyPad() const
  4017. {
  4018. #ifdef RECYCLER_MEMORY_VERIFY
  4019. return recycler->GetVerifyPad();
  4020. #else
  4021. return 0;
  4022. #endif
  4023. }
  4024. JavascriptFunction* ScriptContext::GetBuiltInLibraryFunction(JavascriptMethod entryPoint)
  4025. {
  4026. JavascriptFunction * function = NULL;
  4027. if (builtInLibraryFunctions)
  4028. {
  4029. builtInLibraryFunctions->TryGetValue(entryPoint, &function);
  4030. }
  4031. return function;
  4032. }
  4033. #if ENABLE_PROFILE_INFO
  4034. void ScriptContext::AddDynamicProfileInfo(FunctionBody * functionBody, WriteBarrierPtr<DynamicProfileInfo>* dynamicProfileInfo)
  4035. {
  4036. Assert(functionBody->GetScriptContext() == this);
  4037. Assert(functionBody->HasValidSourceInfo());
  4038. DynamicProfileInfo * newDynamicProfileInfo = *dynamicProfileInfo;
  4039. // If it is a dynamic script - we should create a profile info bound to the threadContext for its lifetime.
  4040. SourceContextInfo* sourceContextInfo = functionBody->GetSourceContextInfo();
  4041. SourceDynamicProfileManager* profileManager = sourceContextInfo->sourceDynamicProfileManager;
  4042. if (sourceContextInfo->IsDynamic())
  4043. {
  4044. if (profileManager != nullptr)
  4045. {
  4046. // There is an in-memory cache and dynamic profile info is coming from there
  4047. if (newDynamicProfileInfo == nullptr)
  4048. {
  4049. newDynamicProfileInfo = DynamicProfileInfo::New(this->GetRecycler(), functionBody, true /* persistsAcrossScriptContexts */);
  4050. profileManager->UpdateDynamicProfileInfo(functionBody->GetLocalFunctionId(), newDynamicProfileInfo);
  4051. *dynamicProfileInfo = newDynamicProfileInfo;
  4052. }
  4053. profileManager->MarkAsExecuted(functionBody->GetLocalFunctionId());
  4054. newDynamicProfileInfo->UpdateFunctionInfo(functionBody, this->GetRecycler());
  4055. }
  4056. else
  4057. {
  4058. if (newDynamicProfileInfo == nullptr)
  4059. {
  4060. newDynamicProfileInfo = functionBody->AllocateDynamicProfile();
  4061. }
  4062. *dynamicProfileInfo = newDynamicProfileInfo;
  4063. }
  4064. }
  4065. else
  4066. {
  4067. if (newDynamicProfileInfo == nullptr)
  4068. {
  4069. newDynamicProfileInfo = functionBody->AllocateDynamicProfile();
  4070. *dynamicProfileInfo = newDynamicProfileInfo;
  4071. }
  4072. Assert(functionBody->GetInterpretedCount() == 0);
  4073. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  4074. if (profileInfoList)
  4075. {
  4076. profileInfoList->Prepend(this->GetRecycler(), newDynamicProfileInfo);
  4077. }
  4078. #endif
  4079. if (!startupComplete)
  4080. {
  4081. Assert(profileManager);
  4082. profileManager->MarkAsExecuted(functionBody->GetLocalFunctionId());
  4083. }
  4084. }
  4085. Assert(*dynamicProfileInfo != nullptr);
  4086. }
  4087. #endif
  4088. CharClassifier const * ScriptContext::GetCharClassifier(void) const
  4089. {
  4090. return this->charClassifier;
  4091. }
  4092. void ScriptContext::OnStartupComplete()
  4093. {
  4094. JS_ETW(EventWriteJSCRIPT_ON_STARTUP_COMPLETE(this));
  4095. SaveStartupProfileAndRelease();
  4096. }
  4097. void ScriptContext::SaveStartupProfileAndRelease(bool isSaveOnClose)
  4098. {
  4099. // No need to save profiler info in JSRT scenario at this time.
  4100. if (GetThreadContext()->IsJSRT())
  4101. {
  4102. return;
  4103. }
  4104. if (!startupComplete && this->cache->sourceContextInfoMap)
  4105. {
  4106. #if ENABLE_PROFILE_INFO
  4107. this->cache->sourceContextInfoMap->Map([&](DWORD_PTR dwHostSourceContext, SourceContextInfo* info)
  4108. {
  4109. Assert(info->sourceDynamicProfileManager);
  4110. uint bytesWritten = info->sourceDynamicProfileManager->SaveToProfileCacheAndRelease(info);
  4111. if (bytesWritten > 0)
  4112. {
  4113. JS_ETW(EventWriteJSCRIPT_PROFILE_SAVE(info->dwHostSourceContext, this, bytesWritten, isSaveOnClose));
  4114. OUTPUT_TRACE(Js::DynamicProfilePhase, _u("Profile saving succeeded\n"));
  4115. }
  4116. });
  4117. #endif
  4118. }
  4119. startupComplete = true;
  4120. }
  4121. void ScriptContextBase::ClearGlobalObject()
  4122. {
  4123. #if ENABLE_NATIVE_CODEGEN
  4124. ScriptContext* scriptContext = static_cast<ScriptContext*>(this);
  4125. Assert(scriptContext->IsClosedNativeCodeGenerator());
  4126. #endif
  4127. globalObject = nullptr;
  4128. javascriptLibrary = nullptr;
  4129. }
  4130. void ScriptContext::SetFastDOMenabled()
  4131. {
  4132. fastDOMenabled = true; Assert(globalObject->GetDirectHostObject() != NULL);
  4133. }
  4134. #if DYNAMIC_INTERPRETER_THUNK
  4135. JavascriptMethod ScriptContext::GetNextDynamicAsmJsInterpreterThunk(PVOID* ppDynamicInterpreterThunk)
  4136. {
  4137. #ifdef ASMJS_PLAT
  4138. return (JavascriptMethod)this->asmJsInterpreterThunkEmitter->GetNextThunk(ppDynamicInterpreterThunk);
  4139. #else
  4140. __debugbreak();
  4141. return nullptr;
  4142. #endif
  4143. }
  4144. JavascriptMethod ScriptContext::GetNextDynamicInterpreterThunk(PVOID* ppDynamicInterpreterThunk)
  4145. {
  4146. return (JavascriptMethod)this->interpreterThunkEmitter->GetNextThunk(ppDynamicInterpreterThunk);
  4147. }
  4148. BOOL ScriptContext::IsDynamicInterpreterThunk(void* address)
  4149. {
  4150. return this->interpreterThunkEmitter->IsInHeap(address);
  4151. }
  4152. void ScriptContext::ReleaseDynamicInterpreterThunk(BYTE* address, bool addtoFreeList)
  4153. {
  4154. this->interpreterThunkEmitter->Release(address, addtoFreeList);
  4155. }
  4156. void ScriptContext::ReleaseDynamicAsmJsInterpreterThunk(BYTE* address, bool addtoFreeList)
  4157. {
  4158. #ifdef ASMJS_PLAT
  4159. this->asmJsInterpreterThunkEmitter->Release(address, addtoFreeList);
  4160. #else
  4161. Assert(UNREACHED);
  4162. #endif
  4163. }
  4164. #endif
  4165. bool ScriptContext::IsExceptionWrapperForBuiltInsEnabled()
  4166. {
  4167. return ScriptContext::IsExceptionWrapperForBuiltInsEnabled(this);
  4168. }
  4169. // static
  4170. bool ScriptContext::IsExceptionWrapperForBuiltInsEnabled(ScriptContext* scriptContext)
  4171. {
  4172. Assert(scriptContext);
  4173. return CONFIG_FLAG(EnableContinueAfterExceptionWrappersForBuiltIns);
  4174. }
  4175. bool ScriptContext::IsExceptionWrapperForHelpersEnabled(ScriptContext* scriptContext)
  4176. {
  4177. Assert(scriptContext);
  4178. return CONFIG_FLAG(EnableContinueAfterExceptionWrappersForHelpers);
  4179. }
  4180. void ScriptContextBase::SetGlobalObject(GlobalObject *globalObject)
  4181. {
  4182. #if DBG
  4183. ScriptContext* scriptContext = static_cast<ScriptContext*>(this);
  4184. Assert(scriptContext->IsCloningGlobal() && !this->globalObject);
  4185. #endif
  4186. this->globalObject = globalObject;
  4187. }
  4188. void ConvertKey(const FastEvalMapString& src, EvalMapString& dest)
  4189. {
  4190. dest.str = src.str;
  4191. dest.strict = src.strict;
  4192. dest.moduleID = src.moduleID;
  4193. dest.hash = TAGHASH((hash_t)dest.str);
  4194. }
  4195. void ScriptContext::PrintStats()
  4196. {
  4197. #if ENABLE_PROFILE_INFO
  4198. #if DBG_DUMP
  4199. DynamicProfileInfo::DumpScriptContext(this);
  4200. #endif
  4201. #ifdef RUNTIME_DATA_COLLECTION
  4202. DynamicProfileInfo::DumpScriptContextToFile(this);
  4203. #endif
  4204. #endif
  4205. #ifdef PROFILE_TYPES
  4206. if (Configuration::Global.flags.ProfileTypes)
  4207. {
  4208. ProfileTypes();
  4209. }
  4210. #endif
  4211. #ifdef PROFILE_BAILOUT_RECORD_MEMORY
  4212. if (Configuration::Global.flags.ProfileBailOutRecordMemory)
  4213. {
  4214. Output::Print(_u("CodeSize: %6d\nBailOutRecord Size: %6d\nLocalOffsets Size: %6d\n"), codeSize, bailOutRecordBytes, bailOutOffsetBytes);
  4215. }
  4216. #endif
  4217. #ifdef PROFILE_OBJECT_LITERALS
  4218. if (Configuration::Global.flags.ProfileObjectLiteral)
  4219. {
  4220. ProfileObjectLiteral();
  4221. }
  4222. #endif
  4223. #ifdef PROFILE_STRINGS
  4224. if (stringProfiler != nullptr)
  4225. {
  4226. stringProfiler->PrintAll();
  4227. Adelete(MiscAllocator(), stringProfiler);
  4228. stringProfiler = nullptr;
  4229. }
  4230. #endif
  4231. #ifdef PROFILE_MEM
  4232. if (profileMemoryDump && MemoryProfiler::IsTraceEnabled())
  4233. {
  4234. MemoryProfiler::PrintAll();
  4235. #ifdef PROFILE_RECYCLER_ALLOC
  4236. if (Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::AllPhase)
  4237. || Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::RunPhase))
  4238. {
  4239. GetRecycler()->PrintAllocStats();
  4240. }
  4241. #endif
  4242. }
  4243. #endif
  4244. #if DBG_DUMP
  4245. if (PHASE_STATS1(Js::ByteCodePhase))
  4246. {
  4247. Output::Print(_u(" Total Bytecode size: <%d, %d, %d> = %d\n"),
  4248. byteCodeDataSize,
  4249. byteCodeAuxiliaryDataSize,
  4250. byteCodeAuxiliaryContextDataSize,
  4251. byteCodeDataSize + byteCodeAuxiliaryDataSize + byteCodeAuxiliaryContextDataSize);
  4252. }
  4253. if (Configuration::Global.flags.BytecodeHist)
  4254. {
  4255. Output::Print(_u("ByteCode Histogram\n"));
  4256. Output::Print(_u("\n"));
  4257. uint total = 0;
  4258. uint unique = 0;
  4259. for (int j = 0; j < (int)OpCode::ByteCodeLast; j++)
  4260. {
  4261. total += byteCodeHistogram[j];
  4262. if (byteCodeHistogram[j] > 0)
  4263. {
  4264. unique++;
  4265. }
  4266. }
  4267. Output::Print(_u("%9u Total executed ops\n"), total);
  4268. Output::Print(_u("\n"));
  4269. uint max = UINT_MAX;
  4270. double pctcume = 0.0;
  4271. while (true)
  4272. {
  4273. uint upper = 0;
  4274. int index = -1;
  4275. for (int j = 0; j < (int)OpCode::ByteCodeLast; j++)
  4276. {
  4277. if (OpCodeUtil::IsValidOpcode((OpCode)j) && byteCodeHistogram[j] > upper && byteCodeHistogram[j] < max)
  4278. {
  4279. index = j;
  4280. upper = byteCodeHistogram[j];
  4281. }
  4282. }
  4283. if (index == -1)
  4284. {
  4285. break;
  4286. }
  4287. max = byteCodeHistogram[index];
  4288. for (OpCode j = (OpCode)0; j < OpCode::ByteCodeLast; j++)
  4289. {
  4290. if (OpCodeUtil::IsValidOpcode(j) && max == byteCodeHistogram[(int)j])
  4291. {
  4292. double pct = ((double)max) / total;
  4293. pctcume += pct;
  4294. Output::Print(_u("%9u %5.1lf %5.1lf %04x %s\n"), max, pct * 100, pctcume * 100, j, OpCodeUtil::GetOpCodeName(j));
  4295. }
  4296. }
  4297. }
  4298. Output::Print(_u("\n"));
  4299. Output::Print(_u("Unique opcodes: %d\n"), unique);
  4300. }
  4301. #endif
  4302. #if ENABLE_NATIVE_CODEGEN
  4303. #ifdef BGJIT_STATS
  4304. // We do not care about small script contexts without much activity - unless t
  4305. if (PHASE_STATS1(Js::BGJitPhase) && (this->interpretedCount > 50 || Js::Configuration::Global.flags.IsEnabled(Js::ForceFlag)))
  4306. {
  4307. uint loopJitCodeUsed = 0;
  4308. uint bucketSize1 = 20;
  4309. uint bucketSize2 = 100;
  4310. uint size1CutOffbucketId = 4;
  4311. uint totalBuckets[15] = { 0 };
  4312. uint nativeCodeBuckets[15] = { 0 };
  4313. uint usedNativeCodeBuckets[15] = { 0 };
  4314. uint rejits[15] = { 0 };
  4315. uint zeroInterpretedFunctions = 0;
  4316. uint oneInterpretedFunctions = 0;
  4317. uint nonZeroBytecodeFunctions = 0;
  4318. Output::Print(_u("Script Context: 0x%p Url: %s\n"), this, this->url);
  4319. FunctionBody* anyFunctionBody = this->FindFunction([](FunctionBody* body) { return body != nullptr; });
  4320. if (anyFunctionBody)
  4321. {
  4322. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("Function list\n"));
  4323. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("===============================\n"));
  4324. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("%-24s, %-8s, %-10s, %-10s, %-10s, %-10s, %-10s\n"), _u("Function"), _u("InterpretedCount"), _u("ByteCodeInLoopSize"), _u("ByteCodeSize"), _u("IsJitted"), _u("IsUsed"), _u("NativeCodeSize"));
  4325. this->MapFunction([&](FunctionBody* body)
  4326. {
  4327. bool isNativeCode = false;
  4328. // Filtering interpreted count lowers a lot of noise
  4329. if (body->GetInterpretedCount() > 1 || Js::Configuration::Global.flags.IsEnabled(Js::ForceFlag))
  4330. {
  4331. body->MapEntryPoints([&](uint entryPointIndex, FunctionEntryPointInfo* entryPoint)
  4332. {
  4333. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4334. char rejit = entryPointIndex > 0 ? '*' : ' ';
  4335. isNativeCode = entryPoint->IsNativeCode() | isNativeCode;
  4336. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("%-20s %16s %c, %8d , %10d , %10d, %-10s, %-10s, %10d\n"),
  4337. body->GetExternalDisplayName(),
  4338. body->GetDebugNumberSet(debugStringBuffer),
  4339. rejit,
  4340. body->GetInterpretedCount(),
  4341. body->GetByteCodeInLoopCount(),
  4342. body->GetByteCodeCount(),
  4343. entryPoint->IsNativeCode() ? _u("Jitted") : _u("Interpreted"),
  4344. body->GetNativeEntryPointUsed() ? _u("Used") : _u("NotUsed"),
  4345. entryPoint->IsNativeCode() ? entryPoint->GetCodeSize() : 0);
  4346. });
  4347. }
  4348. if (body->GetInterpretedCount() == 0)
  4349. {
  4350. zeroInterpretedFunctions++;
  4351. if (body->GetByteCodeCount() > 0)
  4352. {
  4353. nonZeroBytecodeFunctions++;
  4354. }
  4355. }
  4356. else if (body->GetInterpretedCount() == 1)
  4357. {
  4358. oneInterpretedFunctions++;
  4359. }
  4360. // Generate a histogram using interpreted counts.
  4361. uint bucket;
  4362. uint intrpCount = body->GetInterpretedCount();
  4363. if (intrpCount < 100)
  4364. {
  4365. bucket = intrpCount / bucketSize1;
  4366. }
  4367. else if (intrpCount < 1000)
  4368. {
  4369. bucket = size1CutOffbucketId + intrpCount / bucketSize2;
  4370. }
  4371. else
  4372. {
  4373. bucket = _countof(totalBuckets) - 1;
  4374. }
  4375. // Explicitly assume that the bucket count is less than the following counts (which are all equal)
  4376. // This is because min will return _countof(totalBuckets) - 1 if the count exceeds _countof(totalBuckets) - 1.
  4377. __analysis_assume(bucket < _countof(totalBuckets));
  4378. __analysis_assume(bucket < _countof(nativeCodeBuckets));
  4379. __analysis_assume(bucket < _countof(usedNativeCodeBuckets));
  4380. __analysis_assume(bucket < _countof(rejits));
  4381. totalBuckets[bucket]++;
  4382. if (isNativeCode)
  4383. {
  4384. nativeCodeBuckets[bucket]++;
  4385. if (body->GetNativeEntryPointUsed())
  4386. {
  4387. usedNativeCodeBuckets[bucket]++;
  4388. }
  4389. if (body->HasRejit())
  4390. {
  4391. rejits[bucket]++;
  4392. }
  4393. }
  4394. body->MapLoopHeaders([&](uint loopNumber, LoopHeader* header)
  4395. {
  4396. char16 loopBodyName[256];
  4397. body->GetLoopBodyName(loopNumber, loopBodyName, _countof(loopBodyName));
  4398. header->MapEntryPoints([&](int index, LoopEntryPointInfo * entryPoint)
  4399. {
  4400. if (entryPoint->IsNativeCode())
  4401. {
  4402. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4403. char rejit = index > 0 ? '*' : ' ';
  4404. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("%-20s %16s %c, %8d , %10d , %10d, %-10s, %-10s, %10d\n"),
  4405. loopBodyName,
  4406. body->GetDebugNumberSet(debugStringBuffer),
  4407. rejit,
  4408. header->interpretCount,
  4409. header->GetByteCodeCount(),
  4410. header->GetByteCodeCount(),
  4411. _u("Jitted"),
  4412. entryPoint->IsUsed() ? _u("Used") : _u("NotUsed"),
  4413. entryPoint->GetCodeSize());
  4414. if (entryPoint->IsUsed())
  4415. {
  4416. loopJitCodeUsed++;
  4417. }
  4418. }
  4419. });
  4420. });
  4421. });
  4422. }
  4423. Output::Print(_u("** SpeculativelyJitted: %6d FunctionsJitted: %6d JittedUsed: %6d Usage:%f ByteCodesJitted: %6d JitCodeUsed: %6d Usage: %f \n"),
  4424. speculativeJitCount, funcJITCount, funcJitCodeUsed, ((float)(funcJitCodeUsed) / funcJITCount) * 100, bytecodeJITCount, jitCodeUsed, ((float)(jitCodeUsed) / bytecodeJITCount) * 100);
  4425. Output::Print(_u("** LoopJITCount: %6d LoopJitCodeUsed: %6d Usage: %f\n"),
  4426. loopJITCount, loopJitCodeUsed, ((float)loopJitCodeUsed / loopJITCount) * 100);
  4427. Output::Print(_u("** TotalInterpretedCalls: %6d MaxFuncInterp: %6d InterpretedHighPri: %6d \n"),
  4428. interpretedCount, maxFuncInterpret, interpretedCallsHighPri);
  4429. Output::Print(_u("** ZeroInterpretedFunctions: %6d OneInterpretedFunctions: %6d ZeroInterpretedWithNonZeroBytecode: %6d \n "), zeroInterpretedFunctions, oneInterpretedFunctions, nonZeroBytecodeFunctions);
  4430. Output::Print(_u("** %-24s : %-10s %-10s %-10s %-10s %-10s\n"), _u("InterpretedCounts"), _u("Total"), _u("NativeCode"), _u("Used"), _u("Usage"), _u("Rejits"));
  4431. uint low = 0;
  4432. uint high = 0;
  4433. for (uint i = 0; i < _countof(totalBuckets); i++)
  4434. {
  4435. low = high;
  4436. if (i <= size1CutOffbucketId)
  4437. {
  4438. high = low + bucketSize1;
  4439. }
  4440. else if (i < (_countof(totalBuckets) - 1))
  4441. {
  4442. high = low + bucketSize2; }
  4443. else
  4444. {
  4445. high = 100000;
  4446. }
  4447. Output::Print(_u("** %10d - %10d : %10d %10d %10d %7.2f %10d\n"), low, high, totalBuckets[i], nativeCodeBuckets[i], usedNativeCodeBuckets[i], ((float)usedNativeCodeBuckets[i] / nativeCodeBuckets[i]) * 100, rejits[i]);
  4448. }
  4449. Output::Print(_u("\n\n"));
  4450. }
  4451. #endif
  4452. #ifdef REJIT_STATS
  4453. if (PHASE_STATS1(Js::ReJITPhase))
  4454. {
  4455. uint totalBailouts = 0;
  4456. uint totalRejits = 0;
  4457. WCHAR buf[256];
  4458. // Dump bailout data.
  4459. Output::Print(_u("%-40s %6s\n"), _u("Bailout Reason,"), _u("Count"));
  4460. bailoutReasonCounts->Map([&totalBailouts](uint kind, uint val) {
  4461. WCHAR buf[256];
  4462. totalBailouts += val;
  4463. if (val != 0)
  4464. {
  4465. swprintf_s(buf, _u("%S,"), GetBailOutKindName((IR::BailOutKind)kind));
  4466. Output::Print(_u("%-40s %6d\n"), buf, val);
  4467. }
  4468. });
  4469. Output::Print(_u("%-40s %6d\n"), _u("TOTAL,"), totalBailouts);
  4470. Output::Print(_u("\n\n"));
  4471. // Dump rejit data.
  4472. Output::Print(_u("%-40s %6s\n"), _u("Rejit Reason,"), _u("Count"));
  4473. for (uint i = 0; i < NumRejitReasons; ++i)
  4474. {
  4475. totalRejits += rejitReasonCounts[i];
  4476. if (rejitReasonCounts[i] != 0)
  4477. {
  4478. swprintf_s(buf, _u("%S,"), RejitReasonNames[i]);
  4479. Output::Print(_u("%-40s %6d\n"), buf, rejitReasonCounts[i]);
  4480. }
  4481. }
  4482. Output::Print(_u("%-40s %6d\n"), _u("TOTAL,"), totalRejits);
  4483. Output::Print(_u("\n\n"));
  4484. // If in verbose mode, dump data for each FunctionBody
  4485. if (Configuration::Global.flags.Verbose && rejitStatsMap != NULL)
  4486. {
  4487. // Aggregated data
  4488. Output::Print(_u("%-30s %14s %14s\n"), _u("Function (#),"), _u("Bailout Count,"), _u("Rejit Count"));
  4489. rejitStatsMap->Map([](Js::FunctionBody const *body, RejitStats *stats, RecyclerWeakReference<const Js::FunctionBody> const*) {
  4490. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4491. for (uint i = 0; i < NumRejitReasons; ++i)
  4492. stats->m_totalRejits += stats->m_rejitReasonCounts[i];
  4493. stats->m_bailoutReasonCounts->Map([stats](uint kind, uint val) {
  4494. stats->m_totalBailouts += val;
  4495. });
  4496. WCHAR buf[256];
  4497. swprintf_s(buf, _u("%s (%s),"), body->GetExternalDisplayName(), (const_cast<Js::FunctionBody*>(body))->GetDebugNumberSet(debugStringBuffer)); //TODO Kount
  4498. Output::Print(_u("%-30s %14d, %14d\n"), buf, stats->m_totalBailouts, stats->m_totalRejits);
  4499. });
  4500. Output::Print(_u("\n\n"));
  4501. // Per FunctionBody data
  4502. rejitStatsMap->Map([](Js::FunctionBody const *body, RejitStats *stats, RecyclerWeakReference<const Js::FunctionBody> const *) {
  4503. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4504. WCHAR buf[256];
  4505. swprintf_s(buf, _u("%s (%s),"), body->GetExternalDisplayName(), (const_cast<Js::FunctionBody*>(body))->GetDebugNumberSet(debugStringBuffer)); //TODO Kount
  4506. Output::Print(_u("%-30s\n\n"), buf);
  4507. // Dump bailout data
  4508. if (stats->m_totalBailouts != 0)
  4509. {
  4510. Output::Print(_u("%10sBailouts:\n"), _u(""));
  4511. stats->m_bailoutReasonCounts->Map([](uint kind, uint val) {
  4512. if (val != 0)
  4513. {
  4514. WCHAR buf[256];
  4515. swprintf_s(buf, _u("%S,"), GetBailOutKindName((IR::BailOutKind)kind));
  4516. Output::Print(_u("%10s%-40s %6d\n"), _u(""), buf, val);
  4517. }
  4518. });
  4519. }
  4520. Output::Print(_u("\n"));
  4521. // Dump rejit data.
  4522. if (stats->m_totalRejits != 0)
  4523. {
  4524. Output::Print(_u("%10sRejits:\n"), _u(""));
  4525. for (uint i = 0; i < NumRejitReasons; ++i)
  4526. {
  4527. if (stats->m_rejitReasonCounts[i] != 0)
  4528. {
  4529. swprintf_s(buf, _u("%S,"), RejitReasonNames[i]);
  4530. Output::Print(_u("%10s%-40s %6d\n"), _u(""), buf, stats->m_rejitReasonCounts[i]);
  4531. }
  4532. }
  4533. Output::Print(_u("\n\n"));
  4534. }
  4535. });
  4536. }
  4537. }
  4538. #endif
  4539. #ifdef FIELD_ACCESS_STATS
  4540. if (PHASE_STATS1(Js::ObjTypeSpecPhase))
  4541. {
  4542. FieldAccessStats globalStats;
  4543. if (this->fieldAccessStatsByFunctionNumber != nullptr)
  4544. {
  4545. this->fieldAccessStatsByFunctionNumber->Map([&globalStats](uint functionNumber, FieldAccessStatsEntry* entry)
  4546. {
  4547. FieldAccessStats functionStats;
  4548. entry->stats.Map([&functionStats](FieldAccessStatsPtr entryPointStats)
  4549. {
  4550. functionStats.Add(entryPointStats);
  4551. });
  4552. if (PHASE_VERBOSE_STATS1(Js::ObjTypeSpecPhase))
  4553. {
  4554. FunctionBody* functionBody = entry->functionBodyWeakRef->Get();
  4555. const char16* functionName = functionBody != nullptr ? functionBody->GetDisplayName() : _u("<unknown>");
  4556. Output::Print(_u("FieldAccessStats: function %s (#%u): inline cache stats:\n"), functionName, functionNumber);
  4557. Output::Print(_u(" overall: total %u, no profile info %u\n"), functionStats.totalInlineCacheCount, functionStats.noInfoInlineCacheCount);
  4558. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  4559. functionStats.monoInlineCacheCount, functionStats.emptyMonoInlineCacheCount, functionStats.clonedMonoInlineCacheCount);
  4560. Output::Print(_u(" poly: total %u (high %u, low %u), null %u, empty %u, ignored %u, disabled %u, equivalent %u, non-equivalent %u, cloned %u\n"),
  4561. functionStats.polyInlineCacheCount, functionStats.highUtilPolyInlineCacheCount, functionStats.lowUtilPolyInlineCacheCount,
  4562. functionStats.nullPolyInlineCacheCount, functionStats.emptyPolyInlineCacheCount, functionStats.ignoredPolyInlineCacheCount, functionStats.disabledPolyInlineCacheCount,
  4563. functionStats.equivPolyInlineCacheCount, functionStats.nonEquivPolyInlineCacheCount, functionStats.clonedPolyInlineCacheCount);
  4564. }
  4565. globalStats.Add(&functionStats);
  4566. });
  4567. }
  4568. Output::Print(_u("FieldAccessStats: totals\n"));
  4569. Output::Print(_u(" overall: total %u, no profile info %u\n"), globalStats.totalInlineCacheCount, globalStats.noInfoInlineCacheCount);
  4570. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  4571. globalStats.monoInlineCacheCount, globalStats.emptyMonoInlineCacheCount, globalStats.clonedMonoInlineCacheCount);
  4572. Output::Print(_u(" poly: total %u (high %u, low %u), null %u, empty %u, ignored %u, disabled %u, equivalent %u, non-equivalent %u, cloned %u\n"),
  4573. globalStats.polyInlineCacheCount, globalStats.highUtilPolyInlineCacheCount, globalStats.lowUtilPolyInlineCacheCount,
  4574. globalStats.nullPolyInlineCacheCount, globalStats.emptyPolyInlineCacheCount, globalStats.ignoredPolyInlineCacheCount, globalStats.disabledPolyInlineCacheCount,
  4575. globalStats.equivPolyInlineCacheCount, globalStats.nonEquivPolyInlineCacheCount, globalStats.clonedPolyInlineCacheCount);
  4576. }
  4577. #endif
  4578. #ifdef MISSING_PROPERTY_STATS
  4579. if (PHASE_STATS1(Js::MissingPropertyCachePhase))
  4580. {
  4581. Output::Print(_u("MissingPropertyStats: hits = %d, misses = %d, cache attempts = %d.\n"),
  4582. this->missingPropertyHits, this->missingPropertyMisses, this->missingPropertyCacheAttempts);
  4583. }
  4584. #endif
  4585. #ifdef INLINE_CACHE_STATS
  4586. if (PHASE_STATS1(Js::PolymorphicInlineCachePhase))
  4587. {
  4588. Output::Print(_u("%s,%s,%s,%s,%s,%s,%s,%s,%s\n"), _u("Function"), _u("Property"), _u("Kind"), _u("Accesses"), _u("Misses"), _u("Miss Rate"), _u("Collisions"), _u("Collision Rate"), _u("Slot Count"));
  4589. cacheDataMap->Map([this](Js::PolymorphicInlineCache const *cache, CacheData *data) {
  4590. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4591. uint total = data->hits + data->misses;
  4592. char16 const *propName = this->threadContext->GetPropertyName(data->propertyId)->GetBuffer();
  4593. wchar funcName[1024];
  4594. swprintf_s(funcName, _u("%s (%s)"), cache->functionBody->GetExternalDisplayName(), cache->functionBody->GetDebugNumberSet(debugStringBuffer));
  4595. Output::Print(_u("%s,%s,%s,%d,%d,%f,%d,%f,%d\n"),
  4596. funcName,
  4597. propName,
  4598. data->isGetCache ? _u("get") : _u("set"),
  4599. total,
  4600. data->misses,
  4601. static_cast<float>(data->misses) / total,
  4602. data->collisions,
  4603. static_cast<float>(data->collisions) / total,
  4604. cache->GetSize()
  4605. );
  4606. });
  4607. }
  4608. #endif
  4609. #if ENABLE_REGEX_CONFIG_OPTIONS
  4610. if (regexStatsDatabase != 0)
  4611. regexStatsDatabase->Print(GetRegexDebugWriter());
  4612. #endif
  4613. OUTPUT_STATS(Js::EmitterPhase, _u("Script Context: 0x%p Url: %s\n"), this, this->url);
  4614. OUTPUT_STATS(Js::EmitterPhase, _u(" Total thread committed code size = %d\n"), this->GetThreadContext()->GetCodeSize());
  4615. OUTPUT_STATS(Js::ParsePhase, _u("Script Context: 0x%p Url: %s\n"), this, this->url);
  4616. OUTPUT_STATS(Js::ParsePhase, _u(" Total ThreadContext source size %d\n"), this->GetThreadContext()->GetSourceSize());
  4617. #endif
  4618. #ifdef ENABLE_BASIC_TELEMETRY
  4619. if (this->telemetry != nullptr)
  4620. {
  4621. // If an exception (e.g. out-of-memory) happens during InitializeAllocations then `this->telemetry` will be null and the Close method will still be called, hence this guard expression.
  4622. this->telemetry->OutputPrint();
  4623. }
  4624. #endif
  4625. Output::Flush();
  4626. }
  4627. void ScriptContext::SetNextPendingClose(ScriptContext * nextPendingClose) {
  4628. this->nextPendingClose = nextPendingClose;
  4629. }
  4630. #ifdef ENABLE_MUTATION_BREAKPOINT
  4631. bool ScriptContext::HasMutationBreakpoints()
  4632. {
  4633. if (this->GetDebugContext() != nullptr && this->GetDebugContext()->GetProbeContainer() != nullptr)
  4634. {
  4635. return this->GetDebugContext()->GetProbeContainer()->HasMutationBreakpoints();
  4636. }
  4637. return false;
  4638. }
  4639. void ScriptContext::InsertMutationBreakpoint(Js::MutationBreakpoint *mutationBreakpoint)
  4640. {
  4641. this->GetDebugContext()->GetProbeContainer()->InsertMutationBreakpoint(mutationBreakpoint);
  4642. }
  4643. #endif
  4644. #ifdef REJIT_STATS
  4645. void ScriptContext::LogDataForFunctionBody(Js::FunctionBody *body, uint idx, bool isRejit)
  4646. {
  4647. if (rejitStatsMap == NULL)
  4648. {
  4649. rejitStatsMap = RecyclerNew(this->recycler, RejitStatsMap, this->recycler);
  4650. BindReference(rejitStatsMap);
  4651. }
  4652. RejitStats *stats = NULL;
  4653. if (!rejitStatsMap->TryGetValue(body, &stats))
  4654. {
  4655. stats = Anew(GeneralAllocator(), RejitStats, this);
  4656. rejitStatsMap->Item(body, stats);
  4657. }
  4658. if (isRejit)
  4659. {
  4660. stats->m_rejitReasonCounts[idx]++;
  4661. }
  4662. else
  4663. {
  4664. if (!stats->m_bailoutReasonCounts->ContainsKey(idx))
  4665. {
  4666. stats->m_bailoutReasonCounts->Item(idx, 1);
  4667. }
  4668. else
  4669. {
  4670. uint val = stats->m_bailoutReasonCounts->Item(idx);
  4671. ++val;
  4672. stats->m_bailoutReasonCounts->Item(idx, val);
  4673. }
  4674. }
  4675. }
  4676. void ScriptContext::LogRejit(Js::FunctionBody *body, uint reason)
  4677. {
  4678. Assert(reason < NumRejitReasons);
  4679. rejitReasonCounts[reason]++;
  4680. if (Js::Configuration::Global.flags.Verbose)
  4681. {
  4682. LogDataForFunctionBody(body, reason, true);
  4683. }
  4684. }
  4685. void ScriptContext::LogBailout(Js::FunctionBody *body, uint kind)
  4686. {
  4687. if (!bailoutReasonCounts->ContainsKey(kind))
  4688. {
  4689. bailoutReasonCounts->Item(kind, 1);
  4690. }
  4691. else
  4692. {
  4693. uint val = bailoutReasonCounts->Item(kind);
  4694. ++val;
  4695. bailoutReasonCounts->Item(kind, val);
  4696. }
  4697. if (Js::Configuration::Global.flags.Verbose)
  4698. {
  4699. LogDataForFunctionBody(body, kind, false);
  4700. }
  4701. }
  4702. #endif
  4703. #ifdef ENABLE_BASIC_TELEMETRY
  4704. ScriptContextTelemetry& ScriptContext::GetTelemetry()
  4705. {
  4706. return *this->telemetry;
  4707. }
  4708. bool ScriptContext::HasTelemetry()
  4709. {
  4710. return this->telemetry != nullptr;
  4711. }
  4712. #endif
  4713. bool ScriptContext::IsScriptContextInNonDebugMode() const
  4714. {
  4715. if (this->debugContext != nullptr)
  4716. {
  4717. return this->GetDebugContext()->IsDebugContextInNonDebugMode();
  4718. }
  4719. return true;
  4720. }
  4721. bool ScriptContext::IsScriptContextInDebugMode() const
  4722. {
  4723. if (this->debugContext != nullptr)
  4724. {
  4725. return this->GetDebugContext()->IsDebugContextInDebugMode();
  4726. }
  4727. return false;
  4728. }
  4729. bool ScriptContext::IsScriptContextInSourceRundownOrDebugMode() const
  4730. {
  4731. if (this->debugContext != nullptr)
  4732. {
  4733. return this->GetDebugContext()->IsDebugContextInSourceRundownOrDebugMode();
  4734. }
  4735. return false;
  4736. }
  4737. bool ScriptContext::IsIntlEnabled()
  4738. {
  4739. if (GetConfig()->IsIntlEnabled())
  4740. {
  4741. #ifdef ENABLE_GLOBALIZATION
  4742. // This will try to load globalization dlls if not already loaded.
  4743. Js::DelayLoadWindowsGlobalization* globLibrary = GetThreadContext()->GetWindowsGlobalizationLibrary();
  4744. return globLibrary->HasGlobalizationDllLoaded();
  4745. #endif
  4746. }
  4747. return false;
  4748. }
  4749. #ifdef INLINE_CACHE_STATS
  4750. void ScriptContext::LogCacheUsage(Js::PolymorphicInlineCache *cache, bool isGetter, Js::PropertyId propertyId, bool hit, bool collision)
  4751. {
  4752. if (cacheDataMap == NULL)
  4753. {
  4754. cacheDataMap = RecyclerNew(this->recycler, CacheDataMap, this->recycler);
  4755. BindReference(cacheDataMap);
  4756. }
  4757. CacheData *data = NULL;
  4758. if (!cacheDataMap->TryGetValue(cache, &data))
  4759. {
  4760. data = Anew(GeneralAllocator(), CacheData);
  4761. cacheDataMap->Item(cache, data);
  4762. data->isGetCache = isGetter;
  4763. data->propertyId = propertyId;
  4764. }
  4765. Assert(data->isGetCache == isGetter);
  4766. Assert(data->propertyId == propertyId);
  4767. if (hit)
  4768. {
  4769. data->hits++;
  4770. }
  4771. else
  4772. {
  4773. data->misses++;
  4774. }
  4775. if (collision)
  4776. {
  4777. data->collisions++;
  4778. }
  4779. }
  4780. #endif
  4781. #ifdef FIELD_ACCESS_STATS
  4782. void ScriptContext::RecordFieldAccessStats(FunctionBody* functionBody, FieldAccessStatsPtr fieldAccessStats)
  4783. {
  4784. Assert(fieldAccessStats != nullptr);
  4785. if (!PHASE_STATS1(Js::ObjTypeSpecPhase))
  4786. {
  4787. return;
  4788. }
  4789. FieldAccessStatsEntry* entry;
  4790. if (!this->fieldAccessStatsByFunctionNumber->TryGetValue(functionBody->GetFunctionNumber(), &entry))
  4791. {
  4792. RecyclerWeakReference<FunctionBody>* functionBodyWeakRef;
  4793. this->recycler->FindOrCreateWeakReferenceHandle(functionBody, &functionBodyWeakRef);
  4794. entry = RecyclerNew(this->recycler, FieldAccessStatsEntry, functionBodyWeakRef, this->recycler);
  4795. this->fieldAccessStatsByFunctionNumber->AddNew(functionBody->GetFunctionNumber(), entry);
  4796. }
  4797. entry->stats.Prepend(fieldAccessStats);
  4798. }
  4799. #endif
  4800. #ifdef MISSING_PROPERTY_STATS
  4801. void ScriptContext::RecordMissingPropertyMiss()
  4802. {
  4803. this->missingPropertyMisses++;
  4804. }
  4805. void ScriptContext::RecordMissingPropertyHit()
  4806. {
  4807. this->missingPropertyHits++;
  4808. }
  4809. void ScriptContext::RecordMissingPropertyCacheAttempt()
  4810. {
  4811. this->missingPropertyCacheAttempts++;
  4812. }
  4813. #endif
  4814. bool ScriptContext::IsIntConstPropertyOnGlobalObject(Js::PropertyId propId)
  4815. {
  4816. return intConstPropsOnGlobalObject->ContainsKey(propId);
  4817. }
  4818. void ScriptContext::TrackIntConstPropertyOnGlobalObject(Js::PropertyId propertyId)
  4819. {
  4820. intConstPropsOnGlobalObject->AddNew(propertyId);
  4821. }
  4822. bool ScriptContext::IsIntConstPropertyOnGlobalUserObject(Js::PropertyId propertyId)
  4823. {
  4824. return intConstPropsOnGlobalUserObject->ContainsKey(propertyId) != NULL;
  4825. }
  4826. void ScriptContext::TrackIntConstPropertyOnGlobalUserObject(Js::PropertyId propertyId)
  4827. {
  4828. intConstPropsOnGlobalUserObject->AddNew(propertyId);
  4829. }
  4830. void ScriptContext::AddCalleeSourceInfoToList(Utf8SourceInfo* sourceInfo)
  4831. {
  4832. Assert(sourceInfo);
  4833. RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef = nullptr;
  4834. this->GetRecycler()->FindOrCreateWeakReferenceHandle(sourceInfo, &sourceInfoWeakRef);
  4835. Assert(sourceInfoWeakRef);
  4836. if (!calleeUtf8SourceInfoList)
  4837. {
  4838. Recycler *recycler = this->GetRecycler();
  4839. calleeUtf8SourceInfoList.Root(RecyclerNew(recycler, CalleeSourceList, recycler), recycler);
  4840. }
  4841. if (!calleeUtf8SourceInfoList->Contains(sourceInfoWeakRef))
  4842. {
  4843. calleeUtf8SourceInfoList->Add(sourceInfoWeakRef);
  4844. }
  4845. }
  4846. #ifdef ENABLE_JS_ETW
  4847. void ScriptContext::EmitStackTraceEvent(__in UINT64 operationID, __in USHORT maxFrameCount, bool emitV2AsyncStackEvent)
  4848. {
  4849. // If call root level is zero, there is no EntryExitRecord and the stack walk will fail.
  4850. if (GetThreadContext()->GetCallRootLevel() == 0)
  4851. {
  4852. return;
  4853. }
  4854. Assert(EventEnabledJSCRIPT_STACKTRACE() || EventEnabledJSCRIPT_ASYNCCAUSALITY_STACKTRACE_V2() || PHASE_TRACE1(Js::StackFramesEventPhase));
  4855. BEGIN_TEMP_ALLOCATOR(tempAllocator, this, _u("StackTraceEvent"))
  4856. {
  4857. JsUtil::List<StackFrameInfo, ArenaAllocator> stackFrames(tempAllocator);
  4858. Js::JavascriptStackWalker walker(this);
  4859. unsigned short nameBufferLength = 0;
  4860. Js::StringBuilder<ArenaAllocator> nameBuffer(tempAllocator);
  4861. nameBuffer.Reset();
  4862. OUTPUT_TRACE(Js::StackFramesEventPhase, _u("\nPosting stack trace via ETW:\n"));
  4863. ushort frameCount = walker.WalkUntil((ushort)maxFrameCount, [&](Js::JavascriptFunction* function, ushort frameIndex) -> bool
  4864. {
  4865. ULONG lineNumber = 0;
  4866. LONG columnNumber = 0;
  4867. UINT32 methodIdOrNameId = 0;
  4868. UINT8 isFrameIndex = 0; // FALSE
  4869. const WCHAR* name = nullptr;
  4870. if (function->IsScriptFunction() && !function->IsLibraryCode())
  4871. {
  4872. Js::FunctionBody * functionBody = function->GetFunctionBody();
  4873. functionBody->GetLineCharOffset(walker.GetByteCodeOffset(), &lineNumber, &columnNumber);
  4874. methodIdOrNameId = EtwTrace::GetFunctionId(functionBody);
  4875. name = functionBody->GetExternalDisplayName();
  4876. }
  4877. else
  4878. {
  4879. if (function->IsScriptFunction())
  4880. {
  4881. name = function->GetFunctionBody()->GetExternalDisplayName();
  4882. }
  4883. else
  4884. {
  4885. name = walker.GetCurrentNativeLibraryEntryName();
  4886. }
  4887. ushort nameLen = ProcessNameAndGetLength(&nameBuffer, name);
  4888. methodIdOrNameId = nameBufferLength;
  4889. // Keep track of the current length of the buffer. The next nameIndex will be at this position (+1 for each '\\', '\"', and ';' character added above).
  4890. nameBufferLength += nameLen;
  4891. isFrameIndex = 1; // TRUE;
  4892. }
  4893. StackFrameInfo frame((DWORD_PTR)function->GetScriptContext(),
  4894. (UINT32)lineNumber,
  4895. (UINT32)columnNumber,
  4896. methodIdOrNameId,
  4897. isFrameIndex);
  4898. OUTPUT_TRACE(Js::StackFramesEventPhase, _u("Frame : (%s : %u) (%s), LineNumber : %u, ColumnNumber : %u\n"),
  4899. (isFrameIndex == 1) ? (_u("NameBufferIndex")) : (_u("MethodID")),
  4900. methodIdOrNameId,
  4901. name,
  4902. lineNumber,
  4903. columnNumber);
  4904. stackFrames.Add(frame);
  4905. return false;
  4906. });
  4907. Assert(frameCount == (ushort)stackFrames.Count());
  4908. if (frameCount > 0) // No need to emit event if there are no script frames.
  4909. {
  4910. auto nameBufferString = nameBuffer.Detach();
  4911. if (nameBufferLength > 0)
  4912. {
  4913. // Account for the terminating null character.
  4914. nameBufferLength++;
  4915. }
  4916. if (emitV2AsyncStackEvent)
  4917. {
  4918. JS_ETW(EventWriteJSCRIPT_ASYNCCAUSALITY_STACKTRACE_V2(operationID, frameCount, nameBufferLength, sizeof(StackFrameInfo), &stackFrames.Item(0), nameBufferString));
  4919. }
  4920. else
  4921. {
  4922. JS_ETW(EventWriteJSCRIPT_STACKTRACE(operationID, frameCount, nameBufferLength, sizeof(StackFrameInfo), &stackFrames.Item(0), nameBufferString));
  4923. }
  4924. }
  4925. }
  4926. END_TEMP_ALLOCATOR(tempAllocator, this);
  4927. OUTPUT_FLUSH();
  4928. }
  4929. #endif
  4930. // Info: Append sourceString to stringBuilder after escaping charToEscape with escapeChar.
  4931. // "SomeBadly\0Formed\0String" => "SomeBadly\\\0Formed\\\0String"
  4932. // Parameters: stringBuilder - The Js::StringBuilder to which we should append sourceString.
  4933. // sourceString - The string we want to escape and append to stringBuilder.
  4934. // sourceStringLen - Length of sourceString.
  4935. // escapeChar - Char to use for escaping.
  4936. // charToEscape - The char which we should escape with escapeChar.
  4937. // Returns: Count of chars written to stringBuilder.
  4938. charcount_t ScriptContext::AppendWithEscapeCharacters(Js::StringBuilder<ArenaAllocator>* stringBuilder, const WCHAR* sourceString, charcount_t sourceStringLen, WCHAR escapeChar, WCHAR charToEscape)
  4939. {
  4940. const WCHAR* charToEscapePtr = wcschr(sourceString, charToEscape);
  4941. charcount_t charsPadding = 0;
  4942. // Only escape characters if sourceString contains one.
  4943. if (charToEscapePtr)
  4944. {
  4945. charcount_t charsWritten = 0;
  4946. charcount_t charsToAppend = 0;
  4947. while (charToEscapePtr)
  4948. {
  4949. charsToAppend = static_cast<charcount_t>(charToEscapePtr - sourceString) - charsWritten;
  4950. stringBuilder->Append(sourceString + charsWritten, charsToAppend);
  4951. stringBuilder->Append(escapeChar);
  4952. stringBuilder->Append(charToEscape);
  4953. // Keep track of this extra escapeChar character so we can update the buffer length correctly below.
  4954. charsPadding++;
  4955. // charsWritten is a count of the chars from sourceString which have been written - not count of chars Appended to stringBuilder.
  4956. charsWritten += charsToAppend + 1;
  4957. // Find next charToEscape.
  4958. charToEscapePtr++;
  4959. charToEscapePtr = wcschr(charToEscapePtr, charToEscape);
  4960. }
  4961. // Append the final part of the string if there is any left after the final charToEscape.
  4962. if (charsWritten != sourceStringLen)
  4963. {
  4964. charsToAppend = sourceStringLen - charsWritten;
  4965. stringBuilder->Append(sourceString + charsWritten, charsToAppend);
  4966. }
  4967. }
  4968. else
  4969. {
  4970. stringBuilder->AppendSz(sourceString);
  4971. }
  4972. return sourceStringLen + charsPadding;
  4973. }
  4974. /*static*/
  4975. ushort ScriptContext::ProcessNameAndGetLength(Js::StringBuilder<ArenaAllocator>* nameBuffer, const WCHAR* name)
  4976. {
  4977. Assert(nameBuffer);
  4978. Assert(name);
  4979. ushort nameLen = (ushort)wcslen(name);
  4980. // Surround each function name with quotes and escape any quote characters in the function name itself with '\\'.
  4981. nameBuffer->Append('\"');
  4982. // Adjust nameLen based on any escape characters we added to escape the '\"' in name.
  4983. nameLen = (unsigned short)AppendWithEscapeCharacters(nameBuffer, name, nameLen, '\\', '\"');
  4984. nameBuffer->AppendCppLiteral(_u("\";"));
  4985. // Add 3 padding characters here - one for initial '\"' character, too.
  4986. nameLen += 3;
  4987. return nameLen;
  4988. }
  4989. Js::Var* ScriptContext::GetModuleExportSlotArrayAddress(uint moduleIndex, uint slotIndex)
  4990. {
  4991. Js::SourceTextModuleRecord* moduleRecord = this->GetModuleRecord(moduleIndex);
  4992. Assert(moduleRecord != nullptr);
  4993. // Require caller to also provide the intended access slot so we can do bounds check now.
  4994. if (moduleRecord->GetLocalExportCount() + 1 <= slotIndex)
  4995. {
  4996. Js::Throw::FatalInternalError();
  4997. }
  4998. return moduleRecord->GetLocalExportSlots();
  4999. }
  5000. } // End namespace Js