OSDN Git Service

Merge "simpleperf: make file feature section used in more report commands."
[android-x86/system-extras.git] / simpleperf / cmd_report.cpp
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <inttypes.h>
18 #include <algorithm>
19 #include <functional>
20 #include <map>
21 #include <set>
22 #include <string>
23 #include <unordered_map>
24 #include <unordered_set>
25 #include <vector>
26
27 #include <android-base/logging.h>
28 #include <android-base/parsedouble.h>
29 #include <android-base/parseint.h>
30 #include <android-base/stringprintf.h>
31 #include <android-base/strings.h>
32
33 #include "command.h"
34 #include "dwarf_unwind.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 "tracing.h"
43 #include "utils.h"
44
45 namespace {
46
47 static std::set<std::string> branch_sort_keys = {
48     "dso_from", "dso_to", "symbol_from", "symbol_to",
49 };
50 struct BranchFromEntry {
51   const MapEntry* map;
52   const Symbol* symbol;
53   uint64_t vaddr_in_file;
54   uint64_t flags;
55
56   BranchFromEntry()
57       : map(nullptr), symbol(nullptr), vaddr_in_file(0), flags(0) {}
58 };
59
60 struct SampleEntry {
61   uint64_t time;
62   uint64_t period;
63   // accumuated when appearing in other sample's callchain
64   uint64_t accumulated_period;
65   uint64_t sample_count;
66   const ThreadEntry* thread;
67   const char* thread_comm;
68   const MapEntry* map;
69   const Symbol* symbol;
70   uint64_t vaddr_in_file;
71   BranchFromEntry branch_from;
72   // a callchain tree representing all callchains in the sample
73   CallChainRoot<SampleEntry> callchain;
74
75   SampleEntry(uint64_t time, uint64_t period, uint64_t accumulated_period,
76               uint64_t sample_count, const ThreadEntry* thread,
77               const MapEntry* map, const Symbol* symbol, uint64_t vaddr_in_file)
78       : time(time),
79         period(period),
80         accumulated_period(accumulated_period),
81         sample_count(sample_count),
82         thread(thread),
83         thread_comm(thread->comm),
84         map(map),
85         symbol(symbol),
86         vaddr_in_file(vaddr_in_file) {}
87
88   // The data member 'callchain' can only move, not copy.
89   SampleEntry(SampleEntry&&) = default;
90   SampleEntry(SampleEntry&) = delete;
91 };
92
93 struct SampleTree {
94   std::vector<SampleEntry*> samples;
95   uint64_t total_samples;
96   uint64_t total_period;
97 };
98
99 BUILD_COMPARE_VALUE_FUNCTION(CompareVaddrInFile, vaddr_in_file);
100 BUILD_DISPLAY_HEX64_FUNCTION(DisplayVaddrInFile, vaddr_in_file);
101
102 class ReportCmdSampleTreeBuilder
103     : public SampleTreeBuilder<SampleEntry, uint64_t> {
104  public:
105   ReportCmdSampleTreeBuilder(SampleComparator<SampleEntry> sample_comparator,
106                              ThreadTree* thread_tree)
107       : SampleTreeBuilder(sample_comparator),
108         thread_tree_(thread_tree),
109         total_samples_(0),
110         total_period_(0) {}
111
112   void SetFilters(const std::unordered_set<int>& pid_filter,
113                   const std::unordered_set<int>& tid_filter,
114                   const std::unordered_set<std::string>& comm_filter,
115                   const std::unordered_set<std::string>& dso_filter,
116                   const std::unordered_set<std::string>& symbol_filter) {
117     pid_filter_ = pid_filter;
118     tid_filter_ = tid_filter;
119     comm_filter_ = comm_filter;
120     dso_filter_ = dso_filter;
121     symbol_filter_ = symbol_filter;
122   }
123
124   SampleTree GetSampleTree() const {
125     SampleTree sample_tree;
126     sample_tree.samples = GetSamples();
127     sample_tree.total_samples = total_samples_;
128     sample_tree.total_period = total_period_;
129     return sample_tree;
130   }
131
132  protected:
133   SampleEntry* CreateSample(const SampleRecord& r, bool in_kernel,
134                             uint64_t* acc_info) override {
135     const ThreadEntry* thread =
136         thread_tree_->FindThreadOrNew(r.tid_data.pid, r.tid_data.tid);
137     const MapEntry* map =
138         thread_tree_->FindMap(thread, r.ip_data.ip, in_kernel);
139     uint64_t vaddr_in_file;
140     const Symbol* symbol =
141         thread_tree_->FindSymbol(map, r.ip_data.ip, &vaddr_in_file);
142     *acc_info = r.period_data.period;
143     return InsertSample(std::unique_ptr<SampleEntry>(
144         new SampleEntry(r.time_data.time, r.period_data.period, 0, 1, thread,
145                         map, symbol, vaddr_in_file)));
146   }
147
148   SampleEntry* CreateBranchSample(const SampleRecord& r,
149                                   const BranchStackItemType& item) override {
150     const ThreadEntry* thread =
151         thread_tree_->FindThreadOrNew(r.tid_data.pid, r.tid_data.tid);
152     const MapEntry* from_map = thread_tree_->FindMap(thread, item.from);
153     uint64_t from_vaddr_in_file;
154     const Symbol* from_symbol =
155         thread_tree_->FindSymbol(from_map, item.from, &from_vaddr_in_file);
156     const MapEntry* to_map = thread_tree_->FindMap(thread, item.to);
157     uint64_t to_vaddr_in_file;
158     const Symbol* to_symbol =
159         thread_tree_->FindSymbol(to_map, item.to, &to_vaddr_in_file);
160     std::unique_ptr<SampleEntry> sample(
161         new SampleEntry(r.time_data.time, r.period_data.period, 0, 1, thread,
162                         to_map, to_symbol, to_vaddr_in_file));
163     sample->branch_from.map = from_map;
164     sample->branch_from.symbol = from_symbol;
165     sample->branch_from.vaddr_in_file = from_vaddr_in_file;
166     sample->branch_from.flags = item.flags;
167     return InsertSample(std::move(sample));
168   }
169
170   SampleEntry* CreateCallChainSample(const SampleEntry* sample, uint64_t ip,
171                                      bool in_kernel,
172                                      const std::vector<SampleEntry*>& callchain,
173                                      const uint64_t& acc_info) override {
174     const ThreadEntry* thread = sample->thread;
175     const MapEntry* map = thread_tree_->FindMap(thread, ip, in_kernel);
176     uint64_t vaddr_in_file;
177     const Symbol* symbol = thread_tree_->FindSymbol(map, ip, &vaddr_in_file);
178     std::unique_ptr<SampleEntry> callchain_sample(new SampleEntry(
179         sample->time, 0, acc_info, 0, thread, map, symbol, vaddr_in_file));
180     return InsertCallChainSample(std::move(callchain_sample), callchain);
181   }
182
183   const ThreadEntry* GetThreadOfSample(SampleEntry* sample) override {
184     return sample->thread;
185   }
186
187   uint64_t GetPeriodForCallChain(const uint64_t& acc_info) override {
188     return acc_info;
189   }
190
191   bool FilterSample(const SampleEntry* sample) override {
192     if (!pid_filter_.empty() &&
193         pid_filter_.find(sample->thread->pid) == pid_filter_.end()) {
194       return false;
195     }
196     if (!tid_filter_.empty() &&
197         tid_filter_.find(sample->thread->tid) == tid_filter_.end()) {
198       return false;
199     }
200     if (!comm_filter_.empty() &&
201         comm_filter_.find(sample->thread_comm) == comm_filter_.end()) {
202       return false;
203     }
204     if (!dso_filter_.empty() &&
205         dso_filter_.find(sample->map->dso->Path()) == dso_filter_.end()) {
206       return false;
207     }
208     if (!symbol_filter_.empty() &&
209         symbol_filter_.find(sample->symbol->DemangledName()) ==
210             symbol_filter_.end()) {
211       return false;
212     }
213     return true;
214   }
215
216   void UpdateSummary(const SampleEntry* sample) override {
217     total_samples_ += sample->sample_count;
218     total_period_ += sample->period;
219   }
220
221   void MergeSample(SampleEntry* sample1, SampleEntry* sample2) override {
222     sample1->period += sample2->period;
223     sample1->accumulated_period += sample2->accumulated_period;
224     sample1->sample_count += sample2->sample_count;
225   }
226
227  private:
228   ThreadTree* thread_tree_;
229
230   std::unordered_set<int> pid_filter_;
231   std::unordered_set<int> tid_filter_;
232   std::unordered_set<std::string> comm_filter_;
233   std::unordered_set<std::string> dso_filter_;
234   std::unordered_set<std::string> symbol_filter_;
235
236   uint64_t total_samples_;
237   uint64_t total_period_;
238 };
239
240 using ReportCmdSampleTreeSorter = SampleTreeSorter<SampleEntry>;
241 using ReportCmdSampleTreeDisplayer =
242     SampleTreeDisplayer<SampleEntry, SampleTree>;
243
244 using ReportCmdCallgraphDisplayer =
245     CallgraphDisplayer<SampleEntry, CallChainNode<SampleEntry>>;
246
247 class ReportCmdCallgraphDisplayerWithVaddrInFile
248     : public ReportCmdCallgraphDisplayer {
249  protected:
250   std::string PrintSampleName(const SampleEntry* sample) override {
251     return android::base::StringPrintf("%s [+0x%" PRIx64 "]",
252                                        sample->symbol->DemangledName(),
253                                        sample->vaddr_in_file);
254   }
255 };
256
257 struct EventAttrWithName {
258   perf_event_attr attr;
259   std::string name;
260 };
261
262 class ReportCommand : public Command {
263  public:
264   ReportCommand()
265       : Command(
266             "report", "report sampling information in perf.data",
267             // clang-format off
268 "Usage: simpleperf report [options]\n"
269 "-b    Use the branch-to addresses in sampled take branches instead of the\n"
270 "      instruction addresses. Only valid for perf.data recorded with -b/-j\n"
271 "      option.\n"
272 "--children    Print the overhead accumulated by appearing in the callchain.\n"
273 "--comms comm1,comm2,...   Report only for selected comms.\n"
274 "--dsos dso1,dso2,...      Report only for selected dsos.\n"
275 "-g [callee|caller]    Print call graph. If callee mode is used, the graph\n"
276 "                      shows how functions are called from others. Otherwise,\n"
277 "                      the graph shows how functions call others.\n"
278 "                      Default is caller mode.\n"
279 "-i <file>  Specify path of record file, default is perf.data.\n"
280 "--max-stack <frames>  Set max stack frames shown when printing call graph.\n"
281 "-n         Print the sample count for each item.\n"
282 "--no-demangle         Don't demangle symbol names.\n"
283 "--no-show-ip          Don't show vaddr in file for unknown symbols.\n"
284 "-o report_file_name   Set report file name, default is stdout.\n"
285 "--percent-limit <percent>  Set min percentage shown when printing call graph.\n"
286 "--pids pid1,pid2,...  Report only for selected pids.\n"
287 "--sort key1,key2,...  Select keys used to sort and print the report. The\n"
288 "                      appearance order of keys decides the order of keys used\n"
289 "                      to sort and print the report.\n"
290 "                      Possible keys include:\n"
291 "                        pid             -- process id\n"
292 "                        tid             -- thread id\n"
293 "                        comm            -- thread name (can be changed during\n"
294 "                                           the lifetime of a thread)\n"
295 "                        dso             -- shared library\n"
296 "                        symbol          -- function name in the shared library\n"
297 "                        vaddr_in_file   -- virtual address in the shared\n"
298 "                                           library\n"
299 "                      Keys can only be used with -b option:\n"
300 "                        dso_from        -- shared library branched from\n"
301 "                        dso_to          -- shared library branched to\n"
302 "                        symbol_from     -- name of function branched from\n"
303 "                        symbol_to       -- name of function branched to\n"
304 "                      The default sort keys are:\n"
305 "                        comm,pid,tid,dso,symbol\n"
306 "--symbols symbol1;symbol2;...    Report only for selected symbols.\n"
307 "--symfs <dir>         Look for files with symbols relative to this directory.\n"
308 "--tids tid1,tid2,...  Report only for selected tids.\n"
309 "--vmlinux <file>      Parse kernel symbols from <file>.\n"
310             // clang-format on
311             ),
312         record_filename_("perf.data"),
313         record_file_arch_(GetBuildArch()),
314         use_branch_address_(false),
315         system_wide_collection_(false),
316         accumulate_callchain_(false),
317         print_callgraph_(false),
318         callgraph_show_callee_(false),
319         callgraph_max_stack_(UINT32_MAX),
320         callgraph_percent_limit_(0) {}
321
322   bool Run(const std::vector<std::string>& args);
323
324  private:
325   bool ParseOptions(const std::vector<std::string>& args);
326   bool ReadEventAttrFromRecordFile();
327   bool ReadFeaturesFromRecordFile();
328   bool ReadSampleTreeFromRecordFile();
329   bool ProcessRecord(std::unique_ptr<Record> record);
330   bool ProcessTracingData(const std::vector<char>& data);
331   bool PrintReport();
332   void PrintReportContext(FILE* fp);
333
334   std::string record_filename_;
335   ArchType record_file_arch_;
336   std::unique_ptr<RecordFileReader> record_file_reader_;
337   std::vector<EventAttrWithName> event_attrs_;
338   ThreadTree thread_tree_;
339   SampleTree sample_tree_;
340   std::unique_ptr<ReportCmdSampleTreeBuilder> sample_tree_builder_;
341   std::unique_ptr<ReportCmdSampleTreeSorter> sample_tree_sorter_;
342   std::unique_ptr<ReportCmdSampleTreeDisplayer> sample_tree_displayer_;
343   bool use_branch_address_;
344   std::string record_cmdline_;
345   bool system_wide_collection_;
346   bool accumulate_callchain_;
347   bool print_callgraph_;
348   bool callgraph_show_callee_;
349   uint32_t callgraph_max_stack_;
350   double callgraph_percent_limit_;
351
352   std::string report_filename_;
353 };
354
355 bool ReportCommand::Run(const std::vector<std::string>& args) {
356   // 1. Parse options.
357   if (!ParseOptions(args)) {
358     return false;
359   }
360
361   // 2. Read record file and build SampleTree.
362   record_file_reader_ = RecordFileReader::CreateInstance(record_filename_);
363   if (record_file_reader_ == nullptr) {
364     return false;
365   }
366   if (!ReadEventAttrFromRecordFile()) {
367     return false;
368   }
369   // Read features first to prepare build ids used when building SampleTree.
370   if (!ReadFeaturesFromRecordFile()) {
371     return false;
372   }
373   ScopedCurrentArch scoped_arch(record_file_arch_);
374   if (!ReadSampleTreeFromRecordFile()) {
375     return false;
376   }
377
378   // 3. Show collected information.
379   if (!PrintReport()) {
380     return false;
381   }
382
383   return true;
384 }
385
386 bool ReportCommand::ParseOptions(const std::vector<std::string>& args) {
387   bool demangle = true;
388   bool show_ip_for_unknown_symbol = true;
389   std::string symfs_dir;
390   std::string vmlinux;
391   bool print_sample_count = false;
392   std::vector<std::string> sort_keys = {"comm", "pid", "tid", "dso", "symbol"};
393   std::unordered_set<std::string> comm_filter;
394   std::unordered_set<std::string> dso_filter;
395   std::unordered_set<std::string> symbol_filter;
396   std::unordered_set<int> pid_filter;
397   std::unordered_set<int> tid_filter;
398
399   for (size_t i = 0; i < args.size(); ++i) {
400     if (args[i] == "-b") {
401       use_branch_address_ = true;
402     } else if (args[i] == "--children") {
403       accumulate_callchain_ = true;
404     } else if (args[i] == "--comms" || args[i] == "--dsos") {
405       std::unordered_set<std::string>& filter =
406           (args[i] == "--comms" ? comm_filter : dso_filter);
407       if (!NextArgumentOrError(args, &i)) {
408         return false;
409       }
410       std::vector<std::string> strs = android::base::Split(args[i], ",");
411       filter.insert(strs.begin(), strs.end());
412
413     } else if (args[i] == "-g") {
414       print_callgraph_ = true;
415       accumulate_callchain_ = true;
416       if (i + 1 < args.size() && args[i + 1][0] != '-') {
417         ++i;
418         if (args[i] == "callee") {
419           callgraph_show_callee_ = true;
420         } else if (args[i] == "caller") {
421           callgraph_show_callee_ = false;
422         } else {
423           LOG(ERROR) << "Unknown argument with -g option: " << args[i];
424           return false;
425         }
426       }
427     } else if (args[i] == "-i") {
428       if (!NextArgumentOrError(args, &i)) {
429         return false;
430       }
431       record_filename_ = args[i];
432
433     } else if (args[i] == "--max-stack") {
434       if (!NextArgumentOrError(args, &i)) {
435         return false;
436       }
437       if (!android::base::ParseUint(args[i].c_str(), &callgraph_max_stack_)) {
438         LOG(ERROR) << "invalid arg for --max-stack: " << args[i];
439         return false;
440       }
441     } else if (args[i] == "-n") {
442       print_sample_count = true;
443
444     } else if (args[i] == "--no-demangle") {
445       demangle = false;
446     } else if (args[i] == "--no-show-ip") {
447       show_ip_for_unknown_symbol = false;
448     } else if (args[i] == "-o") {
449       if (!NextArgumentOrError(args, &i)) {
450         return false;
451       }
452       report_filename_ = args[i];
453     } else if (args[i] == "--percent-limit") {
454       if (!NextArgumentOrError(args, &i)) {
455         return false;
456       }
457       if (!android::base::ParseDouble(args[i].c_str(),
458                                       &callgraph_percent_limit_, 0.0)) {
459         LOG(ERROR) << "invalid arg for --percent-limit: " << args[i];
460       }
461     } else if (args[i] == "--pids" || args[i] == "--tids") {
462       const std::string& option = args[i];
463       std::unordered_set<int>& filter =
464           (option == "--pids" ? pid_filter : tid_filter);
465       if (!NextArgumentOrError(args, &i)) {
466         return false;
467       }
468       std::vector<std::string> strs = android::base::Split(args[i], ",");
469       for (const auto& s : strs) {
470         int id;
471         if (!android::base::ParseInt(s.c_str(), &id, 0)) {
472           LOG(ERROR) << "invalid id in " << option << " option: " << s;
473           return false;
474         }
475         filter.insert(id);
476       }
477
478     } else if (args[i] == "--sort") {
479       if (!NextArgumentOrError(args, &i)) {
480         return false;
481       }
482       sort_keys = android::base::Split(args[i], ",");
483     } else if (args[i] == "--symbols") {
484       if (!NextArgumentOrError(args, &i)) {
485         return false;
486       }
487       std::vector<std::string> strs = android::base::Split(args[i], ";");
488       symbol_filter.insert(strs.begin(), strs.end());
489     } else if (args[i] == "--symfs") {
490       if (!NextArgumentOrError(args, &i)) {
491         return false;
492       }
493       symfs_dir = args[i];
494
495     } else if (args[i] == "--vmlinux") {
496       if (!NextArgumentOrError(args, &i)) {
497         return false;
498       }
499       vmlinux = args[i];
500     } else {
501       ReportUnknownOption(args, i);
502       return false;
503     }
504   }
505
506   Dso::SetDemangle(demangle);
507   if (!Dso::SetSymFsDir(symfs_dir)) {
508     return false;
509   }
510   if (!vmlinux.empty()) {
511     Dso::SetVmlinux(vmlinux);
512   }
513
514   if (show_ip_for_unknown_symbol) {
515     thread_tree_.ShowIpForUnknownSymbol();
516   }
517
518   SampleDisplayer<SampleEntry, SampleTree> displayer;
519   SampleComparator<SampleEntry> comparator;
520
521   if (accumulate_callchain_) {
522     displayer.AddDisplayFunction("Children", DisplayAccumulatedOverhead);
523     displayer.AddDisplayFunction("Self", DisplaySelfOverhead);
524   } else {
525     displayer.AddDisplayFunction("Overhead", DisplaySelfOverhead);
526   }
527   if (print_sample_count) {
528     displayer.AddDisplayFunction("Sample", DisplaySampleCount);
529   }
530
531   for (auto& key : sort_keys) {
532     if (!use_branch_address_ &&
533         branch_sort_keys.find(key) != branch_sort_keys.end()) {
534       LOG(ERROR) << "sort key '" << key << "' can only be used with -b option.";
535       return false;
536     }
537     if (key == "pid") {
538       comparator.AddCompareFunction(ComparePid);
539       displayer.AddDisplayFunction("Pid", DisplayPid);
540     } else if (key == "tid") {
541       comparator.AddCompareFunction(CompareTid);
542       displayer.AddDisplayFunction("Tid", DisplayTid);
543     } else if (key == "comm") {
544       comparator.AddCompareFunction(CompareComm);
545       displayer.AddDisplayFunction("Command", DisplayComm);
546     } else if (key == "dso") {
547       comparator.AddCompareFunction(CompareDso);
548       displayer.AddDisplayFunction("Shared Object", DisplayDso);
549     } else if (key == "symbol") {
550       comparator.AddCompareFunction(CompareSymbol);
551       displayer.AddDisplayFunction("Symbol", DisplaySymbol);
552     } else if (key == "vaddr_in_file") {
553       comparator.AddCompareFunction(CompareVaddrInFile);
554       displayer.AddDisplayFunction("VaddrInFile", DisplayVaddrInFile);
555     } else if (key == "dso_from") {
556       comparator.AddCompareFunction(CompareDsoFrom);
557       displayer.AddDisplayFunction("Source Shared Object", DisplayDsoFrom);
558     } else if (key == "dso_to") {
559       comparator.AddCompareFunction(CompareDso);
560       displayer.AddDisplayFunction("Target Shared Object", DisplayDso);
561     } else if (key == "symbol_from") {
562       comparator.AddCompareFunction(CompareSymbolFrom);
563       displayer.AddDisplayFunction("Source Symbol", DisplaySymbolFrom);
564     } else if (key == "symbol_to") {
565       comparator.AddCompareFunction(CompareSymbol);
566       displayer.AddDisplayFunction("Target Symbol", DisplaySymbol);
567     } else {
568       LOG(ERROR) << "Unknown sort key: " << key;
569       return false;
570     }
571   }
572   if (print_callgraph_) {
573     bool has_symbol_key = false;
574     bool has_vaddr_in_file_key = false;
575     for (const auto& key : sort_keys) {
576       if (key == "symbol") {
577         has_symbol_key = true;
578       } else if (key == "vaddr_in_file") {
579         has_vaddr_in_file_key = true;
580       }
581     }
582     if (has_symbol_key) {
583       if (has_vaddr_in_file_key) {
584         displayer.AddExclusiveDisplayFunction(
585             ReportCmdCallgraphDisplayerWithVaddrInFile());
586       } else {
587         displayer.AddExclusiveDisplayFunction(ReportCmdCallgraphDisplayer(
588             callgraph_max_stack_, callgraph_percent_limit_));
589       }
590     }
591   }
592
593   sample_tree_builder_.reset(
594       new ReportCmdSampleTreeBuilder(comparator, &thread_tree_));
595   sample_tree_builder_->SetFilters(pid_filter, tid_filter, comm_filter,
596                                    dso_filter, symbol_filter);
597
598   SampleComparator<SampleEntry> sort_comparator;
599   sort_comparator.AddCompareFunction(CompareTotalPeriod);
600   sort_comparator.AddComparator(comparator);
601   sample_tree_sorter_.reset(new ReportCmdSampleTreeSorter(sort_comparator));
602   sample_tree_displayer_.reset(new ReportCmdSampleTreeDisplayer(displayer));
603   return true;
604 }
605
606 bool ReportCommand::ReadEventAttrFromRecordFile() {
607   std::vector<EventAttrWithId> attrs = record_file_reader_->AttrSection();
608   for (const auto& attr_with_id : attrs) {
609     EventAttrWithName attr;
610     attr.attr = *attr_with_id.attr;
611     attr.name = GetEventNameByAttr(attr.attr);
612     event_attrs_.push_back(attr);
613   }
614   if (use_branch_address_) {
615     bool has_branch_stack = true;
616     for (const auto& attr : event_attrs_) {
617       if ((attr.attr.sample_type & PERF_SAMPLE_BRANCH_STACK) == 0) {
618         has_branch_stack = false;
619         break;
620       }
621     }
622     if (!has_branch_stack) {
623       LOG(ERROR) << record_filename_
624                  << " is not recorded with branch stack sampling option.";
625       return false;
626     }
627   }
628   return true;
629 }
630
631 bool ReportCommand::ReadFeaturesFromRecordFile() {
632   record_file_reader_->LoadBuildIdAndFileFeatures(thread_tree_);
633
634   std::string arch =
635       record_file_reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH);
636   if (!arch.empty()) {
637     record_file_arch_ = GetArchType(arch);
638     if (record_file_arch_ == ARCH_UNSUPPORTED) {
639       return false;
640     }
641   }
642
643   std::vector<std::string> cmdline = record_file_reader_->ReadCmdlineFeature();
644   if (!cmdline.empty()) {
645     record_cmdline_ = android::base::Join(cmdline, ' ');
646     // TODO: the code to detect system wide collection option is fragile, remove
647     // it once we can do cross unwinding.
648     for (size_t i = 0; i < cmdline.size(); i++) {
649       std::string& s = cmdline[i];
650       if (s == "-a") {
651         system_wide_collection_ = true;
652         break;
653       } else if (s == "--call-graph" || s == "--cpu" || s == "-e" ||
654                  s == "-f" || s == "-F" || s == "-j" || s == "-m" ||
655                  s == "-o" || s == "-p" || s == "-t") {
656         i++;
657       } else if (!s.empty() && s[0] != '-') {
658         break;
659       }
660     }
661   }
662   if (record_file_reader_->HasFeature(PerfFileFormat::FEAT_TRACING_DATA)) {
663     std::vector<char> tracing_data;
664     if (!record_file_reader_->ReadFeatureSection(
665             PerfFileFormat::FEAT_TRACING_DATA, &tracing_data)) {
666       return false;
667     }
668     if (!ProcessTracingData(tracing_data)) {
669       return false;
670     }
671   }
672   return true;
673 }
674
675 bool ReportCommand::ReadSampleTreeFromRecordFile() {
676   sample_tree_builder_->SetBranchSampleOption(use_branch_address_);
677   // Normally do strict arch check when unwinding stack. But allow unwinding
678   // 32-bit processes on 64-bit devices for system wide profiling.
679   bool strict_unwind_arch_check = !system_wide_collection_;
680   sample_tree_builder_->SetCallChainSampleOptions(
681       accumulate_callchain_, print_callgraph_, !callgraph_show_callee_,
682       strict_unwind_arch_check);
683   if (!record_file_reader_->ReadDataSection(
684           [this](std::unique_ptr<Record> record) {
685             return ProcessRecord(std::move(record));
686           })) {
687     return false;
688   }
689   sample_tree_ = sample_tree_builder_->GetSampleTree();
690   sample_tree_sorter_->Sort(sample_tree_.samples, print_callgraph_);
691   return true;
692 }
693
694 bool ReportCommand::ProcessRecord(std::unique_ptr<Record> record) {
695   thread_tree_.Update(*record);
696   if (record->type() == PERF_RECORD_SAMPLE) {
697     sample_tree_builder_->ProcessSampleRecord(
698         *static_cast<const SampleRecord*>(record.get()));
699   } else if (record->type() == PERF_RECORD_TRACING_DATA) {
700     const auto& r = *static_cast<TracingDataRecord*>(record.get());
701     if (!ProcessTracingData(std::vector<char>(r.data, r.data + r.data_size))) {
702       return false;
703     }
704   }
705   return true;
706 }
707
708 bool ReportCommand::ProcessTracingData(const std::vector<char>& data) {
709   Tracing tracing(data);
710   for (auto& attr : event_attrs_) {
711     if (attr.attr.type == PERF_TYPE_TRACEPOINT) {
712       uint64_t trace_event_id = attr.attr.config;
713       attr.name = tracing.GetTracingEventNameHavingId(trace_event_id);
714     }
715   }
716   return true;
717 }
718
719 bool ReportCommand::PrintReport() {
720   std::unique_ptr<FILE, decltype(&fclose)> file_handler(nullptr, fclose);
721   FILE* report_fp = stdout;
722   if (!report_filename_.empty()) {
723     report_fp = fopen(report_filename_.c_str(), "w");
724     if (report_fp == nullptr) {
725       PLOG(ERROR) << "failed to open file " << report_filename_;
726       return false;
727     }
728     file_handler.reset(report_fp);
729   }
730   PrintReportContext(report_fp);
731   sample_tree_displayer_->DisplaySamples(report_fp, sample_tree_.samples,
732                                          &sample_tree_);
733   fflush(report_fp);
734   if (ferror(report_fp) != 0) {
735     PLOG(ERROR) << "print report failed";
736     return false;
737   }
738   return true;
739 }
740
741 void ReportCommand::PrintReportContext(FILE* report_fp) {
742   if (!record_cmdline_.empty()) {
743     fprintf(report_fp, "Cmdline: %s\n", record_cmdline_.c_str());
744   }
745   fprintf(report_fp, "Arch: %s\n", GetArchString(record_file_arch_).c_str());
746   for (const auto& attr : event_attrs_) {
747     fprintf(report_fp, "Event: %s (type %u, config %llu)\n", attr.name.c_str(),
748             attr.attr.type, attr.attr.config);
749   }
750   fprintf(report_fp, "Samples: %" PRIu64 "\n", sample_tree_.total_samples);
751   fprintf(report_fp, "Event count: %" PRIu64 "\n\n", sample_tree_.total_period);
752 }
753
754 }  // namespace
755
756 void RegisterReportCommand() {
757   RegisterCommand("report",
758                   [] { return std::unique_ptr<Command>(new ReportCommand()); });
759 }