• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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_V8_NATIVE_ENGINE_H
17 #define FOUNDATION_ACE_NAPI_NATIVE_ENGINE_V8_NATIVE_ENGINE_H
18 
19 #include "v8_headers.h"
20 
21 #include "native_engine/native_engine.h"
22 
23 namespace {
24 const int MB = 1024 * 1024;
25 const int MAX_SERIALIZER_MEMORY_USAGE = 1 * MB;
26 } // namespace
27 
28 #define DCHECK(condition)           assert(condition)
29 #define DCHECK_NOT_NULL(val) DCHECK((val) != nullptr)
30 
31 #define DISALLOW_COPY_AND_ASSIGN(TypeName)         \
32     TypeName(const TypeName&) = delete;            \
33     TypeName& operator=(const TypeName&) = delete
34 
35 class SerializationData {
36 public:
SerializationData()37     SerializationData() : data_(nullptr), size_(0) {}
38     ~SerializationData() = default;
39 
GetData()40     uint8_t* GetData() const
41     {
42         return data_.get();
43     }
GetSize()44     size_t GetSize() const
45     {
46         return size_;
47     }
GetBackingStores()48     const std::vector<std::shared_ptr<v8::BackingStore>>& GetBackingStores()
49     {
50         return backingStores_;
51     }
52 
53 private:
54     struct DataDeleter {
operatorDataDeleter55         void operator()(uint8_t* p) const
56         {
57             free(p);
58         }
59     };
60 
61     std::unique_ptr<uint8_t, DataDeleter> data_;
62     size_t size_;
63     std::vector<std::shared_ptr<v8::BackingStore>> backingStores_;
64 
65 private:
66     friend class Serializer;
67 
68     DISALLOW_COPY_AND_ASSIGN(SerializationData);
69 };
70 
71 class WorkerIsolateScope {
72 public:
WorkerIsolateScope()73     WorkerIsolateScope() {}
WorkerIsolateScope(v8::Isolate * isolate)74     explicit WorkerIsolateScope(v8::Isolate* isolate) : isolate_(isolate) {}
75 
SetIsolate(v8::Isolate * isolate)76     void SetIsolate(v8::Isolate* isolate)
77     {
78         isolate_ = isolate;
79     }
80 
~WorkerIsolateScope()81     ~WorkerIsolateScope()
82     {
83         if (isolate_ != nullptr) {
84             v8::Isolate::Scope iscope(isolate_);
85             isolate_->LowMemoryNotification();
86         }
87     }
88 private:
89     v8::Isolate* isolate_ { nullptr };
90 };
91 
92 class V8NativeEngine : public NativeEngine {
93 public:
94     // V8NativeEngine constructor
95     V8NativeEngine(v8::Platform *platform, v8::Isolate* isolate, v8::Persistent<v8::Context>& context, void* jsEngine);
96     // V8NativeEngine destructor
97     virtual ~V8NativeEngine();
98 
99     virtual void Loop(LoopMode mode, bool needSync = false) override;
100 
101     v8::Isolate* GetIsolate();
102     v8::Local<v8::Context> GetContext();
MarkAutoDispose()103     void MarkAutoDispose()
104     {
105         workerIsolateScope_.SetIsolate(isolate_);
106     }
107 
108     // Get global native object value
109     virtual NativeValue* GetGlobal() override;
110     // Create native null value
111     virtual NativeValue* CreateNull() override;
112     // Create native undefined value
113     virtual NativeValue* CreateUndefined() override;
114     // Create native boolean value
115     virtual NativeValue* CreateBoolean(bool value) override;
116     // Create number value by int32_t
117     virtual NativeValue* CreateNumber(int32_t value) override;
118     // Create number value by uint32_t
119     virtual NativeValue* CreateNumber(uint32_t value) override;
120     // Create native number value by int64_t
121     virtual NativeValue* CreateNumber(int64_t value) override;
122     // Create native number value by double
123     virtual NativeValue* CreateNumber(double value) override;
124     // Create native string value by const char pointer
125     virtual NativeValue* CreateString(const char* value, size_t length) override;
126     // Create native symbol value
127     virtual NativeValue* CreateSymbol(NativeValue* value) override;
128     // Create native value of external pointer
129     virtual NativeValue* CreateExternal(void* value, NativeFinalize callback, void* hint) override;
130     // Create native object value
131     virtual NativeValue* CreateObject() override;
132     // Create native function value
133     virtual NativeValue* CreateFunction(const char* name, size_t length, NativeCallback cb, void* value) override;
134     // Create native array value
135     virtual NativeValue* CreateArray(size_t length) override;
136     // Create native array buffer value
137     virtual NativeValue* CreateArrayBuffer(void** value, size_t length) override;
138     // Create native array buffer value of external
139     virtual NativeValue* CreateArrayBufferExternal(void* value, size_t length, NativeFinalize cb, void* hint) override;
140     // Create native typed array value
141     virtual NativeValue* CreateTypedArray(NativeTypedArrayType type,
142                                           NativeValue* value,
143                                           size_t length,
144                                           size_t offset) override;
145     // Create native data view value
146     virtual NativeValue* CreateDataView(NativeValue* value, size_t length, size_t offset) override;
147     // Create native promise value
148     virtual NativeValue* CreatePromise(NativeDeferred** deferred) override;
149     virtual void SetPromiseRejectCallback(NativeReference* rejectCallbackRef,
150                                           NativeReference* checkCallbackRef) override;
151     static void PromiseRejectCallback(v8::PromiseRejectMessage message);
152     // Create native error value
153     virtual NativeValue* CreateError(NativeValue* code, NativeValue* message) override;
154     // Call function
155     virtual NativeValue* CallFunction(NativeValue* thisVar,
156                                       NativeValue* function,
157                                       NativeValue* const* argv,
158                                       size_t argc) override;
159     // Run script
160     virtual NativeValue* RunScript(NativeValue* script) override;
161     // Run buffer script
162     virtual NativeValue* RunBufferScript(std::vector<uint8_t>& buffer) override;
163     virtual NativeValue* RunActor(std::vector<uint8_t>& buffer, const char *descriptor) override;
164     // Define native class
165     virtual NativeValue* DefineClass(const char* name,
166                                      NativeCallback callback,
167                                      void* data,
168                                      const NativePropertyDescriptor* properties,
169                                      size_t length) override;
170 
171     virtual NativeAsyncWork* CreateAsyncWork(NativeValue* asyncResource,
172                                              NativeValue* asyncResourceName,
173                                              NativeAsyncExecuteCallback execute,
174                                              NativeAsyncCompleteCallback complete,
175                                              void* data) override;
176 
177     // Create instance by defined class
178     virtual NativeValue* CreateInstance(NativeValue* constructor, NativeValue* const* argv, size_t argc) override;
179 
180     // Create native reference
181     virtual NativeReference* CreateReference(NativeValue* value, uint32_t initialRefcount) override;
182     // Throw exception
183     virtual bool Throw(NativeValue* error) override;
184     // Throw exception
185     virtual bool Throw(NativeErrorType type, const char* code, const char* message) override;
186 
187     virtual void* CreateRuntime() override;
188     virtual NativeValue* Serialize(NativeEngine* context, NativeValue* value, NativeValue* transfer) override;
189     virtual NativeValue* Deserialize(NativeEngine* context, NativeValue* recorder) override;
190     virtual ExceptionInfo* GetExceptionForWorker() const override;
191     virtual void DeleteSerializationData(NativeValue* value) const override;
192     void SetPackagePath(const std::string& packagePath);
193 
194     static NativeValue* V8ValueToNativeValue(V8NativeEngine* engine, v8::Local<v8::Value> value);
195     virtual NativeValue* LoadModule(NativeValue* str, const std::string& fileName) override;
196     virtual NativeValue* ValueToNativeValue(JSValueWrapper& value) override;
197 
198     v8::Local<v8::Object> GetModuleFromName(
199         const std::string& moduleName, bool isAppModule, const std::string& id, const std::string& param,
200         const std::string& instanceName, void** instance);
201     v8::Local<v8::Object> LoadModuleByName(
202         const std::string& moduleName, bool isAppModule, const std::string& param,
203         const std::string& instanceName, void* instance);
204     void StartCpuProfiler(const std::string fileName = "") override {}
StopCpuProfiler()205     void StopCpuProfiler() override {}
206 
ResumeVM()207     void ResumeVM() override {}
SuspendVM()208     bool SuspendVM() override
209     {
210         return false;
211     }
IsSuspended()212     bool IsSuspended() override
213     {
214         return false;
215     }
CheckSafepoint()216     bool CheckSafepoint() override
217     {
218         return false;
219     }
220 
221     void DumpHeapSnapShot(const std::string &path, bool isVmMode = true,
222         DumpFormat dumpFormat = DumpFormat::JSON) override {}
BuildNativeAndJsBackStackTrace()223     std::string BuildNativeAndJsBackStackTrace() override
224     {
225         return nullptr;
226     }
227     bool StartHeapTracking(double timeInterval, bool isVmMode = true) override
228     {
229         return false;
230     }
231     bool StopHeapTracking(const std::string &filePath, DumpFormat dumpFormat = DumpFormat::JSON) override
232     {
233         return false;
234     }
235 
PrintStatisticResult()236     void PrintStatisticResult() override {}
StartRuntimeStat()237     void StartRuntimeStat() override {}
StopRuntimeStat()238     void StopRuntimeStat() override {}
GetArrayBufferSize()239     size_t GetArrayBufferSize() override
240     {
241         return 0;
242     }
GetHeapTotalSize()243     size_t GetHeapTotalSize() override
244     {
245         return 0;
246     }
GetHeapUsedSize()247     size_t GetHeapUsedSize() override
248     {
249         return 0;
250     }
251 
RegisterUncaughtExceptionHandler(UncaughtExceptionCallback callback)252     void RegisterUncaughtExceptionHandler(UncaughtExceptionCallback callback) override {}
HandleUncaughtException()253     void HandleUncaughtException() override {}
254 private:
255     static void ExecuteWrap(NativeEngine* engine, void* data);
256     static void CompleteWrap(NativeEngine* engine, int status, void* data);
257 
258     v8::Platform* platform_;
259     v8::Isolate* isolate_;
260     WorkerIsolateScope workerIsolateScope_;
261     v8::Global<v8::Context> context_;
262     v8::Isolate::Scope isolateScope_;
263     v8::HandleScope handleScope_;
264     v8::Context::Scope contextScope_;
265     v8::TryCatch tryCatch_ { NULL };
266     NativeReference* promiseRejectCallbackRef_ { nullptr };
267     NativeReference* checkCallbackRef_ { nullptr };
268 };
269 
270 #endif /* FOUNDATION_ACE_NAPI_NATIVE_ENGINE_V8_NATIVE_ENGINE_H */
271