perf annotate: Introduce scnprintf ins_ops method
[firefly-linux-kernel-4.4.55.git] / tools / perf / util / annotate.c
1 /*
2  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
3  *
4  * Parts came from builtin-annotate.c, see those files for further
5  * copyright notes.
6  *
7  * Released under the GPL v2. (and only v2, not any later version)
8  */
9
10 #include "util.h"
11 #include "build-id.h"
12 #include "color.h"
13 #include "cache.h"
14 #include "symbol.h"
15 #include "debug.h"
16 #include "annotate.h"
17 #include <pthread.h>
18
19 const char      *disassembler_style;
20
21 static int call_ops__parse_target(const char *operands, u64 *target)
22 {
23         *target = strtoull(operands, NULL, 16);
24         return 0;
25 }
26
27 static struct ins_ops call_ops = {
28         .parse_target = call_ops__parse_target,
29 };
30
31 bool ins__is_call(const struct ins *ins)
32 {
33         return ins->ops == &call_ops;
34 }
35
36 static int jump_ops__parse_target(const char *operands, u64 *target)
37 {
38         const char *s = strchr(operands, '+');
39
40         if (s++ == NULL)
41                 return -1;
42
43         *target = strtoll(s, NULL, 16);
44         return 0;
45 }
46
47 static int jump_ops__scnprintf(struct ins *ins, char *bf, size_t size,
48                                const char *operands, u64 target)
49 {
50         if (operands)
51                 return scnprintf(bf, size, "%-6.6s %s", ins->name, operands);
52
53         return scnprintf(bf, size, "%-6.6s %" PRIx64, ins->name, target);
54 }
55
56 static struct ins_ops jump_ops = {
57         .parse_target = jump_ops__parse_target,
58         .scnprintf = jump_ops__scnprintf,
59 };
60
61 bool ins__is_jump(const struct ins *ins)
62 {
63         return ins->ops == &jump_ops;
64 }
65
66 /*
67  * Must be sorted by name!
68  */
69 static struct ins instructions[] = {
70         { .name = "call",  .ops  = &call_ops, },
71         { .name = "callq", .ops  = &call_ops, },
72         { .name = "ja",    .ops  = &jump_ops, },
73         { .name = "je",    .ops  = &jump_ops, },
74         { .name = "jmp",   .ops  = &jump_ops, },
75         { .name = "jmpq",  .ops  = &jump_ops, },
76         { .name = "jne",   .ops  = &jump_ops, },
77         { .name = "js",    .ops  = &jump_ops, },
78 };
79
80 static int ins__cmp(const void *name, const void *insp)
81 {
82         const struct ins *ins = insp;
83
84         return strcmp(name, ins->name);
85 }
86
87 static struct ins *ins__find(const char *name)
88 {
89         const int nmemb = ARRAY_SIZE(instructions);
90
91         return bsearch(name, instructions, nmemb, sizeof(struct ins), ins__cmp);
92 }
93
94 int symbol__annotate_init(struct map *map __used, struct symbol *sym)
95 {
96         struct annotation *notes = symbol__annotation(sym);
97         pthread_mutex_init(&notes->lock, NULL);
98         return 0;
99 }
100
101 int symbol__alloc_hist(struct symbol *sym)
102 {
103         struct annotation *notes = symbol__annotation(sym);
104         const size_t size = sym->end - sym->start + 1;
105         size_t sizeof_sym_hist = (sizeof(struct sym_hist) + size * sizeof(u64));
106
107         notes->src = zalloc(sizeof(*notes->src) + symbol_conf.nr_events * sizeof_sym_hist);
108         if (notes->src == NULL)
109                 return -1;
110         notes->src->sizeof_sym_hist = sizeof_sym_hist;
111         notes->src->nr_histograms   = symbol_conf.nr_events;
112         INIT_LIST_HEAD(&notes->src->source);
113         return 0;
114 }
115
116 void symbol__annotate_zero_histograms(struct symbol *sym)
117 {
118         struct annotation *notes = symbol__annotation(sym);
119
120         pthread_mutex_lock(&notes->lock);
121         if (notes->src != NULL)
122                 memset(notes->src->histograms, 0,
123                        notes->src->nr_histograms * notes->src->sizeof_sym_hist);
124         pthread_mutex_unlock(&notes->lock);
125 }
126
127 int symbol__inc_addr_samples(struct symbol *sym, struct map *map,
128                              int evidx, u64 addr)
129 {
130         unsigned offset;
131         struct annotation *notes;
132         struct sym_hist *h;
133
134         notes = symbol__annotation(sym);
135         if (notes->src == NULL)
136                 return -ENOMEM;
137
138         pr_debug3("%s: addr=%#" PRIx64 "\n", __func__, map->unmap_ip(map, addr));
139
140         if (addr < sym->start || addr > sym->end)
141                 return -ERANGE;
142
143         offset = addr - sym->start;
144         h = annotation__histogram(notes, evidx);
145         h->sum++;
146         h->addr[offset]++;
147
148         pr_debug3("%#" PRIx64 " %s: period++ [addr: %#" PRIx64 ", %#" PRIx64
149                   ", evidx=%d] => %" PRIu64 "\n", sym->start, sym->name,
150                   addr, addr - sym->start, evidx, h->addr[offset]);
151         return 0;
152 }
153
154 static void disasm_line__init_ins(struct disasm_line *dl)
155 {
156         dl->ins = ins__find(dl->name);
157
158         if (dl->ins == NULL)
159                 return;
160
161         if (!dl->ins->ops)
162                 return;
163
164         if (dl->ins->ops->parse_target)
165                 dl->ins->ops->parse_target(dl->operands, &dl->target);
166 }
167
168 static struct disasm_line *disasm_line__new(s64 offset, char *line, size_t privsize)
169 {
170         struct disasm_line *dl = zalloc(sizeof(*dl) + privsize);
171
172         if (dl != NULL) {
173                 dl->offset = offset;
174                 dl->line = strdup(line);
175                 if (dl->line == NULL)
176                         goto out_delete;
177
178                 if (offset != -1) {
179                         char *name = dl->line, tmp;
180
181                         while (isspace(name[0]))
182                                 ++name;
183
184                         if (name[0] == '\0')
185                                 goto out_delete;
186
187                         dl->operands = name + 1;
188
189                         while (dl->operands[0] != '\0' &&
190                                !isspace(dl->operands[0]))
191                                 ++dl->operands;
192
193                         tmp = dl->operands[0];
194                         dl->operands[0] = '\0';
195                         dl->name = strdup(name);
196
197                         if (dl->name == NULL)
198                                 goto out_free_line;
199
200                         dl->operands[0] = tmp;
201
202                         if (dl->operands[0] != '\0') {
203                                 dl->operands++;
204                                 while (isspace(dl->operands[0]))
205                                         ++dl->operands;
206                         }
207
208                         disasm_line__init_ins(dl);
209                 }
210         }
211
212         return dl;
213
214 out_free_line:
215         free(dl->line);
216 out_delete:
217         free(dl);
218         return NULL;
219 }
220
221 void disasm_line__free(struct disasm_line *dl)
222 {
223         free(dl->line);
224         free(dl->name);
225         free(dl);
226 }
227
228 static void disasm__add(struct list_head *head, struct disasm_line *line)
229 {
230         list_add_tail(&line->node, head);
231 }
232
233 struct disasm_line *disasm__get_next_ip_line(struct list_head *head, struct disasm_line *pos)
234 {
235         list_for_each_entry_continue(pos, head, node)
236                 if (pos->offset >= 0)
237                         return pos;
238
239         return NULL;
240 }
241
242 static int disasm_line__print(struct disasm_line *dl, struct symbol *sym, u64 start,
243                       int evidx, u64 len, int min_pcnt, int printed,
244                       int max_lines, struct disasm_line *queue)
245 {
246         static const char *prev_line;
247         static const char *prev_color;
248
249         if (dl->offset != -1) {
250                 const char *path = NULL;
251                 unsigned int hits = 0;
252                 double percent = 0.0;
253                 const char *color;
254                 struct annotation *notes = symbol__annotation(sym);
255                 struct source_line *src_line = notes->src->lines;
256                 struct sym_hist *h = annotation__histogram(notes, evidx);
257                 s64 offset = dl->offset;
258                 const u64 addr = start + offset;
259                 struct disasm_line *next;
260
261                 next = disasm__get_next_ip_line(&notes->src->source, dl);
262
263                 while (offset < (s64)len &&
264                        (next == NULL || offset < next->offset)) {
265                         if (src_line) {
266                                 if (path == NULL)
267                                         path = src_line[offset].path;
268                                 percent += src_line[offset].percent;
269                         } else
270                                 hits += h->addr[offset];
271
272                         ++offset;
273                 }
274
275                 if (src_line == NULL && h->sum)
276                         percent = 100.0 * hits / h->sum;
277
278                 if (percent < min_pcnt)
279                         return -1;
280
281                 if (max_lines && printed >= max_lines)
282                         return 1;
283
284                 if (queue != NULL) {
285                         list_for_each_entry_from(queue, &notes->src->source, node) {
286                                 if (queue == dl)
287                                         break;
288                                 disasm_line__print(queue, sym, start, evidx, len,
289                                                     0, 0, 1, NULL);
290                         }
291                 }
292
293                 color = get_percent_color(percent);
294
295                 /*
296                  * Also color the filename and line if needed, with
297                  * the same color than the percentage. Don't print it
298                  * twice for close colored addr with the same filename:line
299                  */
300                 if (path) {
301                         if (!prev_line || strcmp(prev_line, path)
302                                        || color != prev_color) {
303                                 color_fprintf(stdout, color, " %s", path);
304                                 prev_line = path;
305                                 prev_color = color;
306                         }
307                 }
308
309                 color_fprintf(stdout, color, " %7.2f", percent);
310                 printf(" :      ");
311                 color_fprintf(stdout, PERF_COLOR_MAGENTA, "  %" PRIx64 ":", addr);
312                 color_fprintf(stdout, PERF_COLOR_BLUE, "%s\n", dl->line);
313         } else if (max_lines && printed >= max_lines)
314                 return 1;
315         else {
316                 if (queue)
317                         return -1;
318
319                 if (!*dl->line)
320                         printf("         :\n");
321                 else
322                         printf("         :      %s\n", dl->line);
323         }
324
325         return 0;
326 }
327
328 static int symbol__parse_objdump_line(struct symbol *sym, struct map *map,
329                                       FILE *file, size_t privsize)
330 {
331         struct annotation *notes = symbol__annotation(sym);
332         struct disasm_line *dl;
333         char *line = NULL, *parsed_line, *tmp, *tmp2, *c;
334         size_t line_len;
335         s64 line_ip, offset = -1;
336
337         if (getline(&line, &line_len, file) < 0)
338                 return -1;
339
340         if (!line)
341                 return -1;
342
343         while (line_len != 0 && isspace(line[line_len - 1]))
344                 line[--line_len] = '\0';
345
346         c = strchr(line, '\n');
347         if (c)
348                 *c = 0;
349
350         line_ip = -1;
351         parsed_line = line;
352
353         /*
354          * Strip leading spaces:
355          */
356         tmp = line;
357         while (*tmp) {
358                 if (*tmp != ' ')
359                         break;
360                 tmp++;
361         }
362
363         if (*tmp) {
364                 /*
365                  * Parse hexa addresses followed by ':'
366                  */
367                 line_ip = strtoull(tmp, &tmp2, 16);
368                 if (*tmp2 != ':' || tmp == tmp2 || tmp2[1] == '\0')
369                         line_ip = -1;
370         }
371
372         if (line_ip != -1) {
373                 u64 start = map__rip_2objdump(map, sym->start),
374                     end = map__rip_2objdump(map, sym->end);
375
376                 offset = line_ip - start;
377                 if (offset < 0 || (u64)line_ip > end)
378                         offset = -1;
379                 else
380                         parsed_line = tmp2 + 1;
381         }
382
383         dl = disasm_line__new(offset, parsed_line, privsize);
384         free(line);
385
386         if (dl == NULL)
387                 return -1;
388
389         disasm__add(&notes->src->source, dl);
390
391         return 0;
392 }
393
394 int symbol__annotate(struct symbol *sym, struct map *map, size_t privsize)
395 {
396         struct dso *dso = map->dso;
397         char *filename = dso__build_id_filename(dso, NULL, 0);
398         bool free_filename = true;
399         char command[PATH_MAX * 2];
400         FILE *file;
401         int err = 0;
402         char symfs_filename[PATH_MAX];
403
404         if (filename) {
405                 snprintf(symfs_filename, sizeof(symfs_filename), "%s%s",
406                          symbol_conf.symfs, filename);
407         }
408
409         if (filename == NULL) {
410                 if (dso->has_build_id) {
411                         pr_err("Can't annotate %s: not enough memory\n",
412                                sym->name);
413                         return -ENOMEM;
414                 }
415                 goto fallback;
416         } else if (readlink(symfs_filename, command, sizeof(command)) < 0 ||
417                    strstr(command, "[kernel.kallsyms]") ||
418                    access(symfs_filename, R_OK)) {
419                 free(filename);
420 fallback:
421                 /*
422                  * If we don't have build-ids or the build-id file isn't in the
423                  * cache, or is just a kallsyms file, well, lets hope that this
424                  * DSO is the same as when 'perf record' ran.
425                  */
426                 filename = dso->long_name;
427                 snprintf(symfs_filename, sizeof(symfs_filename), "%s%s",
428                          symbol_conf.symfs, filename);
429                 free_filename = false;
430         }
431
432         if (dso->symtab_type == SYMTAB__KALLSYMS) {
433                 char bf[BUILD_ID_SIZE * 2 + 16] = " with build id ";
434                 char *build_id_msg = NULL;
435
436                 if (dso->annotate_warned)
437                         goto out_free_filename;
438
439                 if (dso->has_build_id) {
440                         build_id__sprintf(dso->build_id,
441                                           sizeof(dso->build_id), bf + 15);
442                         build_id_msg = bf;
443                 }
444                 err = -ENOENT;
445                 dso->annotate_warned = 1;
446                 pr_err("Can't annotate %s:\n\n"
447                        "No vmlinux file%s\nwas found in the path.\n\n"
448                        "Please use:\n\n"
449                        "  perf buildid-cache -av vmlinux\n\n"
450                        "or:\n\n"
451                        "  --vmlinux vmlinux\n",
452                        sym->name, build_id_msg ?: "");
453                 goto out_free_filename;
454         }
455
456         pr_debug("%s: filename=%s, sym=%s, start=%#" PRIx64 ", end=%#" PRIx64 "\n", __func__,
457                  filename, sym->name, map->unmap_ip(map, sym->start),
458                  map->unmap_ip(map, sym->end));
459
460         pr_debug("annotating [%p] %30s : [%p] %30s\n",
461                  dso, dso->long_name, sym, sym->name);
462
463         snprintf(command, sizeof(command),
464                  "objdump %s%s --start-address=0x%016" PRIx64
465                  " --stop-address=0x%016" PRIx64
466                  " -d %s %s -C %s|grep -v %s|expand",
467                  disassembler_style ? "-M " : "",
468                  disassembler_style ? disassembler_style : "",
469                  map__rip_2objdump(map, sym->start),
470                  map__rip_2objdump(map, sym->end+1),
471                  symbol_conf.annotate_asm_raw ? "" : "--no-show-raw",
472                  symbol_conf.annotate_src ? "-S" : "",
473                  symfs_filename, filename);
474
475         pr_debug("Executing: %s\n", command);
476
477         file = popen(command, "r");
478         if (!file)
479                 goto out_free_filename;
480
481         while (!feof(file))
482                 if (symbol__parse_objdump_line(sym, map, file, privsize) < 0)
483                         break;
484
485         pclose(file);
486 out_free_filename:
487         if (free_filename)
488                 free(filename);
489         return err;
490 }
491
492 static void insert_source_line(struct rb_root *root, struct source_line *src_line)
493 {
494         struct source_line *iter;
495         struct rb_node **p = &root->rb_node;
496         struct rb_node *parent = NULL;
497
498         while (*p != NULL) {
499                 parent = *p;
500                 iter = rb_entry(parent, struct source_line, node);
501
502                 if (src_line->percent > iter->percent)
503                         p = &(*p)->rb_left;
504                 else
505                         p = &(*p)->rb_right;
506         }
507
508         rb_link_node(&src_line->node, parent, p);
509         rb_insert_color(&src_line->node, root);
510 }
511
512 static void symbol__free_source_line(struct symbol *sym, int len)
513 {
514         struct annotation *notes = symbol__annotation(sym);
515         struct source_line *src_line = notes->src->lines;
516         int i;
517
518         for (i = 0; i < len; i++)
519                 free(src_line[i].path);
520
521         free(src_line);
522         notes->src->lines = NULL;
523 }
524
525 /* Get the filename:line for the colored entries */
526 static int symbol__get_source_line(struct symbol *sym, struct map *map,
527                                    int evidx, struct rb_root *root, int len,
528                                    const char *filename)
529 {
530         u64 start;
531         int i;
532         char cmd[PATH_MAX * 2];
533         struct source_line *src_line;
534         struct annotation *notes = symbol__annotation(sym);
535         struct sym_hist *h = annotation__histogram(notes, evidx);
536
537         if (!h->sum)
538                 return 0;
539
540         src_line = notes->src->lines = calloc(len, sizeof(struct source_line));
541         if (!notes->src->lines)
542                 return -1;
543
544         start = map__rip_2objdump(map, sym->start);
545
546         for (i = 0; i < len; i++) {
547                 char *path = NULL;
548                 size_t line_len;
549                 u64 offset;
550                 FILE *fp;
551
552                 src_line[i].percent = 100.0 * h->addr[i] / h->sum;
553                 if (src_line[i].percent <= 0.5)
554                         continue;
555
556                 offset = start + i;
557                 sprintf(cmd, "addr2line -e %s %016" PRIx64, filename, offset);
558                 fp = popen(cmd, "r");
559                 if (!fp)
560                         continue;
561
562                 if (getline(&path, &line_len, fp) < 0 || !line_len)
563                         goto next;
564
565                 src_line[i].path = malloc(sizeof(char) * line_len + 1);
566                 if (!src_line[i].path)
567                         goto next;
568
569                 strcpy(src_line[i].path, path);
570                 insert_source_line(root, &src_line[i]);
571
572         next:
573                 pclose(fp);
574         }
575
576         return 0;
577 }
578
579 static void print_summary(struct rb_root *root, const char *filename)
580 {
581         struct source_line *src_line;
582         struct rb_node *node;
583
584         printf("\nSorted summary for file %s\n", filename);
585         printf("----------------------------------------------\n\n");
586
587         if (RB_EMPTY_ROOT(root)) {
588                 printf(" Nothing higher than %1.1f%%\n", MIN_GREEN);
589                 return;
590         }
591
592         node = rb_first(root);
593         while (node) {
594                 double percent;
595                 const char *color;
596                 char *path;
597
598                 src_line = rb_entry(node, struct source_line, node);
599                 percent = src_line->percent;
600                 color = get_percent_color(percent);
601                 path = src_line->path;
602
603                 color_fprintf(stdout, color, " %7.2f %s", percent, path);
604                 node = rb_next(node);
605         }
606 }
607
608 static void symbol__annotate_hits(struct symbol *sym, int evidx)
609 {
610         struct annotation *notes = symbol__annotation(sym);
611         struct sym_hist *h = annotation__histogram(notes, evidx);
612         u64 len = sym->end - sym->start, offset;
613
614         for (offset = 0; offset < len; ++offset)
615                 if (h->addr[offset] != 0)
616                         printf("%*" PRIx64 ": %" PRIu64 "\n", BITS_PER_LONG / 2,
617                                sym->start + offset, h->addr[offset]);
618         printf("%*s: %" PRIu64 "\n", BITS_PER_LONG / 2, "h->sum", h->sum);
619 }
620
621 int symbol__annotate_printf(struct symbol *sym, struct map *map, int evidx,
622                             bool full_paths, int min_pcnt, int max_lines,
623                             int context)
624 {
625         struct dso *dso = map->dso;
626         const char *filename = dso->long_name, *d_filename;
627         struct annotation *notes = symbol__annotation(sym);
628         struct disasm_line *pos, *queue = NULL;
629         u64 start = map__rip_2objdump(map, sym->start);
630         int printed = 2, queue_len = 0;
631         int more = 0;
632         u64 len;
633
634         if (full_paths)
635                 d_filename = filename;
636         else
637                 d_filename = basename(filename);
638
639         len = sym->end - sym->start;
640
641         printf(" Percent |      Source code & Disassembly of %s\n", d_filename);
642         printf("------------------------------------------------\n");
643
644         if (verbose)
645                 symbol__annotate_hits(sym, evidx);
646
647         list_for_each_entry(pos, &notes->src->source, node) {
648                 if (context && queue == NULL) {
649                         queue = pos;
650                         queue_len = 0;
651                 }
652
653                 switch (disasm_line__print(pos, sym, start, evidx, len,
654                                             min_pcnt, printed, max_lines,
655                                             queue)) {
656                 case 0:
657                         ++printed;
658                         if (context) {
659                                 printed += queue_len;
660                                 queue = NULL;
661                                 queue_len = 0;
662                         }
663                         break;
664                 case 1:
665                         /* filtered by max_lines */
666                         ++more;
667                         break;
668                 case -1:
669                 default:
670                         /*
671                          * Filtered by min_pcnt or non IP lines when
672                          * context != 0
673                          */
674                         if (!context)
675                                 break;
676                         if (queue_len == context)
677                                 queue = list_entry(queue->node.next, typeof(*queue), node);
678                         else
679                                 ++queue_len;
680                         break;
681                 }
682         }
683
684         return more;
685 }
686
687 void symbol__annotate_zero_histogram(struct symbol *sym, int evidx)
688 {
689         struct annotation *notes = symbol__annotation(sym);
690         struct sym_hist *h = annotation__histogram(notes, evidx);
691
692         memset(h, 0, notes->src->sizeof_sym_hist);
693 }
694
695 void symbol__annotate_decay_histogram(struct symbol *sym, int evidx)
696 {
697         struct annotation *notes = symbol__annotation(sym);
698         struct sym_hist *h = annotation__histogram(notes, evidx);
699         int len = sym->end - sym->start, offset;
700
701         h->sum = 0;
702         for (offset = 0; offset < len; ++offset) {
703                 h->addr[offset] = h->addr[offset] * 7 / 8;
704                 h->sum += h->addr[offset];
705         }
706 }
707
708 void disasm__purge(struct list_head *head)
709 {
710         struct disasm_line *pos, *n;
711
712         list_for_each_entry_safe(pos, n, head, node) {
713                 list_del(&pos->node);
714                 disasm_line__free(pos);
715         }
716 }
717
718 static size_t disasm_line__fprintf(struct disasm_line *dl, FILE *fp)
719 {
720         size_t printed;
721
722         if (dl->offset == -1)
723                 return fprintf(fp, "%s\n", dl->line);
724
725         printed = fprintf(fp, "%#" PRIx64 " %s", dl->offset, dl->name);
726
727         if (dl->operands[0] != '\0') {
728                 printed += fprintf(fp, "%.*s %s\n", 6 - (int)printed, " ",
729                                    dl->operands);
730         }
731
732         return printed + fprintf(fp, "\n");
733 }
734
735 size_t disasm__fprintf(struct list_head *head, FILE *fp)
736 {
737         struct disasm_line *pos;
738         size_t printed = 0;
739
740         list_for_each_entry(pos, head, node)
741                 printed += disasm_line__fprintf(pos, fp);
742
743         return printed;
744 }
745
746 int symbol__tty_annotate(struct symbol *sym, struct map *map, int evidx,
747                          bool print_lines, bool full_paths, int min_pcnt,
748                          int max_lines)
749 {
750         struct dso *dso = map->dso;
751         const char *filename = dso->long_name;
752         struct rb_root source_line = RB_ROOT;
753         u64 len;
754
755         if (symbol__annotate(sym, map, 0) < 0)
756                 return -1;
757
758         len = sym->end - sym->start;
759
760         if (print_lines) {
761                 symbol__get_source_line(sym, map, evidx, &source_line,
762                                         len, filename);
763                 print_summary(&source_line, filename);
764         }
765
766         symbol__annotate_printf(sym, map, evidx, full_paths,
767                                 min_pcnt, max_lines, 0);
768         if (print_lines)
769                 symbol__free_source_line(sym, len);
770
771         disasm__purge(&symbol__annotation(sym)->src->source);
772
773         return 0;
774 }