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