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 <android-base/file.h>
28 #include <android-base/logging.h>
29 #include <android-base/parsedouble.h>
30 #include <android-base/parseint.h>
31 #include <android-base/stringprintf.h>
32 #include <android-base/strings.h>
35 #include "dwarf_unwind.h"
36 #include "event_attr.h"
37 #include "event_type.h"
38 #include "perf_regs.h"
40 #include "record_file.h"
41 #include "sample_tree.h"
42 #include "thread_tree.h"
48 static std::set<std::string> branch_sort_keys = {
49 "dso_from", "dso_to", "symbol_from", "symbol_to",
51 struct BranchFromEntry {
54 uint64_t vaddr_in_file;
58 : map(nullptr), symbol(nullptr), vaddr_in_file(0), flags(0) {}
64 // accumuated when appearing in other sample's callchain
65 uint64_t accumulated_period;
66 uint64_t sample_count;
67 const ThreadEntry* thread;
68 const char* thread_comm;
71 uint64_t vaddr_in_file;
72 BranchFromEntry branch_from;
73 // a callchain tree representing all callchains in the sample
74 CallChainRoot<SampleEntry> callchain;
76 SampleEntry(uint64_t time, uint64_t period, uint64_t accumulated_period,
77 uint64_t sample_count, const ThreadEntry* thread,
78 const MapEntry* map, const Symbol* symbol, uint64_t vaddr_in_file)
81 accumulated_period(accumulated_period),
82 sample_count(sample_count),
84 thread_comm(thread->comm),
87 vaddr_in_file(vaddr_in_file) {}
89 // The data member 'callchain' can only move, not copy.
90 SampleEntry(SampleEntry&&) = default;
91 SampleEntry(SampleEntry&) = delete;
93 uint64_t GetPeriod() const {
99 std::vector<SampleEntry*> samples;
100 uint64_t total_samples;
101 uint64_t total_period;
104 BUILD_COMPARE_VALUE_FUNCTION(CompareVaddrInFile, vaddr_in_file);
105 BUILD_DISPLAY_HEX64_FUNCTION(DisplayVaddrInFile, vaddr_in_file);
107 class ReportCmdSampleTreeBuilder
108 : public SampleTreeBuilder<SampleEntry, uint64_t> {
110 ReportCmdSampleTreeBuilder(SampleComparator<SampleEntry> sample_comparator,
111 ThreadTree* thread_tree)
112 : SampleTreeBuilder(sample_comparator),
113 thread_tree_(thread_tree),
117 void SetFilters(const std::unordered_set<int>& pid_filter,
118 const std::unordered_set<int>& tid_filter,
119 const std::unordered_set<std::string>& comm_filter,
120 const std::unordered_set<std::string>& dso_filter,
121 const std::unordered_set<std::string>& symbol_filter) {
122 pid_filter_ = pid_filter;
123 tid_filter_ = tid_filter;
124 comm_filter_ = comm_filter;
125 dso_filter_ = dso_filter;
126 symbol_filter_ = symbol_filter;
129 SampleTree GetSampleTree() const {
130 SampleTree sample_tree;
131 sample_tree.samples = GetSamples();
132 sample_tree.total_samples = total_samples_;
133 sample_tree.total_period = total_period_;
138 SampleEntry* CreateSample(const SampleRecord& r, bool in_kernel,
139 uint64_t* acc_info) override {
140 const ThreadEntry* thread =
141 thread_tree_->FindThreadOrNew(r.tid_data.pid, r.tid_data.tid);
142 const MapEntry* map =
143 thread_tree_->FindMap(thread, r.ip_data.ip, in_kernel);
144 uint64_t vaddr_in_file;
145 const Symbol* symbol =
146 thread_tree_->FindSymbol(map, r.ip_data.ip, &vaddr_in_file);
147 *acc_info = r.period_data.period;
148 return InsertSample(std::unique_ptr<SampleEntry>(
149 new SampleEntry(r.time_data.time, r.period_data.period, 0, 1, thread,
150 map, symbol, vaddr_in_file)));
153 SampleEntry* CreateBranchSample(const SampleRecord& r,
154 const BranchStackItemType& item) override {
155 const ThreadEntry* thread =
156 thread_tree_->FindThreadOrNew(r.tid_data.pid, r.tid_data.tid);
157 const MapEntry* from_map = thread_tree_->FindMap(thread, item.from);
158 uint64_t from_vaddr_in_file;
159 const Symbol* from_symbol =
160 thread_tree_->FindSymbol(from_map, item.from, &from_vaddr_in_file);
161 const MapEntry* to_map = thread_tree_->FindMap(thread, item.to);
162 uint64_t to_vaddr_in_file;
163 const Symbol* to_symbol =
164 thread_tree_->FindSymbol(to_map, item.to, &to_vaddr_in_file);
165 std::unique_ptr<SampleEntry> sample(
166 new SampleEntry(r.time_data.time, r.period_data.period, 0, 1, thread,
167 to_map, to_symbol, to_vaddr_in_file));
168 sample->branch_from.map = from_map;
169 sample->branch_from.symbol = from_symbol;
170 sample->branch_from.vaddr_in_file = from_vaddr_in_file;
171 sample->branch_from.flags = item.flags;
172 return InsertSample(std::move(sample));
175 SampleEntry* CreateCallChainSample(const SampleEntry* sample, uint64_t ip,
177 const std::vector<SampleEntry*>& callchain,
178 const uint64_t& acc_info) override {
179 const ThreadEntry* thread = sample->thread;
180 const MapEntry* map = thread_tree_->FindMap(thread, ip, in_kernel);
181 uint64_t vaddr_in_file;
182 const Symbol* symbol = thread_tree_->FindSymbol(map, ip, &vaddr_in_file);
183 std::unique_ptr<SampleEntry> callchain_sample(new SampleEntry(
184 sample->time, 0, acc_info, 0, thread, map, symbol, vaddr_in_file));
185 callchain_sample->thread_comm = sample->thread_comm;
186 return InsertCallChainSample(std::move(callchain_sample), callchain);
189 const ThreadEntry* GetThreadOfSample(SampleEntry* sample) override {
190 return sample->thread;
193 uint64_t GetPeriodForCallChain(const uint64_t& acc_info) override {
197 bool FilterSample(const SampleEntry* sample) override {
198 if (!pid_filter_.empty() &&
199 pid_filter_.find(sample->thread->pid) == pid_filter_.end()) {
202 if (!tid_filter_.empty() &&
203 tid_filter_.find(sample->thread->tid) == tid_filter_.end()) {
206 if (!comm_filter_.empty() &&
207 comm_filter_.find(sample->thread_comm) == comm_filter_.end()) {
210 if (!dso_filter_.empty() &&
211 dso_filter_.find(sample->map->dso->Path()) == dso_filter_.end()) {
214 if (!symbol_filter_.empty() &&
215 symbol_filter_.find(sample->symbol->DemangledName()) ==
216 symbol_filter_.end()) {
222 void UpdateSummary(const SampleEntry* sample) override {
223 total_samples_ += sample->sample_count;
224 total_period_ += sample->period;
227 void MergeSample(SampleEntry* sample1, SampleEntry* sample2) override {
228 sample1->period += sample2->period;
229 sample1->accumulated_period += sample2->accumulated_period;
230 sample1->sample_count += sample2->sample_count;
234 ThreadTree* thread_tree_;
236 std::unordered_set<int> pid_filter_;
237 std::unordered_set<int> tid_filter_;
238 std::unordered_set<std::string> comm_filter_;
239 std::unordered_set<std::string> dso_filter_;
240 std::unordered_set<std::string> symbol_filter_;
242 uint64_t total_samples_;
243 uint64_t total_period_;
246 struct SampleTreeBuilderOptions {
247 SampleComparator<SampleEntry> comparator;
248 ThreadTree* thread_tree;
249 std::unordered_set<std::string> comm_filter;
250 std::unordered_set<std::string> dso_filter;
251 std::unordered_set<std::string> symbol_filter;
252 std::unordered_set<int> pid_filter;
253 std::unordered_set<int> tid_filter;
254 bool use_branch_address;
255 bool accumulate_callchain;
256 bool build_callchain;
257 bool use_caller_as_callchain_root;
258 bool strict_unwind_arch_check;
260 std::unique_ptr<ReportCmdSampleTreeBuilder> CreateSampleTreeBuilder() {
261 std::unique_ptr<ReportCmdSampleTreeBuilder> builder(
262 new ReportCmdSampleTreeBuilder(comparator, thread_tree));
263 builder->SetFilters(pid_filter, tid_filter, comm_filter, dso_filter, symbol_filter);
264 builder->SetBranchSampleOption(use_branch_address);
265 builder->SetCallChainSampleOptions(accumulate_callchain, build_callchain,
266 use_caller_as_callchain_root, strict_unwind_arch_check);
271 using ReportCmdSampleTreeSorter = SampleTreeSorter<SampleEntry>;
272 using ReportCmdSampleTreeDisplayer =
273 SampleTreeDisplayer<SampleEntry, SampleTree>;
275 using ReportCmdCallgraphDisplayer =
276 CallgraphDisplayer<SampleEntry, CallChainNode<SampleEntry>>;
278 class ReportCmdCallgraphDisplayerWithVaddrInFile
279 : public ReportCmdCallgraphDisplayer {
281 std::string PrintSampleName(const SampleEntry* sample) override {
282 return android::base::StringPrintf("%s [+0x%" PRIx64 "]",
283 sample->symbol->DemangledName(),
284 sample->vaddr_in_file);
288 struct EventAttrWithName {
289 perf_event_attr attr;
293 class ReportCommand : public Command {
297 "report", "report sampling information in perf.data",
299 "Usage: simpleperf report [options]\n"
300 "-b Use the branch-to addresses in sampled take branches instead of the\n"
301 " instruction addresses. Only valid for perf.data recorded with -b/-j\n"
303 "--children Print the overhead accumulated by appearing in the callchain.\n"
304 "--comms comm1,comm2,... Report only for selected comms.\n"
305 "--dsos dso1,dso2,... Report only for selected dsos.\n"
306 "-g [callee|caller] Print call graph. If callee mode is used, the graph\n"
307 " shows how functions are called from others. Otherwise,\n"
308 " the graph shows how functions call others.\n"
309 " Default is caller mode.\n"
310 "-i <file> Specify path of record file, default is perf.data.\n"
311 "--kallsyms <file> Set the file to read kernel symbols.\n"
312 "--max-stack <frames> Set max stack frames shown when printing call graph.\n"
313 "-n Print the sample count for each item.\n"
314 "--no-demangle Don't demangle symbol names.\n"
315 "--no-show-ip Don't show vaddr in file for unknown symbols.\n"
316 "-o report_file_name Set report file name, default is stdout.\n"
317 "--percent-limit <percent> Set min percentage shown when printing call graph.\n"
318 "--pids pid1,pid2,... Report only for selected pids.\n"
319 "--sort key1,key2,... Select keys used to sort and print the report. The\n"
320 " appearance order of keys decides the order of keys used\n"
321 " to sort and print the report.\n"
322 " Possible keys include:\n"
323 " pid -- process id\n"
324 " tid -- thread id\n"
325 " comm -- thread name (can be changed during\n"
326 " the lifetime of a thread)\n"
327 " dso -- shared library\n"
328 " symbol -- function name in the shared library\n"
329 " vaddr_in_file -- virtual address in the shared\n"
331 " Keys can only be used with -b option:\n"
332 " dso_from -- shared library branched from\n"
333 " dso_to -- shared library branched to\n"
334 " symbol_from -- name of function branched from\n"
335 " symbol_to -- name of function branched to\n"
336 " The default sort keys are:\n"
337 " comm,pid,tid,dso,symbol\n"
338 "--symbols symbol1;symbol2;... Report only for selected symbols.\n"
339 "--symfs <dir> Look for files with symbols relative to this directory.\n"
340 "--tids tid1,tid2,... Report only for selected tids.\n"
341 "--vmlinux <file> Parse kernel symbols from <file>.\n"
344 record_filename_("perf.data"),
345 record_file_arch_(GetBuildArch()),
346 use_branch_address_(false),
347 system_wide_collection_(false),
348 accumulate_callchain_(false),
349 print_callgraph_(false),
350 callgraph_show_callee_(false),
351 callgraph_max_stack_(UINT32_MAX),
352 callgraph_percent_limit_(0) {}
354 bool Run(const std::vector<std::string>& args);
357 bool ParseOptions(const std::vector<std::string>& args);
358 bool ReadEventAttrFromRecordFile();
359 bool ReadFeaturesFromRecordFile();
360 bool ReadSampleTreeFromRecordFile();
361 bool ProcessRecord(std::unique_ptr<Record> record);
362 bool ProcessTracingData(const std::vector<char>& data);
364 void PrintReportContext(FILE* fp);
366 std::string record_filename_;
367 ArchType record_file_arch_;
368 std::unique_ptr<RecordFileReader> record_file_reader_;
369 std::vector<EventAttrWithName> event_attrs_;
370 ThreadTree thread_tree_;
371 // Create a SampleTreeBuilder and SampleTree for each event_attr.
372 std::vector<SampleTree> sample_tree_;
373 SampleTreeBuilderOptions sample_tree_builder_options_;
374 std::vector<std::unique_ptr<ReportCmdSampleTreeBuilder>> sample_tree_builder_;
376 std::unique_ptr<ReportCmdSampleTreeSorter> sample_tree_sorter_;
377 std::unique_ptr<ReportCmdSampleTreeDisplayer> sample_tree_displayer_;
378 bool use_branch_address_;
379 std::string record_cmdline_;
380 bool system_wide_collection_;
381 bool accumulate_callchain_;
382 bool print_callgraph_;
383 bool callgraph_show_callee_;
384 uint32_t callgraph_max_stack_;
385 double callgraph_percent_limit_;
387 std::string report_filename_;
390 bool ReportCommand::Run(const std::vector<std::string>& args) {
392 if (!ParseOptions(args)) {
396 // 2. Read record file and build SampleTree.
397 record_file_reader_ = RecordFileReader::CreateInstance(record_filename_);
398 if (record_file_reader_ == nullptr) {
401 if (!ReadEventAttrFromRecordFile()) {
404 // Read features first to prepare build ids used when building SampleTree.
405 if (!ReadFeaturesFromRecordFile()) {
408 ScopedCurrentArch scoped_arch(record_file_arch_);
409 if (!ReadSampleTreeFromRecordFile()) {
413 // 3. Show collected information.
414 if (!PrintReport()) {
421 bool ReportCommand::ParseOptions(const std::vector<std::string>& args) {
422 bool demangle = true;
423 bool show_ip_for_unknown_symbol = true;
424 std::string symfs_dir;
426 bool print_sample_count = false;
427 std::vector<std::string> sort_keys = {"comm", "pid", "tid", "dso", "symbol"};
429 for (size_t i = 0; i < args.size(); ++i) {
430 if (args[i] == "-b") {
431 use_branch_address_ = true;
432 } else if (args[i] == "--children") {
433 accumulate_callchain_ = true;
434 } else if (args[i] == "--comms" || args[i] == "--dsos") {
435 std::unordered_set<std::string>& filter =
436 (args[i] == "--comms" ? sample_tree_builder_options_.comm_filter
437 : sample_tree_builder_options_.dso_filter);
438 if (!NextArgumentOrError(args, &i)) {
441 std::vector<std::string> strs = android::base::Split(args[i], ",");
442 filter.insert(strs.begin(), strs.end());
444 } else if (args[i] == "-g") {
445 print_callgraph_ = true;
446 accumulate_callchain_ = true;
447 if (i + 1 < args.size() && args[i + 1][0] != '-') {
449 if (args[i] == "callee") {
450 callgraph_show_callee_ = true;
451 } else if (args[i] == "caller") {
452 callgraph_show_callee_ = false;
454 LOG(ERROR) << "Unknown argument with -g option: " << args[i];
458 } else if (args[i] == "-i") {
459 if (!NextArgumentOrError(args, &i)) {
462 record_filename_ = args[i];
464 } else if (args[i] == "--kallsyms") {
465 if (!NextArgumentOrError(args, &i)) {
468 std::string kallsyms;
469 if (!android::base::ReadFileToString(args[i], &kallsyms)) {
470 LOG(ERROR) << "Can't read kernel symbols from " << args[i];
473 Dso::SetKallsyms(kallsyms);
474 } else if (args[i] == "--max-stack") {
475 if (!NextArgumentOrError(args, &i)) {
478 if (!android::base::ParseUint(args[i].c_str(), &callgraph_max_stack_)) {
479 LOG(ERROR) << "invalid arg for --max-stack: " << args[i];
482 } else if (args[i] == "-n") {
483 print_sample_count = true;
485 } else if (args[i] == "--no-demangle") {
487 } else if (args[i] == "--no-show-ip") {
488 show_ip_for_unknown_symbol = false;
489 } else if (args[i] == "-o") {
490 if (!NextArgumentOrError(args, &i)) {
493 report_filename_ = args[i];
494 } else if (args[i] == "--percent-limit") {
495 if (!NextArgumentOrError(args, &i)) {
498 if (!android::base::ParseDouble(args[i].c_str(),
499 &callgraph_percent_limit_, 0.0)) {
500 LOG(ERROR) << "invalid arg for --percent-limit: " << args[i];
502 } else if (args[i] == "--pids" || args[i] == "--tids") {
503 const std::string& option = args[i];
504 std::unordered_set<int>& filter =
505 (option == "--pids" ? sample_tree_builder_options_.pid_filter
506 : sample_tree_builder_options_.tid_filter);
507 if (!NextArgumentOrError(args, &i)) {
510 std::vector<std::string> strs = android::base::Split(args[i], ",");
511 for (const auto& s : strs) {
513 if (!android::base::ParseInt(s.c_str(), &id, 0)) {
514 LOG(ERROR) << "invalid id in " << option << " option: " << s;
520 } else if (args[i] == "--sort") {
521 if (!NextArgumentOrError(args, &i)) {
524 sort_keys = android::base::Split(args[i], ",");
525 } else if (args[i] == "--symbols") {
526 if (!NextArgumentOrError(args, &i)) {
529 std::vector<std::string> strs = android::base::Split(args[i], ";");
530 sample_tree_builder_options_.symbol_filter.insert(strs.begin(), strs.end());
531 } else if (args[i] == "--symfs") {
532 if (!NextArgumentOrError(args, &i)) {
537 } else if (args[i] == "--vmlinux") {
538 if (!NextArgumentOrError(args, &i)) {
543 ReportUnknownOption(args, i);
548 Dso::SetDemangle(demangle);
549 if (!Dso::SetSymFsDir(symfs_dir)) {
552 if (!vmlinux.empty()) {
553 Dso::SetVmlinux(vmlinux);
556 if (show_ip_for_unknown_symbol) {
557 thread_tree_.ShowIpForUnknownSymbol();
560 SampleDisplayer<SampleEntry, SampleTree> displayer;
561 SampleComparator<SampleEntry> comparator;
563 if (accumulate_callchain_) {
564 displayer.AddDisplayFunction("Children", DisplayAccumulatedOverhead);
565 displayer.AddDisplayFunction("Self", DisplaySelfOverhead);
567 displayer.AddDisplayFunction("Overhead", DisplaySelfOverhead);
569 if (print_sample_count) {
570 displayer.AddDisplayFunction("Sample", DisplaySampleCount);
573 for (auto& key : sort_keys) {
574 if (!use_branch_address_ &&
575 branch_sort_keys.find(key) != branch_sort_keys.end()) {
576 LOG(ERROR) << "sort key '" << key << "' can only be used with -b option.";
580 comparator.AddCompareFunction(ComparePid);
581 displayer.AddDisplayFunction("Pid", DisplayPid);
582 } else if (key == "tid") {
583 comparator.AddCompareFunction(CompareTid);
584 displayer.AddDisplayFunction("Tid", DisplayTid);
585 } else if (key == "comm") {
586 comparator.AddCompareFunction(CompareComm);
587 displayer.AddDisplayFunction("Command", DisplayComm);
588 } else if (key == "dso") {
589 comparator.AddCompareFunction(CompareDso);
590 displayer.AddDisplayFunction("Shared Object", DisplayDso);
591 } else if (key == "symbol") {
592 comparator.AddCompareFunction(CompareSymbol);
593 displayer.AddDisplayFunction("Symbol", DisplaySymbol);
594 } else if (key == "vaddr_in_file") {
595 comparator.AddCompareFunction(CompareVaddrInFile);
596 displayer.AddDisplayFunction("VaddrInFile", DisplayVaddrInFile);
597 } else if (key == "dso_from") {
598 comparator.AddCompareFunction(CompareDsoFrom);
599 displayer.AddDisplayFunction("Source Shared Object", DisplayDsoFrom);
600 } else if (key == "dso_to") {
601 comparator.AddCompareFunction(CompareDso);
602 displayer.AddDisplayFunction("Target Shared Object", DisplayDso);
603 } else if (key == "symbol_from") {
604 comparator.AddCompareFunction(CompareSymbolFrom);
605 displayer.AddDisplayFunction("Source Symbol", DisplaySymbolFrom);
606 } else if (key == "symbol_to") {
607 comparator.AddCompareFunction(CompareSymbol);
608 displayer.AddDisplayFunction("Target Symbol", DisplaySymbol);
610 LOG(ERROR) << "Unknown sort key: " << key;
614 if (print_callgraph_) {
615 bool has_symbol_key = false;
616 bool has_vaddr_in_file_key = false;
617 for (const auto& key : sort_keys) {
618 if (key == "symbol") {
619 has_symbol_key = true;
620 } else if (key == "vaddr_in_file") {
621 has_vaddr_in_file_key = true;
624 if (has_symbol_key) {
625 if (has_vaddr_in_file_key) {
626 displayer.AddExclusiveDisplayFunction(
627 ReportCmdCallgraphDisplayerWithVaddrInFile());
629 displayer.AddExclusiveDisplayFunction(ReportCmdCallgraphDisplayer(
630 callgraph_max_stack_, callgraph_percent_limit_));
635 sample_tree_builder_options_.comparator = comparator;
636 sample_tree_builder_options_.thread_tree = &thread_tree_;
638 SampleComparator<SampleEntry> sort_comparator;
639 sort_comparator.AddCompareFunction(CompareTotalPeriod);
640 sort_comparator.AddComparator(comparator);
641 sample_tree_sorter_.reset(new ReportCmdSampleTreeSorter(sort_comparator));
642 sample_tree_displayer_.reset(new ReportCmdSampleTreeDisplayer(displayer));
646 bool ReportCommand::ReadEventAttrFromRecordFile() {
647 std::vector<EventAttrWithId> attrs = record_file_reader_->AttrSection();
648 for (const auto& attr_with_id : attrs) {
649 EventAttrWithName attr;
650 attr.attr = *attr_with_id.attr;
651 attr.name = GetEventNameByAttr(attr.attr);
652 event_attrs_.push_back(attr);
654 if (use_branch_address_) {
655 bool has_branch_stack = true;
656 for (const auto& attr : event_attrs_) {
657 if ((attr.attr.sample_type & PERF_SAMPLE_BRANCH_STACK) == 0) {
658 has_branch_stack = false;
662 if (!has_branch_stack) {
663 LOG(ERROR) << record_filename_
664 << " is not recorded with branch stack sampling option.";
671 bool ReportCommand::ReadFeaturesFromRecordFile() {
672 record_file_reader_->LoadBuildIdAndFileFeatures(thread_tree_);
675 record_file_reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH);
677 record_file_arch_ = GetArchType(arch);
678 if (record_file_arch_ == ARCH_UNSUPPORTED) {
683 std::vector<std::string> cmdline = record_file_reader_->ReadCmdlineFeature();
684 if (!cmdline.empty()) {
685 record_cmdline_ = android::base::Join(cmdline, ' ');
686 // TODO: the code to detect system wide collection option is fragile, remove
687 // it once we can do cross unwinding.
688 for (size_t i = 0; i < cmdline.size(); i++) {
689 std::string& s = cmdline[i];
691 system_wide_collection_ = true;
693 } else if (s == "--call-graph" || s == "--cpu" || s == "-e" ||
694 s == "-f" || s == "-F" || s == "-j" || s == "-m" ||
695 s == "-o" || s == "-p" || s == "-t") {
697 } else if (!s.empty() && s[0] != '-') {
702 if (record_file_reader_->HasFeature(PerfFileFormat::FEAT_TRACING_DATA)) {
703 std::vector<char> tracing_data;
704 if (!record_file_reader_->ReadFeatureSection(
705 PerfFileFormat::FEAT_TRACING_DATA, &tracing_data)) {
708 if (!ProcessTracingData(tracing_data)) {
715 bool ReportCommand::ReadSampleTreeFromRecordFile() {
716 sample_tree_builder_options_.use_branch_address = use_branch_address_;
717 // Normally do strict arch check when unwinding stack. But allow unwinding
718 // 32-bit processes on 64-bit devices for system wide profiling.
719 sample_tree_builder_options_.strict_unwind_arch_check = !system_wide_collection_;
720 sample_tree_builder_options_.accumulate_callchain = accumulate_callchain_;
721 sample_tree_builder_options_.build_callchain = print_callgraph_;
722 sample_tree_builder_options_.use_caller_as_callchain_root = !callgraph_show_callee_;
724 for (size_t i = 0; i < event_attrs_.size(); ++i) {
725 sample_tree_builder_.push_back(sample_tree_builder_options_.CreateSampleTreeBuilder());
728 if (!record_file_reader_->ReadDataSection(
729 [this](std::unique_ptr<Record> record) {
730 return ProcessRecord(std::move(record));
734 for (size_t i = 0; i < sample_tree_builder_.size(); ++i) {
735 sample_tree_.push_back(sample_tree_builder_[i]->GetSampleTree());
736 sample_tree_sorter_->Sort(sample_tree_.back().samples, print_callgraph_);
741 bool ReportCommand::ProcessRecord(std::unique_ptr<Record> record) {
742 thread_tree_.Update(*record);
743 if (record->type() == PERF_RECORD_SAMPLE) {
744 size_t attr_id = record_file_reader_->GetAttrIndexOfRecord(record.get());
745 sample_tree_builder_[attr_id]->ProcessSampleRecord(
746 *static_cast<const SampleRecord*>(record.get()));
747 } else if (record->type() == PERF_RECORD_TRACING_DATA) {
748 const auto& r = *static_cast<TracingDataRecord*>(record.get());
749 if (!ProcessTracingData(std::vector<char>(r.data, r.data + r.data_size))) {
756 bool ReportCommand::ProcessTracingData(const std::vector<char>& data) {
757 Tracing tracing(data);
758 for (auto& attr : event_attrs_) {
759 if (attr.attr.type == PERF_TYPE_TRACEPOINT) {
760 uint64_t trace_event_id = attr.attr.config;
761 attr.name = tracing.GetTracingEventNameHavingId(trace_event_id);
767 bool ReportCommand::PrintReport() {
768 std::unique_ptr<FILE, decltype(&fclose)> file_handler(nullptr, fclose);
769 FILE* report_fp = stdout;
770 if (!report_filename_.empty()) {
771 report_fp = fopen(report_filename_.c_str(), "w");
772 if (report_fp == nullptr) {
773 PLOG(ERROR) << "failed to open file " << report_filename_;
776 file_handler.reset(report_fp);
778 PrintReportContext(report_fp);
779 for (size_t i = 0; i < event_attrs_.size(); ++i) {
781 fprintf(report_fp, "\n");
783 EventAttrWithName& attr = event_attrs_[i];
784 SampleTree& sample_tree = sample_tree_[i];
785 fprintf(report_fp, "Event: %s (type %u, config %llu)\n", attr.name.c_str(),
786 attr.attr.type, attr.attr.config);
787 fprintf(report_fp, "Samples: %" PRIu64 "\n", sample_tree.total_samples);
788 fprintf(report_fp, "Event count: %" PRIu64 "\n\n", sample_tree.total_period);
789 sample_tree_displayer_->DisplaySamples(report_fp, sample_tree.samples, &sample_tree);
792 if (ferror(report_fp) != 0) {
793 PLOG(ERROR) << "print report failed";
799 void ReportCommand::PrintReportContext(FILE* report_fp) {
800 if (!record_cmdline_.empty()) {
801 fprintf(report_fp, "Cmdline: %s\n", record_cmdline_.c_str());
803 fprintf(report_fp, "Arch: %s\n", GetArchString(record_file_arch_).c_str());
808 void RegisterReportCommand() {
809 RegisterCommand("report",
810 [] { return std::unique_ptr<Command>(new ReportCommand()); });