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