xref: /linux/tools/perf/builtin-annotate.c (revision 035efae7df32bc2800bbe525b28f5be5dbcaf701)
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 <errno.h>
10 #include <inttypes.h>
11 #include <stdbool.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 
16 #include <dlfcn.h>
17 #include <linux/bitmap.h>
18 #include <linux/err.h>
19 #include <linux/list.h>
20 #include <linux/rbtree.h>
21 
22 #include <subcmd/parse-options.h>
23 
24 #include "arch/common.h"
25 #include "builtin.h"
26 #include "perf.h"
27 #include "ui/keysyms.h"
28 #include "ui/progress.h"
29 #include "ui/ui.h"
30 #include "util/annotate-data.h"
31 #include "util/annotate.h"
32 #include "util/block-range.h"
33 #include "util/branch.h"
34 #include "util/data.h"
35 #include "util/debug.h"
36 #include "util/dso.h"
37 #include "util/event.h"
38 #include "util/evlist.h"
39 #include "util/evsel.h"
40 #include "util/hist.h"
41 #include "util/machine.h"
42 #include "util/map.h"
43 #include "util/map_symbol.h"
44 #include "util/session.h"
45 #include "util/sort.h"
46 #include "util/symbol.h"
47 #include "util/tool.h"
48 #include "util/util.h"
49 
50 #ifndef HAVE_SLANG_SUPPORT
51 #undef K_LEFT
52 #define K_LEFT  -1000
53 #undef K_RIGHT
54 #define K_RIGHT -2000
55 #endif
56 
57 struct perf_annotate {
58 	struct perf_tool tool;
59 	struct perf_session *session;
60 #ifdef HAVE_SLANG_SUPPORT
61 	bool	   use_tui;
62 #endif
63 	bool	   use_stdio, use_stdio2;
64 #ifdef HAVE_GTK4_SUPPORT
65 	bool	   use_gtk;
66 #endif
67 	bool	   skip_missing;
68 	bool	   has_br_stack;
69 	bool	   group_set;
70 	bool	   data_type;
71 	bool	   type_stat;
72 	bool	   insn_stat;
73 	float	   min_percent;
74 	const char *sym_hist_filter;
75 	const char *cpu_list;
76 	const char *target_data_type;
77 	DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
78 };
79 
80 /*
81  * Given one basic block:
82  *
83  *	from	to		branch_i
84  *	* ----> *
85  *		|
86  *		| block
87  *		v
88  *		* ----> *
89  *		from	to	branch_i+1
90  *
91  * where the horizontal are the branches and the vertical is the executed
92  * block of instructions.
93  *
94  * We count, for each 'instruction', the number of blocks that covered it as
95  * well as count the ratio each branch is taken.
96  *
97  * We can do this without knowing the actual instruction stream by keeping
98  * track of the address ranges. We break down ranges such that there is no
99  * overlap and iterate from the start until the end.
100  *
101  * @acme: once we parse the objdump output _before_ processing the samples,
102  * we can easily fold the branch.cycles IPC bits in.
103  */
104 static void process_basic_block(struct addr_map_symbol *start,
105 				struct addr_map_symbol *end,
106 				struct branch_flags *flags)
107 {
108 	struct symbol *sym = start->ms.sym;
109 	struct annotation *notes = sym ? symbol__annotation(sym) : NULL;
110 	struct block_range_iter iter;
111 	struct block_range *entry;
112 	struct annotated_branch *branch;
113 
114 	/*
115 	 * Sanity; NULL isn't executable and the CPU cannot execute backwards
116 	 */
117 	if (!start->addr || start->addr > end->addr)
118 		return;
119 
120 	iter = block_range__create(start->addr, end->addr);
121 	if (!block_range_iter__valid(&iter))
122 		return;
123 
124 	branch = annotation__get_branch(notes);
125 
126 	/*
127 	 * First block in range is a branch target.
128 	 */
129 	entry = block_range_iter(&iter);
130 	assert(entry->is_target);
131 	entry->entry++;
132 
133 	do {
134 		entry = block_range_iter(&iter);
135 
136 		entry->coverage++;
137 		entry->sym = sym;
138 
139 		if (branch)
140 			branch->max_coverage = max(branch->max_coverage, entry->coverage);
141 
142 	} while (block_range_iter__next(&iter));
143 
144 	/*
145 	 * Last block in rage is a branch.
146 	 */
147 	entry = block_range_iter(&iter);
148 	assert(entry->is_branch);
149 	entry->taken++;
150 	if (flags->predicted)
151 		entry->pred++;
152 }
153 
154 static void process_branch_stack(struct branch_stack *bs, struct addr_location *al,
155 				 struct perf_sample *sample)
156 {
157 	struct addr_map_symbol *prev = NULL;
158 	struct branch_info *bi;
159 	int i;
160 
161 	if (!bs || !bs->nr)
162 		return;
163 
164 	bi = sample__resolve_bstack(sample, al);
165 	if (!bi)
166 		return;
167 
168 	for (i = bs->nr - 1; i >= 0; i--) {
169 		/*
170 		 * XXX filter against symbol
171 		 */
172 		if (prev)
173 			process_basic_block(prev, &bi[i].from, &bi[i].flags);
174 		prev = &bi[i].to;
175 	}
176 
177 	free(bi);
178 }
179 
180 static int hist_iter__branch_callback(struct hist_entry_iter *iter,
181 				      struct addr_location *al __maybe_unused,
182 				      bool single __maybe_unused,
183 				      void *arg __maybe_unused)
184 {
185 	struct hist_entry *he = iter->he;
186 	struct branch_info *bi;
187 	struct perf_sample *sample = iter->sample;
188 	int err;
189 
190 	bi = he->branch_info;
191 	err = addr_map_symbol__inc_samples(&bi->from, sample);
192 
193 	if (err)
194 		goto out;
195 
196 	err = addr_map_symbol__inc_samples(&bi->to, sample);
197 
198 out:
199 	return err;
200 }
201 
202 static int process_branch_callback(struct perf_sample *sample,
203 				   struct addr_location *al,
204 				   struct perf_annotate *ann,
205 				   struct machine *machine)
206 {
207 	struct hist_entry_iter iter = {
208 		.sample		= sample,
209 		.add_entry_cb	= hist_iter__branch_callback,
210 		.hide_unresolved	= symbol_conf.hide_unresolved,
211 		.ops		= &hist_iter_branch,
212 	};
213 	struct addr_location a;
214 	int ret;
215 
216 	addr_location__init(&a);
217 	if (machine__resolve(machine, &a, sample) < 0) {
218 		ret = -1;
219 		goto out;
220 	}
221 
222 	if (a.sym == NULL) {
223 		ret = 0;
224 		goto out;
225 	}
226 
227 	if (a.map != NULL)
228 		dso__set_hit(map__dso(a.map));
229 
230 	hist__account_cycles(sample->branch_stack, al, sample, /*nonany_branch_mode=*/false,
231 			     /*total_cycles=*/NULL);
232 
233 	ret = hist_entry_iter__add(&iter, &a, PERF_MAX_STACK_DEPTH, ann);
234 out:
235 	addr_location__exit(&a);
236 	return ret;
237 }
238 
239 static bool has_annotation(struct perf_annotate *ann)
240 {
241 	return ui__has_annotation() || ann->use_stdio2;
242 }
243 
244 static int add_sample(struct perf_sample *sample,
245 		      struct addr_location *al, struct perf_annotate *ann,
246 		      struct machine *machine)
247 {
248 	struct hists *hists = evsel__hists(sample->evsel);
249 	struct hist_entry *he;
250 	int ret;
251 
252 	if ((!ann->has_br_stack || !has_annotation(ann)) &&
253 	    ann->sym_hist_filter != NULL &&
254 	    (al->sym == NULL ||
255 	     strcmp(ann->sym_hist_filter, al->sym->name) != 0)) {
256 		/* We're only interested in a symbol named sym_hist_filter */
257 		/*
258 		 * FIXME: why isn't this done in the symbol_filter when loading
259 		 * the DSO?
260 		 */
261 		if (al->sym != NULL) {
262 			struct dso *dso = map__dso(al->map);
263 
264 			rb_erase_cached(&al->sym->rb_node, dso__symbols(dso));
265 			symbol__delete(al->sym);
266 			dso__reset_find_symbol_cache(dso);
267 		}
268 		return 0;
269 	}
270 
271 	/*
272 	 * XXX filtered samples can still have branch entries pointing into our
273 	 * symbol and are missed.
274 	 */
275 	process_branch_stack(sample->branch_stack, al, sample);
276 
277 	if (ann->has_br_stack && has_annotation(ann))
278 		return process_branch_callback(sample, al, ann, machine);
279 
280 	he = hists__add_entry(hists, al, NULL, NULL, NULL, NULL, sample, true);
281 	if (he == NULL)
282 		return -ENOMEM;
283 
284 	ret = hist_entry__inc_addr_samples(he, sample, al->addr);
285 	hists__inc_nr_samples(hists, true);
286 	return ret;
287 }
288 
289 static int process_sample_event(const struct perf_tool *tool,
290 				union perf_event *event,
291 				struct perf_sample *sample,
292 				struct machine *machine)
293 {
294 	struct perf_annotate *ann = container_of(tool, struct perf_annotate, tool);
295 	struct addr_location al;
296 	int ret = 0;
297 
298 	addr_location__init(&al);
299 	if (machine__resolve(machine, &al, sample) < 0) {
300 		pr_warning("problem processing %s (%u) event at offset %#" PRIx64 ", skipping it.\n",
301 			   perf_event__name(event->header.type), event->header.type,
302 			   sample->file_offset);
303 		ret = -1;
304 		goto out_put;
305 	}
306 
307 	if (ann->cpu_list && (sample->cpu >= MAX_NR_CPUS ||
308 			     !test_bit(sample->cpu, ann->cpu_bitmap)))
309 		goto out_put;
310 
311 	if (!al.filtered &&
312 	    add_sample(sample, &al, ann, machine)) {
313 		pr_warning("problem incrementing symbol count, "
314 			   "skipping event\n");
315 		ret = -1;
316 	}
317 out_put:
318 	addr_location__exit(&al);
319 	return ret;
320 }
321 
322 static int hist_entry__stdio_annotate(struct hist_entry *he,
323 				    struct evsel *evsel,
324 				    struct perf_annotate *ann)
325 {
326 	if (ann->use_stdio2)
327 		return hist_entry__tty_annotate2(he, evsel);
328 
329 	return hist_entry__tty_annotate(he, evsel);
330 }
331 
332 static void print_annotate_data_stat(struct annotated_data_stat *s)
333 {
334 #define PRINT_STAT(fld) if (s->fld) printf("%10d : %s\n", s->fld, #fld)
335 
336 	int bad = s->no_sym +
337 			s->no_insn +
338 			s->no_insn_ops +
339 			s->no_mem_ops +
340 			s->no_reg +
341 			s->no_dbginfo +
342 			s->no_cuinfo +
343 			s->no_var +
344 			s->no_typeinfo +
345 			s->invalid_size +
346 			s->bad_offset;
347 	int ok = s->total - bad;
348 
349 	printf("Annotate data type stats:\n");
350 	printf("total %d, ok %d (%.1f%%), bad %d (%.1f%%)\n",
351 		s->total, ok, 100.0 * ok / (s->total ?: 1), bad, 100.0 * bad / (s->total ?: 1));
352 	printf("-----------------------------------------------------------\n");
353 	PRINT_STAT(no_sym);
354 	PRINT_STAT(no_insn);
355 	PRINT_STAT(no_insn_ops);
356 	PRINT_STAT(no_mem_ops);
357 	PRINT_STAT(no_reg);
358 	PRINT_STAT(no_dbginfo);
359 	PRINT_STAT(no_cuinfo);
360 	PRINT_STAT(no_var);
361 	PRINT_STAT(no_typeinfo);
362 	PRINT_STAT(invalid_size);
363 	PRINT_STAT(bad_offset);
364 	PRINT_STAT(insn_track);
365 	printf("\n");
366 
367 #undef PRINT_STAT
368 }
369 
370 static void print_annotate_item_stat(struct list_head *head, const char *title)
371 {
372 	struct annotated_item_stat *istat, *pos, *iter;
373 	int total_good, total_bad, total;
374 	int sum1, sum2;
375 	LIST_HEAD(tmp);
376 
377 	/* sort the list by count */
378 	list_splice_init(head, &tmp);
379 	total_good = total_bad = 0;
380 
381 	list_for_each_entry_safe(istat, pos, &tmp, list) {
382 		total_good += istat->good;
383 		total_bad += istat->bad;
384 		sum1 = istat->good + istat->bad;
385 
386 		list_for_each_entry(iter, head, list) {
387 			sum2 = iter->good + iter->bad;
388 			if (sum1 > sum2)
389 				break;
390 		}
391 		list_move_tail(&istat->list, &iter->list);
392 	}
393 	total = total_good + total_bad;
394 
395 	printf("Annotate %s stats\n", title);
396 	printf("total %d, ok %d (%.1f%%), bad %d (%.1f%%)\n\n", total,
397 	       total_good, 100.0 * total_good / (total ?: 1),
398 	       total_bad, 100.0 * total_bad / (total ?: 1));
399 	printf("  %-20s: %5s %5s\n", "Name/opcode", "Good", "Bad");
400 	printf("-----------------------------------------------------------\n");
401 	list_for_each_entry(istat, head, list)
402 		printf("  %-20s: %5d %5d\n", istat->name, istat->good, istat->bad);
403 	printf("\n");
404 }
405 
406 static void hists__find_annotations(struct hists *hists,
407 				    struct evsel *evsel,
408 				    struct perf_annotate *ann)
409 {
410 	struct rb_node *nd = rb_first_cached(&hists->entries), *next;
411 	int key = K_RIGHT;
412 
413 	if (ann->type_stat)
414 		print_annotate_data_stat(&ann_data_stat);
415 	if (ann->insn_stat)
416 		print_annotate_item_stat(&ann_insn_stat, "Instruction");
417 
418 	while (nd) {
419 		struct hist_entry *he = rb_entry(nd, struct hist_entry, rb_node);
420 		struct annotation *notes;
421 
422 		if (he->ms.sym == NULL || dso__annotate_warned(map__dso(he->ms.map)))
423 			goto find_next;
424 
425 		if (ann->sym_hist_filter &&
426 		    (strcmp(he->ms.sym->name, ann->sym_hist_filter) != 0))
427 			goto find_next;
428 
429 		if (ann->min_percent) {
430 			float percent = 0;
431 			u64 total = hists__total_period(hists);
432 
433 			if (total)
434 				percent = 100.0 * he->stat.period / total;
435 
436 			if (percent < ann->min_percent)
437 				goto find_next;
438 		}
439 
440 		notes = symbol__annotation(he->ms.sym);
441 		if (notes->src == NULL) {
442 find_next:
443 			if (key == K_LEFT || key == '<')
444 				nd = rb_prev(nd);
445 			else
446 				nd = rb_next(nd);
447 			continue;
448 		}
449 
450 		if (ann->data_type) {
451 			/* skip unknown type */
452 			if (he->mem_type->histograms == NULL)
453 				goto find_next;
454 
455 			if (ann->target_data_type) {
456 				const char *type_name = he->mem_type->self.type_name;
457 
458 				/* skip 'struct ' prefix in the type name */
459 				if (strncmp(ann->target_data_type, "struct ", 7) &&
460 				    !strncmp(type_name, "struct ", 7))
461 					type_name += 7;
462 
463 				/* skip 'union ' prefix in the type name */
464 				if (strncmp(ann->target_data_type, "union ", 6) &&
465 				    !strncmp(type_name, "union ", 6))
466 					type_name += 6;
467 
468 				if (strcmp(ann->target_data_type, type_name))
469 					goto find_next;
470 			}
471 
472 			if (use_browser == 1)
473 				key = hist_entry__annotate_data_tui(he, evsel, NULL);
474 			else
475 				key = hist_entry__annotate_data_tty(he, evsel);
476 
477 			switch (key) {
478 			case -1:
479 				if (!ann->skip_missing)
480 					return;
481 				/* fall through */
482 			case K_RIGHT:
483 			case '>':
484 				next = rb_next(nd);
485 				break;
486 			case K_LEFT:
487 			case '<':
488 				next = rb_prev(nd);
489 				break;
490 			default:
491 				return;
492 			}
493 
494 			if (use_browser == 0 || next != NULL)
495 				nd = next;
496 
497 			continue;
498 		}
499 
500 		if (use_browser == 2) {
501 			int ret;
502 			int (*annotate)(struct hist_entry *he,
503 					struct evsel *evsel,
504 					struct hist_browser_timer *hbt);
505 
506 			annotate = dlsym(perf_gtk_handle,
507 					 "hist_entry__gtk_annotate");
508 			if (annotate == NULL) {
509 				ui__error("GTK browser not found!\n");
510 				return;
511 			}
512 
513 			ret = annotate(he, evsel, NULL);
514 			if (!ret || !ann->skip_missing)
515 				return;
516 
517 			/* skip missing symbols */
518 			nd = rb_next(nd);
519 		} else if (use_browser == 1) {
520 			key = hist_entry__tui_annotate(he, evsel, NULL, NO_ADDR);
521 
522 			switch (key) {
523 			case -1:
524 				if (!ann->skip_missing)
525 					return;
526 				/* fall through */
527 			case K_RIGHT:
528 			case '>':
529 				next = rb_next(nd);
530 				break;
531 			case K_LEFT:
532 			case '<':
533 				next = rb_prev(nd);
534 				break;
535 			default:
536 				return;
537 			}
538 
539 			if (next != NULL)
540 				nd = next;
541 		} else {
542 			hist_entry__stdio_annotate(he, evsel, ann);
543 			nd = rb_next(nd);
544 		}
545 	}
546 }
547 
548 static int __cmd_annotate(struct perf_annotate *ann)
549 {
550 	int ret;
551 	struct perf_session *session = ann->session;
552 	struct evsel *pos;
553 	u64 total_nr_samples;
554 
555 	if (ann->cpu_list) {
556 		ret = perf_session__cpu_bitmap(session, ann->cpu_list,
557 					       ann->cpu_bitmap);
558 		if (ret)
559 			goto out;
560 	}
561 
562 	if (!annotate_opts.objdump_path) {
563 		ret = perf_env__lookup_objdump(perf_session__env(session),
564 					       &annotate_opts.objdump_path);
565 		if (ret)
566 			goto out;
567 	}
568 
569 	ret = perf_session__process_events(session);
570 	if (ret)
571 		goto out;
572 
573 	if ((use_browser == 1 || ann->use_stdio2) && ann->has_br_stack)
574 		if (evlist__nr_br_cntr(session->evlist) > 0)
575 			annotate_opts.show_br_cntr = true;
576 
577 	if (dump_trace) {
578 		perf_session__fprintf_nr_events(session, stdout);
579 		evlist__fprintf_nr_events(session->evlist, stdout);
580 		goto out;
581 	}
582 
583 	if (verbose > 3)
584 		perf_session__fprintf(session, stdout);
585 
586 	if (verbose > 2)
587 		perf_session__fprintf_dsos(session, stdout);
588 
589 	total_nr_samples = 0;
590 	evlist__for_each_entry(session->evlist, pos) {
591 		struct hists *hists = evsel__hists(pos);
592 		u32 nr_samples = hists->stats.nr_samples;
593 		struct ui_progress prog;
594 
595 		if (nr_samples > 0) {
596 			total_nr_samples += nr_samples;
597 
598 			ui_progress__init(&prog, nr_samples,
599 					  "Merging related events...");
600 			hists__collapse_resort(hists, &prog);
601 			ui_progress__finish();
602 
603 			/* Don't sort callchain */
604 			evsel__reset_sample_bit(pos, CALLCHAIN);
605 
606 			ui_progress__init(&prog, nr_samples,
607 					  "Sorting events for output...");
608 			evsel__output_resort(pos, &prog);
609 			ui_progress__finish();
610 
611 			/*
612 			 * An event group needs to display other events too.
613 			 * Let's delay printing until other events are processed.
614 			 */
615 			if (symbol_conf.event_group) {
616 				if (!evsel__is_group_leader(pos)) {
617 					struct hists *leader_hists;
618 
619 					leader_hists = evsel__hists(evsel__leader(pos));
620 					hists__match(leader_hists, hists);
621 					hists__link(leader_hists, hists);
622 				}
623 				continue;
624 			}
625 
626 			hists__find_annotations(hists, pos, ann);
627 		}
628 	}
629 
630 	if (total_nr_samples == 0) {
631 		ui__error("The %s data has no samples!\n", session->data->path);
632 		goto out;
633 	}
634 
635 	/* Display group events together */
636 	evlist__for_each_entry(session->evlist, pos) {
637 		struct hists *hists = evsel__hists(pos);
638 		u32 nr_samples = hists->stats.nr_samples;
639 		struct ui_progress prog;
640 		struct evsel *evsel;
641 
642 		if (!symbol_conf.event_group || !evsel__is_group_leader(pos))
643 			continue;
644 
645 		for_each_group_member(evsel, pos)
646 			nr_samples += evsel__hists(evsel)->stats.nr_samples;
647 
648 		if (nr_samples == 0)
649 			continue;
650 
651 		ui_progress__init(&prog, nr_samples,
652 				  "Sorting group events for output...");
653 		evsel__output_resort(pos, &prog);
654 		ui_progress__finish();
655 
656 		hists__find_annotations(hists, pos, ann);
657 	}
658 
659 	if (use_browser == 2) {
660 		void (*show_annotations)(void);
661 
662 		show_annotations = dlsym(perf_gtk_handle,
663 					 "perf_gtk__show_annotations");
664 		if (show_annotations == NULL) {
665 			ui__error("GTK browser not found!\n");
666 			goto out;
667 		}
668 		show_annotations();
669 	}
670 
671 out:
672 	return ret;
673 }
674 
675 static int parse_percent_limit(const struct option *opt, const char *str,
676 			       int unset __maybe_unused)
677 {
678 	struct perf_annotate *ann = opt->value;
679 	double pcnt = strtof(str, NULL);
680 
681 	ann->min_percent = pcnt;
682 	return 0;
683 }
684 
685 static int parse_data_type(const struct option *opt, const char *str, int unset)
686 {
687 	struct perf_annotate *ann = opt->value;
688 
689 	ann->data_type = !unset;
690 	if (str)
691 		ann->target_data_type = strdup(str);
692 
693 	return 0;
694 }
695 
696 static const char * const annotate_usage[] = {
697 	"perf annotate [<options>]",
698 	NULL
699 };
700 
701 int cmd_annotate(int argc, const char **argv)
702 {
703 	struct perf_annotate annotate = {};
704 	struct perf_data data = {
705 		.mode  = PERF_DATA_MODE_READ,
706 	};
707 	struct itrace_synth_opts itrace_synth_opts = {
708 		.set = 0,
709 	};
710 	const char *disassembler_style = NULL, *objdump_path = NULL, *addr2line_path = NULL;
711 	struct option options[] = {
712 	OPT_STRING('i', "input", &input_name, "file",
713 		    "input file name"),
714 	OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
715 		   "only consider symbols in these dsos"),
716 	OPT_STRING('s', "symbol", &annotate.sym_hist_filter, "symbol",
717 		    "symbol to annotate"),
718 	OPT_BOOLEAN('f', "force", &data.force, "don't complain, do it"),
719 	OPT_INCR('v', "verbose", &verbose,
720 		    "be more verbose (show symbol address, etc)"),
721 	OPT_BOOLEAN('q', "quiet", &quiet, "do now show any warnings or messages"),
722 	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
723 		    "dump raw trace in ASCII"),
724 #ifdef HAVE_GTK4_SUPPORT
725 	OPT_BOOLEAN(0, "gtk", &annotate.use_gtk, "Use the GTK interface"),
726 #endif
727 #ifdef HAVE_SLANG_SUPPORT
728 	OPT_BOOLEAN(0, "tui", &annotate.use_tui, "Use the TUI interface"),
729 #endif
730 	OPT_BOOLEAN(0, "stdio", &annotate.use_stdio, "Use the stdio interface"),
731 	OPT_BOOLEAN(0, "weights", &symbol_conf.annotate_weight,
732 		    "Show or hide weight columns in annotation. Default show if non zero."),
733 	OPT_BOOLEAN(0, "stdio2", &annotate.use_stdio2, "Use the stdio interface"),
734 	OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
735                     "don't load vmlinux even if found"),
736 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
737 		   "file", "vmlinux pathname"),
738 	OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
739 		    "load module symbols - WARNING: use only with -k and LIVE kernel"),
740 	OPT_BOOLEAN('l', "print-line", &annotate_opts.print_lines,
741 		    "print matching source lines (may be slow)"),
742 	OPT_BOOLEAN('P', "full-paths", &annotate_opts.full_path,
743 		    "Don't shorten the displayed pathnames"),
744 	OPT_BOOLEAN(0, "skip-missing", &annotate.skip_missing,
745 		    "Skip symbols that cannot be annotated"),
746 	OPT_BOOLEAN_SET(0, "group", &symbol_conf.event_group,
747 			&annotate.group_set,
748 			"Show event group information together"),
749 	OPT_STRING('C', "cpu", &annotate.cpu_list, "cpu", "list of cpus to profile"),
750 	OPT_CALLBACK(0, "symfs", NULL, "directory[,layout]", SYMFS_HELP,
751 		     symbol__config_symfs),
752 	OPT_BOOLEAN(0, "source", &annotate_opts.annotate_src,
753 		    "Interleave source code with assembly code (default)"),
754 	OPT_BOOLEAN(0, "asm-raw", &annotate_opts.show_asm_raw,
755 		    "Display raw encoding of assembly instructions (default)"),
756 	OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
757 		   "Specify disassembler style (e.g. -M intel for intel syntax)"),
758 	OPT_STRING(0, "prefix", &annotate_opts.prefix, "prefix",
759 		    "Add prefix to source file path names in programs (with --prefix-strip)"),
760 	OPT_STRING(0, "prefix-strip", &annotate_opts.prefix_strip, "N",
761 		    "Strip first N entries of source file path name in programs (with --prefix)"),
762 	OPT_STRING(0, "objdump", &objdump_path, "path",
763 		   "objdump binary to use for disassembly and annotations"),
764 	OPT_STRING(0, "addr2line", &addr2line_path, "path",
765 		   "addr2line binary to use for line numbers"),
766 	OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
767 		    "Enable symbol demangling"),
768 	OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
769 		    "Enable kernel symbol demangling"),
770 	OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
771 		    "Show a column with the sum of periods"),
772 	OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
773 		    "Show a column with the number of samples"),
774 	OPT_CALLBACK_DEFAULT(0, "stdio-color", NULL, "mode",
775 			     "'always' (default), 'never' or 'auto' only applicable to --stdio mode",
776 			     stdio__config_color, "always"),
777 	OPT_CALLBACK(0, "percent-type", &annotate_opts, "local-period",
778 		     "Set percent type local/global-period/hits",
779 		     annotate_parse_percent_type),
780 	OPT_CALLBACK(0, "percent-limit", &annotate, "percent",
781 		     "Don't show entries under that percent", parse_percent_limit),
782 	OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
783 			    "Instruction Tracing options\n" ITRACE_HELP,
784 			    itrace_parse_synth_opts),
785 	OPT_CALLBACK_OPTARG(0, "data-type", &annotate, NULL, "name",
786 			    "Show data type annotate for the memory accesses",
787 			    parse_data_type),
788 	OPT_BOOLEAN(0, "type-stat", &annotate.type_stat,
789 		    "Show stats for the data type annotation"),
790 	OPT_BOOLEAN(0, "insn-stat", &annotate.insn_stat,
791 		    "Show instruction stats for the data type annotation"),
792 	OPT_BOOLEAN(0, "skip-empty", &symbol_conf.skip_empty,
793 		    "Do not display empty (or dummy) events in the output"),
794 	OPT_BOOLEAN(0, "code-with-type", &annotate_opts.code_with_type,
795 		    "Show data type info in code annotation (memory instructions only)"),
796 	OPT_END()
797 	};
798 	int ret;
799 
800 	set_option_flag(options, 0, "show-total-period", PARSE_OPT_EXCLUSIVE);
801 	set_option_flag(options, 0, "show-nr-samples", PARSE_OPT_EXCLUSIVE);
802 	symbol_conf.annotate_weight = true;
803 
804 	annotation_options__init();
805 
806 	ret = hists__init();
807 	if (ret < 0)
808 		return ret;
809 
810 	annotation_config__init();
811 
812 	argc = parse_options(argc, argv, options, annotate_usage, 0);
813 	if (argc) {
814 		/*
815 		 * Special case: if there's an argument left then assume that
816 		 * it's a symbol filter:
817 		 */
818 		if (argc > 1)
819 			usage_with_options(annotate_usage, options);
820 
821 		annotate.sym_hist_filter = argv[0];
822 	}
823 
824 	if (disassembler_style) {
825 		annotate_opts.disassembler_style = strdup(disassembler_style);
826 		if (!annotate_opts.disassembler_style)
827 			return -ENOMEM;
828 	}
829 	if (objdump_path) {
830 		annotate_opts.objdump_path = strdup(objdump_path);
831 		if (!annotate_opts.objdump_path)
832 			return -ENOMEM;
833 	}
834 	if (addr2line_path) {
835 		symbol_conf.addr2line_path = strdup(addr2line_path);
836 		if (!symbol_conf.addr2line_path)
837 			return -ENOMEM;
838 	}
839 
840 	if (annotate_check_args() < 0)
841 		return -EINVAL;
842 
843 #ifdef HAVE_GTK4_SUPPORT
844 	if (symbol_conf.show_nr_samples && annotate.use_gtk) {
845 		pr_err("--show-nr-samples is not available in --gtk mode at this time\n");
846 		return ret;
847 	}
848 #endif
849 
850 #ifndef HAVE_LIBDW_SUPPORT
851 	if (annotate.data_type) {
852 		pr_err("Error: Data type profiling is disabled due to missing DWARF support\n");
853 		return -ENOTSUP;
854 	}
855 #endif
856 
857 	ret = symbol__validate_sym_arguments();
858 	if (ret)
859 		return ret;
860 
861 	if (quiet)
862 		perf_quiet_option();
863 
864 	data.path = input_name;
865 
866 	perf_tool__init(&annotate.tool, /*ordered_events=*/true);
867 	annotate.tool.sample	= process_sample_event;
868 	annotate.tool.mmap	= perf_event__process_mmap;
869 	annotate.tool.mmap2	= perf_event__process_mmap2;
870 	annotate.tool.comm	= perf_event__process_comm;
871 	annotate.tool.exit	= perf_event__process_exit;
872 	annotate.tool.fork	= perf_event__process_fork;
873 	annotate.tool.namespaces = perf_event__process_namespaces;
874 	annotate.tool.attr	= perf_event__process_attr;
875 	annotate.tool.build_id = perf_event__process_build_id;
876 #ifdef HAVE_LIBTRACEEVENT
877 	annotate.tool.tracing_data   = perf_event__process_tracing_data;
878 #endif
879 	annotate.tool.id_index	= perf_event__process_id_index;
880 	annotate.tool.auxtrace_info	= perf_event__process_auxtrace_info;
881 	annotate.tool.auxtrace	= perf_event__process_auxtrace;
882 	annotate.tool.feature	= perf_event__process_feature;
883 	annotate.tool.ordering_requires_timestamps = true;
884 
885 	annotate.session = perf_session__new(&data, &annotate.tool);
886 	if (IS_ERR(annotate.session))
887 		return PTR_ERR(annotate.session);
888 	/*
889 	 * Hardware tracing (e.g., ARM SPE) may synthesize multiple events per
890 	 * instruction. When data type profiling is enabled, default to synthesizing
891 	 * at most one event (equivalent to --itrace=i1i) to prevent skewed
892 	 * statistics.
893 	 */
894 	if (annotate.data_type && !itrace_synth_opts.set)
895 		itrace_synth_opts.default_single_event_per_ip = true;
896 
897 	annotate.session->itrace_synth_opts = &itrace_synth_opts;
898 
899 	annotate.has_br_stack = perf_header__has_feat(&annotate.session->header,
900 						      HEADER_BRANCH_STACK);
901 
902 	if (annotate.group_set)
903 		evlist__force_leader(annotate.session->evlist);
904 
905 	ret = symbol__annotation_init();
906 	if (ret < 0)
907 		goto out_delete;
908 
909 	symbol_conf.try_vmlinux_path = true;
910 
911 	ret = symbol__init(perf_session__env(annotate.session));
912 	if (ret < 0)
913 		goto out_delete;
914 
915 	if (annotate.use_stdio || annotate.use_stdio2)
916 		use_browser = 0;
917 #ifdef HAVE_SLANG_SUPPORT
918 	else if (annotate.use_tui)
919 		use_browser = 1;
920 #endif
921 #ifdef HAVE_GTK4_SUPPORT
922 	else if (annotate.use_gtk)
923 		use_browser = 2;
924 #endif
925 
926 	if (annotate.data_type) {
927 		annotate_opts.annotate_src = false;
928 		symbol_conf.annotate_data_member = true;
929 		symbol_conf.annotate_data_sample = true;
930 	} else if (annotate_opts.code_with_type) {
931 		symbol_conf.annotate_data_member = true;
932 	}
933 
934 	setup_browser(true);
935 
936 	/*
937 	 * Events of different processes may correspond to the same
938 	 * symbol, we do not care about the processes in annotate,
939 	 * set sort order to avoid repeated output.
940 	 */
941 	if (annotate.data_type)
942 		sort_order = "dso,type";
943 	else
944 		sort_order = "dso,symbol";
945 
946 	/*
947 	 * Set SORT_MODE__BRANCH so that annotate displays IPC/Cycle and
948 	 * branch counters, if the corresponding branch info is available
949 	 * in the perf data in the TUI mode.
950 	 */
951 	if ((use_browser == 1 || annotate.use_stdio2) && annotate.has_br_stack) {
952 		sort__mode = SORT_MODE__BRANCH;
953 		if (evlist__nr_br_cntr(annotate.session->evlist) > 0)
954 			annotate_opts.show_br_cntr = true;
955 	}
956 
957 	if (setup_sorting(/*evlist=*/NULL, perf_session__env(annotate.session)) < 0)
958 		usage_with_options(annotate_usage, options);
959 
960 	ret = __cmd_annotate(&annotate);
961 
962 out_delete:
963 	/*
964 	 * Speed up the exit process by only deleting for debug builds. For
965 	 * large files this can save time.
966 	 */
967 #ifndef NDEBUG
968 	perf_session__delete(annotate.session);
969 #endif
970 	annotation_options__exit();
971 
972 	return ret;
973 }
974