ScriptContext.cpp 264 KB

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