ScriptContext.cpp 232 KB

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