ScriptContext.cpp 254 KB

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