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