ThreadContext.cpp 159 KB

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