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