• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.hidebug (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
10This module provides multiple methods for debugging and profiling applications. With these methods, you can obtain memory, CPU, GPU, and GC data, collect process trace and profiler data, and dump VM heap snapshots. Since most APIs of this module are both performance-consuming and time-consuming, and are defined based on the HiDebug module, you are advised to use these APIs only during the application debugging and profiling phases. If the APIs are required in other scenarios, evaluate the impact of the APIs on application performance.
11
12> **NOTE**
13>
14> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
15
16## Modules to Import
17
18```ts
19import { hidebug } from '@kit.PerformanceAnalysisKit';
20```
21
22## hidebug.getNativeHeapSize
23
24getNativeHeapSize(): bigint
25
26Obtains the total number of bytes occupied by the total space (**uordblks** + **fordblks**, which are obtained from **mallinfo**) held by a process, which is measured by the memory allocator.
27
28**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
29
30**Return value**
31
32| Type  | Description                                        |
33| ------ |--------------------------------------------|
34| bigint | Size of the memory occupied by the total space held by the process, in bytes.|
35
36**Example**
37
38```ts
39import { hidebug } from '@kit.PerformanceAnalysisKit';
40
41let nativeHeapSize: bigint = hidebug.getNativeHeapSize();
42```
43
44## hidebug.getNativeHeapAllocatedSize
45
46getNativeHeapAllocatedSize(): bigint
47
48Obtains the total number of bytes occupied by the total allocated space (**uordblks**, which is obtained from **mallinfo**) held by a process, which is measured by the memory allocator.
49
50**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
51
52**Return value**
53
54| Type  | Description                             |
55| ------ | --------------------------------- |
56| bigint | Size of the memory occupied by the total allocated space held by the process, in bytes.|
57
58
59**Example**
60```ts
61import { hidebug } from '@kit.PerformanceAnalysisKit';
62
63let nativeHeapAllocatedSize: bigint = hidebug.getNativeHeapAllocatedSize();
64```
65
66## hidebug.getNativeHeapFreeSize
67
68getNativeHeapFreeSize(): bigint
69
70Obtains 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.
71
72**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
73
74**Return value**
75
76| Type  | Description                           |
77| ------ | ----------------------------- |
78| bigint | Size of the memory occupied by the total free space held by the process, in bytes.|
79
80**Example**
81```ts
82import { hidebug } from '@kit.PerformanceAnalysisKit';
83
84let nativeHeapFreeSize: bigint = hidebug.getNativeHeapFreeSize();
85```
86
87## hidebug.getPss
88
89getPss(): bigint
90
91Obtains the size of the physical memory actually used by the application process. This API is implemented by summing up the values of **Pss** and **SwapPss** in the **/proc/{pid}/smaps_rollup** node.
92
93> **NOTE**
94>
95> Reading the **/proc/{pid}/smaps_rollup** node is time-consuming. Therefore, you are advised not to use this API in the main thread. You can use this API in the asynchronous thread started by calling [@ohos.taskpool](../apis-arkts/js-apis-taskpool.md) or [@ohos.worker](../apis-arkts/js-apis-worker.md) to avoid frame freezing.
96
97**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
98
99**Return value**
100
101| Type  | Description                     |
102| ------ | ------------------------- |
103| bigint | Size of the physical memory actually used by the application process, in KB.|
104
105**Example**
106```ts
107import { hidebug } from '@kit.PerformanceAnalysisKit';
108
109let pss: bigint = hidebug.getPss();
110```
111
112## hidebug.getVss<sup>11+</sup>
113
114getVss(): bigint
115
116Obtains the virtual set size used by the application process. This API is implemented by multiplying the value of **size** (number of memory pages) in the **/proc/{pid}/statm** node by the page size (4 KB per page).
117
118**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
119
120**Return value**
121
122| Type  | Description                                    |
123| ------ | ---------------------------------------- |
124| bigint | Virtual set size used by the application process, in KB.|
125
126**Example**
127
128```ts
129import { hidebug } from '@kit.PerformanceAnalysisKit';
130
131let vss: bigint = hidebug.getVss();
132```
133
134## hidebug.getSharedDirty
135
136getSharedDirty(): bigint
137
138Obtains the size of the shared dirty memory of a process. This API is implemented by reading the value of **Shared_Dirty** in the **/proc/{pid}/smaps_rollup** node.
139
140> **NOTE**
141>
142> Reading the **/proc/{pid}/smaps_rollup** node is time-consuming. Therefore, you are advised not to use this API in the main thread. You can use this API in the asynchronous thread started by calling [@ohos.taskpool](../apis-arkts/js-apis-taskpool.md) or [@ohos.worker](../apis-arkts/js-apis-worker.md) to avoid frame freezing.
143
144**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
145
146**Return value**
147
148| Type  | Description                      |
149| ------ | -------------------------- |
150| bigint | Size of the shared dirty memory of the process, in KB.|
151
152
153**Example**
154```ts
155import { hidebug } from '@kit.PerformanceAnalysisKit';
156
157let sharedDirty: bigint = hidebug.getSharedDirty();
158```
159
160## hidebug.getPrivateDirty<sup>9+</sup>
161
162getPrivateDirty(): bigint
163
164Obtains 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.
165
166> **NOTE**
167>
168> Reading the **/proc/{pid}/smaps_rollup** node is time-consuming. Therefore, you are advised not to use this API in the main thread. You can use this API in the asynchronous thread started by calling [@ohos.taskpool](../apis-arkts/js-apis-taskpool.md) or [@ohos.worker](../apis-arkts/js-apis-worker.md) to avoid frame freezing.
169
170**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
171
172**Return value**
173
174| Type  | Description                      |
175| ------ | -------------------------- |
176| bigint | Size of the private dirty memory of the process, in KB.|
177
178**Example**
179```ts
180import { hidebug } from '@kit.PerformanceAnalysisKit';
181
182let privateDirty: bigint = hidebug.getPrivateDirty();
183```
184
185## hidebug.getCpuUsage<sup>9+</sup>
186
187getCpuUsage(): number
188
189Obtains the CPU usage of a process.
190
191For example, if the CPU usage is **50%**, **0.5** is returned.
192
193> **NOTE**
194>
195> This API involves cross-process communication and takes a long time. To avoid performance problems, you are advised not to call this API in the main thread.
196
197**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
198
199**Return value**
200
201| Type  | Description                      |
202| ------ | -------------------------- |
203| number | CPU usage of the process.|
204
205
206**Example**
207```ts
208import { hidebug } from '@kit.PerformanceAnalysisKit';
209
210let cpuUsage: number = hidebug.getCpuUsage();
211```
212
213## hidebug.getServiceDump<sup>9+</sup>
214
215getServiceDump(serviceid: number, fd: number, args: Array\<string>) : void
216
217Obtains system service information.
218
219**Required permissions**: ohos.permission.DUMP (available only for system applications)
220
221**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
222
223**Parameters**
224
225| Name  | Type  | Mandatory| Description                        |
226| -------- | ------ | ---- |----------------------------|
227| serviceid | number | Yes  | Service ID used to obtain system service information.|
228| fd | number | Yes  | File descriptor to which data is written by the API.        |
229| args | Array&lt;string&gt; | Yes  | Parameter list of the **Dump** API of the system service.          |
230
231**Error codes**
232
233For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
234
235| ID| Error Message|
236| ------- | ----------------------------------------------------------------- |
237| 401 | the parameter check failed,Possible causes:1.the parameter type error 2.the args parameter is not string array.  |
238| 11400101 | ServiceId invalid. The system ability does not exist.                                           |
239
240**Example**
241
242<!--code_no_check-->
243```ts
244import { fileIo } from '@kit.CoreFileKit';
245import { hidebug } from '@kit.PerformanceAnalysisKit';
246import { BusinessError } from '@kit.BasicServicesKit';
247
248let fileFd = -1;
249try {
250  // Obtain the context from the component and ensure that the return value of this.getUiContext().getHostContext() is UIAbilityContext.
251  let path: string = this.getUIContext().getHostContext()!.filesDir + "/serviceInfo.txt";
252  console.info("output path: " + path);
253  fileFd = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE).fd;
254  let serviceId: number = 10;
255  let args: Array<string> = new Array("allInfo");
256  hidebug.getServiceDump(serviceId, fileFd, args);
257} catch (error) {
258  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
259}
260
261if (fileFd >= 0) {
262  fileIo.closeSync(fileFd);
263}
264```
265
266## hidebug.startJsCpuProfiling<sup>9+</sup>
267
268startJsCpuProfiling(filename: string) : void
269
270Starts the VM profiling method. **startJsCpuProfiling(filename: string)** and **stopJsCpuProfiling()** are called in pairs. **startJsCpuProfiling(filename: string)** always occurs before **stopJsCpuProfiling()**. You are advised not to call either of these methods repeatedly. Otherwise, an exception may occur.
271
272**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
273
274**Parameters**
275
276| Name  | Type  | Mandatory| Description                                              |
277| -------- | ------ | ---- |--------------------------------------------------|
278| filename | string | Yes  | Custom file name of the sampling data. The .json file is generated in the **files** directory of the application based on the specified file name.|
279
280**Error codes**
281
282For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
283
284| ID| Error Message|
285| ------- | ----------------------------------------------------------------- |
286| 401 | the parameter check failed,Parameter type error.                        |
287
288**Example**
289
290```ts
291import { hidebug } from '@kit.PerformanceAnalysisKit';
292import { BusinessError } from '@kit.BasicServicesKit';
293
294try {
295  hidebug.startJsCpuProfiling("cpu_profiling");
296  // ...
297  hidebug.stopJsCpuProfiling();
298} catch (error) {
299  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
300}
301```
302
303## hidebug.stopJsCpuProfiling<sup>9+</sup>
304
305stopJsCpuProfiling() : void
306
307Stops the VM profiling method. **stopJsCpuProfiling()** and **startJsCpuProfiling(filename: string)** are called in pairs. **startJsCpuProfiling()** always occurs before **stopJsCpuProfiling()**. You are advised not to call either of these methods repeatedly. Otherwise, an exception may occur.
308
309**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
310
311**Example**
312
313```ts
314import { hidebug } from '@kit.PerformanceAnalysisKit';
315import { BusinessError } from '@kit.BasicServicesKit';
316
317try {
318  hidebug.startJsCpuProfiling("cpu_profiling");
319  // ...
320  hidebug.stopJsCpuProfiling();
321} catch (error) {
322  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
323}
324```
325
326## hidebug.dumpJsHeapData<sup>9+</sup>
327
328dumpJsHeapData(filename: string) : void
329
330Exports the heap data.
331
332> **NOTE**
333>
334> Exporting the VM heap is time-consuming, and this API is a synchronous API. Therefore, you are advised not to call this API in the release version. Otherwise, the application screen may freeze, affecting user experience.
335
336**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
337
338**Parameters**
339
340| Name  | Type  | Mandatory| Description                                           |
341| -------- | ------ | ---- | ----------------------------------------------- |
342| filename | string | Yes  | Custom file name of the sampling data. The .heapsnapshot file is generated in the **files** directory of the application based on the specified file name.|
343
344**Error codes**
345
346For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
347
348| ID| Error Message|
349| ------- | ----------------------------------------------------------------- |
350| 401 | the parameter check failed, Parameter type error.                      |
351
352**Example**
353
354```ts
355import { hidebug } from '@kit.PerformanceAnalysisKit';
356import { BusinessError } from '@kit.BasicServicesKit';
357
358try {
359  hidebug.dumpJsHeapData("heapData");
360} catch (error) {
361  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
362}
363```
364
365## hidebug.startProfiling<sup>(deprecated)</sup>
366
367startProfiling(filename: string) : void
368
369> **NOTE**
370>
371> This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9).
372
373Starts the VM profiling method. **startProfiling(filename: string)** and **stopProfiling()** are called in pairs. **startProfiling(filename: string)** always occurs before **stopProfiling()**. You are advised not to call either of these methods repeatedly. Otherwise, an exception may occur.
374
375**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
376
377**Parameters**
378
379| Name  | Type  | Mandatory| Description                                            |
380| -------- | ------ | ---- | ------------------------------------------------ |
381| filename | string | Yes  | Custom file name of the sampling data. The .json file is generated in the **files** directory of the application based on the specified file name.|
382
383**Example**
384
385```ts
386import { hidebug } from '@kit.PerformanceAnalysisKit';
387
388hidebug.startProfiling("cpuprofiler-20220216");
389// code block
390// ...
391// code block
392hidebug.stopProfiling();
393```
394
395## hidebug.stopProfiling<sup>(deprecated)</sup>
396
397stopProfiling() : void
398
399> **NOTE**
400>
401> This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9).
402
403Stops the VM profiling method. **stopProfiling()** and **startProfiling(filename: string)** are called in pairs. **startProfiling(filename: string)** always occurs before **stopProfiling()**. You are advised not to call either of these methods repeatedly. Otherwise, an exception may occur.
404
405**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
406
407**Example**
408
409```ts
410import { hidebug } from '@kit.PerformanceAnalysisKit';
411
412hidebug.startProfiling("cpuprofiler-20220216");
413// code block
414// ...
415// code block
416hidebug.stopProfiling();
417```
418
419## hidebug.dumpHeapData<sup>(deprecated)</sup>
420
421dumpHeapData(filename: string) : void
422
423> **NOTE**
424>
425> This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9).
426
427Exports the VM heap data and generates a **filename.heapsnapshot** file.
428
429**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
430
431**Parameters**
432
433| Name  | Type  | Mandatory| Description                                                     |
434| -------- | ------ | ---- |---------------------------------------------------------|
435| filename | string | Yes  | User-defined heap file name. The .heapsnapshot file is generated in the **files** directory of the application based on the specified file name.|
436
437**Example**
438
439```ts
440import { hidebug } from '@kit.PerformanceAnalysisKit';
441
442hidebug.dumpHeapData("heap-20220216");
443```
444
445## hidebug.getAppVMMemoryInfo<sup>12+</sup>
446
447getAppVMMemoryInfo(): VMMemoryInfo
448
449Obtains VM memory information.
450
451**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
452
453**Return value**
454
455| Type        | Description                                   |
456| -------------| --------------------------------------- |
457| [VMMemoryInfo](#vmmemoryinfo12) | VM memory information.|
458
459**Example**
460
461```ts
462import { hidebug } from '@kit.PerformanceAnalysisKit';
463
464let vmMemory: hidebug.VMMemoryInfo = hidebug.getAppVMMemoryInfo();
465console.info(`totalHeap = ${vmMemory.totalHeap}, heapUsed = ${vmMemory.heapUsed},` +
466  `allArraySize = ${vmMemory.allArraySize}` );
467```
468
469## hidebug.getAppThreadCpuUsage<sup>12+</sup>
470
471getAppThreadCpuUsage(): ThreadCpuUsage[]
472
473Obtains the CPU usage of application threads.
474
475> **NOTE**
476>
477> This API involves cross-process communication and takes a long time. To avoid performance problems, you are advised not to call this API in the main thread.
478
479**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
480
481**Return value**
482
483| Type            | Description                                                       |
484| -----------------| ------------------------------------------------------------|
485| [ThreadCpuUsage](#threadcpuusage12)[] | CPU usage of all threads of the current application process.|
486
487
488
489**Example**
490
491```ts
492import { hidebug } from '@kit.PerformanceAnalysisKit';
493
494let appThreadCpuUsage: hidebug.ThreadCpuUsage[] = hidebug.getAppThreadCpuUsage();
495for (let i = 0; i < appThreadCpuUsage.length; i++) {
496  console.info(`threadId=${appThreadCpuUsage[i].threadId}, cpuUsage=${appThreadCpuUsage[i].cpuUsage}`);
497}
498```
499
500## hidebug.startAppTraceCapture<sup>12+</sup>
501
502startAppTraceCapture(tags: number[], flag: TraceFlag, limitSize: number) : string
503
504Starts automatic trace collection in a specified scope. This API is a supplement to the [HiTrace](../../dfx/hitrace.md) module. The performance consumption during trace collection increases with the collection scope. Therefore, before using this API, you are advised to run the **hitrace** command to capture trace logs and select the key scope of trace collection to improve the API performance.
505
506**startAppTraceCapture()** and [stopAppTraceCapture()](#hidebugstopapptracecapture12) must be called in pairs. Repeat calling of **startAppTraceCapture()** will cause exceptions. Trace collection consumes a lot of performance resources. Therefore, call **stopAppTraceCapture()** immediately after trace collection is complete.
507
508When an application calls **startAppTraceCapture()** to collect trace data and the size of the data exceeds the value of **limitSize**, the system automatically calls **stopAppTraceCapture()** to stop trace collection. Therefore, if **limitSize** is set improperly, the generated trace data is insufficient for fault analysis. Therefore, you need to evaluate the value of **limitSize** as required.
509
510Evaluation method: limitSize = Expected trace collection duration x Unit trace traffic.
511
512Expected trace collection duration: You can determine the duration based on the fault scenario. The unit is second.
513
514Unit trace traffic: The size of trace data generated by an application per second. The recommended value is 300 KB/s. You are advised to use the actual value of your application. The unit is KB/s.
515
516To obtain the unit trace traffic of an application, you can call **startAppTraceCapture()** with **limitSize** set to the maximum value 500 MB. After **N** seconds, call **stopAppTraceCapture()** to stop the collection and check the size **S** (KB) of the trace data. The unit trace traffic is **S**/**N** (KB/s).
517
518**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
519
520**Parameters**
521
522| Name  | Type    | Mandatory| Description                                |
523| -------- | ------   | ---- |------------------------------------|
524| tags     | number[] | Yes  | Scope for trace collection. For details, see [tags](#hidebugtags12).  |
525| flag     | TraceFlag| Yes  | For details, see [TraceFlag](#traceflag12).       |
526| limitSize| number   | Yes  | Limit on the trace file size, in bytes. The maximum size of a single file is 500 MB.|
527
528**Return value**
529
530| Type            | Description           |
531| -----------------|---------------|
532| string           | Path of the trace file.|
533
534**Error codes**
535
536For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
537
538| ID| Error Message|
539| ------- | ----------------------------------------------------------------- |
540| 401 | Invalid argument, Possible causes:1.The limit parameter is too small 2.The parameter is not within the enumeration type 3.The parameter type error or parameter order error. |
541| 11400102 | Capture trace already enabled.                                         |
542| 11400103 | No write permission on the file.                                |
543| 11400104 | Abnormal trace status.                                 |
544
545**Example**
546
547```ts
548import { hidebug } from '@kit.PerformanceAnalysisKit';
549import { BusinessError } from '@kit.BasicServicesKit';
550
551let tags: number[] = [hidebug.tags.ABILITY_MANAGER, hidebug.tags.ARKUI];
552let flag: hidebug.TraceFlag = hidebug.TraceFlag.MAIN_THREAD;
553let limitSize: number = 1024 * 1024;
554
555try {
556  let fileName: string = hidebug.startAppTraceCapture(tags, flag, limitSize);
557  // code block
558  // ...
559  // code block
560  hidebug.stopAppTraceCapture();
561} catch (error) {
562  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
563}
564```
565
566## hidebug.stopAppTraceCapture<sup>12+</sup>
567
568stopAppTraceCapture() : void
569
570Stops application trace collection. Use [startAppTraceCapture()](#hidebugstartapptracecapture12) to start collection before calling this API. If this API is called before trace collection or it is repeatedly called, an exception will occur.
571
572If **startAppTraceCapture ()** is called without a properly specified **limitSize**, the size of the generated trace may exceed the **limitSize** value, causing the system to automatically call **stopAppTraceCapture()**. In this case, if **stopAppTraceCapture()** is called again, an error code 11400105 will be displayed.
573
574**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
575
576**Error codes**
577
578For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
579
580| ID| Error Message|
581| ------- | ----------------------------------------------------------------- |
582| 11400104 | The status of the trace is abnormal.                                |
583| 11400105 | No capture trace running.                                       |
584
585**Example**
586
587```ts
588import { hidebug } from '@kit.PerformanceAnalysisKit';
589import { BusinessError } from '@kit.BasicServicesKit';
590
591let tags: number[] = [hidebug.tags.ABILITY_MANAGER, hidebug.tags.ARKUI];
592let flag: hidebug.TraceFlag = hidebug.TraceFlag.MAIN_THREAD;
593let limitSize: number = 1024 * 1024;
594try {
595  let fileName: string = hidebug.startAppTraceCapture(tags, flag, limitSize);
596  // code block
597  // ...
598  // code block
599  hidebug.stopAppTraceCapture();
600} catch (error) {
601  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
602}
603```
604
605## hidebug.getAppMemoryLimit<sup>12+</sup>
606
607getAppMemoryLimit() : MemoryLimit
608
609Obtains the memory limit of an application process.
610
611**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
612
613**Return value**
614
615| Type | Description                     |
616| ------ | -------------------------- |
617| [MemoryLimit](#memorylimit12) | Memory limit of the application process.|
618
619**Example**
620
621```ts
622import { hidebug } from '@kit.PerformanceAnalysisKit';
623
624let appMemoryLimit:hidebug.MemoryLimit = hidebug.getAppMemoryLimit();
625```
626
627## hidebug.getSystemCpuUsage<sup>12+</sup>
628
629getSystemCpuUsage() : number
630
631Obtains the CPU usage of the system.
632
633For example, if the CPU usage of system resources is **50%**, **0.5** is returned.
634
635> **NOTE**
636>
637> This API involves cross-process communication and takes a long time. To avoid performance problems, you are advised not to call this API in the main thread.
638
639**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
640
641**Return value**
642
643| Type    | Description         |
644|--------|-------------|
645| number | CPU usage of the system.|
646
647**Error codes**
648
649For details about the error codes, see [HiDebug CPU Usage Error Codes](errorcode-hiviewdfx-hidebug-cpuusage.md).
650
651| ID| Error Message                                           |
652| ------- |-------------------------------------------------|
653| 11400104 | The status of the system CPU usage is abnormal. |
654
655**Example**
656```ts
657import { hidebug } from '@kit.PerformanceAnalysisKit';
658import { BusinessError } from '@kit.BasicServicesKit';
659
660try {
661  console.info(`getSystemCpuUsage: ${hidebug.getSystemCpuUsage()}`)
662} catch (error) {
663  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
664}
665```
666
667## hidebug.setAppResourceLimit<sup>12+</sup>
668
669setAppResourceLimit(type: string, value: number, enableDebugLog: boolean) : void
670
671Sets the number of FDs, number of threads, JS memory, or native memory limit of the application.
672
673This API is used to construct a memory leak. For details, see [Subscribing to Resource Leak Events (ArkTS)](../../dfx/hiappevent-watcher-resourceleak-events-arkts.md) and [Subscribing to Resource Leak Events (C/C++)](../../dfx/hiappevent-watcher-resourceleak-events-ndk.md).
674
675> **NOTE**
676>
677> This API is valid only when the **Developer options** is enabled.
678
679**Atomic service API**: This API can be used in atomic services since API version 12.
680
681**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
682
683**Parameters**
684
685| Name  | Type  | Mandatory| Description                                                                                                                                                                     |
686| -------- | ------ | ---- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
687| type | string |  Yes | Types of leak resources:<br>- pss_memory (native memory)<br>- js_heap (JavaScript heap memory)<br>- fd (file descriptor)<br>- thread (thread)                                                                           |
688| value | number |  Yes | Value range of the maximum values of the leak resource types:<br>- pss_memory: **[1024, 4 x 1024 x 1024]** (Unit: KB)<br>- js_heap: **[85, 95]** (85% to 95% of the upper size limit of the JS heap memory)<br>- fd: **[10, 10000]**<br>- thread: **[1, 1000]**|
689| enableDebugLog | boolean |  Yes | Whether to enable external debugging logs. Enable external debugging logs only in the grayscale version (test version released to a small number of users before the official version is released). Collecting debugging logs occupies a large number of CPU and memory resources, which may cause application smoothness problems.<br>The value **true** means to enable external debugging logs, and false means the opposite.<br>                                     |
690
691**Error codes**
692
693For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
694
695| ID| Error Message|
696| ------- | ----------------------------------------------------------------- |
697| 401 | Invalid argument, Possible causes:1.The limit parameter is too small 2.The parameter is not in the specified type 3.The parameter type error or parameter order error.  |
698| 11400104 | Set limit failed due to remote exception. |
699
700**Example**
701
702```ts
703import { hidebug } from '@kit.PerformanceAnalysisKit';
704import { BusinessError } from '@kit.BasicServicesKit';
705
706let type: string = 'js_heap';
707let value: number = 85;
708let enableDebugLog: boolean = false;
709try {
710  hidebug.setAppResourceLimit(type, value, enableDebugLog);
711} catch (error) {
712  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
713}
714```
715
716## hidebug.getAppNativeMemInfo<sup>12+</sup>
717
718getAppNativeMemInfo(): NativeMemInfo
719
720Obtains 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.
721
722**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
723
724> **NOTE**
725>
726> Reading the **/proc/{pid}/smaps_rollup** node takes a long time. You are advised to use the asynchronous API [hidebug.getAppNativeMemInfoAsync](#hidebuggetappnativememinfoasync20) to avoid frame loss or frame freezing.
727
728**Return value**
729
730| Type | Description                     |
731| ------ | -------------------------- |
732| [NativeMemInfo](#nativememinfo12) | Memory information of the application process.|
733
734**Example**
735
736```ts
737import { hidebug } from '@kit.PerformanceAnalysisKit';
738
739let nativeMemInfo: hidebug.NativeMemInfo = hidebug.getAppNativeMemInfo();
740console.info(`pss: ${nativeMemInfo.pss}, vss: ${nativeMemInfo.vss}, rss: ${nativeMemInfo.rss}, ` +
741  `sharedDirty: ${nativeMemInfo.sharedDirty}, privateDirty: ${nativeMemInfo.privateDirty}, ` +
742  `sharedClean: ${nativeMemInfo.sharedClean}, privateClean: ${nativeMemInfo.privateClean}`);
743```
744
745## hidebug.getAppNativeMemInfoAsync<sup>20+</sup>
746
747getAppNativeMemInfoAsync(): Promise&lt;NativeMemInfo&gt;
748
749Obtains the memory information of an application process in asynchronous mode. This API is implemented by reading data from the **/proc/{pid}/smaps_rollup and /proc/{pid}/statm** node.
750
751**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
752
753**Return value**
754
755| Type                                              | Description                     |
756|--------------------------------------------------| -------------------------- |
757| Promise&lt;[NativeMemInfo](#nativememinfo12)&gt; | Promise used to return the application process memory information.|
758
759**Example**
760
761```ts
762hidebug.getAppNativeMemInfoAsync().then((nativeMemInfo: hidebug.NativeMemInfo)=>{
763  console.info(`pss: ${nativeMemInfo.pss}, vss: ${nativeMemInfo.vss}, rss: ${nativeMemInfo.rss}, ` +
764    `sharedDirty: ${nativeMemInfo.sharedDirty}, privateDirty: ${nativeMemInfo.privateDirty}, ` +
765    `sharedClean: ${nativeMemInfo.sharedClean}, privateClean: ${nativeMemInfo.privateClean}`);
766});
767```
768
769## hidebug.getAppNativeMemInfoWithCache<sup>20+</sup>
770
771getAppNativeMemInfoWithCache(forceRefresh?: boolean): NativeMemInfo
772
773Obtains the memory information of the application process. This API uses the cache mechanism and has higher performance than the **getAppNativeMemInfo** API. The cache is valid for 5 minutes.
774
775> **NOTE**
776>
777> Reading **/proc/{pid}/smaps_rollup** is time-consuming. Therefore, you are advised not to use this API in the main thread. You can use @ohos.taskpool or @ohos.worker to enable asynchronous threads to avoid application freezing.
778
779**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
780
781**Parameters**
782
783| Name                    | Type     | Mandatory| Description                                                                                                    |
784|-------------------------|---------|----|--------------------------------------------------------------------------------------------------------|
785| forceRefresh         | boolean | No | Whether to ignore the cache validity and forcibly update the cache value. The default value is **false**.<br>The value **true** means to directly obtain the current memory data and update the cache value.<br>The value **false** means to directly return the cache value if the cache is valid and obtain the current memory data and update the cache value if the cache is invalid.|
786
787**Return value**
788
789| Type | Description                     |
790| ------ | -------------------------- |
791| [NativeMemInfo](#nativememinfo12) | Memory information of the application process.|
792
793**Example**
794
795```ts
796let nativeMemInfo: hidebug.NativeMemInfo = hidebug.getAppNativeMemInfoWithCache();
797console.info(`pss: ${nativeMemInfo.pss}, vss: ${nativeMemInfo.vss}, rss: ${nativeMemInfo.rss}, ` +
798  `sharedDirty: ${nativeMemInfo.sharedDirty}, privateDirty: ${nativeMemInfo.privateDirty}, ` +
799  `sharedClean: ${nativeMemInfo.sharedClean}, privateClean: ${nativeMemInfo.privateClean}`);
800```
801
802## hidebug.getSystemMemInfo<sup>12+</sup>
803
804getSystemMemInfo(): SystemMemInfo
805
806Obtains system memory information. This API is implemented by reading data from the **/proc/meminfo** node.
807
808**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
809
810**Return value**
811
812| Type | Description                     |
813| ------ | -------------------------- |
814| [SystemMemInfo](#systemmeminfo12) | System memory information.|
815
816**Example**
817
818```ts
819import { hidebug } from '@kit.PerformanceAnalysisKit';
820
821let systemMemInfo: hidebug.SystemMemInfo = hidebug.getSystemMemInfo();
822
823console.info(`totalMem: ${systemMemInfo.totalMem}, freeMem: ${systemMemInfo.freeMem}, ` +
824  `availableMem: ${systemMemInfo.availableMem}`);
825```
826
827## hidebug.getVMRuntimeStats<sup>12+</sup>
828
829getVMRuntimeStats(): GcStats
830
831Obtains the system [GC](../../arkts-utils/gc-introduction.md) statistics.
832
833**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
834
835**Return value**
836
837| Type                   | Description      |
838|-----------------------|----------|
839| [GcStats](#gcstats12) | System GC statistics.|
840
841**Example**
842
843```ts
844import { hidebug } from '@kit.PerformanceAnalysisKit';
845
846let vMRuntimeStats: hidebug.GcStats = hidebug.getVMRuntimeStats();
847console.info(`gc-count: ${vMRuntimeStats['ark.gc.gc-count']}`);
848console.info(`gc-time: ${vMRuntimeStats['ark.gc.gc-time']}`);
849console.info(`gc-bytes-allocated: ${vMRuntimeStats['ark.gc.gc-bytes-allocated']}`);
850console.info(`gc-bytes-freed: ${vMRuntimeStats['ark.gc.gc-bytes-freed']}`);
851console.info(`fullgc-longtime-count: ${vMRuntimeStats['ark.gc.fullgc-longtime-count']}`);
852```
853
854## hidebug.getVMRuntimeStat<sup>12+</sup>
855
856getVMRuntimeStat(item: string): number
857
858Obtains the specified system [GC](../../arkts-utils/gc-introduction.md) statistics based on parameters.
859
860**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
861
862**Parameters**
863
864| Name  | Type  | Mandatory| Description         |
865| -------- | ------ | ---- |-------------|
866| item | string | Yes  | Item of the GC statistics to be obtained.|
867
868**Return value**
869
870| Type    | Description                       |
871|--------|---------------------------|
872| number | System GC statistics returned based on the input parameters.|
873
874| Input Parameter                        | Return Value Description         |
875|------------------------------|----------------|
876| ark.gc.gc-count | Count of GC of the calling thread.    |
877| ark.gc.gc-time | GC time triggered by the calling thread, in milliseconds.|
878| ark.gc.gc-bytes-allocated | Memory size allocated to the Ark VM of the calling thread, in bytes.|
879| ark.gc.gc-bytes-freed | Memory freed by the GC of the calling thread, in bytes.|
880| ark.gc.fullgc-longtime-count | Count of long fullGC of the calling thread.|
881
882**Error codes**
883
884| ID| Error Message                                                                                                      |
885| ------- |------------------------------------------------------------------------------------------------------------|
886| 401 | Possible causes:1. Invalid parameter, a string parameter required. 2. Invalid parameter, unknown property. |
887
888**Example**
889
890```ts
891import { hidebug } from '@kit.PerformanceAnalysisKit';
892import { BusinessError } from '@kit.BasicServicesKit';
893
894try {
895  console.info(`gc-count: ${hidebug.getVMRuntimeStat('ark.gc.gc-count')}`);
896  console.info(`gc-time: ${hidebug.getVMRuntimeStat('ark.gc.gc-time')}`);
897  console.info(`gc-bytes-allocated: ${hidebug.getVMRuntimeStat('ark.gc.gc-bytes-allocated')}`);
898  console.info(`gc-bytes-freed: ${hidebug.getVMRuntimeStat('ark.gc.gc-bytes-freed')}`);
899  console.info(`fullgc-longtime-count: ${hidebug.getVMRuntimeStat('ark.gc.fullgc-longtime-count')}`);
900} catch (error) {
901  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
902}
903```
904
905## MemoryLimit<sup>12+</sup>
906
907Defines the memory limit of the application process.
908
909**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
910
911| Name     | Type  | Read Only| Optional| Description        |
912| --------- | ------ | --|----| ------------ |
913| rssLimit    | bigint |  No | No | Limit on the resident set size, in KB.    |
914| vssLimit  | bigint |  No | No | Limit on the virtual memory size, in KB.      |
915| vmHeapLimit | bigint |  No | No | Limit on the JS VM heap size of the calling thread, in KB.|
916| vmTotalHeapSize | bigint |  No | No | Size limit of the JS heap memory of the process, in KB. |
917
918## VMMemoryInfo<sup>12+</sup>
919
920Describes the VM memory information.
921
922**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
923
924| Name              | Type   | Read Only| Optional| Description                               |
925| -------------------| ------- | ---|----| ---------------------------------- |
926| totalHeap          | bigint  | No | No | Total heap size of the current VM, in KB.    |
927| heapUsed           | bigint  | No | No | Heap size used by the current VM, in KB.   |
928| allArraySize       | bigint  | No | No | Size of all array objects of the current VM, in KB.|
929
930## ThreadCpuUsage<sup>12+</sup>
931
932Describes the CPU usage of a thread.
933
934**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
935
936| Name              | Type   | Read Only| Optional| Description                               |
937| -------------------| ------- |----|----| ----------------------------------- |
938| threadId           | number  | No | No | Thread ID.     |
939| cpuUsage           | number  | No | No | CPU usage of the thread.|
940
941## hidebug.tags<sup>12+</sup>
942
943Enumerates the tags used in trace collection. You can use the [HiTrace](../../dfx/hitrace.md) commands to capture the trace data of a specified tag.
944
945> **NOTE**
946>
947> The following tag values are defined by the system and may change with the version upgrade. To avoid compatibility issues after the upgrade, use the tag names instead of the tag values in application development.
948
949**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
950
951| Name                    | Type   | Read Only | Description                                        |
952| -------------------------| ------- |-----|--------------------------------------------|
953| ABILITY_MANAGER          | number  | Yes| Capability management. The corresponding HiTrace command is **tagName:ability**.                 |
954| ARKUI                    | number  | Yes| ArkUI development framework. The corresponding HiTrace command is **tagName:ace**.               |
955| ARK                      | number  | Yes| JSVM VM. The corresponding HiTrace command is **tagName:ark**.                 |
956| BLUETOOTH                | number  | Yes| Bluetooth. The corresponding HiTrace command is **tagName:bluetooth**.                |
957| COMMON_LIBRARY           | number  | Yes| Common library subsystem. The corresponding HiTrace command is **tagName:commonlibrary**.        |
958| DISTRIBUTED_HARDWARE_DEVICE_MANAGER | number  | Yes| Distributed hardware device management. The corresponding HiTrace command is **tagName:devicemanager**.     |
959| DISTRIBUTED_AUDIO        | number  | Yes| Distributed audio. The corresponding HiTrace command is **tagName:daudio**.                |
960| DISTRIBUTED_CAMERA       | number  | Yes| Distributed camera. The corresponding HiTrace command is **tagName:dcamera**.               |
961| DISTRIBUTED_DATA         | number  | Yes| Distributed data management. The corresponding HiTrace command is **tagName:distributeddatamgr**.|
962| DISTRIBUTED_HARDWARE_FRAMEWORK | number  | Yes| Distributed hardware framework. The corresponding HiTrace command is **tagName:dhfwk**.                |
963| DISTRIBUTED_INPUT        | number  | Yes| Distributed input. The corresponding HiTrace command is **tagName:dinput**.                |
964| DISTRIBUTED_SCREEN       | number  | Yes| Distributed screen. The corresponding HiTrace command is **tagName:dscreen**.               |
965| DISTRIBUTED_SCHEDULER    | number  | Yes| Distributed scheduler. The corresponding HiTrace command is **tagName:dsched**.               |
966| FFRT                     | number  | Yes| FFRT task. The corresponding HiTrace command is **tagName:ffrt**.                 |
967| FILE_MANAGEMENT          | number  | Yes| File management system. The corresponding HiTrace command is **tagName:filemanagement**.       |
968| GLOBAL_RESOURCE_MANAGER  | number  | Yes| Global resource management. The corresponding HiTrace command is **tagName:gresource**.            |
969| GRAPHICS                 | number  | Yes| Graphics module. The corresponding HiTrace command is **tagName:graphic**.                |
970| HDF                      | number  | Yes| HDF subsystem. The corresponding HiTrace command is **tagName:hdf**.                  |
971| MISC                     | number  | Yes| MISC module. The corresponding HiTrace command is **tagName:misc**.                 |
972| MULTIMODAL_INPUT         | number  | Yes| Multi-modal input module. The corresponding HiTrace command is **tagName:multimodalinput**.     |
973| NET                      | number  | Yes| Network. The corresponding HiTrace command is **tagName:net**.                      |
974| NOTIFICATION             | number  | Yes| Notification module. The corresponding HiTrace command is **tagName:notification**.           |
975| NWEB                     | number  | Yes| Nweb. The corresponding HiTrace command is **tagName:nweb**.                   |
976| OHOS                     | number  | Yes| OHOS. The corresponding HiTrace command is **tagName:ohos**.                 |
977| POWER_MANAGER            | number  | Yes| Power management. The corresponding HiTrace command is **tagName:power**.                  |
978| RPC                      | number  | Yes| RPC. The corresponding HiTrace command is **tagName:rpc**.                     |
979| SAMGR                    | number  | Yes| System capability management. The corresponding HiTrace command is **tagName:samgr**.                |
980| WINDOW_MANAGER           | number  | Yes| Window management. The corresponding HiTrace command is **tagName:window**.                 |
981| AUDIO                    | number  | Yes| Audio module. The corresponding HiTrace command is **tagName:zaudio**.                 |
982| CAMERA                   | number  | Yes| Camera module. The corresponding HiTrace command is **tagName:zcamera**.                |
983| IMAGE                    | number  | Yes| Image module. The corresponding HiTrace command is **tagName:zimage**.                 |
984| MEDIA                    | number  | Yes| Media module. The corresponding HiTrace command is **tagName:zmedia**.                 |
985
986## NativeMemInfo<sup>12+</sup>
987
988Describes memory information of the application process.
989
990**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
991
992| Name     | Type  | Read Only | Optional| Description                                                                            |
993| --------- | ------ | --|----|--------------------------------------------------------------------------------|
994| pss  | bigint |  No | No | Size of the occupied physical memory (including the proportionally allocated memory occupied by the shared library), in KB. The value of this parameter is obtained by summing up the values of **Pss** and **SwapPss** in the **/proc/{pid}/smaps_rollup** node.|
995| vss  | bigint |  No | No |  Size of the occupied virtual memory (including the memory occupied by the shared library), in KB. The value of this parameter is obtained by multiplying the value of **size** in the **/proc/{pid}/statm** node by **4**.               |
996| rss  | bigint |  No | No | Size of the occupied physical memory (including the memory occupied by the shared library), in KB. The value of this parameter is obtained by reading the value of **Rss** in the **/proc/{pid}/smaps_rollup** node.               |
997| sharedDirty  | bigint |  No | No | Size of the shared dirty memory, in KB. The value of this parameter is obtained by reading the value of **Shared_Dirty** in the **/proc/{pid}/smaps_rollup** node.                   |
998| privateDirty  | bigint |  No | No | Size of the private dirty memory, in KB. The value of this parameter is obtained by reading the value of **Private_Dirty** in the **/proc/{pid}/smaps_rollup** node.                  |
999| sharedClean  | bigint |  No | No | Size of the shared clean memory, in KB. The value of this parameter is obtained by reading the value of **Shared_Clean** in the **/proc/{pid}/smaps_rollup** node.                   |
1000| privateClean  | bigint |  No | No | Size of the private clean memory, in KB. The value of this parameter is obtained by reading the value of **Private_Clean** in the **/proc/{pid}/smaps_rollup** node.                 |
1001
1002## SystemMemInfo<sup>12+</sup>
1003
1004Describes the system memory information, including the total memory, free memory, and available memory.
1005
1006**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1007
1008| Name     | Type  | Read Only | Optional| Description                                             |
1009| --------- | ------ | ---- |---- |-------------------------------------------------|
1010| totalMem  | bigint |  No |   No |Total memory of the system, in KB. The value of this parameter is obtained by reading the value of **MemTotal** in the **/proc/meminfo** node.     |
1011| freeMem  | bigint |  No |   No |Free memory of the system, in KB. The value of this parameter is obtained by reading the value of **MemFree** in the **/proc/meminfo** node.     |
1012| availableMem  | bigint |  No |   No |Available memory of the system, in KB. The value of this parameter is obtained by reading the value of **MemAvailable** in the **/proc/meminfo** node.|
1013
1014## TraceFlag<sup>12+</sup>
1015
1016Describes types of trace collection threads, including the main thread and all threads.
1017
1018**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1019
1020| Name                        | Value| Description                   |
1021| --------------------------- |---| ----------------------- |
1022| MAIN_THREAD                 | 1 | The main thread of the application.|
1023| ALL_THREADS                 | 2 | All threads of the application.|
1024
1025## GcStats<sup>12+</sup>
1026
1027type GcStats = Record&lt;string, number&gt;
1028
1029Describes the key-value pair used to store GC statistics. This type does not support multi-thread operations. If this type is operated by multiple threads at the same time in an application, use a lock for it.
1030
1031**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1032
1033| Type     | Description                         |
1034| -----------| ---------------------------- |
1035| Record&lt;string, number&gt;     | Key-value pair format used to store GC statistics.    |
1036
1037GcStats contains the following information:
1038
1039| Name                    | Type  | Description                     |
1040|-------------------------| ------ |------------------------- |
1041| ark.gc.gc-count         | number |  Count of GC of the calling thread.|
1042| ark.gc.gc-time          | number |  GC time triggered by the calling thread, in milliseconds.|
1043| ark.gc.gc-bytes-allocated | number | Memory size allocated to the Ark VM of the calling thread, in bytes.|
1044| ark.gc.gc-bytes-freed   | number | Memory freed by the GC of the calling thread, in bytes.|
1045| ark.gc.fullgc-longtime-count | number |  Count of long fullGC of the calling thread.|
1046
1047## JsRawHeapTrimLevel<sup>20+</sup>
1048
1049Enumerates the trimming levels of the heap snapshot.
1050
1051**TRIM_LEVEL_2** takes a longer time than **TRIM_LEVEL_1**. The threshold for screen freezing is 6 seconds. With **TRIM_LEVEL_1**, the trim duration stays below this threshold. When switched to **TRIM_LEVEL_2**, the duration may exceed 6s, triggering an **APP_FREEZE** (screen freeze event) and causing the system to kill the application; the trim level then reverts to **TRIM_LEVEL_1**.
1052
1053You are advised to use **TRIM_LEVEL_1** to ensure application stability and use **TRIM_LEVEL_2 **only when more complete trimming is required.
1054
1055**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1056
1057| Name        | Value  | Description                                                        |
1058| ------------ | ---- | ------------------------------------------------------------ |
1059| TRIM_LEVEL_1 | 0    | Level 1 trimming, mainly used for strings.                      |
1060| TRIM_LEVEL_2 | 1    | Level 2 trimming, which reduces the size of the object address identifier from 8 bytes to 4 bytes.|
1061
1062## hidebug.isDebugState<sup>12+</sup>
1063
1064isDebugState(): boolean
1065
1066Obtains the debugging state of an application process.
1067
1068**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1069
1070**Return value**
1071
1072| Type | Description                                                  |
1073| ------ |------------------------------------------------------|
1074| boolean | Whether the Ark or native layer of the application process is in the debugging state. The value **true** indicates that the layer is in the debugging state, and **false** indicates the opposite.|
1075
1076**Example**
1077
1078```ts
1079import { hidebug } from '@kit.PerformanceAnalysisKit';
1080
1081console.info(`isDebugState = ${hidebug.isDebugState()}`)
1082```
1083
1084## hidebug.getGraphicsMemory<sup>14+</sup>
1085
1086getGraphicsMemory(): Promise&lt;number&gt;
1087
1088Obtains the size of the GPU memory. This API uses a promise to return the result.
1089
1090**Atomic service API**: This API can be used in atomic services since API version 14.
1091
1092**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1093
1094**Return value**
1095
1096| Type                   | Description                          |
1097|-----------------------|------------------------------|
1098| Promise&lt;number&gt; | Size of the GPU memory, in KB.|
1099
1100**Error codes**
1101
1102| ID| Error Message|
1103| ------- | ----------------------------------------------------------------- |
1104| 11400104 | Failed to get the application memory due to a remote exception. |
1105
1106**Example**
1107
1108```ts
1109import { hidebug, hilog } from '@kit.PerformanceAnalysisKit';
1110import { BusinessError } from '@kit.BasicServicesKit';
1111
1112hidebug.getGraphicsMemory().then((ret: number) => {
1113  console.info(`graphicsMemory: ${ret}`)
1114}).catch((error: BusinessError) => {
1115  console.error(`error code: ${error.code}, error msg: ${error.message}`);
1116})
1117```
1118
1119## hidebug.getGraphicsMemorySync<sup>14+</sup>
1120
1121getGraphicsMemorySync(): number
1122
1123Obtains the size of the GPU memory synchronously.
1124
1125> **NOTE**
1126>
1127> This API involves multiple cross-process communications, which may take seconds. To avoid performance problems, you are advised to use the asynchronous API **getGraphicsMemory** instead of this API in the main thread.
1128
1129**Atomic service API**: This API can be used in atomic services since API version 14.
1130
1131**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1132
1133**Return value**
1134
1135| Type | Description            |
1136| ------ |----------------|
1137| number | Size of the GPU memory, in KB.|
1138
1139**Error codes**
1140
1141| ID| Error Message|
1142| ------- | ----------------------------------------------------------------- |
1143| 11400104 | Failed to get the application memory due to a remote exception. |
1144
1145**Example**
1146
1147```ts
1148import { hidebug } from '@kit.PerformanceAnalysisKit';
1149import { BusinessError } from '@kit.BasicServicesKit';
1150
1151try {
1152  console.info(`graphicsMemory: ${hidebug.getGraphicsMemorySync()}`)
1153} catch (error) {
1154  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
1155}
1156```
1157
1158## hidebug.dumpJsRawHeapData<sup>18+</sup>
1159
1160dumpJsRawHeapData(needGC?: boolean): Promise&lt;string&gt;
1161
1162Dumps the original heap snapshot of the VM for the current thread. The API uses a promise to return the path of the .rawheap file. You can use [rawheap-translator](../../tools/rawheap-translator.md) to convert the generated file into a .heapsnapshot file for parsing.
1163
1164> **NOTE**
1165>
1166> This API is resource-consuming. Therefore, the calling frequency and times are strictly limited. You need to delete the files immediately after processing them.
1167> You are advised to use this API only in the grayscale version of an application.
1168
1169**Atomic service API**: This API can be used in atomic services since API version 18.
1170
1171**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1172
1173**Parameters**
1174
1175| Name                    | Type     | Mandatory| Description                                         |
1176|-------------------------|---------|----|---------------------------------------------|
1177| needGC         | boolean | No | Whether GC is required before storing heap snapshots. The value **true** indicates that GC is required, and **false** indicates the opposite. The default value is **true**.|
1178
1179**Return value**
1180
1181| Type | Description                                                                                                  |
1182| ------ |------------------------------------------------------------------------------------------------------|
1183| Promise&lt;string&gt; | Path of the generated snapshot file. ([Application Sandbox](../../file-management/app-sandbox-directory.md#application-file-directory-and-application-file-path))|
1184
1185**Error codes**
1186
1187For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
1188
1189| ID   | Error Message|
1190|----------| ----------------------------------------------------------------- |
1191| 11400106 | Quota exceeded. |
1192| 11400107 | Fork operation failed. |
1193| 11400108 | Failed to wait for the child process to finish. |
1194| 11400109 | Timeout while waiting for the child process to finish. |
1195| 11400110 | Disk remaining space too low. |
1196| 11400111 | Napi interface call exception. |
1197| 11400112 | Repeated data dump. |
1198| 11400113 | Failed to create dump file. |
1199
1200**Example**
1201
1202```ts
1203import { hidebug } from '@kit.PerformanceAnalysisKit';
1204import { BusinessError } from '@kit.BasicServicesKit';
1205hidebug.dumpJsRawHeapData().then((filePath: string) => {
1206  console.info(`dumpJsRawHeapData success and generated file path is ${filePath}`)
1207}).catch((error: BusinessError) => {
1208  console.error(`error code: ${error.code}, error msg: ${error.message}`);
1209})
1210```
1211
1212## hidebug.enableGwpAsanGrayscale<sup>20+</sup>
1213
1214enableGwpAsanGrayscale(options?: GwpAsanOptions, duration?: number): void
1215
1216Enables GWP-Asan to detect illegal behaviors in heap memory usage.
1217
1218This API is used to dynamically configure and enable GWP-Asan to adapt to the custom GWP-Asan detection policy. The configuration takes effect after the application is restarted.
1219
1220For details about GWP-Asan, see [Using GWP-Asan to Detect Memory Errors](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-stability-gwpasan-detection).
1221
1222> **NOTE**
1223>
1224> 1. If more than 20 applications have been enabled during device running, this API will fail to be called and an error code will be thrown.
1225> 2. To prevent abnormal application exit, use **try-catch** to capture exceptions.
1226
1227**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1228
1229**Parameters**
1230
1231| Name  | Type  | Mandatory| Description  |
1232|---------|---------|--------|-----|
1233|options | [GwpAsanOptions](#gwpasanoptions20) | No| Configuration options of GWP-Asan. If no parameter is set, the default value is used.|
1234|duration | number | No| GWP-Asan duration. The default value is 7 days. The value must be a positive integer.|
1235
1236**Error codes**
1237
1238For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
1239
1240| ID   | Error Message|
1241|----------| ----------------------------------------------------------------- |
1242| 11400114 | The number of GWP-ASAN applications of this device overflowed after last boot. |
1243
1244**Example**:
1245
1246```ts
1247import { hidebug } from '@kit.PerformanceAnalysisKit';
1248import { BusinessError } from '@kit.BasicServicesKit';
1249
1250let options: hidebug.GwpAsanOptions = {
1251  alwaysEnabled: true,
1252  sampleRate: 2500,
1253  maxSimutaneousAllocations: 5000,
1254};
1255let duration: number = 4;
1256
1257try {
1258  hidebug.enableGwpAsanGrayscale(options, duration);
1259  console.info(`Succeeded in enabling GWP-Asan.`);
1260} catch (error) {
1261  const err: BusinessError = error as BusinessError;
1262  console.error(`Failed to enable GWP-Asan. Code: ${err.code}, message: ${err.message}`);
1263}
1264```
1265## GwpAsanOptions<sup>20+</sup>
1266Defines configuration options of GWP-Asan. You can configure whether to enable GWP-Asan, the sampling frequency, and the maximum number of allocated slots.
1267
1268**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1269
1270| Name        | Type | Read Only | Optional| Description|
1271|--------------|------|-------|-------|-----|
1272|alwaysEnabled | boolean | No | Yes| Whether to always enable GWP-Asan. The value **true** means to always enable GWP-Asan.<br>The value **false** means to enable GWP-Asan at a probability of 1/128.<br> The default value is **false**.|
1273|sampleRate    |number| No |Yes|Sampling rate of GWP-Asan. The default value is **2500**. The value must be a positive integer greater than 0. If the value is a decimal, it is rounded up.<br> GWP-Asan performs sampling on the allocated memory at a probability of 1/**sampleRate**.|
1274|maxSimutaneousAllocations|number|No|Yes|Maximum number of allocated slots. The default value is **1000**. The value must be a positive integer greater than 0. If the value is a decimal, it is rounded up.<br>When the slots are used up, the newly allocated memory is no longer monitored.<br>After the used memory is released, the slots occupied by the memory are automatically reused to facilitate subsequent memory monitoring.|
1275
1276## hidebug.disableGwpAsanGrayscale<sup>20+</sup>
1277disableGwpAsanGrayscale(): void
1278
1279Disables GWP-Asan. This API is used to cancel the custom configuration and restore the default parameter [GwpAsanOptions](#gwpasanoptions20).
1280
1281**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1282
1283**Example**:
1284
1285```ts
1286import { hidebug } from '@kit.PerformanceAnalysisKit';
1287
1288hidebug.disableGwpAsanGrayscale();
1289```
1290
1291## hidebug.getGwpAsanGrayscaleState<sup>20+</sup>
1292getGwpAsanGrayscaleState(): number
1293
1294Obtains the number of remaining days for enabling GWP-Asan.
1295
1296**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1297
1298**Return value**
1299
1300| Type| Description|
1301|-----------|-------------|
1302| number    |Number of remaining days for enabling GWP-Asan. If GWP-Asan is disabled, **0** is returned.|
1303
1304**Example**:
1305
1306```ts
1307import { hidebug } from '@kit.PerformanceAnalysisKit';
1308
1309let remainDays: number = hidebug.getGwpAsanGrayscaleState();
1310console.info(`remainDays: ${remainDays}`);
1311```
1312
1313## hidebug.setJsRawHeapTrimLevel<sup>20+</sup>
1314
1315setJsRawHeapTrimLevel(level: JsRawHeapTrimLevel): void
1316
1317Sets the trimming level of the original heap snapshot stored by the current process. Using **TRIM_LEVEL_2** for this API can effectively reduce the size of the heap snapshot file.
1318
1319> **NOTE**
1320>
1321> The default trimming level is **TRIM_LEVEL_1**. If **TRIM_LEVEL_2** is set, you need to use [rawheap-translator](../../tools/rawheap-translator.md) since API version 20 to convert the .rawheap file to the .heapsnapshot file. Otherwise, the conversion may fail.
1322>
1323> This API affects the result of [dumpJsRawHeapData](#hidebugdumpjsrawheapdata18).
1324
1325**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1326
1327| Name| Type                                       | Mandatory| Description                  |
1328| ------ | ------------------------------------------- | ---- | ---------------------- |
1329| level  | [JsRawHeapTrimLevel](#jsrawheaptrimlevel20) | Yes  | Trimming level for storing heap snapshots. The default value is **TRIM_LEVEL_1**.|
1330
1331**Example**
1332
1333```ts
1334import { hidebug } from '@kit.PerformanceAnalysisKit';
1335import { BusinessError } from '@kit.BasicServicesKit';
1336
1337hidebug.setJsRawHeapTrimLevel(TRIM_LEVEL_2);
1338}
1339```
1340