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
16 #define HILOG_TAG "Stat"
17
18 #include "subcommand_stat.h"
19
20 #include <csignal>
21 #include <iostream>
22 #include <memory>
23
24 #include "debug_logger.h"
25 #include "utilities.h"
26
27 const uint16_t ONE_HUNDRED = 100;
28 const uint16_t THOUSNADS_SEPARATOR = 3;
29 namespace OHOS {
30 namespace Developtools {
31 namespace HiPerf {
32 static std::map<pid_t, ThreadInfos> thread_map_;
33 static bool g_reportCpuFlag = false;
34 static bool g_reportThreadFlag = false;
35 static VirtualRuntime g_runtimeInstance;
DumpOptions() const36 void SubCommandStat::DumpOptions() const
37 {
38 printf("DumpOptions:\n");
39 printf(" targetSystemWide:\t%s\n", targetSystemWide_ ? "true" : "false");
40 printf(" selectCpus:\t%s\n", VectorToString(selectCpus_).c_str());
41 printf(" timeStopSec:\t%f sec\n", timeStopSec_);
42 printf(" timeReportMs:\t%d ms\n", timeReportMs_);
43 printf(" selectEvents:\t%s\n", VectorToString(selectEvents_).c_str());
44 printf(" selectGroups:\t%s\n", VectorToString(selectGroups_).c_str());
45 printf(" noCreateNew:\t%s\n", noCreateNew_ ? "true" : "false");
46 printf(" appPackage:\t%s\n", appPackage_.c_str());
47 printf(" checkAppMs_:\t%d\n", checkAppMs_);
48 printf(" selectPids:\t%s\n", VectorToString(selectPids_).c_str());
49 printf(" selectTids:\t%s\n", VectorToString(selectTids_).c_str());
50 printf(" restart:\t%s\n", restart_ ? "true" : "false");
51 printf(" perCore:\t%s\n", perCpus_ ? "true" : "false");
52 printf(" perTread:\t%s\n", perThreads_ ? "true" : "false");
53 printf(" verbose:\t%s\n", verboseReport_ ? "true" : "false");
54 }
55
ParseOption(std::vector<std::string> & args)56 bool SubCommandStat::ParseOption(std::vector<std::string> &args)
57 {
58 if (args.size() == 1 and args[0] == "-h") {
59 args.clear();
60 helpOption_ = true;
61 PrintUsage();
62 return true;
63 }
64 if (!Option::GetOptionValue(args, "-a", targetSystemWide_)) {
65 HLOGD("get option -a failed");
66 return false;
67 }
68 if (targetSystemWide_ && !IsSupportNonDebuggableApp()) {
69 HLOGD("-a option needs root privilege for system wide profiling.");
70 printf("-a option needs root privilege for system wide profiling.\n");
71 return false;
72 }
73 if (!Option::GetOptionValue(args, "-c", selectCpus_)) {
74 HLOGD("get option -c failed");
75 return false;
76 }
77 if (!Option::GetOptionValue(args, "-d", timeStopSec_)) {
78 HLOGD("get option -d failed");
79 return false;
80 }
81 if (!Option::GetOptionValue(args, "-i", timeReportMs_)) {
82 HLOGD("get option -i failed");
83 return false;
84 }
85 if (!Option::GetOptionValue(args, "-e", selectEvents_)) {
86 HLOGD("get option -e failed");
87 return false;
88 }
89 if (!Option::GetOptionValue(args, "-g", selectGroups_)) {
90 HLOGD("get option -g failed");
91 return false;
92 }
93 if (!Option::GetOptionValue(args, "--no-inherit", noCreateNew_)) {
94 HLOGD("get option --no-inherit failed");
95 return false;
96 }
97 if (!Option::GetOptionValue(args, "--app", appPackage_)) {
98 HLOGD("get option --app failed");
99 return false;
100 }
101 if (!Option::GetOptionValue(args, "--chkms", checkAppMs_)) {
102 return false;
103 }
104 if (!Option::GetOptionValue(args, "-p", selectPids_)) {
105 HLOGD("get option -p failed");
106 return false;
107 }
108 if (!Option::GetOptionValue(args, "-t", selectTids_)) {
109 HLOGD("get option -t failed");
110 return false;
111 }
112 if (!Option::GetOptionValue(args, "--restart", restart_)) {
113 HLOGD("get option --restart failed");
114 return false;
115 }
116 if (!Option::GetOptionValue(args, "--per-core", perCpus_)) {
117 HLOGD("get option --per-core failed");
118 return false;
119 }
120 if (!Option::GetOptionValue(args, "--per-thread", perThreads_)) {
121 HLOGD("get option --per-thread failed");
122 return false;
123 }
124 if (!Option::GetOptionValue(args, "--verbose", verboseReport_)) {
125 HLOGD("get option --verbose failed");
126 return false;
127 }
128 return ParseSpecialOption(args);
129 }
130
ParseSpecialOption(std::vector<std::string> & args)131 bool SubCommandStat::ParseSpecialOption(std::vector<std::string> &args)
132 {
133 if (!Option::GetOptionTrackedCommand(args, trackedCommand_)) {
134 HLOGD("get cmd failed");
135 return false;
136 }
137 if (!args.empty()) {
138 HLOGD("redundant option(s)");
139 return false;
140 }
141 return true;
142 }
143
PrintUsage()144 void SubCommandStat::PrintUsage()
145 {
146 printf("%s\n", Help().c_str());
147 }
148
SetReportFlags(bool cpuFlag,bool threadFlag)149 void SubCommandStat::SetReportFlags(bool cpuFlag, bool threadFlag)
150 {
151 g_reportCpuFlag = cpuFlag;
152 g_reportThreadFlag = threadFlag;
153 }
154
Report(const std::map<std::string,std::unique_ptr<PerfEvents::CountEvent>> & countEvents)155 void SubCommandStat::Report(const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents)
156 {
157 bool isNeedPerCpuTid = false;
158 for (auto it = countEvents.begin(); it != countEvents.end(); ++it) {
159 if (!(it->second->summaries.empty())) {
160 isNeedPerCpuTid = true;
161 break;
162 }
163 }
164 if (isNeedPerCpuTid) {
165 PrintPerHead();
166 ReportDetailInfos(countEvents);
167 } else {
168 ReportNormal(countEvents);
169 }
170 }
171
PrintPerHead()172 void SubCommandStat::PrintPerHead()
173 {
174 // print head
175 if (g_reportCpuFlag && g_reportThreadFlag) {
176 printf(" %24s %-30s | %-30s %10s %10s %10s | %-32s | %s\n", "count", "event_name", "thread_name",
177 "pid", "tid", "coreid", "comment", "coverage");
178 return;
179 }
180 if (g_reportCpuFlag) {
181 printf(" %24s %-30s | %10s | %-32s | %s\n", "count", "event_name", "coreid", "comment", "coverage");
182 return;
183 }
184 printf(" %24s %-30s | %-30s %10s %10s | %-32s | %s\n", "count", "event_name", "thread_name", "pid", "tid",
185 "comment", "coverage");
186 return;
187 }
188
PrintPerValue(const std::unique_ptr<PerfEvents::ReportSum> & reportSum,const float & ratio,std::string & configName)189 void SubCommandStat::PrintPerValue(const std::unique_ptr<PerfEvents::ReportSum> &reportSum, const float &ratio,
190 std::string &configName)
191 {
192 if (reportSum == nullptr) {
193 return;
194 }
195 // print value
196 std::string strEventCount = std::to_string(reportSum->eventCountSum);
197 for (size_t i = strEventCount.size() >= 1 ? strEventCount.size() - 1 : 0, j = 1; i > 0; --i, ++j) {
198 if (j == THOUSNADS_SEPARATOR) {
199 j = 0;
200 strEventCount.insert(strEventCount.begin() + i, ',');
201 }
202 }
203
204 std::string commentStr;
205 MakeComments(reportSum, commentStr);
206
207 if (g_reportCpuFlag && g_reportThreadFlag) {
208 printf(" %24s %-30s | %-30s %10d %10d %10d | %-32s | (%.0lf%%)\n", strEventCount.c_str(), configName.c_str(),
209 reportSum->threadName.c_str(), reportSum->pid, reportSum->tid, reportSum->cpu, commentStr.c_str(),
210 reportSum->scaleSum * ratio);
211 } else if (g_reportCpuFlag) {
212 printf(" %24s %-30s | %10d | %-32s | (%.0lf%%)\n", strEventCount.c_str(), configName.c_str(),
213 reportSum->cpu, commentStr.c_str(), reportSum->scaleSum * ratio);
214 } else {
215 printf(" %24s %-30s | %-30s %10d %10d | %-32s | (%.0lf%%)\n", strEventCount.c_str(), configName.c_str(),
216 reportSum->threadName.c_str(), reportSum->pid, reportSum->tid, commentStr.c_str(),
217 reportSum->scaleSum * ratio);
218 }
219 fflush(stdout);
220 }
221
InitPerMap(const std::unique_ptr<PerfEvents::ReportSum> & newPerMap,const PerfEvents::Summary & summary,VirtualRuntime & virtualInstance)222 void SubCommandStat::InitPerMap(const std::unique_ptr<PerfEvents::ReportSum> &newPerMap,
223 const PerfEvents::Summary &summary, VirtualRuntime& virtualInstance)
224 {
225 if (newPerMap == nullptr) {
226 return;
227 }
228 newPerMap->cpu = summary.cpu;
229 if (g_reportCpuFlag && !g_reportThreadFlag) {
230 return;
231 }
232 newPerMap->tid = summary.tid;
233 newPerMap->pid = thread_map_.find(summary.tid)->second.pid;
234 bool isTid = true;
235 if (newPerMap->pid == newPerMap->tid) {
236 isTid = false;
237 }
238 newPerMap->threadName = virtualInstance.ReadThreadName(summary.tid, isTid);
239 }
240
GetPerKey(std::string & perKey,const PerfEvents::Summary & summary)241 void SubCommandStat::GetPerKey(std::string &perKey, const PerfEvents::Summary &summary)
242 {
243 perKey = "";
244 if (g_reportCpuFlag) {
245 perKey += std::to_string(summary.cpu);
246 perKey += "|";
247 }
248 if (g_reportThreadFlag) {
249 perKey += std::to_string(summary.tid);
250 }
251 return;
252 }
253
ReportDetailInfos(const std::map<std::string,std::unique_ptr<PerfEvents::CountEvent>> & countEvents)254 void SubCommandStat::ReportDetailInfos(
255 const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents)
256 {
257 std::string perKey = "";
258 std::map<std::string, std::unique_ptr<PerfEvents::ReportSum>> perMaps;
259 for (auto event = countEvents.begin(); event != countEvents.end(); ++event) {
260 if (event->second == nullptr || event->second->eventCount == 0) {
261 continue;
262 }
263 constexpr float ratio {100.0};
264 std::string configName = event->first;
265 perMaps.clear();
266 for (auto &it : event->second->summaries) {
267 GetPerKey(perKey, it);
268 if (perMaps.count(perKey) == 0) {
269 auto perMap = std::make_unique<PerfEvents::ReportSum>(PerfEvents::ReportSum {});
270 InitPerMap(perMap, it, g_runtimeInstance);
271 perMaps[perKey] = std::move(perMap);
272 }
273 if (perMaps[perKey] == nullptr) {
274 continue;
275 }
276 perMaps[perKey]->configName = GetDetailComments(event->second, perMaps[perKey]->commentSum,
277 it, configName);
278 perMaps[perKey]->eventCountSum += it.eventCount;
279 if (it.timeRunning < it.timeEnabled && it.timeRunning != 0) {
280 perMaps[perKey]->scaleSum += 1 / (static_cast<double>(it.timeEnabled) / it.timeRunning);
281 }
282 }
283 for (auto iper = perMaps.begin(); iper != perMaps.end(); iper++) {
284 PrintPerValue(iper->second, ratio, configName);
285 }
286 }
287 }
288
ReportNormal(const std::map<std::string,std::unique_ptr<PerfEvents::CountEvent>> & countEvents)289 void SubCommandStat::ReportNormal(
290 const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents)
291 {
292 // print head
293 printf(" %24s %-30s | %-32s | %s\n", "count", "name", "comment", "coverage");
294 std::map<std::string, std::string> comments;
295 GetComments(countEvents, comments);
296 for (auto it = countEvents.begin(); it != countEvents.end(); ++it) {
297 double scale = 1.0;
298 constexpr float ratio {100.0};
299 std::string configName = it->first;
300 std::string comment = comments[configName];
301 std::string strEventCount = std::to_string(it->second->eventCount);
302 for (size_t i = strEventCount.size() >= 1 ? strEventCount.size() - 1 : 0, j = 1; i > 0; --i, ++j) {
303 if (j == THOUSNADS_SEPARATOR) {
304 strEventCount.insert(strEventCount.begin() + i, ',');
305 j = 0;
306 }
307 }
308 if (it->second->timeRunning < it->second->timeEnabled && it->second->timeRunning != 0) {
309 scale = 1 / (static_cast<double>(it->second->timeEnabled) / it->second->timeRunning);
310 }
311 printf(" %24s %-30s | %-32s | (%.0lf%%)\n", strEventCount.c_str(), configName.c_str(),
312 comment.c_str(), scale * ratio);
313
314 fflush(stdout);
315 }
316 }
317
FindEventCount(const std::map<std::string,std::unique_ptr<PerfEvents::CountEvent>> & countEvents,const std::string & configName,const __u64 group_id,__u64 & eventCount,double & scale)318 bool SubCommandStat::FindEventCount(const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents,
319 const std::string &configName, const __u64 group_id, __u64 &eventCount, double &scale)
320 {
321 auto itr = countEvents.find(configName);
322 if (itr != countEvents.end()) {
323 eventCount = itr->second->eventCount;
324 if (itr->second->id == group_id
325 && itr->second->timeRunning < itr->second->timeEnabled
326 && itr->second->timeRunning != 0) {
327 scale = static_cast<double>(itr->second->timeEnabled) / itr->second->timeRunning;
328 return true;
329 }
330 }
331 return false;
332 }
333
FindPerCoreEventCount(PerfEvents::Summary & summary,__u64 & eventCount,double & scale)334 bool SubCommandStat::FindPerCoreEventCount(PerfEvents::Summary &summary, __u64 &eventCount, double &scale)
335 {
336 eventCount = summary.eventCount;
337 if (summary.timeRunning < summary.timeEnabled && summary.timeRunning != 0) {
338 scale = static_cast<double>(summary.timeEnabled) / summary.timeRunning;
339 return true;
340 }
341 return false;
342 }
343
GetCommentConfigName(const std::unique_ptr<PerfEvents::CountEvent> & countEvent,std::string eventName)344 std::string SubCommandStat::GetCommentConfigName(
345 const std::unique_ptr<PerfEvents::CountEvent> &countEvent, std::string eventName)
346 {
347 std::string commentConfigName = "";
348 if (countEvent == nullptr || eventName.length() == 0) {
349 return commentConfigName;
350 }
351 if (countEvent->userOnly) {
352 commentConfigName = eventName + ":u";
353 } else if (countEvent->kernelOnly) {
354 commentConfigName = eventName + ":k";
355 } else {
356 commentConfigName = eventName;
357 }
358 return commentConfigName;
359 }
360
MakeComments(const std::unique_ptr<PerfEvents::ReportSum> & reportSum,std::string & commentStr)361 void SubCommandStat::MakeComments(const std::unique_ptr<PerfEvents::ReportSum> &reportSum, std::string &commentStr)
362 {
363 if (reportSum == nullptr || reportSum->commentSum == 0) {
364 return;
365 }
366 if (reportSum->configName == "sw-task-clock") {
367 commentStr = StringPrintf("%lf cpus used", reportSum->commentSum);
368 return;
369 }
370 if (reportSum->configName == "hw-cpu-cycles") {
371 commentStr = StringPrintf("%lf GHz", reportSum->commentSum);
372 return;
373 }
374 if (reportSum->configName == "hw-instructions") {
375 commentStr = StringPrintf("%lf cycles per instruction", reportSum->commentSum);
376 return;
377 }
378 if (reportSum->configName == "hw-branch-misses") {
379 commentStr = StringPrintf("%lf miss rate", reportSum->commentSum);
380 return;
381 }
382
383 if (reportSum->commentSum > 1e9) {
384 commentStr = StringPrintf("%.3lf G/sec", reportSum->commentSum / 1e9);
385 return;
386 }
387 if (reportSum->commentSum > 1e6) {
388 commentStr = StringPrintf("%.3lf M/sec", reportSum->commentSum / 1e6);
389 return;
390 }
391 if (reportSum->commentSum > 1e3) {
392 commentStr = StringPrintf("%.3lf K/sec", reportSum->commentSum / 1e3);
393 return;
394 }
395 commentStr = StringPrintf("%.3lf /sec", reportSum->commentSum);
396 }
397
GetDetailComments(const std::unique_ptr<PerfEvents::CountEvent> & countEvent,double & comment,PerfEvents::Summary & summary,std::string & configName)398 std::string SubCommandStat::GetDetailComments(const std::unique_ptr<PerfEvents::CountEvent> &countEvent,
399 double &comment, PerfEvents::Summary &summary, std::string &configName)
400 {
401 double running_time_in_sec = 0;
402 double main_scale = 1.0;
403 bool findRunningTime = FindPercoreRunningTime(summary, running_time_in_sec, main_scale);
404 if (configName == GetCommentConfigName(countEvent, "sw-cpu-clock")) {
405 comment = 0;
406 return "sw-cpu-clock";
407 }
408 double scale = 1.0;
409 if (summary.timeRunning < summary.timeEnabled && summary.timeRunning != 0) {
410 scale = static_cast<double>(summary.timeEnabled) / summary.timeRunning;
411 }
412 if (configName == GetCommentConfigName(countEvent, "sw-task-clock")) {
413 comment += countEvent->usedCpus * scale;
414 return "sw-task-clock";
415 }
416 if (configName == GetCommentConfigName(countEvent, "hw-cpu-cycles")) {
417 if (findRunningTime) {
418 double hz = 0;
419 if (running_time_in_sec != 0) {
420 hz = summary.eventCount / (running_time_in_sec / scale);
421 }
422 comment += hz / 1e9;
423 } else {
424 comment += 0;
425 }
426 return "hw-cpu-cycles";
427 }
428 if (configName == GetCommentConfigName(countEvent, "hw-instructions") && summary.eventCount != 0) {
429 double otherScale = 1.0;
430 __u64 cpuCyclesCount = 0;
431 bool other = FindPerCoreEventCount(summary, cpuCyclesCount, otherScale);
432 if (other || (IsMonitoredAtAllTime(otherScale) && IsMonitoredAtAllTime(scale))) {
433 comment += static_cast<double>(cpuCyclesCount) / summary.eventCount;
434 return "hw-instructions";
435 }
436 }
437 if (configName == GetCommentConfigName(countEvent, "hw-branch-misses")) {
438 double otherScale = 1.0;
439 __u64 branchInstructionsCount = 0;
440 bool other = FindPerCoreEventCount(summary, branchInstructionsCount, otherScale);
441 if ((other || (IsMonitoredAtAllTime(otherScale) && IsMonitoredAtAllTime(scale))) &&
442 branchInstructionsCount != 0) {
443 comment += (static_cast<double>(summary.eventCount) / branchInstructionsCount) * ONE_HUNDRED;
444 return "hw-branch-misses";
445 }
446 }
447 return HandleOtherConfig(comment, summary, running_time_in_sec, scale, findRunningTime);
448 }
449
HandleOtherConfig(double & comment,PerfEvents::Summary & summary,double running_time_in_sec,double scale,bool findRunningTime)450 std::string SubCommandStat::HandleOtherConfig(double &comment, PerfEvents::Summary &summary, double running_time_in_sec,
451 double scale, bool findRunningTime)
452 {
453 comment = 0;
454 if (findRunningTime) {
455 double rate = 0;
456 if (scale != 0) {
457 rate = summary.eventCount / (running_time_in_sec / scale);
458 }
459 comment += rate;
460 }
461 return "";
462 }
463
IsMonitoredAtAllTime(const double & scale)464 bool SubCommandStat::IsMonitoredAtAllTime(const double &scale)
465 {
466 constexpr double SCALE_ERROR_LIMIT = 1e-5;
467 return (fabs(scale - 1.0) < SCALE_ERROR_LIMIT);
468 }
469
GetComments(const std::map<std::string,std::unique_ptr<PerfEvents::CountEvent>> & countEvents,std::map<std::string,std::string> & comments)470 void SubCommandStat::GetComments(const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents,
471 std::map<std::string, std::string> &comments)
472 {
473 double running_time_in_sec = 0;
474 __u64 group_id = 0;
475 double main_scale = 1.0;
476 bool findRunningTime = FindRunningTime(countEvents, running_time_in_sec, group_id, main_scale);
477 for (auto it = countEvents.begin(); it != countEvents.end(); it++) {
478 std::string configName = it->first;
479 std::string commentConfigName = GetCommentConfigName(it->second, "sw-cpu-clock");
480 if (configName == commentConfigName) {
481 comments[configName] = "";
482 continue;
483 }
484 double scale = 1.0;
485 if (it->second->timeRunning < it->second->timeEnabled && it->second->timeRunning != 0) {
486 scale = static_cast<double>(it->second->timeEnabled) / it->second->timeRunning;
487 }
488 commentConfigName = GetCommentConfigName(it->second, "sw-task-clock");
489 if (configName == commentConfigName) {
490 double usedCpus = it->second->usedCpus * scale;
491 comments[configName] = StringPrintf("%lf cpus used", usedCpus);
492 continue;
493 }
494 commentConfigName = GetCommentConfigName(it->second, "hw-cpu-cycles");
495 if (configName == commentConfigName) {
496 if (findRunningTime &&
497 ((group_id == it->second->id) ||
498 (IsMonitoredAtAllTime(main_scale) && IsMonitoredAtAllTime(scale)))) {
499 double hz = 0;
500 if (running_time_in_sec != 0) {
501 hz = it->second->eventCount / (running_time_in_sec / scale);
502 }
503 comments[configName] = StringPrintf("%lf GHz", hz / 1e9);
504 } else {
505 comments[configName] = "";
506 }
507 continue;
508 }
509 commentConfigName = GetCommentConfigName(it->second, "hw-instructions");
510 if (configName == commentConfigName && it->second->eventCount != 0) {
511 std::string cpuSyclesName = GetCommentConfigName(it->second, "hw-cpu-cycles");
512 double otherScale = 1.0;
513 __u64 cpuCyclesCount = 0;
514 bool other = FindEventCount(countEvents, cpuSyclesName, it->second->id, cpuCyclesCount,
515 otherScale);
516 if (other || (IsMonitoredAtAllTime(otherScale) && IsMonitoredAtAllTime(scale))) {
517 double cpi = static_cast<double>(cpuCyclesCount) / it->second->eventCount;
518 comments[configName] = StringPrintf("%lf cycles per instruction", cpi);
519 continue;
520 }
521 }
522 commentConfigName = GetCommentConfigName(it->second, "hw-branch-misses");
523 if (configName == commentConfigName) {
524 std::string branchInsName = GetCommentConfigName(it->second, "hw-branch-instructions");
525 double otherScale = 1.0;
526 __u64 branchInstructionsCount = 0;
527 bool other = FindEventCount(countEvents, branchInsName, it->second->id,
528 branchInstructionsCount, otherScale);
529 if ((other || (IsMonitoredAtAllTime(otherScale) && IsMonitoredAtAllTime(scale))) &&
530 branchInstructionsCount != 0) {
531 double miss_rate =
532 static_cast<double>(it->second->eventCount) / branchInstructionsCount;
533 comments[configName] = StringPrintf("%lf miss rate", miss_rate * ONE_HUNDRED);
534 continue;
535 }
536 }
537 if (findRunningTime && ((group_id == it->second->id) || (IsMonitoredAtAllTime(main_scale) &&
538 IsMonitoredAtAllTime(scale)))) {
539 double rate = it->second->eventCount / (running_time_in_sec / scale);
540 if (rate > 1e9) {
541 comments[configName] = StringPrintf("%.3lf G/sec", rate / 1e9);
542 continue;
543 }
544 if (rate > 1e6) {
545 comments[configName] = StringPrintf("%.3lf M/sec", rate / 1e6);
546 continue;
547 }
548 if (rate > 1e3) {
549 comments[configName] = StringPrintf("%.3lf K/sec", rate / 1e3);
550 continue;
551 }
552 comments[configName] = StringPrintf("%.3lf /sec", rate);
553 } else {
554 comments[configName] = "";
555 }
556 }
557 }
558
FindRunningTime(const std::map<std::string,std::unique_ptr<PerfEvents::CountEvent>> & countEvents,double & running_time_in_sec,__u64 & group_id,double & main_scale)559 bool SubCommandStat::FindRunningTime(
560 const std::map<std::string, std::unique_ptr<PerfEvents::CountEvent>> &countEvents,
561 double &running_time_in_sec, __u64 &group_id, double &main_scale)
562 {
563 for (auto it = countEvents.begin(); it != countEvents.end(); it++) {
564 if ((it->first == "sw-task-clock" || it->first == "sw-task-clock:u" ||
565 it->first == "sw-task-clock:k" || it->first == "sw-cpu-clock" ||
566 it->first == "sw-cpu-clock:u" || it->first == "sw-cpu-clock:k") &&
567 it->second->eventCount != 0u) {
568 group_id = it->second->id;
569 running_time_in_sec = it->second->eventCount / 1e9;
570 if (it->second->timeRunning < it->second->timeEnabled &&
571 it->second->timeRunning != 0) {
572 main_scale =
573 static_cast<double>(it->second->timeEnabled) / it->second->timeRunning;
574 }
575 return true;
576 }
577 }
578 return false;
579 }
580
FindPercoreRunningTime(PerfEvents::Summary & summary,double & running_time_int_sec,double & main_scale)581 bool SubCommandStat::FindPercoreRunningTime(PerfEvents::Summary &summary, double &running_time_int_sec,
582 double &main_scale)
583 {
584 if (summary.eventCount == 0) {
585 return false;
586 }
587 running_time_int_sec = summary.eventCount / 1e9;
588 if (summary.timeRunning < summary.timeEnabled && summary.timeRunning != 0) {
589 main_scale = static_cast<double>(summary.timeEnabled) / summary.timeRunning;
590 }
591 return true;
592 }
593
CheckOptionPidAndApp(std::vector<pid_t> pids)594 bool SubCommandStat::CheckOptionPidAndApp(std::vector<pid_t> pids)
595 {
596 if (!CheckOptionPid(pids)) {
597 printf("Problems finding threads of monitor\n\n");
598 printf("Usage: perf stat [<options>] [<command>]\n\n");
599 printf("-p <pid> stat events on existing process id\n");
600 printf("-t <tid> stat events on existing thread id\n");
601 return false;
602 }
603 return true;
604 }
605
CheckOptionPid(std::vector<pid_t> pids)606 bool SubCommandStat::CheckOptionPid(std::vector<pid_t> pids)
607 {
608 if (pids.empty()) {
609 return true;
610 }
611
612 for (auto pid : pids) {
613 if (!IsDir("/proc/" + std::to_string(pid))) {
614 printf("not exit pid %d\n", pid);
615 return false;
616 }
617 }
618 return true;
619 }
620
SetPerfEvent()621 void SubCommandStat::SetPerfEvent()
622 {
623 SetReportFlags(perCpus_, perThreads_);
624 perfEvents_.SetSystemTarget(targetSystemWide_);
625 perfEvents_.SetTimeOut(timeStopSec_);
626 perfEvents_.SetTimeReport(timeReportMs_);
627 perfEvents_.SetPerCpu(perCpus_);
628 perfEvents_.SetPerThread(perThreads_);
629 perfEvents_.SetVerboseReport(verboseReport_);
630 perfEvents_.SetInherit(!noCreateNew_);
631 perfEvents_.SetTrackedCommand(trackedCommand_);
632 // set report handle
633 perfEvents_.SetStatCallBack(Report);
634 }
635
OnSubCommand(std::vector<std::string> & args)636 bool SubCommandStat::OnSubCommand(std::vector<std::string> &args)
637 {
638 if (HelpOption()) {
639 return true;
640 }
641 if (!CheckRestartOption(appPackage_, targetSystemWide_, restart_, selectPids_)) {
642 return false;
643 }
644 // check option
645 if (!CheckSelectCpuPidOption()) {
646 return false;
647 }
648 if (!CheckOptions(selectPids_)) {
649 HLOGV("CheckOptions() failed");
650 return false;
651 }
652 if (!CheckAppIsRunning(selectPids_, appPackage_, checkAppMs_)) {
653 HLOGV("CheckAppIsRunning() failed");
654 return false;
655 }
656
657 perfEvents_.SetCpu(selectCpus_);
658 std::vector<pid_t> pids;
659 for (auto selectPid : selectPids_) {
660 HLOGD("[OnSubCommand] selectPid %d\n", selectPid);
661 std::vector<pid_t> subTids = GetSubthreadIDs(selectPid, thread_map_);
662 if (!subTids.empty()) {
663 pids.insert(pids.end(), subTids.begin(), subTids.end());
664 } else {
665 HLOGD("[OnSubCommand] subTids empty for %d\n", selectPid);
666 }
667 }
668 pids.insert(pids.end(), selectTids_.begin(), selectTids_.end());
669 perfEvents_.SetPid(pids);
670 if (!CheckOptionPidAndApp(pids)) {
671 HLOGV("CheckOptionPidAndApp() failed");
672 return false;
673 }
674 SetPerfEvent();
675 if (!PrepairEvents()) {
676 HLOGV("PrepairEvents() failed");
677 return false;
678 }
679
680 // preapare fd
681 perfEvents_.PrepareTracking();
682
683 // start tracking
684 perfEvents_.StartTracking();
685
686 return true;
687 }
688
RegisterSubCommandStat()689 bool RegisterSubCommandStat()
690 {
691 return SubCommand::RegisterSubCommand("stat", std::make_unique<SubCommandStat>());
692 }
693
PrepairEvents()694 bool SubCommandStat::PrepairEvents()
695 {
696 if (selectEvents_.empty() && selectGroups_.empty()) {
697 perfEvents_.AddDefaultEvent(PERF_TYPE_HARDWARE);
698 perfEvents_.AddDefaultEvent(PERF_TYPE_SOFTWARE);
699 } else {
700 for (auto events : selectEvents_) {
701 if (!perfEvents_.AddEvents(events)) {
702 HLOGV("add events failed");
703 return false;
704 }
705 }
706 for (auto events : selectGroups_) {
707 if (!perfEvents_.AddEvents(events, true)) {
708 HLOGV("add groups failed");
709 return false;
710 }
711 }
712 }
713 return true;
714 }
715
CheckSelectCpuPidOption()716 bool SubCommandStat::CheckSelectCpuPidOption()
717 {
718 if (!selectCpus_.empty()) {
719 // the only value is not -1
720 if (!(selectCpus_.size() == 1 && selectCpus_.front() == -1)) {
721 int maxCpuid = sysconf(_SC_NPROCESSORS_CONF) - 1;
722 for (auto cpu : selectCpus_) {
723 if (cpu < 0 || cpu > maxCpuid) {
724 printf("Invalid -c value '%d', the CPU ID should be in 0~%d \n", cpu, maxCpuid);
725 return false;
726 }
727 }
728 }
729 } else {
730 // the cpu default -1
731 if (!targetSystemWide_) {
732 selectCpus_.push_back(-1);
733 }
734 }
735
736 if (!selectPids_.empty()) {
737 for (auto pid : selectPids_) {
738 if (pid <= 0) {
739 printf("Invalid -p value '%d', the pid should be larger than 0\n", pid);
740 return false;
741 }
742 }
743 }
744 if (!selectTids_.empty()) {
745 for (auto tid : selectTids_) {
746 if (tid <= 0) {
747 printf("Invalid -t value '%d', the tid should be larger than 0\n", tid);
748 return false;
749 }
750 }
751 }
752 return true;
753 }
754
CheckOptions(const std::vector<pid_t> & pids)755 bool SubCommandStat::CheckOptions(const std::vector<pid_t> &pids)
756 {
757 if (targetSystemWide_) {
758 if (!pids.empty() || !selectTids_.empty()) {
759 printf("You cannot specify -a and -t/-p at the same time\n");
760 return false;
761 }
762 if (!appPackage_.empty()) {
763 printf("You cannot specify -a and --app at the same time\n");
764 return false;
765 }
766 }
767 if (!appPackage_.empty() && (!pids.empty() || !selectTids_.empty())) {
768 printf("You cannot specify --app and -t/-p at the same time\n");
769 return false;
770 }
771 if (!targetSystemWide_ && trackedCommand_.empty() && pids.empty() && appPackage_.empty()
772 && selectTids_.empty() ) {
773 printf("You need to set the -p option or --app option.\n");
774 return false;
775 }
776 if (targetSystemWide_ && !trackedCommand_.empty()) {
777 printf("You cannot specify -a and a cmd at the same time\n");
778 return false;
779 }
780 if (!trackedCommand_.empty()) {
781 if (!pids.empty() || !selectTids_.empty()) {
782 printf("You cannot specify a cmd and -t/-p at the same time\n");
783 return false;
784 }
785 if (!appPackage_.empty()) {
786 printf("You cannot specify a cmd and --app at the same time\n");
787 return false;
788 }
789 }
790 if (checkAppMs_ < MIN_CHECK_APP_MS || checkAppMs_ > MAX_CHECK_APP_MS) {
791 printf("Invalid --chkms value '%d', the milliseconds should be in %d~%d \n", checkAppMs_,
792 MIN_CHECK_APP_MS, MAX_CHECK_APP_MS);
793 return false;
794 }
795 if (timeStopSec_ < 0) {
796 printf("monitoring duration should be positive but %f is given\n", timeStopSec_);
797 return false;
798 }
799 if (timeReportMs_ < 0) {
800 printf("print interval should be non-negative but %d is given\n", timeReportMs_);
801 return false;
802 }
803 return true;
804 }
805 } // namespace HiPerf
806 } // namespace Developtools
807 } // namespace OHOS
808