2
0

ThreadContext.h 66 KB

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