ThreadContext.cpp 158 KB

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