!3374 fix napi crash

Merge pull request !3374 from shenqihang/master
This commit is contained in:
openharmony_ci 2024-11-21 07:26:15 +00:00 committed by Gitee
commit 43126280fe
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
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