OSDN Git Service

Merge "simpleperf: add python report interface on linux." am: 2cb0a666a2
[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/parseint.h>
29 #include <android-base/stringprintf.h>
30 #include <android-base/strings.h>
31
32 #include "command.h"
33 #include "dwarf_unwind.h"
34 #include "environment.h"
35 #include "event_attr.h"
36 #include "event_type.h"
37 #include "perf_regs.h"
38 #include "record.h"
39 #include "record_file.h"
40 #include "sample_tree.h"
41 #include "thread_tree.h"
42 #include "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 "-n         Print the sample count for each item.\n"
281 "--no-demangle         Don't demangle symbol names.\n"
282 "--no-show-ip          Don't show vaddr in file for unknown symbols.\n"
283 "-o report_file_name   Set report file name, default is stdout.\n"
284 "--pids pid1,pid2,...  Report only for selected pids.\n"
285 "--sort key1,key2,...  Select keys used to sort and print the report. The\n"
286 "                      appearance order of keys decides the order of keys used\n"
287 "                      to sort and print the report.\n"
288 "                      Possible keys include:\n"
289 "                        pid             -- process id\n"
290 "                        tid             -- thread id\n"
291 "                        comm            -- thread name (can be changed during\n"
292 "                                           the lifetime of a thread)\n"
293 "                        dso             -- shared library\n"
294 "                        symbol          -- function name in the shared library\n"
295 "                        vaddr_in_file   -- virtual address in the shared\n"
296 "                                           library\n"
297 "                      Keys can only be used with -b option:\n"
298 "                        dso_from        -- shared library branched from\n"
299 "                        dso_to          -- shared library branched to\n"
300 "                        symbol_from     -- name of function branched from\n"
301 "                        symbol_to       -- name of function branched to\n"
302 "                      The default sort keys are:\n"
303 "                        comm,pid,tid,dso,symbol\n"
304 "--symbols symbol1;symbol2;...    Report only for selected symbols.\n"
305 "--symfs <dir>         Look for files with symbols relative to this directory.\n"
306 "--tids tid1,tid2,...  Report only for selected tids.\n"
307 "--vmlinux <file>      Parse kernel symbols from <file>.\n"
308             // clang-format on
309             ),
310         record_filename_("perf.data"),
311         record_file_arch_(GetBuildArch()),
312         use_branch_address_(false),
313         system_wide_collection_(false),
314         accumulate_callchain_(false),
315         print_callgraph_(false),
316         callgraph_show_callee_(false) {}
317
318   bool Run(const std::vector<std::string>& args);
319
320  private:
321   bool ParseOptions(const std::vector<std::string>& args);
322   bool ReadEventAttrFromRecordFile();
323   bool ReadFeaturesFromRecordFile();
324   bool ReadSampleTreeFromRecordFile();
325   bool ProcessRecord(std::unique_ptr<Record> record);
326   bool ProcessTracingData(const std::vector<char>& data);
327   bool PrintReport();
328   void PrintReportContext(FILE* fp);
329
330   std::string record_filename_;
331   ArchType record_file_arch_;
332   std::unique_ptr<RecordFileReader> record_file_reader_;
333   std::vector<EventAttrWithName> event_attrs_;
334   ThreadTree thread_tree_;
335   SampleTree sample_tree_;
336   std::unique_ptr<ReportCmdSampleTreeBuilder> sample_tree_builder_;
337   std::unique_ptr<ReportCmdSampleTreeSorter> sample_tree_sorter_;
338   std::unique_ptr<ReportCmdSampleTreeDisplayer> sample_tree_displayer_;
339   bool use_branch_address_;
340   std::string record_cmdline_;
341   bool system_wide_collection_;
342   bool accumulate_callchain_;
343   bool print_callgraph_;
344   bool callgraph_show_callee_;
345
346   std::string report_filename_;
347 };
348
349 bool ReportCommand::Run(const std::vector<std::string>& args) {
350   // 1. Parse options.
351   if (!ParseOptions(args)) {
352     return false;
353   }
354
355   // 2. Read record file and build SampleTree.
356   record_file_reader_ = RecordFileReader::CreateInstance(record_filename_);
357   if (record_file_reader_ == nullptr) {
358     return false;
359   }
360   if (!ReadEventAttrFromRecordFile()) {
361     return false;
362   }
363   // Read features first to prepare build ids used when building SampleTree.
364   if (!ReadFeaturesFromRecordFile()) {
365     return false;
366   }
367   ScopedCurrentArch scoped_arch(record_file_arch_);
368   if (!ReadSampleTreeFromRecordFile()) {
369     return false;
370   }
371
372   // 3. Show collected information.
373   if (!PrintReport()) {
374     return false;
375   }
376
377   return true;
378 }
379
380 bool ReportCommand::ParseOptions(const std::vector<std::string>& args) {
381   bool demangle = true;
382   bool show_ip_for_unknown_symbol = true;
383   std::string symfs_dir;
384   std::string vmlinux;
385   bool print_sample_count = false;
386   std::vector<std::string> sort_keys = {"comm", "pid", "tid", "dso", "symbol"};
387   std::unordered_set<std::string> comm_filter;
388   std::unordered_set<std::string> dso_filter;
389   std::unordered_set<std::string> symbol_filter;
390   std::unordered_set<int> pid_filter;
391   std::unordered_set<int> tid_filter;
392
393   for (size_t i = 0; i < args.size(); ++i) {
394     if (args[i] == "-b") {
395       use_branch_address_ = true;
396     } else if (args[i] == "--children") {
397       accumulate_callchain_ = true;
398     } else if (args[i] == "--comms" || args[i] == "--dsos") {
399       std::unordered_set<std::string>& filter =
400           (args[i] == "--comms" ? comm_filter : dso_filter);
401       if (!NextArgumentOrError(args, &i)) {
402         return false;
403       }
404       std::vector<std::string> strs = android::base::Split(args[i], ",");
405       filter.insert(strs.begin(), strs.end());
406
407     } else if (args[i] == "-g") {
408       print_callgraph_ = true;
409       accumulate_callchain_ = true;
410       if (i + 1 < args.size() && args[i + 1][0] != '-') {
411         ++i;
412         if (args[i] == "callee") {
413           callgraph_show_callee_ = true;
414         } else if (args[i] == "caller") {
415           callgraph_show_callee_ = false;
416         } else {
417           LOG(ERROR) << "Unknown argument with -g option: " << args[i];
418           return false;
419         }
420       }
421     } else if (args[i] == "-i") {
422       if (!NextArgumentOrError(args, &i)) {
423         return false;
424       }
425       record_filename_ = args[i];
426
427     } else if (args[i] == "-n") {
428       print_sample_count = true;
429
430     } else if (args[i] == "--no-demangle") {
431       demangle = false;
432     } else if (args[i] == "--no-show-ip") {
433       show_ip_for_unknown_symbol = false;
434     } else if (args[i] == "-o") {
435       if (!NextArgumentOrError(args, &i)) {
436         return false;
437       }
438       report_filename_ = args[i];
439
440     } else if (args[i] == "--pids" || args[i] == "--tids") {
441       const std::string& option = args[i];
442       std::unordered_set<int>& filter =
443           (option == "--pids" ? pid_filter : tid_filter);
444       if (!NextArgumentOrError(args, &i)) {
445         return false;
446       }
447       std::vector<std::string> strs = android::base::Split(args[i], ",");
448       for (const auto& s : strs) {
449         int id;
450         if (!android::base::ParseInt(s.c_str(), &id, 0)) {
451           LOG(ERROR) << "invalid id in " << option << " option: " << s;
452           return false;
453         }
454         filter.insert(id);
455       }
456
457     } else if (args[i] == "--sort") {
458       if (!NextArgumentOrError(args, &i)) {
459         return false;
460       }
461       sort_keys = android::base::Split(args[i], ",");
462     } else if (args[i] == "--symbols") {
463       if (!NextArgumentOrError(args, &i)) {
464         return false;
465       }
466       std::vector<std::string> strs = android::base::Split(args[i], ";");
467       symbol_filter.insert(strs.begin(), strs.end());
468     } else if (args[i] == "--symfs") {
469       if (!NextArgumentOrError(args, &i)) {
470         return false;
471       }
472       symfs_dir = args[i];
473
474     } else if (args[i] == "--vmlinux") {
475       if (!NextArgumentOrError(args, &i)) {
476         return false;
477       }
478       vmlinux = args[i];
479     } else {
480       ReportUnknownOption(args, i);
481       return false;
482     }
483   }
484
485   Dso::SetDemangle(demangle);
486   if (!Dso::SetSymFsDir(symfs_dir)) {
487     return false;
488   }
489   if (!vmlinux.empty()) {
490     Dso::SetVmlinux(vmlinux);
491   }
492
493   if (show_ip_for_unknown_symbol) {
494     thread_tree_.ShowIpForUnknownSymbol();
495   }
496
497   SampleDisplayer<SampleEntry, SampleTree> displayer;
498   SampleComparator<SampleEntry> comparator;
499
500   if (accumulate_callchain_) {
501     displayer.AddDisplayFunction("Children", DisplayAccumulatedOverhead);
502     displayer.AddDisplayFunction("Self", DisplaySelfOverhead);
503   } else {
504     displayer.AddDisplayFunction("Overhead", DisplaySelfOverhead);
505   }
506   if (print_sample_count) {
507     displayer.AddDisplayFunction("Sample", DisplaySampleCount);
508   }
509
510   for (auto& key : sort_keys) {
511     if (!use_branch_address_ &&
512         branch_sort_keys.find(key) != branch_sort_keys.end()) {
513       LOG(ERROR) << "sort key '" << key << "' can only be used with -b option.";
514       return false;
515     }
516     if (key == "pid") {
517       comparator.AddCompareFunction(ComparePid);
518       displayer.AddDisplayFunction("Pid", DisplayPid);
519     } else if (key == "tid") {
520       comparator.AddCompareFunction(CompareTid);
521       displayer.AddDisplayFunction("Tid", DisplayTid);
522     } else if (key == "comm") {
523       comparator.AddCompareFunction(CompareComm);
524       displayer.AddDisplayFunction("Command", DisplayComm);
525     } else if (key == "dso") {
526       comparator.AddCompareFunction(CompareDso);
527       displayer.AddDisplayFunction("Shared Object", DisplayDso);
528     } else if (key == "symbol") {
529       comparator.AddCompareFunction(CompareSymbol);
530       displayer.AddDisplayFunction("Symbol", DisplaySymbol);
531     } else if (key == "vaddr_in_file") {
532       comparator.AddCompareFunction(CompareVaddrInFile);
533       displayer.AddDisplayFunction("VaddrInFile", DisplayVaddrInFile);
534     } else if (key == "dso_from") {
535       comparator.AddCompareFunction(CompareDsoFrom);
536       displayer.AddDisplayFunction("Source Shared Object", DisplayDsoFrom);
537     } else if (key == "dso_to") {
538       comparator.AddCompareFunction(CompareDso);
539       displayer.AddDisplayFunction("Target Shared Object", DisplayDso);
540     } else if (key == "symbol_from") {
541       comparator.AddCompareFunction(CompareSymbolFrom);
542       displayer.AddDisplayFunction("Source Symbol", DisplaySymbolFrom);
543     } else if (key == "symbol_to") {
544       comparator.AddCompareFunction(CompareSymbol);
545       displayer.AddDisplayFunction("Target Symbol", DisplaySymbol);
546     } else {
547       LOG(ERROR) << "Unknown sort key: " << key;
548       return false;
549     }
550   }
551   if (print_callgraph_) {
552     bool has_symbol_key = false;
553     bool has_vaddr_in_file_key = false;
554     for (const auto& key : sort_keys) {
555       if (key == "symbol") {
556         has_symbol_key = true;
557       } else if (key == "vaddr_in_file") {
558         has_vaddr_in_file_key = true;
559       }
560     }
561     if (has_symbol_key) {
562       if (has_vaddr_in_file_key) {
563         displayer.AddExclusiveDisplayFunction(
564             ReportCmdCallgraphDisplayerWithVaddrInFile());
565       } else {
566         displayer.AddExclusiveDisplayFunction(ReportCmdCallgraphDisplayer());
567       }
568     }
569   }
570
571   sample_tree_builder_.reset(
572       new ReportCmdSampleTreeBuilder(comparator, &thread_tree_));
573   sample_tree_builder_->SetFilters(pid_filter, tid_filter, comm_filter,
574                                    dso_filter, symbol_filter);
575
576   SampleComparator<SampleEntry> sort_comparator;
577   sort_comparator.AddCompareFunction(CompareTotalPeriod);
578   sort_comparator.AddComparator(comparator);
579   sample_tree_sorter_.reset(new ReportCmdSampleTreeSorter(sort_comparator));
580   sample_tree_displayer_.reset(new ReportCmdSampleTreeDisplayer(displayer));
581   return true;
582 }
583
584 bool ReportCommand::ReadEventAttrFromRecordFile() {
585   std::vector<AttrWithId> attrs = record_file_reader_->AttrSection();
586   for (const auto& attr_with_id : attrs) {
587     EventAttrWithName attr;
588     attr.attr = *attr_with_id.attr;
589     attr.name = GetEventNameByAttr(attr.attr);
590     event_attrs_.push_back(attr);
591   }
592   if (use_branch_address_) {
593     bool has_branch_stack = true;
594     for (const auto& attr : event_attrs_) {
595       if ((attr.attr.sample_type & PERF_SAMPLE_BRANCH_STACK) == 0) {
596         has_branch_stack = false;
597         break;
598       }
599     }
600     if (!has_branch_stack) {
601       LOG(ERROR) << record_filename_
602                  << " is not recorded with branch stack sampling option.";
603       return false;
604     }
605   }
606   return true;
607 }
608
609 bool ReportCommand::ReadFeaturesFromRecordFile() {
610   std::vector<BuildIdRecord> records =
611       record_file_reader_->ReadBuildIdFeature();
612   std::vector<std::pair<std::string, BuildId>> build_ids;
613   for (auto& r : records) {
614     build_ids.push_back(std::make_pair(r.filename, r.build_id));
615   }
616   Dso::SetBuildIds(build_ids);
617
618   std::string arch =
619       record_file_reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH);
620   if (!arch.empty()) {
621     record_file_arch_ = GetArchType(arch);
622     if (record_file_arch_ == ARCH_UNSUPPORTED) {
623       return false;
624     }
625   }
626
627   std::vector<std::string> cmdline = record_file_reader_->ReadCmdlineFeature();
628   if (!cmdline.empty()) {
629     record_cmdline_ = android::base::Join(cmdline, ' ');
630     // TODO: the code to detect system wide collection option is fragile, remove
631     // it once we can do cross unwinding.
632     for (size_t i = 0; i < cmdline.size(); i++) {
633       std::string& s = cmdline[i];
634       if (s == "-a") {
635         system_wide_collection_ = true;
636         break;
637       } else if (s == "--call-graph" || s == "--cpu" || s == "-e" ||
638                  s == "-f" || s == "-F" || s == "-j" || s == "-m" ||
639                  s == "-o" || s == "-p" || s == "-t") {
640         i++;
641       } else if (!s.empty() && s[0] != '-') {
642         break;
643       }
644     }
645   }
646   if (record_file_reader_->HasFeature(PerfFileFormat::FEAT_TRACING_DATA)) {
647     std::vector<char> tracing_data;
648     if (!record_file_reader_->ReadFeatureSection(
649             PerfFileFormat::FEAT_TRACING_DATA, &tracing_data)) {
650       return false;
651     }
652     if (!ProcessTracingData(tracing_data)) {
653       return false;
654     }
655   }
656   return true;
657 }
658
659 bool ReportCommand::ReadSampleTreeFromRecordFile() {
660   sample_tree_builder_->SetBranchSampleOption(use_branch_address_);
661   // Normally do strict arch check when unwinding stack. But allow unwinding
662   // 32-bit processes on 64-bit devices for system wide profiling.
663   bool strict_unwind_arch_check = !system_wide_collection_;
664   sample_tree_builder_->SetCallChainSampleOptions(
665       accumulate_callchain_, print_callgraph_, !callgraph_show_callee_,
666       strict_unwind_arch_check);
667   if (!record_file_reader_->ReadDataSection(
668           [this](std::unique_ptr<Record> record) {
669             return ProcessRecord(std::move(record));
670           })) {
671     return false;
672   }
673   sample_tree_ = sample_tree_builder_->GetSampleTree();
674   sample_tree_sorter_->Sort(sample_tree_.samples, print_callgraph_);
675   return true;
676 }
677
678 bool ReportCommand::ProcessRecord(std::unique_ptr<Record> record) {
679   thread_tree_.Update(*record);
680   if (record->type() == PERF_RECORD_SAMPLE) {
681     sample_tree_builder_->ProcessSampleRecord(
682         *static_cast<const SampleRecord*>(record.get()));
683   } else if (record->type() == PERF_RECORD_TRACING_DATA) {
684     const auto& r = *static_cast<TracingDataRecord*>(record.get());
685     if (!ProcessTracingData(std::vector<char>(r.data, r.data + r.data_size))) {
686       return false;
687     }
688   }
689   return true;
690 }
691
692 bool ReportCommand::ProcessTracingData(const std::vector<char>& data) {
693   Tracing tracing(data);
694   for (auto& attr : event_attrs_) {
695     if (attr.attr.type == PERF_TYPE_TRACEPOINT) {
696       uint64_t trace_event_id = attr.attr.config;
697       attr.name = tracing.GetTracingEventNameHavingId(trace_event_id);
698     }
699   }
700   return true;
701 }
702
703 bool ReportCommand::PrintReport() {
704   std::unique_ptr<FILE, decltype(&fclose)> file_handler(nullptr, fclose);
705   FILE* report_fp = stdout;
706   if (!report_filename_.empty()) {
707     report_fp = fopen(report_filename_.c_str(), "w");
708     if (report_fp == nullptr) {
709       PLOG(ERROR) << "failed to open file " << report_filename_;
710       return false;
711     }
712     file_handler.reset(report_fp);
713   }
714   PrintReportContext(report_fp);
715   sample_tree_displayer_->DisplaySamples(report_fp, sample_tree_.samples,
716                                          &sample_tree_);
717   fflush(report_fp);
718   if (ferror(report_fp) != 0) {
719     PLOG(ERROR) << "print report failed";
720     return false;
721   }
722   return true;
723 }
724
725 void ReportCommand::PrintReportContext(FILE* report_fp) {
726   if (!record_cmdline_.empty()) {
727     fprintf(report_fp, "Cmdline: %s\n", record_cmdline_.c_str());
728   }
729   fprintf(report_fp, "Arch: %s\n", GetArchString(record_file_arch_).c_str());
730   for (const auto& attr : event_attrs_) {
731     fprintf(report_fp, "Event: %s (type %u, config %llu)\n", attr.name.c_str(),
732             attr.attr.type, attr.attr.config);
733   }
734   fprintf(report_fp, "Samples: %" PRIu64 "\n", sample_tree_.total_samples);
735   fprintf(report_fp, "Event count: %" PRIu64 "\n\n", sample_tree_.total_period);
736 }
737
738 }  // namespace
739
740 void RegisterReportCommand() {
741   RegisterCommand("report",
742                   [] { return std::unique_ptr<Command>(new ReportCommand()); });
743 }