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