From dbffd0cc1e62c95d4b1ae259f2b0145dd8cdf0b7 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Tue, 3 Jun 2025 22:45:25 +0800 Subject: [PATCH] bugfix for napi crash Signed-off-by: linzlinz <2495670683@qq.com> --- frameworks/js/napi/include/napi_async_work.h | 5 +++++ frameworks/js/napi/src/common/napi_async_work.cpp | 10 +++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/frameworks/js/napi/include/napi_async_work.h b/frameworks/js/napi/include/napi_async_work.h index 151d7c9d..437f6f36 100644 --- a/frameworks/js/napi/include/napi_async_work.h +++ b/frameworks/js/napi/include/napi_async_work.h @@ -21,6 +21,7 @@ #include "napi_bluetooth_utils.h" #include "napi_ha_event_utils.h" #include "napi_native_object.h" +#include namespace OHOS { namespace Bluetooth { @@ -90,6 +91,10 @@ private: std::atomic_bool needCallback_ = false; // Indicates whether an asynchronous work needs to wait for callback. std::atomic_bool triggered_ = false; // Indicates whether the asynchronous callback is called. std::shared_ptr haUtils_; // HA report tool, which is transferred fron the original API interface + + // Used for thread synchronization so that the JS thread is finished after the IPC thread. + std::shared_ptr> threadPromise_ = nullptr; + std::future threadFuture_; }; class NapiAsyncWorkFactory { diff --git a/frameworks/js/napi/src/common/napi_async_work.cpp b/frameworks/js/napi/src/common/napi_async_work.cpp index a5d3ad2b..021469e7 100644 --- a/frameworks/js/napi/src/common/napi_async_work.cpp +++ b/frameworks/js/napi/src/common/napi_async_work.cpp @@ -169,16 +169,24 @@ void NapiAsyncWork::CallFunction(int errCode, std::shared_ptr NapiTimer::GetInstance()->Unregister(timerId_); triggered_ = true; - auto func = [errCode, nativeObj, asyncWorkPtr = shared_from_this()]() { + auto func = [this, errCode, nativeObj, asyncWorkPtr = shared_from_this()]() { if (asyncWorkPtr && asyncWorkPtr->napiAsyncCallback_) { auto haUtils = asyncWorkPtr->GetHaUtilsPtr(); if (haUtils) { haUtils->WriteErrCode(errCode); } asyncWorkPtr->napiAsyncCallback_->CallFunction(errCode, nativeObj); + // Wait for IPC thread to avoid crash due to destruction of asyncWork in IPC thread. + threadPromise_ = std::make_shared>(); + threadFuture_ = threadPromise_->get_future(); + threadFuture_.wait(); } }; DoInJsMainThread(env_, std::move(func)); + + if (threadPromise_ != nullptr) { + threadPromise_->set_value(); + } } napi_value NapiAsyncWork::GetRet(void) -- Gitee