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 "--raw-period Report period count instead of period percentage.\n"
320 "--sort key1,key2,... Select keys used to sort and print the report. The\n"
321 " appearance order of keys decides the order of keys used\n"
322 " to sort and print the report.\n"
323 " Possible keys include:\n"
324 " pid -- process id\n"
325 " tid -- thread id\n"
326 " comm -- thread name (can be changed during\n"
327 " the lifetime of a thread)\n"
328 " dso -- shared library\n"
329 " symbol -- function name in the shared library\n"
330 " vaddr_in_file -- virtual address in the shared\n"
332 " Keys can only be used with -b option:\n"
333 " dso_from -- shared library branched from\n"
334 " dso_to -- shared library branched to\n"
335 " symbol_from -- name of function branched from\n"
336 " symbol_to -- name of function branched to\n"
337 " The default sort keys are:\n"
338 " comm,pid,tid,dso,symbol\n"
339 "--symbols symbol1;symbol2;... Report only for selected symbols.\n"
340 "--symfs <dir> Look for files with symbols relative to this directory.\n"
341 "--tids tid1,tid2,... Report only for selected tids.\n"
342 "--vmlinux <file> Parse kernel symbols from <file>.\n"
345 record_filename_("perf.data"),
346 record_file_arch_(GetBuildArch()),
347 use_branch_address_(false),
348 system_wide_collection_(false),
349 accumulate_callchain_(false),
350 print_callgraph_(false),
351 callgraph_show_callee_(false),
352 callgraph_max_stack_(UINT32_MAX),
353 callgraph_percent_limit_(0),
354 raw_period_(false) {}
356 bool Run(const std::vector<std::string>& args);
359 bool ParseOptions(const std::vector<std::string>& args);
360 bool ReadEventAttrFromRecordFile();
361 bool ReadFeaturesFromRecordFile();
362 bool ReadSampleTreeFromRecordFile();
363 bool ProcessRecord(std::unique_ptr<Record> record);
364 bool ProcessTracingData(const std::vector<char>& data);
366 void PrintReportContext(FILE* fp);
368 std::string record_filename_;
369 ArchType record_file_arch_;
370 std::unique_ptr<RecordFileReader> record_file_reader_;
371 std::vector<EventAttrWithName> event_attrs_;
372 ThreadTree thread_tree_;
373 // Create a SampleTreeBuilder and SampleTree for each event_attr.
374 std::vector<SampleTree> sample_tree_;
375 SampleTreeBuilderOptions sample_tree_builder_options_;
376 std::vector<std::unique_ptr<ReportCmdSampleTreeBuilder>> sample_tree_builder_;
378 std::unique_ptr<ReportCmdSampleTreeSorter> sample_tree_sorter_;
379 std::unique_ptr<ReportCmdSampleTreeDisplayer> sample_tree_displayer_;
380 bool use_branch_address_;
381 std::string record_cmdline_;
382 bool system_wide_collection_;
383 bool accumulate_callchain_;
384 bool print_callgraph_;
385 bool callgraph_show_callee_;
386 uint32_t callgraph_max_stack_;
387 double callgraph_percent_limit_;
390 std::string report_filename_;
393 bool ReportCommand::Run(const std::vector<std::string>& args) {
395 if (!ParseOptions(args)) {
399 // 2. Read record file and build SampleTree.
400 record_file_reader_ = RecordFileReader::CreateInstance(record_filename_);
401 if (record_file_reader_ == nullptr) {
404 if (!ReadEventAttrFromRecordFile()) {
407 // Read features first to prepare build ids used when building SampleTree.
408 if (!ReadFeaturesFromRecordFile()) {
411 ScopedCurrentArch scoped_arch(record_file_arch_);
412 if (!ReadSampleTreeFromRecordFile()) {
416 // 3. Show collected information.
417 if (!PrintReport()) {
424 bool ReportCommand::ParseOptions(const std::vector<std::string>& args) {
425 bool demangle = true;
426 bool show_ip_for_unknown_symbol = true;
427 std::string symfs_dir;
429 bool print_sample_count = false;
430 std::vector<std::string> sort_keys = {"comm", "pid", "tid", "dso", "symbol"};
432 for (size_t i = 0; i < args.size(); ++i) {
433 if (args[i] == "-b") {
434 use_branch_address_ = true;
435 } else if (args[i] == "--children") {
436 accumulate_callchain_ = true;
437 } else if (args[i] == "--comms" || args[i] == "--dsos") {
438 std::unordered_set<std::string>& filter =
439 (args[i] == "--comms" ? sample_tree_builder_options_.comm_filter
440 : sample_tree_builder_options_.dso_filter);
441 if (!NextArgumentOrError(args, &i)) {
444 std::vector<std::string> strs = android::base::Split(args[i], ",");
445 filter.insert(strs.begin(), strs.end());
447 } else if (args[i] == "-g") {
448 print_callgraph_ = true;
449 accumulate_callchain_ = true;
450 if (i + 1 < args.size() && args[i + 1][0] != '-') {
452 if (args[i] == "callee") {
453 callgraph_show_callee_ = true;
454 } else if (args[i] == "caller") {
455 callgraph_show_callee_ = false;
457 LOG(ERROR) << "Unknown argument with -g option: " << args[i];
461 } else if (args[i] == "-i") {
462 if (!NextArgumentOrError(args, &i)) {
465 record_filename_ = args[i];
467 } else if (args[i] == "--kallsyms") {
468 if (!NextArgumentOrError(args, &i)) {
471 std::string kallsyms;
472 if (!android::base::ReadFileToString(args[i], &kallsyms)) {
473 LOG(ERROR) << "Can't read kernel symbols from " << args[i];
476 Dso::SetKallsyms(kallsyms);
477 } else if (args[i] == "--max-stack") {
478 if (!NextArgumentOrError(args, &i)) {
481 if (!android::base::ParseUint(args[i].c_str(), &callgraph_max_stack_)) {
482 LOG(ERROR) << "invalid arg for --max-stack: " << args[i];
485 } else if (args[i] == "-n") {
486 print_sample_count = true;
488 } else if (args[i] == "--no-demangle") {
490 } else if (args[i] == "--no-show-ip") {
491 show_ip_for_unknown_symbol = false;
492 } else if (args[i] == "-o") {
493 if (!NextArgumentOrError(args, &i)) {
496 report_filename_ = args[i];
497 } else if (args[i] == "--percent-limit") {
498 if (!NextArgumentOrError(args, &i)) {
501 if (!android::base::ParseDouble(args[i].c_str(),
502 &callgraph_percent_limit_, 0.0)) {
503 LOG(ERROR) << "invalid arg for --percent-limit: " << args[i];
505 } else if (args[i] == "--pids" || args[i] == "--tids") {
506 const std::string& option = args[i];
507 std::unordered_set<int>& filter =
508 (option == "--pids" ? sample_tree_builder_options_.pid_filter
509 : sample_tree_builder_options_.tid_filter);
510 if (!NextArgumentOrError(args, &i)) {
513 std::vector<std::string> strs = android::base::Split(args[i], ",");
514 for (const auto& s : strs) {
516 if (!android::base::ParseInt(s.c_str(), &id, 0)) {
517 LOG(ERROR) << "invalid id in " << option << " option: " << s;
522 } else if (args[i] == "--raw-period") {
524 } else if (args[i] == "--sort") {
525 if (!NextArgumentOrError(args, &i)) {
528 sort_keys = android::base::Split(args[i], ",");
529 } else if (args[i] == "--symbols") {
530 if (!NextArgumentOrError(args, &i)) {
533 std::vector<std::string> strs = android::base::Split(args[i], ";");
534 sample_tree_builder_options_.symbol_filter.insert(strs.begin(), strs.end());
535 } else if (args[i] == "--symfs") {
536 if (!NextArgumentOrError(args, &i)) {
541 } else if (args[i] == "--vmlinux") {
542 if (!NextArgumentOrError(args, &i)) {
547 ReportUnknownOption(args, i);
552 Dso::SetDemangle(demangle);
553 if (!Dso::SetSymFsDir(symfs_dir)) {
556 if (!vmlinux.empty()) {
557 Dso::SetVmlinux(vmlinux);
560 if (show_ip_for_unknown_symbol) {
561 thread_tree_.ShowIpForUnknownSymbol();
564 SampleDisplayer<SampleEntry, SampleTree> displayer;
565 SampleComparator<SampleEntry> comparator;
567 if (accumulate_callchain_) {
569 displayer.AddDisplayFunction("Children", DisplayAccumulatedPeriod);
570 displayer.AddDisplayFunction("Self", DisplaySelfPeriod);
572 displayer.AddDisplayFunction("Children", DisplayAccumulatedOverhead);
573 displayer.AddDisplayFunction("Self", DisplaySelfOverhead);
577 displayer.AddDisplayFunction("Overhead", DisplaySelfPeriod);
579 displayer.AddDisplayFunction("Overhead", DisplaySelfOverhead);
582 if (print_sample_count) {
583 displayer.AddDisplayFunction("Sample", DisplaySampleCount);
586 for (auto& key : sort_keys) {
587 if (!use_branch_address_ &&
588 branch_sort_keys.find(key) != branch_sort_keys.end()) {
589 LOG(ERROR) << "sort key '" << key << "' can only be used with -b option.";
593 comparator.AddCompareFunction(ComparePid);
594 displayer.AddDisplayFunction("Pid", DisplayPid);
595 } else if (key == "tid") {
596 comparator.AddCompareFunction(CompareTid);
597 displayer.AddDisplayFunction("Tid", DisplayTid);
598 } else if (key == "comm") {
599 comparator.AddCompareFunction(CompareComm);
600 displayer.AddDisplayFunction("Command", DisplayComm);
601 } else if (key == "dso") {
602 comparator.AddCompareFunction(CompareDso);
603 displayer.AddDisplayFunction("Shared Object", DisplayDso);
604 } else if (key == "symbol") {
605 comparator.AddCompareFunction(CompareSymbol);
606 displayer.AddDisplayFunction("Symbol", DisplaySymbol);
607 } else if (key == "vaddr_in_file") {
608 comparator.AddCompareFunction(CompareVaddrInFile);
609 displayer.AddDisplayFunction("VaddrInFile", DisplayVaddrInFile);
610 } else if (key == "dso_from") {
611 comparator.AddCompareFunction(CompareDsoFrom);
612 displayer.AddDisplayFunction("Source Shared Object", DisplayDsoFrom);
613 } else if (key == "dso_to") {
614 comparator.AddCompareFunction(CompareDso);
615 displayer.AddDisplayFunction("Target Shared Object", DisplayDso);
616 } else if (key == "symbol_from") {
617 comparator.AddCompareFunction(CompareSymbolFrom);
618 displayer.AddDisplayFunction("Source Symbol", DisplaySymbolFrom);
619 } else if (key == "symbol_to") {
620 comparator.AddCompareFunction(CompareSymbol);
621 displayer.AddDisplayFunction("Target Symbol", DisplaySymbol);
623 LOG(ERROR) << "Unknown sort key: " << key;
627 if (print_callgraph_) {
628 bool has_symbol_key = false;
629 bool has_vaddr_in_file_key = false;
630 for (const auto& key : sort_keys) {
631 if (key == "symbol") {
632 has_symbol_key = true;
633 } else if (key == "vaddr_in_file") {
634 has_vaddr_in_file_key = true;
637 if (has_symbol_key) {
638 if (has_vaddr_in_file_key) {
639 displayer.AddExclusiveDisplayFunction(
640 ReportCmdCallgraphDisplayerWithVaddrInFile());
642 displayer.AddExclusiveDisplayFunction(ReportCmdCallgraphDisplayer(
643 callgraph_max_stack_, callgraph_percent_limit_));
648 sample_tree_builder_options_.comparator = comparator;
649 sample_tree_builder_options_.thread_tree = &thread_tree_;
651 SampleComparator<SampleEntry> sort_comparator;
652 sort_comparator.AddCompareFunction(CompareTotalPeriod);
653 sort_comparator.AddComparator(comparator);
654 sample_tree_sorter_.reset(new ReportCmdSampleTreeSorter(sort_comparator));
655 sample_tree_displayer_.reset(new ReportCmdSampleTreeDisplayer(displayer));
659 bool ReportCommand::ReadEventAttrFromRecordFile() {
660 std::vector<EventAttrWithId> attrs = record_file_reader_->AttrSection();
661 for (const auto& attr_with_id : attrs) {
662 EventAttrWithName attr;
663 attr.attr = *attr_with_id.attr;
664 attr.name = GetEventNameByAttr(attr.attr);
665 event_attrs_.push_back(attr);
667 if (use_branch_address_) {
668 bool has_branch_stack = true;
669 for (const auto& attr : event_attrs_) {
670 if ((attr.attr.sample_type & PERF_SAMPLE_BRANCH_STACK) == 0) {
671 has_branch_stack = false;
675 if (!has_branch_stack) {
676 LOG(ERROR) << record_filename_
677 << " is not recorded with branch stack sampling option.";
684 bool ReportCommand::ReadFeaturesFromRecordFile() {
685 record_file_reader_->LoadBuildIdAndFileFeatures(thread_tree_);
688 record_file_reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH);
690 record_file_arch_ = GetArchType(arch);
691 if (record_file_arch_ == ARCH_UNSUPPORTED) {
696 std::vector<std::string> cmdline = record_file_reader_->ReadCmdlineFeature();
697 if (!cmdline.empty()) {
698 record_cmdline_ = android::base::Join(cmdline, ' ');
699 // TODO: the code to detect system wide collection option is fragile, remove
700 // it once we can do cross unwinding.
701 for (size_t i = 0; i < cmdline.size(); i++) {
702 std::string& s = cmdline[i];
704 system_wide_collection_ = true;
706 } else if (s == "--call-graph" || s == "--cpu" || s == "-e" ||
707 s == "-f" || s == "-F" || s == "-j" || s == "-m" ||
708 s == "-o" || s == "-p" || s == "-t") {
710 } else if (!s.empty() && s[0] != '-') {
715 if (record_file_reader_->HasFeature(PerfFileFormat::FEAT_TRACING_DATA)) {
716 std::vector<char> tracing_data;
717 if (!record_file_reader_->ReadFeatureSection(
718 PerfFileFormat::FEAT_TRACING_DATA, &tracing_data)) {
721 if (!ProcessTracingData(tracing_data)) {
728 bool ReportCommand::ReadSampleTreeFromRecordFile() {
729 sample_tree_builder_options_.use_branch_address = use_branch_address_;
730 // Normally do strict arch check when unwinding stack. But allow unwinding
731 // 32-bit processes on 64-bit devices for system wide profiling.
732 sample_tree_builder_options_.strict_unwind_arch_check = !system_wide_collection_;
733 sample_tree_builder_options_.accumulate_callchain = accumulate_callchain_;
734 sample_tree_builder_options_.build_callchain = print_callgraph_;
735 sample_tree_builder_options_.use_caller_as_callchain_root = !callgraph_show_callee_;
737 for (size_t i = 0; i < event_attrs_.size(); ++i) {
738 sample_tree_builder_.push_back(sample_tree_builder_options_.CreateSampleTreeBuilder());
741 if (!record_file_reader_->ReadDataSection(
742 [this](std::unique_ptr<Record> record) {
743 return ProcessRecord(std::move(record));
747 for (size_t i = 0; i < sample_tree_builder_.size(); ++i) {
748 sample_tree_.push_back(sample_tree_builder_[i]->GetSampleTree());
749 sample_tree_sorter_->Sort(sample_tree_.back().samples, print_callgraph_);
754 bool ReportCommand::ProcessRecord(std::unique_ptr<Record> record) {
755 thread_tree_.Update(*record);
756 if (record->type() == PERF_RECORD_SAMPLE) {
757 size_t attr_id = record_file_reader_->GetAttrIndexOfRecord(record.get());
758 sample_tree_builder_[attr_id]->ProcessSampleRecord(
759 *static_cast<const SampleRecord*>(record.get()));
760 } else if (record->type() == PERF_RECORD_TRACING_DATA) {
761 const auto& r = *static_cast<TracingDataRecord*>(record.get());
762 if (!ProcessTracingData(std::vector<char>(r.data, r.data + r.data_size))) {
769 bool ReportCommand::ProcessTracingData(const std::vector<char>& data) {
770 Tracing tracing(data);
771 for (auto& attr : event_attrs_) {
772 if (attr.attr.type == PERF_TYPE_TRACEPOINT) {
773 uint64_t trace_event_id = attr.attr.config;
774 attr.name = tracing.GetTracingEventNameHavingId(trace_event_id);
780 bool ReportCommand::PrintReport() {
781 std::unique_ptr<FILE, decltype(&fclose)> file_handler(nullptr, fclose);
782 FILE* report_fp = stdout;
783 if (!report_filename_.empty()) {
784 report_fp = fopen(report_filename_.c_str(), "w");
785 if (report_fp == nullptr) {
786 PLOG(ERROR) << "failed to open file " << report_filename_;
789 file_handler.reset(report_fp);
791 PrintReportContext(report_fp);
792 for (size_t i = 0; i < event_attrs_.size(); ++i) {
794 fprintf(report_fp, "\n");
796 EventAttrWithName& attr = event_attrs_[i];
797 SampleTree& sample_tree = sample_tree_[i];
798 fprintf(report_fp, "Event: %s (type %u, config %llu)\n", attr.name.c_str(),
799 attr.attr.type, attr.attr.config);
800 fprintf(report_fp, "Samples: %" PRIu64 "\n", sample_tree.total_samples);
801 fprintf(report_fp, "Event count: %" PRIu64 "\n\n", sample_tree.total_period);
802 sample_tree_displayer_->DisplaySamples(report_fp, sample_tree.samples, &sample_tree);
805 if (ferror(report_fp) != 0) {
806 PLOG(ERROR) << "print report failed";
812 void ReportCommand::PrintReportContext(FILE* report_fp) {
813 if (!record_cmdline_.empty()) {
814 fprintf(report_fp, "Cmdline: %s\n", record_cmdline_.c_str());
816 fprintf(report_fp, "Arch: %s\n", GetArchString(record_file_arch_).c_str());
821 void RegisterReportCommand() {
822 RegisterCommand("report",
823 [] { return std::unique_ptr<Command>(new ReportCommand()); });