2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
23 #include <unordered_map>
24 #include <unordered_set>
27 #include <base/logging.h>
28 #include <base/stringprintf.h>
29 #include <base/strings.h>
32 #include "environment.h"
33 #include "event_attr.h"
34 #include "event_type.h"
35 #include "perf_regs.h"
37 #include "record_file.h"
38 #include "sample_tree.h"
39 #include "thread_tree.h"
44 Displayable(const std::string& name) : name_(name), width_(name.size()) {
47 virtual ~Displayable() {
50 const std::string& Name() const {
53 size_t Width() const {
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);
64 const std::string name_;
68 class AccumulatedOverheadItem : public Displayable {
70 AccumulatedOverheadItem(const SampleTree& sample_tree)
71 : Displayable("Children"), sample_tree_(sample_tree) {
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);
82 const SampleTree& sample_tree_;
85 class SelfOverheadItem : public Displayable {
87 SelfOverheadItem(const SampleTree& sample_tree, const std::string& name = "Self")
88 : Displayable(name), sample_tree_(sample_tree) {
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);
99 const SampleTree& sample_tree_;
102 class SampleCountItem : public Displayable {
104 SampleCountItem() : Displayable("Sample") {
107 std::string Show(const SampleEntry& sample) const override {
108 return android::base::StringPrintf("%" PRId64, sample.sample_count);
114 virtual ~Comparable() {
117 virtual int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const = 0;
120 class PidItem : public Displayable, public Comparable {
122 PidItem() : Displayable("Pid") {
125 int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
126 return sample1.thread->pid - sample2.thread->pid;
129 std::string Show(const SampleEntry& sample) const override {
130 return android::base::StringPrintf("%d", sample.thread->pid);
134 class TidItem : public Displayable, public Comparable {
136 TidItem() : Displayable("Tid") {
139 int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
140 return sample1.thread->tid - sample2.thread->tid;
143 std::string Show(const SampleEntry& sample) const override {
144 return android::base::StringPrintf("%d", sample.thread->tid);
148 class CommItem : public Displayable, public Comparable {
150 CommItem() : Displayable("Command") {
153 int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
154 return strcmp(sample1.thread_comm, sample2.thread_comm);
157 std::string Show(const SampleEntry& sample) const override {
158 return sample.thread_comm;
162 class DsoItem : public Displayable, public Comparable {
164 DsoItem(const std::string& name = "Shared Object") : Displayable(name) {
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());
171 std::string Show(const SampleEntry& sample) const override {
172 return sample.map->dso->Path();
176 class SymbolItem : public Displayable, public Comparable {
178 SymbolItem(const std::string& name = "Symbol") : Displayable(name) {
181 int Compare(const SampleEntry& sample1, const SampleEntry& sample2) const override {
182 return strcmp(sample1.symbol->DemangledName(), sample2.symbol->DemangledName());
185 std::string Show(const SampleEntry& sample) const override {
186 return sample.symbol->DemangledName();
190 class DsoFromItem : public Displayable, public Comparable {
192 DsoFromItem() : Displayable("Source Shared Object") {
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());
200 std::string Show(const SampleEntry& sample) const override {
201 return sample.branch_from.map->dso->Path();
205 class DsoToItem : public DsoItem {
207 DsoToItem() : DsoItem("Target Shared Object") {
211 class SymbolFromItem : public Displayable, public Comparable {
213 SymbolFromItem() : Displayable("Source Symbol") {
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());
221 std::string Show(const SampleEntry& sample) const override {
222 return sample.branch_from.symbol->DemangledName();
226 class SymbolToItem : public SymbolItem {
228 SymbolToItem() : SymbolItem("Target Symbol") {
232 static std::set<std::string> branch_sort_keys = {
233 "dso_from", "dso_to", "symbol_from", "symbol_to",
236 class ReportCommand : public 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"
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);
277 std::unique_ptr<SampleTree>(new SampleTree(&thread_tree_, compare_sample_callback));
280 bool Run(const std::vector<std::string>& args);
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);
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);
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_;
311 bool ReportCommand::Run(const std::vector<std::string>& args) {
313 if (!ParseOptions(args)) {
317 // 2. Read record file and build SampleTree.
318 record_file_reader_ = RecordFileReader::CreateInstance(record_filename_);
319 if (record_file_reader_ == nullptr) {
322 if (!ReadEventAttrFromRecordFile()) {
325 // Read features first to prepare build ids used when building SampleTree.
326 if (!ReadFeaturesFromRecordFile()) {
329 ReadSampleTreeFromRecordFile();
331 // 3. Show collected information.
337 bool ReportCommand::ParseOptions(const std::vector<std::string>& args) {
338 bool demangle = true;
339 std::string symfs_dir;
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;
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)) {
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());
361 } else if (args[i] == "-g") {
362 print_callgraph_ = true;
363 accumulate_callchain_ = true;
364 if (i + 1 < args.size() && args[i + 1][0] != '-') {
366 if (args[i] == "callee") {
367 callgraph_show_callee_ = true;
368 } else if (args[i] == "caller") {
369 callgraph_show_callee_ = false;
371 LOG(ERROR) << "Unknown argument with -g option: " << args[i];
375 } else if (args[i] == "-i") {
376 if (!NextArgumentOrError(args, &i)) {
379 record_filename_ = args[i];
381 } else if (args[i] == "-n") {
382 print_sample_count = true;
384 } else if (args[i] == "--no-demangle") {
387 } else if (args[i] == "--pids" || args[i] == "--tids") {
388 if (!NextArgumentOrError(args, &i)) {
391 std::vector<std::string> strs = android::base::Split(args[i], ",");
392 std::vector<int> ids;
393 for (auto& s : strs) {
395 if (!StringToPid(s, &id)) {
396 LOG(ERROR) << "invalid id in " << args[i] << " option: " << s;
401 std::unordered_set<int>& filter = (args[i] == "--pids" ? pid_filter : tid_filter);
402 filter.insert(ids.begin(), ids.end());
404 } else if (args[i] == "--sort") {
405 if (!NextArgumentOrError(args, &i)) {
408 sort_keys = android::base::Split(args[i], ",");
409 } else if (args[i] == "--symfs") {
410 if (!NextArgumentOrError(args, &i)) {
415 } else if (args[i] == "--vmlinux") {
416 if (!NextArgumentOrError(args, &i)) {
421 ReportUnknownOption(args, i);
426 Dso::SetDemangle(demangle);
427 if (!Dso::SetSymFsDir(symfs_dir)) {
430 if (!vmlinux.empty()) {
431 Dso::SetVmlinux(vmlinux);
434 if (!accumulate_callchain_) {
435 displayable_items_.push_back(
436 std::unique_ptr<Displayable>(new SelfOverheadItem(*sample_tree_, "Overhead")));
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_)));
442 if (print_sample_count) {
443 displayable_items_.push_back(std::unique_ptr<Displayable>(new SampleCountItem));
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.";
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);
487 LOG(ERROR) << "Unknown sort key: " << key;
491 sample_tree_->SetFilters(pid_filter, tid_filter, comm_filter, dso_filter);
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";
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.";
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()));
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);
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) {
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) {
543 case PERF_CONTEXT_KERNEL:
546 case PERF_CONTEXT_USER:
550 LOG(ERROR) << "Unexpected perf_context in callchain: " << ip;
554 // Remove duplication with sampled ip.
555 if (ip == r.ip_data.ip) {
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);
566 if (print_callgraph_) {
567 std::set<SampleEntry*> added_set;
568 if (!callgraph_show_callee_) {
569 std::reverse(callchain.begin(), callchain.end());
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()) {
578 added_set.insert(sample);
579 sample_tree_->InsertCallChainForSample(sample, callchain, r.period_data.period);
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));
592 Dso::SetBuildIds(build_ids);
594 std::string arch = record_file_reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH);
596 if (!SetCurrentArch(arch)) {
601 std::vector<std::string> cmdline = record_file_reader_->ReadCmdlineFeature();
602 if (!cmdline.empty()) {
603 record_cmdline_ = android::base::Join(cmdline, ' ');
608 int ReportCommand::CompareSampleEntry(const SampleEntry& sample1, const SampleEntry& sample2) {
609 for (auto& item : comparable_items_) {
610 int result = item->Compare(sample1, sample2);
618 void ReportCommand::PrintReport() {
619 PrintReportContext();
620 CollectReportWidth();
622 sample_tree_->VisitAllSamples(
623 std::bind(&ReportCommand::PrintReportEntry, this, std::placeholders::_1));
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;
634 android::base::StringPrintf("(type %u, config %llu)", event_attr_.type, event_attr_.config);
636 if (!record_cmdline_.empty()) {
637 printf("Cmdline: %s\n", record_cmdline_.c_str());
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());
644 void ReportCommand::CollectReportWidth() {
645 sample_tree_->VisitAllSamples(
646 std::bind(&ReportCommand::CollectReportEntryWidth, this, std::placeholders::_1));
649 void ReportCommand::CollectReportEntryWidth(const SampleEntry& sample) {
650 for (auto& item : displayable_items_) {
651 item->AdjustWidth(sample);
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());
661 printf("%s\n", item->Name().c_str());
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());
672 printf("%s\n", item->Show(sample).c_str());
675 if (print_callgraph_) {
676 PrintCallGraph(sample);
680 static void PrintCallGraphEntry(size_t depth, std::string prefix,
681 const std::unique_ptr<CallChainNode>& node, uint64_t parent_period,
684 LOG(WARNING) << "truncated callgraph at depth " << depth;
688 printf("%s\n", prefix.c_str());
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);
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());
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()));
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()));
720 __attribute__((constructor)) static void RegisterReportCommand() {
721 RegisterCommand("report", [] { return std::unique_ptr<Command>(new ReportCommand()); });