ThreadContext.cpp 138 KB

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