• 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     // check if file exist
442     if (access(recordFile_[index_].c_str(), F_OK) != 0) {
443         // file not exists
444         printf("Can not access data file %s\n", recordFile_[index_].c_str());
445         return false;
446     }
447 
448     // try load the file
449     recordFileReader_ = PerfFileReader::Instance(recordFile_[index_]);
450     if (recordFileReader_ == nullptr) {
451         HLOGE("FileReader::Instance(%s) return null", recordFile_[index_].c_str());
452         return false;
453     }
454 
455     if (!recordFileReader_->ReadFeatureSection()) {
456         printf("record format error.\n");
457         return false;
458     }
459     if (jsonFormat_) {
460         reportJsonFile_ =
461             std::make_unique<ReportJsonFile>(recordFileReader_, GetReport().virtualRuntime_);
462     }
463 
464     ProcessFeaturesData();
465     ProcessSymbolsData();
466 
467     HLOGD("process record");
468     recordFileReader_->ReadDataSection(
469         std::bind(&SubCommandReport::RecordCallBack, this, std::placeholders::_1));
470     if (cpuOffMode_) {
471         FlushCacheRecord();
472     }
473     HLOGD("process record completed");
474 
475     LoadPerfDataCompleted();
476     return true;
477 }
478 
OutputStd()479 bool SubCommandReport::OutputStd()
480 {
481     if (fprintf(output_, "<<Hiperf Report%s>>\n", diffMode_ ? " Diff" : "") < 0) {
482         return false;
483     }
484 
485     // feature string:
486     const auto &featureSections = recordFileReader_->GetFeatureSections();
487     HLOGV("featureSections: %zu ", featureSections.size());
488 
489     for (auto &featureSection : featureSections) {
490         if (recordFileReader_->IsFeatrureStringSection(featureSection->featureId_)) {
491             const PerfFileSectionString *sectionString =
492                 static_cast<const PerfFileSectionString *>(featureSection.get());
493 
494             fprintf(output_, "%s: %s\n",
495                     PerfFileSection::GetFeatureName(featureSection.get()->featureId_).c_str(),
496                     sectionString->toString().c_str());
497         }
498     }
499 
500     if (cpuOffMode_) {
501         fprintf(output_, "cpu off mode: enabled\n");
502     }
503 
504     if (!diffMode_) {
505         GetReport(FIRST).AdjustReportItems();
506         GetReport(FIRST).OutputStd(output_);
507     } else {
508         GetReport(FIRST).AdjustReportItems();
509         GetReport(SECOND).AdjustReportItems();
510         GetReport(FIRST).OutputStdDiff(output_, GetReport(SECOND));
511     }
512 
513     return true;
514 }
515 
OutputReport()516 bool SubCommandReport::OutputReport()
517 {
518     if (output_ == nullptr) {
519         HLOGD("nothing need output");
520         return true; //
521     } else if (jsonFormat_) {
522         HLOGD("report as json");
523         return reportJsonFile_->OutputJson(output_);
524     } else {
525         return OutputStd();
526     }
527 }
528 
PrepareOutput()529 bool SubCommandReport::PrepareOutput()
530 {
531     if (protobufFormat_) {
532 #if HAVE_PROTOBUF
533         printf("save to protobuf file: '%s'\n", reportFile_.c_str());
534         protobufOutputFileWriter_ = std::make_unique<ReportProtobufFileWriter>();
535         protobufOutputFileWriter_->Create(reportFile_);
536 #endif
537         return true;
538     }
539 
540     if (!reportFile_.empty()) {
541         std::string resolvedPath = CanonicalizeSpecPath(reportFile_.c_str());
542         output_ = fopen(resolvedPath.c_str(), "w");
543         if (output_ == nullptr) {
544             printf("unable open file to '%s' because '%d'\n", reportFile_.c_str(), errno);
545             return false;
546         } else {
547             printf("report will save at '%s'\n", reportFile_.c_str());
548         }
549     } else {
550         output_ = stdout;
551     }
552 
553     return true;
554 }
555 
~SubCommandReport()556 SubCommandReport::~SubCommandReport()
557 {
558 #if HAVE_PROTOBUF
559     if (protobufOutputFileWriter_ != nullptr) {
560         protobufOutputFileWriter_->Close();
561     }
562 #endif
563     if (output_ != nullptr && output_ != stdout) {
564         fclose(output_);
565     }
566 
567     SymbolsFile::onRecording_ = true; // back to default for UT
568 }
569 
OnSubCommand(std::vector<std::string> & args)570 bool SubCommandReport::OnSubCommand(std::vector<std::string> &args)
571 {
572     if (!PrepareOutput()) {
573         return false;
574     }
575 
576     // any way tell symbols this is not on recording
577     SymbolsFile::onRecording_ = false;
578 
579     printf("loading data\n");
580     if (!LoadPerfData()) {
581         return false;
582     }
583 
584     if (diffMode_) {
585         // we are in diff mode
586         index_ = SECOND;
587         // load again with second file
588         if (!LoadPerfData()) {
589             return false;
590         }
591         // back to first
592         index_ = FIRST;
593     }
594     printf("prepare report\n");
595     if (!OutputReport()) {
596         HLOGD("OutputReport failed");
597         return false;
598     }
599 #ifdef HIPERF_DEBUG_TIME
600     printf("SymbolicRecordTimes: %0.3f ms\n",
601            GetReport(FIRST).virtualRuntime_.symbolicRecordTimes_.count() / MS_DUARTION);
602 #endif
603 
604     printf("report done\n");
605     return true;
606 }
607 
RegisterSubCommandReport()608 bool SubCommandReport::RegisterSubCommandReport()
609 {
610     std::unique_ptr<SubCommand> cmd = std::make_unique<SubCommandReport>();
611     return SubCommand::RegisterSubCommand("report", std::move(cmd));
612 }
613 } // namespace HiPerf
614 } // namespace Developtools
615 } // namespace OHOS
616