ScriptContext.cpp 235 KB

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