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/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>
33 
34 #include "command.h"
35 #include "dwarf_unwind.h"
36 #include "event_attr.h"
37 #include "event_type.h"
38 #include "perf_regs.h"
39 #include "record.h"
40 #include "record_file.h"
41 #include "sample_tree.h"
42 #include "thread_tree.h"
43 #include "tracing.h"
44 #include "utils.h"
45 
46 namespace {
47 
48 static std::set<std::string> branch_sort_keys = {
49     "dso_from", "dso_to", "symbol_from", "symbol_to",
50 };
51 struct BranchFromEntry {
52   const MapEntry* map;
53   const Symbol* symbol;
54   uint64_t vaddr_in_file;
55   uint64_t flags;
56 
BranchFromEntry__anon235bfe9f0111::BranchFromEntry57   BranchFromEntry()
58       : map(nullptr), symbol(nullptr), vaddr_in_file(0), flags(0) {}
59 };
60 
61 struct SampleEntry {
62   uint64_t time;
63   uint64_t period;
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;
69   const MapEntry* map;
70   const Symbol* symbol;
71   uint64_t vaddr_in_file;
72   BranchFromEntry branch_from;
73   // a callchain tree representing all callchains in the sample
74   CallChainRoot<SampleEntry> callchain;
75 
SampleEntry__anon235bfe9f0111::SampleEntry76   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)
79       : time(time),
80         period(period),
81         accumulated_period(accumulated_period),
82         sample_count(sample_count),
83         thread(thread),
84         thread_comm(thread->comm),
85         map(map),
86         symbol(symbol),
87         vaddr_in_file(vaddr_in_file) {}
88 
89   // The data member 'callchain' can only move, not copy.
90   SampleEntry(SampleEntry&&) = default;
91   SampleEntry(SampleEntry&) = delete;
92 
GetPeriod__anon235bfe9f0111::SampleEntry93   uint64_t GetPeriod() const {
94     return period;
95   }
96 };
97 
98 struct SampleTree {
99   std::vector<SampleEntry*> samples;
100   uint64_t total_samples;
101   uint64_t total_period;
102 };
103 
104 BUILD_COMPARE_VALUE_FUNCTION(CompareVaddrInFile, vaddr_in_file);
105 BUILD_DISPLAY_HEX64_FUNCTION(DisplayVaddrInFile, vaddr_in_file);
106 
107 class ReportCmdSampleTreeBuilder
108     : public SampleTreeBuilder<SampleEntry, uint64_t> {
109  public:
ReportCmdSampleTreeBuilder(SampleComparator<SampleEntry> sample_comparator,ThreadTree * thread_tree)110   ReportCmdSampleTreeBuilder(SampleComparator<SampleEntry> sample_comparator,
111                              ThreadTree* thread_tree)
112       : SampleTreeBuilder(sample_comparator),
113         thread_tree_(thread_tree),
114         total_samples_(0),
115         total_period_(0) {}
116 
SetFilters(const std::unordered_set<int> & pid_filter,const std::unordered_set<int> & tid_filter,const std::unordered_set<std::string> & comm_filter,const std::unordered_set<std::string> & dso_filter,const std::unordered_set<std::string> & symbol_filter)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;
127   }
128 
GetSampleTree() const129   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_;
134     return sample_tree;
135   }
136 
137  protected:
CreateSample(const SampleRecord & r,bool in_kernel,uint64_t * acc_info)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)));
151   }
152 
CreateBranchSample(const SampleRecord & r,const BranchStackItemType & item)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));
173   }
174 
CreateCallChainSample(const SampleEntry * sample,uint64_t ip,bool in_kernel,const std::vector<SampleEntry * > & callchain,const uint64_t & acc_info)175   SampleEntry* CreateCallChainSample(const SampleEntry* sample, uint64_t ip,
176                                      bool in_kernel,
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);
187   }
188 
GetThreadOfSample(SampleEntry * sample)189   const ThreadEntry* GetThreadOfSample(SampleEntry* sample) override {
190     return sample->thread;
191   }
192 
GetPeriodForCallChain(const uint64_t & acc_info)193   uint64_t GetPeriodForCallChain(const uint64_t& acc_info) override {
194     return acc_info;
195   }
196 
FilterSample(const SampleEntry * sample)197   bool FilterSample(const SampleEntry* sample) override {
198     if (!pid_filter_.empty() &&
199         pid_filter_.find(sample->thread->pid) == pid_filter_.end()) {
200       return false;
201     }
202     if (!tid_filter_.empty() &&
203         tid_filter_.find(sample->thread->tid) == tid_filter_.end()) {
204       return false;
205     }
206     if (!comm_filter_.empty() &&
207         comm_filter_.find(sample->thread_comm) == comm_filter_.end()) {
208       return false;
209     }
210     if (!dso_filter_.empty() &&
211         dso_filter_.find(sample->map->dso->Path()) == dso_filter_.end()) {
212       return false;
213     }
214     if (!symbol_filter_.empty() &&
215         symbol_filter_.find(sample->symbol->DemangledName()) ==
216             symbol_filter_.end()) {
217       return false;
218     }
219     return true;
220   }
221 
UpdateSummary(const SampleEntry * sample)222   void UpdateSummary(const SampleEntry* sample) override {
223     total_samples_ += sample->sample_count;
224     total_period_ += sample->period;
225   }
226 
MergeSample(SampleEntry * sample1,SampleEntry * sample2)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;
231   }
232 
233  private:
234   ThreadTree* thread_tree_;
235 
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_;
241 
242   uint64_t total_samples_;
243   uint64_t total_period_;
244 };
245 
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;
259 
CreateSampleTreeBuilder__anon235bfe9f0111::SampleTreeBuilderOptions260   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);
267     return builder;
268   }
269 };
270 
271 using ReportCmdSampleTreeSorter = SampleTreeSorter<SampleEntry>;
272 using ReportCmdSampleTreeDisplayer =
273     SampleTreeDisplayer<SampleEntry, SampleTree>;
274 
275 using ReportCmdCallgraphDisplayer =
276     CallgraphDisplayer<SampleEntry, CallChainNode<SampleEntry>>;
277 
278 class ReportCmdCallgraphDisplayerWithVaddrInFile
279     : public ReportCmdCallgraphDisplayer {
280  protected:
PrintSampleName(const SampleEntry * sample)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);
285   }
286 };
287 
288 struct EventAttrWithName {
289   perf_event_attr attr;
290   std::string name;
291 };
292 
293 class ReportCommand : public Command {
294  public:
ReportCommand()295   ReportCommand()
296       : Command(
297             "report", "report sampling information in perf.data",
298             // clang-format off
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"
302 "      option.\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"
331 "                                           library\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"
343             // clang-format on
344             ),
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) {}
355 
356   bool Run(const std::vector<std::string>& args);
357 
358  private:
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);
365   bool PrintReport();
366   void PrintReportContext(FILE* fp);
367 
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_;
377 
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_;
388   bool raw_period_;
389 
390   std::string report_filename_;
391 };
392 
Run(const std::vector<std::string> & args)393 bool ReportCommand::Run(const std::vector<std::string>& args) {
394   // 1. Parse options.
395   if (!ParseOptions(args)) {
396     return false;
397   }
398 
399   // 2. Read record file and build SampleTree.
400   record_file_reader_ = RecordFileReader::CreateInstance(record_filename_);
401   if (record_file_reader_ == nullptr) {
402     return false;
403   }
404   if (!ReadEventAttrFromRecordFile()) {
405     return false;
406   }
407   // Read features first to prepare build ids used when building SampleTree.
408   if (!ReadFeaturesFromRecordFile()) {
409     return false;
410   }
411   ScopedCurrentArch scoped_arch(record_file_arch_);
412   if (!ReadSampleTreeFromRecordFile()) {
413     return false;
414   }
415 
416   // 3. Show collected information.
417   if (!PrintReport()) {
418     return false;
419   }
420 
421   return true;
422 }
423 
ParseOptions(const std::vector<std::string> & args)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;
428   std::string vmlinux;
429   bool print_sample_count = false;
430   std::vector<std::string> sort_keys = {"comm", "pid", "tid", "dso", "symbol"};
431 
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)) {
442         return false;
443       }
444       std::vector<std::string> strs = android::base::Split(args[i], ",");
445       filter.insert(strs.begin(), strs.end());
446 
447     } else if (args[i] == "-g") {
448       print_callgraph_ = true;
449       accumulate_callchain_ = true;
450       if (i + 1 < args.size() && args[i + 1][0] != '-') {
451         ++i;
452         if (args[i] == "callee") {
453           callgraph_show_callee_ = true;
454         } else if (args[i] == "caller") {
455           callgraph_show_callee_ = false;
456         } else {
457           LOG(ERROR) << "Unknown argument with -g option: " << args[i];
458           return false;
459         }
460       }
461     } else if (args[i] == "-i") {
462       if (!NextArgumentOrError(args, &i)) {
463         return false;
464       }
465       record_filename_ = args[i];
466 
467     } else if (args[i] == "--kallsyms") {
468       if (!NextArgumentOrError(args, &i)) {
469         return false;
470       }
471       std::string kallsyms;
472       if (!android::base::ReadFileToString(args[i], &kallsyms)) {
473         LOG(ERROR) << "Can't read kernel symbols from " << args[i];
474         return false;
475       }
476       Dso::SetKallsyms(kallsyms);
477     } else if (args[i] == "--max-stack") {
478       if (!NextArgumentOrError(args, &i)) {
479         return false;
480       }
481       if (!android::base::ParseUint(args[i].c_str(), &callgraph_max_stack_)) {
482         LOG(ERROR) << "invalid arg for --max-stack: " << args[i];
483         return false;
484       }
485     } else if (args[i] == "-n") {
486       print_sample_count = true;
487 
488     } else if (args[i] == "--no-demangle") {
489       demangle = false;
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)) {
494         return false;
495       }
496       report_filename_ = args[i];
497     } else if (args[i] == "--percent-limit") {
498       if (!NextArgumentOrError(args, &i)) {
499         return false;
500       }
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];
504       }
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)) {
511         return false;
512       }
513       std::vector<std::string> strs = android::base::Split(args[i], ",");
514       for (const auto& s : strs) {
515         int id;
516         if (!android::base::ParseInt(s.c_str(), &id, 0)) {
517           LOG(ERROR) << "invalid id in " << option << " option: " << s;
518           return false;
519         }
520         filter.insert(id);
521       }
522     } else if (args[i] == "--raw-period") {
523       raw_period_ = true;
524     } else if (args[i] == "--sort") {
525       if (!NextArgumentOrError(args, &i)) {
526         return false;
527       }
528       sort_keys = android::base::Split(args[i], ",");
529     } else if (args[i] == "--symbols") {
530       if (!NextArgumentOrError(args, &i)) {
531         return false;
532       }
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)) {
537         return false;
538       }
539       symfs_dir = args[i];
540 
541     } else if (args[i] == "--vmlinux") {
542       if (!NextArgumentOrError(args, &i)) {
543         return false;
544       }
545       vmlinux = args[i];
546     } else {
547       ReportUnknownOption(args, i);
548       return false;
549     }
550   }
551 
552   Dso::SetDemangle(demangle);
553   if (!Dso::SetSymFsDir(symfs_dir)) {
554     return false;
555   }
556   if (!vmlinux.empty()) {
557     Dso::SetVmlinux(vmlinux);
558   }
559 
560   if (show_ip_for_unknown_symbol) {
561     thread_tree_.ShowIpForUnknownSymbol();
562   }
563 
564   SampleDisplayer<SampleEntry, SampleTree> displayer;
565   SampleComparator<SampleEntry> comparator;
566 
567   if (accumulate_callchain_) {
568     if (raw_period_) {
569       displayer.AddDisplayFunction("Children", DisplayAccumulatedPeriod);
570       displayer.AddDisplayFunction("Self", DisplaySelfPeriod);
571     } else {
572       displayer.AddDisplayFunction("Children", DisplayAccumulatedOverhead);
573       displayer.AddDisplayFunction("Self", DisplaySelfOverhead);
574     }
575   } else {
576     if (raw_period_) {
577       displayer.AddDisplayFunction("Overhead", DisplaySelfPeriod);
578     } else {
579       displayer.AddDisplayFunction("Overhead", DisplaySelfOverhead);
580     }
581   }
582   if (print_sample_count) {
583     displayer.AddDisplayFunction("Sample", DisplaySampleCount);
584   }
585 
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.";
590       return false;
591     }
592     if (key == "pid") {
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);
622     } else {
623       LOG(ERROR) << "Unknown sort key: " << key;
624       return false;
625     }
626   }
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;
635       }
636     }
637     if (has_symbol_key) {
638       if (has_vaddr_in_file_key) {
639         displayer.AddExclusiveDisplayFunction(
640             ReportCmdCallgraphDisplayerWithVaddrInFile());
641       } else {
642         displayer.AddExclusiveDisplayFunction(ReportCmdCallgraphDisplayer(
643             callgraph_max_stack_, callgraph_percent_limit_));
644       }
645     }
646   }
647 
648   sample_tree_builder_options_.comparator = comparator;
649   sample_tree_builder_options_.thread_tree = &thread_tree_;
650 
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));
656   return true;
657 }
658 
ReadEventAttrFromRecordFile()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);
666   }
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;
672         break;
673       }
674     }
675     if (!has_branch_stack) {
676       LOG(ERROR) << record_filename_
677                  << " is not recorded with branch stack sampling option.";
678       return false;
679     }
680   }
681   return true;
682 }
683 
ReadFeaturesFromRecordFile()684 bool ReportCommand::ReadFeaturesFromRecordFile() {
685   record_file_reader_->LoadBuildIdAndFileFeatures(thread_tree_);
686 
687   std::string arch =
688       record_file_reader_->ReadFeatureString(PerfFileFormat::FEAT_ARCH);
689   if (!arch.empty()) {
690     record_file_arch_ = GetArchType(arch);
691     if (record_file_arch_ == ARCH_UNSUPPORTED) {
692       return false;
693     }
694   }
695 
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];
703       if (s == "-a") {
704         system_wide_collection_ = true;
705         break;
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") {
709         i++;
710       } else if (!s.empty() && s[0] != '-') {
711         break;
712       }
713     }
714   }
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)) {
719       return false;
720     }
721     if (!ProcessTracingData(tracing_data)) {
722       return false;
723     }
724   }
725   return true;
726 }
727 
ReadSampleTreeFromRecordFile()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_;
736 
737   for (size_t i = 0; i < event_attrs_.size(); ++i) {
738     sample_tree_builder_.push_back(sample_tree_builder_options_.CreateSampleTreeBuilder());
739   }
740 
741   if (!record_file_reader_->ReadDataSection(
742           [this](std::unique_ptr<Record> record) {
743             return ProcessRecord(std::move(record));
744           })) {
745     return false;
746   }
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_);
750   }
751   return true;
752 }
753 
ProcessRecord(std::unique_ptr<Record> record)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))) {
763       return false;
764     }
765   }
766   return true;
767 }
768 
ProcessTracingData(const std::vector<char> & data)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);
775     }
776   }
777   return true;
778 }
779 
PrintReport()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_;
787       return false;
788     }
789     file_handler.reset(report_fp);
790   }
791   PrintReportContext(report_fp);
792   for (size_t i = 0; i < event_attrs_.size(); ++i) {
793     if (i != 0) {
794       fprintf(report_fp, "\n");
795     }
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);
803   }
804   fflush(report_fp);
805   if (ferror(report_fp) != 0) {
806     PLOG(ERROR) << "print report failed";
807     return false;
808   }
809   return true;
810 }
811 
PrintReportContext(FILE * report_fp)812 void ReportCommand::PrintReportContext(FILE* report_fp) {
813   if (!record_cmdline_.empty()) {
814     fprintf(report_fp, "Cmdline: %s\n", record_cmdline_.c_str());
815   }
816   fprintf(report_fp, "Arch: %s\n", GetArchString(record_file_arch_).c_str());
817 }
818 
819 }  // namespace
820 
RegisterReportCommand()821 void RegisterReportCommand() {
822   RegisterCommand("report",
823                   [] { return std::unique_ptr<Command>(new ReportCommand()); });
824 }
825