OSDN Git Service

Merge "Revert "Crypto performance benchmark"" into nyc-dev
[android-x86/system-extras.git] / simpleperf / cmd_report.cpp
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <inttypes.h>
18 #include <algorithm>
19 #include <functional>
20 #include <map>
21 #include <set>
22 #include <string>
23 #include <unordered_map>
24 #include <unordered_set>
25 #include <vector>
26
27 #include <android-base/logging.h>
28 #include <android-base/parseint.h>
29 #include <android-base/stringprintf.h>
30 #include <android-base/strings.h>
31
32 #include "command.h"
33 #include "dwarf_unwind.h"
34 #include "environment.h"
35 #include "event_attr.h"
36 #include "event_type.h"
37 #include "perf_regs.h"
38 #include "record.h"
39 #include "record_file.h"
40 #include "sample_tree.h"
41 #include "thread_tree.h"
42 #include "utils.h"
43
44 class Displayable {
45  public:
46   Displayable(const std::string& name) : name_(name), width_(name.size()) {
47   }
48
49   virtual ~Displayable() {
50   }
51
52   const std::string& Name() const {
53     return name_;
54   }
55   size_t Width() const {
56     return width_;
57   }
58
59   virtual std::string Show(const SampleEntry& sample) const = 0;
60   void AdjustWidth(const SampleEntry& sample) {
61     size_t size = Show(sample).size();
62     width_ = std::max(width_, size);
63   }
64
65  private:
66   const std::string name_;
67   size_t width_;
68 };
69
70 class AccumulatedOverheadItem : public Displayable {
71  public:
72   AccumulatedOverheadItem(const SampleTree& sample_tree)
73       : Displayable("Children"), sample_tree_(sample_tree) {
74   }
75
76   std::string Show(const SampleEntry& sample) const override {
77     uint64_t period = sample.period + sample.accumulated_period;
78     uint64_t total_period = sample_tree_.TotalPeriod();
79     double percentage = (total_period != 0) ? 100.0 * period / total_period : 0.0;
80     return android::base::StringPrintf("%.2lf%%", percentage);
81   }
82
83  private:
84   const SampleTree& sample_tree_;
85 };
86
87 class SelfOverheadItem : public Displayable {
88  public:
89   SelfOverheadItem(const SampleTree& sample_tree, const std::string& name = "Self")
90       : Displayable(name), sample_tree_(sample_tree) {
91   }
92
93   std::string Show(const SampleEntry& sample) const override {
94     uint64_t period = sample.period;
95     uint64_t total_period = sample_tree_.TotalPeriod();
96     double percentage = (total_period != 0) ? 100.0 * period / total_period : 0.0;
97     return android::base::StringPrintf("%.2lf%%", percentage);
98   }
99
100  private:
101   const SampleTree& sample_tree_;
102 };
103
104 class SampleCountItem : public Displayable {
105  public:
106   SampleCountItem() : Displayable("Sample") {
107   }
108
109   std::string Show(const SampleEntry& sample) const override {
110     return android::base::StringPrintf("%" PRId64, sample.sample_count);
111   }
112 };
113
114 class Comparable {
115  public:
116   virtual ~Comparable() {
117   }
118
119   virtual int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const = 0;
120 };
121
122 class PidItem : public Displayable, public Comparable {
123  public:
124   PidItem() : Displayable("Pid") {
125   }
126
127   int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
128     return sample1.thread->pid - sample2.thread->pid;
129   }
130
131   std::string Show(const SampleEntry& sample) const override {
132     return android::base::StringPrintf("%d", sample.thread->pid);
133   }
134 };
135
136 class TidItem : public Displayable, public Comparable {
137  public:
138   TidItem() : Displayable("Tid") {
139   }
140
141   int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
142     return sample1.thread->tid - sample2.thread->tid;
143   }
144
145   std::string Show(const SampleEntry& sample) const override {
146     return android::base::StringPrintf("%d", sample.thread->tid);
147   }
148 };
149
150 class CommItem : public Displayable, public Comparable {
151  public:
152   CommItem() : Displayable("Command") {
153   }
154
155   int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
156     return strcmp(sample1.thread_comm, sample2.thread_comm);
157   }
158
159   std::string Show(const SampleEntry& sample) const override {
160     return sample.thread_comm;
161   }
162 };
163
164 class DsoItem : public Displayable, public Comparable {
165  public:
166   DsoItem(const std::string& name = "Shared Object") : Displayable(name) {
167   }
168
169   int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
170     return strcmp(sample1.map->dso->Path().c_str(), sample2.map->dso->Path().c_str());
171   }
172
173   std::string Show(const SampleEntry& sample) const override {
174     return sample.map->dso->Path();
175   }
176 };
177
178 class SymbolItem : public Displayable, public Comparable {
179  public:
180   SymbolItem(const std::string& name = "Symbol") : Displayable(name) {
181   }
182
183   int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
184     return strcmp(sample1.symbol->DemangledName(), sample2.symbol->DemangledName());
185   }
186
187   std::string Show(const SampleEntry& sample) const override {
188     return sample.symbol->DemangledName();
189   }
190 };
191
192 class DsoFromItem : public Displayable, public Comparable {
193  public:
194   DsoFromItem() : Displayable("Source Shared Object") {
195   }
196
197   int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
198     return strcmp(sample1.branch_from.map->dso->Path().c_str(),
199                   sample2.branch_from.map->dso->Path().c_str());
200   }
201
202   std::string Show(const SampleEntry& sample) const override {
203     return sample.branch_from.map->dso->Path();
204   }
205 };
206
207 class DsoToItem : public DsoItem {
208  public:
209   DsoToItem() : DsoItem("Target Shared Object") {
210   }
211 };
212
213 class SymbolFromItem : public Displayable, public Comparable {
214  public:
215   SymbolFromItem() : Displayable("Source Symbol") {
216   }
217
218   int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
219     return strcmp(sample1.branch_from.symbol->DemangledName(),
220                   sample2.branch_from.symbol->DemangledName());
221   }
222
223   std::string Show(const SampleEntry& sample) const override {
224     return sample.branch_from.symbol->DemangledName();
225   }
226 };
227
228 class SymbolToItem : public SymbolItem {
229  public:
230   SymbolToItem() : SymbolItem("Target Symbol") {
231   }
232 };
233
234 static std::set<std::string> branch_sort_keys = {
235     "dso_from", "dso_to", "symbol_from", "symbol_to",
236 };
237
238 class ReportCommand : public Command {
239  public:
240   ReportCommand()
241       : Command(
242             "report", "report sampling information in perf.data",
243             "Usage: simpleperf report [options]\n"
244             "    -b            Use the branch-to addresses in sampled take branches instead of\n"
245             "                  the instruction addresses. Only valid for perf.data recorded with\n"
246             "                  -b/-j option.\n"
247             "    --children    Print the overhead accumulated by appearing in the callchain.\n"
248             "    --comms comm1,comm2,...\n"
249             "                  Report only for selected comms.\n"
250             "    --dsos dso1,dso2,...\n"
251             "                  Report only for selected dsos.\n"
252             "    -g [callee|caller]\n"
253             "                  Print call graph. If callee mode is used, the graph shows how\n"
254             "                  functions are called from others. Otherwise, the graph shows how\n"
255             "                  functions call others. Default is callee mode.\n"
256             "    -i <file>     Specify path of record file, default is perf.data.\n"
257             "    -n            Print the sample count for each item.\n"
258             "    --no-demangle        Don't demangle symbol names.\n"
259             "    -o report_file_name  Set report file name, default is stdout.\n"
260             "    --pid pid1,pid2,...\n"
261             "                  Report only for selected pids.\n"
262             "    --sort key1,key2,...\n"
263             "                  Select the keys to sort and print the report. Possible keys\n"
264             "                  include pid, tid, comm, dso, symbol, dso_from, dso_to, symbol_from\n"
265             "                  symbol_to. dso_from, dso_to, symbol_from, symbol_to can only be\n"
266             "                  used with -b option. Default keys are \"comm,pid,tid,dso,symbol\"\n"
267             "    --symfs <dir> Look for files with symbols relative to this directory.\n"
268             "    --tids tid1,tid2,...\n"
269             "                  Report only for selected tids.\n"
270             "    --vmlinux <file>\n"
271             "                  Parse kernel symbols from <file>.\n"),
272         record_filename_("perf.data"),
273         use_branch_address_(false),
274         accumulate_callchain_(false),
275         print_callgraph_(false),
276         callgraph_show_callee_(true),
277         report_fp_(nullptr) {
278     compare_sample_func_t compare_sample_callback = std::bind(
279         &ReportCommand::CompareSampleEntry, this, std::placeholders::_1, std::placeholders::_2);
280     sample_tree_ =
281         std::unique_ptr<SampleTree>(new SampleTree(&thread_tree_, compare_sample_callback));
282   }
283
284   bool Run(const std::vector<std::string>& args);
285
286  private:
287   bool ParseOptions(const std::vector<std::string>& args);
288   bool ReadEventAttrFromRecordFile();
289   void ReadSampleTreeFromRecordFile();
290   void ProcessRecord(std::unique_ptr<Record> record);
291   void ProcessSampleRecord(const SampleRecord& r);
292   bool ReadFeaturesFromRecordFile();
293   int CompareSampleEntry(const SampleEntry& sample1, const SampleEntry& sample2);
294   bool PrintReport();
295   void PrintReportContext();
296   void CollectReportWidth();
297   void CollectReportEntryWidth(const SampleEntry& sample);
298   void PrintReportHeader();
299   void PrintReportEntry(const SampleEntry& sample);
300   void PrintCallGraph(const SampleEntry& sample);
301   void PrintCallGraphEntry(size_t depth, std::string prefix, const std::unique_ptr<CallChainNode>& node,
302                            uint64_t parent_period, bool last);
303
304   std::string record_filename_;
305   std::unique_ptr<RecordFileReader> record_file_reader_;
306   perf_event_attr event_attr_;
307   std::vector<std::unique_ptr<Displayable>> displayable_items_;
308   std::vector<Comparable*> comparable_items_;
309   ThreadTree thread_tree_;
310   std::unique_ptr<SampleTree> sample_tree_;
311   bool use_branch_address_;
312   std::string record_cmdline_;
313   bool accumulate_callchain_;
314   bool print_callgraph_;
315   bool callgraph_show_callee_;
316
317   std::string report_filename_;
318   FILE* report_fp_;
319 };
320
321 bool ReportCommand::Run(const std::vector<std::string>& args) {
322   // 1. Parse options.
323   if (!ParseOptions(args)) {
324     return false;
325   }
326
327   // 2. Read record file and build SampleTree.
328   record_file_reader_ = RecordFileReader::CreateInstance(record_filename_);
329   if (record_file_reader_ == nullptr) {
330     return false;
331   }
332   if (!ReadEventAttrFromRecordFile()) {
333     return false;
334   }
335   // Read features first to prepare build ids used when building SampleTree.
336   if (!ReadFeaturesFromRecordFile()) {
337     return false;
338   }
339   ReadSampleTreeFromRecordFile();
340
341   // 3. Show collected information.
342   if (!PrintReport()) {
343     return false;
344   }
345
346   return true;
347 }
348
349 bool ReportCommand::ParseOptions(const std::vector<std::string>& args) {
350   bool demangle = true;
351   std::string symfs_dir;
352   std::string vmlinux;
353   bool print_sample_count = false;
354   std::vector<std::string> sort_keys = {"comm", "pid", "tid", "dso", "symbol"};
355   std::unordered_set<std::string> comm_filter;
356   std::unordered_set<std::string> dso_filter;
357   std::unordered_set<int> pid_filter;
358   std::unordered_set<int> tid_filter;
359
360   for (size_t i = 0; i < args.size(); ++i) {
361     if (args[i] == "-b") {
362       use_branch_address_ = true;
363     } else if (args[i] == "--children") {
364       accumulate_callchain_ = true;
365     } else if (args[i] == "--comms" || args[i] == "--dsos") {
366       std::unordered_set<std::string>& filter = (args[i] == "--comms" ? comm_filter : dso_filter);
367       if (!NextArgumentOrError(args, &i)) {
368         return false;
369       }
370       std::vector<std::string> strs = android::base::Split(args[i], ",");
371       filter.insert(strs.begin(), strs.end());
372
373     } else if (args[i] == "-g") {
374       print_callgraph_ = true;
375       accumulate_callchain_ = true;
376       if (i + 1 < args.size() && args[i + 1][0] != '-') {
377         ++i;
378         if (args[i] == "callee") {
379           callgraph_show_callee_ = true;
380         } else if (args[i] == "caller") {
381           callgraph_show_callee_ = false;
382         } else {
383           LOG(ERROR) << "Unknown argument with -g option: " << args[i];
384           return false;
385         }
386       }
387     } else if (args[i] == "-i") {
388       if (!NextArgumentOrError(args, &i)) {
389         return false;
390       }
391       record_filename_ = args[i];
392
393     } else if (args[i] == "-n") {
394       print_sample_count = true;
395
396     } else if (args[i] == "--no-demangle") {
397       demangle = false;
398     } else if (args[i] == "-o") {
399       if (!NextArgumentOrError(args, &i)) {
400         return false;
401       }
402       report_filename_ = args[i];
403
404     } else if (args[i] == "--pids" || args[i] == "--tids") {
405       if (!NextArgumentOrError(args, &i)) {
406         return false;
407       }
408       std::vector<std::string> strs = android::base::Split(args[i], ",");
409       std::vector<int> ids;
410       for (const auto& s : strs) {
411         int id;
412         if (!android::base::ParseInt(s.c_str(), &id, 0)) {
413           LOG(ERROR) << "invalid id in " << args[i] << " option: " << s;
414           return false;
415         }
416         ids.push_back(id);
417       }
418       std::unordered_set<int>& filter = (args[i] == "--pids" ? pid_filter : tid_filter);
419       filter.insert(ids.begin(), ids.end());
420
421     } else if (args[i] == "--sort") {
422       if (!NextArgumentOrError(args, &i)) {
423         return false;
424       }
425       sort_keys = android::base::Split(args[i], ",");
426     } else if (args[i] == "--symfs") {
427       if (!NextArgumentOrError(args, &i)) {
428         return false;
429       }
430       symfs_dir = args[i];
431
432     } else if (args[i] == "--vmlinux") {
433       if (!NextArgumentOrError(args, &i)) {
434         return false;
435       }
436       vmlinux = args[i];
437     } else {
438       ReportUnknownOption(args, i);
439       return false;
440     }
441   }
442
443   Dso::SetDemangle(demangle);
444   if (!Dso::SetSymFsDir(symfs_dir)) {
445     return false;
446   }
447   if (!vmlinux.empty()) {
448     Dso::SetVmlinux(vmlinux);
449   }
450
451   if (!accumulate_callchain_) {
452     displayable_items_.push_back(
453         std::unique_ptr<Displayable>(new SelfOverheadItem(*sample_tree_, "Overhead")));
454   } else {
455     displayable_items_.push_back(
456         std::unique_ptr<Displayable>(new AccumulatedOverheadItem(*sample_tree_)));
457     displayable_items_.push_back(std::unique_ptr<Displayable>(new SelfOverheadItem(*sample_tree_)));
458   }
459   if (print_sample_count) {
460     displayable_items_.push_back(std::unique_ptr<Displayable>(new SampleCountItem));
461   }
462   for (auto& key : sort_keys) {
463     if (!use_branch_address_ && branch_sort_keys.find(key) != branch_sort_keys.end()) {
464       LOG(ERROR) << "sort key '" << key << "' can only be used with -b option.";
465       return false;
466     }
467     if (key == "pid") {
468       PidItem* item = new PidItem;
469       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
470       comparable_items_.push_back(item);
471     } else if (key == "tid") {
472       TidItem* item = new TidItem;
473       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
474       comparable_items_.push_back(item);
475     } else if (key == "comm") {
476       CommItem* item = new CommItem;
477       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
478       comparable_items_.push_back(item);
479     } else if (key == "dso") {
480       DsoItem* item = new DsoItem;
481       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
482       comparable_items_.push_back(item);
483     } else if (key == "symbol") {
484       SymbolItem* item = new SymbolItem;
485       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
486       comparable_items_.push_back(item);
487     } else if (key == "dso_from") {
488       DsoFromItem* item = new DsoFromItem;
489       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
490       comparable_items_.push_back(item);
491     } else if (key == "dso_to") {
492       DsoToItem* item = new DsoToItem;
493       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
494       comparable_items_.push_back(item);
495     } else if (key == "symbol_from") {
496       SymbolFromItem* item = new SymbolFromItem;
497       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
498       comparable_items_.push_back(item);
499     } else if (key == "symbol_to") {
500       SymbolToItem* item = new SymbolToItem;
501       displayable_items_.push_back(std::unique_ptr<Displayable>(item));
502       comparable_items_.push_back(item);
503     } else {
504       LOG(ERROR) << "Unknown sort key: " << key;
505       return false;
506     }
507   }
508   sample_tree_->SetFilters(pid_filter, tid_filter, comm_filter, dso_filter);
509   return true;
510 }
511
512 bool ReportCommand::ReadEventAttrFromRecordFile() {
513   const std::vector<PerfFileFormat::FileAttr>& attrs = record_file_reader_->AttrSection();
514   if (attrs.size() != 1) {
515     LOG(ERROR) << "record file contains " << attrs.size() << " attrs";
516     return false;
517   }
518   event_attr_ = attrs[0].attr;
519   if (use_branch_address_ && (event_attr_.sample_type & PERF_SAMPLE_BRANCH_STACK) == 0) {
520     LOG(ERROR) << record_filename_ << " is not recorded with branch stack sampling option.";
521     return false;
522   }
523   return true;
524 }
525
526 void ReportCommand::ReadSampleTreeFromRecordFile() {
527   thread_tree_.AddThread(0, 0, "swapper");
528   record_file_reader_->ReadDataSection([this](std::unique_ptr<Record> record) {
529     ProcessRecord(std::move(record));
530     return true;
531   });
532 }
533
534 void ReportCommand::ProcessRecord(std::unique_ptr<Record> record) {
535   BuildThreadTree(*record, &thread_tree_);
536   if (record->header.type == PERF_RECORD_SAMPLE) {
537     ProcessSampleRecord(*static_cast<const SampleRecord*>(record.get()));
538   }
539 }
540
541 void ReportCommand::ProcessSampleRecord(const SampleRecord& r) {
542   if (use_branch_address_ && (r.sample_type & PERF_SAMPLE_BRANCH_STACK)) {
543     for (auto& item : r.branch_stack_data.stack) {
544       if (item.from != 0 && item.to != 0) {
545         sample_tree_->AddBranchSample(r.tid_data.pid, r.tid_data.tid, item.from, item.to,
546                                       item.flags, r.time_data.time, r.period_data.period);
547       }
548     }
549   } else {
550     bool in_kernel = (r.header.misc & PERF_RECORD_MISC_CPUMODE_MASK) == PERF_RECORD_MISC_KERNEL;
551     SampleEntry* sample = sample_tree_->AddSample(r.tid_data.pid, r.tid_data.tid, r.ip_data.ip,
552                                                   r.time_data.time, r.period_data.period, in_kernel);
553     if (sample == nullptr) {
554       return;
555     }
556     if (accumulate_callchain_) {
557       std::vector<uint64_t> ips;
558       if (r.sample_type & PERF_SAMPLE_CALLCHAIN) {
559         ips.insert(ips.end(), r.callchain_data.ips.begin(), r.callchain_data.ips.end());
560       }
561       // Use stack_user_data.data.size() instead of stack_user_data.dyn_size, to make up for
562       // the missing kernel patch in N9. See b/22612370.
563       if ((r.sample_type & PERF_SAMPLE_REGS_USER) && (r.regs_user_data.reg_mask != 0) &&
564           (r.sample_type & PERF_SAMPLE_STACK_USER) && (!r.stack_user_data.data.empty())) {
565         RegSet regs = CreateRegSet(r.regs_user_data.reg_mask, r.regs_user_data.regs);
566         std::vector<char> stack(r.stack_user_data.data.begin(),
567                                 r.stack_user_data.data.begin() + r.stack_user_data.data.size());
568         std::vector<uint64_t> unwind_ips = UnwindCallChain(*sample->thread, regs, stack);
569         if (!unwind_ips.empty()) {
570           ips.push_back(PERF_CONTEXT_USER);
571           ips.insert(ips.end(), unwind_ips.begin(), unwind_ips.end());
572         }
573       }
574
575       std::vector<SampleEntry*> callchain;
576       callchain.push_back(sample);
577
578       bool first_ip = true;
579       for (auto& ip : ips) {
580         if (ip >= PERF_CONTEXT_MAX) {
581           switch (ip) {
582             case PERF_CONTEXT_KERNEL:
583               in_kernel = true;
584               break;
585             case PERF_CONTEXT_USER:
586               in_kernel = false;
587               break;
588             default:
589               LOG(ERROR) << "Unexpected perf_context in callchain: " << ip;
590           }
591         } else {
592           if (first_ip) {
593             first_ip = false;
594             // Remove duplication with sampled ip.
595             if (ip == r.ip_data.ip) {
596               continue;
597             }
598           }
599           SampleEntry* sample =
600               sample_tree_->AddCallChainSample(r.tid_data.pid, r.tid_data.tid, ip, r.time_data.time,
601                                                r.period_data.period, in_kernel, callchain);
602           callchain.push_back(sample);
603         }
604       }
605
606       if (print_callgraph_) {
607         std::set<SampleEntry*> added_set;
608         if (!callgraph_show_callee_) {
609           std::reverse(callchain.begin(), callchain.end());
610         }
611         while (callchain.size() >= 2) {
612           SampleEntry* sample = callchain[0];
613           callchain.erase(callchain.begin());
614           // Add only once for recursive calls on callchain.
615           if (added_set.find(sample) != added_set.end()) {
616             continue;
617           }
618           added_set.insert(sample);
619           sample_tree_->InsertCallChainForSample(sample, callchain, r.period_data.period);
620         }
621       }
622     }
623   }
624 }
625
626 bool ReportCommand::ReadFeaturesFromRecordFile() {
627   std::vector<BuildIdRecord> records = record_file_reader_->ReadBuildIdFeature();
628   std::vector<std::pair<std::string, BuildId>> build_ids;
629   for (auto& r : records) {
630     build_ids.push_back(std::make_pair(r.filename, r.build_id));
631   }
632   Dso::SetBuildIds(build_ids);
633
634   std::string arch = record_file_reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH);
635   if (!arch.empty()) {
636     if (!SetCurrentArch(arch)) {
637       return false;
638     }
639   }
640
641   std::vector<std::string> cmdline = record_file_reader_->ReadCmdlineFeature();
642   if (!cmdline.empty()) {
643     record_cmdline_ = android::base::Join(cmdline, ' ');
644   }
645   return true;
646 }
647
648 int ReportCommand::CompareSampleEntry(const SampleEntry& sample1, const SampleEntry& sample2) {
649   for (auto& item : comparable_items_) {
650     int result = item->Compare(sample1, sample2);
651     if (result != 0) {
652       return result;
653     }
654   }
655   return 0;
656 }
657
658 bool ReportCommand::PrintReport() {
659   std::unique_ptr<FILE, decltype(&fclose)> file_handler(nullptr, fclose);
660   if (report_filename_.empty()) {
661     report_fp_ = stdout;
662   } else {
663     report_fp_ = fopen(report_filename_.c_str(), "w");
664     if (report_fp_ == nullptr) {
665       PLOG(ERROR) << "failed to open file " << report_filename_;
666       return false;
667     }
668     file_handler.reset(report_fp_);
669   }
670   PrintReportContext();
671   CollectReportWidth();
672   PrintReportHeader();
673   sample_tree_->VisitAllSamples(
674       std::bind(&ReportCommand::PrintReportEntry, this, std::placeholders::_1));
675   fflush(report_fp_);
676   if (ferror(report_fp_) != 0) {
677     PLOG(ERROR) << "print report failed";
678     return false;
679   }
680   return true;
681 }
682
683 void ReportCommand::PrintReportContext() {
684   const EventType* event_type = FindEventTypeByConfig(event_attr_.type, event_attr_.config);
685   std::string event_type_name;
686   if (event_type != nullptr) {
687     event_type_name = event_type->name;
688   } else {
689     event_type_name =
690         android::base::StringPrintf("(type %u, config %llu)", event_attr_.type, event_attr_.config);
691   }
692   if (!record_cmdline_.empty()) {
693     fprintf(report_fp_, "Cmdline: %s\n", record_cmdline_.c_str());
694   }
695   fprintf(report_fp_, "Samples: %" PRIu64 " of event '%s'\n", sample_tree_->TotalSamples(),
696           event_type_name.c_str());
697   fprintf(report_fp_, "Event count: %" PRIu64 "\n\n", sample_tree_->TotalPeriod());
698 }
699
700 void ReportCommand::CollectReportWidth() {
701   sample_tree_->VisitAllSamples(
702       std::bind(&ReportCommand::CollectReportEntryWidth, this, std::placeholders::_1));
703 }
704
705 void ReportCommand::CollectReportEntryWidth(const SampleEntry& sample) {
706   for (auto& item : displayable_items_) {
707     item->AdjustWidth(sample);
708   }
709 }
710
711 void ReportCommand::PrintReportHeader() {
712   for (size_t i = 0; i < displayable_items_.size(); ++i) {
713     auto& item = displayable_items_[i];
714     if (i != displayable_items_.size() - 1) {
715       fprintf(report_fp_, "%-*s  ", static_cast<int>(item->Width()), item->Name().c_str());
716     } else {
717       fprintf(report_fp_, "%s\n", item->Name().c_str());
718     }
719   }
720 }
721
722 void ReportCommand::PrintReportEntry(const SampleEntry& sample) {
723   for (size_t i = 0; i < displayable_items_.size(); ++i) {
724     auto& item = displayable_items_[i];
725     if (i != displayable_items_.size() - 1) {
726       fprintf(report_fp_, "%-*s  ", static_cast<int>(item->Width()), item->Show(sample).c_str());
727     } else {
728       fprintf(report_fp_, "%s\n", item->Show(sample).c_str());
729     }
730   }
731   if (print_callgraph_) {
732     PrintCallGraph(sample);
733   }
734 }
735
736 void ReportCommand::PrintCallGraph(const SampleEntry& sample) {
737   std::string prefix = "       ";
738   fprintf(report_fp_, "%s|\n", prefix.c_str());
739   fprintf(report_fp_, "%s-- %s\n", prefix.c_str(), sample.symbol->DemangledName());
740   prefix.append(3, ' ');
741   for (size_t i = 0; i < sample.callchain.children.size(); ++i) {
742     PrintCallGraphEntry(1, prefix, sample.callchain.children[i], sample.callchain.children_period,
743                         (i + 1 == sample.callchain.children.size()));
744   }
745 }
746
747 void ReportCommand::PrintCallGraphEntry(size_t depth, std::string prefix,
748                                         const std::unique_ptr<CallChainNode>& node,
749                                         uint64_t parent_period, bool last) {
750   if (depth > 20) {
751     LOG(WARNING) << "truncated callgraph at depth " << depth;
752     return;
753   }
754   prefix += "|";
755   fprintf(report_fp_, "%s\n", prefix.c_str());
756   if (last) {
757     prefix.back() = ' ';
758   }
759   std::string percentage_s = "-- ";
760   if (node->period + node->children_period != parent_period) {
761     double percentage = 100.0 * (node->period + node->children_period) / parent_period;
762     percentage_s = android::base::StringPrintf("--%.2lf%%-- ", percentage);
763   }
764   fprintf(report_fp_, "%s%s%s\n", prefix.c_str(), percentage_s.c_str(), node->chain[0]->symbol->DemangledName());
765   prefix.append(percentage_s.size(), ' ');
766   for (size_t i = 1; i < node->chain.size(); ++i) {
767     fprintf(report_fp_, "%s%s\n", prefix.c_str(), node->chain[i]->symbol->DemangledName());
768   }
769
770   for (size_t i = 0; i < node->children.size(); ++i) {
771     PrintCallGraphEntry(depth + 1, prefix, node->children[i], node->children_period,
772                         (i + 1 == node->children.size()));
773   }
774 }
775
776 void RegisterReportCommand() {
777   RegisterCommand("report", [] { return std::unique_ptr<Command>(new ReportCommand()); });
778 }