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