perf report: Fix ELF symbol parsing
[safe/jmp/linux-2.6] / Documentation / perf_counter / builtin-report.c
1 #include "util/util.h"
2
3 #include <libelf.h>
4 #include <gelf.h>
5 #include <elf.h>
6
7 #include "util/list.h"
8 #include "util/rbtree.h"
9
10 #include "perf.h"
11
12 #include "util/parse-options.h"
13 #include "util/parse-events.h"
14
15 #define SHOW_KERNEL     1
16 #define SHOW_USER       2
17 #define SHOW_HV         4
18
19 static char             const *input_name = "output.perf";
20 static int              input;
21 static int              show_mask = SHOW_KERNEL | SHOW_USER | SHOW_HV;
22
23 static unsigned long    page_size;
24 static unsigned long    mmap_window = 32;
25
26 const char *perf_event_names[] = {
27         [PERF_EVENT_MMAP]   = " PERF_EVENT_MMAP",
28         [PERF_EVENT_MUNMAP] = " PERF_EVENT_MUNMAP",
29         [PERF_EVENT_COMM]   = " PERF_EVENT_COMM",
30 };
31
32 struct ip_event {
33         struct perf_event_header header;
34         __u64 ip;
35         __u32 pid, tid;
36 };
37 struct mmap_event {
38         struct perf_event_header header;
39         __u32 pid, tid;
40         __u64 start;
41         __u64 len;
42         __u64 pgoff;
43         char filename[PATH_MAX];
44 };
45 struct comm_event {
46         struct perf_event_header header;
47         __u32 pid,tid;
48         char comm[16];
49 };
50
51 typedef union event_union {
52         struct perf_event_header header;
53         struct ip_event ip;
54         struct mmap_event mmap;
55         struct comm_event comm;
56 } event_t;
57
58 struct symbol {
59         struct rb_node rb_node;
60         uint64_t       start;
61         uint64_t       end;
62         char           name[0];
63 };
64
65 static struct symbol *symbol__new(uint64_t start, uint64_t len, const char *name)
66 {
67         struct symbol *self = malloc(sizeof(*self) + strlen(name) + 1);
68
69         if (self != NULL) {
70                 self->start = start;
71                 self->end   = start + len;
72                 strcpy(self->name, name);
73         }
74
75         return self;
76 }
77
78 static void symbol__delete(struct symbol *self)
79 {
80         free(self);
81 }
82
83 static size_t symbol__fprintf(struct symbol *self, FILE *fp)
84 {
85         return fprintf(fp, " %lx-%lx %s\n",
86                        self->start, self->end, self->name);
87 }
88
89 struct dso {
90         struct list_head node;
91         struct rb_root   syms;
92         char             name[0];
93 };
94
95 static struct dso *dso__new(const char *name)
96 {
97         struct dso *self = malloc(sizeof(*self) + strlen(name) + 1);
98
99         if (self != NULL) {
100                 strcpy(self->name, name);
101                 self->syms = RB_ROOT;
102         }
103
104         return self;
105 }
106
107 static void dso__delete_symbols(struct dso *self)
108 {
109         struct symbol *pos;
110         struct rb_node *next = rb_first(&self->syms);
111
112         while (next) {
113                 pos = rb_entry(next, struct symbol, rb_node);
114                 next = rb_next(&pos->rb_node);
115                 symbol__delete(pos);
116         }
117 }
118
119 static void dso__delete(struct dso *self)
120 {
121         dso__delete_symbols(self);
122         free(self);
123 }
124
125 static void dso__insert_symbol(struct dso *self, struct symbol *sym)
126 {
127         struct rb_node **p = &self->syms.rb_node;
128         struct rb_node *parent = NULL;
129         const uint64_t ip = sym->start;
130         struct symbol *s;
131
132         while (*p != NULL) {
133                 parent = *p;
134                 s = rb_entry(parent, struct symbol, rb_node);
135                 if (ip < s->start)
136                         p = &(*p)->rb_left;
137                 else
138                         p = &(*p)->rb_right;
139         }
140         rb_link_node(&sym->rb_node, parent, p);
141         rb_insert_color(&sym->rb_node, &self->syms);
142 }
143
144 static struct symbol *dso__find_symbol(struct dso *self, uint64_t ip)
145 {
146         if (self == NULL)
147                 return NULL;
148
149         struct rb_node *n = self->syms.rb_node;
150
151         while (n) {
152                 struct symbol *s = rb_entry(n, struct symbol, rb_node);
153
154                 if (ip < s->start)
155                         n = n->rb_left;
156                 else if (ip > s->end)
157                         n = n->rb_right;
158                 else
159                         return s;
160         }
161
162         return NULL;
163 }
164
165 /**
166  * elf_symtab__for_each_symbol - iterate thru all the symbols
167  *
168  * @self: struct elf_symtab instance to iterate
169  * @index: uint32_t index
170  * @sym: GElf_Sym iterator
171  */
172 #define elf_symtab__for_each_symbol(syms, nr_syms, index, sym) \
173         for (index = 0, gelf_getsym(syms, index, &sym);\
174              index < nr_syms; \
175              index++, gelf_getsym(syms, index, &sym))
176
177 static inline uint8_t elf_sym__type(const GElf_Sym *sym)
178 {
179         return GELF_ST_TYPE(sym->st_info);
180 }
181
182 static inline int elf_sym__is_function(const GElf_Sym *sym)
183 {
184         return elf_sym__type(sym) == STT_FUNC &&
185                sym->st_name != 0 &&
186                sym->st_shndx != SHN_UNDEF;
187 }
188
189 static inline const char *elf_sym__name(const GElf_Sym *sym,
190                                         const Elf_Data *symstrs)
191 {
192         return symstrs->d_buf + sym->st_name;
193 }
194
195 static Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
196                                     GElf_Shdr *shp, const char *name,
197                                     size_t *index)
198 {
199         Elf_Scn *sec = NULL;
200         size_t cnt = 1;
201
202         while ((sec = elf_nextscn(elf, sec)) != NULL) {
203                 char *str;
204
205                 gelf_getshdr(sec, shp);
206                 str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
207                 if (!strcmp(name, str)) {
208                         if (index)
209                                 *index = cnt;
210                         break;
211                 }
212                 ++cnt;
213         }
214
215         return sec;
216 }
217
218 static int dso__load(struct dso *self)
219 {
220         int fd = open(self->name, O_RDONLY), err = -1;
221
222         if (fd == -1)
223                 return -1;
224
225         Elf *elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
226         if (elf == NULL) {
227                 fprintf(stderr, "%s: cannot read %s ELF file.\n",
228                         __func__, self->name);
229                 goto out_close;
230         }
231
232         GElf_Ehdr ehdr;
233         if (gelf_getehdr(elf, &ehdr) == NULL) {
234                 fprintf(stderr, "%s: cannot get elf header.\n", __func__);
235                 goto out_elf_end;
236         }
237
238         GElf_Shdr shdr;
239         Elf_Scn *sec = elf_section_by_name(elf, &ehdr, &shdr, ".symtab", NULL);
240         if (sec == NULL)
241                 sec = elf_section_by_name(elf, &ehdr, &shdr, ".dynsym", NULL);
242
243         if (sec == NULL)
244                 goto out_elf_end;
245
246         Elf_Data *syms = elf_getdata(sec, NULL);
247         if (syms == NULL)
248                 goto out_elf_end;
249
250         sec = elf_getscn(elf, shdr.sh_link);
251         if (sec == NULL)
252                 goto out_elf_end;
253
254         Elf_Data *symstrs = elf_getdata(sec, NULL);
255         if (symstrs == NULL)
256                 goto out_elf_end;
257
258         const uint32_t nr_syms = shdr.sh_size / shdr.sh_entsize;
259
260         GElf_Sym sym;
261         uint32_t index;
262         elf_symtab__for_each_symbol(syms, nr_syms, index, sym) {
263                 struct symbol *f;
264
265                 if (!elf_sym__is_function(&sym))
266                         continue;
267
268                 sec = elf_getscn(elf, sym.st_shndx);
269                 if (!sec)
270                         goto out_elf_end;
271
272                 gelf_getshdr(sec, &shdr);
273                 sym.st_value -= shdr.sh_addr - shdr.sh_offset;
274
275                 f = symbol__new(sym.st_value, sym.st_size,
276                                 elf_sym__name(&sym, symstrs));
277                 if (!f)
278                         goto out_elf_end;
279
280                 dso__insert_symbol(self, f);
281         }
282
283         err = 0;
284 out_elf_end:
285         elf_end(elf);
286 out_close:
287         close(fd);
288         return err;
289 }
290
291 static size_t dso__fprintf(struct dso *self, FILE *fp)
292 {
293         size_t ret = fprintf(fp, "dso: %s\n", self->name);
294
295         struct rb_node *nd;
296         for (nd = rb_first(&self->syms); nd; nd = rb_next(nd)) {
297                 struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
298                 ret += symbol__fprintf(pos, fp);
299         }
300
301         return ret;
302 }
303
304 static LIST_HEAD(dsos);
305 static struct dso *kernel_dso;
306
307 static void dsos__add(struct dso *dso)
308 {
309         list_add_tail(&dso->node, &dsos);
310 }
311
312 static struct dso *dsos__find(const char *name)
313 {
314         struct dso *pos;
315
316         list_for_each_entry(pos, &dsos, node)
317                 if (strcmp(pos->name, name) == 0)
318                         return pos;
319         return NULL;
320 }
321
322 static struct dso *dsos__findnew(const char *name)
323 {
324         struct dso *dso = dsos__find(name);
325
326         if (dso == NULL) {
327                 dso = dso__new(name);
328                 if (dso != NULL && dso__load(dso) < 0)
329                         goto out_delete_dso;
330
331                 dsos__add(dso);
332         }
333
334         return dso;
335
336 out_delete_dso:
337         dso__delete(dso);
338         return NULL;
339 }
340
341 void dsos__fprintf(FILE *fp)
342 {
343         struct dso *pos;
344
345         list_for_each_entry(pos, &dsos, node)
346                 dso__fprintf(pos, fp);
347 }
348
349 static int load_kallsyms(void)
350 {
351         kernel_dso = dso__new("[kernel]");
352         if (kernel_dso == NULL)
353                 return -1;
354
355         FILE *file = fopen("/proc/kallsyms", "r");
356
357         if (file == NULL)
358                 goto out_delete_dso;
359
360         char *line = NULL;
361         size_t n;
362
363         while (!feof(file)) {
364                 unsigned long long start;
365                 char c, symbf[4096];
366
367                 if (getline(&line, &n, file) < 0)
368                         break;
369
370                 if (!line)
371                         goto out_delete_dso;
372
373                 if (sscanf(line, "%llx %c %s", &start, &c, symbf) == 3) {
374                         struct symbol *sym = symbol__new(start, 0x1000000, symbf);
375
376                         if (sym == NULL)
377                                 goto out_delete_dso;
378
379                         dso__insert_symbol(kernel_dso, sym);
380                 }
381         }
382
383         dsos__add(kernel_dso);
384         free(line);
385         fclose(file);
386         return 0;
387
388 out_delete_dso:
389         dso__delete(kernel_dso);
390         return -1;
391 }
392
393 struct map {
394         struct list_head node;
395         uint64_t         start;
396         uint64_t         end;
397         uint64_t         pgoff;
398         struct dso       *dso;
399 };
400
401 static struct map *map__new(struct mmap_event *event)
402 {
403         struct map *self = malloc(sizeof(*self));
404
405         if (self != NULL) {
406                 self->start = event->start;
407                 self->end   = event->start + event->len;
408                 self->pgoff = event->pgoff;
409
410                 self->dso = dsos__findnew(event->filename);
411                 if (self->dso == NULL)
412                         goto out_delete;
413         }
414         return self;
415 out_delete:
416         free(self);
417         return NULL;
418 }
419
420 static size_t map__fprintf(struct map *self, FILE *fp)
421 {
422         return fprintf(fp, " %lx-%lx %lx %s\n",
423                        self->start, self->end, self->pgoff, self->dso->name);
424 }
425
426 struct symhist {
427         struct rb_node   rb_node;
428         struct dso       *dso;
429         struct symbol    *sym;
430         uint64_t         ip;
431         uint32_t         count;
432         char             level;
433 };
434
435 static struct symhist *symhist__new(struct symbol *sym, uint64_t ip,
436                                     struct dso *dso, char level)
437 {
438         struct symhist *self = malloc(sizeof(*self));
439
440         if (self != NULL) {
441                 self->sym   = sym;
442                 self->ip    = ip;
443                 self->dso   = dso;
444                 self->level = level;
445                 self->count = 1;
446         }
447
448         return self;
449 }
450
451 void symhist__delete(struct symhist *self)
452 {
453         free(self);
454 }
455
456 static void symhist__inc(struct symhist *self)
457 {
458         ++self->count;
459 }
460
461 static size_t symhist__fprintf(struct symhist *self, FILE *fp)
462 {
463         size_t ret = fprintf(fp, "%#llx [%c] ", (unsigned long long)self->ip, self->level);
464
465         if (self->level != '.')
466                 ret += fprintf(fp, "%s", self->sym ? self->sym->name: "<unknown>");
467         else
468                 ret += fprintf(fp, "%s: %s",
469                                self->dso ? self->dso->name : "<unknown>",
470                                self->sym ? self->sym->name : "<unknown>");
471         return ret + fprintf(fp, ": %u\n", self->count);
472 }
473
474 struct thread {
475         struct rb_node   rb_node;
476         struct list_head maps;
477         struct rb_root   symhists;
478         pid_t            pid;
479         char             *comm;
480 };
481
482 static struct thread *thread__new(pid_t pid)
483 {
484         struct thread *self = malloc(sizeof(*self));
485
486         if (self != NULL) {
487                 self->pid = pid;
488                 self->comm = NULL;
489                 INIT_LIST_HEAD(&self->maps);
490                 self->symhists = RB_ROOT;
491         }
492
493         return self;
494 }
495
496 static int thread__symbol_incnew(struct thread *self, struct symbol *sym,
497                                  uint64_t ip, struct dso *dso, char level)
498 {
499         struct rb_node **p = &self->symhists.rb_node;
500         struct rb_node *parent = NULL;
501         struct symhist *sh;
502
503         while (*p != NULL) {
504                 parent = *p;
505                 sh = rb_entry(parent, struct symhist, rb_node);
506
507                 if (sh->sym == sym || ip == sh->ip) {
508                         symhist__inc(sh);
509                         return 0;
510                 }
511
512                 /* Handle unresolved symbols too */
513                 const uint64_t start = !sh->sym ? sh->ip : sh->sym->start;
514
515                 if (ip < start)
516                         p = &(*p)->rb_left;
517                 else
518                         p = &(*p)->rb_right;
519         }
520
521         sh = symhist__new(sym, ip, dso, level);
522         if (sh == NULL)
523                 return -ENOMEM;
524         rb_link_node(&sh->rb_node, parent, p);
525         rb_insert_color(&sh->rb_node, &self->symhists);
526         return 0;
527 }
528
529 static int thread__set_comm(struct thread *self, const char *comm)
530 {
531         self->comm = strdup(comm);
532         return self->comm ? 0 : -ENOMEM;
533 }
534
535 size_t thread__maps_fprintf(struct thread *self, FILE *fp)
536 {
537         struct map *pos;
538         size_t ret = 0;
539
540         list_for_each_entry(pos, &self->maps, node)
541                 ret += map__fprintf(pos, fp);
542
543         return ret;
544 }
545
546 static size_t thread__fprintf(struct thread *self, FILE *fp)
547 {
548         int ret = fprintf(fp, "thread: %d %s\n", self->pid, self->comm);
549         struct rb_node *nd;
550
551         for (nd = rb_first(&self->symhists); nd; nd = rb_next(nd)) {
552                 struct symhist *pos = rb_entry(nd, struct symhist, rb_node);
553                 ret += symhist__fprintf(pos, fp);
554         }
555
556         return ret;
557 }
558
559 static struct rb_root threads = RB_ROOT;
560
561 static struct thread *threads__findnew(pid_t pid)
562 {
563         struct rb_node **p = &threads.rb_node;
564         struct rb_node *parent = NULL;
565         struct thread *th;
566
567         while (*p != NULL) {
568                 parent = *p;
569                 th = rb_entry(parent, struct thread, rb_node);
570
571                 if (th->pid == pid)
572                         return th;
573
574                 if (pid < th->pid)
575                         p = &(*p)->rb_left;
576                 else
577                         p = &(*p)->rb_right;
578         }
579
580         th = thread__new(pid);
581         if (th != NULL) {
582                 rb_link_node(&th->rb_node, parent, p);
583                 rb_insert_color(&th->rb_node, &threads);
584         }
585         return th;
586 }
587
588 static void thread__insert_map(struct thread *self, struct map *map)
589 {
590         list_add_tail(&map->node, &self->maps);
591 }
592
593 static struct map *thread__find_map(struct thread *self, uint64_t ip)
594 {
595         if (self == NULL)
596                 return NULL;
597
598         struct map *pos;
599
600         list_for_each_entry(pos, &self->maps, node)
601                 if (ip >= pos->start && ip <= pos->end)
602                         return pos;
603
604         return NULL;
605 }
606
607 static void threads__fprintf(FILE *fp)
608 {
609         struct rb_node *nd;
610         for (nd = rb_first(&threads); nd; nd = rb_next(nd)) {
611                 struct thread *pos = rb_entry(nd, struct thread, rb_node);
612                 thread__fprintf(pos, fp);
613         }
614 }
615
616 static int __cmd_report(void)
617 {
618         unsigned long offset = 0;
619         unsigned long head = 0;
620         struct stat stat;
621         char *buf;
622         event_t *event;
623         int ret, rc = EXIT_FAILURE;
624         unsigned long total = 0;
625
626         input = open(input_name, O_RDONLY);
627         if (input < 0) {
628                 perror("failed to open file");
629                 exit(-1);
630         }
631
632         ret = fstat(input, &stat);
633         if (ret < 0) {
634                 perror("failed to stat file");
635                 exit(-1);
636         }
637
638         if (!stat.st_size) {
639                 fprintf(stderr, "zero-sized file, nothing to do!\n");
640                 exit(0);
641         }
642
643         if (load_kallsyms() < 0) {
644                 perror("failed to open kallsyms");
645                 return EXIT_FAILURE;
646         }
647
648 remap:
649         buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
650                            MAP_SHARED, input, offset);
651         if (buf == MAP_FAILED) {
652                 perror("failed to mmap file");
653                 exit(-1);
654         }
655
656 more:
657         event = (event_t *)(buf + head);
658
659         if (head + event->header.size >= page_size * mmap_window) {
660                 unsigned long shift = page_size * (head / page_size);
661                 int ret;
662
663                 ret = munmap(buf, page_size * mmap_window);
664                 assert(ret == 0);
665
666                 offset += shift;
667                 head -= shift;
668                 goto remap;
669         }
670
671
672         if (!event->header.size) {
673                 fprintf(stderr, "zero-sized event at file offset %ld\n", offset + head);
674                 fprintf(stderr, "skipping %ld bytes of events.\n", stat.st_size - offset - head);
675                 goto done;
676         }
677
678         head += event->header.size;
679
680         if (event->header.misc & PERF_EVENT_MISC_OVERFLOW) {
681                 char level;
682                 int show = 0;
683                 struct dso *dso = NULL;
684                 struct thread *thread = threads__findnew(event->ip.pid);
685                 uint64_t ip = event->ip.ip;
686
687                 if (thread == NULL) {
688                         fprintf(stderr, "problem processing %d event, bailing out\n",
689                                 event->header.type);
690                         goto done;
691                 }
692
693                 if (event->header.misc & PERF_EVENT_MISC_KERNEL) {
694                         show = SHOW_KERNEL;
695                         level = 'k';
696                         dso = kernel_dso;
697                 } else if (event->header.misc & PERF_EVENT_MISC_USER) {
698                         show = SHOW_USER;
699                         level = '.';
700                         struct map *map = thread__find_map(thread, ip);
701                         if (map != NULL) {
702                                 dso = map->dso;
703                                 ip -= map->start + map->pgoff;
704                         }
705                 } else {
706                         show = SHOW_HV;
707                         level = 'H';
708                 }
709
710                 if (show & show_mask) {
711                         struct symbol *sym = dso__find_symbol(dso, ip);
712
713                         if (thread__symbol_incnew(thread, sym, ip, dso, level)) {
714                                 fprintf(stderr, "problem incrementing symbol count, bailing out\n");
715                                 goto done;
716                         }
717                 }
718                 total++;
719         } else switch (event->header.type) {
720         case PERF_EVENT_MMAP: {
721                 struct thread *thread = threads__findnew(event->mmap.pid);
722                 struct map *map = map__new(&event->mmap);
723
724                 if (thread == NULL || map == NULL) {
725                         fprintf(stderr, "problem processing PERF_EVENT_MMAP, bailing out\n");
726                         goto done;
727                 }
728                 thread__insert_map(thread, map);
729                 break;
730         }
731         case PERF_EVENT_COMM: {
732                 struct thread *thread = threads__findnew(event->comm.pid);
733
734                 if (thread == NULL ||
735                     thread__set_comm(thread, event->comm.comm)) {
736                         fprintf(stderr, "problem processing PERF_EVENT_COMM, bailing out\n");
737                         goto done;
738                 }
739                 break;
740         }
741         }
742
743         if (offset + head < stat.st_size)
744                 goto more;
745
746         rc = EXIT_SUCCESS;
747 done:
748         close(input);
749         //dsos__fprintf(stdout);
750         threads__fprintf(stdout);
751 #if 0
752         std::map<std::string, int>::iterator hi = hist.begin();
753
754         while (hi != hist.end()) {
755                 rev_hist.insert(std::pair<int, std::string>(hi->second, hi->first));
756                 hist.erase(hi++);
757         }
758
759         std::multimap<int, std::string>::const_iterator ri = rev_hist.begin();
760
761         while (ri != rev_hist.end()) {
762                 printf(" %5.2f %s\n", (100.0 * ri->first)/total, ri->second.c_str());
763                 ri++;
764         }
765 #endif
766         return rc;
767 }
768
769 static const char * const report_usage[] = {
770         "perf report [<options>] <command>",
771         NULL
772 };
773
774 static const struct option options[] = {
775         OPT_STRING('i', "input", &input_name, "file",
776                     "input file name"),
777         OPT_END()
778 };
779
780 int cmd_report(int argc, const char **argv, const char *prefix)
781 {
782         elf_version(EV_CURRENT);
783
784         page_size = getpagesize();
785
786         parse_options(argc, argv, options, report_usage, 0);
787
788         return __cmd_report();
789 }