OSDN Git Service

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