• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import {
17  ArkTSConfig,
18  CreateSessionRequest, FFRTConfig,
19  FpsConfig,
20  HiebpfConfig,
21  HilogConfig,
22  HiperfPluginConfig,
23  levelFromJSON,
24  MemoryConfig,
25  NativeHookConfig,
26  ProfilerSessionConfig,
27  ProfilerSessionConfigBufferConfig,
28  ProfilerSessionConfigBufferConfigPolicy,
29  ProfilerSessionConfigMode,
30  sysMeminfoTypeFromJSON,
31  sysVMeminfoTypeFromJSON,
32  TracePluginConfig,
33} from './setting/bean/ProfilerServiceTypes';
34import { SpRecordSetting } from './setting/SpRecordSetting';
35import { SpVmTracker } from './setting/SpVmTracker';
36import { SpProbesConfig } from './setting/SpProbesConfig';
37import { info } from '../../log/Log';
38import { SpAllocations } from './setting/SpAllocations';
39import { SpApplication } from '../SpApplication';
40import { PerfConfig, SpRecordPerf } from './setting/SpRecordPerf';
41import { SpFileSystem } from './setting/SpFileSystem';
42import { SpSdkConfig } from './setting/SpSdkConfig';
43import { SpHisysEvent } from './setting/SpHisysEvent';
44import { SpArkTs } from './setting/SpArkTs';
45import { SpHilogRecord } from './setting/SpHilogRecord';
46import { SpFFRTConfig } from './setting/SpFFRTConfig';
47
48export const MEM_INFO = [
49  'MEMINFO_ACTIVE',
50  'MEMINFO_ACTIVE_ANON',
51  'MEMINFO_ACTIVE_FILE',
52  'MEMINFO_ANON_PAGES',
53  'MEMINFO_BUFFERS',
54  'MEMINFO_CACHED',
55  'MEMINFO_CMA_FREE',
56  'MEMINFO_CMA_TOTAL',
57  'MEMINFO_COMMIT_LIMIT',
58  'MEMINFO_COMMITED_AS',
59  'MEMINFO_DIRTY',
60  'MEMINFO_INACTIVE',
61  'MEMINFO_INACTIVE_ANON',
62  'MEMINFO_INACTIVE_FILE',
63  'MEMINFO_KERNEL_STACK',
64  'MEMINFO_MAPPED',
65  'MEMINFO_MEM_AVAILABLE',
66  'MEMINFO_MEM_FREE',
67  'MEMINFO_MEM_TOTAL',
68  'MEMINFO_MLOCKED',
69  'MEMINFO_PAGE_TABLES',
70  'MEMINFO_SHMEM',
71  'MEMINFO_SLAB',
72  'MEMINFO_SLAB_RECLAIMABLE',
73  'MEMINFO_SLAB_UNRECLAIMABLE',
74  'MEMINFO_SWAP_CACHED',
75  'MEMINFO_SWAP_FREE',
76  'MEMINFO_SWAP_TOTAL',
77  'MEMINFO_UNEVICTABLE',
78  'MEMINFO_VMALLOC_CHUNK',
79  'MEMINFO_VMALLOC_TOTAL',
80  'MEMINFO_VMALLOC_USED',
81  'MEMINFO_WRITEBACK',
82  'MEMINFO_KERNEL_RECLAIMABLE',
83  'PMEM_ACTIVE_PURG',
84  'PMEM_INACTIVE_PURG',
85  'PMEM_PINED_PURG',
86];
87
88export const VMEM_INFO = [
89  'VMEMINFO_UNSPECIFIED',
90  'VMEMINFO_NR_FREE_PAGES',
91  'VMEMINFO_NR_ALLOC_BATCH',
92  'VMEMINFO_NR_INACTIVE_ANON',
93  'VMEMINFO_NR_ACTIVE_ANON',
94  'VMEMINFO_NR_INACTIVE_FILE',
95  'VMEMINFO_NR_ACTIVE_FILE',
96  'VMEMINFO_NR_UNEVICTABLE',
97  'VMEMINFO_NR_MLOCK',
98  'VMEMINFO_NR_ANON_PAGES',
99  'VMEMINFO_NR_MAPPED',
100  'VMEMINFO_NR_FILE_PAGES',
101  'VMEMINFO_NR_DIRTY',
102  'VMEMINFO_NR_WRITEBACK',
103  'VMEMINFO_NR_SLAB_RECLAIMABLE',
104  'VMEMINFO_NR_SLAB_UNRECLAIMABLE',
105  'VMEMINFO_NR_PAGE_TABLE_PAGES',
106  'VMEMINFO_NR_KERNEL_STACK',
107  'VMEMINFO_NR_OVERHEAD',
108  'VMEMINFO_NR_UNSTABLE',
109  'VMEMINFO_NR_BOUNCE',
110  'VMEMINFO_NR_VMSCAN_WRITE',
111  'VMEMINFO_NR_VMSCAN_IMMEDIATE_RECLAIM',
112  'VMEMINFO_NR_WRITEBACK_TEMP',
113  'VMEMINFO_NR_ISOLATED_ANON',
114  'VMEMINFO_NR_ISOLATED_FILE',
115  'VMEMINFO_NR_SHMEM',
116  'VMEMINFO_NR_DIRTIED',
117  'VMEMINFO_NR_WRITTEN',
118  'VMEMINFO_NR_PAGES_SCANNED',
119  'VMEMINFO_WORKINGSET_REFAULT',
120  'VMEMINFO_WORKINGSET_ACTIVATE',
121  'VMEMINFO_WORKINGSET_NODERECLAIM',
122  'VMEMINFO_NR_ANON_TRANSPARENT_HUGEPAGES',
123  'VMEMINFO_NR_FREE_CMA',
124  'VMEMINFO_NR_SWAPCACHE',
125  'VMEMINFO_NR_DIRTY_THRESHOLD',
126  'VMEMINFO_NR_DIRTY_BACKGROUND_THRESHOLD',
127  'VMEMINFO_PGPGIN',
128  'VMEMINFO_PGPGOUT',
129  'VMEMINFO_PGPGOUTCLEAN',
130  'VMEMINFO_PSWPIN',
131  'VMEMINFO_PSWPOUT',
132  'VMEMINFO_PGALLOC_DMA',
133];
134
135export const VMEM_INFO_SECOND = [
136  'VMEMINFO_PGALLOC_NORMAL',
137  'VMEMINFO_PGALLOC_MOVABLE',
138  'VMEMINFO_PGFREE',
139  'VMEMINFO_PGACTIVATE',
140  'VMEMINFO_PGDEACTIVATE',
141  'VMEMINFO_PGFAULT',
142  'VMEMINFO_PGMAJFAULT',
143  'VMEMINFO_PGREFILL_DMA',
144  'VMEMINFO_PGREFILL_NORMAL',
145  'VMEMINFO_PGREFILL_MOVABLE',
146  'VMEMINFO_PGSTEAL_KSWAPD_DMA',
147  'VMEMINFO_PGSTEAL_KSWAPD_NORMAL',
148  'VMEMINFO_PGSTEAL_KSWAPD_MOVABLE',
149  'VMEMINFO_PGSTEAL_DIRECT_DMA',
150  'VMEMINFO_PGSTEAL_DIRECT_NORMAL',
151  'VMEMINFO_PGSTEAL_DIRECT_MOVABLE',
152  'VMEMINFO_PGSCAN_KSWAPD_DMA',
153  'VMEMINFO_PGSCAN_KSWAPD_NORMAL',
154  'VMEMINFO_PGSCAN_KSWAPD_MOVABLE',
155  'VMEMINFO_PGSCAN_DIRECT_DMA',
156  'VMEMINFO_PGSCAN_DIRECT_NORMAL',
157  'VMEMINFO_PGSCAN_DIRECT_MOVABLE',
158  'VMEMINFO_PGSCAN_DIRECT_THROTTLE',
159  'VMEMINFO_PGINODESTEAL',
160  'VMEMINFO_SLABS_SCANNED',
161  'VMEMINFO_KSWAPD_INODESTEAL',
162  'VMEMINFO_KSWAPD_LOW_WMARK_HIT_QUICKLY',
163  'VMEMINFO_KSWAPD_HIGH_WMARK_HIT_QUICKLY',
164  'VMEMINFO_PAGEOUTRUN',
165  'VMEMINFO_ALLOCSTALL',
166  'VMEMINFO_PGROTATED',
167  'VMEMINFO_DROP_PAGECACHE',
168  'VMEMINFO_DROP_SLAB',
169  'VMEMINFO_PGMIGRATE_SUCCESS',
170  'VMEMINFO_PGMIGRATE_FAIL',
171  'VMEMINFO_COMPACT_MIGRATE_SCANNED',
172  'VMEMINFO_COMPACT_FREE_SCANNED',
173  'VMEMINFO_COMPACT_ISOLATED',
174  'VMEMINFO_COMPACT_STALL',
175  'VMEMINFO_COMPACT_FAIL',
176  'VMEMINFO_COMPACT_SUCCESS',
177  'VMEMINFO_COMPACT_DAEMON_WAKE',
178  'VMEMINFO_UNEVICTABLE_PGS_CULLED',
179  'VMEMINFO_UNEVICTABLE_PGS_SCANNED',
180  'VMEMINFO_UNEVICTABLE_PGS_RESCUED',
181  'VMEMINFO_UNEVICTABLE_PGS_MLOCKED',
182  'VMEMINFO_UNEVICTABLE_PGS_MUNLOCKED',
183];
184
185export const VMEM_INFO_THIRD = [
186  'VMEMINFO_UNEVICTABLE_PGS_CLEARED',
187  'VMEMINFO_UNEVICTABLE_PGS_STRANDED',
188  'VMEMINFO_NR_ZSPAGES',
189  'VMEMINFO_NR_ION_HEAP',
190  'VMEMINFO_NR_GPU_HEAP',
191  'VMEMINFO_ALLOCSTALL_DMA',
192  'VMEMINFO_ALLOCSTALL_MOVABLE',
193  'VMEMINFO_ALLOCSTALL_NORMAL',
194  'VMEMINFO_COMPACT_DAEMON_FREE_SCANNED',
195  'VMEMINFO_COMPACT_DAEMON_MIGRATE_SCANNED',
196  'VMEMINFO_NR_FASTRPC',
197  'VMEMINFO_NR_INDIRECTLY_RECLAIMABLE',
198  'VMEMINFO_NR_ION_HEAP_POOL',
199  'VMEMINFO_NR_KERNEL_MISC_RECLAIMABLE',
200  'VMEMINFO_NR_SHADOW_CALL_STACK_BYTES',
201  'VMEMINFO_NR_SHMEM_HUGEPAGES',
202  'VMEMINFO_NR_SHMEM_PMDMAPPED',
203  'VMEMINFO_NR_UNRECLAIMABLE_PAGES',
204  'VMEMINFO_NR_ZONE_ACTIVE_ANON',
205  'VMEMINFO_NR_ZONE_ACTIVE_FILE',
206  'VMEMINFO_NR_ZONE_INACTIVE_ANON',
207  'VMEMINFO_NR_ZONE_INACTIVE_FILE',
208  'VMEMINFO_NR_ZONE_UNEVICTABLE',
209  'VMEMINFO_NR_ZONE_WRITE_PENDING',
210  'VMEMINFO_OOM_KILL',
211  'VMEMINFO_PGLAZYFREE',
212  'VMEMINFO_PGLAZYFREED',
213  'VMEMINFO_PGREFILL',
214  'VMEMINFO_PGSCAN_DIRECT',
215  'VMEMINFO_PGSCAN_KSWAPD',
216  'VMEMINFO_PGSKIP_DMA',
217  'VMEMINFO_PGSKIP_MOVABLE',
218  'VMEMINFO_PGSKIP_NORMAL',
219  'VMEMINFO_PGSTEAL_DIRECT',
220  'VMEMINFO_PGSTEAL_KSWAPD',
221  'VMEMINFO_SWAP_RA',
222  'VMEMINFO_SWAP_RA_HIT',
223  'VMEMINFO_WORKINGSET_RESTORE',
224];
225// sys.mem.total   sys.mem.free sys.mem.buffers sys.mem.cached  sys.mem.shmem  sys.mem.slab  sys.mem.swap.total
226// sys.mem.swap.free sys.mem.mapped  sys.mem.vmalloc.used  sys.mem.page.tables  sys.mem.kernel.stack
227// sys.mem.active sys.mem.inactive  sys.mem.unevictable  sys.mem.vmalloc.total sys.mem.slab.unreclaimable
228// sys.mem.cma.total sys.mem.cma.free
229export const ABALITY_MEM_INFO = [
230  'MEMINFO_MEM_TOTAL',
231  'MEMINFO_MEM_FREE',
232  'MEMINFO_BUFFERS',
233  'MEMINFO_CACHED',
234  'MEMINFO_SHMEM',
235  'MEMINFO_SLAB',
236  'MEMINFO_SWAP_TOTAL',
237  'MEMINFO_SWAP_FREE',
238  'MEMINFO_MAPPED',
239  'MEMINFO_VMALLOC_USED',
240  'MEMINFO_PAGE_TABLES',
241  'MEMINFO_KERNEL_STACK',
242  'MEMINFO_ACTIVE',
243  'MEMINFO_INACTIVE',
244  'MEMINFO_UNEVICTABLE',
245  'MEMINFO_VMALLOC_TOTAL',
246  'MEMINFO_SLAB_UNRECLAIMABLE',
247  'MEMINFO_CMA_TOTAL',
248  'MEMINFO_CMA_FREE',
249  'MEMINFO_KERNEL_RECLAIMABLE',
250  'PMEM_ACTIVE_PURG',
251  'PMEM_INACTIVE_PURG',
252  'PMEM_PINED_PURG',
253];
254
255export const schedulingEvents = [
256  'sched/sched_switch',
257  'power/suspend_resume',
258  'sched/sched_wakeup',
259  'sched/sched_wakeup_new',
260  'sched/sched_waking',
261  'sched/sched_process_exit',
262  'sched/sched_process_free',
263  'task/task_newtask',
264  'task/task_rename',
265];
266
267export const powerEvents = [
268  'regulator/regulator_set_voltage',
269  'regulator/regulator_set_voltage_complete',
270  'power/clock_enable',
271  'power/clock_disable',
272  'power/clock_set_rate',
273  'power/suspend_resume',
274];
275
276export const cpuFreqEvents = ['power/cpu_frequency', 'power/cpu_idle', 'power/suspend_resume'];
277
278export const sysCallsEvents = ['raw_syscalls/sys_enter', 'raw_syscalls/sys_exit'];
279
280export const highFrequencyEvents = [
281  'mm_event/mm_event_record',
282  'kmem/rss_stat',
283  'ion/ion_stat',
284  'dmabuf_heap/dma_heap_stat',
285  'kmem/ion_heap_grow',
286  'kmem/ion_heap_shrink',
287];
288
289export const advancedConfigEvents = [
290  'sched/sched_switch',
291  'sched/sched_wakeup',
292  'sched/sched_wakeup_new',
293  'sched/sched_waking',
294  'sched/sched_process_exit',
295  'sched/sched_process_free',
296  'irq/irq_handler_entry',
297  'irq/irq_handler_exit',
298  'irq/softirq_entry',
299  'irq/softirq_exit',
300  'irq/softirq_raise',
301  'power/clock_disable',
302  'power/clock_enable',
303  'power/clock_set_rate',
304  'power/cpu_frequency',
305  'power/cpu_idle',
306  'clk/clk_disable',
307  'clk/clk_disable_complete',
308  'clk/clk_enable',
309  'clk/clk_enable_complete',
310  'clk/clk_set_rate',
311  'clk/clk_set_rate_complete',
312  'binder/binder_transaction',
313  'binder/binder_transaction_alloc_buf',
314  'binder/binder_transaction_received',
315  'binder/binder_lock',
316  'binder/binder_locked',
317  'binder/binder_unlock',
318  'workqueue/workqueue_execute_start',
319  'workqueue/workqueue_execute_end',
320  'oom/oom_score_adj_update',
321  'ftrace/print',
322];
323
324export function createSessionRequest(recordSetting: SpRecordSetting): CreateSessionRequest {
325  let bufferConfig: ProfilerSessionConfigBufferConfig = {
326    pages: recordSetting.bufferSize * 256,
327    policy: ProfilerSessionConfigBufferConfigPolicy.RECYCLE,
328  };
329  let sessionConfig: ProfilerSessionConfig = {
330    buffers: [bufferConfig],
331    sessionMode: ProfilerSessionConfigMode.OFFLINE,
332    resultMaxSize: 0,
333    keepAliveTime: 0,
334  };
335  return {
336    requestId: 1,
337    sessionConfig: sessionConfig,
338    pluginConfigs: [],
339  };
340}
341
342export function createMemoryPluginConfig(
343  reportingFrequency: number,
344  spVmTracker: SpVmTracker,
345  probesConfig: SpProbesConfig,
346  request: CreateSessionRequest
347): void {
348  let hasSamp = spVmTracker!.startSamp && spVmTracker!.process !== '';
349  if (probesConfig!.memoryConfig.length > 0 || hasMonitorMemory || hasSamp) {
350    let memoryConfig = initMemoryPluginConfig(hasSamp, spVmTracker, probesConfig);
351    if (hasMonitorMemory) {
352      ABALITY_MEM_INFO.forEach((va) => {
353        memoryConfig.sysMeminfoCounters.push(sysMeminfoTypeFromJSON(va));
354      });
355    }
356    probesConfig!.memoryConfig.forEach((value) => {
357      if (value.indexOf('Kernel meminfo') !== -1) {
358        if (hasMonitorMemory) {
359          memoryConfig.sysMeminfoCounters = [];
360        }
361        MEM_INFO.forEach((va) => {
362          memoryConfig.sysMeminfoCounters.push(sysMeminfoTypeFromJSON(va));
363        });
364      }
365      if (value.indexOf('Virtual memory stats') !== -1) {
366        VMEM_INFO.forEach((me) => {
367          memoryConfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me));
368        });
369        VMEM_INFO_SECOND.forEach((me) => {
370          memoryConfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me));
371        });
372        VMEM_INFO_THIRD.forEach((me) => {
373          memoryConfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me));
374        });
375      }
376    });
377    request.pluginConfigs.push({
378      pluginName: 'memory-plugin',
379      sampleInterval: reportingFrequency * 1000,
380      configData: memoryConfig,
381    });
382  }
383}
384
385function initMemoryPluginConfig(
386  hasSamp: boolean,
387  spVmTracker: SpVmTracker,
388  probesConfig: SpProbesConfig
389): MemoryConfig {
390  let memoryConfig: MemoryConfig = {
391    reportProcessTree: false,
392    reportSysmemMemInfo: false,
393    sysMeminfoCounters: [],
394    reportSysmemVmemInfo: false,
395    sysVmeminfoCounters: [],
396    reportProcessMemInfo: false,
397    reportAppMemInfo: false,
398    reportAppMemByMemoryService: false,
399    pid: [],
400  };
401  if (probesConfig!.memoryConfig.length > 0 || hasMonitorMemory) {
402    memoryConfig.reportProcessTree = true;
403    memoryConfig.reportSysmemMemInfo = true;
404    memoryConfig.reportSysmemVmemInfo = true;
405    memoryConfig.reportProcessMemInfo = true;
406  }
407  if (spVmTracker!.startSamp) {
408    memoryConfig.reportProcessMemInfo = true;
409  }
410  if (hasSamp || hasMonitorMemory) {
411    memoryConfig.reportPurgeableAshmemInfo = true;
412    memoryConfig.reportDmaMemInfo = true;
413    memoryConfig.reportGpuMemInfo = true;
414  }
415  if (hasSamp) {
416    memoryConfig.reportSmapsMemInfo = true;
417    memoryConfig.reportGpuDumpInfo = true;
418    let pid = Number(spVmTracker?.process);
419    memoryConfig.pid.push(pid);
420  }
421  return memoryConfig;
422}
423
424export function createHTracePluginConfig(probesConfig: SpProbesConfig, request: CreateSessionRequest): void {
425  if (probesConfig!.traceConfig.length > 0 && probesConfig!.traceConfig.find((value) => value !== 'FPS')) {
426    let tracePluginConfig: TracePluginConfig = {
427      ftraceEvents: createTraceEvents(probesConfig!.traceConfig),
428      hitraceCategories: [],
429      hitraceApps: [],
430      bufferSizeKb: probesConfig!.ftraceBufferSize,
431      flushIntervalMs: 1000,
432      flushThresholdKb: 4096,
433      parseKsyms: true,
434      clock: 'boot',
435      tracePeriodMs: 200,
436      rawDataPrefix: '',
437      traceDurationMs: 0,
438      debugOn: false,
439    };
440    if (probesConfig!.traceEvents.length > 0) {
441      tracePluginConfig.hitraceCategories = probesConfig!.traceEvents;
442    }
443    request.pluginConfigs.push({
444      pluginName: 'ftrace-plugin',
445      sampleInterval: 1000,
446      configData: tracePluginConfig,
447    });
448  }
449}
450
451export function createFpsPluginConfig(probesConfig: SpProbesConfig, request: CreateSessionRequest): void {
452  let fpsConfig: FpsConfig = {
453    reportFps: true,
454  };
455  if (probesConfig!.traceConfig.length > 0 && probesConfig!.traceConfig.indexOf('FPS') !== -1) {
456    request.pluginConfigs.push({
457      pluginName: 'hidump-plugin',
458      sampleInterval: 1000,
459      configData: fpsConfig,
460    });
461  }
462}
463
464export function createMonitorPlugin(probesConfig: SpProbesConfig, request: CreateSessionRequest): void {
465  hasMonitorMemory = probesConfig.recordAbility;
466  if (!probesConfig.recordAbility) {
467    return;
468  }
469  let cpuPlugin = {
470    pluginName: 'cpu-plugin',
471    sampleInterval: 1000,
472    configData: {
473      pid: 0,
474      reportProcessInfo: true,
475    },
476  };
477  let processPlugin = {
478    pluginName: 'process-plugin',
479    sampleInterval: 1000,
480    configData: {
481      report_process_tree: true,
482      report_cpu: true,
483      report_diskio: true,
484      report_pss: true,
485    },
486  };
487  let diskIoPlugin = {
488    pluginName: 'diskio-plugin',
489    sampleInterval: 1000,
490    configData: {
491      reportIoStats: 'IO_REPORT',
492    },
493  };
494  let netWorkPlugin = {
495    pluginName: 'network-plugin',
496    sampleInterval: 1000,
497    configData: {},
498  };
499  request.pluginConfigs.push(processPlugin);
500  request.pluginConfigs.push(cpuPlugin);
501  request.pluginConfigs.push(diskIoPlugin);
502  request.pluginConfigs.push(netWorkPlugin);
503}
504
505export function createNativePluginConfig(
506  reportingFrequency: number,
507  spAllocations: SpAllocations,
508  selectVersion: string | null,
509  request: CreateSessionRequest
510): void {
511  if (spAllocations!.appProcess !== '' && spAllocations!.startSamp) {
512    let nativeConfig = initNativePluginConfig(spAllocations, selectVersion);
513    let maxProcessSize = 4;
514    if (selectVersion !== undefined && selectVersion !== '3.2') {
515      nativeConfig.callframeCompress = true;
516      nativeConfig.recordAccurately = spAllocations!.record_accurately;
517      nativeConfig.offlineSymbolization = spAllocations!.offline_symbolization;
518      if (spAllocations!.record_statistics) {
519        nativeConfig.statisticsInterval = spAllocations!.statistics_interval;
520      }
521      nativeConfig.startupMode = spAllocations!.startup_mode;
522      if (spAllocations!.response_lib_mode) {
523        nativeConfig.responseLibraryMode = spAllocations!.response_lib_mode;
524        maxProcessSize = 8;
525      }
526      if (spAllocations && spAllocations.sample_interval) {
527        if (spAllocations.record_statistics) {
528          nativeConfig.sampleInterval = spAllocations.sample_interval;
529        } else {
530          nativeConfig.mallocFreeMatchingInterval = spAllocations.sample_interval;
531        }
532      }
533      nativeConfig.jsStackReport = spAllocations!.recordJsStack ? 1 : 0;
534      if (spAllocations!.recordJsStack) {
535        nativeConfig.maxJsStackDepth = spAllocations!.max_js_stack_depth;
536        nativeConfig.filterNapiName = spAllocations!.filter_napi_name;
537      }
538    }
539    if (spAllocations!.expandPids.length > 1) {
540      nativeConfig.expandPids = spAllocations!.expandPids.splice(0, maxProcessSize);
541    }
542    request.pluginConfigs.push({
543      pluginName: 'nativehook',
544      sampleInterval: reportingFrequency * 1000,
545      configData: nativeConfig,
546    });
547  }
548}
549
550function initNativePluginConfig(spAllocations: SpAllocations, selectVersion: string | null): NativeHookConfig {
551  let appProcess = spAllocations!.appProcess;
552  let processName = '';
553  let processId = '';
554  if (spAllocations!.startup_mode && selectVersion !== '3.2') {
555    processName = appProcess;
556  } else {
557    if (appProcess.indexOf('(') !== -1) {
558      processId = appProcess.slice(appProcess.lastIndexOf('(') + 1, appProcess.lastIndexOf(')'));
559    } else {
560      processId = appProcess;
561    }
562    if (/^[0-9]+.?[0-9]*/.test(processId)) {
563      let pid = Number(processId);
564    } else {
565      processName = appProcess;
566    }
567  }
568  let nativeConfig: NativeHookConfig;
569  if (spAllocations!.expandPids.length === 1) {
570    nativeConfig = {
571      pid: spAllocations!.expandPids[0],
572      saveFile: false,
573      fileName: '',
574      filterSize: spAllocations!.filter,
575      smbPages: spAllocations!.shared,
576      maxStackDepth: spAllocations!.unwind,
577      processName: processName,
578      stringCompressed: true,
579      fpUnwind: spAllocations!.fp_unwind,
580      blocked: true,
581    };
582  } else {
583    nativeConfig = {
584      saveFile: false,
585      fileName: '',
586      filterSize: spAllocations!.filter,
587      smbPages: spAllocations!.shared,
588      maxStackDepth: spAllocations!.unwind,
589      processName: processName,
590      stringCompressed: true,
591      fpUnwind: spAllocations!.fp_unwind,
592      blocked: true,
593    };
594  }
595  return nativeConfig;
596}
597
598function initHiPerfConfig(perfConfig: PerfConfig | undefined, recordArgs: string): string {
599  if (!perfConfig) {
600    return '';
601  }
602  if (perfConfig.cpu && !perfConfig.cpu.includes('ALL') && perfConfig.cpu.length > 0) {
603    recordArgs = `${recordArgs} -c ${perfConfig.cpu}`;
604  }
605  if (perfConfig.cpuPercent !== 0) {
606    recordArgs = `${recordArgs} --cpu-limit ${perfConfig.cpuPercent}`;
607  }
608  if (perfConfig.eventList && !perfConfig.eventList.includes('NONE') && perfConfig.eventList.length > 0) {
609    recordArgs = `${recordArgs} -e ${perfConfig.eventList}`;
610    if (perfConfig.isOffCpu) {
611      recordArgs = `${recordArgs},sched:sched_waking`;
612    }
613  } else {
614    recordArgs = `${recordArgs} -e hw-cpu-cycles`;
615    if (perfConfig.isOffCpu) {
616      recordArgs = `${recordArgs},sched:sched_waking`;
617    }
618  }
619  if (perfConfig.callStack !== 'none') {
620    recordArgs = `${recordArgs} --call-stack ${perfConfig.callStack}`;
621  }
622  if (perfConfig.branch !== 'none') {
623    recordArgs = `${recordArgs} -j ${perfConfig.branch}`;
624  }
625  if (perfConfig.clockType) {
626    recordArgs = `${recordArgs} --clockid ${perfConfig.clockType}`;
627  }
628  if (perfConfig.isOffCpu) {
629    recordArgs = `${recordArgs} --offcpu`;
630  }
631  if (perfConfig?.isKernelChain) {
632    recordArgs = `${recordArgs} --kernel-callchain`;
633  }
634  if (perfConfig.noInherit) {
635    recordArgs = `${recordArgs} --no-inherit`;
636  }
637  if (perfConfig.mmap) {
638    recordArgs = `${recordArgs} -m ${perfConfig.mmap}`;
639  }
640  return recordArgs;
641}
642
643export function createHiPerfConfig(
644  reportingFrequency: number,
645  spRecordPerf: SpRecordPerf,
646  recordSetting: SpRecordSetting,
647  request: CreateSessionRequest
648): void {
649  if (!spRecordPerf!.startSamp) {
650    return;
651  }
652  let perfConfig = spRecordPerf!.getPerfConfig();
653  let recordArgs = '';
654  recordArgs = `${recordArgs}-f ${perfConfig?.frequency}`;
655  if (perfConfig?.process && !perfConfig?.process.includes('ALL') && perfConfig?.process.length > 0) {
656    let process = perfConfig.process;
657    if (process.indexOf(',') !== -1) {
658      let processIdOrName = process.split(',');
659      if (!isNaN(Number(processIdOrName[0]))) {
660        recordArgs = `${recordArgs} -p ${perfConfig?.process}`;
661      } else {
662        recordArgs = `${recordArgs} --app ${perfConfig?.process}`;
663      }
664    } else {
665      if (!isNaN(Number(process))) {
666        recordArgs = `${recordArgs} -p ${perfConfig?.process}`;
667      } else {
668        recordArgs = `${recordArgs} --app ${perfConfig?.process}`;
669      }
670    }
671  } else {
672    recordArgs = `${recordArgs} -a `;
673  }
674  recordArgs = initHiPerfConfig(perfConfig, recordArgs);
675  info('record config Args is: ', recordArgs);
676  let hiPerf: HiperfPluginConfig = {
677    isRoot: false,
678    outfileName: '/data/local/tmp/perf.data',
679    recordArgs: recordArgs,
680  };
681  if (SpApplication.isLongTrace) {
682    hiPerf.splitOutfileName = `${recordSetting!.longOutPath}hiprofiler_data_hiperf.htrace`;
683  }
684  request.pluginConfigs.push({
685    pluginName: 'hiperf-plugin',
686    sampleInterval: reportingFrequency * 1000,
687    configData: hiPerf,
688  });
689}
690
691export function createSystemConfig(
692  spFileSystem: SpFileSystem,
693  recordSetting: SpRecordSetting,
694  request: CreateSessionRequest
695): void {
696  if (!spFileSystem!.startRecord) {
697    return;
698  }
699  let systemConfig = spFileSystem!.getSystemConfig();
700  let recordArgs = 'hiebpf';
701  let recordEvent = [];
702  if (spFileSystem?.startFileSystem) {
703    recordEvent.push('fs');
704  }
705  if (spFileSystem?.startVirtualMemory) {
706    recordEvent.push('ptrace');
707  }
708  if (spFileSystem?.startIo) {
709    recordEvent.push('bio');
710  }
711  if (recordEvent.length > 0) {
712    recordArgs += ` --events ${recordEvent.toString()}`;
713  }
714  recordArgs += ` --duration ${recordSetting?.maxDur}`;
715  if (systemConfig?.process && !systemConfig?.process.includes('ALL') && systemConfig?.process.length > 0) {
716    recordArgs = `${recordArgs} --pids ${systemConfig?.process}`;
717  }
718  recordArgs += ` --max_stack_depth ${systemConfig?.unWindLevel}`;
719  let systemPluginConfig: HiebpfConfig = {
720    cmdLine: recordArgs,
721    outfileName: '/data/local/tmp/ebpf.data',
722  };
723  if (SpApplication.isLongTrace) {
724    systemPluginConfig.splitOutfileName = `${recordSetting?.longOutPath}hiprofiler_data_ebpf.htrace`;
725  }
726  request.pluginConfigs.push({
727    pluginName: 'hiebpf-plugin',
728    sampleInterval: 1000,
729    configData: systemPluginConfig,
730  });
731}
732
733export function createSdkConfig(spSdkConfig: SpSdkConfig, request: CreateSessionRequest): void {
734  if (spSdkConfig.startSamp && spSdkConfig.getPlugName() !== '') {
735    let gpuConfig = spSdkConfig!.getGpuConfig();
736    request.pluginConfigs.push({
737      pluginName: spSdkConfig!.getPlugName(),
738      sampleInterval: spSdkConfig!.getSampleInterval(),
739      configData: gpuConfig,
740    });
741  }
742  return;
743}
744
745export function createHiSystemEventPluginConfig(spHiSysEvent: SpHisysEvent, request: CreateSessionRequest): void {
746  if (!spHiSysEvent.startSamp) {
747    return;
748  }
749  request.pluginConfigs.push({
750    pluginName: 'hisysevent-plugin',
751    configData: {
752      msg: 'hisysevent-plugin',
753      subscribe_domain: spHiSysEvent.domain,
754      subscribe_event: spHiSysEvent.eventName,
755    },
756  });
757}
758
759export function createArkTsConfig(
760  spArkTs: SpArkTs,
761  recordSetting: SpRecordSetting,
762  request: CreateSessionRequest
763): void {
764  if (spArkTs.process !== '' && spArkTs.startSamp) {
765    let process = spArkTs!.process;
766    let re = /^[0-9]+.?[0-9]*/;
767    let pid = 0;
768    let processId = '';
769    if (process.indexOf('(') !== -1) {
770      processId = process.slice(process.lastIndexOf('(') + 1, process.lastIndexOf(')'));
771    } else {
772      processId = process;
773    }
774    if (re.test(processId)) {
775      pid = Number(processId);
776    }
777    let arkTSConfig: ArkTSConfig = {
778      pid: pid,
779      type: spArkTs.radioBoxType,
780      interval: spArkTs.intervalValue,
781      capture_numeric_value: spArkTs.grabNumeric,
782      track_allocations: spArkTs.grabAllocations,
783      enable_cpu_profiler: spArkTs.grabCpuProfiler,
784      cpu_profiler_interval: spArkTs.intervalCpuValue,
785    };
786    if (SpApplication.isLongTrace) {
787      arkTSConfig.splitOutfileName = `${recordSetting?.longOutPath}hiprofiler_data_arkts.htrace`;
788    }
789    request.pluginConfigs.push({
790      pluginName: 'arkts-plugin',
791      sampleInterval: 5000,
792      configData: arkTSConfig,
793    });
794  }
795  return;
796}
797
798export function createHiLogConfig(
799  reportingFrequency: number,
800  spHiLog: SpHilogRecord,
801  request: CreateSessionRequest
802): void {
803  if (!spHiLog.recordHilog) {
804    return;
805  }
806  let appProcess = spHiLog!.appProcess;
807  let re = /^[0-9]+.?[0-9]*/;
808  let pid = 0;
809  let processId = '';
810  if (appProcess.indexOf('(') !== -1) {
811    processId = appProcess.slice(appProcess.lastIndexOf('(') + 1, appProcess.lastIndexOf(')'));
812  } else {
813    processId = appProcess;
814  }
815  if (re.test(processId)) {
816    pid = Number(processId);
817  }
818  let hiLogConfig: HilogConfig = {
819    pid: pid,
820    logLevel: levelFromJSON(spHiLog!.appLogLevel),
821    needClear: true,
822  };
823  request.pluginConfigs.push({
824    pluginName: 'hilog-plugin',
825    sampleInterval: reportingFrequency * 1000,
826    configData: hiLogConfig,
827  });
828}
829
830export function createFFRTPluginConfig(
831  currentConfigPage: SpFFRTConfig,
832  selectVersion: string | null,
833  request: CreateSessionRequest
834): void {
835  if (currentConfigPage &&
836    (
837      currentConfigPage.processIds.length > 0 ||
838      currentConfigPage.restartProcessNames.length > 0 ||
839      currentConfigPage.startupProcessNames.length > 0
840    ) &&
841    currentConfigPage.startSamp) {
842    let config: FFRTConfig = {};
843    if (currentConfigPage.processIds.length > 0) {
844      config.pid = currentConfigPage.processIds;
845    }
846    if (currentConfigPage.startupProcessNames.length > 0) {
847      config.startupProcessName = currentConfigPage!.startupProcessNames;
848    }
849    if (currentConfigPage.restartProcessNames.length > 0) {
850      config.restartProcessName = currentConfigPage.restartProcessNames;
851    }
852    config.smbPages = currentConfigPage.smbPages;
853    config.flushInterval = currentConfigPage.flushInterval;
854    config.block = currentConfigPage.useBlock;
855    config.clockId = currentConfigPage!.clockType;
856    request.pluginConfigs.push({
857      pluginName: 'ffrt-profiler',
858      configData: config,
859    });
860  }
861}
862
863export function createTraceEvents(traceConfig: Array<string>): Array<string> {
864  let traceEvents = new Set<string>();
865  traceConfig.forEach((config) => {
866    switch (config) {
867      case 'Scheduling details':
868        schedulingEvents.forEach((eve: string) => {
869          traceEvents.add(eve);
870        });
871        break;
872      case 'CPU Frequency and idle states':
873        cpuFreqEvents.forEach((eve: string) => {
874          traceEvents.add(eve);
875        });
876        break;
877      case 'High frequency memory':
878        highFrequencyEvents.forEach((eve: string) => {
879          traceEvents.add(eve);
880        });
881        break;
882      case 'Advanced ftrace config':
883        advancedConfigEvents.forEach((eve: string) => {
884          traceEvents.add(eve);
885        });
886        break;
887      case 'Syscalls':
888        sysCallsEvents.forEach((eve: string) => {
889          traceEvents.add(eve);
890        });
891        break;
892      case 'Board voltages & frequency':
893        powerEvents.forEach((eve: string) => {
894          traceEvents.add(eve);
895        });
896        break;
897    }
898  });
899  let ftraceEventsArray: string[] = [];
900  info('traceEvents length is: ', traceEvents.size);
901  for (const ftraceEvent of traceEvents) {
902    ftraceEventsArray.push(ftraceEvent);
903  }
904  return ftraceEventsArray;
905}
906
907let hasMonitorMemory = false;
908