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