ScriptContext.h 82 KB

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