• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef ECMASCRIPT_ECMA_VM_H
17 #define ECMASCRIPT_ECMA_VM_H
18 
19 #include "ecmascript/cross_vm/ecma_vm_hybrid.h"
20 
21 #include <mutex>
22 
23 #ifdef PANDA_JS_ETS_HYBRID_MODE
24 #include "ecmascript/cross_vm/cross_vm_operator.h"
25 #endif  // PANDA_JS_ETS_HYBRID_MODE
26 
27 #include "ecmascript/base/config.h"
28 #include "ecmascript/builtins/builtins_method_index.h"
29 #include "ecmascript/global_env_constants.h"
30 #include "ecmascript/global_handle_collection.h"
31 #include "ecmascript/js_handle.h"
32 #include "ecmascript/js_runtime_options.h"
33 #include "ecmascript/mem/c_containers.h"
34 #include "ecmascript/mem/c_string.h"
35 #include "ecmascript/mem/gc_key_stats.h"
36 #include "ecmascript/mem/gc_stats.h"
37 #include "ecmascript/mem/heap_region_allocator.h"
38 #include "ecmascript/napi/include/dfx_jsnapi.h"
39 #include "ecmascript/patch/patch_loader.h"
40 #include "ecmascript/stackmap/ark_stackmap.h"
41 #include "ecmascript/napi/include/jsnapi_expo.h"
42 #include "ecmascript/platform/mutex.h"
43 #include "ecmascript/waiter_list.h"
44 #include "libpandafile/bytecode_instruction-inl.h"
45 
46 namespace panda {
47 class JSNApi;
48 struct HmsMap;
49 namespace panda_file {
50 class File;
51 }  // namespace panda_file
52 
53 namespace ecmascript {
54 class GlobalEnv;
55 class ObjectFactory;
56 class RegExpParserCache;
57 class EcmaRuntimeStat;
58 class Heap;
59 class HeapTracker;
60 class JSNativePointer;
61 class Program;
62 class GCStats;
63 class GCKeyStats;
64 class CpuProfiler;
65 class Tracing;
66 class AsyncStackTrace;
67 class RegExpExecResultCache;
68 class RegExpParserCache;
69 class JSPromise;
70 enum class PromiseRejectionEvent : uint8_t;
71 enum class Concurrent { YES, NO };
72 class JSPandaFileManager;
73 class JSPandaFile;
74 class EcmaStringTable;
75 class SnapshotEnv;
76 class SnapshotSerialize;
77 class SnapshotProcessor;
78 class JSThread;
79 
80 namespace pgo {
81     class PGOProfiler;
82 } // namespace pgo
83 
84 class OptCodeProfiler;
85 class TypedOpProfiler;
86 class FunctionProtoTransitionTable;
87 struct CJSInfo;
88 
89 namespace kungfu {
90 class PGOTypeManager;
91 } // namespace kungfu
92 
93 using PGOProfiler = pgo::PGOProfiler;
94 #if !WIN_OR_MAC_OR_IOS_PLATFORM
95 class HeapProfilerInterface;
96 class HeapProfiler;
97 #endif
98 namespace job {
99 class MicroJobQueue;
100 }  // namespace job
101 
102 namespace tooling {
103 class JsDebuggerManager;
104 }  // namespace tooling
105 
106 template<typename T>
107 class JSHandle;
108 class JSArrayBuffer;
109 class JSFunction;
110 class SourceTextModule;
111 class Program;
112 class AOTFileManager;
113 class SlowRuntimeStub;
114 class RequireManager;
115 class QuickFixManager;
116 class ConstantPool;
117 class FunctionCallTimer;
118 class EcmaStringTable;
119 class JSObjectResizingStrategy;
120 class Jit;
121 class JitThread;
122 class AbcBufferCache;
123 class SustainingJSHandle;
124 class SustainingJSHandleList;
125 struct CJSInfo;
126 enum class CompareStringsOption : uint8_t;
127 
128 using NativePtrGetter = void* (*)(void* info);
129 using SourceMapCallback = std::function<std::string(const std::string& rawStack)>;
130 using SourceMapTranslateCallback = std::function<bool(std::string& url, int& line, int& column,
131     std::string &packageName)>;
132 using ResolveBufferCallback =
133     std::function<bool(std::string dirPath, uint8_t **buff, size_t *buffSize, std::string &errorMsg)>;
134 using TimerCallbackFunc = void (*)(void *data);
135 using TimerTaskCallback = void* (*)(EcmaVM *vm, void *data, TimerCallbackFunc func, uint64_t timeout, bool repeat);
136 using CancelTimerCallback = void (*)(void *timerCallbackInfo);
137 using UnloadNativeModuleCallback = std::function<bool(const std::string &moduleKey)>;
138 using RequestAotCallback =
139     std::function<int32_t(const std::string &bundleName, const std::string &moduleName, int32_t triggerMode)>;
140 using SearchHapPathCallBack = std::function<bool(const std::string moduleName, std::string &hapPath)>;
141 using DeviceDisconnectCallback = std::function<bool()>;
142 using UncatchableErrorHandler = std::function<void(panda::TryCatch&)>;
143 using StopPreLoadSoCallback = std::function<void()>;
144 using HostPromiseRejectionTracker = void (*)(const EcmaVM* vm,
145                                              const JSHandle<JSPromise> promise,
146                                              const JSHandle<JSTaggedValue> reason,
147                                              PromiseRejectionEvent operation,
148                                              void* data);
149 using PromiseRejectCallback = void (*)(void* info);
150 
151 using namespace panda;
152 
153 enum class IcuFormatterType: uint8_t {
154     SIMPLE_DATE_FORMAT_DEFAULT,
155     SIMPLE_DATE_FORMAT_DATE,
156     SIMPLE_DATE_FORMAT_TIME,
157     NUMBER_FORMATTER,
158     COLLATOR,
159     ICU_FORMATTER_TYPE_COUNT
160 };
161 
162 class IntlCache {
163 public:
164     IntlCache() = default;
165 
SetDefaultLocale(const std::string & locale)166     void SetDefaultLocale(const std::string& locale)
167     {
168         defaultLocale_ = locale;
169     }
170 
GetDefaultLocale()171     const std::string& GetDefaultLocale() const
172     {
173         return defaultLocale_;
174     }
175 
SetDefaultCompareStringsOption(const CompareStringsOption csOption)176     void SetDefaultCompareStringsOption(const CompareStringsOption csOption)
177     {
178         defaultCompareStringsOption_ = csOption;
179     }
180 
GetDefaultCompareStringsOption()181     std::optional<CompareStringsOption> GetDefaultCompareStringsOption() const
182     {
183         return defaultCompareStringsOption_;
184     }
185 
186     void SetIcuFormatterToCache(IcuFormatterType type, const std::string& locale, void* icuObj,
187                                 NativePointerCallback deleteEntry = nullptr)
188     {
189         icuObjCache_[static_cast<int>(type)] = IcuFormatter(locale, icuObj, deleteEntry);
190     }
191 
GetIcuFormatterFromCache(IcuFormatterType type,const std::string & locale)192     void* GetIcuFormatterFromCache(IcuFormatterType type, const std::string& locale) const
193     {
194         const auto& icuFormatter = icuObjCache_[static_cast<int>(type)];
195         return icuFormatter.locale == locale ? icuFormatter.icuObj : nullptr;
196     }
197 
ClearIcuCache(void * vmPtr)198     void ClearIcuCache(void* vmPtr)
199     {
200         for (uint32_t i = 0; i < static_cast<uint32_t>(IcuFormatterType::ICU_FORMATTER_TYPE_COUNT); ++i) {
201             auto& icuFormatter = icuObjCache_[i];
202             if (icuFormatter.deleteEntry != nullptr) {
203                 // Fill nullptr into the IcuDeleteEntry's unused env (specifically for napi) field.
204                 icuFormatter.deleteEntry(nullptr, icuFormatter.icuObj, vmPtr);
205             }
206         }
207     }
208 
209 private:
210     class IcuFormatter {
211     public:
212         std::string locale;
213         void* icuObj {nullptr};
214         NativePointerCallback deleteEntry {nullptr};
215 
216         IcuFormatter() = default;
217         IcuFormatter(const std::string& locale, void* icuObj, NativePointerCallback deleteEntry = nullptr)
locale(locale)218             : locale(locale), icuObj(icuObj), deleteEntry(deleteEntry) {}
219     };
220 
221     std::string defaultLocale_;
222     std::optional<CompareStringsOption> defaultCompareStringsOption_ {std::nullopt};
223     IcuFormatter icuObjCache_[static_cast<uint32_t>(IcuFormatterType::ICU_FORMATTER_TYPE_COUNT)];
224 };
225 
226 class EcmaVM {
227 public:
228     static EcmaVM *Create(const JSRuntimeOptions &options);
229 
230     static bool Destroy(EcmaVM *vm);
231 
232     EcmaVM(JSRuntimeOptions options, EcmaParamConfiguration config);
233 
234     EcmaVM();
235 
236     ~EcmaVM();
237 
SetLoop(void * loop)238     void SetLoop(void *loop)
239     {
240         loop_ = loop;
241     }
242 
GetLoop()243     void *GetLoop() const
244     {
245         return loop_;
246     }
247 
IsInitialized()248     bool IsInitialized() const
249     {
250         return initialized_;
251     }
252 
SetPreForked(bool preForked)253     void SetPreForked(bool preForked)
254     {
255         preForked_ = preForked;
256     }
257 
SetPostForked(bool postForked)258     void SetPostForked(bool postForked)
259     {
260         postForked_ = postForked;
261     }
262 
IsPreForked()263     bool IsPreForked() const
264     {
265         return preForked_;
266     }
267 
IsPostForked()268     bool IsPostForked() const
269     {
270         return postForked_;
271     }
272 
SetAgentCanSuspend(bool agentCanSuspend)273     void SetAgentCanSuspend(bool agentCanSuspend)
274     {
275         agentCanSuspend_ = agentCanSuspend;
276     }
277 
GetAgentCanSuspend()278     bool GetAgentCanSuspend() const
279     {
280         return agentCanSuspend_;
281     }
282 
IsAsynTranslateClasses()283     bool IsAsynTranslateClasses()
284     {
285         if (!GetJSOptions().IsAsyncLoadAbcTest()) {
286             return IsPostForked() && GetJSOptions().IsAsyncLoadAbc();
287         }
288         return GetJSOptions().IsAsyncLoadAbc();
289     }
290 
GetFactory()291     ObjectFactory *GetFactory() const
292     {
293         return factory_;
294     }
295 
296     void InitializePGOProfiler();
297     void ResetPGOProfiler();
298     void DisablePGOProfilerWithAOTFile(const std::string &aotFileName);
299 
300     bool PUBLIC_API IsEnablePGOProfiler() const;
301     bool PUBLIC_API IsEnableMutantArray() const;
302     bool PUBLIC_API IsEnableElementsKind() const;
303 
304     bool Initialize();
305     void InitializeForJit(JitThread *thread);
306 
GetEcmaGCStats()307     GCStats *GetEcmaGCStats() const
308     {
309         return gcStats_;
310     }
311 
GetEcmaGCKeyStats()312     GCKeyStats *GetEcmaGCKeyStats() const
313     {
314         return gcKeyStats_;
315     }
316 
SetJSThread(JSThread * thread)317     void SetJSThread(JSThread *thread)
318     {
319         thread_ = thread;
320     }
321 
GetAssociatedJSThread()322     JSThread *GetAssociatedJSThread() const
323     {
324         return thread_;
325     }
326 
GetJSOptions()327     JSRuntimeOptions &GetJSOptions()
328     {
329         return options_;
330     }
331 
GetEcmaParamConfiguration()332     const EcmaParamConfiguration &GetEcmaParamConfiguration() const
333     {
334         return ecmaParamConfiguration_;
335     }
336 
GetGlobalEnv()337     JSHandle<GlobalEnv> PUBLIC_API GetGlobalEnv() const
338     {
339         return thread_->GetGlobalEnv();
340     }
341 
ConstCast(const EcmaVM * vm)342     static EcmaVM *ConstCast(const EcmaVM *vm)
343     {
344         return const_cast<EcmaVM *>(vm);
345     }
346 
347     void PUBLIC_API CheckThread() const;
348     JSThread *GetAndFastCheckJSThread() const;
349     bool CheckSingleThread() const;
350 
GetThreadCheckStatus()351     ARK_INLINE uint32_t GetThreadCheckStatus() const
352     {
353         return options_.EnableThreadCheck() || EcmaVM::GetMultiThreadCheck();
354     }
355 
GetJSThread()356     ARK_INLINE JSThread *GetJSThread() const
357     {
358         // default enable multi-thread check in asan
359 #ifdef ECMASCRIPT_ENABLE_ASAN_THREAD_CHECK
360         CheckThread();
361 #else
362         if (GetThreadCheckStatus()) {
363             CheckThread();
364         }
365 #endif
366         return thread_;
367     }
368 
GetJSThreadNoCheck()369     JSThread *GetJSThreadNoCheck() const
370     {
371         return thread_;
372     }
373 
ICEnabled()374     bool ICEnabled() const
375     {
376         return icEnabled_;
377     }
378 
IsEnableCMCGC()379     uint32_t IsEnableCMCGC() const
380     {
381         return isEnableCMCGC_;
382     }
383 
384     void PushToNativePointerList(JSNativePointer *pointer, Concurrent isConcurrent = Concurrent::NO);
385     void RemoveFromNativePointerList(JSNativePointer *pointer);
386     void PushToDeregisterModuleList(const CString &module);
387     void RemoveFromDeregisterModuleList(CString module);
388     bool ContainInDeregisterModuleList(CString module);
389     JSHandle<ecmascript::JSTaggedValue> GetAndClearEcmaUncaughtException() const;
390     JSHandle<ecmascript::JSTaggedValue> GetEcmaUncaughtException() const;
391 
GetRuntimeStat()392     EcmaRuntimeStat *GetRuntimeStat() const
393     {
394         return runtimeStat_;
395     }
396 
397     void InitializeEcmaScriptRunStat();
398     void SetRuntimeStatEnable(bool flag);
399 
IsOptionalLogEnabled()400     bool IsOptionalLogEnabled() const
401     {
402         return optionalLogEnabled_;
403     }
404 
GetHandleScopeStorageNext()405     JSTaggedType *GetHandleScopeStorageNext() const
406     {
407         return handleScopeStorageNext_;
408     }
409 
SetHandleScopeStorageNext(JSTaggedType * value)410     void SetHandleScopeStorageNext(JSTaggedType *value)
411     {
412         handleScopeStorageNext_ = value;
413     }
414 
GetHandleScopeStorageEnd()415     JSTaggedType *GetHandleScopeStorageEnd() const
416     {
417         return handleScopeStorageEnd_;
418     }
419 
SetHandleScopeStorageEnd(JSTaggedType * value)420     void SetHandleScopeStorageEnd(JSTaggedType *value)
421     {
422         handleScopeStorageEnd_ = value;
423     }
424 
GetCurrentHandleStorageIndex()425     int GetCurrentHandleStorageIndex() const
426     {
427         return currentHandleStorageIndex_;
428     }
429 
GetPrimitiveScopeStorageNext()430     JSTaggedType *GetPrimitiveScopeStorageNext() const
431     {
432         return primitiveScopeStorageNext_;
433     }
434 
SetPrimitiveScopeStorageNext(JSTaggedType * value)435     void SetPrimitiveScopeStorageNext(JSTaggedType *value)
436     {
437         primitiveScopeStorageNext_ = value;
438     }
439 
GetPrimitiveScopeStorageEnd()440     JSTaggedType *GetPrimitiveScopeStorageEnd() const
441     {
442         return primitiveScopeStorageEnd_;
443     }
444 
SetPrimitiveScopeStorageEnd(JSTaggedType * value)445     void SetPrimitiveScopeStorageEnd(JSTaggedType *value)
446     {
447         primitiveScopeStorageEnd_ = value;
448     }
449 
GetCurrentPrimitiveStorageIndex()450     int GetCurrentPrimitiveStorageIndex() const
451     {
452         return currentPrimitiveStorageIndex_;
453     }
454 
455     uintptr_t *ExpandHandleStorage();
456     void ShrinkHandleStorage(int prevIndex);
457     void DeleteHandleStorage();
458     uintptr_t *ExpandPrimitiveStorage();
459     void ShrinkPrimitiveStorage(int prevIndex);
460     void DeletePrimitiveStorage();
461 
462     size_t IterateHandle(RootVisitor &visitor);
463     // Visit all roots, including STW-only and concurrent roots
464     void Iterate(RootVisitor &v);
465     // STW roots are unsafe to visit duirng GC
466     void IterateSTWRoots(RootVisitor &v);
467     // Concurrent roots supports being visited while GC is ongoing
468     void IterateConcurrentRoots(RootVisitor &v);
469     void IterateWeakGlobalEnvList(WeakVisitor &visitor);
470     void IterateGlobalEnvField(RootVisitor &visitor);
471 
GetHeap()472     const Heap *GetHeap() const
473     {
474         return heap_;
475     }
476     void CollectGarbage(TriggerGCType gcType, GCReason reason = GCReason::OTHER) const;
477 
GetNativeAreaAllocator()478     NativeAreaAllocator *GetNativeAreaAllocator() const
479     {
480         return nativeAreaAllocator_.get();
481     }
482 
GetHeapRegionAllocator()483     HeapRegionAllocator *GetHeapRegionAllocator() const
484     {
485         return heapRegionAllocator_.get();
486     }
487 
GetChunk()488     Chunk *GetChunk() const
489     {
490         return const_cast<Chunk *>(&chunk_);
491     }
492     void ProcessNativeDelete(const WeakRootVisitor &visitor);
493     void ProcessReferences(const WeakRootVisitor &visitor);
494     void ProcessSnapShotEnv(const WeakRootVisitor& visitor);
495     void IteratorSnapShotEnv(WeakVisitor& visitor);
496 
GetAsyncStackTrace()497     AsyncStackTrace *GetAsyncStackTrace() const
498     {
499         return asyncStackTrace_;
500     }
501 
502     uint32_t GetAsyncTaskId();
503 
504     bool InsertAsyncStackTrace(const JSHandle<JSPromise> &promise);
505 
506     bool RemoveAsyncStackTrace(const JSHandle<JSPromise> &promise);
507 
GetSnapshotEnv()508     SnapshotEnv *GetSnapshotEnv() const
509     {
510         return snapshotEnv_;
511     }
512 
GetJsDebuggerManager()513     tooling::JsDebuggerManager *GetJsDebuggerManager() const
514     {
515         return debuggerManager_;
516     }
517 
SetDeviceDisconnectCallback(DeviceDisconnectCallback cb)518     void SetDeviceDisconnectCallback(DeviceDisconnectCallback cb)
519     {
520         deviceDisconnectCallback_ = cb;
521     }
522 
GetDeviceDisconnectCallback()523     DeviceDisconnectCallback GetDeviceDisconnectCallback() const
524     {
525         return deviceDisconnectCallback_;
526     }
527 
SetEnableForceGC(bool enable)528     void SetEnableForceGC(bool enable)
529     {
530         options_.SetEnableForceGC(enable);
531     }
532 
SetNativePtrGetter(NativePtrGetter cb)533     void SetNativePtrGetter(NativePtrGetter cb)
534     {
535         nativePtrGetter_ = cb;
536     }
537 
GetNativePtrGetter()538     NativePtrGetter GetNativePtrGetter() const
539     {
540         return nativePtrGetter_;
541     }
542 
SetSourceMapCallback(SourceMapCallback cb)543     void SetSourceMapCallback(SourceMapCallback cb)
544     {
545         sourceMapCallback_ = cb;
546     }
547 
GetSourceMapCallback()548     SourceMapCallback GetSourceMapCallback() const
549     {
550         return sourceMapCallback_;
551     }
552 
SetSourceMapTranslateCallback(SourceMapTranslateCallback cb)553     void SetSourceMapTranslateCallback(SourceMapTranslateCallback cb)
554     {
555         sourceMapTranslateCallback_ = cb;
556     }
557 
GetSourceMapTranslateCallback()558     SourceMapTranslateCallback GetSourceMapTranslateCallback() const
559     {
560         return sourceMapTranslateCallback_;
561     }
562 
SetResolveBufferCallback(ResolveBufferCallback cb)563     void SetResolveBufferCallback(ResolveBufferCallback cb)
564     {
565         resolveBufferCallback_ = cb;
566     }
567 
GetResolveBufferCallback()568     ResolveBufferCallback GetResolveBufferCallback() const
569     {
570         return resolveBufferCallback_;
571     }
572 
SetResolveBufferCallbackForHybridApp(ResolveBufferCallback cb)573     void SetResolveBufferCallbackForHybridApp(ResolveBufferCallback cb)
574     {
575         resolveBufferCallbackForHybridApp_ = cb;
576     }
577 
GetResolveBufferCallbackForHybridApp()578     ResolveBufferCallback GetResolveBufferCallbackForHybridApp() const
579     {
580         return resolveBufferCallbackForHybridApp_;
581     }
582 
SetTimerTaskCallback(TimerTaskCallback callback)583     void SetTimerTaskCallback(TimerTaskCallback callback)
584     {
585         timerTaskCallback_ = callback;
586     }
587 
GetTimerTaskCallback()588     TimerTaskCallback GetTimerTaskCallback() const
589     {
590         return timerTaskCallback_;
591     }
592 
SetCancelTimerCallback(CancelTimerCallback callback)593     void SetCancelTimerCallback(CancelTimerCallback callback)
594     {
595         cancelTimerCallback_ = callback;
596     }
597 
GetCancelTimerCallback()598     CancelTimerCallback GetCancelTimerCallback() const
599     {
600         return cancelTimerCallback_;
601     }
602 
SetSearchHapPathCallBack(SearchHapPathCallBack cb)603     void SetSearchHapPathCallBack(SearchHapPathCallBack cb)
604     {
605         SearchHapPathCallBack_ = cb;
606     }
607 
GetSearchHapPathCallBack()608     SearchHapPathCallBack GetSearchHapPathCallBack() const
609     {
610         return SearchHapPathCallBack_;
611     }
612 
SetUnloadNativeModuleCallback(const UnloadNativeModuleCallback & cb)613     void SetUnloadNativeModuleCallback(const UnloadNativeModuleCallback &cb)
614     {
615         unloadNativeModuleCallback_ = cb;
616     }
617 
GetUnloadNativeModuleCallback()618     UnloadNativeModuleCallback GetUnloadNativeModuleCallback() const
619     {
620         return unloadNativeModuleCallback_;
621     }
622 
SetConcurrentCallback(ConcurrentCallback callback,void * data)623     void SetConcurrentCallback(ConcurrentCallback callback, void *data)
624     {
625         concurrentCallback_ = callback;
626         concurrentData_ = data;
627     }
628 
AddStopPreLoadCallback(const StopPreLoadSoCallback & cb)629     void AddStopPreLoadCallback(const StopPreLoadSoCallback &cb)
630     {
631         stopPreLoadCallbacks_.emplace_back(cb);
632     }
633 
GetStopPreLoadCallbacks()634     CVector<StopPreLoadSoCallback> GetStopPreLoadCallbacks() const
635     {
636         return stopPreLoadCallbacks_;
637     }
638 
639     void StopPreLoadSoOrAbc();
640 
641     void TriggerConcurrentCallback(JSTaggedValue result, JSTaggedValue hint);
642 
643     void WorkersetInfo(EcmaVM *workerVm);
644 
645     EcmaVM *GetWorkerVm(uint32_t tid);
646 
647     bool DeleteWorker(EcmaVM *workerVm);
648 
649     bool SuspendWorkerVm(uint32_t tid);
650 
651     void ResumeWorkerVm(uint32_t tid);
652 
653     template<typename Callback>
EnumerateWorkerVm(Callback cb)654     void EnumerateWorkerVm(Callback cb)
655     {
656         // since there is a lock, so cannot mark function const
657         LockHolder lock(mutex_);
658         for (const auto &item : workerList_) {
659             cb(item.second);
660         }
661     }
662 
IsWorkerThread()663     bool IsWorkerThread() const
664     {
665         return options_.IsWorker();
666     }
667 
IsRestrictedWorkerThread()668     bool IsRestrictedWorkerThread() const
669     {
670         return options_.IsRestrictedWorker();
671     }
672 
IsBundlePack()673     bool IsBundlePack() const
674     {
675         return isBundlePack_;
676     }
677 
SetIsBundlePack(bool value)678     void SetIsBundlePack(bool value)
679     {
680         isBundlePack_ = value;
681     }
682 
683     // UnifiedOhmUrlPack means app compiles ohmurl using old format like "@bundle:",
684     // or new unified rules like "@normalize:"
685     // if pkgContextInfoList is empty, means use old ohmurl packing.
IsNormalizedOhmUrlPack()686     bool IsNormalizedOhmUrlPack()
687     {
688         ReadLockHolder lock(pkgContextInfoLock_);
689         return !pkgContextInfoList_.empty();
690     }
691 
SetPkgNameList(const CMap<CString,CString> & list)692     void SetPkgNameList(const CMap<CString, CString> &list)
693     {
694         WriteLockHolder lock(pkgNameListLock_);
695         pkgNameList_ = list;
696     }
697 
UpdatePkgNameList(const CMap<CString,CString> & list)698     void UpdatePkgNameList(const CMap<CString, CString> &list)
699     {
700         WriteLockHolder lock(pkgNameListLock_);
701         pkgNameList_.insert(list.begin(), list.end());
702     }
703 
GetPkgNameList()704     CMap<CString, CString> GetPkgNameList()
705     {
706         ReadLockHolder lock(pkgNameListLock_);
707         return pkgNameList_;
708     }
709 
GetPkgName(const CString & moduleName)710     inline CString GetPkgName(const CString &moduleName)
711     {
712         ReadLockHolder lock(pkgNameListLock_);
713         auto it = pkgNameList_.find(moduleName);
714         if (it == pkgNameList_.end()) {
715             LOG_ECMA(INFO) << " Get Pkg Name failed";
716             return moduleName;
717         }
718         return it->second;
719     }
720 
UpdatePkgContextInfoList(const CMap<CString,CMap<CString,CVector<CString>>> & list)721     void UpdatePkgContextInfoList(const CMap<CString, CMap<CString, CVector<CString>>> &list)
722     {
723         WriteLockHolder lock(pkgContextInfoLock_);
724         pkgContextInfoList_.insert(list.begin(), list.end());
725     }
726 
GetPkgContextInfoList()727     inline CMap<CString, CMap<CString, CVector<CString>>> GetPkgContextInfoList()
728     {
729         ReadLockHolder lock(pkgContextInfoLock_);
730         return pkgContextInfoList_;
731     }
732 
GetPkgNameWithAlias(const CString & alias)733     inline CString GetPkgNameWithAlias(const CString &alias)
734     {
735         ReadLockHolder lock(pkgAliasListLock_);
736         auto it = pkgAliasList_.find(alias);
737         if (it == pkgAliasList_.end()) {
738             return alias;
739         }
740         return it->second;
741     }
742 
SetPkgAliasList(const CMap<CString,CString> & list)743     void SetPkgAliasList(const CMap<CString, CString> &list)
744     {
745         WriteLockHolder lock(pkgAliasListLock_);
746         pkgAliasList_ = list;
747     }
748 
UpdatePkgAliasList(const CMap<CString,CString> & list)749     void UpdatePkgAliasList(const CMap<CString, CString> &list)
750     {
751         WriteLockHolder lock(pkgAliasListLock_);
752         pkgAliasList_.insert(list.begin(), list.end());
753     }
754 
GetPkgAliasList()755     CMap<CString, CString> GetPkgAliasList()
756     {
757         ReadLockHolder lock(pkgAliasListLock_);
758         return pkgAliasList_;
759     }
760 
SetMockModuleList(const std::map<std::string,std::string> & list)761     void SetMockModuleList(const std::map<std::string, std::string> &list)
762     {
763         for (auto it = list.begin(); it != list.end(); ++it) {
764             mockModuleList_.emplace(it->first.c_str(), it->second.c_str());
765         }
766     }
767 
IsMockModule(const CString & moduleStr)768     inline bool IsMockModule(const CString &moduleStr) const
769     {
770         if (mockModuleList_.empty()) {
771             return false;
772         }
773         auto it = mockModuleList_.find(moduleStr);
774         if (it == mockModuleList_.end()) {
775             return false;
776         }
777         return true;
778     }
779 
GetMockModule(const CString & module)780     inline CString GetMockModule(const CString &module) const
781     {
782         auto it = mockModuleList_.find(module);
783         if (it == mockModuleList_.end()) {
784             LOG_ECMA(FATAL) << " Get Mock Module failed";
785         }
786         return it->second;
787     }
788 
789 #if defined(ECMASCRIPT_SUPPORT_HEAPPROFILER)
790     void DeleteHeapProfile();
791     HeapProfilerInterface *GetHeapProfile();
SetHeapProfile(HeapProfilerInterface * heapProfile)792     void  SetHeapProfile(HeapProfilerInterface *heapProfile) { heapProfile_ = heapProfile; }
793     HeapProfilerInterface *GetOrNewHeapProfile();
794     void StartHeapTracking();
795     void StopHeapTracking();
796 #endif
797 
SetAssetPath(const CString & assetPath)798     void SetAssetPath(const CString &assetPath)
799     {
800         assetPath_ = assetPath;
801     }
802 
GetAssetPath()803     CString GetAssetPath() const
804     {
805         return assetPath_;
806     }
807 
SetBundleName(const CString & bundleName)808     inline void SetBundleName(const CString &bundleName)
809     {
810         bundleName_ = bundleName;
811     }
812 
GetBundleName()813     CString GetBundleName() const
814     {
815         return bundleName_;
816     }
817 
SetModuleName(const CString & moduleName)818     void SetModuleName(const CString &moduleName)
819     {
820         moduleName_ = moduleName;
821     }
822 
GetModuleName()823     CString GetModuleName() const
824     {
825         return moduleName_;
826     }
827 
828     std::pair<std::string, std::string> GetCurrentModuleInfo(bool needRecordName = false);
829 
830     void SetHmsModuleList(const std::vector<panda::HmsMap> &list);
831 
832     bool IsHmsModule(const CString &moduleStr) const;
833 
834     CString GetHmsModule(const CString &module) const;
835 
836     void SetpkgContextInfoList(const CMap<CString, CMap<CString, CVector<CString>>> &list);
837 
838 #if defined(ECMASCRIPT_SUPPORT_CPUPROFILER)
GetProfiler()839     CpuProfiler *GetProfiler() const
840     {
841         return profiler_;
842     }
843 
SetProfiler(CpuProfiler * profiler)844     void SetProfiler(CpuProfiler *profiler)
845     {
846         profiler_ = profiler;
847     }
848 #endif
849 
850 #if defined(ECMASCRIPT_SUPPORT_TRACING)
GetTracing()851     Tracing *GetTracing() const
852     {
853         return tracing_;
854     }
855 
SetTracing(Tracing * tracing)856     void SetTracing(Tracing *tracing)
857     {
858         tracing_ = tracing;
859     }
860 #endif
861 
GetPGOProfiler()862     std::shared_ptr<PGOProfiler> GetPGOProfiler() const
863     {
864         return pgoProfiler_;
865     }
866 
867     void PreFork();
868     void PostFork(const JSRuntimeOptions &option);
869 
870     // For Internal Native MethodLiteral.
871     JSTaggedValue GetMethodByIndex(MethodIndex idx);
872 
GetQuickFixManager()873     QuickFixManager *GetQuickFixManager() const
874     {
875         return quickFixManager_;
876     }
877 
878     JSTaggedValue FastCallAot(size_t actualNumArgs, JSTaggedType *args, const JSTaggedType *prevFp);
879 
RegisterUncatchableErrorHandler(const UncatchableErrorHandler & uncatchableErrorHandler)880     void RegisterUncatchableErrorHandler(const UncatchableErrorHandler &uncatchableErrorHandler)
881     {
882         uncatchableErrorHandler_ = uncatchableErrorHandler;
883     }
884 
885     // handle uncatchable errors, such as oom
886     void HandleUncatchableError();
887 
888     void DumpCallTimeInfo();
889 
GetCallTimer()890     FunctionCallTimer *GetCallTimer() const
891     {
892         return callTimer_;
893     }
894 
GetEcmaStringTable()895     EcmaStringTable *GetEcmaStringTable() const
896     {
897         ASSERT(stringTable_ != nullptr);
898         return stringTable_;
899     }
900 
IncreaseCallDepth()901     void IncreaseCallDepth()
902     {
903         callDepth_++;
904     }
905 
DecreaseCallDepth()906     void DecreaseCallDepth()
907     {
908         ASSERT(callDepth_ > 0);
909         callDepth_--;
910     }
911 
IsTopLevelCallDepth()912     bool IsTopLevelCallDepth()
913     {
914         return callDepth_ == 0;
915     }
916 
SetProfilerState(bool state)917     void SetProfilerState(bool state)
918     {
919         isProfiling_ = state;
920     }
921 
GetProfilerState()922     bool GetProfilerState()
923     {
924         return isProfiling_;
925     }
926 
GetJSObjectResizingStrategy()927     JSObjectResizingStrategy *GetJSObjectResizingStrategy()
928     {
929         return strategy_;
930     }
931 
GetWorkList()932     CMap<uint32_t, EcmaVM *> GetWorkList() const
933     {
934         return workerList_;
935     }
936 
GetProcessStartRealtime()937     int GetProcessStartRealtime() const
938     {
939         return processStartRealtime_;
940     }
941 
SetProcessStartRealtime(int value)942     void SetProcessStartRealtime(int value)
943     {
944         processStartRealtime_ = value;
945     }
946 
947     Jit *GetJit() const;
948     bool PUBLIC_API IsEnableFastJit() const;
949     bool PUBLIC_API IsEnableBaselineJit() const;
950 
IsEnableOsr()951     bool IsEnableOsr() const
952     {
953         return isEnableOsr_;
954     }
955 
SetEnableOsr(bool state)956     void SetEnableOsr(bool state)
957     {
958         isEnableOsr_ = state;
959     }
960 
GetAOTFileManager()961     PUBLIC_API AOTFileManager *GetAOTFileManager() const
962     {
963         return aotFileManager_;
964     }
965 
966     uint32_t GetTid() const;
967 
GetConcurrentNativePointerCallbacks()968     std::vector<NativePointerCallbackData> &GetConcurrentNativePointerCallbacks()
969     {
970         return concurrentNativeCallbacks_;
971     }
972 
GetAsyncNativePointerCallbacksPack()973     AsyncNativeCallbacksPack &GetAsyncNativePointerCallbacksPack()
974     {
975         return asyncNativeCallbacksPack_;
976     }
977 
SetIsJitCompileVM(bool isJitCompileVM)978     void SetIsJitCompileVM(bool isJitCompileVM)
979     {
980         isJitCompileVM_ = isJitCompileVM;
981     }
982 
IsJitCompileVM()983     bool IsJitCompileVM() const
984     {
985         return isJitCompileVM_;
986     }
987 
SetMultiThreadCheck(bool multiThreadCheck)988     static void SetMultiThreadCheck(bool multiThreadCheck)
989     {
990         multiThreadCheck_ = multiThreadCheck;
991     }
992 
GetMultiThreadCheck()993     PUBLIC_API static bool GetMultiThreadCheck()
994     {
995         return multiThreadCheck_;
996     }
997 
SetErrorInfoEnhance(bool errorInfoEnhance)998     static void SetErrorInfoEnhance(bool errorInfoEnhance)
999     {
1000         errorInfoEnhanced_ = errorInfoEnhance;
1001     }
1002 
GetErrorInfoEnhance()1003     static bool GetErrorInfoEnhance()
1004     {
1005         return errorInfoEnhanced_;
1006     }
1007 
1008     static void InitializeIcuData(const JSRuntimeOptions &options);
1009 
1010     static int InitializeStartRealTime();
1011 
1012 #if ECMASCRIPT_ENABLE_SCOPE_LOCK_STAT
ResetScopeLockStats()1013     void ResetScopeLockStats()
1014     {
1015         enterThreadManagedScopeCount_ = 0;
1016         enterJsiNativeScopeCount_ = 0;
1017         enterFastNativeScopeCount_ = 0;
1018         updateThreadStateTransCount_ = 0;
1019         stringTableLockCount_ = 0;
1020     }
1021 
IsCollectingScopeLockStats()1022     bool IsCollectingScopeLockStats() const
1023     {
1024         return isCollectingScopeLockStats_;
1025     }
1026 
StartCollectingScopeLockStats()1027     void StartCollectingScopeLockStats()
1028     {
1029         isCollectingScopeLockStats_ = true;
1030     }
1031 
StopCollectingScopeLockStats()1032     void StopCollectingScopeLockStats()
1033     {
1034         isCollectingScopeLockStats_ = false;
1035     }
1036 
GetEnterThreadManagedScopeCount()1037     int GetEnterThreadManagedScopeCount() const
1038     {
1039         return enterThreadManagedScopeCount_;
1040     }
1041 
IncreaseEnterThreadManagedScopeCount()1042     void IncreaseEnterThreadManagedScopeCount()
1043     {
1044         enterThreadManagedScopeCount_++;
1045     }
1046 
GetEnterFastNativeScopeCount()1047     int GetEnterFastNativeScopeCount() const
1048     {
1049         return enterFastNativeScopeCount_;
1050     }
1051 
IncreaseEnterFastNativeScopeCount()1052     void IncreaseEnterFastNativeScopeCount()
1053     {
1054         enterFastNativeScopeCount_++;
1055     }
1056 
GetEnterJsiNativeScopeCount()1057     int GetEnterJsiNativeScopeCount() const
1058     {
1059         return enterJsiNativeScopeCount_;
1060     }
1061 
IncreaseEnterJsiNativeScopeCount()1062     void IncreaseEnterJsiNativeScopeCount()
1063     {
1064         enterJsiNativeScopeCount_++;
1065     }
1066 
GetUpdateThreadStateTransCount()1067     int GetUpdateThreadStateTransCount() const
1068     {
1069         return updateThreadStateTransCount_;
1070     }
1071 
IncreaseUpdateThreadStateTransCount()1072     void IncreaseUpdateThreadStateTransCount()
1073     {
1074         updateThreadStateTransCount_++;
1075     }
1076 
GetStringTableLockCount()1077     int GetStringTableLockCount() const
1078     {
1079         return stringTableLockCount_;
1080     }
1081 
IncreaseStringTableLockCount()1082     void IncreaseStringTableLockCount()
1083     {
1084         stringTableLockCount_++;
1085     }
1086 #endif
1087 
GetEnableJitLogSkip()1088     bool GetEnableJitLogSkip() const
1089     {
1090         return enableJitLogSkip_;
1091     }
1092 
SetEnableJitLogSkip(bool flag)1093     void SetEnableJitLogSkip(bool flag)
1094     {
1095         enableJitLogSkip_ = flag;
1096     }
1097 
1098     void AddAOTSnapShotStats(std::string tag, uint32_t count = 1)
1099     {
1100         aotSnapShotStatsMap_[tag] += count;
1101     }
1102 
GetIntlCache()1103     IntlCache& GetIntlCache()
1104     {
1105         return intlCache_;
1106     }
1107 
1108     void PUBLIC_API PrintAOTSnapShotStats();
1109 
SetVMAPIVersion(uint32_t APIVersion)1110     void SetVMAPIVersion(uint32_t APIVersion)
1111     {
1112         apiVersion_ = APIVersion;
1113     }
1114 
GetVMAPIVersion()1115     uint32_t GetVMAPIVersion()
1116     {
1117         return apiVersion_;
1118     }
1119 
GetRegisterSymbols()1120     JSTaggedValue GetRegisterSymbols() const
1121     {
1122         return registerSymbols_;
1123     }
1124 
SetRegisterSymbols(JSTaggedValue value)1125     void SetRegisterSymbols(JSTaggedValue value)
1126     {
1127         registerSymbols_ = value;
1128     }
1129 
GetFinRegLists()1130     JSTaggedValue GetFinRegLists() const
1131     {
1132         return finRegLists_;
1133     }
1134 
SetFinRegLists(JSTaggedValue value)1135     void SetFinRegLists(JSTaggedValue value)
1136     {
1137         finRegLists_ = value;
1138     }
1139 
1140     JSHandle<job::MicroJobQueue> GetMicroJobQueue() const;
1141 
1142     bool HasPendingJob() const;
1143 
1144     bool ExecutePromisePendingJob();
1145 
SetPromiseRejectCallback(PromiseRejectCallback cb)1146     void SetPromiseRejectCallback(PromiseRejectCallback cb)
1147     {
1148         promiseRejectCallback_ = cb;
1149     }
1150 
GetPromiseRejectCallback()1151     PromiseRejectCallback GetPromiseRejectCallback() const
1152     {
1153         return promiseRejectCallback_;
1154     }
1155 
SetHostPromiseRejectionTracker(HostPromiseRejectionTracker cb)1156     void SetHostPromiseRejectionTracker(HostPromiseRejectionTracker cb)
1157     {
1158         hostPromiseRejectionTracker_ = cb;
1159     }
1160 
PromiseRejectionTracker(const JSHandle<JSPromise> & promise,const JSHandle<JSTaggedValue> & reason,PromiseRejectionEvent operation)1161     void PromiseRejectionTracker(const JSHandle<JSPromise> &promise,
1162                                  const JSHandle<JSTaggedValue> &reason, PromiseRejectionEvent operation)
1163     {
1164         if (hostPromiseRejectionTracker_ != nullptr) {
1165             hostPromiseRejectionTracker_(this, promise, reason, operation, data_);
1166         }
1167     }
1168 
SetPromiseRejectInfoData(void * data)1169     void SetPromiseRejectInfoData(void* data)
1170     {
1171         data_ = data;
1172     }
1173 
IsExecutingPendingJob()1174     bool IsExecutingPendingJob() const
1175     {
1176         return isProcessingPendingJob_.load();
1177     }
1178     JSTaggedValue PUBLIC_API FindUnsharedConstpool(JSTaggedValue sharedConstpool);
1179     JSTaggedValue PUBLIC_API FindOrCreateUnsharedConstpool(JSTaggedValue sharedConstpool);
1180     void EraseUnusedConstpool(const JSPandaFile *jsPandaFile, int32_t index, int32_t constpoolIndex);
1181     JSTaggedValue PUBLIC_API FindConstpool(const JSPandaFile *jsPandaFile, int32_t index);
1182     // For new version instruction.
1183     JSTaggedValue PUBLIC_API FindConstpool(const JSPandaFile *jsPandaFile, panda_file::File::EntityId id);
1184     bool HasCachedConstpool(const JSPandaFile *jsPandaFile) const;
1185     JSHandle<ConstantPool> AddOrUpdateConstpool(const JSPandaFile *jsPandaFile,
1186                                                 JSHandle<ConstantPool> constpool,
1187                                                 int32_t index = 0);
1188     void SetUnsharedConstpool(JSHandle<ConstantPool> sharedConstpool, JSTaggedValue unsharedConstpool);
1189     void SetUnsharedConstpool(int32_t constpoolIndex, JSTaggedValue unsharedConstpool);
1190     void CreateAllConstpool(const JSPandaFile *jsPandaFile);
1191     std::optional<std::reference_wrapper<CMap<int32_t, JSTaggedValue>>> FindConstpools(const JSPandaFile *jsPandaFile);
1192     void UpdateConstpoolWhenDeserialAI(const std::string& fileName,
1193                                        JSHandle<ConstantPool> aiCP,
1194                                        int32_t index = 0);
1195     JSHandle<ConstantPool> PUBLIC_API FindOrCreateConstPool(const JSPandaFile *jsPandaFile,
1196                                                             panda_file::File::EntityId id);
ClearCachedConstantPool()1197     void ClearCachedConstantPool()
1198     {
1199         cachedSharedConstpools_.clear();
1200     }
1201 
GetUnsharedConstpoolsPointer()1202     JSTaggedValue *GetUnsharedConstpoolsPointer() const
1203     {
1204         return unsharedConstpools_;
1205     }
1206 
1207 #if ECMASCRIPT_ENABLE_COLLECTING_OPCODES
SetBytecodeStatsStack(std::unordered_map<BytecodeInstruction::Opcode,int> & bytecodeStatsMap)1208     void SetBytecodeStatsStack(std::unordered_map<BytecodeInstruction::Opcode, int> &bytecodeStatsMap)
1209     {
1210         bytecodeStatsStack_.push(bytecodeStatsMap);
1211     }
1212 
GetBytecodeStatsStack()1213     std::stack<std::unordered_map<BytecodeInstruction::Opcode, int>>& GetBytecodeStatsStack()
1214     {
1215         return bytecodeStatsStack_;
1216     }
1217 
1218     void PrintCollectedByteCode();
1219 #endif
1220 
GetRegExpParserCache()1221     RegExpParserCache *GetRegExpParserCache() const
1222     {
1223         ASSERT(regExpParserCache_ != nullptr);
1224         return regExpParserCache_;
1225     }
1226 
GetWaiterListNode()1227     WaiterListNode *GetWaiterListNode()
1228     {
1229         return &waiterListNode_;
1230     }
1231 
GetAbcBufferCache()1232     AbcBufferCache *GetAbcBufferCache() const
1233     {
1234         return abcBufferCache_;
1235     }
1236 
1237     void AddSustainingJSHandle(SustainingJSHandle *sustainingHandle);
1238     void RemoveSustainingJSHandle(SustainingJSHandle *sustainingHandle);
1239 
GetPTManager()1240     kungfu::PGOTypeManager* GetPTManager() const
1241     {
1242         return ptManager_;
1243     }
1244 
GetOptCodeProfiler()1245     OptCodeProfiler* GetOptCodeProfiler() const
1246     {
1247         return optCodeProfiler_;
1248     }
1249 
GetTypedOpProfiler()1250     TypedOpProfiler* GetTypedOpProfiler() const
1251     {
1252         return typedOpProfiler_;
1253     }
1254 
GetFunctionProtoTransitionTable()1255     FunctionProtoTransitionTable* GetFunctionProtoTransitionTable() const
1256     {
1257         return functionProtoTransitionTable_;
1258     }
1259 
1260     void PrintOptStat();
1261     void DumpAOTInfo() const DUMP_API_ATTR;
1262     std::tuple<uint64_t, uint8_t*, int, kungfu::CalleeRegAndOffsetVec> CalCallSiteInfo(uintptr_t retAddr,
1263                                                                                        bool isDeopt) const;
1264     void LoadStubFile();
1265     bool LoadAOTFilesInternal(const std::string& aotFileName);
1266     bool LoadAOTFiles(const std::string& aotFileName);
1267     bool LoadAOTFiles(const std::string &aotFileName,
1268                       std::function<bool(std::string fileName, uint8_t **buff, size_t *buffSize)> cb);
1269     void PUBLIC_API LoadProtoTransitionTable(JSTaggedValue constpool);
1270     void PUBLIC_API ResetProtoTransitionTableOnConstpool(JSTaggedValue constpool);
1271 
AddPatchModule(const CString & recordName,const JSHandle<JSTaggedValue> moduleRecord)1272     void AddPatchModule(const CString &recordName, const JSHandle<JSTaggedValue> moduleRecord)
1273     {
1274         cachedPatchModules_.emplace(recordName, moduleRecord);
1275     }
1276 
FindPatchModule(const CString & recordName)1277     JSHandle<JSTaggedValue> FindPatchModule(const CString &recordName) const
1278     {
1279         auto iter = cachedPatchModules_.find(recordName);
1280         if (iter != cachedPatchModules_.end()) {
1281             return iter->second;
1282         }
1283         return JSHandle<JSTaggedValue>(thread_, JSTaggedValue::Hole());
1284     }
1285 
ClearPatchModules()1286     void ClearPatchModules()
1287     {
1288         GlobalHandleCollection globalHandleCollection(thread_);
1289         for (auto &item : cachedPatchModules_) {
1290             globalHandleCollection.Dispose(item.second);
1291         }
1292         cachedPatchModules_.clear();
1293     }
1294 
GetStageOfColdReload()1295     StageOfColdReload GetStageOfColdReload() const
1296     {
1297         return stageOfColdReload_;
1298     }
1299 
SetStageOfColdReload(StageOfColdReload stageOfColdReload)1300     void SetStageOfColdReload(StageOfColdReload stageOfColdReload)
1301     {
1302         stageOfColdReload_ = stageOfColdReload;
1303     }
1304 
SetApplicationVersionCode(const uint32_t versionCode)1305     void SetApplicationVersionCode(const uint32_t versionCode)
1306     {
1307         applicationVersionCode_ = versionCode;
1308     }
1309 
GetApplicationVersionCode()1310     uint32_t GetApplicationVersionCode() const
1311     {
1312         return applicationVersionCode_;
1313     }
1314 
RecordGlobalEnv(GlobalEnv * globalEnv)1315     void RecordGlobalEnv(GlobalEnv *globalEnv)
1316     {
1317         globalEnvRecordList_.push_back(static_cast<JSTaggedType>(ToUintPtr(globalEnv)));
1318     }
1319 
1320     JSTaggedValue ExecuteAot(size_t actualNumArgs, JSTaggedType *args, const JSTaggedType *prevFp,
1321                              bool needPushArgv);
1322 
1323     static void ClearKeptObjects(JSThread *thread);
1324     static void AddToKeptObjects(JSThread *thread, JSHandle<JSTaggedValue> value);
1325     void AddModuleManager(ModuleManager *moduleManager);
GetDataViewType(JSTaggedType type)1326     int8_t GetDataViewType(JSTaggedType type) const
1327     {
1328         auto result = dataViewTypeTable_.find(type);
1329         if (result == dataViewTypeTable_.end()) {
1330             return -1;
1331         }
1332         return result->second;
1333     }
1334 
1335 #ifdef PANDA_JS_ETS_HYBRID_MODE
1336     ECMAVM_PUBLIC_HYBRID_MODE_EXTENSION()
1337 #endif  /* PANDA_JS_ETS_HYBRID_MODE */
1338     ECMAVM_PUBLIC_HYBRID_EXTENSION();
1339 
1340 protected:
1341     ECMAVM_PROTECTED_HYBRID_EXTENSION();
1342 
1343 private:
1344     void ClearBufferData();
1345     void ClearConstpoolBufferData();
1346     void CheckStartCpuProfiler();
1347     void SetMicroJobQueue(job::MicroJobQueue *queue);
1348     // For Internal Native MethodLiteral.
1349     void GenerateInternalNativeMethods();
1350     void CacheToGlobalConstants(JSTaggedValue value, ConstantIndex constant);
1351 
1352     JSTaggedValue FindConstpoolFromContextCache(const JSPandaFile *jsPandaFile, int32_t index);
1353     void AddContextConstpoolCache(const JSPandaFile *jsPandaFile,
1354                                   JSHandle<ConstantPool> constpool,
1355                                   int32_t index);
1356     JSTaggedValue FindCachedConstpoolAndLoadAiIfNeeded(const JSPandaFile *jsPandaFile, int32_t index);
1357     void GrowUnsharedConstpoolArray(int32_t index);
1358     void ResizeUnsharedConstpoolArray(int32_t oldCapacity, int32_t minCapacity);
ClearUnsharedConstpoolArray()1359     void ClearUnsharedConstpoolArray()
1360     {
1361         if (unsharedConstpools_ != nullptr) {
1362             delete[] unsharedConstpools_;
1363             unsharedConstpools_ = nullptr;
1364             thread_->SetUnsharedConstpools(reinterpret_cast<uintptr_t>(nullptr));
1365             thread_->SetUnsharedConstpoolsArrayLen(0);
1366         }
1367     }
1368 
GetUnsharedConstpoolsArrayLen()1369     int32_t GetUnsharedConstpoolsArrayLen() const
1370     {
1371         return unsharedConstpoolsArrayLen_;
1372     }
1373 
SetUnsharedConstpoolsArrayLen(int32_t len)1374     void SetUnsharedConstpoolsArrayLen(int32_t len)
1375     {
1376         unsharedConstpoolsArrayLen_ = len;
1377     }
1378 
1379     void CJSExecution(JSHandle<JSFunction> &func, JSHandle<JSTaggedValue> &thisArg,
1380                       const JSPandaFile *jsPandaFile, std::string_view entryPoint);
1381     JSTaggedValue InvokeEcmaAotEntrypoint(JSHandle<JSFunction> mainFunc, JSHandle<JSTaggedValue> &thisArg,
1382                                           const JSPandaFile *jsPandaFile, std::string_view entryPoint,
1383                                           CJSInfo *cjsInfo = nullptr);
1384     Expected<JSTaggedValue, bool> InvokeEcmaEntrypoint(const JSPandaFile *jsPandaFile, std::string_view entryPoint,
1385                                                        const ExecuteTypes &executeType = ExecuteTypes::STATIC);
1386     Expected<JSTaggedValue, bool> InvokeEcmaEntrypointForHotReload(
1387         const JSPandaFile *jsPandaFile, std::string_view entryPoint, const ExecuteTypes &executeType);
1388     Expected<JSTaggedValue, bool> CommonInvokeEcmaEntrypoint(const JSPandaFile *jsPandaFile,
1389         std::string_view entryPoint, JSHandle<JSFunction> &func, const ExecuteTypes &executeType);
1390 
1391     void InitDataViewTypeTable(const GlobalEnvConstants *constant);
1392 
1393     NO_MOVE_SEMANTIC(EcmaVM);
1394     NO_COPY_SEMANTIC(EcmaVM);
1395 
1396     // VM startup states.
1397     JSRuntimeOptions options_;
1398     bool icEnabled_ {true};
1399     uint32_t isEnableCMCGC_ {0};
1400     bool initialized_ {false};
1401     bool preForked_ {false};
1402     bool postForked_ {false};
1403     bool agentCanSuspend_ {true};
1404     GCStats *gcStats_ {nullptr};
1405     GCKeyStats *gcKeyStats_ {nullptr};
1406     EcmaStringTable *stringTable_ {nullptr};
1407     PUBLIC_API static bool multiThreadCheck_;
1408     static bool errorInfoEnhanced_;
1409 
1410     // for constpool.The shared constpool includes string, method, sendable classLiteral, etc.
1411     // The unshared constpool includes objectLiteral, arrayLiteral, unsendable classLiteral, etc.
1412     CMap<const JSPandaFile *, CMap<int32_t, JSTaggedValue>> cachedSharedConstpools_ {};
1413     JSTaggedValue* unsharedConstpools_ = nullptr;
1414     int32_t unsharedConstpoolsArrayLen_ = UNSHARED_CONSTANTPOOL_COUNT;
1415     static constexpr int32_t SHARED_CONSTPOOL_KEY_NOT_FOUND = INT32_MAX; // INT32_MAX :invalid value.
1416 
1417     //apiVersion states
1418     uint32_t apiVersion_ = 8;
1419 
1420     // VM memory management.
1421     std::unique_ptr<NativeAreaAllocator> nativeAreaAllocator_;
1422     std::unique_ptr<HeapRegionAllocator> heapRegionAllocator_;
1423     Chunk chunk_;
1424     Heap *heap_ {nullptr};
1425     ObjectFactory *factory_ {nullptr};
1426 
1427     std::vector<NativePointerCallbackData> concurrentNativeCallbacks_ {};
1428     AsyncNativeCallbacksPack asyncNativeCallbacksPack_ {};
1429     // VM execution states.
1430     JSThread *thread_ {nullptr};
1431 
1432     EcmaRuntimeStat *runtimeStat_ {nullptr};
1433 
1434     CUnorderedMap<std::string, uint32_t> aotSnapShotStatsMap_;
1435 
1436     // VM resources.
1437     SnapshotEnv *snapshotEnv_ {nullptr};
1438     bool optionalLogEnabled_ {false};
1439     // Debugger
1440     tooling::JsDebuggerManager *debuggerManager_ {nullptr};
1441 
1442     // DFX
1443     AsyncStackTrace *asyncStackTrace_ {nullptr};
1444 
1445     // isBundle means app compile mode is JSBundle
1446     bool isBundlePack_ {true};
1447 #if !WIN_OR_MAC_OR_IOS_PLATFORM
1448     HeapProfilerInterface *heapProfile_ {nullptr};
1449 #endif
1450     CString assetPath_;
1451     CString bundleName_;
1452     CString moduleName_;
1453     std::set<CString> deregisterModuleList_;
1454     CMap<CString, CString> mockModuleList_;
1455     std::map<CString, HmsMap> hmsModuleList_;
1456     CMap<CString, CString> pkgNameList_;
1457     CMap<CString, CMap<CString, CVector<CString>>> pkgContextInfoList_;
1458     CMap<CString, CString> pkgAliasList_;
1459     RWLock pkgContextInfoLock_;
1460     RWLock pkgAliasListLock_;
1461     RWLock pkgNameListLock_;
1462 
1463     CVector<StopPreLoadSoCallback> stopPreLoadCallbacks_;
1464     NativePtrGetter nativePtrGetter_ {nullptr};
1465     SourceMapCallback sourceMapCallback_ {nullptr};
1466     SourceMapTranslateCallback sourceMapTranslateCallback_ {nullptr};
1467     void *loop_ {nullptr};
1468 
1469     // resolve path to get abc's buffer
1470     ResolveBufferCallback resolveBufferCallback_ {nullptr};
1471     ResolveBufferCallback resolveBufferCallbackForHybridApp_ {nullptr};
1472 
1473     // set timer task to execute callback on time
1474     TimerTaskCallback timerTaskCallback_ {nullptr};
1475     // set cancel timer task to execute callback on time
1476     CancelTimerCallback cancelTimerCallback_ {nullptr};
1477 
1478     // delete the native module and dlclose so from NativeModuleManager
1479     UnloadNativeModuleCallback unloadNativeModuleCallback_ {nullptr};
1480 
1481     // Concurrent taskpool callback and data
1482     ConcurrentCallback concurrentCallback_ {nullptr};
1483     void *concurrentData_ {nullptr};
1484 
1485     // serch happath callback
1486     SearchHapPathCallBack SearchHapPathCallBack_ {nullptr};
1487 
1488     // vm parameter configurations
1489     EcmaParamConfiguration ecmaParamConfiguration_;
1490 #if defined(ECMASCRIPT_SUPPORT_CPUPROFILER)
1491     CpuProfiler *profiler_ {nullptr};
1492 #endif
1493 #if defined(ECMASCRIPT_SUPPORT_TRACING)
1494     Tracing *tracing_ {nullptr};
1495 #endif
1496     FunctionCallTimer *callTimer_ {nullptr};
1497     JSObjectResizingStrategy *strategy_ {nullptr};
1498 
1499     // For Native MethodLiteral
1500     static void *InternalMethodTable[static_cast<uint8_t>(MethodIndex::METHOD_END)];
1501     CVector<JSTaggedValue> internalNativeMethods_;
1502 
1503     // For repair patch.
1504     QuickFixManager *quickFixManager_ {nullptr};
1505 
1506     // PGO Profiler
1507     std::shared_ptr<PGOProfiler> pgoProfiler_ {nullptr};
1508 
1509     //AOT File Manager
1510     AOTFileManager *aotFileManager_ {nullptr};
1511     kungfu::PGOTypeManager* ptManager_ {nullptr};
1512 
1513     // c++ call js
1514     size_t callDepth_ {0};
1515 
1516     bool isProfiling_ {false};
1517 
1518     DeviceDisconnectCallback deviceDisconnectCallback_ {nullptr};
1519 
1520     UncatchableErrorHandler uncatchableErrorHandler_ {nullptr};
1521 
1522     IntlCache intlCache_;
1523 
1524     friend class Snapshot;
1525     friend class SnapshotProcessor;
1526     friend class ObjectFactory;
1527     friend class ValueSerializer;
1528     friend class panda::JSNApi;
1529     friend class JSPandaFileExecutor;
1530     friend class JitVM;
1531     CMap<uint32_t, EcmaVM *> workerList_ {};
1532     Mutex mutex_;
1533     bool isEnableOsr_ {false};
1534     bool isJitCompileVM_ {false};
1535     // SustainingJSHandleList for jit compile hold ref
1536     SustainingJSHandleList *sustainingJSHandleList_ {nullptr};
1537 
1538     // process StartRealTime
1539     int processStartRealtime_ = 0;
1540 
1541     bool enableJitLogSkip_ = true;
1542 
1543     // Registered Callbacks
1544     PromiseRejectCallback promiseRejectCallback_ {nullptr};
1545     HostPromiseRejectionTracker hostPromiseRejectionTracker_ {nullptr};
1546     void* data_{nullptr};
1547 
1548     JSTaggedValue finRegLists_ {JSTaggedValue::Hole()};
1549     JSTaggedValue registerSymbols_ {JSTaggedValue::Hole()};
1550     JSTaggedValue microJobQueue_ {JSTaggedValue::Hole()};
1551     std::atomic<bool> isProcessingPendingJob_{false};
1552 
1553     std::unordered_map<JSTaggedType, int8_t> dataViewTypeTable_;
1554 #if ECMASCRIPT_ENABLE_SCOPE_LOCK_STAT
1555     // Stats for Thread-State-Transition and String-Table Locks
1556     bool isCollectingScopeLockStats_ = false;
1557     int enterThreadManagedScopeCount_ = 0;
1558     int enterFastNativeScopeCount_ = 0;
1559     int enterJsiNativeScopeCount_ = 0;
1560     int updateThreadStateTransCount_ = 0;
1561     int stringTableLockCount_ = 0;
1562 #endif
1563 
1564 #if ECMASCRIPT_ENABLE_COLLECTING_OPCODES
1565     std::stack<std::unordered_map<BytecodeInstruction::Opcode, int>> bytecodeStatsStack_;
1566 #endif
1567 
1568     // HandleScope
1569     static const uint32_t NODE_BLOCK_SIZE_LOG2 = 10;
1570     static const uint32_t NODE_BLOCK_SIZE = 1U << NODE_BLOCK_SIZE_LOG2;
1571     static constexpr int32_t MIN_HANDLE_STORAGE_SIZE = 2;
1572     JSTaggedType *handleScopeStorageNext_ {nullptr};
1573     JSTaggedType *handleScopeStorageEnd_ {nullptr};
1574     std::vector<std::array<JSTaggedType, NODE_BLOCK_SIZE> *> handleStorageNodes_ {};
1575     int32_t currentHandleStorageIndex_ {-1};
1576     // PrimitveScope
1577     static constexpr int32_t MIN_PRIMITIVE_STORAGE_SIZE = 2;
1578     JSTaggedType *primitiveScopeStorageNext_ {nullptr};
1579     JSTaggedType *primitiveScopeStorageEnd_ {nullptr};
1580     std::vector<std::array<JSTaggedType, NODE_BLOCK_SIZE> *> primitiveStorageNodes_ {};
1581     int32_t currentPrimitiveStorageIndex_ {-1};
1582     // for recording the transition of function prototype
1583     FunctionProtoTransitionTable* functionProtoTransitionTable_ {nullptr};
1584     // opt code Profiler
1585     OptCodeProfiler* optCodeProfiler_ {nullptr};
1586     // opt code loop hoist
1587     TypedOpProfiler* typedOpProfiler_ {nullptr};
1588     // RegExpParserCache
1589     RegExpParserCache *regExpParserCache_ {nullptr};
1590     // WaiterListNode(atomics)
1591     WaiterListNode waiterListNode_;
1592     AbcBufferCache *abcBufferCache_ {nullptr};
1593 
1594     // for HotReload of module.
1595     CMap<CString, JSHandle<JSTaggedValue>> cachedPatchModules_;
1596     StageOfColdReload stageOfColdReload_ = StageOfColdReload::NOT_COLD_RELOAD;
1597 
1598     // record globalEnv as weak reference
1599     std::vector<JSTaggedType> globalEnvRecordList_;
1600 
1601     // store multi-context module manager
1602     class ModuleManagers {
1603         Mutex CMCGCMutex_;
1604         std::vector<ModuleManager *> moduleManagersVec_ {};
1605 
1606     public:
1607         void Iterate(RootVisitor &v);
1608 
1609         template <typename T>
1610         void PushBack(T moduleManager);
1611 
1612         void DestroyAllNativeObj();
1613 
1614         void Clear();
1615     } moduleManagers_;
1616 
1617     // store Application versionCode
1618     uint32_t applicationVersionCode_ {0};
1619 #ifdef PANDA_JS_ETS_HYBRID_MODE
1620     ECMAVM_PRIVATE_HYBRID_EXTENSION();
1621 #endif /* PANDA_JS_ETS_HYBRID_MODE */
1622 };
1623 }  // namespace ecmascript
1624 }  // namespace panda
1625 
1626 #endif
1627