ThreadContext.cpp 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft Corporation and contributors. 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. #include "BackendApi.h"
  7. #include "ThreadServiceWrapper.h"
  8. #include "Types/TypePropertyCache.h"
  9. #include "Debug/DebuggingFlags.h"
  10. #include "Debug/DiagProbe.h"
  11. #include "Debug/DebugManager.h"
  12. #include "Chars.h"
  13. #include "CaseInsensitive.h"
  14. #include "CharSet.h"
  15. #include "CharMap.h"
  16. #include "StandardChars.h"
  17. #include "Base/ThreadContextTlsEntry.h"
  18. #include "Base/ThreadBoundThreadContextManager.h"
  19. #include "Language/SourceDynamicProfileManager.h"
  20. #include "Language/CodeGenRecyclableData.h"
  21. #include "Language/InterpreterStackFrame.h"
  22. #include "Language/JavascriptStackWalker.h"
  23. #include "Base/ScriptMemoryDumper.h"
  24. // SIMD_JS
  25. #include "Library/SimdLib.h"
  26. #if DBG
  27. #include "Memory/StressTest.h"
  28. #endif
  29. #ifdef DYNAMIC_PROFILE_MUTATOR
  30. #include "Language/DynamicProfileMutator.h"
  31. #endif
  32. #ifdef ENABLE_BASIC_TELEMETRY
  33. #include "Telemetry.h"
  34. #endif
  35. const int TotalNumberOfBuiltInProperties = Js::PropertyIds::_countJSOnlyProperty;
  36. /*
  37. * When we aren't adding any additional properties
  38. */
  39. void DefaultInitializeAdditionalProperties(ThreadContext *threadContext)
  40. {
  41. }
  42. /*
  43. *
  44. */
  45. void (*InitializeAdditionalProperties)(ThreadContext *threadContext) = DefaultInitializeAdditionalProperties;
  46. CriticalSection ThreadContext::s_csThreadContext;
  47. size_t ThreadContext::processNativeCodeSize = 0;
  48. ThreadContext * ThreadContext::globalListFirst = nullptr;
  49. ThreadContext * ThreadContext::globalListLast = nullptr;
  50. THREAD_LOCAL uint ThreadContext::activeScriptSiteCount = 0;
  51. const Js::PropertyRecord * const ThreadContext::builtInPropertyRecords[] =
  52. {
  53. Js::BuiltInPropertyRecords::EMPTY,
  54. #define ENTRY_INTERNAL_SYMBOL(n) Js::BuiltInPropertyRecords::n,
  55. #define ENTRY_SYMBOL(n, d) Js::BuiltInPropertyRecords::n,
  56. #define ENTRY(n) Js::BuiltInPropertyRecords::n,
  57. #define ENTRY2(n, s) ENTRY(n)
  58. #include "Base/JnDirectFields.h"
  59. };
  60. ThreadContext::RecyclableData::RecyclableData(Recycler *const recycler) :
  61. soErrorObject(nullptr, nullptr, nullptr, true),
  62. oomErrorObject(nullptr, nullptr, nullptr, true),
  63. terminatedErrorObject(nullptr, nullptr, nullptr),
  64. typesWithProtoPropertyCache(recycler),
  65. propertyGuards(recycler, 128),
  66. oldEntryPointInfo(nullptr),
  67. returnedValueList(nullptr),
  68. constructorCacheInvalidationCount(0)
  69. {
  70. }
  71. ThreadContext::ThreadContext(AllocationPolicyManager * allocationPolicyManager, JsUtil::ThreadService::ThreadServiceCallback threadServiceCallback, bool enableExperimentalFeatures) :
  72. currentThreadId(::GetCurrentThreadId()),
  73. stackLimitForCurrentThread(0),
  74. stackProber(nullptr),
  75. isThreadBound(false),
  76. hasThrownPendingException(false),
  77. pendingFinallyException(nullptr),
  78. noScriptScope(false),
  79. heapEnum(nullptr),
  80. threadContextFlags(ThreadContextFlagNoFlag),
  81. JsUtil::DoublyLinkedListElement<ThreadContext>(),
  82. allocationPolicyManager(allocationPolicyManager),
  83. threadService(threadServiceCallback),
  84. isOptimizedForManyInstances(Js::Configuration::Global.flags.OptimizeForManyInstances),
  85. bgJit(Js::Configuration::Global.flags.BgJit),
  86. pageAllocator(allocationPolicyManager, PageAllocatorType_Thread, Js::Configuration::Global.flags, 0, PageAllocator::DefaultMaxFreePageCount,
  87. false
  88. #if ENABLE_BACKGROUND_PAGE_FREEING
  89. , &backgroundPageQueue
  90. #endif
  91. ),
  92. recycler(nullptr),
  93. hasCollectionCallBack(false),
  94. callDispose(true),
  95. #if ENABLE_NATIVE_CODEGEN
  96. jobProcessor(nullptr),
  97. #endif
  98. interruptPoller(nullptr),
  99. expirableCollectModeGcCount(-1),
  100. expirableObjectList(nullptr),
  101. expirableObjectDisposeList(nullptr),
  102. numExpirableObjects(0),
  103. disableExpiration(false),
  104. callRootLevel(0),
  105. nextTypeId((Js::TypeId)Js::Constants::ReservedTypeIds),
  106. entryExitRecord(nullptr),
  107. leafInterpreterFrame(nullptr),
  108. threadServiceWrapper(nullptr),
  109. temporaryArenaAllocatorCount(0),
  110. temporaryGuestArenaAllocatorCount(0),
  111. crefSContextForDiag(0),
  112. m_prereservedRegionAddr(0),
  113. scriptContextList(nullptr),
  114. scriptContextEverRegistered(false),
  115. #if DBG_DUMP || defined(PROFILE_EXEC)
  116. topLevelScriptSite(nullptr),
  117. #endif
  118. polymorphicCacheState(0),
  119. stackProbeCount(0),
  120. #ifdef BAILOUT_INJECTION
  121. bailOutByteCodeLocationCount(0),
  122. #endif
  123. sourceCodeSize(0),
  124. nativeCodeSize(0),
  125. threadAlloc(_u("TC"), GetPageAllocator(), Js::Throw::OutOfMemory),
  126. inlineCacheThreadInfoAllocator(_u("TC-InlineCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
  127. isInstInlineCacheThreadInfoAllocator(_u("TC-IsInstInlineCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
  128. equivalentTypeCacheInfoAllocator(_u("TC-EquivalentTypeCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
  129. preReservedVirtualAllocator(),
  130. protoInlineCacheByPropId(&inlineCacheThreadInfoAllocator, 512),
  131. storeFieldInlineCacheByPropId(&inlineCacheThreadInfoAllocator, 256),
  132. isInstInlineCacheByFunction(&isInstInlineCacheThreadInfoAllocator, 128),
  133. registeredInlineCacheCount(0),
  134. unregisteredInlineCacheCount(0),
  135. prototypeChainEnsuredToHaveOnlyWritableDataPropertiesAllocator(_u("TC-ProtoWritableProp"), GetPageAllocator(), Js::Throw::OutOfMemory),
  136. standardUTF8Chars(0),
  137. standardUnicodeChars(0),
  138. hasUnhandledException(FALSE),
  139. hasCatchHandler(FALSE),
  140. disableImplicitFlags(DisableImplicitNoFlag),
  141. hasCatchHandlerToUserCode(false),
  142. caseInvariantPropertySet(nullptr),
  143. entryPointToBuiltInOperationIdCache(&threadAlloc, 0),
  144. #if ENABLE_NATIVE_CODEGEN
  145. #if !FLOATVAR
  146. codeGenNumberThreadAllocator(nullptr),
  147. xProcNumberPageSegmentManager(nullptr),
  148. #endif
  149. m_jitNumericProperties(nullptr),
  150. m_jitNeedsPropertyUpdate(false),
  151. #if DYNAMIC_INTERPRETER_THUNK || defined(ASMJS_PLAT)
  152. thunkPageAllocators(allocationPolicyManager, /* allocXData */ false, /* virtualAllocator */ nullptr, GetCurrentProcess()),
  153. #endif
  154. codePageAllocators(allocationPolicyManager, ALLOC_XDATA, GetPreReservedVirtualAllocator(), GetCurrentProcess()),
  155. #if defined(_CONTROL_FLOW_GUARD) && (_M_IX86 || _M_X64)
  156. jitThunkEmitter(this, &VirtualAllocWrapper::Instance , GetCurrentProcess()),
  157. #endif
  158. #endif
  159. dynamicObjectEnumeratorCacheMap(&HeapAllocator::Instance, 16),
  160. //threadContextFlags(ThreadContextFlagNoFlag),
  161. #ifdef NTBUILD
  162. telemetryBlock(&localTelemetryBlock),
  163. #endif
  164. configuration(enableExperimentalFeatures),
  165. jsrtRuntime(nullptr),
  166. propertyMap(nullptr),
  167. rootPendingClose(nullptr),
  168. exceptionCode(0),
  169. isProfilingUserCode(true),
  170. loopDepth(0),
  171. redeferralState(InitialRedeferralState),
  172. gcSinceLastRedeferral(0),
  173. gcSinceCallCountsCollected(0),
  174. tridentLoadAddress(nullptr),
  175. m_remoteThreadContextInfo(nullptr),
  176. debugManager(nullptr)
  177. #if ENABLE_TTD
  178. , TTDContext(nullptr)
  179. , TTDExecutionInfo(nullptr)
  180. , TTDLog(nullptr)
  181. , TTDRootNestingCount(0)
  182. #endif
  183. #ifdef ENABLE_DIRECTCALL_TELEMETRY
  184. , directCallTelemetry(this)
  185. #endif
  186. #if ENABLE_JS_REENTRANCY_CHECK
  187. , noJsReentrancy(false)
  188. #endif
  189. {
  190. pendingProjectionContextCloseList = JsUtil::List<IProjectionContext*, ArenaAllocator>::New(GetThreadAlloc());
  191. hostScriptContextStack = Anew(GetThreadAlloc(), JsUtil::Stack<HostScriptContext*>, GetThreadAlloc());
  192. functionCount = 0;
  193. sourceInfoCount = 0;
  194. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  195. scriptContextCount = 0;
  196. #endif
  197. isScriptActive = false;
  198. #ifdef ENABLE_CUSTOM_ENTROPY
  199. entropy.Initialize();
  200. #endif
  201. #if ENABLE_NATIVE_CODEGEN
  202. this->bailOutRegisterSaveSpace = AnewArrayZ(this->GetThreadAlloc(), Js::Var, GetBailOutRegisterSaveSlotCount());
  203. #endif
  204. #if defined(ENABLE_SIMDJS) && ENABLE_NATIVE_CODEGEN
  205. simdFuncInfoToOpcodeMap = Anew(this->GetThreadAlloc(), FuncInfoToOpcodeMap, this->GetThreadAlloc());
  206. simdOpcodeToSignatureMap = AnewArrayZ(this->GetThreadAlloc(), SimdFuncSignature, Js::Simd128OpcodeCount());
  207. {
  208. #define MACRO_SIMD_WMS(op, LayoutAsmJs, OpCodeAttrAsmJs, OpCodeAttr, ...) \
  209. AddSimdFuncToMaps(Js::OpCode::##op, __VA_ARGS__);
  210. #define MACRO_SIMD_EXTEND_WMS(op, LayoutAsmJs, OpCodeAttrAsmJs, OpCodeAttr, ...) MACRO_SIMD_WMS(op, LayoutAsmJs, OpCodeAttrAsmJs, OpCodeAttr, __VA_ARGS__)
  211. #include "ByteCode/OpCodesSimd.h"
  212. }
  213. #endif // defined(ENABLE_SIMDJS) && ENABLE_NATIVE_CODEGEN
  214. #if DBG_DUMP
  215. scriptSiteCount = 0;
  216. pageAllocator.debugName = _u("Thread");
  217. #endif
  218. #ifdef DYNAMIC_PROFILE_MUTATOR
  219. this->dynamicProfileMutator = DynamicProfileMutator::GetMutator();
  220. #endif
  221. PERF_COUNTER_INC(Basic, ThreadContext);
  222. #ifdef LEAK_REPORT
  223. this->rootTrackerScriptContext = nullptr;
  224. this->threadId = ::GetCurrentThreadId();
  225. #endif
  226. #ifdef NTBUILD
  227. memset(&localTelemetryBlock, 0, sizeof(localTelemetryBlock));
  228. #endif
  229. AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
  230. ThreadContext::LinkToBeginning(this, &ThreadContext::globalListFirst, &ThreadContext::globalListLast);
  231. #if DBG
  232. // Since we created our page allocator while we were constructing this thread context
  233. // it will pick up the thread context id that is current on the thread. We need to update
  234. // that now.
  235. pageAllocator.UpdateThreadContextHandle((ThreadContextId)this);
  236. #endif
  237. #ifdef ENABLE_PROJECTION
  238. #if DBG_DUMP
  239. this->projectionMemoryInformation = nullptr;
  240. #endif
  241. #endif
  242. this->InitAvailableCommit();
  243. }
  244. void ThreadContext::InitAvailableCommit()
  245. {
  246. // Once per process: get the available commit for the process from the OS and push it to the AutoSystemInfo.
  247. // (This must be done lazily, outside DllMain. And it must be done from the Runtime, since the common lib
  248. // doesn't have access to the DelayLoadLibrary stuff.)
  249. ULONG64 commit;
  250. BOOL success = AutoSystemInfo::Data.GetAvailableCommit(&commit);
  251. if (!success)
  252. {
  253. commit = (ULONG64)-1;
  254. #ifdef NTBUILD
  255. APP_MEMORY_INFORMATION AppMemInfo;
  256. success = GetWinCoreProcessThreads()->GetProcessInformation(
  257. GetCurrentProcess(),
  258. ProcessAppMemoryInfo,
  259. &AppMemInfo,
  260. sizeof(AppMemInfo));
  261. if (success)
  262. {
  263. commit = AppMemInfo.AvailableCommit;
  264. }
  265. #endif
  266. AutoSystemInfo::Data.SetAvailableCommit(commit);
  267. }
  268. }
  269. void ThreadContext::SetStackProber(StackProber * stackProber)
  270. {
  271. this->stackProber = stackProber;
  272. if (stackProber != NULL && this->stackLimitForCurrentThread != Js::Constants::StackLimitForScriptInterrupt)
  273. {
  274. this->stackLimitForCurrentThread = stackProber->GetScriptStackLimit();
  275. }
  276. }
  277. size_t ThreadContext::GetScriptStackLimit() const
  278. {
  279. return stackProber->GetScriptStackLimit();
  280. }
  281. HANDLE
  282. ThreadContext::GetProcessHandle() const
  283. {
  284. return GetCurrentProcess();
  285. }
  286. intptr_t
  287. ThreadContext::GetThreadStackLimitAddr() const
  288. {
  289. return (intptr_t)GetAddressOfStackLimitForCurrentThread();
  290. }
  291. #if ENABLE_NATIVE_CODEGEN && defined(ENABLE_SIMDJS) && (defined(_M_IX86) || defined(_M_X64))
  292. intptr_t
  293. ThreadContext::GetSimdTempAreaAddr(uint8 tempIndex) const
  294. {
  295. return (intptr_t)&X86_TEMP_SIMD[tempIndex];
  296. }
  297. #endif
  298. intptr_t
  299. ThreadContext::GetDisableImplicitFlagsAddr() const
  300. {
  301. return (intptr_t)&disableImplicitFlags;
  302. }
  303. intptr_t
  304. ThreadContext::GetImplicitCallFlagsAddr() const
  305. {
  306. return (intptr_t)&implicitCallFlags;
  307. }
  308. ptrdiff_t
  309. ThreadContext::GetChakraBaseAddressDifference() const
  310. {
  311. return 0;
  312. }
  313. ptrdiff_t
  314. ThreadContext::GetCRTBaseAddressDifference() const
  315. {
  316. return 0;
  317. }
  318. IActiveScriptProfilerHeapEnum* ThreadContext::GetHeapEnum()
  319. {
  320. return heapEnum;
  321. }
  322. void ThreadContext::SetHeapEnum(IActiveScriptProfilerHeapEnum* newHeapEnum)
  323. {
  324. Assert((newHeapEnum != nullptr && heapEnum == nullptr) || (newHeapEnum == nullptr && heapEnum != nullptr));
  325. heapEnum = newHeapEnum;
  326. }
  327. void ThreadContext::ClearHeapEnum()
  328. {
  329. Assert(heapEnum != nullptr);
  330. heapEnum = nullptr;
  331. }
  332. void ThreadContext::GlobalInitialize()
  333. {
  334. for (int i = 0; i < _countof(builtInPropertyRecords); i++)
  335. {
  336. builtInPropertyRecords[i]->SetHash(JsUtil::CharacterBuffer<WCHAR>::StaticGetHashCode(builtInPropertyRecords[i]->GetBuffer(), builtInPropertyRecords[i]->GetLength()));
  337. }
  338. }
  339. ThreadContext::~ThreadContext()
  340. {
  341. {
  342. AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
  343. ThreadContext::Unlink(this, &ThreadContext::globalListFirst, &ThreadContext::globalListLast);
  344. }
  345. #if ENABLE_TTD
  346. if(this->TTDContext != nullptr)
  347. {
  348. TT_HEAP_DELETE(TTD::ThreadContextTTD, this->TTDContext);
  349. this->TTDContext = nullptr;
  350. }
  351. if(this->TTDExecutionInfo != nullptr)
  352. {
  353. TT_HEAP_DELETE(TTD::ThreadContextTTD, this->TTDExecutionInfo);
  354. this->TTDExecutionInfo = nullptr;
  355. }
  356. if(this->TTDLog != nullptr)
  357. {
  358. TT_HEAP_DELETE(TTD::EventLog, this->TTDLog);
  359. this->TTDLog = nullptr;
  360. }
  361. #endif
  362. #ifdef LEAK_REPORT
  363. if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
  364. {
  365. AUTO_LEAK_REPORT_SECTION(Js::Configuration::Global.flags, _u("Thread Context (%p): %s (TID: %d)"), this,
  366. this->GetRecycler()->IsInDllCanUnloadNow()? _u("DllCanUnloadNow") :
  367. this->GetRecycler()->IsInDetachProcess()? _u("DetachProcess") : _u("Destructor"), this->threadId);
  368. LeakReport::DumpUrl(this->threadId);
  369. }
  370. #endif
  371. if (interruptPoller)
  372. {
  373. HeapDelete(interruptPoller);
  374. interruptPoller = nullptr;
  375. }
  376. #if DBG
  377. // ThreadContext dtor may be running on a different thread.
  378. // Recycler may call finalizer that free temp Arenas, which will free pages back to
  379. // the page Allocator, which will try to suspend idle on a different thread.
  380. // So we need to disable idle decommit asserts.
  381. pageAllocator.ShutdownIdleDecommit();
  382. #endif
  383. // Allocating memory during the shutdown codepath is not preferred
  384. // so we'll close the page allocator before we release the GC
  385. // If any dispose is allocating memory during shutdown, that is a bug
  386. pageAllocator.Close();
  387. // The recycler need to delete before the background code gen thread
  388. // because that might run finalizer which need access to the background code gen thread.
  389. if (recycler != nullptr)
  390. {
  391. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next)
  392. {
  393. if (!scriptContext->IsActuallyClosed())
  394. {
  395. // We close ScriptContext here because anyhow HeapDelete(recycler) when disposing the
  396. // JavaScriptLibrary will close ScriptContext. Explicit close gives us chance to clear
  397. // other things to which ScriptContext holds reference to
  398. AssertMsg(!IsInScript(), "Can we be in script here?");
  399. scriptContext->MarkForClose();
  400. }
  401. }
  402. // If all scriptContext's have been closed, then the sourceProfileManagersByUrl
  403. // should have been released
  404. AssertMsg(this->recyclableData->sourceProfileManagersByUrl == nullptr ||
  405. this->recyclableData->sourceProfileManagersByUrl->Count() == 0, "There seems to have been a refcounting imbalance.");
  406. this->recyclableData->sourceProfileManagersByUrl = nullptr;
  407. this->recyclableData->oldEntryPointInfo = nullptr;
  408. if (this->recyclableData->symbolRegistrationMap != nullptr)
  409. {
  410. this->recyclableData->symbolRegistrationMap->Clear();
  411. this->recyclableData->symbolRegistrationMap = nullptr;
  412. }
  413. if (this->recyclableData->returnedValueList != nullptr)
  414. {
  415. this->recyclableData->returnedValueList->Clear();
  416. this->recyclableData->returnedValueList = nullptr;
  417. }
  418. if (this->propertyMap != nullptr)
  419. {
  420. HeapDelete(this->propertyMap);
  421. this->propertyMap = nullptr;
  422. }
  423. #if ENABLE_NATIVE_CODEGEN
  424. if (this->m_jitNumericProperties != nullptr)
  425. {
  426. HeapDelete(this->m_jitNumericProperties);
  427. this->m_jitNumericProperties = nullptr;
  428. }
  429. #endif
  430. // Unpin the memory for leak report so we don't report this as a leak.
  431. recyclableData.Unroot(recycler);
  432. #if defined(LEAK_REPORT) || defined(CHECK_MEMORY_LEAK)
  433. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next)
  434. {
  435. scriptContext->ClearSourceContextInfoMaps();
  436. scriptContext->ShutdownClearSourceLists();
  437. }
  438. #ifdef LEAK_REPORT
  439. // heuristically figure out which one is the root tracker script engine
  440. // and force close on it
  441. if (this->rootTrackerScriptContext != nullptr)
  442. {
  443. this->rootTrackerScriptContext->Close(false);
  444. }
  445. #endif
  446. #endif
  447. #if ENABLE_NATIVE_CODEGEN
  448. #if !FLOATVAR
  449. if (this->codeGenNumberThreadAllocator)
  450. {
  451. HeapDelete(this->codeGenNumberThreadAllocator);
  452. this->codeGenNumberThreadAllocator = nullptr;
  453. }
  454. if (this->xProcNumberPageSegmentManager)
  455. {
  456. HeapDelete(this->xProcNumberPageSegmentManager);
  457. this->xProcNumberPageSegmentManager = nullptr;
  458. }
  459. #endif
  460. #endif
  461. Assert(this->debugManager == nullptr);
  462. HeapDelete(recycler);
  463. }
  464. #if ENABLE_NATIVE_CODEGEN
  465. if(jobProcessor)
  466. {
  467. if(this->bgJit)
  468. {
  469. HeapDelete(static_cast<JsUtil::BackgroundJobProcessor *>(jobProcessor));
  470. }
  471. else
  472. {
  473. HeapDelete(static_cast<JsUtil::ForegroundJobProcessor *>(jobProcessor));
  474. }
  475. jobProcessor = nullptr;
  476. }
  477. #endif
  478. // Do not require all GC callbacks to be revoked, because Trident may not revoke if there
  479. // is a leak, and we don't want the leak to be masked by an assert
  480. #ifdef ENABLE_PROJECTION
  481. externalWeakReferenceCacheList.Clear(&HeapAllocator::Instance);
  482. #endif
  483. this->collectCallBackList.Clear(&HeapAllocator::Instance);
  484. this->protoInlineCacheByPropId.Reset();
  485. this->storeFieldInlineCacheByPropId.Reset();
  486. this->isInstInlineCacheByFunction.Reset();
  487. this->equivalentTypeCacheEntryPoints.Reset();
  488. this->prototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext.Reset();
  489. this->registeredInlineCacheCount = 0;
  490. this->unregisteredInlineCacheCount = 0;
  491. AssertMsg(this->GetHeapEnum() == nullptr, "Heap enumeration should have been cleared/closed by the ScriptSite.");
  492. if (this->GetHeapEnum() != nullptr)
  493. {
  494. this->ClearHeapEnum();
  495. }
  496. #ifdef BAILOUT_INJECTION
  497. if (Js::Configuration::Global.flags.IsEnabled(Js::BailOutByteCodeFlag)
  498. && Js::Configuration::Global.flags.BailOutByteCode.Empty())
  499. {
  500. Output::Print(_u("Bail out byte code location count: %d"), this->bailOutByteCodeLocationCount);
  501. }
  502. #endif
  503. Assert(processNativeCodeSize >= nativeCodeSize);
  504. ::InterlockedExchangeSubtract(&processNativeCodeSize, nativeCodeSize);
  505. PERF_COUNTER_DEC(Basic, ThreadContext);
  506. #ifdef DYNAMIC_PROFILE_MUTATOR
  507. if (this->dynamicProfileMutator != nullptr)
  508. {
  509. this->dynamicProfileMutator->Delete();
  510. }
  511. #endif
  512. #ifdef ENABLE_PROJECTION
  513. #if DBG_DUMP
  514. if (this->projectionMemoryInformation)
  515. {
  516. this->projectionMemoryInformation->Release();
  517. this->projectionMemoryInformation = nullptr;
  518. }
  519. #endif
  520. #endif
  521. }
  522. void
  523. ThreadContext::SetJSRTRuntime(void* runtime)
  524. {
  525. Assert(jsrtRuntime == nullptr);
  526. jsrtRuntime = runtime;
  527. #ifdef ENABLE_BASIC_TELEMETRY
  528. Telemetry::EnsureInitializeForJSRT();
  529. #endif
  530. }
  531. void ThreadContext::CloseForJSRT()
  532. {
  533. // This is used for JSRT APIs only.
  534. Assert(this->jsrtRuntime);
  535. #ifdef ENABLE_BASIC_TELEMETRY
  536. // log any relevant telemetry before disposing the current thread for cases which are properly shutdown
  537. Telemetry::OnJSRTThreadContextClose();
  538. #endif
  539. ShutdownThreads();
  540. }
  541. ThreadContext* ThreadContext::GetContextForCurrentThread()
  542. {
  543. ThreadContextTLSEntry * tlsEntry = ThreadContextTLSEntry::GetEntryForCurrentThread();
  544. if (tlsEntry != nullptr)
  545. {
  546. return static_cast<ThreadContext *>(tlsEntry->GetThreadContext());
  547. }
  548. return nullptr;
  549. }
  550. void ThreadContext::ValidateThreadContext()
  551. {
  552. #if DBG
  553. // verify the runtime pointer is valid.
  554. {
  555. BOOL found = FALSE;
  556. AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
  557. ThreadContext* currentThreadContext = GetThreadContextList();
  558. while (currentThreadContext)
  559. {
  560. if (currentThreadContext == this)
  561. {
  562. return;
  563. }
  564. currentThreadContext = currentThreadContext->Next();
  565. }
  566. AssertMsg(found, "invalid thread context");
  567. }
  568. #endif
  569. }
  570. #if ENABLE_NATIVE_CODEGEN && defined(ENABLE_SIMDJS)
  571. void ThreadContext::AddSimdFuncToMaps(Js::OpCode op, ...)
  572. {
  573. Assert(simdFuncInfoToOpcodeMap != nullptr);
  574. Assert(simdOpcodeToSignatureMap != nullptr);
  575. va_list arguments;
  576. va_start(arguments, op);
  577. int argumentsCount = va_arg(arguments, int);
  578. AssertMsg(argumentsCount >= 0 && argumentsCount <= 20, "Invalid arguments count for SIMD opcode");
  579. if (argumentsCount == 0)
  580. {
  581. // no info to add
  582. return;
  583. }
  584. Js::FunctionInfo *funcInfo = va_arg(arguments, Js::FunctionInfo*);
  585. AddSimdFuncInfo(op, funcInfo);
  586. SimdFuncSignature simdFuncSignature;
  587. simdFuncSignature.valid = true;
  588. simdFuncSignature.argCount = argumentsCount - 2; // arg count to Simd func = argumentsCount - FuncInfo and return Type fields.
  589. simdFuncSignature.returnType = va_arg(arguments, ValueType);
  590. simdFuncSignature.args = AnewArrayZ(this->GetThreadAlloc(), ValueType, simdFuncSignature.argCount);
  591. for (uint iArg = 0; iArg < simdFuncSignature.argCount; iArg++)
  592. {
  593. simdFuncSignature.args[iArg] = va_arg(arguments, ValueType);
  594. }
  595. simdOpcodeToSignatureMap[Js::SIMDUtils::SimdOpcodeAsIndex(op)] = simdFuncSignature;
  596. va_end(arguments);
  597. }
  598. void ThreadContext::AddSimdFuncInfo(Js::OpCode op, Js::FunctionInfo *funcInfo)
  599. {
  600. // primary funcInfo
  601. simdFuncInfoToOpcodeMap->AddNew(funcInfo, op);
  602. // Entry points of SIMD loads/stores of non-full width all map to the same opcode. This is not captured in the opcode table, so add additional entry points here.
  603. switch (op)
  604. {
  605. case Js::OpCode::Simd128_LdArr_F4:
  606. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDFloat32x4Lib::EntryInfo::Load1, op);
  607. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDFloat32x4Lib::EntryInfo::Load2, op);
  608. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDFloat32x4Lib::EntryInfo::Load3, op);
  609. break;
  610. case Js::OpCode::Simd128_StArr_F4:
  611. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDFloat32x4Lib::EntryInfo::Store1, op);
  612. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDFloat32x4Lib::EntryInfo::Store2, op);
  613. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDFloat32x4Lib::EntryInfo::Store3, op);
  614. break;
  615. case Js::OpCode::Simd128_LdArr_I4:
  616. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDInt32x4Lib::EntryInfo::Load1, op);
  617. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDInt32x4Lib::EntryInfo::Load2, op);
  618. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDInt32x4Lib::EntryInfo::Load3, op);
  619. break;
  620. case Js::OpCode::Simd128_StArr_I4:
  621. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDInt32x4Lib::EntryInfo::Store1, op);
  622. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDInt32x4Lib::EntryInfo::Store2, op);
  623. simdFuncInfoToOpcodeMap->AddNew(&Js::SIMDInt32x4Lib::EntryInfo::Store3, op);
  624. break;
  625. }
  626. }
  627. Js::OpCode ThreadContext::GetSimdOpcodeFromFuncInfo(Js::FunctionInfo * funcInfo)
  628. {
  629. Assert(simdFuncInfoToOpcodeMap != nullptr);
  630. if (simdFuncInfoToOpcodeMap->ContainsKey(funcInfo))
  631. {
  632. return simdFuncInfoToOpcodeMap->Item(funcInfo);
  633. }
  634. return (Js::OpCode) 0;
  635. }
  636. void ThreadContext::GetSimdFuncSignatureFromOpcode(Js::OpCode op, SimdFuncSignature &funcSignature)
  637. {
  638. Assert(simdOpcodeToSignatureMap != nullptr);
  639. funcSignature = simdOpcodeToSignatureMap[Js::SIMDUtils::SimdOpcodeAsIndex(op)];
  640. }
  641. #endif
  642. class AutoRecyclerPtr : public AutoPtr<Recycler>
  643. {
  644. public:
  645. AutoRecyclerPtr(Recycler * ptr) : AutoPtr<Recycler>(ptr) {}
  646. ~AutoRecyclerPtr()
  647. {
  648. #if ENABLE_CONCURRENT_GC
  649. if (ptr != nullptr)
  650. {
  651. ptr->ShutdownThread();
  652. }
  653. #endif
  654. }
  655. };
  656. Recycler* ThreadContext::EnsureRecycler()
  657. {
  658. if (recycler == NULL)
  659. {
  660. AutoRecyclerPtr newRecycler(HeapNew(Recycler, GetAllocationPolicyManager(), &pageAllocator, Js::Throw::OutOfMemory, Js::Configuration::Global.flags));
  661. newRecycler->Initialize(isOptimizedForManyInstances, &threadService); // use in-thread GC when optimizing for many instances
  662. newRecycler->SetCollectionWrapper(this);
  663. #if ENABLE_NATIVE_CODEGEN
  664. // This may throw, so it needs to be after the recycler is initialized,
  665. // otherwise, the recycler dtor may encounter problems
  666. #if !FLOATVAR
  667. // TODO: we only need one of the following, one for OOP jit and one for in-proc BG JIT
  668. AutoPtr<CodeGenNumberThreadAllocator> localCodeGenNumberThreadAllocator(
  669. HeapNew(CodeGenNumberThreadAllocator, newRecycler));
  670. AutoPtr<XProcNumberPageSegmentManager> localXProcNumberPageSegmentManager(
  671. HeapNew(XProcNumberPageSegmentManager, newRecycler));
  672. #endif
  673. #endif
  674. this->recyclableData.Root(RecyclerNewZ(newRecycler, RecyclableData, newRecycler), newRecycler);
  675. if (this->IsThreadBound())
  676. {
  677. newRecycler->SetIsThreadBound();
  678. }
  679. // Assign the recycler to the ThreadContext after everything is initialized, because an OOM during initialization would
  680. // result in only partial initialization, so the 'recycler' member variable should remain null to cause full
  681. // reinitialization when requested later. Anything that happens after the Detach must have special cleanup code.
  682. this->recycler = newRecycler.Detach();
  683. try
  684. {
  685. #ifdef RECYCLER_WRITE_BARRIER
  686. #ifdef _M_X64_OR_ARM64
  687. if (!RecyclerWriteBarrierManager::OnThreadInit())
  688. {
  689. Js::Throw::OutOfMemory();
  690. }
  691. #endif
  692. #endif
  693. this->expirableObjectList = Anew(&this->threadAlloc, ExpirableObjectList, &this->threadAlloc);
  694. this->expirableObjectDisposeList = Anew(&this->threadAlloc, ExpirableObjectList, &this->threadAlloc);
  695. InitializePropertyMaps(); // has many dependencies on the recycler and other members of the thread context
  696. #if ENABLE_NATIVE_CODEGEN
  697. #if !FLOATVAR
  698. this->codeGenNumberThreadAllocator = localCodeGenNumberThreadAllocator.Detach();
  699. this->xProcNumberPageSegmentManager = localXProcNumberPageSegmentManager.Detach();
  700. #endif
  701. #endif
  702. }
  703. catch(...)
  704. {
  705. // Initialization failed, undo what was done above. Callees that throw must clean up after themselves.
  706. if (this->recyclableData != nullptr)
  707. {
  708. this->recyclableData.Unroot(this->recycler);
  709. }
  710. {
  711. // AutoRecyclerPtr's destructor takes care of shutting down the background thread and deleting the recycler
  712. AutoRecyclerPtr recyclerToDelete(this->recycler);
  713. this->recycler = nullptr;
  714. }
  715. throw;
  716. }
  717. JS_ETW(EventWriteJSCRIPT_GC_INIT(this->recycler, this->GetHiResTimer()->Now()));
  718. }
  719. #if DBG
  720. if (CONFIG_FLAG(RecyclerTest))
  721. {
  722. StressTester test(recycler);
  723. test.Run();
  724. }
  725. #endif
  726. return recycler;
  727. }
  728. Js::PropertyRecord const *
  729. ThreadContext::GetPropertyName(Js::PropertyId propertyId)
  730. {
  731. // This API should only be use on the main thread
  732. Assert(GetCurrentThreadContextId() == (ThreadContextId)this);
  733. return this->GetPropertyNameImpl<false>(propertyId);
  734. }
  735. Js::PropertyRecord const *
  736. ThreadContext::GetPropertyNameLocked(Js::PropertyId propertyId)
  737. {
  738. return GetPropertyNameImpl<true>(propertyId);
  739. }
  740. template <bool locked>
  741. Js::PropertyRecord const *
  742. ThreadContext::GetPropertyNameImpl(Js::PropertyId propertyId)
  743. {
  744. //TODO: Remove this when completely transformed to use PropertyRecord*. Currently this is only partially done,
  745. // and there are calls to GetPropertyName with InternalPropertyId.
  746. if (propertyId >= 0 && Js::IsInternalPropertyId(propertyId))
  747. {
  748. return Js::InternalPropertyRecords::GetInternalPropertyName(propertyId);
  749. }
  750. int propertyIndex = propertyId - Js::PropertyIds::_none;
  751. if (propertyIndex < 0 || propertyIndex > propertyMap->GetLastIndex())
  752. {
  753. propertyIndex = 0;
  754. }
  755. const Js::PropertyRecord * propertyRecord = nullptr;
  756. if (locked) { propertyMap->LockResize(); }
  757. bool found = propertyMap->TryGetValueAt(propertyIndex, &propertyRecord);
  758. if (locked) { propertyMap->UnlockResize(); }
  759. AssertMsg(found && propertyRecord != nullptr, "using invalid propertyid");
  760. return propertyRecord;
  761. }
  762. void
  763. ThreadContext::FindPropertyRecord(Js::JavascriptString *pstName, Js::PropertyRecord const ** propertyRecord)
  764. {
  765. LPCWSTR psz = pstName->GetSz();
  766. FindPropertyRecord(psz, pstName->GetLength(), propertyRecord);
  767. }
  768. void
  769. ThreadContext::FindPropertyRecord(__in LPCWSTR propertyName, __in int propertyNameLength, Js::PropertyRecord const ** propertyRecord)
  770. {
  771. EnterPinnedScope((volatile void **)propertyRecord);
  772. *propertyRecord = FindPropertyRecord(propertyName, propertyNameLength);
  773. LeavePinnedScope();
  774. }
  775. Js::PropertyRecord const *
  776. ThreadContext::GetPropertyRecord(Js::PropertyId propertyId)
  777. {
  778. return GetPropertyNameLocked(propertyId);
  779. }
  780. bool
  781. ThreadContext::IsNumericProperty(Js::PropertyId propertyId)
  782. {
  783. return GetPropertyRecord(propertyId)->IsNumeric();
  784. }
  785. const Js::PropertyRecord *
  786. ThreadContext::FindPropertyRecord(const char16 * propertyName, int propertyNameLength)
  787. {
  788. Js::PropertyRecord const * propertyRecord = nullptr;
  789. if (IsDirectPropertyName(propertyName, propertyNameLength))
  790. {
  791. propertyRecord = propertyNamesDirect[propertyName[0]];
  792. Assert(propertyRecord == propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(propertyName, propertyNameLength)));
  793. }
  794. else
  795. {
  796. propertyRecord = propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(propertyName, propertyNameLength));
  797. }
  798. return propertyRecord;
  799. }
  800. Js::PropertyRecord const *
  801. ThreadContext::UncheckedAddPropertyId(__in LPCWSTR propertyName, __in int propertyNameLength, bool bind, bool isSymbol)
  802. {
  803. return UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength), bind, isSymbol);
  804. }
  805. void ThreadContext::InitializePropertyMaps()
  806. {
  807. Assert(this->recycler != nullptr);
  808. Assert(this->recyclableData != nullptr);
  809. Assert(this->propertyMap == nullptr);
  810. Assert(this->caseInvariantPropertySet == nullptr);
  811. try
  812. {
  813. this->propertyMap = HeapNew(PropertyMap, &HeapAllocator::Instance, TotalNumberOfBuiltInProperties + 700);
  814. this->recyclableData->boundPropertyStrings = RecyclerNew(this->recycler, JsUtil::List<Js::PropertyRecord const*>, this->recycler);
  815. memset(propertyNamesDirect, 0, 128*sizeof(Js::PropertyRecord *));
  816. Js::JavascriptLibrary::InitializeProperties(this);
  817. InitializeAdditionalProperties(this);
  818. //Js::JavascriptLibrary::InitializeDOMProperties(this);
  819. }
  820. catch(...)
  821. {
  822. // Initialization failed, undo what was done above. Callees that throw must clean up after themselves. The recycler will
  823. // be trashed, so clear members that point to recyclable memory. Stuff in 'recyclableData' will be taken care of by the
  824. // recycler, and the 'recyclableData' instance will be trashed as well.
  825. if (this->propertyMap != nullptr)
  826. {
  827. HeapDelete(this->propertyMap);
  828. }
  829. this->propertyMap = nullptr;
  830. this->caseInvariantPropertySet = nullptr;
  831. memset(propertyNamesDirect, 0, 128*sizeof(Js::PropertyRecord *));
  832. throw;
  833. }
  834. }
  835. void ThreadContext::UncheckedAddBuiltInPropertyId()
  836. {
  837. for (int i = 0; i < _countof(builtInPropertyRecords); i++)
  838. {
  839. AddPropertyRecordInternal(builtInPropertyRecords[i]);
  840. }
  841. }
  842. bool
  843. ThreadContext::IsDirectPropertyName(const char16 * propertyName, int propertyNameLength)
  844. {
  845. return ((propertyNameLength == 1) && ((propertyName[0] & 0xFF80) == 0));
  846. }
  847. RecyclerWeakReference<const Js::PropertyRecord> *
  848. ThreadContext::CreatePropertyRecordWeakRef(const Js::PropertyRecord * propertyRecord)
  849. {
  850. RecyclerWeakReference<const Js::PropertyRecord> * propertyRecordWeakRef;
  851. if (propertyRecord->IsBound())
  852. {
  853. // Create a fake weak ref
  854. propertyRecordWeakRef = RecyclerNewLeaf(this->recycler, StaticPropertyRecordReference, propertyRecord);
  855. }
  856. else
  857. {
  858. propertyRecordWeakRef = recycler->CreateWeakReferenceHandle(propertyRecord);
  859. }
  860. return propertyRecordWeakRef;
  861. }
  862. Js::PropertyRecord const *
  863. ThreadContext::UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR> const& propertyName, bool bind, bool isSymbol)
  864. {
  865. #if ENABLE_TTD
  866. if(isSymbol & this->IsRuntimeInTTDMode())
  867. {
  868. if(this->TTDContext->GetActiveScriptContext() != nullptr && this->TTDContext->GetActiveScriptContext()->ShouldPerformReplayAction())
  869. {
  870. //We reload all properties that occour in the trace so they only way we get here in TTD mode is:
  871. //(1) if the program is creating a new symbol (which always gets a fresh id) and we should recreate it or
  872. //(2) if it is forcing arguments in debug parse mode (instead of regular which we recorded in)
  873. Js::PropertyId propertyId = Js::Constants::NoProperty;
  874. this->TTDLog->ReplaySymbolCreationEvent(&propertyId);
  875. //Don't recreate the symbol below, instead return the known symbol by looking up on the pid
  876. const Js::PropertyRecord* res = this->GetPropertyName(propertyId);
  877. AssertMsg(res != nullptr, "This should never happen!!!");
  878. return res;
  879. }
  880. }
  881. #endif
  882. this->propertyMap->EnsureCapacity();
  883. // Automatically bind direct (single-character) property names, so that they can be
  884. // stored in the direct property table
  885. if (IsDirectPropertyName(propertyName.GetBuffer(), propertyName.GetLength()))
  886. {
  887. bind = true;
  888. }
  889. // Create the PropertyRecord
  890. int length = propertyName.GetLength();
  891. uint bytelength = sizeof(char16) * length;
  892. uint32 indexVal = 0;
  893. // Symbol properties cannot be numeric since their description is not to be used!
  894. bool isNumeric = !isSymbol && Js::PropertyRecord::IsPropertyNameNumeric(propertyName.GetBuffer(), propertyName.GetLength(), &indexVal);
  895. uint hash = JsUtil::CharacterBuffer<WCHAR>::StaticGetHashCode(propertyName.GetBuffer(), propertyName.GetLength());
  896. size_t allocLength = bytelength + sizeof(char16) + (isNumeric ? sizeof(uint32) : 0);
  897. // If it's bound, create it in the thread arena, along with a fake weak ref
  898. Js::PropertyRecord * propertyRecord;
  899. if (bind)
  900. {
  901. propertyRecord = AnewPlus(GetThreadAlloc(), allocLength, Js::PropertyRecord, bytelength, isNumeric, hash, isSymbol);
  902. propertyRecord->isBound = true;
  903. }
  904. else
  905. {
  906. propertyRecord = RecyclerNewFinalizedLeafPlus(recycler, allocLength, Js::PropertyRecord, bytelength, isNumeric, hash, isSymbol);
  907. }
  908. // Copy string and numeric info
  909. char16* buffer = (char16 *)(propertyRecord + 1);
  910. js_memcpy_s(buffer, bytelength, propertyName.GetBuffer(), bytelength);
  911. buffer[length] = _u('\0');
  912. if (isNumeric)
  913. {
  914. *(uint32 *)(buffer + length + 1) = indexVal;
  915. Assert(propertyRecord->GetNumericValue() == indexVal);
  916. }
  917. Js::PropertyId propertyId = this->GetNextPropertyId();
  918. #if ENABLE_TTD
  919. if(isSymbol & this->IsRuntimeInTTDMode())
  920. {
  921. if(this->TTDContext->GetActiveScriptContext() != nullptr && this->TTDContext->GetActiveScriptContext()->ShouldPerformRecordAction())
  922. {
  923. this->TTDLog->RecordSymbolCreationEvent(propertyId);
  924. }
  925. }
  926. #endif
  927. propertyRecord->pid = propertyId;
  928. AddPropertyRecordInternal(propertyRecord);
  929. return propertyRecord;
  930. }
  931. void
  932. ThreadContext::AddPropertyRecordInternal(const Js::PropertyRecord * propertyRecord)
  933. {
  934. // At this point the PropertyRecord is constructed but not added to the map.
  935. const char16 * propertyName = propertyRecord->GetBuffer();
  936. int propertyNameLength = propertyRecord->GetLength();
  937. Js::PropertyId propertyId = propertyRecord->GetPropertyId();
  938. Assert(propertyId == GetNextPropertyId());
  939. Assert(!IsActivePropertyId(propertyId));
  940. #if DBG
  941. // Only Assert we can't find the property if we are not adding a symbol.
  942. // For a symbol, the propertyName is not used and may collide with something in the map already.
  943. if (!propertyRecord->IsSymbol())
  944. {
  945. Assert(FindPropertyRecord(propertyName, propertyNameLength) == nullptr);
  946. }
  947. #endif
  948. #if ENABLE_TTD
  949. if(this->IsRuntimeInTTDMode())
  950. {
  951. this->TTDLog->AddPropertyRecord(propertyRecord);
  952. }
  953. #endif
  954. // Add to the map
  955. propertyMap->Add(propertyRecord);
  956. #if ENABLE_NATIVE_CODEGEN
  957. if (m_jitNumericProperties)
  958. {
  959. if (propertyRecord->IsNumeric())
  960. {
  961. m_jitNumericProperties->Set(propertyRecord->GetPropertyId());
  962. m_jitNeedsPropertyUpdate = true;
  963. }
  964. }
  965. #endif
  966. PropertyRecordTrace(_u("Added property '%s' at 0x%08x, pid = %d\n"), propertyName, propertyRecord, propertyId);
  967. // Do not store the pid for symbols in the direct property name table.
  968. // We don't want property ids for symbols to be searchable anyway.
  969. if (!propertyRecord->IsSymbol() && IsDirectPropertyName(propertyName, propertyNameLength))
  970. {
  971. // Store the pids for single character properties in the propertyNamesDirect array.
  972. // This property record should have been created as bound by the caller.
  973. Assert(propertyRecord->IsBound());
  974. Assert(propertyNamesDirect[propertyName[0]] == nullptr);
  975. propertyNamesDirect[propertyName[0]] = propertyRecord;
  976. }
  977. if (caseInvariantPropertySet)
  978. {
  979. AddCaseInvariantPropertyRecord(propertyRecord);
  980. }
  981. // Check that everything was added correctly
  982. #if DBG
  983. // Only Assert we can find the property if we are not adding a symbol.
  984. // For a symbol, the propertyName is not used and we won't be able to look the pid up via name.
  985. if (!propertyRecord->IsSymbol())
  986. {
  987. Assert(FindPropertyRecord(propertyName, propertyNameLength) == propertyRecord);
  988. }
  989. // We will still be able to lookup the symbol property by the property id, so go ahead and check that.
  990. Assert(GetPropertyName(propertyRecord->GetPropertyId()) == propertyRecord);
  991. #endif
  992. JS_ETW_INTERNAL(EventWriteJSCRIPT_HOSTING_PROPERTYID_LIST(propertyRecord, propertyRecord->GetBuffer()));
  993. }
  994. void
  995. ThreadContext::AddCaseInvariantPropertyRecord(const Js::PropertyRecord * propertyRecord)
  996. {
  997. Assert(this->caseInvariantPropertySet != nullptr);
  998. // Create a weak reference to the property record here (since we no longer use weak refs in the property map)
  999. RecyclerWeakReference<const Js::PropertyRecord> * propertyRecordWeakRef = CreatePropertyRecordWeakRef(propertyRecord);
  1000. JsUtil::CharacterBuffer<WCHAR> newPropertyName(propertyRecord->GetBuffer(), propertyRecord->GetLength());
  1001. Js::CaseInvariantPropertyListWithHashCode* list;
  1002. if (!FindExistingPropertyRecord(newPropertyName, &list))
  1003. {
  1004. // This binds all the property string that is key in this map with no hope of reclaiming them
  1005. // TODO: do better
  1006. list = RecyclerNew(recycler, Js::CaseInvariantPropertyListWithHashCode, recycler, 1);
  1007. // Do the add first so that the list is non-empty and we can calculate its hashcode correctly
  1008. list->Add(propertyRecordWeakRef);
  1009. // This will calculate the hashcode
  1010. caseInvariantPropertySet->Add(list);
  1011. }
  1012. else
  1013. {
  1014. list->Add(propertyRecordWeakRef);
  1015. }
  1016. }
  1017. void
  1018. ThreadContext::BindPropertyRecord(const Js::PropertyRecord * propertyRecord)
  1019. {
  1020. if (!propertyRecord->IsBound())
  1021. {
  1022. Assert(!this->recyclableData->boundPropertyStrings->Contains(propertyRecord));
  1023. this->recyclableData->boundPropertyStrings->Add(propertyRecord);
  1024. // Cast around constness to set propertyRecord as bound
  1025. const_cast<Js::PropertyRecord *>(propertyRecord)->isBound = true;
  1026. }
  1027. }
  1028. void ThreadContext::GetOrAddPropertyId(__in LPCWSTR propertyName, __in int propertyNameLength, Js::PropertyRecord const ** propertyRecord)
  1029. {
  1030. GetOrAddPropertyId(JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength), propertyRecord);
  1031. }
  1032. void ThreadContext::GetOrAddPropertyId(JsUtil::CharacterBuffer<WCHAR> const& propertyName, Js::PropertyRecord const ** propRecord)
  1033. {
  1034. EnterPinnedScope((volatile void **)propRecord);
  1035. *propRecord = GetOrAddPropertyRecord(propertyName);
  1036. LeavePinnedScope();
  1037. }
  1038. const Js::PropertyRecord *
  1039. ThreadContext::GetOrAddPropertyRecordImpl(JsUtil::CharacterBuffer<char16> propertyName, bool bind)
  1040. {
  1041. // Make sure the recycler is around so that we can take weak references to the property strings
  1042. EnsureRecycler();
  1043. const Js::PropertyRecord * propertyRecord;
  1044. FindPropertyRecord(propertyName.GetBuffer(), propertyName.GetLength(), &propertyRecord);
  1045. if (propertyRecord == nullptr)
  1046. {
  1047. propertyRecord = UncheckedAddPropertyId(propertyName, bind);
  1048. }
  1049. else
  1050. {
  1051. // PropertyRecord exists, but may not be bound. Bind now if requested.
  1052. if (bind)
  1053. {
  1054. BindPropertyRecord(propertyRecord);
  1055. }
  1056. }
  1057. Assert(propertyRecord != nullptr);
  1058. Assert(!bind || propertyRecord->IsBound());
  1059. return propertyRecord;
  1060. }
  1061. void ThreadContext::AddBuiltInPropertyRecord(const Js::PropertyRecord *propertyRecord)
  1062. {
  1063. this->AddPropertyRecordInternal(propertyRecord);
  1064. }
  1065. BOOL ThreadContext::IsNumericPropertyId(Js::PropertyId propertyId, uint32* value)
  1066. {
  1067. Js::PropertyRecord const * propertyRecord = this->GetPropertyName(propertyId);
  1068. Assert(propertyRecord != nullptr);
  1069. if (propertyRecord == nullptr || !propertyRecord->IsNumeric())
  1070. {
  1071. return false;
  1072. }
  1073. *value = propertyRecord->GetNumericValue();
  1074. return true;
  1075. }
  1076. bool ThreadContext::IsActivePropertyId(Js::PropertyId pid)
  1077. {
  1078. Assert(pid != Js::Constants::NoProperty);
  1079. if (Js::IsInternalPropertyId(pid))
  1080. {
  1081. return true;
  1082. }
  1083. int propertyIndex = pid - Js::PropertyIds::_none;
  1084. const Js::PropertyRecord * propertyRecord;
  1085. if (propertyMap->TryGetValueAt(propertyIndex, &propertyRecord) && propertyRecord != nullptr)
  1086. {
  1087. return true;
  1088. }
  1089. return false;
  1090. }
  1091. void ThreadContext::InvalidatePropertyRecord(const Js::PropertyRecord * propertyRecord)
  1092. {
  1093. InternalInvalidateProtoTypePropertyCaches(propertyRecord->GetPropertyId()); // use the internal version so we don't check for active property id
  1094. #if ENABLE_NATIVE_CODEGEN
  1095. if (propertyRecord->IsNumeric() && m_jitNumericProperties)
  1096. {
  1097. m_jitNumericProperties->Clear(propertyRecord->GetPropertyId());
  1098. m_jitNeedsPropertyUpdate = true;
  1099. }
  1100. #endif
  1101. this->propertyMap->Remove(propertyRecord);
  1102. PropertyRecordTrace(_u("Reclaimed property '%s' at 0x%08x, pid = %d\n"),
  1103. propertyRecord->GetBuffer(), propertyRecord, propertyRecord->GetPropertyId());
  1104. }
  1105. Js::PropertyId ThreadContext::GetNextPropertyId()
  1106. {
  1107. return this->propertyMap->GetNextIndex() + Js::PropertyIds::_none;
  1108. }
  1109. Js::PropertyId ThreadContext::GetMaxPropertyId()
  1110. {
  1111. auto maxPropertyId = this->propertyMap->Count() + Js::InternalPropertyIds::Count;
  1112. return maxPropertyId;
  1113. }
  1114. void ThreadContext::CreateNoCasePropertyMap()
  1115. {
  1116. Assert(caseInvariantPropertySet == nullptr);
  1117. caseInvariantPropertySet = RecyclerNew(recycler, PropertyNoCaseSetType, recycler, 173);
  1118. // Prevent the set from being reclaimed
  1119. // Individual items in the set can be reclaimed though since they're lists of weak references
  1120. // The lists themselves can be reclaimed when all the weak references in them are cleared
  1121. this->recyclableData->caseInvariantPropertySet = caseInvariantPropertySet;
  1122. // Note that we are allocating from the recycler below, so we may cause a GC at any time, which
  1123. // could cause PropertyRecords to be collected and removed from the propertyMap.
  1124. // Thus, don't use BaseDictionary::Map here, as it cannot tolerate changes while mapping.
  1125. // Instead, walk the PropertyRecord entries in index order. This will work even if a GC occurs.
  1126. for (int propertyIndex = 0; propertyIndex <= this->propertyMap->GetLastIndex(); propertyIndex++)
  1127. {
  1128. const Js::PropertyRecord * propertyRecord;
  1129. if (this->propertyMap->TryGetValueAt(propertyIndex, &propertyRecord) && propertyRecord != nullptr)
  1130. {
  1131. AddCaseInvariantPropertyRecord(propertyRecord);
  1132. }
  1133. }
  1134. }
  1135. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>*
  1136. ThreadContext::FindPropertyIdNoCase(Js::ScriptContext * scriptContext, LPCWSTR propertyName, int propertyNameLength)
  1137. {
  1138. return ThreadContext::FindPropertyIdNoCase(scriptContext, JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength));
  1139. }
  1140. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>*
  1141. ThreadContext::FindPropertyIdNoCase(Js::ScriptContext * scriptContext, JsUtil::CharacterBuffer<WCHAR> const& propertyName)
  1142. {
  1143. if (caseInvariantPropertySet == nullptr)
  1144. {
  1145. this->CreateNoCasePropertyMap();
  1146. }
  1147. Js::CaseInvariantPropertyListWithHashCode* list;
  1148. if (FindExistingPropertyRecord(propertyName, &list))
  1149. {
  1150. return list;
  1151. }
  1152. return nullptr;
  1153. }
  1154. bool
  1155. ThreadContext::FindExistingPropertyRecord(_In_ JsUtil::CharacterBuffer<WCHAR> const& propertyName, Js::CaseInvariantPropertyListWithHashCode** list)
  1156. {
  1157. Js::CaseInvariantPropertyListWithHashCode* l = this->caseInvariantPropertySet->LookupWithKey(propertyName);
  1158. (*list) = l;
  1159. return (l != nullptr);
  1160. }
  1161. void ThreadContext::CleanNoCasePropertyMap()
  1162. {
  1163. if (this->caseInvariantPropertySet != nullptr)
  1164. {
  1165. this->caseInvariantPropertySet->MapAndRemoveIf([](Js::CaseInvariantPropertyListWithHashCode* value) -> bool {
  1166. if (value && value->Count() == 0)
  1167. {
  1168. // Remove entry
  1169. return true;
  1170. }
  1171. // Keep entry
  1172. return false;
  1173. });
  1174. }
  1175. }
  1176. void
  1177. ThreadContext::ForceCleanPropertyMap()
  1178. {
  1179. // No-op now that we no longer use weak refs
  1180. }
  1181. #if ENABLE_NATIVE_CODEGEN
  1182. JsUtil::JobProcessor *
  1183. ThreadContext::GetJobProcessor()
  1184. {
  1185. if(bgJit && isOptimizedForManyInstances)
  1186. {
  1187. return ThreadBoundThreadContextManager::GetSharedJobProcessor();
  1188. }
  1189. if (!jobProcessor)
  1190. {
  1191. if(bgJit && !isOptimizedForManyInstances)
  1192. {
  1193. jobProcessor = HeapNew(JsUtil::BackgroundJobProcessor, GetAllocationPolicyManager(), &threadService, false /*disableParallelThreads*/);
  1194. }
  1195. else
  1196. {
  1197. jobProcessor = HeapNew(JsUtil::ForegroundJobProcessor);
  1198. }
  1199. }
  1200. return jobProcessor;
  1201. }
  1202. #endif
  1203. void
  1204. ThreadContext::RegisterCodeGenRecyclableData(Js::CodeGenRecyclableData *const codeGenRecyclableData)
  1205. {
  1206. Assert(codeGenRecyclableData);
  1207. Assert(recyclableData);
  1208. // Linking must not be done concurrently with unlinking (caller must use lock)
  1209. recyclableData->codeGenRecyclableDatas.LinkToEnd(codeGenRecyclableData);
  1210. }
  1211. void
  1212. ThreadContext::UnregisterCodeGenRecyclableData(Js::CodeGenRecyclableData *const codeGenRecyclableData)
  1213. {
  1214. Assert(codeGenRecyclableData);
  1215. if(!recyclableData)
  1216. {
  1217. // The thread context's recyclable data may have already been released to the recycler if we're shutting down
  1218. return;
  1219. }
  1220. // Unlinking may be done from a background thread, but not concurrently with linking (caller must use lock). Partial unlink
  1221. // does not zero the previous and next links for the unlinked node so that the recycler can scan through the node from the
  1222. // main thread.
  1223. recyclableData->codeGenRecyclableDatas.UnlinkPartial(codeGenRecyclableData);
  1224. }
  1225. uint
  1226. ThreadContext::EnterScriptStart(Js::ScriptEntryExitRecord * record, bool doCleanup)
  1227. {
  1228. Recycler * recycler = this->GetRecycler();
  1229. Assert(recycler->IsReentrantState());
  1230. JS_ETW_INTERNAL(EventWriteJSCRIPT_RUN_START(this,0));
  1231. // Increment the callRootLevel early so that Dispose ran during FinishConcurrent will not close the current scriptContext
  1232. uint oldCallRootLevel = this->callRootLevel++;
  1233. if (oldCallRootLevel == 0)
  1234. {
  1235. Assert(!this->hasThrownPendingException);
  1236. RECORD_TIMESTAMP(lastScriptStartTime);
  1237. InterruptPoller *poller = this->interruptPoller;
  1238. if (poller)
  1239. {
  1240. poller->StartScript();
  1241. }
  1242. recycler->SetIsInScript(true);
  1243. if (doCleanup)
  1244. {
  1245. recycler->EnterIdleDecommit();
  1246. #if ENABLE_CONCURRENT_GC
  1247. recycler->FinishConcurrent<FinishConcurrentOnEnterScript>();
  1248. #endif
  1249. if (threadServiceWrapper == NULL)
  1250. {
  1251. // Reschedule the next collection at the start of the script.
  1252. recycler->ScheduleNextCollection();
  1253. }
  1254. }
  1255. }
  1256. this->PushEntryExitRecord(record);
  1257. AssertMsg(!this->IsScriptActive(),
  1258. "Missing EnterScriptEnd or LeaveScriptStart");
  1259. this->isScriptActive = true;
  1260. recycler->SetIsScriptActive(true);
  1261. #if DBG_DUMP
  1262. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase))
  1263. {
  1264. Output::Trace(Js::RunPhase, _u("%p> EnterScriptStart(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel);
  1265. Output::Flush();
  1266. }
  1267. #endif
  1268. return oldCallRootLevel;
  1269. }
  1270. void
  1271. ThreadContext::EnterScriptEnd(Js::ScriptEntryExitRecord * record, bool doCleanup)
  1272. {
  1273. #if DBG_DUMP
  1274. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase))
  1275. {
  1276. Output::Trace(Js::RunPhase, _u("%p> EnterScriptEnd (%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel);
  1277. Output::Flush();
  1278. }
  1279. #endif
  1280. this->PopEntryExitRecord(record);
  1281. AssertMsg(this->IsScriptActive(),
  1282. "Missing EnterScriptStart or LeaveScriptEnd");
  1283. this->isScriptActive = false;
  1284. this->GetRecycler()->SetIsScriptActive(false);
  1285. this->callRootLevel--;
  1286. #ifdef EXCEPTION_CHECK
  1287. ExceptionCheck::SetHandledExceptionType(record->handledExceptionType);
  1288. #endif
  1289. #ifdef RECYCLER_MEMORY_VERIFY
  1290. recycler->Verify(Js::RunPhase);
  1291. #endif
  1292. if (this->callRootLevel == 0)
  1293. {
  1294. RECORD_TIMESTAMP(lastScriptEndTime);
  1295. this->GetRecycler()->SetIsInScript(false);
  1296. InterruptPoller *poller = this->interruptPoller;
  1297. if (poller)
  1298. {
  1299. poller->EndScript();
  1300. }
  1301. ClosePendingProjectionContexts();
  1302. ClosePendingScriptContexts();
  1303. Assert(rootPendingClose == nullptr);
  1304. if (this->hasThrownPendingException)
  1305. {
  1306. // We have some cases where the thread instant of JavascriptExceptionObject
  1307. // are ignored and not clear. To avoid leaks, clear it here when
  1308. // we are not in script, where no one should be using these JavascriptExceptionObject
  1309. this->ClearPendingOOMError();
  1310. this->ClearPendingSOError();
  1311. this->hasThrownPendingException = false;
  1312. }
  1313. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1314. if (Js::Configuration::Global.flags.FreeRejittedCode)
  1315. #endif
  1316. {
  1317. // Since we're no longer in script, old entry points can now be collected
  1318. Js::FunctionEntryPointInfo* current = this->recyclableData->oldEntryPointInfo;
  1319. this->recyclableData->oldEntryPointInfo = nullptr;
  1320. // Clear out the next pointers so older entry points wont be held on
  1321. // as a false positive
  1322. while (current != nullptr)
  1323. {
  1324. Js::FunctionEntryPointInfo* next = current->nextEntryPoint;
  1325. current->nextEntryPoint = nullptr;
  1326. current = next;
  1327. }
  1328. }
  1329. if (doCleanup)
  1330. {
  1331. ThreadServiceWrapper* threadServiceWrapper = GetThreadServiceWrapper();
  1332. if (!threadServiceWrapper || !threadServiceWrapper->ScheduleNextCollectOnExit())
  1333. {
  1334. // Do the idle GC now if we fail schedule one.
  1335. recycler->CollectNow<CollectOnScriptExit>();
  1336. }
  1337. recycler->LeaveIdleDecommit();
  1338. }
  1339. }
  1340. if (doCleanup)
  1341. {
  1342. PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in EnterScriptEnd: %d\n"), this->recycler->NeedDispose());
  1343. if (this->recycler->NeedDispose())
  1344. {
  1345. this->recycler->FinishDisposeObjectsNow<FinishDispose>();
  1346. }
  1347. }
  1348. JS_ETW_INTERNAL(EventWriteJSCRIPT_RUN_STOP(this,0));
  1349. }
  1350. void
  1351. ThreadContext::SetForceOneIdleCollection()
  1352. {
  1353. ThreadServiceWrapper* threadServiceWrapper = GetThreadServiceWrapper();
  1354. if (threadServiceWrapper)
  1355. {
  1356. threadServiceWrapper->SetForceOneIdleCollection();
  1357. }
  1358. }
  1359. BOOLEAN
  1360. ThreadContext::IsOnStack(void const *ptr)
  1361. {
  1362. #if defined(_M_IX86) && defined(_MSC_VER)
  1363. return ptr < (void*)__readfsdword(0x4) && ptr >= (void*)__readfsdword(0xE0C);
  1364. #elif defined(_M_AMD64) && defined(_MSC_VER)
  1365. return ptr < (void*)__readgsqword(0x8) && ptr >= (void*)__readgsqword(0x1478);
  1366. #elif defined(_M_ARM)
  1367. ULONG lowLimit, highLimit;
  1368. ::GetCurrentThreadStackLimits(&lowLimit, &highLimit);
  1369. bool isOnStack = (void*)lowLimit <= ptr && ptr < (void*)highLimit;
  1370. return isOnStack;
  1371. #elif defined(_M_ARM64)
  1372. ULONG64 lowLimit, highLimit;
  1373. ::GetCurrentThreadStackLimits(&lowLimit, &highLimit);
  1374. bool isOnStack = (void*)lowLimit <= ptr && ptr < (void*)highLimit;
  1375. return isOnStack;
  1376. #elif !defined(_MSC_VER)
  1377. return ::IsAddressOnStack((ULONG_PTR) ptr);
  1378. #else
  1379. AssertMsg(FALSE, "IsOnStack -- not implemented yet case");
  1380. Js::Throw::NotImplemented();
  1381. return false;
  1382. #endif
  1383. }
  1384. size_t
  1385. ThreadContext::GetStackLimitForCurrentThread() const
  1386. {
  1387. FAULTINJECT_SCRIPT_TERMINATION;
  1388. size_t limit = this->stackLimitForCurrentThread;
  1389. Assert(limit == Js::Constants::StackLimitForScriptInterrupt
  1390. || !this->GetStackProber()
  1391. || limit == this->GetStackProber()->GetScriptStackLimit());
  1392. return limit;
  1393. }
  1394. void
  1395. ThreadContext::SetStackLimitForCurrentThread(size_t limit)
  1396. {
  1397. this->stackLimitForCurrentThread = limit;
  1398. }
  1399. _NOINLINE //Win8 947081: might use wrong _AddressOfReturnAddress() if this and caller are inlined
  1400. bool
  1401. ThreadContext::IsStackAvailable(size_t size)
  1402. {
  1403. size_t sp = (size_t)_AddressOfReturnAddress();
  1404. size_t stackLimit = this->GetStackLimitForCurrentThread();
  1405. bool stackAvailable = (sp > size && (sp - size) > stackLimit);
  1406. // Verify that JIT'd frames didn't mess up the ABI stack alignment
  1407. Assert(((uintptr_t)sp & (AutoSystemInfo::StackAlign - 1)) == (sizeof(void*) & (AutoSystemInfo::StackAlign - 1)));
  1408. #if DBG
  1409. this->GetStackProber()->AdjustKnownStackLimit(sp, size);
  1410. #endif
  1411. FAULTINJECT_STACK_PROBE
  1412. if (stackAvailable)
  1413. {
  1414. return true;
  1415. }
  1416. if (sp <= stackLimit)
  1417. {
  1418. if (stackLimit == Js::Constants::StackLimitForScriptInterrupt)
  1419. {
  1420. if (sp <= this->GetStackProber()->GetScriptStackLimit())
  1421. {
  1422. // Take down the process if we cant recover from the stack overflow
  1423. Js::Throw::FatalInternalError();
  1424. }
  1425. }
  1426. }
  1427. return false;
  1428. }
  1429. _NOINLINE //Win8 947081: might use wrong _AddressOfReturnAddress() if this and caller are inlined
  1430. bool
  1431. ThreadContext::IsStackAvailableNoThrow(size_t size)
  1432. {
  1433. size_t sp = (size_t)_AddressOfReturnAddress();
  1434. size_t stackLimit = this->GetStackLimitForCurrentThread();
  1435. bool stackAvailable = (sp > stackLimit) && (sp > size) && ((sp - size) > stackLimit);
  1436. FAULTINJECT_STACK_PROBE
  1437. return stackAvailable;
  1438. }
  1439. /* static */ bool
  1440. ThreadContext::IsCurrentStackAvailable(size_t size)
  1441. {
  1442. ThreadContext *currentContext = GetContextForCurrentThread();
  1443. Assert(currentContext);
  1444. return currentContext->IsStackAvailable(size);
  1445. }
  1446. /*
  1447. returnAddress will be passed in the stackprobe call at the beginning of interpreter frame.
  1448. We need to probe the stack before we link up the InterpreterFrame structure in threadcontext,
  1449. and if we throw there, the stack walker might get confused when trying to identify a frame
  1450. is interpreter frame by comparing the current ebp in ebp chain with return address specified
  1451. in the last InterpreterFrame linked in threadcontext. We need to pass in the return address
  1452. of the probing frame to skip the right one (we need to skip first match in a->a->a recursion,
  1453. but not in a->b->a recursion).
  1454. */
  1455. void
  1456. ThreadContext::ProbeStackNoDispose(size_t size, Js::ScriptContext *scriptContext, PVOID returnAddress)
  1457. {
  1458. AssertCanHandleStackOverflow();
  1459. if (!this->IsStackAvailable(size))
  1460. {
  1461. if (this->IsExecutionDisabled())
  1462. {
  1463. // The probe failed because we hammered the stack limit to trigger script interrupt.
  1464. Assert(this->DoInterruptProbe());
  1465. throw Js::ScriptAbortException();
  1466. }
  1467. Js::Throw::StackOverflow(scriptContext, returnAddress);
  1468. }
  1469. #if defined(NTBUILD) || defined(__IOS__) || defined(__ANDROID__)
  1470. // Use every Nth stack probe as a QC trigger.
  1471. if (AutoSystemInfo::ShouldQCMoreFrequently() && this->HasInterruptPoller() && this->IsScriptActive())
  1472. {
  1473. ++(this->stackProbeCount);
  1474. if (this->stackProbeCount > ThreadContext::StackProbePollThreshold)
  1475. {
  1476. this->stackProbeCount = 0;
  1477. this->CheckInterruptPoll();
  1478. }
  1479. }
  1480. #endif
  1481. }
  1482. void
  1483. ThreadContext::ProbeStack(size_t size, Js::ScriptContext *scriptContext, PVOID returnAddress)
  1484. {
  1485. this->ProbeStackNoDispose(size, scriptContext, returnAddress);
  1486. // BACKGROUND-GC TODO: If we're stuck purely in JITted code, we should have the
  1487. // background GC thread modify the threads stack limit to trigger the runtime stack probe
  1488. if (this->callDispose && this->recycler->NeedDispose())
  1489. {
  1490. PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in ProbeStack: %d\n"), this->recycler->NeedDispose());
  1491. this->recycler->FinishDisposeObjectsNow<FinishDisposeTimed>();
  1492. }
  1493. }
  1494. void
  1495. ThreadContext::ProbeStack(size_t size, Js::RecyclableObject * obj, Js::ScriptContext *scriptContext)
  1496. {
  1497. AssertCanHandleStackOverflowCall(obj->IsExternal() ||
  1498. (Js::JavascriptOperators::GetTypeId(obj) == Js::TypeIds_Function &&
  1499. Js::JavascriptFunction::FromVar(obj)->IsExternalFunction()));
  1500. if (!this->IsStackAvailable(size))
  1501. {
  1502. if (this->IsExecutionDisabled())
  1503. {
  1504. // The probe failed because we hammered the stack limit to trigger script interrupt.
  1505. Assert(this->DoInterruptProbe());
  1506. throw Js::ScriptAbortException();
  1507. }
  1508. if (obj->IsExternal() ||
  1509. (Js::JavascriptOperators::GetTypeId(obj) == Js::TypeIds_Function &&
  1510. Js::JavascriptFunction::FromVar(obj)->IsExternalFunction()))
  1511. {
  1512. Js::JavascriptError::ThrowStackOverflowError(scriptContext);
  1513. }
  1514. Js::Throw::StackOverflow(scriptContext, NULL);
  1515. }
  1516. }
  1517. void
  1518. ThreadContext::ProbeStack(size_t size)
  1519. {
  1520. Assert(this->IsScriptActive());
  1521. Js::ScriptEntryExitRecord *entryExitRecord = this->GetScriptEntryExit();
  1522. Assert(entryExitRecord);
  1523. Js::ScriptContext *scriptContext = entryExitRecord->scriptContext;
  1524. Assert(scriptContext);
  1525. this->ProbeStack(size, scriptContext);
  1526. }
  1527. /* static */ void
  1528. ThreadContext::ProbeCurrentStack(size_t size, Js::ScriptContext *scriptContext)
  1529. {
  1530. Assert(scriptContext != nullptr);
  1531. Assert(scriptContext->GetThreadContext() == GetContextForCurrentThread());
  1532. scriptContext->GetThreadContext()->ProbeStack(size, scriptContext);
  1533. }
  1534. /* static */ void
  1535. ThreadContext::ProbeCurrentStackNoDispose(size_t size, Js::ScriptContext *scriptContext)
  1536. {
  1537. Assert(scriptContext != nullptr);
  1538. Assert(scriptContext->GetThreadContext() == GetContextForCurrentThread());
  1539. scriptContext->GetThreadContext()->ProbeStackNoDispose(size, scriptContext);
  1540. }
  1541. template <bool leaveForHost>
  1542. void
  1543. ThreadContext::LeaveScriptStart(void * frameAddress)
  1544. {
  1545. Assert(this->IsScriptActive());
  1546. #if DBG_DUMP
  1547. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase))
  1548. {
  1549. Output::Trace(Js::RunPhase, _u("%p> LeaveScriptStart(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel);
  1550. Output::Flush();
  1551. }
  1552. #endif
  1553. Js::ScriptEntryExitRecord * entryExitRecord = this->GetScriptEntryExit();
  1554. AssertMsg(entryExitRecord && entryExitRecord->frameIdOfScriptExitFunction == nullptr,
  1555. "Missing LeaveScriptEnd or EnterScriptStart");
  1556. entryExitRecord->frameIdOfScriptExitFunction = frameAddress;
  1557. this->isScriptActive = false;
  1558. this->GetRecycler()->SetIsScriptActive(false);
  1559. AssertMsg(!(leaveForHost && this->IsDisableImplicitCall()),
  1560. "Disable implicit call should have been caught before leaving script for host");
  1561. // Save the implicit call flags
  1562. entryExitRecord->savedImplicitCallFlags = this->GetImplicitCallFlags();
  1563. // clear the hasReentered to detect if we have reentered into script
  1564. entryExitRecord->hasReentered = false;
  1565. #if DBG || defined(PROFILE_EXEC)
  1566. entryExitRecord->leaveForHost = leaveForHost;
  1567. #endif
  1568. #if DBG
  1569. entryExitRecord->leaveForAsyncHostOperation = false;
  1570. #endif
  1571. #ifdef PROFILE_EXEC
  1572. if (leaveForHost)
  1573. {
  1574. entryExitRecord->scriptContext->ProfileEnd(Js::RunPhase);
  1575. }
  1576. #endif
  1577. }
  1578. void ThreadContext::DisposeOnLeaveScript()
  1579. {
  1580. PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in LeaveScriptStart: %d\n"), this->recycler->NeedDispose());
  1581. if (this->callDispose && this->recycler->NeedDispose())
  1582. {
  1583. this->recycler->FinishDisposeObjectsNow<FinishDispose>();
  1584. }
  1585. }
  1586. template <bool leaveForHost>
  1587. void
  1588. ThreadContext::LeaveScriptEnd(void * frameAddress)
  1589. {
  1590. Assert(!this->IsScriptActive());
  1591. #if DBG_DUMP
  1592. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase))
  1593. {
  1594. Output::Trace(Js::RunPhase, _u("%p> LeaveScriptEnd(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel);
  1595. Output::Flush();
  1596. }
  1597. #endif
  1598. Js::ScriptEntryExitRecord * entryExitRecord = this->GetScriptEntryExit();
  1599. AssertMsg(entryExitRecord && entryExitRecord->frameIdOfScriptExitFunction,
  1600. "LeaveScriptEnd without LeaveScriptStart");
  1601. AssertMsg(frameAddress == nullptr || frameAddress == entryExitRecord->frameIdOfScriptExitFunction,
  1602. "Mismatched script exit frames");
  1603. Assert(!!entryExitRecord->leaveForHost == leaveForHost);
  1604. entryExitRecord->frameIdOfScriptExitFunction = nullptr;
  1605. AssertMsg(!this->IsScriptActive(), "Missing LeaveScriptStart or LeaveScriptStart");
  1606. this->isScriptActive = true;
  1607. this->GetRecycler()->SetIsScriptActive(true);
  1608. Js::ImplicitCallFlags savedImplicitCallFlags = entryExitRecord->savedImplicitCallFlags;
  1609. if (leaveForHost)
  1610. {
  1611. savedImplicitCallFlags = (Js::ImplicitCallFlags)(savedImplicitCallFlags | Js::ImplicitCall_External);
  1612. }
  1613. else if (entryExitRecord->hasReentered)
  1614. {
  1615. savedImplicitCallFlags = (Js::ImplicitCallFlags)(savedImplicitCallFlags | Js::ImplicitCall_AsyncHostOperation);
  1616. }
  1617. // Restore the implicit call flags
  1618. this->SetImplicitCallFlags(savedImplicitCallFlags);
  1619. #ifdef PROFILE_EXEC
  1620. if (leaveForHost)
  1621. {
  1622. entryExitRecord->scriptContext->ProfileBegin(Js::RunPhase);
  1623. }
  1624. #endif
  1625. }
  1626. // explicit instantiations
  1627. template void ThreadContext::LeaveScriptStart<true>(void * frameAddress);
  1628. template void ThreadContext::LeaveScriptStart<false>(void * frameAddress);
  1629. template void ThreadContext::LeaveScriptEnd<true>(void * frameAddress);
  1630. template void ThreadContext::LeaveScriptEnd<false>(void * frameAddress);
  1631. void
  1632. ThreadContext::PushInterpreterFrame(Js::InterpreterStackFrame *interpreterFrame)
  1633. {
  1634. interpreterFrame->SetPreviousFrame(this->leafInterpreterFrame);
  1635. this->leafInterpreterFrame = interpreterFrame;
  1636. }
  1637. Js::InterpreterStackFrame *
  1638. ThreadContext::PopInterpreterFrame()
  1639. {
  1640. Js::InterpreterStackFrame *interpreterFrame = this->leafInterpreterFrame;
  1641. Assert(interpreterFrame);
  1642. this->leafInterpreterFrame = interpreterFrame->GetPreviousFrame();
  1643. return interpreterFrame;
  1644. }
  1645. BOOL
  1646. ThreadContext::ExecuteRecyclerCollectionFunctionCommon(Recycler * recycler, CollectionFunction function, CollectionFlags flags)
  1647. {
  1648. return __super::ExecuteRecyclerCollectionFunction(recycler, function, flags);
  1649. }
  1650. #if DBG
  1651. bool
  1652. ThreadContext::IsInAsyncHostOperation() const
  1653. {
  1654. if (!this->IsScriptActive())
  1655. {
  1656. Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord;
  1657. if (lastRecord != NULL)
  1658. {
  1659. return !!lastRecord->leaveForAsyncHostOperation;
  1660. }
  1661. }
  1662. return false;
  1663. }
  1664. #endif
  1665. #if ENABLE_NATIVE_CODEGEN
  1666. void
  1667. ThreadContext::SetJITConnectionInfo(HANDLE processHandle, void* serverSecurityDescriptor, UUID connectionId)
  1668. {
  1669. Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
  1670. if (!JITManager::GetJITManager()->IsConnected())
  1671. {
  1672. // TODO: return HRESULT
  1673. JITManager::GetJITManager()->ConnectRpcServer(processHandle, serverSecurityDescriptor, connectionId);
  1674. }
  1675. }
  1676. bool
  1677. ThreadContext::EnsureJITThreadContext(bool allowPrereserveAlloc)
  1678. {
  1679. #if ENABLE_OOP_NATIVE_CODEGEN
  1680. Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
  1681. if (!JITManager::GetJITManager()->IsConnected())
  1682. {
  1683. return false;
  1684. }
  1685. if (m_remoteThreadContextInfo)
  1686. {
  1687. return true;
  1688. }
  1689. #ifdef USE_RPC_HANDLE_MARSHALLING
  1690. HANDLE processHandle;
  1691. if (!DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &processHandle, 0, false, DUPLICATE_SAME_ACCESS))
  1692. {
  1693. return false;
  1694. }
  1695. AutoCloseHandle autoClose(processHandle);
  1696. #endif
  1697. ThreadContextDataIDL contextData;
  1698. contextData.chakraBaseAddress = (intptr_t)AutoSystemInfo::Data.GetChakraBaseAddr();
  1699. contextData.crtBaseAddress = (intptr_t)AutoSystemInfo::GetCRTHandle();
  1700. contextData.threadStackLimitAddr = reinterpret_cast<intptr_t>(GetAddressOfStackLimitForCurrentThread());
  1701. contextData.bailOutRegisterSaveSpaceAddr = (intptr_t)bailOutRegisterSaveSpace;
  1702. contextData.disableImplicitFlagsAddr = (intptr_t)GetAddressOfDisableImplicitFlags();
  1703. contextData.implicitCallFlagsAddr = (intptr_t)GetAddressOfImplicitCallFlags();
  1704. contextData.scriptStackLimit = GetScriptStackLimit();
  1705. contextData.isThreadBound = IsThreadBound();
  1706. contextData.allowPrereserveAlloc = allowPrereserveAlloc;
  1707. #if defined(ENABLE_SIMDJS) && (_M_IX86 || _M_AMD64)
  1708. contextData.simdTempAreaBaseAddr = (intptr_t)GetSimdTempArea();
  1709. #endif
  1710. m_jitNumericProperties = HeapNew(BVSparse<HeapAllocator>, &HeapAllocator::Instance);
  1711. for (auto iter = propertyMap->GetIterator(); iter.IsValid(); iter.MoveNext())
  1712. {
  1713. if (iter.CurrentKey()->IsNumeric())
  1714. {
  1715. m_jitNumericProperties->Set(iter.CurrentKey()->GetPropertyId());
  1716. m_jitNeedsPropertyUpdate = true;
  1717. }
  1718. }
  1719. HRESULT hr = JITManager::GetJITManager()->InitializeThreadContext(
  1720. &contextData,
  1721. #ifdef USE_RPC_HANDLE_MARSHALLING
  1722. processHandle,
  1723. #endif
  1724. &m_remoteThreadContextInfo,
  1725. &m_prereservedRegionAddr,
  1726. &m_jitThunkStartAddr);
  1727. JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate);
  1728. return m_remoteThreadContextInfo != nullptr;
  1729. #endif
  1730. }
  1731. #endif
  1732. #if ENABLE_TTD
  1733. void ThreadContext::InitTimeTravel(ThreadContext* threadContext, void* runtimeHandle, uint32 snapInterval, uint32 snapHistoryLength)
  1734. {
  1735. TTDAssert(!this->IsRuntimeInTTDMode(), "We should only init once.");
  1736. this->TTDContext = HeapNew(TTD::ThreadContextTTD, this, runtimeHandle, snapInterval, snapHistoryLength);
  1737. this->TTDLog = HeapNew(TTD::EventLog, this);
  1738. }
  1739. void ThreadContext::InitHostFunctionsAndTTData(bool record, bool replay, bool debug, size_t optTTUriLength, const char* optTTUri,
  1740. TTD::TTDOpenResourceStreamCallback openResourceStreamfp, TTD::TTDReadBytesFromStreamCallback readBytesFromStreamfp,
  1741. TTD::TTDWriteBytesToStreamCallback writeBytesToStreamfp, TTD::TTDFlushAndCloseStreamCallback flushAndCloseStreamfp,
  1742. TTD::TTDCreateExternalObjectCallback createExternalObjectfp,
  1743. TTD::TTDCreateJsRTContextCallback createJsRTContextCallbackfp, TTD::TTDReleaseJsRTContextCallback releaseJsRTContextCallbackfp, TTD::TTDSetActiveJsRTContext setActiveJsRTContextfp)
  1744. {
  1745. AssertMsg(this->IsRuntimeInTTDMode(), "Need to call init first.");
  1746. this->TTDContext->TTDataIOInfo = { openResourceStreamfp, readBytesFromStreamfp, writeBytesToStreamfp, flushAndCloseStreamfp, 0, nullptr };
  1747. this->TTDContext->TTDExternalObjectFunctions = { createExternalObjectfp, createJsRTContextCallbackfp, releaseJsRTContextCallbackfp, setActiveJsRTContextfp };
  1748. if(record)
  1749. {
  1750. TTDAssert(optTTUri == nullptr, "No URI is needed in record mode (the host explicitly provides it when writing.");
  1751. this->TTDLog->InitForTTDRecord();
  1752. }
  1753. else
  1754. {
  1755. TTDAssert(optTTUri != nullptr, "We need a URI in replay mode so we can initialize the log from it");
  1756. this->TTDLog->InitForTTDReplay(this->TTDContext->TTDataIOInfo, optTTUri, optTTUriLength, debug);
  1757. this->sourceInfoCount = this->TTDLog->GetSourceInfoCount();
  1758. }
  1759. #if !ENABLE_TTD_DIAGNOSTICS_TRACING
  1760. if(debug)
  1761. {
  1762. #endif
  1763. this->TTDExecutionInfo = HeapNew(TTD::ExecutionInfoManager);
  1764. #if !ENABLE_TTD_DIAGNOSTICS_TRACING
  1765. }
  1766. #endif
  1767. }
  1768. #endif
  1769. BOOL
  1770. ThreadContext::ExecuteRecyclerCollectionFunction(Recycler * recycler, CollectionFunction function, CollectionFlags flags)
  1771. {
  1772. // If the thread context doesn't have an associated Recycler set, don't do anything
  1773. if (this->recycler == nullptr)
  1774. {
  1775. return FALSE;
  1776. }
  1777. // Take etw rundown lock on this thread context. We can't collect entryPoints if we are in etw rundown.
  1778. AutoCriticalSection autocs(this->GetFunctionBodyLock());
  1779. // Disable calling dispose from leave script or the stack probe
  1780. // while we're executing the recycler wrapper
  1781. AutoRestoreValue<bool> callDispose(&this->callDispose, false);
  1782. BOOL ret = FALSE;
  1783. #if ENABLE_TTD
  1784. //
  1785. //TODO: We lose any events that happen in the callbacks (such as JsRelease) which may be a problem in the future.
  1786. // It may be possible to defer the collection of these objects to an explicit collection at the yield loop (same for weak set/map).
  1787. // We already indirectly do this for ScriptContext collection (but that is buggy so needs to be fixed too).
  1788. //
  1789. if(this->IsRuntimeInTTDMode())
  1790. {
  1791. this->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionTTAction);
  1792. }
  1793. #endif
  1794. if (!this->IsScriptActive())
  1795. {
  1796. Assert(!this->IsDisableImplicitCall() || this->IsInAsyncHostOperation());
  1797. ret = this->ExecuteRecyclerCollectionFunctionCommon(recycler, function, flags);
  1798. // Make sure that we finish a collect that is activated outside of script, since
  1799. // we won't have exit script to schedule it
  1800. if (!this->IsInScript() && recycler->CollectionInProgress()
  1801. && ((flags & CollectOverride_DisableIdleFinish) == 0) && threadServiceWrapper)
  1802. {
  1803. threadServiceWrapper->ScheduleFinishConcurrent();
  1804. }
  1805. }
  1806. else
  1807. {
  1808. void * frameAddr = nullptr;
  1809. GET_CURRENT_FRAME_ID(frameAddr);
  1810. // We may need stack to call out from Dispose or QC
  1811. if (!this->IsDisableImplicitCall()) // otherwise Dispose/QC disabled
  1812. {
  1813. // If we don't have stack space to call out from Dispose or QC,
  1814. // don't throw, simply return false. This gives SnailAlloc a better
  1815. // chance of allocating in low stack-space situations (like allocating
  1816. // a StackOverflowException object)
  1817. if (!this->IsStackAvailableNoThrow(Js::Constants::MinStackCallout))
  1818. {
  1819. return false;
  1820. }
  1821. }
  1822. this->LeaveScriptStart<false>(frameAddr);
  1823. ret = this->ExecuteRecyclerCollectionFunctionCommon(recycler, function, flags);
  1824. this->LeaveScriptEnd<false>(frameAddr);
  1825. if (this->callRootLevel != 0)
  1826. {
  1827. this->CheckScriptInterrupt();
  1828. }
  1829. }
  1830. #if ENABLE_TTD
  1831. if(this->IsRuntimeInTTDMode())
  1832. {
  1833. this->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionTTAction);
  1834. }
  1835. #endif
  1836. return ret;
  1837. }
  1838. void
  1839. ThreadContext::DisposeObjects(Recycler * recycler)
  1840. {
  1841. if (this->IsDisableImplicitCall())
  1842. {
  1843. // Don't dispose objects when implicit calls are disabled, since disposing may cause implicit calls. Objects will remain
  1844. // in the dispose queue and will be disposed later when implicit calls are not disabled.
  1845. return;
  1846. }
  1847. // We shouldn't DisposeObjects in NoScriptScope as this might lead to script execution.
  1848. // Callers of DisposeObjects should ensure !IsNoScriptScope() before calling DisposeObjects.
  1849. if (this->IsNoScriptScope())
  1850. {
  1851. FromDOM_NoScriptScope_fatal_error();
  1852. }
  1853. if (!this->IsScriptActive())
  1854. {
  1855. __super::DisposeObjects(recycler);
  1856. }
  1857. else
  1858. {
  1859. void * frameAddr = nullptr;
  1860. GET_CURRENT_FRAME_ID(frameAddr);
  1861. // We may need stack to call out from Dispose
  1862. this->ProbeStack(Js::Constants::MinStackCallout);
  1863. this->LeaveScriptStart<false>(frameAddr);
  1864. __super::DisposeObjects(recycler);
  1865. this->LeaveScriptEnd<false>(frameAddr);
  1866. }
  1867. }
  1868. void
  1869. ThreadContext::PushEntryExitRecord(Js::ScriptEntryExitRecord * record)
  1870. {
  1871. AssertMsg(record, "Didn't provide a script entry record to push");
  1872. Assert(record->next == nullptr);
  1873. Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord;
  1874. if (lastRecord != nullptr)
  1875. {
  1876. // If we enter script again, we should have leave with leaveForHost or leave for dispose.
  1877. Assert(lastRecord->leaveForHost || lastRecord->leaveForAsyncHostOperation);
  1878. lastRecord->hasReentered = true;
  1879. record->next = lastRecord;
  1880. // these are on stack, which grows down. if this condition doesn't hold, then the list somehow got messed up
  1881. if (!IsOnStack(lastRecord) || (uintptr_t)record >= (uintptr_t)lastRecord)
  1882. {
  1883. EntryExitRecord_Corrupted_fatal_error();
  1884. }
  1885. }
  1886. this->entryExitRecord = record;
  1887. }
  1888. void ThreadContext::PopEntryExitRecord(Js::ScriptEntryExitRecord * record)
  1889. {
  1890. AssertMsg(record && record == this->entryExitRecord, "Mismatch script entry/exit");
  1891. // these are on stack, which grows down. if this condition doesn't hold, then the list somehow got messed up
  1892. Js::ScriptEntryExitRecord * next = this->entryExitRecord->next;
  1893. if (next && (!IsOnStack(next) || (uintptr_t)this->entryExitRecord >= (uintptr_t)next))
  1894. {
  1895. EntryExitRecord_Corrupted_fatal_error();
  1896. }
  1897. this->entryExitRecord = next;
  1898. }
  1899. BOOL ThreadContext::ReserveStaticTypeIds(__in int first, __in int last)
  1900. {
  1901. if ( nextTypeId <= first )
  1902. {
  1903. nextTypeId = (Js::TypeId) last;
  1904. return TRUE;
  1905. }
  1906. else
  1907. {
  1908. return FALSE;
  1909. }
  1910. }
  1911. Js::TypeId ThreadContext::ReserveTypeIds(int count)
  1912. {
  1913. Js::TypeId firstTypeId = nextTypeId;
  1914. nextTypeId = (Js::TypeId)(nextTypeId + count);
  1915. return firstTypeId;
  1916. }
  1917. Js::TypeId ThreadContext::CreateTypeId()
  1918. {
  1919. return nextTypeId = (Js::TypeId)(nextTypeId + 1);
  1920. }
  1921. void ThreadContext::SetWellKnownHostTypeId(WellKnownHostType wellKnownType, Js::TypeId typeId)
  1922. {
  1923. AssertMsg(wellKnownType <= WellKnownHostType_Last, "ThreadContext::SetWellKnownHostTypeId called on unknown type");
  1924. if (wellKnownType >= 0 && wellKnownType <= WellKnownHostType_Last)
  1925. {
  1926. this->wellKnownHostTypeIds[wellKnownType] = typeId;
  1927. #if ENABLE_NATIVE_CODEGEN
  1928. // The jit server really only needs to know about WellKnownHostType_HTMLAllCollection
  1929. if (this->m_remoteThreadContextInfo && wellKnownType == WellKnownHostType_HTMLAllCollection)
  1930. {
  1931. HRESULT hr = JITManager::GetJITManager()->SetWellKnownHostTypeId(this->m_remoteThreadContextInfo, (int)typeId);
  1932. JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate);
  1933. }
  1934. #endif
  1935. }
  1936. }
  1937. void ThreadContext::EnsureDebugManager()
  1938. {
  1939. if (this->debugManager == nullptr)
  1940. {
  1941. this->debugManager = HeapNew(Js::DebugManager, this, this->GetAllocationPolicyManager());
  1942. }
  1943. InterlockedIncrement(&crefSContextForDiag);
  1944. Assert(this->debugManager != nullptr);
  1945. }
  1946. void ThreadContext::ReleaseDebugManager()
  1947. {
  1948. Assert(crefSContextForDiag > 0);
  1949. Assert(this->debugManager != nullptr);
  1950. LONG lref = InterlockedDecrement(&crefSContextForDiag);
  1951. if (lref == 0)
  1952. {
  1953. if (this->recyclableData != nullptr)
  1954. {
  1955. this->recyclableData->returnedValueList = nullptr;
  1956. }
  1957. if (this->debugManager != nullptr)
  1958. {
  1959. this->debugManager->Close();
  1960. HeapDelete(this->debugManager);
  1961. this->debugManager = nullptr;
  1962. }
  1963. }
  1964. }
  1965. Js::TempArenaAllocatorObject *
  1966. ThreadContext::GetTemporaryAllocator(LPCWSTR name)
  1967. {
  1968. AssertCanHandleOutOfMemory();
  1969. if (temporaryArenaAllocatorCount != 0)
  1970. {
  1971. temporaryArenaAllocatorCount--;
  1972. Js::TempArenaAllocatorObject * allocator = recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount];
  1973. recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount] = nullptr;
  1974. return allocator;
  1975. }
  1976. return Js::TempArenaAllocatorObject::Create(this);
  1977. }
  1978. void
  1979. ThreadContext::ReleaseTemporaryAllocator(Js::TempArenaAllocatorObject * tempAllocator)
  1980. {
  1981. if (temporaryArenaAllocatorCount < MaxTemporaryArenaAllocators)
  1982. {
  1983. tempAllocator->GetAllocator()->Reset();
  1984. recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount] = tempAllocator;
  1985. temporaryArenaAllocatorCount++;
  1986. return;
  1987. }
  1988. tempAllocator->Dispose(false);
  1989. }
  1990. Js::TempGuestArenaAllocatorObject *
  1991. ThreadContext::GetTemporaryGuestAllocator(LPCWSTR name)
  1992. {
  1993. AssertCanHandleOutOfMemory();
  1994. if (temporaryGuestArenaAllocatorCount != 0)
  1995. {
  1996. temporaryGuestArenaAllocatorCount--;
  1997. Js::TempGuestArenaAllocatorObject * allocator = recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount];
  1998. allocator->AdviseInUse();
  1999. recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount] = nullptr;
  2000. return allocator;
  2001. }
  2002. return Js::TempGuestArenaAllocatorObject::Create(this);
  2003. }
  2004. void
  2005. ThreadContext::ReleaseTemporaryGuestAllocator(Js::TempGuestArenaAllocatorObject * tempGuestAllocator)
  2006. {
  2007. if (temporaryGuestArenaAllocatorCount < MaxTemporaryArenaAllocators)
  2008. {
  2009. tempGuestAllocator->AdviseNotInUse();
  2010. recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount] = tempGuestAllocator;
  2011. temporaryGuestArenaAllocatorCount++;
  2012. return;
  2013. }
  2014. tempGuestAllocator->Dispose(false);
  2015. }
  2016. void
  2017. ThreadContext::AddToPendingScriptContextCloseList(Js::ScriptContext * scriptContext)
  2018. {
  2019. Assert(scriptContext != nullptr);
  2020. if (rootPendingClose == nullptr)
  2021. {
  2022. rootPendingClose = scriptContext;
  2023. return;
  2024. }
  2025. // Prepend to the list.
  2026. scriptContext->SetNextPendingClose(rootPendingClose);
  2027. rootPendingClose = scriptContext;
  2028. }
  2029. void
  2030. ThreadContext::RemoveFromPendingClose(Js::ScriptContext * scriptContext)
  2031. {
  2032. Assert(scriptContext != nullptr);
  2033. if (rootPendingClose == nullptr)
  2034. {
  2035. // We already sent a close message, ignore the notification.
  2036. return;
  2037. }
  2038. // Base case: The root is being removed. Move the root along.
  2039. if (scriptContext == rootPendingClose)
  2040. {
  2041. rootPendingClose = rootPendingClose->GetNextPendingClose();
  2042. return;
  2043. }
  2044. Js::ScriptContext * currScriptContext = rootPendingClose;
  2045. Js::ScriptContext * nextScriptContext = nullptr;
  2046. while (currScriptContext)
  2047. {
  2048. nextScriptContext = currScriptContext->GetNextPendingClose();
  2049. if (!nextScriptContext)
  2050. {
  2051. break;
  2052. }
  2053. if (nextScriptContext == scriptContext) {
  2054. // The next pending close ScriptContext is the one to be removed - set prev->next to next->next
  2055. currScriptContext->SetNextPendingClose(nextScriptContext->GetNextPendingClose());
  2056. return;
  2057. }
  2058. currScriptContext = nextScriptContext;
  2059. }
  2060. // We expect to find scriptContext in the pending close list.
  2061. Assert(false);
  2062. }
  2063. void ThreadContext::ClosePendingScriptContexts()
  2064. {
  2065. Js::ScriptContext * scriptContext = rootPendingClose;
  2066. if (scriptContext == nullptr)
  2067. {
  2068. return;
  2069. }
  2070. Js::ScriptContext * nextScriptContext;
  2071. do
  2072. {
  2073. nextScriptContext = scriptContext->GetNextPendingClose();
  2074. scriptContext->Close(false);
  2075. scriptContext = nextScriptContext;
  2076. }
  2077. while (scriptContext);
  2078. rootPendingClose = nullptr;
  2079. }
  2080. void
  2081. ThreadContext::AddToPendingProjectionContextCloseList(IProjectionContext *projectionContext)
  2082. {
  2083. pendingProjectionContextCloseList->Add(projectionContext);
  2084. }
  2085. void
  2086. ThreadContext::RemoveFromPendingClose(IProjectionContext* projectionContext)
  2087. {
  2088. pendingProjectionContextCloseList->Remove(projectionContext);
  2089. }
  2090. void ThreadContext::ClosePendingProjectionContexts()
  2091. {
  2092. IProjectionContext* projectionContext;
  2093. for (int i = 0 ; i < pendingProjectionContextCloseList->Count(); i++)
  2094. {
  2095. projectionContext = pendingProjectionContextCloseList->Item(i);
  2096. projectionContext->Close();
  2097. }
  2098. pendingProjectionContextCloseList->Clear();
  2099. }
  2100. void
  2101. ThreadContext::RegisterScriptContext(Js::ScriptContext *scriptContext)
  2102. {
  2103. // NOTE: ETW rundown thread may be reading the scriptContextList concurrently. We don't need to
  2104. // lock access because we only insert to the front here.
  2105. scriptContext->next = this->scriptContextList;
  2106. if (this->scriptContextList)
  2107. {
  2108. Assert(this->scriptContextList->prev == NULL);
  2109. this->scriptContextList->prev = scriptContext;
  2110. }
  2111. scriptContext->prev = NULL;
  2112. this->scriptContextList = scriptContext;
  2113. if(NoJIT())
  2114. {
  2115. scriptContext->ForceNoNative();
  2116. }
  2117. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  2118. scriptContextCount++;
  2119. #endif
  2120. scriptContextEverRegistered = true;
  2121. }
  2122. void
  2123. ThreadContext::UnregisterScriptContext(Js::ScriptContext *scriptContext)
  2124. {
  2125. // NOTE: ETW rundown thread may be reading the scriptContextList concurrently. Since this function
  2126. // is only called by ~ScriptContext() which already synchronized to ETW rundown, we are safe here.
  2127. if (scriptContext == this->scriptContextList)
  2128. {
  2129. Assert(scriptContext->prev == NULL);
  2130. this->scriptContextList = scriptContext->next;
  2131. }
  2132. else
  2133. {
  2134. scriptContext->prev->next = scriptContext->next;
  2135. }
  2136. if (scriptContext->next)
  2137. {
  2138. scriptContext->next->prev = scriptContext->prev;
  2139. }
  2140. scriptContext->prev = nullptr;
  2141. scriptContext->next = nullptr;
  2142. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  2143. scriptContextCount--;
  2144. #endif
  2145. }
  2146. ThreadContext::CollectCallBack *
  2147. ThreadContext::AddRecyclerCollectCallBack(RecyclerCollectCallBackFunction callback, void * context)
  2148. {
  2149. AutoCriticalSection autocs(&csCollectionCallBack);
  2150. CollectCallBack * collectCallBack = this->collectCallBackList.PrependNode(&HeapAllocator::Instance);
  2151. collectCallBack->callback = callback;
  2152. collectCallBack->context = context;
  2153. this->hasCollectionCallBack = true;
  2154. return collectCallBack;
  2155. }
  2156. void
  2157. ThreadContext::RemoveRecyclerCollectCallBack(ThreadContext::CollectCallBack * collectCallBack)
  2158. {
  2159. AutoCriticalSection autocs(&csCollectionCallBack);
  2160. this->collectCallBackList.RemoveElement(&HeapAllocator::Instance, collectCallBack);
  2161. this->hasCollectionCallBack = !this->collectCallBackList.Empty();
  2162. }
  2163. void
  2164. ThreadContext::PreCollectionCallBack(CollectionFlags flags)
  2165. {
  2166. #ifdef PERF_COUNTERS
  2167. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: deferparse - # of func: %d # deferparsed: %d\n"), PerfCounter::CodeCounterSet::GetTotalFunctionCounter().GetValue(), PerfCounter::CodeCounterSet::GetDeferredFunctionCounter().GetValue());
  2168. #endif
  2169. // This needs to be done before ClearInlineCaches since that method can empty the list of
  2170. // script contexts with inline caches
  2171. this->ClearScriptContextCaches();
  2172. // Clear up references to types to avoid keep them alive
  2173. this->ClearPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesCaches();
  2174. // Clean up unused memory before we start collecting
  2175. this->CleanNoCasePropertyMap();
  2176. this->TryEnterExpirableCollectMode();
  2177. const BOOL concurrent = flags & CollectMode_Concurrent;
  2178. const BOOL partial = flags & CollectMode_Partial;
  2179. if (!partial)
  2180. {
  2181. // Integrate allocated pages from background JIT threads
  2182. #if ENABLE_NATIVE_CODEGEN
  2183. #if !FLOATVAR
  2184. if (codeGenNumberThreadAllocator)
  2185. {
  2186. codeGenNumberThreadAllocator->Integrate();
  2187. }
  2188. if (this->xProcNumberPageSegmentManager)
  2189. {
  2190. this->xProcNumberPageSegmentManager->Integrate();
  2191. }
  2192. #endif
  2193. #endif
  2194. }
  2195. RecyclerCollectCallBackFlags callBackFlags = (RecyclerCollectCallBackFlags)
  2196. ((concurrent ? Collect_Begin_Concurrent : Collect_Begin) | (partial? Collect_Begin_Partial : Collect_Begin));
  2197. CollectionCallBack(callBackFlags);
  2198. }
  2199. void
  2200. ThreadContext::PreSweepCallback()
  2201. {
  2202. #ifdef PERSISTENT_INLINE_CACHES
  2203. ClearInlineCachesWithDeadWeakRefs();
  2204. #else
  2205. ClearInlineCaches();
  2206. #endif
  2207. ClearIsInstInlineCaches();
  2208. ClearEquivalentTypeCaches();
  2209. ClearForInCaches();
  2210. this->dynamicObjectEnumeratorCacheMap.Clear();
  2211. }
  2212. void
  2213. ThreadContext::CollectionCallBack(RecyclerCollectCallBackFlags flags)
  2214. {
  2215. DListBase<CollectCallBack>::Iterator i(&this->collectCallBackList);
  2216. while (i.Next())
  2217. {
  2218. i.Data().callback(i.Data().context, flags);
  2219. }
  2220. }
  2221. void
  2222. ThreadContext::WaitCollectionCallBack()
  2223. {
  2224. // Avoid taking the lock if there are no call back
  2225. if (hasCollectionCallBack)
  2226. {
  2227. AutoCriticalSection autocs(&csCollectionCallBack);
  2228. CollectionCallBack(Collect_Wait);
  2229. }
  2230. }
  2231. void
  2232. ThreadContext::PostCollectionCallBack()
  2233. {
  2234. CollectionCallBack(Collect_End);
  2235. TryExitExpirableCollectMode();
  2236. // Recycler is null in the case where the ThreadContext is in the process of creating the recycler and
  2237. // we have a GC triggered (say because the -recyclerStress flag is passed in)
  2238. if (this->recycler != NULL)
  2239. {
  2240. if (this->recycler->InCacheCleanupCollection())
  2241. {
  2242. this->recycler->ClearCacheCleanupCollection();
  2243. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next)
  2244. {
  2245. scriptContext->CleanupWeakReferenceDictionaries();
  2246. }
  2247. }
  2248. }
  2249. }
  2250. void
  2251. ThreadContext::PostSweepRedeferralCallBack()
  2252. {
  2253. if (this->DoTryRedeferral())
  2254. {
  2255. HRESULT hr = S_OK;
  2256. BEGIN_TRANSLATE_OOM_TO_HRESULT
  2257. {
  2258. this->TryRedeferral();
  2259. }
  2260. END_TRANSLATE_OOM_TO_HRESULT(hr);
  2261. }
  2262. this->UpdateRedeferralState();
  2263. }
  2264. bool
  2265. ThreadContext::DoTryRedeferral() const
  2266. {
  2267. if (PHASE_FORCE1(Js::RedeferralPhase) || PHASE_STRESS1(Js::RedeferralPhase))
  2268. {
  2269. return true;
  2270. }
  2271. if (PHASE_OFF1(Js::RedeferralPhase))
  2272. {
  2273. return false;
  2274. }
  2275. switch (this->redeferralState)
  2276. {
  2277. case InitialRedeferralState:
  2278. return false;
  2279. case StartupRedeferralState:
  2280. return gcSinceCallCountsCollected >= StartupRedeferralInactiveThreshold;
  2281. case MainRedeferralState:
  2282. return gcSinceCallCountsCollected >= MainRedeferralInactiveThreshold;
  2283. default:
  2284. Assert(0);
  2285. return false;
  2286. };
  2287. }
  2288. bool
  2289. ThreadContext::DoRedeferFunctionBodies() const
  2290. {
  2291. #if ENABLE_TTD
  2292. if (this->IsRuntimeInTTDMode())
  2293. {
  2294. return false;
  2295. }
  2296. #endif
  2297. if (PHASE_FORCE1(Js::RedeferralPhase) || PHASE_STRESS1(Js::RedeferralPhase))
  2298. {
  2299. return true;
  2300. }
  2301. if (PHASE_OFF1(Js::RedeferralPhase))
  2302. {
  2303. return false;
  2304. }
  2305. switch (this->redeferralState)
  2306. {
  2307. case InitialRedeferralState:
  2308. return false;
  2309. case StartupRedeferralState:
  2310. return gcSinceLastRedeferral >= StartupRedeferralCheckInterval;
  2311. case MainRedeferralState:
  2312. return gcSinceLastRedeferral >= MainRedeferralCheckInterval;
  2313. default:
  2314. Assert(0);
  2315. return false;
  2316. };
  2317. }
  2318. uint
  2319. ThreadContext::GetRedeferralCollectionInterval() const
  2320. {
  2321. switch(this->redeferralState)
  2322. {
  2323. case InitialRedeferralState:
  2324. return InitialRedeferralDelay;
  2325. case StartupRedeferralState:
  2326. return StartupRedeferralCheckInterval;
  2327. case MainRedeferralState:
  2328. return MainRedeferralCheckInterval;
  2329. default:
  2330. Assert(0);
  2331. return (uint)-1;
  2332. }
  2333. }
  2334. uint
  2335. ThreadContext::GetRedeferralInactiveThreshold() const
  2336. {
  2337. switch(this->redeferralState)
  2338. {
  2339. case InitialRedeferralState:
  2340. return InitialRedeferralDelay;
  2341. case StartupRedeferralState:
  2342. return StartupRedeferralInactiveThreshold;
  2343. case MainRedeferralState:
  2344. return MainRedeferralInactiveThreshold;
  2345. default:
  2346. Assert(0);
  2347. return (uint)-1;
  2348. }
  2349. }
  2350. void
  2351. ThreadContext::TryRedeferral()
  2352. {
  2353. bool doRedefer = this->DoRedeferFunctionBodies();
  2354. // Collect the set of active functions.
  2355. ActiveFunctionSet *pActiveFuncs = nullptr;
  2356. if (doRedefer)
  2357. {
  2358. pActiveFuncs = Anew(this->GetThreadAlloc(), ActiveFunctionSet, this->GetThreadAlloc());
  2359. this->GetActiveFunctions(pActiveFuncs);
  2360. #if DBG
  2361. this->redeferredFunctions = 0;
  2362. this->recoveredBytes = 0;
  2363. #endif
  2364. }
  2365. uint inactiveThreshold = this->GetRedeferralInactiveThreshold();
  2366. Js::ScriptContext *scriptContext;
  2367. for (scriptContext = GetScriptContextList(); scriptContext; scriptContext = scriptContext->next)
  2368. {
  2369. if (scriptContext->IsClosed())
  2370. {
  2371. continue;
  2372. }
  2373. scriptContext->RedeferFunctionBodies(pActiveFuncs, inactiveThreshold);
  2374. }
  2375. if (pActiveFuncs)
  2376. {
  2377. Adelete(this->GetThreadAlloc(), pActiveFuncs);
  2378. #if DBG
  2379. if (PHASE_STATS1(Js::RedeferralPhase) && this->redeferredFunctions)
  2380. {
  2381. Output::Print(_u("Redeferred: %d, Bytes: 0x%x\n"), this->redeferredFunctions, this->recoveredBytes);
  2382. }
  2383. #endif
  2384. }
  2385. }
  2386. void
  2387. ThreadContext::GetActiveFunctions(ActiveFunctionSet * pActiveFuncs)
  2388. {
  2389. if (!this->IsInScript() || this->entryExitRecord == nullptr)
  2390. {
  2391. return;
  2392. }
  2393. Js::JavascriptStackWalker walker(GetScriptContextList(), TRUE, NULL, true);
  2394. Js::JavascriptFunction *function = nullptr;
  2395. while (walker.GetCallerWithoutInlinedFrames(&function))
  2396. {
  2397. if (function->GetFunctionInfo()->HasBody())
  2398. {
  2399. Js::FunctionBody *body = function->GetFunctionInfo()->GetFunctionBody();
  2400. body->UpdateActiveFunctionSet(pActiveFuncs, nullptr);
  2401. }
  2402. }
  2403. }
  2404. void
  2405. ThreadContext::UpdateRedeferralState()
  2406. {
  2407. uint inactiveThreshold = this->GetRedeferralInactiveThreshold();
  2408. uint collectInterval = this->GetRedeferralCollectionInterval();
  2409. if (this->gcSinceCallCountsCollected >= inactiveThreshold)
  2410. {
  2411. this->gcSinceCallCountsCollected = 0;
  2412. if (this->gcSinceLastRedeferral >= collectInterval)
  2413. {
  2414. // Advance state
  2415. switch (this->redeferralState)
  2416. {
  2417. case InitialRedeferralState:
  2418. this->redeferralState = StartupRedeferralState;
  2419. break;
  2420. case StartupRedeferralState:
  2421. this->redeferralState = MainRedeferralState;
  2422. break;
  2423. case MainRedeferralState:
  2424. break;
  2425. default:
  2426. Assert(0);
  2427. break;
  2428. }
  2429. this->gcSinceLastRedeferral = 0;
  2430. }
  2431. }
  2432. else
  2433. {
  2434. this->gcSinceCallCountsCollected++;
  2435. this->gcSinceLastRedeferral++;
  2436. }
  2437. }
  2438. void
  2439. ThreadContext::PreDisposeObjectsCallBack()
  2440. {
  2441. this->expirableObjectDisposeList->Clear();
  2442. }
  2443. #ifdef FAULT_INJECTION
  2444. void
  2445. ThreadContext::DisposeScriptContextByFaultInjectionCallBack()
  2446. {
  2447. if (FAULTINJECT_SCRIPT_TERMINATION_ON_DISPOSE) {
  2448. int scriptContextToClose = -1;
  2449. /* inject only if we have more than 1 script context*/
  2450. uint totalScriptCount = GetScriptContextCount();
  2451. if (totalScriptCount > 1) {
  2452. if (Js::Configuration::Global.flags.FaultInjectionScriptContextToTerminateCount > 0)
  2453. {
  2454. scriptContextToClose = Js::Configuration::Global.flags.FaultInjectionScriptContextToTerminateCount % totalScriptCount;
  2455. for (Js::ScriptContext *scriptContext = GetScriptContextList(); scriptContext; scriptContext = scriptContext->next)
  2456. {
  2457. if (scriptContextToClose-- == 0)
  2458. {
  2459. scriptContext->DisposeScriptContextByFaultInjection();
  2460. break;
  2461. }
  2462. }
  2463. }
  2464. else
  2465. {
  2466. fwprintf(stderr, _u("***FI: FaultInjectionScriptContextToTerminateCount Failed, Value should be > 0. \n"));
  2467. }
  2468. }
  2469. }
  2470. }
  2471. #endif
  2472. #pragma region "Expirable Object Methods"
  2473. void
  2474. ThreadContext::TryExitExpirableCollectMode()
  2475. {
  2476. // If this feature is turned off or if we're already in profile collection mode, do nothing
  2477. // We also do nothing if expiration is explicitly disabled by someone lower down the stack
  2478. if (PHASE_OFF1(Js::ExpirableCollectPhase) || !InExpirableCollectMode() || this->disableExpiration)
  2479. {
  2480. return;
  2481. }
  2482. if (InExpirableCollectMode())
  2483. {
  2484. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Checking to see whether to complete Expirable Object Collection: GC Count is %d\n"), this->expirableCollectModeGcCount);
  2485. if (this->expirableCollectModeGcCount > 0)
  2486. {
  2487. this->expirableCollectModeGcCount--;
  2488. }
  2489. if (this->expirableCollectModeGcCount == 0 &&
  2490. (this->recycler->InCacheCleanupCollection() || CONFIG_FLAG(ForceExpireOnNonCacheCollect)))
  2491. {
  2492. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Completing Expirable Object Collection\n"));
  2493. ExpirableObjectList::Iterator expirableObjectIterator(this->expirableObjectList);
  2494. while (expirableObjectIterator.Next())
  2495. {
  2496. ExpirableObject* object = expirableObjectIterator.Data();
  2497. Assert(object);
  2498. if (!object->IsObjectUsed())
  2499. {
  2500. object->Expire();
  2501. }
  2502. }
  2503. // Leave expirable collection mode
  2504. expirableCollectModeGcCount = -1;
  2505. }
  2506. }
  2507. }
  2508. bool
  2509. ThreadContext::InExpirableCollectMode()
  2510. {
  2511. // We're in expirable collect if we have expirable objects registered,
  2512. // and expirableCollectModeGcCount is not negative
  2513. // and when debugger is attaching, it might have set the function to deferredParse.
  2514. return (expirableObjectList != nullptr &&
  2515. numExpirableObjects > 0 &&
  2516. expirableCollectModeGcCount >= 0 &&
  2517. (this->GetDebugManager() != nullptr &&
  2518. !this->GetDebugManager()->IsDebuggerAttaching()));
  2519. }
  2520. void
  2521. ThreadContext::TryEnterExpirableCollectMode()
  2522. {
  2523. // If this feature is turned off or if we're already in profile collection mode, do nothing
  2524. if (PHASE_OFF1(Js::ExpirableCollectPhase) || InExpirableCollectMode())
  2525. {
  2526. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Not running Expirable Object Collection\n"));
  2527. return;
  2528. }
  2529. double entryPointCollectionThreshold = Js::Configuration::Global.flags.ExpirableCollectionTriggerThreshold / 100.0;
  2530. double currentThreadNativeCodeRatio = ((double) GetCodeSize()) / Js::Constants::MaxThreadJITCodeHeapSize;
  2531. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Current native code ratio: %f\n"), currentThreadNativeCodeRatio);
  2532. if (currentThreadNativeCodeRatio > entryPointCollectionThreshold)
  2533. {
  2534. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Setting up Expirable Object Collection\n"));
  2535. this->expirableCollectModeGcCount = Js::Configuration::Global.flags.ExpirableCollectionGCCount;
  2536. ExpirableObjectList::Iterator expirableObjectIterator(this->expirableObjectList);
  2537. while (expirableObjectIterator.Next())
  2538. {
  2539. ExpirableObject* object = expirableObjectIterator.Data();
  2540. Assert(object);
  2541. object->EnterExpirableCollectMode();
  2542. }
  2543. if (this->entryExitRecord != nullptr)
  2544. {
  2545. // If we're in script, we will do a stack walk, find the JavascriptFunction's on the stack
  2546. // and mark their entry points as being used so that we don't prematurely expire them
  2547. Js::ScriptContext* topScriptContext = this->entryExitRecord->scriptContext;
  2548. Js::JavascriptStackWalker walker(topScriptContext, TRUE);
  2549. Js::JavascriptFunction* javascriptFunction = nullptr;
  2550. while (walker.GetCallerWithoutInlinedFrames(&javascriptFunction))
  2551. {
  2552. if (javascriptFunction != nullptr && Js::ScriptFunction::Is(javascriptFunction))
  2553. {
  2554. Js::ScriptFunction* scriptFunction = (Js::ScriptFunction*) javascriptFunction;
  2555. Js::FunctionEntryPointInfo* entryPointInfo = scriptFunction->GetFunctionEntryPointInfo();
  2556. entryPointInfo->SetIsObjectUsed();
  2557. scriptFunction->GetFunctionBody()->MapEntryPoints([](int index, Js::FunctionEntryPointInfo* entryPoint){
  2558. entryPoint->SetIsObjectUsed();
  2559. });
  2560. }
  2561. }
  2562. }
  2563. }
  2564. }
  2565. void
  2566. ThreadContext::RegisterExpirableObject(ExpirableObject* object)
  2567. {
  2568. Assert(this->expirableObjectList);
  2569. Assert(object->registrationHandle == nullptr);
  2570. ExpirableObject** registrationData = this->expirableObjectList->PrependNode();
  2571. (*registrationData) = object;
  2572. object->registrationHandle = (void*) registrationData;
  2573. OUTPUT_VERBOSE_TRACE(Js::ExpirableCollectPhase, _u("Registered 0x%p\n"), object);
  2574. numExpirableObjects++;
  2575. }
  2576. void
  2577. ThreadContext::UnregisterExpirableObject(ExpirableObject* object)
  2578. {
  2579. Assert(this->expirableObjectList);
  2580. Assert(object->registrationHandle != nullptr);
  2581. ExpirableObject** registrationData = (ExpirableObject**)PointerValue(object->registrationHandle);
  2582. Assert(*registrationData == object);
  2583. this->expirableObjectList->MoveElementTo(registrationData, this->expirableObjectDisposeList);
  2584. object->registrationHandle = nullptr;
  2585. OUTPUT_VERBOSE_TRACE(Js::ExpirableCollectPhase, _u("Unregistered 0x%p\n"), object);
  2586. numExpirableObjects--;
  2587. }
  2588. #pragma endregion
  2589. void
  2590. ThreadContext::ClearScriptContextCaches()
  2591. {
  2592. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext != nullptr; scriptContext = scriptContext->next)
  2593. {
  2594. scriptContext->ClearScriptContextCaches();
  2595. }
  2596. }
  2597. #ifdef PERSISTENT_INLINE_CACHES
  2598. void
  2599. ThreadContext::ClearInlineCachesWithDeadWeakRefs()
  2600. {
  2601. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext != nullptr; scriptContext = scriptContext->next)
  2602. {
  2603. scriptContext->ClearInlineCachesWithDeadWeakRefs();
  2604. }
  2605. if (PHASE_TRACE1(Js::InlineCachePhase))
  2606. {
  2607. size_t size = 0;
  2608. size_t freeListSize = 0;
  2609. size_t polyInlineCacheSize = 0;
  2610. uint scriptContextCount = 0;
  2611. for (Js::ScriptContext *scriptContext = scriptContextList;
  2612. scriptContext;
  2613. scriptContext = scriptContext->next)
  2614. {
  2615. scriptContextCount++;
  2616. size += scriptContext->GetInlineCacheAllocator()->AllocatedSize();
  2617. freeListSize += scriptContext->GetInlineCacheAllocator()->FreeListSize();
  2618. #ifdef POLY_INLINE_CACHE_SIZE_STATS
  2619. polyInlineCacheSize += scriptContext->GetInlineCacheAllocator()->GetPolyInlineCacheSize();
  2620. #endif
  2621. };
  2622. printf("Inline cache arena: total = %5I64u KB, free list = %5I64u KB, poly caches = %5I64u KB, script contexts = %u\n",
  2623. static_cast<uint64>(size / 1024), static_cast<uint64>(freeListSize / 1024), static_cast<uint64>(polyInlineCacheSize / 1024), scriptContextCount);
  2624. }
  2625. }
  2626. void
  2627. ThreadContext::ClearInvalidatedUniqueGuards()
  2628. {
  2629. // If a propertyGuard was invalidated, make sure to remove it's entry from unique property guard table of other property records.
  2630. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards;
  2631. guards.Map([this](Js::PropertyRecord const * propertyRecord, PropertyGuardEntry* entry, const RecyclerWeakReference<const Js::PropertyRecord>* weakRef)
  2632. {
  2633. entry->uniqueGuards.MapAndRemoveIf([=](RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef)
  2634. {
  2635. Js::PropertyGuard* guard = guardWeakRef->Get();
  2636. bool shouldRemove = guard != nullptr && !guard->IsValid();
  2637. if (shouldRemove)
  2638. {
  2639. if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase))
  2640. {
  2641. Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"),
  2642. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue());
  2643. Output::Flush();
  2644. }
  2645. if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase))
  2646. {
  2647. Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"),
  2648. propertyRecord->GetBuffer(), guard->GetValue());
  2649. Output::Flush();
  2650. }
  2651. }
  2652. return shouldRemove;
  2653. });
  2654. });
  2655. }
  2656. void
  2657. ThreadContext::ClearInlineCaches()
  2658. {
  2659. if (PHASE_TRACE1(Js::InlineCachePhase))
  2660. {
  2661. size_t size = 0;
  2662. size_t freeListSize = 0;
  2663. size_t polyInlineCacheSize = 0;
  2664. uint scriptContextCount = 0;
  2665. for (Js::ScriptContext *scriptContext = scriptContextList;
  2666. scriptContext;
  2667. scriptContext = scriptContext->next)
  2668. {
  2669. scriptContextCount++;
  2670. size += scriptContext->GetInlineCacheAllocator()->AllocatedSize();
  2671. freeListSize += scriptContext->GetInlineCacheAllocator()->FreeListSize();
  2672. #ifdef POLY_INLINE_CACHE_SIZE_STATS
  2673. polyInlineCacheSize += scriptContext->GetInlineCacheAllocator()->GetPolyInlineCacheSize();
  2674. #endif
  2675. };
  2676. printf("Inline cache arena: total = %5I64u KB, free list = %5I64u KB, poly caches = %5I64u KB, script contexts = %u\n",
  2677. static_cast<uint64>(size / 1024), static_cast<uint64>(freeListSize / 1024), static_cast<uint64>(polyInlineCacheSize / 1024), scriptContextCount);
  2678. }
  2679. Js::ScriptContext *scriptContext = this->scriptContextList;
  2680. while (scriptContext != nullptr)
  2681. {
  2682. scriptContext->ClearInlineCaches();
  2683. scriptContext = scriptContext->next;
  2684. }
  2685. inlineCacheThreadInfoAllocator.Reset();
  2686. protoInlineCacheByPropId.ResetNoDelete();
  2687. storeFieldInlineCacheByPropId.ResetNoDelete();
  2688. registeredInlineCacheCount = 0;
  2689. unregisteredInlineCacheCount = 0;
  2690. }
  2691. #endif //PERSISTENT_INLINE_CACHES
  2692. void
  2693. ThreadContext::ClearIsInstInlineCaches()
  2694. {
  2695. Js::ScriptContext *scriptContext = this->scriptContextList;
  2696. while (scriptContext != nullptr)
  2697. {
  2698. scriptContext->ClearIsInstInlineCaches();
  2699. scriptContext = scriptContext->next;
  2700. }
  2701. isInstInlineCacheThreadInfoAllocator.Reset();
  2702. isInstInlineCacheByFunction.ResetNoDelete();
  2703. }
  2704. void
  2705. ThreadContext::ClearForInCaches()
  2706. {
  2707. Js::ScriptContext *scriptContext = this->scriptContextList;
  2708. while (scriptContext != nullptr)
  2709. {
  2710. scriptContext->ClearForInCaches();
  2711. scriptContext = scriptContext->next;
  2712. }
  2713. }
  2714. void
  2715. ThreadContext::ClearEquivalentTypeCaches()
  2716. {
  2717. #if ENABLE_NATIVE_CODEGEN
  2718. // Called from PreSweepCallback to clear pointers to types that have no live object references left.
  2719. // The EquivalentTypeCache used to keep these types alive, but this caused memory growth in cases where
  2720. // entry points stayed around for a long time.
  2721. // In future we may want to pin the reference/guard type to the entry point, but that choice will depend
  2722. // on a use case where pinning the type helps us optimize. Lacking that, clearing the guard type is a
  2723. // simpler short-term solution.
  2724. // Note that clearing unmarked types from the cache and guard is needed for correctness if the cache doesn't keep
  2725. // the types alive.
  2726. FOREACH_DLISTBASE_ENTRY_EDITING(Js::EntryPointInfo *, entryPoint, &equivalentTypeCacheEntryPoints, iter)
  2727. {
  2728. bool isLive = entryPoint->ClearEquivalentTypeCaches();
  2729. if (!isLive)
  2730. {
  2731. iter.RemoveCurrent(&equivalentTypeCacheInfoAllocator);
  2732. }
  2733. }
  2734. NEXT_DLISTBASE_ENTRY_EDITING;
  2735. // Note: Don't reset the list, because we're only clearing the dead types from these caches.
  2736. // There may still be type references we need to keep an eye on.
  2737. #endif
  2738. }
  2739. Js::EntryPointInfo **
  2740. ThreadContext::RegisterEquivalentTypeCacheEntryPoint(Js::EntryPointInfo * entryPoint)
  2741. {
  2742. return equivalentTypeCacheEntryPoints.PrependNode(&equivalentTypeCacheInfoAllocator, entryPoint);
  2743. }
  2744. void
  2745. ThreadContext::UnregisterEquivalentTypeCacheEntryPoint(Js::EntryPointInfo ** entryPoint)
  2746. {
  2747. equivalentTypeCacheEntryPoints.RemoveElement(&equivalentTypeCacheInfoAllocator, entryPoint);
  2748. }
  2749. void
  2750. ThreadContext::RegisterProtoInlineCache(Js::InlineCache * inlineCache, Js::PropertyId propertyId)
  2751. {
  2752. if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2753. {
  2754. Output::Print(_u("InlineCacheInvalidation: registering proto cache 0x%p for property %s(%u)\n"),
  2755. inlineCache, GetPropertyName(propertyId)->GetBuffer(), propertyId);
  2756. Output::Flush();
  2757. }
  2758. RegisterInlineCache(protoInlineCacheByPropId, inlineCache, propertyId);
  2759. }
  2760. void
  2761. ThreadContext::RegisterStoreFieldInlineCache(Js::InlineCache * inlineCache, Js::PropertyId propertyId)
  2762. {
  2763. if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2764. {
  2765. Output::Print(_u("InlineCacheInvalidation: registering store field cache 0x%p for property %s(%u)\n"),
  2766. inlineCache, GetPropertyName(propertyId)->GetBuffer(), propertyId);
  2767. Output::Flush();
  2768. }
  2769. RegisterInlineCache(storeFieldInlineCacheByPropId, inlineCache, propertyId);
  2770. }
  2771. void
  2772. ThreadContext::RegisterInlineCache(InlineCacheListMapByPropertyId& inlineCacheMap, Js::InlineCache * inlineCache, Js::PropertyId propertyId)
  2773. {
  2774. InlineCacheList* inlineCacheList;
  2775. if (!inlineCacheMap.TryGetValue(propertyId, &inlineCacheList))
  2776. {
  2777. inlineCacheList = Anew(&this->inlineCacheThreadInfoAllocator, InlineCacheList, &this->inlineCacheThreadInfoAllocator);
  2778. inlineCacheMap.AddNew(propertyId, inlineCacheList);
  2779. }
  2780. Js::InlineCache** inlineCacheRef = inlineCacheList->PrependNode();
  2781. Assert(inlineCacheRef != nullptr);
  2782. *inlineCacheRef = inlineCache;
  2783. inlineCache->invalidationListSlotPtr = inlineCacheRef;
  2784. this->registeredInlineCacheCount++;
  2785. }
  2786. void ThreadContext::NotifyInlineCacheBatchUnregistered(uint count)
  2787. {
  2788. this->unregisteredInlineCacheCount += count;
  2789. // Negative or 0 InlineCacheInvalidationListCompactionThreshold forces compaction all the time.
  2790. if (CONFIG_FLAG(InlineCacheInvalidationListCompactionThreshold) <= 0 ||
  2791. this->registeredInlineCacheCount / this->unregisteredInlineCacheCount < (uint)CONFIG_FLAG(InlineCacheInvalidationListCompactionThreshold))
  2792. {
  2793. CompactInlineCacheInvalidationLists();
  2794. }
  2795. }
  2796. void
  2797. ThreadContext::InvalidateProtoInlineCaches(Js::PropertyId propertyId)
  2798. {
  2799. InlineCacheList* inlineCacheList;
  2800. if (protoInlineCacheByPropId.TryGetValueAndRemove(propertyId, &inlineCacheList))
  2801. {
  2802. if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2803. {
  2804. Output::Print(_u("InlineCacheInvalidation: invalidating proto caches for property %s(%u)\n"),
  2805. GetPropertyName(propertyId)->GetBuffer(), propertyId);
  2806. Output::Flush();
  2807. }
  2808. InvalidateAndDeleteInlineCacheList(inlineCacheList);
  2809. }
  2810. }
  2811. void
  2812. ThreadContext::InvalidateStoreFieldInlineCaches(Js::PropertyId propertyId)
  2813. {
  2814. InlineCacheList* inlineCacheList;
  2815. if (storeFieldInlineCacheByPropId.TryGetValueAndRemove(propertyId, &inlineCacheList))
  2816. {
  2817. if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2818. {
  2819. Output::Print(_u("InlineCacheInvalidation: invalidating store field caches for property %s(%u)\n"),
  2820. GetPropertyName(propertyId)->GetBuffer(), propertyId);
  2821. Output::Flush();
  2822. }
  2823. InvalidateAndDeleteInlineCacheList(inlineCacheList);
  2824. }
  2825. }
  2826. void
  2827. ThreadContext::InvalidateAndDeleteInlineCacheList(InlineCacheList* inlineCacheList)
  2828. {
  2829. Assert(inlineCacheList != nullptr);
  2830. uint cacheCount = 0;
  2831. uint nullCacheCount = 0;
  2832. FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList)
  2833. {
  2834. cacheCount++;
  2835. if (inlineCache != nullptr)
  2836. {
  2837. if (PHASE_VERBOSE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2838. {
  2839. Output::Print(_u("InlineCacheInvalidation: invalidating cache 0x%p\n"), inlineCache);
  2840. Output::Flush();
  2841. }
  2842. memset(inlineCache, 0, sizeof(Js::InlineCache));
  2843. }
  2844. else
  2845. {
  2846. nullCacheCount++;
  2847. }
  2848. }
  2849. NEXT_SLISTBASE_ENTRY;
  2850. Adelete(&this->inlineCacheThreadInfoAllocator, inlineCacheList);
  2851. this->registeredInlineCacheCount = this->registeredInlineCacheCount > cacheCount ? this->registeredInlineCacheCount - cacheCount : 0;
  2852. this->unregisteredInlineCacheCount = this->unregisteredInlineCacheCount > nullCacheCount ? this->unregisteredInlineCacheCount - nullCacheCount : 0;
  2853. }
  2854. void
  2855. ThreadContext::CompactInlineCacheInvalidationLists()
  2856. {
  2857. #if DBG
  2858. uint countOfNodesToCompact = this->unregisteredInlineCacheCount;
  2859. this->totalUnregisteredCacheCount = 0;
  2860. #endif
  2861. Assert(this->unregisteredInlineCacheCount > 0);
  2862. CompactProtoInlineCaches();
  2863. if (this->unregisteredInlineCacheCount > 0)
  2864. {
  2865. CompactStoreFieldInlineCaches();
  2866. }
  2867. Assert(countOfNodesToCompact == this->totalUnregisteredCacheCount);
  2868. }
  2869. void
  2870. ThreadContext::CompactProtoInlineCaches()
  2871. {
  2872. protoInlineCacheByPropId.MapUntil([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  2873. {
  2874. CompactInlineCacheList(inlineCacheList);
  2875. return this->unregisteredInlineCacheCount == 0;
  2876. });
  2877. }
  2878. void
  2879. ThreadContext::CompactStoreFieldInlineCaches()
  2880. {
  2881. storeFieldInlineCacheByPropId.MapUntil([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  2882. {
  2883. CompactInlineCacheList(inlineCacheList);
  2884. return this->unregisteredInlineCacheCount == 0;
  2885. });
  2886. }
  2887. void
  2888. ThreadContext::CompactInlineCacheList(InlineCacheList* inlineCacheList)
  2889. {
  2890. Assert(inlineCacheList != nullptr);
  2891. uint cacheCount = 0;
  2892. FOREACH_SLISTBASE_ENTRY_EDITING(Js::InlineCache*, inlineCache, inlineCacheList, iterator)
  2893. {
  2894. if (inlineCache == nullptr)
  2895. {
  2896. iterator.RemoveCurrent();
  2897. cacheCount++;
  2898. }
  2899. }
  2900. NEXT_SLISTBASE_ENTRY_EDITING;
  2901. #if DBG
  2902. this->totalUnregisteredCacheCount += cacheCount;
  2903. #endif
  2904. if (cacheCount > 0)
  2905. {
  2906. AssertMsg(this->unregisteredInlineCacheCount >= cacheCount, "Some codepaths didn't unregistered the inlineCaches which might leak memory.");
  2907. this->unregisteredInlineCacheCount = this->unregisteredInlineCacheCount > cacheCount ?
  2908. this->unregisteredInlineCacheCount - cacheCount : 0;
  2909. AssertMsg(this->registeredInlineCacheCount >= cacheCount, "Some codepaths didn't registered the inlineCaches which might leak memory.");
  2910. this->registeredInlineCacheCount = this->registeredInlineCacheCount > cacheCount ?
  2911. this->registeredInlineCacheCount - cacheCount : 0;
  2912. }
  2913. }
  2914. #if DBG
  2915. bool
  2916. ThreadContext::IsProtoInlineCacheRegistered(const Js::InlineCache* inlineCache, Js::PropertyId propertyId)
  2917. {
  2918. return IsInlineCacheRegistered(protoInlineCacheByPropId, inlineCache, propertyId);
  2919. }
  2920. bool
  2921. ThreadContext::IsStoreFieldInlineCacheRegistered(const Js::InlineCache* inlineCache, Js::PropertyId propertyId)
  2922. {
  2923. return IsInlineCacheRegistered(storeFieldInlineCacheByPropId, inlineCache, propertyId);
  2924. }
  2925. bool
  2926. ThreadContext::IsInlineCacheRegistered(InlineCacheListMapByPropertyId& inlineCacheMap, const Js::InlineCache* inlineCache, Js::PropertyId propertyId)
  2927. {
  2928. InlineCacheList* inlineCacheList;
  2929. if (inlineCacheMap.TryGetValue(propertyId, &inlineCacheList))
  2930. {
  2931. return IsInlineCacheInList(inlineCache, inlineCacheList);
  2932. }
  2933. else
  2934. {
  2935. return false;
  2936. }
  2937. }
  2938. bool
  2939. ThreadContext::IsInlineCacheInList(const Js::InlineCache* inlineCache, const InlineCacheList* inlineCacheList)
  2940. {
  2941. Assert(inlineCache != nullptr);
  2942. Assert(inlineCacheList != nullptr);
  2943. FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, curInlineCache, inlineCacheList)
  2944. {
  2945. if (curInlineCache == inlineCache)
  2946. {
  2947. return true;
  2948. }
  2949. }
  2950. NEXT_SLISTBASE_ENTRY;
  2951. return false;
  2952. }
  2953. #endif
  2954. #if ENABLE_NATIVE_CODEGEN
  2955. ThreadContext::PropertyGuardEntry*
  2956. ThreadContext::EnsurePropertyGuardEntry(const Js::PropertyRecord* propertyRecord, bool& foundExistingEntry)
  2957. {
  2958. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards;
  2959. PropertyGuardEntry* entry = nullptr;
  2960. foundExistingEntry = guards.TryGetValue(propertyRecord, &entry);
  2961. if (!foundExistingEntry)
  2962. {
  2963. entry = RecyclerNew(GetRecycler(), PropertyGuardEntry, GetRecycler());
  2964. guards.UncheckedAdd(CreatePropertyRecordWeakRef(propertyRecord), entry);
  2965. }
  2966. return entry;
  2967. }
  2968. Js::PropertyGuard*
  2969. ThreadContext::RegisterSharedPropertyGuard(Js::PropertyId propertyId)
  2970. {
  2971. Assert(IsActivePropertyId(propertyId));
  2972. const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId);
  2973. bool foundExistingGuard;
  2974. PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard);
  2975. if (entry->sharedGuard == nullptr)
  2976. {
  2977. entry->sharedGuard = Js::PropertyGuard::New(GetRecycler());
  2978. }
  2979. Js::PropertyGuard* guard = entry->sharedGuard;
  2980. PHASE_PRINT_VERBOSE_TRACE1(Js::FixedMethodsPhase, _u("FixedFields: registered shared guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p, %s\n"),
  2981. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue(), foundExistingGuard ? _u("existing") : _u("new"));
  2982. PHASE_PRINT_TESTTRACE1(Js::FixedMethodsPhase, _u("FixedFields: registered shared guard: name: %s, value: 0x%p, %s\n"),
  2983. propertyRecord->GetBuffer(), guard->GetValue(), foundExistingGuard ? _u("existing") : _u("new"));
  2984. return guard;
  2985. }
  2986. void
  2987. ThreadContext::RegisterLazyBailout(Js::PropertyId propertyId, Js::EntryPointInfo* entryPoint)
  2988. {
  2989. const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId);
  2990. bool foundExistingGuard;
  2991. PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard);
  2992. if (!entry->entryPoints)
  2993. {
  2994. entry->entryPoints = RecyclerNew(recycler, PropertyGuardEntry::EntryPointDictionary, recycler, /*capacity*/ 3);
  2995. }
  2996. entry->entryPoints->UncheckedAdd(entryPoint, NULL);
  2997. }
  2998. void
  2999. ThreadContext::RegisterUniquePropertyGuard(Js::PropertyId propertyId, Js::PropertyGuard* guard)
  3000. {
  3001. Assert(IsActivePropertyId(propertyId));
  3002. Assert(guard != nullptr);
  3003. RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef = this->recycler->CreateWeakReferenceHandle(guard);
  3004. RegisterUniquePropertyGuard(propertyId, guardWeakRef);
  3005. }
  3006. void
  3007. ThreadContext::RegisterUniquePropertyGuard(Js::PropertyId propertyId, RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef)
  3008. {
  3009. Assert(IsActivePropertyId(propertyId));
  3010. Assert(guardWeakRef != nullptr);
  3011. Js::PropertyGuard* guard = guardWeakRef->Get();
  3012. Assert(guard != nullptr);
  3013. const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId);
  3014. bool foundExistingGuard;
  3015. PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard);
  3016. entry->uniqueGuards.Item(guardWeakRef);
  3017. if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase))
  3018. {
  3019. Output::Print(_u("FixedFields: registered unique guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p, %s entry\n"),
  3020. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue(), foundExistingGuard ? _u("existing") : _u("new"));
  3021. Output::Flush();
  3022. }
  3023. if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase))
  3024. {
  3025. Output::Print(_u("FixedFields: registered unique guard: name: %s, value: 0x%p, %s entry\n"),
  3026. propertyRecord->GetBuffer(), guard->GetValue(), foundExistingGuard ? _u("existing") : _u("new"));
  3027. Output::Flush();
  3028. }
  3029. }
  3030. void
  3031. ThreadContext::RegisterConstructorCache(Js::PropertyId propertyId, Js::ConstructorCache* cache)
  3032. {
  3033. Assert(Js::ConstructorCache::GetOffsetOfGuardValue() == Js::PropertyGuard::GetOffsetOfValue());
  3034. Assert(Js::ConstructorCache::GetSizeOfGuardValue() == Js::PropertyGuard::GetSizeOfValue());
  3035. RegisterUniquePropertyGuard(propertyId, reinterpret_cast<Js::PropertyGuard*>(cache));
  3036. }
  3037. void
  3038. ThreadContext::InvalidatePropertyGuardEntry(const Js::PropertyRecord* propertyRecord, PropertyGuardEntry* entry, bool isAllPropertyGuardsInvalidation)
  3039. {
  3040. Assert(entry != nullptr);
  3041. if (entry->sharedGuard != nullptr)
  3042. {
  3043. Js::PropertyGuard* guard = entry->sharedGuard;
  3044. if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase))
  3045. {
  3046. Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"),
  3047. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue());
  3048. Output::Flush();
  3049. }
  3050. if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase))
  3051. {
  3052. Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"), propertyRecord->GetBuffer(), guard->GetValue());
  3053. Output::Flush();
  3054. }
  3055. guard->Invalidate();
  3056. }
  3057. uint count = 0;
  3058. entry->uniqueGuards.Map([&count, propertyRecord](RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef)
  3059. {
  3060. Js::PropertyGuard* guard = guardWeakRef->Get();
  3061. if (guard != nullptr)
  3062. {
  3063. if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase))
  3064. {
  3065. Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"),
  3066. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue());
  3067. Output::Flush();
  3068. }
  3069. if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase))
  3070. {
  3071. Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"),
  3072. propertyRecord->GetBuffer(), guard->GetValue());
  3073. Output::Flush();
  3074. }
  3075. guard->Invalidate();
  3076. count++;
  3077. }
  3078. });
  3079. entry->uniqueGuards.Clear();
  3080. // Count no. of invalidations done so far. Exclude if this is all property guards invalidation in which case
  3081. // the unique Guards will be cleared anyway.
  3082. if (!isAllPropertyGuardsInvalidation)
  3083. {
  3084. this->recyclableData->constructorCacheInvalidationCount += count;
  3085. if (this->recyclableData->constructorCacheInvalidationCount > (uint)CONFIG_FLAG(ConstructorCacheInvalidationThreshold))
  3086. {
  3087. // TODO: In future, we should compact the uniqueGuards dictionary so this function can be called from PreCollectionCallback
  3088. // instead
  3089. this->ClearInvalidatedUniqueGuards();
  3090. this->recyclableData->constructorCacheInvalidationCount = 0;
  3091. }
  3092. }
  3093. if (entry->entryPoints && entry->entryPoints->Count() > 0)
  3094. {
  3095. Js::JavascriptStackWalker stackWalker(this->GetScriptContextList());
  3096. Js::JavascriptFunction* caller = nullptr;
  3097. while (stackWalker.GetCaller(&caller, /*includeInlineFrames*/ false))
  3098. {
  3099. // If the current frame is already from a bailout - we do not need to do on stack invalidation
  3100. if (caller != nullptr && Js::ScriptFunction::Is(caller) && !stackWalker.GetCurrentFrameFromBailout())
  3101. {
  3102. BYTE dummy;
  3103. Js::FunctionEntryPointInfo* functionEntryPoint = caller->GetFunctionBody()->GetDefaultFunctionEntryPointInfo();
  3104. if (functionEntryPoint->IsInNativeAddressRange((DWORD_PTR)stackWalker.GetInstructionPointer()))
  3105. {
  3106. if (entry->entryPoints->TryGetValue(functionEntryPoint, &dummy))
  3107. {
  3108. functionEntryPoint->DoLazyBailout(stackWalker.GetCurrentAddressOfInstructionPointer(),
  3109. caller->GetFunctionBody(), propertyRecord);
  3110. }
  3111. }
  3112. }
  3113. }
  3114. entry->entryPoints->Map([=](Js::EntryPointInfo* info, BYTE& dummy, const RecyclerWeakReference<Js::EntryPointInfo>* infoWeakRef)
  3115. {
  3116. OUTPUT_TRACE2(Js::LazyBailoutPhase, info->GetFunctionBody(), _u("Lazy bailout - Invalidation due to property: %s \n"), propertyRecord->GetBuffer());
  3117. info->Invalidate(true);
  3118. });
  3119. entry->entryPoints->Clear();
  3120. }
  3121. }
  3122. void
  3123. ThreadContext::InvalidatePropertyGuards(Js::PropertyId propertyId)
  3124. {
  3125. const Js::PropertyRecord* propertyRecord = GetPropertyName(propertyId);
  3126. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards;
  3127. PropertyGuardEntry* entry = nullptr;
  3128. if (guards.TryGetValueAndRemove(propertyRecord, &entry))
  3129. {
  3130. InvalidatePropertyGuardEntry(propertyRecord, entry, false);
  3131. }
  3132. }
  3133. void
  3134. ThreadContext::InvalidateAllPropertyGuards()
  3135. {
  3136. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards;
  3137. if (guards.Count() > 0)
  3138. {
  3139. guards.Map([this](Js::PropertyRecord const * propertyRecord, PropertyGuardEntry* entry, const RecyclerWeakReference<const Js::PropertyRecord>* weakRef)
  3140. {
  3141. InvalidatePropertyGuardEntry(propertyRecord, entry, true);
  3142. });
  3143. guards.Clear();
  3144. }
  3145. }
  3146. #endif
  3147. void
  3148. ThreadContext::InvalidateAllProtoInlineCaches()
  3149. {
  3150. protoInlineCacheByPropId.Map([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  3151. {
  3152. InvalidateAndDeleteInlineCacheList(inlineCacheList);
  3153. });
  3154. protoInlineCacheByPropId.Reset();
  3155. }
  3156. #if DBG
  3157. // Verifies if object is registered in any proto InlineCache
  3158. bool
  3159. ThreadContext::IsObjectRegisteredInProtoInlineCaches(Js::DynamicObject * object)
  3160. {
  3161. return protoInlineCacheByPropId.MapUntil([object](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  3162. {
  3163. FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList)
  3164. {
  3165. if (inlineCache != nullptr && !inlineCache->IsEmpty())
  3166. {
  3167. // Verify this object is not present in prototype chain of inlineCache's type
  3168. bool isObjectPresentOnPrototypeChain =
  3169. Js::JavascriptOperators::MapObjectAndPrototypesUntil<true>(inlineCache->GetType()->GetPrototype(), [=](Js::RecyclableObject* prototype)
  3170. {
  3171. return prototype == object;
  3172. });
  3173. if (isObjectPresentOnPrototypeChain) {
  3174. return true;
  3175. }
  3176. }
  3177. }
  3178. NEXT_SLISTBASE_ENTRY;
  3179. return false;
  3180. });
  3181. }
  3182. // Verifies if object is registered in any storeField InlineCache
  3183. bool
  3184. ThreadContext::IsObjectRegisteredInStoreFieldInlineCaches(Js::DynamicObject * object)
  3185. {
  3186. return storeFieldInlineCacheByPropId.MapUntil([object](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  3187. {
  3188. FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList)
  3189. {
  3190. if (inlineCache != nullptr && !inlineCache->IsEmpty())
  3191. {
  3192. // Verify this object is not present in prototype chain of inlineCache's type
  3193. bool isObjectPresentOnPrototypeChain =
  3194. Js::JavascriptOperators::MapObjectAndPrototypesUntil<true>(inlineCache->GetType()->GetPrototype(), [=](Js::RecyclableObject* prototype)
  3195. {
  3196. return prototype == object;
  3197. });
  3198. if (isObjectPresentOnPrototypeChain) {
  3199. return true;
  3200. }
  3201. }
  3202. }
  3203. NEXT_SLISTBASE_ENTRY;
  3204. return false;
  3205. });
  3206. }
  3207. #endif
  3208. bool
  3209. ThreadContext::AreAllProtoInlineCachesInvalidated()
  3210. {
  3211. return protoInlineCacheByPropId.Count() == 0;
  3212. }
  3213. void
  3214. ThreadContext::InvalidateAllStoreFieldInlineCaches()
  3215. {
  3216. storeFieldInlineCacheByPropId.Map([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  3217. {
  3218. InvalidateAndDeleteInlineCacheList(inlineCacheList);
  3219. });
  3220. storeFieldInlineCacheByPropId.Reset();
  3221. }
  3222. bool
  3223. ThreadContext::AreAllStoreFieldInlineCachesInvalidated()
  3224. {
  3225. return storeFieldInlineCacheByPropId.Count() == 0;
  3226. }
  3227. #if DBG
  3228. bool
  3229. ThreadContext::IsIsInstInlineCacheRegistered(Js::IsInstInlineCache * inlineCache, Js::Var function)
  3230. {
  3231. Assert(inlineCache != nullptr);
  3232. Assert(function != nullptr);
  3233. Js::IsInstInlineCache* firstInlineCache;
  3234. if (this->isInstInlineCacheByFunction.TryGetValue(function, &firstInlineCache))
  3235. {
  3236. return IsIsInstInlineCacheInList(inlineCache, firstInlineCache);
  3237. }
  3238. else
  3239. {
  3240. return false;
  3241. }
  3242. }
  3243. #endif
  3244. void
  3245. ThreadContext::RegisterIsInstInlineCache(Js::IsInstInlineCache * inlineCache, Js::Var function)
  3246. {
  3247. Assert(function != nullptr);
  3248. Assert(inlineCache != nullptr);
  3249. // We should never cross-register or re-register a cache that is already on some invalidation list (for its function or some other function).
  3250. // Every cache must be first cleared and unregistered before being registered again.
  3251. AssertMsg(inlineCache->function == nullptr, "We should only register instance-of caches that have not yet been populated.");
  3252. Js::IsInstInlineCache** inlineCacheRef = nullptr;
  3253. if (this->isInstInlineCacheByFunction.TryGetReference(function, &inlineCacheRef))
  3254. {
  3255. AssertMsg(!IsIsInstInlineCacheInList(inlineCache, *inlineCacheRef), "Why are we registering a cache that is already registered?");
  3256. inlineCache->next = *inlineCacheRef;
  3257. *inlineCacheRef = inlineCache;
  3258. }
  3259. else
  3260. {
  3261. inlineCache->next = nullptr;
  3262. this->isInstInlineCacheByFunction.Add(function, inlineCache);
  3263. }
  3264. }
  3265. void
  3266. ThreadContext::UnregisterIsInstInlineCache(Js::IsInstInlineCache * inlineCache, Js::Var function)
  3267. {
  3268. Assert(inlineCache != nullptr);
  3269. Js::IsInstInlineCache** inlineCacheRef = nullptr;
  3270. if (this->isInstInlineCacheByFunction.TryGetReference(function, &inlineCacheRef))
  3271. {
  3272. Assert(*inlineCacheRef != nullptr);
  3273. if (inlineCache == *inlineCacheRef)
  3274. {
  3275. *inlineCacheRef = (*inlineCacheRef)->next;
  3276. if (*inlineCacheRef == nullptr)
  3277. {
  3278. this->isInstInlineCacheByFunction.Remove(function);
  3279. }
  3280. }
  3281. else
  3282. {
  3283. Js::IsInstInlineCache * prevInlineCache;
  3284. Js::IsInstInlineCache * curInlineCache;
  3285. for (prevInlineCache = *inlineCacheRef, curInlineCache = (*inlineCacheRef)->next; curInlineCache != nullptr;
  3286. prevInlineCache = curInlineCache, curInlineCache = curInlineCache->next)
  3287. {
  3288. if (curInlineCache == inlineCache)
  3289. {
  3290. prevInlineCache->next = curInlineCache->next;
  3291. return;
  3292. }
  3293. }
  3294. AssertMsg(false, "Why are we unregistering a cache that is not registered?");
  3295. }
  3296. }
  3297. }
  3298. void
  3299. ThreadContext::InvalidateIsInstInlineCacheList(Js::IsInstInlineCache* inlineCacheList)
  3300. {
  3301. Assert(inlineCacheList != nullptr);
  3302. Js::IsInstInlineCache* curInlineCache;
  3303. Js::IsInstInlineCache* nextInlineCache;
  3304. for (curInlineCache = inlineCacheList; curInlineCache != nullptr; curInlineCache = nextInlineCache)
  3305. {
  3306. if (PHASE_VERBOSE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  3307. {
  3308. Output::Print(_u("InlineCacheInvalidation: invalidating instanceof cache 0x%p\n"), curInlineCache);
  3309. Output::Flush();
  3310. }
  3311. // Stash away the next cache before we zero out the current one (including its next pointer).
  3312. nextInlineCache = curInlineCache->next;
  3313. // Clear the current cache to invalidate it.
  3314. memset(curInlineCache, 0, sizeof(Js::IsInstInlineCache));
  3315. }
  3316. }
  3317. void
  3318. ThreadContext::InvalidateIsInstInlineCachesForFunction(Js::Var function)
  3319. {
  3320. Js::IsInstInlineCache* inlineCacheList;
  3321. if (this->isInstInlineCacheByFunction.TryGetValueAndRemove(function, &inlineCacheList))
  3322. {
  3323. InvalidateIsInstInlineCacheList(inlineCacheList);
  3324. }
  3325. }
  3326. void
  3327. ThreadContext::InvalidateAllIsInstInlineCaches()
  3328. {
  3329. isInstInlineCacheByFunction.Map([this](const Js::Var function, Js::IsInstInlineCache* inlineCacheList)
  3330. {
  3331. InvalidateIsInstInlineCacheList(inlineCacheList);
  3332. });
  3333. isInstInlineCacheByFunction.Clear();
  3334. }
  3335. bool
  3336. ThreadContext::AreAllIsInstInlineCachesInvalidated() const
  3337. {
  3338. return isInstInlineCacheByFunction.Count() == 0;
  3339. }
  3340. #if DBG
  3341. bool
  3342. ThreadContext::IsIsInstInlineCacheInList(const Js::IsInstInlineCache* inlineCache, const Js::IsInstInlineCache* inlineCacheList)
  3343. {
  3344. Assert(inlineCache != nullptr);
  3345. Assert(inlineCacheList != nullptr);
  3346. for (const Js::IsInstInlineCache* curInlineCache = inlineCacheList; curInlineCache != nullptr; curInlineCache = curInlineCache->next)
  3347. {
  3348. if (curInlineCache == inlineCache)
  3349. {
  3350. return true;
  3351. }
  3352. }
  3353. return false;
  3354. }
  3355. #endif
  3356. void ThreadContext::RegisterTypeWithProtoPropertyCache(const Js::PropertyId propertyId, Js::Type *const type)
  3357. {
  3358. Assert(propertyId != Js::Constants::NoProperty);
  3359. Assert(IsActivePropertyId(propertyId));
  3360. Assert(type);
  3361. PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache;
  3362. TypeHashSet *typeHashSet = nullptr;
  3363. if(!typesWithProtoPropertyCache.TryGetValue(propertyId, &typeHashSet))
  3364. {
  3365. typeHashSet = RecyclerNew(recycler, TypeHashSet, recycler);
  3366. typesWithProtoPropertyCache.Add(propertyId, typeHashSet);
  3367. }
  3368. typeHashSet->Item(type, false);
  3369. }
  3370. void ThreadContext::InvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId)
  3371. {
  3372. Assert(propertyId != Js::Constants::NoProperty);
  3373. Assert(IsActivePropertyId(propertyId));
  3374. InternalInvalidateProtoTypePropertyCaches(propertyId);
  3375. }
  3376. void ThreadContext::InternalInvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId)
  3377. {
  3378. // Get the hash set of registered types associated with the property ID, invalidate each type in the hash set, and
  3379. // remove the property ID and its hash set from the map
  3380. PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache;
  3381. TypeHashSet *typeHashSet = nullptr;
  3382. if(typesWithProtoPropertyCache.Count() != 0 && typesWithProtoPropertyCache.TryGetValueAndRemove(propertyId, &typeHashSet))
  3383. {
  3384. DoInvalidateProtoTypePropertyCaches(propertyId, typeHashSet);
  3385. }
  3386. }
  3387. void ThreadContext::InvalidateAllProtoTypePropertyCaches()
  3388. {
  3389. PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache;
  3390. if (typesWithProtoPropertyCache.Count() > 0)
  3391. {
  3392. typesWithProtoPropertyCache.Map([this](Js::PropertyId propertyId, TypeHashSet * typeHashSet)
  3393. {
  3394. DoInvalidateProtoTypePropertyCaches(propertyId, typeHashSet);
  3395. });
  3396. typesWithProtoPropertyCache.Clear();
  3397. }
  3398. }
  3399. void ThreadContext::DoInvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId, TypeHashSet *const typeHashSet)
  3400. {
  3401. Assert(propertyId != Js::Constants::NoProperty);
  3402. Assert(typeHashSet);
  3403. typeHashSet->Map(
  3404. [propertyId](Js::Type *const type, const bool unused, const RecyclerWeakReference<Js::Type>*)
  3405. {
  3406. type->GetPropertyCache()->ClearIfPropertyIsOnAPrototype(propertyId);
  3407. });
  3408. }
  3409. Js::ScriptContext **
  3410. ThreadContext::RegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(Js::ScriptContext * scriptContext)
  3411. {
  3412. return prototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext.PrependNode(&prototypeChainEnsuredToHaveOnlyWritableDataPropertiesAllocator, scriptContext);
  3413. }
  3414. void
  3415. ThreadContext::UnregisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(Js::ScriptContext ** scriptContext)
  3416. {
  3417. prototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext.RemoveElement(&prototypeChainEnsuredToHaveOnlyWritableDataPropertiesAllocator, scriptContext);
  3418. }
  3419. void
  3420. ThreadContext::ClearPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesCaches()
  3421. {
  3422. bool hasItem = false;
  3423. FOREACH_DLISTBASE_ENTRY(Js::ScriptContext *, scriptContext, &prototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext)
  3424. {
  3425. scriptContext->ClearPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesCaches();
  3426. hasItem = true;
  3427. }
  3428. NEXT_DLISTBASE_ENTRY;
  3429. if (!hasItem)
  3430. {
  3431. return;
  3432. }
  3433. prototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext.Reset();
  3434. prototypeChainEnsuredToHaveOnlyWritableDataPropertiesAllocator.Reset();
  3435. }
  3436. BOOL ThreadContext::HasPreviousHostScriptContext()
  3437. {
  3438. return hostScriptContextStack->Count() != 0;
  3439. }
  3440. HostScriptContext* ThreadContext::GetPreviousHostScriptContext()
  3441. {
  3442. return hostScriptContextStack->Peek();
  3443. }
  3444. void ThreadContext::PushHostScriptContext(HostScriptContext* topProvider)
  3445. {
  3446. // script engine can be created coming from GetDispID, so push/pop can be
  3447. // happening after the first round of enterscript as well. we might need to
  3448. // revisit the whole callRootLevel but probably not now.
  3449. // Assert(HasPreviousHostScriptContext() || callRootLevel == 0);
  3450. hostScriptContextStack->Push(topProvider);
  3451. }
  3452. HostScriptContext* ThreadContext::PopHostScriptContext()
  3453. {
  3454. return hostScriptContextStack->Pop();
  3455. // script engine can be created coming from GetDispID, so push/pop can be
  3456. // happening after the first round of enterscript as well. we might need to
  3457. // revisit the whole callRootLevel but probably not now.
  3458. // Assert(HasPreviousHostScriptContext() || callRootLevel == 0);
  3459. }
  3460. #if DBG || defined(PROFILE_EXEC)
  3461. bool
  3462. ThreadContext::AsyncHostOperationStart(void * suspendRecord)
  3463. {
  3464. bool wasInAsync = false;
  3465. Assert(!this->IsScriptActive());
  3466. Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord;
  3467. if (lastRecord != NULL)
  3468. {
  3469. if (!lastRecord->leaveForHost)
  3470. {
  3471. #if DBG
  3472. wasInAsync = !!lastRecord->leaveForAsyncHostOperation;
  3473. lastRecord->leaveForAsyncHostOperation = true;
  3474. #endif
  3475. #ifdef PROFILE_EXEC
  3476. lastRecord->scriptContext->ProfileSuspend(Js::RunPhase, (Js::Profiler::SuspendRecord *)suspendRecord);
  3477. #endif
  3478. }
  3479. else
  3480. {
  3481. Assert(!lastRecord->leaveForAsyncHostOperation);
  3482. }
  3483. }
  3484. return wasInAsync;
  3485. }
  3486. void
  3487. ThreadContext::AsyncHostOperationEnd(bool wasInAsync, void * suspendRecord)
  3488. {
  3489. Assert(!this->IsScriptActive());
  3490. Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord;
  3491. if (lastRecord != NULL)
  3492. {
  3493. if (!lastRecord->leaveForHost)
  3494. {
  3495. Assert(lastRecord->leaveForAsyncHostOperation);
  3496. #if DBG
  3497. lastRecord->leaveForAsyncHostOperation = wasInAsync;
  3498. #endif
  3499. #ifdef PROFILE_EXEC
  3500. lastRecord->scriptContext->ProfileResume((Js::Profiler::SuspendRecord *)suspendRecord);
  3501. #endif
  3502. }
  3503. else
  3504. {
  3505. Assert(!lastRecord->leaveForAsyncHostOperation);
  3506. Assert(!wasInAsync);
  3507. }
  3508. }
  3509. }
  3510. #endif
  3511. #ifdef RECYCLER_DUMP_OBJECT_GRAPH
  3512. void DumpRecyclerObjectGraph()
  3513. {
  3514. ThreadContext * threadContext = ThreadContext::GetContextForCurrentThread();
  3515. if (threadContext == nullptr)
  3516. {
  3517. Output::Print(_u("No thread context"));
  3518. }
  3519. threadContext->GetRecycler()->DumpObjectGraph();
  3520. }
  3521. #endif
  3522. #if ENABLE_NATIVE_CODEGEN
  3523. bool ThreadContext::IsNativeAddressHelper(void * pCodeAddr, Js::ScriptContext* currentScriptContext)
  3524. {
  3525. bool isNativeAddr = false;
  3526. if (currentScriptContext && currentScriptContext->GetJitFuncRangeCache() != nullptr)
  3527. {
  3528. isNativeAddr = currentScriptContext->GetJitFuncRangeCache()->IsNativeAddr(pCodeAddr);
  3529. }
  3530. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext && !isNativeAddr; scriptContext = scriptContext->next)
  3531. {
  3532. if (scriptContext == currentScriptContext || scriptContext->GetJitFuncRangeCache() == nullptr)
  3533. {
  3534. continue;
  3535. }
  3536. isNativeAddr = scriptContext->GetJitFuncRangeCache()->IsNativeAddr(pCodeAddr);
  3537. }
  3538. return isNativeAddr;
  3539. }
  3540. BOOL ThreadContext::IsNativeAddress(void * pCodeAddr, Js::ScriptContext* currentScriptContext)
  3541. {
  3542. #if ENABLE_OOP_NATIVE_CODEGEN
  3543. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  3544. {
  3545. if (PreReservedVirtualAllocWrapper::IsInRange((void*)m_prereservedRegionAddr, pCodeAddr))
  3546. {
  3547. return true;
  3548. }
  3549. if (IsAllJITCodeInPreReservedRegion())
  3550. {
  3551. return false;
  3552. }
  3553. if (AutoSystemInfo::IsJscriptModulePointer(pCodeAddr))
  3554. {
  3555. return false;
  3556. }
  3557. #if DBG
  3558. boolean result;
  3559. HRESULT hr = JITManager::GetJITManager()->IsNativeAddr(this->m_remoteThreadContextInfo, (intptr_t)pCodeAddr, &result);
  3560. #endif
  3561. bool isNativeAddr = IsNativeAddressHelper(pCodeAddr, currentScriptContext);
  3562. #if DBG
  3563. Assert(FAILED(hr) || result == (isNativeAddr? TRUE:FALSE));
  3564. #endif
  3565. return isNativeAddr;
  3566. }
  3567. else
  3568. #endif
  3569. {
  3570. PreReservedVirtualAllocWrapper *preReservedVirtualAllocWrapper = this->GetPreReservedVirtualAllocator();
  3571. if (preReservedVirtualAllocWrapper->IsInRange(pCodeAddr))
  3572. {
  3573. return TRUE;
  3574. }
  3575. if (!this->IsAllJITCodeInPreReservedRegion())
  3576. {
  3577. #if DBG
  3578. AutoCriticalSection autoLock(&this->codePageAllocators.cs);
  3579. #endif
  3580. bool isNativeAddr = IsNativeAddressHelper(pCodeAddr, currentScriptContext);
  3581. #if DBG
  3582. Assert(this->codePageAllocators.IsInNonPreReservedPageAllocator(pCodeAddr) == isNativeAddr);
  3583. #endif
  3584. return isNativeAddr;
  3585. }
  3586. return FALSE;
  3587. }
  3588. }
  3589. #endif
  3590. #if ENABLE_PROFILE_INFO
  3591. void ThreadContext::EnsureSourceProfileManagersByUrlMap()
  3592. {
  3593. if(this->recyclableData->sourceProfileManagersByUrl == nullptr)
  3594. {
  3595. this->EnsureRecycler();
  3596. this->recyclableData->sourceProfileManagersByUrl = RecyclerNew(GetRecycler(), SourceProfileManagersByUrlMap, GetRecycler());
  3597. }
  3598. }
  3599. //
  3600. // Returns the cache profile manager for the URL and hash combination for a particular dynamic script. There is a ref count added for every script context
  3601. // that references the shared profile manager info.
  3602. //
  3603. Js::SourceDynamicProfileManager* ThreadContext::GetSourceDynamicProfileManager(_In_z_ const WCHAR* url, _In_ uint hash, _Inout_ bool* addRef)
  3604. {
  3605. EnsureSourceProfileManagersByUrlMap();
  3606. Js::SourceDynamicProfileManager* profileManager = nullptr;
  3607. SourceDynamicProfileManagerCache* managerCache = nullptr;
  3608. bool newCache = false;
  3609. if(!this->recyclableData->sourceProfileManagersByUrl->TryGetValue(url, &managerCache))
  3610. {
  3611. if(this->recyclableData->sourceProfileManagersByUrl->Count() >= INMEMORY_CACHE_MAX_URL)
  3612. {
  3613. return nullptr;
  3614. }
  3615. managerCache = RecyclerNewZ(this->GetRecycler(), SourceDynamicProfileManagerCache);
  3616. newCache = true;
  3617. }
  3618. bool createProfileManager = false;
  3619. if(!managerCache->sourceProfileManagerMap)
  3620. {
  3621. managerCache->sourceProfileManagerMap = RecyclerNew(this->GetRecycler(), SourceDynamicProfileManagerMap, this->GetRecycler());
  3622. createProfileManager = true;
  3623. }
  3624. else
  3625. {
  3626. createProfileManager = !managerCache->sourceProfileManagerMap->TryGetValue(hash, &profileManager);
  3627. }
  3628. if(createProfileManager)
  3629. {
  3630. if(managerCache->sourceProfileManagerMap->Count() < INMEMORY_CACHE_MAX_PROFILE_MANAGER)
  3631. {
  3632. profileManager = RecyclerNewZ(this->GetRecycler(), Js::SourceDynamicProfileManager, this->GetRecycler());
  3633. managerCache->sourceProfileManagerMap->Add(hash, profileManager);
  3634. }
  3635. }
  3636. else
  3637. {
  3638. profileManager->Reuse();
  3639. }
  3640. if(!*addRef)
  3641. {
  3642. managerCache->AddRef();
  3643. *addRef = true;
  3644. OUTPUT_VERBOSE_TRACE(Js::DynamicProfilePhase, _u("Addref dynamic source profile manger - Url: %s\n"), url);
  3645. }
  3646. if (newCache)
  3647. {
  3648. // Let's make a copy of the URL because there is no guarantee this URL will remain alive in the future.
  3649. size_t lengthInChars = wcslen(url) + 1;
  3650. WCHAR* urlCopy = RecyclerNewArrayLeaf(GetRecycler(), WCHAR, lengthInChars);
  3651. js_memcpy_s(urlCopy, lengthInChars * sizeof(WCHAR), url, lengthInChars * sizeof(WCHAR));
  3652. this->recyclableData->sourceProfileManagersByUrl->Add(urlCopy, managerCache);
  3653. }
  3654. return profileManager;
  3655. }
  3656. //
  3657. // Decrement the ref count for this URL and cleanup the corresponding record if there are no other references to it.
  3658. //
  3659. uint ThreadContext::ReleaseSourceDynamicProfileManagers(const WCHAR* url)
  3660. {
  3661. // If we've already freed the recyclable data, we're shutting down the thread context so skip clean up
  3662. if (this->recyclableData == nullptr) return 0;
  3663. SourceDynamicProfileManagerCache* managerCache = this->recyclableData->sourceProfileManagersByUrl->Lookup(url, nullptr);
  3664. uint refCount = 0;
  3665. if(managerCache) // manager cache may be null we exceeded -INMEMORY_CACHE_MAX_URL
  3666. {
  3667. refCount = managerCache->Release();
  3668. OUTPUT_VERBOSE_TRACE(Js::DynamicProfilePhase, _u("Release dynamic source profile manger %d Url: %s\n"), refCount, url);
  3669. Output::Flush();
  3670. if(refCount == 0)
  3671. {
  3672. this->recyclableData->sourceProfileManagersByUrl->Remove(url);
  3673. }
  3674. }
  3675. return refCount;
  3676. }
  3677. #endif
  3678. void ThreadContext::EnsureSymbolRegistrationMap()
  3679. {
  3680. if (this->recyclableData->symbolRegistrationMap == nullptr)
  3681. {
  3682. this->EnsureRecycler();
  3683. this->recyclableData->symbolRegistrationMap = RecyclerNew(GetRecycler(), SymbolRegistrationMap, GetRecycler());
  3684. }
  3685. }
  3686. const Js::PropertyRecord* ThreadContext::GetSymbolFromRegistrationMap(const char16* stringKey, charcount_t stringLength)
  3687. {
  3688. this->EnsureSymbolRegistrationMap();
  3689. Js::HashedCharacterBuffer<char16> propertyName = Js::HashedCharacterBuffer<char16>(stringKey, stringLength);
  3690. return this->recyclableData->symbolRegistrationMap->LookupWithKey(&propertyName, nullptr);
  3691. }
  3692. const Js::PropertyRecord* ThreadContext::AddSymbolToRegistrationMap(const char16* stringKey, charcount_t stringLength)
  3693. {
  3694. this->EnsureSymbolRegistrationMap();
  3695. const Js::PropertyRecord* propertyRecord = this->UncheckedAddPropertyId(stringKey, stringLength, /*bind*/false, /*isSymbol*/true);
  3696. Assert(propertyRecord);
  3697. // We need to support null characters in the Symbol names. For e.g. "A\0Z" is a valid symbol name and is different than "A\0Y".
  3698. // However, as the key contains a null character we need to hash the symbol name past the null character. The default implementation terminates
  3699. // at the null character, so we use the Js::HashedCharacterBuffer as key. We allocate the key in the recycler memory as it needs to be around
  3700. // for the lifetime of the map.
  3701. Js::HashedCharacterBuffer<char16> * propertyName = RecyclerNew(GetRecycler(), Js::HashedCharacterBuffer<char16>, propertyRecord->GetBuffer(), propertyRecord->GetLength());
  3702. this->recyclableData->symbolRegistrationMap->Add(propertyName, propertyRecord);
  3703. return propertyRecord;
  3704. }
  3705. #if ENABLE_TTD
  3706. JsUtil::BaseDictionary<Js::HashedCharacterBuffer<char16>*, const Js::PropertyRecord*, Recycler, PowerOf2SizePolicy, Js::PropertyRecordStringHashComparer>* ThreadContext::GetSymbolRegistrationMap_TTD()
  3707. {
  3708. //This adds a little memory but makes simplifies other logic -- maybe revise later
  3709. this->EnsureSymbolRegistrationMap();
  3710. return this->recyclableData->symbolRegistrationMap;
  3711. }
  3712. #endif
  3713. void ThreadContext::ClearImplicitCallFlags()
  3714. {
  3715. SetImplicitCallFlags(Js::ImplicitCall_None);
  3716. }
  3717. void ThreadContext::ClearImplicitCallFlags(Js::ImplicitCallFlags flags)
  3718. {
  3719. Assert((flags & Js::ImplicitCall_None) == 0);
  3720. SetImplicitCallFlags((Js::ImplicitCallFlags)(implicitCallFlags & ~flags));
  3721. }
  3722. void ThreadContext::CheckAndResetImplicitCallAccessorFlag()
  3723. {
  3724. Js::ImplicitCallFlags accessorCallFlag = (Js::ImplicitCallFlags)(Js::ImplicitCall_Accessor & ~Js::ImplicitCall_None);
  3725. if ((GetImplicitCallFlags() & accessorCallFlag) != 0)
  3726. {
  3727. ClearImplicitCallFlags(accessorCallFlag);
  3728. AddImplicitCallFlags(Js::ImplicitCall_NonProfiledAccessor);
  3729. }
  3730. }
  3731. bool ThreadContext::HasNoSideEffect(Js::RecyclableObject * function) const
  3732. {
  3733. Js::FunctionInfo::Attributes attributes = Js::FunctionInfo::GetAttributes(function);
  3734. return this->HasNoSideEffect(function, attributes);
  3735. }
  3736. bool ThreadContext::HasNoSideEffect(Js::RecyclableObject * function, Js::FunctionInfo::Attributes attributes) const
  3737. {
  3738. if (((attributes & Js::FunctionInfo::CanBeHoisted) != 0)
  3739. || ((attributes & Js::FunctionInfo::HasNoSideEffect) != 0 && !IsDisableImplicitException()))
  3740. {
  3741. Assert((attributes & Js::FunctionInfo::HasNoSideEffect) != 0);
  3742. return true;
  3743. }
  3744. return false;
  3745. }
  3746. bool
  3747. ThreadContext::RecordImplicitException()
  3748. {
  3749. // Record the exception in the implicit call flag
  3750. AddImplicitCallFlags(Js::ImplicitCall_Exception);
  3751. if (IsDisableImplicitException())
  3752. {
  3753. // Indicate that we shouldn't throw if ImplicitExceptions have been disabled
  3754. return false;
  3755. }
  3756. // Disabling implicit exception when disabling implicit calls can result in valid exceptions not being thrown.
  3757. // Instead we tell not to throw only if an implicit call happened and they are disabled. This is to cover the case
  3758. // of an exception being thrown because an implicit call not executed left the execution in a bad state.
  3759. // Since there is an implicit call, we expect to bailout and handle this operation in the interpreter instead.
  3760. bool hasImplicitCallHappened = IsDisableImplicitCall() && (GetImplicitCallFlags() & ~Js::ImplicitCall_Exception);
  3761. return !hasImplicitCallHappened;
  3762. }
  3763. void ThreadContext::SetThreadServiceWrapper(ThreadServiceWrapper* inThreadServiceWrapper)
  3764. {
  3765. AssertMsg(threadServiceWrapper == NULL || inThreadServiceWrapper == NULL, "double set ThreadServiceWrapper");
  3766. threadServiceWrapper = inThreadServiceWrapper;
  3767. }
  3768. ThreadServiceWrapper* ThreadContext::GetThreadServiceWrapper()
  3769. {
  3770. return threadServiceWrapper;
  3771. }
  3772. uint ThreadContext::GetRandomNumber()
  3773. {
  3774. #ifdef ENABLE_CUSTOM_ENTROPY
  3775. return (uint)GetEntropy().GetRand();
  3776. #else
  3777. uint randomNumber = 0;
  3778. errno_t e = rand_s(&randomNumber);
  3779. Assert(e == 0);
  3780. return randomNumber;
  3781. #endif
  3782. }
  3783. #if defined(ENABLE_JS_ETW) && defined(NTBUILD)
  3784. void ThreadContext::EtwLogPropertyIdList()
  3785. {
  3786. propertyMap->Map([&](const Js::PropertyRecord* propertyRecord){
  3787. EventWriteJSCRIPT_HOSTING_PROPERTYID_LIST(propertyRecord, propertyRecord->GetBuffer());
  3788. });
  3789. }
  3790. #endif
  3791. #ifdef ENABLE_PROJECTION
  3792. void ThreadContext::AddExternalWeakReferenceCache(ExternalWeakReferenceCache *externalWeakReferenceCache)
  3793. {
  3794. this->externalWeakReferenceCacheList.Prepend(&HeapAllocator::Instance, externalWeakReferenceCache);
  3795. }
  3796. void ThreadContext::RemoveExternalWeakReferenceCache(ExternalWeakReferenceCache *externalWeakReferenceCache)
  3797. {
  3798. Assert(!externalWeakReferenceCacheList.Empty());
  3799. this->externalWeakReferenceCacheList.Remove(&HeapAllocator::Instance, externalWeakReferenceCache);
  3800. }
  3801. void ThreadContext::MarkExternalWeakReferencedObjects(bool inPartialCollect)
  3802. {
  3803. SListBase<ExternalWeakReferenceCache *, HeapAllocator>::Iterator iteratorWeakRefCache(&this->externalWeakReferenceCacheList);
  3804. while (iteratorWeakRefCache.Next())
  3805. {
  3806. iteratorWeakRefCache.Data()->MarkNow(recycler, inPartialCollect);
  3807. }
  3808. }
  3809. void ThreadContext::ResolveExternalWeakReferencedObjects()
  3810. {
  3811. SListBase<ExternalWeakReferenceCache *, HeapAllocator>::Iterator iteratorWeakRefCache(&this->externalWeakReferenceCacheList);
  3812. while (iteratorWeakRefCache.Next())
  3813. {
  3814. iteratorWeakRefCache.Data()->ResolveNow(recycler);
  3815. }
  3816. }
  3817. #if DBG_DUMP
  3818. void ThreadContext::RegisterProjectionMemoryInformation(IProjectionContextMemoryInfo* projectionContextMemoryInfo)
  3819. {
  3820. Assert(this->projectionMemoryInformation == nullptr || this->projectionMemoryInformation == projectionContextMemoryInfo);
  3821. this->projectionMemoryInformation = projectionContextMemoryInfo;
  3822. }
  3823. void ThreadContext::DumpProjectionContextMemoryStats(LPCWSTR headerMsg, bool forceDetailed)
  3824. {
  3825. if (this->projectionMemoryInformation)
  3826. {
  3827. this->projectionMemoryInformation->DumpCurrentStats(headerMsg, forceDetailed);
  3828. }
  3829. }
  3830. IProjectionContextMemoryInfo* ThreadContext::GetProjectionContextMemoryInformation()
  3831. {
  3832. return this->projectionMemoryInformation;
  3833. }
  3834. #endif
  3835. #endif
  3836. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3837. Js::Var ThreadContext::GetMemoryStat(Js::ScriptContext* scriptContext)
  3838. {
  3839. ScriptMemoryDumper dumper(scriptContext);
  3840. return dumper.Dump();
  3841. }
  3842. void ThreadContext::SetAutoProxyName(LPCWSTR objectName)
  3843. {
  3844. recyclableData->autoProxyName = objectName;
  3845. }
  3846. #endif
  3847. //
  3848. // Regex helpers
  3849. //
  3850. UnifiedRegex::StandardChars<uint8>* ThreadContext::GetStandardChars(__inout_opt uint8* dummy)
  3851. {
  3852. if (standardUTF8Chars == 0)
  3853. {
  3854. ArenaAllocator* allocator = GetThreadAlloc();
  3855. standardUTF8Chars = Anew(allocator, UnifiedRegex::UTF8StandardChars, allocator);
  3856. }
  3857. return standardUTF8Chars;
  3858. }
  3859. UnifiedRegex::StandardChars<char16>* ThreadContext::GetStandardChars(__inout_opt char16* dummy)
  3860. {
  3861. if (standardUnicodeChars == 0)
  3862. {
  3863. ArenaAllocator* allocator = GetThreadAlloc();
  3864. standardUnicodeChars = Anew(allocator, UnifiedRegex::UnicodeStandardChars, allocator);
  3865. }
  3866. return standardUnicodeChars;
  3867. }
  3868. void ThreadContext::CheckScriptInterrupt()
  3869. {
  3870. if (TestThreadContextFlag(ThreadContextFlagCanDisableExecution))
  3871. {
  3872. if (this->IsExecutionDisabled())
  3873. {
  3874. Assert(this->DoInterruptProbe());
  3875. throw Js::ScriptAbortException();
  3876. }
  3877. }
  3878. else
  3879. {
  3880. this->CheckInterruptPoll();
  3881. }
  3882. }
  3883. void ThreadContext::CheckInterruptPoll()
  3884. {
  3885. // Disable QC when implicit calls are disabled since the host can do anything before returning back, like servicing the
  3886. // message loop, which may in turn cause script code to be executed and implicit calls to be made
  3887. if (!IsDisableImplicitCall())
  3888. {
  3889. InterruptPoller *poller = this->interruptPoller;
  3890. if (poller)
  3891. {
  3892. poller->CheckInterruptPoll();
  3893. }
  3894. }
  3895. }
  3896. void *
  3897. ThreadContext::GetDynamicObjectEnumeratorCache(Js::DynamicType const * dynamicType)
  3898. {
  3899. void * data = nullptr;
  3900. return this->dynamicObjectEnumeratorCacheMap.TryGetValue(dynamicType, &data)? data : nullptr;
  3901. }
  3902. void
  3903. ThreadContext::AddDynamicObjectEnumeratorCache(Js::DynamicType const * dynamicType, void * cache)
  3904. {
  3905. this->dynamicObjectEnumeratorCacheMap.Item(dynamicType, cache);
  3906. }
  3907. InterruptPoller::InterruptPoller(ThreadContext *tc) :
  3908. threadContext(tc),
  3909. lastPollTick(0),
  3910. lastResetTick(0),
  3911. isDisabled(FALSE)
  3912. {
  3913. tc->SetInterruptPoller(this);
  3914. }
  3915. void InterruptPoller::CheckInterruptPoll()
  3916. {
  3917. if (!isDisabled)
  3918. {
  3919. Js::ScriptEntryExitRecord *entryExitRecord = this->threadContext->GetScriptEntryExit();
  3920. if (entryExitRecord)
  3921. {
  3922. Js::ScriptContext *scriptContext = entryExitRecord->scriptContext;
  3923. if (scriptContext)
  3924. {
  3925. this->TryInterruptPoll(scriptContext);
  3926. }
  3927. }
  3928. }
  3929. }
  3930. void InterruptPoller::GetStatementCount(ULONG *pluHi, ULONG *pluLo)
  3931. {
  3932. DWORD resetTick = this->lastResetTick;
  3933. DWORD pollTick = this->lastPollTick;
  3934. DWORD elapsed;
  3935. elapsed = pollTick - resetTick;
  3936. ULONGLONG statements = (ULONGLONG)elapsed * InterruptPoller::TicksToStatements;
  3937. *pluLo = (ULONG)statements;
  3938. *pluHi = (ULONG)(statements >> 32);
  3939. }
  3940. void ThreadContext::DisableExecution()
  3941. {
  3942. Assert(TestThreadContextFlag(ThreadContextFlagCanDisableExecution));
  3943. // Hammer the stack limit with a value that will cause script abort on the next stack probe.
  3944. this->SetStackLimitForCurrentThread(Js::Constants::StackLimitForScriptInterrupt);
  3945. return;
  3946. }
  3947. void ThreadContext::EnableExecution()
  3948. {
  3949. Assert(this->GetStackProber());
  3950. // Restore the normal stack limit.
  3951. this->SetStackLimitForCurrentThread(this->GetStackProber()->GetScriptStackLimit());
  3952. // It's possible that the host disabled execution after the script threw an exception
  3953. // of it's own, so we shouldn't clear that. Only exceptions for script termination
  3954. // should be cleared.
  3955. if (GetRecordedException() == GetPendingTerminatedErrorObject())
  3956. {
  3957. SetRecordedException(NULL);
  3958. }
  3959. }
  3960. bool ThreadContext::TestThreadContextFlag(ThreadContextFlags contextFlag) const
  3961. {
  3962. return (this->threadContextFlags & contextFlag) != 0;
  3963. }
  3964. void ThreadContext::SetThreadContextFlag(ThreadContextFlags contextFlag)
  3965. {
  3966. this->threadContextFlags = (ThreadContextFlags)(this->threadContextFlags | contextFlag);
  3967. }
  3968. void ThreadContext::ClearThreadContextFlag(ThreadContextFlags contextFlag)
  3969. {
  3970. this->threadContextFlags = (ThreadContextFlags)(this->threadContextFlags & ~contextFlag);
  3971. }
  3972. #ifdef ENABLE_GLOBALIZATION
  3973. Js::DelayLoadWinRtString * ThreadContext::GetWinRTStringLibrary()
  3974. {
  3975. delayLoadWinRtString.EnsureFromSystemDirOnly();
  3976. return &delayLoadWinRtString;
  3977. }
  3978. #ifdef ENABLE_PROJECTION
  3979. Js::DelayLoadWinRtError * ThreadContext::GetWinRTErrorLibrary()
  3980. {
  3981. delayLoadWinRtError.EnsureFromSystemDirOnly();
  3982. return &delayLoadWinRtError;
  3983. }
  3984. Js::DelayLoadWinRtTypeResolution* ThreadContext::GetWinRTTypeResolutionLibrary()
  3985. {
  3986. delayLoadWinRtTypeResolution.EnsureFromSystemDirOnly();
  3987. return &delayLoadWinRtTypeResolution;
  3988. }
  3989. Js::DelayLoadWinRtRoParameterizedIID* ThreadContext::GetWinRTRoParameterizedIIDLibrary()
  3990. {
  3991. delayLoadWinRtRoParameterizedIID.EnsureFromSystemDirOnly();
  3992. return &delayLoadWinRtRoParameterizedIID;
  3993. }
  3994. #endif
  3995. #if defined(ENABLE_INTL_OBJECT) || defined(ENABLE_ES6_CHAR_CLASSIFIER)
  3996. Js::WindowsGlobalizationAdapter* ThreadContext::GetWindowsGlobalizationAdapter()
  3997. {
  3998. return &windowsGlobalizationAdapter;
  3999. }
  4000. Js::DelayLoadWindowsGlobalization* ThreadContext::GetWindowsGlobalizationLibrary()
  4001. {
  4002. delayLoadWindowsGlobalizationLibrary.Ensure(this->GetWinRTStringLibrary());
  4003. return &delayLoadWindowsGlobalizationLibrary;
  4004. }
  4005. #endif
  4006. #ifdef ENABLE_FOUNDATION_OBJECT
  4007. Js::WindowsFoundationAdapter* ThreadContext::GetWindowsFoundationAdapter()
  4008. {
  4009. return &windowsFoundationAdapter;
  4010. }
  4011. Js::DelayLoadWinRtFoundation* ThreadContext::GetWinRtFoundationLibrary()
  4012. {
  4013. delayLoadWinRtFoundationLibrary.EnsureFromSystemDirOnly();
  4014. return &delayLoadWinRtFoundationLibrary;
  4015. }
  4016. #endif
  4017. #endif // ENABLE_GLOBALIZATION
  4018. // Despite the name, callers expect this to return the highest propid + 1.
  4019. uint ThreadContext::GetHighestPropertyNameIndex() const
  4020. {
  4021. return propertyMap->GetLastIndex() + 1 + Js::InternalPropertyIds::Count;
  4022. }
  4023. #if defined(CHECK_MEMORY_LEAK) || defined(LEAK_REPORT)
  4024. void ThreadContext::ReportAndCheckLeaksOnProcessDetach()
  4025. {
  4026. bool needReportOrCheck = false;
  4027. #ifdef LEAK_REPORT
  4028. needReportOrCheck = needReportOrCheck || Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag);
  4029. #endif
  4030. #ifdef CHECK_MEMORY_LEAK
  4031. needReportOrCheck = needReportOrCheck ||
  4032. (Js::Configuration::Global.flags.CheckMemoryLeak && MemoryLeakCheck::IsEnableOutput());
  4033. #endif
  4034. if (!needReportOrCheck)
  4035. {
  4036. return;
  4037. }
  4038. // Report leaks even if this is a force termination and we have not clean up the thread
  4039. // This is call during process detach. No one should be creating new thread context.
  4040. // So don't need to take the lock
  4041. ThreadContext * current = GetThreadContextList();
  4042. while (current)
  4043. {
  4044. #if DBG
  4045. current->pageAllocator.ClearConcurrentThreadId();
  4046. #endif
  4047. Recycler * recycler = current->GetRecycler();
  4048. #ifdef LEAK_REPORT
  4049. if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
  4050. {
  4051. AUTO_LEAK_REPORT_SECTION(Js::Configuration::Global.flags, _u("Thread Context (%p): Process Termination (TID: %d)"), current, current->threadId);
  4052. LeakReport::DumpUrl(current->threadId);
  4053. // Heuristically figure out which one is the root tracker script engine
  4054. // and force close on it
  4055. if (current->rootTrackerScriptContext != nullptr)
  4056. {
  4057. current->rootTrackerScriptContext->Close(false);
  4058. }
  4059. recycler->ReportLeaksOnProcessDetach();
  4060. }
  4061. #endif
  4062. #ifdef CHECK_MEMORY_LEAK
  4063. recycler->CheckLeaksOnProcessDetach(_u("Process Termination"));
  4064. #endif
  4065. current = current->Next();
  4066. }
  4067. }
  4068. #endif
  4069. #ifdef LEAK_REPORT
  4070. void
  4071. ThreadContext::SetRootTrackerScriptContext(Js::ScriptContext * scriptContext)
  4072. {
  4073. Assert(this->rootTrackerScriptContext == nullptr);
  4074. this->rootTrackerScriptContext = scriptContext;
  4075. scriptContext->isRootTrackerScriptContext = true;
  4076. }
  4077. void
  4078. ThreadContext::ClearRootTrackerScriptContext(Js::ScriptContext * scriptContext)
  4079. {
  4080. Assert(this->rootTrackerScriptContext == scriptContext);
  4081. this->rootTrackerScriptContext->isRootTrackerScriptContext = false;
  4082. this->rootTrackerScriptContext = nullptr;
  4083. }
  4084. #endif
  4085. AutoTagNativeLibraryEntry::AutoTagNativeLibraryEntry(Js::RecyclableObject* function, Js::CallInfo callInfo, PCWSTR name, void* addr)
  4086. {
  4087. // Save function/callInfo values (for StackWalker). Compiler may stackpack/optimize them for built-in native functions.
  4088. entry.function = function;
  4089. entry.callInfo = callInfo;
  4090. entry.name = name;
  4091. entry.addr = addr;
  4092. ThreadContext* threadContext = function->GetScriptContext()->GetThreadContext();
  4093. threadContext->PushNativeLibraryEntry(&entry);
  4094. }
  4095. AutoTagNativeLibraryEntry::~AutoTagNativeLibraryEntry()
  4096. {
  4097. ThreadContext* threadContext = entry.function->GetScriptContext()->GetThreadContext();
  4098. Assert(threadContext->PeekNativeLibraryEntry() == &entry);
  4099. threadContext->PopNativeLibraryEntry();
  4100. }