• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_engine.h"
17 
18 #include <mutex>
19 #include <optional>
20 #include <regex>
21 #include <unistd.h>
22 
23 #include "base/utils/utils.h"
24 #ifdef WINDOWS_PLATFORM
25 #include <algorithm>
26 #endif
27 
28 #include "scope_manager/native_scope_manager.h"
29 
30 #include "base/base64/base64_util.h"
31 #include "base/i18n/localization.h"
32 #include "base/log/ace_trace.h"
33 #include "base/log/event_report.h"
34 #include "core/common/ace_application_info.h"
35 #include "core/common/ace_view.h"
36 #include "core/common/card_scope.h"
37 #include "core/common/connect_server_manager.h"
38 #include "core/common/container.h"
39 #include "core/common/container_scope.h"
40 #include "core/components_v2/inspector/inspector_constants.h"
41 #include "frameworks/bridge/card_frontend/card_frontend_declarative.h"
42 #include "frameworks/bridge/card_frontend/form_frontend_declarative.h"
43 #include "frameworks/bridge/common/utils/engine_helper.h"
44 #include "frameworks/bridge/declarative_frontend/engine/js_converter.h"
45 #include "frameworks/bridge/declarative_frontend/engine/js_ref_ptr.h"
46 #include "frameworks/bridge/declarative_frontend/engine/js_types.h"
47 #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_group_js_bridge.h"
48 #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_types.h"
49 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_context_module.h"
50 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_module_manager.h"
51 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_syscap_module.h"
52 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_timer_module.h"
53 #include "frameworks/bridge/declarative_frontend/jsview/js_local_storage.h"
54 #include "frameworks/bridge/declarative_frontend/jsview/js_view_register.h"
55 #include "frameworks/bridge/declarative_frontend/jsview/js_xcomponent.h"
56 #include "frameworks/bridge/declarative_frontend/view_stack_processor.h"
57 #include "frameworks/bridge/js_frontend/engine/common/js_api_perf.h"
58 #include "frameworks/bridge/js_frontend/engine/common/runtime_constants.h"
59 #include "frameworks/bridge/js_frontend/engine/jsi/ark_js_runtime.h"
60 #include "frameworks/bridge/js_frontend/engine/jsi/ark_js_value.h"
61 #include "frameworks/bridge/js_frontend/engine/jsi/jsi_base_utils.h"
62 #include "frameworks/core/components/xcomponent/xcomponent_component_client.h"
63 #include "frameworks/core/components_ng/base/view_stack_processor.h"
64 #include "frameworks/core/components_ng/pattern/xcomponent/xcomponent_pattern.h"
65 
66 #if defined(PREVIEW)
67 extern const char _binary_jsMockSystemPlugin_abc_start[];
68 extern const char _binary_jsMockSystemPlugin_abc_end[];
69 #endif
70 extern const char _binary_stateMgmt_abc_start[];
71 extern const char _binary_stateMgmt_abc_end[];
72 extern const char _binary_jsEnumStyle_abc_start[];
73 extern const char _binary_jsEnumStyle_abc_end[];
74 
75 namespace OHOS::Ace::Framework {
76 namespace {
77 
78 #if defined(ANDROID_PLATFORM)
79 const std::string ARK_DEBUGGER_LIB_PATH = "libark_debugger.so";
80 #elif defined(APP_USE_ARM)
81 const std::string ARK_DEBUGGER_LIB_PATH = "/system/lib/libark_debugger.z.so";
82 #else
83 const std::string ARK_DEBUGGER_LIB_PATH = "/system/lib64/libark_debugger.z.so";
84 #endif
85 const std::string FORM_ES_MODULE_CARD_PATH = "ets/widgets.abc";
86 const std::string FORM_ES_MODULE_PATH = "ets/modules.abc";
87 
88 const std::string ASSET_PATH_PREFIX = "/data/storage/el1/bundle/";
89 
90 #ifdef PREVIEW
91 constexpr uint32_t PREFIX_LETTER_NUMBER = 4;
92 #endif
93 
94 std::mutex loadFormMutex_;
95 
96 // native implementation for js function: perfutil.print()
JsPerfPrint(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)97 shared_ptr<JsValue> JsPerfPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
98     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
99 {
100     std::string ret = JsApiPerf::GetInstance().PrintToLogs();
101     return runtime->NewString(ret);
102 }
103 
104 // native implementation for js function: perfutil.sleep()
JsPerfSleep(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)105 shared_ptr<JsValue> JsPerfSleep(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
106     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
107 {
108     int32_t valInt = argv[0]->ToInt32(runtime);
109     usleep(valInt);
110     return runtime->NewNull();
111 }
112 
113 // native implementation for js function: perfutil.begin()
JsPerfBegin(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)114 shared_ptr<JsValue> JsPerfBegin(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
115     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
116 {
117     int64_t currentTime = GetMicroTickCount();
118     JsApiPerf::GetInstance().InsertJsBeginLog(argv[0]->ToString(runtime), currentTime);
119     return runtime->NewNull();
120 }
121 
122 // native implementation for js function: perfutil.end()
JsPerfEnd(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)123 shared_ptr<JsValue> JsPerfEnd(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
124     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
125 {
126     int64_t currentTime = GetMicroTickCount();
127     JsApiPerf::GetInstance().InsertJsEndLog(argv[0]->ToString(runtime), currentTime);
128     return runtime->NewNull();
129 }
130 
RequireNativeModule(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)131 shared_ptr<JsValue> RequireNativeModule(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
132     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
133 {
134     std::string moduleName = argv[0]->ToString(runtime);
135 
136     // has already init module object
137     shared_ptr<JsValue> global = runtime->GetGlobal();
138     shared_ptr<JsValue> moduleObject = global->GetProperty(runtime, moduleName);
139     if (moduleObject != nullptr && moduleObject->IsObject(runtime)) {
140         LOGE("has already init moduleObject %{private}s", moduleName.c_str());
141         return moduleObject;
142     }
143 
144     // init module object first time
145     shared_ptr<JsValue> newObject = runtime->NewObject();
146     if (ModuleManager::GetInstance()->InitModule(runtime, newObject, moduleName)) {
147         global->SetProperty(runtime, moduleName, newObject);
148         return newObject;
149     }
150 
151     return runtime->NewNull();
152 }
153 } // namespace
154 
155 // -----------------------
156 // Start JsiDeclarativeEngineInstance
157 // -----------------------
158 std::map<std::string, std::string> JsiDeclarativeEngineInstance::mediaResourceFileMap_;
159 
160 std::unique_ptr<JsonValue> JsiDeclarativeEngineInstance::currentConfigResourceData_;
161 
162 bool JsiDeclarativeEngineInstance::isModulePreloaded_ = false;
163 bool JsiDeclarativeEngineInstance::isModuleInitialized_ = false;
164 shared_ptr<JsRuntime> JsiDeclarativeEngineInstance::globalRuntime_;
165 
166 // for async task callback executed after this instance has been destroyed.
167 thread_local void* cardRuntime_;
168 thread_local shared_ptr<JsRuntime> localRuntime_;
169 
170 // ArkTsCard start
171 thread_local bool isUnique_ = false;
172 // ArkTsCard end
173 
~JsiDeclarativeEngineInstance()174 JsiDeclarativeEngineInstance::~JsiDeclarativeEngineInstance()
175 {
176     CHECK_RUN_ON(JS);
177     LOG_DESTROY();
178 
179     if (runningPage_) {
180         runningPage_->OnJsEngineDestroy();
181     }
182 
183     if (stagingPage_) {
184         stagingPage_->OnJsEngineDestroy();
185     }
186 
187     if (runtime_) {
188         runtime_->RegisterUncaughtExceptionHandler(nullptr);
189         runtime_->Reset();
190     }
191     runtime_.reset();
192     runtime_ = nullptr;
193 }
194 
InitJsEnv(bool debuggerMode,const std::unordered_map<std::string,void * > & extraNativeObject,const shared_ptr<JsRuntime> & runtime)195 bool JsiDeclarativeEngineInstance::InitJsEnv(bool debuggerMode,
196     const std::unordered_map<std::string, void*>& extraNativeObject, const shared_ptr<JsRuntime>& runtime)
197 {
198     CHECK_RUN_ON(JS);
199     ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitJsEnv");
200     if (runtime != nullptr) {
201         LOGD("JsiDeclarativeEngineInstance InitJsEnv usingSharedRuntime");
202         runtime_ = runtime;
203         usingSharedRuntime_ = true;
204     } else {
205         LOGD("JsiDeclarativeEngineInstance InitJsEnv not usingSharedRuntime, create own");
206         runtime_.reset(new ArkJSRuntime());
207     }
208 
209     if (runtime_ == nullptr) {
210         LOGE("Js Engine cannot allocate JSI JSRuntime");
211         EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR);
212         return false;
213     }
214 
215     runtime_->SetLogPrint(PrintLog);
216     std::string libraryPath = "";
217     if (debuggerMode) {
218         libraryPath = ARK_DEBUGGER_LIB_PATH;
219         SetDebuggerPostTask();
220     }
221     if (!usingSharedRuntime_ && !runtime_->Initialize(libraryPath, isDebugMode_, instanceId_)) {
222         LOGE("Js Engine initialize runtime failed");
223         return false;
224     }
225 
226     runtime_->SetEmbedderData(this);
227     runtime_->RegisterUncaughtExceptionHandler(JsiBaseUtils::ReportJsErrorEvent);
228 
229 #if !defined(PREVIEW)
230     for (const auto& [key, value] : extraNativeObject) {
231         shared_ptr<JsValue> nativeValue = runtime_->NewNativePointer(value);
232         runtime_->GetGlobal()->SetProperty(runtime_, key, nativeValue);
233     }
234 
235     runtime_->StartDebugger();
236 #endif
237 
238     LocalScope scope(std::static_pointer_cast<ArkJSRuntime>(runtime_)->GetEcmaVm());
239     if (!isModulePreloaded_ || !usingSharedRuntime_ || IsPlugin()) {
240         InitGlobalObjectTemplate();
241     }
242 
243     // no need to initialize functions on global when use shared runtime
244     if (usingSharedRuntime_ && isModuleInitialized_ && !isUnique_) { // ArtTsCard
245         LOGI("InitJsEnv SharedRuntime has initialized, skip...");
246     } else {
247         InitGroupJsBridge();
248         if (!isModulePreloaded_ || !usingSharedRuntime_ || IsPlugin() || isUnique_) { // ArtTsCard
249             InitConsoleModule();
250             InitAceModule();
251             InitJsExportsUtilObject();
252             InitJsNativeModuleObject();
253             InitPerfUtilModule();
254             InitJsContextModuleObject();
255         }
256     }
257 
258     if (usingSharedRuntime_) {
259         isModuleInitialized_ = true;
260     }
261 
262     // load resourceConfig
263     currentConfigResourceData_ = JsonUtil::CreateArray(true);
264     frontendDelegate_->LoadResourceConfiguration(mediaResourceFileMap_, currentConfigResourceData_);
265     isEngineInstanceInitialized_ = true;
266     return true;
267 }
268 
FireJsEvent(const std::string & eventStr)269 bool JsiDeclarativeEngineInstance::FireJsEvent(const std::string& eventStr)
270 {
271     return true;
272 }
273 
InitAceModule()274 void JsiDeclarativeEngineInstance::InitAceModule()
275 {
276     if (isUnique_ == false) {
277         uint8_t* codeStart;
278         int32_t codeLength;
279         codeStart = (uint8_t*)_binary_stateMgmt_abc_start;
280         codeLength = _binary_stateMgmt_abc_end - _binary_stateMgmt_abc_start;
281         bool stateMgmtResult = runtime_->EvaluateJsCode(codeStart, codeLength);
282         if (!stateMgmtResult) {
283             LOGE("EvaluateJsCode stateMgmt failed");
284         }
285         bool jsEnumStyleResult = runtime_->EvaluateJsCode(
286             (uint8_t*)_binary_jsEnumStyle_abc_start, _binary_jsEnumStyle_abc_end - _binary_jsEnumStyle_abc_start);
287         if (!jsEnumStyleResult) {
288             LOGE("EvaluateJsCode jsEnumStyle failed");
289         }
290     }
291 #if defined(PREVIEW)
292     std::string jsMockSystemPluginString(_binary_jsMockSystemPlugin_abc_start,
293         _binary_jsMockSystemPlugin_abc_end - _binary_jsMockSystemPlugin_abc_start);
294     bool jsMockSystemPlugin =
295         runtime_->EvaluateJsCode((uint8_t*)(jsMockSystemPluginString.c_str()), jsMockSystemPluginString.length());
296     if (!jsMockSystemPlugin) {
297         LOGE("EvaluateJsCode jsMockSystemPlugin failed");
298     }
299 #endif
300 }
301 
OHOS_ACE_PreloadAceModule(void * runtime)302 extern "C" ACE_FORCE_EXPORT void OHOS_ACE_PreloadAceModule(void* runtime)
303 {
304     LOGI("Ace ark lib loaded, PreloadAceModule.");
305     JsiDeclarativeEngineInstance::PreloadAceModule(runtime);
306 }
307 
PreloadAceModule(void * runtime)308 void JsiDeclarativeEngineInstance::PreloadAceModule(void* runtime)
309 {
310     if (isModulePreloaded_ && !IsPlugin()) {
311         LOGE("PreloadAceModule already preloaded");
312         return;
313     }
314     auto sharedRuntime = reinterpret_cast<NativeEngine*>(runtime);
315 
316     if (!sharedRuntime) {
317         LOGE("PreloadAceModule null runtime");
318         return;
319     }
320     std::shared_ptr<ArkJSRuntime> arkRuntime = std::make_shared<ArkJSRuntime>();
321     auto nativeArkEngine = static_cast<ArkNativeEngine*>(sharedRuntime);
322     EcmaVM* vm = const_cast<EcmaVM*>(nativeArkEngine->GetEcmaVm());
323     if (vm == nullptr) {
324         LOGE("PreloadAceModule NativeDeclarativeEngine Initialize, vm is null");
325         return;
326     }
327     if (!arkRuntime->InitializeFromExistVM(vm)) {
328         LOGE("PreloadAceModule Ark Engine initialize runtime failed");
329         return;
330     }
331     LocalScope scope(vm);
332     globalRuntime_ = arkRuntime;
333     // preload js views
334     JsRegisterViews(JSNApi::GetGlobalObject(vm));
335 
336     // preload aceConsole
337     shared_ptr<JsValue> global = arkRuntime->GetGlobal();
338     shared_ptr<JsValue> aceConsoleObj = arkRuntime->NewObject();
339     aceConsoleObj->SetProperty(arkRuntime, "log", arkRuntime->NewFunction(JsiBaseUtils::JsInfoLogPrint));
340     aceConsoleObj->SetProperty(arkRuntime, "debug", arkRuntime->NewFunction(JsiBaseUtils::JsDebugLogPrint));
341     aceConsoleObj->SetProperty(arkRuntime, "info", arkRuntime->NewFunction(JsiBaseUtils::JsInfoLogPrint));
342     aceConsoleObj->SetProperty(arkRuntime, "warn", arkRuntime->NewFunction(JsiBaseUtils::JsWarnLogPrint));
343     aceConsoleObj->SetProperty(arkRuntime, "error", arkRuntime->NewFunction(JsiBaseUtils::JsErrorLogPrint));
344     global->SetProperty(arkRuntime, "aceConsole", aceConsoleObj);
345 
346     // preload aceTrace
347     shared_ptr<JsValue> aceTraceObj = arkRuntime->NewObject();
348     aceTraceObj->SetProperty(arkRuntime, "begin", arkRuntime->NewFunction(JsiBaseUtils::JsTraceBegin));
349     aceTraceObj->SetProperty(arkRuntime, "end", arkRuntime->NewFunction(JsiBaseUtils::JsTraceEnd));
350     global->SetProperty(arkRuntime, "aceTrace", aceTraceObj);
351 
352     // preload getContext
353     JsiContextModule::GetInstance()->InitContextModule(arkRuntime, global);
354 
355     // preload perfutil
356     shared_ptr<JsValue> perfObj = arkRuntime->NewObject();
357     perfObj->SetProperty(arkRuntime, "printlog", arkRuntime->NewFunction(JsPerfPrint));
358     perfObj->SetProperty(arkRuntime, "sleep", arkRuntime->NewFunction(JsPerfSleep));
359     perfObj->SetProperty(arkRuntime, "begin", arkRuntime->NewFunction(JsPerfBegin));
360     perfObj->SetProperty(arkRuntime, "end", arkRuntime->NewFunction(JsPerfEnd));
361     global->SetProperty(arkRuntime, "perfutil", perfObj);
362 
363     // preload exports and requireNative
364     shared_ptr<JsValue> exportsUtilObj = arkRuntime->NewObject();
365     global->SetProperty(arkRuntime, "exports", exportsUtilObj);
366     global->SetProperty(arkRuntime, "requireNativeModule", arkRuntime->NewFunction(RequireNativeModule));
367 
368     // preload js enums
369     bool jsEnumStyleResult = arkRuntime->EvaluateJsCode(
370         (uint8_t*)_binary_jsEnumStyle_abc_start, _binary_jsEnumStyle_abc_end - _binary_jsEnumStyle_abc_start);
371     if (!jsEnumStyleResult) {
372         LOGE("EvaluateJsCode jsEnumStyle failed");
373         globalRuntime_ = nullptr;
374         return;
375     }
376 
377     // preload state management
378     uint8_t* codeStart;
379     int32_t codeLength;
380     codeStart = (uint8_t*)_binary_stateMgmt_abc_start;
381     codeLength = _binary_stateMgmt_abc_end - _binary_stateMgmt_abc_start;
382     bool evalResult = arkRuntime->EvaluateJsCode(codeStart, codeLength);
383     if (!evalResult) {
384         LOGE("PreloadAceModule EvaluateJsCode stateMgmt failed");
385     }
386 
387     isModulePreloaded_ = evalResult;
388     globalRuntime_ = nullptr;
389     LOGI("PreloadAceModule loaded:%{public}d", isModulePreloaded_);
390     localRuntime_ = arkRuntime;
391     cardRuntime_ = runtime;
392 }
393 
InitConsoleModule()394 void JsiDeclarativeEngineInstance::InitConsoleModule()
395 {
396     ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitConsoleModule");
397     LOGD("JsiDeclarativeEngineInstance InitConsoleModule");
398     shared_ptr<JsValue> global = runtime_->GetGlobal();
399 
400     // app log method
401     if (!usingSharedRuntime_) {
402         shared_ptr<JsValue> consoleObj = runtime_->NewObject();
403         consoleObj->SetProperty(runtime_, "log", runtime_->NewFunction(JsiBaseUtils::AppInfoLogPrint));
404         consoleObj->SetProperty(runtime_, "debug", runtime_->NewFunction(JsiBaseUtils::AppDebugLogPrint));
405         consoleObj->SetProperty(runtime_, "info", runtime_->NewFunction(JsiBaseUtils::AppInfoLogPrint));
406         consoleObj->SetProperty(runtime_, "warn", runtime_->NewFunction(JsiBaseUtils::AppWarnLogPrint));
407         consoleObj->SetProperty(runtime_, "error", runtime_->NewFunction(JsiBaseUtils::AppErrorLogPrint));
408         global->SetProperty(runtime_, "console", consoleObj);
409     }
410 
411     if (isModulePreloaded_ && usingSharedRuntime_ && !IsPlugin() && !isUnique_) { // ArkTsCard
412         LOGD("console module has already preloaded");
413         return;
414     }
415 
416     // js framework log method
417     shared_ptr<JsValue> aceConsoleObj = runtime_->NewObject();
418     aceConsoleObj->SetProperty(runtime_, "log", runtime_->NewFunction(JsiBaseUtils::JsInfoLogPrint));
419     aceConsoleObj->SetProperty(runtime_, "debug", runtime_->NewFunction(JsiBaseUtils::JsDebugLogPrint));
420     aceConsoleObj->SetProperty(runtime_, "info", runtime_->NewFunction(JsiBaseUtils::JsInfoLogPrint));
421     aceConsoleObj->SetProperty(runtime_, "warn", runtime_->NewFunction(JsiBaseUtils::JsWarnLogPrint));
422     aceConsoleObj->SetProperty(runtime_, "error", runtime_->NewFunction(JsiBaseUtils::JsErrorLogPrint));
423     global->SetProperty(runtime_, "aceConsole", aceConsoleObj);
424 
425     // js framework trace method
426     shared_ptr<JsValue> aceTraceObj = runtime_->NewObject();
427     aceTraceObj->SetProperty(runtime_, "begin", runtime_->NewFunction(JsiBaseUtils::JsTraceBegin));
428     aceTraceObj->SetProperty(runtime_, "end", runtime_->NewFunction(JsiBaseUtils::JsTraceEnd));
429     global->SetProperty(runtime_, "aceTrace", aceTraceObj);
430 }
431 
InitConsoleModule(ArkNativeEngine * engine)432 void JsiDeclarativeEngineInstance::InitConsoleModule(ArkNativeEngine* engine)
433 {
434     ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::RegisterConsoleModule");
435     LOGD("JsiDeclarativeEngineInstance RegisterConsoleModule to nativeEngine");
436     NativeValue* global = engine->GetGlobal();
437     if (global->TypeOf() != NATIVE_OBJECT) {
438         LOGE("global is not NativeObject");
439         return;
440     }
441     auto nativeGlobal = reinterpret_cast<NativeObject*>(global->GetInterface(NativeObject::INTERFACE_ID));
442 
443     // app log method
444     NativeValue* console = engine->CreateObject();
445     auto consoleObj = reinterpret_cast<NativeObject*>(console->GetInterface(NativeObject::INTERFACE_ID));
446     consoleObj->SetProperty("log", engine->CreateFunction("log", strlen("log"), AppInfoLogPrint, nullptr));
447     consoleObj->SetProperty("debug", engine->CreateFunction("debug", strlen("debug"), AppDebugLogPrint, nullptr));
448     consoleObj->SetProperty("info", engine->CreateFunction("info", strlen("info"), AppInfoLogPrint, nullptr));
449     consoleObj->SetProperty("warn", engine->CreateFunction("warn", strlen("warn"), AppWarnLogPrint, nullptr));
450     consoleObj->SetProperty("error", engine->CreateFunction("error", strlen("error"), AppErrorLogPrint, nullptr));
451     nativeGlobal->SetProperty("console", console);
452 }
453 
InitPerfUtilModule()454 void JsiDeclarativeEngineInstance::InitPerfUtilModule()
455 {
456     ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitPerfUtilModule");
457     LOGD("JsiDeclarativeEngineInstance InitPerfUtilModule");
458     shared_ptr<JsValue> perfObj = runtime_->NewObject();
459     perfObj->SetProperty(runtime_, "printlog", runtime_->NewFunction(JsPerfPrint));
460     perfObj->SetProperty(runtime_, "sleep", runtime_->NewFunction(JsPerfSleep));
461     perfObj->SetProperty(runtime_, "begin", runtime_->NewFunction(JsPerfBegin));
462     perfObj->SetProperty(runtime_, "end", runtime_->NewFunction(JsPerfEnd));
463 
464     shared_ptr<JsValue> global = runtime_->GetGlobal();
465     global->SetProperty(runtime_, "perfutil", perfObj);
466 }
467 
InitJsExportsUtilObject()468 void JsiDeclarativeEngineInstance::InitJsExportsUtilObject()
469 {
470     shared_ptr<JsValue> exportsUtilObj = runtime_->NewObject();
471     shared_ptr<JsValue> global = runtime_->GetGlobal();
472     global->SetProperty(runtime_, "exports", exportsUtilObj);
473 }
474 
InitJsNativeModuleObject()475 void JsiDeclarativeEngineInstance::InitJsNativeModuleObject()
476 {
477     shared_ptr<JsValue> global = runtime_->GetGlobal();
478     global->SetProperty(runtime_, "requireNativeModule", runtime_->NewFunction(RequireNativeModule));
479     auto context = PipelineBase::GetCurrentContext();
480     CHECK_NULL_VOID(context);
481     if (!usingSharedRuntime_) {
482         if (!context->IsFormRender()) {
483             JsiTimerModule::GetInstance()->InitTimerModule(runtime_, global);
484         } else {
485             LOGI("Not supported TimerModule when form render");
486         }
487 
488         JsiSyscapModule::GetInstance()->InitSyscapModule(runtime_, global);
489     }
490 }
491 
InitJsContextModuleObject()492 void JsiDeclarativeEngineInstance::InitJsContextModuleObject()
493 {
494     JsiContextModule::GetInstance()->InitContextModule(runtime_, runtime_->GetGlobal());
495 }
496 
InitGlobalObjectTemplate()497 void JsiDeclarativeEngineInstance::InitGlobalObjectTemplate()
498 {
499     auto runtime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
500     JsRegisterViews(JSNApi::GetGlobalObject(runtime->GetEcmaVm()));
501 }
502 
InitGroupJsBridge()503 void JsiDeclarativeEngineInstance::InitGroupJsBridge()
504 {
505     auto groupJsBridge = DynamicCast<JsiDeclarativeGroupJsBridge>(frontendDelegate_->GetGroupJsBridge());
506     if (groupJsBridge == nullptr || groupJsBridge->InitializeGroupJsBridge(runtime_) == JS_CALL_FAIL) {
507         LOGE("Js Engine Initialize GroupJsBridge failed!");
508         EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR);
509     }
510 }
511 
RootViewHandle(panda::Local<panda::ObjectRef> value)512 void JsiDeclarativeEngineInstance::RootViewHandle(panda::Local<panda::ObjectRef> value)
513 {
514     LOGD("RootViewHandle");
515     RefPtr<JsAcePage> page = JsiDeclarativeEngineInstance::GetStagingPage(Container::CurrentId());
516     if (page != nullptr) {
517         auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(GetCurrentRuntime());
518         if (!arkRuntime) {
519             LOGE("ark engine is null");
520             return;
521         }
522         auto engine = EngineHelper::GetCurrentEngine();
523         auto jsiEngine = AceType::DynamicCast<JsiDeclarativeEngine>(engine);
524         if (!jsiEngine) {
525             LOGE("jsiEngine is null");
526             return;
527         }
528         auto engineInstance = jsiEngine->GetEngineInstance();
529         if (engineInstance == nullptr) {
530             LOGE("engineInstance is nullptr");
531             return;
532         }
533         engineInstance->SetRootView(page->GetPageId(), panda::Global<panda::ObjectRef>(arkRuntime->GetEcmaVm(), value));
534     }
535 }
536 
DestroyRootViewHandle(int32_t pageId)537 void JsiDeclarativeEngineInstance::DestroyRootViewHandle(int32_t pageId)
538 {
539     CHECK_RUN_ON(JS);
540     JAVASCRIPT_EXECUTION_SCOPE_STATIC;
541     if (rootViewMap_.count(pageId) != 0) {
542         auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
543         if (!arkRuntime) {
544             LOGE("ark engine is null");
545             return;
546         }
547         panda::Local<panda::ObjectRef> rootView = rootViewMap_[pageId].ToLocal(arkRuntime->GetEcmaVm());
548         auto* jsView = static_cast<JSView*>(rootView->GetNativePointerField(0));
549         if (jsView != nullptr) {
550             jsView->Destroy(nullptr);
551         }
552         rootViewMap_[pageId].FreeGlobalHandleAddr();
553         rootViewMap_.erase(pageId);
554     }
555 }
556 
DestroyAllRootViewHandle()557 void JsiDeclarativeEngineInstance::DestroyAllRootViewHandle()
558 {
559     CHECK_RUN_ON(JS);
560     JAVASCRIPT_EXECUTION_SCOPE_STATIC;
561     if (rootViewMap_.size() > 0) {
562         LOGI("DestroyAllRootViewHandle release left %{private}zu views ", rootViewMap_.size());
563     }
564     auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
565     if (!arkRuntime) {
566         LOGE("ark engine is null");
567         return;
568     }
569     for (const auto& pair : rootViewMap_) {
570         auto globalRootView = pair.second;
571         panda::Local<panda::ObjectRef> rootView = globalRootView.ToLocal(arkRuntime->GetEcmaVm());
572         auto* jsView = static_cast<JSView*>(rootView->GetNativePointerField(0));
573         if (jsView != nullptr) {
574             jsView->Destroy(nullptr);
575         }
576         globalRootView.FreeGlobalHandleAddr();
577     }
578     rootViewMap_.clear();
579 }
580 
FlushReload()581 void JsiDeclarativeEngineInstance::FlushReload()
582 {
583     CHECK_RUN_ON(JS);
584     JAVASCRIPT_EXECUTION_SCOPE_STATIC;
585     if (rootViewMap_.empty()) {
586         LOGW("FlushReload release left %{private}zu views ", rootViewMap_.size());
587         return;
588     }
589     auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
590     if (!arkRuntime) {
591         LOGE("ark runtime is null");
592         return;
593     }
594     for (const auto& pair : rootViewMap_) {
595         auto globalRootView = pair.second;
596         panda::Local<panda::ObjectRef> rootView = globalRootView.ToLocal(arkRuntime->GetEcmaVm());
597         auto* jsView = static_cast<JSView*>(rootView->GetNativePointerField(0));
598         if (jsView != nullptr) {
599             jsView->MarkNeedUpdate();
600         }
601     }
602     LOGI("JSI engine finished flush reload");
603 }
604 
GetI18nStringResource(const std::string & targetStringKey,const std::string & targetStringValue)605 std::unique_ptr<JsonValue> JsiDeclarativeEngineInstance::GetI18nStringResource(
606     const std::string& targetStringKey, const std::string& targetStringValue)
607 {
608     auto resourceI18nFileNum = currentConfigResourceData_->GetArraySize();
609     for (int i = 0; i < resourceI18nFileNum; i++) {
610         auto priorResource = currentConfigResourceData_->GetArrayItem(i);
611         if ((priorResource->Contains(targetStringKey))) {
612             auto valuePair = priorResource->GetValue(targetStringKey);
613             if (valuePair->Contains(targetStringValue)) {
614                 return valuePair->GetValue(targetStringValue);
615             }
616         }
617     }
618 
619     return JsonUtil::Create(true);
620 }
621 
GetMediaResource(const std::string & targetFileName)622 std::string JsiDeclarativeEngineInstance::GetMediaResource(const std::string& targetFileName)
623 {
624     auto iter = mediaResourceFileMap_.find(targetFileName);
625 
626     if (iter != mediaResourceFileMap_.end()) {
627         return iter->second;
628     }
629 
630     return std::string();
631 }
632 
GetRunningPage(int32_t instanceId)633 RefPtr<JsAcePage> JsiDeclarativeEngineInstance::GetRunningPage(int32_t instanceId)
634 {
635     auto engine = EngineHelper::GetEngine(instanceId);
636     auto jsiEngine = AceType::DynamicCast<JsiDeclarativeEngine>(engine);
637     if (!jsiEngine) {
638         LOGE("jsiEngine is null");
639         return nullptr;
640     }
641     auto engineInstance = jsiEngine->GetEngineInstance();
642     if (engineInstance == nullptr) {
643         LOGE("engineInstance is nullptr");
644         return nullptr;
645     }
646     return engineInstance->GetRunningPage();
647 }
648 
GetStagingPage(int32_t instanceId)649 RefPtr<JsAcePage> JsiDeclarativeEngineInstance::GetStagingPage(int32_t instanceId)
650 {
651     auto engine = EngineHelper::GetEngine(instanceId);
652     auto jsiEngine = AceType::DynamicCast<JsiDeclarativeEngine>(engine);
653     if (!jsiEngine) {
654         LOGE("jsiEngine is null");
655         return nullptr;
656     }
657     auto engineInstance = jsiEngine->GetEngineInstance();
658     LOGD("GetStagingPage id:%{public}d", instanceId);
659     if (engineInstance == nullptr) {
660         LOGE("engineInstance is nullptr");
661         return nullptr;
662     }
663     return engineInstance->GetStagingPage();
664 }
665 
GetCurrentRuntime()666 shared_ptr<JsRuntime> JsiDeclarativeEngineInstance::GetCurrentRuntime()
667 {
668     auto jsRuntime = InnerGetCurrentRuntime();
669     if (isUnique_ && jsRuntime) {
670         return jsRuntime;
671     }
672 
673     // ArkTsCard
674     if (isUnique_ && localRuntime_) {
675         return localRuntime_;
676     }
677 
678     // Preload
679     if (globalRuntime_) {
680         return globalRuntime_;
681     }
682 
683     return jsRuntime == nullptr ? localRuntime_ : jsRuntime;
684 }
685 
InnerGetCurrentRuntime()686 shared_ptr<JsRuntime> JsiDeclarativeEngineInstance::InnerGetCurrentRuntime()
687 {
688     auto engine = EngineHelper::GetCurrentEngine();
689     auto jsiEngine = AceType::DynamicCast<JsiDeclarativeEngine>(engine);
690     if (!jsiEngine) {
691         LOGE("jsiEngine is null");
692         return nullptr;
693     }
694 
695     auto engineInstance = jsiEngine->GetEngineInstance();
696     if (engineInstance == nullptr) {
697         LOGE("engineInstance is nullptr");
698         return nullptr;
699     }
700 
701     if (isUnique_ && !engineInstance->IsEngineInstanceInitialized()) {
702         LOGI("engineInstance is not Initialized");
703         return nullptr;
704     }
705 
706     return engineInstance->GetJsRuntime();
707 }
708 
PostJsTask(const shared_ptr<JsRuntime> & runtime,std::function<void ()> && task)709 void JsiDeclarativeEngineInstance::PostJsTask(const shared_ptr<JsRuntime>& runtime, std::function<void()>&& task)
710 {
711     LOGD("PostJsTask");
712     if (runtime == nullptr) {
713         LOGE("jsRuntime is nullptr");
714         return;
715     }
716     auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData());
717     if (engineInstance == nullptr) {
718         LOGE("engineInstance is nullptr");
719         return;
720     }
721     engineInstance->GetDelegate()->PostJsTask(std::move(task));
722 }
723 
TriggerPageUpdate(const shared_ptr<JsRuntime> & runtime)724 void JsiDeclarativeEngineInstance::TriggerPageUpdate(const shared_ptr<JsRuntime>& runtime)
725 {
726     LOGD("TriggerPageUpdate");
727     CHECK_NULL_VOID(runtime);
728     auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData());
729     CHECK_NULL_VOID(engineInstance);
730     auto page = engineInstance->GetRunningPage();
731     CHECK_NULL_VOID(page);
732     engineInstance->GetDelegate()->TriggerPageUpdate(page->GetPageId());
733 }
734 
GetPipelineContext(const shared_ptr<JsRuntime> & runtime)735 RefPtr<PipelineBase> JsiDeclarativeEngineInstance::GetPipelineContext(const shared_ptr<JsRuntime>& runtime)
736 {
737     LOGD("GetPipelineContext");
738     if (runtime == nullptr) {
739         LOGE("jsRuntime is nullptr");
740         return nullptr;
741     }
742     auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData());
743     if (engineInstance == nullptr) {
744         LOGE("engineInstance is nullptr");
745         return nullptr;
746     }
747     return engineInstance->GetDelegate()->GetPipelineContext();
748 }
749 
FlushCommandBuffer(void * context,const std::string & command)750 void JsiDeclarativeEngineInstance::FlushCommandBuffer(void* context, const std::string& command)
751 {
752     return;
753 }
754 
IsPlugin()755 bool JsiDeclarativeEngineInstance::IsPlugin()
756 {
757     return (ContainerScope::CurrentId() >= MIN_PLUGIN_SUBCONTAINER_ID);
758 }
759 
SetDebuggerPostTask()760 void JsiDeclarativeEngineInstance::SetDebuggerPostTask()
761 {
762     auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(frontendDelegate_));
763     auto&& postTask = [weakDelegate](std::function<void()>&& task) {
764         auto delegate = weakDelegate.Upgrade();
765         if (delegate == nullptr) {
766             LOGE("delegate is nullptr");
767             return;
768         }
769         delegate->PostJsTask(std::move(task));
770     };
771     std::static_pointer_cast<ArkJSRuntime>(runtime_)->SetDebuggerPostTask(postTask);
772 }
773 
RegisterFaPlugin()774 void JsiDeclarativeEngineInstance::RegisterFaPlugin()
775 {
776     shared_ptr<JsValue> global = runtime_->GetGlobal();
777     shared_ptr<JsValue> requireNapiFunc = global->GetProperty(runtime_, "requireNapi");
778     if (!requireNapiFunc || !requireNapiFunc->IsFunction(runtime_)) {
779         LOGW("requireNapi func not found");
780     }
781     std::vector<shared_ptr<JsValue>> argv = { runtime_->NewString("FeatureAbility") };
782     requireNapiFunc->Call(runtime_, global, argv, argv.size());
783 }
784 
785 // -----------------------
786 // Start JsiDeclarativeEngine
787 // -----------------------
~JsiDeclarativeEngine()788 JsiDeclarativeEngine::~JsiDeclarativeEngine()
789 {
790     CHECK_RUN_ON(JS);
791     LOG_DESTROY();
792 }
793 
Destroy()794 void JsiDeclarativeEngine::Destroy()
795 {
796     LOGI("JsiDeclarativeEngine Destroy");
797     CHECK_RUN_ON(JS);
798 
799 #ifdef USE_ARK_ENGINE
800     JSLocalStorage::RemoveStorage(instanceId_);
801     JsiContextModule::RemoveContext(instanceId_);
802 #endif
803 
804     engineInstance_->GetDelegate()->RemoveTaskObserver();
805     engineInstance_->DestroyAllRootViewHandle();
806     if (isUnique_) {
807         RunFullGarbageCollection();
808     }
809 
810     if (!runtime_ && nativeEngine_ != nullptr) {
811 #if !defined(PREVIEW)
812         nativeEngine_->CancelCheckUVLoop();
813 #endif
814         nativeEngine_->DeleteEngine();
815         delete nativeEngine_;
816         nativeEngine_ = nullptr;
817     }
818 }
819 
Initialize(const RefPtr<FrontendDelegate> & delegate)820 bool JsiDeclarativeEngine::Initialize(const RefPtr<FrontendDelegate>& delegate)
821 {
822     CHECK_RUN_ON(JS);
823     ACE_SCOPED_TRACE("JsiDeclarativeEngine::Initialize");
824     LOGI("JsiDeclarativeEngine Initialize");
825     ACE_DCHECK(delegate);
826     engineInstance_ = AceType::MakeRefPtr<JsiDeclarativeEngineInstance>(delegate);
827     auto sharedRuntime = reinterpret_cast<NativeEngine*>(runtime_);
828     std::shared_ptr<ArkJSRuntime> arkRuntime;
829     EcmaVM* vm = nullptr;
830     if (!sharedRuntime) {
831         LOGI("Initialize will not use sharedRuntime");
832     } else {
833         LOGI("Initialize will use sharedRuntime");
834         arkRuntime = std::make_shared<ArkJSRuntime>();
835         if (isUnique_ && reinterpret_cast<NativeEngine*>(cardRuntime_) != nullptr) {
836             sharedRuntime = reinterpret_cast<NativeEngine*>(cardRuntime_);
837         }
838         auto nativeArkEngine = static_cast<ArkNativeEngine*>(sharedRuntime);
839         vm = const_cast<EcmaVM*>(nativeArkEngine->GetEcmaVm());
840         if (vm == nullptr) {
841             LOGE("NativeDeclarativeEngine Initialize, vm is null");
842             return false;
843         }
844         if (!arkRuntime->InitializeFromExistVM(vm)) {
845             LOGE("Ark Engine initialize runtime failed");
846             return false;
847         }
848         nativeEngine_ = nativeArkEngine;
849     }
850     engineInstance_->SetInstanceId(instanceId_);
851     engineInstance_->SetDebugMode(NeedDebugBreakPoint());
852     bool result = engineInstance_->InitJsEnv(IsDebugVersion(), GetExtraNativeObject(), arkRuntime);
853     if (!result) {
854         LOGE("JsiDeclarativeEngine Initialize, init js env failed");
855         return false;
856     }
857 
858     auto runtime = engineInstance_->GetJsRuntime();
859     vm = vm ? vm : const_cast<EcmaVM*>(std::static_pointer_cast<ArkJSRuntime>(runtime)->GetEcmaVm());
860     if (vm == nullptr) {
861         LOGE("JsiDeclarativeEngine Initialize, vm is null");
862         return false;
863     }
864 
865     if (nativeEngine_ == nullptr) {
866         nativeEngine_ = new ArkNativeEngine(vm, static_cast<void*>(this));
867     }
868     engineInstance_->SetNativeEngine(nativeEngine_);
869     if (!sharedRuntime) {
870         SetPostTask(nativeEngine_);
871 #if !defined(PREVIEW)
872         nativeEngine_->CheckUVLoop();
873 #endif
874 
875         if (delegate && delegate->GetAssetManager()) {
876             std::vector<std::string> packagePath = delegate->GetAssetManager()->GetLibPath();
877             auto appLibPathKey = delegate->GetAssetManager()->GetAppLibPathKey();
878             if (!packagePath.empty()) {
879                 auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine_);
880                 arkNativeEngine->SetPackagePath(appLibPathKey, packagePath);
881             }
882         }
883 
884         RegisterWorker();
885         engineInstance_->RegisterFaPlugin();
886     } else {
887         LOGI("Using sharedRuntime, UVLoop handled by AbilityRuntime");
888     }
889 
890     return result;
891 }
892 
SetPostTask(NativeEngine * nativeEngine)893 void JsiDeclarativeEngine::SetPostTask(NativeEngine* nativeEngine)
894 {
895     LOGI("SetPostTask");
896     auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate()));
897     auto&& postTask = [weakDelegate, weakEngine = AceType::WeakClaim(this), id = instanceId_](bool needSync) {
898         auto delegate = weakDelegate.Upgrade();
899         if (delegate == nullptr) {
900             LOGE("delegate is nullptr");
901             return;
902         }
903         delegate->PostJsTask([weakEngine, needSync, id]() {
904             auto jsEngine = weakEngine.Upgrade();
905             if (jsEngine == nullptr) {
906                 LOGW("jsEngine is nullptr");
907                 return;
908             }
909             auto nativeEngine = jsEngine->GetNativeEngine();
910             if (nativeEngine == nullptr) {
911                 return;
912             }
913             ContainerScope scope(id);
914             nativeEngine->Loop(LOOP_NOWAIT, needSync);
915         });
916     };
917     nativeEngine_->SetPostTask(postTask);
918 }
919 
RegisterInitWorkerFunc()920 void JsiDeclarativeEngine::RegisterInitWorkerFunc()
921 {
922     auto weakInstance = AceType::WeakClaim(AceType::RawPtr(engineInstance_));
923     bool debugVersion = IsDebugVersion();
924     bool debugMode = NeedDebugBreakPoint();
925     std::string libraryPath = "";
926     if (debugVersion) {
927         libraryPath = ARK_DEBUGGER_LIB_PATH;
928     }
929     auto&& initWorkerFunc = [weakInstance, debugMode, libraryPath](NativeEngine* nativeEngine) {
930         LOGI("WorkerCore RegisterInitWorkerFunc called");
931         if (nativeEngine == nullptr) {
932             LOGE("nativeEngine is nullptr");
933             return;
934         }
935         auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine);
936         if (arkNativeEngine == nullptr) {
937             LOGE("arkNativeEngine is nullptr");
938             return;
939         }
940         auto instance = weakInstance.Upgrade();
941         if (instance == nullptr) {
942             LOGE("instance is nullptr");
943             return;
944         }
945 #ifdef OHOS_PLATFORM
946         ConnectServerManager::Get().AddInstance(gettid());
947         auto vm = const_cast<EcmaVM*>(arkNativeEngine->GetEcmaVm());
948         auto workerPostTask = [nativeEngine](std::function<void()>&& callback) {
949             nativeEngine->CallDebuggerPostTaskFunc(std::move(callback));
950         };
951         panda::JSNApi::StartDebugger(libraryPath.c_str(), vm, debugMode, gettid(), workerPostTask);
952 #endif
953         instance->InitConsoleModule(arkNativeEngine);
954 
955         std::vector<uint8_t> buffer((uint8_t*)_binary_jsEnumStyle_abc_start, (uint8_t*)_binary_jsEnumStyle_abc_end);
956         auto stateMgmtResult = arkNativeEngine->RunBufferScript(buffer);
957         if (stateMgmtResult == nullptr) {
958             LOGE("init worker error");
959         }
960     };
961     nativeEngine_->SetInitWorkerFunc(initWorkerFunc);
962 }
963 
964 #ifdef OHOS_PLATFORM
RegisterOffWorkerFunc()965 void JsiDeclarativeEngine::RegisterOffWorkerFunc()
966 {
967     auto weakInstance = AceType::WeakClaim(AceType::RawPtr(engineInstance_));
968     bool debugVersion = IsDebugVersion();
969     auto&& offWorkerFunc = [debugVersion](NativeEngine* nativeEngine) {
970         LOGI("WorkerCore RegisterOffWorkerFunc called");
971         if (!debugVersion) {
972             return;
973         }
974         if (nativeEngine == nullptr) {
975             LOGE("nativeEngine is nullptr");
976             return;
977         }
978         auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine);
979         if (arkNativeEngine == nullptr) {
980             LOGE("arkNativeEngine is nullptr");
981             return;
982         }
983         ConnectServerManager::Get().RemoveInstance(gettid());
984         auto vm = const_cast<EcmaVM*>(arkNativeEngine->GetEcmaVm());
985         panda::JSNApi::StopDebugger(vm);
986     };
987     nativeEngine_->SetOffWorkerFunc(offWorkerFunc);
988 }
989 #endif
990 
RegisterAssetFunc()991 void JsiDeclarativeEngine::RegisterAssetFunc()
992 {
993     auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate()));
994     auto&& assetFunc = [weakDelegate](const std::string& uri, std::vector<uint8_t>& content, std::string& ami) {
995         LOGI("WorkerCore RegisterAssetFunc called");
996         auto delegate = weakDelegate.Upgrade();
997         if (delegate == nullptr) {
998             LOGE("delegate is nullptr");
999             return;
1000         }
1001         size_t index = uri.find_last_of(".");
1002         if (index == std::string::npos) {
1003             LOGE("invalid uri");
1004         } else {
1005             delegate->GetResourceData(uri.substr(0, index) + ".abc", content, ami);
1006         }
1007     };
1008     nativeEngine_->SetGetAssetFunc(assetFunc);
1009 }
1010 
RegisterWorker()1011 void JsiDeclarativeEngine::RegisterWorker()
1012 {
1013     RegisterInitWorkerFunc();
1014 #ifdef OHOS_PLATFORM
1015     RegisterOffWorkerFunc();
1016 #endif
1017     RegisterAssetFunc();
1018 }
1019 
ExecuteAbc(const std::string & fileName)1020 bool JsiDeclarativeEngine::ExecuteAbc(const std::string& fileName)
1021 {
1022     auto runtime = engineInstance_->GetJsRuntime();
1023     auto delegate = engineInstance_->GetDelegate();
1024     std::vector<uint8_t> content;
1025     if (!delegate->GetAssetContent(fileName, content)) {
1026         LOGD("GetAssetContent \"%{public}s\" failed.", fileName.c_str());
1027         return true;
1028     }
1029 #ifdef OHOS_PLATFORM
1030     const std::string abcPath = delegate->GetAssetPath(fileName).append(fileName);
1031 #else
1032     const std::string& abcPath = fileName;
1033 #endif
1034     if (!runtime->EvaluateJsCode(content.data(), content.size(), abcPath, needUpdate_)) {
1035         LOGE("EvaluateJsCode \"%{public}s\" failed.", fileName.c_str());
1036         return false;
1037     }
1038     return true;
1039 }
1040 
ExecuteCardAbc(const std::string & fileName,int64_t cardId)1041 bool JsiDeclarativeEngine::ExecuteCardAbc(const std::string& fileName, int64_t cardId)
1042 {
1043     auto runtime = engineInstance_->GetJsRuntime();
1044     CHECK_NULL_RETURN(runtime, false);
1045 
1046     auto container = Container::Current();
1047     CHECK_NULL_RETURN(container, false);
1048 
1049     LOGI("JsiDeclarativeEngine::ExecuteCardAbc fileName = %{public}s", fileName.c_str());
1050     CardScope cardScope(cardId);
1051     std::string abcPath;
1052     std::vector<uint8_t> content;
1053     if (container->IsFRSCardContainer()) {
1054         LOGI("ExecuteCardAbc In FRS");
1055         auto frontEnd = AceType::DynamicCast<FormFrontendDeclarative>(container->GetCardFrontend(cardId).Upgrade());
1056         CHECK_NULL_RETURN(frontEnd, false);
1057         auto delegate = frontEnd->GetDelegate();
1058         CHECK_NULL_RETURN(delegate, false);
1059         if (frontEnd->IsBundle()) {
1060             if (!delegate->GetAssetContent(fileName, content)) {
1061                 LOGE("EvaluateJsCode GetAssetContent \"%{public}s\" failed.", fileName.c_str());
1062                 return false;
1063             }
1064             abcPath = delegate->GetAssetPath(fileName).append(fileName);
1065             if (!runtime->EvaluateJsCode(content.data(), content.size(), abcPath)) {
1066                 LOGE("ExecuteCardAbc EvaluateJsCode \"%{public}s\" failed.", fileName.c_str());
1067                 return false;
1068             }
1069             return true;
1070         }
1071         if (!delegate->GetAssetContent(FORM_ES_MODULE_CARD_PATH, content)) {
1072             LOGE("EvaluateJsCode GetAssetContent \"%{public}s\" failed.", FORM_ES_MODULE_CARD_PATH.c_str());
1073             return false;
1074         }
1075         const std::string bundleName = frontEnd->GetBundleName();
1076         std::string moduleName = frontEnd->GetModuleName();
1077 #ifdef PREVIEW
1078         const std::string assetPath = delegate->GetAssetPath(FORM_ES_MODULE_CARD_PATH).append(FORM_ES_MODULE_CARD_PATH);
1079 #else
1080         const std::string assetPath =
1081             ASSET_PATH_PREFIX + bundleName + "/" + moduleName + "/" + FORM_ES_MODULE_CARD_PATH;
1082 #endif
1083         LOGI("bundleName = %{public}s, moduleName = %{public}s, assetPath = %{public}s", bundleName.c_str(),
1084             moduleName.c_str(), assetPath.c_str());
1085         auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1086         CHECK_NULL_RETURN(arkRuntime, false);
1087         arkRuntime->SetBundleName(bundleName);
1088         arkRuntime->SetAssetPath(assetPath);
1089         arkRuntime->SetBundle(false);
1090         arkRuntime->SetModuleName(moduleName);
1091 #ifdef PREVIEW
1092         // remove the prefix of "ets/"
1093         abcPath = fileName.substr(PREFIX_LETTER_NUMBER);
1094 #else
1095         abcPath = moduleName.append("/").append(fileName);
1096 #endif
1097         LOGI("JsiDeclarativeEngine::ExecuteCardAbc abcPath = %{public}s", abcPath.c_str());
1098         {
1099             std::lock_guard<std::mutex> lock(loadFormMutex_);
1100             if (!arkRuntime->ExecuteModuleBuffer(content.data(), content.size(), abcPath, true)) {
1101                 LOGE("ExecuteCardAbc ExecuteModuleBuffer \"%{public}s\" failed.", fileName.c_str());
1102                 return false;
1103             }
1104         }
1105         return true;
1106     } else {
1107         LOGI("ExecuteCardAbc In HOST");
1108         auto frontEnd = AceType::DynamicCast<CardFrontendDeclarative>(container->GetCardFrontend(cardId).Upgrade());
1109         CHECK_NULL_RETURN(frontEnd, false);
1110         auto delegate = frontEnd->GetDelegate();
1111         CHECK_NULL_RETURN(delegate, false);
1112         if (!delegate->GetAssetContent(fileName, content)) {
1113             LOGE("EvaluateJsCode GetAssetContent \"%{public}s\" failed.", fileName.c_str());
1114             return false;
1115         }
1116         abcPath = delegate->GetAssetPath(fileName).append(fileName);
1117     }
1118 
1119     LOGI("JsiDeclarativeEngine::ExecuteCardAbc abcPath = %{public}s", abcPath.c_str());
1120     if (!runtime->EvaluateJsCode(content.data(), content.size(), abcPath)) {
1121         LOGE("ExecuteCardAbc EvaluateJsCode \"%{public}s\" failed.", fileName.c_str());
1122         return false;
1123     }
1124     return true;
1125 }
1126 
LoadJs(const std::string & url,const RefPtr<JsAcePage> & page,bool isMainPage)1127 void JsiDeclarativeEngine::LoadJs(const std::string& url, const RefPtr<JsAcePage>& page, bool isMainPage)
1128 {
1129     ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadJs");
1130     LOGI("JsiDeclarativeEngine LoadJs page:%{public}d", page->GetPageId());
1131     ACE_DCHECK(engineInstance_);
1132     engineInstance_->SetStagingPage(page);
1133     if (isMainPage) {
1134         ACE_DCHECK(!engineInstance_->GetRunningPage());
1135         engineInstance_->SetRunningPage(page);
1136     }
1137     auto runtime = engineInstance_->GetJsRuntime();
1138     auto delegate = engineInstance_->GetDelegate();
1139     auto vm = const_cast<EcmaVM*>(std::static_pointer_cast<ArkJSRuntime>(runtime)->GetEcmaVm());
1140     // get source map
1141     std::string jsSourceMap;
1142     if (JSNApi::IsBundle(vm)) {
1143         if (delegate->GetAssetContent(url + ".map", jsSourceMap)) {
1144             page->SetPageMap(jsSourceMap);
1145         } else {
1146             LOGW("js source map load failed!");
1147         }
1148     }
1149     // get js bundle content
1150     shared_ptr<JsValue> jsCode = runtime->NewUndefined();
1151     shared_ptr<JsValue> jsAppCode = runtime->NewUndefined();
1152     const char js_ext[] = ".js";
1153     const char bin_ext[] = ".abc";
1154     auto pos = url.rfind(js_ext);
1155     if (pos != std::string::npos && pos == url.length() - (sizeof(js_ext) - 1)) {
1156         std::string urlName = url.substr(0, pos) + bin_ext;
1157         if (isMainPage) {
1158 #if !defined(PREVIEW)
1159             if (LoadJsWithModule(urlName)) {
1160                 return;
1161             }
1162 #endif
1163             if (!ExecuteAbc("commons.abc")) {
1164                 return;
1165             }
1166             if (!ExecuteAbc("vendors.abc")) {
1167                 return;
1168             }
1169             std::string appMap;
1170             if (delegate->GetAssetContent("app.js.map", appMap)) {
1171                 page->SetAppMap(appMap);
1172             } else {
1173                 LOGW("app map load failed!");
1174             }
1175             if (!ExecuteAbc("app.abc")) {
1176                 LOGW("ExecuteJsBin \"app.js\" failed.");
1177             } else {
1178                 CallAppFunc("onCreate");
1179             }
1180         }
1181 #if !defined(PREVIEW)
1182         if (LoadJsWithModule(urlName)) {
1183             return;
1184         }
1185         if (!ExecuteAbc(urlName)) {
1186             return;
1187         }
1188 #else
1189         if (!assetPath_.empty() && !isBundle_) {
1190             auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1191             arkRuntime->SetBundleName(bundleName_);
1192             arkRuntime->SetAssetPath(assetPath_);
1193             arkRuntime->SetBundle(isBundle_);
1194             arkRuntime->SetModuleName(moduleName_);
1195             std::vector<uint8_t> content;
1196             if (!delegate->GetAssetContent("modules.abc", content)) {
1197                 LOGE("GetAssetContent \"%{public}s\" failed.", urlName.c_str());
1198                 return;
1199             }
1200             if (!arkRuntime->ExecuteModuleBuffer(content.data(), content.size(), urlName)) {
1201                 LOGE("EvaluateJsCode \"%{public}s\" failed.", urlName.c_str());
1202                 return;
1203             }
1204         } else {
1205             ExecuteAbc(urlName);
1206         }
1207 #endif
1208     }
1209 }
1210 
LoadJsWithModule(std::string & urlName,const std::function<void (const std::string &,int32_t)> & errorCallback)1211 bool JsiDeclarativeEngine::LoadJsWithModule(std::string& urlName,
1212     const std::function<void(const std::string&, int32_t)>& errorCallback)
1213 {
1214     auto container = Container::Current();
1215     CHECK_NULL_RETURN(container, false);
1216     if (container->IsModule()) {
1217         const std::string assetPath = ASSET_PATH_PREFIX +
1218             container->GetModuleName() + "/" + FORM_ES_MODULE_PATH;
1219         auto runtime = std::static_pointer_cast<ArkJSRuntime>(engineInstance_->GetJsRuntime());
1220         runtime->SetAssetPath(assetPath);
1221         urlName = container->GetModuleName() + "/ets/" + urlName;
1222         if (!runtime->ExecuteJsBin(urlName, errorCallback)) {
1223             LOGE("ExecuteJsBin %{private}s failed.", urlName.c_str());
1224         }
1225         return true;
1226     }
1227     return false;
1228 }
1229 
1230 // Load the app.js file of the FA model in NG structure.
LoadFaAppSource()1231 bool JsiDeclarativeEngine::LoadFaAppSource()
1232 {
1233     ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadFaAppSource");
1234     if (!ExecuteAbc("commons.abc")) {
1235         return false;
1236     }
1237     if (!ExecuteAbc("vendors.abc")) {
1238         return false;
1239     }
1240     if (!ExecuteAbc("app.abc")) {
1241         LOGW("ExecuteJsBin \"app.js\" failed.");
1242         return false;
1243     }
1244     CallAppFunc("onCreate");
1245     return true;
1246 }
1247 
1248 // Load the js file of the page in NG structure..
LoadPageSource(const std::string & url,const std::function<void (const std::string &,int32_t)> & errorCallback)1249 bool JsiDeclarativeEngine::LoadPageSource(const std::string& url,
1250     const std::function<void(const std::string&, int32_t)>& errorCallback)
1251 {
1252     ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadPageSource");
1253     LOGI("JsiDeclarativeEngine LoadJs %{private}s page", url.c_str());
1254     ACE_DCHECK(engineInstance_);
1255     // get js bundle content
1256     const char jsExt[] = ".js";
1257     const char binExt[] = ".abc";
1258     std::optional<std::string> urlName;
1259     auto pos = url.rfind(jsExt);
1260     if (pos != std::string::npos && pos == url.length() - (sizeof(jsExt) - 1)) {
1261         urlName = url.substr(0, pos) + binExt;
1262     }
1263     if (!urlName.has_value()) {
1264         LOGE("fail to find abc file");
1265         return false;
1266     }
1267 
1268 #if !defined(PREVIEW)
1269     if (LoadJsWithModule(urlName.value(), errorCallback)) {
1270         return true;
1271     }
1272 #else
1273     auto runtime = engineInstance_->GetJsRuntime();
1274     auto delegate = engineInstance_->GetDelegate();
1275     if (!assetPath_.empty() && !isBundle_) {
1276         auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1277         arkRuntime->SetBundleName(bundleName_);
1278         arkRuntime->SetAssetPath(assetPath_);
1279         arkRuntime->SetBundle(isBundle_);
1280         arkRuntime->SetModuleName(moduleName_);
1281         std::vector<uint8_t> content;
1282         if (!delegate->GetAssetContent("modules.abc", content)) {
1283             LOGE("GetAssetContent \"%{public}s\" failed.", urlName.value().c_str());
1284             return false;
1285         }
1286         if (!arkRuntime->ExecuteModuleBuffer(content.data(), content.size(), urlName.value())) {
1287             LOGE("EvaluateJsCode \"%{public}s\" failed.", urlName.value().c_str());
1288             return false;
1289         }
1290         return true;
1291     }
1292 #endif
1293     return ExecuteAbc(urlName.value());
1294 }
1295 
LoadCard(const std::string & url,int64_t cardId)1296 bool JsiDeclarativeEngine::LoadCard(const std::string& url, int64_t cardId)
1297 {
1298     ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadCard");
1299     return ExecuteCardAbc(url, cardId);
1300 }
1301 
1302 #if defined(PREVIEW)
ReplaceJSContent(const std::string & url,const std::string componentName)1303 void JsiDeclarativeEngine::ReplaceJSContent(const std::string& url, const std::string componentName)
1304 {
1305     ACE_DCHECK(engineInstance_);
1306     if (engineInstance_ == nullptr) {
1307         LOGE("engineInstance is nullptr");
1308         return;
1309     }
1310     auto runtime = engineInstance_->GetJsRuntime();
1311     std::static_pointer_cast<ArkJSRuntime>(runtime)->SetPreviewFlag(true);
1312     std::static_pointer_cast<ArkJSRuntime>(runtime)->SetRequiredComponent(componentName);
1313     engineInstance_->GetDelegate()->Replace(url, "");
1314 }
1315 
GetNewComponentWithJsCode(const std::string & jsCode,const std::string & viewID)1316 RefPtr<Component> JsiDeclarativeEngine::GetNewComponentWithJsCode(const std::string& jsCode, const std::string& viewID)
1317 {
1318     std::string dest;
1319     if (!Base64Util::Decode(jsCode, dest)) {
1320         return nullptr;
1321     }
1322 
1323     ViewStackProcessor::GetInstance()->ClearStack();
1324     ViewStackProcessor::GetInstance()->PushKey(viewID);
1325     bool result = engineInstance_->InitAceModule((uint8_t*)dest.data(), dest.size());
1326     ViewStackProcessor::GetInstance()->PopKey();
1327     if (!result) {
1328         return nullptr;
1329     }
1330     auto component = ViewStackProcessor::GetInstance()->GetNewComponent();
1331     return component;
1332 }
1333 
ExecuteJsForFastPreview(const std::string & jsCode,const std::string & viewID)1334 bool JsiDeclarativeEngine::ExecuteJsForFastPreview(const std::string& jsCode, const std::string& viewID)
1335 {
1336     std::string dest;
1337     if (!Base64Util::Decode(jsCode, dest)) {
1338         return false;
1339     }
1340     NG::ViewStackProcessor::GetInstance()->ClearStack();
1341     NG::ViewStackProcessor::GetInstance()->PushKey(viewID);
1342     bool result = engineInstance_->InitAceModule((uint8_t*)dest.data(), dest.size());
1343     NG::ViewStackProcessor::GetInstance()->PopKey();
1344     return result;
1345 }
1346 
1347 #endif
1348 
UpdateRunningPage(const RefPtr<JsAcePage> & page)1349 void JsiDeclarativeEngine::UpdateRunningPage(const RefPtr<JsAcePage>& page)
1350 {
1351     LOGD("JsiDeclarativeEngine UpdateRunningPage");
1352     ACE_DCHECK(engineInstance_);
1353     engineInstance_->SetRunningPage(page);
1354 }
1355 
UpdateStagingPage(const RefPtr<JsAcePage> & page)1356 void JsiDeclarativeEngine::UpdateStagingPage(const RefPtr<JsAcePage>& page)
1357 {
1358     LOGI("JsiDeclarativeEngine UpdateStagingPage %{public}d", page->GetPageId());
1359     ACE_DCHECK(engineInstance_);
1360     engineInstance_->SetStagingPage(page);
1361 }
1362 
ResetStagingPage()1363 void JsiDeclarativeEngine::ResetStagingPage()
1364 {
1365     LOGD("JsiDeclarativeEngine ResetStagingPage");
1366     ACE_DCHECK(engineInstance_);
1367     auto runningPage = engineInstance_->GetRunningPage();
1368     engineInstance_->ResetStagingPage(runningPage);
1369 }
1370 
SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher> & dispatcher)1371 void JsiDeclarativeEngine::SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher>& dispatcher)
1372 {
1373     LOGD("JsiDeclarativeEngine SetJsMessageDispatcher");
1374     ACE_DCHECK(engineInstance_);
1375     engineInstance_->SetJsMessageDispatcher(dispatcher);
1376 }
1377 
FireAsyncEvent(const std::string & eventId,const std::string & param)1378 void JsiDeclarativeEngine::FireAsyncEvent(const std::string& eventId, const std::string& param)
1379 {
1380     LOGD("JsiDeclarativeEngine FireAsyncEvent");
1381     std::string callBuf = std::string("[{\"args\": [\"")
1382                               .append(eventId)
1383                               .append("\",")
1384                               .append(param)
1385                               .append("], \"method\":\"fireEvent\"}]");
1386     LOGD("FireASyncEvent string: %{private}s", callBuf.c_str());
1387 
1388     ACE_DCHECK(engineInstance_);
1389     if (!engineInstance_->FireJsEvent(callBuf.c_str())) {
1390         LOGE("Js Engine FireSyncEvent FAILED!");
1391     }
1392 }
1393 
FireSyncEvent(const std::string & eventId,const std::string & param)1394 void JsiDeclarativeEngine::FireSyncEvent(const std::string& eventId, const std::string& param)
1395 {
1396     LOGD("JsiDeclarativeEngine FireSyncEvent");
1397     std::string callBuf = std::string("[{\"args\": [\"")
1398                               .append(eventId)
1399                               .append("\",")
1400                               .append(param)
1401                               .append("], \"method\":\"fireEventSync\"}]");
1402     LOGD("FireSyncEvent string: %{private}s", callBuf.c_str());
1403 
1404     ACE_DCHECK(engineInstance_);
1405     if (!engineInstance_->FireJsEvent(callBuf.c_str())) {
1406         LOGE("Js Engine FireSyncEvent FAILED!");
1407     }
1408 }
1409 
InitXComponent(const std::string & componentId)1410 void JsiDeclarativeEngine::InitXComponent(const std::string& componentId)
1411 {
1412     ACE_DCHECK(engineInstance_);
1413     std::tie(nativeXComponentImpl_, nativeXComponent_) =
1414         XComponentClient::GetInstance().GetNativeXComponentFromXcomponentsMap(componentId);
1415 }
1416 
FireExternalEvent(const std::string & componentId,const uint32_t nodeId,const bool isDestroy)1417 void JsiDeclarativeEngine::FireExternalEvent(
1418     const std::string& componentId, const uint32_t nodeId, const bool isDestroy)
1419 {
1420     CHECK_RUN_ON(JS);
1421     if (Container::IsCurrentUseNewPipeline()) {
1422         ACE_DCHECK(engineInstance_);
1423         auto xcFrameNode = NG::FrameNode::GetFrameNode(V2::XCOMPONENT_ETS_TAG, static_cast<int32_t>(nodeId));
1424         if (!xcFrameNode) {
1425             LOGE("FireExternalEvent xcFrameNode is null.");
1426             return;
1427         }
1428         auto xcPattern = DynamicCast<NG::XComponentPattern>(xcFrameNode->GetPattern());
1429         CHECK_NULL_VOID(xcPattern);
1430 
1431         void* nativeWindow = nullptr;
1432 
1433         nativeWindow = xcPattern->GetNativeWindow();
1434 
1435         std::weak_ptr<OH_NativeXComponent> weakNativeXComponent;
1436         RefPtr<OHOS::Ace::NativeXComponentImpl> nativeXComponentImpl = nullptr;
1437 
1438         std::tie(nativeXComponentImpl, weakNativeXComponent) = xcPattern->GetNativeXComponent();
1439         auto nativeXComponent = weakNativeXComponent.lock();
1440         CHECK_NULL_VOID(nativeXComponent);
1441         CHECK_NULL_VOID(nativeXComponentImpl);
1442 
1443         if (!nativeWindow) {
1444             LOGE("FireExternalEvent nativeWindow invalid");
1445             return;
1446         }
1447         nativeXComponentImpl->SetSurface(nativeWindow);
1448         nativeXComponentImpl->SetXComponentId(componentId);
1449 
1450         auto* arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine_);
1451         if (arkNativeEngine == nullptr) {
1452             LOGE("FireExternalEvent arkNativeEngine is nullptr");
1453             return;
1454         }
1455 
1456         std::string arguments;
1457         auto soPath = xcPattern->GetSoPath().value_or("");
1458         auto runtime = engineInstance_->GetJsRuntime();
1459         shared_ptr<ArkJSRuntime> pandaRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1460         LocalScope scope(pandaRuntime->GetEcmaVm());
1461         auto objXComp = arkNativeEngine->LoadModuleByName(xcPattern->GetLibraryName(), true, arguments,
1462             OH_NATIVE_XCOMPONENT_OBJ, reinterpret_cast<void*>(nativeXComponent.get()), soPath);
1463         if (objXComp.IsEmpty() || pandaRuntime->HasPendingException()) {
1464             LOGE("LoadModuleByName failed.");
1465             return;
1466         }
1467 
1468         renderContext_ = runtime->NewObject();
1469         auto renderContext = std::static_pointer_cast<ArkJSValue>(renderContext_);
1470         renderContext->SetValue(pandaRuntime, objXComp);
1471 
1472         auto objContext = JsiObject(objXComp);
1473         JSRef<JSObject> obj = JSRef<JSObject>::Make(objContext);
1474         OHOS::Ace::Framework::XComponentClient::GetInstance().AddJsValToJsValMap(componentId, obj);
1475 
1476         auto task = [weak = WeakClaim(this), weakPattern = AceType::WeakClaim(AceType::RawPtr(xcPattern))]() {
1477             auto pattern = weakPattern.Upgrade();
1478             if (!pattern) {
1479                 return;
1480             }
1481             auto bridge = weak.Upgrade();
1482             if (bridge) {
1483 #ifdef XCOMPONENT_SUPPORTED
1484                 pattern->NativeXComponentInit();
1485 #endif
1486             }
1487         };
1488 
1489         auto delegate = engineInstance_->GetDelegate();
1490         if (!delegate) {
1491             LOGE("Delegate is null");
1492             return;
1493         }
1494         delegate->PostSyncTaskToPage(task);
1495         return;
1496     }
1497     if (isDestroy) {
1498         XComponentComponentClient::GetInstance().DeleteFromXcomponentsMapById(componentId);
1499         XComponentClient::GetInstance().DeleteControllerFromJSXComponentControllersMap(componentId);
1500         XComponentClient::GetInstance().DeleteFromNativeXcomponentsMapById(componentId);
1501         XComponentClient::GetInstance().DeleteFromJsValMapById(componentId);
1502         return;
1503     }
1504     InitXComponent(componentId);
1505     RefPtr<XComponentComponent> xcomponent =
1506         XComponentComponentClient::GetInstance().GetXComponentFromXcomponentsMap(componentId);
1507     if (!xcomponent) {
1508         LOGE("FireExternalEvent xcomponent is null.");
1509         return;
1510     }
1511 
1512     void* nativeWindow = nullptr;
1513 #ifdef OHOS_STANDARD_SYSTEM
1514     nativeWindow = const_cast<void*>(xcomponent->GetNativeWindow());
1515 #else
1516     auto container = Container::Current();
1517     if (!container) {
1518         LOGE("FireExternalEvent Current container null");
1519         return;
1520     }
1521     auto nativeView = static_cast<AceView*>(container->GetView());
1522     if (!nativeView) {
1523         LOGE("FireExternalEvent nativeView null");
1524         return;
1525     }
1526     auto textureId = static_cast<int64_t>(xcomponent->GetTextureId());
1527     nativeWindow = const_cast<void*>(nativeView->GetNativeWindowById(textureId));
1528 #endif
1529 
1530     if (!nativeWindow) {
1531         LOGE("FireExternalEvent nativeWindow invalid");
1532         return;
1533     }
1534     nativeXComponentImpl_->SetSurface(nativeWindow);
1535     nativeXComponentImpl_->SetXComponentId(xcomponent->GetId());
1536 
1537     auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine_);
1538     if (arkNativeEngine == nullptr) {
1539         LOGE("FireExternalEvent arkNativeEngine is nullptr");
1540         return;
1541     }
1542 
1543     std::string arguments;
1544     auto soPath = xcomponent->GetSoPath().value_or("");
1545     auto runtime = engineInstance_->GetJsRuntime();
1546     shared_ptr<ArkJSRuntime> pandaRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1547     LocalScope scope(pandaRuntime->GetEcmaVm());
1548     auto objXComp = arkNativeEngine->LoadModuleByName(xcomponent->GetLibraryName(), true, arguments,
1549         OH_NATIVE_XCOMPONENT_OBJ, reinterpret_cast<void*>(nativeXComponent_), soPath);
1550     if (objXComp.IsEmpty() || pandaRuntime->HasPendingException()) {
1551         LOGE("LoadModuleByName failed.");
1552         return;
1553     }
1554 
1555     renderContext_ = runtime->NewObject();
1556     auto renderContext = std::static_pointer_cast<ArkJSValue>(renderContext_);
1557     renderContext->SetValue(pandaRuntime, objXComp);
1558 
1559     auto objContext = JsiObject(objXComp);
1560     JSRef<JSObject> obj = JSRef<JSObject>::Make(objContext);
1561     XComponentClient::GetInstance().AddJsValToJsValMap(componentId, obj);
1562 
1563     auto task = [weak = WeakClaim(this), xcomponent]() {
1564         auto pool = xcomponent->GetTaskPool();
1565         if (!pool) {
1566             return;
1567         }
1568         auto bridge = weak.Upgrade();
1569         if (bridge) {
1570 #ifdef XCOMPONENT_SUPPORTED
1571             pool->NativeXComponentInit(
1572                 bridge->nativeXComponent_, AceType::WeakClaim(AceType::RawPtr(bridge->nativeXComponentImpl_)));
1573 #endif
1574         }
1575     };
1576 
1577     auto delegate = engineInstance_->GetDelegate();
1578     if (!delegate) {
1579         LOGE("Delegate is null");
1580         return;
1581     }
1582     delegate->PostSyncTaskToPage(task);
1583 }
1584 
TimerCallback(const std::string & callbackId,const std::string & delay,bool isInterval)1585 void JsiDeclarativeEngine::TimerCallback(const std::string& callbackId, const std::string& delay, bool isInterval)
1586 {
1587     TimerCallJs(callbackId);
1588     auto runtime = JsiDeclarativeEngineInstance::GetCurrentRuntime();
1589     if (!runtime) {
1590         LOGE("get runtime failed");
1591         return;
1592     }
1593     auto instance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData());
1594     if (instance == nullptr) {
1595         LOGE("get jsi engine instance failed");
1596         return;
1597     }
1598     auto delegate = instance->GetDelegate();
1599     if (!delegate) {
1600         LOGE("get frontend delegate failed");
1601         return;
1602     }
1603 
1604     if (isInterval) {
1605         delegate->WaitTimer(callbackId, delay, isInterval, false);
1606     } else {
1607         JsiTimerModule::GetInstance()->RemoveCallBack(std::stoi(callbackId));
1608         delegate->ClearTimer(callbackId);
1609     }
1610 }
1611 
TimerCallJs(const std::string & callbackId) const1612 void JsiDeclarativeEngine::TimerCallJs(const std::string& callbackId) const
1613 {
1614     shared_ptr<JsValue> func;
1615     std::vector<shared_ptr<JsValue>> params;
1616     if (!JsiTimerModule::GetInstance()->GetCallBack(std::stoi(callbackId), func, params)) {
1617         LOGE("get callback failed");
1618         return;
1619     }
1620     auto runtime = JsiDeclarativeEngineInstance::GetCurrentRuntime();
1621     if (func) {
1622         func->Call(runtime, runtime->GetGlobal(), params, params.size());
1623     }
1624 }
1625 
DestroyPageInstance(int32_t pageId)1626 void JsiDeclarativeEngine::DestroyPageInstance(int32_t pageId)
1627 {
1628     LOGI("JsiDeclarativeEngine DestroyPageInstance %{public}d", pageId);
1629     ACE_DCHECK(engineInstance_);
1630 
1631     engineInstance_->DestroyRootViewHandle(pageId);
1632 }
1633 
DestroyApplication(const std::string & packageName)1634 void JsiDeclarativeEngine::DestroyApplication(const std::string& packageName)
1635 {
1636     LOGI("JsiDeclarativeEngine DestroyApplication, packageName %{public}s", packageName.c_str());
1637     if (engineInstance_) {
1638         shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1639         CallAppFunc("onDestroy");
1640     }
1641 }
1642 
UpdateApplicationState(const std::string & packageName,Frontend::State state)1643 void JsiDeclarativeEngine::UpdateApplicationState(const std::string& packageName, Frontend::State state)
1644 {
1645     LOGI("JsiDeclarativeEngine UpdateApplicationState, packageName %{public}s, state: %{public}d", packageName.c_str(),
1646         static_cast<int32_t>(state));
1647     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1648     if (!runtime) {
1649         LOGE("update app state failed, runtime is null.");
1650         return;
1651     }
1652     switch (state) {
1653         case Frontend::State::ON_SHOW:
1654             CallAppFunc("onShow");
1655             break;
1656         case Frontend::State::ON_HIDE:
1657             CallAppFunc("onHide");
1658             break;
1659         case Frontend::State::ON_ACTIVE:
1660             CallAppFunc("onActive");
1661             break;
1662         case Frontend::State::ON_INACTIVE:
1663             CallAppFunc("onInactive");
1664             break;
1665         case Frontend::State::ON_DESTROY:
1666             CallAppFunc("onDestroy");
1667             break;
1668         default:
1669             LOGW("unsupported state: %{public}d", state);
1670             return;
1671     }
1672 }
1673 
OnWindowDisplayModeChanged(bool isShownInMultiWindow,const std::string & data)1674 void JsiDeclarativeEngine::OnWindowDisplayModeChanged(bool isShownInMultiWindow, const std::string& data)
1675 {
1676     LOGI("JsiDeclarativeEngine OnWindowDisplayModeChanged");
1677     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1678     std::vector<shared_ptr<JsValue>> argv = { runtime->NewBoolean(isShownInMultiWindow), runtime->NewString(data) };
1679     CallAppFunc("onWindowDisplayModeChanged", argv);
1680 }
1681 
CallAppFunc(const std::string & appFuncName)1682 bool JsiDeclarativeEngine::CallAppFunc(const std::string& appFuncName)
1683 {
1684     std::vector<shared_ptr<JsValue>> argv = {};
1685     return CallAppFunc(appFuncName, argv);
1686 }
1687 
CallAppFunc(const std::string & appFuncName,std::vector<shared_ptr<JsValue>> & argv)1688 bool JsiDeclarativeEngine::CallAppFunc(const std::string& appFuncName, std::vector<shared_ptr<JsValue>>& argv)
1689 {
1690     LOGD("JsiDeclarativeEngine CallAppFunc");
1691     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1692     ACE_DCHECK(runtime);
1693     shared_ptr<JsValue> global = runtime->GetGlobal();
1694     shared_ptr<JsValue> exportsObject = global->GetProperty(runtime, "exports");
1695     if (!exportsObject->IsObject(runtime)) {
1696         LOGE("property \"exports\" is not a object");
1697         return false;
1698     }
1699     shared_ptr<JsValue> defaultObject = exportsObject->GetProperty(runtime, "default");
1700     if (!defaultObject->IsObject(runtime)) {
1701         LOGE("property \"default\" is not a object");
1702         return false;
1703     }
1704     shared_ptr<JsValue> func = defaultObject->GetProperty(runtime, appFuncName);
1705     if (!func || !func->IsFunction(runtime)) {
1706         return false;
1707     }
1708     shared_ptr<JsValue> result;
1709     result = func->Call(runtime, defaultObject, argv, argv.size());
1710     return (result->ToString(runtime) == "true");
1711 }
1712 
MediaQueryCallback(const std::string & callbackId,const std::string & args)1713 void JsiDeclarativeEngine::MediaQueryCallback(const std::string& callbackId, const std::string& args)
1714 {
1715     JsEngine::MediaQueryCallback(callbackId, args);
1716 }
1717 
RequestAnimationCallback(const std::string & callbackId,uint64_t timeStamp)1718 void JsiDeclarativeEngine::RequestAnimationCallback(const std::string& callbackId, uint64_t timeStamp) {}
1719 
JsCallback(const std::string & callbackId,const std::string & args)1720 void JsiDeclarativeEngine::JsCallback(const std::string& callbackId, const std::string& args) {}
1721 
RunGarbageCollection()1722 void JsiDeclarativeEngine::RunGarbageCollection()
1723 {
1724     if (engineInstance_ && engineInstance_->GetJsRuntime()) {
1725         engineInstance_->GetJsRuntime()->RunGC();
1726     }
1727 }
1728 
RunFullGarbageCollection()1729 void JsiDeclarativeEngine::RunFullGarbageCollection()
1730 {
1731     if (engineInstance_ && engineInstance_->GetJsRuntime()) {
1732         engineInstance_->GetJsRuntime()->RunFullGC();
1733     }
1734 }
1735 
DumpHeapSnapshot(bool isPrivate)1736 void JsiDeclarativeEngine::DumpHeapSnapshot(bool isPrivate)
1737 {
1738     if (engineInstance_ && engineInstance_->GetJsRuntime()) {
1739         engineInstance_->GetJsRuntime()->DumpHeapSnapshot(isPrivate);
1740     }
1741 }
1742 
GetStacktraceMessage()1743 std::string JsiDeclarativeEngine::GetStacktraceMessage()
1744 {
1745     auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine_);
1746     if (!arkNativeEngine) {
1747         LOGE("GetStacktraceMessage arkNativeEngine is nullptr");
1748         return "";
1749     }
1750     std::string stack;
1751     arkNativeEngine->SuspendVM();
1752     bool getStackSuccess = arkNativeEngine->BuildJsStackTrace(stack);
1753     arkNativeEngine->ResumeVM();
1754     if (!getStackSuccess) {
1755         LOGE("GetStacktraceMessage arkNativeEngine get stack failed");
1756         return "JS stacktrace is empty";
1757     }
1758 
1759     auto runningPage = engineInstance_ ? engineInstance_->GetRunningPage() : nullptr;
1760     return JsiBaseUtils::TransSourceStack(runningPage, stack);
1761 }
1762 
SetLocalStorage(int32_t instanceId,NativeReference * nativeValue)1763 void JsiDeclarativeEngine::SetLocalStorage(int32_t instanceId, NativeReference* nativeValue)
1764 {
1765     LOGI("SetLocalStorage instanceId:%{public}d", instanceId);
1766 #ifdef USE_ARK_ENGINE
1767     auto jsValue = JsConverter::ConvertNativeValueToJsVal(*nativeValue);
1768     if (jsValue->IsObject()) {
1769         auto storage = JSRef<JSObject>::Cast(jsValue);
1770         JSLocalStorage::AddStorage(instanceId, storage);
1771     } else {
1772         LOGI("SetLocalStorage instanceId:%{public}d invalid storage", instanceId);
1773         delete nativeValue;
1774         nativeValue = nullptr;
1775     }
1776 #endif
1777 }
1778 
SetContext(int32_t instanceId,NativeReference * nativeValue)1779 void JsiDeclarativeEngine::SetContext(int32_t instanceId, NativeReference* nativeValue)
1780 {
1781     LOGI("SetContext instanceId:%{public}d", instanceId);
1782 #ifdef USE_ARK_ENGINE
1783     NativeScopeManager* scopeManager = nativeEngine_->GetScopeManager();
1784     auto nativeScope = scopeManager->Open();
1785     NativeValue* value = *nativeValue;
1786     Global<JSValueRef> globalRef = *value;
1787     auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(JsiDeclarativeEngineInstance::GetCurrentRuntime());
1788     if (!arkRuntime || !arkRuntime->GetEcmaVm()) {
1789         LOGE("SetContext null ark runtime");
1790         return;
1791     }
1792     JAVASCRIPT_EXECUTION_SCOPE_STATIC;
1793     auto localRef = globalRef.ToLocal(arkRuntime->GetEcmaVm());
1794     std::shared_ptr<JsValue> jsValue = std::make_shared<ArkJSValue>(arkRuntime, localRef);
1795     if (jsValue->IsObject(arkRuntime)) {
1796         JsiContextModule::AddContext(instanceId_, jsValue);
1797     } else {
1798         LOGI("SetContext instanceId:%{public}d invalid context", instanceId);
1799     }
1800     scopeManager->Close(nativeScope);
1801 #endif
1802 }
1803 
GetGroupJsBridge()1804 RefPtr<GroupJsBridge> JsiDeclarativeEngine::GetGroupJsBridge()
1805 {
1806     return AceType::MakeRefPtr<JsiDeclarativeGroupJsBridge>();
1807 }
1808 
OnActive()1809 void JsiDeclarativeEngine::OnActive()
1810 {
1811     LOGI("JsiDeclarativeEngine onActive called.");
1812     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1813     if (!runtime) {
1814         LOGE("onActive failed, runtime is null.");
1815         return;
1816     }
1817     CallAppFunc("onActive");
1818 }
1819 
OnInactive()1820 void JsiDeclarativeEngine::OnInactive()
1821 {
1822     LOGI("JsiDeclarativeEngine OnInactive called.");
1823     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1824     if (!runtime) {
1825         LOGE("OnInactive failed, runtime is null.");
1826         return;
1827     }
1828     CallAppFunc("onInactive");
1829 }
1830 
OnNewWant(const std::string & data)1831 void JsiDeclarativeEngine::OnNewWant(const std::string& data)
1832 {
1833     LOGI("JsiDeclarativeEngine OnNewWant called.");
1834     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1835     if (!runtime) {
1836         LOGE("OnNewWant failed, runtime is null.");
1837         return;
1838     }
1839 
1840     shared_ptr<JsValue> object = runtime->ParseJson(data);
1841     std::vector<shared_ptr<JsValue>> argv = { object };
1842     CallAppFunc("onNewWant", argv);
1843 }
1844 
OnStartContinuation()1845 bool JsiDeclarativeEngine::OnStartContinuation()
1846 {
1847     LOGI("JsiDeclarativeEngine OnStartContinuation");
1848     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1849     if (!runtime) {
1850         LOGE("OnStartContinuation failed, runtime is null.");
1851         return false;
1852     }
1853 
1854     return CallAppFunc("onStartContinuation");
1855 }
1856 
OnCompleteContinuation(int32_t code)1857 void JsiDeclarativeEngine::OnCompleteContinuation(int32_t code)
1858 {
1859     LOGI("JsiDeclarativeEngine OnCompleteContinuation");
1860     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1861     if (!runtime) {
1862         LOGE("OnCompleteContinuation failed, runtime is null.");
1863         return;
1864     }
1865 
1866     std::vector<shared_ptr<JsValue>> argv = { runtime->NewNumber(code) };
1867     CallAppFunc("onCompleteContinuation", argv);
1868 }
1869 
ClearCache()1870 void JsiDeclarativeEngine::ClearCache()
1871 {
1872     JSNApi::CleanJSVMCache();
1873 }
1874 
OnRemoteTerminated()1875 void JsiDeclarativeEngine::OnRemoteTerminated()
1876 {
1877     LOGI("JsiDeclarativeEngine OnRemoteTerminated");
1878     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1879     if (!runtime) {
1880         LOGE("OnRemoteTerminated failed, runtime is null.");
1881         return;
1882     }
1883 
1884     CallAppFunc("onRemoteTerminated");
1885 }
1886 
OnSaveData(std::string & data)1887 void JsiDeclarativeEngine::OnSaveData(std::string& data)
1888 {
1889     LOGI("JsiDeclarativeEngine OnSaveData");
1890     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1891     if (!runtime) {
1892         LOGE("OnSaveData failed, runtime is null.");
1893         return;
1894     }
1895 
1896     shared_ptr<JsValue> object = runtime->NewObject();
1897     std::vector<shared_ptr<JsValue>> argv = { object };
1898     if (CallAppFunc("onSaveData", argv)) {
1899         data = object->GetJsonString(runtime);
1900     }
1901 }
1902 
SetErrorEventHandler(std::function<void (const std::string &,const std::string &)> && errorCallback)1903 void JsiDeclarativeEngine::SetErrorEventHandler(
1904     std::function<void(const std::string&, const std::string&)>&& errorCallback)
1905 {
1906     LOGI("JsiDeclarativeEngine SetErrorEventHandler");
1907     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1908     if (!runtime) {
1909         LOGE("SetErrorEventHandler failed, runtime is null.");
1910         return;
1911     }
1912 
1913     runtime->SetErrorEventHandler(std::move(errorCallback));
1914 }
1915 
OnRestoreData(const std::string & data)1916 bool JsiDeclarativeEngine::OnRestoreData(const std::string& data)
1917 {
1918     LOGI("JsiDeclarativeEngine OnRestoreData");
1919     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1920     if (!runtime) {
1921         LOGE("OnRestoreData failed, runtime is null.");
1922         return false;
1923     }
1924     shared_ptr<JsValue> result;
1925     shared_ptr<JsValue> jsonObj = runtime->ParseJson(data);
1926     if (jsonObj->IsUndefined(runtime) || jsonObj->IsException(runtime)) {
1927         LOGE("JsiDeclarativeEngine: Parse json for restore data failed.");
1928         return false;
1929     }
1930     std::vector<shared_ptr<JsValue>> argv = { jsonObj };
1931     return CallAppFunc("onRestoreData", argv);
1932 }
1933 
1934 // ArkTsCard start
OHOS_ACE_PreloadAceModuleCard(void * runtime)1935 extern "C" ACE_FORCE_EXPORT void OHOS_ACE_PreloadAceModuleCard(void* runtime)
1936 {
1937     JsiDeclarativeEngineInstance::PreloadAceModuleCard(runtime);
1938 }
1939 
PreloadAceModuleCard(void * runtime)1940 void JsiDeclarativeEngineInstance::PreloadAceModuleCard(void* runtime)
1941 {
1942     isUnique_ = true;
1943     if (isModulePreloaded_ && !IsPlugin() && !isUnique_) {
1944         LOGE("PreloadAceModule already preloaded");
1945         return;
1946     }
1947     auto sharedRuntime = reinterpret_cast<NativeEngine*>(runtime);
1948 
1949     if (!sharedRuntime) {
1950         LOGE("PreloadAceModule null runtime");
1951         return;
1952     }
1953     std::shared_ptr<ArkJSRuntime> arkRuntime = std::make_shared<ArkJSRuntime>();
1954     localRuntime_ = arkRuntime;
1955     auto nativeArkEngine = static_cast<ArkNativeEngine*>(sharedRuntime);
1956     EcmaVM* vm = const_cast<EcmaVM*>(nativeArkEngine->GetEcmaVm());
1957     if (vm == nullptr) {
1958         LOGE("PreloadAceModule NativeDeclarativeEngine Initialize, vm is null");
1959         return;
1960     }
1961     if (!arkRuntime->InitializeFromExistVM(vm)) {
1962         LOGE("PreloadAceModule Ark Engine initialize runtime failed");
1963         return;
1964     }
1965     LocalScope scope(vm);
1966     globalRuntime_ = arkRuntime;
1967 
1968     // preload js views
1969     JsRegisterFormViews(JSNApi::GetGlobalObject(vm));
1970 
1971     // preload aceConsole
1972     shared_ptr<JsValue> global = arkRuntime->GetGlobal();
1973     shared_ptr<JsValue> aceConsoleObj = arkRuntime->NewObject();
1974     aceConsoleObj->SetProperty(arkRuntime, "log", arkRuntime->NewFunction(JsiBaseUtils::JsInfoLogPrint));
1975     aceConsoleObj->SetProperty(arkRuntime, "debug", arkRuntime->NewFunction(JsiBaseUtils::JsDebugLogPrint));
1976     aceConsoleObj->SetProperty(arkRuntime, "info", arkRuntime->NewFunction(JsiBaseUtils::JsInfoLogPrint));
1977     aceConsoleObj->SetProperty(arkRuntime, "warn", arkRuntime->NewFunction(JsiBaseUtils::JsWarnLogPrint));
1978     aceConsoleObj->SetProperty(arkRuntime, "error", arkRuntime->NewFunction(JsiBaseUtils::JsErrorLogPrint));
1979     global->SetProperty(arkRuntime, "aceConsole", aceConsoleObj);
1980 
1981     // preload aceTrace
1982     shared_ptr<JsValue> aceTraceObj = arkRuntime->NewObject();
1983     aceTraceObj->SetProperty(arkRuntime, "begin", arkRuntime->NewFunction(JsiBaseUtils::JsTraceBegin));
1984     aceTraceObj->SetProperty(arkRuntime, "end", arkRuntime->NewFunction(JsiBaseUtils::JsTraceEnd));
1985     global->SetProperty(arkRuntime, "aceTrace", aceTraceObj);
1986 
1987     // preload getContext
1988     JsiContextModule::GetInstance()->InitContextModule(arkRuntime, global);
1989 
1990     // preload exports and requireNative
1991     shared_ptr<JsValue> exportsUtilObj = arkRuntime->NewObject();
1992     global->SetProperty(arkRuntime, "exports", exportsUtilObj);
1993     global->SetProperty(arkRuntime, "requireNativeModule", arkRuntime->NewFunction(RequireNativeModule));
1994 
1995     // preload js enums
1996     bool jsEnumStyleResult = arkRuntime->EvaluateJsCode(
1997         (uint8_t*)_binary_jsEnumStyle_abc_start, _binary_jsEnumStyle_abc_end - _binary_jsEnumStyle_abc_start);
1998     if (!jsEnumStyleResult) {
1999         LOGE("EvaluateJsCode jsEnumStyle failed");
2000         globalRuntime_ = nullptr;
2001         return;
2002     }
2003 
2004     // preload state management
2005     uint8_t* codeStart;
2006     int32_t codeLength;
2007     codeStart = (uint8_t*)_binary_stateMgmt_abc_start;
2008     codeLength = _binary_stateMgmt_abc_end - _binary_stateMgmt_abc_start;
2009     bool evalResult = arkRuntime->EvaluateJsCode(codeStart, codeLength);
2010     if (!evalResult) {
2011         LOGE("PreloadAceModuleCard EvaluateJsCode stateMgmt failed");
2012     }
2013     isModulePreloaded_ = evalResult;
2014     globalRuntime_ = nullptr;
2015     cardRuntime_ = runtime;
2016     JSNApi::TriggerGC(vm, JSNApi::TRIGGER_GC_TYPE::FULL_GC);
2017 }
2018 // ArkTsCard end
2019 } // namespace OHOS::Ace::Framework
2020