projects/linux·blob master · refs

3228 lines · 78.7 KiB

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