• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 #ifndef SUBCOMMAND_RECORD_H
16 #define SUBCOMMAND_RECORD_H
17 
18 // some debug feaure
19 #define HIDEBUG_RECORD_NOT_PROCESS       0
20 #define HIDEBUG_RECORD_NOT_PROCESS_VM    0
21 #define HIDEBUG_RECORD_NOT_SAVE          0
22 #define HIDEBUG_SKIP_PROCESS_SYMBOLS     0
23 #define HIDEBUG_SKIP_MATCH_SYMBOLS       0
24 #define HIDEBUG_SKIP_LOAD_KERNEL_SYMBOLS 0
25 #define HIDEBUG_SKIP_SAVE_SYMBOLS        0
26 #define USE_COLLECT_SYMBOLIC             1
27 
28 #include <functional>
29 #include <thread>
30 #include <unordered_map>
31 #include <unordered_set>
32 #include <chrono>
33 #include "perf_event_record.h"
34 #include "perf_events.h"
35 #include "perf_file_writer.h"
36 #include "subcommand.h"
37 #include "virtual_runtime.h"
38 
39 namespace OHOS {
40 namespace Developtools {
41 namespace HiPerf {
42 class SubCommandRecord : public SubCommand {
43 public:
44     static constexpr int DEFAULT_CPU_PERCENT = 25;
45     static constexpr int MIN_CPU_PERCENT = 1;
46     static constexpr int MAX_CPU_PERCENT = 100;
47     static constexpr int MIN_SAMPLE_FREQUENCY = 1;
48     static constexpr int MAX_SAMPLE_FREQUENCY = 100000;
49     static constexpr int DEFAULT_MMAP_PAGES = 256;
50     static constexpr int MIN_PERF_MMAP_PAGE = 2;
51     static constexpr int MAX_PERF_MMAP_PAGE = 1024;
52     static constexpr int DEFAULT_CHECK_APP_MS = 10;
53     static constexpr int MIN_CHECK_APP_MS = 1;
54     static constexpr int MAX_CHECK_APP_MS = 200;
55     static constexpr float MIN_STOP_SECONDS = 0.100;
56     static constexpr float MAX_STOP_SECONDS = 10000.0;
57     static constexpr int MIN_SAVED_CMDLINES_SIZE = 512;
58     static constexpr int DEFAULT_SAVED_CMDLINES_SIZE = 2048;
59     static constexpr int MAX_SAVED_CMDLINES_SIZE = 4096;
60     static constexpr uint64_t MIN_BACKTRACK_TIME_SEC = 5;
61     static constexpr uint64_t DEFAULT_BACKTRACK_TIME_SEC = 10;
62     static constexpr uint64_t MAX_BACKTRACK_TIME_SEC = 30;
63 
SubCommandRecord()64     SubCommandRecord()
65         // clang-format off
66         : SubCommand("record", "Collect performance sample information",
67         "Usage: hiperf record [options] [command [command-args]]\n"
68         "       Collect performance sampling information of running [command].\n"
69         "       The default options are: -c <all cpu> --cpu-limit 25 -d 10000.0 -e hw-cpu-cycles\n"
70         "       -f 4000 -m 1024 -o /data/local/tmp/perf.data.\n"
71         "   -a\n"
72         "         Collect system-wide information.\n"
73         "         for measures all processes/threads\n"
74         "         This requires CAP_PERFMON (since Linux 5.8) or CAP_SYS_ADMIN capability or a\n"
75         "         /proc/sys/kernel/perf_event_paranoid value of less than 1.\n"
76         "   --exclude-hiperf\n"
77         "         Don't record events issued by hiperf itself.\n"
78         "   -c <cpuid>[<,cpuid>]...\n"
79         "         cpuid should be 0,1,2...\n"
80         "         Limit the CPU that collects data.\n"
81         "         0 means cpu0, 1 means cpu1 ...\n"
82         "   --cpu-limit <percent>\n"
83         "         Set the max percent of cpu time used for recording.\n"
84         "         percent is in range [1-100], default is 25.\n"
85         "   -d <sec>\n"
86         "         stop in <sec> seconds. floating point number. seconds is in range [0.100-10000.0]\n"
87         "         default is 10000.0\n"
88         "   -f <freq>\n"
89         "         Set event sampling frequency. default is 4000 samples every second.\n"
90         "         check /proc/sys/kernel/perf_event_max_sample_rate for maximum allowed frequency\n"
91         "   --period <num>\n"
92         "         Set event sampling period for tracepoint events. recording one sample when <num> events happen.\n"
93         "         The default <num> is 1\n"
94         "   -e <event1[:<u|k>]>[,event1[:<u|k>]]...\n"
95         "         Customize the name of the event that needs to be sampled.\n"
96         "         The name can use the names listed in the list parameter.\n"
97         "         It can also be represented by the value of 0x<hex>.\n"
98         "           u - monitor user space events only\n"
99         "           k - monitor kernel space events only\n"
100         "   -g <event1[:<u|k>]>[,event1[:<u|k>]]...\n"
101         "         Put the events into a group, can set multiple groups by multiple -g\n"
102         "         PMU is required to report data in designated groups\n"
103         "         limited by HW capability, too many events cannot be reported in the same sampling)\n"
104         "   --no-inherit\n"
105         "         Don't trace child processes.\n"
106         "   -p <pid1>[,pid2]...\n"
107         "         Limit the process id of the collection target. Conflicts with the -a option.\n"
108         "   -t <tid1>[,tid2]...\n"
109         "         Limit the thread id of the collection target. Conflicts with the -a option.\n"
110         "   --exclude-tid <tid1>[,tid2]...\n"
111         "         Exclude threads of the collection target by thread ids. Conflicts with the -a option.\n"
112         "   --exclude-thread <tname1>[,tname2]...\n"
113         "         Exclude threads of the collection target by thread names. Conflicts with the -a option.\n"
114         "   --exclude-process <pname1>[,pname2]...\n"
115         "         Exclude processes by process names. Must be used with -a.\n"
116         "   --offcpu\n"
117         "         Trace when threads are scheduled off cpu.\n"
118         "   -j <branch_filter1>[,branch_filter2]...\n"
119         "         taken branch stack sampling, filter can be:\n"
120         "           any: any type of branch\n"
121         "           any_call: any function call or system call\n"
122         "           any_ret: any function return or system call return\n"
123         "           ind_call: any indirect branch\n"
124         "           ind_jmp: any indirect jump\n"
125         "           cond: conditional branches\n"
126         "           call: direct calls, including far (to/from kernel) calls\n"
127         "           u: only when the branch target is at the user level\n"
128         "           k: only when the branch target is in the kernel\n"
129         "         requires at least one of any, any_call, any_ret, ind_call, ind_jmp, cond, call\n"
130         "   -s / --call-stack <fp|dwarf[,size]>\n"
131         "         Setup and enable call stack (stack chain/backtrace) recording, Default is 'fp'.\n"
132         "           the value can be:\n"
133         "             fp: frame pointer\n"
134         "             dwarf: DWARF's CFI - Call Frame Information\n"
135         "               'dwarf,size' set sample stack size, size should be in 8~65528 and 8 byte aligned. \n"
136         "           as the method to collect the information used to show the call stacks.\n"
137         "   --kernel-callchain\n"
138         "         collect kernel callchain, must used with -s fp/dwarf simultaneously.\n"
139         "   --callchain-useronly\n"
140         "         collect only user callchain.\n"
141         "   --delay-unwind\n"
142         "         If '-s dwarf' used, stack will be unwind while recording, use this option to switch\n"
143         "         to unwind after recording.\n"
144         "   --disable-unwind\n"
145         "         If '-s dwarf' is used, stack will be unwind while recording by default\n"
146         "         use this option to disable unwinding.\n"
147         "   --disable-callstack-expand\n"
148         "         If '-s dwarf' is used, to break the 64k stack limit, callstack is merged by default\n"
149         "         to build more complete call stack. that may not be correct sometimes.\n"
150         "   --enable-debuginfo-symbolic\n"
151         "         If '-s fp/dwarf' is used, symbols in .gnu_debugdata section of an elf, also called minidebuginfo\n"
152         "         will be parsed, if not use this option, we will not parse minidebuginfo by default.\n"
153         "   --clockid <clock_id>\n"
154         "         Set the clock id to use for the various time fields in the perf_event_type records.\n"
155         "         monotonic and monotonic_raw are supported,\n"
156         "         some events might also allow boottime, realtime and clock_tai.\n"
157         "   --symbol-dir <dir>\n"
158         "         Set directory to look for symbol files, used for unwinding. \n"
159         "   -m <mmap_pages>\n"
160         "         Number of the mmap pages, used to receiving record data from kernel,\n"
161         "         must be a power of two, rang[2,1024], default is 1024.\n"
162         "   --app <package_name>\n"
163         "         Collect profile info for an OHOS app, the app must be debuggable.\n"
164         "         Record will exit if the process is not started within 20 seconds.\n"
165         "   --chkms <millisec>\n"
166         "         Set the interval of querying the <package_name>.\n"
167         "         <millisec> is in range [1-200], default is 10.\n"
168         "   --data-limit <SIZE[K|M|G]>\n"
169         "         Stop recording after SIZE bytes of records. Default is unlimited.\n"
170         "   -o <output_file_name>\n"
171         "         Set output file name, default is /data/local/tmp/perf.data.\n"
172         "   -z\n"
173         "         Compress record data.\n"
174         "   --restart\n"
175         "         Collect performance counter information of application startup.\n"
176         "         Record will exit if the process is not started within 30 seconds.\n"
177         "   --verbose\n"
178         "         Show more detailed reports.\n"
179         "   --control <command>\n"
180         "         Control sampling by <command>, the <command> can be:\n"
181         "           prepare: set arguments and prepare sampling\n"
182         "           start: start sampling\n"
183         "           pause: pause sampling\n"
184         "           resume: resume sampling\n"
185         "           output: output sampling data\n"
186         "           stop: stop sampling\n"
187         "   --dedup_stack\n"
188         "         Remove duplicated stacks in perf record, conflicts with -a, only restrain using with -p\n"
189         "   --cmdline-size <size>\n"
190         "         set value to /sys/kernel/tracing/saved_cmdlines_size\n"
191         "         the value should be between 512 and 4096\n"
192         "   --report\n"
193         "         Report with callstack after record. Conflicts with the -a option.\n"
194         "   --backtrack\n"
195         "         Collect data of the previous period. only restrain using with --control.\n"
196         "   --backtrack-sec\n"
197         "         If '--backtrack' is used, stop in <sec> seconds. seconds is in range [5-30]\n"
198         "         default is 10\n"
199         "   --dumpoptions\n"
200         "         Dump command options.\n"
201         )
202     // clang-format on
203     {
204     }
205 
206     ~SubCommandRecord();
207     HiperfError OnSubCommand(std::vector<std::string>& args) override;
208     bool ParseOption(std::vector<std::string> &args) override;
209     void DumpOptions(void) const override;
210 
211     // add args for hisysevent
212     void AddReportArgs(CommandReporter& reporter) override;
213 
214     static bool RegisterSubCommandRecord(void);
215     std::map<const std::string, uint64_t> speOptMap_ = {
216         {"branch_filter", 0},   {"load_filter", 0},
217         {"store_filter", 0},    {"ts_enable", 0},
218         {"pa_enable", 0},       {"jitter", 0},
219         {"min_latency", 0},      {"event_filter", 0},
220         {"pct_enable", 0},
221     };
222 
223     static SubCommand& GetInstance();
224 
225 private:
226     PerfEvents perfEvents_;
227 
228     bool targetSystemWide_ = false;
229     bool compressData_ = false;
230     bool noInherit_ = false;
231     bool excludeHiperf_ = false;
232     bool offCPU_ = false;
233     bool delayUnwind_ = false;
234     bool disableUnwind_ = false;
235     bool disableCallstackExpend_ = false;
236     bool enableDebugInfoSymbolic_ = false;
237     bool verboseReport_ = false;
238     bool kernelCallChain_ = true;
239     bool callChainUserOnly_ = false;
240     bool report_ = false;
241     float timeStopSec_ = PerfEvents::DEFAULT_TIMEOUT;
242     int frequency_ = 0;
243     int period_ = 0;
244     int cpuPercent_ = DEFAULT_CPU_PERCENT;
245     int mmapPages_ = MAX_PERF_MMAP_PAGE;
246     int cmdlinesSize_ = DEFAULT_SAVED_CMDLINES_SIZE;
247     int oldCmdlinesSize_ = 0;
248     std::vector<std::string> symbolDir_ = {};
249     std::string outputFilename_ = "/data/local/tmp/perf.data";
250     std::string appPackage_ = {};
251     int checkAppMs_ = DEFAULT_CHECK_APP_MS;
252     std::string clockId_ = {};
253     std::string strLimit_ = {};
254     std::vector<pid_t> selectCpus_ = {};
255     std::vector<pid_t> selectPids_ = {};
256     std::vector<pid_t> selectTids_ = {};
257     std::vector<pid_t> inputPidTidArgs_ = {};
258     bool restart_ = false;
259     std::vector<std::string> selectEvents_ = {};
260     std::vector<std::vector<std::string>> selectGroups_ = {};
261     std::vector<std::string> callStackType_ = {};
262     std::vector<std::string> vecBranchFilters_ = {};
263     std::vector<std::string> trackedCommand_ = {};
264 
265     // for exclude process and thread
266     std::vector<pid_t> excludeTidArgs_ = {};
267     std::vector<std::string> excludeThreadNameArgs_ = {};
268     std::vector<std::string> excludeProcessNameArgs_ = {};
269     std::set<pid_t> excludePids_ = {};
270     std::set<pid_t> excludeTids_ = {};
271     void CollectExcludeThread();
272     void SetExcludeHiperf();
273     bool IsThreadExcluded(pid_t pid, pid_t tid);
274 
275     // for background track
276     bool backtrack_ = false;
277     uint64_t backtrackTime_ = DEFAULT_BACKTRACK_TIME_SEC;   // 10 seconds
278     bool outputEnd_ = false;
279     bool PreOutputRecordFile();
280     void OutputRecordFile();
281     bool PostOutputRecordFile(bool output);
282 
283     bool GetOptions(std::vector<std::string> &args);
284     bool CheckArgsRange();
285     bool CheckExcludeArgs();
286     bool CheckOptions();
287     bool GetSpeOptions();
288     bool CheckDataLimitOption();
289     bool CheckSelectCpuPidOption();
290     bool GetOptionFrequencyAndPeriod(std::vector<std::string> &args);
291 
292     bool isCallStackDwarf_ = false;
293     bool isCallStackFp_ = false;
294     uint32_t callStackDwarfSize_ = MAX_SAMPLE_STACK_SIZE;
295     uint64_t branchSampleType_ = 0;
296     uint64_t dataSizeLimit_ = 0;
297     bool isDataSizeLimitStop_ = false;
298 
299     std::unique_ptr<PerfFileWriter> fileWriter_ = nullptr;
300 
301     // for client
302     int clientPipeInput_ = -1;
303     int clientPipeOutput_ = -1;
304     int nullFd_ = -1;
305     std::thread clientCommandHanle_;
306     bool clientRunning_ = true;
307     struct ControlCommandHandler {
308         std::function<bool()> preProcess = []() -> bool {
309             return false;
310         };
311         std::function<void(bool)> postProcess = [](bool) {};
312     };
313     std::unordered_map<std::string, ControlCommandHandler> controlCommandHandlerMap_ = {};
314     inline void CreateClientThread();
315     void ClientCommandHandle();
316     void InitControlCommandHandlerMap();
317     void DispatchControlCommand(const std::string& command);
318     bool ClientCommandResponse(bool response);
319     bool ClientCommandResponse(const std::string& str);
320     bool IsSamplingRunning();
321 
322     // for cmdline client
323     bool allowIpc_ = true;
324     std::string controlCmd_ = {};
325     bool isFifoServer_ = false;
326     bool isFifoClient_ = false;
327     bool dedupStack_ = false;
328     std::map<pid_t, std::vector<pid_t>> mapPids_;
329     bool ProcessControl();
330     void ProcessStopCommand(bool ret);
331     void ProcessOutputCommand(bool ret);
332     bool CreateFifoServer();
333     bool SendFifoAndWaitReply(const std::string &cmd, const std::chrono::milliseconds &timeOut);
334     bool WaitFifoReply(int fd, const std::chrono::milliseconds &timeOut);
335     void WaitFifoReply(int fd, const std::chrono::milliseconds &timeOut, std::string& reply);
336     void CloseClientThread();
337     std::string HandleAppInfo();
338 
339     bool PreparePerfEvent();
340     bool PrepareSysKernel();
341     void PrepareKernelMaps();
342     bool PrepareVirtualRuntime();
343 
344     size_t recordSamples_ = 0;
345     size_t recordNoSamples_ = 0;
346 
347     bool isNeedSetPerfHarden_ = false;
348     bool isSpe_ = false;
349 
350     // callback to process record
351     bool ProcessRecord(PerfEventRecord& record);
352     bool SaveRecord(const PerfEventRecord& record);
353 
354     // file format like as 0,1-3,4-6,7,8
355     uint32_t GetCountFromFile(const std::string &fileName);
356     std::string GetCpuDescFromFile();
357     bool AddCpuFeature();
358     void AddMemTotalFeature();
359     void AddEventDescFeature();
360     void AddRecordTimeFeature();
361     void AddWorkloadCmdFeature();
362     void AddCommandLineFeature();
363     void AddCpuOffFeature();
364     void AddDevhostFeature();
365     bool AddFeatureRecordFile();
366 
367     bool CreateInitRecordFile(bool compressData = false);
368     bool FinishWriteRecordFile();
369     bool PostProcessRecordFile();
370     bool RecordCompleted();
371 #ifdef HIPERF_DEBUG_TIME
372     void ReportTime();
373 #endif
374 
375     bool CollectionSymbol(PerfEventRecord& record);
376     void CollectSymbol(PerfRecordSample *sample);
377     bool SetPerfLimit(const std::string& file, int value, std::function<bool (int, int)> const& cmd,
378         const std::string& param);
379     bool SetPerfCpuMaxPercent();
380     bool SetPerfMaxSampleRate();
381     bool SetPerfEventMlock();
382     bool SetPerfHarden();
383 
384     bool TraceOffCpu();
385     bool ParseCallStackOption(const std::vector<std::string> &callStackType);
386     bool ParseDataLimitOption(const std::string &str);
387     bool ParseBranchSampleType(const std::vector<std::string> &vecBranchSampleTypes);
388     bool ParseControlCmd(const std::string cmd);
389     bool CheckTargetProcessOptions();
390     bool CheckTargetPids();
391     bool CheckReportOption();
392     bool CheckBacktrackOption();
393     bool CheckSpeOption();
394     void WriteCommEventBeforeSampling();
395     void RemoveVdsoTmpFile();
396 
397     VirtualRuntime virtualRuntime_;
398 #if USE_COLLECT_SYMBOLIC
399     std::unordered_map<pid_t, std::unordered_set<uint64_t>> kernelThreadSymbolsHits_;
400     kSymbolsHits kernelSymbolsHits_;
401     uSymbolsHits userSymbolsHits_;
402     void SymbolicHits();
403 #endif
404 
405 #ifdef HIPERF_DEBUG_TIME
406     std::chrono::microseconds prcessRecordTimes_ = std::chrono::microseconds::zero();
407     std::chrono::microseconds saveRecordTimes_ = std::chrono::microseconds::zero();
408     std::chrono::microseconds saveFeatureTimes_ = std::chrono::microseconds::zero();
409 #endif
410     std::chrono::time_point<std::chrono::steady_clock> startSaveFileTimes_;
411 
412     void SetHM();
413     void SetSavedCmdlinesSize();
414     void RecoverSavedCmdlinesSize();
415     bool OnlineReportData();
416 
417     // only used in UT
418     using CheckRecordCallBack = std::function<void(const PerfEventRecord&)>;
419     void SetCheckRecordCallback(CheckRecordCallBack callback);
420     CheckRecordCallBack checkCallback_ = nullptr;
421 };
422 } // namespace HiPerf
423 } // namespace Developtools
424 } // namespace OHOS
425 #endif // SUBCOMMAND_RECORD_H
426