ScriptContext.cpp 222 KB

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