ThreadContext.cpp 160 KB

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