xref: /linux/tools/perf/util/annotate.c (revision 6b718ac6874c2233b8dec369a8a377d6c5b638e6)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
4  *
5  * Parts came from builtin-annotate.c, see those files for further
6  * copyright notes.
7  */
8 
9 #include <errno.h>
10 #include <inttypes.h>
11 #include <libgen.h>
12 #include <stdlib.h>
13 #include "util.h" // hex_width()
14 #include "ui/ui.h"
15 #include "sort.h"
16 #include "build-id.h"
17 #include "color.h"
18 #include "config.h"
19 #include "disasm.h"
20 #include "dso.h"
21 #include "env.h"
22 #include "map.h"
23 #include "maps.h"
24 #include "symbol.h"
25 #include "srcline.h"
26 #include "units.h"
27 #include "debug.h"
28 #include "annotate.h"
29 #include "annotate-data.h"
30 #include "evsel.h"
31 #include "evlist.h"
32 #include "bpf-event.h"
33 #include "bpf-utils.h"
34 #include "block-range.h"
35 #include "string2.h"
36 #include "dwarf-regs.h"
37 #include "util/event.h"
38 #include "util/sharded_mutex.h"
39 #include "arch/common.h"
40 #include "namespaces.h"
41 #include "thread.h"
42 #include "hashmap.h"
43 #include <regex.h>
44 #include <linux/bitops.h>
45 #include <linux/kernel.h>
46 #include <linux/string.h>
47 #include <linux/zalloc.h>
48 #include <subcmd/parse-options.h>
49 #include <subcmd/run-command.h>
50 
51 /* FIXME: For the HE_COLORSET */
52 #include "ui/browser.h"
53 
54 /*
55  * FIXME: Using the same values as slang.h,
56  * but that header may not be available everywhere
57  */
58 #define LARROW_CHAR	((unsigned char)',')
59 #define RARROW_CHAR	((unsigned char)'+')
60 #define DARROW_CHAR	((unsigned char)'.')
61 #define UARROW_CHAR	((unsigned char)'-')
62 
63 #include <linux/ctype.h>
64 
65 /* global annotation options */
66 struct annotation_options annotate_opts;
67 
68 /* Data type collection debug statistics */
69 struct annotated_data_stat ann_data_stat;
70 LIST_HEAD(ann_insn_stat);
71 
72 /* Pseudo data types */
73 struct annotated_data_type stackop_type = {
74 	.self = {
75 		.type_name = (char *)"(stack operation)",
76 		.children = LIST_HEAD_INIT(stackop_type.self.children),
77 	},
78 };
79 
80 struct annotated_data_type canary_type = {
81 	.self = {
82 		.type_name = (char *)"(stack canary)",
83 		.children = LIST_HEAD_INIT(canary_type.self.children),
84 	},
85 };
86 
87 /* symbol histogram: key = offset << 16 | evsel->core.idx */
88 static size_t sym_hist_hash(long key, void *ctx __maybe_unused)
89 {
90 	return (key >> 16) + (key & 0xffff);
91 }
92 
93 static bool sym_hist_equal(long key1, long key2, void *ctx __maybe_unused)
94 {
95 	return key1 == key2;
96 }
97 
98 static struct annotated_source *annotated_source__new(void)
99 {
100 	struct annotated_source *src = zalloc(sizeof(*src));
101 
102 	if (src != NULL)
103 		INIT_LIST_HEAD(&src->source);
104 
105 	return src;
106 }
107 
108 static __maybe_unused void annotated_source__delete(struct annotated_source *src)
109 {
110 	if (src == NULL)
111 		return;
112 
113 	hashmap__free(src->samples);
114 	zfree(&src->histograms);
115 	free(src);
116 }
117 
118 static int annotated_source__alloc_histograms(struct annotated_source *src,
119 					      int nr_hists)
120 {
121 	src->nr_histograms   = nr_hists;
122 	src->histograms	     = calloc(nr_hists, sizeof(*src->histograms));
123 
124 	if (src->histograms == NULL)
125 		return -1;
126 
127 	src->samples = hashmap__new(sym_hist_hash, sym_hist_equal, NULL);
128 	if (src->samples == NULL)
129 		zfree(&src->histograms);
130 
131 	return src->histograms ? 0 : -1;
132 }
133 
134 void symbol__annotate_zero_histograms(struct symbol *sym)
135 {
136 	struct annotation *notes = symbol__annotation(sym);
137 
138 	annotation__lock(notes);
139 	if (notes->src != NULL) {
140 		memset(notes->src->histograms, 0,
141 		       notes->src->nr_histograms * sizeof(*notes->src->histograms));
142 		hashmap__clear(notes->src->samples);
143 	}
144 	if (notes->branch && notes->branch->cycles_hist) {
145 		memset(notes->branch->cycles_hist, 0,
146 		       symbol__size(sym) * sizeof(struct cyc_hist));
147 	}
148 	annotation__unlock(notes);
149 }
150 
151 static int __symbol__account_cycles(struct cyc_hist *ch,
152 				    u64 start,
153 				    unsigned offset, unsigned cycles,
154 				    unsigned have_start)
155 {
156 	/*
157 	 * For now we can only account one basic block per
158 	 * final jump. But multiple could be overlapping.
159 	 * Always account the longest one. So when
160 	 * a shorter one has been already seen throw it away.
161 	 *
162 	 * We separately always account the full cycles.
163 	 */
164 	ch[offset].num_aggr++;
165 	ch[offset].cycles_aggr += cycles;
166 
167 	if (cycles > ch[offset].cycles_max)
168 		ch[offset].cycles_max = cycles;
169 
170 	if (ch[offset].cycles_min) {
171 		if (cycles && cycles < ch[offset].cycles_min)
172 			ch[offset].cycles_min = cycles;
173 	} else
174 		ch[offset].cycles_min = cycles;
175 
176 	if (!have_start && ch[offset].have_start)
177 		return 0;
178 	if (ch[offset].num) {
179 		if (have_start && (!ch[offset].have_start ||
180 				   ch[offset].start > start)) {
181 			ch[offset].have_start = 0;
182 			ch[offset].cycles = 0;
183 			ch[offset].num = 0;
184 			if (ch[offset].reset < 0xffff)
185 				ch[offset].reset++;
186 		} else if (have_start &&
187 			   ch[offset].start < start)
188 			return 0;
189 	}
190 
191 	if (ch[offset].num < NUM_SPARKS)
192 		ch[offset].cycles_spark[ch[offset].num] = cycles;
193 
194 	ch[offset].have_start = have_start;
195 	ch[offset].start = start;
196 	ch[offset].cycles += cycles;
197 	ch[offset].num++;
198 	return 0;
199 }
200 
201 static int __symbol__inc_addr_samples(struct map_symbol *ms,
202 				      struct annotated_source *src, int evidx, u64 addr,
203 				      struct perf_sample *sample)
204 {
205 	struct symbol *sym = ms->sym;
206 	long hash_key;
207 	u64 offset;
208 	struct sym_hist *h;
209 	struct sym_hist_entry *entry;
210 
211 	pr_debug3("%s: addr=%#" PRIx64 "\n", __func__, map__unmap_ip(ms->map, addr));
212 
213 	if ((addr < sym->start || addr >= sym->end) &&
214 	    (addr != sym->end || sym->start != sym->end)) {
215 		pr_debug("%s(%d): ERANGE! sym->name=%s, start=%#" PRIx64 ", addr=%#" PRIx64 ", end=%#" PRIx64 "\n",
216 		       __func__, __LINE__, sym->name, sym->start, addr, sym->end);
217 		return -ERANGE;
218 	}
219 
220 	offset = addr - sym->start;
221 	h = annotated_source__histogram(src, evidx);
222 	if (h == NULL) {
223 		pr_debug("%s(%d): ENOMEM! sym->name=%s, start=%#" PRIx64 ", addr=%#" PRIx64 ", end=%#" PRIx64 ", func: %d\n",
224 			 __func__, __LINE__, sym->name, sym->start, addr, sym->end, sym->type == STT_FUNC);
225 		return -ENOMEM;
226 	}
227 
228 	hash_key = offset << 16 | evidx;
229 	if (!hashmap__find(src->samples, hash_key, &entry)) {
230 		entry = zalloc(sizeof(*entry));
231 		if (entry == NULL)
232 			return -ENOMEM;
233 
234 		if (hashmap__add(src->samples, hash_key, entry) < 0)
235 			return -ENOMEM;
236 	}
237 
238 	h->nr_samples++;
239 	h->period += sample->period;
240 	entry->nr_samples++;
241 	entry->period += sample->period;
242 
243 	pr_debug3("%#" PRIx64 " %s: period++ [addr: %#" PRIx64 ", %#" PRIx64
244 		  ", evidx=%d] => nr_samples: %" PRIu64 ", period: %" PRIu64 "\n",
245 		  sym->start, sym->name, addr, addr - sym->start, evidx,
246 		  entry->nr_samples, entry->period);
247 	return 0;
248 }
249 
250 struct annotated_branch *annotation__get_branch(struct annotation *notes)
251 {
252 	if (notes == NULL)
253 		return NULL;
254 
255 	if (notes->branch == NULL)
256 		notes->branch = zalloc(sizeof(*notes->branch));
257 
258 	return notes->branch;
259 }
260 
261 static struct cyc_hist *symbol__cycles_hist(struct symbol *sym)
262 {
263 	struct annotation *notes = symbol__annotation(sym);
264 	struct annotated_branch *branch;
265 
266 	branch = annotation__get_branch(notes);
267 	if (branch == NULL)
268 		return NULL;
269 
270 	if (branch->cycles_hist == NULL) {
271 		const size_t size = symbol__size(sym);
272 
273 		branch->cycles_hist = calloc(size, sizeof(struct cyc_hist));
274 	}
275 
276 	return branch->cycles_hist;
277 }
278 
279 struct annotated_source *symbol__hists(struct symbol *sym, int nr_hists)
280 {
281 	struct annotation *notes = symbol__annotation(sym);
282 
283 	if (notes->src == NULL) {
284 		notes->src = annotated_source__new();
285 		if (notes->src == NULL)
286 			return NULL;
287 		goto alloc_histograms;
288 	}
289 
290 	if (notes->src->histograms == NULL) {
291 alloc_histograms:
292 		annotated_source__alloc_histograms(notes->src, nr_hists);
293 	}
294 
295 	return notes->src;
296 }
297 
298 static int symbol__inc_addr_samples(struct map_symbol *ms,
299 				    struct evsel *evsel, u64 addr,
300 				    struct perf_sample *sample)
301 {
302 	struct symbol *sym = ms->sym;
303 	struct annotated_source *src;
304 
305 	if (sym == NULL)
306 		return 0;
307 	src = symbol__hists(sym, evsel->evlist->core.nr_entries);
308 	return src ? __symbol__inc_addr_samples(ms, src, evsel->core.idx, addr, sample) : 0;
309 }
310 
311 static int symbol__account_cycles(u64 addr, u64 start,
312 				  struct symbol *sym, unsigned cycles)
313 {
314 	struct cyc_hist *cycles_hist;
315 	unsigned offset;
316 
317 	if (sym == NULL)
318 		return 0;
319 	cycles_hist = symbol__cycles_hist(sym);
320 	if (cycles_hist == NULL)
321 		return -ENOMEM;
322 	if (addr < sym->start || addr >= sym->end)
323 		return -ERANGE;
324 
325 	if (start) {
326 		if (start < sym->start || start >= sym->end)
327 			return -ERANGE;
328 		if (start >= addr)
329 			start = 0;
330 	}
331 	offset = addr - sym->start;
332 	return __symbol__account_cycles(cycles_hist,
333 					start ? start - sym->start : 0,
334 					offset, cycles,
335 					!!start);
336 }
337 
338 int addr_map_symbol__account_cycles(struct addr_map_symbol *ams,
339 				    struct addr_map_symbol *start,
340 				    unsigned cycles)
341 {
342 	u64 saddr = 0;
343 	int err;
344 
345 	if (!cycles)
346 		return 0;
347 
348 	/*
349 	 * Only set start when IPC can be computed. We can only
350 	 * compute it when the basic block is completely in a single
351 	 * function.
352 	 * Special case the case when the jump is elsewhere, but
353 	 * it starts on the function start.
354 	 */
355 	if (start &&
356 		(start->ms.sym == ams->ms.sym ||
357 		 (ams->ms.sym &&
358 		  start->addr == ams->ms.sym->start + map__start(ams->ms.map))))
359 		saddr = start->al_addr;
360 	if (saddr == 0)
361 		pr_debug2("BB with bad start: addr %"PRIx64" start %"PRIx64" sym %"PRIx64" saddr %"PRIx64"\n",
362 			ams->addr,
363 			start ? start->addr : 0,
364 			ams->ms.sym ? ams->ms.sym->start + map__start(ams->ms.map) : 0,
365 			saddr);
366 	err = symbol__account_cycles(ams->al_addr, saddr, ams->ms.sym, cycles);
367 	if (err)
368 		pr_debug2("account_cycles failed %d\n", err);
369 	return err;
370 }
371 
372 struct annotation_line *annotated_source__get_line(struct annotated_source *src,
373 						   s64 offset)
374 {
375 	struct annotation_line *al;
376 
377 	list_for_each_entry(al, &src->source, node) {
378 		if (al->offset == offset)
379 			return al;
380 	}
381 	return NULL;
382 }
383 
384 static unsigned annotation__count_insn(struct annotation *notes, u64 start, u64 end)
385 {
386 	struct annotation_line *al;
387 	unsigned n_insn = 0;
388 
389 	al = annotated_source__get_line(notes->src, start);
390 	if (al == NULL)
391 		return 0;
392 
393 	list_for_each_entry_from(al, &notes->src->source, node) {
394 		if (al->offset == -1)
395 			continue;
396 		if ((u64)al->offset > end)
397 			break;
398 		n_insn++;
399 	}
400 	return n_insn;
401 }
402 
403 static void annotated_branch__delete(struct annotated_branch *branch)
404 {
405 	if (branch) {
406 		zfree(&branch->cycles_hist);
407 		free(branch);
408 	}
409 }
410 
411 static void annotation__count_and_fill(struct annotation *notes, u64 start, u64 end, struct cyc_hist *ch)
412 {
413 	unsigned n_insn;
414 	unsigned int cover_insn = 0;
415 
416 	n_insn = annotation__count_insn(notes, start, end);
417 	if (n_insn && ch->num && ch->cycles) {
418 		struct annotation_line *al;
419 		struct annotated_branch *branch;
420 		float ipc = n_insn / ((double)ch->cycles / (double)ch->num);
421 
422 		/* Hide data when there are too many overlaps. */
423 		if (ch->reset >= 0x7fff)
424 			return;
425 
426 		al = annotated_source__get_line(notes->src, start);
427 		if (al == NULL)
428 			return;
429 
430 		list_for_each_entry_from(al, &notes->src->source, node) {
431 			if (al->offset == -1)
432 				continue;
433 			if ((u64)al->offset > end)
434 				break;
435 			if (al->cycles && al->cycles->ipc == 0.0) {
436 				al->cycles->ipc = ipc;
437 				cover_insn++;
438 			}
439 		}
440 
441 		branch = annotation__get_branch(notes);
442 		if (cover_insn && branch) {
443 			branch->hit_cycles += ch->cycles;
444 			branch->hit_insn += n_insn * ch->num;
445 			branch->cover_insn += cover_insn;
446 		}
447 	}
448 }
449 
450 static int annotation__compute_ipc(struct annotation *notes, size_t size)
451 {
452 	int err = 0;
453 	s64 offset;
454 
455 	if (!notes->branch || !notes->branch->cycles_hist)
456 		return 0;
457 
458 	notes->branch->total_insn = annotation__count_insn(notes, 0, size - 1);
459 	notes->branch->hit_cycles = 0;
460 	notes->branch->hit_insn = 0;
461 	notes->branch->cover_insn = 0;
462 
463 	annotation__lock(notes);
464 	for (offset = size - 1; offset >= 0; --offset) {
465 		struct cyc_hist *ch;
466 
467 		ch = &notes->branch->cycles_hist[offset];
468 		if (ch && ch->cycles) {
469 			struct annotation_line *al;
470 
471 			al = annotated_source__get_line(notes->src, offset);
472 			if (al && al->cycles == NULL) {
473 				al->cycles = zalloc(sizeof(*al->cycles));
474 				if (al->cycles == NULL) {
475 					err = ENOMEM;
476 					break;
477 				}
478 			}
479 			if (ch->have_start)
480 				annotation__count_and_fill(notes, ch->start, offset, ch);
481 			if (al && ch->num_aggr) {
482 				al->cycles->avg = ch->cycles_aggr / ch->num_aggr;
483 				al->cycles->max = ch->cycles_max;
484 				al->cycles->min = ch->cycles_min;
485 			}
486 		}
487 	}
488 
489 	if (err) {
490 		while (++offset < (s64)size) {
491 			struct cyc_hist *ch = &notes->branch->cycles_hist[offset];
492 
493 			if (ch && ch->cycles) {
494 				struct annotation_line *al;
495 
496 				al = annotated_source__get_line(notes->src, offset);
497 				if (al)
498 					zfree(&al->cycles);
499 			}
500 		}
501 	}
502 
503 	annotation__unlock(notes);
504 	return 0;
505 }
506 
507 int addr_map_symbol__inc_samples(struct addr_map_symbol *ams, struct perf_sample *sample,
508 				 struct evsel *evsel)
509 {
510 	return symbol__inc_addr_samples(&ams->ms, evsel, ams->al_addr, sample);
511 }
512 
513 int hist_entry__inc_addr_samples(struct hist_entry *he, struct perf_sample *sample,
514 				 struct evsel *evsel, u64 ip)
515 {
516 	return symbol__inc_addr_samples(&he->ms, evsel, ip, sample);
517 }
518 
519 
520 void annotation__exit(struct annotation *notes)
521 {
522 	annotated_source__delete(notes->src);
523 	annotated_branch__delete(notes->branch);
524 }
525 
526 static struct sharded_mutex *sharded_mutex;
527 
528 static void annotation__init_sharded_mutex(void)
529 {
530 	/* As many mutexes as there are CPUs. */
531 	sharded_mutex = sharded_mutex__new(cpu__max_present_cpu().cpu);
532 }
533 
534 static size_t annotation__hash(const struct annotation *notes)
535 {
536 	return (size_t)notes;
537 }
538 
539 static struct mutex *annotation__get_mutex(const struct annotation *notes)
540 {
541 	static pthread_once_t once = PTHREAD_ONCE_INIT;
542 
543 	pthread_once(&once, annotation__init_sharded_mutex);
544 	if (!sharded_mutex)
545 		return NULL;
546 
547 	return sharded_mutex__get_mutex(sharded_mutex, annotation__hash(notes));
548 }
549 
550 void annotation__lock(struct annotation *notes)
551 	NO_THREAD_SAFETY_ANALYSIS
552 {
553 	struct mutex *mutex = annotation__get_mutex(notes);
554 
555 	if (mutex)
556 		mutex_lock(mutex);
557 }
558 
559 void annotation__unlock(struct annotation *notes)
560 	NO_THREAD_SAFETY_ANALYSIS
561 {
562 	struct mutex *mutex = annotation__get_mutex(notes);
563 
564 	if (mutex)
565 		mutex_unlock(mutex);
566 }
567 
568 bool annotation__trylock(struct annotation *notes)
569 {
570 	struct mutex *mutex = annotation__get_mutex(notes);
571 
572 	if (!mutex)
573 		return false;
574 
575 	return mutex_trylock(mutex);
576 }
577 
578 void annotation_line__add(struct annotation_line *al, struct list_head *head)
579 {
580 	list_add_tail(&al->node, head);
581 }
582 
583 struct annotation_line *
584 annotation_line__next(struct annotation_line *pos, struct list_head *head)
585 {
586 	list_for_each_entry_continue(pos, head, node)
587 		if (pos->offset >= 0)
588 			return pos;
589 
590 	return NULL;
591 }
592 
593 static const char *annotate__address_color(struct block_range *br)
594 {
595 	double cov = block_range__coverage(br);
596 
597 	if (cov >= 0) {
598 		/* mark red for >75% coverage */
599 		if (cov > 0.75)
600 			return PERF_COLOR_RED;
601 
602 		/* mark dull for <1% coverage */
603 		if (cov < 0.01)
604 			return PERF_COLOR_NORMAL;
605 	}
606 
607 	return PERF_COLOR_MAGENTA;
608 }
609 
610 static const char *annotate__asm_color(struct block_range *br)
611 {
612 	double cov = block_range__coverage(br);
613 
614 	if (cov >= 0) {
615 		/* mark dull for <1% coverage */
616 		if (cov < 0.01)
617 			return PERF_COLOR_NORMAL;
618 	}
619 
620 	return PERF_COLOR_BLUE;
621 }
622 
623 static void annotate__branch_printf(struct block_range *br, u64 addr)
624 {
625 	bool emit_comment = true;
626 
627 	if (!br)
628 		return;
629 
630 #if 1
631 	if (br->is_target && br->start == addr) {
632 		struct block_range *branch = br;
633 		double p;
634 
635 		/*
636 		 * Find matching branch to our target.
637 		 */
638 		while (!branch->is_branch)
639 			branch = block_range__next(branch);
640 
641 		p = 100 *(double)br->entry / branch->coverage;
642 
643 		if (p > 0.1) {
644 			if (emit_comment) {
645 				emit_comment = false;
646 				printf("\t#");
647 			}
648 
649 			/*
650 			 * The percentage of coverage joined at this target in relation
651 			 * to the next branch.
652 			 */
653 			printf(" +%.2f%%", p);
654 		}
655 	}
656 #endif
657 	if (br->is_branch && br->end == addr) {
658 		double p = 100*(double)br->taken / br->coverage;
659 
660 		if (p > 0.1) {
661 			if (emit_comment) {
662 				emit_comment = false;
663 				printf("\t#");
664 			}
665 
666 			/*
667 			 * The percentage of coverage leaving at this branch, and
668 			 * its prediction ratio.
669 			 */
670 			printf(" -%.2f%% (p:%.2f%%)", p, 100*(double)br->pred  / br->taken);
671 		}
672 	}
673 }
674 
675 static int disasm_line__print(struct disasm_line *dl, u64 start, int addr_fmt_width)
676 {
677 	s64 offset = dl->al.offset;
678 	const u64 addr = start + offset;
679 	struct block_range *br;
680 
681 	br = block_range__find(addr);
682 	color_fprintf(stdout, annotate__address_color(br), "  %*" PRIx64 ":", addr_fmt_width, addr);
683 	color_fprintf(stdout, annotate__asm_color(br), "%s", dl->al.line);
684 	annotate__branch_printf(br, addr);
685 	return 0;
686 }
687 
688 static int
689 annotation_line__print(struct annotation_line *al, struct symbol *sym, u64 start,
690 		       struct evsel *evsel, u64 len, int min_pcnt, int printed,
691 		       int max_lines, struct annotation_line *queue, int addr_fmt_width,
692 		       int percent_type)
693 {
694 	struct disasm_line *dl = container_of(al, struct disasm_line, al);
695 	static const char *prev_line;
696 
697 	if (al->offset != -1) {
698 		double max_percent = 0.0;
699 		int i, nr_percent = 1;
700 		const char *color;
701 		struct annotation *notes = symbol__annotation(sym);
702 
703 		for (i = 0; i < al->data_nr; i++) {
704 			double percent;
705 
706 			percent = annotation_data__percent(&al->data[i],
707 							   percent_type);
708 
709 			if (percent > max_percent)
710 				max_percent = percent;
711 		}
712 
713 		if (al->data_nr > nr_percent)
714 			nr_percent = al->data_nr;
715 
716 		if (max_percent < min_pcnt)
717 			return -1;
718 
719 		if (max_lines && printed >= max_lines)
720 			return 1;
721 
722 		if (queue != NULL) {
723 			list_for_each_entry_from(queue, &notes->src->source, node) {
724 				if (queue == al)
725 					break;
726 				annotation_line__print(queue, sym, start, evsel, len,
727 						       0, 0, 1, NULL, addr_fmt_width,
728 						       percent_type);
729 			}
730 		}
731 
732 		color = get_percent_color(max_percent);
733 
734 		for (i = 0; i < nr_percent; i++) {
735 			struct annotation_data *data = &al->data[i];
736 			double percent;
737 
738 			percent = annotation_data__percent(data, percent_type);
739 			color = get_percent_color(percent);
740 
741 			if (symbol_conf.show_total_period)
742 				color_fprintf(stdout, color, " %11" PRIu64,
743 					      data->he.period);
744 			else if (symbol_conf.show_nr_samples)
745 				color_fprintf(stdout, color, " %7" PRIu64,
746 					      data->he.nr_samples);
747 			else
748 				color_fprintf(stdout, color, " %7.2f", percent);
749 		}
750 
751 		printf(" : ");
752 
753 		disasm_line__print(dl, start, addr_fmt_width);
754 
755 		/*
756 		 * Also color the filename and line if needed, with
757 		 * the same color than the percentage. Don't print it
758 		 * twice for close colored addr with the same filename:line
759 		 */
760 		if (al->path) {
761 			if (!prev_line || strcmp(prev_line, al->path)) {
762 				color_fprintf(stdout, color, " // %s", al->path);
763 				prev_line = al->path;
764 			}
765 		}
766 
767 		printf("\n");
768 	} else if (max_lines && printed >= max_lines)
769 		return 1;
770 	else {
771 		int width = symbol_conf.show_total_period ? 12 : 8;
772 
773 		if (queue)
774 			return -1;
775 
776 		if (evsel__is_group_event(evsel))
777 			width *= evsel->core.nr_members;
778 
779 		if (!*al->line)
780 			printf(" %*s:\n", width, " ");
781 		else
782 			printf(" %*s: %-*d %s\n", width, " ", addr_fmt_width, al->line_nr, al->line);
783 	}
784 
785 	return 0;
786 }
787 
788 static void calc_percent(struct annotation *notes,
789 			 struct evsel *evsel,
790 			 struct annotation_data *data,
791 			 s64 offset, s64 end)
792 {
793 	struct hists *hists = evsel__hists(evsel);
794 	int evidx = evsel->core.idx;
795 	struct sym_hist *sym_hist = annotation__histogram(notes, evidx);
796 	unsigned int hits = 0;
797 	u64 period = 0;
798 
799 	while (offset < end) {
800 		struct sym_hist_entry *entry;
801 
802 		entry = annotated_source__hist_entry(notes->src, evidx, offset);
803 		if (entry) {
804 			hits   += entry->nr_samples;
805 			period += entry->period;
806 		}
807 		++offset;
808 	}
809 
810 	if (sym_hist->nr_samples) {
811 		data->he.period     = period;
812 		data->he.nr_samples = hits;
813 		data->percent[PERCENT_HITS_LOCAL] = 100.0 * hits / sym_hist->nr_samples;
814 	}
815 
816 	if (hists->stats.nr_non_filtered_samples)
817 		data->percent[PERCENT_HITS_GLOBAL] = 100.0 * hits / hists->stats.nr_non_filtered_samples;
818 
819 	if (sym_hist->period)
820 		data->percent[PERCENT_PERIOD_LOCAL] = 100.0 * period / sym_hist->period;
821 
822 	if (hists->stats.total_period)
823 		data->percent[PERCENT_PERIOD_GLOBAL] = 100.0 * period / hists->stats.total_period;
824 }
825 
826 static void annotation__calc_percent(struct annotation *notes,
827 				     struct evsel *leader, s64 len)
828 {
829 	struct annotation_line *al, *next;
830 	struct evsel *evsel;
831 
832 	list_for_each_entry(al, &notes->src->source, node) {
833 		s64 end;
834 		int i = 0;
835 
836 		if (al->offset == -1)
837 			continue;
838 
839 		next = annotation_line__next(al, &notes->src->source);
840 		end  = next ? next->offset : len;
841 
842 		for_each_group_evsel(evsel, leader) {
843 			struct annotation_data *data;
844 
845 			BUG_ON(i >= al->data_nr);
846 
847 			data = &al->data[i++];
848 
849 			calc_percent(notes, evsel, data, al->offset, end);
850 		}
851 	}
852 }
853 
854 void symbol__calc_percent(struct symbol *sym, struct evsel *evsel)
855 {
856 	struct annotation *notes = symbol__annotation(sym);
857 
858 	annotation__calc_percent(notes, evsel, symbol__size(sym));
859 }
860 
861 static int evsel__get_arch(struct evsel *evsel, struct arch **parch)
862 {
863 	struct perf_env *env = evsel__env(evsel);
864 	const char *arch_name = perf_env__arch(env);
865 	struct arch *arch;
866 	int err;
867 
868 	if (!arch_name) {
869 		*parch = NULL;
870 		return errno;
871 	}
872 
873 	*parch = arch = arch__find(arch_name);
874 	if (arch == NULL) {
875 		pr_err("%s: unsupported arch %s\n", __func__, arch_name);
876 		return ENOTSUP;
877 	}
878 
879 	if (arch->init) {
880 		err = arch->init(arch, env ? env->cpuid : NULL);
881 		if (err) {
882 			pr_err("%s: failed to initialize %s arch priv area\n",
883 			       __func__, arch->name);
884 			return err;
885 		}
886 	}
887 	return 0;
888 }
889 
890 int symbol__annotate(struct map_symbol *ms, struct evsel *evsel,
891 		     struct arch **parch)
892 {
893 	struct symbol *sym = ms->sym;
894 	struct annotation *notes = symbol__annotation(sym);
895 	struct annotate_args args = {
896 		.evsel		= evsel,
897 		.options	= &annotate_opts,
898 	};
899 	struct arch *arch = NULL;
900 	int err;
901 
902 	err = evsel__get_arch(evsel, &arch);
903 	if (err < 0)
904 		return err;
905 
906 	if (parch)
907 		*parch = arch;
908 
909 	args.arch = arch;
910 	args.ms = *ms;
911 
912 	if (notes->src == NULL) {
913 		notes->src = annotated_source__new();
914 		if (notes->src == NULL)
915 			return -1;
916 	}
917 
918 	if (annotate_opts.full_addr)
919 		notes->src->start = map__objdump_2mem(ms->map, ms->sym->start);
920 	else
921 		notes->src->start = map__rip_2objdump(ms->map, ms->sym->start);
922 
923 	return symbol__disassemble(sym, &args);
924 }
925 
926 static void insert_source_line(struct rb_root *root, struct annotation_line *al)
927 {
928 	struct annotation_line *iter;
929 	struct rb_node **p = &root->rb_node;
930 	struct rb_node *parent = NULL;
931 	unsigned int percent_type = annotate_opts.percent_type;
932 	int i, ret;
933 
934 	while (*p != NULL) {
935 		parent = *p;
936 		iter = rb_entry(parent, struct annotation_line, rb_node);
937 
938 		ret = strcmp(iter->path, al->path);
939 		if (ret == 0) {
940 			for (i = 0; i < al->data_nr; i++) {
941 				iter->data[i].percent_sum += annotation_data__percent(&al->data[i],
942 										      percent_type);
943 			}
944 			return;
945 		}
946 
947 		if (ret < 0)
948 			p = &(*p)->rb_left;
949 		else
950 			p = &(*p)->rb_right;
951 	}
952 
953 	for (i = 0; i < al->data_nr; i++) {
954 		al->data[i].percent_sum = annotation_data__percent(&al->data[i],
955 								   percent_type);
956 	}
957 
958 	rb_link_node(&al->rb_node, parent, p);
959 	rb_insert_color(&al->rb_node, root);
960 }
961 
962 static int cmp_source_line(struct annotation_line *a, struct annotation_line *b)
963 {
964 	int i;
965 
966 	for (i = 0; i < a->data_nr; i++) {
967 		if (a->data[i].percent_sum == b->data[i].percent_sum)
968 			continue;
969 		return a->data[i].percent_sum > b->data[i].percent_sum;
970 	}
971 
972 	return 0;
973 }
974 
975 static void __resort_source_line(struct rb_root *root, struct annotation_line *al)
976 {
977 	struct annotation_line *iter;
978 	struct rb_node **p = &root->rb_node;
979 	struct rb_node *parent = NULL;
980 
981 	while (*p != NULL) {
982 		parent = *p;
983 		iter = rb_entry(parent, struct annotation_line, rb_node);
984 
985 		if (cmp_source_line(al, iter))
986 			p = &(*p)->rb_left;
987 		else
988 			p = &(*p)->rb_right;
989 	}
990 
991 	rb_link_node(&al->rb_node, parent, p);
992 	rb_insert_color(&al->rb_node, root);
993 }
994 
995 static void resort_source_line(struct rb_root *dest_root, struct rb_root *src_root)
996 {
997 	struct annotation_line *al;
998 	struct rb_node *node;
999 
1000 	node = rb_first(src_root);
1001 	while (node) {
1002 		struct rb_node *next;
1003 
1004 		al = rb_entry(node, struct annotation_line, rb_node);
1005 		next = rb_next(node);
1006 		rb_erase(node, src_root);
1007 
1008 		__resort_source_line(dest_root, al);
1009 		node = next;
1010 	}
1011 }
1012 
1013 static void print_summary(struct rb_root *root, const char *filename)
1014 {
1015 	struct annotation_line *al;
1016 	struct rb_node *node;
1017 
1018 	printf("\nSorted summary for file %s\n", filename);
1019 	printf("----------------------------------------------\n\n");
1020 
1021 	if (RB_EMPTY_ROOT(root)) {
1022 		printf(" Nothing higher than %1.1f%%\n", MIN_GREEN);
1023 		return;
1024 	}
1025 
1026 	node = rb_first(root);
1027 	while (node) {
1028 		double percent, percent_max = 0.0;
1029 		const char *color;
1030 		char *path;
1031 		int i;
1032 
1033 		al = rb_entry(node, struct annotation_line, rb_node);
1034 		for (i = 0; i < al->data_nr; i++) {
1035 			percent = al->data[i].percent_sum;
1036 			color = get_percent_color(percent);
1037 			color_fprintf(stdout, color, " %7.2f", percent);
1038 
1039 			if (percent > percent_max)
1040 				percent_max = percent;
1041 		}
1042 
1043 		path = al->path;
1044 		color = get_percent_color(percent_max);
1045 		color_fprintf(stdout, color, " %s\n", path);
1046 
1047 		node = rb_next(node);
1048 	}
1049 }
1050 
1051 static void symbol__annotate_hits(struct symbol *sym, struct evsel *evsel)
1052 {
1053 	int evidx = evsel->core.idx;
1054 	struct annotation *notes = symbol__annotation(sym);
1055 	struct sym_hist *h = annotation__histogram(notes, evidx);
1056 	u64 len = symbol__size(sym), offset;
1057 
1058 	for (offset = 0; offset < len; ++offset) {
1059 		struct sym_hist_entry *entry;
1060 
1061 		entry = annotated_source__hist_entry(notes->src, evidx, offset);
1062 		if (entry && entry->nr_samples != 0)
1063 			printf("%*" PRIx64 ": %" PRIu64 "\n", BITS_PER_LONG / 2,
1064 			       sym->start + offset, entry->nr_samples);
1065 	}
1066 	printf("%*s: %" PRIu64 "\n", BITS_PER_LONG / 2, "h->nr_samples", h->nr_samples);
1067 }
1068 
1069 static int annotated_source__addr_fmt_width(struct list_head *lines, u64 start)
1070 {
1071 	char bf[32];
1072 	struct annotation_line *line;
1073 
1074 	list_for_each_entry_reverse(line, lines, node) {
1075 		if (line->offset != -1)
1076 			return scnprintf(bf, sizeof(bf), "%" PRIx64, start + line->offset);
1077 	}
1078 
1079 	return 0;
1080 }
1081 
1082 int symbol__annotate_printf(struct map_symbol *ms, struct evsel *evsel)
1083 {
1084 	struct map *map = ms->map;
1085 	struct symbol *sym = ms->sym;
1086 	struct dso *dso = map__dso(map);
1087 	char *filename;
1088 	const char *d_filename;
1089 	const char *evsel_name = evsel__name(evsel);
1090 	struct annotation *notes = symbol__annotation(sym);
1091 	struct sym_hist *h = annotation__histogram(notes, evsel->core.idx);
1092 	struct annotation_line *pos, *queue = NULL;
1093 	struct annotation_options *opts = &annotate_opts;
1094 	u64 start = map__rip_2objdump(map, sym->start);
1095 	int printed = 2, queue_len = 0, addr_fmt_width;
1096 	int more = 0;
1097 	bool context = opts->context;
1098 	u64 len;
1099 	int width = symbol_conf.show_total_period ? 12 : 8;
1100 	int graph_dotted_len;
1101 	char buf[512];
1102 
1103 	filename = strdup(dso->long_name);
1104 	if (!filename)
1105 		return -ENOMEM;
1106 
1107 	if (opts->full_path)
1108 		d_filename = filename;
1109 	else
1110 		d_filename = basename(filename);
1111 
1112 	len = symbol__size(sym);
1113 
1114 	if (evsel__is_group_event(evsel)) {
1115 		width *= evsel->core.nr_members;
1116 		evsel__group_desc(evsel, buf, sizeof(buf));
1117 		evsel_name = buf;
1118 	}
1119 
1120 	graph_dotted_len = printf(" %-*.*s|	Source code & Disassembly of %s for %s (%" PRIu64 " samples, "
1121 				  "percent: %s)\n",
1122 				  width, width, symbol_conf.show_total_period ? "Period" :
1123 				  symbol_conf.show_nr_samples ? "Samples" : "Percent",
1124 				  d_filename, evsel_name, h->nr_samples,
1125 				  percent_type_str(opts->percent_type));
1126 
1127 	printf("%-*.*s----\n",
1128 	       graph_dotted_len, graph_dotted_len, graph_dotted_line);
1129 
1130 	if (verbose > 0)
1131 		symbol__annotate_hits(sym, evsel);
1132 
1133 	addr_fmt_width = annotated_source__addr_fmt_width(&notes->src->source, start);
1134 
1135 	list_for_each_entry(pos, &notes->src->source, node) {
1136 		int err;
1137 
1138 		if (context && queue == NULL) {
1139 			queue = pos;
1140 			queue_len = 0;
1141 		}
1142 
1143 		err = annotation_line__print(pos, sym, start, evsel, len,
1144 					     opts->min_pcnt, printed, opts->max_lines,
1145 					     queue, addr_fmt_width, opts->percent_type);
1146 
1147 		switch (err) {
1148 		case 0:
1149 			++printed;
1150 			if (context) {
1151 				printed += queue_len;
1152 				queue = NULL;
1153 				queue_len = 0;
1154 			}
1155 			break;
1156 		case 1:
1157 			/* filtered by max_lines */
1158 			++more;
1159 			break;
1160 		case -1:
1161 		default:
1162 			/*
1163 			 * Filtered by min_pcnt or non IP lines when
1164 			 * context != 0
1165 			 */
1166 			if (!context)
1167 				break;
1168 			if (queue_len == context)
1169 				queue = list_entry(queue->node.next, typeof(*queue), node);
1170 			else
1171 				++queue_len;
1172 			break;
1173 		}
1174 	}
1175 
1176 	free(filename);
1177 
1178 	return more;
1179 }
1180 
1181 static void FILE__set_percent_color(void *fp __maybe_unused,
1182 				    double percent __maybe_unused,
1183 				    bool current __maybe_unused)
1184 {
1185 }
1186 
1187 static int FILE__set_jumps_percent_color(void *fp __maybe_unused,
1188 					 int nr __maybe_unused, bool current __maybe_unused)
1189 {
1190 	return 0;
1191 }
1192 
1193 static int FILE__set_color(void *fp __maybe_unused, int color __maybe_unused)
1194 {
1195 	return 0;
1196 }
1197 
1198 static void FILE__printf(void *fp, const char *fmt, ...)
1199 {
1200 	va_list args;
1201 
1202 	va_start(args, fmt);
1203 	vfprintf(fp, fmt, args);
1204 	va_end(args);
1205 }
1206 
1207 static void FILE__write_graph(void *fp, int graph)
1208 {
1209 	const char *s;
1210 	switch (graph) {
1211 
1212 	case DARROW_CHAR: s = "↓"; break;
1213 	case UARROW_CHAR: s = "↑"; break;
1214 	case LARROW_CHAR: s = "←"; break;
1215 	case RARROW_CHAR: s = "→"; break;
1216 	default:		s = "?"; break;
1217 	}
1218 
1219 	fputs(s, fp);
1220 }
1221 
1222 static int symbol__annotate_fprintf2(struct symbol *sym, FILE *fp)
1223 {
1224 	struct annotation *notes = symbol__annotation(sym);
1225 	struct annotation_write_ops wops = {
1226 		.first_line		 = true,
1227 		.obj			 = fp,
1228 		.set_color		 = FILE__set_color,
1229 		.set_percent_color	 = FILE__set_percent_color,
1230 		.set_jumps_percent_color = FILE__set_jumps_percent_color,
1231 		.printf			 = FILE__printf,
1232 		.write_graph		 = FILE__write_graph,
1233 	};
1234 	struct annotation_line *al;
1235 
1236 	list_for_each_entry(al, &notes->src->source, node) {
1237 		if (annotation_line__filter(al))
1238 			continue;
1239 		annotation_line__write(al, notes, &wops);
1240 		fputc('\n', fp);
1241 		wops.first_line = false;
1242 	}
1243 
1244 	return 0;
1245 }
1246 
1247 int map_symbol__annotation_dump(struct map_symbol *ms, struct evsel *evsel)
1248 {
1249 	const char *ev_name = evsel__name(evsel);
1250 	char buf[1024];
1251 	char *filename;
1252 	int err = -1;
1253 	FILE *fp;
1254 
1255 	if (asprintf(&filename, "%s.annotation", ms->sym->name) < 0)
1256 		return -1;
1257 
1258 	fp = fopen(filename, "w");
1259 	if (fp == NULL)
1260 		goto out_free_filename;
1261 
1262 	if (evsel__is_group_event(evsel)) {
1263 		evsel__group_desc(evsel, buf, sizeof(buf));
1264 		ev_name = buf;
1265 	}
1266 
1267 	fprintf(fp, "%s() %s\nEvent: %s\n\n",
1268 		ms->sym->name, map__dso(ms->map)->long_name, ev_name);
1269 	symbol__annotate_fprintf2(ms->sym, fp);
1270 
1271 	fclose(fp);
1272 	err = 0;
1273 out_free_filename:
1274 	free(filename);
1275 	return err;
1276 }
1277 
1278 void symbol__annotate_zero_histogram(struct symbol *sym, int evidx)
1279 {
1280 	struct annotation *notes = symbol__annotation(sym);
1281 	struct sym_hist *h = annotation__histogram(notes, evidx);
1282 
1283 	memset(h, 0, sizeof(*notes->src->histograms) * notes->src->nr_histograms);
1284 }
1285 
1286 void symbol__annotate_decay_histogram(struct symbol *sym, int evidx)
1287 {
1288 	struct annotation *notes = symbol__annotation(sym);
1289 	struct sym_hist *h = annotation__histogram(notes, evidx);
1290 	struct annotation_line *al;
1291 
1292 	h->nr_samples = 0;
1293 	list_for_each_entry(al, &notes->src->source, node) {
1294 		struct sym_hist_entry *entry;
1295 
1296 		if (al->offset == -1)
1297 			continue;
1298 
1299 		entry = annotated_source__hist_entry(notes->src, evidx, al->offset);
1300 		if (entry == NULL)
1301 			continue;
1302 
1303 		entry->nr_samples = entry->nr_samples * 7 / 8;
1304 		h->nr_samples += entry->nr_samples;
1305 	}
1306 }
1307 
1308 void annotated_source__purge(struct annotated_source *as)
1309 {
1310 	struct annotation_line *al, *n;
1311 
1312 	list_for_each_entry_safe(al, n, &as->source, node) {
1313 		list_del_init(&al->node);
1314 		disasm_line__free(disasm_line(al));
1315 	}
1316 }
1317 
1318 static size_t disasm_line__fprintf(struct disasm_line *dl, FILE *fp)
1319 {
1320 	size_t printed;
1321 
1322 	if (dl->al.offset == -1)
1323 		return fprintf(fp, "%s\n", dl->al.line);
1324 
1325 	printed = fprintf(fp, "%#" PRIx64 " %s", dl->al.offset, dl->ins.name);
1326 
1327 	if (dl->ops.raw[0] != '\0') {
1328 		printed += fprintf(fp, "%.*s %s\n", 6 - (int)printed, " ",
1329 				   dl->ops.raw);
1330 	}
1331 
1332 	return printed + fprintf(fp, "\n");
1333 }
1334 
1335 size_t disasm__fprintf(struct list_head *head, FILE *fp)
1336 {
1337 	struct disasm_line *pos;
1338 	size_t printed = 0;
1339 
1340 	list_for_each_entry(pos, head, al.node)
1341 		printed += disasm_line__fprintf(pos, fp);
1342 
1343 	return printed;
1344 }
1345 
1346 bool disasm_line__is_valid_local_jump(struct disasm_line *dl, struct symbol *sym)
1347 {
1348 	if (!dl || !dl->ins.ops || !ins__is_jump(&dl->ins) ||
1349 	    !disasm_line__has_local_offset(dl) || dl->ops.target.offset < 0 ||
1350 	    dl->ops.target.offset >= (s64)symbol__size(sym))
1351 		return false;
1352 
1353 	return true;
1354 }
1355 
1356 static void
1357 annotation__mark_jump_targets(struct annotation *notes, struct symbol *sym)
1358 {
1359 	struct annotation_line *al;
1360 
1361 	/* PLT symbols contain external offsets */
1362 	if (strstr(sym->name, "@plt"))
1363 		return;
1364 
1365 	list_for_each_entry(al, &notes->src->source, node) {
1366 		struct disasm_line *dl;
1367 		struct annotation_line *target;
1368 
1369 		dl = disasm_line(al);
1370 
1371 		if (!disasm_line__is_valid_local_jump(dl, sym))
1372 			continue;
1373 
1374 		target = annotated_source__get_line(notes->src,
1375 						    dl->ops.target.offset);
1376 		/*
1377 		 * FIXME: Oops, no jump target? Buggy disassembler? Or do we
1378 		 * have to adjust to the previous offset?
1379 		 */
1380 		if (target == NULL)
1381 			continue;
1382 
1383 		if (++target->jump_sources > notes->src->max_jump_sources)
1384 			notes->src->max_jump_sources = target->jump_sources;
1385 	}
1386 }
1387 
1388 static void annotation__set_index(struct annotation *notes)
1389 {
1390 	struct annotation_line *al;
1391 	struct annotated_source *src = notes->src;
1392 
1393 	src->widths.max_line_len = 0;
1394 	src->nr_entries = 0;
1395 	src->nr_asm_entries = 0;
1396 
1397 	list_for_each_entry(al, &src->source, node) {
1398 		size_t line_len = strlen(al->line);
1399 
1400 		if (src->widths.max_line_len < line_len)
1401 			src->widths.max_line_len = line_len;
1402 		al->idx = src->nr_entries++;
1403 		if (al->offset != -1)
1404 			al->idx_asm = src->nr_asm_entries++;
1405 		else
1406 			al->idx_asm = -1;
1407 	}
1408 }
1409 
1410 static inline int width_jumps(int n)
1411 {
1412 	if (n >= 100)
1413 		return 5;
1414 	if (n / 10)
1415 		return 2;
1416 	return 1;
1417 }
1418 
1419 static int annotation__max_ins_name(struct annotation *notes)
1420 {
1421 	int max_name = 0, len;
1422 	struct annotation_line *al;
1423 
1424         list_for_each_entry(al, &notes->src->source, node) {
1425 		if (al->offset == -1)
1426 			continue;
1427 
1428 		len = strlen(disasm_line(al)->ins.name);
1429 		if (max_name < len)
1430 			max_name = len;
1431 	}
1432 
1433 	return max_name;
1434 }
1435 
1436 static void
1437 annotation__init_column_widths(struct annotation *notes, struct symbol *sym)
1438 {
1439 	notes->src->widths.addr = notes->src->widths.target =
1440 		notes->src->widths.min_addr = hex_width(symbol__size(sym));
1441 	notes->src->widths.max_addr = hex_width(sym->end);
1442 	notes->src->widths.jumps = width_jumps(notes->src->max_jump_sources);
1443 	notes->src->widths.max_ins_name = annotation__max_ins_name(notes);
1444 }
1445 
1446 void annotation__update_column_widths(struct annotation *notes)
1447 {
1448 	if (annotate_opts.use_offset)
1449 		notes->src->widths.target = notes->src->widths.min_addr;
1450 	else if (annotate_opts.full_addr)
1451 		notes->src->widths.target = BITS_PER_LONG / 4;
1452 	else
1453 		notes->src->widths.target = notes->src->widths.max_addr;
1454 
1455 	notes->src->widths.addr = notes->src->widths.target;
1456 
1457 	if (annotate_opts.show_nr_jumps)
1458 		notes->src->widths.addr += notes->src->widths.jumps + 1;
1459 }
1460 
1461 void annotation__toggle_full_addr(struct annotation *notes, struct map_symbol *ms)
1462 {
1463 	annotate_opts.full_addr = !annotate_opts.full_addr;
1464 
1465 	if (annotate_opts.full_addr)
1466 		notes->src->start = map__objdump_2mem(ms->map, ms->sym->start);
1467 	else
1468 		notes->src->start = map__rip_2objdump(ms->map, ms->sym->start);
1469 
1470 	annotation__update_column_widths(notes);
1471 }
1472 
1473 static void annotation__calc_lines(struct annotation *notes, struct map_symbol *ms,
1474 				   struct rb_root *root)
1475 {
1476 	struct annotation_line *al;
1477 	struct rb_root tmp_root = RB_ROOT;
1478 
1479 	list_for_each_entry(al, &notes->src->source, node) {
1480 		double percent_max = 0.0;
1481 		u64 addr;
1482 		int i;
1483 
1484 		for (i = 0; i < al->data_nr; i++) {
1485 			double percent;
1486 
1487 			percent = annotation_data__percent(&al->data[i],
1488 							   annotate_opts.percent_type);
1489 
1490 			if (percent > percent_max)
1491 				percent_max = percent;
1492 		}
1493 
1494 		if (percent_max <= 0.5)
1495 			continue;
1496 
1497 		addr = map__rip_2objdump(ms->map, ms->sym->start);
1498 		al->path = get_srcline(map__dso(ms->map), addr + al->offset, NULL,
1499 				       false, true, ms->sym->start + al->offset);
1500 		insert_source_line(&tmp_root, al);
1501 	}
1502 
1503 	resort_source_line(root, &tmp_root);
1504 }
1505 
1506 static void symbol__calc_lines(struct map_symbol *ms, struct rb_root *root)
1507 {
1508 	struct annotation *notes = symbol__annotation(ms->sym);
1509 
1510 	annotation__calc_lines(notes, ms, root);
1511 }
1512 
1513 int symbol__tty_annotate2(struct map_symbol *ms, struct evsel *evsel)
1514 {
1515 	struct dso *dso = map__dso(ms->map);
1516 	struct symbol *sym = ms->sym;
1517 	struct rb_root source_line = RB_ROOT;
1518 	struct hists *hists = evsel__hists(evsel);
1519 	char buf[1024];
1520 	int err;
1521 
1522 	err = symbol__annotate2(ms, evsel, NULL);
1523 	if (err) {
1524 		char msg[BUFSIZ];
1525 
1526 		dso->annotate_warned = true;
1527 		symbol__strerror_disassemble(ms, err, msg, sizeof(msg));
1528 		ui__error("Couldn't annotate %s:\n%s", sym->name, msg);
1529 		return -1;
1530 	}
1531 
1532 	if (annotate_opts.print_lines) {
1533 		srcline_full_filename = annotate_opts.full_path;
1534 		symbol__calc_lines(ms, &source_line);
1535 		print_summary(&source_line, dso->long_name);
1536 	}
1537 
1538 	hists__scnprintf_title(hists, buf, sizeof(buf));
1539 	fprintf(stdout, "%s, [percent: %s]\n%s() %s\n",
1540 		buf, percent_type_str(annotate_opts.percent_type), sym->name,
1541 		dso->long_name);
1542 	symbol__annotate_fprintf2(sym, stdout);
1543 
1544 	annotated_source__purge(symbol__annotation(sym)->src);
1545 
1546 	return 0;
1547 }
1548 
1549 int symbol__tty_annotate(struct map_symbol *ms, struct evsel *evsel)
1550 {
1551 	struct dso *dso = map__dso(ms->map);
1552 	struct symbol *sym = ms->sym;
1553 	struct rb_root source_line = RB_ROOT;
1554 	int err;
1555 
1556 	err = symbol__annotate(ms, evsel, NULL);
1557 	if (err) {
1558 		char msg[BUFSIZ];
1559 
1560 		dso->annotate_warned = true;
1561 		symbol__strerror_disassemble(ms, err, msg, sizeof(msg));
1562 		ui__error("Couldn't annotate %s:\n%s", sym->name, msg);
1563 		return -1;
1564 	}
1565 
1566 	symbol__calc_percent(sym, evsel);
1567 
1568 	if (annotate_opts.print_lines) {
1569 		srcline_full_filename = annotate_opts.full_path;
1570 		symbol__calc_lines(ms, &source_line);
1571 		print_summary(&source_line, dso->long_name);
1572 	}
1573 
1574 	symbol__annotate_printf(ms, evsel);
1575 
1576 	annotated_source__purge(symbol__annotation(sym)->src);
1577 
1578 	return 0;
1579 }
1580 
1581 bool ui__has_annotation(void)
1582 {
1583 	return use_browser == 1 && perf_hpp_list.sym;
1584 }
1585 
1586 
1587 static double annotation_line__max_percent(struct annotation_line *al,
1588 					   struct annotation *notes,
1589 					   unsigned int percent_type)
1590 {
1591 	double percent_max = 0.0;
1592 	int i;
1593 
1594 	for (i = 0; i < notes->src->nr_events; i++) {
1595 		double percent;
1596 
1597 		percent = annotation_data__percent(&al->data[i],
1598 						   percent_type);
1599 
1600 		if (percent > percent_max)
1601 			percent_max = percent;
1602 	}
1603 
1604 	return percent_max;
1605 }
1606 
1607 static void disasm_line__write(struct disasm_line *dl, struct annotation *notes,
1608 			       void *obj, char *bf, size_t size,
1609 			       void (*obj__printf)(void *obj, const char *fmt, ...),
1610 			       void (*obj__write_graph)(void *obj, int graph))
1611 {
1612 	if (dl->ins.ops && dl->ins.ops->scnprintf) {
1613 		if (ins__is_jump(&dl->ins)) {
1614 			bool fwd;
1615 
1616 			if (dl->ops.target.outside)
1617 				goto call_like;
1618 			fwd = dl->ops.target.offset > dl->al.offset;
1619 			obj__write_graph(obj, fwd ? DARROW_CHAR : UARROW_CHAR);
1620 			obj__printf(obj, " ");
1621 		} else if (ins__is_call(&dl->ins)) {
1622 call_like:
1623 			obj__write_graph(obj, RARROW_CHAR);
1624 			obj__printf(obj, " ");
1625 		} else if (ins__is_ret(&dl->ins)) {
1626 			obj__write_graph(obj, LARROW_CHAR);
1627 			obj__printf(obj, " ");
1628 		} else {
1629 			obj__printf(obj, "  ");
1630 		}
1631 	} else {
1632 		obj__printf(obj, "  ");
1633 	}
1634 
1635 	disasm_line__scnprintf(dl, bf, size, !annotate_opts.use_offset,
1636 			       notes->src->widths.max_ins_name);
1637 }
1638 
1639 static void ipc_coverage_string(char *bf, int size, struct annotation *notes)
1640 {
1641 	double ipc = 0.0, coverage = 0.0;
1642 	struct annotated_branch *branch = annotation__get_branch(notes);
1643 
1644 	if (branch && branch->hit_cycles)
1645 		ipc = branch->hit_insn / ((double)branch->hit_cycles);
1646 
1647 	if (branch && branch->total_insn) {
1648 		coverage = branch->cover_insn * 100.0 /
1649 			((double)branch->total_insn);
1650 	}
1651 
1652 	scnprintf(bf, size, "(Average IPC: %.2f, IPC Coverage: %.1f%%)",
1653 		  ipc, coverage);
1654 }
1655 
1656 static void __annotation_line__write(struct annotation_line *al, struct annotation *notes,
1657 				     bool first_line, bool current_entry, bool change_color, int width,
1658 				     void *obj, unsigned int percent_type,
1659 				     int  (*obj__set_color)(void *obj, int color),
1660 				     void (*obj__set_percent_color)(void *obj, double percent, bool current),
1661 				     int  (*obj__set_jumps_percent_color)(void *obj, int nr, bool current),
1662 				     void (*obj__printf)(void *obj, const char *fmt, ...),
1663 				     void (*obj__write_graph)(void *obj, int graph))
1664 
1665 {
1666 	double percent_max = annotation_line__max_percent(al, notes, percent_type);
1667 	int pcnt_width = annotation__pcnt_width(notes),
1668 	    cycles_width = annotation__cycles_width(notes);
1669 	bool show_title = false;
1670 	char bf[256];
1671 	int printed;
1672 
1673 	if (first_line && (al->offset == -1 || percent_max == 0.0)) {
1674 		if (notes->branch && al->cycles) {
1675 			if (al->cycles->ipc == 0.0 && al->cycles->avg == 0)
1676 				show_title = true;
1677 		} else
1678 			show_title = true;
1679 	}
1680 
1681 	if (al->offset != -1 && percent_max != 0.0) {
1682 		int i;
1683 
1684 		for (i = 0; i < notes->src->nr_events; i++) {
1685 			double percent;
1686 
1687 			percent = annotation_data__percent(&al->data[i], percent_type);
1688 
1689 			obj__set_percent_color(obj, percent, current_entry);
1690 			if (symbol_conf.show_total_period) {
1691 				obj__printf(obj, "%11" PRIu64 " ", al->data[i].he.period);
1692 			} else if (symbol_conf.show_nr_samples) {
1693 				obj__printf(obj, "%6" PRIu64 " ",
1694 						   al->data[i].he.nr_samples);
1695 			} else {
1696 				obj__printf(obj, "%6.2f ", percent);
1697 			}
1698 		}
1699 	} else {
1700 		obj__set_percent_color(obj, 0, current_entry);
1701 
1702 		if (!show_title)
1703 			obj__printf(obj, "%-*s", pcnt_width, " ");
1704 		else {
1705 			obj__printf(obj, "%-*s", pcnt_width,
1706 					   symbol_conf.show_total_period ? "Period" :
1707 					   symbol_conf.show_nr_samples ? "Samples" : "Percent");
1708 		}
1709 	}
1710 
1711 	if (notes->branch) {
1712 		if (al->cycles && al->cycles->ipc)
1713 			obj__printf(obj, "%*.2f ", ANNOTATION__IPC_WIDTH - 1, al->cycles->ipc);
1714 		else if (!show_title)
1715 			obj__printf(obj, "%*s", ANNOTATION__IPC_WIDTH, " ");
1716 		else
1717 			obj__printf(obj, "%*s ", ANNOTATION__IPC_WIDTH - 1, "IPC");
1718 
1719 		if (!annotate_opts.show_minmax_cycle) {
1720 			if (al->cycles && al->cycles->avg)
1721 				obj__printf(obj, "%*" PRIu64 " ",
1722 					   ANNOTATION__CYCLES_WIDTH - 1, al->cycles->avg);
1723 			else if (!show_title)
1724 				obj__printf(obj, "%*s",
1725 					    ANNOTATION__CYCLES_WIDTH, " ");
1726 			else
1727 				obj__printf(obj, "%*s ",
1728 					    ANNOTATION__CYCLES_WIDTH - 1,
1729 					    "Cycle");
1730 		} else {
1731 			if (al->cycles) {
1732 				char str[32];
1733 
1734 				scnprintf(str, sizeof(str),
1735 					"%" PRIu64 "(%" PRIu64 "/%" PRIu64 ")",
1736 					al->cycles->avg, al->cycles->min,
1737 					al->cycles->max);
1738 
1739 				obj__printf(obj, "%*s ",
1740 					    ANNOTATION__MINMAX_CYCLES_WIDTH - 1,
1741 					    str);
1742 			} else if (!show_title)
1743 				obj__printf(obj, "%*s",
1744 					    ANNOTATION__MINMAX_CYCLES_WIDTH,
1745 					    " ");
1746 			else
1747 				obj__printf(obj, "%*s ",
1748 					    ANNOTATION__MINMAX_CYCLES_WIDTH - 1,
1749 					    "Cycle(min/max)");
1750 		}
1751 
1752 		if (show_title && !*al->line) {
1753 			ipc_coverage_string(bf, sizeof(bf), notes);
1754 			obj__printf(obj, "%*s", ANNOTATION__AVG_IPC_WIDTH, bf);
1755 		}
1756 	}
1757 
1758 	obj__printf(obj, " ");
1759 
1760 	if (!*al->line)
1761 		obj__printf(obj, "%-*s", width - pcnt_width - cycles_width, " ");
1762 	else if (al->offset == -1) {
1763 		if (al->line_nr && annotate_opts.show_linenr)
1764 			printed = scnprintf(bf, sizeof(bf), "%-*d ",
1765 					    notes->src->widths.addr + 1, al->line_nr);
1766 		else
1767 			printed = scnprintf(bf, sizeof(bf), "%-*s  ",
1768 					    notes->src->widths.addr, " ");
1769 		obj__printf(obj, bf);
1770 		obj__printf(obj, "%-*s", width - printed - pcnt_width - cycles_width + 1, al->line);
1771 	} else {
1772 		u64 addr = al->offset;
1773 		int color = -1;
1774 
1775 		if (!annotate_opts.use_offset)
1776 			addr += notes->src->start;
1777 
1778 		if (!annotate_opts.use_offset) {
1779 			printed = scnprintf(bf, sizeof(bf), "%" PRIx64 ": ", addr);
1780 		} else {
1781 			if (al->jump_sources &&
1782 			    annotate_opts.offset_level >= ANNOTATION__OFFSET_JUMP_TARGETS) {
1783 				if (annotate_opts.show_nr_jumps) {
1784 					int prev;
1785 					printed = scnprintf(bf, sizeof(bf), "%*d ",
1786 							    notes->src->widths.jumps,
1787 							    al->jump_sources);
1788 					prev = obj__set_jumps_percent_color(obj, al->jump_sources,
1789 									    current_entry);
1790 					obj__printf(obj, bf);
1791 					obj__set_color(obj, prev);
1792 				}
1793 print_addr:
1794 				printed = scnprintf(bf, sizeof(bf), "%*" PRIx64 ": ",
1795 						    notes->src->widths.target, addr);
1796 			} else if (ins__is_call(&disasm_line(al)->ins) &&
1797 				   annotate_opts.offset_level >= ANNOTATION__OFFSET_CALL) {
1798 				goto print_addr;
1799 			} else if (annotate_opts.offset_level == ANNOTATION__MAX_OFFSET_LEVEL) {
1800 				goto print_addr;
1801 			} else {
1802 				printed = scnprintf(bf, sizeof(bf), "%-*s  ",
1803 						    notes->src->widths.addr, " ");
1804 			}
1805 		}
1806 
1807 		if (change_color)
1808 			color = obj__set_color(obj, HE_COLORSET_ADDR);
1809 		obj__printf(obj, bf);
1810 		if (change_color)
1811 			obj__set_color(obj, color);
1812 
1813 		disasm_line__write(disasm_line(al), notes, obj, bf, sizeof(bf), obj__printf, obj__write_graph);
1814 
1815 		obj__printf(obj, "%-*s", width - pcnt_width - cycles_width - 3 - printed, bf);
1816 	}
1817 
1818 }
1819 
1820 void annotation_line__write(struct annotation_line *al, struct annotation *notes,
1821 			    struct annotation_write_ops *wops)
1822 {
1823 	__annotation_line__write(al, notes, wops->first_line, wops->current_entry,
1824 				 wops->change_color, wops->width, wops->obj,
1825 				 annotate_opts.percent_type,
1826 				 wops->set_color, wops->set_percent_color,
1827 				 wops->set_jumps_percent_color, wops->printf,
1828 				 wops->write_graph);
1829 }
1830 
1831 int symbol__annotate2(struct map_symbol *ms, struct evsel *evsel,
1832 		      struct arch **parch)
1833 {
1834 	struct symbol *sym = ms->sym;
1835 	struct annotation *notes = symbol__annotation(sym);
1836 	size_t size = symbol__size(sym);
1837 	int nr_pcnt = 1, err;
1838 
1839 	if (evsel__is_group_event(evsel))
1840 		nr_pcnt = evsel->core.nr_members;
1841 
1842 	err = symbol__annotate(ms, evsel, parch);
1843 	if (err)
1844 		return err;
1845 
1846 	symbol__calc_percent(sym, evsel);
1847 
1848 	annotation__set_index(notes);
1849 	annotation__mark_jump_targets(notes, sym);
1850 
1851 	err = annotation__compute_ipc(notes, size);
1852 	if (err)
1853 		return err;
1854 
1855 	annotation__init_column_widths(notes, sym);
1856 	notes->src->nr_events = nr_pcnt;
1857 
1858 	annotation__update_column_widths(notes);
1859 	sym->annotate2 = 1;
1860 
1861 	return 0;
1862 }
1863 
1864 static int annotation__config(const char *var, const char *value, void *data)
1865 {
1866 	struct annotation_options *opt = data;
1867 
1868 	if (!strstarts(var, "annotate."))
1869 		return 0;
1870 
1871 	if (!strcmp(var, "annotate.offset_level")) {
1872 		perf_config_u8(&opt->offset_level, "offset_level", value);
1873 
1874 		if (opt->offset_level > ANNOTATION__MAX_OFFSET_LEVEL)
1875 			opt->offset_level = ANNOTATION__MAX_OFFSET_LEVEL;
1876 		else if (opt->offset_level < ANNOTATION__MIN_OFFSET_LEVEL)
1877 			opt->offset_level = ANNOTATION__MIN_OFFSET_LEVEL;
1878 	} else if (!strcmp(var, "annotate.hide_src_code")) {
1879 		opt->hide_src_code = perf_config_bool("hide_src_code", value);
1880 	} else if (!strcmp(var, "annotate.jump_arrows")) {
1881 		opt->jump_arrows = perf_config_bool("jump_arrows", value);
1882 	} else if (!strcmp(var, "annotate.show_linenr")) {
1883 		opt->show_linenr = perf_config_bool("show_linenr", value);
1884 	} else if (!strcmp(var, "annotate.show_nr_jumps")) {
1885 		opt->show_nr_jumps = perf_config_bool("show_nr_jumps", value);
1886 	} else if (!strcmp(var, "annotate.show_nr_samples")) {
1887 		symbol_conf.show_nr_samples = perf_config_bool("show_nr_samples",
1888 								value);
1889 	} else if (!strcmp(var, "annotate.show_total_period")) {
1890 		symbol_conf.show_total_period = perf_config_bool("show_total_period",
1891 								value);
1892 	} else if (!strcmp(var, "annotate.use_offset")) {
1893 		opt->use_offset = perf_config_bool("use_offset", value);
1894 	} else if (!strcmp(var, "annotate.disassembler_style")) {
1895 		opt->disassembler_style = strdup(value);
1896 		if (!opt->disassembler_style) {
1897 			pr_err("Not enough memory for annotate.disassembler_style\n");
1898 			return -1;
1899 		}
1900 	} else if (!strcmp(var, "annotate.objdump")) {
1901 		opt->objdump_path = strdup(value);
1902 		if (!opt->objdump_path) {
1903 			pr_err("Not enough memory for annotate.objdump\n");
1904 			return -1;
1905 		}
1906 	} else if (!strcmp(var, "annotate.addr2line")) {
1907 		symbol_conf.addr2line_path = strdup(value);
1908 		if (!symbol_conf.addr2line_path) {
1909 			pr_err("Not enough memory for annotate.addr2line\n");
1910 			return -1;
1911 		}
1912 	} else if (!strcmp(var, "annotate.demangle")) {
1913 		symbol_conf.demangle = perf_config_bool("demangle", value);
1914 	} else if (!strcmp(var, "annotate.demangle_kernel")) {
1915 		symbol_conf.demangle_kernel = perf_config_bool("demangle_kernel", value);
1916 	} else {
1917 		pr_debug("%s variable unknown, ignoring...", var);
1918 	}
1919 
1920 	return 0;
1921 }
1922 
1923 void annotation_options__init(void)
1924 {
1925 	struct annotation_options *opt = &annotate_opts;
1926 
1927 	memset(opt, 0, sizeof(*opt));
1928 
1929 	/* Default values. */
1930 	opt->use_offset = true;
1931 	opt->jump_arrows = true;
1932 	opt->annotate_src = true;
1933 	opt->offset_level = ANNOTATION__OFFSET_JUMP_TARGETS;
1934 	opt->percent_type = PERCENT_PERIOD_LOCAL;
1935 }
1936 
1937 void annotation_options__exit(void)
1938 {
1939 	zfree(&annotate_opts.disassembler_style);
1940 	zfree(&annotate_opts.objdump_path);
1941 }
1942 
1943 void annotation_config__init(void)
1944 {
1945 	perf_config(annotation__config, &annotate_opts);
1946 }
1947 
1948 static unsigned int parse_percent_type(char *str1, char *str2)
1949 {
1950 	unsigned int type = (unsigned int) -1;
1951 
1952 	if (!strcmp("period", str1)) {
1953 		if (!strcmp("local", str2))
1954 			type = PERCENT_PERIOD_LOCAL;
1955 		else if (!strcmp("global", str2))
1956 			type = PERCENT_PERIOD_GLOBAL;
1957 	}
1958 
1959 	if (!strcmp("hits", str1)) {
1960 		if (!strcmp("local", str2))
1961 			type = PERCENT_HITS_LOCAL;
1962 		else if (!strcmp("global", str2))
1963 			type = PERCENT_HITS_GLOBAL;
1964 	}
1965 
1966 	return type;
1967 }
1968 
1969 int annotate_parse_percent_type(const struct option *opt __maybe_unused, const char *_str,
1970 				int unset __maybe_unused)
1971 {
1972 	unsigned int type;
1973 	char *str1, *str2;
1974 	int err = -1;
1975 
1976 	str1 = strdup(_str);
1977 	if (!str1)
1978 		return -ENOMEM;
1979 
1980 	str2 = strchr(str1, '-');
1981 	if (!str2)
1982 		goto out;
1983 
1984 	*str2++ = 0;
1985 
1986 	type = parse_percent_type(str1, str2);
1987 	if (type == (unsigned int) -1)
1988 		type = parse_percent_type(str2, str1);
1989 	if (type != (unsigned int) -1) {
1990 		annotate_opts.percent_type = type;
1991 		err = 0;
1992 	}
1993 
1994 out:
1995 	free(str1);
1996 	return err;
1997 }
1998 
1999 int annotate_check_args(void)
2000 {
2001 	struct annotation_options *args = &annotate_opts;
2002 
2003 	if (args->prefix_strip && !args->prefix) {
2004 		pr_err("--prefix-strip requires --prefix\n");
2005 		return -1;
2006 	}
2007 	return 0;
2008 }
2009 
2010 /*
2011  * Get register number and access offset from the given instruction.
2012  * It assumes AT&T x86 asm format like OFFSET(REG).  Maybe it needs
2013  * to revisit the format when it handles different architecture.
2014  * Fills @reg and @offset when return 0.
2015  */
2016 static int extract_reg_offset(struct arch *arch, const char *str,
2017 			      struct annotated_op_loc *op_loc)
2018 {
2019 	char *p;
2020 	char *regname;
2021 
2022 	if (arch->objdump.register_char == 0)
2023 		return -1;
2024 
2025 	/*
2026 	 * It should start from offset, but it's possible to skip 0
2027 	 * in the asm.  So 0(%rax) should be same as (%rax).
2028 	 *
2029 	 * However, it also start with a segment select register like
2030 	 * %gs:0x18(%rbx).  In that case it should skip the part.
2031 	 */
2032 	if (*str == arch->objdump.register_char) {
2033 		if (arch__is(arch, "x86")) {
2034 			/* FIXME: Handle other segment registers */
2035 			if (!strncmp(str, "%gs:", 4))
2036 				op_loc->segment = INSN_SEG_X86_GS;
2037 		}
2038 
2039 		while (*str && !isdigit(*str) &&
2040 		       *str != arch->objdump.memory_ref_char)
2041 			str++;
2042 	}
2043 
2044 	op_loc->offset = strtol(str, &p, 0);
2045 
2046 	p = strchr(p, arch->objdump.register_char);
2047 	if (p == NULL)
2048 		return -1;
2049 
2050 	regname = strdup(p);
2051 	if (regname == NULL)
2052 		return -1;
2053 
2054 	op_loc->reg1 = get_dwarf_regnum(regname, 0);
2055 	free(regname);
2056 
2057 	/* Get the second register */
2058 	if (op_loc->multi_regs) {
2059 		p = strchr(p + 1, arch->objdump.register_char);
2060 		if (p == NULL)
2061 			return -1;
2062 
2063 		regname = strdup(p);
2064 		if (regname == NULL)
2065 			return -1;
2066 
2067 		op_loc->reg2 = get_dwarf_regnum(regname, 0);
2068 		free(regname);
2069 	}
2070 	return 0;
2071 }
2072 
2073 /**
2074  * annotate_get_insn_location - Get location of instruction
2075  * @arch: the architecture info
2076  * @dl: the target instruction
2077  * @loc: a buffer to save the data
2078  *
2079  * Get detailed location info (register and offset) in the instruction.
2080  * It needs both source and target operand and whether it accesses a
2081  * memory location.  The offset field is meaningful only when the
2082  * corresponding mem flag is set.  The reg2 field is meaningful only
2083  * when multi_regs flag is set.
2084  *
2085  * Some examples on x86:
2086  *
2087  *   mov  (%rax), %rcx   # src_reg1 = rax, src_mem = 1, src_offset = 0
2088  *                       # dst_reg1 = rcx, dst_mem = 0
2089  *
2090  *   mov  0x18, %r8      # src_reg1 = -1, src_mem = 0
2091  *                       # dst_reg1 = r8, dst_mem = 0
2092  *
2093  *   mov  %rsi, 8(%rbx,%rcx,4)  # src_reg1 = rsi, src_mem = 0, dst_multi_regs = 0
2094  *                              # dst_reg1 = rbx, dst_reg2 = rcx, dst_mem = 1
2095  *                              # dst_multi_regs = 1, dst_offset = 8
2096  */
2097 int annotate_get_insn_location(struct arch *arch, struct disasm_line *dl,
2098 			       struct annotated_insn_loc *loc)
2099 {
2100 	struct ins_operands *ops;
2101 	struct annotated_op_loc *op_loc;
2102 	int i;
2103 
2104 	if (ins__is_lock(&dl->ins))
2105 		ops = dl->ops.locked.ops;
2106 	else
2107 		ops = &dl->ops;
2108 
2109 	if (ops == NULL)
2110 		return -1;
2111 
2112 	memset(loc, 0, sizeof(*loc));
2113 
2114 	for_each_insn_op_loc(loc, i, op_loc) {
2115 		const char *insn_str = ops->source.raw;
2116 		bool multi_regs = ops->source.multi_regs;
2117 
2118 		if (i == INSN_OP_TARGET) {
2119 			insn_str = ops->target.raw;
2120 			multi_regs = ops->target.multi_regs;
2121 		}
2122 
2123 		/* Invalidate the register by default */
2124 		op_loc->reg1 = -1;
2125 		op_loc->reg2 = -1;
2126 
2127 		if (insn_str == NULL)
2128 			continue;
2129 
2130 		if (strchr(insn_str, arch->objdump.memory_ref_char)) {
2131 			op_loc->mem_ref = true;
2132 			op_loc->multi_regs = multi_regs;
2133 			extract_reg_offset(arch, insn_str, op_loc);
2134 		} else {
2135 			char *s, *p = NULL;
2136 
2137 			if (arch__is(arch, "x86")) {
2138 				/* FIXME: Handle other segment registers */
2139 				if (!strncmp(insn_str, "%gs:", 4)) {
2140 					op_loc->segment = INSN_SEG_X86_GS;
2141 					op_loc->offset = strtol(insn_str + 4,
2142 								&p, 0);
2143 					if (p && p != insn_str + 4)
2144 						op_loc->imm = true;
2145 					continue;
2146 				}
2147 			}
2148 
2149 			s = strdup(insn_str);
2150 			if (s == NULL)
2151 				return -1;
2152 
2153 			if (*s == arch->objdump.register_char)
2154 				op_loc->reg1 = get_dwarf_regnum(s, 0);
2155 			else if (*s == arch->objdump.imm_char) {
2156 				op_loc->offset = strtol(s + 1, &p, 0);
2157 				if (p && p != s + 1)
2158 					op_loc->imm = true;
2159 			}
2160 			free(s);
2161 		}
2162 	}
2163 
2164 	return 0;
2165 }
2166 
2167 static struct disasm_line *find_disasm_line(struct symbol *sym, u64 ip,
2168 					    bool allow_update)
2169 {
2170 	struct disasm_line *dl;
2171 	struct annotation *notes;
2172 
2173 	notes = symbol__annotation(sym);
2174 
2175 	list_for_each_entry(dl, &notes->src->source, al.node) {
2176 		if (dl->al.offset == -1)
2177 			continue;
2178 
2179 		if (sym->start + dl->al.offset == ip) {
2180 			/*
2181 			 * llvm-objdump places "lock" in a separate line and
2182 			 * in that case, we want to get the next line.
2183 			 */
2184 			if (ins__is_lock(&dl->ins) &&
2185 			    *dl->ops.raw == '\0' && allow_update) {
2186 				ip++;
2187 				continue;
2188 			}
2189 			return dl;
2190 		}
2191 	}
2192 	return NULL;
2193 }
2194 
2195 static struct annotated_item_stat *annotate_data_stat(struct list_head *head,
2196 						      const char *name)
2197 {
2198 	struct annotated_item_stat *istat;
2199 
2200 	list_for_each_entry(istat, head, list) {
2201 		if (!strcmp(istat->name, name))
2202 			return istat;
2203 	}
2204 
2205 	istat = zalloc(sizeof(*istat));
2206 	if (istat == NULL)
2207 		return NULL;
2208 
2209 	istat->name = strdup(name);
2210 	if (istat->name == NULL) {
2211 		free(istat);
2212 		return NULL;
2213 	}
2214 
2215 	list_add_tail(&istat->list, head);
2216 	return istat;
2217 }
2218 
2219 static bool is_stack_operation(struct arch *arch, struct disasm_line *dl)
2220 {
2221 	if (arch__is(arch, "x86")) {
2222 		if (!strncmp(dl->ins.name, "push", 4) ||
2223 		    !strncmp(dl->ins.name, "pop", 3) ||
2224 		    !strncmp(dl->ins.name, "ret", 3))
2225 			return true;
2226 	}
2227 
2228 	return false;
2229 }
2230 
2231 static bool is_stack_canary(struct arch *arch, struct annotated_op_loc *loc)
2232 {
2233 	/* On x86_64, %gs:40 is used for stack canary */
2234 	if (arch__is(arch, "x86")) {
2235 		if (loc->segment == INSN_SEG_X86_GS && loc->imm &&
2236 		    loc->offset == 40)
2237 			return true;
2238 	}
2239 
2240 	return false;
2241 }
2242 
2243 static struct disasm_line *
2244 annotation__prev_asm_line(struct annotation *notes, struct disasm_line *curr)
2245 {
2246 	struct list_head *sources = &notes->src->source;
2247 	struct disasm_line *prev;
2248 
2249 	if (curr == list_first_entry(sources, struct disasm_line, al.node))
2250 		return NULL;
2251 
2252 	prev = list_prev_entry(curr, al.node);
2253 	while (prev->al.offset == -1 &&
2254 	       prev != list_first_entry(sources, struct disasm_line, al.node))
2255 		prev = list_prev_entry(prev, al.node);
2256 
2257 	if (prev->al.offset == -1)
2258 		return NULL;
2259 
2260 	return prev;
2261 }
2262 
2263 static struct disasm_line *
2264 annotation__next_asm_line(struct annotation *notes, struct disasm_line *curr)
2265 {
2266 	struct list_head *sources = &notes->src->source;
2267 	struct disasm_line *next;
2268 
2269 	if (curr == list_last_entry(sources, struct disasm_line, al.node))
2270 		return NULL;
2271 
2272 	next = list_next_entry(curr, al.node);
2273 	while (next->al.offset == -1 &&
2274 	       next != list_last_entry(sources, struct disasm_line, al.node))
2275 		next = list_next_entry(next, al.node);
2276 
2277 	if (next->al.offset == -1)
2278 		return NULL;
2279 
2280 	return next;
2281 }
2282 
2283 u64 annotate_calc_pcrel(struct map_symbol *ms, u64 ip, int offset,
2284 			struct disasm_line *dl)
2285 {
2286 	struct annotation *notes;
2287 	struct disasm_line *next;
2288 	u64 addr;
2289 
2290 	notes = symbol__annotation(ms->sym);
2291 	/*
2292 	 * PC-relative addressing starts from the next instruction address
2293 	 * But the IP is for the current instruction.  Since disasm_line
2294 	 * doesn't have the instruction size, calculate it using the next
2295 	 * disasm_line.  If it's the last one, we can use symbol's end
2296 	 * address directly.
2297 	 */
2298 	next = annotation__next_asm_line(notes, dl);
2299 	if (next == NULL)
2300 		addr = ms->sym->end + offset;
2301 	else
2302 		addr = ip + (next->al.offset - dl->al.offset) + offset;
2303 
2304 	return map__rip_2objdump(ms->map, addr);
2305 }
2306 
2307 /**
2308  * hist_entry__get_data_type - find data type for given hist entry
2309  * @he: hist entry
2310  *
2311  * This function first annotates the instruction at @he->ip and extracts
2312  * register and offset info from it.  Then it searches the DWARF debug
2313  * info to get a variable and type information using the address, register,
2314  * and offset.
2315  */
2316 struct annotated_data_type *hist_entry__get_data_type(struct hist_entry *he)
2317 {
2318 	struct map_symbol *ms = &he->ms;
2319 	struct evsel *evsel = hists_to_evsel(he->hists);
2320 	struct arch *arch;
2321 	struct disasm_line *dl;
2322 	struct annotated_insn_loc loc;
2323 	struct annotated_op_loc *op_loc;
2324 	struct annotated_data_type *mem_type;
2325 	struct annotated_item_stat *istat;
2326 	u64 ip = he->ip;
2327 	int i;
2328 
2329 	ann_data_stat.total++;
2330 
2331 	if (ms->map == NULL || ms->sym == NULL) {
2332 		ann_data_stat.no_sym++;
2333 		return NULL;
2334 	}
2335 
2336 	if (!symbol_conf.init_annotation) {
2337 		ann_data_stat.no_sym++;
2338 		return NULL;
2339 	}
2340 
2341 	/* Make sure it has the disasm of the function */
2342 	if (symbol__annotate(ms, evsel, &arch) < 0) {
2343 		ann_data_stat.no_insn++;
2344 		return NULL;
2345 	}
2346 
2347 	/*
2348 	 * Get a disasm to extract the location from the insn.
2349 	 * This is too slow...
2350 	 */
2351 	dl = find_disasm_line(ms->sym, ip, /*allow_update=*/true);
2352 	if (dl == NULL) {
2353 		ann_data_stat.no_insn++;
2354 		return NULL;
2355 	}
2356 
2357 retry:
2358 	istat = annotate_data_stat(&ann_insn_stat, dl->ins.name);
2359 	if (istat == NULL) {
2360 		ann_data_stat.no_insn++;
2361 		return NULL;
2362 	}
2363 
2364 	if (annotate_get_insn_location(arch, dl, &loc) < 0) {
2365 		ann_data_stat.no_insn_ops++;
2366 		istat->bad++;
2367 		return NULL;
2368 	}
2369 
2370 	if (is_stack_operation(arch, dl)) {
2371 		istat->good++;
2372 		he->mem_type_off = 0;
2373 		return &stackop_type;
2374 	}
2375 
2376 	for_each_insn_op_loc(&loc, i, op_loc) {
2377 		struct data_loc_info dloc = {
2378 			.arch = arch,
2379 			.thread = he->thread,
2380 			.ms = ms,
2381 			/* Recalculate IP for LOCK prefix or insn fusion */
2382 			.ip = ms->sym->start + dl->al.offset,
2383 			.cpumode = he->cpumode,
2384 			.op = op_loc,
2385 		};
2386 
2387 		if (!op_loc->mem_ref && op_loc->segment == INSN_SEG_NONE)
2388 			continue;
2389 
2390 		/* Recalculate IP because of LOCK prefix or insn fusion */
2391 		ip = ms->sym->start + dl->al.offset;
2392 
2393 		/* PC-relative addressing */
2394 		if (op_loc->reg1 == DWARF_REG_PC) {
2395 			dloc.var_addr = annotate_calc_pcrel(ms, dloc.ip,
2396 							    op_loc->offset, dl);
2397 		}
2398 
2399 		/* This CPU access in kernel - pretend PC-relative addressing */
2400 		if (map__dso(ms->map)->kernel && arch__is(arch, "x86") &&
2401 		    op_loc->segment == INSN_SEG_X86_GS && op_loc->imm) {
2402 			dloc.var_addr = op_loc->offset;
2403 			op_loc->reg1 = DWARF_REG_PC;
2404 		}
2405 
2406 		mem_type = find_data_type(&dloc);
2407 
2408 		if (mem_type == NULL && is_stack_canary(arch, op_loc)) {
2409 			istat->good++;
2410 			he->mem_type_off = 0;
2411 			return &canary_type;
2412 		}
2413 
2414 		if (mem_type)
2415 			istat->good++;
2416 		else
2417 			istat->bad++;
2418 
2419 		if (symbol_conf.annotate_data_sample) {
2420 			annotated_data_type__update_samples(mem_type, evsel,
2421 							    dloc.type_offset,
2422 							    he->stat.nr_events,
2423 							    he->stat.period);
2424 		}
2425 		he->mem_type_off = dloc.type_offset;
2426 		return mem_type;
2427 	}
2428 
2429 	/*
2430 	 * Some instructions can be fused and the actual memory access came
2431 	 * from the previous instruction.
2432 	 */
2433 	if (dl->al.offset > 0) {
2434 		struct annotation *notes;
2435 		struct disasm_line *prev_dl;
2436 
2437 		notes = symbol__annotation(ms->sym);
2438 		prev_dl = annotation__prev_asm_line(notes, dl);
2439 
2440 		if (prev_dl && ins__is_fused(arch, prev_dl->ins.name, dl->ins.name)) {
2441 			dl = prev_dl;
2442 			goto retry;
2443 		}
2444 	}
2445 
2446 	ann_data_stat.no_mem_ops++;
2447 	istat->bad++;
2448 	return NULL;
2449 }
2450 
2451 /* Basic block traversal (BFS) data structure */
2452 struct basic_block_data {
2453 	struct list_head queue;
2454 	struct list_head visited;
2455 };
2456 
2457 /*
2458  * During the traversal, it needs to know the parent block where the current
2459  * block block started from.  Note that single basic block can be parent of
2460  * two child basic blocks (in case of condition jump).
2461  */
2462 struct basic_block_link {
2463 	struct list_head node;
2464 	struct basic_block_link *parent;
2465 	struct annotated_basic_block *bb;
2466 };
2467 
2468 /* Check any of basic block in the list already has the offset */
2469 static bool basic_block_has_offset(struct list_head *head, s64 offset)
2470 {
2471 	struct basic_block_link *link;
2472 
2473 	list_for_each_entry(link, head, node) {
2474 		s64 begin_offset = link->bb->begin->al.offset;
2475 		s64 end_offset = link->bb->end->al.offset;
2476 
2477 		if (begin_offset <= offset && offset <= end_offset)
2478 			return true;
2479 	}
2480 	return false;
2481 }
2482 
2483 static bool is_new_basic_block(struct basic_block_data *bb_data,
2484 			       struct disasm_line *dl)
2485 {
2486 	s64 offset = dl->al.offset;
2487 
2488 	if (basic_block_has_offset(&bb_data->visited, offset))
2489 		return false;
2490 	if (basic_block_has_offset(&bb_data->queue, offset))
2491 		return false;
2492 	return true;
2493 }
2494 
2495 /* Add a basic block starting from dl and link it to the parent */
2496 static int add_basic_block(struct basic_block_data *bb_data,
2497 			   struct basic_block_link *parent,
2498 			   struct disasm_line *dl)
2499 {
2500 	struct annotated_basic_block *bb;
2501 	struct basic_block_link *link;
2502 
2503 	if (dl == NULL)
2504 		return -1;
2505 
2506 	if (!is_new_basic_block(bb_data, dl))
2507 		return 0;
2508 
2509 	bb = zalloc(sizeof(*bb));
2510 	if (bb == NULL)
2511 		return -1;
2512 
2513 	bb->begin = dl;
2514 	bb->end = dl;
2515 	INIT_LIST_HEAD(&bb->list);
2516 
2517 	link = malloc(sizeof(*link));
2518 	if (link == NULL) {
2519 		free(bb);
2520 		return -1;
2521 	}
2522 
2523 	link->bb = bb;
2524 	link->parent = parent;
2525 	list_add_tail(&link->node, &bb_data->queue);
2526 	return 0;
2527 }
2528 
2529 /* Returns true when it finds the target in the current basic block */
2530 static bool process_basic_block(struct basic_block_data *bb_data,
2531 				struct basic_block_link *link,
2532 				struct symbol *sym, u64 target)
2533 {
2534 	struct disasm_line *dl, *next_dl, *last_dl;
2535 	struct annotation *notes = symbol__annotation(sym);
2536 	bool found = false;
2537 
2538 	dl = link->bb->begin;
2539 	/* Check if it's already visited */
2540 	if (basic_block_has_offset(&bb_data->visited, dl->al.offset))
2541 		return false;
2542 
2543 	last_dl = list_last_entry(&notes->src->source,
2544 				  struct disasm_line, al.node);
2545 	if (last_dl->al.offset == -1)
2546 		last_dl = annotation__prev_asm_line(notes, last_dl);
2547 
2548 	if (last_dl == NULL)
2549 		return false;
2550 
2551 	list_for_each_entry_from(dl, &notes->src->source, al.node) {
2552 		/* Skip comment or debug info line */
2553 		if (dl->al.offset == -1)
2554 			continue;
2555 		/* Found the target instruction */
2556 		if (sym->start + dl->al.offset == target) {
2557 			found = true;
2558 			break;
2559 		}
2560 		/* End of the function, finish the block */
2561 		if (dl == last_dl)
2562 			break;
2563 		/* 'return' instruction finishes the block */
2564 		if (ins__is_ret(&dl->ins))
2565 			break;
2566 		/* normal instructions are part of the basic block */
2567 		if (!ins__is_jump(&dl->ins))
2568 			continue;
2569 		/* jump to a different function, tail call or return */
2570 		if (dl->ops.target.outside)
2571 			break;
2572 		/* jump instruction creates new basic block(s) */
2573 		next_dl = find_disasm_line(sym, sym->start + dl->ops.target.offset,
2574 					   /*allow_update=*/false);
2575 		if (next_dl)
2576 			add_basic_block(bb_data, link, next_dl);
2577 
2578 		/*
2579 		 * FIXME: determine conditional jumps properly.
2580 		 * Conditional jumps create another basic block with the
2581 		 * next disasm line.
2582 		 */
2583 		if (!strstr(dl->ins.name, "jmp")) {
2584 			next_dl = annotation__next_asm_line(notes, dl);
2585 			if (next_dl)
2586 				add_basic_block(bb_data, link, next_dl);
2587 		}
2588 		break;
2589 
2590 	}
2591 	link->bb->end = dl;
2592 	return found;
2593 }
2594 
2595 /*
2596  * It founds a target basic block, build a proper linked list of basic blocks
2597  * by following the link recursively.
2598  */
2599 static void link_found_basic_blocks(struct basic_block_link *link,
2600 				    struct list_head *head)
2601 {
2602 	while (link) {
2603 		struct basic_block_link *parent = link->parent;
2604 
2605 		list_move(&link->bb->list, head);
2606 		list_del(&link->node);
2607 		free(link);
2608 
2609 		link = parent;
2610 	}
2611 }
2612 
2613 static void delete_basic_blocks(struct basic_block_data *bb_data)
2614 {
2615 	struct basic_block_link *link, *tmp;
2616 
2617 	list_for_each_entry_safe(link, tmp, &bb_data->queue, node) {
2618 		list_del(&link->node);
2619 		free(link->bb);
2620 		free(link);
2621 	}
2622 
2623 	list_for_each_entry_safe(link, tmp, &bb_data->visited, node) {
2624 		list_del(&link->node);
2625 		free(link->bb);
2626 		free(link);
2627 	}
2628 }
2629 
2630 /**
2631  * annotate_get_basic_blocks - Get basic blocks for given address range
2632  * @sym: symbol to annotate
2633  * @src: source address
2634  * @dst: destination address
2635  * @head: list head to save basic blocks
2636  *
2637  * This function traverses disasm_lines from @src to @dst and save them in a
2638  * list of annotated_basic_block to @head.  It uses BFS to find the shortest
2639  * path between two.  The basic_block_link is to maintain parent links so
2640  * that it can build a list of blocks from the start.
2641  */
2642 int annotate_get_basic_blocks(struct symbol *sym, s64 src, s64 dst,
2643 			      struct list_head *head)
2644 {
2645 	struct basic_block_data bb_data = {
2646 		.queue = LIST_HEAD_INIT(bb_data.queue),
2647 		.visited = LIST_HEAD_INIT(bb_data.visited),
2648 	};
2649 	struct basic_block_link *link;
2650 	struct disasm_line *dl;
2651 	int ret = -1;
2652 
2653 	dl = find_disasm_line(sym, src, /*allow_update=*/false);
2654 	if (dl == NULL)
2655 		return -1;
2656 
2657 	if (add_basic_block(&bb_data, /*parent=*/NULL, dl) < 0)
2658 		return -1;
2659 
2660 	/* Find shortest path from src to dst using BFS */
2661 	while (!list_empty(&bb_data.queue)) {
2662 		link = list_first_entry(&bb_data.queue, struct basic_block_link, node);
2663 
2664 		if (process_basic_block(&bb_data, link, sym, dst)) {
2665 			link_found_basic_blocks(link, head);
2666 			ret = 0;
2667 			break;
2668 		}
2669 		list_move(&link->node, &bb_data.visited);
2670 	}
2671 	delete_basic_blocks(&bb_data);
2672 	return ret;
2673 }
2674