ScriptContext.cpp 265 KB

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