ThreadContext.h 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #pragma once
  6. namespace Js
  7. {
  8. class ScriptContext;
  9. struct InlineCache;
  10. class CodeGenRecyclableData;
  11. #ifdef ENABLE_SCRIPT_DEBUGGING
  12. class DebugManager;
  13. struct ReturnedValue;
  14. typedef JsUtil::List<ReturnedValue*> ReturnedValueList;
  15. #endif
  16. }
  17. typedef BVSparse<ArenaAllocator> ActiveFunctionSet;
  18. using namespace PlatformAgnostic;
  19. struct IAuthorFileContext;
  20. class HostScriptContext;
  21. class ScriptSite;
  22. class ThreadServiceWrapper;
  23. struct IActiveScriptProfilerHeapEnum;
  24. class DynamicProfileMutator;
  25. class StackProber;
  26. enum DisableImplicitFlags : BYTE
  27. {
  28. DisableImplicitNoFlag = 0x00,
  29. DisableImplicitCallFlag = 0x01,
  30. DisableImplicitExceptionFlag = 0x02,
  31. DisableImplicitCallAndExceptionFlag = DisableImplicitCallFlag | DisableImplicitExceptionFlag
  32. };
  33. enum ThreadContextFlags
  34. {
  35. ThreadContextFlagNoFlag = 0x00000000,
  36. ThreadContextFlagCanDisableExecution = 0x00000001,
  37. ThreadContextFlagEvalDisabled = 0x00000002,
  38. ThreadContextFlagNoJIT = 0x00000004,
  39. ThreadContextFlagDisableFatalOnOOM = 0x00000008,
  40. ThreadContextFlagNoDynamicThunks = 0x00000010,
  41. };
  42. const int LS_MAX_STACK_SIZE_KB = 300;
  43. struct IProjectionContext
  44. {
  45. public:
  46. virtual HRESULT Close() = 0;
  47. };
  48. class ThreadContext;
  49. class InterruptPoller
  50. {
  51. // Interface with a polling object located in the hosting layer.
  52. public:
  53. InterruptPoller(ThreadContext *tc);
  54. virtual ~InterruptPoller() { }
  55. void CheckInterruptPoll();
  56. void GetStatementCount(ULONG *pluHi, ULONG *pluLo);
  57. void ResetStatementCount() { lastResetTick = lastPollTick; }
  58. void StartScript() { lastResetTick = lastPollTick = ::GetTickCount(); }
  59. void EndScript() { lastResetTick = lastPollTick = 0;}
  60. bool IsDisabled() const { return isDisabled; }
  61. void SetDisabled(bool disable) { isDisabled = disable; }
  62. virtual void TryInterruptPoll(Js::ScriptContext *scriptContext) = 0;
  63. // Default: throw up QC dialog after 5M statements == 2 minutes
  64. static const DWORD TicksToStatements = (5000000 / 120000);
  65. protected:
  66. ThreadContext *threadContext;
  67. DWORD lastPollTick;
  68. DWORD lastResetTick;
  69. bool isDisabled;
  70. };
  71. #define PROBE_STACK(scriptContext, size) ((scriptContext)->GetThreadContext()->ProbeStack(size, scriptContext))
  72. #define PROBE_STACK_NO_DISPOSE(scriptContext, size) ((scriptContext)->GetThreadContext()->ProbeStackNoDispose(size, scriptContext))
  73. #define PROBE_STACK_PARTIAL_INITIALIZED_INTERPRETER_FRAME(scriptContext, size) ((scriptContext)->GetThreadContext()->ProbeStack(size, scriptContext, _ReturnAddress()))
  74. #define PROBE_STACK_PARTIAL_INITIALIZED_BAILOUT_FRAME(scriptContext, size, returnAddress) ((scriptContext)->GetThreadContext()->ProbeStack(size, scriptContext, returnAddress))
  75. #define PROBE_STACK_CALL(scriptContext, obj, size) ((scriptContext)->GetThreadContext()->ProbeStack(size, obj, scriptContext))
  76. #define AssertInScript() Assert(ThreadContext::GetContextForCurrentThread()->IsScriptActive());
  77. #define AssertNotInScript() Assert(!ThreadContext::GetContextForCurrentThread()->IsScriptActive());
  78. #define LEAVE_SCRIPT_START_EX(scriptContext, stackProbe, leaveForHost, isFPUControlRestoreNeeded) \
  79. { \
  80. void * __frameAddr = nullptr; \
  81. GET_CURRENT_FRAME_ID(__frameAddr); \
  82. Js::LeaveScriptObject<stackProbe, leaveForHost, isFPUControlRestoreNeeded> __leaveScriptObject(scriptContext, __frameAddr); \
  83. AutoReentrancyHandler autoReentrancyHandler(scriptContext->GetThreadContext());
  84. #define LEAVE_SCRIPT_END_EX(scriptContext) \
  85. if (scriptContext != nullptr) \
  86. { \
  87. scriptContext->GetThreadContext()->DisposeOnLeaveScript(); \
  88. }\
  89. }
  90. #define LEAVE_SCRIPT_IF_ACTIVE(scriptContext, externalCall) \
  91. if (scriptContext->GetThreadContext()->IsScriptActive()) \
  92. { \
  93. BEGIN_LEAVE_SCRIPT(scriptContext); \
  94. externalCall \
  95. END_LEAVE_SCRIPT(scriptContext); \
  96. } \
  97. else \
  98. { \
  99. DECLARE_EXCEPTION_CHECK_DATA \
  100. SAVE_EXCEPTION_CHECK \
  101. externalCall \
  102. RESTORE_EXCEPTION_CHECK \
  103. }
  104. #define ENTER_SCRIPT_IF(scriptContext, doCleanup, isCallRoot, hasCaller, condition, block) \
  105. if (condition) \
  106. { \
  107. BEGIN_ENTER_SCRIPT(scriptContext, doCleanup, isCallRoot, hasCaller); \
  108. block \
  109. END_ENTER_SCRIPT(scriptContext, doCleanup, isCallRoot, hasCaller); \
  110. } \
  111. else \
  112. { \
  113. block \
  114. }
  115. #define BEGIN_LEAVE_SCRIPT(scriptContext) \
  116. LEAVE_SCRIPT_START_EX(scriptContext, /* stackProbe */ true, /* leaveForHost */ true, /* isFPUControlRestoreNeeded */ false)
  117. #define BEGIN_LEAVE_SCRIPT_SAVE_FPU_CONTROL(scriptContext) \
  118. LEAVE_SCRIPT_START_EX(scriptContext, /* stackProbe */ true, /* leaveForHost */ true, /* isFPUControlRestoreNeeded */ true)
  119. // BEGIN_LEAVE_SCRIPT_INTERNAL is used when there are no explicit external call after leave script,
  120. // but we might have external call when allocation memory doing QC or GC Dispose, which may enter script again.
  121. // This will record the reentry as an implicit call (ImplicitCall_AsyncHostOperation)
  122. #define BEGIN_LEAVE_SCRIPT_INTERNAL(scriptContext) \
  123. LEAVE_SCRIPT_START_EX(scriptContext, /* stackProbe */ true, /* leaveForHost */ false, /* isFPUControlRestoreNeeded */ false)
  124. #define BEGIN_LEAVE_SCRIPT_NO_STACK_PROBE(scriptContext) \
  125. LEAVE_SCRIPT_START_EX(scriptContext, /* stackProbe */ false, /* leaveForHost */ true, /* isFPUControlRestoreNeeded */ false)
  126. #define END_LEAVE_SCRIPT(scriptContext) \
  127. LEAVE_SCRIPT_END_EX(scriptContext)
  128. #define END_LEAVE_SCRIPT_RESTORE_FPU_CONTROL(scriptContext) \
  129. LEAVE_SCRIPT_END_EX(scriptContext)
  130. #define END_LEAVE_SCRIPT_INTERNAL(scriptContext) \
  131. LEAVE_SCRIPT_END_EX(scriptContext)
  132. #define END_LEAVE_SCRIPT_NO_STACK_PROBE(scriptContext) \
  133. LEAVE_SCRIPT_END_EX(scriptContext)
  134. #define BEGIN_LEAVE_SCRIPT_WITH_EXCEPTION(scriptContext) \
  135. BEGIN_LEAVE_SCRIPT(scriptContext)
  136. #define END_LEAVE_SCRIPT_WITH_EXCEPTION(scriptContext) \
  137. Assert(!scriptContext->HasRecordedException()); \
  138. END_LEAVE_SCRIPT(scriptContext)
  139. #define BEGIN_SAFE_REENTRANT_CALL(threadContext) \
  140. { \
  141. AutoReentrancyHandler autoReentrancyHandler(threadContext);
  142. #define END_SAFE_REENTRANT_CALL }
  143. #define BEGIN_SAFE_REENTRANT_REGION(threadContext) \
  144. { \
  145. AutoReentrancySafeRegion autoReentrancySafeRegion(threadContext);
  146. #define END_SAFE_REENTRANT_REGION }
  147. // Keep in sync with CollectGarbageCallBackFlags in scriptdirect.idl
  148. enum RecyclerCollectCallBackFlags
  149. {
  150. Collect_Begin = 0x01,
  151. Collect_Begin_Concurrent = 0x11,
  152. Collect_Begin_Partial = 0x21,
  153. Collect_Begin_Concurrent_Partial = Collect_Begin_Concurrent | Collect_Begin_Partial,
  154. Collect_End = 0x02,
  155. Collect_Wait = 0x04 // callback can be from another thread
  156. };
  157. typedef void (__cdecl *RecyclerCollectCallBackFunction)(void * context, RecyclerCollectCallBackFlags flags);
  158. #ifdef ENABLE_PROJECTION
  159. class ExternalWeakReferenceCache
  160. {
  161. public:
  162. virtual void MarkNow(Recycler *recycler, bool inPartialCollect) = 0;
  163. virtual void ResolveNow(Recycler *recycler) = 0;
  164. };
  165. #if DBG_DUMP
  166. class IProjectionContextMemoryInfo abstract
  167. {
  168. public:
  169. virtual void DumpCurrentStats(LPCWSTR headerMsg, bool forceDetailed) = 0;
  170. virtual void Release() = 0;
  171. };
  172. #endif
  173. #endif
  174. #ifdef NTBUILD
  175. struct ThreadContextWatsonTelemetryBlock
  176. {
  177. FILETIME lastScriptStartTime;
  178. FILETIME lastScriptEndTime;
  179. };
  180. #endif
  181. class NativeLibraryEntryRecord
  182. {
  183. public:
  184. struct Entry
  185. {
  186. Js::RecyclableObject* function;
  187. Js::CallInfo callInfo;
  188. PCWSTR name;
  189. PVOID addr;
  190. Entry* next;
  191. };
  192. private:
  193. Entry* head;
  194. public:
  195. NativeLibraryEntryRecord() : head(nullptr)
  196. {
  197. }
  198. const Entry* Peek() const
  199. {
  200. return head;
  201. }
  202. void Push(_In_ Entry* e)
  203. {
  204. e->next = head;
  205. head = e;
  206. }
  207. void Pop()
  208. {
  209. head = head->next;
  210. }
  211. };
  212. class AutoTagNativeLibraryEntry
  213. {
  214. private:
  215. NativeLibraryEntryRecord::Entry entry;
  216. public:
  217. AutoTagNativeLibraryEntry(Js::RecyclableObject* function, Js::CallInfo callInfo, PCWSTR name, void* addr);
  218. ~AutoTagNativeLibraryEntry();
  219. };
  220. #define AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, name) \
  221. AutoTagNativeLibraryEntry __tag(function, callInfo, name, _AddressOfReturnAddress())
  222. class ThreadConfiguration
  223. {
  224. public:
  225. ThreadConfiguration(bool enableExperimentalFeatures)
  226. {
  227. CopyGlobalFlags();
  228. if (enableExperimentalFeatures)
  229. {
  230. EnableExperimentalFeatures();
  231. ResetExperimentalFeaturesFromConfig();
  232. }
  233. }
  234. #define DEFINE_FLAG(threadFlag, globalFlag) \
  235. public: \
  236. inline bool threadFlag() const { return m_##globalFlag##; } \
  237. \
  238. private: \
  239. bool m_##globalFlag##;
  240. #define FLAG(threadFlag, globalFlag) DEFINE_FLAG(threadFlag, globalFlag)
  241. #define FLAG_RELEASE(threadFlag, globalFlag) DEFINE_FLAG(threadFlag, globalFlag)
  242. #include "ThreadConfigFlagsList.h"
  243. #undef FLAG_RELEASE
  244. #undef FLAG
  245. #undef DEFINE_FLAG
  246. private:
  247. void CopyGlobalFlags()
  248. {
  249. AutoCriticalSection autocs(&Js::Configuration::Global.flags.csExperimentalFlags);
  250. #define FLAG(threadFlag, globalFlag) m_##globalFlag## = CONFIG_FLAG(globalFlag);
  251. #define FLAG_RELEASE(threadFlag, globalFlag) m_##globalFlag## = CONFIG_FLAG_RELEASE(globalFlag);
  252. #include "ThreadConfigFlagsList.h"
  253. #undef FLAG_RELEASE
  254. #undef FLAG
  255. }
  256. void EnableExperimentalFeatures()
  257. {
  258. // If a ES6 flag is disabled using compile flag don't enable it
  259. #define FLAG_REGOVR_EXP(type, name, ...) m_##name## = COMPILE_DISABLE_##name## ? false : true;
  260. #include "ConfigFlagsList.h"
  261. #undef FLAG_REGOVR_EXP
  262. }
  263. void ResetExperimentalFeaturesFromConfig()
  264. {
  265. // If a flag was overridden using config/command line it should take precedence
  266. #define FLAG_REGOVR_EXP(type, name, ...) if(CONFIG_ISENABLED(Js::Flag::##name##Flag)) { m_##name## = CONFIG_FLAG_RELEASE(##name##); }
  267. #include "ConfigFlagsList.h"
  268. #undef FLAG_REGOVR_EXP
  269. }
  270. };
  271. class AutoReentrancyHandler;
  272. class ThreadContext sealed :
  273. public DefaultRecyclerCollectionWrapper,
  274. public JsUtil::DoublyLinkedListElement<ThreadContext>,
  275. public ThreadContextInfo
  276. {
  277. public:
  278. static void GlobalInitialize();
  279. static const DWORD NoThread = 0xFFFFFFFF;
  280. struct CollectCallBack
  281. {
  282. RecyclerCollectCallBackFunction callback;
  283. void * context;
  284. };
  285. struct WorkerThread
  286. {
  287. // Abstract notion to hold onto threadHandle of worker thread
  288. HANDLE threadHandle;
  289. WorkerThread(HANDLE handle = nullptr) :threadHandle(handle){};
  290. };
  291. void SetCurrentThreadId(DWORD threadId) { this->currentThreadId = threadId; }
  292. DWORD GetCurrentThreadId() const { return this->currentThreadId; }
  293. void SetIsThreadBound()
  294. {
  295. if (this->recycler)
  296. {
  297. this->recycler->SetIsThreadBound();
  298. }
  299. this->isThreadBound = true;
  300. }
  301. bool IsJSRT() const { return !this->isThreadBound; }
  302. virtual bool IsThreadBound() const override { return this->isThreadBound; }
  303. void SetStackProber(StackProber * stackProber);
  304. static DWORD GetStackLimitForCurrentThreadOffset() { return offsetof(ThreadContext, stackLimitForCurrentThread); }
  305. template <class Fn>
  306. Js::ImplicitCallFlags TryWithDisabledImplicitCall(Fn fn)
  307. {
  308. DisableImplicitFlags prevDisableImplicitFlags = this->GetDisableImplicitFlags();
  309. Js::ImplicitCallFlags savedImplicitCallFlags = this->GetImplicitCallFlags();
  310. this->DisableImplicitCall();
  311. this->SetImplicitCallFlags(Js::ImplicitCallFlags::ImplicitCall_None);
  312. fn();
  313. Js::ImplicitCallFlags curImplicitCallFlags = this->GetImplicitCallFlags();
  314. this->SetDisableImplicitFlags(prevDisableImplicitFlags);
  315. this->SetImplicitCallFlags(savedImplicitCallFlags);
  316. return curImplicitCallFlags;
  317. }
  318. void * GetAddressOfStackLimitForCurrentThread() const
  319. {
  320. FAULTINJECT_SCRIPT_TERMINATION
  321. return &this->stackLimitForCurrentThread;
  322. }
  323. void InitAvailableCommit();
  324. // This is always on for JSRT APIs.
  325. bool IsRentalThreadingEnabledInJSRT() const { return true; }
  326. IActiveScriptProfilerHeapEnum* GetHeapEnum();
  327. void SetHeapEnum(IActiveScriptProfilerHeapEnum* newHeapEnum);
  328. void ClearHeapEnum();
  329. Js::PropertyRecord const * GetPropertyRecord(Js::PropertyId propertyId);
  330. virtual bool IsNumericProperty(Js::PropertyId propertyId) override;
  331. #ifdef ENABLE_WASM_SIMD
  332. #if _M_IX86 || _M_AMD64
  333. // auxiliary SIMD values in memory to help JIT'ed code. E.g. used for Int8x16 shuffle.
  334. _x86_SIMDValue X86_TEMP_SIMD[SIMD_TEMP_SIZE];
  335. _x86_SIMDValue * GetSimdTempArea() { return X86_TEMP_SIMD; }
  336. #endif
  337. #endif
  338. public:
  339. Js::PropertyRecord const * GetEmptyStringPropertyRecord()
  340. {
  341. if (!emptyStringPropertyRecord)
  342. {
  343. emptyStringPropertyRecord = propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(_u(""), 0));
  344. if (emptyStringPropertyRecord == nullptr)
  345. {
  346. emptyStringPropertyRecord = this->UncheckedAddPropertyId(_u(""), 0, true);
  347. }
  348. }
  349. return emptyStringPropertyRecord;
  350. }
  351. Js::PropertyId GetEmptyStringPropertyId()
  352. {
  353. return GetEmptyStringPropertyRecord()->GetPropertyId();
  354. }
  355. private:
  356. const Js::PropertyRecord * emptyStringPropertyRecord;
  357. bool noScriptScope;
  358. #ifdef ENABLE_SCRIPT_DEBUGGING
  359. Js::DebugManager * debugManager;
  360. #endif
  361. static uint const MaxTemporaryArenaAllocators = 5;
  362. static CriticalSection s_csThreadContext;
  363. StackProber * GetStackProber() const { return this->stackProber; }
  364. size_t GetStackLimitForCurrentThread() const;
  365. void SetStackLimitForCurrentThread(size_t limit);
  366. // The current heap enumeration object being used during enumeration.
  367. IActiveScriptProfilerHeapEnum* heapEnum;
  368. struct PropertyGuardEntry
  369. {
  370. public:
  371. typedef JsUtil::BaseHashSet<RecyclerWeakReference<Js::PropertyGuard>*, Recycler, PowerOf2SizePolicy> PropertyGuardHashSet;
  372. // we do not have WeaklyReferencedKeyHashSet - hence use BYTE as a dummy value.
  373. typedef JsUtil::WeaklyReferencedKeyDictionary<Js::EntryPointInfo, BYTE> EntryPointDictionary;
  374. // The sharedGuard is strongly referenced and will be kept alive by ThreadContext::propertyGuards until it's invalidated or
  375. // the property record itself is collected. If the code using the guard needs access to it after it's been invalidated, it
  376. // (the code) is responsible for keeping it alive.
  377. // Each unique guard, is weakly referenced, such that it can be reclaimed if not referenced elsewhere even without being
  378. // invalidated. The entry of a unique guard is removed from the table once the corresponding cache is invalidated.
  379. Field(Js::PropertyGuard*) sharedGuard;
  380. Field(PropertyGuardHashSet) uniqueGuards;
  381. Field(EntryPointDictionary*) entryPoints;
  382. PropertyGuardEntry(Recycler* recycler) : sharedGuard(nullptr), uniqueGuards(recycler), entryPoints(nullptr) {}
  383. };
  384. public:
  385. typedef JsUtil::BaseHashSet<const Js::PropertyRecord *, HeapAllocator, PowerOf2SizePolicy, const Js::PropertyRecord *,
  386. Js::PropertyRecordStringHashComparer, JsUtil::SimpleHashedEntry, JsUtil::AsymetricResizeLock> PropertyMap;
  387. PropertyMap * propertyMap;
  388. typedef JsUtil::BaseHashSet<Js::CaseInvariantPropertyListWithHashCode*, Recycler, PowerOf2SizePolicy, Js::CaseInvariantPropertyListWithHashCode*, JsUtil::NoCaseComparer, JsUtil::SimpleDictionaryEntry>
  389. PropertyNoCaseSetType;
  390. typedef JsUtil::WeaklyReferencedKeyDictionary<Js::Type, bool> TypeHashSet;
  391. typedef JsUtil::BaseDictionary<Js::PropertyId, TypeHashSet *, Recycler, PowerOf2SizePolicy> PropertyIdToTypeHashSetDictionary;
  392. typedef JsUtil::WeaklyReferencedKeyDictionary<const Js::PropertyRecord, PropertyGuardEntry*, Js::PropertyRecordPointerComparer> PropertyGuardDictionary;
  393. private:
  394. PTHREADCONTEXT_HANDLE m_remoteThreadContextInfo;
  395. intptr_t m_prereservedRegionAddr;
  396. intptr_t m_jitThunkStartAddr;
  397. #if ENABLE_NATIVE_CODEGEN
  398. BVSparse<HeapAllocator> * m_jitNumericProperties;
  399. bool m_jitNeedsPropertyUpdate;
  400. public:
  401. intptr_t GetPreReservedRegionAddr()
  402. {
  403. return m_prereservedRegionAddr;
  404. }
  405. intptr_t GetJITThunkStartAddr()
  406. {
  407. return m_jitThunkStartAddr;
  408. }
  409. BVSparse<HeapAllocator> * GetJITNumericProperties() const
  410. {
  411. return m_jitNumericProperties;
  412. }
  413. bool JITNeedsPropUpdate() const
  414. {
  415. return m_jitNeedsPropertyUpdate;
  416. }
  417. void ResetJITNeedsPropUpdate()
  418. {
  419. m_jitNeedsPropertyUpdate = false;
  420. }
  421. static void SetJITConnectionInfo(HANDLE processHandle, void* serverSecurityDescriptor, UUID connectionId);
  422. bool EnsureJITThreadContext(bool allowPrereserveAlloc);
  423. PTHREADCONTEXT_HANDLE GetRemoteThreadContextAddr()
  424. {
  425. Assert(m_remoteThreadContextInfo);
  426. return m_remoteThreadContextInfo;
  427. }
  428. #endif
  429. private:
  430. typedef JsUtil::BaseDictionary<uint, Js::SourceDynamicProfileManager*, Recycler, PowerOf2SizePolicy> SourceDynamicProfileManagerMap;
  431. typedef JsUtil::BaseDictionary<Js::HashedCharacterBuffer<char16>*, const Js::PropertyRecord*, Recycler, PowerOf2SizePolicy, Js::PropertyRecordStringHashComparer> SymbolRegistrationMap;
  432. class SourceDynamicProfileManagerCache
  433. {
  434. public:
  435. SourceDynamicProfileManagerCache() : refCount(0), sourceProfileManagerMap(nullptr) {}
  436. Field(SourceDynamicProfileManagerMap*) sourceProfileManagerMap;
  437. void AddRef() { refCount++; }
  438. uint Release() { Assert(refCount > 0); return --refCount; }
  439. private:
  440. Field(uint) refCount; // For every script context using this cache, there is a ref count added.
  441. };
  442. typedef JsUtil::BaseDictionary<const WCHAR*, SourceDynamicProfileManagerCache*, Recycler, PowerOf2SizePolicy> SourceProfileManagersByUrlMap;
  443. struct RecyclableData
  444. {
  445. RecyclableData(Recycler *const recycler);
  446. Field(Js::TempArenaAllocatorObject *) temporaryArenaAllocators[MaxTemporaryArenaAllocators];
  447. Field(Js::TempGuestArenaAllocatorObject *) temporaryGuestArenaAllocators[MaxTemporaryArenaAllocators];
  448. Field(Js::JavascriptExceptionObject *) pendingFinallyException;
  449. Field(Js::JavascriptExceptionObject *) exceptionObject;
  450. Field(bool) propagateException;
  451. // We throw a JS catchable SO exception if we detect we might overflow the stack. Allocating this (JS)
  452. // object though might really overflow the stack. So use this thread global to identify them from the throw point
  453. // to where they are caught; where the stack has been unwound and it is safer to allocate the real exception
  454. // object and throw.
  455. Field(Js::JavascriptExceptionObject) soErrorObject;
  456. // We can't allocate an out of memory object... So use this static as a way to identify
  457. // them from the throw point to where they are caught.
  458. Field(Js::JavascriptExceptionObject) oomErrorObject;
  459. // This is for JsRT scenario where a runtime is not usable after a suspend request, before a resume runtime call is made
  460. Field(Js::JavascriptExceptionObject) terminatedErrorObject;
  461. Field(Js::JavascriptExceptionObject*) unhandledExceptionObject;
  462. // Used to temporarily keep throwing exception object alive (thrown but not yet caught)
  463. Field(Js::JavascriptExceptionObject*) tempUncaughtException;
  464. // Contains types that have property caches that need to be tracked, as the caches may need to be cleared. Types that
  465. // contain a property cache for a property that is on a prototype object will be tracked in this map since those caches
  466. // need to be cleared if for instance, the property is deleted from the prototype object.
  467. //
  468. // It is expected that over time, types that are deleted will eventually be removed by the weak reference hash sets when
  469. // they're searching through a bucket while registering a type or enumerating types to invalidate, or when a property ID
  470. // is reclaimed. If none of those happen, then this collection may contain weak reference handles to deleted objects
  471. // that would not get removed, but it would also not get any bigger.
  472. Field(PropertyIdToTypeHashSetDictionary) typesWithProtoPropertyCache;
  473. #if ENABLE_NATIVE_CODEGEN
  474. // The property guard dictionary contains property guards which need to be invalidated in response to properties changing
  475. // from writable to read-only and vice versa, properties being shadowed or unshadowed on prototypes, etc. The dictionary
  476. // holds only weak references to property guards and their lifetimes are controlled by their creators (typically entry points).
  477. // When a guard is no longer needed it is garbage collected, but the weak references and dictionary entries remain, until
  478. // the guards for a given property get invalidated.
  479. // TODO: Create and use a self-cleaning weak reference dictionary, which would periodically remove any unused weak references.
  480. Field(PropertyGuardDictionary) propertyGuards;
  481. #endif
  482. Field(PropertyNoCaseSetType *) caseInvariantPropertySet;
  483. Field(JsUtil::List<Js::PropertyRecord const*>*) boundPropertyStrings; // Recycler allocated list of property strings that we need to strongly reference so that they're not reclaimed
  484. Field(SourceProfileManagersByUrlMap*) sourceProfileManagersByUrl;
  485. // Used to register recyclable data that needs to be kept alive while jitting
  486. typedef JsUtil::DoublyLinkedList<Js::CodeGenRecyclableData, Recycler> CodeGenRecyclableDataList;
  487. Field(CodeGenRecyclableDataList) codeGenRecyclableDatas;
  488. // Used to root old entry points so that they're not prematurely collected
  489. Field(Js::FunctionEntryPointInfo*) oldEntryPointInfo;
  490. // Used to store a mapping of string to Symbol for cross-realm Symbol registration
  491. // See ES6 (draft 22) 19.4.2.2
  492. Field(SymbolRegistrationMap*) symbolRegistrationMap;
  493. #ifdef ENABLE_SCRIPT_DEBUGGING
  494. // Just holding the reference to the returnedValueList of the stepController. This way that list will not get recycled prematurely.
  495. Field(Js::ReturnedValueList *) returnedValueList;
  496. #endif
  497. Field(uint) constructorCacheInvalidationCount;
  498. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  499. // use for autoProxy called from Debug.setAutoProxyName. we need to keep the buffer from GetSz() alive.
  500. Field(LPCWSTR) autoProxyName;
  501. #endif
  502. };
  503. static ThreadContext * globalListLast;
  504. ThreadContextFlags threadContextFlags;
  505. DWORD currentThreadId;
  506. mutable size_t stackLimitForCurrentThread;
  507. StackProber * stackProber;
  508. bool isThreadBound;
  509. bool hasThrownPendingException;
  510. bool * hasBailedOutBitPtr;
  511. bool callDispose;
  512. #if ENABLE_JS_REENTRANCY_CHECK
  513. bool noJsReentrancy;
  514. #endif
  515. private:
  516. bool reentrancySafeOrHandled;
  517. bool isInReentrancySafeRegion;
  518. AllocationPolicyManager * allocationPolicyManager;
  519. JsUtil::ThreadService threadService;
  520. #if ENABLE_NATIVE_CODEGEN
  521. PreReservedVirtualAllocWrapper preReservedVirtualAllocator;
  522. #endif
  523. uint callRootLevel;
  524. #if ENABLE_BACKGROUND_PAGE_FREEING
  525. // The thread page allocator is used by the recycler and need the background page queue
  526. PageAllocator::BackgroundPageQueue backgroundPageQueue;
  527. #endif
  528. IdleDecommitPageAllocator pageAllocator;
  529. Recycler* recycler;
  530. // Fake RecyclerWeakReference for built-in properties
  531. class StaticPropertyRecordReference : public RecyclerWeakReference<const Js::PropertyRecord>
  532. {
  533. public:
  534. StaticPropertyRecordReference(const Js::PropertyRecord* propertyRecord)
  535. {
  536. strongRef = (char*)propertyRecord;
  537. strongRefHeapBlock = &CollectedRecyclerWeakRefHeapBlock::Instance;
  538. }
  539. };
  540. static const Js::PropertyRecord * const builtInPropertyRecords[];
  541. PropertyNoCaseSetType * caseInvariantPropertySet;
  542. Js::ScriptContext * rootPendingClose;
  543. JsUtil::List<IProjectionContext *, ArenaAllocator>* pendingProjectionContextCloseList;
  544. Js::ScriptEntryExitRecord * entryExitRecord;
  545. Js::InterpreterStackFrame* leafInterpreterFrame;
  546. const Js::PropertyRecord * propertyNamesDirect[128];
  547. ArenaAllocator threadAlloc;
  548. ThreadServiceWrapper* threadServiceWrapper;
  549. uint functionCount;
  550. uint sourceInfoCount;
  551. void * tryHandlerAddrOfReturnAddr;
  552. enum RedeferralState
  553. {
  554. InitialRedeferralState,
  555. StartupRedeferralState,
  556. MainRedeferralState
  557. };
  558. RedeferralState redeferralState;
  559. uint gcSinceLastRedeferral;
  560. uint gcSinceCallCountsCollected;
  561. static const uint InitialRedeferralDelay = 5;
  562. static const uint StartupRedeferralCheckInterval = 10;
  563. static const uint StartupRedeferralInactiveThreshold = 5;
  564. static const uint MainRedeferralCheckInterval = 20;
  565. static const uint MainRedeferralInactiveThreshold = 10;
  566. Js::TypeId nextTypeId;
  567. uint32 polymorphicCacheState;
  568. #ifdef ENABLE_PROJECTION
  569. SListBase<ExternalWeakReferenceCache *, HeapAllocator> externalWeakReferenceCacheList;
  570. #if DBG_DUMP
  571. IProjectionContextMemoryInfo *projectionMemoryInformation;
  572. #endif
  573. #endif
  574. #if ENABLE_NATIVE_CODEGEN
  575. JsUtil::JobProcessor *jobProcessor;
  576. Js::Var * bailOutRegisterSaveSpace;
  577. #if !FLOATVAR
  578. CodeGenNumberThreadAllocator * codeGenNumberThreadAllocator;
  579. XProcNumberPageSegmentManager * xProcNumberPageSegmentManager;
  580. #endif
  581. #if DYNAMIC_INTERPRETER_THUNK || defined(ASMJS_PLAT)
  582. CustomHeap::InProcCodePageAllocators thunkPageAllocators;
  583. #endif
  584. CustomHeap::InProcCodePageAllocators codePageAllocators;
  585. #if defined(_CONTROL_FLOW_GUARD) && !defined(_M_ARM)
  586. InProcJITThunkEmitter jitThunkEmitter;
  587. #endif
  588. #endif
  589. RecyclerRootPtr<RecyclableData> recyclableData;
  590. uint temporaryArenaAllocatorCount;
  591. uint temporaryGuestArenaAllocatorCount;
  592. #if DBG_DUMP || defined(PROFILE_EXEC)
  593. ScriptSite* topLevelScriptSite;
  594. #endif
  595. Js::ScriptContext *scriptContextList;
  596. bool scriptContextEverRegistered;
  597. static size_t processNativeCodeSize;
  598. size_t nativeCodeSize;
  599. size_t sourceCodeSize;
  600. DateTime::HiResTimer hTimer;
  601. int stackProbeCount;
  602. // Count stack probes and poll for continuation every n probes
  603. static const int StackProbePollThreshold = 1000;
  604. EXCEPTION_POINTERS exceptionInfo;
  605. uint32 exceptionCode;
  606. ArenaAllocator inlineCacheThreadInfoAllocator;
  607. ArenaAllocator isInstInlineCacheThreadInfoAllocator;
  608. ArenaAllocator equivalentTypeCacheInfoAllocator;
  609. DListBase<Js::EntryPointInfo *> equivalentTypeCacheEntryPoints;
  610. typedef SList<Js::InlineCache*> InlineCacheList;
  611. typedef JsUtil::BaseDictionary<Js::PropertyId, InlineCacheList*, ArenaAllocator, PrimeSizePolicy> InlineCacheListMapByPropertyId;
  612. InlineCacheListMapByPropertyId protoInlineCacheByPropId;
  613. InlineCacheListMapByPropertyId storeFieldInlineCacheByPropId;
  614. uint registeredInlineCacheCount;
  615. uint unregisteredInlineCacheCount;
  616. #if DBG
  617. uint totalUnregisteredCacheCount;
  618. uint arrayMutationSeed; // This is mostly to aid in debugging.
  619. #endif
  620. typedef JsUtil::BaseDictionary<Js::Var, Js::IsInstInlineCache*, ArenaAllocator, PrimeSizePolicy> IsInstInlineCacheListMapByFunction;
  621. IsInstInlineCacheListMapByFunction isInstInlineCacheByFunction;
  622. Js::IsConcatSpreadableCache isConcatSpreadableCache;
  623. Js::NoSpecialPropertyThreadRegistry noSpecialPropertyRegistry;
  624. Js::OnlyWritablePropertyThreadRegistry onlyWritablePropertyRegistry;
  625. DListBase<CollectCallBack> collectCallBackList;
  626. CriticalSection csCollectionCallBack;
  627. bool hasCollectionCallBack;
  628. bool isOptimizedForManyInstances;
  629. bool bgJit;
  630. // We report library code to profiler only if called directly by user code. Not if called by library implementation.
  631. bool isProfilingUserCode;
  632. void* jsrtRuntime;
  633. bool hasUnhandledException;
  634. bool hasCatchHandler;
  635. DisableImplicitFlags disableImplicitFlags;
  636. // Used for identifying that any particular time, the caller chain has try/catch blocks belong to the user code.
  637. // If all try/catch blocks in the current stack marked as non-user code then this member will remain false.
  638. bool hasCatchHandlerToUserCode;
  639. #ifdef ENABLE_GLOBALIZATION
  640. Js::DelayLoadWinRtString delayLoadWinRtString;
  641. #ifdef ENABLE_PROJECTION
  642. Js::DelayLoadWinRtError delayLoadWinRtError;
  643. Js::DelayLoadWinRtTypeResolution delayLoadWinRtTypeResolution;
  644. Js::DelayLoadWinRtRoParameterizedIID delayLoadWinRtRoParameterizedIID;
  645. #endif
  646. #if defined(ENABLE_INTL_OBJECT) || defined(ENABLE_ES6_CHAR_CLASSIFIER)
  647. #ifdef INTL_WINGLOB
  648. Js::DelayLoadWindowsGlobalization delayLoadWindowsGlobalizationLibrary;
  649. Js::WindowsGlobalizationAdapter windowsGlobalizationAdapter;
  650. #endif
  651. #endif
  652. #ifdef ENABLE_FOUNDATION_OBJECT
  653. Js::DelayLoadWinRtFoundation delayLoadWinRtFoundationLibrary;
  654. Js::WindowsFoundationAdapter windowsFoundationAdapter;
  655. #endif
  656. #endif
  657. // Number of script context attached with probe manager.
  658. // This counter will be used as addref when the script context is created, this way we maintain the life of diagnostic object.
  659. // Once no script context available , diagnostic will go away.
  660. LONG crefSContextForDiag;
  661. Entropy entropy;
  662. JsUtil::Stack<HostScriptContext*>* hostScriptContextStack;
  663. //
  664. // Regex globals
  665. //
  666. UnifiedRegex::StandardChars<uint8>* standardUTF8Chars;
  667. UnifiedRegex::StandardChars<char16>* standardUnicodeChars;
  668. Js::ImplicitCallFlags implicitCallFlags;
  669. THREAD_LOCAL static uint activeScriptSiteCount;
  670. bool isScriptActive;
  671. // When ETW rundown in background thread which needs to walk scriptContext/functionBody/entryPoint lists,
  672. // or when JIT thread is getting auxPtrs from function body, we should not be modifying the list of
  673. // functionBody/entrypoints, or expanding the auxPtrs
  674. CriticalSection csFunctionBody;
  675. #ifdef _M_X64
  676. friend class Js::Amd64StackFrame;
  677. Js::Amd64ContextsManager amd64ContextsManager;
  678. Js::Amd64ContextsManager* GetAmd64ContextsManager() { return &amd64ContextsManager; }
  679. #endif
  680. typedef JsUtil::BaseDictionary<Js::DynamicType const *, void *, HeapAllocator, PowerOf2SizePolicy> DynamicObjectEnumeratorCacheMap;
  681. DynamicObjectEnumeratorCacheMap dynamicObjectEnumeratorCacheMap;
  682. #ifdef NTBUILD
  683. ThreadContextWatsonTelemetryBlock localTelemetryBlock;
  684. ThreadContextWatsonTelemetryBlock * telemetryBlock;
  685. #endif
  686. NativeLibraryEntryRecord nativeLibraryEntry;
  687. UCrtC99MathApis ucrtC99MathApis;
  688. // Indicates the current loop depth as observed by the interpreter. The interpreter causes this value to be updated upon
  689. // entering and leaving a loop.
  690. uint8 loopDepth;
  691. const ThreadConfiguration configuration;
  692. public:
  693. static ThreadContext * globalListFirst;
  694. static uint GetScriptSiteHolderCount() { return activeScriptSiteCount; }
  695. static uint IncrementActiveScriptSiteCount() { return ++activeScriptSiteCount; }
  696. static uint DecrementActiveScriptSiteCount() { return --activeScriptSiteCount; }
  697. static ThreadContext * GetThreadContextList() { return globalListFirst; }
  698. void ValidateThreadContext();
  699. bool IsInScript() const { return callRootLevel != 0; }
  700. uint GetCallRootLevel() const { return callRootLevel; }
  701. PageAllocator * GetPageAllocator() { return &pageAllocator; }
  702. AllocationPolicyManager * GetAllocationPolicyManager() { return allocationPolicyManager; }
  703. // used for diagnosing abnormally high number of closed, but still formally reachable script contexts
  704. // at the time of failfast due to allocation limits.
  705. // high number may indicate that context leaks have occured.
  706. uint closedScriptContextCount;
  707. enum VisibilityState : BYTE
  708. {
  709. Undefined = 0,
  710. Visible = 1,
  711. NotVisible = 2
  712. };
  713. // indicates the visibility state of the hosting application/window/tab if known.
  714. VisibilityState visibilityState;
  715. #if ENABLE_NATIVE_CODEGEN
  716. PreReservedVirtualAllocWrapper * GetPreReservedVirtualAllocator() { return &preReservedVirtualAllocator; }
  717. #if DYNAMIC_INTERPRETER_THUNK || defined(ASMJS_PLAT)
  718. CustomHeap::InProcCodePageAllocators * GetThunkPageAllocators() { return &thunkPageAllocators; }
  719. #endif
  720. CustomHeap::InProcCodePageAllocators * GetCodePageAllocators() { return &codePageAllocators; }
  721. #if defined(_CONTROL_FLOW_GUARD) && !defined(_M_ARM)
  722. InProcJITThunkEmitter * GetJITThunkEmitter() { return &jitThunkEmitter; }
  723. #endif
  724. #endif // ENABLE_NATIVE_CODEGEN
  725. CriticalSection* GetFunctionBodyLock() { return &csFunctionBody; }
  726. UCrtC99MathApis* GetUCrtC99MathApis() { return &ucrtC99MathApis; }
  727. Js::IsConcatSpreadableCache* GetIsConcatSpreadableCache() { return &isConcatSpreadableCache; }
  728. #ifdef ENABLE_GLOBALIZATION
  729. Js::DelayLoadWinRtString *GetWinRTStringLibrary();
  730. #ifdef ENABLE_PROJECTION
  731. Js::DelayLoadWinRtError *GetWinRTErrorLibrary();
  732. Js::DelayLoadWinRtTypeResolution* GetWinRTTypeResolutionLibrary();
  733. Js::DelayLoadWinRtRoParameterizedIID* GetWinRTRoParameterizedIIDLibrary();
  734. #endif
  735. #if defined(ENABLE_INTL_OBJECT) || defined(ENABLE_ES6_CHAR_CLASSIFIER)
  736. #ifdef INTL_WINGLOB
  737. Js::DelayLoadWindowsGlobalization *GetWindowsGlobalizationLibrary();
  738. Js::WindowsGlobalizationAdapter *GetWindowsGlobalizationAdapter();
  739. #endif
  740. #endif
  741. #ifdef ENABLE_FOUNDATION_OBJECT
  742. Js::DelayLoadWinRtFoundation *GetWinRtFoundationLibrary();
  743. Js::WindowsFoundationAdapter *GetWindowsFoundationAdapter();
  744. #endif
  745. #endif
  746. void SetAbnormalExceptionRecord(EXCEPTION_POINTERS *exceptionInfo) { this->exceptionInfo = *exceptionInfo; }
  747. void SetAbnormalExceptionCode(uint32 exceptionInfo) { this->exceptionCode = exceptionInfo; }
  748. uint32 GetAbnormalExceptionCode() const { return this->exceptionCode; }
  749. #ifdef ENABLE_BASIC_TELEMETRY
  750. GUID activityId;
  751. LPFILETIME GetLastScriptExecutionEndTime() const;
  752. #endif
  753. void *tridentLoadAddress;
  754. void* GetTridentLoadAddress() const { return tridentLoadAddress; }
  755. void SetTridentLoadAddress(void *loadAddress) { tridentLoadAddress = loadAddress; }
  756. Js::NoSpecialPropertyThreadRegistry* GetNoSpecialPropertyRegistry() { return &this->noSpecialPropertyRegistry; }
  757. Js::OnlyWritablePropertyThreadRegistry* GetOnlyWritablePropertyRegistry() { return &this->onlyWritablePropertyRegistry; }
  758. #ifdef ENABLE_DIRECTCALL_TELEMETRY
  759. DirectCallTelemetry directCallTelemetry;
  760. #endif
  761. BOOL HasPreviousHostScriptContext();
  762. HostScriptContext* GetPreviousHostScriptContext() ;
  763. void PushHostScriptContext(HostScriptContext* topProvider);
  764. HostScriptContext* PopHostScriptContext();
  765. void SetInterruptPoller(InterruptPoller *poller) { interruptPoller = poller; }
  766. InterruptPoller *GetInterruptPoller() const { return interruptPoller; }
  767. BOOL HasInterruptPoller() const { return interruptPoller != nullptr; }
  768. void CheckScriptInterrupt();
  769. void CheckInterruptPoll();
  770. bool DoInterruptProbe(Js::FunctionBody *const func) const
  771. {
  772. return
  773. (this->TestThreadContextFlag(ThreadContextFlagCanDisableExecution) &&
  774. !PHASE_OFF(Js::InterruptProbePhase, func)) ||
  775. PHASE_ON(Js::InterruptProbePhase, func);
  776. }
  777. bool DoInterruptProbe() const
  778. {
  779. return
  780. (this->TestThreadContextFlag(ThreadContextFlagCanDisableExecution) &&
  781. !PHASE_OFF1(Js::InterruptProbePhase)) ||
  782. PHASE_ON1(Js::InterruptProbePhase);
  783. }
  784. bool EvalDisabled() const
  785. {
  786. return this->TestThreadContextFlag(ThreadContextFlagEvalDisabled);
  787. }
  788. bool NoJIT() const
  789. {
  790. return this->TestThreadContextFlag(ThreadContextFlagNoJIT);
  791. }
  792. bool NoDynamicThunks() const
  793. {
  794. return this->TestThreadContextFlag(ThreadContextFlagNoDynamicThunks);
  795. }
  796. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  797. Js::Var GetMemoryStat(Js::ScriptContext* scriptContext);
  798. void SetAutoProxyName(LPCWSTR objectName);
  799. LPCWSTR GetAutoProxyName() const { return recyclableData->autoProxyName; }
  800. Js::PropertyId handlerPropertyId = Js::Constants::NoProperty;
  801. #endif
  802. #ifdef ENABLE_SCRIPT_DEBUGGING
  803. void SetReturnedValueList(Js::ReturnedValueList *returnedValueList)
  804. {
  805. Assert(this->recyclableData != nullptr);
  806. this->recyclableData->returnedValueList = returnedValueList;
  807. }
  808. #if DBG
  809. void EnsureNoReturnedValueList()
  810. {
  811. Assert(this->recyclableData == nullptr || this->recyclableData->returnedValueList == nullptr);
  812. }
  813. #endif
  814. #endif
  815. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  816. uint GetScriptContextCount() const { return this->scriptContextCount; }
  817. #endif
  818. Js::ScriptContext* GetScriptContextList() const { return this->scriptContextList; }
  819. bool WasAnyScriptContextEverRegistered() const { return this->scriptContextEverRegistered; }
  820. #if DBG_DUMP || defined(PROFILE_EXEC)
  821. void SetTopLevelScriptSite(ScriptSite* topScriptSite) { this->topLevelScriptSite = topScriptSite; }
  822. ScriptSite* GetTopLevelScriptSite () { return this->topLevelScriptSite; }
  823. #endif
  824. #if DBG || defined(PROFILE_EXEC)
  825. virtual bool AsyncHostOperationStart(void *) override;
  826. virtual void AsyncHostOperationEnd(bool wasInAsync, void *) override;
  827. #endif
  828. #if DBG
  829. virtual void CheckJsReentrancyOnDispose() override;
  830. bool IsInAsyncHostOperation() const;
  831. #endif
  832. #if ENABLE_TTD
  833. //The class that holds info on the TTD state for the thread context
  834. TTD::ThreadContextTTD* TTDContext;
  835. //The class that holds information on TTD <-> debugger interaction state
  836. TTD::ExecutionInfoManager* TTDExecutionInfo;
  837. //The event log for time-travel (or null if TTD is not turned on)
  838. TTD::EventLog* TTDLog;
  839. //Keep track of the number of re-entrant calls currently pending (i.e., if we make an external call it may call back into Chakra)
  840. int32 TTDRootNestingCount;
  841. bool IsRuntimeInTTDMode() const
  842. {
  843. return this->TTDLog != nullptr;
  844. }
  845. //Initialize the context for time-travel
  846. void InitTimeTravel(ThreadContext* threadContext, void* runtimeHandle, uint32 snapInterval, uint32 snapHistoryLength);
  847. void InitHostFunctionsAndTTData(bool record, bool replay, bool debug, size_t optTTUriLength, const char* optTTUri,
  848. TTD::TTDOpenResourceStreamCallback openResourceStreamfp, TTD::TTDReadBytesFromStreamCallback readBytesFromStreamfp,
  849. TTD::TTDWriteBytesToStreamCallback writeBytesToStreamfp, TTD::TTDFlushAndCloseStreamCallback flushAndCloseStreamfp,
  850. TTD::TTDCreateExternalObjectCallback createExternalObjectfp,
  851. TTD::TTDCreateJsRTContextCallback createJsRTContextCallbackfp, TTD::TTDReleaseJsRTContextCallback releaseJsRTContextCallbackfp, TTD::TTDSetActiveJsRTContext fpSetActiveJsRTContext);
  852. #endif
  853. BOOL ReserveStaticTypeIds(__in int first, __in int last);
  854. Js::TypeId ReserveTypeIds(int count);
  855. Js::TypeId CreateTypeId();
  856. Js::TypeId GetNextTypeId() { return nextTypeId; }
  857. // Lookup the well known type registered with a Js::TypeId.
  858. // wellKnownType: The well known type which we should register
  859. // typeId: The type id to match
  860. // returns: true if the typeid is the wellKnownType
  861. template<WellKnownHostType wellKnownType>
  862. bool IsWellKnownHostType(Js::TypeId typeId)
  863. {
  864. CompileAssert(wellKnownType <= WellKnownHostType_Last);
  865. return wellKnownHostTypeIds[wellKnownType] == typeId;
  866. }
  867. // Register a well known type to a Js::TypeId.
  868. // wellKnownType: The well known type which we should register
  869. // typeId: The type id which matches to the well known type
  870. void SetWellKnownHostTypeId(WellKnownHostType wellKnownType, Js::TypeId typeId);
  871. uint32 GetNextPolymorphicCacheState()
  872. {
  873. return ++polymorphicCacheState;
  874. };
  875. ~ThreadContext();
  876. void CloseForJSRT();
  877. //Call back is called for one or more handles
  878. //It does multiple callbacks (For example: separate call back for GC thread handle & JIT thread handles)
  879. // template<class Fn>
  880. //void ShutdownThreads(Fn callback);
  881. void ShutdownThreads()
  882. {
  883. #if ENABLE_NATIVE_CODEGEN
  884. if (jobProcessor)
  885. {
  886. jobProcessor->Close();
  887. }
  888. if (JITManager::GetJITManager()->IsOOPJITEnabled() && JITManager::GetJITManager()->IsConnected() && m_remoteThreadContextInfo)
  889. {
  890. if (JITManager::GetJITManager()->CleanupThreadContext(&m_remoteThreadContextInfo) == S_OK)
  891. {
  892. Assert(m_remoteThreadContextInfo == nullptr);
  893. }
  894. m_remoteThreadContextInfo = nullptr;
  895. }
  896. #endif
  897. #if ENABLE_CONCURRENT_GC
  898. if (this->recycler != nullptr)
  899. {
  900. this->recycler->ShutdownThread();
  901. }
  902. #endif
  903. }
  904. DateTime::HiResTimer * GetHiResTimer() { return &hTimer; }
  905. ArenaAllocator* GetThreadAlloc() { return &threadAlloc; }
  906. static CriticalSection * GetCriticalSection() { return &s_csThreadContext; }
  907. ThreadContext(AllocationPolicyManager * allocationPolicyManager = nullptr, JsUtil::ThreadService::ThreadServiceCallback threadServiceCallback = nullptr, bool enableExperimentalFeatures = false);
  908. static void Add(ThreadContext *threadContext);
  909. ThreadConfiguration const * GetConfig() const { return &configuration; }
  910. public:
  911. #ifdef NTBUILD
  912. void SetTelemetryBlock(ThreadContextWatsonTelemetryBlock * telemetryBlock) { this->telemetryBlock = telemetryBlock; }
  913. #endif
  914. static ThreadContext* GetContextForCurrentThread();
  915. Recycler* GetRecycler() { return recycler; }
  916. Recycler* EnsureRecycler();
  917. ThreadContext::CollectCallBack * AddRecyclerCollectCallBack(RecyclerCollectCallBackFunction callback, void * context);
  918. void RemoveRecyclerCollectCallBack(ThreadContext::CollectCallBack * collectCallBack);
  919. void AddToPendingProjectionContextCloseList(IProjectionContext *projectionContext);
  920. void RemoveFromPendingClose(IProjectionContext *projectionContext);
  921. void ClosePendingProjectionContexts();
  922. void AddToPendingScriptContextCloseList(Js::ScriptContext * scriptContext);
  923. void RemoveFromPendingClose(Js::ScriptContext * scriptContext);
  924. void ClosePendingScriptContexts();
  925. Js::PropertyRecord const * GetPropertyName(Js::PropertyId propertyId);
  926. Js::PropertyRecord const * GetPropertyNameLocked(Js::PropertyId propertyId);
  927. private:
  928. template <bool locked> Js::PropertyRecord const * GetPropertyNameImpl(Js::PropertyId propertyId);
  929. public:
  930. void FindPropertyRecord(Js::JavascriptString *pstName, Js::PropertyRecord const ** propertyRecord);
  931. void FindPropertyRecord(__in LPCWCH propertyName, __in int propertyNameLength, Js::PropertyRecord const ** propertyRecord);
  932. const Js::PropertyRecord * FindPropertyRecord(const char16 * propertyName, int propertyNameLength);
  933. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>* FindPropertyIdNoCase(Js::ScriptContext * scriptContext, LPCWSTR propertyName, int propertyNameLength);
  934. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>* FindPropertyIdNoCase(Js::ScriptContext * scriptContext, JsUtil::CharacterBuffer<WCHAR> const& propertyName);
  935. bool FindExistingPropertyRecord(_In_ JsUtil::CharacterBuffer<WCHAR> const& propertyName, Js::CaseInvariantPropertyListWithHashCode** propertyRecord);
  936. void CleanNoCasePropertyMap();
  937. void ForceCleanPropertyMap();
  938. const Js::PropertyRecord * GetOrAddPropertyRecord(JsUtil::CharacterBuffer<char16> propertyName)
  939. {
  940. return GetOrAddPropertyRecordImpl(propertyName, false);
  941. }
  942. const Js::PropertyRecord * GetOrAddPropertyRecordBind(JsUtil::CharacterBuffer<char16> propertyName)
  943. {
  944. return GetOrAddPropertyRecordImpl(propertyName, true);
  945. }
  946. void AddBuiltInPropertyRecord(const Js::PropertyRecord *propertyRecord);
  947. void GetOrAddPropertyId(_In_ LPCWSTR propertyName, _In_ int propertyNameLength, _Out_ Js::PropertyRecord const** propertyRecord);
  948. void GetOrAddPropertyId(_In_ JsUtil::CharacterBuffer<WCHAR> const& propertyName, _Out_ Js::PropertyRecord const** propertyRecord);
  949. Js::PropertyRecord const * UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR> const& propertyName, bool bind, bool isSymbol = false);
  950. Js::PropertyRecord const * UncheckedAddPropertyId(__in LPCWSTR propertyName, __in int propertyNameLength, bool bind = false, bool isSymbol = false);
  951. #ifdef ENABLE_JS_ETW
  952. void EtwLogPropertyIdList();
  953. #endif
  954. private:
  955. const Js::PropertyRecord * GetOrAddPropertyRecordImpl(JsUtil::CharacterBuffer<char16> propertyName, bool bind);
  956. void AddPropertyRecordInternal(const Js::PropertyRecord * propertyRecord);
  957. void BindPropertyRecord(const Js::PropertyRecord * propertyRecord);
  958. bool IsDirectPropertyName(const char16 * propertyName, int propertyNameLength);
  959. RecyclerWeakReference<const Js::PropertyRecord> * CreatePropertyRecordWeakRef(const Js::PropertyRecord * propertyRecord);
  960. void AddCaseInvariantPropertyRecord(const Js::PropertyRecord * propertyRecord);
  961. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  962. uint scriptContextCount;
  963. #endif
  964. public:
  965. void UncheckedAddBuiltInPropertyId();
  966. BOOL IsNumericPropertyId(Js::PropertyId propertyId, uint32* value);
  967. bool IsActivePropertyId(Js::PropertyId pid);
  968. void InvalidatePropertyRecord(const Js::PropertyRecord * propertyRecord);
  969. Js::PropertyId GetNextPropertyId();
  970. Js::PropertyId GetMaxPropertyId();
  971. uint GetHighestPropertyNameIndex() const;
  972. void SetThreadServiceWrapper(ThreadServiceWrapper*);
  973. ThreadServiceWrapper* GetThreadServiceWrapper();
  974. #ifdef ENABLE_PROJECTION
  975. void AddExternalWeakReferenceCache(ExternalWeakReferenceCache *externalWeakReferenceCache);
  976. void RemoveExternalWeakReferenceCache(ExternalWeakReferenceCache *externalWeakReferenceCache);
  977. virtual void MarkExternalWeakReferencedObjects(bool inPartialCollect) override;
  978. virtual void ResolveExternalWeakReferencedObjects() override;
  979. #if DBG_DUMP
  980. void RegisterProjectionMemoryInformation(IProjectionContextMemoryInfo* projectionContextMemoryInfo);
  981. void DumpProjectionContextMemoryStats(LPCWSTR headerMsg, bool forceDetailed = false);
  982. IProjectionContextMemoryInfo* GetProjectionContextMemoryInformation();
  983. #endif
  984. #endif
  985. uint NewFunctionNumber() { return ++functionCount; }
  986. uint PeekNewFunctionNumber() { return functionCount + 1; }
  987. uint NewSourceInfoNumber() { return ++sourceInfoCount; }
  988. void AddCodeSize(size_t newCode)
  989. {
  990. ::InterlockedExchangeAdd(&nativeCodeSize, newCode);
  991. ::InterlockedExchangeAdd(&processNativeCodeSize, newCode);
  992. }
  993. void AddSourceSize(size_t newCode) { sourceCodeSize += newCode; }
  994. void SubCodeSize(size_t deadCode)
  995. {
  996. Assert(nativeCodeSize >= deadCode);
  997. Assert(processNativeCodeSize >= deadCode);
  998. ::InterlockedExchangeSubtract(&nativeCodeSize, deadCode);
  999. ::InterlockedExchangeSubtract(&processNativeCodeSize, deadCode);
  1000. }
  1001. void SubSourceSize(size_t deadCode) { Assert(sourceCodeSize >= deadCode); sourceCodeSize -= deadCode; }
  1002. size_t GetCodeSize() { return nativeCodeSize; }
  1003. static size_t GetProcessCodeSize() { return processNativeCodeSize; }
  1004. size_t GetSourceSize() { return sourceCodeSize; }
  1005. bool DoTryRedeferral() const;
  1006. void TryRedeferral();
  1007. bool DoRedeferFunctionBodies() const;
  1008. void UpdateRedeferralState();
  1009. uint GetRedeferralCollectionInterval() const;
  1010. uint GetRedeferralInactiveThreshold() const;
  1011. void GetActiveFunctions(ActiveFunctionSet * pActive);
  1012. #if DBG
  1013. uint redeferredFunctions;
  1014. uint recoveredBytes;
  1015. #endif
  1016. Js::ScriptEntryExitRecord * GetScriptEntryExit() const { return entryExitRecord; }
  1017. void RegisterCodeGenRecyclableData(Js::CodeGenRecyclableData *const codeGenRecyclableData);
  1018. void UnregisterCodeGenRecyclableData(Js::CodeGenRecyclableData *const codeGenRecyclableData);
  1019. #if ENABLE_NATIVE_CODEGEN
  1020. bool IsNativeAddressHelper(void * pCodeAddr, Js::ScriptContext* currentScriptContext);
  1021. BOOL IsNativeAddress(void * pCodeAddr, Js::ScriptContext* currentScriptContext = nullptr);
  1022. JsUtil::JobProcessor *GetJobProcessor();
  1023. Js::Var * GetBailOutRegisterSaveSpace() const { return bailOutRegisterSaveSpace; }
  1024. virtual intptr_t GetBailOutRegisterSaveSpaceAddr() const override { return (intptr_t)bailOutRegisterSaveSpace; }
  1025. #if !FLOATVAR
  1026. CodeGenNumberThreadAllocator * GetCodeGenNumberThreadAllocator() const
  1027. {
  1028. return codeGenNumberThreadAllocator;
  1029. }
  1030. XProcNumberPageSegmentManager * GetXProcNumberPageSegmentManager() const
  1031. {
  1032. return this->xProcNumberPageSegmentManager;
  1033. }
  1034. #endif
  1035. #endif
  1036. void ResetFunctionCount() { Assert(this->GetScriptSiteHolderCount() == 0); this->functionCount = 0; }
  1037. void PushEntryExitRecord(Js::ScriptEntryExitRecord *);
  1038. void PopEntryExitRecord(Js::ScriptEntryExitRecord *);
  1039. uint EnterScriptStart(Js::ScriptEntryExitRecord *, bool doCleanup);
  1040. void EnterScriptEnd(Js::ScriptEntryExitRecord *, bool doCleanup);
  1041. void * GetTryHandlerAddrOfReturnAddr() { return this->tryHandlerAddrOfReturnAddr; }
  1042. void SetTryHandlerAddrOfReturnAddr(void * addrOfReturnAddr) { this->tryHandlerAddrOfReturnAddr = addrOfReturnAddr; }
  1043. template <bool leaveForHost>
  1044. void LeaveScriptStart(void *);
  1045. template <bool leaveForHost>
  1046. void LeaveScriptEnd(void *);
  1047. void DisposeOnLeaveScript();
  1048. void PushInterpreterFrame(Js::InterpreterStackFrame *interpreterFrame);
  1049. Js::InterpreterStackFrame *PopInterpreterFrame();
  1050. Js::InterpreterStackFrame *GetLeafInterpreterFrame() const { return leafInterpreterFrame; }
  1051. Js::TempArenaAllocatorObject * GetTemporaryAllocator(LPCWSTR name);
  1052. void ReleaseTemporaryAllocator(Js::TempArenaAllocatorObject * tempAllocator);
  1053. Js::TempGuestArenaAllocatorObject * GetTemporaryGuestAllocator(LPCWSTR name);
  1054. void ReleaseTemporaryGuestAllocator(Js::TempGuestArenaAllocatorObject * tempAllocator);
  1055. #ifdef ENABLE_SCRIPT_DEBUGGING
  1056. // Should be called from script context, at the time when construction for scriptcontext is just done.
  1057. void EnsureDebugManager();
  1058. // Should be called from script context 's destructor,
  1059. void ReleaseDebugManager();
  1060. #endif
  1061. void RegisterScriptContext(Js::ScriptContext *scriptContext);
  1062. void UnregisterScriptContext(Js::ScriptContext *scriptContext);
  1063. // NoScriptScope
  1064. void SetNoScriptScope(bool noScriptScope) { this->noScriptScope = noScriptScope; }
  1065. bool IsNoScriptScope() { return this->noScriptScope; }
  1066. void SetPendingFinallyException(Js::JavascriptExceptionObject * exceptionObj)
  1067. {
  1068. recyclableData->pendingFinallyException = exceptionObj;
  1069. }
  1070. Js::JavascriptExceptionObject * GetPendingFinallyException()
  1071. {
  1072. return recyclableData->pendingFinallyException;
  1073. }
  1074. Js::EntryPointInfo ** RegisterEquivalentTypeCacheEntryPoint(Js::EntryPointInfo * entryPoint);
  1075. void UnregisterEquivalentTypeCacheEntryPoint(Js::EntryPointInfo ** entryPoint);
  1076. void RegisterProtoInlineCache(Js::InlineCache * inlineCache, Js::PropertyId propertyId);
  1077. void RegisterStoreFieldInlineCache(Js::InlineCache * inlineCache, Js::PropertyId propertyId);
  1078. void NotifyInlineCacheBatchUnregistered(uint count);
  1079. #if DBG
  1080. bool IsProtoInlineCacheRegistered(const Js::InlineCache * inlineCache, Js::PropertyId propertyId);
  1081. bool IsStoreFieldInlineCacheRegistered(const Js::InlineCache * inlineCache, Js::PropertyId propertyId);
  1082. #endif
  1083. #if ENABLE_NATIVE_CODEGEN
  1084. Js::PropertyGuard* RegisterSharedPropertyGuard(Js::PropertyId propertyId);
  1085. void RegisterLazyBailout(Js::PropertyId propertyId, Js::EntryPointInfo* entryPoint);
  1086. void RegisterUniquePropertyGuard(Js::PropertyId propertyId, Js::PropertyGuard* guard);
  1087. void RegisterUniquePropertyGuard(Js::PropertyId propertyId, RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef);
  1088. void RegisterConstructorCache(Js::PropertyId propertyId, Js::ConstructorCache* cache);
  1089. #endif
  1090. virtual size_t GetScriptStackLimit() const override;
  1091. virtual HANDLE GetProcessHandle() const override;
  1092. virtual intptr_t GetThreadStackLimitAddr() const override;
  1093. #if ENABLE_NATIVE_CODEGEN && defined(ENABLE_WASM_SIMD)
  1094. virtual intptr_t GetSimdTempAreaAddr(uint8 tempIndex) const override;
  1095. #endif
  1096. virtual intptr_t GetDisableImplicitFlagsAddr() const override;
  1097. virtual intptr_t GetImplicitCallFlagsAddr() const override;
  1098. virtual ptrdiff_t GetChakraBaseAddressDifference() const override;
  1099. virtual ptrdiff_t GetCRTBaseAddressDifference() const override;
  1100. private:
  1101. void RegisterInlineCache(InlineCacheListMapByPropertyId& inlineCacheMap, Js::InlineCache* inlineCache, Js::PropertyId propertyId);
  1102. static bool IsInlineCacheRegistered(InlineCacheListMapByPropertyId& inlineCacheMap, const Js::InlineCache* inlineCache, Js::PropertyId propertyId);
  1103. void InvalidateAndDeleteInlineCacheList(InlineCacheList *inlineCacheList);
  1104. void CompactInlineCacheList(InlineCacheList *inlineCacheList);
  1105. void CompactInlineCacheInvalidationLists();
  1106. void CompactProtoInlineCaches();
  1107. void CompactStoreFieldInlineCaches();
  1108. #if DBG
  1109. static bool IsInlineCacheInList(const Js::InlineCache* inlineCache, const InlineCacheList* inlineCacheChain);
  1110. #endif
  1111. #if ENABLE_NATIVE_CODEGEN
  1112. void InvalidateFixedFieldGuard(Js::PropertyGuard* guard);
  1113. PropertyGuardEntry* EnsurePropertyGuardEntry(const Js::PropertyRecord* propertyRecord, bool& foundExistingEntry);
  1114. void InvalidatePropertyGuardEntry(const Js::PropertyRecord* propertyRecord, PropertyGuardEntry* entry, bool isAllPropertyGuardsInvalidation);
  1115. #endif
  1116. public:
  1117. class AutoDisableExpiration
  1118. {
  1119. public:
  1120. AutoDisableExpiration(ThreadContext* threadContext):
  1121. _threadContext(threadContext),
  1122. _oldExpirationDisabled(threadContext->disableExpiration)
  1123. {
  1124. _threadContext->disableExpiration = true;
  1125. }
  1126. ~AutoDisableExpiration()
  1127. {
  1128. _threadContext->disableExpiration = _oldExpirationDisabled;
  1129. }
  1130. private:
  1131. ThreadContext* _threadContext;
  1132. bool _oldExpirationDisabled;
  1133. };
  1134. void InvalidateProtoInlineCaches(Js::PropertyId propertyId);
  1135. void InvalidateStoreFieldInlineCaches(Js::PropertyId propertyId);
  1136. void InvalidateAllProtoInlineCaches();
  1137. #if DBG
  1138. bool IsObjectRegisteredInProtoInlineCaches(Js::DynamicObject * object);
  1139. bool IsObjectRegisteredInStoreFieldInlineCaches(Js::DynamicObject * object);
  1140. #endif
  1141. bool AreAllProtoInlineCachesInvalidated();
  1142. void InvalidateAllStoreFieldInlineCaches();
  1143. bool AreAllStoreFieldInlineCachesInvalidated();
  1144. void InvalidatePropertyGuards(Js::PropertyId propertyId);
  1145. void InvalidateAllPropertyGuards();
  1146. void RegisterIsInstInlineCache(Js::IsInstInlineCache * inlineCache, Js::Var function);
  1147. void UnregisterIsInstInlineCache(Js::IsInstInlineCache * inlineCache, Js::Var function);
  1148. #if DBG
  1149. bool IsIsInstInlineCacheRegistered(Js::IsInstInlineCache * inlineCache, Js::Var function);
  1150. #endif
  1151. private:
  1152. void InvalidateIsInstInlineCacheList(Js::IsInstInlineCache* inlineCacheList);
  1153. #if DBG
  1154. bool IsIsInstInlineCacheInList(const Js::IsInstInlineCache* inlineCache, const Js::IsInstInlineCache* inlineCacheList);
  1155. #endif
  1156. public:
  1157. void InvalidateIsInstInlineCachesForFunction(Js::Var function);
  1158. void InvalidateAllIsInstInlineCaches();
  1159. bool AreAllIsInstInlineCachesInvalidated() const;
  1160. #ifdef PERSISTENT_INLINE_CACHES
  1161. void ClearInlineCachesWithDeadWeakRefs();
  1162. #endif
  1163. void ClearInvalidatedUniqueGuards();
  1164. void ClearInlineCaches();
  1165. void ClearIsInstInlineCaches();
  1166. void ClearEnumeratorCaches();
  1167. void ClearEquivalentTypeCaches();
  1168. void ClearScriptContextCaches();
  1169. void RegisterTypeWithProtoPropertyCache(const Js::PropertyId propertyId, Js::Type *const type);
  1170. void InvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId);
  1171. void InternalInvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId);
  1172. void InvalidateAllProtoTypePropertyCaches();
  1173. BOOL HasUnhandledException() const { return hasUnhandledException; }
  1174. void SetHasUnhandledException() {hasUnhandledException = TRUE; }
  1175. void ResetHasUnhandledException() {hasUnhandledException = FALSE; }
  1176. void SetUnhandledExceptionObject(Js::JavascriptExceptionObject* exceptionObject) {recyclableData->unhandledExceptionObject = exceptionObject; }
  1177. Js::JavascriptExceptionObject* GetUnhandledExceptionObject() const { return recyclableData->unhandledExceptionObject; };
  1178. // To temporarily keep throwing exception object alive (thrown but not yet caught)
  1179. void SaveTempUncaughtException(Js::JavascriptExceptionObject* exceptionObject)
  1180. {
  1181. Js::JavascriptExceptionObject::Insert(&recyclableData->tempUncaughtException, exceptionObject);
  1182. }
  1183. void ClearTempUncaughtException(Js::JavascriptExceptionObject* exceptionObject)
  1184. {
  1185. Js::JavascriptExceptionObject::Remove(&recyclableData->tempUncaughtException, exceptionObject);
  1186. }
  1187. public:
  1188. bool HasCatchHandler() const { return hasCatchHandler; }
  1189. void SetHasCatchHandler(bool hasCatchHandler) { this->hasCatchHandler = hasCatchHandler; }
  1190. bool IsUserCode() const { return this->hasCatchHandlerToUserCode; }
  1191. void SetIsUserCode(bool set) { this->hasCatchHandlerToUserCode = set; }
  1192. void QueueFreeOldEntryPointInfoIfInScript(Js::FunctionEntryPointInfo* oldEntryPointInfo)
  1193. {
  1194. if (this->IsInScript())
  1195. {
  1196. // Add it to the list only if it's not already in it
  1197. if (oldEntryPointInfo->nextEntryPoint == nullptr && !oldEntryPointInfo->IsCleanedUp())
  1198. {
  1199. oldEntryPointInfo->nextEntryPoint = recyclableData->oldEntryPointInfo;
  1200. recyclableData->oldEntryPointInfo = oldEntryPointInfo;
  1201. }
  1202. }
  1203. }
  1204. static bool IsOnStack(void const *ptr);
  1205. _NOINLINE bool IsStackAvailable(size_t size, bool* isInterrupt = nullptr);
  1206. _NOINLINE bool IsStackAvailableNoThrow(size_t size = Js::Constants::MinStackDefault);
  1207. static bool IsCurrentStackAvailable(size_t size);
  1208. void ProbeStackNoDispose(size_t size, Js::ScriptContext *scriptContext, PVOID returnAddress = nullptr);
  1209. void ProbeStack(size_t size, Js::ScriptContext *scriptContext, PVOID returnAddress = nullptr);
  1210. void ProbeStack(size_t size, Js::RecyclableObject * obj, Js::ScriptContext *scriptContext);
  1211. void ProbeStack(size_t size);
  1212. static void __stdcall ProbeCurrentStackNoDispose(size_t size, Js::ScriptContext *scriptContext);
  1213. static void __stdcall ProbeCurrentStack(size_t size, Js::ScriptContext *scriptContext);
  1214. static void __stdcall ProbeCurrentStack2(size_t size, Js::ScriptContext *scriptContext, uint32 u1, uint32 u2)
  1215. {
  1216. ProbeCurrentStack(size, scriptContext);
  1217. }
  1218. #if ENABLE_PROFILE_INFO
  1219. void EnsureSourceProfileManagersByUrlMap();
  1220. Js::SourceDynamicProfileManager* GetSourceDynamicProfileManager(_In_z_ const WCHAR* url, _In_ uint hash, _Inout_ bool* addref);
  1221. uint ReleaseSourceDynamicProfileManagers(const WCHAR* url);
  1222. #endif
  1223. void EnsureSymbolRegistrationMap();
  1224. const Js::PropertyRecord* GetSymbolFromRegistrationMap(const char16* stringKey, charcount_t stringLength);
  1225. const Js::PropertyRecord* AddSymbolToRegistrationMap(const char16* stringKey, charcount_t stringLength);
  1226. #if ENABLE_TTD
  1227. JsUtil::BaseDictionary<Js::HashedCharacterBuffer<char16>*, const Js::PropertyRecord*, Recycler, PowerOf2SizePolicy, Js::PropertyRecordStringHashComparer>* GetSymbolRegistrationMap_TTD();
  1228. #endif
  1229. inline void ClearPendingSOError()
  1230. {
  1231. this->GetPendingSOErrorObject()->ClearError();
  1232. }
  1233. inline void ClearPendingOOMError()
  1234. {
  1235. this->GetPendingOOMErrorObject()->ClearError();
  1236. }
  1237. Js::JavascriptExceptionObject *GetPendingSOErrorObject()
  1238. {
  1239. Assert(recyclableData->soErrorObject.IsPendingExceptionObject());
  1240. return &recyclableData->soErrorObject;
  1241. }
  1242. Js::JavascriptExceptionObject *GetPendingOOMErrorObject()
  1243. {
  1244. Assert(recyclableData->oomErrorObject.IsPendingExceptionObject());
  1245. return &recyclableData->oomErrorObject;
  1246. }
  1247. Js::JavascriptExceptionObject *GetPendingTerminatedErrorObject()
  1248. {
  1249. return &recyclableData->terminatedErrorObject;
  1250. }
  1251. Js::JavascriptExceptionObject* GetRecordedException()
  1252. {
  1253. return recyclableData->exceptionObject;
  1254. }
  1255. bool GetPropagateException()
  1256. {
  1257. return recyclableData->propagateException;
  1258. }
  1259. void SetHasThrownPendingException()
  1260. {
  1261. Assert(this->IsInScript());
  1262. this->hasThrownPendingException = true;
  1263. }
  1264. bool * GetHasBailedOutBitPtr()
  1265. {
  1266. return this->hasBailedOutBitPtr;
  1267. }
  1268. void SetHasBailedOutBitPtr(bool *setValue)
  1269. {
  1270. this->hasBailedOutBitPtr = setValue;
  1271. }
  1272. void SetRecordedException(Js::JavascriptExceptionObject* exceptionObject, bool propagateToDebugger = false)
  1273. {
  1274. this->recyclableData->exceptionObject = exceptionObject;
  1275. this->recyclableData->propagateException = propagateToDebugger;
  1276. }
  1277. #ifdef ENABLE_CUSTOM_ENTROPY
  1278. Entropy& GetEntropy()
  1279. {
  1280. return entropy;
  1281. }
  1282. #endif
  1283. Js::ImplicitCallFlags * GetAddressOfImplicitCallFlags()
  1284. {
  1285. return &implicitCallFlags;
  1286. }
  1287. DisableImplicitFlags * GetAddressOfDisableImplicitFlags()
  1288. {
  1289. return &disableImplicitFlags;
  1290. }
  1291. Js::ImplicitCallFlags GetImplicitCallFlags()
  1292. {
  1293. return implicitCallFlags;
  1294. }
  1295. void SetImplicitCallFlags(Js::ImplicitCallFlags flags)
  1296. {
  1297. //Note: this action is inlined into JITed code in Lowerer::GenerateCallProfiling.
  1298. // if you change this, you might want to add it there too.
  1299. implicitCallFlags = flags;
  1300. }
  1301. void ClearImplicitCallFlags();
  1302. void ClearImplicitCallFlags(Js::ImplicitCallFlags flags);
  1303. void AddImplicitCallFlags(Js::ImplicitCallFlags flags)
  1304. {
  1305. SetImplicitCallFlags((Js::ImplicitCallFlags)(implicitCallFlags | flags));
  1306. }
  1307. void CheckAndResetImplicitCallAccessorFlag();
  1308. template <class Fn>
  1309. inline Js::Var ExecuteImplicitCall(Js::RecyclableObject * function, Js::ImplicitCallFlags flags, Fn implicitCall)
  1310. {
  1311. AutoReentrancyHandler autoReentrancyHandler(this);
  1312. Js::FunctionInfo::Attributes attributes = Js::FunctionInfo::GetAttributes(function);
  1313. // we can hoist out const method if we know the function doesn't have side effect,
  1314. // and the value can be hoisted.
  1315. if (this->HasNoSideEffect(function, attributes))
  1316. {
  1317. // Has no side effect means the function does not change global value or
  1318. // will check for implicit call flags
  1319. Js::Var result = implicitCall();
  1320. // If the value is on stack we need to bailout so that it can be boxed.
  1321. // Instead of putting this in valueOf (or other builtins which have no side effect) adding
  1322. // the check here to cover any other scenario we might miss.
  1323. if (IsOnStack(result))
  1324. {
  1325. AddImplicitCallFlags(flags);
  1326. }
  1327. return result;
  1328. }
  1329. // Don't call the implicit call if disable implicit call
  1330. if (IsDisableImplicitCall())
  1331. {
  1332. AddImplicitCallFlags(flags);
  1333. // Return "undefined" just so we have a valid var, in case subsequent instructions are executed
  1334. // before we bail out.
  1335. return function->GetScriptContext()->GetLibrary()->GetUndefined();
  1336. }
  1337. if ((attributes & Js::FunctionInfo::HasNoSideEffect) != 0)
  1338. {
  1339. // Has no side effect means the function does not change global value or
  1340. // will check for implicit call flags
  1341. Js::Var result = implicitCall();
  1342. // If the value is on stack we need to bailout so that it can be boxed.
  1343. // Instead of putting this in valueOf (or other builtins which have no side effect) adding
  1344. // the check here to cover any other scenario we might miss.
  1345. if (IsOnStack(result))
  1346. {
  1347. AddImplicitCallFlags(flags);
  1348. }
  1349. return result;
  1350. }
  1351. // Save and restore implicit flags around the implicit call
  1352. struct RestoreFlags
  1353. {
  1354. ThreadContext * const ctx;
  1355. const Js::ImplicitCallFlags flags;
  1356. const Js::ImplicitCallFlags savedFlags;
  1357. RestoreFlags(ThreadContext *ctx, Js::ImplicitCallFlags flags) :
  1358. ctx(ctx),
  1359. flags(flags),
  1360. savedFlags(ctx->GetImplicitCallFlags())
  1361. {
  1362. }
  1363. ~RestoreFlags()
  1364. {
  1365. ctx->SetImplicitCallFlags(static_cast<Js::ImplicitCallFlags>(savedFlags | flags));
  1366. }
  1367. };
  1368. RestoreFlags restoreFlags(this, flags);
  1369. return implicitCall();
  1370. }
  1371. bool HasNoSideEffect(Js::RecyclableObject * function) const;
  1372. bool HasNoSideEffect(Js::RecyclableObject * function, Js::FunctionInfo::Attributes attr) const;
  1373. bool RecordImplicitException();
  1374. DisableImplicitFlags GetDisableImplicitFlags() const { return disableImplicitFlags; }
  1375. void SetDisableImplicitFlags(DisableImplicitFlags flags) { disableImplicitFlags = flags; }
  1376. bool IsDisableImplicitCall() const { return (disableImplicitFlags & DisableImplicitCallFlag) != 0; }
  1377. bool IsDisableImplicitException() const { return (disableImplicitFlags & DisableImplicitExceptionFlag) != 0; }
  1378. void DisableImplicitCall() { disableImplicitFlags = (DisableImplicitFlags)(disableImplicitFlags | DisableImplicitCallFlag); }
  1379. void ClearDisableImplicitFlags() { disableImplicitFlags = DisableImplicitNoFlag; }
  1380. virtual uint GetRandomNumber() override;
  1381. virtual bool DoSpecialMarkOnScanStack() override { return this->DoRedeferFunctionBodies(); }
  1382. virtual void PostSweepRedeferralCallBack() override;
  1383. // DefaultCollectWrapper
  1384. virtual void PreCollectionCallBack(CollectionFlags flags) override;
  1385. virtual void PreSweepCallback() override;
  1386. virtual void PreRescanMarkCallback() override;
  1387. virtual void WaitCollectionCallBack() override;
  1388. virtual void PostCollectionCallBack() override;
  1389. virtual BOOL ExecuteRecyclerCollectionFunction(Recycler * recycler, CollectionFunction function, CollectionFlags flags) override;
  1390. #ifdef FAULT_INJECTION
  1391. virtual void DisposeScriptContextByFaultInjectionCallBack() override;
  1392. #endif
  1393. virtual void DisposeObjects(Recycler * recycler) override;
  1394. virtual void PreDisposeObjectsCallBack() override;
  1395. void DoExpirableCollectModeStackWalk();
  1396. typedef DList<ExpirableObject*, ArenaAllocator> ExpirableObjectList;
  1397. ExpirableObjectList* expirableObjectList;
  1398. ExpirableObjectList* expirableObjectDisposeList;
  1399. int numExpirableObjects;
  1400. int expirableCollectModeGcCount;
  1401. bool disableExpiration;
  1402. bool InExpirableCollectMode();
  1403. void TryEnterExpirableCollectMode();
  1404. void TryExitExpirableCollectMode();
  1405. void RegisterExpirableObject(ExpirableObject* object);
  1406. void UnregisterExpirableObject(ExpirableObject* object);
  1407. void * GetDynamicObjectEnumeratorCache(Js::DynamicType const * dynamicType);
  1408. void AddDynamicObjectEnumeratorCache(Js::DynamicType const * dynamicType, void * cache);
  1409. public:
  1410. bool IsScriptActive() const { return isScriptActive; }
  1411. void SetIsScriptActive(bool isActive) { isScriptActive = isActive; }
  1412. bool IsExecutionDisabled() const
  1413. {
  1414. return this->GetStackLimitForCurrentThread() == Js::Constants::StackLimitForScriptInterrupt;
  1415. }
  1416. void DisableExecution();
  1417. void EnableExecution();
  1418. bool TestThreadContextFlag(ThreadContextFlags threadContextFlag) const;
  1419. void SetThreadContextFlag(ThreadContextFlags threadContextFlag);
  1420. void ClearThreadContextFlag(ThreadContextFlags threadContextFlag);
  1421. void SetForceOneIdleCollection();
  1422. bool IsInThreadServiceCallback() const { return threadService.IsInCallback(); }
  1423. #ifdef ENABLE_SCRIPT_DEBUGGING
  1424. Js::DebugManager * GetDebugManager() const { return this->debugManager; }
  1425. #endif
  1426. const NativeLibraryEntryRecord::Entry* PeekNativeLibraryEntry() const { return this->nativeLibraryEntry.Peek(); }
  1427. void PushNativeLibraryEntry(_In_ NativeLibraryEntryRecord::Entry* entry) { this->nativeLibraryEntry.Push(entry); }
  1428. void PopNativeLibraryEntry() { this->nativeLibraryEntry.Pop(); }
  1429. bool IsProfilingUserCode() const { return isProfilingUserCode; }
  1430. void SetIsProfilingUserCode(bool value) { isProfilingUserCode = value; }
  1431. #if DBG_DUMP
  1432. uint scriptSiteCount;
  1433. #endif
  1434. #ifdef BAILOUT_INJECTION
  1435. uint bailOutByteCodeLocationCount;
  1436. #endif
  1437. #ifdef DYNAMIC_PROFILE_MUTATOR
  1438. DynamicProfileMutator * dynamicProfileMutator;
  1439. #endif
  1440. //
  1441. // Regex helpers
  1442. //
  1443. UnifiedRegex::StandardChars<uint8>* GetStandardChars(__inout_opt uint8* dummy);
  1444. UnifiedRegex::StandardChars<char16>* GetStandardChars(__inout_opt char16* dummy);
  1445. bool IsOptimizedForManyInstances() const { return isOptimizedForManyInstances; }
  1446. void OptimizeForManyInstances(const bool optimizeForManyInstances)
  1447. {
  1448. Assert(!recycler || optimizeForManyInstances == isOptimizedForManyInstances); // mode cannot be changed after recycler is created
  1449. isOptimizedForManyInstances = optimizeForManyInstances;
  1450. }
  1451. #if ENABLE_NATIVE_CODEGEN
  1452. bool IsBgJitEnabled() const { return bgJit; }
  1453. void EnableBgJit(const bool enableBgJit)
  1454. {
  1455. Assert(!jobProcessor || enableBgJit == bgJit);
  1456. bgJit = enableBgJit;
  1457. }
  1458. #endif
  1459. void* GetJSRTRuntime() const { return jsrtRuntime; }
  1460. void SetJSRTRuntime(void* runtime);
  1461. private:
  1462. BOOL ExecuteRecyclerCollectionFunctionCommon(Recycler * recycler, CollectionFunction function, CollectionFlags flags);
  1463. void DoInvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId, TypeHashSet *const typeHashSet);
  1464. void InitializePropertyMaps();
  1465. void CreateNoCasePropertyMap();
  1466. InterruptPoller *interruptPoller;
  1467. void CollectionCallBack(RecyclerCollectCallBackFlags flags);
  1468. // Cache used by HostDispatch::GetBuiltInOperationFromEntryPoint
  1469. private:
  1470. JsUtil::BaseDictionary<Js::JavascriptMethod, uint, ArenaAllocator, PowerOf2SizePolicy> entryPointToBuiltInOperationIdCache;
  1471. #if ENABLE_JS_REENTRANCY_CHECK
  1472. public:
  1473. void SetNoJsReentrancy(bool val) { noJsReentrancy = val; }
  1474. bool GetNoJsReentrancy() { return noJsReentrancy; }
  1475. void AssertJsReentrancy()
  1476. {
  1477. if (GetNoJsReentrancy())
  1478. {
  1479. Js::Throw::FatalJsReentrancyError();
  1480. }
  1481. }
  1482. #else
  1483. void AssertJsReentrancy() {}
  1484. #endif
  1485. public:
  1486. void CheckAndResetReentrancySafeOrHandled()
  1487. {
  1488. AssertOrFailFast(reentrancySafeOrHandled || isInReentrancySafeRegion);
  1489. SetReentrancySafeOrHandled(false);
  1490. }
  1491. void SetReentrancySafeOrHandled(bool val) { reentrancySafeOrHandled = val; }
  1492. bool GetReentrancySafeOrHandled() { return reentrancySafeOrHandled; }
  1493. void SetIsInReentrancySafeRegion(bool val) { isInReentrancySafeRegion = val; }
  1494. bool GetIsInReentrancySafeRegion() { return isInReentrancySafeRegion; }
  1495. template <typename Fn>
  1496. Js::Var SafeReentrantCall(Fn fn)
  1497. {
  1498. AutoReentrancyHandler autoReentrancyHandler(this);
  1499. return fn();
  1500. }
  1501. bool IsEntryPointToBuiltInOperationIdCacheInitialized()
  1502. {
  1503. return entryPointToBuiltInOperationIdCache.Count() != 0;
  1504. }
  1505. bool GetBuiltInOperationIdFromEntryPoint(Js::JavascriptMethod entryPoint, uint * id)
  1506. {
  1507. return entryPointToBuiltInOperationIdCache.TryGetValue(entryPoint, id);
  1508. }
  1509. void SetBuiltInOperationIdForEntryPoint(Js::JavascriptMethod entryPoint, uint id)
  1510. {
  1511. entryPointToBuiltInOperationIdCache.Add(entryPoint, id);
  1512. }
  1513. void ResetEntryPointToBuiltInOperationIdCache()
  1514. {
  1515. entryPointToBuiltInOperationIdCache.ResetNoDelete();
  1516. }
  1517. uint8 LoopDepth() const
  1518. {
  1519. return loopDepth;
  1520. }
  1521. void SetLoopDepth(const uint8 loopDepth)
  1522. {
  1523. this->loopDepth = loopDepth;
  1524. }
  1525. void IncrementLoopDepth()
  1526. {
  1527. if(loopDepth != UCHAR_MAX)
  1528. {
  1529. ++loopDepth;
  1530. }
  1531. }
  1532. void DecrementLoopDepth()
  1533. {
  1534. if(loopDepth != 0)
  1535. {
  1536. --loopDepth;
  1537. }
  1538. }
  1539. #if defined(CHECK_MEMORY_LEAK) || defined(LEAK_REPORT)
  1540. static void ReportAndCheckLeaksOnProcessDetach();
  1541. #endif
  1542. #ifdef LEAK_REPORT
  1543. void SetRootTrackerScriptContext(Js::ScriptContext * scriptContext);
  1544. void ClearRootTrackerScriptContext(Js::ScriptContext * scriptContext);
  1545. private:
  1546. Js::ScriptContext * rootTrackerScriptContext;
  1547. DWORD threadId;
  1548. #endif
  1549. private:
  1550. class ThreadContextRecyclerTelemetryHostInterface : public RecyclerTelemetryHostInterface
  1551. {
  1552. public:
  1553. ThreadContextRecyclerTelemetryHostInterface(ThreadContext* tc) :
  1554. tc(tc)
  1555. {
  1556. }
  1557. virtual LPFILETIME GetLastScriptExecutionEndTime() const;
  1558. virtual bool TransmitGCTelemetryStats(RecyclerTelemetryInfo& rti);
  1559. virtual bool TransmitTelemetryError(const RecyclerTelemetryInfo& rti, const char * msg);
  1560. virtual bool TransmitHeapUsage(size_t totalHeapBytes, size_t usedHeapBytes, double heapUsedRatio);
  1561. virtual bool ThreadContextRecyclerTelemetryHostInterface::IsThreadBound() const;
  1562. virtual DWORD ThreadContextRecyclerTelemetryHostInterface::GetCurrentScriptThreadID() const;
  1563. virtual bool IsTelemetryProviderEnabled() const;
  1564. virtual uint GetClosedContextCount() const;
  1565. private:
  1566. ThreadContext * tc;
  1567. };
  1568. ThreadContextRecyclerTelemetryHostInterface recyclerTelemetryHostInterface;
  1569. };
  1570. extern void(*InitializeAdditionalProperties)(ThreadContext *threadContext);
  1571. // This is for protecting a region of code, where we can't recover and be consistent upon failures (mainly due to OOM and SO).
  1572. // FailFast on that.
  1573. class AutoDisableInterrupt
  1574. {
  1575. public:
  1576. AutoDisableInterrupt(ThreadContext *threadContext, bool explicitCompletion = true)
  1577. : m_operationCompleted(false), m_interruptDisableState(false), m_threadContext(threadContext), m_explicitCompletion(explicitCompletion)
  1578. {
  1579. if (m_threadContext->HasInterruptPoller())
  1580. {
  1581. m_interruptDisableState = m_threadContext->GetInterruptPoller()->IsDisabled();
  1582. m_threadContext->GetInterruptPoller()->SetDisabled(true);
  1583. }
  1584. }
  1585. ~AutoDisableInterrupt()
  1586. {
  1587. if (m_threadContext->HasInterruptPoller())
  1588. {
  1589. m_threadContext->GetInterruptPoller()->SetDisabled(m_interruptDisableState);
  1590. }
  1591. if (m_explicitCompletion && !m_operationCompleted)
  1592. {
  1593. AssertOrFailFast(false);
  1594. }
  1595. }
  1596. void RequireExplicitCompletion() { m_explicitCompletion = true; }
  1597. void Completed() { m_operationCompleted = true; }
  1598. private:
  1599. ThreadContext * m_threadContext;
  1600. bool m_operationCompleted;
  1601. bool m_interruptDisableState;
  1602. bool m_explicitCompletion;
  1603. };
  1604. class AutoReentrancyHandler
  1605. {
  1606. ThreadContext * m_threadContext;
  1607. bool m_savedReentrancySafeOrHandled;
  1608. public:
  1609. AutoReentrancyHandler(ThreadContext * threadContext)
  1610. {
  1611. m_threadContext = threadContext;
  1612. m_savedReentrancySafeOrHandled = threadContext->GetReentrancySafeOrHandled();
  1613. threadContext->SetReentrancySafeOrHandled(true);
  1614. }
  1615. ~AutoReentrancyHandler()
  1616. {
  1617. m_threadContext->SetReentrancySafeOrHandled(m_savedReentrancySafeOrHandled);
  1618. }
  1619. };
  1620. class AutoReentrancySafeRegion
  1621. {
  1622. ThreadContext * m_threadContext;
  1623. bool m_savedIsInReentrancySafeRegion;
  1624. public:
  1625. AutoReentrancySafeRegion(ThreadContext * threadContext)
  1626. {
  1627. m_threadContext = threadContext;
  1628. m_savedIsInReentrancySafeRegion = threadContext->GetIsInReentrancySafeRegion();
  1629. threadContext->SetIsInReentrancySafeRegion(true);
  1630. }
  1631. ~AutoReentrancySafeRegion()
  1632. {
  1633. m_threadContext->SetIsInReentrancySafeRegion(m_savedIsInReentrancySafeRegion);
  1634. }
  1635. };
  1636. #if ENABLE_JS_REENTRANCY_CHECK
  1637. class JsReentLock
  1638. {
  1639. ThreadContext *m_threadContext;
  1640. #if DBG
  1641. Js::Var m_arrayObject;
  1642. Js::Var m_arrayObject2; // This is for adding the second object in the mutation equation.
  1643. #endif
  1644. bool m_savedNoJsReentrancy;
  1645. public:
  1646. JsReentLock(ThreadContext *threadContext)
  1647. #if DBG
  1648. : m_arrayObject(nullptr), m_arrayObject2(nullptr)
  1649. #endif
  1650. {
  1651. m_savedNoJsReentrancy = threadContext->GetNoJsReentrancy();
  1652. threadContext->SetNoJsReentrancy(true);
  1653. m_threadContext = threadContext;
  1654. }
  1655. void unlock() { m_threadContext->SetNoJsReentrancy(m_savedNoJsReentrancy); }
  1656. void relock() { m_threadContext->SetNoJsReentrancy(true); }
  1657. #if DBG
  1658. void setObjectForMutation(Js::Var object);
  1659. void setSecondObjectForMutation(Js::Var object);
  1660. void MutateArrayObject();
  1661. #endif
  1662. ~JsReentLock()
  1663. {
  1664. m_threadContext->SetNoJsReentrancy(m_savedNoJsReentrancy);
  1665. }
  1666. #if DBG
  1667. private:
  1668. static void MutateArrayObject(Js::Var arrayObject);
  1669. #endif
  1670. };
  1671. #endif