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