ScriptContext.cpp 213 KB

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