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
44class 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
70class 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
87class 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
104class 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
114class Comparable {
115 public:
116  virtual ~Comparable() {
117  }
118
119  virtual int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const = 0;
120};
121
122class 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
136class 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
150class 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
164class 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
178class 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
192class 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
207class DsoToItem : public DsoItem {
208 public:
209  DsoToItem() : DsoItem("Target Shared Object") {
210  }
211};
212
213class 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
228class SymbolToItem : public SymbolItem {
229 public:
230  SymbolToItem() : SymbolItem("Target Symbol") {
231  }
232};
233
234static std::set<std::string> branch_sort_keys = {
235    "dso_from", "dso_to", "symbol_from", "symbol_to",
236};
237
238class 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        record_file_arch_(GetBuildArch()),
274        use_branch_address_(false),
275        accumulate_callchain_(false),
276        print_callgraph_(false),
277        callgraph_show_callee_(true),
278        report_fp_(nullptr) {
279    compare_sample_func_t compare_sample_callback = std::bind(
280        &ReportCommand::CompareSampleEntry, this, std::placeholders::_1, std::placeholders::_2);
281    sample_tree_ =
282        std::unique_ptr<SampleTree>(new SampleTree(&thread_tree_, compare_sample_callback));
283  }
284
285  bool Run(const std::vector<std::string>& args);
286
287 private:
288  bool ParseOptions(const std::vector<std::string>& args);
289  bool ReadEventAttrFromRecordFile();
290  void ReadSampleTreeFromRecordFile();
291  void ProcessRecord(std::unique_ptr<Record> record);
292  void ProcessSampleRecord(const SampleRecord& r);
293  bool ReadFeaturesFromRecordFile();
294  int CompareSampleEntry(const SampleEntry& sample1, const SampleEntry& sample2);
295  bool PrintReport();
296  void PrintReportContext();
297  void CollectReportWidth();
298  void CollectReportEntryWidth(const SampleEntry& sample);
299  void PrintReportHeader();
300  void PrintReportEntry(const SampleEntry& sample);
301  void PrintCallGraph(const SampleEntry& sample);
302  void PrintCallGraphEntry(size_t depth, std::string prefix, const std::unique_ptr<CallChainNode>& node,
303                           uint64_t parent_period, bool last);
304
305  std::string record_filename_;
306  ArchType record_file_arch_;
307  std::unique_ptr<RecordFileReader> record_file_reader_;
308  perf_event_attr event_attr_;
309  std::vector<std::unique_ptr<Displayable>> displayable_items_;
310  std::vector<Comparable*> comparable_items_;
311  ThreadTree thread_tree_;
312  std::unique_ptr<SampleTree> sample_tree_;
313  bool use_branch_address_;
314  std::string record_cmdline_;
315  bool accumulate_callchain_;
316  bool print_callgraph_;
317  bool callgraph_show_callee_;
318
319  std::string report_filename_;
320  FILE* report_fp_;
321};
322
323bool ReportCommand::Run(const std::vector<std::string>& args) {
324  // 1. Parse options.
325  if (!ParseOptions(args)) {
326    return false;
327  }
328
329  // 2. Read record file and build SampleTree.
330  record_file_reader_ = RecordFileReader::CreateInstance(record_filename_);
331  if (record_file_reader_ == nullptr) {
332    return false;
333  }
334  if (!ReadEventAttrFromRecordFile()) {
335    return false;
336  }
337  // Read features first to prepare build ids used when building SampleTree.
338  if (!ReadFeaturesFromRecordFile()) {
339    return false;
340  }
341  ScopedCurrentArch scoped_arch(record_file_arch_);
342  ReadSampleTreeFromRecordFile();
343
344  // 3. Show collected information.
345  if (!PrintReport()) {
346    return false;
347  }
348
349  return true;
350}
351
352bool ReportCommand::ParseOptions(const std::vector<std::string>& args) {
353  bool demangle = true;
354  std::string symfs_dir;
355  std::string vmlinux;
356  bool print_sample_count = false;
357  std::vector<std::string> sort_keys = {"comm", "pid", "tid", "dso", "symbol"};
358  std::unordered_set<std::string> comm_filter;
359  std::unordered_set<std::string> dso_filter;
360  std::unordered_set<int> pid_filter;
361  std::unordered_set<int> tid_filter;
362
363  for (size_t i = 0; i < args.size(); ++i) {
364    if (args[i] == "-b") {
365      use_branch_address_ = true;
366    } else if (args[i] == "--children") {
367      accumulate_callchain_ = true;
368    } else if (args[i] == "--comms" || args[i] == "--dsos") {
369      std::unordered_set<std::string>& filter = (args[i] == "--comms" ? comm_filter : dso_filter);
370      if (!NextArgumentOrError(args, &i)) {
371        return false;
372      }
373      std::vector<std::string> strs = android::base::Split(args[i], ",");
374      filter.insert(strs.begin(), strs.end());
375
376    } else if (args[i] == "-g") {
377      print_callgraph_ = true;
378      accumulate_callchain_ = true;
379      if (i + 1 < args.size() && args[i + 1][0] != '-') {
380        ++i;
381        if (args[i] == "callee") {
382          callgraph_show_callee_ = true;
383        } else if (args[i] == "caller") {
384          callgraph_show_callee_ = false;
385        } else {
386          LOG(ERROR) << "Unknown argument with -g option: " << args[i];
387          return false;
388        }
389      }
390    } else if (args[i] == "-i") {
391      if (!NextArgumentOrError(args, &i)) {
392        return false;
393      }
394      record_filename_ = args[i];
395
396    } else if (args[i] == "-n") {
397      print_sample_count = true;
398
399    } else if (args[i] == "--no-demangle") {
400      demangle = false;
401    } else if (args[i] == "-o") {
402      if (!NextArgumentOrError(args, &i)) {
403        return false;
404      }
405      report_filename_ = args[i];
406
407    } else if (args[i] == "--pids" || args[i] == "--tids") {
408      if (!NextArgumentOrError(args, &i)) {
409        return false;
410      }
411      std::vector<std::string> strs = android::base::Split(args[i], ",");
412      std::vector<int> ids;
413      for (const auto& s : strs) {
414        int id;
415        if (!android::base::ParseInt(s.c_str(), &id, 0)) {
416          LOG(ERROR) << "invalid id in " << args[i] << " option: " << s;
417          return false;
418        }
419        ids.push_back(id);
420      }
421      std::unordered_set<int>& filter = (args[i] == "--pids" ? pid_filter : tid_filter);
422      filter.insert(ids.begin(), ids.end());
423
424    } else if (args[i] == "--sort") {
425      if (!NextArgumentOrError(args, &i)) {
426        return false;
427      }
428      sort_keys = android::base::Split(args[i], ",");
429    } else if (args[i] == "--symfs") {
430      if (!NextArgumentOrError(args, &i)) {
431        return false;
432      }
433      symfs_dir = args[i];
434
435    } else if (args[i] == "--vmlinux") {
436      if (!NextArgumentOrError(args, &i)) {
437        return false;
438      }
439      vmlinux = args[i];
440    } else {
441      ReportUnknownOption(args, i);
442      return false;
443    }
444  }
445
446  Dso::SetDemangle(demangle);
447  if (!Dso::SetSymFsDir(symfs_dir)) {
448    return false;
449  }
450  if (!vmlinux.empty()) {
451    Dso::SetVmlinux(vmlinux);
452  }
453
454  if (!accumulate_callchain_) {
455    displayable_items_.push_back(
456        std::unique_ptr<Displayable>(new SelfOverheadItem(*sample_tree_, "Overhead")));
457  } else {
458    displayable_items_.push_back(
459        std::unique_ptr<Displayable>(new AccumulatedOverheadItem(*sample_tree_)));
460    displayable_items_.push_back(std::unique_ptr<Displayable>(new SelfOverheadItem(*sample_tree_)));
461  }
462  if (print_sample_count) {
463    displayable_items_.push_back(std::unique_ptr<Displayable>(new SampleCountItem));
464  }
465  for (auto& key : sort_keys) {
466    if (!use_branch_address_ && branch_sort_keys.find(key) != branch_sort_keys.end()) {
467      LOG(ERROR) << "sort key '" << key << "' can only be used with -b option.";
468      return false;
469    }
470    if (key == "pid") {
471      PidItem* item = new PidItem;
472      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
473      comparable_items_.push_back(item);
474    } else if (key == "tid") {
475      TidItem* item = new TidItem;
476      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
477      comparable_items_.push_back(item);
478    } else if (key == "comm") {
479      CommItem* item = new CommItem;
480      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
481      comparable_items_.push_back(item);
482    } else if (key == "dso") {
483      DsoItem* item = new DsoItem;
484      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
485      comparable_items_.push_back(item);
486    } else if (key == "symbol") {
487      SymbolItem* item = new SymbolItem;
488      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
489      comparable_items_.push_back(item);
490    } else if (key == "dso_from") {
491      DsoFromItem* item = new DsoFromItem;
492      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
493      comparable_items_.push_back(item);
494    } else if (key == "dso_to") {
495      DsoToItem* item = new DsoToItem;
496      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
497      comparable_items_.push_back(item);
498    } else if (key == "symbol_from") {
499      SymbolFromItem* item = new SymbolFromItem;
500      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
501      comparable_items_.push_back(item);
502    } else if (key == "symbol_to") {
503      SymbolToItem* item = new SymbolToItem;
504      displayable_items_.push_back(std::unique_ptr<Displayable>(item));
505      comparable_items_.push_back(item);
506    } else {
507      LOG(ERROR) << "Unknown sort key: " << key;
508      return false;
509    }
510  }
511  sample_tree_->SetFilters(pid_filter, tid_filter, comm_filter, dso_filter);
512  return true;
513}
514
515bool ReportCommand::ReadEventAttrFromRecordFile() {
516  const std::vector<PerfFileFormat::FileAttr>& attrs = record_file_reader_->AttrSection();
517  if (attrs.size() != 1) {
518    LOG(ERROR) << "record file contains " << attrs.size() << " attrs";
519    return false;
520  }
521  event_attr_ = attrs[0].attr;
522  if (use_branch_address_ && (event_attr_.sample_type & PERF_SAMPLE_BRANCH_STACK) == 0) {
523    LOG(ERROR) << record_filename_ << " is not recorded with branch stack sampling option.";
524    return false;
525  }
526  return true;
527}
528
529void ReportCommand::ReadSampleTreeFromRecordFile() {
530  thread_tree_.AddThread(0, 0, "swapper");
531  record_file_reader_->ReadDataSection([this](std::unique_ptr<Record> record) {
532    ProcessRecord(std::move(record));
533    return true;
534  });
535}
536
537void ReportCommand::ProcessRecord(std::unique_ptr<Record> record) {
538  BuildThreadTree(*record, &thread_tree_);
539  if (record->header.type == PERF_RECORD_SAMPLE) {
540    ProcessSampleRecord(*static_cast<const SampleRecord*>(record.get()));
541  }
542}
543
544void ReportCommand::ProcessSampleRecord(const SampleRecord& r) {
545  if (use_branch_address_ && (r.sample_type & PERF_SAMPLE_BRANCH_STACK)) {
546    for (auto& item : r.branch_stack_data.stack) {
547      if (item.from != 0 && item.to != 0) {
548        sample_tree_->AddBranchSample(r.tid_data.pid, r.tid_data.tid, item.from, item.to,
549                                      item.flags, r.time_data.time, r.period_data.period);
550      }
551    }
552  } else {
553    bool in_kernel = (r.header.misc & PERF_RECORD_MISC_CPUMODE_MASK) == PERF_RECORD_MISC_KERNEL;
554    SampleEntry* sample = sample_tree_->AddSample(r.tid_data.pid, r.tid_data.tid, r.ip_data.ip,
555                                                  r.time_data.time, r.period_data.period, in_kernel);
556    if (sample == nullptr) {
557      return;
558    }
559    if (accumulate_callchain_) {
560      std::vector<uint64_t> ips;
561      if (r.sample_type & PERF_SAMPLE_CALLCHAIN) {
562        ips.insert(ips.end(), r.callchain_data.ips.begin(), r.callchain_data.ips.end());
563      }
564      // Use stack_user_data.data.size() instead of stack_user_data.dyn_size, to make up for
565      // the missing kernel patch in N9. See b/22612370.
566      if ((r.sample_type & PERF_SAMPLE_REGS_USER) && (r.regs_user_data.reg_mask != 0) &&
567          (r.sample_type & PERF_SAMPLE_STACK_USER) && (!r.stack_user_data.data.empty())) {
568        RegSet regs = CreateRegSet(r.regs_user_data.reg_mask, r.regs_user_data.regs);
569        std::vector<char> stack(r.stack_user_data.data.begin(),
570                                r.stack_user_data.data.begin() + r.stack_user_data.data.size());
571        std::vector<uint64_t> unwind_ips =
572            UnwindCallChain(ScopedCurrentArch::GetCurrentArch(), *sample->thread, regs, stack);
573        if (!unwind_ips.empty()) {
574          ips.push_back(PERF_CONTEXT_USER);
575          ips.insert(ips.end(), unwind_ips.begin(), unwind_ips.end());
576        }
577      }
578
579      std::vector<SampleEntry*> callchain;
580      callchain.push_back(sample);
581
582      bool first_ip = true;
583      for (auto& ip : ips) {
584        if (ip >= PERF_CONTEXT_MAX) {
585          switch (ip) {
586            case PERF_CONTEXT_KERNEL:
587              in_kernel = true;
588              break;
589            case PERF_CONTEXT_USER:
590              in_kernel = false;
591              break;
592            default:
593              LOG(ERROR) << "Unexpected perf_context in callchain: " << ip;
594          }
595        } else {
596          if (first_ip) {
597            first_ip = false;
598            // Remove duplication with sampled ip.
599            if (ip == r.ip_data.ip) {
600              continue;
601            }
602          }
603          SampleEntry* sample =
604              sample_tree_->AddCallChainSample(r.tid_data.pid, r.tid_data.tid, ip, r.time_data.time,
605                                               r.period_data.period, in_kernel, callchain);
606          callchain.push_back(sample);
607        }
608      }
609
610      if (print_callgraph_) {
611        std::set<SampleEntry*> added_set;
612        if (!callgraph_show_callee_) {
613          std::reverse(callchain.begin(), callchain.end());
614        }
615        while (callchain.size() >= 2) {
616          SampleEntry* sample = callchain[0];
617          callchain.erase(callchain.begin());
618          // Add only once for recursive calls on callchain.
619          if (added_set.find(sample) != added_set.end()) {
620            continue;
621          }
622          added_set.insert(sample);
623          sample_tree_->InsertCallChainForSample(sample, callchain, r.period_data.period);
624        }
625      }
626    }
627  }
628}
629
630bool ReportCommand::ReadFeaturesFromRecordFile() {
631  std::vector<BuildIdRecord> records = record_file_reader_->ReadBuildIdFeature();
632  std::vector<std::pair<std::string, BuildId>> build_ids;
633  for (auto& r : records) {
634    build_ids.push_back(std::make_pair(r.filename, r.build_id));
635  }
636  Dso::SetBuildIds(build_ids);
637
638  std::string arch = record_file_reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH);
639  if (!arch.empty()) {
640    record_file_arch_ = GetArchType(arch);
641    if (record_file_arch_ == ARCH_UNSUPPORTED) {
642      return false;
643    }
644  }
645
646  std::vector<std::string> cmdline = record_file_reader_->ReadCmdlineFeature();
647  if (!cmdline.empty()) {
648    record_cmdline_ = android::base::Join(cmdline, ' ');
649  }
650  return true;
651}
652
653int ReportCommand::CompareSampleEntry(const SampleEntry& sample1, const SampleEntry& sample2) {
654  for (auto& item : comparable_items_) {
655    int result = item->Compare(sample1, sample2);
656    if (result != 0) {
657      return result;
658    }
659  }
660  return 0;
661}
662
663bool ReportCommand::PrintReport() {
664  std::unique_ptr<FILE, decltype(&fclose)> file_handler(nullptr, fclose);
665  if (report_filename_.empty()) {
666    report_fp_ = stdout;
667  } else {
668    report_fp_ = fopen(report_filename_.c_str(), "w");
669    if (report_fp_ == nullptr) {
670      PLOG(ERROR) << "failed to open file " << report_filename_;
671      return false;
672    }
673    file_handler.reset(report_fp_);
674  }
675  PrintReportContext();
676  CollectReportWidth();
677  PrintReportHeader();
678  sample_tree_->VisitAllSamples(
679      std::bind(&ReportCommand::PrintReportEntry, this, std::placeholders::_1));
680  fflush(report_fp_);
681  if (ferror(report_fp_) != 0) {
682    PLOG(ERROR) << "print report failed";
683    return false;
684  }
685  return true;
686}
687
688void ReportCommand::PrintReportContext() {
689  const EventType* event_type = FindEventTypeByConfig(event_attr_.type, event_attr_.config);
690  std::string event_type_name;
691  if (event_type != nullptr) {
692    event_type_name = event_type->name;
693  } else {
694    event_type_name =
695        android::base::StringPrintf("(type %u, config %llu)", event_attr_.type, event_attr_.config);
696  }
697  if (!record_cmdline_.empty()) {
698    fprintf(report_fp_, "Cmdline: %s\n", record_cmdline_.c_str());
699  }
700  fprintf(report_fp_, "Samples: %" PRIu64 " of event '%s'\n", sample_tree_->TotalSamples(),
701          event_type_name.c_str());
702  fprintf(report_fp_, "Event count: %" PRIu64 "\n\n", sample_tree_->TotalPeriod());
703}
704
705void ReportCommand::CollectReportWidth() {
706  sample_tree_->VisitAllSamples(
707      std::bind(&ReportCommand::CollectReportEntryWidth, this, std::placeholders::_1));
708}
709
710void ReportCommand::CollectReportEntryWidth(const SampleEntry& sample) {
711  for (auto& item : displayable_items_) {
712    item->AdjustWidth(sample);
713  }
714}
715
716void ReportCommand::PrintReportHeader() {
717  for (size_t i = 0; i < displayable_items_.size(); ++i) {
718    auto& item = displayable_items_[i];
719    if (i != displayable_items_.size() - 1) {
720      fprintf(report_fp_, "%-*s  ", static_cast<int>(item->Width()), item->Name().c_str());
721    } else {
722      fprintf(report_fp_, "%s\n", item->Name().c_str());
723    }
724  }
725}
726
727void ReportCommand::PrintReportEntry(const SampleEntry& sample) {
728  for (size_t i = 0; i < displayable_items_.size(); ++i) {
729    auto& item = displayable_items_[i];
730    if (i != displayable_items_.size() - 1) {
731      fprintf(report_fp_, "%-*s  ", static_cast<int>(item->Width()), item->Show(sample).c_str());
732    } else {
733      fprintf(report_fp_, "%s\n", item->Show(sample).c_str());
734    }
735  }
736  if (print_callgraph_) {
737    PrintCallGraph(sample);
738  }
739}
740
741void ReportCommand::PrintCallGraph(const SampleEntry& sample) {
742  std::string prefix = "       ";
743  fprintf(report_fp_, "%s|\n", prefix.c_str());
744  fprintf(report_fp_, "%s-- %s\n", prefix.c_str(), sample.symbol->DemangledName());
745  prefix.append(3, ' ');
746  for (size_t i = 0; i < sample.callchain.children.size(); ++i) {
747    PrintCallGraphEntry(1, prefix, sample.callchain.children[i], sample.callchain.children_period,
748                        (i + 1 == sample.callchain.children.size()));
749  }
750}
751
752void ReportCommand::PrintCallGraphEntry(size_t depth, std::string prefix,
753                                        const std::unique_ptr<CallChainNode>& node,
754                                        uint64_t parent_period, bool last) {
755  if (depth > 20) {
756    LOG(WARNING) << "truncated callgraph at depth " << depth;
757    return;
758  }
759  prefix += "|";
760  fprintf(report_fp_, "%s\n", prefix.c_str());
761  if (last) {
762    prefix.back() = ' ';
763  }
764  std::string percentage_s = "-- ";
765  if (node->period + node->children_period != parent_period) {
766    double percentage = 100.0 * (node->period + node->children_period) / parent_period;
767    percentage_s = android::base::StringPrintf("--%.2lf%%-- ", percentage);
768  }
769  fprintf(report_fp_, "%s%s%s\n", prefix.c_str(), percentage_s.c_str(), node->chain[0]->symbol->DemangledName());
770  prefix.append(percentage_s.size(), ' ');
771  for (size_t i = 1; i < node->chain.size(); ++i) {
772    fprintf(report_fp_, "%s%s\n", prefix.c_str(), node->chain[i]->symbol->DemangledName());
773  }
774
775  for (size_t i = 0; i < node->children.size(); ++i) {
776    PrintCallGraphEntry(depth + 1, prefix, node->children[i], node->children_period,
777                        (i + 1 == node->children.size()));
778  }
779}
780
781void RegisterReportCommand() {
782  RegisterCommand("report", [] { return std::unique_ptr<Command>(new ReportCommand()); });
783}
784