ThreadContext.cpp 155 KB

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