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