1 /*
2 * Copyright (c) 2025 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 "napi_env_watcher_manager.h"
17
18 #include <algorithm>
19
20 #include "app_event_observer_mgr.h"
21 #include "hilog/log.h"
22
23 #undef LOG_DOMAIN
24 #define LOG_DOMAIN 0xD002D07
25
26 #undef LOG_TAG
27 #define LOG_TAG "EnvWatcherManager"
28
29 namespace OHOS {
30 namespace HiviewDFX {
31
GetInstance()32 EnvWatcherManager &EnvWatcherManager::GetInstance()
33 {
34 static EnvWatcherManager envWatcherManager;
35 return envWatcherManager;
36 }
37
RemoveEnvWatcherRecord(const NapiAppEventWatcher * watcher)38 void EnvWatcherManager::RemoveEnvWatcherRecord(const NapiAppEventWatcher* watcher)
39 {
40 if (watcher) {
41 std::lock_guard<std::mutex> lockGuard(mutex_);
42 napiEnvWatcherRecords_.remove_if([watcher](const auto& pair) {
43 return pair.second == watcher;
44 });
45 }
46 }
47
AddEnvWatcherRecord(const napi_env env,NapiAppEventWatcher * watcher)48 void EnvWatcherManager::AddEnvWatcherRecord(const napi_env env, NapiAppEventWatcher* watcher)
49 {
50 if (!watcher) {
51 return;
52 }
53 std::lock_guard<std::mutex> lockGuard(mutex_);
54 if (envs_.find(env) == envs_.end()) {
55 auto envPtr = new napi_env{env};
56 if (napi_add_env_cleanup_hook(env, EnvWatcherManager::OnEnvRemove, envPtr) == napi_ok) {
57 envs_.insert(env);
58 } else {
59 HILOG_ERROR(LOG_CORE, "failed in napi_add_env_cleanup_hook.");
60 delete envPtr;
61 }
62 }
63 napiEnvWatcherRecords_.emplace_back(env, watcher);
64 }
65
OnEnvRemove(void * envPtr)66 void EnvWatcherManager::OnEnvRemove(void* envPtr)
67 {
68 if (envPtr == nullptr) {
69 HILOG_ERROR(LOG_CORE, "cur envPtr is nullptr.");
70 return;
71 }
72 auto env = reinterpret_cast<napi_env*>(envPtr);
73 EnvWatcherManager& manager = GetInstance();
74 std::lock_guard<std::mutex> lockGuard(manager.mutex_);
75 manager.envs_.erase(*env);
76 manager.napiEnvWatcherRecords_.remove_if([env](const auto& pair) {
77 if (pair.first == *env) {
78 pair.second->DeleteWatcherContext();
79 return true;
80 }
81 return false;
82 });
83 delete env;
84 }
85 }
86 }
87