ScriptContext.h 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994
  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. #if defined(_WIN32) && defined(ENABLE_SCRIPT_PROFILING)
  7. #include "activprof.h"
  8. #endif
  9. #if DBG || ENABLE_REGEX_CONFIG_OPTIONS || defined(PROFILE_STRINGS)
  10. #define NEED_MISC_ALLOCATOR
  11. #endif
  12. #define BuiltInFunctionsScriptId 0
  13. using namespace PlatformAgnostic;
  14. class NativeCodeGenerator;
  15. class BackgroundParser;
  16. class BGParseManager;
  17. struct IActiveScriptDirect;
  18. namespace Js
  19. {
  20. #ifdef ENABLE_BASIC_TELEMETRY
  21. class ScriptContextTelemetry;
  22. #endif
  23. class ScriptContext;
  24. class ScriptEditQuery;
  25. class MutationBreakpoint;
  26. class StringProfiler;
  27. class DebugContext;
  28. struct HaltCallback;
  29. struct DebuggerOptionsCallback;
  30. class ModuleRecordBase;
  31. class SimpleDataCacheWrapper;
  32. }
  33. // Created for every source buffer passed by host.
  34. // This structure has all the details.
  35. class SRCINFO
  36. {
  37. // We currently don't free SRCINFO object so we don't want to add extra variables here.
  38. // In future, when we do make it freeable and will be able to allocate more than one per Module,
  39. // we can move variables m_isGlobalFunc and m_isEval from FunctionBody.cpp here.
  40. public:
  41. Field(SourceContextInfo *) sourceContextInfo;
  42. Field(ULONG) dlnHost; // Line number passed to ParseScriptText
  43. Field(ULONG) ulColumnHost; // Column number on the line where the parse script text started
  44. Field(ULONG) lnMinHost; // Line offset of first host-supplied line
  45. Field(ULONG) ichMinHost; // Range of host supplied characters
  46. Field(ULONG) ichLimHost;
  47. Field(ULONG) ulCharOffset; // Char offset of the source text relative to the document. (Populated using IActiveScriptContext)
  48. Field(Js::ModuleID) moduleID;
  49. Field(ULONG) grfsi;
  50. static SRCINFO* Copy(Recycler* recycler, const SRCINFO* srcInfo)
  51. {
  52. SRCINFO* copySrcInfo = RecyclerNew(recycler, SRCINFO, *srcInfo);
  53. return copySrcInfo;
  54. }
  55. SRCINFO()
  56. {
  57. }
  58. SRCINFO(const SRCINFO& other)
  59. :sourceContextInfo(other.sourceContextInfo),
  60. dlnHost(other.dlnHost),
  61. ulColumnHost(other.ulColumnHost),
  62. lnMinHost(other.lnMinHost),
  63. ichMinHost(other.ichMinHost),
  64. ichLimHost(other.ichLimHost),
  65. ulCharOffset(other.ulCharOffset),
  66. moduleID(other.moduleID),
  67. grfsi(other.grfsi)
  68. {
  69. }
  70. SRCINFO(
  71. SourceContextInfo*sourceContextInfo,
  72. ULONG dlnHost,
  73. ULONG ulColumnHost,
  74. ULONG lnMinHost,
  75. ULONG ichMinHost,
  76. ULONG ichLimHost,
  77. ULONG ulCharOffset,
  78. Js::ModuleID moduleID,
  79. ULONG grfsi
  80. ):sourceContextInfo(sourceContextInfo),
  81. dlnHost(dlnHost),
  82. ulColumnHost(ulColumnHost),
  83. lnMinHost(lnMinHost),
  84. ichMinHost(ichMinHost),
  85. ichLimHost(ichLimHost),
  86. ulCharOffset(ulCharOffset),
  87. moduleID(moduleID),
  88. grfsi(grfsi)
  89. {
  90. }
  91. };
  92. struct CustomExternalObjectOperations
  93. {
  94. size_t offsetOfOperationsUsage;
  95. DWORD operationFlagEquals;
  96. DWORD operationFlagStrictEquals;
  97. };
  98. enum ExternalJitData
  99. {
  100. ExternalJitData_CustomExternalObjectOperations
  101. };
  102. enum LoadScriptFlag
  103. {
  104. LoadScriptFlag_None = 0x0,
  105. LoadScriptFlag_Expression = 0x1, // the script returns a value.
  106. LoadScriptFlag_disableDeferredParse = 0x2, // do not defer-parse the code.
  107. LoadScriptFlag_isByteCodeBufferForLibrary = 0x4, // for bytecode buffer
  108. LoadScriptFlag_disableAsmJs = 0x8, // disable parse as asmjs. The code is not conform to asmjs requirement.
  109. LoadScriptFlag_Module = 0x10, // input script is module code.
  110. LoadScriptFlag_isFunction = 0x20, // input script is in a function scope, not global code.
  111. LoadScriptFlag_Utf8Source = 0x40, // input buffer is utf8 encoded.
  112. LoadScriptFlag_LibraryCode = 0x80, // for debugger, indicating 'not my code'
  113. LoadScriptFlag_ExternalArrayBuffer = 0x100, // for ExternalArrayBuffer
  114. LoadScriptFlag_CreateParserState = 0x200, // create the parser state cache while parsing.
  115. LoadScriptFlag_StrictMode = 0x400 // parse using strict mode semantics
  116. };
  117. enum class ScriptContextPrivilegeLevel
  118. {
  119. Low,
  120. Medium,
  121. High
  122. };
  123. #ifdef INLINE_CACHE_STATS
  124. // Used to store inline cache stats
  125. struct InlineCacheData
  126. {
  127. uint hits;
  128. uint misses;
  129. uint collisions;
  130. bool isGetCache;
  131. Js::PropertyId propertyId;
  132. InlineCacheData() : hits(0), misses(0), collisions(0), isGetCache(false), propertyId(Js::PropertyIds::_none) { }
  133. };
  134. #endif
  135. class HostScriptContext
  136. {
  137. public:
  138. HostScriptContext(Js::ScriptContext* inScriptContext) { this->scriptContext = inScriptContext; }
  139. virtual void Delete() = 0;
  140. virtual HRESULT GetPreviousHostScriptContext(__deref_out HostScriptContext** ppUnkCaller) = 0;
  141. virtual HRESULT PushHostScriptContext() = 0;
  142. virtual void PopHostScriptContext() = 0;
  143. virtual HRESULT SetCaller(IUnknown *punkNew, IUnknown **ppunkPrev) = 0;
  144. virtual HRESULT GetDispatchExCaller(__deref_out void** dispatchExCaller) = 0;
  145. virtual void ReleaseDispatchExCaller(__in void* dispatchExCaler) = 0;
  146. virtual Js::ModuleRoot * GetModuleRoot(int moduleID) = 0;
  147. virtual HRESULT CheckCrossDomainScriptContext(__in Js::ScriptContext* scriptContext) = 0;
  148. virtual HRESULT GetHostContextUrl(__in DWORD_PTR hostSourceContext, __out BSTR& pUrl) = 0;
  149. virtual BOOL HasCaller() = 0;
  150. virtual void CleanDynamicCodeCache() = 0;
  151. virtual HRESULT VerifyDOMSecurity(Js::ScriptContext* targetContext, Js::Var obj) = 0;
  152. virtual HRESULT CheckEvalRestriction() = 0;
  153. virtual HRESULT HostExceptionFromHRESULT(HRESULT hr, Js::Var* outError) = 0;
  154. virtual HRESULT GetExternalJitData(ExternalJitData id, void *data) = 0;
  155. virtual HRESULT SetDispatchInvoke(Js::JavascriptMethod dispatchInvoke) = 0;
  156. virtual HRESULT EnqueuePromiseTask(Js::Var varTask) = 0;
  157. virtual HRESULT FetchImportedModule(Js::ModuleRecordBase* referencingModule, LPCOLESTR specifier, Js::ModuleRecordBase** dependentModuleRecord) = 0;
  158. virtual HRESULT FetchImportedModuleFromScript(DWORD_PTR dwReferencingSourceContext, LPCOLESTR specifier, Js::ModuleRecordBase** dependentModuleRecord) = 0;
  159. virtual HRESULT NotifyHostAboutModuleReady(Js::ModuleRecordBase* referencingModule, Js::Var exceptionVar) = 0;
  160. virtual HRESULT InitializeImportMeta(Js::ModuleRecordBase* referencingModule, Js::Var importMetaObject) = 0;
  161. virtual bool ReportModuleCompletion(Js::ModuleRecordBase* module, Js::Var exception) = 0;
  162. virtual HRESULT ThrowIfFailed(HRESULT hr) = 0;
  163. Js::ScriptContext* GetScriptContext() { return scriptContext; }
  164. virtual bool SetCrossSiteForFunctionType(Js::JavascriptFunction * function) = 0;
  165. #if DBG_DUMP || defined(PROFILE_EXEC) || defined(PROFILE_MEM)
  166. virtual void EnsureParentInfo(Js::ScriptContext* scriptContext = NULL) = 0;
  167. #endif
  168. #if DBG
  169. virtual bool IsHostCrossSiteThunk(Js::JavascriptMethod address) = 0;
  170. #endif
  171. private:
  172. Js::ScriptContext* scriptContext;
  173. };
  174. class HostStream
  175. {
  176. public:
  177. virtual byte * ExtendBuffer(byte *oldBuffer, size_t newSize, size_t *allocatedSize) = 0;
  178. virtual bool WriteHostObject(void* data) = 0;
  179. };
  180. class HostReadStream
  181. {
  182. public:
  183. virtual Js::Var ReadHostObject() = 0;
  184. };
  185. #if ENABLE_TTD
  186. typedef void (CALLBACK *JsTTDOnScriptLoadCallback)(FinalizableObject* hostContext, Js::FunctionBody* body, Js::Utf8SourceInfo* utf8SourceInfo, CompileScriptException* compileException, bool notify);
  187. typedef uint32 (CALLBACK *JsTTDOnBPRegisterCallback)(void* hostRuntime, int64 bpID, Js::ScriptContext* scriptContext, Js::Utf8SourceInfo* utf8SourceInfo, uint32 line, uint32 column, BOOL* isNewBP);
  188. typedef void (CALLBACK *JsTTDOnBPDeleteCallback)(void* hostRuntime, uint32 bpID);
  189. typedef void (CALLBACK *JsTTDOnBPClearDocumentCallback)(void* hostRuntime);
  190. //A class that we use to pass in a functor from the host when we need to inform it about something we are doing
  191. class HostScriptContextCallbackFunctor
  192. {
  193. public:
  194. FinalizableObject* HostContext;
  195. void* HostRuntime;
  196. JsTTDOnScriptLoadCallback pfOnScriptLoadCallback;
  197. JsTTDOnBPRegisterCallback pfOnBPRegisterCallback;
  198. JsTTDOnBPDeleteCallback pfOnBPDeleteCallback;
  199. JsTTDOnBPClearDocumentCallback pfOnBPClearDocumentCallback;
  200. HostScriptContextCallbackFunctor()
  201. : HostContext(nullptr), HostRuntime(nullptr), pfOnScriptLoadCallback(nullptr), pfOnBPRegisterCallback(nullptr), pfOnBPDeleteCallback(nullptr), pfOnBPClearDocumentCallback(nullptr)
  202. {
  203. ;
  204. }
  205. HostScriptContextCallbackFunctor(FinalizableObject* hostContext, void* hostRuntime, JsTTDOnScriptLoadCallback callbackOnScriptLoad, JsTTDOnBPRegisterCallback callbackOnBPRegister, JsTTDOnBPDeleteCallback callbackOnBPDelete, JsTTDOnBPClearDocumentCallback callbackOnBPClearDocument)
  206. : HostContext(hostContext), HostRuntime(hostRuntime), pfOnScriptLoadCallback(callbackOnScriptLoad), pfOnBPRegisterCallback(callbackOnBPRegister), pfOnBPDeleteCallback(callbackOnBPDelete), pfOnBPClearDocumentCallback(callbackOnBPClearDocument)
  207. {
  208. ;
  209. }
  210. };
  211. #endif
  212. namespace Js
  213. {
  214. #pragma pack(push, 1)
  215. struct StackFrameInfo
  216. {
  217. StackFrameInfo() { }
  218. StackFrameInfo(DWORD_PTR _scriptContextID
  219. , UINT32 _sourceLocationLineNumber
  220. , UINT32 _sourceLocationColumnNumber
  221. , UINT32 _methodIDOrNameIndex
  222. , UINT8 _isFrameIndex)
  223. : scriptContextID(_scriptContextID)
  224. , sourceLocationLineNumber(_sourceLocationLineNumber)
  225. , sourceLocationColumnNumber(_sourceLocationColumnNumber)
  226. , methodIDOrNameIndex(_methodIDOrNameIndex)
  227. , isFrameIndex(_isFrameIndex)
  228. { }
  229. DWORD_PTR scriptContextID;
  230. UINT32 sourceLocationLineNumber;
  231. UINT32 sourceLocationColumnNumber;
  232. UINT32 methodIDOrNameIndex;
  233. UINT8 isFrameIndex;
  234. };
  235. #pragma pack(pop)
  236. class ScriptConfiguration
  237. {
  238. public:
  239. ScriptConfiguration(const ThreadConfiguration * const threadConfig, const bool isOptimizedForManyInstances) :
  240. NoNative(Configuration::Global.flags.NoNative),
  241. NoDynamicThunks(false),
  242. isOptimizedForManyInstances(isOptimizedForManyInstances),
  243. threadConfig(threadConfig)
  244. {
  245. }
  246. #define FORWARD_THREAD_CONFIG(flag) inline bool flag() const { return threadConfig->flag(); }
  247. #define FLAG(threadFlag, globalFlag) FORWARD_THREAD_CONFIG(threadFlag)
  248. #define FLAG_RELEASE(threadFlag, globalFlag) FORWARD_THREAD_CONFIG(threadFlag)
  249. #include "../Base/ThreadConfigFlagsList.h"
  250. #undef FLAG_RELEASE
  251. #undef FLAG
  252. #undef FORWARD_THREAD_CONFIG
  253. void ForceNoDynamicThunks() { this->NoDynamicThunks = true; }
  254. bool IsNoDynamicThunks() const { return this->NoDynamicThunks; }
  255. void ForceNoNative() { this->NoNative = true; }
  256. void ForceNative() { this->NoNative = false; }
  257. bool IsNoNative() const { return this->NoNative; }
  258. void SetCanOptimizeGlobalLookupFlag(BOOL f){ this->fCanOptimizeGlobalLookup = f;}
  259. BOOL CanOptimizeGlobalLookup() const { return this->fCanOptimizeGlobalLookup;}
  260. bool IsOptimizedForManyInstances() const { return isOptimizedForManyInstances; }
  261. void CopyFrom(ScriptConfiguration& other)
  262. {
  263. this->NoNative = other.NoNative;
  264. this->fCanOptimizeGlobalLookup = other.fCanOptimizeGlobalLookup;
  265. }
  266. private:
  267. // Per script configurations
  268. bool NoNative;
  269. bool NoDynamicThunks;
  270. BOOL fCanOptimizeGlobalLookup;
  271. const bool isOptimizedForManyInstances;
  272. const ThreadConfiguration * const threadConfig;
  273. };
  274. struct ScriptEntryExitRecord
  275. {
  276. bool hasCaller : 1;
  277. bool hasReentered : 1;
  278. #if DBG_DUMP
  279. bool isCallRoot : 1;
  280. #endif
  281. #if DBG || defined(PROFILE_EXEC)
  282. bool leaveForHost : 1;
  283. #endif
  284. #if DBG
  285. bool leaveForAsyncHostOperation : 1;
  286. #endif
  287. #ifdef CHECK_STACKWALK_EXCEPTION
  288. bool ignoreStackWalkException: 1;
  289. #endif
  290. Js::ImplicitCallFlags savedImplicitCallFlags;
  291. void * returnAddrOfScriptEntryFunction;
  292. void * addrOfReturnAddrOfScriptEntryFunction;
  293. void * frameIdOfScriptExitFunction; // the frameAddres in x86, the return address in amd64/arm_soc
  294. ScriptContext * scriptContext;
  295. struct ScriptEntryExitRecord * next;
  296. #if defined(_M_IX86) && defined(DBG)
  297. void * scriptEntryFS0;
  298. #endif
  299. #ifdef EXCEPTION_CHECK
  300. ExceptionType handledExceptionType;
  301. #endif
  302. };
  303. #if ENABLE_NATIVE_CODEGEN
  304. /*
  305. * This class caches jitted func address ranges.
  306. * This is to facilitate WER scenarios to use this cache for checking native addresses.
  307. */
  308. class JITPageAddrToFuncRangeCache
  309. {
  310. public:
  311. typedef JsUtil::BaseDictionary<void *, uint, HeapAllocator> RangeMap;
  312. typedef JsUtil::BaseDictionary<void *, RangeMap*, HeapAllocator, PrimeSizePolicy> JITPageAddrToFuncRangeMap;
  313. typedef JsUtil::BaseDictionary<void *, uint, HeapAllocator, PrimeSizePolicy> LargeJITFuncAddrToSizeMap;
  314. private:
  315. JITPageAddrToFuncRangeMap * jitPageAddrToFuncRangeMap;
  316. LargeJITFuncAddrToSizeMap * largeJitFuncToSizeMap;
  317. static CriticalSection cs;
  318. public:
  319. JITPageAddrToFuncRangeCache() :jitPageAddrToFuncRangeMap(nullptr), largeJitFuncToSizeMap(nullptr) {}
  320. ~JITPageAddrToFuncRangeCache()
  321. {
  322. ClearCache();
  323. }
  324. void ClearCache();
  325. void AddFuncRange(void * address, uint bytes);
  326. void RemoveFuncRange(void * address);
  327. void * GetPageAddr(void * address);
  328. bool IsNativeAddr(void * address);
  329. JITPageAddrToFuncRangeMap * GetJITPageAddrToFuncRangeMap();
  330. LargeJITFuncAddrToSizeMap * GetLargeJITFuncAddrToSizeMap();
  331. static CriticalSection * GetCriticalSection() { return &cs; }
  332. };
  333. #endif
  334. class ScriptContext : public ScriptContextBase, public ScriptContextInfo
  335. {
  336. friend class LowererMD;
  337. friend class RemoteScriptContext;
  338. friend class GlobalObject; // InitializeCache
  339. friend class SourceTextModuleRecord; // for module bytecode gen.
  340. #if ENABLE_NATIVE_CODEGEN
  341. public:
  342. static DWORD GetThreadContextOffset() { return offsetof(ScriptContext, threadContext); }
  343. static DWORD GetOptimizationOverridesOffset() { return offsetof(ScriptContext, optimizationOverrides); }
  344. static DWORD GetRecyclerOffset() { return offsetof(ScriptContext, recycler); }
  345. static DWORD GetNumberAllocatorOffset() { return offsetof(ScriptContext, numberAllocator); }
  346. JITPageAddrToFuncRangeCache * GetJitFuncRangeCache();
  347. private:
  348. JITPageAddrToFuncRangeCache * jitFuncRangeCache;
  349. #endif
  350. public:
  351. ScriptContext *next;
  352. ScriptContext *prev;
  353. bool IsRegistered() { return next != nullptr || prev != nullptr || threadContext->GetScriptContextList() == this; }
  354. ScriptContextOptimizationOverrideInfo optimizationOverrides;
  355. Js::JavascriptMethod CurrentThunk;
  356. Js::JavascriptMethod CurrentCrossSiteThunk;
  357. Js::JavascriptMethod DeferredParsingThunk;
  358. Js::JavascriptMethod DeferredDeserializationThunk;
  359. Js::JavascriptMethod DispatchDefaultInvoke;
  360. Js::JavascriptMethod DispatchProfileInvoke;
  361. #ifdef ENABLE_SCRIPT_DEBUGGING
  362. typedef HRESULT (*GetDocumentContextFunction)(
  363. Js::FunctionBody *pFunctionBody,
  364. IDebugDocumentContext **ppDebugDocumentContext);
  365. GetDocumentContextFunction GetDocumentContext;
  366. #endif // ENABLE_SCRIPT_DEBUGGING
  367. #ifdef ENABLE_SCRIPT_PROFILING
  368. typedef HRESULT (*CleanupDocumentContextFunction)(ScriptContext *pContext);
  369. CleanupDocumentContextFunction CleanupDocumentContext;
  370. #endif
  371. const ScriptContextBase* GetScriptContextBase() const { return static_cast<const ScriptContextBase*>(this); }
  372. void RedeferFunctionBodies(ActiveFunctionSet *pActive, uint inactiveThreshold);
  373. bool DoUndeferGlobalFunctions() const;
  374. bool IsUndeclBlockVar(Var var) const { return this->javascriptLibrary->IsUndeclBlockVar(var); }
  375. void TrackPid(const PropertyRecord* propertyRecord);
  376. void TrackPid(PropertyId propertyId);
  377. bool IsTrackedPropertyId(Js::PropertyId propertyId);
  378. void InvalidateHostObjects()
  379. {
  380. AssertMsg(!isClosed, "Host Object invalidation should occur before the engine is fully closed. Figure our how isClosed got set beforehand.");
  381. isInvalidatedForHostObjects = true;
  382. }
  383. bool IsInvalidatedForHostObjects()
  384. {
  385. return isInvalidatedForHostObjects;
  386. }
  387. #if ENABLE_NATIVE_CODEGEN
  388. void InitializeRemoteScriptContext();
  389. #endif
  390. #ifdef ENABLE_JS_ETW
  391. void EmitStackTraceEvent(__in UINT64 operationID, __in USHORT maxFrameCount, bool emitV2AsyncStackEvent);
  392. static ushort ProcessNameAndGetLength(Js::StringBuilder<ArenaAllocator>* nameBuffer, const WCHAR* name);
  393. #endif
  394. void SetPrivilegeLevel(ScriptContextPrivilegeLevel level) { this->scriptContextPrivilegeLevel = level; }
  395. ScriptContextPrivilegeLevel GetPrivilegeLevel() { return this->scriptContextPrivilegeLevel; }
  396. void SetIsDiagnosticsScriptContext(bool);
  397. bool IsDiagnosticsScriptContext() const { return this->isDiagnosticsScriptContext; }
  398. bool IsScriptContextInNonDebugMode() const;
  399. bool IsScriptContextInDebugMode() const;
  400. bool IsScriptContextInSourceRundownOrDebugMode() const;
  401. #ifdef ENABLE_SCRIPT_DEBUGGING
  402. bool IsDebuggerRecording() const;
  403. void SetIsDebuggerRecording(bool isDebuggerRecording);
  404. #endif
  405. bool IsRunningScript() const { return this->threadContext->GetScriptEntryExit() != nullptr; }
  406. typedef JsUtil::List<RecyclerWeakReference<Utf8SourceInfo>*, Recycler, false, Js::WeakRefFreeListedRemovePolicy> CalleeSourceList;
  407. RecyclerRootPtr<CalleeSourceList> calleeUtf8SourceInfoList;
  408. void AddCalleeSourceInfoToList(Utf8SourceInfo* sourceInfo);
  409. bool HaveCalleeSources() { return calleeUtf8SourceInfoList && !calleeUtf8SourceInfoList->Empty(); }
  410. template<class TMapFunction>
  411. void MapCalleeSources(TMapFunction map)
  412. {
  413. if (this->HaveCalleeSources())
  414. {
  415. calleeUtf8SourceInfoList->Map([&](uint i, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef)
  416. {
  417. if (calleeUtf8SourceInfoList->IsItemValid(i))
  418. {
  419. Js::Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
  420. map(sourceInfo);
  421. }
  422. });
  423. }
  424. if (calleeUtf8SourceInfoList)
  425. {
  426. calleeUtf8SourceInfoList.Unroot(this->GetRecycler());
  427. }
  428. }
  429. #ifdef ASMJS_PLAT
  430. inline AsmJsCodeGenerator* GetAsmJsCodeGenerator() const{return asmJsCodeGenerator;}
  431. AsmJsCodeGenerator* InitAsmJsCodeGenerator();
  432. #endif
  433. bool IsExceptionWrapperForBuiltInsEnabled();
  434. static bool IsExceptionWrapperForBuiltInsEnabled(ScriptContext* scriptContext);
  435. static bool IsExceptionWrapperForHelpersEnabled(ScriptContext* scriptContext);
  436. bool IsEnumerateNonUserFunctionsOnly() const { return m_enumerateNonUserFunctionsOnly; }
  437. #ifdef ENABLE_SCRIPT_PROFILING
  438. bool IsTraceDomCall() const { return !!m_fTraceDomCall; }
  439. #elif defined(ENABLE_SCRIPT_DEBUGGING)
  440. bool IsTraceDomCall() const { return false; }
  441. #endif
  442. InlineCache * GetValueOfInlineCache() const { return valueOfInlineCache;}
  443. InlineCache * GetToStringInlineCache() const { return toStringInlineCache; }
  444. NoSpecialPropertyScriptRegistry* GetNoSpecialPropertyRegistry() { return &this->noSpecialPropertyRegistry; }
  445. OnlyWritablePropertyScriptRegistry* GetOnlyWritablePropertyRegistry() { return &this->onlyWritablePropertyRegistry; }
  446. private:
  447. JavascriptFunction* GenerateRootFunction(ParseNodeProg * parseTree, uint sourceIndex, Parser* parser, uint32 grfscr, CompileScriptException * pse, const char16 *rootDisplayName);
  448. typedef void (*EventHandler)(ScriptContext *);
  449. NoSpecialPropertyScriptRegistry noSpecialPropertyRegistry;
  450. OnlyWritablePropertyScriptRegistry onlyWritablePropertyRegistry;
  451. ArenaAllocator generalAllocator;
  452. #ifdef ENABLE_BASIC_TELEMETRY
  453. ArenaAllocator telemetryAllocator;
  454. #endif
  455. ArenaAllocator dynamicProfileInfoAllocator;
  456. InlineCacheAllocator inlineCacheAllocator;
  457. CacheAllocator isInstInlineCacheAllocator;
  458. CacheAllocator enumeratorCacheAllocator;
  459. ArenaAllocator* interpreterArena;
  460. #ifdef ENABLE_SCRIPT_DEBUGGING
  461. ArenaAllocator* diagnosticArena;
  462. #endif
  463. #if ENABLE_NATIVE_CODEGEN
  464. PSCRIPTCONTEXT_HANDLE m_remoteScriptContextAddr;
  465. #endif
  466. bool startupComplete; // Indicates if the heuristic startup phase for this script context is complete
  467. bool isInvalidatedForHostObjects; // Indicates that we've invalidate all objects in the host so stop calling them.
  468. #ifdef ENABLE_SCRIPT_DEBUGGING
  469. bool isEnumeratingRecyclerObjects; // Indicates this scriptContext is enumerating recycler objects. Used by recycler enumerating callbacks to filter out other unrelated scriptContexts.
  470. #endif
  471. bool m_enumerateNonUserFunctionsOnly; // Indicates that recycler enumeration callback will consider only non-user functions (which are built-ins, external, winrt etc).
  472. ThreadContext* threadContext;
  473. TypeId directHostTypeId;
  474. InlineCache * valueOfInlineCache;
  475. InlineCache * toStringInlineCache;
  476. typedef JsUtil::BaseHashSet<Js::PropertyId, ArenaAllocator> PropIdSetForConstProp;
  477. PropIdSetForConstProp * intConstPropsOnGlobalObject;
  478. PropIdSetForConstProp * intConstPropsOnGlobalUserObject;
  479. void * firstInterpreterFrameReturnAddress;
  480. #ifdef SEPARATE_ARENA
  481. ArenaAllocator sourceCodeAllocator;
  482. ArenaAllocator regexAllocator;
  483. #endif
  484. #ifdef NEED_MISC_ALLOCATOR
  485. ArenaAllocator miscAllocator;
  486. #endif
  487. #if DBG
  488. JsUtil::BaseHashSet<void *, ArenaAllocator> bindRef;
  489. int m_iProfileSession;
  490. #endif
  491. #ifdef PROFILE_EXEC
  492. ScriptContextProfiler * profiler;
  493. bool isProfilerCreated;
  494. bool disableProfiler;
  495. bool ensureParentInfo;
  496. Profiler * CreateProfiler();
  497. #endif
  498. #ifdef PROFILE_MEM
  499. bool profileMemoryDump;
  500. #endif
  501. #ifdef PROFILE_STRINGS
  502. StringProfiler* stringProfiler;
  503. #endif
  504. public:
  505. #ifdef PROFILE_TYPES
  506. int convertNullToSimpleCount;
  507. int convertNullToSimpleDictionaryCount;
  508. int convertNullToDictionaryCount;
  509. int convertDeferredToDictionaryCount;
  510. int convertDeferredToSimpleDictionaryCount;
  511. int convertSimpleToDictionaryCount;
  512. int convertSimpleToSimpleDictionaryCount;
  513. int convertPathToDictionaryExceededLengthCount;
  514. int convertPathToDictionaryDeletedCount;
  515. int convertPathToDictionaryAttributesCount;
  516. int convertPathToDictionaryItemAttributesCount;
  517. int convertPathToDictionaryAccessorsCount;
  518. int convertPathToDictionaryItemAccessorsCount;
  519. int convertPathToDictionaryExtensionsCount;
  520. int convertPathToDictionaryProtoCount;
  521. int convertPathToDictionaryNoRootCount;
  522. int convertPathToDictionaryResetCount;
  523. int convertPathToSimpleDictionaryCount;
  524. int convertSimplePathToPathCount;
  525. int convertSimpleDictionaryToDictionaryCount;
  526. int convertSimpleSharedDictionaryToNonSharedCount;
  527. int convertSimpleSharedToNonSharedCount;
  528. int pathTypeHandlerCount;
  529. int promoteCount;
  530. int cacheCount;
  531. int branchCount;
  532. int maxPathLength;
  533. int typeCount[TypeIds_Limit];
  534. int instanceCount[TypeIds_Limit];
  535. #endif
  536. #ifdef PROFILE_BAILOUT_RECORD_MEMORY
  537. __int64 bailOutRecordBytes;
  538. __int64 bailOutOffsetBytes;
  539. __int64 codeSize;
  540. #endif
  541. #ifdef PROFILE_OBJECT_LITERALS
  542. int objectLiteralInstanceCount;
  543. int objectLiteralPathCount;
  544. int objectLiteralCount[TypePath::MaxPathTypeHandlerLength];
  545. int objectLiteralSimpleDictionaryCount;
  546. uint32 objectLiteralMaxLength;
  547. int objectLiteralPromoteCount;
  548. int objectLiteralCacheCount;
  549. int objectLiteralBranchCount;
  550. #endif
  551. #if DBG_DUMP
  552. uint byteCodeDataSize;
  553. uint byteCodeAuxiliaryDataSize;
  554. uint byteCodeAuxiliaryContextDataSize;
  555. uint byteCodeHistogram[static_cast<uint>(OpCode::ByteCodeLast)];
  556. uint32 forinCache;
  557. uint32 forinNoCache;
  558. #endif
  559. #ifdef BGJIT_STATS
  560. uint interpretedCount;
  561. uint funcJITCount;
  562. uint loopJITCount;
  563. uint bytecodeJITCount;
  564. uint interpretedCallsHighPri;
  565. uint maxFuncInterpret;
  566. uint jitCodeUsed;
  567. uint funcJitCodeUsed;
  568. uint speculativeJitCount;
  569. #endif
  570. #if DBG
  571. // Count how many Out of Memory and Stack overflow exceptions happened during the execution
  572. uint oomExceptionCount = 0;
  573. uint soExceptionCount = 0;
  574. #endif
  575. #ifdef REJIT_STATS
  576. // Used to store bailout stats
  577. typedef JsUtil::BaseDictionary<uint, uint, ArenaAllocator> BailoutStatsMap;
  578. struct RejitStats
  579. {
  580. uint *m_rejitReasonCounts;
  581. BailoutStatsMap* m_bailoutReasonCounts;
  582. uint m_totalRejits;
  583. uint m_totalBailouts;
  584. RejitStats(ScriptContext *scriptContext) : m_totalRejits(0), m_totalBailouts(0)
  585. {
  586. m_rejitReasonCounts = AnewArrayZ(scriptContext->GeneralAllocator(), uint, NumRejitReasons);
  587. m_bailoutReasonCounts = Anew(scriptContext->GeneralAllocator(), BailoutStatsMap, scriptContext->GeneralAllocator());
  588. }
  589. };
  590. void LogDataForFunctionBody(Js::FunctionBody *body, uint idx, bool isRejit);
  591. void LogRejit(Js::FunctionBody *body, RejitReason reason);
  592. void LogBailout(Js::FunctionBody *body, uint kind);
  593. // Used to centrally collect stats for all function bodies.
  594. typedef JsUtil::WeaklyReferencedKeyDictionary<const Js::FunctionBody, RejitStats*> RejitStatsMap;
  595. RejitStatsMap* rejitStatsMap;
  596. BailoutStatsMap *bailoutReasonCounts;
  597. BailoutStatsMap *bailoutReasonCountsCap;
  598. uint *rejitReasonCounts;
  599. uint *rejitReasonCountsCap;
  600. void ClearBailoutReasonCountsMap();
  601. void ClearRejitReasonCountsArray();
  602. #endif
  603. #ifdef ENABLE_BASIC_TELEMETRY
  604. private:
  605. Js::ScriptContextTelemetry * telemetry;
  606. public:
  607. Js::ScriptContextTelemetry& GetTelemetry();
  608. bool HasTelemetry();
  609. #endif
  610. #ifdef INLINE_CACHE_STATS
  611. // This is a strongly referenced dictionary, since we want to know hit rates for dead caches.
  612. typedef JsUtil::BaseDictionary<const Js::PolymorphicInlineCache*, InlineCacheData*, Recycler> CacheDataMap;
  613. CacheDataMap *cacheDataMap;
  614. void LogCacheUsage(Js::PolymorphicInlineCache *cache, bool isGet, Js::PropertyId propertyId, bool hit, bool collision);
  615. #endif
  616. #ifdef FIELD_ACCESS_STATS
  617. typedef SList<FieldAccessStatsPtr, Recycler> FieldAccessStatsList;
  618. struct FieldAccessStatsEntry
  619. {
  620. Field(RecyclerWeakReference<FunctionBody>*) functionBodyWeakRef;
  621. Field(FieldAccessStatsList) stats;
  622. FieldAccessStatsEntry(RecyclerWeakReference<FunctionBody>* functionBodyWeakRef, Recycler* recycler)
  623. : functionBodyWeakRef(functionBodyWeakRef), stats(recycler) {}
  624. };
  625. typedef JsUtil::BaseDictionary<uint, FieldAccessStatsEntry*, Recycler> FieldAccessStatsByFunctionNumberMap;
  626. FieldAccessStatsByFunctionNumberMap* fieldAccessStatsByFunctionNumber;
  627. void RecordFieldAccessStats(FunctionBody* functionBody, FieldAccessStatsPtr fieldAccessStats);
  628. #endif
  629. #ifdef MISSING_PROPERTY_STATS
  630. int missingPropertyMisses;
  631. int missingPropertyHits;
  632. int missingPropertyCacheAttempts;
  633. void RecordMissingPropertyMiss();
  634. void RecordMissingPropertyHit();
  635. void RecordMissingPropertyCacheAttempt();
  636. #endif
  637. bool IsIntConstPropertyOnGlobalObject(Js::PropertyId propId);
  638. void TrackIntConstPropertyOnGlobalObject(Js::PropertyId propId);
  639. bool IsIntConstPropertyOnGlobalUserObject(Js::PropertyId propertyId);
  640. void TrackIntConstPropertyOnGlobalUserObject(Js::PropertyId propertyId);
  641. private:
  642. //
  643. // Regex globals
  644. //
  645. #if ENABLE_REGEX_CONFIG_OPTIONS
  646. UnifiedRegex::DebugWriter* regexDebugWriter;
  647. UnifiedRegex::RegexStatsDatabase* regexStatsDatabase;
  648. #endif
  649. UnifiedRegex::TrigramAlphabet* trigramAlphabet;
  650. UnifiedRegex::RegexStacks *regexStacks;
  651. JsUtil::Stack<Var>* operationStack;
  652. Recycler* recycler;
  653. RecyclerJavascriptNumberAllocator numberAllocator;
  654. ScriptConfiguration config;
  655. CharClassifier *charClassifier;
  656. // DisableJIT-TODO: Switch this to Dynamic thunk ifdef instead
  657. #if ENABLE_NATIVE_CODEGEN
  658. #if DYNAMIC_INTERPRETER_THUNK
  659. InterpreterThunkEmitter* interpreterThunkEmitter;
  660. #endif
  661. BackgroundParser *backgroundParser;
  662. #ifdef ASMJS_PLAT
  663. InterpreterThunkEmitter* asmJsInterpreterThunkEmitter;
  664. AsmJsCodeGenerator* asmJsCodeGenerator;
  665. typedef JsUtil::BaseDictionary<void*, SList<AsmJsScriptFunction *>*, ArenaAllocator> AsmFunctionMap;
  666. AsmFunctionMap* asmJsEnvironmentMap;
  667. ArenaAllocator* debugTransitionAlloc;
  668. #endif
  669. NativeCodeGenerator* nativeCodeGen;
  670. #endif
  671. DateTime::DaylightTimeHelper daylightTimeHelper;
  672. DateTime::Utility dateTimeUtility;
  673. public:
  674. inline const WCHAR *GetStandardName(size_t *nameLength, DateTime::YMD *ymd = NULL)
  675. {
  676. return dateTimeUtility.GetStandardName(nameLength, ymd);
  677. }
  678. inline const WCHAR *GetDaylightName(size_t *nameLength, DateTime::YMD *ymd = NULL)
  679. {
  680. return dateTimeUtility.GetDaylightName(nameLength, ymd);
  681. }
  682. private:
  683. HostScriptContext * hostScriptContext;
  684. HaltCallback* scriptEngineHaltCallback;
  685. EventHandler scriptStartEventHandler;
  686. EventHandler scriptEndEventHandler;
  687. #ifdef FAULT_INJECTION
  688. EventHandler disposeScriptByFaultInjectionEventHandler;
  689. #endif
  690. #ifndef CC_LOW_MEMORY_TARGET
  691. uint integerStringMapCacheMissCount;
  692. uint integerStringMapCacheUseCount;
  693. #endif
  694. double lastNumberToStringRadix10;
  695. double lastUtcTimeFromStr;
  696. #if ENABLE_PROFILE_INFO
  697. bool referencesSharedDynamicSourceContextInfo;
  698. #endif
  699. // We could delay the actual close after callRootLevel is 0.
  700. // this is to indicate the actual close is called once only.
  701. bool isScriptContextActuallyClosed;
  702. bool isFinalized;
  703. bool isEvalRestricted;
  704. #if DBG
  705. bool isInitialized;
  706. bool isCloningGlobal;
  707. #endif
  708. bool fastDOMenabled;
  709. bool hasUsedInlineCache;
  710. bool hasProtoOrStoreFieldInlineCache;
  711. bool hasIsInstInlineCache;
  712. bool deferredBody;
  713. bool isPerformingNonreentrantWork;
  714. bool isDiagnosticsScriptContext; // mentions that current script context belongs to the diagnostics OM.
  715. // Privilege levels are a way of enforcing a relationship hierarchy between two script contexts
  716. // A less privileged script context is not allowed to marshal in objects that live in a more privileged context
  717. ScriptContextPrivilegeLevel scriptContextPrivilegeLevel;
  718. size_t sourceSize;
  719. void CleanSourceListInternal(bool calledDuringMark);
  720. typedef JsUtil::List<RecyclerWeakReference<Utf8SourceInfo>*, Recycler, false, Js::FreeListedRemovePolicy> SourceList;
  721. RecyclerRootPtr<SourceList> sourceList;
  722. #ifdef ENABLE_SCRIPT_DEBUGGING
  723. typedef void(*RaiseMessageToDebuggerFunctionType)(ScriptContext *, DEBUG_EVENT_INFO_TYPE, LPCWSTR, LPCWSTR);
  724. RaiseMessageToDebuggerFunctionType raiseMessageToDebuggerFunctionType;
  725. typedef void(*TransitionToDebugModeIfFirstSourceFn)(ScriptContext *, Utf8SourceInfo *);
  726. TransitionToDebugModeIfFirstSourceFn transitionToDebugModeIfFirstSourceFn;
  727. DebugContext* debugContext;
  728. CriticalSection debugContextCloseCS;
  729. #endif
  730. #ifdef ENABLE_SCRIPT_PROFILING
  731. IActiveScriptProfilerHeapEnum* heapEnum;
  732. // Profiler Probes
  733. // In future these can be list of callbacks ?
  734. // Profiler Callback information
  735. IActiveScriptProfilerCallback *m_pProfileCallback;
  736. BOOL m_fTraceFunctionCall;
  737. BOOL m_fTraceNativeFunctionCall;
  738. DWORD m_dwEventMask;
  739. IActiveScriptProfilerCallback2 *m_pProfileCallback2;
  740. BOOL m_fTraceDomCall;
  741. BOOL m_inProfileCallback;
  742. #endif // ENABLE_SCRIPT_PROFILING
  743. // List of weak reference dictionaries. We'll walk through them
  744. // and clean them up post-collection
  745. // IWeakReferenceDictionary objects are added to this list by calling
  746. // RegisterWeakReferenceDictionary. If you use JsUtil::WeakReferenceDictionary,
  747. // which also exposes the IWeakReferenceDictionary interface, it'll
  748. // automatically register the dictionary on the script context
  749. SListBase<JsUtil::IWeakReferenceDictionary*> weakReferenceDictionaryList;
  750. bool isWeakReferenceDictionaryListCleared;
  751. ScriptContext(ThreadContext* threadContext);
  752. void InitializeAllocations();
  753. void InitializePreGlobal();
  754. void InitializePostGlobal();
  755. void InitializeCache();
  756. bool isDebugContextInitialized;
  757. // Source Info
  758. void EnsureSourceContextInfoMap();
  759. void EnsureDynamicSourceContextInfoMap();
  760. void AddToEvalMapHelper(FastEvalMapString & key, BOOL isIndirect, ScriptFunction *pFuncScript);
  761. uint moduleSrcInfoCount;
  762. #ifdef RUNTIME_DATA_COLLECTION
  763. time_t createTime;
  764. #endif
  765. char16 const * url;
  766. void PrintStats();
  767. void InternalClose();
  768. template <typename TProperty> void InvalidatePropertyCache(PropertyId propertyId, Type* type);
  769. void InvalidatePropertyRecordUsageCache(PropertyRecordUsageCache* propertyRecordUsageCache, Type *type);
  770. template <typename TProperty> TProperty* TryGetProperty(PropertyId propertyId);
  771. template <typename TProperty> TProperty* GetProperty(PropertyId propertyId, const PropertyRecord* propertyRecord);
  772. template <typename TProperty> TProperty* CreateAndCacheSymbolOrPropertyString(const PropertyRecord* propertyRecord);
  773. public:
  774. #ifdef LEAK_REPORT
  775. LeakReport::UrlRecord * urlRecord;
  776. bool isRootTrackerScriptContext;
  777. #endif
  778. DateTime::DaylightTimeHelper *GetDaylightTimeHelper() { return &daylightTimeHelper; }
  779. DateTime::Utility *GetDateUtility() { return &dateTimeUtility; }
  780. virtual bool IsClosed() const override { return isClosed; }
  781. void SetIsClosed();
  782. bool IsFinalized() const { return isFinalized; }
  783. void SetIsFinalized() { isFinalized = true; }
  784. bool IsActuallyClosed() const { return isScriptContextActuallyClosed; }
  785. void SetEvalRestriction(bool set) { this->isEvalRestricted = set; }
  786. bool IsEvalRestriction() const { return this->isEvalRestricted; }
  787. #if ENABLE_NATIVE_CODEGEN
  788. bool IsClosedNativeCodeGenerator() const
  789. {
  790. return !nativeCodeGen || ::IsClosedNativeCodeGenerator(nativeCodeGen);
  791. }
  792. #endif
  793. void SetHasUsedInlineCache(bool value)
  794. {
  795. hasUsedInlineCache = value;
  796. #if DBG
  797. if(hasUsedInlineCache)
  798. {
  799. inlineCacheAllocator.Unlock();
  800. }
  801. #endif
  802. }
  803. void SetDirectHostTypeId(TypeId typeId) {directHostTypeId = typeId; }
  804. TypeId GetDirectHostTypeId() const { return directHostTypeId; }
  805. #if ENABLE_NATIVE_CODEGEN
  806. PSCRIPTCONTEXT_HANDLE GetRemoteScriptAddr(bool allowInitialize = true)
  807. {
  808. #if ENABLE_OOP_NATIVE_CODEGEN
  809. if (!m_remoteScriptContextAddr && allowInitialize)
  810. {
  811. InitializeRemoteScriptContext();
  812. }
  813. #endif
  814. return m_remoteScriptContextAddr;
  815. }
  816. #endif
  817. char16 const * GetUrl() const { return url; }
  818. void SetUrl(BSTR bstr);
  819. #ifdef RUNTIME_DATA_COLLECTION
  820. time_t GetCreateTime() const { return createTime; }
  821. uint GetAllocId() const { return allocId; }
  822. #endif
  823. #ifdef HEAP_ENUMERATION_VALIDATION
  824. bool IsInitialized() { return this->isInitialized; }
  825. #endif
  826. #ifdef ENABLE_SCRIPT_DEBUGGING
  827. bool IsDebugContextInitialized() const { return this->isDebugContextInitialized; }
  828. DebugContext* GetDebugContext() const;
  829. CriticalSection* GetDebugContextCloseCS() { return &debugContextCloseCS; }
  830. #endif
  831. uint callCount;
  832. // if the current context is for webworker
  833. DWORD webWorkerId;
  834. static ScriptContext * New(ThreadContext * threadContext);
  835. ~ScriptContext();
  836. #ifdef PROFILE_TYPES
  837. void ProfileTypes();
  838. #endif
  839. #ifdef PROFILE_OBJECT_LITERALS
  840. void ProfileObjectLiteral();
  841. #endif
  842. //
  843. // Regex helpers
  844. //
  845. #if ENABLE_REGEX_CONFIG_OPTIONS
  846. UnifiedRegex::RegexStatsDatabase* GetRegexStatsDatabase();
  847. UnifiedRegex::DebugWriter* GetRegexDebugWriter();
  848. #endif
  849. RegexPatternMruMap* GetDynamicRegexMap() const;
  850. UnifiedRegex::TrigramAlphabet* GetTrigramAlphabet() { return trigramAlphabet; }
  851. void SetTrigramAlphabet(UnifiedRegex::TrigramAlphabet * trigramAlphabet);
  852. UnifiedRegex::RegexStacks *RegexStacks();
  853. UnifiedRegex::RegexStacks *AllocRegexStacks();
  854. UnifiedRegex::RegexStacks *SaveRegexStacks();
  855. void RestoreRegexStacks(UnifiedRegex::RegexStacks *const contStack);
  856. void InitializeGlobalObject();
  857. bool IsIntlEnabled();
  858. bool IsJsBuiltInEnabled();
  859. JavascriptLibrary* GetLibrary() const { return javascriptLibrary; }
  860. Js::Cache* Cache() const{ return &this->javascriptLibrary->cache; }
  861. const JavascriptLibraryBase* GetLibraryBase() const { return javascriptLibrary->GetLibraryBase(); }
  862. #if DBG
  863. BOOL IsCloningGlobal() const { return isCloningGlobal;}
  864. #endif
  865. void PushObject(Var object);
  866. Var PopObject();
  867. BOOL CheckObject(Var object);
  868. inline bool IsHeapEnumInProgress() { return GetRecycler()->IsHeapEnumInProgress(); }
  869. bool IsInterpreted() { return config.IsNoNative(); }
  870. void ForceNoDynamicThunks() { config.ForceNoDynamicThunks(); }
  871. void ForceNoNative() { config.ForceNoNative(); }
  872. void ForceNative() { config.ForceNative(); }
  873. ScriptConfiguration const * GetConfig(void) const { return &config; }
  874. CharClassifier const * GetCharClassifier(void) const;
  875. static bool ExceedsStackNestedFuncCount(uint count);
  876. ThreadContext * GetThreadContext() const { return threadContext; }
  877. static const int MaxEvalSourceSize = 400;
  878. bool IsInEvalMap(FastEvalMapString const& key, BOOL isIndirect, ScriptFunction **ppFuncScript);
  879. void AddToEvalMap(FastEvalMapString & key, BOOL isIndirect, ScriptFunction *pFuncScript);
  880. template <typename TCacheType>
  881. void CleanDynamicFunctionCache(TCacheType* cacheType);
  882. template <class TDelegate>
  883. void MapFunction(TDelegate mapper);
  884. template <class TDelegate>
  885. FunctionBody* FindFunction(TDelegate predicate);
  886. inline bool EnableEvalMapCleanup() { return CONFIG_FLAG(EnableEvalMapCleanup); };
  887. uint GetNextSourceContextId();
  888. bool IsInNewFunctionMap(EvalMapString const& key, FunctionInfo **ppFuncInfo);
  889. void AddToNewFunctionMap(EvalMapString const& key, FunctionInfo *pFuncInfo);
  890. SourceContextInfo * GetSourceContextInfo(DWORD_PTR hostSourceContext, SimpleDataCacheWrapper* dataCacheWrapper);
  891. SourceContextInfo * GetSourceContextInfo(uint hash);
  892. SourceContextInfo * CreateSourceContextInfo(uint hash, DWORD_PTR hostSourceContext);
  893. SourceContextInfo * CreateSourceContextInfo(DWORD_PTR hostSourceContext, char16 const * url, size_t len,
  894. SimpleDataCacheWrapper* dataCacheWrapper, char16 const * sourceMapUrl = nullptr, size_t sourceMapUrlLen = 0);
  895. #if defined(LEAK_REPORT) || defined(CHECK_MEMORY_LEAK)
  896. void ClearSourceContextInfoMaps()
  897. {
  898. #if ENABLE_PROFILE_INFO
  899. this->referencesSharedDynamicSourceContextInfo = false;
  900. #endif
  901. }
  902. #endif
  903. #if ENABLE_PROFILE_INFO
  904. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  905. void ClearDynamicProfileList()
  906. {
  907. if (this->Cache()->profileInfoList)
  908. {
  909. this->Cache()->profileInfoList->Reset();
  910. this->Cache()->profileInfoList = nullptr;
  911. }
  912. }
  913. DynamicProfileInfoList * GetProfileInfoList() { return this->Cache()->profileInfoList; }
  914. #endif
  915. #endif
  916. SRCINFO const * GetModuleSrcInfo(Js::ModuleID moduleID);
  917. SourceContextInfoMap* GetSourceContextInfoMap()
  918. {
  919. return this->Cache()->sourceContextInfoMap;
  920. }
  921. DynamicSourceContextInfoMap* GetDynamicSourceContextInfoMap()
  922. {
  923. return this->Cache()->dynamicSourceContextInfoMap;
  924. }
  925. #if ENABLE_TTD
  926. //The host callback functor info
  927. HostScriptContextCallbackFunctor TTDHostCallbackFunctor;
  928. //The LogTag for this script context (the same as the tag for the global object but we put it here for fast lookup)
  929. TTD_LOG_PTR_ID ScriptContextLogTag;
  930. //Info about the core image for the context
  931. TTD::RuntimeContextInfo* TTDWellKnownInfo;
  932. //Additional runtime context that we only care about if TTD is running (or will be running)
  933. TTD::ScriptContextTTD* TTDContextInfo;
  934. //A flag indicating a TTDSnapshot is in progress
  935. bool TTDSnapshotOrInflateInProgress;
  936. //Check if a snapshot is in progress on this context
  937. bool IsTTDSnapshotOrInflateInProgress() const { return this->TTDSnapshotOrInflateInProgress; }
  938. //Memoized results for frequently used Record/Replay action checks
  939. bool TTDRecordOrReplayModeEnabled;
  940. bool TTDRecordModeEnabled;
  941. bool TTDReplayModeEnabled;
  942. bool TTDShouldPerformRecordOrReplayAction;
  943. bool TTDShouldPerformRecordAction;
  944. bool TTDShouldPerformReplayAction;
  945. bool TTDShouldPerformRecordOrReplayDebuggerAction;
  946. bool TTDShouldPerformRecordDebuggerAction;
  947. bool TTDShouldPerformReplayDebuggerAction;
  948. bool TTDShouldSuppressGetterInvocationForDebuggerEvaluation;
  949. //Check if the TTD system has been activated (and record/replay may or may not be enabled)
  950. bool IsTTDRecordOrReplayModeEnabled() const { return this->TTDRecordOrReplayModeEnabled; }
  951. //Check if the TTD Record system has been activated (and may or may not be enabled)
  952. bool IsTTDRecordModeEnabled() const { return this->TTDRecordModeEnabled; }
  953. //Check if the TTD Replay system has been activated (and may or may not be enabled)
  954. bool IsTTDReplayModeEnabled() const { return this->TTDReplayModeEnabled; }
  955. //Check if we are in (record OR replay) AND this code is being run on behalf of the user application
  956. bool ShouldPerformRecordOrReplayAction() const { return this->TTDShouldPerformRecordOrReplayAction; }
  957. //Use this to check specifically if we are in record AND this code is being run on behalf of the user application
  958. bool ShouldPerformRecordAction() const { return this->TTDShouldPerformRecordAction; }
  959. //Use this to check specifically if we are in replay mode AND this code is being run on behalf of the user application
  960. bool ShouldPerformReplayAction() const { return this->TTDShouldPerformReplayAction; }
  961. //Use this to check specifically if we are in debugging mode AND this code is being run on behalf of the user application
  962. bool ShouldPerformRecordOrReplayDebuggerAction() const { return this->TTDShouldPerformRecordOrReplayDebuggerAction; }
  963. //Use this to check specifically if we are in debugging record mode AND this code is being run on behalf of the user application
  964. bool ShouldPerformRecordDebuggerAction() const { return this->TTDShouldPerformRecordDebuggerAction; }
  965. //Use this to check specifically if we are in debugging replay mode AND this code is being run on behalf of the user application
  966. bool ShouldPerformReplayDebuggerAction() const { return this->TTDShouldPerformReplayDebuggerAction; }
  967. //A special check to see if we are debugging and want to suppress the execution of getters (which may be triggered by displaying values in the debugger)
  968. bool ShouldSuppressGetterInvocationForDebuggerEvaluation() const { return this->TTDShouldSuppressGetterInvocationForDebuggerEvaluation; }
  969. //
  970. //TODO: this is currently called explicitly -- we need to fix up the core image computation and this will be eliminated then
  971. //
  972. //Initialize the core object image for TTD
  973. void InitializeCoreImage_TTD();
  974. #endif
  975. void SetFirstInterpreterFrameReturnAddress(void * returnAddress) { firstInterpreterFrameReturnAddress = returnAddress;}
  976. void *GetFirstInterpreterFrameReturnAddress() { return firstInterpreterFrameReturnAddress;}
  977. void CleanupWeakReferenceDictionaries();
  978. void Initialize();
  979. bool Close(bool inDestructor);
  980. void MarkForClose();
  981. void SetCanOptimizeGlobalLookupFlag(BOOL f){ config.SetCanOptimizeGlobalLookupFlag(f);}
  982. BOOL CanOptimizeGlobalLookup(){ return config.CanOptimizeGlobalLookup();}
  983. bool IsFastDOMEnabled() { return fastDOMenabled; }
  984. void SetFastDOMenabled();
  985. BOOL VerifyAlive(BOOL isJSFunction = FALSE, ScriptContext* requestScriptContext = nullptr);
  986. void VerifyAliveWithHostContext(BOOL isJSFunction, HostScriptContext* requestHostScriptContext);
  987. void BindReference(void* addr);
  988. void InitPropertyStringMap(int i);
  989. PropertyString* AddPropertyString2(const Js::PropertyRecord* propertyRecord);
  990. PropertyString* CachePropertyString2(const Js::PropertyRecord* propertyRecord);
  991. PropertyString* GetPropertyString2(char16 ch1, char16 ch2);
  992. void FindPropertyRecord(__in LPCWSTR pszPropertyName, __in int propertyNameLength, PropertyRecord const** propertyRecord);
  993. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>* FindPropertyIdNoCase(__in LPCWSTR pszPropertyName, __in int propertyNameLength);
  994. void FindPropertyRecord(JavascriptString* pstName, PropertyRecord const** propertyRecord);
  995. PropertyRecord const * GetPropertyName(PropertyId propertyId);
  996. PropertyRecord const * GetPropertyNameLocked(PropertyId propertyId);
  997. void GetOrAddPropertyRecord(JsUtil::CharacterBuffer<WCHAR> const& propName, PropertyRecord const** propertyRecord);
  998. template <size_t N> void GetOrAddPropertyRecord(const char16(&propertyName)[N], PropertyRecord const** propertyRecord)
  999. {
  1000. GetOrAddPropertyRecord(propertyName, N - 1, propertyRecord);
  1001. }
  1002. void GetOrAddPropertyRecord(_In_ Js::JavascriptString * propertyString, _Out_ PropertyRecord const** propertyRecord);
  1003. PropertyId GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName);
  1004. template <size_t N> PropertyId GetOrAddPropertyIdTracked(const char16(&propertyName)[N])
  1005. {
  1006. return GetOrAddPropertyIdTracked(propertyName, N - 1);
  1007. }
  1008. PropertyId GetOrAddPropertyIdTracked(__in_ecount(propertyNameLength) LPCWSTR pszPropertyName, __in int propertyNameLength);
  1009. void GetOrAddPropertyRecord(__in_ecount(propertyNameLength) LPCWSTR pszPropertyName, _In_ int propertyNameLength, _Out_ PropertyRecord const** propertyRecord);
  1010. BOOL IsNumericPropertyId(PropertyId propertyId, uint32* value);
  1011. void RegisterWeakReferenceDictionary(JsUtil::IWeakReferenceDictionary* weakReferenceDictionary);
  1012. void ResetWeakReferenceDictionaryList() { weakReferenceDictionaryList.Reset(); }
  1013. BOOL ReserveStaticTypeIds(__in int first, __in int last);
  1014. TypeId ReserveTypeIds(int count);
  1015. TypeId CreateTypeId();
  1016. template<WellKnownHostType wellKnownType>
  1017. bool IsWellKnownHostType(Js::TypeId typeId) { return threadContext->IsWellKnownHostType<wellKnownType>(typeId); }
  1018. void SetWellKnownHostTypeId(WellKnownHostType wellKnownType, Js::TypeId typeId) { threadContext->SetWellKnownHostTypeId(wellKnownType, typeId); }
  1019. ParseNodeProg * ParseScript(Parser* parser, const byte* script,
  1020. size_t cb, SRCINFO const * pSrcInfo,
  1021. CompileScriptException * pse, Utf8SourceInfo** ppSourceInfo,
  1022. const char16 *rootDisplayName, LoadScriptFlag loadScriptFlag,
  1023. uint* sourceIndex, Js::Var scriptSource = nullptr);
  1024. JavascriptFunction* LoadScript(const byte* script, size_t cb,
  1025. SRCINFO const * pSrcInfo,
  1026. CompileScriptException * pse, Utf8SourceInfo** ppSourceInfo,
  1027. const char16 *rootDisplayName, LoadScriptFlag loadScriptFlag,
  1028. Js::Var scriptSource = nullptr);
  1029. JavascriptFunction* LoadScriptInternal(Parser* parser,
  1030. const byte* script, size_t cb,
  1031. SRCINFO const * pSrcInfo,
  1032. CompileScriptException * pse, Utf8SourceInfo** ppSourceInfo,
  1033. const char16 *rootDisplayName, LoadScriptFlag loadScriptFlag,
  1034. Js::Var scriptSource = nullptr);
  1035. HRESULT TryDeserializeParserState(
  1036. _In_ ULONG grfscr,
  1037. _In_ uint sourceCRC,
  1038. _In_ charcount_t cchLength,
  1039. _In_ SRCINFO *srcInfo,
  1040. _In_ Js::Utf8SourceInfo* utf8SourceInfo,
  1041. _Inout_ uint& sourceIndex,
  1042. _In_ bool isCesu8,
  1043. _In_opt_ NativeModule* nativeModule,
  1044. _Outptr_ Js::ParseableFunctionInfo ** func,
  1045. _Outptr_result_buffer_(*parserStateCacheByteCount) byte** parserStateCacheBuffer,
  1046. _Out_ DWORD* parserStateCacheByteCount,
  1047. _In_ Js::SimpleDataCacheWrapper* pDataCache);
  1048. HRESULT TrySerializeParserState(
  1049. _In_ uint sourceCRC,
  1050. _In_reads_bytes_(cbLength) LPCUTF8 pszSrc,
  1051. _In_ size_t cbLength,
  1052. _In_ SRCINFO *srcInfo,
  1053. _In_ Js::ParseableFunctionInfo* func,
  1054. _In_reads_bytes_(parserStateCacheByteCount) byte* parserStateCacheBuffer,
  1055. _In_ DWORD parserStateCacheByteCount,
  1056. _In_ Js::SimpleDataCacheWrapper* pDataCache);
  1057. HRESULT CompileUTF8Core(
  1058. __in Parser& ps,
  1059. __in Js::Utf8SourceInfo* utf8SourceInfo,
  1060. __in SRCINFO *srcInfo,
  1061. __in BOOL fOriginalUTF8Code,
  1062. _In_reads_bytes_(cbLength) LPCUTF8 pszSrc,
  1063. __in size_t cbLength,
  1064. __in ULONG grfscr,
  1065. __in CompileScriptException *pse,
  1066. __inout charcount_t& cchLength,
  1067. __out size_t& srcLength,
  1068. __out uint& sourceIndex,
  1069. __deref_out Js::ParseableFunctionInfo ** func,
  1070. __in_opt Js::SimpleDataCacheWrapper* pDataCache);
  1071. HRESULT SerializeParserState(const byte* script, size_t cb,
  1072. SRCINFO const * pSrcInfo,
  1073. CompileScriptException * pse, Utf8SourceInfo** ppSourceInfo,
  1074. const char16 *rootDisplayName, LoadScriptFlag loadScriptFlag,
  1075. byte** buffer, DWORD* bufferSize, ArenaAllocator* alloc,
  1076. JavascriptFunction** function = nullptr,
  1077. Js::Var scriptSource = nullptr);
  1078. void MakeUtf8SourceInfo(const byte* script,
  1079. size_t cb,
  1080. SRCINFO const * pSrcInfo,
  1081. Utf8SourceInfo** ppSourceInfo,
  1082. LoadScriptFlag loadScriptFlag,
  1083. Js::Var scriptSource);
  1084. ULONG GetParseFlags(LoadScriptFlag loadScriptFlag, Utf8SourceInfo* pSourceInfo, SourceContextInfo* sourceContextInfo);
  1085. ArenaAllocator* GeneralAllocator() { return &generalAllocator; }
  1086. #ifdef ENABLE_BASIC_TELEMETRY
  1087. ArenaAllocator* TelemetryAllocator() { return &telemetryAllocator; }
  1088. #endif
  1089. #ifdef SEPARATE_ARENA
  1090. ArenaAllocator* SourceCodeAllocator() { return &sourceCodeAllocator; }
  1091. ArenaAllocator* RegexAllocator() { return &regexAllocator; }
  1092. #else
  1093. ArenaAllocator* SourceCodeAllocator() { return &generalAllocator; }
  1094. ArenaAllocator* RegexAllocator() { return &generalAllocator; }
  1095. #endif
  1096. #ifdef NEED_MISC_ALLOCATOR
  1097. ArenaAllocator* MiscAllocator() { return &miscAllocator; }
  1098. #endif
  1099. InlineCacheAllocator* GetInlineCacheAllocator() { return &inlineCacheAllocator; }
  1100. CacheAllocator* GetIsInstInlineCacheAllocator() { return &isInstInlineCacheAllocator; }
  1101. CacheAllocator * GetEnumeratorAllocator() { return &enumeratorCacheAllocator; }
  1102. ArenaAllocator* DynamicProfileInfoAllocator() { return &dynamicProfileInfoAllocator; }
  1103. #ifdef ENABLE_SCRIPT_DEBUGGING
  1104. ArenaAllocator* AllocatorForDiagnostics();
  1105. #endif
  1106. Js::TempArenaAllocatorObject* GetTemporaryAllocator(LPCWSTR name);
  1107. void ReleaseTemporaryAllocator(Js::TempArenaAllocatorObject* tempAllocator);
  1108. Js::TempGuestArenaAllocatorObject* GetTemporaryGuestAllocator(LPCWSTR name);
  1109. void ReleaseTemporaryGuestAllocator(Js::TempGuestArenaAllocatorObject* tempAllocator);
  1110. bool EnsureInterpreterArena(ArenaAllocator **);
  1111. void ReleaseInterpreterArena();
  1112. Recycler* GetRecycler() const { return recycler; }
  1113. RecyclerJavascriptNumberAllocator * GetNumberAllocator() { return &numberAllocator; }
  1114. #if ENABLE_NATIVE_CODEGEN
  1115. NativeCodeGenerator * GetNativeCodeGenerator() const { return nativeCodeGen; }
  1116. #endif
  1117. #if ENABLE_BACKGROUND_PARSING
  1118. BackgroundParser * GetBackgroundParser() const { return backgroundParser; }
  1119. #endif
  1120. void OnScriptStart(bool isRoot, bool isScript);
  1121. void OnScriptEnd(bool isRoot, bool isForcedEnd);
  1122. template <bool stackProbe, bool leaveForHost>
  1123. bool LeaveScriptStart(void * frameAddress);
  1124. template <bool leaveForHost>
  1125. void LeaveScriptEnd(void * frameAddress);
  1126. HostScriptContext * GetHostScriptContext() const { return hostScriptContext; }
  1127. void SetHostScriptContext(HostScriptContext * hostScriptContext);
  1128. void SetScriptEngineHaltCallback(HaltCallback* scriptEngine);
  1129. void ClearHostScriptContext();
  1130. IActiveScriptProfilerHeapEnum* GetHeapEnum();
  1131. void SetHeapEnum(IActiveScriptProfilerHeapEnum* newHeapEnum);
  1132. void ClearHeapEnum();
  1133. void SetScriptStartEventHandler(EventHandler eventHandler);
  1134. void SetScriptEndEventHandler(EventHandler eventHandler);
  1135. #ifdef FAULT_INJECTION
  1136. void DisposeScriptContextByFaultInjection();
  1137. void SetDisposeDisposeByFaultInjectionEventHandler(EventHandler eventHandler);
  1138. #endif
  1139. EnumeratedObjectCache* GetEnumeratedObjectCache() { return &(this->Cache()->enumObjCache); }
  1140. PropertyString* GetPropertyString(PropertyId propertyId);
  1141. PropertyString* GetPropertyString(const PropertyRecord* propertyRecord);
  1142. JavascriptSymbol* GetSymbol(PropertyId propertyId);
  1143. JavascriptSymbol* GetSymbol(const PropertyRecord* propertyRecord);
  1144. void InvalidatePropertyStringAndSymbolCaches(PropertyId propertyId, Type* type);
  1145. JavascriptString* GetIntegerString(Var aValue);
  1146. JavascriptString* GetIntegerString(int value);
  1147. JavascriptString* GetIntegerString(uint value);
  1148. void CheckEvalRestriction();
  1149. RecyclableObject* GetMissingPropertyResult();
  1150. RecyclableObject* GetMissingItemResult();
  1151. bool HasRecordedException() const { return threadContext->GetRecordedException() != nullptr; }
  1152. Js::JavascriptExceptionObject * GetAndClearRecordedException(bool *considerPassingToDebugger = nullptr);
  1153. void RecordException(Js::JavascriptExceptionObject * exceptionObject, bool propagateToDebugger = false);
  1154. __declspec(noreturn) void RethrowRecordedException(JavascriptExceptionObject::HostWrapperCreateFuncType hostWrapperCreateFunc);
  1155. #if ENABLE_NATIVE_CODEGEN
  1156. BOOL IsNativeAddress(void * codeAddr);
  1157. #endif
  1158. uint SaveSourceNoCopy(Utf8SourceInfo* sourceInfo, int cchLength, bool isCesu8);
  1159. Utf8SourceInfo* GetSource(uint sourceIndex);
  1160. void RemoveSource(uint sourceIndex);
  1161. uint SourceCount() const { return (uint)sourceList->Count(); }
  1162. void CleanSourceList() { CleanSourceListInternal(false); }
  1163. SourceList* GetSourceList() const { return sourceList; }
  1164. bool IsItemValidInSourceList(int index);
  1165. template <typename TFunction>
  1166. void MapScript(TFunction mapper)
  1167. {
  1168. this->sourceList->Map([mapper] (int, RecyclerWeakReference<Utf8SourceInfo>* sourceInfoWeakReference)
  1169. {
  1170. Utf8SourceInfo* strongRef = sourceInfoWeakReference->Get();
  1171. if (strongRef)
  1172. {
  1173. mapper(strongRef);
  1174. }
  1175. });
  1176. }
  1177. #ifdef CHECK_STACKWALK_EXCEPTION
  1178. void SetIgnoreStackWalkException() {threadContext->GetScriptEntryExit()->ignoreStackWalkException = true; }
  1179. #endif
  1180. // For debugging scenarios where execution will go to debugging manager and come back to engine again, enforce the current EER to have
  1181. // 'hasCaller' property set, which will enable the stack walking across frames.
  1182. // Do not call this directly, look for ENFORCE_ENTRYEXITRECORD_HASCALLER macro.
  1183. void EnforceEERHasCaller() { threadContext->GetScriptEntryExit()->hasCaller = true; }
  1184. #ifdef ENABLE_SCRIPT_DEBUGGING
  1185. void SetRaiseMessageToDebuggerFunction(RaiseMessageToDebuggerFunctionType function)
  1186. {
  1187. raiseMessageToDebuggerFunctionType = function;
  1188. }
  1189. void RaiseMessageToDebugger(DEBUG_EVENT_INFO_TYPE messageType, LPCWSTR message, LPCWSTR url)
  1190. {
  1191. if (raiseMessageToDebuggerFunctionType != nullptr)
  1192. {
  1193. raiseMessageToDebuggerFunctionType(this, messageType, message, url);
  1194. }
  1195. }
  1196. void SetTransitionToDebugModeIfFirstSourceFn(TransitionToDebugModeIfFirstSourceFn function)
  1197. {
  1198. transitionToDebugModeIfFirstSourceFn = function;
  1199. }
  1200. void TransitionToDebugModeIfFirstSource(Utf8SourceInfo *sourceInfo)
  1201. {
  1202. if (transitionToDebugModeIfFirstSourceFn != nullptr)
  1203. {
  1204. transitionToDebugModeIfFirstSourceFn(this, sourceInfo);
  1205. }
  1206. }
  1207. #endif
  1208. void AddSourceSize(size_t sourceSize)
  1209. {
  1210. this->sourceSize += sourceSize;
  1211. this->threadContext->AddSourceSize(sourceSize);
  1212. }
  1213. size_t GetSourceSize()
  1214. {
  1215. return this->sourceSize;
  1216. }
  1217. BOOL SetDeferredBody(BOOL set)
  1218. {
  1219. bool old = this->deferredBody;
  1220. this->deferredBody = !!set;
  1221. return old;
  1222. }
  1223. BOOL GetDeferredBody(void) const
  1224. {
  1225. return this->deferredBody;
  1226. }
  1227. private:
  1228. Js::PropertyId emptyStringPropertyId;
  1229. public:
  1230. Js::PropertyId GetEmptyStringPropertyId()
  1231. {
  1232. return threadContext->GetEmptyStringPropertyId();
  1233. }
  1234. void FreeFunctionEntryPoint(Js::JavascriptMethod codeAddress, Js::JavascriptMethod thunkAddress);
  1235. public:
  1236. void RegisterProtoInlineCache(InlineCache *pCache, PropertyId propId);
  1237. void InvalidateProtoCaches(const PropertyId propertyId);
  1238. void InvalidateAllProtoCaches();
  1239. void RegisterStoreFieldInlineCache(InlineCache *pCache, PropertyId propId);
  1240. void InvalidateStoreFieldCaches(const PropertyId propertyId);
  1241. void InvalidateAllStoreFieldCaches();
  1242. void RegisterIsInstInlineCache(Js::IsInstInlineCache * cache, Js::Var function);
  1243. #if DBG
  1244. bool IsIsInstInlineCacheRegistered(Js::IsInstInlineCache * cache, Js::Var function);
  1245. #endif
  1246. void ClearInlineCaches();
  1247. void ClearIsInstInlineCaches();
  1248. void ClearEnumeratorCaches();
  1249. #ifdef PERSISTENT_INLINE_CACHES
  1250. void ClearInlineCachesWithDeadWeakRefs();
  1251. #endif
  1252. void ClearScriptContextCaches();
  1253. #if ENABLE_NATIVE_CODEGEN
  1254. void RegisterConstructorCache(Js::PropertyId propertyId, Js::ConstructorCache* cache);
  1255. #endif
  1256. public:
  1257. JavascriptString * GetLastNumberToStringRadix10(double value);
  1258. void SetLastNumberToStringRadix10(double value, JavascriptString * str);
  1259. bool GetLastUtcTimeFromStr(JavascriptString * str, double& dbl);
  1260. void SetLastUtcTimeFromStr(JavascriptString * str, double value);
  1261. bool IsNoContextSourceContextInfo(SourceContextInfo *sourceContextInfo) const
  1262. {
  1263. return sourceContextInfo == this->Cache()->noContextSourceContextInfo;
  1264. }
  1265. BOOL IsProfiling()
  1266. {
  1267. #ifdef ENABLE_SCRIPT_PROFILING
  1268. return (m_pProfileCallback != nullptr);
  1269. #else
  1270. return FALSE;
  1271. #endif
  1272. }
  1273. BOOL IsInProfileCallback()
  1274. {
  1275. #ifdef ENABLE_SCRIPT_PROFILING
  1276. return m_inProfileCallback;
  1277. #else
  1278. return FALSE;
  1279. #endif
  1280. }
  1281. SRCINFO *AddHostSrcInfo(SRCINFO const *pSrcInfo);
  1282. #if DBG
  1283. SourceContextInfo const * GetNoContextSourceContextInfo() const { return this->Cache()->noContextSourceContextInfo; }
  1284. bool hadProfiled;
  1285. bool HadProfiled() const { return hadProfiled; }
  1286. #ifdef ENABLE_SCRIPT_PROFILING
  1287. int GetProfileSession()
  1288. {
  1289. AssertMsg(m_pProfileCallback != nullptr, "Asking for profile session when we aren't in one.");
  1290. return m_iProfileSession;
  1291. }
  1292. void StartNewProfileSession()
  1293. {
  1294. AssertMsg(m_pProfileCallback != nullptr, "New Session when the profiler isn't set to any callback.");
  1295. m_iProfileSession++;
  1296. }
  1297. void StopProfileSession()
  1298. {
  1299. AssertMsg(m_pProfileCallback == nullptr, "How to stop when there is still the callback out there");
  1300. }
  1301. #endif // ENABLE_SCRIPT_PROFILING
  1302. #endif
  1303. #ifdef ENABLE_SCRIPT_PROFILING
  1304. void CoreSetProfileEventMask(DWORD dwEventMask);
  1305. typedef HRESULT(*RegisterExternalLibraryType)(Js::ScriptContext *pScriptContext);
  1306. HRESULT RegisterProfileProbe(IActiveScriptProfilerCallback *pProfileCallback, DWORD dwEventMask, DWORD dwContext, RegisterExternalLibraryType RegisterExternalLibrary, JavascriptMethod dispatchInvoke);
  1307. HRESULT DeRegisterProfileProbe(HRESULT hrReason, JavascriptMethod dispatchInvoke);
  1308. HRESULT RegisterLibraryFunction(const char16 *pwszObjectName, const char16 *pwszFunctionName, Js::PropertyId functionPropertyId, JavascriptMethod entryPoint);
  1309. HRESULT RegisterBuiltinFunctions(RegisterExternalLibraryType RegisterExternalLibrary);
  1310. HRESULT SetProfileEventMask(DWORD dwEventMask);
  1311. HRESULT RegisterScript(Js::FunctionProxy *pFunctionBody, BOOL fRegisterScript = TRUE);
  1312. // Register static and dynamic scripts
  1313. HRESULT RegisterAllScripts();
  1314. #endif
  1315. #ifdef ENABLE_SCRIPT_DEBUGGING
  1316. // Iterate through utf8sourceinfo and clear debug document if they are there.
  1317. void EnsureClearDebugDocument();
  1318. void UpdateRecyclerFunctionEntryPointsForDebugger();
  1319. static void RecyclerFunctionCallbackForDebugger(void *address, size_t size);
  1320. void SetFunctionInRecyclerToProfileMode(bool enumerateNonUserFunctionsOnly = false);
  1321. #ifdef ASMJS_PLAT
  1322. void TransitionEnvironmentForDebugger(ScriptFunction * scriptFunction);
  1323. #endif
  1324. #endif
  1325. // To be called directly only when the thread context is shutting down
  1326. void ShutdownClearSourceLists();
  1327. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  1328. void RegisterDebugThunk(bool calledDuringAttach = true);
  1329. void UnRegisterDebugThunk();
  1330. static void SetEntryPointToProfileThunk(JavascriptFunction* function);
  1331. static void RestoreEntryPointFromProfileThunk(JavascriptFunction* function);
  1332. static void RecyclerEnumClassEnumeratorCallback(void *address, size_t size);
  1333. #endif
  1334. #if ENABLE_NATIVE_CODEGEN
  1335. HRESULT RecreateNativeCodeGenerator(NativeCodeGenerator ** previousCodeGen = nullptr);
  1336. void DeletePreviousNativeCodeGenerator(NativeCodeGenerator * codeGen);
  1337. HRESULT OnDebuggerAttachedDetached(bool attach, NativeCodeGenerator ** previousCodeGenHolder = nullptr);
  1338. #else
  1339. HRESULT OnDebuggerAttachedDetached(bool attach);
  1340. #endif
  1341. bool IsForceNoNative();
  1342. #ifdef ENABLE_SCRIPT_DEBUGGING
  1343. HRESULT OnDebuggerAttached();
  1344. HRESULT OnDebuggerDetached();
  1345. void InitializeDebugging();
  1346. bool IsEnumeratingRecyclerObjects() const { return isEnumeratingRecyclerObjects; }
  1347. private:
  1348. class AutoEnumeratingRecyclerObjects
  1349. {
  1350. public:
  1351. AutoEnumeratingRecyclerObjects(ScriptContext* scriptContext):
  1352. m_scriptContext(scriptContext)
  1353. {
  1354. Assert(!m_scriptContext->IsEnumeratingRecyclerObjects());
  1355. m_scriptContext->isEnumeratingRecyclerObjects = true;
  1356. }
  1357. ~AutoEnumeratingRecyclerObjects()
  1358. {
  1359. Assert(m_scriptContext->IsEnumeratingRecyclerObjects());
  1360. m_scriptContext->isEnumeratingRecyclerObjects = false;
  1361. }
  1362. private:
  1363. ScriptContext* m_scriptContext;
  1364. };
  1365. #endif
  1366. #ifdef EDIT_AND_CONTINUE
  1367. private:
  1368. ScriptEditQuery* activeScriptEditQuery;
  1369. void BeginScriptEditEnumFunctions(ScriptEditQuery* scriptEditQuery) { Assert(!activeScriptEditQuery); activeScriptEditQuery = scriptEditQuery; }
  1370. void EndScriptEditEnumFunctions() { Assert(activeScriptEditQuery); activeScriptEditQuery = nullptr; }
  1371. public:
  1372. ScriptEditQuery* GetActiveScriptEditQuery() const { return activeScriptEditQuery; }
  1373. class AutoScriptEditEnumFunctions
  1374. {
  1375. public:
  1376. AutoScriptEditEnumFunctions(ScriptContext* scriptContext, ScriptEditQuery* scriptEditQuery) : m_scriptContext(scriptContext)
  1377. {
  1378. scriptContext->BeginScriptEditEnumFunctions(scriptEditQuery);
  1379. }
  1380. ~AutoScriptEditEnumFunctions() { m_scriptContext->EndScriptEditEnumFunctions(); }
  1381. private:
  1382. ScriptContext* m_scriptContext;
  1383. };
  1384. #endif
  1385. private:
  1386. typedef JsUtil::BaseDictionary<JavascriptMethod, Js::PropertyId, ArenaAllocator, PrimeSizePolicy> BuiltinFunctionIdDictionary;
  1387. BuiltinFunctionIdDictionary *m_pBuiltinFunctionIdMap;
  1388. Js::PropertyId GetFunctionNumber(JavascriptMethod entryPoint);
  1389. static const char16* CopyString(const char16* str, size_t charCount, ArenaAllocator* alloc);
  1390. #ifdef ENABLE_JS_ETW
  1391. static charcount_t AppendWithEscapeCharacters(Js::StringBuilder<ArenaAllocator>* stringBuilder, const WCHAR* sourceString, charcount_t sourceStringLen, WCHAR escapeChar, WCHAR charToEscape);
  1392. #endif
  1393. public:
  1394. #if DYNAMIC_INTERPRETER_THUNK
  1395. JavascriptMethod GetNextDynamicAsmJsInterpreterThunk(PVOID* ppDynamicInterpreterThunk);
  1396. JavascriptMethod GetNextDynamicInterpreterThunk(PVOID* ppDynamicInterpreterThunk);
  1397. #if DBG
  1398. BOOL IsDynamicInterpreterThunk(JavascriptMethod address);
  1399. #endif
  1400. void ReleaseDynamicInterpreterThunk(BYTE* address, bool addtoFreeList);
  1401. void ReleaseDynamicAsmJsInterpreterThunk(BYTE* address, bool addtoFreeList);
  1402. #endif
  1403. static Var DebugProfileProbeThunk(RecyclableObject* function, CallInfo callInfo, ...);
  1404. static JavascriptMethod ProfileModeDeferredParse(ScriptFunction **function);
  1405. static Var ProfileModeDeferredParsingThunk(RecyclableObject* function, CallInfo callInfo, ...);
  1406. // Thunks for deferred deserialization of function bodies from the byte code cache
  1407. static JavascriptMethod ProfileModeDeferredDeserialize(ScriptFunction* function);
  1408. static Var ProfileModeDeferredDeserializeThunk(RecyclableObject* function, CallInfo callInfo, ...);
  1409. #if defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  1410. static Var ProfileModeThunk_DebugModeWrapper(JavascriptFunction* function, ScriptContext* scriptContext, JavascriptMethod entryPoint, Arguments& args);
  1411. static JavascriptMethod GetProfileModeThunk(JavascriptMethod entryPoint);
  1412. #endif
  1413. #ifdef ENABLE_SCRIPT_PROFILING
  1414. void SetProfileMode(BOOL fSet);
  1415. BOOL GetProfileInfo(
  1416. JavascriptFunction* function,
  1417. PROFILER_TOKEN &scriptId,
  1418. PROFILER_TOKEN &functionId);
  1419. HRESULT OnScriptCompiled(PROFILER_TOKEN scriptId, PROFILER_SCRIPT_TYPE type, IUnknown *pIDebugDocumentContext);
  1420. HRESULT OnFunctionCompiled(
  1421. PROFILER_TOKEN functionId,
  1422. PROFILER_TOKEN scriptId,
  1423. const WCHAR *pwszFunctionName,
  1424. const WCHAR *pwszFunctionNameHint,
  1425. IUnknown *pIDebugDocumentContext);
  1426. HRESULT OnFunctionEnter(PROFILER_TOKEN scriptId, PROFILER_TOKEN functionId);
  1427. HRESULT OnFunctionExit(PROFILER_TOKEN scriptId, PROFILER_TOKEN functionId);
  1428. static HRESULT FunctionExitSenderThunk(PROFILER_TOKEN functionId, PROFILER_TOKEN scriptId, ScriptContext *pScriptContext);
  1429. static HRESULT FunctionExitByNameSenderThunk(const char16 *pwszFunctionName, ScriptContext *pScriptContext);
  1430. bool SetDispatchProfile(bool fSet, JavascriptMethod dispatchInvoke);
  1431. HRESULT OnDispatchFunctionEnter(const WCHAR *pwszFunctionName);
  1432. HRESULT OnDispatchFunctionExit(const WCHAR *pwszFunctionName);
  1433. #endif // ENABLE_SCRIPT_PROFILING
  1434. void OnStartupComplete();
  1435. void SaveStartupProfileAndRelease(bool isSaveOnClose = false);
  1436. #if ENABLE_PROFILE_INFO
  1437. template<template<typename> class BarrierT>
  1438. void AddDynamicProfileInfo(FunctionBody * functionBody, BarrierT<DynamicProfileInfo>& dynamicProfileInfo);
  1439. #endif
  1440. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  1441. uint allocId;
  1442. #endif
  1443. #ifdef PROFILE_EXEC
  1444. void DisableProfiler();
  1445. void SetRecyclerProfiler();
  1446. void SetProfilerFromScriptContext(ScriptContext * scriptContext);
  1447. void ProfileBegin(Js::Phase);
  1448. void ProfileEnd(Js::Phase);
  1449. void ProfileSuspend(Js::Phase, Js::Profiler::SuspendRecord * suspendRecord);
  1450. void ProfileResume(Js::Profiler::SuspendRecord * suspendRecord);
  1451. void ProfilePrint();
  1452. bool IsProfilerCreated() const { return isProfilerCreated; }
  1453. #endif
  1454. #ifdef PROFILE_MEM
  1455. void DisableProfileMemoryDumpOnDelete() { profileMemoryDump = false; }
  1456. #endif
  1457. #ifdef PROFILE_STRINGS
  1458. StringProfiler * GetStringProfiler(); // May be null if string profiling not enabled
  1459. #endif
  1460. public:
  1461. virtual intptr_t GetNullAddr() const override;
  1462. virtual intptr_t GetUndefinedAddr() const override;
  1463. virtual intptr_t GetTrueAddr() const override;
  1464. virtual intptr_t GetFalseAddr() const override;
  1465. virtual intptr_t GetUndeclBlockVarAddr() const override;
  1466. virtual intptr_t GetEmptyStringAddr() const override;
  1467. virtual intptr_t GetNegativeZeroAddr() const override;
  1468. virtual intptr_t GetNumberTypeStaticAddr() const override;
  1469. virtual intptr_t GetStringTypeStaticAddr() const override;
  1470. virtual intptr_t GetSymbolTypeStaticAddr() const override;
  1471. virtual intptr_t GetObjectTypeAddr() const override;
  1472. virtual intptr_t GetObjectHeaderInlinedTypeAddr() const override;
  1473. virtual intptr_t GetRegexTypeAddr() const override;
  1474. virtual intptr_t GetArrayTypeAddr() const override;
  1475. virtual intptr_t GetNativeIntArrayTypeAddr() const override;
  1476. virtual intptr_t GetNativeFloatArrayTypeAddr() const override;
  1477. virtual intptr_t GetArrayConstructorAddr() const override;
  1478. virtual intptr_t GetCharStringCacheAddr() const override;
  1479. virtual intptr_t GetSideEffectsAddr() const override;
  1480. virtual intptr_t GetArraySetElementFastPathVtableAddr() const override;
  1481. virtual intptr_t GetIntArraySetElementFastPathVtableAddr() const override;
  1482. virtual intptr_t GetFloatArraySetElementFastPathVtableAddr() const override;
  1483. virtual intptr_t GetLibraryAddr() const override;
  1484. virtual intptr_t GetGlobalObjectAddr() const override;
  1485. virtual intptr_t GetGlobalObjectThisAddr() const override;
  1486. virtual intptr_t GetObjectPrototypeAddr() const;
  1487. virtual intptr_t GetFunctionPrototypeAddr() const;
  1488. virtual intptr_t GetNumberAllocatorAddr() const override;
  1489. virtual intptr_t GetRecyclerAddr() const override;
  1490. virtual bool GetRecyclerAllowNativeCodeBumpAllocation() const override;
  1491. virtual bool IsPRNGSeeded() const override;
  1492. virtual intptr_t GetBuiltinFunctionsBaseAddr() const override;
  1493. #ifdef ENABLE_SCRIPT_DEBUGGING
  1494. virtual intptr_t GetDebuggingFlagsAddr() const override;
  1495. virtual intptr_t GetDebugStepTypeAddr() const override;
  1496. virtual intptr_t GetDebugFrameAddressAddr() const override;
  1497. virtual intptr_t GetDebugScriptIdWhenSetAddr() const override;
  1498. #endif
  1499. virtual intptr_t GetChakraLibAddr() const override;
  1500. virtual intptr_t GetAddr() const override;
  1501. virtual intptr_t GetVTableAddress(VTableValue vtableType) const override;
  1502. virtual bool IsRecyclerVerifyEnabled() const override;
  1503. virtual uint GetRecyclerVerifyPad() const override;
  1504. virtual Field(Js::Var)* GetModuleExportSlotArrayAddress(uint moduleIndex, uint slotIndex) override;
  1505. Js::SourceTextModuleRecord* GetModuleRecord(uint moduleId) const
  1506. {
  1507. return javascriptLibrary->GetModuleRecord(moduleId);
  1508. }
  1509. void SetBuiltInLibraryFunction(JavascriptMethod entryPoint, JavascriptFunction* function);
  1510. JavascriptFunction* GetBuiltInLibraryFunction(JavascriptMethod entryPoint);
  1511. private:
  1512. BuiltInLibraryFunctionMap* builtInLibraryFunctions;
  1513. #ifdef RECYCLER_PERF_COUNTERS
  1514. size_t bindReferenceCount;
  1515. #endif
  1516. ScriptContext * nextPendingClose;
  1517. public:
  1518. void SetNextPendingClose(ScriptContext * nextPendingClose);
  1519. inline ScriptContext * GetNextPendingClose() const { return nextPendingClose; }
  1520. #ifdef ENABLE_MUTATION_BREAKPOINT
  1521. // Keep track of all breakpoints in order to properly clean up on debugger detach
  1522. bool HasMutationBreakpoints();
  1523. void InsertMutationBreakpoint(Js::MutationBreakpoint *mutationBreakpoint);
  1524. #endif
  1525. };
  1526. class AutoDynamicCodeReference
  1527. {
  1528. public:
  1529. AutoDynamicCodeReference(ScriptContext* scriptContext):
  1530. m_scriptContext(scriptContext)
  1531. {
  1532. scriptContext->GetLibrary()->BeginDynamicFunctionReferences();
  1533. }
  1534. ~AutoDynamicCodeReference()
  1535. {
  1536. m_scriptContext->GetLibrary()->EndDynamicFunctionReferences();
  1537. }
  1538. private:
  1539. ScriptContext* m_scriptContext;
  1540. };
  1541. template <typename TCacheType>
  1542. void ScriptContext::CleanDynamicFunctionCache(TCacheType* cacheType)
  1543. {
  1544. // Remove eval map functions that haven't been recently used
  1545. // TODO: Metric based on allocation size too? So don't clean if there hasn't been much allocated?
  1546. cacheType->Clean([this](const typename TCacheType::KeyType& key, typename TCacheType::ValueType value) {
  1547. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1548. if (CONFIG_FLAG(DumpEvalStringOnRemoval))
  1549. {
  1550. Output::Print(_u("EvalMap: Removing Dynamic Function String from dynamic function cache: %s\n"), key.str.GetBuffer()); Output::Flush();
  1551. }
  1552. #endif
  1553. });
  1554. }
  1555. template <class TDelegate>
  1556. void ScriptContext::MapFunction(TDelegate mapper)
  1557. {
  1558. if (this->sourceList)
  1559. {
  1560. this->sourceList->Map([&mapper](int, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfo)
  1561. {
  1562. Utf8SourceInfo* sourceInfoStrongRef = sourceInfo->Get();
  1563. if (sourceInfoStrongRef)
  1564. {
  1565. sourceInfoStrongRef->MapFunction(mapper);
  1566. }
  1567. });
  1568. }
  1569. }
  1570. template <class TDelegate>
  1571. FunctionBody* ScriptContext::FindFunction(TDelegate predicate)
  1572. {
  1573. FunctionBody* functionBody = nullptr;
  1574. this->sourceList->MapUntil([&functionBody, &predicate](int, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfo) -> bool
  1575. {
  1576. Utf8SourceInfo* sourceInfoStrongRef = sourceInfo->Get();
  1577. if (sourceInfoStrongRef)
  1578. {
  1579. functionBody = sourceInfoStrongRef->FindFunction(predicate);
  1580. if (functionBody)
  1581. {
  1582. return true;
  1583. }
  1584. }
  1585. return false;
  1586. });
  1587. return functionBody;
  1588. }
  1589. class AutoProfilingPhase
  1590. {
  1591. public:
  1592. AutoProfilingPhase(ScriptContext* scriptcontext, Js::Phase phase) : scriptcontext(scriptcontext), phase(phase), isPhaseComplete(false)
  1593. {
  1594. #ifdef PROFILE_EXEC
  1595. scriptcontext->ProfileBegin(phase);
  1596. #endif
  1597. }
  1598. ~AutoProfilingPhase()
  1599. {
  1600. if(!this->isPhaseComplete)
  1601. {
  1602. EndProfile();
  1603. }
  1604. }
  1605. void EndProfile()
  1606. {
  1607. this->isPhaseComplete = true;
  1608. #ifdef PROFILE_EXEC
  1609. scriptcontext->ProfileEnd(phase);
  1610. #endif
  1611. }
  1612. private:
  1613. ScriptContext* scriptcontext;
  1614. Js::Phase phase;
  1615. bool isPhaseComplete;
  1616. };
  1617. #ifdef ENABLE_SCRIPT_DEBUGGING
  1618. // Set up a scope in which we will initialize library JS code (like Intl.js),
  1619. // which should not be treated as user-level JS code.
  1620. // We should not profile and should not log debugger information in such a scope.
  1621. class AutoInitLibraryCodeScope
  1622. {
  1623. private:
  1624. ScriptContext * const scriptContext;
  1625. const bool oldIsProfilingUserCode;
  1626. const bool oldIsDebuggerRecording;
  1627. public:
  1628. AutoInitLibraryCodeScope(ScriptContext *scriptContext) :
  1629. scriptContext(scriptContext),
  1630. oldIsProfilingUserCode(scriptContext->GetThreadContext()->IsProfilingUserCode()),
  1631. oldIsDebuggerRecording(scriptContext->IsDebuggerRecording())
  1632. {
  1633. this->scriptContext->GetThreadContext()->SetIsProfilingUserCode(false);
  1634. this->scriptContext->SetIsDebuggerRecording(false);
  1635. }
  1636. ~AutoInitLibraryCodeScope()
  1637. {
  1638. this->scriptContext->GetThreadContext()->SetIsProfilingUserCode(this->oldIsProfilingUserCode);
  1639. this->scriptContext->SetIsDebuggerRecording(this->oldIsDebuggerRecording);
  1640. }
  1641. };
  1642. #endif
  1643. }
  1644. #define BEGIN_TEMP_ALLOCATOR(allocator, scriptContext, name) \
  1645. Js::TempArenaAllocatorObject *temp##allocator = scriptContext->GetTemporaryAllocator(name); \
  1646. ArenaAllocator * allocator = temp##allocator->GetAllocator();
  1647. #define END_TEMP_ALLOCATOR(allocator, scriptContext) \
  1648. scriptContext->ReleaseTemporaryAllocator(temp##allocator);
  1649. #define DECLARE_TEMP_ALLOCATOR(allocator) \
  1650. Js::TempArenaAllocatorObject *temp##allocator = nullptr; \
  1651. ArenaAllocator * allocator = nullptr;
  1652. #define ACQUIRE_TEMP_ALLOCATOR(allocator, scriptContext, name) \
  1653. temp##allocator = scriptContext->GetTemporaryAllocator(name); \
  1654. allocator = temp##allocator->GetAllocator();
  1655. #define RELEASE_TEMP_ALLOCATOR(allocator, scriptContext) \
  1656. if (temp##allocator) \
  1657. scriptContext->ReleaseTemporaryAllocator(temp##allocator);
  1658. #define DECLARE_TEMP_GUEST_ALLOCATOR(allocator) \
  1659. Js::TempGuestArenaAllocatorObject *tempGuest##allocator = nullptr; \
  1660. ArenaAllocator * allocator = nullptr;
  1661. #define ACQUIRE_TEMP_GUEST_ALLOCATOR(allocator, scriptContext, name) \
  1662. tempGuest##allocator = scriptContext->GetTemporaryGuestAllocator(name); \
  1663. allocator = tempGuest##allocator->GetAllocator();
  1664. #define RELEASE_TEMP_GUEST_ALLOCATOR(allocator, scriptContext) \
  1665. if (tempGuest##allocator) \
  1666. scriptContext->ReleaseTemporaryGuestAllocator(tempGuest##allocator);