From a20bb447a001accde655cb96f46b255e65db555a Mon Sep 17 00:00:00 2001 From: qiuguohua Date: Tue, 11 Feb 2025 16:46:31 +0800 Subject: [PATCH] Fix cross threading issue when calling callStatic Method (#18316) * Fix cross threading issue when calling callStatic Method * Rename AsyncCallParam to CallParam --------- Co-authored-by: qiuguohua --- .../bindings/manual/JavaScriptArkTsBridge.cpp | 74 +-------- .../platform/openharmony/napi/NapiHelper.h | 155 ++++++++++++++---- .../source/platforms/harmonyos-next.ts | 4 +- .../entry/src/main/ets/pages/index.ets | 8 +- 4 files changed, 136 insertions(+), 105 deletions(-) diff --git a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp index e6aabd2ee4..a4b9ac0e21 100644 --- a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp +++ b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp @@ -107,79 +107,21 @@ bool JavaScriptArkTsBridge::CallInfo::execute(se::Value& rval) { module_name = pos != std::string::npos ? pathStr.substr(0, pos).c_str() : "entry"; } - auto env = cc::NapiHelper::getWorkerEnv(); - napi_status status; - napi_value result; char* module_info = __getModuleInfo(module_name); - status = napi_load_module_with_info(env, _clsPath, module_info, &result); - free(module_info); - module_info = nullptr; - if (status != napi_ok) { - CC_LOG_WARNING("callNativeMethod napi_load_module_with_info fail, status=%{public}d", status); - return false; - } - - napi_value func; - status = napi_get_named_property(env, result, method, &func); - if (status != napi_ok) { - CC_LOG_WARNING("callNativeMethod napi_get_named_property fail, status=%{public}d", status); - return false; - } - - if (_isSyn) { - napi_value jsArg = Napi::String::New(env, _paramStr); - napi_value return_val; - status = napi_call_function(env, result, func, 1, &jsArg, &return_val); - if (status != napi_ok) { - CC_LOG_WARNING("callNativeMethod napi_call_function fail, status=%{public}d", status); - return false; - } - - napi_valuetype valueType; - status = napi_typeof(env, return_val, &valueType); - if (status != napi_ok) { - CC_LOG_WARNING("callNativeMethod napi_typeof fail, status=%{public}d", status); - return false; - } - - switch (valueType) { - case napi_string: { - size_t str_size; - napi_get_value_string_utf8(env, return_val, nullptr, 0, &str_size); - char* buf = new char[str_size + 1]; - napi_get_value_string_utf8(env, return_val, buf, str_size + 1, &str_size); - rval = se::Value(std::string(buf)); - delete[] buf; - break; - } - case napi_number: { - double num_value; - napi_get_value_double(env, return_val, &num_value); - CC_LOG_INFO("Returned number: %f", num_value); - rval = se::Value(num_value); - break; - } - case napi_boolean: { - bool bool_value; - napi_get_value_bool(env, return_val, &bool_value); - rval = se::Value(bool_value); - break; - } - default: - CC_LOG_WARNING("Unhandled return value type"); - break; - } - return true; - } - std::promise promise; std::function cb = [&promise](cc::CallbackParamType message) { promise.set_value(message); }; - cc::AsyncCallParam* callParam = new cc::AsyncCallParam{cb, _paramStr, func}; - cc::JSFunction::getFunction("executeNativeMethod").invokeAsync(callParam); + cc::CallParam *callParam = new cc::CallParam{cb, _paramStr, module_info, _clsPath, method}; + if (_isSyn) { + cc::JSFunction::getFunction("executeMethodSync").invoke(callParam, _isSyn); + } else { + cc::JSFunction::getFunction("executeMethodAsync").invoke(callParam, _isSyn); + } cc::CallbackParamType methodResult = promise.get_future().get(); + free(module_info); + delete callParam; rval = se::Value(convertToSeValue(methodResult)); return true; } diff --git a/native/cocos/platform/openharmony/napi/NapiHelper.h b/native/cocos/platform/openharmony/napi/NapiHelper.h index dde84568f5..fef08a2317 100644 --- a/native/cocos/platform/openharmony/napi/NapiHelper.h +++ b/native/cocos/platform/openharmony/napi/NapiHelper.h @@ -26,19 +26,21 @@ #pragma once #define NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS 1 -#define NAPI_DISABLE_CPP_EXCEPTIONS 1 -#define NODE_ADDON_API_DISABLE_DEPRECATED 1 -#include "napi.h" +#define NAPI_DISABLE_CPP_EXCEPTIONS 1 +#define NODE_ADDON_API_DISABLE_DEPRECATED 1 #include "NapiValueConverter.h" #include "base/Log.h" +#include "napi.h" namespace cc { using CallbackParamType = std::variant; -struct AsyncCallParam { +struct CallParam { std::function cb; std::string paramStr; - napi_value callFunc; + char *module_info; + const char *clsPath; + const char *method; napi_ref executeFuncRef; }; @@ -46,45 +48,44 @@ class NapiHelper { public: static Napi::Env getWorkerEnv(); static Napi::Object init(Napi::Env env, Napi::Object exports); - static Napi::Value napiCallFunction(const char* functionName); - static Napi::Value napiCallFunction(const char *functionName,float duration); - static void postMessageToUIThread(const std::string& type, Napi::Value param); - static Napi::Value postSyncMessageToUIThread(const std::string& type, Napi::Value param); + static Napi::Value napiCallFunction(const char *functionName); + static Napi::Value napiCallFunction(const char *functionName, float duration); + static void postMessageToUIThread(const std::string &type, Napi::Value param); + static Napi::Value postSyncMessageToUIThread(const std::string &type, Napi::Value param); }; class JSFunction { public: napi_ref funcRef; napi_env env; - char* name = nullptr; + char *name = nullptr; public: static std::unordered_map jsFunctionMap; - explicit JSFunction(char* name, napi_env env, napi_ref funcRef) - : name(name), env(env), funcRef(funcRef){} + explicit JSFunction(char *name, napi_env env, napi_ref funcRef) + : name(name), env(env), funcRef(funcRef) {} - explicit JSFunction(char* name, napi_env env) - : name(name), env(env){} + explicit JSFunction(char *name, napi_env env) + : name(name), env(env) {} - explicit JSFunction(char* name) - : name(name){} + explicit JSFunction(char *name) + : name(name) {} - static JSFunction getFunction(std::string functionName) - { + static JSFunction getFunction(std::string functionName) { return jsFunctionMap.at(functionName); } - static void addFunction(std::string name, JSFunction* jsFunction) { + static void addFunction(std::string name, JSFunction *jsFunction) { jsFunctionMap.emplace(name, *jsFunction); } - template + template typename std::enable_if::value, ReturnType>::type invoke(Args... args) { napi_value global; napi_status status = napi_get_global(env, &global); - //if (status != napi_ok) return; + // if (status != napi_ok) return; napi_value func; status = napi_get_reference_value(env, funcRef, &func); @@ -100,7 +101,7 @@ public: return value; } - template + template typename std::enable_if::value, void>::type invoke(Args... args) { napi_value global; @@ -115,7 +116,7 @@ public: status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val); } - void invokeAsync(AsyncCallParam *callParam) { + void invoke(CallParam *callParam, bool isSync) { callParam->executeFuncRef = funcRef; napi_status status; @@ -134,11 +135,14 @@ public: } napi_threadsafe_function save_func; - status = napi_create_threadsafe_function(env, func, nullptr, workName, 0, 1, nullptr, - [](napi_env env, void *raw, void *hint) {}, callParam, CallJS, &save_func); - if (status != napi_ok) { - CC_LOG_WARNING("invokeAsync napi_create_threadsafe_function fail,status=%{public}d", status); - return; + if (isSync) { + status = napi_create_threadsafe_function( + env, func, nullptr, workName, 0, 1, nullptr, [](napi_env env, void *raw, void *hint) {}, callParam, + CallJsSync, &save_func); + } else { + status = napi_create_threadsafe_function( + env, func, nullptr, workName, 0, 1, nullptr, [](napi_env env, void *raw, void *hint) {}, callParam, + CallJsAsync, &save_func); } status = napi_acquire_threadsafe_function(save_func); @@ -154,10 +158,10 @@ public: } } - static void CallJS(napi_env env, napi_value js_cb, void *context, void *data) { - AsyncCallParam *callParam = (AsyncCallParam*) (context); + static void CallJsAsync(napi_env env, napi_value js_cb, void *context, void *data) { + CallParam *callParam = (CallParam *)(context); if (callParam == nullptr) { - CC_LOG_WARNING("CallJS AsyncCallParam callParam is null"); + CC_LOG_WARNING("CallJS CallParam callParam is null"); return; } @@ -177,9 +181,9 @@ public: napi_value return_val; napi_get_undefined(env, &return_val); - AsyncCallParam *callbackParam = reinterpret_cast(param_in); + CallParam *callbackParam = reinterpret_cast(param_in); if (callbackParam == nullptr) { - CC_LOG_WARNING("CallJS AsyncCallParam callbackParam is null"); + CC_LOG_WARNING("CallJS CallParam callbackParam is null"); return return_val; } @@ -202,6 +206,7 @@ public: callbackValue = resultBol; } else { callbackValue = "unknown"; + CC_LOG_WARNING("callbackValue returns incorrect value type"); } callbackParam->cb(callbackValue); return return_val; @@ -214,7 +219,21 @@ public: return; } - napi_value jsArgs[3] = {callParam->callFunc, NapiValueConverter::ToNapiValue(env, callParam->paramStr), callbackFunc}; + napi_value result; + status = napi_load_module_with_info(env, callParam->clsPath, callParam->module_info, &result); + if (status != napi_ok) { + CC_LOG_WARNING("callNativeMethod napi_load_module_with_info fail, status=%{public}d", status); + return; + } + + napi_value callFunc; + status = napi_get_named_property(env, result, callParam->method, &callFunc); + if (status != napi_ok) { + CC_LOG_WARNING("callNativeMethod napi_get_named_property fail, status=%{public}d", status); + return; + } + + napi_value jsArgs[3] = {callFunc, NapiValueConverter::ToNapiValue(env, callParam->paramStr), callbackFunc}; napi_value return_val; napi_value global; status = napi_get_global(env, &global); @@ -227,6 +246,72 @@ public: CC_LOG_WARNING("CallJS napi_call_function fail,status=%{public}d", status); } } + + static void CallJsSync(napi_env env, napi_value js_cb, void *context, void *data) { + CallParam *callParam = (CallParam *)(context); + if (callParam == nullptr) { + CC_LOG_WARNING("CallJS CallParam callParam is null"); + return; + } + + napi_status status; + status = napi_get_reference_value(env, callParam->executeFuncRef, &js_cb); + if (status != napi_ok) { + CC_LOG_WARNING("CallJS napi_get_reference_value fail,status=%{public}d", status); + return; + } + + napi_value result; + status = napi_load_module_with_info(env, callParam->clsPath, callParam->module_info, &result); + if (status != napi_ok) { + CC_LOG_WARNING("callNativeMethod napi_load_module_with_info fail, status=%{public}d", status); + return; + } + + napi_value callFunc; + status = napi_get_named_property(env, result, callParam->method, &callFunc); + if (status != napi_ok) { + CC_LOG_WARNING("callNativeMethod napi_get_named_property fail, status=%{public}d", status); + return; + } + + napi_value jsArgs[2] = {callFunc, NapiValueConverter::ToNapiValue(env, callParam->paramStr)}; + napi_value return_val; + napi_value global; + status = napi_get_global(env, &global); + if (status != napi_ok) { + CC_LOG_WARNING("CallJS napi_get_global fail,status=%{public}d", status); + } + + status = napi_call_function(env, global, js_cb, 2, jsArgs, &return_val); + + napi_valuetype type; + napi_typeof(env, return_val, &type); + + CallbackParamType callbackValue; + + if (type == napi_string) { + std::string resultStr; + NapiValueConverter::ToCppValue(env, return_val, resultStr); + callbackValue = std::move(resultStr); + } else if (type == napi_number) { + double resultNum; + NapiValueConverter::ToCppValue(env, return_val, resultNum); + callbackValue = resultNum; + } else if (type == napi_boolean) { + bool resultBol; + NapiValueConverter::ToCppValue(env, return_val, resultBol); + callbackValue = resultBol; + } else { + callbackValue = "unknown"; + CC_LOG_WARNING("callbackValue returns incorrect value type"); + } + callParam->cb(callbackValue); + + if (status != napi_ok) { + CC_LOG_WARNING("CallJS napi_call_function fail,status=%{public}d", status); + } + } }; -} // namespace cc +} // namespace cc diff --git a/scripts/native-pack-tool/source/platforms/harmonyos-next.ts b/scripts/native-pack-tool/source/platforms/harmonyos-next.ts index a31a1801ca..95a4ebcde1 100644 --- a/scripts/native-pack-tool/source/platforms/harmonyos-next.ts +++ b/scripts/native-pack-tool/source/platforms/harmonyos-next.ts @@ -71,10 +71,10 @@ export class HarmonyOSNextPackTool extends NativePackTool { moduleJSON.module.abilities[0].orientation = 'auto_rotation'; } else if (cfg.landscapeRight && !cfg.landscapeLeft) { - moduleJSON.module.abilities[0].orientation = 'landscape_inverted'; + moduleJSON.module.abilities[0].orientation = 'landscape'; } else if (!cfg.landscapeRight && cfg.landscapeLeft) { - moduleJSON.module.abilities[0].orientation = 'landscape'; + moduleJSON.module.abilities[0].orientation = 'landscape_inverted'; } else if (cfg.landscapeRight && cfg.landscapeLeft) { moduleJSON.module.abilities[0].orientation = 'auto_rotation_landscape'; diff --git a/templates/harmonyos-next/entry/src/main/ets/pages/index.ets b/templates/harmonyos-next/entry/src/main/ets/pages/index.ets index ece83ee022..fca4f64089 100644 --- a/templates/harmonyos-next/entry/src/main/ets/pages/index.ets +++ b/templates/harmonyos-next/entry/src/main/ets/pages/index.ets @@ -38,10 +38,14 @@ const nativePageLifecycle :context = nativerender.getContext(ContextType.JSPAGE_ const engineUtils :context = nativerender.getContext(ContextType.ENGINE_UTILS); -function executeNativeMethod(nativeFunc: Function, funcData: string, funCb: Function): void { +function executeMethodAsync(nativeFunc: Function, funcData: string, funCb: Function): void { nativeFunc && nativeFunc(funcData, funCb); } -engineUtils.registerFunction("executeNativeMethod", executeNativeMethod); +function executeMethodSync(nativeFunc: Function, funcData: string): string|boolean|number { + return nativeFunc && nativeFunc(funcData); +} +engineUtils.registerFunction("executeMethodAsync", executeMethodAsync); +engineUtils.registerFunction("executeMethodSync", executeMethodSync); interface WorkerMessage { type: string;