ScriptContext.h 82 KB

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