1# Subscribing to Resource Leak Events (C/C++)
2
3## Available APIs
4
5For details about how to use the APIs (such as parameter usage restrictions and value ranges), see [HiAppEvent](../reference/apis-performance-analysis-kit/_hi_app_event.md#hiappevent).
6
7**Subscription APIs**
8
9| API                                                        | Description                                        |
10|-------------------------------------------------------------| -------------------------------------------- |
11| int OH_HiAppEvent_AddWatcher(HiAppEvent_Watcher *watcher)   | Adds a watcher to listen for application events.|
12| int OH_HiAppEvent_RemoveWatcher(HiAppEvent_Watcher *watcher) | Removes a watcher to unsubscribe from the application events.|
13
14## How to Develop
15
161. Create a native C++ project and import the **jsoncpp** file to the project. The directory structure is as follows:
17
18   ```yml
19   entry:
20     src:
21       main:
22         cpp:
23           - json:
24               - json.h
25               - json-forwards.h
26           - types:
27               libentry:
28                 - index.d.ts
29           - CMakeLists.txt
30           - napi_init.cpp
31           - jsoncpp.cpp
32         ets:
33           - entryability:
34               - EntryAbility.ets
35           - pages:
36               - Index.ets
37   ```
38
392. In the **CMakeLists.txt** file, add the source file and dynamic libraries.
40
41   ```cmake
42   # Add the jsoncpp.cpp file, which is used to parse the JSON strings in the subscription events.
43   add_library(entry SHARED napi_init.cpp jsoncpp.cpp)
44   # Add libhiappevent_ndk.z.so and libhilog_ndk.z.so (log output).
45   target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libhiappevent_ndk.z.so)
46   ```
47
483. Import the dependency files to the **napi_init.cpp** file, and define **LOG_TAG**.
49
50   ```c++
51   #include "napi/native_api.h"
52   #include "json/json.h"
53   #include "hilog/log.h"
54   #include "hiappevent/hiappevent.h"
55
56   #undef LOG_TAG
57   #define LOG_TAG "testTag"
58   ```
59
604. Subscribe to system events.
61
62    - Watcher of the onReceive type:
63
64      In the **napi_init.cpp** file, define the methods related to the watcher of the onReceive type.
65
66      ```c++
67      // Define a variable to cache the pointer to the created watcher.
68      static HiAppEvent_Watcher *systemEventWatcher;
69
70      static void OnReceive(const char *domain, const struct HiAppEvent_AppEventGroup *appEventGroups, uint32_t groupLen) {
71          for (int i = 0; i < groupLen; ++i) {
72              for (int j = 0; j < appEventGroups[i].infoLen; ++j) {
73                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", appEventGroups[i].appEventInfos[j].domain);
74                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", appEventGroups[i].appEventInfos[j].name);
75                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", appEventGroups[i].appEventInfos[j].type);
76                  if (strcmp(appEventGroups[i].appEventInfos[j].domain, DOMAIN_OS) == 0 &&
77                      strcmp(appEventGroups[i].appEventInfos[j].name, EVENT_RESOURCE_OVERLIMIT) == 0) {
78                      Json::Value params;
79                      Json::Reader reader(Json::Features::strictMode());
80                      Json::FastWriter writer;
81                      if (reader.parse(appEventGroups[i].appEventInfos[j].params, params)) {
82                          auto time = params["time"].asInt64();
83                          auto pid = params["pid"].asInt();
84                          auto uid = params["uid"].asInt();
85                          auto resourceType = params["resourceType"].asString();
86                          auto bundleName = params["bundle_name"].asString();
87                          auto bundleVersion = params["bundle_version"].asString();
88                          auto memory = writer.write(params["memory"]);
89                          auto externalLog = writer.write(eventInfo["external_log"]);
90                          std::string logOverLimit = eventInfo["log_over_limit"].asBool() ? "true":"false";
91                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time);
92                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid);
93                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid);
94                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.resource_type=%{public}s", resourceType.c_str());
95                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s", bundleName.c_str());
96                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str());
97                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str());
98                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str());
99                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit.c_str());
100                      }
101                  }
102              }
103          }
104      }
105
106      static napi_value RegisterWatcher(napi_env env, napi_callback_info info) {
107          // Set the watcher name. The system identifies different watchers based on their names.
108          systemEventWatcher = OH_HiAppEvent_CreateWatcher("onReceiverWatcher");
109          // Set the event to watch to EVENT_RESOURCE_OVERLIMIT.
110          const char *names[] = {EVENT_RESOURCE_OVERLIMIT};
111          // Add the events to watch, for example, system events.
112          OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1);
113          // Set the implemented callback. After receiving the event, the watcher immediately triggers the OnReceive callback.
114          OH_HiAppEvent_SetWatcherOnReceive(systemEventWatcher, OnReceive);
115          // Add a watcher to listen for the specified event.
116          OH_HiAppEvent_AddWatcher(systemEventWatcher);
117          return {};
118      }
119      ```
120
121    - Watcher of the onTrigger type:
122
123      In the **napi_init.cpp** file, define the methods related to the watcher of the OnTrigger type.
124
125      ```c++
126      // Implement the callback function used to return the listened events. The content pointed to by the events pointer is valid only in this function.
127      static void OnTake(const char *const *events, uint32_t eventLen) {
128          Json::Reader reader(Json::Features::strictMode());
129          Json::FastWriter writer;
130          for (int i = 0; i < eventLen; ++i) {
131              Json::Value eventInfo;
132              if (reader.parse(events[i], eventInfo)) {
133                  auto domain =  eventInfo["domain_"].asString();
134                  auto name = eventInfo["name_"].asString();
135                  auto type = eventInfo["type_"].asInt();
136                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", domain.c_str());
137                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", name.c_str());
138                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", type);
139                  if (domain ==  DOMAIN_OS && name == EVENT_RESOURCE_OVERLIMIT) {
140                      auto time = eventInfo["time"].asInt64();
141                      auto pid = eventInfo["pid"].asInt();
142                      auto uid = eventInfo["uid"].asInt();
143                      auto resourceType = eventInfo["resourceType"].asString();
144                      auto bundleName = eventInfo["bundle_name"].asString();
145                      auto bundleVersion = eventInfo["bundle_version"].asString();
146                      auto memory = writer.write(eventInfo["memory"]);
147                      auto externalLog = writer.write(eventInfo["external_log"]);
148                      std::string logOverLimit = eventInfo["log_over_limit"].asBool() ? "true":"false";
149                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time);
150                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid);
151                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid);
152                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.resource_type=%{public}s", resourceType.c_str());
153                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s", bundleName.c_str());
154                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str());
155                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str());
156                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str());
157                      OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit.c_str());
158                  }
159              }
160          }
161      }
162
163      // Implement the subscription callback function to apply custom processing to the obtained event logging data.
164      static void OnTrigger(int row, int size) {
165          // After the callback is received, obtain the specified number of received events.
166          OH_HiAppEvent_TakeWatcherData(systemEventWatcher, row, OnTake);
167      }
168
169      static napi_value RegisterWatcher(napi_env env, napi_callback_info info) {
170          // Set the watcher name. The system identifies different watchers based on their names.
171          systemEventWatcher = OH_HiAppEvent_CreateWatcher("onTriggerWatcher");
172          // Set the event to watch to EVENT_RESOURCE_OVERLIMIT.
173          const char *names[] = {EVENT_RESOURCE_OVERLIMIT};
174          // Add the events to watch, for example, system events.
175          OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1);
176          // Set the implemented callback function. The callback function will be triggered when the conditions set by OH_HiAppEvent_SetTriggerCondition are met.
177          OH_HiAppEvent_SetWatcherOnTrigger(systemEventWatcher, OnTrigger);
178          // Set the conditions for triggering the subscription callback. For example, trigger this onTrigger callback when the number of new event logs is 2.
179          OH_HiAppEvent_SetTriggerCondition(systemEventWatcher, 1, 0, 0);
180          // Add a watcher to listen for the specified event.
181          OH_HiAppEvent_AddWatcher(systemEventWatcher);
182          return {};
183      }
184      ```
185
1865. Register **RegisterWatcher** as an ArkTS API.
187
188   In the **napi_init.cpp** file, register **RegisterWatcher** as an ArkTS API.
189
190   ```c++
191   static napi_value Init(napi_env env, napi_value exports)
192   {
193       napi_property_descriptor desc[] = {
194           { "registerWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr }
195       };
196       napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
197       return exports;
198   }
199   ```
200
201   In the **index.d.ts** file, define the ArkTS API.
202
203   ```typescript
204   export const registerWatcher: () => void;
205   ```
206
2076. In the **EntryAbility.ets** file, add the following interface invocation to **onCreate()**.
208
209   ```typescript
210   import testNapi from 'libentry.so'
211   import hidebug from '@kit.PerformanceAnalysisKit'
212   export default class EntryAbility extends UIAbility {
213     onCreate(want, launchParam) {
214       // Register the system event watcher at startup.
215       testNapi.registerWatcher();
216     }
217   }
218   ```
219
2207. In the **entry/src/main/ets/pages/index.ets** file, add the **memoryleak** button and construct a scenario for triggering a resource leak event in **onClick()**.
221   In this case, use [hidebug.setAppResourceLimit](../reference/apis-performance-analysis-kit/js-apis-hidebug.md#hidebugsetappresourcelimit12) to set the memory limit to trigger a memory leak event, and enable **System resource leak log** in **Developer options**. The sample code is as follows:
222
223   ```ts
224    import hidebug from "@ohos.hidebug";
225
226    @Entry
227    @Component
228    struct Index {
229    @State leakedArray: string[][] = [];
230
231    build() {
232      Column() {
233        Row() {
234          Column() {
235            Button("pss leak")
236              .onClick(() => {
237                hidebug.setAppResourceLimit("pss_memory", 1024, true);
238                for (let i = 0; i < 20 * 1024; i++) {
239                  this.leakedArray.push(new Array(1).fill("leak"));
240                }
241              })
242          }
243        }
244        .height('100%')
245        .width('100%')
246      }
247    }
248   ```
249
2508. Click the **Run** button in DevEco Studio to run the project, and then a memory leak event will be reported after 15 to 30 minutes.
251   For the same application, the memory leak event can be reported at most once within 24 hours. If the memory leak needs to be reported again within a shorter time, restart the device.
252
2539. After the memory leak event is reported, you can view the following event information in the **Log** window.
254
255   ```text
256   08-07 03:53:35.314 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.domain=OS
257   08-07 03:53:35.314 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.name=RESOURCE_OVERLIMIT
258   08-07 03:53:35.314 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.eventType=1
259   08-07 03:53:35.349 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.time=1502049167732
260   08-07 03:53:35.349 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.pid=1587
261   08-07 03:53:35.349 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.uid=20010043
262   08-07 03:53:35.349 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.resource_type=pss_memory
263   08-07 03:53:35.349 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.bundle_name=com.example.myapplication
264   08-07 03:53:35.349 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.bundle_version=1.0.0
265   08-07 03:53:35.350 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.memory={"pss":2100257,"rss":1352644,"sys_avail_mem":250272,"sys_free_mem":60004,"sys_total_mem":1992340,"vss":2462936}
266   08-07 03:53:35.350 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/resourcelimit/RESOURCE_OVERLIMIT_1725614572401_6808.log","/data/storage/el2/log/resourcelimit/RESOURCE_OVERLIMIT_1725614572412_6808.log"]
267   08-07 03:53:35.350 1719-1738/? I A00000/testTag: HiAppEvent eventInfo.params.log_over_limit=false
268   ```
269
27010. Remove the event watcher.
271
272    ```c++
273    static napi_value RemoveWatcher(napi_env env, napi_callback_info info) {
274        // Remove the watcher.
275        OH_HiAppEvent_RemoveWatcher(systemEventWatcher);
276        return {};
277    }
278    ```
279
28011. Destroy the event watcher.
281
282    ```c++
283    static napi_value DestroyWatcher(napi_env env, napi_callback_info info) {
284        // Destroy the created watcher and set systemEventWatcher to nullptr.
285        OH_HiAppEvent_DestroyWatcher(systemEventWatcher);
286        systemEventWatcher = nullptr;
287        return {};
288    }
289    ```
290