• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.hidebug (HiDebug)
2
3> **NOTE**
4>
5> 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.
6
7The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
8
9## Modules to Import
10
11```ts
12import { hidebug } from '@kit.PerformanceAnalysisKit';
13```
14
15## hidebug.getNativeHeapSize
16
17getNativeHeapSize(): bigint
18
19Obtains the size of heap memory (including the allocator metadata) held by a process, which is measured by the memory allocator.
20
21**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
22
23**Return value**
24
25| Type  | Description                       |
26| ------ | --------------------------- |
27| bigint | Size of the heap memory (including the allocator metadata) held by the process, in bytes.|
28
29**Example**
30
31```ts
32import { hidebug } from '@kit.PerformanceAnalysisKit';
33
34let nativeHeapSize: bigint = hidebug.getNativeHeapSize();
35```
36
37## hidebug.getNativeHeapAllocatedSize
38
39getNativeHeapAllocatedSize(): bigint
40
41Obtains the size of the heap memory allocated to a process service, which is measured by the memory allocator.
42
43**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
44
45**Return value**
46
47| Type  | Description                             |
48| ------ | --------------------------------- |
49| bigint | Size of the heap memory allocated to a process service, in bytes.|
50
51
52**Example**
53```ts
54import { hidebug } from '@kit.PerformanceAnalysisKit';
55
56let nativeHeapAllocatedSize: bigint = hidebug.getNativeHeapAllocatedSize();
57```
58
59## hidebug.getNativeHeapFreeSize
60
61getNativeHeapFreeSize(): bigint
62
63Obtains the size of the cache memory held by the memory allocator.
64
65**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
66
67**Return value**
68
69| Type  | Description                           |
70| ------ | ------------------------------- |
71| bigint | Size of the cache memory held by the memory allocator, in bytes.|
72
73**Example**
74```ts
75import { hidebug } from '@kit.PerformanceAnalysisKit';
76
77let nativeHeapFreeSize: bigint = hidebug.getNativeHeapFreeSize();
78```
79
80## hidebug.getPss
81
82getPss(): bigint
83
84Obtains the size of the physical memory actually used by the application process.
85
86**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
87
88**Return value**
89
90| Type  | Description                     |
91| ------ | ------------------------- |
92| bigint | Size of the physical memory actually used by the application process, in KB.|
93
94**Example**
95```ts
96import { hidebug } from '@kit.PerformanceAnalysisKit';
97
98let pss: bigint = hidebug.getPss();
99```
100
101## hidebug.getVss<sup>11+<sup>
102
103getVss(): bigint
104
105Obtains the virtual set size used by the application process.
106
107**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
108
109**Return value**
110
111| Type  | Description                                    |
112| ------ | ---------------------------------------- |
113| bigint | Virtual set size used by the application process, in KB.|
114
115**Example**
116
117```ts
118import { hidebug } from '@kit.PerformanceAnalysisKit';
119
120let vss: bigint = hidebug.getVss();
121```
122
123## hidebug.getSharedDirty
124
125getSharedDirty(): bigint
126
127Obtains the size of the shared dirty memory of a process.
128
129**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
130
131**Return value**
132
133| Type  | Description                      |
134| ------ | -------------------------- |
135| bigint | Size of the shared dirty memory of the process, in KB.|
136
137
138**Example**
139```ts
140import { hidebug } from '@kit.PerformanceAnalysisKit';
141
142let sharedDirty: bigint = hidebug.getSharedDirty();
143```
144
145## hidebug.getPrivateDirty<sup>9+<sup>
146
147getPrivateDirty(): bigint
148
149Obtains the size of the private dirty memory of a process.
150
151**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
152
153**Return value**
154
155| Type  | Description                      |
156| ------ | -------------------------- |
157| bigint | Size of the private dirty memory of the process, in KB.|
158
159**Example**
160```ts
161import { hidebug } from '@kit.PerformanceAnalysisKit';
162
163let privateDirty: bigint = hidebug.getPrivateDirty();
164```
165
166## hidebug.getCpuUsage<sup>9+<sup>
167
168getCpuUsage(): number
169
170Obtains the CPU usage of a process.
171
172For example, if the CPU usage is **50%**, **0.5** is returned.
173
174**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
175
176**Return value**
177
178| Type  | Description                      |
179| ------ | -------------------------- |
180| number | CPU usage of the process.|
181
182
183**Example**
184```ts
185import { hidebug } from '@kit.PerformanceAnalysisKit';
186
187let cpuUsage: number = hidebug.getCpuUsage();
188```
189
190## hidebug.getServiceDump<sup>9+<sup>
191
192getServiceDump(serviceid : number, fd : number, args : Array\<string>) : void
193
194Obtains system service information.
195
196**Required permissions**: ohos.permission.DUMP (available only for system applications)
197
198**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
199
200**Parameters**
201
202| Name  | Type  | Mandatory| Description                                                        |
203| -------- | ------ | ---- | ------------------------------------------------------------ |
204| serviceid | number | Yes  | Obtains the system service information based on the specified service ID.|
205| fd | number | Yes  | File descriptor to which data is written by the API.|
206| args | Array\<string> | Yes  | Parameter list corresponding to the **Dump** API of the system service.|
207
208**Error codes**
209
210For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
211
212| ID| Error Message|
213| ------- | ----------------------------------------------------------------- |
214| 401 | the parameter check failed,Possible causes:1.the parameter type error 2.the args parameter is not string array  |
215| 11400101 | ServiceId invalid. The system ability does not exist.                                           |
216
217**Example**
218
219```ts
220import { fileIo } from '@kit.CoreFileKit';
221import { hidebug } from '@kit.PerformanceAnalysisKit';
222import { common } from '@kit.AbilityKit';
223import { BusinessError } from '@kit.BasicServicesKit';
224
225let applicationContext: common.Context | null = null;
226try {
227  let context = getContext() as common.UIAbilityContext;
228  applicationContext = context.getApplicationContext();
229} catch (error) {
230  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
231}
232
233let filesDir: string = applicationContext!.filesDir;
234let path: string = filesDir + "/serviceInfo.txt";
235console.info("output path: " + path);
236let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
237let serviceId: number = 10;
238let args: Array<string> = new Array("allInfo");
239
240try {
241  hidebug.getServiceDump(serviceId, file.fd, args);
242} catch (error) {
243  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
244}
245fileIo.closeSync(file);
246```
247
248## hidebug.startJsCpuProfiling<sup>9+</sup>
249
250startJsCpuProfiling(filename : string) : void
251
252Starts the profiling method. `startJsCpuProfiling()` and `stopJsCpuProfiling()` are called in pairs. `startJsCpuProfiling()` always occurs before `stopJsCpuProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
253
254**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
255
256**Parameters**
257
258| Name  | Type  | Mandatory| Description                                                        |
259| -------- | ------ | ---- | ------------------------------------------------------------ |
260| filename | string | Yes  | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
261
262**Error codes**
263
264For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
265
266| ID| Error Message|
267| ------- | ----------------------------------------------------------------- |
268| 401 | the parameter check failed,Parameter type error                        |
269
270**Example**
271
272```ts
273import { hidebug } from '@kit.PerformanceAnalysisKit';
274import { BusinessError } from '@kit.BasicServicesKit';
275
276try {
277  hidebug.startJsCpuProfiling("cpu_profiling");
278  // ...
279  hidebug.stopJsCpuProfiling();
280} catch (error) {
281  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
282}
283```
284
285## hidebug.stopJsCpuProfiling<sup>9+</sup>
286
287stopJsCpuProfiling() : void
288
289Stops the profiling method. `startJsCpuProfiling()` and `stopJsCpuProfiling()` are called in pairs. `startJsCpuProfiling()` always occurs before `stopJsCpuProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
290
291**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
292
293**Example**
294
295```ts
296import { hidebug } from '@kit.PerformanceAnalysisKit';
297import { BusinessError } from '@kit.BasicServicesKit';
298
299try {
300  hidebug.startJsCpuProfiling("cpu_profiling");
301  // ...
302  hidebug.stopJsCpuProfiling();
303} catch (error) {
304  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
305}
306```
307
308## hidebug.dumpJsHeapData<sup>9+</sup>
309
310dumpJsHeapData(filename : string) : void
311
312Exports the heap data.
313
314**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
315
316**Parameters**
317
318| Name  | Type  | Mandatory| Description                                                        |
319| -------- | ------ | ---- | ------------------------------------------------------------ |
320| filename | string | Yes  | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
321
322**Error codes**
323
324For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
325
326| ID| Error Message|
327| ------- | ----------------------------------------------------------------- |
328| 401 | the parameter check failed, Parameter type error                      |
329
330**Example**
331
332```ts
333import { hidebug } from '@kit.PerformanceAnalysisKit';
334import { BusinessError } from '@kit.BasicServicesKit';
335
336try {
337  hidebug.dumpJsHeapData("heapData");
338} catch (error) {
339  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
340}
341```
342
343## hidebug.startProfiling<sup>(deprecated)</sup>
344
345startProfiling(filename : string) : void
346
347> **NOTE**
348> This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9).
349
350Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
351
352**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
353
354**Parameters**
355
356| Name  | Type  | Mandatory| Description                                                        |
357| -------- | ------ | ---- | ------------------------------------------------------------ |
358| filename | string | Yes  | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
359
360**Example**
361
362```ts
363import { hidebug } from '@kit.PerformanceAnalysisKit';
364
365hidebug.startProfiling("cpuprofiler-20220216");
366// code block
367// ...
368// code block
369hidebug.stopProfiling();
370```
371
372## hidebug.stopProfiling<sup>(deprecated)</sup>
373
374stopProfiling() : void
375
376> **NOTE**
377> This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9).
378
379Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
380
381**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
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.dumpHeapData<sup>(deprecated)</sup>
396
397dumpHeapData(filename : string) : void
398
399> **NOTE**
400> This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9).
401
402Exports the heap data.
403
404**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
405
406**Parameters**
407
408| Name  | Type  | Mandatory| Description                                                        |
409| -------- | ------ | ---- | ------------------------------------------------------------ |
410| filename | string | Yes  | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
411
412**Example**
413
414```ts
415import { hidebug } from '@kit.PerformanceAnalysisKit';
416
417hidebug.dumpHeapData("heap-20220216");
418```
419
420## hidebug.getAppVMMemoryInfo<sup>12+</sup>
421
422getAppVMMemoryInfo(): VMMemoryInfo
423
424Obtains VM memory information.
425
426**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
427
428**Return value**
429
430| Type        | Description                                   |
431| -------------| --------------------------------------- |
432| [VMMemoryInfo](#vmmemoryinfo12) | VM memory information.|
433
434**Example**
435
436```ts
437import { hidebug } from '@kit.PerformanceAnalysisKit';
438
439let vmMemory: hidebug.VMMemoryInfo = hidebug.getAppVMMemoryInfo();
440console.info(`totalHeap = ${vmMemory.totalHeap}, heapUsed = ${vmMemory.heapUsed},` +
441  `allArraySize = ${vmMemory.allArraySize}` );
442```
443
444## hidebug.getAppThreadCpuUsage<sup>12+</sup>
445
446getAppThreadCpuUsage(): ThreadCpuUsage[]
447
448Obtains the CPU usage of application threads.
449
450**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
451
452**Return value**
453
454| Type            | Description                                                       |
455| -----------------| ------------------------------------------------------------|
456| [ThreadCpuUsage](#threadcpuusage12)[] | CPU usage of all threads of the current application process.|
457
458
459
460**Example**
461
462```ts
463import { hidebug } from '@kit.PerformanceAnalysisKit';
464
465let appThreadCpuUsage: hidebug.ThreadCpuUsage[] = hidebug.getAppThreadCpuUsage();
466for (let i = 0; i < appThreadCpuUsage.length; i++) {
467  console.info(`threadId=${appThreadCpuUsage[i].threadId}, cpuUsage=${appThreadCpuUsage[i].cpuUsage}`);
468}
469```
470
471## hidebug.startAppTraceCapture<sup>12+</sup>
472
473startAppTraceCapture(tags : number[], flag: TraceFlag, limitSize: number) : string
474
475Starts automatic trace collection for a specified scope. This API is a supplement to the [hitrace](../../dfx/hitrace.md) module.
476The 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.
477
478**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.
479
480When 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 collected trace data is insufficient for fault analysis. Therefore, you need to evaluate the value of **limitSize** as required.
481
482Evaluation method: limitSize = Expected trace collection duration x Unit trace traffic.
483
484Expected trace collection duration: You can determine the duration based on the fault scenario. The unit is second.
485
486Unit trace traffic: The size of a trace 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.
487
488To obtain the unit trace traffic, 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 trace size (**S** KB). The unit trace traffic is S/N.
489
490**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
491
492**Parameters**
493
494| Name  | Type    | Mandatory| Description                                |
495| -------- | ------   | ---- |------------------------------------|
496| tags     | number[] | Yes  | Scope for trace collection. For details, see [tags](#hidebugtags12).  |
497| flag     | TraceFlag| Yes  | For details, see [TraceFlag](#traceflag12).       |
498| limitSize| number   | Yes  | Limit on the trace file size, in bytes. The maximum size of a single file is 500 MB.|
499
500**Return value**
501
502| Type            | Description           |
503| -----------------|---------------|
504| string           | Path of the trace file.|
505
506**Error codes**
507
508For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
509
510| ID| Error Message|
511| ------- | ----------------------------------------------------------------- |
512| 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|
513| 11400102 | Capture trace already enabled.                                         |
514| 11400103 | No write permission on the file.                                |
515| 11400104 | Abnormal trace status.                                 |
516
517**Example**
518
519```ts
520import { hidebug } from '@kit.PerformanceAnalysisKit';
521import { BusinessError } from '@kit.BasicServicesKit';
522
523let tags: number[] = [hidebug.tags.ABILITY_MANAGER, hidebug.tags.ARKUI];
524let flag: hidebug.TraceFlag = hidebug.TraceFlag.MAIN_THREAD;
525let limitSize: number = 1024 * 1024;
526
527try {
528  let fileName: string = hidebug.startAppTraceCapture(tags, flag, limitSize);
529  // code block
530  // ...
531  // code block
532  hidebug.stopAppTraceCapture();
533} catch (error) {
534  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
535}
536```
537
538## hidebug.stopAppTraceCapture<sup>12+</sup>
539
540stopAppTraceCapture() : void
541
542Stops 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.
543
544If **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.
545
546**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
547
548**Error codes**
549
550For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
551
552| ID| Error Message|
553| ------- | ----------------------------------------------------------------- |
554| 11400104 | The status of the trace is abnormal                                |
555| 11400105 |   No capture trace running                                       |
556
557**Example**
558
559```ts
560import { hidebug } from '@kit.PerformanceAnalysisKit';
561import { BusinessError } from '@kit.BasicServicesKit';
562
563let tags: number[] = [hidebug.tags.ABILITY_MANAGER, hidebug.tags.ARKUI];
564let flag: hidebug.TraceFlag = hidebug.TraceFlag.MAIN_THREAD;
565let limitSize: number = 1024 * 1024;
566try {
567  let fileName: string = hidebug.startAppTraceCapture(tags, flag, limitSize);
568  // code block
569  // ...
570  // code block
571  hidebug.stopAppTraceCapture();
572} catch (error) {
573  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
574}
575```
576
577## hidebug.getAppMemoryLimit<sup>12+</sup>
578
579getAppMemoryLimit() : MemoryLimit
580
581Obtains the memory limit of the application process.
582
583**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
584
585**Return value**
586
587| Type | Description                     |
588| ------ | -------------------------- |
589| [MemoryLimit](#memorylimit12) | Defines the memory limit of the application process.|
590
591**Example**
592
593```ts
594import { hidebug } from '@kit.PerformanceAnalysisKit';
595
596let appMemoryLimit:hidebug.MemoryLimit = hidebug.getAppMemoryLimit();
597```
598
599## hidebug.getSystemCpuUsage<sup>12+</sup>
600
601getSystemCpuUsage() : number
602
603Obtains the CPU usage of the system.
604
605For example, if the CPU usage of system resources is **50%**, **0.5** is returned.
606
607**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
608
609**Return value**
610
611| Type    | Description         |
612|--------|-------------|
613| number | CPU usage of the system.|
614
615**Error codes**
616
617For details about the error codes, see [HiDebug CPU Usage Error Codes](errorcode-hiviewdfx-hidebug-cpuusage.md).
618
619| ID| Error Message                                           |
620| ------- |-------------------------------------------------|
621| 11400104 | The status of the system CPU usage is abnormal. |
622
623**Example**
624```ts
625import { hidebug } from '@kit.PerformanceAnalysisKit';
626import { BusinessError } from '@kit.BasicServicesKit';
627
628try {
629  console.info(`getSystemCpuUsage: ${hidebug.getSystemCpuUsage()}`)
630} catch (error) {
631  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
632}
633```
634
635## hidebug.setAppResourceLimit<sup>12+</sup>
636
637setAppResourceLimit(type: string, value: number, enableDebugLog: boolean) : void
638
639Sets the number of FDs, number of threads, JS memory, or native memory limit of the application.
640**NOTE**: This feature is available only after **Developer options** is enabled and the device is restarted.
641
642**Atomic service API**: This API can be used in atomic services since API version 12.
643
644**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
645
646**Parameters**
647
648| Name  | Type  | Mandatory| Description                                                        |
649| -------- | ------ | ---- | ------------------------------------------------------------ |
650| type | string |  Yes | Types of resource leak: pss_memory (native memory) leak, js_heap (js heap memory) leak, fd (file descriptor) leak, and thread (thread) leak.                                                                        |
651| value | number |  Yes | The maximum value of a resource leakage type. Value range: pss_memory leak **[1024, 4 * 1024 * 1024] (in KB)**, js_heap memory leak **[85, 95]** (85% to 95% of the upper limit of the JS heap memory), fd leak [10, 10000], thread leak **[1, 1000]**.|
652| enableDebugLog | boolean |  Yes | Whether to enable debug log. The default value is **false**. Set this parameter to **true** only in the dark version because collecting debug logs consumes too much CPU or memory.                                                                                    |
653
654**Error codes**
655
656For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
657
658| ID| Error Message|
659| ------- | ----------------------------------------------------------------- |
660| 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  |
661| 11400104 | Set limit failed due to remote exception |
662
663**Example**
664
665```ts
666import { hidebug } from '@kit.PerformanceAnalysisKit';
667import { BusinessError } from '@kit.BasicServicesKit';
668
669let type: string = 'js_heap';
670let value: number = 85;
671let enableDebugLog: boolean = false;
672try {
673  hidebug.setAppResourceLimit(type, value, enableDebugLog);
674} catch (error) {
675  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
676}
677```
678
679## hidebug.getAppNativeMemInfo<sup>12+</sup>
680
681getAppNativeMemInfo(): NativeMemInfo
682
683Obtains the memory information of the application process.
684
685**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
686
687**Return value**
688
689| Type | Description                     |
690| ------ | -------------------------- |
691| [NativeMemInfo](#nativememinfo12) | Memory information of the application process.|
692
693**Example**
694
695```ts
696import { hidebug } from '@kit.PerformanceAnalysisKit';
697
698let nativeMemInfo: hidebug.NativeMemInfo = hidebug.getAppNativeMemInfo();
699console.info(`pss: ${nativeMemInfo.pss}, vss: ${nativeMemInfo.vss}, rss: ${nativeMemInfo.rss}, ` +
700  `sharedDirty: ${nativeMemInfo.sharedDirty}, privateDirty: ${nativeMemInfo.privateDirty}, ` +
701  `sharedClean: ${nativeMemInfo.sharedClean}, privateClean: ${nativeMemInfo.privateClean}`);
702```
703
704## hidebug.getSystemMemInfo<sup>12+</sup>
705
706getSystemMemInfo(): SystemMemInfo
707
708Obtains system memory information.
709
710**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
711
712**Return value**
713
714| Type | Description                     |
715| ------ | -------------------------- |
716| [SystemMemInfo](#systemmeminfo12) | System memory information.|
717
718**Example**
719
720```ts
721import { hidebug } from '@kit.PerformanceAnalysisKit';
722
723let systemMemInfo: hidebug.SystemMemInfo = hidebug.getSystemMemInfo();
724
725console.info(`totalMem: ${systemMemInfo.totalMem}, freeMem: ${systemMemInfo.freeMem}, ` +
726  `availableMem: ${systemMemInfo.availableMem}`);
727```
728
729## hidebug.getVMRuntimeStats<sup>12+</sup>
730
731getVMRuntimeStats(): GcStats
732
733Obtains all system GC statistics.
734
735**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
736
737**Return value**
738
739| Type                   | Description      |
740|-----------------------|----------|
741| [GcStats](#gcstats12) | System GC statistics.|
742
743**Example**
744
745```ts
746import { hidebug } from '@kit.PerformanceAnalysisKit';
747
748let vMRuntimeStats: hidebug.GcStats = hidebug.getVMRuntimeStats();
749console.info(`gc-count: ${vMRuntimeStats['ark.gc.gc-count']}`);
750console.info(`gc-time: ${vMRuntimeStats['ark.gc.gc-time']}`);
751console.info(`gc-bytes-allocated: ${vMRuntimeStats['ark.gc.gc-bytes-allocated']}`);
752console.info(`gc-bytes-freed: ${vMRuntimeStats['ark.gc.gc-bytes-freed']}`);
753console.info(`fullgc-longtime-count: ${vMRuntimeStats['ark.gc.fullgc-longtime-count']}`);
754```
755
756## hidebug.getVMRuntimeStat<sup>12+</sup>
757
758getVMRuntimeStat(item : string): number
759
760Obtains the specified system GC statistics based on parameters.
761
762**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
763
764**Parameters**
765
766| Name  | Type  | Mandatory| Description         |
767| -------- | ------ | ---- |-------------|
768| item | string | Yes  | Item of the GC statistics to be obtained.|
769
770| Input Parameter                        | Return Value Description         |
771|------------------------------|----------------|
772| ark.gc.gc-count | Count of GC of the calling thread.    |
773| ark.gc.gc-time | GC time triggered by the calling thread, in milliseconds.|
774| ark.gc.gc-bytes-allocated | Memory size allocated to the Ark VM of the calling thread, in bytes.|
775| ark.gc.gc-bytes-freed | Memory freed by the GC of the calling thread, in bytes.|
776| ark.gc.fullgc-longtime-count | Count of long fullGC of the calling thread.|
777
778**Error codes**
779
780| ID| Error Message                                                                                                      |
781| ------- |------------------------------------------------------------------------------------------------------------|
782| 401 | Possible causes:1. Invalid parameter, a string parameter required. 2. Invalid parameter, unknown property. |
783
784**Example**
785
786```ts
787import { hidebug } from '@kit.PerformanceAnalysisKit';
788import { BusinessError } from '@kit.BasicServicesKit';
789
790try {
791  console.info(`gc-count: ${hidebug.getVMRuntimeStat('ark.gc.gc-count')}`);
792  console.info(`gc-time: ${hidebug.getVMRuntimeStat('ark.gc.gc-time')}`);
793  console.info(`gc-bytes-allocated: ${hidebug.getVMRuntimeStat('ark.gc.gc-bytes-allocated')}`);
794  console.info(`gc-bytes-freed: ${hidebug.getVMRuntimeStat('ark.gc.gc-bytes-freed')}`);
795  console.info(`fullgc-longtime-count: ${hidebug.getVMRuntimeStat('ark.gc.fullgc-longtime-count')}`);
796} catch (error) {
797  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
798}
799```
800
801## MemoryLimit<sup>12+</sup>
802
803Defines the memory limit of the application process.
804
805**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
806
807| Name     | Type  | Mandatory| Description        |
808| --------- | ------ | ---- | ------------ |
809| rssLimit    | bigint |  Yes | Limit on the resident set size, in KB.    |
810| vssLimit  | bigint |  Yes | Limit on the virtual memory size, in KB.      |
811| vmHeapLimit | bigint |  Yes | Limit on the JS VM heap size of the calling thread, in KB.|
812| vmTotalHeapSize | bigint |  Yes | Size limit of the JS heap memory of the process, in KB. |
813
814## VMMemoryInfo<sup>12+</sup>
815
816Describes the VM memory information.
817
818**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
819
820| Name              | Type   | Readable| Writable| Description                               |
821| -------------------| ------- | ---- | ---- | ---------------------------------- |
822| totalHeap          | bigint  | Yes  | No  | Total heap size of the current VM, in KB.    |
823| heapUsed           | bigint  | Yes  | No  | Heap size used by the current VM, in KB.   |
824| allArraySize       | bigint  | Yes  | No  | Size of all array objects of the current VM, in KB.|
825
826## ThreadCpuUsage<sup>12+</sup>
827
828Describes the CPU usage of a thread.
829
830**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
831
832| Name              | Type   | Readable| Writable| Description                               |
833| -------------------| ------- | ---- | ---- | ----------------------------------- |
834| threadId           | number  | Yes  | No  | Thread ID.     |
835| cpuUsage           | number  | Yes  | No  | CPU usage of the thread.|
836
837## hidebug.tags<sup>12+</sup>
838
839Enumerates the tags used in trace collection. You can use the [hitrace](../../dfx/hitrace.md) commands to capture the trace data of a specified tag for preview.
840
841Note that the 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.
842
843**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
844
845| Name                    | Type   | Read Only | Description                                        |
846| -------------------------| ------- |-----|--------------------------------------------|
847| ABILITY_MANAGER          | number  | Yes| Capability management. The corresponding HiTrace command is **tagName:ability**.                 |
848| ARKUI                    | number  | Yes| ArkUI development framework. The corresponding HiTrace command is **tagName:ace**.               |
849| ARK                      | number  | Yes| JSVM VM. The corresponding HiTrace command is **tagName:ark**.                 |
850| BLUETOOTH                | number  | Yes| Bluetooth. The corresponding HiTrace command is **tagName:bluetooth**.                |
851| COMMON_LIBRARY           | number  | Yes| Common library subsystem. The corresponding HiTrace command is **tagName:commonlibrary**.        |
852| DISTRIBUTED_HARDWARE_DEVICE_MANAGER | number  | Yes| Distributed hardware device management. The corresponding HiTrace command is **tagName:devicemanager**.     |
853| DISTRIBUTED_AUDIO        | number  | Yes| Distributed audio. The corresponding HiTrace command is **tagName:daudio**.                |
854| DISTRIBUTED_CAMERA       | number  | Yes| Distributed camera. The corresponding HiTrace command is **tagName:dcamera**.               |
855| DISTRIBUTED_DATA         | number  | Yes| Distributed data management. The corresponding HiTrace command is **tagName:distributeddatamgr**.|
856| DISTRIBUTED_HARDWARE_FRAMEWORK | number  | Yes| Distributed hardware framework. The corresponding HiTrace command is **tagName:dhfwk**.                |
857| DISTRIBUTED_INPUT        | number  | Yes| Distributed input. The corresponding HiTrace command is **tagName:dinput**.                |
858| DISTRIBUTED_SCREEN       | number  | Yes| Distributed screen. The corresponding HiTrace command is **tagName:dscreen**.               |
859| DISTRIBUTED_SCHEDULER    | number  | Yes| Distributed scheduler. The corresponding HiTrace command is **tagName:dsched**.               |
860| FFRT                     | number  | Yes| FFRT task. The corresponding HiTrace command is **tagName:ffrt**.                 |
861| FILE_MANAGEMENT          | number  | Yes| File management system. The corresponding HiTrace command is **tagName:filemanagement**.       |
862| GLOBAL_RESOURCE_MANAGER  | number  | Yes| Global resource management. The corresponding HiTrace command is **tagName:gresource**.            |
863| GRAPHICS                 | number  | Yes| Graphics module. The corresponding HiTrace command is **tagName:graphic**.                |
864| HDF                      | number  | Yes| HDF subsystem. The corresponding HiTrace command is **tagName:hdf**.                  |
865| MISC                     | number  | Yes| MISC module. The corresponding HiTrace command is **tagName:misc**.                 |
866| MULTIMODAL_INPUT         | number  | Yes| Multi-modal input module. The corresponding HiTrace command is **tagName:multimodalinput**.     |
867| NET                      | number  | Yes| Network. The corresponding HiTrace command is **tagName:net**.                      |
868| NOTIFICATION             | number  | Yes| Notification module. The corresponding HiTrace command is **tagName:notification**.           |
869| NWEB                     | number  | Yes| Nweb. The corresponding HiTrace command is **tagName:nweb**.                   |
870| OHOS                     | number  | Yes| OHOS. The corresponding HiTrace command is **tagName:ohos**.                 |
871| POWER_MANAGER            | number  | Yes| Power management. The corresponding HiTrace command is **tagName:power**.                  |
872| RPC                      | number  | Yes| RPC. The corresponding HiTrace command is **tagName:rpc**.                     |
873| SAMGR                    | number  | Yes| System capability management. The corresponding HiTrace command is **tagName:samgr**.                |
874| WINDOW_MANAGER           | number  | Yes| Window management. The corresponding HiTrace command is **tagName:window**.                 |
875| AUDIO                    | number  | Yes| Audio module. The corresponding HiTrace command is **tagName:zaudio**.                 |
876| CAMERA                   | number  | Yes| Camera module. The corresponding HiTrace command is **tagName:zcamera**.                |
877| IMAGE                    | number  | Yes| Image module. The corresponding HiTrace command is **tagName:zimage**.                 |
878| MEDIA                    | number  | Yes| Media module. The corresponding HiTrace command is **tagName:zmedia**.                 |
879
880## NativeMemInfo<sup>12+</sup>
881
882Describes memory information of the application process.
883
884**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
885
886| Name     | Type  | Mandatory| Description        |
887| --------- | ------ | ---- | ------------ |
888| pss  | bigint |  Yes | Size of the occupied physical memory (including the proportionally allocated memory occupied by the shared library), in KB.|
889| vss  | bigint |  Yes | Size of the occupied virtual memory (including the memory occupied by the shared library), in KB.     |
890| rss  | bigint |  Yes | Size of the occupied physical memory (including the memory occupied by the shared library), in KB.     |
891| sharedDirty  | bigint |  Yes | Size of the shared dirty memory, in KB.                  |
892| privateDirty  | bigint |  Yes | Size of the private dirty memory, in KB.                  |
893| sharedClean  | bigint |  Yes | Size of the shared clean memory, in KB.                 |
894| privateClean  | bigint |  Yes | Size of the private clean memory, in KB.                 |
895
896## SystemMemInfo<sup>12+</sup>
897
898Describes the system memory information.
899
900**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
901
902| Name     | Type  | Mandatory| Description        |
903| --------- | ------ | ---- | ------------ |
904| totalMem  | bigint |  Yes | Total memory of the system, in KB. |
905| freeMem  | bigint |  Yes | Free memory of the system, in KB.|
906| availableMem  | bigint |  Yes | Available memory of the system, in KB.|
907
908## TraceFlag<sup>12+</sup>
909
910Defines the type of the trace collection thread.
911
912**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
913
914| Name                        | Value| Description                   |
915| --------------------------- |---| ----------------------- |
916| MAIN_THREAD                 | 1 | The main thread of the application.|
917| ALL_THREADS                 | 2 | All threads of the application.|
918
919## GcStats<sup>12+</sup>
920
921type GcStats = Record&lt;string, number&gt;
922
923Key-value pair format used to store GC statistics. This type is not multi-thread safe. If a **GcStats** instance is operated by multiple threads at the same time in an application, use the lock mechanism for the instance.
924
925System capability: SystemCapability.HiviewDFX.HiProfiler.HiDebug
926
927| Type     | Description                         |
928| -----------| ---------------------------- |
929| Record&lt;string, number&gt;     | Indicates the value is in **Record** key-value pair format.    |
930
931**GcStats** contain the following key values:
932
933| Name                    | Type  | Description                     |
934|-------------------------| ------ |------------------------- |
935| ark.gc.gc-count         | number |  Count of GC of the calling thread.|
936| ark.gc.gc-time          | number |  GC time triggered by the calling thread, in milliseconds.|
937| ark.gc.gc-bytes-allocated | number | Memory size allocated to the Ark VM of the calling thread, in bytes.|
938| ark.gc.gc-bytes-freed   | number | Memory freed by the GC of the calling thread, in bytes.|
939| ark.gc.fullgc-longtime-count | number |  Count of long fullGC of the calling thread.|
940
941## hidebug.isDebugState<sup>12+</sup>
942
943isDebugState(): boolean
944
945Obtains whether an application process is being debugged. If the ark or native layer of the application process is being debugged, **true** is returned. Otherwise, **false** is returned.
946
947**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
948
949**Return value**
950
951| Type | Description                     |
952| ------ | -------------------------- |
953| boolean | Whether an application process is being debugged.|
954
955**Example**
956
957```ts
958import { hidebug } from '@kit.PerformanceAnalysisKit';
959
960console.info(`isDebugState = ${hidebug.isDebugState()}`)
961```
962
963## hidebug.getGraphicsMemory<sup>14+</sup>
964
965getGraphicsMemory(): Promise&lt;number&gt;
966
967Obtains the size of the GPU memory. This API uses a promise to return the result.
968
969**Atomic service API**: This API can be used in atomic services since API version 14.
970
971**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
972
973**Return value**
974
975| Type                   | Description                          |
976|-----------------------|------------------------------|
977| Promise&lt;number&gt; | Size of the GPU memory, in KB.|
978
979**Error codes**
980
981| ID| Error Message|
982| ------- | ----------------------------------------------------------------- |
983| 11400104 | Failed to get the application memory due to a remote exception. |
984
985**Example**
986
987```ts
988import { hidebug, hilog } from '@kit.PerformanceAnalysisKit';
989import { BusinessError } from '@kit.BasicServicesKit';
990
991hidebug.getGraphicsMemory().then((ret: number) => {
992  console.info(`graphicsMemory: ${ret}`)
993}).catch((error: BusinessError) => {
994  console.error(`error code: ${error.code}, error msg: ${error.message}`);
995})
996```
997
998## hidebug.getGraphicsMemorySync<sup>14+</sup>
999
1000getGraphicsMemorySync(): number
1001
1002Obtains the size of the GPU memory. This API uses a synchronous callback to return the result.
1003
1004**Note**: This API involves multiple cross-process communications and may have performance problems. The asynchronous API **getGraphicsMemory** is recommended.
1005
1006**Atomic service API**: This API can be used in atomic services since API version 14.
1007
1008**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1009
1010**Return value**
1011
1012| Type | Description            |
1013| ------ |----------------|
1014| number | Size of the GPU memory, in KB.|
1015
1016**Error codes**
1017
1018| ID| Error Message|
1019| ------- | ----------------------------------------------------------------- |
1020| 11400104 | Failed to get the application memory due to a remote exception. |
1021
1022**Example**
1023
1024```ts
1025import { hidebug } from '@kit.PerformanceAnalysisKit';
1026import { BusinessError } from '@kit.BasicServicesKit';
1027
1028try {
1029  console.info(`graphicsMemory: ${hidebug.getGraphicsMemorySync()}`)
1030} catch (error) {
1031  console.error(`error code: ${(error as BusinessError).code}, error msg: ${(error as BusinessError).message}`);
1032}
1033```
1034
1035## hidebug.dumpJsRawHeapData<sup>18+</sup>
1036
1037dumpJsRawHeapData(needGC?: boolean): Promise&lt;string&gt;
1038
1039Dumps the original heap snapshot of the VM for the calling thread. This API uses a promise to return the result.
1040
1041> **NOTE**
1042>
1043> When this API is used to dump snapshots, a large number of system resources are consumed. Therefore, the system strictly controls the calling frequency and times of this API. Generally, the file generated by this API is large. You are advised to delete the file immediately after processing it.
1044> You are advised to use this API only in the gray test version of your application. If it is used in the release version, the application smoothness may be affected.
1045
1046**Atomic service API**: This API can be used in atomic services since API version 18.
1047
1048**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
1049
1050| Name                    | Type     | Mandatory| Description                                      |
1051|-------------------------|---------|----|------------------------------------------|
1052| needGC         | boolean | No | Whether GC is required when heap snapshots are dumped. The default value is **true**. If this parameter is not specified, GC is triggered before dumping.|
1053
1054**Return value**
1055
1056| Type | Description                                                                                                  |
1057| ------ |------------------------------------------------------------------------------------------------------|
1058| Promise&lt;number&gt; | Path of the generated snapshot file. ([Application Sandbox](../../file-management/app-sandbox-directory.md#application-file-directory-and-application-file-path))|
1059
1060**Error codes**
1061
1062For details about the error codes, see [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md).
1063
1064| ID   | Error Message|
1065|----------| ----------------------------------------------------------------- |
1066| 401      | Invalid parameter. |
1067| 11400106 | Quota exceeded. |
1068| 11400107 | Fork operation failed. |
1069| 11400108 | Failed to wait for the child process to finish. |
1070| 11400109 | Timeout while waiting for the child process to finish. |
1071| 11400110 | Disk remaining space too low. |
1072| 11400111 | Napi interface call exception. |
1073| 11400112 | Repeated data dump. |
1074| 11400113 | Failed to create dump file. |
1075
1076**Example**
1077
1078```ts
1079import { hidebug } from '@kit.PerformanceAnalysisKit';
1080import { BusinessError } from '@kit.BasicServicesKit';
1081hidebug.dumpJsRawHeapData().then((filePath: string) => {
1082  console.info(`dumpJsRawHeapData success and generated file path is ${filePath}`)
1083}).catch((error: BusinessError) => {
1084  console.error(`error code: ${error.code}, error msg: ${error.message}`);
1085})
1086```
1087