• 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 #define HILOG_TAG "Report"
16 
17 #include "subcommand_report.h"
18 
19 #include <memory>
20 #include <set>
21 #include <sstream>
22 
23 #if is_mingw
24 #include <windows.h>
25 #else
26 #include <sys/ioctl.h>
27 #endif
28 
29 #include "perf_events.h"
30 #include "register.h"
31 #include "utilities.h"
32 
33 namespace OHOS {
34 namespace Developtools {
35 namespace HiPerf {
ParseOption(std::vector<std::string> & args)36 bool SubCommandReport::ParseOption(std::vector<std::string> &args)
37 {
38     if (!Option::GetOptionValue(args, "-i", recordFile_[FIRST])) {
39         return false;
40     }
41     if (!Option::GetOptionValue(args, "-o", reportFile_)) {
42         return false;
43     }
44     if (!Option::GetOptionValue(args, "--diff", recordFile_[SECOND])) {
45         return false;
46     }
47     if (!recordFile_[SECOND].empty()) {
48         // remove tid pid
49         reportOption_.sortKeys_ = {"comm", "dso", "func"};
50     }
51     if (!Option::GetOptionValue(args, "--sort", reportOption_.sortKeys_)) {
52         return false;
53     }
54 
55     if (!Option::GetOptionValue(args, "--symbol-dir", symbolsPaths_)) {
56         return false;
57     }
58     if (!Option::GetOptionValue(args, "--limit-percent", reportOption_.heatLimit_)) {
59         return false;
60     }
61 
62     if (!Option::GetOptionValue(args, "-s", showCallStack_)) {
63         return false;
64     }
65     if (!Option::GetOptionValue(args, "--call-stack", showCallStack_)) {
66         return false;
67     }
68 
69     if (!Option::GetOptionValue(args, "--call-stack-limit-percent",
70                                 reportOption_.callStackHeatLimit_)) {
71         return false;
72     }
73 
74     if (!Option::GetOptionValue(args, "--comms", reportOption_.displayComms_)) {
75         return false;
76     }
77     if (!Option::GetOptionValue(args, "--pids", reportOption_.displayPids_)) {
78         return false;
79     }
80     if (!Option::GetOptionValue(args, "--tids", reportOption_.displayTids_)) {
81         return false;
82     }
83     if (!Option::GetOptionValue(args, "--dsos", reportOption_.displayDsos_)) {
84         return false;
85     }
86     if (!Option::GetOptionValue(args, "--funcs", reportOption_.displayFuncs_)) {
87         return false;
88     }
89     if (!Option::GetOptionValue(args, "--from_dsos", reportOption_.displayFuncs_)) {
90         return false;
91     }
92     if (!Option::GetOptionValue(args, "--from_funcs", reportOption_.displayFuncs_)) {
93         return false;
94     }
95     if (!Option::GetOptionValue(args, "--proto", protobufFormat_)) {
96         return false;
97     }
98     if (!Option::GetOptionValue(args, "--json", jsonFormat_)) {
99         return false;
100     }
101     if (!Option::GetOptionValue(args, "--debug", debug_)) {
102         return false;
103     }
104     if (!Option::GetOptionValue(args, "--branch", branch_)) {
105         return false;
106     }
107     // this is a hidden option for compare result
108     if (!Option::GetOptionValue(args, "--hide_count", reportOption_.hideCount_)) {
109         return false;
110     }
111     return VerifyOption();
112 }
113 
DumpOptions() const114 void SubCommandReport::DumpOptions() const
115 {
116     printf("DumpOptions:\n");
117     printf(" recordFile_:\t%s\n", recordFile_[FIRST].c_str());
118     printf(" recordFile_:\t%s\n", recordFile_[SECOND].c_str());
119     printf(" reportFile_:\t%s\n", reportFile_.c_str());
120     printf(" sortKeys:\t%s\n", VectorToString(reportOption_.sortKeys_).c_str());
121 }
VerifyDisplayOption()122 bool SubCommandReport::VerifyDisplayOption()
123 {
124     for (std::string &number : reportOption_.displayPids_) {
125         if (!IsDigits(number) or number.front() == '-') {
126             printf("error number for pid '%s'\n", number.c_str());
127             return false;
128         }
129     }
130 
131     for (std::string &number : reportOption_.displayTids_) {
132         if (!IsDigits(number) or number.front() == '-') {
133             printf("error number for tid '%s'\n", number.c_str());
134             return false;
135         }
136     }
137     return true;
138 }
139 
VerifyOption()140 bool SubCommandReport::VerifyOption()
141 {
142     for (auto key : reportOption_.sortKeys_) {
143         if (key == "count") {
144             printf("unknown sort key name '%s'\n", key.c_str());
145             return false;
146         } else if (GetReport().reportKeyMap_.count(key) == 0) {
147             printf("unknown sort key name '%s'\n", key.c_str());
148             return false;
149         }
150     }
151     const float min = 0.0;
152     const float max = 100.0;
153     if (reportOption_.heatLimit_ < min or reportOption_.heatLimit_ > max) {
154         printf("head limit error. must in (0 <= limit < 100).\n");
155         return false;
156     }
157     if (reportOption_.callStackHeatLimit_ < min or reportOption_.callStackHeatLimit_ > max) {
158         printf("head limit error. must in (0 <= limit < 100).\n");
159         return false;
160     }
161     if (recordFile_[FIRST].empty()) {
162         printf("input file name can't be empty\n");
163         return false;
164     }
165     if (!recordFile_[SECOND].empty()) {
166         if (protobufFormat_ or jsonFormat_ or showCallStack_) {
167             printf("diff don't support any export mode(like json , flame or proto)\n");
168         } else {
169             diffMode_ = true;
170         }
171     }
172 
173     // default report file name
174     if (reportFile_.empty()) {
175         if (protobufFormat_) {
176             reportFile_ = "perf.proto";
177         } else if (jsonFormat_) {
178             reportFile_ = "perf.json";
179         }
180     }
181 
182     // misc config
183     reportOption_.debug_ = debug_;
184     ReportJsonFile::debug_ = debug_;
185 
186     return VerifyDisplayOption();
187 }
188 
BroadcastSample(std::unique_ptr<PerfRecordSample> & sample)189 void SubCommandReport::BroadcastSample(std::unique_ptr<PerfRecordSample> &sample)
190 {
191     // this func use for cpuoff mode , it will Broadcast the sampe to every event config
192     for (auto &config : GetReport().configs_) {
193         HLOGM("resend as id %" PRIu64 "", config.ids_[0]);
194         sample->data_.id = config.ids_[0];
195         ProcessSample(sample);
196     }
197 }
198 
ProcessSample(std::unique_ptr<PerfRecordSample> & sample)199 void SubCommandReport::ProcessSample(std::unique_ptr<PerfRecordSample> &sample)
200 {
201     sample->DumpLog(__FUNCTION__);
202     if (jsonFormat_) {
203         reportJsonFile_->UpdateReportSample(sample->data_.id, sample->data_.pid, sample->data_.tid,
204                                             sample->data_.period);
205         reportJsonFile_->UpdateReportCallStack(sample->data_.id, sample->data_.pid,
206                                                sample->data_.tid, sample->data_.period,
207                                                sample->callFrames_);
208     } else if (protobufFormat_) {
209 #if HAVE_PROTOBUF
210         // make some cook
211         // redesgin here
212         protobufOutputFileWriter_->ProcessSampleRecord(
213             *sample, static_cast<uint32_t>(GetReport().GetConfigIndex(sample->data_.id)),
214             GetReport().virtualRuntime_.GetSymbolsFiles());
215 #endif
216     } else {
217         if (branch_) {
218             GetReport().AddReportItemBranch(*sample);
219         } else {
220             GetReport().AddReportItem(*sample, showCallStack_);
221         }
222     }
223 }
224 
RecordCallBack(std::unique_ptr<PerfEventRecord> record)225 bool SubCommandReport::RecordCallBack(std::unique_ptr<PerfEventRecord> record)
226 {
227     // tell process tree what happend for rebuild symbols
228     GetReport().virtualRuntime_.UpdateFromRecord(*record);
229 
230     if (record->GetType() == PERF_RECORD_SAMPLE) {
231         std::unique_ptr<PerfRecordSample> sample(static_cast<PerfRecordSample *>(record.release()));
232         std::unique_ptr<PerfRecordSample> prevSample = nullptr;
233         if (cpuOffMode_) {
234             auto prevIt = prevSampleCache_.find(sample->data_.tid);
235             if (prevIt == prevSampleCache_.end()) {
236                 // this thread first sample
237                 prevSampleCache_[sample->data_.tid] = std::move(sample);
238                 // do nothing because we unable to calc the period
239                 return true;
240             } else {
241                 // we have prev sample
242                 prevSample = std::move(prevIt->second);
243                 HLOGV("calc time %llu - %llu", sample->data_.time, prevSample->data_.time);
244                 if (sample->data_.time > prevSample->data_.time) {
245                     prevSample->data_.period = sample->data_.time - prevSample->data_.time;
246                 } else {
247                     prevSample->data_.period = 1u;
248                 }
249 
250                 // current move the prev
251                 prevIt->second = std::move(sample);
252                 // go on with prevSample
253                 sample = std::move(prevSample);
254 
255                 HLOGV("current sample period %llu ", sample->data_.period);
256             }
257         }
258         if (cpuOffMode_ and cpuOffids_.size() > 0 and cpuOffids_.count(sample->data_.id) > 0) {
259             BroadcastSample(sample);
260         } else {
261             ProcessSample(sample);
262         }
263     } else {
264 #if HAVE_PROTOBUF
265         if (protobufFormat_) {
266             protobufOutputFileWriter_->ProcessRecord(*record);
267         }
268 #endif
269     }
270     return true;
271 }
272 
LoadPerfDataCompleted()273 void SubCommandReport::LoadPerfDataCompleted()
274 {
275     if (jsonFormat_) {
276         reportJsonFile_->UpdateCallNodeEventCount();
277     }
278     HLOGV("load perf data done");
279 }
280 
ProcessSymbolsData()281 void SubCommandReport::ProcessSymbolsData()
282 {
283     GetReport().virtualRuntime_.SetSymbolsPaths(symbolsPaths_);
284     // we need unwind it (for function name match) even not give us path
285     GetReport().virtualRuntime_.SetDisableUnwind(false);
286 
287     // found symbols in file
288     const auto featureSection = recordFileReader_->GetFeatureSection(FEATURE::HIPERF_FILES_SYMBOL);
289     if (featureSection != nullptr) {
290         const PerfFileSectionSymbolsFiles *sectionSymbolsFiles =
291             static_cast<const PerfFileSectionSymbolsFiles *>(featureSection);
292         GetReport().virtualRuntime_.UpdateFromPerfData(sectionSymbolsFiles->symbolFileStructs_);
293     }
294 #if HAVE_PROTOBUF
295     // we have load the elf
296     // write it to proto first
297     if (protobufFormat_) {
298         protobufOutputFileWriter_->ProcessSymbolsFiles(
299             GetReport().virtualRuntime_.GetSymbolsFiles());
300     }
301 #endif
302     if (jsonFormat_) {
303         reportJsonFile_->ProcessSymbolsFiles(GetReport().virtualRuntime_.GetSymbolsFiles());
304     }
305 }
306 
UpdateReportInfo()307 void SubCommandReport::UpdateReportInfo()
308 {
309     // get some meta info for protobuf
310     if (protobufFormat_) {
311         // workload
312         const PerfFileSection *featureSection =
313             recordFileReader_->GetFeatureSection(FEATURE::HIPERF_WORKLOAD_CMD);
314         std::string workloader = "";
315         if (featureSection != nullptr) {
316             HLOGV("found HIPERF_META_WORKLOAD_CMD");
317             const PerfFileSectionString *sectionString =
318                 static_cast<const PerfFileSectionString *>(featureSection);
319             workloader = sectionString->toString();
320         } else {
321             HLOGW("NOT found HIPERF_META_WORKLOAD_CMD");
322         }
323         protobufOutputFileWriter_->ProcessReportInfo(configNames_, workloader);
324     }
325 }
326 
LoadEventConfigData()327 void SubCommandReport::LoadEventConfigData()
328 {
329     auto features = recordFileReader_->GetFeatures();
330     cpuOffMode_ = find(features.begin(), features.end(), FEATURE::HIPERF_CPU_OFF) != features.end();
331     if (cpuOffMode_) {
332         HLOGD("this is cpuOffMode ");
333     }
334     const PerfFileSection *featureSection =
335         recordFileReader_->GetFeatureSection(FEATURE::EVENT_DESC);
336     if (featureSection != nullptr) {
337         HLOGV("have EVENT_DESC");
338         LoadEventDesc();
339     } else {
340         HLOGV("have Attr Section");
341         LoadAttrSection();
342     }
343     HLOG_ASSERT(GetReport().configs_.size() > 0);
344     HLOGV("record %d have %zu configs", index_, GetReport().configs_.size());
345 }
346 
LoadEventDesc()347 void SubCommandReport::LoadEventDesc()
348 {
349     const PerfFileSection *featureSection =
350         recordFileReader_->GetFeatureSection(FEATURE::EVENT_DESC);
351     const PerfFileSectionEventDesc &sectionEventdesc =
352         *static_cast<const PerfFileSectionEventDesc *>(featureSection);
353     HLOGV("Event descriptions: %zu", sectionEventdesc.eventDesces_.size());
354     for (size_t i = 0; i < sectionEventdesc.eventDesces_.size(); i++) {
355         const AttrWithId &fileAttr = sectionEventdesc.eventDesces_[i];
356 
357         HLOGV("event name[%zu]: %s ids: %s", i, fileAttr.name.c_str(),
358               VectorToString(fileAttr.ids).c_str());
359         if (cpuOffMode_ and fileAttr.name == cpuOffEventName) {
360             // found cpuoff event id
361             std::set<uint64_t> cpuOffids(fileAttr.ids.begin(), fileAttr.ids.end());
362             cpuOffids_ = cpuOffids;
363             HLOGV("this is cpu off event");
364         } else {
365             // don't add cpuoff event
366             if (protobufFormat_) {
367                 configNames_.emplace_back(fileAttr.name);
368             }
369             for (uint64_t id : fileAttr.ids) {
370                 GetReport().configIdIndexMaps_[id] = GetReport().configs_.size(); // setup index
371                 HLOGV("add config id map %" PRIu64 " to %zu", id, GetReport().configs_.size());
372             }
373             // when cpuOffMode_ , don't use count mode , use time mode.
374             auto &config =
375                 GetReport().configs_.emplace_back(fileAttr.name, fileAttr.attr.type,
376                                                   fileAttr.attr.config, cpuOffMode_ ? false : true);
377             config.ids_ = fileAttr.ids;
378             HLOG_ASSERT(config.ids_.size() > 0);
379             if (jsonFormat_) {
380                 reportJsonFile_->reportConfigItems_.emplace(
381                     fileAttr.ids,
382                     ReportConfigItem(reportJsonFile_->reportConfigItems_.size(), fileAttr.name));
383             }
384         }
385     }
386 }
387 
LoadAttrSection()388 void SubCommandReport::LoadAttrSection()
389 {
390     std::vector<AttrWithId> attrIds = recordFileReader_->GetAttrSection();
391     for (size_t i = 0; i < attrIds.size(); ++i) {
392         const AttrWithId &fileAttr = attrIds[i];
393         std::string name = PerfEvents::GetStaticConfigName(
394             static_cast<perf_type_id>(fileAttr.attr.type), fileAttr.attr.config);
395         configNames_.emplace_back(name);
396         for (uint64_t id : fileAttr.ids) {
397             GetReport().configIdIndexMaps_[id] = GetReport().configs_.size(); // setup index
398             HLOGV("add config id map %" PRIu64 " to %zu", id, GetReport().configs_.size());
399         }
400         auto &config = GetReport().configs_.emplace_back(fileAttr.name, fileAttr.attr.type,
401                                                          fileAttr.attr.config);
402         config.ids_ = fileAttr.ids;
403         HLOG_ASSERT(config.ids_.size() > 0);
404         if (jsonFormat_) {
405             reportJsonFile_->reportConfigItems_.emplace(
406                 fileAttr.ids, ReportConfigItem(reportJsonFile_->reportConfigItems_.size(), name));
407         }
408         HLOGV("event name[%zu]: %s ids: %s", i, name_.c_str(),
409               VectorToString(fileAttr.ids).c_str());
410     }
411 }
412 
ProcessFeaturesData()413 void SubCommandReport::ProcessFeaturesData()
414 {
415     LoadEventConfigData();
416 
417     // update device arch from feature
418     SetDeviceArch(GetArchTypeFromUname(recordFileReader_->GetFeatureString(FEATURE::ARCH)));
419 
420 #if HAVE_PROTOBUF
421     UpdateReportInfo();
422 #endif
423 }
424 
FlushCacheRecord()425 void SubCommandReport::FlushCacheRecord()
426 {
427     for (auto &pair : prevSampleCache_) {
428         std::unique_ptr<PerfRecordSample> sample = std::move(pair.second);
429         sample->data_.period = 1u;
430         if (cpuOffMode_ and cpuOffids_.size() > 0 and cpuOffids_.count(sample->data_.id) > 0) {
431             BroadcastSample(sample);
432         } else {
433             ProcessSample(sample);
434         }
435     }
436     prevSampleCache_.clear();
437 }
438 
LoadPerfData()439 bool SubCommandReport::LoadPerfData()
440 {
441     HLOGV("enter");
442     // check if file exist
443     if (access(recordFile_[index_].c_str(), F_OK) != 0) {
444         // file not exists
445         printf("Can not access data file %s\n", recordFile_[index_].c_str());
446         return false;
447     }
448 
449     // try load the file
450     recordFileReader_ = PerfFileReader::Instance(recordFile_[index_]);
451     if (recordFileReader_ == nullptr) {
452         HLOGE("FileReader::Instance(%s) return null", recordFile_[index_].c_str());
453         return false;
454     }
455 
456     if (!recordFileReader_->ReadFeatureSection()) {
457         printf("record format error.\n");
458         return false;
459     }
460     if (jsonFormat_) {
461         reportJsonFile_ =
462             std::make_unique<ReportJsonFile>(recordFileReader_, GetReport().virtualRuntime_);
463     }
464 
465     ProcessFeaturesData();
466     ProcessSymbolsData();
467 
468     HLOGD("process record");
469     recordFileReader_->ReadDataSection(
470         std::bind(&SubCommandReport::RecordCallBack, this, std::placeholders::_1));
471     if (cpuOffMode_) {
472         FlushCacheRecord();
473     }
474     HLOGD("process record completed");
475 
476     LoadPerfDataCompleted();
477     return true;
478 }
479 
OutputStd()480 bool SubCommandReport::OutputStd()
481 {
482     if (fprintf(output_, "<<Hiperf Report%s>>\n", diffMode_ ? " Diff" : "") < 0) {
483         return false;
484     }
485 
486     // feature string:
487     const auto &featureSections = recordFileReader_->GetFeatureSections();
488     HLOGV("featureSections: %zu ", featureSections.size());
489 
490     for (auto &featureSection : featureSections) {
491         if (recordFileReader_->IsFeatrureStringSection(featureSection->featureId_)) {
492             const PerfFileSectionString *sectionString =
493                 static_cast<const PerfFileSectionString *>(featureSection.get());
494 
495             fprintf(output_, "%s: %s\n",
496                     PerfFileSection::GetFeatureName(featureSection.get()->featureId_).c_str(),
497                     sectionString->toString().c_str());
498         }
499     }
500 
501     if (cpuOffMode_) {
502         fprintf(output_, "cpu off mode: enabled\n");
503     }
504 
505     if (!diffMode_) {
506         GetReport(FIRST).AdjustReportItems();
507         GetReport(FIRST).OutputStd(output_);
508     } else {
509         GetReport(FIRST).AdjustReportItems();
510         GetReport(SECOND).AdjustReportItems();
511         GetReport(FIRST).OutputStdDiff(output_, GetReport(SECOND));
512     }
513 
514     return true;
515 }
516 
OutputReport()517 bool SubCommandReport::OutputReport()
518 {
519     HLOGV("enter");
520     if (output_ == nullptr) {
521         HLOGD("nothing need output");
522         return true; //
523     } else if (jsonFormat_) {
524         HLOGD("report as json");
525         return reportJsonFile_->OutputJson(output_);
526     } else {
527         return OutputStd();
528     }
529 }
530 
PrepareOutput()531 bool SubCommandReport::PrepareOutput()
532 {
533     HLOGV("enter");
534     if (protobufFormat_) {
535 #if HAVE_PROTOBUF
536         printf("save to protobuf file: '%s'\n", reportFile_.c_str());
537         protobufOutputFileWriter_ = std::make_unique<ReportProtobufFileWriter>();
538         protobufOutputFileWriter_->Create(reportFile_);
539 #endif
540         return true;
541     }
542 
543     if (!reportFile_.empty()) {
544         std::string resolvedPath = CanonicalizeSpecPath(reportFile_.c_str());
545         output_ = fopen(resolvedPath.c_str(), "w");
546         if (output_ == nullptr) {
547             printf("unable open file to '%s' because '%d'\n", reportFile_.c_str(), errno);
548             return false;
549         } else {
550             printf("report will save at '%s'\n", reportFile_.c_str());
551         }
552     } else {
553         output_ = stdout;
554     }
555 
556     return true;
557 }
558 
~SubCommandReport()559 SubCommandReport::~SubCommandReport()
560 {
561     HLOGV("enter");
562 #if HAVE_PROTOBUF
563     if (protobufOutputFileWriter_ != nullptr) {
564         protobufOutputFileWriter_->Close();
565     }
566 #endif
567     if (output_ != nullptr && output_ != stdout) {
568         fclose(output_);
569     }
570 
571     SymbolsFile::onRecording_ = true; // back to default for UT
572 }
573 
OnSubCommand(std::vector<std::string> & args)574 bool SubCommandReport::OnSubCommand(std::vector<std::string> &args)
575 {
576     HLOGV("enter");
577 
578     if (!PrepareOutput()) {
579         return false;
580     }
581 
582     // any way tell symbols this is not on recording
583     SymbolsFile::onRecording_ = false;
584 
585     printf("loading data\n");
586     if (!LoadPerfData()) {
587         return false;
588     }
589 
590     if (diffMode_) {
591         // we are in diff mode
592         index_ = SECOND;
593         // load again with second file
594         if (!LoadPerfData()) {
595             return false;
596         }
597         // back to first
598         index_ = FIRST;
599     }
600     printf("prepare report\n");
601     if (!OutputReport()) {
602         HLOGD("OutputReport failed");
603         return false;
604     }
605 #ifdef HIPERF_DEBUG_TIME
606     printf("SymbolicRecordTimes: %0.3f ms\n",
607            GetReport(FIRST).virtualRuntime_.symbolicRecordTimes_.count() / MS_DUARTION);
608 #endif
609 
610     printf("report done\n");
611     return true;
612 }
613 
RegisterSubCommandReport()614 bool SubCommandReport::RegisterSubCommandReport()
615 {
616     HLOGV("enter");
617     std::unique_ptr<SubCommand> cmd = std::make_unique<SubCommandReport>();
618     return SubCommand::RegisterSubCommand("report", std::move(cmd));
619 }
620 } // namespace HiPerf
621 } // namespace Developtools
622 } // namespace OHOS
623