1# Introduction to HiDebug 2 3<!--Kit: Performance Analysis Kit--> 4<!--Subsystem: HiviewDFX--> 5<!--Owner: @hello_harmony; @yu_haoqiaida--> 6<!--Designer: @kutcherzhou1--> 7<!--Tester: @gcw_KuLfPSbe--> 8<!--Adviser: @foryourself--> 9 10HiDebug can obtain the memory, CPU, and GPU data of the system or application processes, and enable process trace collection. 11 12This topic describes the ArkTS and C/C++ APIs of the HiDebug module and classifies them by API capability. 13 14For details about the APIs, see [ArkTS API Reference](../reference/apis-performance-analysis-kit/js-apis-hidebug.md) and [C API Reference](../reference/apis-performance-analysis-kit/capi-hidebug-h.md). 15 16## Constraints 17 18API calls of this module are time-consuming. Some API calls take seconds, which may cause thread freezes. It is recommended that the APIs of the HiDebug module be used only in the application debugging and optimization phases. If the APIs are required in other scenarios, evaluate the impact of the APIs on application performance. 19 20## Obtaining Memory Information 21 22HiDebug can obtain the system memory, application process memory usage, application thread memory usage, and native memory allocation data collected by the memory allocator. During program development, these memory data can be used to detect and solve problems, optimize program performance, and ensure program stability. 23 24### APIs (ArkTS) 25 26| Name| Description | 27| -------- | -------- | 28| hidebug.getNativeHeapSize | Obtains the total number of bytes occupied by the total space (**uordblks** and **fordblks**, which are obtained through **mallinfo**) held by a process, which is measured by the memory allocator.| 29| hidebug.getNativeHeapAllocatedSize | Obtains the total number of bytes occupied by the total allocated space (**uordblks**, which is obtained through **mallinfo**) held by a process, which is measured by the memory allocator.| 30| hidebug.getNativeHeapFreeSize | Obtains the total number of bytes occupied by the total free space (**fordblks**, which is obtained from **mallinfo**) held by a process, which is measured by the memory allocator.| 31| hidebug.getPss | Obtains the size of the physical memory actually used by the application process. This API is implemented by reading and summing up the values of **Pss** and **SwapPss** in the **/proc/{pid}/smaps_rollup** node.| 32| hidebug.getVss | Obtains the virtual set size used by the application process. This API is implemented by reading the value of **size** (number of memory pages) from the **/proc/{pid}/statm** node and calculating the value using the following formula: **vss** = **size** × page size (4 KB/page).| 33| hidebug.getSharedDirty | Obtains the size of the shared dirty memory of a process. This API is implemented by reading the value of **Shared_Dirty** in **/proc/{pid}/smaps_rollup**.| 34| hidebug.getPrivateDirty | Obtains the size of the private dirty memory of a process. This API is implemented by reading the value of **Private_Dirty** in the **/proc/{pid}/smaps_rollup** node.| 35| hidebug.getAppNativeMemInfo | Obtains the memory information of the application process. This API is implemented by reading data from the **/proc/{pid}/smaps_rollup and /proc/{pid}/statm** node.| 36| hidebug.getAppNativeMemInfoAsync | Obtains the memory information of an application process in asynchronous mode.<br>**Note**: This API is supported since API version 20.| 37| hidebug.getAppNativeMemInfoWithCache | Obtains the memory information of an application process. This API has a cache mechanism to improve its performance.<br>**Note**: This API is supported since API version 20.| 38| hidebug.getSystemMemInfo | Obtains system memory information. This API is implemented by reading data from the **/proc/meminfo** node.| 39| hidebug.getAppMemoryLimit | Obtains the memory limit of an application process. **rsslimit** and **vsslimit** are the values of **RLIMIT_RSS** and **RLIMIT_AS** obtained through the **getrlimit** API, respectively.| 40| hidebug.setJsRawHeapTrimLevel | Sets the trimming level of the original heap snapshot stored by the current process.<br>**Note**: This API is supported since API version 20.| 41 42### APIs (C/C++) 43 44| Name| Description | 45| -------- | -------- | 46| OH_HiDebug_GetSystemMemInfo | Obtains system memory information. This API is implemented by reading data from the **/proc/meminfo** node.| 47| OH_HiDebug_GetAppNativeMemInfo | Obtains the memory information of the application process. This API is implemented by reading data from the **/proc/{pid}/smaps_rollup and /proc/{pid}/statm** node.| 48| OH_HiDebug_GetAppNativeMemInfoWithCache | Obtains the memory information of an application process. This API has a cache mechanism to improve its performance.<br>**Note**: This API is supported since API version 20.| 49| OH_HiDebug_GetAppMemoryLimit | Obtains the memory limit of an application process. **rsslimit** and **vsslimit** are the values of **RLIMIT_RSS** and **RLIMIT_AS** obtained through the getrlimit API, respectively.| 50 51## Obtaining GPU Memory Information 52 53HiDebug can obtain the GPU memory information of an application. In graphics-intensive applications, GPU memory management is critical. Misuse of GPU memory resources will cause severe frame freezes and affect user experience. GPU memory resources include: 54 551. Memory tracked by MemoryTracker, which is directly allocated by the GPU driver using the physical page allocator. Its size depends on the implementation of the GPU hardware driver. 56 572. Memory occupied by RenderService for loading required resources, such as images and textures. 58 59### APIs (ArkTS) 60 61| Name| Description | 62| -------- | -------- | 63| hidebug.getGraphicsMemory | Obtains the GPU memory size of an application in asynchronous mode.| 64| hidebug.getGraphicsMemorySync | Obtains the GPU memory size of an application in synchronous mode.| 65 66### APIs (C/C++) 67 68| Name| Description | 69| -------- | -------- | 70| OH_HiDebug_GetGraphicsMemory | Obtains the GPU memory size of an application.| 71 72## Obtaining CPU Usage 73 74Monitoring the CPU usage is critical to performance analysis during application development. It helps optimize application performance and ensure smooth running. HiDebug provides multiple APIs to obtain the CPU usage. 75 76### Implementation Principles 77 78The HiView process obtains and caches the running data of the current CPU every 10 seconds as the benchmark for calculating the CPU usage. The following data is included: 79 801. System CPU usage data 81 82The **/proc/stat** node contains the statistics of the CPU running data since the system is started. You can run the following command on the terminal to view the node information: 83 84``` 85cat /proc/stat 86cpu 648079 547 703220 16994706 23006 101071 0 0 0 0 87... 88``` 89 90Fields in the CPU indicator: 91 92The CPU statistics from left to right are as follows (**cpu** indicates the total running data of the CPU): 93 94- **user**: user-mode time, in jiffies 95 96- **nice**: nice user-mode time, in jiffies 97 98- **system**: kernel-mode time, in jiffies 99 100- **idle**: idle time, in jiffies (excluding the I/O wait time) 101 102- **iowait**: I/O wait time, in jiffies 103 104- **irq**: hard interrupt time, in jiffies 105 106- **softirq**: soft interrupt time, in jiffies 107 108- **steal**: stolen time (time spent running other operating systems in a virtual environment) 109 110- **guest**: guest time (time spent running virtual CPUs by the operating system) 111 112- **guest_nice**: nice guest time (time spent running a guest with a **nice** value) 113 1142. Process/Thread CPU usage data 115 116``` 117// Process CPU running data collected by the kernel 118struct ucollection_process_cpu_item { 119 int pid; 120 unsigned int thread_total; 121 unsigned long long min_flt; 122 unsigned long long maj_flt; 123 unsigned long long cpu_usage_utime; // User-mode CPU running duration 124 unsigned long long cpu_usage_stime;// Kernel-mode CPU running duration 125 unsigned long long cpu_load_time; 126}; 127// Thread CPU running data collected by the kernel 128struct ucollection_thread_cpu_item { 129 int tid; 130 char name[16]; // 16 : max length of thread name 131 unsigned long long cpu_usage_utime;// User-mode CPU running duration 132 unsigned long long cpu_usage_stime;// Kernel-mode CPU running duration 133 unsigned long long cpu_load_time; 134}; 135``` 136 137You can call the API to obtain the current data, calculate the increments based on the baseline data, and use the following formulas to obtain the CPU usages: 138 139System CPU usage: 140 141``` 142(**systemUsage** increment + **niceUsage** increment + **userUsage** increment)/(**userTime** increment + **niceTime** increment + **systemTime** increment + **idleTime** increment + **ioWaitTime** increment + **irqTime** increment + **softIrqTime** increment) 143``` 144 145Process/Thread CPU usage: 146 147``` 148(**cpu_usage_utime** increment + **cpu_usage_stime** increment)/(ms-level timestamp increment) 149``` 150 151### APIs (ArkTS) 152 153| Name| Description | 154| -------- | -------- | 155| hidebug.getAppThreadCpuUsage | Obtains the CPU usage of an application thread.| 156| hidebug.getCpuUsage | Obtains the CPU usage of an application process.| 157| hidebug.getSystemCpuUsage | Obtains the system CPU usage.| 158 159### APIs (C/C++) 160 161| Name| Description | 162| -------- | -------- | 163| OH_HiDebug_GetSystemCpuUsage | Obtains the system CPU usage.| 164| OH_HiDebug_GetAppCpuUsage | Obtains the CPU usage of a process.| 165| OH_HiDebug_GetAppThreadCpuUsage | Obtains the CPU usage of all threads in an application.| 166| OH_HiDebug_FreeThreadCpuUsage | Releases the data obtained by calling **OH_HiDebug_GetAppThreadCpuUsage**.| 167 168## Obtaining VM Information 169 170HiDebug can obtain VM memory data, GC statistics, and VM heap dump data. 171 172### APIs (ArkTS) 173 174| Name| Description | 175| -------- | -------- | 176| hidebug.getAppVMMemoryInfo | Obtains VM memory information.| 177| hidebug.getVMRuntimeStats | Obtains the system [GC](../arkts-utils/gc-introduction.md) statistics.| 178| hidebug.getVMRuntimeStat | Obtains the specified system [GC](../arkts-utils/gc-introduction.md) statistics based on parameters.| 179| hidebug.dumpJsRawHeapData | Dumps the original VM heap snapshot for the current thread in asynchronous mode. This API is used for [JavaScript memory leak analysis](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-stability-js-memleak-detection).| 180| hidebug.dumpJsHeapData | Dumps the VM heap data in synchronous mode. This API is used for [JavaScript memory leak analysis](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-stability-js-memleak-detection).| 181| hidebug.getAppMemoryLimit | Obtains the memory limit of an application process. **vmHeapLimit** is the VM heap size limit of the current thread, and **vmTotalHeapSize** is the total size limit of all VM heaps in the current process.| 182 183## Obtaining Application Trace Records 184 185HiTrace provides APIs to implement call chain tracing throughout a service process. This can help you obtain the run log for the call chain of a service process and locate faults across devices, processes, and threads. For details, see [Introduction to HiTraceMeter](hitracemeter-intro.md). To implement automatic HiTrace collection, the HiDebug module provides APIs for starting and stopping a HiTrace collection. 186 187### APIs (ArkTS) 188 189| Name| Description | 190| -------- | -------- | 191| hidebug.startAppTraceCapture | Starts an application trace collection.| 192| hidebug.stopAppTraceCapture | Stops an application trace collection.| 193 194### APIs (C/C++) 195 196| Name| Description | 197| -------- | -------- | 198| OH_HiDebug_StartAppTraceCapture | Starts an application trace collection.| 199| OH_HiDebug_StopAppTraceCapture | Stops an application trace collection.| 200 201## Starting VM CpuProfiler 202 203HiDebug provides APIs for starting and stopping a VM CpuProfiler, helping you implement an automatic CpuProfiler collection. 204 205### APIs (ArkTS) 206 207| Name| Description | 208| -------- | -------- | 209| hidebug.startJsCpuProfiling | Starts the VM CPU profiling.| 210| hidebug.stopJsCpuProfiling | Stops the VM CPU profiling.| 211 212## Obtaining Call Stack 213 214Obtaining call stack information is useful for debugging and error handling. It helps you understand the method calling sequence and caller information. HiDebug provides APIs for obtaining call stack information. 215 216### Stack Backtracing Principles 217 218The following figure shows the structure of the function stack frame in the ARM64 architecture. 219 220**Figure 1** 221 222 223**FP**: stack top pointer to the top of a stack frame. When a function jumps, the start position of the stack is recorded. 224 225**SP**: stack pointer (stack bottom pointer) to the current position of the stack. 226 227**LR**: pointer to the address returned by the function. 228 229As shown in the preceding figure, the address adjacent to the FP stores the FP address of the previous frame and the function return address of the current frame. During stack backtracing, the stack information of the previous frame is parsed based on the function return address, and the LR and FP addresses stored in each function stack frame are found in sequence based on the FP address of the previous frame. Based on the FP stack backtracing feature, the current function can only obtain its own return address for stack parsing. Therefore, the call stack information of the current function cannot be obtained. 230 231### APIs (C/C++) 232 233| Name| Description | 234| -------- | -------- | 235| OH_HiDebug_CreateBacktraceObject | Creates an object for stack backtracing and stack parsing.<br>Note: This API is supported since API version 20.| 236| OH_HiDebug_DestroyBacktraceObject | Destroys the object created by **OH_HiDebug_CreateBacktraceObject** for stack backtracing and stack parsing.<br>Note: This API is supported since API version 20.| 237| OH_HiDebug_BacktraceFromFp | Obtains the backtrace frame starting from the specified stack frame pointer.<br>Note: This API is supported since API version 20.| 238| OH_HiDebug_SymbolicAddress | Obtains detailed symbol information based on the specified program counter (PC).<br>Note: This API is supported since API version 20.| 239 240## Setting Resource Leak Detection Threshold 241 242HiDebug provides APIs for setting the threshold of system resource leak detection. You can customize this threshold as required. This API is used to assist in memory leak detection and feature development. For details, see [Analyzing Resource Leaks](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/resource-leak-guidelines). 243 244### APIs (ArkTS) 245 246| Name| Description| 247| -------- | -------- | 248| hidebug.setAppResourceLimit | Sets the threshold for triggering resource leak detection based on the number of file descriptors (FDs), number of threads, JavaScript memory, or native memory of an application.| 249 250## Managing GWP-Asan 251 252HiDebug provides the capabilities of enabling and disabling GWP-Asan and querying the number of days when GWP-Asan is enabled. 253 254### APIs (ArkTS) 255 256| Name| Description| 257| -------- | -------- | 258| hidebug.enableGwpAsanGrayscale | Enables GWP-Asan to detect illegal behaviors in heap memory usage.| 259| hidebug.disableGwpAsanGrayscale | Disables GWP-Asan.| 260| hidebug.getGwpAsanGrayscaleState | Obtains the number of remaining days for enabling GWP-Asan.| 261 262## Others 263 264HiDebug provides features such as obtaining the application debugging status and starting the dump information collection of system processes. 265 266### APIs (ArkTS) 267 268| Name| Description| 269| -------- | -------- | 270| hidebug.isDebugState | Obtains the debugging state of an application process. If the Ark or native layer of the application process is in debugging state, **true** is returned. Otherwise, **false** is returned.| 271| hidebug.getServiceDump | Obtains the dump information of a system service. This API can be called only by system applications.| 272 273## FAQs 274 275What should I do if the **OH_HiDebug_StartAppTraceCapture** and **startAppTraceCapture** APIs return local physical paths when capturing HiTrace logs? 276 277The returned path is the real physical path on the device. If you need to access the path in the application, convert the real physical path to the sandbox path by referring to [Mappings Between Application Sandbox Paths and Physical Paths](../file-management/app-sandbox-directory.md#mappings-between-application-sandbox-paths-and-physical-paths). 278 279Example: **/data/app/el2/100/log/com.example.myapplication/trace/com.example.myapplication_20250604_173158.trace** -> **/data/storage/el2/base/trace/com.example.myapplication_20250604_173158.trace** 280 281What should I do if the **OH_HiDebug_GetAppThreadCpuUsage** and **getAppThreadCpuUsage** APIs report that the CPU usage of a newly created thread is 0? 282 283If the calculation is based on the CPU usage, you need to obtain the current CPU running statistics and the calculation baseline value updated by HiView every 10 seconds. The new thread does not have a calculation baseline value. As a result, the CPU usage cannot be calculated, and 0 is returned by default. 284