ScriptContext.cpp 259 KB

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