• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ENGINE_H
17 #define FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ENGINE_H
18 
19 #include <functional>
20 #include <string>
21 #include <unordered_map>
22 #include <unordered_set>
23 #include <vector>
24 
25 #include "callback_scope_manager/native_callback_scope_manager.h"
26 #include "module_manager/native_module_manager.h"
27 #include "native_engine/native_async_work.h"
28 #include "native_engine/native_deferred.h"
29 #include "native_engine/native_reference.h"
30 #include "native_engine/native_safe_async_work.h"
31 #include "native_engine/native_value.h"
32 #include "native_property.h"
33 #include "reference_manager/native_reference_manager.h"
34 #include "scope_manager/native_scope_manager.h"
35 #include "utils/macros.h"
36 #include "native_engine_interface.h"
37 
38 typedef int32_t (*GetContainerScopeIdCallback)(void);
39 typedef void (*ContainerScopeCallback)(int32_t);
40 
41 using PostTask = std::function<void(bool needSync)>;
42 using CleanEnv = std::function<void()>;
43 using InitWorkerFunc = std::function<void(NativeEngine* engine)>;
44 using GetAssetFunc = std::function<void(const std::string& uri, std::vector<uint8_t>& content, std::string& ami)>;
45 using OffWorkerFunc = std::function<void(NativeEngine* engine)>;
46 using DebuggerPostTask = std::function<void(std::function<void()>&&)>;
47 using UncaughtExceptionCallback = std::function<void(NativeValue* value)>;
48 
49 class NAPI_EXPORT NativeEngine {
50 public:
51     explicit NativeEngine(void* jsEngine);
52     virtual ~NativeEngine();
53 
54     virtual NativeScopeManager* GetScopeManager();
55     virtual NativeModuleManager* GetModuleManager();
56     virtual NativeReferenceManager* GetReferenceManager();
57     virtual NativeCallbackScopeManager* GetCallbackScopeManager();
58     virtual uv_loop_t* GetUVLoop() const;
59     virtual pthread_t GetTid() const;
60 
61     virtual bool ReinitUVLoop();
62 
63     virtual void Loop(LoopMode mode, bool needSync = false);
64     virtual void SetPostTask(PostTask postTask);
65     virtual void TriggerPostTask();
66 #if !defined(PREVIEW)
67     virtual void CheckUVLoop();
68     virtual void CancelCheckUVLoop();
69 #endif
70     virtual void* GetJsEngine();
71     virtual void DeleteEngine();
72 
73     virtual NativeValue* GetGlobal() = 0;
74 
75     virtual NativeValue* CreateNull() = 0;
76     virtual NativeValue* CreateUndefined() = 0;
77     virtual NativeValue* CreateBoolean(bool value) = 0;
78     virtual NativeValue* CreateNumber(int32_t value) = 0;
79     virtual NativeValue* CreateNumber(uint32_t value) = 0;
80     virtual NativeValue* CreateNumber(int64_t value) = 0;
81     virtual NativeValue* CreateNumber(double value) = 0;
82     virtual NativeValue* CreateBigInt(int64_t value) = 0;
83     virtual NativeValue* CreateBigInt(uint64_t value) = 0;
84     virtual NativeValue* CreateString(const char* value, size_t length) = 0;
85     virtual NativeValue* CreateString16(const char16_t* value, size_t length) = 0;
86 
87     virtual NativeValue* CreateSymbol(NativeValue* value) = 0;
88     virtual NativeValue* CreateExternal(void* value, NativeFinalize callback, void* hint,
89         size_t nativeBindingSize = 0) = 0;
90 
91     virtual NativeValue* CreateObject() = 0;
92     virtual NativeValue* CreateNativeBindingObject(void* detach, void* attach) = 0;
93     virtual NativeValue* CreateNBObject(DetachCallback detach, AttachCallback attach) = 0;
94     virtual NativeValue* CreateFunction(const char* name, size_t length, NativeCallback cb, void* value) = 0;
95     virtual NativeValue* CreateArray(size_t length) = 0;
96     virtual NativeValue* CreateBuffer(void** value, size_t length) = 0;
97     virtual NativeValue* CreateBufferCopy(void** value, size_t length, const void* data) = 0;
98     virtual NativeValue* CreateBufferExternal(void* value, size_t length, NativeFinalize cb, void* hint) = 0;
99     virtual NativeValue* CreateArrayBuffer(void** value, size_t length) = 0;
100     virtual NativeValue* CreateArrayBufferExternal(void* value, size_t length, NativeFinalize cb, void* hint) = 0;
101 
102     virtual NativeValue* CreateTypedArray(NativeTypedArrayType type,
103                                           NativeValue* value,
104                                           size_t length,
105                                           size_t offset) = 0;
106     virtual NativeValue* CreateDataView(NativeValue* value, size_t length, size_t offset) = 0;
107     virtual NativeValue* CreatePromise(NativeDeferred** deferred) = 0;
108     virtual void SetPromiseRejectCallback(NativeReference* rejectCallbackRef, NativeReference* checkCallbackRef) = 0;
109     virtual NativeValue* CreateError(NativeValue* code, NativeValue* message) = 0;
110 
111     virtual bool InitTaskPoolThread(NativeEngine* engine, NapiConcurrentCallback callback) = 0;
112     virtual bool InitTaskPoolFunc(NativeEngine* engine, NativeValue* func) = 0;
113     virtual NativeValue* CallFunction(NativeValue* thisVar,
114                                       NativeValue* function,
115                                       NativeValue* const *argv,
116                                       size_t argc) = 0;
117     virtual NativeValue* RunScript(NativeValue* script) = 0;
118     virtual NativeValue* RunScriptPath(const char* path) = 0;
119     virtual NativeValue* RunScriptBuffer(const char* path, std::vector<uint8_t>& buffer, bool isBundle) = 0;
120     virtual NativeValue* RunBufferScript(std::vector<uint8_t>& buffer) = 0;
121     virtual NativeValue* RunActor(std::vector<uint8_t>& buffer, const char* descriptor) = 0;
122     virtual NativeValue* DefineClass(const char* name,
123                                      NativeCallback callback,
124                                      void* data,
125                                      const NativePropertyDescriptor* properties,
126                                      size_t length) = 0;
127 
128     virtual NativeValue* CreateInstance(NativeValue* constructor, NativeValue* const *argv, size_t argc) = 0;
129 
130     virtual NativeReference* CreateReference(NativeValue* value, uint32_t initialRefcount,
131         NativeFinalize callback = nullptr, void* data = nullptr, void* hint = nullptr) = 0;
132 
133     virtual NativeAsyncWork* CreateAsyncWork(NativeValue* asyncResource,
134                                              NativeValue* asyncResourceName,
135                                              NativeAsyncExecuteCallback execute,
136                                              NativeAsyncCompleteCallback complete,
137                                              void* data);
138 
139     virtual NativeAsyncWork* CreateAsyncWork(const std::string &asyncResourceName,
140                                              NativeAsyncExecuteCallback execute,
141                                              NativeAsyncCompleteCallback complete,
142                                              void* data);
143     virtual NativeSafeAsyncWork* CreateSafeAsyncWork(NativeValue* func, NativeValue* asyncResource,
144         NativeValue* asyncResourceName, size_t maxQueueSize, size_t threadCount, void* finalizeData,
145         NativeFinalize finalizeCallback, void* context, NativeThreadSafeFunctionCallJs callJsCallback);
146 
147     virtual bool Throw(NativeValue* error) = 0;
148     virtual bool Throw(NativeErrorType type, const char* code, const char* message) = 0;
149 
150     virtual void* CreateRuntime() = 0;
151     virtual NativeValue* Serialize(NativeEngine* context, NativeValue* value, NativeValue* transfer) = 0;
152     virtual NativeValue* Deserialize(NativeEngine* context, NativeValue* recorder) = 0;
153     virtual void DeleteSerializationData(NativeValue* value) const = 0;
154     virtual NativeValue* LoadModule(NativeValue* str, const std::string& fileName) = 0;
155 
156     virtual void StartCpuProfiler(const std::string& fileName = "") = 0;
157     virtual void StopCpuProfiler() = 0;
158 
159     virtual void ResumeVM() = 0;
160     virtual bool SuspendVM() = 0;
161     virtual bool IsSuspended() = 0;
162     virtual bool CheckSafepoint() = 0;
163 
164     virtual void DumpHeapSnapshot(const std::string &path, bool isVmMode = true,
165         DumpFormat dumpFormat = DumpFormat::JSON) = 0;
166     virtual void DumpHeapSnapshot(bool isVmMode = true, DumpFormat dumpFormat = DumpFormat::JSON,
167         bool isPrivate = false) = 0;
168     virtual bool BuildNativeAndJsStackTrace(std::string &stackTraceStr) = 0;
169     virtual bool BuildJsStackTrace(std::string &stackTraceStr) = 0;
170     virtual bool BuildJsStackInfoList(uint32_t tid, std::vector<JsFrameInfo>& jsFrames) = 0;
171     virtual bool DeleteWorker(NativeEngine* hostEngine, NativeEngine* workerEngine) = 0;
172     virtual bool StartHeapTracking(double timeInterval, bool isVmMode = true) = 0;
173     virtual bool StopHeapTracking(const std::string &filePath) = 0;
174 
175     NativeErrorExtendedInfo* GetLastError();
176     void SetLastError(int errorCode, uint32_t engineErrorCode = 0, void* engineReserved = nullptr);
177     void ClearLastError();
178     virtual bool IsExceptionPending() const = 0;
179     virtual NativeValue* GetAndClearLastException() = 0;
180     void EncodeToUtf8(NativeValue* nativeValue, char* buffer, int32_t* written, size_t bufferSize, int32_t* nchars);
181     void EncodeToChinese(NativeValue* nativeValue, std::string& buffer, const std::string& encoding);
182     NativeEngine(NativeEngine&) = delete;
183     virtual NativeEngine& operator=(NativeEngine&) = delete;
184 
185     virtual NativeValue* ValueToNativeValue(JSValueWrapper& value) = 0;
186     virtual bool TriggerFatalException(NativeValue* error) = 0;
187     virtual bool AdjustExternalMemory(int64_t ChangeInBytes, int64_t* AdjustedValue) = 0;
188 
MarkSubThread()189     void MarkSubThread()
190     {
191         nativeEngineImpl_->MarkSubThread();
192     }
193 
IsMainThread()194     bool IsMainThread() const
195     {
196         return nativeEngineImpl_->IsMainThread();
197     }
198 
SetCleanEnv(CleanEnv cleanEnv)199     void SetCleanEnv(CleanEnv cleanEnv)
200     {
201         nativeEngineImpl_->SetCleanEnv(cleanEnv);
202     }
203 
204     // register init worker func
205     virtual void SetInitWorkerFunc(InitWorkerFunc func);
206     virtual void SetGetAssetFunc(GetAssetFunc func);
207     virtual void SetOffWorkerFunc(OffWorkerFunc func);
208 
209     // call init worker func
210     virtual bool CallInitWorkerFunc(NativeEngine* engine);
211     virtual bool CallGetAssetFunc(const std::string& uri, std::vector<uint8_t>& content, std::string& ami);
212     virtual bool CallOffWorkerFunc(NativeEngine* engine);
213 
214     // adapt worker to ace container
215     virtual void SetGetContainerScopeIdFunc(GetContainerScopeIdCallback func);
216     virtual void SetInitContainerScopeFunc(ContainerScopeCallback func);
217     virtual void SetFinishContainerScopeFunc(ContainerScopeCallback func);
218     virtual int32_t GetContainerScopeIdFunc();
219     virtual bool InitContainerScopeFunc(int32_t id);
220     virtual bool FinishContainerScopeFunc(int32_t id);
221 
222 #if !defined(PREVIEW)
223     virtual void SetDebuggerPostTaskFunc(DebuggerPostTask func);
224     virtual void CallDebuggerPostTaskFunc(std::function<void()>&& task);
225 #endif
226     virtual NativeValue* CreateDate(double value) = 0;
227     virtual NativeValue* CreateBigWords(int sign_bit, size_t word_count, const uint64_t* words) = 0;
228     using CleanupCallback = CleanupHookCallback::Callback;
229     virtual void AddCleanupHook(CleanupCallback fun, void* arg);
230     virtual void RemoveCleanupHook(CleanupCallback fun, void* arg);
231 
232     void CleanupHandles();
233     void IncreaseWaitingRequestCounter();
234     void DecreaseWaitingRequestCounter();
235     virtual void RunCleanup();
236 
IsStopping()237     bool IsStopping() const
238     {
239         return nativeEngineImpl_->IsStopping();
240     }
241 
SetStopping(bool value)242     void SetStopping(bool value)
243     {
244         nativeEngineImpl_->SetStopping(value);
245     }
246 
247     virtual void PrintStatisticResult() = 0;
248     virtual void StartRuntimeStat() = 0;
249     virtual void StopRuntimeStat() = 0;
250     virtual size_t GetArrayBufferSize() = 0;
251     virtual size_t GetHeapTotalSize() = 0;
252     virtual size_t GetHeapUsedSize() = 0;
253     virtual void NotifyApplicationState(bool inBackground) = 0;
254     virtual void NotifyIdleTime(int idleMicroSec) = 0;
255     virtual void NotifyMemoryPressure(bool inHighMemoryPressure = false) = 0;
256 
257     void RegisterWorkerFunction(const NativeEngine* engine);
258 
259     virtual void RegisterUncaughtExceptionHandler(UncaughtExceptionCallback callback) = 0;
260     virtual void HandleUncaughtException() = 0;
HasPendingException()261     virtual bool HasPendingException()
262     {
263         return false;
264     }
265     // run script by path
266     NativeValue* RunScript(const char* path);
267 
268     NativeEngineInterface* GetNativeEngineImpl();
269 
270     const char* GetModuleFileName();
271 
272     void SetModuleFileName(std::string &moduleName);
273 
274     void SetInstanceData(void* data, NativeFinalize finalize_cb, void* hint);
275     void GetInstanceData(void** data);
276 
277     /**
278      * @brief Set the Extension Infos
279      *
280      * @param extensionInfos extension infos to set
281      */
282     void SetExtensionInfos(std::unordered_map<std::string, int32_t>&& extensionInfos);
283 
284     /**
285      * @brief Get the Extension Infos
286      *
287      * @return extension infos
288      */
289     const std::unordered_map<std::string, int32_t>& GetExtensionInfos();
290 
291     /**
292      * @brief Set the Module Blocklist
293      *
294      * @param blocklist the blocklist set to native engine
295      */
296     void SetModuleBlocklist(std::unordered_map<int32_t, std::unordered_set<std::string>>&& blocklist);
297 
298 protected:
299     void *jsEngine_;
300 
301     NativeEngineInterface* nativeEngineImpl_ = nullptr;
302     bool isAppModule_ = false;
303 
304     // register for worker
305     InitWorkerFunc initWorkerFunc_ {nullptr};
306     GetAssetFunc getAssetFunc_ {nullptr};
307     OffWorkerFunc offWorkerFunc_ {nullptr};
308 #if !defined(PREVIEW)
309     DebuggerPostTask debuggerPostTaskFunc_ {nullptr};
310 #endif
311 
312 private:
313     std::string moduleName_;
314     std::mutex instanceDataLock_;
315     NativeObjectInfo instanceDataInfo_;
316     void FinalizerInstanceData(void);
317     std::unordered_map<std::string, int32_t> extensionInfos_;
318 };
319 
320 #endif /* FOUNDATION_ACE_NAPI_NATIVE_ENGINE_NATIVE_ENGINE_H */
321