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