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