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