ThreadContext.cpp 138 KB

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