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