fix napi crash

Signed-off-by: shenqihang <shenqihang@huawei.com>
This commit is contained in:
shenqihang 2024-11-20 21:40:32 +08:00
parent 79aae75231
commit f96dd3e818
3 changed files with 31 additions and 0 deletions

View File

@ -143,6 +143,7 @@ public:
}
static EventRegister& GetInstance();
static void CleanUp(void *data);
void Register(const napi_env& env, const std::string& type, napi_value handler);
void Unregister(const napi_env& env, const std::string& type, napi_value handler);

View File

@ -420,6 +420,16 @@ static napi_value Init(napi_env env, napi_value exports) {
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc));
napi_env *pEnv = new (std::nothrow) napi_env;
if (pEnv != nullptr) {
*pEnv = env;
auto ret = napi_add_env_cleanup_hook(env, EventRegister::CleanUp, reinterpret_cast<void*>(pEnv));
if (ret != napi_status::napi_ok) {
WIFI_LOGI("Init, napi_add_env_cleanup_hook failed");
}
} else {
WIFI_LOGI("Init, pEnv is nullptr");
}
return exports;
}

View File

@ -809,5 +809,25 @@ void EventRegister::Unregister(const napi_env& env, const std::string& type, nap
g_eventRegisterInfo.erase(iter);
}
}
void EventRegister::CleanUp(void *data)
{
std::unique_lock<std::shared_mutex> guard(g_regInfoMutex);
auto env = *(reinterpret_cast<napi_env*>(data));
for (auto &event : g_eventRegisterInfo) {
auto &vecRegObjs = event.second;
auto iter = vecRegObjs.begin();
for (; iter != vecRegObjs.end();) {
if (env == iter->m_regEnv) {
napi_delete_reference(iter->m_regEnv, iter->m_regHanderRef);
iter = vecRegObjs.erase(iter);
} else {
++iter;
}
}
}
delete reinterpret_cast<napi_env*>(data);
data = nullptr;
}
} // namespace Wifi
} // namespace OHOS