]> Git Repo - linux.git/blob - tools/perf/builtin-annotate.c
Merge tag 'perf-core-for-mingo-5.4-20190920-2' of git://git.kernel.org/pub/scm/linux...
[linux.git] / tools / perf / builtin-annotate.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * builtin-annotate.c
4  *
5  * Builtin annotate command: Analyze the perf.data input file,
6  * look up and read DSOs and symbol information and display
7  * a histogram of results, along various sorting keys.
8  */
9 #include "builtin.h"
10
11 #include "util/color.h"
12 #include <linux/list.h>
13 #include "util/cache.h"
14 #include <linux/rbtree.h>
15 #include <linux/zalloc.h>
16 #include "util/symbol.h"
17
18 #include "perf.h"
19 #include "util/debug.h"
20
21 #include "util/evlist.h"
22 #include "util/evsel.h"
23 #include "util/annotate.h"
24 #include "util/event.h"
25 #include <subcmd/parse-options.h>
26 #include "util/parse-events.h"
27 #include "util/sort.h"
28 #include "util/hist.h"
29 #include "util/dso.h"
30 #include "util/machine.h"
31 #include "util/map.h"
32 #include "util/session.h"
33 #include "util/tool.h"
34 #include "util/data.h"
35 #include "arch/common.h"
36 #include "util/block-range.h"
37 #include "util/map_symbol.h"
38 #include "util/branch.h"
39
40 #include <dlfcn.h>
41 #include <errno.h>
42 #include <linux/bitmap.h>
43
44 struct perf_annotate {
45         struct perf_tool tool;
46         struct perf_session *session;
47         struct annotation_options opts;
48         bool       use_tui, use_stdio, use_stdio2, use_gtk;
49         bool       skip_missing;
50         bool       has_br_stack;
51         bool       group_set;
52         const char *sym_hist_filter;
53         const char *cpu_list;
54         DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
55 };
56
57 /*
58  * Given one basic block:
59  *
60  *      from    to              branch_i
61  *      * ----> *
62  *              |
63  *              | block
64  *              v
65  *              * ----> *
66  *              from    to      branch_i+1
67  *
68  * where the horizontal are the branches and the vertical is the executed
69  * block of instructions.
70  *
71  * We count, for each 'instruction', the number of blocks that covered it as
72  * well as count the ratio each branch is taken.
73  *
74  * We can do this without knowing the actual instruction stream by keeping
75  * track of the address ranges. We break down ranges such that there is no
76  * overlap and iterate from the start until the end.
77  *
78  * @acme: once we parse the objdump output _before_ processing the samples,
79  * we can easily fold the branch.cycles IPC bits in.
80  */
81 static void process_basic_block(struct addr_map_symbol *start,
82                                 struct addr_map_symbol *end,
83                                 struct branch_flags *flags)
84 {
85         struct symbol *sym = start->sym;
86         struct annotation *notes = sym ? symbol__annotation(sym) : NULL;
87         struct block_range_iter iter;
88         struct block_range *entry;
89
90         /*
91          * Sanity; NULL isn't executable and the CPU cannot execute backwards
92          */
93         if (!start->addr || start->addr > end->addr)
94                 return;
95
96         iter = block_range__create(start->addr, end->addr);
97         if (!block_range_iter__valid(&iter))
98                 return;
99
100         /*
101          * First block in range is a branch target.
102          */
103         entry = block_range_iter(&iter);
104         assert(entry->is_target);
105         entry->entry++;
106
107         do {
108                 entry = block_range_iter(&iter);
109
110                 entry->coverage++;
111                 entry->sym = sym;
112
113                 if (notes)
114                         notes->max_coverage = max(notes->max_coverage, entry->coverage);
115
116         } while (block_range_iter__next(&iter));
117
118         /*
119          * Last block in rage is a branch.
120          */
121         entry = block_range_iter(&iter);
122         assert(entry->is_branch);
123         entry->taken++;
124         if (flags->predicted)
125                 entry->pred++;
126 }
127
128 static void process_branch_stack(struct branch_stack *bs, struct addr_location *al,
129                                  struct perf_sample *sample)
130 {
131         struct addr_map_symbol *prev = NULL;
132         struct branch_info *bi;
133         int i;
134
135         if (!bs || !bs->nr)
136                 return;
137
138         bi = sample__resolve_bstack(sample, al);
139         if (!bi)
140                 return;
141
142         for (i = bs->nr - 1; i >= 0; i--) {
143                 /*
144                  * XXX filter against symbol
145                  */
146                 if (prev)
147                         process_basic_block(prev, &bi[i].from, &bi[i].flags);
148                 prev = &bi[i].to;
149         }
150
151         free(bi);
152 }
153
154 static int hist_iter__branch_callback(struct hist_entry_iter *iter,
155                                       struct addr_location *al __maybe_unused,
156                                       bool single __maybe_unused,
157                                       void *arg __maybe_unused)
158 {
159         struct hist_entry *he = iter->he;
160         struct branch_info *bi;
161         struct perf_sample *sample = iter->sample;
162         struct evsel *evsel = iter->evsel;
163         int err;
164
165         bi = he->branch_info;
166         err = addr_map_symbol__inc_samples(&bi->from, sample, evsel);
167
168         if (err)
169                 goto out;
170
171         err = addr_map_symbol__inc_samples(&bi->to, sample, evsel);
172
173 out:
174         return err;
175 }
176
177 static int process_branch_callback(struct evsel *evsel,
178                                    struct perf_sample *sample,
179                                    struct addr_location *al __maybe_unused,
180                                    struct perf_annotate *ann,
181                                    struct machine *machine)
182 {
183         struct hist_entry_iter iter = {
184                 .evsel          = evsel,
185                 .sample         = sample,
186                 .add_entry_cb   = hist_iter__branch_callback,
187                 .hide_unresolved        = symbol_conf.hide_unresolved,
188                 .ops            = &hist_iter_branch,
189         };
190
191         struct addr_location a;
192         int ret;
193
194         if (machine__resolve(machine, &a, sample) < 0)
195                 return -1;
196
197         if (a.sym == NULL)
198                 return 0;
199
200         if (a.map != NULL)
201                 a.map->dso->hit = 1;
202
203         hist__account_cycles(sample->branch_stack, al, sample, false);
204
205         ret = hist_entry_iter__add(&iter, &a, PERF_MAX_STACK_DEPTH, ann);
206         return ret;
207 }
208
209 static bool has_annotation(struct perf_annotate *ann)
210 {
211         return ui__has_annotation() || ann->use_stdio2;
212 }
213
214 static int perf_evsel__add_sample(struct evsel *evsel,
215                                   struct perf_sample *sample,
216                                   struct addr_location *al,
217                                   struct perf_annotate *ann,
218                                   struct machine *machine)
219 {
220         struct hists *hists = evsel__hists(evsel);
221         struct hist_entry *he;
222         int ret;
223
224         if ((!ann->has_br_stack || !has_annotation(ann)) &&
225             ann->sym_hist_filter != NULL &&
226             (al->sym == NULL ||
227              strcmp(ann->sym_hist_filter, al->sym->name) != 0)) {
228                 /* We're only interested in a symbol named sym_hist_filter */
229                 /*
230                  * FIXME: why isn't this done in the symbol_filter when loading
231                  * the DSO?
232                  */
233                 if (al->sym != NULL) {
234                         rb_erase_cached(&al->sym->rb_node,
235                                  &al->map->dso->symbols);
236                         symbol__delete(al->sym);
237                         dso__reset_find_symbol_cache(al->map->dso);
238                 }
239                 return 0;
240         }
241
242         /*
243          * XXX filtered samples can still have branch entires pointing into our
244          * symbol and are missed.
245          */
246         process_branch_stack(sample->branch_stack, al, sample);
247
248         if (ann->has_br_stack && has_annotation(ann))
249                 return process_branch_callback(evsel, sample, al, ann, machine);
250
251         he = hists__add_entry(hists, al, NULL, NULL, NULL, sample, true);
252         if (he == NULL)
253                 return -ENOMEM;
254
255         ret = hist_entry__inc_addr_samples(he, sample, evsel, al->addr);
256         hists__inc_nr_samples(hists, true);
257         return ret;
258 }
259
260 static int process_sample_event(struct perf_tool *tool,
261                                 union perf_event *event,
262                                 struct perf_sample *sample,
263                                 struct evsel *evsel,
264                                 struct machine *machine)
265 {
266         struct perf_annotate *ann = container_of(tool, struct perf_annotate, tool);
267         struct addr_location al;
268         int ret = 0;
269
270         if (machine__resolve(machine, &al, sample) < 0) {
271                 pr_warning("problem processing %d event, skipping it.\n",
272                            event->header.type);
273                 return -1;
274         }
275
276         if (ann->cpu_list && !test_bit(sample->cpu, ann->cpu_bitmap))
277                 goto out_put;
278
279         if (!al.filtered &&
280             perf_evsel__add_sample(evsel, sample, &al, ann, machine)) {
281                 pr_warning("problem incrementing symbol count, "
282                            "skipping event\n");
283                 ret = -1;
284         }
285 out_put:
286         addr_location__put(&al);
287         return ret;
288 }
289
290 static int process_feature_event(struct perf_session *session,
291                                  union perf_event *event)
292 {
293         if (event->feat.feat_id < HEADER_LAST_FEATURE)
294                 return perf_event__process_feature(session, event);
295         return 0;
296 }
297
298 static int hist_entry__tty_annotate(struct hist_entry *he,
299                                     struct evsel *evsel,
300                                     struct perf_annotate *ann)
301 {
302         if (!ann->use_stdio2)
303                 return symbol__tty_annotate(he->ms.sym, he->ms.map, evsel, &ann->opts);
304
305         return symbol__tty_annotate2(he->ms.sym, he->ms.map, evsel, &ann->opts);
306 }
307
308 static void hists__find_annotations(struct hists *hists,
309                                     struct evsel *evsel,
310                                     struct perf_annotate *ann)
311 {
312         struct rb_node *nd = rb_first_cached(&hists->entries), *next;
313         int key = K_RIGHT;
314
315         while (nd) {
316                 struct hist_entry *he = rb_entry(nd, struct hist_entry, rb_node);
317                 struct annotation *notes;
318
319                 if (he->ms.sym == NULL || he->ms.map->dso->annotate_warned)
320                         goto find_next;
321
322                 if (ann->sym_hist_filter &&
323                     (strcmp(he->ms.sym->name, ann->sym_hist_filter) != 0))
324                         goto find_next;
325
326                 notes = symbol__annotation(he->ms.sym);
327                 if (notes->src == NULL) {
328 find_next:
329                         if (key == K_LEFT)
330                                 nd = rb_prev(nd);
331                         else
332                                 nd = rb_next(nd);
333                         continue;
334                 }
335
336                 if (use_browser == 2) {
337                         int ret;
338                         int (*annotate)(struct hist_entry *he,
339                                         struct evsel *evsel,
340                                         struct hist_browser_timer *hbt);
341
342                         annotate = dlsym(perf_gtk_handle,
343                                          "hist_entry__gtk_annotate");
344                         if (annotate == NULL) {
345                                 ui__error("GTK browser not found!\n");
346                                 return;
347                         }
348
349                         ret = annotate(he, evsel, NULL);
350                         if (!ret || !ann->skip_missing)
351                                 return;
352
353                         /* skip missing symbols */
354                         nd = rb_next(nd);
355                 } else if (use_browser == 1) {
356                         key = hist_entry__tui_annotate(he, evsel, NULL, &ann->opts);
357
358                         switch (key) {
359                         case -1:
360                                 if (!ann->skip_missing)
361                                         return;
362                                 /* fall through */
363                         case K_RIGHT:
364                                 next = rb_next(nd);
365                                 break;
366                         case K_LEFT:
367                                 next = rb_prev(nd);
368                                 break;
369                         default:
370                                 return;
371                         }
372
373                         if (next != NULL)
374                                 nd = next;
375                 } else {
376                         hist_entry__tty_annotate(he, evsel, ann);
377                         nd = rb_next(nd);
378                         /*
379                          * Since we have a hist_entry per IP for the same
380                          * symbol, free he->ms.sym->src to signal we already
381                          * processed this symbol.
382                          */
383                         zfree(&notes->src->cycles_hist);
384                         zfree(&notes->src);
385                 }
386         }
387 }
388
389 static int __cmd_annotate(struct perf_annotate *ann)
390 {
391         int ret;
392         struct perf_session *session = ann->session;
393         struct evsel *pos;
394         u64 total_nr_samples;
395
396         if (ann->cpu_list) {
397                 ret = perf_session__cpu_bitmap(session, ann->cpu_list,
398                                                ann->cpu_bitmap);
399                 if (ret)
400                         goto out;
401         }
402
403         if (!ann->opts.objdump_path) {
404                 ret = perf_env__lookup_objdump(&session->header.env,
405                                                &ann->opts.objdump_path);
406                 if (ret)
407                         goto out;
408         }
409
410         ret = perf_session__process_events(session);
411         if (ret)
412                 goto out;
413
414         if (dump_trace) {
415                 perf_session__fprintf_nr_events(session, stdout);
416                 perf_evlist__fprintf_nr_events(session->evlist, stdout);
417                 goto out;
418         }
419
420         if (verbose > 3)
421                 perf_session__fprintf(session, stdout);
422
423         if (verbose > 2)
424                 perf_session__fprintf_dsos(session, stdout);
425
426         total_nr_samples = 0;
427         evlist__for_each_entry(session->evlist, pos) {
428                 struct hists *hists = evsel__hists(pos);
429                 u32 nr_samples = hists->stats.nr_events[PERF_RECORD_SAMPLE];
430
431                 if (nr_samples > 0) {
432                         total_nr_samples += nr_samples;
433                         hists__collapse_resort(hists, NULL);
434                         /* Don't sort callchain */
435                         perf_evsel__reset_sample_bit(pos, CALLCHAIN);
436                         perf_evsel__output_resort(pos, NULL);
437
438                         if (symbol_conf.event_group &&
439                             !perf_evsel__is_group_leader(pos))
440                                 continue;
441
442                         hists__find_annotations(hists, pos, ann);
443                 }
444         }
445
446         if (total_nr_samples == 0) {
447                 ui__error("The %s data has no samples!\n", session->data->path);
448                 goto out;
449         }
450
451         if (use_browser == 2) {
452                 void (*show_annotations)(void);
453
454                 show_annotations = dlsym(perf_gtk_handle,
455                                          "perf_gtk__show_annotations");
456                 if (show_annotations == NULL) {
457                         ui__error("GTK browser not found!\n");
458                         goto out;
459                 }
460                 show_annotations();
461         }
462
463 out:
464         return ret;
465 }
466
467 static const char * const annotate_usage[] = {
468         "perf annotate [<options>]",
469         NULL
470 };
471
472 int cmd_annotate(int argc, const char **argv)
473 {
474         struct perf_annotate annotate = {
475                 .tool = {
476                         .sample = process_sample_event,
477                         .mmap   = perf_event__process_mmap,
478                         .mmap2  = perf_event__process_mmap2,
479                         .comm   = perf_event__process_comm,
480                         .exit   = perf_event__process_exit,
481                         .fork   = perf_event__process_fork,
482                         .namespaces = perf_event__process_namespaces,
483                         .attr   = perf_event__process_attr,
484                         .build_id = perf_event__process_build_id,
485                         .tracing_data   = perf_event__process_tracing_data,
486                         .feature        = process_feature_event,
487                         .ordered_events = true,
488                         .ordering_requires_timestamps = true,
489                 },
490                 .opts = annotation__default_options,
491         };
492         struct perf_data data = {
493                 .mode  = PERF_DATA_MODE_READ,
494         };
495         struct option options[] = {
496         OPT_STRING('i', "input", &input_name, "file",
497                     "input file name"),
498         OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
499                    "only consider symbols in these dsos"),
500         OPT_STRING('s', "symbol", &annotate.sym_hist_filter, "symbol",
501                     "symbol to annotate"),
502         OPT_BOOLEAN('f', "force", &data.force, "don't complain, do it"),
503         OPT_INCR('v', "verbose", &verbose,
504                     "be more verbose (show symbol address, etc)"),
505         OPT_BOOLEAN('q', "quiet", &quiet, "do now show any message"),
506         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
507                     "dump raw trace in ASCII"),
508         OPT_BOOLEAN(0, "gtk", &annotate.use_gtk, "Use the GTK interface"),
509         OPT_BOOLEAN(0, "tui", &annotate.use_tui, "Use the TUI interface"),
510         OPT_BOOLEAN(0, "stdio", &annotate.use_stdio, "Use the stdio interface"),
511         OPT_BOOLEAN(0, "stdio2", &annotate.use_stdio2, "Use the stdio interface"),
512         OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
513                     "don't load vmlinux even if found"),
514         OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
515                    "file", "vmlinux pathname"),
516         OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
517                     "load module symbols - WARNING: use only with -k and LIVE kernel"),
518         OPT_BOOLEAN('l', "print-line", &annotate.opts.print_lines,
519                     "print matching source lines (may be slow)"),
520         OPT_BOOLEAN('P', "full-paths", &annotate.opts.full_path,
521                     "Don't shorten the displayed pathnames"),
522         OPT_BOOLEAN(0, "skip-missing", &annotate.skip_missing,
523                     "Skip symbols that cannot be annotated"),
524         OPT_BOOLEAN_SET(0, "group", &symbol_conf.event_group,
525                         &annotate.group_set,
526                         "Show event group information together"),
527         OPT_STRING('C', "cpu", &annotate.cpu_list, "cpu", "list of cpus to profile"),
528         OPT_CALLBACK(0, "symfs", NULL, "directory",
529                      "Look for files with symbols relative to this directory",
530                      symbol__config_symfs),
531         OPT_BOOLEAN(0, "source", &annotate.opts.annotate_src,
532                     "Interleave source code with assembly code (default)"),
533         OPT_BOOLEAN(0, "asm-raw", &annotate.opts.show_asm_raw,
534                     "Display raw encoding of assembly instructions (default)"),
535         OPT_STRING('M', "disassembler-style", &annotate.opts.disassembler_style, "disassembler style",
536                    "Specify disassembler style (e.g. -M intel for intel syntax)"),
537         OPT_STRING(0, "objdump", &annotate.opts.objdump_path, "path",
538                    "objdump binary to use for disassembly and annotations"),
539         OPT_BOOLEAN(0, "group", &symbol_conf.event_group,
540                     "Show event group information together"),
541         OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
542                     "Show a column with the sum of periods"),
543         OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
544                     "Show a column with the number of samples"),
545         OPT_CALLBACK_DEFAULT(0, "stdio-color", NULL, "mode",
546                              "'always' (default), 'never' or 'auto' only applicable to --stdio mode",
547                              stdio__config_color, "always"),
548         OPT_CALLBACK(0, "percent-type", &annotate.opts, "local-period",
549                      "Set percent type local/global-period/hits",
550                      annotate_parse_percent_type),
551
552         OPT_END()
553         };
554         int ret;
555
556         set_option_flag(options, 0, "show-total-period", PARSE_OPT_EXCLUSIVE);
557         set_option_flag(options, 0, "show-nr-samples", PARSE_OPT_EXCLUSIVE);
558
559
560         ret = hists__init();
561         if (ret < 0)
562                 return ret;
563
564         argc = parse_options(argc, argv, options, annotate_usage, 0);
565         if (argc) {
566                 /*
567                  * Special case: if there's an argument left then assume that
568                  * it's a symbol filter:
569                  */
570                 if (argc > 1)
571                         usage_with_options(annotate_usage, options);
572
573                 annotate.sym_hist_filter = argv[0];
574         }
575
576         if (symbol_conf.show_nr_samples && annotate.use_gtk) {
577                 pr_err("--show-nr-samples is not available in --gtk mode at this time\n");
578                 return ret;
579         }
580
581         if (quiet)
582                 perf_quiet_option();
583
584         data.path = input_name;
585
586         annotate.session = perf_session__new(&data, false, &annotate.tool);
587         if (annotate.session == NULL)
588                 return -1;
589
590         annotate.has_br_stack = perf_header__has_feat(&annotate.session->header,
591                                                       HEADER_BRANCH_STACK);
592
593         if (annotate.group_set)
594                 perf_evlist__force_leader(annotate.session->evlist);
595
596         ret = symbol__annotation_init();
597         if (ret < 0)
598                 goto out_delete;
599
600         annotation_config__init();
601
602         symbol_conf.try_vmlinux_path = true;
603
604         ret = symbol__init(&annotate.session->header.env);
605         if (ret < 0)
606                 goto out_delete;
607
608         if (annotate.use_stdio || annotate.use_stdio2)
609                 use_browser = 0;
610         else if (annotate.use_tui)
611                 use_browser = 1;
612         else if (annotate.use_gtk)
613                 use_browser = 2;
614
615         setup_browser(true);
616
617         if ((use_browser == 1 || annotate.use_stdio2) && annotate.has_br_stack) {
618                 sort__mode = SORT_MODE__BRANCH;
619                 if (setup_sorting(annotate.session->evlist) < 0)
620                         usage_with_options(annotate_usage, options);
621         } else {
622                 if (setup_sorting(NULL) < 0)
623                         usage_with_options(annotate_usage, options);
624         }
625
626         ret = __cmd_annotate(&annotate);
627
628 out_delete:
629         /*
630          * Speed up the exit process, for large files this can
631          * take quite a while.
632          *
633          * XXX Enable this when using valgrind or if we ever
634          * librarize this command.
635          *
636          * Also experiment with obstacks to see how much speed
637          * up we'll get here.
638          *
639          * perf_session__delete(session);
640          */
641         return ret;
642 }
This page took 0.068205 seconds and 4 git commands to generate.