1 // SPDX-License-Identifier: GPL-2.0
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.
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"
18 #include "util/debug.h"
20 #include "util/evlist.h"
21 #include "util/evsel.h"
22 #include "util/annotate.h"
23 #include "util/annotate-data.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"
30 #include "util/machine.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 #include "util/util.h"
43 #include <linux/bitmap.h>
44 #include <linux/err.h>
46 struct perf_annotate {
47 struct perf_tool tool;
48 struct perf_session *session;
49 #ifdef HAVE_SLANG_SUPPORT
52 bool use_stdio, use_stdio2;
53 #ifdef HAVE_GTK2_SUPPORT
61 const char *sym_hist_filter;
63 const char *target_data_type;
64 DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
68 * Given one basic block:
78 * where the horizontal are the branches and the vertical is the executed
79 * block of instructions.
81 * We count, for each 'instruction', the number of blocks that covered it as
82 * well as count the ratio each branch is taken.
84 * We can do this without knowing the actual instruction stream by keeping
85 * track of the address ranges. We break down ranges such that there is no
86 * overlap and iterate from the start until the end.
88 * @acme: once we parse the objdump output _before_ processing the samples,
89 * we can easily fold the branch.cycles IPC bits in.
91 static void process_basic_block(struct addr_map_symbol *start,
92 struct addr_map_symbol *end,
93 struct branch_flags *flags)
95 struct symbol *sym = start->ms.sym;
96 struct annotation *notes = sym ? symbol__annotation(sym) : NULL;
97 struct block_range_iter iter;
98 struct block_range *entry;
99 struct annotated_branch *branch;
102 * Sanity; NULL isn't executable and the CPU cannot execute backwards
104 if (!start->addr || start->addr > end->addr)
107 iter = block_range__create(start->addr, end->addr);
108 if (!block_range_iter__valid(&iter))
111 branch = annotation__get_branch(notes);
114 * First block in range is a branch target.
116 entry = block_range_iter(&iter);
117 assert(entry->is_target);
121 entry = block_range_iter(&iter);
127 branch->max_coverage = max(branch->max_coverage, entry->coverage);
129 } while (block_range_iter__next(&iter));
132 * Last block in rage is a branch.
134 entry = block_range_iter(&iter);
135 assert(entry->is_branch);
137 if (flags->predicted)
141 static void process_branch_stack(struct branch_stack *bs, struct addr_location *al,
142 struct perf_sample *sample)
144 struct addr_map_symbol *prev = NULL;
145 struct branch_info *bi;
151 bi = sample__resolve_bstack(sample, al);
155 for (i = bs->nr - 1; i >= 0; i--) {
157 * XXX filter against symbol
160 process_basic_block(prev, &bi[i].from, &bi[i].flags);
167 static int hist_iter__branch_callback(struct hist_entry_iter *iter,
168 struct addr_location *al __maybe_unused,
169 bool single __maybe_unused,
170 void *arg __maybe_unused)
172 struct hist_entry *he = iter->he;
173 struct branch_info *bi;
174 struct perf_sample *sample = iter->sample;
175 struct evsel *evsel = iter->evsel;
178 bi = he->branch_info;
179 err = addr_map_symbol__inc_samples(&bi->from, sample, evsel);
184 err = addr_map_symbol__inc_samples(&bi->to, sample, evsel);
190 static int process_branch_callback(struct evsel *evsel,
191 struct perf_sample *sample,
192 struct addr_location *al,
193 struct perf_annotate *ann,
194 struct machine *machine)
196 struct hist_entry_iter iter = {
199 .add_entry_cb = hist_iter__branch_callback,
200 .hide_unresolved = symbol_conf.hide_unresolved,
201 .ops = &hist_iter_branch,
203 struct addr_location a;
206 addr_location__init(&a);
207 if (machine__resolve(machine, &a, sample) < 0) {
218 map__dso(a.map)->hit = 1;
220 hist__account_cycles(sample->branch_stack, al, sample, false, NULL);
222 ret = hist_entry_iter__add(&iter, &a, PERF_MAX_STACK_DEPTH, ann);
224 addr_location__exit(&a);
228 static bool has_annotation(struct perf_annotate *ann)
230 return ui__has_annotation() || ann->use_stdio2;
233 static int evsel__add_sample(struct evsel *evsel, struct perf_sample *sample,
234 struct addr_location *al, struct perf_annotate *ann,
235 struct machine *machine)
237 struct hists *hists = evsel__hists(evsel);
238 struct hist_entry *he;
241 if ((!ann->has_br_stack || !has_annotation(ann)) &&
242 ann->sym_hist_filter != NULL &&
244 strcmp(ann->sym_hist_filter, al->sym->name) != 0)) {
245 /* We're only interested in a symbol named sym_hist_filter */
247 * FIXME: why isn't this done in the symbol_filter when loading
250 if (al->sym != NULL) {
251 struct dso *dso = map__dso(al->map);
253 rb_erase_cached(&al->sym->rb_node, &dso->symbols);
254 symbol__delete(al->sym);
255 dso__reset_find_symbol_cache(dso);
261 * XXX filtered samples can still have branch entries pointing into our
262 * symbol and are missed.
264 process_branch_stack(sample->branch_stack, al, sample);
266 if (ann->has_br_stack && has_annotation(ann))
267 return process_branch_callback(evsel, sample, al, ann, machine);
269 he = hists__add_entry(hists, al, NULL, NULL, NULL, NULL, sample, true);
273 ret = hist_entry__inc_addr_samples(he, sample, evsel, al->addr);
274 hists__inc_nr_samples(hists, true);
278 static int process_sample_event(struct perf_tool *tool,
279 union perf_event *event,
280 struct perf_sample *sample,
282 struct machine *machine)
284 struct perf_annotate *ann = container_of(tool, struct perf_annotate, tool);
285 struct addr_location al;
288 addr_location__init(&al);
289 if (machine__resolve(machine, &al, sample) < 0) {
290 pr_warning("problem processing %d event, skipping it.\n",
296 if (ann->cpu_list && !test_bit(sample->cpu, ann->cpu_bitmap))
300 evsel__add_sample(evsel, sample, &al, ann, machine)) {
301 pr_warning("problem incrementing symbol count, "
306 addr_location__exit(&al);
310 static int process_feature_event(struct perf_session *session,
311 union perf_event *event)
313 if (event->feat.feat_id < HEADER_LAST_FEATURE)
314 return perf_event__process_feature(session, event);
318 static int hist_entry__tty_annotate(struct hist_entry *he,
320 struct perf_annotate *ann)
322 if (!ann->use_stdio2)
323 return symbol__tty_annotate(&he->ms, evsel);
325 return symbol__tty_annotate2(&he->ms, evsel);
328 static void print_annotated_data_type(struct annotated_data_type *mem_type,
329 struct annotated_member *member,
330 struct evsel *evsel, int indent)
332 struct annotated_member *child;
333 struct type_hist *h = mem_type->histograms[evsel->core.idx];
336 for (i = 0; i < member->size; i++)
337 samples += h->addr[member->offset + i].nr_samples;
339 printf(" %10d %10d %10d %*s%s\t%s",
340 samples, member->offset, member->size, indent, "", member->type_name,
341 member->var_name ?: "");
343 if (!list_empty(&member->children))
346 list_for_each_entry(child, &member->children, node)
347 print_annotated_data_type(mem_type, child, evsel, indent + 4);
349 if (!list_empty(&member->children))
350 printf("%*s}", 35 + indent, "");
354 static void hists__find_annotations(struct hists *hists,
356 struct perf_annotate *ann)
358 struct rb_node *nd = rb_first_cached(&hists->entries), *next;
362 struct hist_entry *he = rb_entry(nd, struct hist_entry, rb_node);
363 struct annotation *notes;
365 if (he->ms.sym == NULL || map__dso(he->ms.map)->annotate_warned)
368 if (ann->sym_hist_filter &&
369 (strcmp(he->ms.sym->name, ann->sym_hist_filter) != 0))
372 if (ann->min_percent) {
374 u64 total = hists__total_period(hists);
377 percent = 100.0 * he->stat.period / total;
379 if (percent < ann->min_percent)
383 notes = symbol__annotation(he->ms.sym);
384 if (notes->src == NULL) {
386 if (key == K_LEFT || key == '<')
393 if (ann->data_type) {
394 struct dso *dso = map__dso(he->ms.map);
396 /* skip unknown type */
397 if (he->mem_type->histograms == NULL)
400 if (ann->target_data_type) {
401 const char *type_name = he->mem_type->self.type_name;
403 /* skip 'struct ' prefix in the type name */
404 if (strncmp(ann->target_data_type, "struct ", 7) &&
405 !strncmp(type_name, "struct ", 7))
408 /* skip 'union ' prefix in the type name */
409 if (strncmp(ann->target_data_type, "union ", 6) &&
410 !strncmp(type_name, "union ", 6))
413 if (strcmp(ann->target_data_type, type_name))
417 printf("Annotate type: '%s' in %s (%d samples):\n",
418 he->mem_type->self.type_name, dso->name, he->stat.nr_events);
419 printf("============================================================================\n");
420 printf(" %10s %10s %10s %s\n", "samples", "offset", "size", "field");
422 print_annotated_data_type(he->mem_type, &he->mem_type->self, evsel, 0);
427 if (use_browser == 2) {
429 int (*annotate)(struct hist_entry *he,
431 struct hist_browser_timer *hbt);
433 annotate = dlsym(perf_gtk_handle,
434 "hist_entry__gtk_annotate");
435 if (annotate == NULL) {
436 ui__error("GTK browser not found!\n");
440 ret = annotate(he, evsel, NULL);
441 if (!ret || !ann->skip_missing)
444 /* skip missing symbols */
446 } else if (use_browser == 1) {
447 key = hist_entry__tui_annotate(he, evsel, NULL);
451 if (!ann->skip_missing)
469 hist_entry__tty_annotate(he, evsel, ann);
475 static int __cmd_annotate(struct perf_annotate *ann)
478 struct perf_session *session = ann->session;
480 u64 total_nr_samples;
483 ret = perf_session__cpu_bitmap(session, ann->cpu_list,
489 if (!annotate_opts.objdump_path) {
490 ret = perf_env__lookup_objdump(&session->header.env,
491 &annotate_opts.objdump_path);
496 ret = perf_session__process_events(session);
501 perf_session__fprintf_nr_events(session, stdout, false);
502 evlist__fprintf_nr_events(session->evlist, stdout, false);
507 perf_session__fprintf(session, stdout);
510 perf_session__fprintf_dsos(session, stdout);
512 total_nr_samples = 0;
513 evlist__for_each_entry(session->evlist, pos) {
514 struct hists *hists = evsel__hists(pos);
515 u32 nr_samples = hists->stats.nr_samples;
517 if (nr_samples > 0) {
518 total_nr_samples += nr_samples;
519 hists__collapse_resort(hists, NULL);
520 /* Don't sort callchain */
521 evsel__reset_sample_bit(pos, CALLCHAIN);
522 evsel__output_resort(pos, NULL);
524 if (symbol_conf.event_group && !evsel__is_group_leader(pos))
527 hists__find_annotations(hists, pos, ann);
531 if (total_nr_samples == 0) {
532 ui__error("The %s data has no samples!\n", session->data->path);
536 if (use_browser == 2) {
537 void (*show_annotations)(void);
539 show_annotations = dlsym(perf_gtk_handle,
540 "perf_gtk__show_annotations");
541 if (show_annotations == NULL) {
542 ui__error("GTK browser not found!\n");
552 static int parse_percent_limit(const struct option *opt, const char *str,
553 int unset __maybe_unused)
555 struct perf_annotate *ann = opt->value;
556 double pcnt = strtof(str, NULL);
558 ann->min_percent = pcnt;
562 static int parse_data_type(const struct option *opt, const char *str, int unset)
564 struct perf_annotate *ann = opt->value;
566 ann->data_type = !unset;
568 ann->target_data_type = strdup(str);
573 static const char * const annotate_usage[] = {
574 "perf annotate [<options>]",
578 int cmd_annotate(int argc, const char **argv)
580 struct perf_annotate annotate = {
582 .sample = process_sample_event,
583 .mmap = perf_event__process_mmap,
584 .mmap2 = perf_event__process_mmap2,
585 .comm = perf_event__process_comm,
586 .exit = perf_event__process_exit,
587 .fork = perf_event__process_fork,
588 .namespaces = perf_event__process_namespaces,
589 .attr = perf_event__process_attr,
590 .build_id = perf_event__process_build_id,
591 #ifdef HAVE_LIBTRACEEVENT
592 .tracing_data = perf_event__process_tracing_data,
594 .id_index = perf_event__process_id_index,
595 .auxtrace_info = perf_event__process_auxtrace_info,
596 .auxtrace = perf_event__process_auxtrace,
597 .feature = process_feature_event,
598 .ordered_events = true,
599 .ordering_requires_timestamps = true,
602 struct perf_data data = {
603 .mode = PERF_DATA_MODE_READ,
605 struct itrace_synth_opts itrace_synth_opts = {
608 const char *disassembler_style = NULL, *objdump_path = NULL, *addr2line_path = NULL;
609 struct option options[] = {
610 OPT_STRING('i', "input", &input_name, "file",
612 OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
613 "only consider symbols in these dsos"),
614 OPT_STRING('s', "symbol", &annotate.sym_hist_filter, "symbol",
615 "symbol to annotate"),
616 OPT_BOOLEAN('f', "force", &data.force, "don't complain, do it"),
617 OPT_INCR('v', "verbose", &verbose,
618 "be more verbose (show symbol address, etc)"),
619 OPT_BOOLEAN('q', "quiet", &quiet, "do now show any warnings or messages"),
620 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
621 "dump raw trace in ASCII"),
622 #ifdef HAVE_GTK2_SUPPORT
623 OPT_BOOLEAN(0, "gtk", &annotate.use_gtk, "Use the GTK interface"),
625 #ifdef HAVE_SLANG_SUPPORT
626 OPT_BOOLEAN(0, "tui", &annotate.use_tui, "Use the TUI interface"),
628 OPT_BOOLEAN(0, "stdio", &annotate.use_stdio, "Use the stdio interface"),
629 OPT_BOOLEAN(0, "stdio2", &annotate.use_stdio2, "Use the stdio interface"),
630 OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
631 "don't load vmlinux even if found"),
632 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
633 "file", "vmlinux pathname"),
634 OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
635 "load module symbols - WARNING: use only with -k and LIVE kernel"),
636 OPT_BOOLEAN('l', "print-line", &annotate_opts.print_lines,
637 "print matching source lines (may be slow)"),
638 OPT_BOOLEAN('P', "full-paths", &annotate_opts.full_path,
639 "Don't shorten the displayed pathnames"),
640 OPT_BOOLEAN(0, "skip-missing", &annotate.skip_missing,
641 "Skip symbols that cannot be annotated"),
642 OPT_BOOLEAN_SET(0, "group", &symbol_conf.event_group,
644 "Show event group information together"),
645 OPT_STRING('C', "cpu", &annotate.cpu_list, "cpu", "list of cpus to profile"),
646 OPT_CALLBACK(0, "symfs", NULL, "directory",
647 "Look for files with symbols relative to this directory",
648 symbol__config_symfs),
649 OPT_BOOLEAN(0, "source", &annotate_opts.annotate_src,
650 "Interleave source code with assembly code (default)"),
651 OPT_BOOLEAN(0, "asm-raw", &annotate_opts.show_asm_raw,
652 "Display raw encoding of assembly instructions (default)"),
653 OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
654 "Specify disassembler style (e.g. -M intel for intel syntax)"),
655 OPT_STRING(0, "prefix", &annotate_opts.prefix, "prefix",
656 "Add prefix to source file path names in programs (with --prefix-strip)"),
657 OPT_STRING(0, "prefix-strip", &annotate_opts.prefix_strip, "N",
658 "Strip first N entries of source file path name in programs (with --prefix)"),
659 OPT_STRING(0, "objdump", &objdump_path, "path",
660 "objdump binary to use for disassembly and annotations"),
661 OPT_STRING(0, "addr2line", &addr2line_path, "path",
662 "addr2line binary to use for line numbers"),
663 OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
664 "Enable symbol demangling"),
665 OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
666 "Enable kernel symbol demangling"),
667 OPT_BOOLEAN(0, "group", &symbol_conf.event_group,
668 "Show event group information together"),
669 OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
670 "Show a column with the sum of periods"),
671 OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
672 "Show a column with the number of samples"),
673 OPT_CALLBACK_DEFAULT(0, "stdio-color", NULL, "mode",
674 "'always' (default), 'never' or 'auto' only applicable to --stdio mode",
675 stdio__config_color, "always"),
676 OPT_CALLBACK(0, "percent-type", &annotate_opts, "local-period",
677 "Set percent type local/global-period/hits",
678 annotate_parse_percent_type),
679 OPT_CALLBACK(0, "percent-limit", &annotate, "percent",
680 "Don't show entries under that percent", parse_percent_limit),
681 OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
682 "Instruction Tracing options\n" ITRACE_HELP,
683 itrace_parse_synth_opts),
684 OPT_CALLBACK_OPTARG(0, "data-type", &annotate, NULL, "name",
685 "Show data type annotate for the memory accesses",
692 set_option_flag(options, 0, "show-total-period", PARSE_OPT_EXCLUSIVE);
693 set_option_flag(options, 0, "show-nr-samples", PARSE_OPT_EXCLUSIVE);
695 annotation_options__init();
701 annotation_config__init();
703 argc = parse_options(argc, argv, options, annotate_usage, 0);
706 * Special case: if there's an argument left then assume that
707 * it's a symbol filter:
710 usage_with_options(annotate_usage, options);
712 annotate.sym_hist_filter = argv[0];
715 if (disassembler_style) {
716 annotate_opts.disassembler_style = strdup(disassembler_style);
717 if (!annotate_opts.disassembler_style)
721 annotate_opts.objdump_path = strdup(objdump_path);
722 if (!annotate_opts.objdump_path)
725 if (addr2line_path) {
726 symbol_conf.addr2line_path = strdup(addr2line_path);
727 if (!symbol_conf.addr2line_path)
731 if (annotate_check_args() < 0)
734 #ifdef HAVE_GTK2_SUPPORT
735 if (symbol_conf.show_nr_samples && annotate.use_gtk) {
736 pr_err("--show-nr-samples is not available in --gtk mode at this time\n");
741 #ifndef HAVE_DWARF_GETLOCATIONS_SUPPORT
742 if (annotate.data_type) {
743 pr_err("Error: Data type profiling is disabled due to missing DWARF support\n");
748 ret = symbol__validate_sym_arguments();
755 data.path = input_name;
757 annotate.session = perf_session__new(&data, &annotate.tool);
758 if (IS_ERR(annotate.session))
759 return PTR_ERR(annotate.session);
761 annotate.session->itrace_synth_opts = &itrace_synth_opts;
763 annotate.has_br_stack = perf_header__has_feat(&annotate.session->header,
764 HEADER_BRANCH_STACK);
766 if (annotate.group_set)
767 evlist__force_leader(annotate.session->evlist);
769 ret = symbol__annotation_init();
773 symbol_conf.try_vmlinux_path = true;
775 ret = symbol__init(&annotate.session->header.env);
779 if (annotate.use_stdio || annotate.use_stdio2)
781 #ifdef HAVE_SLANG_SUPPORT
782 else if (annotate.use_tui)
785 #ifdef HAVE_GTK2_SUPPORT
786 else if (annotate.use_gtk)
790 /* FIXME: only support stdio for now */
791 if (annotate.data_type) {
793 annotate_opts.annotate_src = false;
794 symbol_conf.annotate_data_member = true;
795 symbol_conf.annotate_data_sample = true;
801 * Events of different processes may correspond to the same
802 * symbol, we do not care about the processes in annotate,
803 * set sort order to avoid repeated output.
805 if (annotate.data_type)
806 sort_order = "dso,type";
808 sort_order = "dso,symbol";
811 * Set SORT_MODE__BRANCH so that annotate display IPC/Cycle
812 * if branch info is in perf data in TUI mode.
814 if ((use_browser == 1 || annotate.use_stdio2) && annotate.has_br_stack)
815 sort__mode = SORT_MODE__BRANCH;
817 if (setup_sorting(NULL) < 0)
818 usage_with_options(annotate_usage, options);
820 ret = __cmd_annotate(&annotate);
824 * Speed up the exit process by only deleting for debug builds. For
825 * large files this can save time.
828 perf_session__delete(annotate.session);
830 annotation_options__exit();