ScriptContext.cpp 259 KB

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