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