xref: /openbmc/linux/tools/perf/util/annotate.c (revision 97d5f2e9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
4  *
5  * Parts came from builtin-annotate.c, see those files for further
6  * copyright notes.
7  */
8 
9 #include <errno.h>
10 #include <inttypes.h>
11 #include <libgen.h>
12 #include <stdlib.h>
13 #include "util.h" // hex_width()
14 #include "ui/ui.h"
15 #include "sort.h"
16 #include "build-id.h"
17 #include "color.h"
18 #include "config.h"
19 #include "dso.h"
20 #include "env.h"
21 #include "map.h"
22 #include "maps.h"
23 #include "symbol.h"
24 #include "srcline.h"
25 #include "units.h"
26 #include "debug.h"
27 #include "annotate.h"
28 #include "evsel.h"
29 #include "evlist.h"
30 #include "bpf-event.h"
31 #include "bpf-utils.h"
32 #include "block-range.h"
33 #include "string2.h"
34 #include "util/event.h"
35 #include "arch/common.h"
36 #include "namespaces.h"
37 #include <regex.h>
38 #include <linux/bitops.h>
39 #include <linux/kernel.h>
40 #include <linux/string.h>
41 #include <linux/zalloc.h>
42 #include <subcmd/parse-options.h>
43 #include <subcmd/run-command.h>
44 
45 /* FIXME: For the HE_COLORSET */
46 #include "ui/browser.h"
47 
48 /*
49  * FIXME: Using the same values as slang.h,
50  * but that header may not be available everywhere
51  */
52 #define LARROW_CHAR	((unsigned char)',')
53 #define RARROW_CHAR	((unsigned char)'+')
54 #define DARROW_CHAR	((unsigned char)'.')
55 #define UARROW_CHAR	((unsigned char)'-')
56 
57 #include <linux/ctype.h>
58 
59 static regex_t	 file_lineno;
60 
61 static struct ins_ops *ins__find(struct arch *arch, const char *name);
62 static void ins__sort(struct arch *arch);
63 static int disasm_line__parse(char *line, const char **namep, char **rawp);
64 
65 struct arch {
66 	const char	*name;
67 	struct ins	*instructions;
68 	size_t		nr_instructions;
69 	size_t		nr_instructions_allocated;
70 	struct ins_ops  *(*associate_instruction_ops)(struct arch *arch, const char *name);
71 	bool		sorted_instructions;
72 	bool		initialized;
73 	const char	*insn_suffix;
74 	void		*priv;
75 	unsigned int	model;
76 	unsigned int	family;
77 	int		(*init)(struct arch *arch, char *cpuid);
78 	bool		(*ins_is_fused)(struct arch *arch, const char *ins1,
79 					const char *ins2);
80 	struct		{
81 		char comment_char;
82 		char skip_functions_char;
83 	} objdump;
84 };
85 
86 static struct ins_ops call_ops;
87 static struct ins_ops dec_ops;
88 static struct ins_ops jump_ops;
89 static struct ins_ops mov_ops;
90 static struct ins_ops nop_ops;
91 static struct ins_ops lock_ops;
92 static struct ins_ops ret_ops;
93 
94 static int arch__grow_instructions(struct arch *arch)
95 {
96 	struct ins *new_instructions;
97 	size_t new_nr_allocated;
98 
99 	if (arch->nr_instructions_allocated == 0 && arch->instructions)
100 		goto grow_from_non_allocated_table;
101 
102 	new_nr_allocated = arch->nr_instructions_allocated + 128;
103 	new_instructions = realloc(arch->instructions, new_nr_allocated * sizeof(struct ins));
104 	if (new_instructions == NULL)
105 		return -1;
106 
107 out_update_instructions:
108 	arch->instructions = new_instructions;
109 	arch->nr_instructions_allocated = new_nr_allocated;
110 	return 0;
111 
112 grow_from_non_allocated_table:
113 	new_nr_allocated = arch->nr_instructions + 128;
114 	new_instructions = calloc(new_nr_allocated, sizeof(struct ins));
115 	if (new_instructions == NULL)
116 		return -1;
117 
118 	memcpy(new_instructions, arch->instructions, arch->nr_instructions);
119 	goto out_update_instructions;
120 }
121 
122 static int arch__associate_ins_ops(struct arch* arch, const char *name, struct ins_ops *ops)
123 {
124 	struct ins *ins;
125 
126 	if (arch->nr_instructions == arch->nr_instructions_allocated &&
127 	    arch__grow_instructions(arch))
128 		return -1;
129 
130 	ins = &arch->instructions[arch->nr_instructions];
131 	ins->name = strdup(name);
132 	if (!ins->name)
133 		return -1;
134 
135 	ins->ops  = ops;
136 	arch->nr_instructions++;
137 
138 	ins__sort(arch);
139 	return 0;
140 }
141 
142 #include "arch/arc/annotate/instructions.c"
143 #include "arch/arm/annotate/instructions.c"
144 #include "arch/arm64/annotate/instructions.c"
145 #include "arch/csky/annotate/instructions.c"
146 #include "arch/loongarch/annotate/instructions.c"
147 #include "arch/mips/annotate/instructions.c"
148 #include "arch/x86/annotate/instructions.c"
149 #include "arch/powerpc/annotate/instructions.c"
150 #include "arch/riscv64/annotate/instructions.c"
151 #include "arch/s390/annotate/instructions.c"
152 #include "arch/sparc/annotate/instructions.c"
153 
154 static struct arch architectures[] = {
155 	{
156 		.name = "arc",
157 		.init = arc__annotate_init,
158 	},
159 	{
160 		.name = "arm",
161 		.init = arm__annotate_init,
162 	},
163 	{
164 		.name = "arm64",
165 		.init = arm64__annotate_init,
166 	},
167 	{
168 		.name = "csky",
169 		.init = csky__annotate_init,
170 	},
171 	{
172 		.name = "mips",
173 		.init = mips__annotate_init,
174 		.objdump = {
175 			.comment_char = '#',
176 		},
177 	},
178 	{
179 		.name = "x86",
180 		.init = x86__annotate_init,
181 		.instructions = x86__instructions,
182 		.nr_instructions = ARRAY_SIZE(x86__instructions),
183 		.insn_suffix = "bwlq",
184 		.objdump =  {
185 			.comment_char = '#',
186 		},
187 	},
188 	{
189 		.name = "powerpc",
190 		.init = powerpc__annotate_init,
191 	},
192 	{
193 		.name = "riscv64",
194 		.init = riscv64__annotate_init,
195 	},
196 	{
197 		.name = "s390",
198 		.init = s390__annotate_init,
199 		.objdump =  {
200 			.comment_char = '#',
201 		},
202 	},
203 	{
204 		.name = "sparc",
205 		.init = sparc__annotate_init,
206 		.objdump = {
207 			.comment_char = '#',
208 		},
209 	},
210 	{
211 		.name = "loongarch",
212 		.init = loongarch__annotate_init,
213 		.objdump = {
214 			.comment_char = '#',
215 		},
216 	},
217 };
218 
219 static void ins__delete(struct ins_operands *ops)
220 {
221 	if (ops == NULL)
222 		return;
223 	zfree(&ops->source.raw);
224 	zfree(&ops->source.name);
225 	zfree(&ops->target.raw);
226 	zfree(&ops->target.name);
227 }
228 
229 static int ins__raw_scnprintf(struct ins *ins, char *bf, size_t size,
230 			      struct ins_operands *ops, int max_ins_name)
231 {
232 	return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name, ops->raw);
233 }
234 
235 int ins__scnprintf(struct ins *ins, char *bf, size_t size,
236 		   struct ins_operands *ops, int max_ins_name)
237 {
238 	if (ins->ops->scnprintf)
239 		return ins->ops->scnprintf(ins, bf, size, ops, max_ins_name);
240 
241 	return ins__raw_scnprintf(ins, bf, size, ops, max_ins_name);
242 }
243 
244 bool ins__is_fused(struct arch *arch, const char *ins1, const char *ins2)
245 {
246 	if (!arch || !arch->ins_is_fused)
247 		return false;
248 
249 	return arch->ins_is_fused(arch, ins1, ins2);
250 }
251 
252 static int call__parse(struct arch *arch, struct ins_operands *ops, struct map_symbol *ms)
253 {
254 	char *endptr, *tok, *name;
255 	struct map *map = ms->map;
256 	struct addr_map_symbol target = {
257 		.ms = { .map = map, },
258 	};
259 
260 	ops->target.addr = strtoull(ops->raw, &endptr, 16);
261 
262 	name = strchr(endptr, '<');
263 	if (name == NULL)
264 		goto indirect_call;
265 
266 	name++;
267 
268 	if (arch->objdump.skip_functions_char &&
269 	    strchr(name, arch->objdump.skip_functions_char))
270 		return -1;
271 
272 	tok = strchr(name, '>');
273 	if (tok == NULL)
274 		return -1;
275 
276 	*tok = '\0';
277 	ops->target.name = strdup(name);
278 	*tok = '>';
279 
280 	if (ops->target.name == NULL)
281 		return -1;
282 find_target:
283 	target.addr = map__objdump_2mem(map, ops->target.addr);
284 
285 	if (maps__find_ams(ms->maps, &target) == 0 &&
286 	    map__rip_2objdump(target.ms.map, map__map_ip(target.ms.map, target.addr)) == ops->target.addr)
287 		ops->target.sym = target.ms.sym;
288 
289 	return 0;
290 
291 indirect_call:
292 	tok = strchr(endptr, '*');
293 	if (tok != NULL) {
294 		endptr++;
295 
296 		/* Indirect call can use a non-rip register and offset: callq  *0x8(%rbx).
297 		 * Do not parse such instruction.  */
298 		if (strstr(endptr, "(%r") == NULL)
299 			ops->target.addr = strtoull(endptr, NULL, 16);
300 	}
301 	goto find_target;
302 }
303 
304 static int call__scnprintf(struct ins *ins, char *bf, size_t size,
305 			   struct ins_operands *ops, int max_ins_name)
306 {
307 	if (ops->target.sym)
308 		return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name, ops->target.sym->name);
309 
310 	if (ops->target.addr == 0)
311 		return ins__raw_scnprintf(ins, bf, size, ops, max_ins_name);
312 
313 	if (ops->target.name)
314 		return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name, ops->target.name);
315 
316 	return scnprintf(bf, size, "%-*s *%" PRIx64, max_ins_name, ins->name, ops->target.addr);
317 }
318 
319 static struct ins_ops call_ops = {
320 	.parse	   = call__parse,
321 	.scnprintf = call__scnprintf,
322 };
323 
324 bool ins__is_call(const struct ins *ins)
325 {
326 	return ins->ops == &call_ops || ins->ops == &s390_call_ops;
327 }
328 
329 /*
330  * Prevents from matching commas in the comment section, e.g.:
331  * ffff200008446e70:       b.cs    ffff2000084470f4 <generic_exec_single+0x314>  // b.hs, b.nlast
332  *
333  * and skip comma as part of function arguments, e.g.:
334  * 1d8b4ac <linemap_lookup(line_maps const*, unsigned int)+0xcc>
335  */
336 static inline const char *validate_comma(const char *c, struct ins_operands *ops)
337 {
338 	if (ops->raw_comment && c > ops->raw_comment)
339 		return NULL;
340 
341 	if (ops->raw_func_start && c > ops->raw_func_start)
342 		return NULL;
343 
344 	return c;
345 }
346 
347 static int jump__parse(struct arch *arch, struct ins_operands *ops, struct map_symbol *ms)
348 {
349 	struct map *map = ms->map;
350 	struct symbol *sym = ms->sym;
351 	struct addr_map_symbol target = {
352 		.ms = { .map = map, },
353 	};
354 	const char *c = strchr(ops->raw, ',');
355 	u64 start, end;
356 
357 	ops->raw_comment = strchr(ops->raw, arch->objdump.comment_char);
358 	ops->raw_func_start = strchr(ops->raw, '<');
359 
360 	c = validate_comma(c, ops);
361 
362 	/*
363 	 * Examples of lines to parse for the _cpp_lex_token@@Base
364 	 * function:
365 	 *
366 	 * 1159e6c: jne    115aa32 <_cpp_lex_token@@Base+0xf92>
367 	 * 1159e8b: jne    c469be <cpp_named_operator2name@@Base+0xa72>
368 	 *
369 	 * The first is a jump to an offset inside the same function,
370 	 * the second is to another function, i.e. that 0xa72 is an
371 	 * offset in the cpp_named_operator2name@@base function.
372 	 */
373 	/*
374 	 * skip over possible up to 2 operands to get to address, e.g.:
375 	 * tbnz	 w0, #26, ffff0000083cd190 <security_file_permission+0xd0>
376 	 */
377 	if (c++ != NULL) {
378 		ops->target.addr = strtoull(c, NULL, 16);
379 		if (!ops->target.addr) {
380 			c = strchr(c, ',');
381 			c = validate_comma(c, ops);
382 			if (c++ != NULL)
383 				ops->target.addr = strtoull(c, NULL, 16);
384 		}
385 	} else {
386 		ops->target.addr = strtoull(ops->raw, NULL, 16);
387 	}
388 
389 	target.addr = map__objdump_2mem(map, ops->target.addr);
390 	start = map__unmap_ip(map, sym->start);
391 	end = map__unmap_ip(map, sym->end);
392 
393 	ops->target.outside = target.addr < start || target.addr > end;
394 
395 	/*
396 	 * FIXME: things like this in _cpp_lex_token (gcc's cc1 program):
397 
398 		cpp_named_operator2name@@Base+0xa72
399 
400 	 * Point to a place that is after the cpp_named_operator2name
401 	 * boundaries, i.e.  in the ELF symbol table for cc1
402 	 * cpp_named_operator2name is marked as being 32-bytes long, but it in
403 	 * fact is much larger than that, so we seem to need a symbols__find()
404 	 * routine that looks for >= current->start and  < next_symbol->start,
405 	 * possibly just for C++ objects?
406 	 *
407 	 * For now lets just make some progress by marking jumps to outside the
408 	 * current function as call like.
409 	 *
410 	 * Actual navigation will come next, with further understanding of how
411 	 * the symbol searching and disassembly should be done.
412 	 */
413 	if (maps__find_ams(ms->maps, &target) == 0 &&
414 	    map__rip_2objdump(target.ms.map, map__map_ip(target.ms.map, target.addr)) == ops->target.addr)
415 		ops->target.sym = target.ms.sym;
416 
417 	if (!ops->target.outside) {
418 		ops->target.offset = target.addr - start;
419 		ops->target.offset_avail = true;
420 	} else {
421 		ops->target.offset_avail = false;
422 	}
423 
424 	return 0;
425 }
426 
427 static int jump__scnprintf(struct ins *ins, char *bf, size_t size,
428 			   struct ins_operands *ops, int max_ins_name)
429 {
430 	const char *c;
431 
432 	if (!ops->target.addr || ops->target.offset < 0)
433 		return ins__raw_scnprintf(ins, bf, size, ops, max_ins_name);
434 
435 	if (ops->target.outside && ops->target.sym != NULL)
436 		return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name, ops->target.sym->name);
437 
438 	c = strchr(ops->raw, ',');
439 	c = validate_comma(c, ops);
440 
441 	if (c != NULL) {
442 		const char *c2 = strchr(c + 1, ',');
443 
444 		c2 = validate_comma(c2, ops);
445 		/* check for 3-op insn */
446 		if (c2 != NULL)
447 			c = c2;
448 		c++;
449 
450 		/* mirror arch objdump's space-after-comma style */
451 		if (*c == ' ')
452 			c++;
453 	}
454 
455 	return scnprintf(bf, size, "%-*s %.*s%" PRIx64, max_ins_name,
456 			 ins->name, c ? c - ops->raw : 0, ops->raw,
457 			 ops->target.offset);
458 }
459 
460 static struct ins_ops jump_ops = {
461 	.parse	   = jump__parse,
462 	.scnprintf = jump__scnprintf,
463 };
464 
465 bool ins__is_jump(const struct ins *ins)
466 {
467 	return ins->ops == &jump_ops;
468 }
469 
470 static int comment__symbol(char *raw, char *comment, u64 *addrp, char **namep)
471 {
472 	char *endptr, *name, *t;
473 
474 	if (strstr(raw, "(%rip)") == NULL)
475 		return 0;
476 
477 	*addrp = strtoull(comment, &endptr, 16);
478 	if (endptr == comment)
479 		return 0;
480 	name = strchr(endptr, '<');
481 	if (name == NULL)
482 		return -1;
483 
484 	name++;
485 
486 	t = strchr(name, '>');
487 	if (t == NULL)
488 		return 0;
489 
490 	*t = '\0';
491 	*namep = strdup(name);
492 	*t = '>';
493 
494 	return 0;
495 }
496 
497 static int lock__parse(struct arch *arch, struct ins_operands *ops, struct map_symbol *ms)
498 {
499 	ops->locked.ops = zalloc(sizeof(*ops->locked.ops));
500 	if (ops->locked.ops == NULL)
501 		return 0;
502 
503 	if (disasm_line__parse(ops->raw, &ops->locked.ins.name, &ops->locked.ops->raw) < 0)
504 		goto out_free_ops;
505 
506 	ops->locked.ins.ops = ins__find(arch, ops->locked.ins.name);
507 
508 	if (ops->locked.ins.ops == NULL)
509 		goto out_free_ops;
510 
511 	if (ops->locked.ins.ops->parse &&
512 	    ops->locked.ins.ops->parse(arch, ops->locked.ops, ms) < 0)
513 		goto out_free_ops;
514 
515 	return 0;
516 
517 out_free_ops:
518 	zfree(&ops->locked.ops);
519 	return 0;
520 }
521 
522 static int lock__scnprintf(struct ins *ins, char *bf, size_t size,
523 			   struct ins_operands *ops, int max_ins_name)
524 {
525 	int printed;
526 
527 	if (ops->locked.ins.ops == NULL)
528 		return ins__raw_scnprintf(ins, bf, size, ops, max_ins_name);
529 
530 	printed = scnprintf(bf, size, "%-*s ", max_ins_name, ins->name);
531 	return printed + ins__scnprintf(&ops->locked.ins, bf + printed,
532 					size - printed, ops->locked.ops, max_ins_name);
533 }
534 
535 static void lock__delete(struct ins_operands *ops)
536 {
537 	struct ins *ins = &ops->locked.ins;
538 
539 	if (ins->ops && ins->ops->free)
540 		ins->ops->free(ops->locked.ops);
541 	else
542 		ins__delete(ops->locked.ops);
543 
544 	zfree(&ops->locked.ops);
545 	zfree(&ops->target.raw);
546 	zfree(&ops->target.name);
547 }
548 
549 static struct ins_ops lock_ops = {
550 	.free	   = lock__delete,
551 	.parse	   = lock__parse,
552 	.scnprintf = lock__scnprintf,
553 };
554 
555 static int mov__parse(struct arch *arch, struct ins_operands *ops, struct map_symbol *ms __maybe_unused)
556 {
557 	char *s = strchr(ops->raw, ','), *target, *comment, prev;
558 
559 	if (s == NULL)
560 		return -1;
561 
562 	*s = '\0';
563 
564 	/*
565 	 * x86 SIB addressing has something like 0x8(%rax, %rcx, 1)
566 	 * then it needs to have the closing parenthesis.
567 	 */
568 	if (strchr(ops->raw, '(')) {
569 		*s = ',';
570 		s = strchr(ops->raw, ')');
571 		if (s == NULL || s[1] != ',')
572 			return -1;
573 		*++s = '\0';
574 	}
575 
576 	ops->source.raw = strdup(ops->raw);
577 	*s = ',';
578 
579 	if (ops->source.raw == NULL)
580 		return -1;
581 
582 	target = skip_spaces(++s);
583 	comment = strchr(s, arch->objdump.comment_char);
584 
585 	if (comment != NULL)
586 		s = comment - 1;
587 	else
588 		s = strchr(s, '\0') - 1;
589 
590 	while (s > target && isspace(s[0]))
591 		--s;
592 	s++;
593 	prev = *s;
594 	*s = '\0';
595 
596 	ops->target.raw = strdup(target);
597 	*s = prev;
598 
599 	if (ops->target.raw == NULL)
600 		goto out_free_source;
601 
602 	if (comment == NULL)
603 		return 0;
604 
605 	comment = skip_spaces(comment);
606 	comment__symbol(ops->source.raw, comment + 1, &ops->source.addr, &ops->source.name);
607 	comment__symbol(ops->target.raw, comment + 1, &ops->target.addr, &ops->target.name);
608 
609 	return 0;
610 
611 out_free_source:
612 	zfree(&ops->source.raw);
613 	return -1;
614 }
615 
616 static int mov__scnprintf(struct ins *ins, char *bf, size_t size,
617 			   struct ins_operands *ops, int max_ins_name)
618 {
619 	return scnprintf(bf, size, "%-*s %s,%s", max_ins_name, ins->name,
620 			 ops->source.name ?: ops->source.raw,
621 			 ops->target.name ?: ops->target.raw);
622 }
623 
624 static struct ins_ops mov_ops = {
625 	.parse	   = mov__parse,
626 	.scnprintf = mov__scnprintf,
627 };
628 
629 static int dec__parse(struct arch *arch __maybe_unused, struct ins_operands *ops, struct map_symbol *ms __maybe_unused)
630 {
631 	char *target, *comment, *s, prev;
632 
633 	target = s = ops->raw;
634 
635 	while (s[0] != '\0' && !isspace(s[0]))
636 		++s;
637 	prev = *s;
638 	*s = '\0';
639 
640 	ops->target.raw = strdup(target);
641 	*s = prev;
642 
643 	if (ops->target.raw == NULL)
644 		return -1;
645 
646 	comment = strchr(s, arch->objdump.comment_char);
647 	if (comment == NULL)
648 		return 0;
649 
650 	comment = skip_spaces(comment);
651 	comment__symbol(ops->target.raw, comment + 1, &ops->target.addr, &ops->target.name);
652 
653 	return 0;
654 }
655 
656 static int dec__scnprintf(struct ins *ins, char *bf, size_t size,
657 			   struct ins_operands *ops, int max_ins_name)
658 {
659 	return scnprintf(bf, size, "%-*s %s", max_ins_name, ins->name,
660 			 ops->target.name ?: ops->target.raw);
661 }
662 
663 static struct ins_ops dec_ops = {
664 	.parse	   = dec__parse,
665 	.scnprintf = dec__scnprintf,
666 };
667 
668 static int nop__scnprintf(struct ins *ins __maybe_unused, char *bf, size_t size,
669 			  struct ins_operands *ops __maybe_unused, int max_ins_name)
670 {
671 	return scnprintf(bf, size, "%-*s", max_ins_name, "nop");
672 }
673 
674 static struct ins_ops nop_ops = {
675 	.scnprintf = nop__scnprintf,
676 };
677 
678 static struct ins_ops ret_ops = {
679 	.scnprintf = ins__raw_scnprintf,
680 };
681 
682 bool ins__is_ret(const struct ins *ins)
683 {
684 	return ins->ops == &ret_ops;
685 }
686 
687 bool ins__is_lock(const struct ins *ins)
688 {
689 	return ins->ops == &lock_ops;
690 }
691 
692 static int ins__key_cmp(const void *name, const void *insp)
693 {
694 	const struct ins *ins = insp;
695 
696 	return strcmp(name, ins->name);
697 }
698 
699 static int ins__cmp(const void *a, const void *b)
700 {
701 	const struct ins *ia = a;
702 	const struct ins *ib = b;
703 
704 	return strcmp(ia->name, ib->name);
705 }
706 
707 static void ins__sort(struct arch *arch)
708 {
709 	const int nmemb = arch->nr_instructions;
710 
711 	qsort(arch->instructions, nmemb, sizeof(struct ins), ins__cmp);
712 }
713 
714 static struct ins_ops *__ins__find(struct arch *arch, const char *name)
715 {
716 	struct ins *ins;
717 	const int nmemb = arch->nr_instructions;
718 
719 	if (!arch->sorted_instructions) {
720 		ins__sort(arch);
721 		arch->sorted_instructions = true;
722 	}
723 
724 	ins = bsearch(name, arch->instructions, nmemb, sizeof(struct ins), ins__key_cmp);
725 	if (ins)
726 		return ins->ops;
727 
728 	if (arch->insn_suffix) {
729 		char tmp[32];
730 		char suffix;
731 		size_t len = strlen(name);
732 
733 		if (len == 0 || len >= sizeof(tmp))
734 			return NULL;
735 
736 		suffix = name[len - 1];
737 		if (strchr(arch->insn_suffix, suffix) == NULL)
738 			return NULL;
739 
740 		strcpy(tmp, name);
741 		tmp[len - 1] = '\0'; /* remove the suffix and check again */
742 
743 		ins = bsearch(tmp, arch->instructions, nmemb, sizeof(struct ins), ins__key_cmp);
744 	}
745 	return ins ? ins->ops : NULL;
746 }
747 
748 static struct ins_ops *ins__find(struct arch *arch, const char *name)
749 {
750 	struct ins_ops *ops = __ins__find(arch, name);
751 
752 	if (!ops && arch->associate_instruction_ops)
753 		ops = arch->associate_instruction_ops(arch, name);
754 
755 	return ops;
756 }
757 
758 static int arch__key_cmp(const void *name, const void *archp)
759 {
760 	const struct arch *arch = archp;
761 
762 	return strcmp(name, arch->name);
763 }
764 
765 static int arch__cmp(const void *a, const void *b)
766 {
767 	const struct arch *aa = a;
768 	const struct arch *ab = b;
769 
770 	return strcmp(aa->name, ab->name);
771 }
772 
773 static void arch__sort(void)
774 {
775 	const int nmemb = ARRAY_SIZE(architectures);
776 
777 	qsort(architectures, nmemb, sizeof(struct arch), arch__cmp);
778 }
779 
780 static struct arch *arch__find(const char *name)
781 {
782 	const int nmemb = ARRAY_SIZE(architectures);
783 	static bool sorted;
784 
785 	if (!sorted) {
786 		arch__sort();
787 		sorted = true;
788 	}
789 
790 	return bsearch(name, architectures, nmemb, sizeof(struct arch), arch__key_cmp);
791 }
792 
793 static struct annotated_source *annotated_source__new(void)
794 {
795 	struct annotated_source *src = zalloc(sizeof(*src));
796 
797 	if (src != NULL)
798 		INIT_LIST_HEAD(&src->source);
799 
800 	return src;
801 }
802 
803 static __maybe_unused void annotated_source__delete(struct annotated_source *src)
804 {
805 	if (src == NULL)
806 		return;
807 	zfree(&src->histograms);
808 	zfree(&src->cycles_hist);
809 	free(src);
810 }
811 
812 static int annotated_source__alloc_histograms(struct annotated_source *src,
813 					      size_t size, int nr_hists)
814 {
815 	size_t sizeof_sym_hist;
816 
817 	/*
818 	 * Add buffer of one element for zero length symbol.
819 	 * When sample is taken from first instruction of
820 	 * zero length symbol, perf still resolves it and
821 	 * shows symbol name in perf report and allows to
822 	 * annotate it.
823 	 */
824 	if (size == 0)
825 		size = 1;
826 
827 	/* Check for overflow when calculating sizeof_sym_hist */
828 	if (size > (SIZE_MAX - sizeof(struct sym_hist)) / sizeof(struct sym_hist_entry))
829 		return -1;
830 
831 	sizeof_sym_hist = (sizeof(struct sym_hist) + size * sizeof(struct sym_hist_entry));
832 
833 	/* Check for overflow in zalloc argument */
834 	if (sizeof_sym_hist > SIZE_MAX / nr_hists)
835 		return -1;
836 
837 	src->sizeof_sym_hist = sizeof_sym_hist;
838 	src->nr_histograms   = nr_hists;
839 	src->histograms	     = calloc(nr_hists, sizeof_sym_hist) ;
840 	return src->histograms ? 0 : -1;
841 }
842 
843 /* The cycles histogram is lazily allocated. */
844 static int symbol__alloc_hist_cycles(struct symbol *sym)
845 {
846 	struct annotation *notes = symbol__annotation(sym);
847 	const size_t size = symbol__size(sym);
848 
849 	notes->src->cycles_hist = calloc(size, sizeof(struct cyc_hist));
850 	if (notes->src->cycles_hist == NULL)
851 		return -1;
852 	return 0;
853 }
854 
855 void symbol__annotate_zero_histograms(struct symbol *sym)
856 {
857 	struct annotation *notes = symbol__annotation(sym);
858 
859 	mutex_lock(&notes->lock);
860 	if (notes->src != NULL) {
861 		memset(notes->src->histograms, 0,
862 		       notes->src->nr_histograms * notes->src->sizeof_sym_hist);
863 		if (notes->src->cycles_hist)
864 			memset(notes->src->cycles_hist, 0,
865 				symbol__size(sym) * sizeof(struct cyc_hist));
866 	}
867 	mutex_unlock(&notes->lock);
868 }
869 
870 static int __symbol__account_cycles(struct cyc_hist *ch,
871 				    u64 start,
872 				    unsigned offset, unsigned cycles,
873 				    unsigned have_start)
874 {
875 	/*
876 	 * For now we can only account one basic block per
877 	 * final jump. But multiple could be overlapping.
878 	 * Always account the longest one. So when
879 	 * a shorter one has been already seen throw it away.
880 	 *
881 	 * We separately always account the full cycles.
882 	 */
883 	ch[offset].num_aggr++;
884 	ch[offset].cycles_aggr += cycles;
885 
886 	if (cycles > ch[offset].cycles_max)
887 		ch[offset].cycles_max = cycles;
888 
889 	if (ch[offset].cycles_min) {
890 		if (cycles && cycles < ch[offset].cycles_min)
891 			ch[offset].cycles_min = cycles;
892 	} else
893 		ch[offset].cycles_min = cycles;
894 
895 	if (!have_start && ch[offset].have_start)
896 		return 0;
897 	if (ch[offset].num) {
898 		if (have_start && (!ch[offset].have_start ||
899 				   ch[offset].start > start)) {
900 			ch[offset].have_start = 0;
901 			ch[offset].cycles = 0;
902 			ch[offset].num = 0;
903 			if (ch[offset].reset < 0xffff)
904 				ch[offset].reset++;
905 		} else if (have_start &&
906 			   ch[offset].start < start)
907 			return 0;
908 	}
909 
910 	if (ch[offset].num < NUM_SPARKS)
911 		ch[offset].cycles_spark[ch[offset].num] = cycles;
912 
913 	ch[offset].have_start = have_start;
914 	ch[offset].start = start;
915 	ch[offset].cycles += cycles;
916 	ch[offset].num++;
917 	return 0;
918 }
919 
920 static int __symbol__inc_addr_samples(struct map_symbol *ms,
921 				      struct annotated_source *src, int evidx, u64 addr,
922 				      struct perf_sample *sample)
923 {
924 	struct symbol *sym = ms->sym;
925 	unsigned offset;
926 	struct sym_hist *h;
927 
928 	pr_debug3("%s: addr=%#" PRIx64 "\n", __func__, map__unmap_ip(ms->map, addr));
929 
930 	if ((addr < sym->start || addr >= sym->end) &&
931 	    (addr != sym->end || sym->start != sym->end)) {
932 		pr_debug("%s(%d): ERANGE! sym->name=%s, start=%#" PRIx64 ", addr=%#" PRIx64 ", end=%#" PRIx64 "\n",
933 		       __func__, __LINE__, sym->name, sym->start, addr, sym->end);
934 		return -ERANGE;
935 	}
936 
937 	offset = addr - sym->start;
938 	h = annotated_source__histogram(src, evidx);
939 	if (h == NULL) {
940 		pr_debug("%s(%d): ENOMEM! sym->name=%s, start=%#" PRIx64 ", addr=%#" PRIx64 ", end=%#" PRIx64 ", func: %d\n",
941 			 __func__, __LINE__, sym->name, sym->start, addr, sym->end, sym->type == STT_FUNC);
942 		return -ENOMEM;
943 	}
944 	h->nr_samples++;
945 	h->addr[offset].nr_samples++;
946 	h->period += sample->period;
947 	h->addr[offset].period += sample->period;
948 
949 	pr_debug3("%#" PRIx64 " %s: period++ [addr: %#" PRIx64 ", %#" PRIx64
950 		  ", evidx=%d] => nr_samples: %" PRIu64 ", period: %" PRIu64 "\n",
951 		  sym->start, sym->name, addr, addr - sym->start, evidx,
952 		  h->addr[offset].nr_samples, h->addr[offset].period);
953 	return 0;
954 }
955 
956 static struct cyc_hist *symbol__cycles_hist(struct symbol *sym)
957 {
958 	struct annotation *notes = symbol__annotation(sym);
959 
960 	if (notes->src == NULL) {
961 		notes->src = annotated_source__new();
962 		if (notes->src == NULL)
963 			return NULL;
964 		goto alloc_cycles_hist;
965 	}
966 
967 	if (!notes->src->cycles_hist) {
968 alloc_cycles_hist:
969 		symbol__alloc_hist_cycles(sym);
970 	}
971 
972 	return notes->src->cycles_hist;
973 }
974 
975 struct annotated_source *symbol__hists(struct symbol *sym, int nr_hists)
976 {
977 	struct annotation *notes = symbol__annotation(sym);
978 
979 	if (notes->src == NULL) {
980 		notes->src = annotated_source__new();
981 		if (notes->src == NULL)
982 			return NULL;
983 		goto alloc_histograms;
984 	}
985 
986 	if (notes->src->histograms == NULL) {
987 alloc_histograms:
988 		annotated_source__alloc_histograms(notes->src, symbol__size(sym),
989 						   nr_hists);
990 	}
991 
992 	return notes->src;
993 }
994 
995 static int symbol__inc_addr_samples(struct map_symbol *ms,
996 				    struct evsel *evsel, u64 addr,
997 				    struct perf_sample *sample)
998 {
999 	struct symbol *sym = ms->sym;
1000 	struct annotated_source *src;
1001 
1002 	if (sym == NULL)
1003 		return 0;
1004 	src = symbol__hists(sym, evsel->evlist->core.nr_entries);
1005 	return src ? __symbol__inc_addr_samples(ms, src, evsel->core.idx, addr, sample) : 0;
1006 }
1007 
1008 static int symbol__account_cycles(u64 addr, u64 start,
1009 				  struct symbol *sym, unsigned cycles)
1010 {
1011 	struct cyc_hist *cycles_hist;
1012 	unsigned offset;
1013 
1014 	if (sym == NULL)
1015 		return 0;
1016 	cycles_hist = symbol__cycles_hist(sym);
1017 	if (cycles_hist == NULL)
1018 		return -ENOMEM;
1019 	if (addr < sym->start || addr >= sym->end)
1020 		return -ERANGE;
1021 
1022 	if (start) {
1023 		if (start < sym->start || start >= sym->end)
1024 			return -ERANGE;
1025 		if (start >= addr)
1026 			start = 0;
1027 	}
1028 	offset = addr - sym->start;
1029 	return __symbol__account_cycles(cycles_hist,
1030 					start ? start - sym->start : 0,
1031 					offset, cycles,
1032 					!!start);
1033 }
1034 
1035 int addr_map_symbol__account_cycles(struct addr_map_symbol *ams,
1036 				    struct addr_map_symbol *start,
1037 				    unsigned cycles)
1038 {
1039 	u64 saddr = 0;
1040 	int err;
1041 
1042 	if (!cycles)
1043 		return 0;
1044 
1045 	/*
1046 	 * Only set start when IPC can be computed. We can only
1047 	 * compute it when the basic block is completely in a single
1048 	 * function.
1049 	 * Special case the case when the jump is elsewhere, but
1050 	 * it starts on the function start.
1051 	 */
1052 	if (start &&
1053 		(start->ms.sym == ams->ms.sym ||
1054 		 (ams->ms.sym &&
1055 		  start->addr == ams->ms.sym->start + map__start(ams->ms.map))))
1056 		saddr = start->al_addr;
1057 	if (saddr == 0)
1058 		pr_debug2("BB with bad start: addr %"PRIx64" start %"PRIx64" sym %"PRIx64" saddr %"PRIx64"\n",
1059 			ams->addr,
1060 			start ? start->addr : 0,
1061 			ams->ms.sym ? ams->ms.sym->start + map__start(ams->ms.map) : 0,
1062 			saddr);
1063 	err = symbol__account_cycles(ams->al_addr, saddr, ams->ms.sym, cycles);
1064 	if (err)
1065 		pr_debug2("account_cycles failed %d\n", err);
1066 	return err;
1067 }
1068 
1069 static unsigned annotation__count_insn(struct annotation *notes, u64 start, u64 end)
1070 {
1071 	unsigned n_insn = 0;
1072 	u64 offset;
1073 
1074 	for (offset = start; offset <= end; offset++) {
1075 		if (notes->offsets[offset])
1076 			n_insn++;
1077 	}
1078 	return n_insn;
1079 }
1080 
1081 static void annotation__count_and_fill(struct annotation *notes, u64 start, u64 end, struct cyc_hist *ch)
1082 {
1083 	unsigned n_insn;
1084 	unsigned int cover_insn = 0;
1085 	u64 offset;
1086 
1087 	n_insn = annotation__count_insn(notes, start, end);
1088 	if (n_insn && ch->num && ch->cycles) {
1089 		float ipc = n_insn / ((double)ch->cycles / (double)ch->num);
1090 
1091 		/* Hide data when there are too many overlaps. */
1092 		if (ch->reset >= 0x7fff)
1093 			return;
1094 
1095 		for (offset = start; offset <= end; offset++) {
1096 			struct annotation_line *al = notes->offsets[offset];
1097 
1098 			if (al && al->ipc == 0.0) {
1099 				al->ipc = ipc;
1100 				cover_insn++;
1101 			}
1102 		}
1103 
1104 		if (cover_insn) {
1105 			notes->hit_cycles += ch->cycles;
1106 			notes->hit_insn += n_insn * ch->num;
1107 			notes->cover_insn += cover_insn;
1108 		}
1109 	}
1110 }
1111 
1112 void annotation__compute_ipc(struct annotation *notes, size_t size)
1113 {
1114 	s64 offset;
1115 
1116 	if (!notes->src || !notes->src->cycles_hist)
1117 		return;
1118 
1119 	notes->total_insn = annotation__count_insn(notes, 0, size - 1);
1120 	notes->hit_cycles = 0;
1121 	notes->hit_insn = 0;
1122 	notes->cover_insn = 0;
1123 
1124 	mutex_lock(&notes->lock);
1125 	for (offset = size - 1; offset >= 0; --offset) {
1126 		struct cyc_hist *ch;
1127 
1128 		ch = &notes->src->cycles_hist[offset];
1129 		if (ch && ch->cycles) {
1130 			struct annotation_line *al;
1131 
1132 			if (ch->have_start)
1133 				annotation__count_and_fill(notes, ch->start, offset, ch);
1134 			al = notes->offsets[offset];
1135 			if (al && ch->num_aggr) {
1136 				al->cycles = ch->cycles_aggr / ch->num_aggr;
1137 				al->cycles_max = ch->cycles_max;
1138 				al->cycles_min = ch->cycles_min;
1139 			}
1140 			notes->have_cycles = true;
1141 		}
1142 	}
1143 	mutex_unlock(&notes->lock);
1144 }
1145 
1146 int addr_map_symbol__inc_samples(struct addr_map_symbol *ams, struct perf_sample *sample,
1147 				 struct evsel *evsel)
1148 {
1149 	return symbol__inc_addr_samples(&ams->ms, evsel, ams->al_addr, sample);
1150 }
1151 
1152 int hist_entry__inc_addr_samples(struct hist_entry *he, struct perf_sample *sample,
1153 				 struct evsel *evsel, u64 ip)
1154 {
1155 	return symbol__inc_addr_samples(&he->ms, evsel, ip, sample);
1156 }
1157 
1158 static void disasm_line__init_ins(struct disasm_line *dl, struct arch *arch, struct map_symbol *ms)
1159 {
1160 	dl->ins.ops = ins__find(arch, dl->ins.name);
1161 
1162 	if (!dl->ins.ops)
1163 		return;
1164 
1165 	if (dl->ins.ops->parse && dl->ins.ops->parse(arch, &dl->ops, ms) < 0)
1166 		dl->ins.ops = NULL;
1167 }
1168 
1169 static int disasm_line__parse(char *line, const char **namep, char **rawp)
1170 {
1171 	char tmp, *name = skip_spaces(line);
1172 
1173 	if (name[0] == '\0')
1174 		return -1;
1175 
1176 	*rawp = name + 1;
1177 
1178 	while ((*rawp)[0] != '\0' && !isspace((*rawp)[0]))
1179 		++*rawp;
1180 
1181 	tmp = (*rawp)[0];
1182 	(*rawp)[0] = '\0';
1183 	*namep = strdup(name);
1184 
1185 	if (*namep == NULL)
1186 		goto out;
1187 
1188 	(*rawp)[0] = tmp;
1189 	*rawp = strim(*rawp);
1190 
1191 	return 0;
1192 
1193 out:
1194 	return -1;
1195 }
1196 
1197 struct annotate_args {
1198 	struct arch		  *arch;
1199 	struct map_symbol	  ms;
1200 	struct evsel		  *evsel;
1201 	struct annotation_options *options;
1202 	s64			  offset;
1203 	char			  *line;
1204 	int			  line_nr;
1205 	char			  *fileloc;
1206 };
1207 
1208 static void annotation_line__init(struct annotation_line *al,
1209 				  struct annotate_args *args,
1210 				  int nr)
1211 {
1212 	al->offset = args->offset;
1213 	al->line = strdup(args->line);
1214 	al->line_nr = args->line_nr;
1215 	al->fileloc = args->fileloc;
1216 	al->data_nr = nr;
1217 }
1218 
1219 static void annotation_line__exit(struct annotation_line *al)
1220 {
1221 	zfree_srcline(&al->path);
1222 	zfree(&al->line);
1223 }
1224 
1225 static size_t disasm_line_size(int nr)
1226 {
1227 	struct annotation_line *al;
1228 
1229 	return (sizeof(struct disasm_line) + (sizeof(al->data[0]) * nr));
1230 }
1231 
1232 /*
1233  * Allocating the disasm annotation line data with
1234  * following structure:
1235  *
1236  *    -------------------------------------------
1237  *    struct disasm_line | struct annotation_line
1238  *    -------------------------------------------
1239  *
1240  * We have 'struct annotation_line' member as last member
1241  * of 'struct disasm_line' to have an easy access.
1242  */
1243 static struct disasm_line *disasm_line__new(struct annotate_args *args)
1244 {
1245 	struct disasm_line *dl = NULL;
1246 	int nr = 1;
1247 
1248 	if (evsel__is_group_event(args->evsel))
1249 		nr = args->evsel->core.nr_members;
1250 
1251 	dl = zalloc(disasm_line_size(nr));
1252 	if (!dl)
1253 		return NULL;
1254 
1255 	annotation_line__init(&dl->al, args, nr);
1256 	if (dl->al.line == NULL)
1257 		goto out_delete;
1258 
1259 	if (args->offset != -1) {
1260 		if (disasm_line__parse(dl->al.line, &dl->ins.name, &dl->ops.raw) < 0)
1261 			goto out_free_line;
1262 
1263 		disasm_line__init_ins(dl, args->arch, &args->ms);
1264 	}
1265 
1266 	return dl;
1267 
1268 out_free_line:
1269 	zfree(&dl->al.line);
1270 out_delete:
1271 	free(dl);
1272 	return NULL;
1273 }
1274 
1275 void disasm_line__free(struct disasm_line *dl)
1276 {
1277 	if (dl->ins.ops && dl->ins.ops->free)
1278 		dl->ins.ops->free(&dl->ops);
1279 	else
1280 		ins__delete(&dl->ops);
1281 	zfree(&dl->ins.name);
1282 	annotation_line__exit(&dl->al);
1283 	free(dl);
1284 }
1285 
1286 int disasm_line__scnprintf(struct disasm_line *dl, char *bf, size_t size, bool raw, int max_ins_name)
1287 {
1288 	if (raw || !dl->ins.ops)
1289 		return scnprintf(bf, size, "%-*s %s", max_ins_name, dl->ins.name, dl->ops.raw);
1290 
1291 	return ins__scnprintf(&dl->ins, bf, size, &dl->ops, max_ins_name);
1292 }
1293 
1294 void annotation__init(struct annotation *notes)
1295 {
1296 	mutex_init(&notes->lock);
1297 }
1298 
1299 void annotation__exit(struct annotation *notes)
1300 {
1301 	annotated_source__delete(notes->src);
1302 	mutex_destroy(&notes->lock);
1303 }
1304 
1305 static void annotation_line__add(struct annotation_line *al, struct list_head *head)
1306 {
1307 	list_add_tail(&al->node, head);
1308 }
1309 
1310 struct annotation_line *
1311 annotation_line__next(struct annotation_line *pos, struct list_head *head)
1312 {
1313 	list_for_each_entry_continue(pos, head, node)
1314 		if (pos->offset >= 0)
1315 			return pos;
1316 
1317 	return NULL;
1318 }
1319 
1320 static const char *annotate__address_color(struct block_range *br)
1321 {
1322 	double cov = block_range__coverage(br);
1323 
1324 	if (cov >= 0) {
1325 		/* mark red for >75% coverage */
1326 		if (cov > 0.75)
1327 			return PERF_COLOR_RED;
1328 
1329 		/* mark dull for <1% coverage */
1330 		if (cov < 0.01)
1331 			return PERF_COLOR_NORMAL;
1332 	}
1333 
1334 	return PERF_COLOR_MAGENTA;
1335 }
1336 
1337 static const char *annotate__asm_color(struct block_range *br)
1338 {
1339 	double cov = block_range__coverage(br);
1340 
1341 	if (cov >= 0) {
1342 		/* mark dull for <1% coverage */
1343 		if (cov < 0.01)
1344 			return PERF_COLOR_NORMAL;
1345 	}
1346 
1347 	return PERF_COLOR_BLUE;
1348 }
1349 
1350 static void annotate__branch_printf(struct block_range *br, u64 addr)
1351 {
1352 	bool emit_comment = true;
1353 
1354 	if (!br)
1355 		return;
1356 
1357 #if 1
1358 	if (br->is_target && br->start == addr) {
1359 		struct block_range *branch = br;
1360 		double p;
1361 
1362 		/*
1363 		 * Find matching branch to our target.
1364 		 */
1365 		while (!branch->is_branch)
1366 			branch = block_range__next(branch);
1367 
1368 		p = 100 *(double)br->entry / branch->coverage;
1369 
1370 		if (p > 0.1) {
1371 			if (emit_comment) {
1372 				emit_comment = false;
1373 				printf("\t#");
1374 			}
1375 
1376 			/*
1377 			 * The percentage of coverage joined at this target in relation
1378 			 * to the next branch.
1379 			 */
1380 			printf(" +%.2f%%", p);
1381 		}
1382 	}
1383 #endif
1384 	if (br->is_branch && br->end == addr) {
1385 		double p = 100*(double)br->taken / br->coverage;
1386 
1387 		if (p > 0.1) {
1388 			if (emit_comment) {
1389 				emit_comment = false;
1390 				printf("\t#");
1391 			}
1392 
1393 			/*
1394 			 * The percentage of coverage leaving at this branch, and
1395 			 * its prediction ratio.
1396 			 */
1397 			printf(" -%.2f%% (p:%.2f%%)", p, 100*(double)br->pred  / br->taken);
1398 		}
1399 	}
1400 }
1401 
1402 static int disasm_line__print(struct disasm_line *dl, u64 start, int addr_fmt_width)
1403 {
1404 	s64 offset = dl->al.offset;
1405 	const u64 addr = start + offset;
1406 	struct block_range *br;
1407 
1408 	br = block_range__find(addr);
1409 	color_fprintf(stdout, annotate__address_color(br), "  %*" PRIx64 ":", addr_fmt_width, addr);
1410 	color_fprintf(stdout, annotate__asm_color(br), "%s", dl->al.line);
1411 	annotate__branch_printf(br, addr);
1412 	return 0;
1413 }
1414 
1415 static int
1416 annotation_line__print(struct annotation_line *al, struct symbol *sym, u64 start,
1417 		       struct evsel *evsel, u64 len, int min_pcnt, int printed,
1418 		       int max_lines, struct annotation_line *queue, int addr_fmt_width,
1419 		       int percent_type)
1420 {
1421 	struct disasm_line *dl = container_of(al, struct disasm_line, al);
1422 	static const char *prev_line;
1423 
1424 	if (al->offset != -1) {
1425 		double max_percent = 0.0;
1426 		int i, nr_percent = 1;
1427 		const char *color;
1428 		struct annotation *notes = symbol__annotation(sym);
1429 
1430 		for (i = 0; i < al->data_nr; i++) {
1431 			double percent;
1432 
1433 			percent = annotation_data__percent(&al->data[i],
1434 							   percent_type);
1435 
1436 			if (percent > max_percent)
1437 				max_percent = percent;
1438 		}
1439 
1440 		if (al->data_nr > nr_percent)
1441 			nr_percent = al->data_nr;
1442 
1443 		if (max_percent < min_pcnt)
1444 			return -1;
1445 
1446 		if (max_lines && printed >= max_lines)
1447 			return 1;
1448 
1449 		if (queue != NULL) {
1450 			list_for_each_entry_from(queue, &notes->src->source, node) {
1451 				if (queue == al)
1452 					break;
1453 				annotation_line__print(queue, sym, start, evsel, len,
1454 						       0, 0, 1, NULL, addr_fmt_width,
1455 						       percent_type);
1456 			}
1457 		}
1458 
1459 		color = get_percent_color(max_percent);
1460 
1461 		for (i = 0; i < nr_percent; i++) {
1462 			struct annotation_data *data = &al->data[i];
1463 			double percent;
1464 
1465 			percent = annotation_data__percent(data, percent_type);
1466 			color = get_percent_color(percent);
1467 
1468 			if (symbol_conf.show_total_period)
1469 				color_fprintf(stdout, color, " %11" PRIu64,
1470 					      data->he.period);
1471 			else if (symbol_conf.show_nr_samples)
1472 				color_fprintf(stdout, color, " %7" PRIu64,
1473 					      data->he.nr_samples);
1474 			else
1475 				color_fprintf(stdout, color, " %7.2f", percent);
1476 		}
1477 
1478 		printf(" : ");
1479 
1480 		disasm_line__print(dl, start, addr_fmt_width);
1481 
1482 		/*
1483 		 * Also color the filename and line if needed, with
1484 		 * the same color than the percentage. Don't print it
1485 		 * twice for close colored addr with the same filename:line
1486 		 */
1487 		if (al->path) {
1488 			if (!prev_line || strcmp(prev_line, al->path)) {
1489 				color_fprintf(stdout, color, " // %s", al->path);
1490 				prev_line = al->path;
1491 			}
1492 		}
1493 
1494 		printf("\n");
1495 	} else if (max_lines && printed >= max_lines)
1496 		return 1;
1497 	else {
1498 		int width = symbol_conf.show_total_period ? 12 : 8;
1499 
1500 		if (queue)
1501 			return -1;
1502 
1503 		if (evsel__is_group_event(evsel))
1504 			width *= evsel->core.nr_members;
1505 
1506 		if (!*al->line)
1507 			printf(" %*s:\n", width, " ");
1508 		else
1509 			printf(" %*s: %-*d %s\n", width, " ", addr_fmt_width, al->line_nr, al->line);
1510 	}
1511 
1512 	return 0;
1513 }
1514 
1515 /*
1516  * symbol__parse_objdump_line() parses objdump output (with -d --no-show-raw)
1517  * which looks like following
1518  *
1519  *  0000000000415500 <_init>:
1520  *    415500:       sub    $0x8,%rsp
1521  *    415504:       mov    0x2f5ad5(%rip),%rax        # 70afe0 <_DYNAMIC+0x2f8>
1522  *    41550b:       test   %rax,%rax
1523  *    41550e:       je     415515 <_init+0x15>
1524  *    415510:       callq  416e70 <__gmon_start__@plt>
1525  *    415515:       add    $0x8,%rsp
1526  *    415519:       retq
1527  *
1528  * it will be parsed and saved into struct disasm_line as
1529  *  <offset>       <name>  <ops.raw>
1530  *
1531  * The offset will be a relative offset from the start of the symbol and -1
1532  * means that it's not a disassembly line so should be treated differently.
1533  * The ops.raw part will be parsed further according to type of the instruction.
1534  */
1535 static int symbol__parse_objdump_line(struct symbol *sym,
1536 				      struct annotate_args *args,
1537 				      char *parsed_line, int *line_nr, char **fileloc)
1538 {
1539 	struct map *map = args->ms.map;
1540 	struct annotation *notes = symbol__annotation(sym);
1541 	struct disasm_line *dl;
1542 	char *tmp;
1543 	s64 line_ip, offset = -1;
1544 	regmatch_t match[2];
1545 
1546 	/* /filename:linenr ? Save line number and ignore. */
1547 	if (regexec(&file_lineno, parsed_line, 2, match, 0) == 0) {
1548 		*line_nr = atoi(parsed_line + match[1].rm_so);
1549 		free(*fileloc);
1550 		*fileloc = strdup(parsed_line);
1551 		return 0;
1552 	}
1553 
1554 	/* Process hex address followed by ':'. */
1555 	line_ip = strtoull(parsed_line, &tmp, 16);
1556 	if (parsed_line != tmp && tmp[0] == ':' && tmp[1] != '\0') {
1557 		u64 start = map__rip_2objdump(map, sym->start),
1558 		    end = map__rip_2objdump(map, sym->end);
1559 
1560 		offset = line_ip - start;
1561 		if ((u64)line_ip < start || (u64)line_ip >= end)
1562 			offset = -1;
1563 		else
1564 			parsed_line = tmp + 1;
1565 	}
1566 
1567 	args->offset  = offset;
1568 	args->line    = parsed_line;
1569 	args->line_nr = *line_nr;
1570 	args->fileloc = *fileloc;
1571 	args->ms.sym  = sym;
1572 
1573 	dl = disasm_line__new(args);
1574 	(*line_nr)++;
1575 
1576 	if (dl == NULL)
1577 		return -1;
1578 
1579 	if (!disasm_line__has_local_offset(dl)) {
1580 		dl->ops.target.offset = dl->ops.target.addr -
1581 					map__rip_2objdump(map, sym->start);
1582 		dl->ops.target.offset_avail = true;
1583 	}
1584 
1585 	/* kcore has no symbols, so add the call target symbol */
1586 	if (dl->ins.ops && ins__is_call(&dl->ins) && !dl->ops.target.sym) {
1587 		struct addr_map_symbol target = {
1588 			.addr = dl->ops.target.addr,
1589 			.ms = { .map = map, },
1590 		};
1591 
1592 		if (!maps__find_ams(args->ms.maps, &target) &&
1593 		    target.ms.sym->start == target.al_addr)
1594 			dl->ops.target.sym = target.ms.sym;
1595 	}
1596 
1597 	annotation_line__add(&dl->al, &notes->src->source);
1598 	return 0;
1599 }
1600 
1601 static __attribute__((constructor)) void symbol__init_regexpr(void)
1602 {
1603 	regcomp(&file_lineno, "^/[^:]+:([0-9]+)", REG_EXTENDED);
1604 }
1605 
1606 static void delete_last_nop(struct symbol *sym)
1607 {
1608 	struct annotation *notes = symbol__annotation(sym);
1609 	struct list_head *list = &notes->src->source;
1610 	struct disasm_line *dl;
1611 
1612 	while (!list_empty(list)) {
1613 		dl = list_entry(list->prev, struct disasm_line, al.node);
1614 
1615 		if (dl->ins.ops) {
1616 			if (dl->ins.ops != &nop_ops)
1617 				return;
1618 		} else {
1619 			if (!strstr(dl->al.line, " nop ") &&
1620 			    !strstr(dl->al.line, " nopl ") &&
1621 			    !strstr(dl->al.line, " nopw "))
1622 				return;
1623 		}
1624 
1625 		list_del_init(&dl->al.node);
1626 		disasm_line__free(dl);
1627 	}
1628 }
1629 
1630 int symbol__strerror_disassemble(struct map_symbol *ms, int errnum, char *buf, size_t buflen)
1631 {
1632 	struct dso *dso = map__dso(ms->map);
1633 
1634 	BUG_ON(buflen == 0);
1635 
1636 	if (errnum >= 0) {
1637 		str_error_r(errnum, buf, buflen);
1638 		return 0;
1639 	}
1640 
1641 	switch (errnum) {
1642 	case SYMBOL_ANNOTATE_ERRNO__NO_VMLINUX: {
1643 		char bf[SBUILD_ID_SIZE + 15] = " with build id ";
1644 		char *build_id_msg = NULL;
1645 
1646 		if (dso->has_build_id) {
1647 			build_id__sprintf(&dso->bid, bf + 15);
1648 			build_id_msg = bf;
1649 		}
1650 		scnprintf(buf, buflen,
1651 			  "No vmlinux file%s\nwas found in the path.\n\n"
1652 			  "Note that annotation using /proc/kcore requires CAP_SYS_RAWIO capability.\n\n"
1653 			  "Please use:\n\n"
1654 			  "  perf buildid-cache -vu vmlinux\n\n"
1655 			  "or:\n\n"
1656 			  "  --vmlinux vmlinux\n", build_id_msg ?: "");
1657 	}
1658 		break;
1659 	case SYMBOL_ANNOTATE_ERRNO__NO_LIBOPCODES_FOR_BPF:
1660 		scnprintf(buf, buflen, "Please link with binutils's libopcode to enable BPF annotation");
1661 		break;
1662 	case SYMBOL_ANNOTATE_ERRNO__ARCH_INIT_REGEXP:
1663 		scnprintf(buf, buflen, "Problems with arch specific instruction name regular expressions.");
1664 		break;
1665 	case SYMBOL_ANNOTATE_ERRNO__ARCH_INIT_CPUID_PARSING:
1666 		scnprintf(buf, buflen, "Problems while parsing the CPUID in the arch specific initialization.");
1667 		break;
1668 	case SYMBOL_ANNOTATE_ERRNO__BPF_INVALID_FILE:
1669 		scnprintf(buf, buflen, "Invalid BPF file: %s.", dso->long_name);
1670 		break;
1671 	case SYMBOL_ANNOTATE_ERRNO__BPF_MISSING_BTF:
1672 		scnprintf(buf, buflen, "The %s BPF file has no BTF section, compile with -g or use pahole -J.",
1673 			  dso->long_name);
1674 		break;
1675 	default:
1676 		scnprintf(buf, buflen, "Internal error: Invalid %d error code\n", errnum);
1677 		break;
1678 	}
1679 
1680 	return 0;
1681 }
1682 
1683 static int dso__disassemble_filename(struct dso *dso, char *filename, size_t filename_size)
1684 {
1685 	char linkname[PATH_MAX];
1686 	char *build_id_filename;
1687 	char *build_id_path = NULL;
1688 	char *pos;
1689 	int len;
1690 
1691 	if (dso->symtab_type == DSO_BINARY_TYPE__KALLSYMS &&
1692 	    !dso__is_kcore(dso))
1693 		return SYMBOL_ANNOTATE_ERRNO__NO_VMLINUX;
1694 
1695 	build_id_filename = dso__build_id_filename(dso, NULL, 0, false);
1696 	if (build_id_filename) {
1697 		__symbol__join_symfs(filename, filename_size, build_id_filename);
1698 		free(build_id_filename);
1699 	} else {
1700 		if (dso->has_build_id)
1701 			return ENOMEM;
1702 		goto fallback;
1703 	}
1704 
1705 	build_id_path = strdup(filename);
1706 	if (!build_id_path)
1707 		return ENOMEM;
1708 
1709 	/*
1710 	 * old style build-id cache has name of XX/XXXXXXX.. while
1711 	 * new style has XX/XXXXXXX../{elf,kallsyms,vdso}.
1712 	 * extract the build-id part of dirname in the new style only.
1713 	 */
1714 	pos = strrchr(build_id_path, '/');
1715 	if (pos && strlen(pos) < SBUILD_ID_SIZE - 2)
1716 		dirname(build_id_path);
1717 
1718 	if (dso__is_kcore(dso))
1719 		goto fallback;
1720 
1721 	len = readlink(build_id_path, linkname, sizeof(linkname) - 1);
1722 	if (len < 0)
1723 		goto fallback;
1724 
1725 	linkname[len] = '\0';
1726 	if (strstr(linkname, DSO__NAME_KALLSYMS) ||
1727 		access(filename, R_OK)) {
1728 fallback:
1729 		/*
1730 		 * If we don't have build-ids or the build-id file isn't in the
1731 		 * cache, or is just a kallsyms file, well, lets hope that this
1732 		 * DSO is the same as when 'perf record' ran.
1733 		 */
1734 		__symbol__join_symfs(filename, filename_size, dso->long_name);
1735 
1736 		mutex_lock(&dso->lock);
1737 		if (access(filename, R_OK) && errno == ENOENT && dso->nsinfo) {
1738 			char *new_name = dso__filename_with_chroot(dso, filename);
1739 			if (new_name) {
1740 				strlcpy(filename, new_name, filename_size);
1741 				free(new_name);
1742 			}
1743 		}
1744 		mutex_unlock(&dso->lock);
1745 	}
1746 
1747 	free(build_id_path);
1748 	return 0;
1749 }
1750 
1751 #if defined(HAVE_LIBBFD_SUPPORT) && defined(HAVE_LIBBPF_SUPPORT)
1752 #define PACKAGE "perf"
1753 #include <bfd.h>
1754 #include <dis-asm.h>
1755 #include <bpf/bpf.h>
1756 #include <bpf/btf.h>
1757 #include <bpf/libbpf.h>
1758 #include <linux/btf.h>
1759 #include <tools/dis-asm-compat.h>
1760 
1761 static int symbol__disassemble_bpf(struct symbol *sym,
1762 				   struct annotate_args *args)
1763 {
1764 	struct annotation *notes = symbol__annotation(sym);
1765 	struct annotation_options *opts = args->options;
1766 	struct bpf_prog_linfo *prog_linfo = NULL;
1767 	struct bpf_prog_info_node *info_node;
1768 	int len = sym->end - sym->start;
1769 	disassembler_ftype disassemble;
1770 	struct map *map = args->ms.map;
1771 	struct perf_bpil *info_linear;
1772 	struct disassemble_info info;
1773 	struct dso *dso = map__dso(map);
1774 	int pc = 0, count, sub_id;
1775 	struct btf *btf = NULL;
1776 	char tpath[PATH_MAX];
1777 	size_t buf_size;
1778 	int nr_skip = 0;
1779 	char *buf;
1780 	bfd *bfdf;
1781 	int ret;
1782 	FILE *s;
1783 
1784 	if (dso->binary_type != DSO_BINARY_TYPE__BPF_PROG_INFO)
1785 		return SYMBOL_ANNOTATE_ERRNO__BPF_INVALID_FILE;
1786 
1787 	pr_debug("%s: handling sym %s addr %" PRIx64 " len %" PRIx64 "\n", __func__,
1788 		  sym->name, sym->start, sym->end - sym->start);
1789 
1790 	memset(tpath, 0, sizeof(tpath));
1791 	perf_exe(tpath, sizeof(tpath));
1792 
1793 	bfdf = bfd_openr(tpath, NULL);
1794 	assert(bfdf);
1795 	assert(bfd_check_format(bfdf, bfd_object));
1796 
1797 	s = open_memstream(&buf, &buf_size);
1798 	if (!s) {
1799 		ret = errno;
1800 		goto out;
1801 	}
1802 	init_disassemble_info_compat(&info, s,
1803 				     (fprintf_ftype) fprintf,
1804 				     fprintf_styled);
1805 	info.arch = bfd_get_arch(bfdf);
1806 	info.mach = bfd_get_mach(bfdf);
1807 
1808 	info_node = perf_env__find_bpf_prog_info(dso->bpf_prog.env,
1809 						 dso->bpf_prog.id);
1810 	if (!info_node) {
1811 		ret = SYMBOL_ANNOTATE_ERRNO__BPF_MISSING_BTF;
1812 		goto out;
1813 	}
1814 	info_linear = info_node->info_linear;
1815 	sub_id = dso->bpf_prog.sub_id;
1816 
1817 	info.buffer = (void *)(uintptr_t)(info_linear->info.jited_prog_insns);
1818 	info.buffer_length = info_linear->info.jited_prog_len;
1819 
1820 	if (info_linear->info.nr_line_info)
1821 		prog_linfo = bpf_prog_linfo__new(&info_linear->info);
1822 
1823 	if (info_linear->info.btf_id) {
1824 		struct btf_node *node;
1825 
1826 		node = perf_env__find_btf(dso->bpf_prog.env,
1827 					  info_linear->info.btf_id);
1828 		if (node)
1829 			btf = btf__new((__u8 *)(node->data),
1830 				       node->data_size);
1831 	}
1832 
1833 	disassemble_init_for_target(&info);
1834 
1835 #ifdef DISASM_FOUR_ARGS_SIGNATURE
1836 	disassemble = disassembler(info.arch,
1837 				   bfd_big_endian(bfdf),
1838 				   info.mach,
1839 				   bfdf);
1840 #else
1841 	disassemble = disassembler(bfdf);
1842 #endif
1843 	assert(disassemble);
1844 
1845 	fflush(s);
1846 	do {
1847 		const struct bpf_line_info *linfo = NULL;
1848 		struct disasm_line *dl;
1849 		size_t prev_buf_size;
1850 		const char *srcline;
1851 		u64 addr;
1852 
1853 		addr = pc + ((u64 *)(uintptr_t)(info_linear->info.jited_ksyms))[sub_id];
1854 		count = disassemble(pc, &info);
1855 
1856 		if (prog_linfo)
1857 			linfo = bpf_prog_linfo__lfind_addr_func(prog_linfo,
1858 								addr, sub_id,
1859 								nr_skip);
1860 
1861 		if (linfo && btf) {
1862 			srcline = btf__name_by_offset(btf, linfo->line_off);
1863 			nr_skip++;
1864 		} else
1865 			srcline = NULL;
1866 
1867 		fprintf(s, "\n");
1868 		prev_buf_size = buf_size;
1869 		fflush(s);
1870 
1871 		if (!opts->hide_src_code && srcline) {
1872 			args->offset = -1;
1873 			args->line = strdup(srcline);
1874 			args->line_nr = 0;
1875 			args->fileloc = NULL;
1876 			args->ms.sym  = sym;
1877 			dl = disasm_line__new(args);
1878 			if (dl) {
1879 				annotation_line__add(&dl->al,
1880 						     &notes->src->source);
1881 			}
1882 		}
1883 
1884 		args->offset = pc;
1885 		args->line = buf + prev_buf_size;
1886 		args->line_nr = 0;
1887 		args->fileloc = NULL;
1888 		args->ms.sym  = sym;
1889 		dl = disasm_line__new(args);
1890 		if (dl)
1891 			annotation_line__add(&dl->al, &notes->src->source);
1892 
1893 		pc += count;
1894 	} while (count > 0 && pc < len);
1895 
1896 	ret = 0;
1897 out:
1898 	free(prog_linfo);
1899 	btf__free(btf);
1900 	fclose(s);
1901 	bfd_close(bfdf);
1902 	return ret;
1903 }
1904 #else // defined(HAVE_LIBBFD_SUPPORT) && defined(HAVE_LIBBPF_SUPPORT)
1905 static int symbol__disassemble_bpf(struct symbol *sym __maybe_unused,
1906 				   struct annotate_args *args __maybe_unused)
1907 {
1908 	return SYMBOL_ANNOTATE_ERRNO__NO_LIBOPCODES_FOR_BPF;
1909 }
1910 #endif // defined(HAVE_LIBBFD_SUPPORT) && defined(HAVE_LIBBPF_SUPPORT)
1911 
1912 static int
1913 symbol__disassemble_bpf_image(struct symbol *sym,
1914 			      struct annotate_args *args)
1915 {
1916 	struct annotation *notes = symbol__annotation(sym);
1917 	struct disasm_line *dl;
1918 
1919 	args->offset = -1;
1920 	args->line = strdup("to be implemented");
1921 	args->line_nr = 0;
1922 	args->fileloc = NULL;
1923 	dl = disasm_line__new(args);
1924 	if (dl)
1925 		annotation_line__add(&dl->al, &notes->src->source);
1926 
1927 	zfree(&args->line);
1928 	return 0;
1929 }
1930 
1931 /*
1932  * Possibly create a new version of line with tabs expanded. Returns the
1933  * existing or new line, storage is updated if a new line is allocated. If
1934  * allocation fails then NULL is returned.
1935  */
1936 static char *expand_tabs(char *line, char **storage, size_t *storage_len)
1937 {
1938 	size_t i, src, dst, len, new_storage_len, num_tabs;
1939 	char *new_line;
1940 	size_t line_len = strlen(line);
1941 
1942 	for (num_tabs = 0, i = 0; i < line_len; i++)
1943 		if (line[i] == '\t')
1944 			num_tabs++;
1945 
1946 	if (num_tabs == 0)
1947 		return line;
1948 
1949 	/*
1950 	 * Space for the line and '\0', less the leading and trailing
1951 	 * spaces. Each tab may introduce 7 additional spaces.
1952 	 */
1953 	new_storage_len = line_len + 1 + (num_tabs * 7);
1954 
1955 	new_line = malloc(new_storage_len);
1956 	if (new_line == NULL) {
1957 		pr_err("Failure allocating memory for tab expansion\n");
1958 		return NULL;
1959 	}
1960 
1961 	/*
1962 	 * Copy regions starting at src and expand tabs. If there are two
1963 	 * adjacent tabs then 'src == i', the memcpy is of size 0 and the spaces
1964 	 * are inserted.
1965 	 */
1966 	for (i = 0, src = 0, dst = 0; i < line_len && num_tabs; i++) {
1967 		if (line[i] == '\t') {
1968 			len = i - src;
1969 			memcpy(&new_line[dst], &line[src], len);
1970 			dst += len;
1971 			new_line[dst++] = ' ';
1972 			while (dst % 8 != 0)
1973 				new_line[dst++] = ' ';
1974 			src = i + 1;
1975 			num_tabs--;
1976 		}
1977 	}
1978 
1979 	/* Expand the last region. */
1980 	len = line_len - src;
1981 	memcpy(&new_line[dst], &line[src], len);
1982 	dst += len;
1983 	new_line[dst] = '\0';
1984 
1985 	free(*storage);
1986 	*storage = new_line;
1987 	*storage_len = new_storage_len;
1988 	return new_line;
1989 
1990 }
1991 
1992 static int symbol__disassemble(struct symbol *sym, struct annotate_args *args)
1993 {
1994 	struct annotation_options *opts = args->options;
1995 	struct map *map = args->ms.map;
1996 	struct dso *dso = map__dso(map);
1997 	char *command;
1998 	FILE *file;
1999 	char symfs_filename[PATH_MAX];
2000 	struct kcore_extract kce;
2001 	bool delete_extract = false;
2002 	bool decomp = false;
2003 	int lineno = 0;
2004 	char *fileloc = NULL;
2005 	int nline;
2006 	char *line;
2007 	size_t line_len;
2008 	const char *objdump_argv[] = {
2009 		"/bin/sh",
2010 		"-c",
2011 		NULL, /* Will be the objdump command to run. */
2012 		"--",
2013 		NULL, /* Will be the symfs path. */
2014 		NULL,
2015 	};
2016 	struct child_process objdump_process;
2017 	int err = dso__disassemble_filename(dso, symfs_filename, sizeof(symfs_filename));
2018 
2019 	if (err)
2020 		return err;
2021 
2022 	pr_debug("%s: filename=%s, sym=%s, start=%#" PRIx64 ", end=%#" PRIx64 "\n", __func__,
2023 		 symfs_filename, sym->name, map__unmap_ip(map, sym->start),
2024 		 map__unmap_ip(map, sym->end));
2025 
2026 	pr_debug("annotating [%p] %30s : [%p] %30s\n",
2027 		 dso, dso->long_name, sym, sym->name);
2028 
2029 	if (dso->binary_type == DSO_BINARY_TYPE__BPF_PROG_INFO) {
2030 		return symbol__disassemble_bpf(sym, args);
2031 	} else if (dso->binary_type == DSO_BINARY_TYPE__BPF_IMAGE) {
2032 		return symbol__disassemble_bpf_image(sym, args);
2033 	} else if (dso__is_kcore(dso)) {
2034 		kce.kcore_filename = symfs_filename;
2035 		kce.addr = map__rip_2objdump(map, sym->start);
2036 		kce.offs = sym->start;
2037 		kce.len = sym->end - sym->start;
2038 		if (!kcore_extract__create(&kce)) {
2039 			delete_extract = true;
2040 			strlcpy(symfs_filename, kce.extract_filename,
2041 				sizeof(symfs_filename));
2042 		}
2043 	} else if (dso__needs_decompress(dso)) {
2044 		char tmp[KMOD_DECOMP_LEN];
2045 
2046 		if (dso__decompress_kmodule_path(dso, symfs_filename,
2047 						 tmp, sizeof(tmp)) < 0)
2048 			return -1;
2049 
2050 		decomp = true;
2051 		strcpy(symfs_filename, tmp);
2052 	}
2053 
2054 	err = asprintf(&command,
2055 		 "%s %s%s --start-address=0x%016" PRIx64
2056 		 " --stop-address=0x%016" PRIx64
2057 		 " -l -d %s %s %s %c%s%c %s%s -C \"$1\"",
2058 		 opts->objdump_path ?: "objdump",
2059 		 opts->disassembler_style ? "-M " : "",
2060 		 opts->disassembler_style ?: "",
2061 		 map__rip_2objdump(map, sym->start),
2062 		 map__rip_2objdump(map, sym->end),
2063 		 opts->show_asm_raw ? "" : "--no-show-raw-insn",
2064 		 opts->annotate_src ? "-S" : "",
2065 		 opts->prefix ? "--prefix " : "",
2066 		 opts->prefix ? '"' : ' ',
2067 		 opts->prefix ?: "",
2068 		 opts->prefix ? '"' : ' ',
2069 		 opts->prefix_strip ? "--prefix-strip=" : "",
2070 		 opts->prefix_strip ?: "");
2071 
2072 	if (err < 0) {
2073 		pr_err("Failure allocating memory for the command to run\n");
2074 		goto out_remove_tmp;
2075 	}
2076 
2077 	pr_debug("Executing: %s\n", command);
2078 
2079 	objdump_argv[2] = command;
2080 	objdump_argv[4] = symfs_filename;
2081 
2082 	/* Create a pipe to read from for stdout */
2083 	memset(&objdump_process, 0, sizeof(objdump_process));
2084 	objdump_process.argv = objdump_argv;
2085 	objdump_process.out = -1;
2086 	objdump_process.err = -1;
2087 	objdump_process.no_stderr = 1;
2088 	if (start_command(&objdump_process)) {
2089 		pr_err("Failure starting to run %s\n", command);
2090 		err = -1;
2091 		goto out_free_command;
2092 	}
2093 
2094 	file = fdopen(objdump_process.out, "r");
2095 	if (!file) {
2096 		pr_err("Failure creating FILE stream for %s\n", command);
2097 		/*
2098 		 * If we were using debug info should retry with
2099 		 * original binary.
2100 		 */
2101 		err = -1;
2102 		goto out_close_stdout;
2103 	}
2104 
2105 	/* Storage for getline. */
2106 	line = NULL;
2107 	line_len = 0;
2108 
2109 	nline = 0;
2110 	while (!feof(file)) {
2111 		const char *match;
2112 		char *expanded_line;
2113 
2114 		if (getline(&line, &line_len, file) < 0 || !line)
2115 			break;
2116 
2117 		/* Skip lines containing "filename:" */
2118 		match = strstr(line, symfs_filename);
2119 		if (match && match[strlen(symfs_filename)] == ':')
2120 			continue;
2121 
2122 		expanded_line = strim(line);
2123 		expanded_line = expand_tabs(expanded_line, &line, &line_len);
2124 		if (!expanded_line)
2125 			break;
2126 
2127 		/*
2128 		 * The source code line number (lineno) needs to be kept in
2129 		 * across calls to symbol__parse_objdump_line(), so that it
2130 		 * can associate it with the instructions till the next one.
2131 		 * See disasm_line__new() and struct disasm_line::line_nr.
2132 		 */
2133 		if (symbol__parse_objdump_line(sym, args, expanded_line,
2134 					       &lineno, &fileloc) < 0)
2135 			break;
2136 		nline++;
2137 	}
2138 	free(line);
2139 	free(fileloc);
2140 
2141 	err = finish_command(&objdump_process);
2142 	if (err)
2143 		pr_err("Error running %s\n", command);
2144 
2145 	if (nline == 0) {
2146 		err = -1;
2147 		pr_err("No output from %s\n", command);
2148 	}
2149 
2150 	/*
2151 	 * kallsyms does not have symbol sizes so there may a nop at the end.
2152 	 * Remove it.
2153 	 */
2154 	if (dso__is_kcore(dso))
2155 		delete_last_nop(sym);
2156 
2157 	fclose(file);
2158 
2159 out_close_stdout:
2160 	close(objdump_process.out);
2161 
2162 out_free_command:
2163 	free(command);
2164 
2165 out_remove_tmp:
2166 	if (decomp)
2167 		unlink(symfs_filename);
2168 
2169 	if (delete_extract)
2170 		kcore_extract__delete(&kce);
2171 
2172 	return err;
2173 }
2174 
2175 static void calc_percent(struct sym_hist *sym_hist,
2176 			 struct hists *hists,
2177 			 struct annotation_data *data,
2178 			 s64 offset, s64 end)
2179 {
2180 	unsigned int hits = 0;
2181 	u64 period = 0;
2182 
2183 	while (offset < end) {
2184 		hits   += sym_hist->addr[offset].nr_samples;
2185 		period += sym_hist->addr[offset].period;
2186 		++offset;
2187 	}
2188 
2189 	if (sym_hist->nr_samples) {
2190 		data->he.period     = period;
2191 		data->he.nr_samples = hits;
2192 		data->percent[PERCENT_HITS_LOCAL] = 100.0 * hits / sym_hist->nr_samples;
2193 	}
2194 
2195 	if (hists->stats.nr_non_filtered_samples)
2196 		data->percent[PERCENT_HITS_GLOBAL] = 100.0 * hits / hists->stats.nr_non_filtered_samples;
2197 
2198 	if (sym_hist->period)
2199 		data->percent[PERCENT_PERIOD_LOCAL] = 100.0 * period / sym_hist->period;
2200 
2201 	if (hists->stats.total_period)
2202 		data->percent[PERCENT_PERIOD_GLOBAL] = 100.0 * period / hists->stats.total_period;
2203 }
2204 
2205 static void annotation__calc_percent(struct annotation *notes,
2206 				     struct evsel *leader, s64 len)
2207 {
2208 	struct annotation_line *al, *next;
2209 	struct evsel *evsel;
2210 
2211 	list_for_each_entry(al, &notes->src->source, node) {
2212 		s64 end;
2213 		int i = 0;
2214 
2215 		if (al->offset == -1)
2216 			continue;
2217 
2218 		next = annotation_line__next(al, &notes->src->source);
2219 		end  = next ? next->offset : len;
2220 
2221 		for_each_group_evsel(evsel, leader) {
2222 			struct hists *hists = evsel__hists(evsel);
2223 			struct annotation_data *data;
2224 			struct sym_hist *sym_hist;
2225 
2226 			BUG_ON(i >= al->data_nr);
2227 
2228 			sym_hist = annotation__histogram(notes, evsel->core.idx);
2229 			data = &al->data[i++];
2230 
2231 			calc_percent(sym_hist, hists, data, al->offset, end);
2232 		}
2233 	}
2234 }
2235 
2236 void symbol__calc_percent(struct symbol *sym, struct evsel *evsel)
2237 {
2238 	struct annotation *notes = symbol__annotation(sym);
2239 
2240 	annotation__calc_percent(notes, evsel, symbol__size(sym));
2241 }
2242 
2243 int symbol__annotate(struct map_symbol *ms, struct evsel *evsel,
2244 		     struct annotation_options *options, struct arch **parch)
2245 {
2246 	struct symbol *sym = ms->sym;
2247 	struct annotation *notes = symbol__annotation(sym);
2248 	struct annotate_args args = {
2249 		.evsel		= evsel,
2250 		.options	= options,
2251 	};
2252 	struct perf_env *env = evsel__env(evsel);
2253 	const char *arch_name = perf_env__arch(env);
2254 	struct arch *arch;
2255 	int err;
2256 
2257 	if (!arch_name)
2258 		return errno;
2259 
2260 	args.arch = arch = arch__find(arch_name);
2261 	if (arch == NULL) {
2262 		pr_err("%s: unsupported arch %s\n", __func__, arch_name);
2263 		return ENOTSUP;
2264 	}
2265 
2266 	if (parch)
2267 		*parch = arch;
2268 
2269 	if (arch->init) {
2270 		err = arch->init(arch, env ? env->cpuid : NULL);
2271 		if (err) {
2272 			pr_err("%s: failed to initialize %s arch priv area\n", __func__, arch->name);
2273 			return err;
2274 		}
2275 	}
2276 
2277 	args.ms = *ms;
2278 	if (notes->options && notes->options->full_addr)
2279 		notes->start = map__objdump_2mem(ms->map, ms->sym->start);
2280 	else
2281 		notes->start = map__rip_2objdump(ms->map, ms->sym->start);
2282 
2283 	return symbol__disassemble(sym, &args);
2284 }
2285 
2286 static void insert_source_line(struct rb_root *root, struct annotation_line *al,
2287 			       struct annotation_options *opts)
2288 {
2289 	struct annotation_line *iter;
2290 	struct rb_node **p = &root->rb_node;
2291 	struct rb_node *parent = NULL;
2292 	int i, ret;
2293 
2294 	while (*p != NULL) {
2295 		parent = *p;
2296 		iter = rb_entry(parent, struct annotation_line, rb_node);
2297 
2298 		ret = strcmp(iter->path, al->path);
2299 		if (ret == 0) {
2300 			for (i = 0; i < al->data_nr; i++) {
2301 				iter->data[i].percent_sum += annotation_data__percent(&al->data[i],
2302 										      opts->percent_type);
2303 			}
2304 			return;
2305 		}
2306 
2307 		if (ret < 0)
2308 			p = &(*p)->rb_left;
2309 		else
2310 			p = &(*p)->rb_right;
2311 	}
2312 
2313 	for (i = 0; i < al->data_nr; i++) {
2314 		al->data[i].percent_sum = annotation_data__percent(&al->data[i],
2315 								   opts->percent_type);
2316 	}
2317 
2318 	rb_link_node(&al->rb_node, parent, p);
2319 	rb_insert_color(&al->rb_node, root);
2320 }
2321 
2322 static int cmp_source_line(struct annotation_line *a, struct annotation_line *b)
2323 {
2324 	int i;
2325 
2326 	for (i = 0; i < a->data_nr; i++) {
2327 		if (a->data[i].percent_sum == b->data[i].percent_sum)
2328 			continue;
2329 		return a->data[i].percent_sum > b->data[i].percent_sum;
2330 	}
2331 
2332 	return 0;
2333 }
2334 
2335 static void __resort_source_line(struct rb_root *root, struct annotation_line *al)
2336 {
2337 	struct annotation_line *iter;
2338 	struct rb_node **p = &root->rb_node;
2339 	struct rb_node *parent = NULL;
2340 
2341 	while (*p != NULL) {
2342 		parent = *p;
2343 		iter = rb_entry(parent, struct annotation_line, rb_node);
2344 
2345 		if (cmp_source_line(al, iter))
2346 			p = &(*p)->rb_left;
2347 		else
2348 			p = &(*p)->rb_right;
2349 	}
2350 
2351 	rb_link_node(&al->rb_node, parent, p);
2352 	rb_insert_color(&al->rb_node, root);
2353 }
2354 
2355 static void resort_source_line(struct rb_root *dest_root, struct rb_root *src_root)
2356 {
2357 	struct annotation_line *al;
2358 	struct rb_node *node;
2359 
2360 	node = rb_first(src_root);
2361 	while (node) {
2362 		struct rb_node *next;
2363 
2364 		al = rb_entry(node, struct annotation_line, rb_node);
2365 		next = rb_next(node);
2366 		rb_erase(node, src_root);
2367 
2368 		__resort_source_line(dest_root, al);
2369 		node = next;
2370 	}
2371 }
2372 
2373 static void print_summary(struct rb_root *root, const char *filename)
2374 {
2375 	struct annotation_line *al;
2376 	struct rb_node *node;
2377 
2378 	printf("\nSorted summary for file %s\n", filename);
2379 	printf("----------------------------------------------\n\n");
2380 
2381 	if (RB_EMPTY_ROOT(root)) {
2382 		printf(" Nothing higher than %1.1f%%\n", MIN_GREEN);
2383 		return;
2384 	}
2385 
2386 	node = rb_first(root);
2387 	while (node) {
2388 		double percent, percent_max = 0.0;
2389 		const char *color;
2390 		char *path;
2391 		int i;
2392 
2393 		al = rb_entry(node, struct annotation_line, rb_node);
2394 		for (i = 0; i < al->data_nr; i++) {
2395 			percent = al->data[i].percent_sum;
2396 			color = get_percent_color(percent);
2397 			color_fprintf(stdout, color, " %7.2f", percent);
2398 
2399 			if (percent > percent_max)
2400 				percent_max = percent;
2401 		}
2402 
2403 		path = al->path;
2404 		color = get_percent_color(percent_max);
2405 		color_fprintf(stdout, color, " %s\n", path);
2406 
2407 		node = rb_next(node);
2408 	}
2409 }
2410 
2411 static void symbol__annotate_hits(struct symbol *sym, struct evsel *evsel)
2412 {
2413 	struct annotation *notes = symbol__annotation(sym);
2414 	struct sym_hist *h = annotation__histogram(notes, evsel->core.idx);
2415 	u64 len = symbol__size(sym), offset;
2416 
2417 	for (offset = 0; offset < len; ++offset)
2418 		if (h->addr[offset].nr_samples != 0)
2419 			printf("%*" PRIx64 ": %" PRIu64 "\n", BITS_PER_LONG / 2,
2420 			       sym->start + offset, h->addr[offset].nr_samples);
2421 	printf("%*s: %" PRIu64 "\n", BITS_PER_LONG / 2, "h->nr_samples", h->nr_samples);
2422 }
2423 
2424 static int annotated_source__addr_fmt_width(struct list_head *lines, u64 start)
2425 {
2426 	char bf[32];
2427 	struct annotation_line *line;
2428 
2429 	list_for_each_entry_reverse(line, lines, node) {
2430 		if (line->offset != -1)
2431 			return scnprintf(bf, sizeof(bf), "%" PRIx64, start + line->offset);
2432 	}
2433 
2434 	return 0;
2435 }
2436 
2437 int symbol__annotate_printf(struct map_symbol *ms, struct evsel *evsel,
2438 			    struct annotation_options *opts)
2439 {
2440 	struct map *map = ms->map;
2441 	struct symbol *sym = ms->sym;
2442 	struct dso *dso = map__dso(map);
2443 	char *filename;
2444 	const char *d_filename;
2445 	const char *evsel_name = evsel__name(evsel);
2446 	struct annotation *notes = symbol__annotation(sym);
2447 	struct sym_hist *h = annotation__histogram(notes, evsel->core.idx);
2448 	struct annotation_line *pos, *queue = NULL;
2449 	u64 start = map__rip_2objdump(map, sym->start);
2450 	int printed = 2, queue_len = 0, addr_fmt_width;
2451 	int more = 0;
2452 	bool context = opts->context;
2453 	u64 len;
2454 	int width = symbol_conf.show_total_period ? 12 : 8;
2455 	int graph_dotted_len;
2456 	char buf[512];
2457 
2458 	filename = strdup(dso->long_name);
2459 	if (!filename)
2460 		return -ENOMEM;
2461 
2462 	if (opts->full_path)
2463 		d_filename = filename;
2464 	else
2465 		d_filename = basename(filename);
2466 
2467 	len = symbol__size(sym);
2468 
2469 	if (evsel__is_group_event(evsel)) {
2470 		width *= evsel->core.nr_members;
2471 		evsel__group_desc(evsel, buf, sizeof(buf));
2472 		evsel_name = buf;
2473 	}
2474 
2475 	graph_dotted_len = printf(" %-*.*s|	Source code & Disassembly of %s for %s (%" PRIu64 " samples, "
2476 				  "percent: %s)\n",
2477 				  width, width, symbol_conf.show_total_period ? "Period" :
2478 				  symbol_conf.show_nr_samples ? "Samples" : "Percent",
2479 				  d_filename, evsel_name, h->nr_samples,
2480 				  percent_type_str(opts->percent_type));
2481 
2482 	printf("%-*.*s----\n",
2483 	       graph_dotted_len, graph_dotted_len, graph_dotted_line);
2484 
2485 	if (verbose > 0)
2486 		symbol__annotate_hits(sym, evsel);
2487 
2488 	addr_fmt_width = annotated_source__addr_fmt_width(&notes->src->source, start);
2489 
2490 	list_for_each_entry(pos, &notes->src->source, node) {
2491 		int err;
2492 
2493 		if (context && queue == NULL) {
2494 			queue = pos;
2495 			queue_len = 0;
2496 		}
2497 
2498 		err = annotation_line__print(pos, sym, start, evsel, len,
2499 					     opts->min_pcnt, printed, opts->max_lines,
2500 					     queue, addr_fmt_width, opts->percent_type);
2501 
2502 		switch (err) {
2503 		case 0:
2504 			++printed;
2505 			if (context) {
2506 				printed += queue_len;
2507 				queue = NULL;
2508 				queue_len = 0;
2509 			}
2510 			break;
2511 		case 1:
2512 			/* filtered by max_lines */
2513 			++more;
2514 			break;
2515 		case -1:
2516 		default:
2517 			/*
2518 			 * Filtered by min_pcnt or non IP lines when
2519 			 * context != 0
2520 			 */
2521 			if (!context)
2522 				break;
2523 			if (queue_len == context)
2524 				queue = list_entry(queue->node.next, typeof(*queue), node);
2525 			else
2526 				++queue_len;
2527 			break;
2528 		}
2529 	}
2530 
2531 	free(filename);
2532 
2533 	return more;
2534 }
2535 
2536 static void FILE__set_percent_color(void *fp __maybe_unused,
2537 				    double percent __maybe_unused,
2538 				    bool current __maybe_unused)
2539 {
2540 }
2541 
2542 static int FILE__set_jumps_percent_color(void *fp __maybe_unused,
2543 					 int nr __maybe_unused, bool current __maybe_unused)
2544 {
2545 	return 0;
2546 }
2547 
2548 static int FILE__set_color(void *fp __maybe_unused, int color __maybe_unused)
2549 {
2550 	return 0;
2551 }
2552 
2553 static void FILE__printf(void *fp, const char *fmt, ...)
2554 {
2555 	va_list args;
2556 
2557 	va_start(args, fmt);
2558 	vfprintf(fp, fmt, args);
2559 	va_end(args);
2560 }
2561 
2562 static void FILE__write_graph(void *fp, int graph)
2563 {
2564 	const char *s;
2565 	switch (graph) {
2566 
2567 	case DARROW_CHAR: s = "↓"; break;
2568 	case UARROW_CHAR: s = "↑"; break;
2569 	case LARROW_CHAR: s = "←"; break;
2570 	case RARROW_CHAR: s = "→"; break;
2571 	default:		s = "?"; break;
2572 	}
2573 
2574 	fputs(s, fp);
2575 }
2576 
2577 static int symbol__annotate_fprintf2(struct symbol *sym, FILE *fp,
2578 				     struct annotation_options *opts)
2579 {
2580 	struct annotation *notes = symbol__annotation(sym);
2581 	struct annotation_write_ops wops = {
2582 		.first_line		 = true,
2583 		.obj			 = fp,
2584 		.set_color		 = FILE__set_color,
2585 		.set_percent_color	 = FILE__set_percent_color,
2586 		.set_jumps_percent_color = FILE__set_jumps_percent_color,
2587 		.printf			 = FILE__printf,
2588 		.write_graph		 = FILE__write_graph,
2589 	};
2590 	struct annotation_line *al;
2591 
2592 	list_for_each_entry(al, &notes->src->source, node) {
2593 		if (annotation_line__filter(al, notes))
2594 			continue;
2595 		annotation_line__write(al, notes, &wops, opts);
2596 		fputc('\n', fp);
2597 		wops.first_line = false;
2598 	}
2599 
2600 	return 0;
2601 }
2602 
2603 int map_symbol__annotation_dump(struct map_symbol *ms, struct evsel *evsel,
2604 				struct annotation_options *opts)
2605 {
2606 	const char *ev_name = evsel__name(evsel);
2607 	char buf[1024];
2608 	char *filename;
2609 	int err = -1;
2610 	FILE *fp;
2611 
2612 	if (asprintf(&filename, "%s.annotation", ms->sym->name) < 0)
2613 		return -1;
2614 
2615 	fp = fopen(filename, "w");
2616 	if (fp == NULL)
2617 		goto out_free_filename;
2618 
2619 	if (evsel__is_group_event(evsel)) {
2620 		evsel__group_desc(evsel, buf, sizeof(buf));
2621 		ev_name = buf;
2622 	}
2623 
2624 	fprintf(fp, "%s() %s\nEvent: %s\n\n",
2625 		ms->sym->name, map__dso(ms->map)->long_name, ev_name);
2626 	symbol__annotate_fprintf2(ms->sym, fp, opts);
2627 
2628 	fclose(fp);
2629 	err = 0;
2630 out_free_filename:
2631 	free(filename);
2632 	return err;
2633 }
2634 
2635 void symbol__annotate_zero_histogram(struct symbol *sym, int evidx)
2636 {
2637 	struct annotation *notes = symbol__annotation(sym);
2638 	struct sym_hist *h = annotation__histogram(notes, evidx);
2639 
2640 	memset(h, 0, notes->src->sizeof_sym_hist);
2641 }
2642 
2643 void symbol__annotate_decay_histogram(struct symbol *sym, int evidx)
2644 {
2645 	struct annotation *notes = symbol__annotation(sym);
2646 	struct sym_hist *h = annotation__histogram(notes, evidx);
2647 	int len = symbol__size(sym), offset;
2648 
2649 	h->nr_samples = 0;
2650 	for (offset = 0; offset < len; ++offset) {
2651 		h->addr[offset].nr_samples = h->addr[offset].nr_samples * 7 / 8;
2652 		h->nr_samples += h->addr[offset].nr_samples;
2653 	}
2654 }
2655 
2656 void annotated_source__purge(struct annotated_source *as)
2657 {
2658 	struct annotation_line *al, *n;
2659 
2660 	list_for_each_entry_safe(al, n, &as->source, node) {
2661 		list_del_init(&al->node);
2662 		disasm_line__free(disasm_line(al));
2663 	}
2664 }
2665 
2666 static size_t disasm_line__fprintf(struct disasm_line *dl, FILE *fp)
2667 {
2668 	size_t printed;
2669 
2670 	if (dl->al.offset == -1)
2671 		return fprintf(fp, "%s\n", dl->al.line);
2672 
2673 	printed = fprintf(fp, "%#" PRIx64 " %s", dl->al.offset, dl->ins.name);
2674 
2675 	if (dl->ops.raw[0] != '\0') {
2676 		printed += fprintf(fp, "%.*s %s\n", 6 - (int)printed, " ",
2677 				   dl->ops.raw);
2678 	}
2679 
2680 	return printed + fprintf(fp, "\n");
2681 }
2682 
2683 size_t disasm__fprintf(struct list_head *head, FILE *fp)
2684 {
2685 	struct disasm_line *pos;
2686 	size_t printed = 0;
2687 
2688 	list_for_each_entry(pos, head, al.node)
2689 		printed += disasm_line__fprintf(pos, fp);
2690 
2691 	return printed;
2692 }
2693 
2694 bool disasm_line__is_valid_local_jump(struct disasm_line *dl, struct symbol *sym)
2695 {
2696 	if (!dl || !dl->ins.ops || !ins__is_jump(&dl->ins) ||
2697 	    !disasm_line__has_local_offset(dl) || dl->ops.target.offset < 0 ||
2698 	    dl->ops.target.offset >= (s64)symbol__size(sym))
2699 		return false;
2700 
2701 	return true;
2702 }
2703 
2704 void annotation__mark_jump_targets(struct annotation *notes, struct symbol *sym)
2705 {
2706 	u64 offset, size = symbol__size(sym);
2707 
2708 	/* PLT symbols contain external offsets */
2709 	if (strstr(sym->name, "@plt"))
2710 		return;
2711 
2712 	for (offset = 0; offset < size; ++offset) {
2713 		struct annotation_line *al = notes->offsets[offset];
2714 		struct disasm_line *dl;
2715 
2716 		dl = disasm_line(al);
2717 
2718 		if (!disasm_line__is_valid_local_jump(dl, sym))
2719 			continue;
2720 
2721 		al = notes->offsets[dl->ops.target.offset];
2722 
2723 		/*
2724 		 * FIXME: Oops, no jump target? Buggy disassembler? Or do we
2725 		 * have to adjust to the previous offset?
2726 		 */
2727 		if (al == NULL)
2728 			continue;
2729 
2730 		if (++al->jump_sources > notes->max_jump_sources)
2731 			notes->max_jump_sources = al->jump_sources;
2732 	}
2733 }
2734 
2735 void annotation__set_offsets(struct annotation *notes, s64 size)
2736 {
2737 	struct annotation_line *al;
2738 
2739 	notes->max_line_len = 0;
2740 	notes->nr_entries = 0;
2741 	notes->nr_asm_entries = 0;
2742 
2743 	list_for_each_entry(al, &notes->src->source, node) {
2744 		size_t line_len = strlen(al->line);
2745 
2746 		if (notes->max_line_len < line_len)
2747 			notes->max_line_len = line_len;
2748 		al->idx = notes->nr_entries++;
2749 		if (al->offset != -1) {
2750 			al->idx_asm = notes->nr_asm_entries++;
2751 			/*
2752 			 * FIXME: short term bandaid to cope with assembly
2753 			 * routines that comes with labels in the same column
2754 			 * as the address in objdump, sigh.
2755 			 *
2756 			 * E.g. copy_user_generic_unrolled
2757  			 */
2758 			if (al->offset < size)
2759 				notes->offsets[al->offset] = al;
2760 		} else
2761 			al->idx_asm = -1;
2762 	}
2763 }
2764 
2765 static inline int width_jumps(int n)
2766 {
2767 	if (n >= 100)
2768 		return 5;
2769 	if (n / 10)
2770 		return 2;
2771 	return 1;
2772 }
2773 
2774 static int annotation__max_ins_name(struct annotation *notes)
2775 {
2776 	int max_name = 0, len;
2777 	struct annotation_line *al;
2778 
2779         list_for_each_entry(al, &notes->src->source, node) {
2780 		if (al->offset == -1)
2781 			continue;
2782 
2783 		len = strlen(disasm_line(al)->ins.name);
2784 		if (max_name < len)
2785 			max_name = len;
2786 	}
2787 
2788 	return max_name;
2789 }
2790 
2791 void annotation__init_column_widths(struct annotation *notes, struct symbol *sym)
2792 {
2793 	notes->widths.addr = notes->widths.target =
2794 		notes->widths.min_addr = hex_width(symbol__size(sym));
2795 	notes->widths.max_addr = hex_width(sym->end);
2796 	notes->widths.jumps = width_jumps(notes->max_jump_sources);
2797 	notes->widths.max_ins_name = annotation__max_ins_name(notes);
2798 }
2799 
2800 void annotation__update_column_widths(struct annotation *notes)
2801 {
2802 	if (notes->options->use_offset)
2803 		notes->widths.target = notes->widths.min_addr;
2804 	else if (notes->options->full_addr)
2805 		notes->widths.target = BITS_PER_LONG / 4;
2806 	else
2807 		notes->widths.target = notes->widths.max_addr;
2808 
2809 	notes->widths.addr = notes->widths.target;
2810 
2811 	if (notes->options->show_nr_jumps)
2812 		notes->widths.addr += notes->widths.jumps + 1;
2813 }
2814 
2815 void annotation__toggle_full_addr(struct annotation *notes, struct map_symbol *ms)
2816 {
2817 	notes->options->full_addr = !notes->options->full_addr;
2818 
2819 	if (notes->options->full_addr)
2820 		notes->start = map__objdump_2mem(ms->map, ms->sym->start);
2821 	else
2822 		notes->start = map__rip_2objdump(ms->map, ms->sym->start);
2823 
2824 	annotation__update_column_widths(notes);
2825 }
2826 
2827 static void annotation__calc_lines(struct annotation *notes, struct map *map,
2828 				   struct rb_root *root,
2829 				   struct annotation_options *opts)
2830 {
2831 	struct annotation_line *al;
2832 	struct rb_root tmp_root = RB_ROOT;
2833 
2834 	list_for_each_entry(al, &notes->src->source, node) {
2835 		double percent_max = 0.0;
2836 		int i;
2837 
2838 		for (i = 0; i < al->data_nr; i++) {
2839 			double percent;
2840 
2841 			percent = annotation_data__percent(&al->data[i],
2842 							   opts->percent_type);
2843 
2844 			if (percent > percent_max)
2845 				percent_max = percent;
2846 		}
2847 
2848 		if (percent_max <= 0.5)
2849 			continue;
2850 
2851 		al->path = get_srcline(map__dso(map), notes->start + al->offset, NULL,
2852 				       false, true, notes->start + al->offset);
2853 		insert_source_line(&tmp_root, al, opts);
2854 	}
2855 
2856 	resort_source_line(root, &tmp_root);
2857 }
2858 
2859 static void symbol__calc_lines(struct map_symbol *ms, struct rb_root *root,
2860 			       struct annotation_options *opts)
2861 {
2862 	struct annotation *notes = symbol__annotation(ms->sym);
2863 
2864 	annotation__calc_lines(notes, ms->map, root, opts);
2865 }
2866 
2867 int symbol__tty_annotate2(struct map_symbol *ms, struct evsel *evsel,
2868 			  struct annotation_options *opts)
2869 {
2870 	struct dso *dso = map__dso(ms->map);
2871 	struct symbol *sym = ms->sym;
2872 	struct rb_root source_line = RB_ROOT;
2873 	struct hists *hists = evsel__hists(evsel);
2874 	char buf[1024];
2875 	int err;
2876 
2877 	err = symbol__annotate2(ms, evsel, opts, NULL);
2878 	if (err) {
2879 		char msg[BUFSIZ];
2880 
2881 		dso->annotate_warned = true;
2882 		symbol__strerror_disassemble(ms, err, msg, sizeof(msg));
2883 		ui__error("Couldn't annotate %s:\n%s", sym->name, msg);
2884 		return -1;
2885 	}
2886 
2887 	if (opts->print_lines) {
2888 		srcline_full_filename = opts->full_path;
2889 		symbol__calc_lines(ms, &source_line, opts);
2890 		print_summary(&source_line, dso->long_name);
2891 	}
2892 
2893 	hists__scnprintf_title(hists, buf, sizeof(buf));
2894 	fprintf(stdout, "%s, [percent: %s]\n%s() %s\n",
2895 		buf, percent_type_str(opts->percent_type), sym->name, dso->long_name);
2896 	symbol__annotate_fprintf2(sym, stdout, opts);
2897 
2898 	annotated_source__purge(symbol__annotation(sym)->src);
2899 
2900 	return 0;
2901 }
2902 
2903 int symbol__tty_annotate(struct map_symbol *ms, struct evsel *evsel,
2904 			 struct annotation_options *opts)
2905 {
2906 	struct dso *dso = map__dso(ms->map);
2907 	struct symbol *sym = ms->sym;
2908 	struct rb_root source_line = RB_ROOT;
2909 	int err;
2910 
2911 	err = symbol__annotate(ms, evsel, opts, NULL);
2912 	if (err) {
2913 		char msg[BUFSIZ];
2914 
2915 		dso->annotate_warned = true;
2916 		symbol__strerror_disassemble(ms, err, msg, sizeof(msg));
2917 		ui__error("Couldn't annotate %s:\n%s", sym->name, msg);
2918 		return -1;
2919 	}
2920 
2921 	symbol__calc_percent(sym, evsel);
2922 
2923 	if (opts->print_lines) {
2924 		srcline_full_filename = opts->full_path;
2925 		symbol__calc_lines(ms, &source_line, opts);
2926 		print_summary(&source_line, dso->long_name);
2927 	}
2928 
2929 	symbol__annotate_printf(ms, evsel, opts);
2930 
2931 	annotated_source__purge(symbol__annotation(sym)->src);
2932 
2933 	return 0;
2934 }
2935 
2936 bool ui__has_annotation(void)
2937 {
2938 	return use_browser == 1 && perf_hpp_list.sym;
2939 }
2940 
2941 
2942 static double annotation_line__max_percent(struct annotation_line *al,
2943 					   struct annotation *notes,
2944 					   unsigned int percent_type)
2945 {
2946 	double percent_max = 0.0;
2947 	int i;
2948 
2949 	for (i = 0; i < notes->nr_events; i++) {
2950 		double percent;
2951 
2952 		percent = annotation_data__percent(&al->data[i],
2953 						   percent_type);
2954 
2955 		if (percent > percent_max)
2956 			percent_max = percent;
2957 	}
2958 
2959 	return percent_max;
2960 }
2961 
2962 static void disasm_line__write(struct disasm_line *dl, struct annotation *notes,
2963 			       void *obj, char *bf, size_t size,
2964 			       void (*obj__printf)(void *obj, const char *fmt, ...),
2965 			       void (*obj__write_graph)(void *obj, int graph))
2966 {
2967 	if (dl->ins.ops && dl->ins.ops->scnprintf) {
2968 		if (ins__is_jump(&dl->ins)) {
2969 			bool fwd;
2970 
2971 			if (dl->ops.target.outside)
2972 				goto call_like;
2973 			fwd = dl->ops.target.offset > dl->al.offset;
2974 			obj__write_graph(obj, fwd ? DARROW_CHAR : UARROW_CHAR);
2975 			obj__printf(obj, " ");
2976 		} else if (ins__is_call(&dl->ins)) {
2977 call_like:
2978 			obj__write_graph(obj, RARROW_CHAR);
2979 			obj__printf(obj, " ");
2980 		} else if (ins__is_ret(&dl->ins)) {
2981 			obj__write_graph(obj, LARROW_CHAR);
2982 			obj__printf(obj, " ");
2983 		} else {
2984 			obj__printf(obj, "  ");
2985 		}
2986 	} else {
2987 		obj__printf(obj, "  ");
2988 	}
2989 
2990 	disasm_line__scnprintf(dl, bf, size, !notes->options->use_offset, notes->widths.max_ins_name);
2991 }
2992 
2993 static void ipc_coverage_string(char *bf, int size, struct annotation *notes)
2994 {
2995 	double ipc = 0.0, coverage = 0.0;
2996 
2997 	if (notes->hit_cycles)
2998 		ipc = notes->hit_insn / ((double)notes->hit_cycles);
2999 
3000 	if (notes->total_insn) {
3001 		coverage = notes->cover_insn * 100.0 /
3002 			((double)notes->total_insn);
3003 	}
3004 
3005 	scnprintf(bf, size, "(Average IPC: %.2f, IPC Coverage: %.1f%%)",
3006 		  ipc, coverage);
3007 }
3008 
3009 static void __annotation_line__write(struct annotation_line *al, struct annotation *notes,
3010 				     bool first_line, bool current_entry, bool change_color, int width,
3011 				     void *obj, unsigned int percent_type,
3012 				     int  (*obj__set_color)(void *obj, int color),
3013 				     void (*obj__set_percent_color)(void *obj, double percent, bool current),
3014 				     int  (*obj__set_jumps_percent_color)(void *obj, int nr, bool current),
3015 				     void (*obj__printf)(void *obj, const char *fmt, ...),
3016 				     void (*obj__write_graph)(void *obj, int graph))
3017 
3018 {
3019 	double percent_max = annotation_line__max_percent(al, notes, percent_type);
3020 	int pcnt_width = annotation__pcnt_width(notes),
3021 	    cycles_width = annotation__cycles_width(notes);
3022 	bool show_title = false;
3023 	char bf[256];
3024 	int printed;
3025 
3026 	if (first_line && (al->offset == -1 || percent_max == 0.0)) {
3027 		if (notes->have_cycles) {
3028 			if (al->ipc == 0.0 && al->cycles == 0)
3029 				show_title = true;
3030 		} else
3031 			show_title = true;
3032 	}
3033 
3034 	if (al->offset != -1 && percent_max != 0.0) {
3035 		int i;
3036 
3037 		for (i = 0; i < notes->nr_events; i++) {
3038 			double percent;
3039 
3040 			percent = annotation_data__percent(&al->data[i], percent_type);
3041 
3042 			obj__set_percent_color(obj, percent, current_entry);
3043 			if (symbol_conf.show_total_period) {
3044 				obj__printf(obj, "%11" PRIu64 " ", al->data[i].he.period);
3045 			} else if (symbol_conf.show_nr_samples) {
3046 				obj__printf(obj, "%6" PRIu64 " ",
3047 						   al->data[i].he.nr_samples);
3048 			} else {
3049 				obj__printf(obj, "%6.2f ", percent);
3050 			}
3051 		}
3052 	} else {
3053 		obj__set_percent_color(obj, 0, current_entry);
3054 
3055 		if (!show_title)
3056 			obj__printf(obj, "%-*s", pcnt_width, " ");
3057 		else {
3058 			obj__printf(obj, "%-*s", pcnt_width,
3059 					   symbol_conf.show_total_period ? "Period" :
3060 					   symbol_conf.show_nr_samples ? "Samples" : "Percent");
3061 		}
3062 	}
3063 
3064 	if (notes->have_cycles) {
3065 		if (al->ipc)
3066 			obj__printf(obj, "%*.2f ", ANNOTATION__IPC_WIDTH - 1, al->ipc);
3067 		else if (!show_title)
3068 			obj__printf(obj, "%*s", ANNOTATION__IPC_WIDTH, " ");
3069 		else
3070 			obj__printf(obj, "%*s ", ANNOTATION__IPC_WIDTH - 1, "IPC");
3071 
3072 		if (!notes->options->show_minmax_cycle) {
3073 			if (al->cycles)
3074 				obj__printf(obj, "%*" PRIu64 " ",
3075 					   ANNOTATION__CYCLES_WIDTH - 1, al->cycles);
3076 			else if (!show_title)
3077 				obj__printf(obj, "%*s",
3078 					    ANNOTATION__CYCLES_WIDTH, " ");
3079 			else
3080 				obj__printf(obj, "%*s ",
3081 					    ANNOTATION__CYCLES_WIDTH - 1,
3082 					    "Cycle");
3083 		} else {
3084 			if (al->cycles) {
3085 				char str[32];
3086 
3087 				scnprintf(str, sizeof(str),
3088 					"%" PRIu64 "(%" PRIu64 "/%" PRIu64 ")",
3089 					al->cycles, al->cycles_min,
3090 					al->cycles_max);
3091 
3092 				obj__printf(obj, "%*s ",
3093 					    ANNOTATION__MINMAX_CYCLES_WIDTH - 1,
3094 					    str);
3095 			} else if (!show_title)
3096 				obj__printf(obj, "%*s",
3097 					    ANNOTATION__MINMAX_CYCLES_WIDTH,
3098 					    " ");
3099 			else
3100 				obj__printf(obj, "%*s ",
3101 					    ANNOTATION__MINMAX_CYCLES_WIDTH - 1,
3102 					    "Cycle(min/max)");
3103 		}
3104 
3105 		if (show_title && !*al->line) {
3106 			ipc_coverage_string(bf, sizeof(bf), notes);
3107 			obj__printf(obj, "%*s", ANNOTATION__AVG_IPC_WIDTH, bf);
3108 		}
3109 	}
3110 
3111 	obj__printf(obj, " ");
3112 
3113 	if (!*al->line)
3114 		obj__printf(obj, "%-*s", width - pcnt_width - cycles_width, " ");
3115 	else if (al->offset == -1) {
3116 		if (al->line_nr && notes->options->show_linenr)
3117 			printed = scnprintf(bf, sizeof(bf), "%-*d ", notes->widths.addr + 1, al->line_nr);
3118 		else
3119 			printed = scnprintf(bf, sizeof(bf), "%-*s  ", notes->widths.addr, " ");
3120 		obj__printf(obj, bf);
3121 		obj__printf(obj, "%-*s", width - printed - pcnt_width - cycles_width + 1, al->line);
3122 	} else {
3123 		u64 addr = al->offset;
3124 		int color = -1;
3125 
3126 		if (!notes->options->use_offset)
3127 			addr += notes->start;
3128 
3129 		if (!notes->options->use_offset) {
3130 			printed = scnprintf(bf, sizeof(bf), "%" PRIx64 ": ", addr);
3131 		} else {
3132 			if (al->jump_sources &&
3133 			    notes->options->offset_level >= ANNOTATION__OFFSET_JUMP_TARGETS) {
3134 				if (notes->options->show_nr_jumps) {
3135 					int prev;
3136 					printed = scnprintf(bf, sizeof(bf), "%*d ",
3137 							    notes->widths.jumps,
3138 							    al->jump_sources);
3139 					prev = obj__set_jumps_percent_color(obj, al->jump_sources,
3140 									    current_entry);
3141 					obj__printf(obj, bf);
3142 					obj__set_color(obj, prev);
3143 				}
3144 print_addr:
3145 				printed = scnprintf(bf, sizeof(bf), "%*" PRIx64 ": ",
3146 						    notes->widths.target, addr);
3147 			} else if (ins__is_call(&disasm_line(al)->ins) &&
3148 				   notes->options->offset_level >= ANNOTATION__OFFSET_CALL) {
3149 				goto print_addr;
3150 			} else if (notes->options->offset_level == ANNOTATION__MAX_OFFSET_LEVEL) {
3151 				goto print_addr;
3152 			} else {
3153 				printed = scnprintf(bf, sizeof(bf), "%-*s  ",
3154 						    notes->widths.addr, " ");
3155 			}
3156 		}
3157 
3158 		if (change_color)
3159 			color = obj__set_color(obj, HE_COLORSET_ADDR);
3160 		obj__printf(obj, bf);
3161 		if (change_color)
3162 			obj__set_color(obj, color);
3163 
3164 		disasm_line__write(disasm_line(al), notes, obj, bf, sizeof(bf), obj__printf, obj__write_graph);
3165 
3166 		obj__printf(obj, "%-*s", width - pcnt_width - cycles_width - 3 - printed, bf);
3167 	}
3168 
3169 }
3170 
3171 void annotation_line__write(struct annotation_line *al, struct annotation *notes,
3172 			    struct annotation_write_ops *wops,
3173 			    struct annotation_options *opts)
3174 {
3175 	__annotation_line__write(al, notes, wops->first_line, wops->current_entry,
3176 				 wops->change_color, wops->width, wops->obj,
3177 				 opts->percent_type,
3178 				 wops->set_color, wops->set_percent_color,
3179 				 wops->set_jumps_percent_color, wops->printf,
3180 				 wops->write_graph);
3181 }
3182 
3183 int symbol__annotate2(struct map_symbol *ms, struct evsel *evsel,
3184 		      struct annotation_options *options, struct arch **parch)
3185 {
3186 	struct symbol *sym = ms->sym;
3187 	struct annotation *notes = symbol__annotation(sym);
3188 	size_t size = symbol__size(sym);
3189 	int nr_pcnt = 1, err;
3190 
3191 	notes->offsets = zalloc(size * sizeof(struct annotation_line *));
3192 	if (notes->offsets == NULL)
3193 		return ENOMEM;
3194 
3195 	if (evsel__is_group_event(evsel))
3196 		nr_pcnt = evsel->core.nr_members;
3197 
3198 	err = symbol__annotate(ms, evsel, options, parch);
3199 	if (err)
3200 		goto out_free_offsets;
3201 
3202 	notes->options = options;
3203 
3204 	symbol__calc_percent(sym, evsel);
3205 
3206 	annotation__set_offsets(notes, size);
3207 	annotation__mark_jump_targets(notes, sym);
3208 	annotation__compute_ipc(notes, size);
3209 	annotation__init_column_widths(notes, sym);
3210 	notes->nr_events = nr_pcnt;
3211 
3212 	annotation__update_column_widths(notes);
3213 	sym->annotate2 = 1;
3214 
3215 	return 0;
3216 
3217 out_free_offsets:
3218 	zfree(&notes->offsets);
3219 	return err;
3220 }
3221 
3222 static int annotation__config(const char *var, const char *value, void *data)
3223 {
3224 	struct annotation_options *opt = data;
3225 
3226 	if (!strstarts(var, "annotate."))
3227 		return 0;
3228 
3229 	if (!strcmp(var, "annotate.offset_level")) {
3230 		perf_config_u8(&opt->offset_level, "offset_level", value);
3231 
3232 		if (opt->offset_level > ANNOTATION__MAX_OFFSET_LEVEL)
3233 			opt->offset_level = ANNOTATION__MAX_OFFSET_LEVEL;
3234 		else if (opt->offset_level < ANNOTATION__MIN_OFFSET_LEVEL)
3235 			opt->offset_level = ANNOTATION__MIN_OFFSET_LEVEL;
3236 	} else if (!strcmp(var, "annotate.hide_src_code")) {
3237 		opt->hide_src_code = perf_config_bool("hide_src_code", value);
3238 	} else if (!strcmp(var, "annotate.jump_arrows")) {
3239 		opt->jump_arrows = perf_config_bool("jump_arrows", value);
3240 	} else if (!strcmp(var, "annotate.show_linenr")) {
3241 		opt->show_linenr = perf_config_bool("show_linenr", value);
3242 	} else if (!strcmp(var, "annotate.show_nr_jumps")) {
3243 		opt->show_nr_jumps = perf_config_bool("show_nr_jumps", value);
3244 	} else if (!strcmp(var, "annotate.show_nr_samples")) {
3245 		symbol_conf.show_nr_samples = perf_config_bool("show_nr_samples",
3246 								value);
3247 	} else if (!strcmp(var, "annotate.show_total_period")) {
3248 		symbol_conf.show_total_period = perf_config_bool("show_total_period",
3249 								value);
3250 	} else if (!strcmp(var, "annotate.use_offset")) {
3251 		opt->use_offset = perf_config_bool("use_offset", value);
3252 	} else if (!strcmp(var, "annotate.disassembler_style")) {
3253 		opt->disassembler_style = strdup(value);
3254 		if (!opt->disassembler_style) {
3255 			pr_err("Not enough memory for annotate.disassembler_style\n");
3256 			return -1;
3257 		}
3258 	} else if (!strcmp(var, "annotate.objdump")) {
3259 		opt->objdump_path = strdup(value);
3260 		if (!opt->objdump_path) {
3261 			pr_err("Not enough memory for annotate.objdump\n");
3262 			return -1;
3263 		}
3264 	} else if (!strcmp(var, "annotate.addr2line")) {
3265 		symbol_conf.addr2line_path = strdup(value);
3266 		if (!symbol_conf.addr2line_path) {
3267 			pr_err("Not enough memory for annotate.addr2line\n");
3268 			return -1;
3269 		}
3270 	} else if (!strcmp(var, "annotate.demangle")) {
3271 		symbol_conf.demangle = perf_config_bool("demangle", value);
3272 	} else if (!strcmp(var, "annotate.demangle_kernel")) {
3273 		symbol_conf.demangle_kernel = perf_config_bool("demangle_kernel", value);
3274 	} else {
3275 		pr_debug("%s variable unknown, ignoring...", var);
3276 	}
3277 
3278 	return 0;
3279 }
3280 
3281 void annotation_options__init(struct annotation_options *opt)
3282 {
3283 	memset(opt, 0, sizeof(*opt));
3284 
3285 	/* Default values. */
3286 	opt->use_offset = true;
3287 	opt->jump_arrows = true;
3288 	opt->annotate_src = true;
3289 	opt->offset_level = ANNOTATION__OFFSET_JUMP_TARGETS;
3290 	opt->percent_type = PERCENT_PERIOD_LOCAL;
3291 }
3292 
3293 
3294 void annotation_options__exit(struct annotation_options *opt)
3295 {
3296 	zfree(&opt->disassembler_style);
3297 	zfree(&opt->objdump_path);
3298 }
3299 
3300 void annotation_config__init(struct annotation_options *opt)
3301 {
3302 	perf_config(annotation__config, opt);
3303 }
3304 
3305 static unsigned int parse_percent_type(char *str1, char *str2)
3306 {
3307 	unsigned int type = (unsigned int) -1;
3308 
3309 	if (!strcmp("period", str1)) {
3310 		if (!strcmp("local", str2))
3311 			type = PERCENT_PERIOD_LOCAL;
3312 		else if (!strcmp("global", str2))
3313 			type = PERCENT_PERIOD_GLOBAL;
3314 	}
3315 
3316 	if (!strcmp("hits", str1)) {
3317 		if (!strcmp("local", str2))
3318 			type = PERCENT_HITS_LOCAL;
3319 		else if (!strcmp("global", str2))
3320 			type = PERCENT_HITS_GLOBAL;
3321 	}
3322 
3323 	return type;
3324 }
3325 
3326 int annotate_parse_percent_type(const struct option *opt, const char *_str,
3327 				int unset __maybe_unused)
3328 {
3329 	struct annotation_options *opts = opt->value;
3330 	unsigned int type;
3331 	char *str1, *str2;
3332 	int err = -1;
3333 
3334 	str1 = strdup(_str);
3335 	if (!str1)
3336 		return -ENOMEM;
3337 
3338 	str2 = strchr(str1, '-');
3339 	if (!str2)
3340 		goto out;
3341 
3342 	*str2++ = 0;
3343 
3344 	type = parse_percent_type(str1, str2);
3345 	if (type == (unsigned int) -1)
3346 		type = parse_percent_type(str2, str1);
3347 	if (type != (unsigned int) -1) {
3348 		opts->percent_type = type;
3349 		err = 0;
3350 	}
3351 
3352 out:
3353 	free(str1);
3354 	return err;
3355 }
3356 
3357 int annotate_check_args(struct annotation_options *args)
3358 {
3359 	if (args->prefix_strip && !args->prefix) {
3360 		pr_err("--prefix-strip requires --prefix\n");
3361 		return -1;
3362 	}
3363 	return 0;
3364 }
3365