perf symbols: Check the right return variable
[linux-2.6.git] / tools / perf / util / symbol.c
1 #include "util.h"
2 #include "../perf.h"
3 #include "sort.h"
4 #include "string.h"
5 #include "symbol.h"
6 #include "thread.h"
7
8 #include "debug.h"
9
10 #include <asm/bug.h>
11 #include <libelf.h>
12 #include <gelf.h>
13 #include <elf.h>
14 #include <limits.h>
15 #include <sys/utsname.h>
16
17 #ifndef NT_GNU_BUILD_ID
18 #define NT_GNU_BUILD_ID 3
19 #endif
20
21 enum dso_origin {
22         DSO__ORIG_KERNEL = 0,
23         DSO__ORIG_JAVA_JIT,
24         DSO__ORIG_BUILD_ID_CACHE,
25         DSO__ORIG_FEDORA,
26         DSO__ORIG_UBUNTU,
27         DSO__ORIG_BUILDID,
28         DSO__ORIG_DSO,
29         DSO__ORIG_KMODULE,
30         DSO__ORIG_NOT_FOUND,
31 };
32
33 static void dsos__add(struct list_head *head, struct dso *dso);
34 static struct map *map__new2(u64 start, struct dso *dso, enum map_type type);
35 static int dso__load_kernel_sym(struct dso *self, struct map *map,
36                                 symbol_filter_t filter);
37 static int vmlinux_path__nr_entries;
38 static char **vmlinux_path;
39
40 struct symbol_conf symbol_conf = {
41         .exclude_other    = true,
42         .use_modules      = true,
43         .try_vmlinux_path = true,
44 };
45
46 bool dso__loaded(const struct dso *self, enum map_type type)
47 {
48         return self->loaded & (1 << type);
49 }
50
51 bool dso__sorted_by_name(const struct dso *self, enum map_type type)
52 {
53         return self->sorted_by_name & (1 << type);
54 }
55
56 static void dso__set_sorted_by_name(struct dso *self, enum map_type type)
57 {
58         self->sorted_by_name |= (1 << type);
59 }
60
61 bool symbol_type__is_a(char symbol_type, enum map_type map_type)
62 {
63         switch (map_type) {
64         case MAP__FUNCTION:
65                 return symbol_type == 'T' || symbol_type == 'W';
66         case MAP__VARIABLE:
67                 return symbol_type == 'D' || symbol_type == 'd';
68         default:
69                 return false;
70         }
71 }
72
73 static void symbols__fixup_end(struct rb_root *self)
74 {
75         struct rb_node *nd, *prevnd = rb_first(self);
76         struct symbol *curr, *prev;
77
78         if (prevnd == NULL)
79                 return;
80
81         curr = rb_entry(prevnd, struct symbol, rb_node);
82
83         for (nd = rb_next(prevnd); nd; nd = rb_next(nd)) {
84                 prev = curr;
85                 curr = rb_entry(nd, struct symbol, rb_node);
86
87                 if (prev->end == prev->start)
88                         prev->end = curr->start - 1;
89         }
90
91         /* Last entry */
92         if (curr->end == curr->start)
93                 curr->end = roundup(curr->start, 4096);
94 }
95
96 static void __map_groups__fixup_end(struct map_groups *self, enum map_type type)
97 {
98         struct map *prev, *curr;
99         struct rb_node *nd, *prevnd = rb_first(&self->maps[type]);
100
101         if (prevnd == NULL)
102                 return;
103
104         curr = rb_entry(prevnd, struct map, rb_node);
105
106         for (nd = rb_next(prevnd); nd; nd = rb_next(nd)) {
107                 prev = curr;
108                 curr = rb_entry(nd, struct map, rb_node);
109                 prev->end = curr->start - 1;
110         }
111
112         /*
113          * We still haven't the actual symbols, so guess the
114          * last map final address.
115          */
116         curr->end = ~0UL;
117 }
118
119 static void map_groups__fixup_end(struct map_groups *self)
120 {
121         int i;
122         for (i = 0; i < MAP__NR_TYPES; ++i)
123                 __map_groups__fixup_end(self, i);
124 }
125
126 static struct symbol *symbol__new(u64 start, u64 len, const char *name)
127 {
128         size_t namelen = strlen(name) + 1;
129         struct symbol *self = zalloc(symbol_conf.priv_size +
130                                      sizeof(*self) + namelen);
131         if (self == NULL)
132                 return NULL;
133
134         if (symbol_conf.priv_size)
135                 self = ((void *)self) + symbol_conf.priv_size;
136
137         self->start = start;
138         self->end   = len ? start + len - 1 : start;
139
140         pr_debug4("%s: %s %#Lx-%#Lx\n", __func__, name, start, self->end);
141
142         memcpy(self->name, name, namelen);
143
144         return self;
145 }
146
147 static void symbol__delete(struct symbol *self)
148 {
149         free(((void *)self) - symbol_conf.priv_size);
150 }
151
152 static size_t symbol__fprintf(struct symbol *self, FILE *fp)
153 {
154         return fprintf(fp, " %llx-%llx %s\n",
155                        self->start, self->end, self->name);
156 }
157
158 void dso__set_long_name(struct dso *self, char *name)
159 {
160         if (name == NULL)
161                 return;
162         self->long_name = name;
163         self->long_name_len = strlen(name);
164 }
165
166 static void dso__set_basename(struct dso *self)
167 {
168         self->short_name = basename(self->long_name);
169 }
170
171 struct dso *dso__new(const char *name)
172 {
173         struct dso *self = zalloc(sizeof(*self) + strlen(name) + 1);
174
175         if (self != NULL) {
176                 int i;
177                 strcpy(self->name, name);
178                 dso__set_long_name(self, self->name);
179                 self->short_name = self->name;
180                 for (i = 0; i < MAP__NR_TYPES; ++i)
181                         self->symbols[i] = self->symbol_names[i] = RB_ROOT;
182                 self->slen_calculated = 0;
183                 self->origin = DSO__ORIG_NOT_FOUND;
184                 self->loaded = 0;
185                 self->sorted_by_name = 0;
186                 self->has_build_id = 0;
187         }
188
189         return self;
190 }
191
192 static void symbols__delete(struct rb_root *self)
193 {
194         struct symbol *pos;
195         struct rb_node *next = rb_first(self);
196
197         while (next) {
198                 pos = rb_entry(next, struct symbol, rb_node);
199                 next = rb_next(&pos->rb_node);
200                 rb_erase(&pos->rb_node, self);
201                 symbol__delete(pos);
202         }
203 }
204
205 void dso__delete(struct dso *self)
206 {
207         int i;
208         for (i = 0; i < MAP__NR_TYPES; ++i)
209                 symbols__delete(&self->symbols[i]);
210         if (self->long_name != self->name)
211                 free(self->long_name);
212         free(self);
213 }
214
215 void dso__set_build_id(struct dso *self, void *build_id)
216 {
217         memcpy(self->build_id, build_id, sizeof(self->build_id));
218         self->has_build_id = 1;
219 }
220
221 static void symbols__insert(struct rb_root *self, struct symbol *sym)
222 {
223         struct rb_node **p = &self->rb_node;
224         struct rb_node *parent = NULL;
225         const u64 ip = sym->start;
226         struct symbol *s;
227
228         while (*p != NULL) {
229                 parent = *p;
230                 s = rb_entry(parent, struct symbol, rb_node);
231                 if (ip < s->start)
232                         p = &(*p)->rb_left;
233                 else
234                         p = &(*p)->rb_right;
235         }
236         rb_link_node(&sym->rb_node, parent, p);
237         rb_insert_color(&sym->rb_node, self);
238 }
239
240 static struct symbol *symbols__find(struct rb_root *self, u64 ip)
241 {
242         struct rb_node *n;
243
244         if (self == NULL)
245                 return NULL;
246
247         n = self->rb_node;
248
249         while (n) {
250                 struct symbol *s = rb_entry(n, struct symbol, rb_node);
251
252                 if (ip < s->start)
253                         n = n->rb_left;
254                 else if (ip > s->end)
255                         n = n->rb_right;
256                 else
257                         return s;
258         }
259
260         return NULL;
261 }
262
263 struct symbol_name_rb_node {
264         struct rb_node  rb_node;
265         struct symbol   sym;
266 };
267
268 static void symbols__insert_by_name(struct rb_root *self, struct symbol *sym)
269 {
270         struct rb_node **p = &self->rb_node;
271         struct rb_node *parent = NULL;
272         struct symbol_name_rb_node *symn = ((void *)sym) - sizeof(*parent), *s;
273
274         while (*p != NULL) {
275                 parent = *p;
276                 s = rb_entry(parent, struct symbol_name_rb_node, rb_node);
277                 if (strcmp(sym->name, s->sym.name) < 0)
278                         p = &(*p)->rb_left;
279                 else
280                         p = &(*p)->rb_right;
281         }
282         rb_link_node(&symn->rb_node, parent, p);
283         rb_insert_color(&symn->rb_node, self);
284 }
285
286 static void symbols__sort_by_name(struct rb_root *self, struct rb_root *source)
287 {
288         struct rb_node *nd;
289
290         for (nd = rb_first(source); nd; nd = rb_next(nd)) {
291                 struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
292                 symbols__insert_by_name(self, pos);
293         }
294 }
295
296 static struct symbol *symbols__find_by_name(struct rb_root *self, const char *name)
297 {
298         struct rb_node *n;
299
300         if (self == NULL)
301                 return NULL;
302
303         n = self->rb_node;
304
305         while (n) {
306                 struct symbol_name_rb_node *s;
307                 int cmp;
308
309                 s = rb_entry(n, struct symbol_name_rb_node, rb_node);
310                 cmp = strcmp(name, s->sym.name);
311
312                 if (cmp < 0)
313                         n = n->rb_left;
314                 else if (cmp > 0)
315                         n = n->rb_right;
316                 else
317                         return &s->sym;
318         }
319
320         return NULL;
321 }
322
323 struct symbol *dso__find_symbol(struct dso *self,
324                                 enum map_type type, u64 addr)
325 {
326         return symbols__find(&self->symbols[type], addr);
327 }
328
329 struct symbol *dso__find_symbol_by_name(struct dso *self, enum map_type type,
330                                         const char *name)
331 {
332         return symbols__find_by_name(&self->symbol_names[type], name);
333 }
334
335 void dso__sort_by_name(struct dso *self, enum map_type type)
336 {
337         dso__set_sorted_by_name(self, type);
338         return symbols__sort_by_name(&self->symbol_names[type],
339                                      &self->symbols[type]);
340 }
341
342 int build_id__sprintf(const u8 *self, int len, char *bf)
343 {
344         char *bid = bf;
345         const u8 *raw = self;
346         int i;
347
348         for (i = 0; i < len; ++i) {
349                 sprintf(bid, "%02x", *raw);
350                 ++raw;
351                 bid += 2;
352         }
353
354         return raw - self;
355 }
356
357 size_t dso__fprintf_buildid(struct dso *self, FILE *fp)
358 {
359         char sbuild_id[BUILD_ID_SIZE * 2 + 1];
360
361         build_id__sprintf(self->build_id, sizeof(self->build_id), sbuild_id);
362         return fprintf(fp, "%s", sbuild_id);
363 }
364
365 size_t dso__fprintf(struct dso *self, enum map_type type, FILE *fp)
366 {
367         struct rb_node *nd;
368         size_t ret = fprintf(fp, "dso: %s (", self->short_name);
369
370         ret += dso__fprintf_buildid(self, fp);
371         ret += fprintf(fp, ")\n");
372         for (nd = rb_first(&self->symbols[type]); nd; nd = rb_next(nd)) {
373                 struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
374                 ret += symbol__fprintf(pos, fp);
375         }
376
377         return ret;
378 }
379
380 int kallsyms__parse(const char *filename, void *arg,
381                     int (*process_symbol)(void *arg, const char *name,
382                                                      char type, u64 start))
383 {
384         char *line = NULL;
385         size_t n;
386         int err = 0;
387         FILE *file = fopen(filename, "r");
388
389         if (file == NULL)
390                 goto out_failure;
391
392         while (!feof(file)) {
393                 u64 start;
394                 int line_len, len;
395                 char symbol_type;
396                 char *symbol_name;
397
398                 line_len = getline(&line, &n, file);
399                 if (line_len < 0)
400                         break;
401
402                 if (!line)
403                         goto out_failure;
404
405                 line[--line_len] = '\0'; /* \n */
406
407                 len = hex2u64(line, &start);
408
409                 len++;
410                 if (len + 2 >= line_len)
411                         continue;
412
413                 symbol_type = toupper(line[len]);
414                 symbol_name = line + len + 2;
415
416                 err = process_symbol(arg, symbol_name, symbol_type, start);
417                 if (err)
418                         break;
419         }
420
421         free(line);
422         fclose(file);
423         return err;
424
425 out_failure:
426         return -1;
427 }
428
429 struct process_kallsyms_args {
430         struct map *map;
431         struct dso *dso;
432 };
433
434 static int map__process_kallsym_symbol(void *arg, const char *name,
435                                        char type, u64 start)
436 {
437         struct symbol *sym;
438         struct process_kallsyms_args *a = arg;
439         struct rb_root *root = &a->dso->symbols[a->map->type];
440
441         if (!symbol_type__is_a(type, a->map->type))
442                 return 0;
443
444         /*
445          * Will fix up the end later, when we have all symbols sorted.
446          */
447         sym = symbol__new(start, 0, name);
448
449         if (sym == NULL)
450                 return -ENOMEM;
451         /*
452          * We will pass the symbols to the filter later, in
453          * map__split_kallsyms, when we have split the maps per module
454          */
455         symbols__insert(root, sym);
456         return 0;
457 }
458
459 /*
460  * Loads the function entries in /proc/kallsyms into kernel_map->dso,
461  * so that we can in the next step set the symbol ->end address and then
462  * call kernel_maps__split_kallsyms.
463  */
464 static int dso__load_all_kallsyms(struct dso *self, const char *filename,
465                                   struct map *map)
466 {
467         struct process_kallsyms_args args = { .map = map, .dso = self, };
468         return kallsyms__parse(filename, &args, map__process_kallsym_symbol);
469 }
470
471 /*
472  * Split the symbols into maps, making sure there are no overlaps, i.e. the
473  * kernel range is broken in several maps, named [kernel].N, as we don't have
474  * the original ELF section names vmlinux have.
475  */
476 static int dso__split_kallsyms(struct dso *self, struct map *map,
477                                symbol_filter_t filter)
478 {
479         struct map_groups *kmaps = map__kmap(map)->kmaps;
480         struct map *curr_map = map;
481         struct symbol *pos;
482         int count = 0;
483         struct rb_root *root = &self->symbols[map->type];
484         struct rb_node *next = rb_first(root);
485         int kernel_range = 0;
486
487         while (next) {
488                 char *module;
489
490                 pos = rb_entry(next, struct symbol, rb_node);
491                 next = rb_next(&pos->rb_node);
492
493                 module = strchr(pos->name, '\t');
494                 if (module) {
495                         if (!symbol_conf.use_modules)
496                                 goto discard_symbol;
497
498                         *module++ = '\0';
499
500                         if (strcmp(curr_map->dso->short_name, module)) {
501                                 curr_map = map_groups__find_by_name(kmaps, map->type, module);
502                                 if (curr_map == NULL) {
503                                         pr_debug("/proc/{kallsyms,modules} "
504                                                  "inconsistency while looking "
505                                                  "for \"%s\" module!\n", module);
506                                         return -1;
507                                 }
508
509                                 if (curr_map->dso->loaded)
510                                         goto discard_symbol;
511                         }
512                         /*
513                          * So that we look just like we get from .ko files,
514                          * i.e. not prelinked, relative to map->start.
515                          */
516                         pos->start = curr_map->map_ip(curr_map, pos->start);
517                         pos->end   = curr_map->map_ip(curr_map, pos->end);
518                 } else if (curr_map != map) {
519                         char dso_name[PATH_MAX];
520                         struct dso *dso;
521
522                         snprintf(dso_name, sizeof(dso_name), "[kernel].%d",
523                                  kernel_range++);
524
525                         dso = dso__new(dso_name);
526                         if (dso == NULL)
527                                 return -1;
528
529                         curr_map = map__new2(pos->start, dso, map->type);
530                         if (curr_map == NULL) {
531                                 dso__delete(dso);
532                                 return -1;
533                         }
534
535                         curr_map->map_ip = curr_map->unmap_ip = identity__map_ip;
536                         map_groups__insert(kmaps, curr_map);
537                         ++kernel_range;
538                 }
539
540                 if (filter && filter(curr_map, pos)) {
541 discard_symbol:         rb_erase(&pos->rb_node, root);
542                         symbol__delete(pos);
543                 } else {
544                         if (curr_map != map) {
545                                 rb_erase(&pos->rb_node, root);
546                                 symbols__insert(&curr_map->dso->symbols[curr_map->type], pos);
547                         }
548                         count++;
549                 }
550         }
551
552         return count;
553 }
554
555 int dso__load_kallsyms(struct dso *self, const char *filename,
556                        struct map *map, symbol_filter_t filter)
557 {
558         if (dso__load_all_kallsyms(self, filename, map) < 0)
559                 return -1;
560
561         symbols__fixup_end(&self->symbols[map->type]);
562         self->origin = DSO__ORIG_KERNEL;
563
564         return dso__split_kallsyms(self, map, filter);
565 }
566
567 static int dso__load_perf_map(struct dso *self, struct map *map,
568                               symbol_filter_t filter)
569 {
570         char *line = NULL;
571         size_t n;
572         FILE *file;
573         int nr_syms = 0;
574
575         file = fopen(self->long_name, "r");
576         if (file == NULL)
577                 goto out_failure;
578
579         while (!feof(file)) {
580                 u64 start, size;
581                 struct symbol *sym;
582                 int line_len, len;
583
584                 line_len = getline(&line, &n, file);
585                 if (line_len < 0)
586                         break;
587
588                 if (!line)
589                         goto out_failure;
590
591                 line[--line_len] = '\0'; /* \n */
592
593                 len = hex2u64(line, &start);
594
595                 len++;
596                 if (len + 2 >= line_len)
597                         continue;
598
599                 len += hex2u64(line + len, &size);
600
601                 len++;
602                 if (len + 2 >= line_len)
603                         continue;
604
605                 sym = symbol__new(start, size, line + len);
606
607                 if (sym == NULL)
608                         goto out_delete_line;
609
610                 if (filter && filter(map, sym))
611                         symbol__delete(sym);
612                 else {
613                         symbols__insert(&self->symbols[map->type], sym);
614                         nr_syms++;
615                 }
616         }
617
618         free(line);
619         fclose(file);
620
621         return nr_syms;
622
623 out_delete_line:
624         free(line);
625 out_failure:
626         return -1;
627 }
628
629 /**
630  * elf_symtab__for_each_symbol - iterate thru all the symbols
631  *
632  * @self: struct elf_symtab instance to iterate
633  * @idx: uint32_t idx
634  * @sym: GElf_Sym iterator
635  */
636 #define elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) \
637         for (idx = 0, gelf_getsym(syms, idx, &sym);\
638              idx < nr_syms; \
639              idx++, gelf_getsym(syms, idx, &sym))
640
641 static inline uint8_t elf_sym__type(const GElf_Sym *sym)
642 {
643         return GELF_ST_TYPE(sym->st_info);
644 }
645
646 static inline int elf_sym__is_function(const GElf_Sym *sym)
647 {
648         return elf_sym__type(sym) == STT_FUNC &&
649                sym->st_name != 0 &&
650                sym->st_shndx != SHN_UNDEF;
651 }
652
653 static inline bool elf_sym__is_object(const GElf_Sym *sym)
654 {
655         return elf_sym__type(sym) == STT_OBJECT &&
656                 sym->st_name != 0 &&
657                 sym->st_shndx != SHN_UNDEF;
658 }
659
660 static inline int elf_sym__is_label(const GElf_Sym *sym)
661 {
662         return elf_sym__type(sym) == STT_NOTYPE &&
663                 sym->st_name != 0 &&
664                 sym->st_shndx != SHN_UNDEF &&
665                 sym->st_shndx != SHN_ABS;
666 }
667
668 static inline const char *elf_sec__name(const GElf_Shdr *shdr,
669                                         const Elf_Data *secstrs)
670 {
671         return secstrs->d_buf + shdr->sh_name;
672 }
673
674 static inline int elf_sec__is_text(const GElf_Shdr *shdr,
675                                         const Elf_Data *secstrs)
676 {
677         return strstr(elf_sec__name(shdr, secstrs), "text") != NULL;
678 }
679
680 static inline bool elf_sec__is_data(const GElf_Shdr *shdr,
681                                     const Elf_Data *secstrs)
682 {
683         return strstr(elf_sec__name(shdr, secstrs), "data") != NULL;
684 }
685
686 static inline const char *elf_sym__name(const GElf_Sym *sym,
687                                         const Elf_Data *symstrs)
688 {
689         return symstrs->d_buf + sym->st_name;
690 }
691
692 static Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
693                                     GElf_Shdr *shp, const char *name,
694                                     size_t *idx)
695 {
696         Elf_Scn *sec = NULL;
697         size_t cnt = 1;
698
699         while ((sec = elf_nextscn(elf, sec)) != NULL) {
700                 char *str;
701
702                 gelf_getshdr(sec, shp);
703                 str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
704                 if (!strcmp(name, str)) {
705                         if (idx)
706                                 *idx = cnt;
707                         break;
708                 }
709                 ++cnt;
710         }
711
712         return sec;
713 }
714
715 #define elf_section__for_each_rel(reldata, pos, pos_mem, idx, nr_entries) \
716         for (idx = 0, pos = gelf_getrel(reldata, 0, &pos_mem); \
717              idx < nr_entries; \
718              ++idx, pos = gelf_getrel(reldata, idx, &pos_mem))
719
720 #define elf_section__for_each_rela(reldata, pos, pos_mem, idx, nr_entries) \
721         for (idx = 0, pos = gelf_getrela(reldata, 0, &pos_mem); \
722              idx < nr_entries; \
723              ++idx, pos = gelf_getrela(reldata, idx, &pos_mem))
724
725 /*
726  * We need to check if we have a .dynsym, so that we can handle the
727  * .plt, synthesizing its symbols, that aren't on the symtabs (be it
728  * .dynsym or .symtab).
729  * And always look at the original dso, not at debuginfo packages, that
730  * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
731  */
732 static int dso__synthesize_plt_symbols(struct  dso *self, struct map *map,
733                                        symbol_filter_t filter)
734 {
735         uint32_t nr_rel_entries, idx;
736         GElf_Sym sym;
737         u64 plt_offset;
738         GElf_Shdr shdr_plt;
739         struct symbol *f;
740         GElf_Shdr shdr_rel_plt, shdr_dynsym;
741         Elf_Data *reldata, *syms, *symstrs;
742         Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
743         size_t dynsym_idx;
744         GElf_Ehdr ehdr;
745         char sympltname[1024];
746         Elf *elf;
747         int nr = 0, symidx, fd, err = 0;
748
749         fd = open(self->long_name, O_RDONLY);
750         if (fd < 0)
751                 goto out;
752
753         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
754         if (elf == NULL)
755                 goto out_close;
756
757         if (gelf_getehdr(elf, &ehdr) == NULL)
758                 goto out_elf_end;
759
760         scn_dynsym = elf_section_by_name(elf, &ehdr, &shdr_dynsym,
761                                          ".dynsym", &dynsym_idx);
762         if (scn_dynsym == NULL)
763                 goto out_elf_end;
764
765         scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
766                                           ".rela.plt", NULL);
767         if (scn_plt_rel == NULL) {
768                 scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
769                                                   ".rel.plt", NULL);
770                 if (scn_plt_rel == NULL)
771                         goto out_elf_end;
772         }
773
774         err = -1;
775
776         if (shdr_rel_plt.sh_link != dynsym_idx)
777                 goto out_elf_end;
778
779         if (elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL) == NULL)
780                 goto out_elf_end;
781
782         /*
783          * Fetch the relocation section to find the idxes to the GOT
784          * and the symbols in the .dynsym they refer to.
785          */
786         reldata = elf_getdata(scn_plt_rel, NULL);
787         if (reldata == NULL)
788                 goto out_elf_end;
789
790         syms = elf_getdata(scn_dynsym, NULL);
791         if (syms == NULL)
792                 goto out_elf_end;
793
794         scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
795         if (scn_symstrs == NULL)
796                 goto out_elf_end;
797
798         symstrs = elf_getdata(scn_symstrs, NULL);
799         if (symstrs == NULL)
800                 goto out_elf_end;
801
802         nr_rel_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
803         plt_offset = shdr_plt.sh_offset;
804
805         if (shdr_rel_plt.sh_type == SHT_RELA) {
806                 GElf_Rela pos_mem, *pos;
807
808                 elf_section__for_each_rela(reldata, pos, pos_mem, idx,
809                                            nr_rel_entries) {
810                         symidx = GELF_R_SYM(pos->r_info);
811                         plt_offset += shdr_plt.sh_entsize;
812                         gelf_getsym(syms, symidx, &sym);
813                         snprintf(sympltname, sizeof(sympltname),
814                                  "%s@plt", elf_sym__name(&sym, symstrs));
815
816                         f = symbol__new(plt_offset, shdr_plt.sh_entsize,
817                                         sympltname);
818                         if (!f)
819                                 goto out_elf_end;
820
821                         if (filter && filter(map, f))
822                                 symbol__delete(f);
823                         else {
824                                 symbols__insert(&self->symbols[map->type], f);
825                                 ++nr;
826                         }
827                 }
828         } else if (shdr_rel_plt.sh_type == SHT_REL) {
829                 GElf_Rel pos_mem, *pos;
830                 elf_section__for_each_rel(reldata, pos, pos_mem, idx,
831                                           nr_rel_entries) {
832                         symidx = GELF_R_SYM(pos->r_info);
833                         plt_offset += shdr_plt.sh_entsize;
834                         gelf_getsym(syms, symidx, &sym);
835                         snprintf(sympltname, sizeof(sympltname),
836                                  "%s@plt", elf_sym__name(&sym, symstrs));
837
838                         f = symbol__new(plt_offset, shdr_plt.sh_entsize,
839                                         sympltname);
840                         if (!f)
841                                 goto out_elf_end;
842
843                         if (filter && filter(map, f))
844                                 symbol__delete(f);
845                         else {
846                                 symbols__insert(&self->symbols[map->type], f);
847                                 ++nr;
848                         }
849                 }
850         }
851
852         err = 0;
853 out_elf_end:
854         elf_end(elf);
855 out_close:
856         close(fd);
857
858         if (err == 0)
859                 return nr;
860 out:
861         pr_warning("%s: problems reading %s PLT info.\n",
862                    __func__, self->long_name);
863         return 0;
864 }
865
866 static bool elf_sym__is_a(GElf_Sym *self, enum map_type type)
867 {
868         switch (type) {
869         case MAP__FUNCTION:
870                 return elf_sym__is_function(self);
871         case MAP__VARIABLE:
872                 return elf_sym__is_object(self);
873         default:
874                 return false;
875         }
876 }
877
878 static bool elf_sec__is_a(GElf_Shdr *self, Elf_Data *secstrs, enum map_type type)
879 {
880         switch (type) {
881         case MAP__FUNCTION:
882                 return elf_sec__is_text(self, secstrs);
883         case MAP__VARIABLE:
884                 return elf_sec__is_data(self, secstrs);
885         default:
886                 return false;
887         }
888 }
889
890 static int dso__load_sym(struct dso *self, struct map *map, const char *name,
891                          int fd, symbol_filter_t filter, int kmodule)
892 {
893         struct kmap *kmap = self->kernel ? map__kmap(map) : NULL;
894         struct map *curr_map = map;
895         struct dso *curr_dso = self;
896         size_t dso_name_len = strlen(self->short_name);
897         Elf_Data *symstrs, *secstrs;
898         uint32_t nr_syms;
899         int err = -1;
900         uint32_t idx;
901         GElf_Ehdr ehdr;
902         GElf_Shdr shdr;
903         Elf_Data *syms;
904         GElf_Sym sym;
905         Elf_Scn *sec, *sec_strndx;
906         Elf *elf;
907         int nr = 0;
908
909         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
910         if (elf == NULL) {
911                 pr_err("%s: cannot read %s ELF file.\n", __func__, name);
912                 goto out_close;
913         }
914
915         if (gelf_getehdr(elf, &ehdr) == NULL) {
916                 pr_err("%s: cannot get elf header.\n", __func__);
917                 goto out_elf_end;
918         }
919
920         sec = elf_section_by_name(elf, &ehdr, &shdr, ".symtab", NULL);
921         if (sec == NULL) {
922                 sec = elf_section_by_name(elf, &ehdr, &shdr, ".dynsym", NULL);
923                 if (sec == NULL)
924                         goto out_elf_end;
925         }
926
927         syms = elf_getdata(sec, NULL);
928         if (syms == NULL)
929                 goto out_elf_end;
930
931         sec = elf_getscn(elf, shdr.sh_link);
932         if (sec == NULL)
933                 goto out_elf_end;
934
935         symstrs = elf_getdata(sec, NULL);
936         if (symstrs == NULL)
937                 goto out_elf_end;
938
939         sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
940         if (sec_strndx == NULL)
941                 goto out_elf_end;
942
943         secstrs = elf_getdata(sec_strndx, NULL);
944         if (secstrs == NULL)
945                 goto out_elf_end;
946
947         nr_syms = shdr.sh_size / shdr.sh_entsize;
948
949         memset(&sym, 0, sizeof(sym));
950         if (!self->kernel) {
951                 self->adjust_symbols = (ehdr.e_type == ET_EXEC ||
952                                 elf_section_by_name(elf, &ehdr, &shdr,
953                                                      ".gnu.prelink_undo",
954                                                      NULL) != NULL);
955         } else self->adjust_symbols = 0;
956
957         elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
958                 struct symbol *f;
959                 const char *elf_name = elf_sym__name(&sym, symstrs);
960                 char *demangled = NULL;
961                 int is_label = elf_sym__is_label(&sym);
962                 const char *section_name;
963
964                 if (kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
965                     strcmp(elf_name, kmap->ref_reloc_sym->name) == 0)
966                         kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
967
968                 if (!is_label && !elf_sym__is_a(&sym, map->type))
969                         continue;
970
971                 sec = elf_getscn(elf, sym.st_shndx);
972                 if (!sec)
973                         goto out_elf_end;
974
975                 gelf_getshdr(sec, &shdr);
976
977                 if (is_label && !elf_sec__is_a(&shdr, secstrs, map->type))
978                         continue;
979
980                 section_name = elf_sec__name(&shdr, secstrs);
981
982                 if (self->kernel || kmodule) {
983                         char dso_name[PATH_MAX];
984
985                         if (strcmp(section_name,
986                                    curr_dso->short_name + dso_name_len) == 0)
987                                 goto new_symbol;
988
989                         if (strcmp(section_name, ".text") == 0) {
990                                 curr_map = map;
991                                 curr_dso = self;
992                                 goto new_symbol;
993                         }
994
995                         snprintf(dso_name, sizeof(dso_name),
996                                  "%s%s", self->short_name, section_name);
997
998                         curr_map = map_groups__find_by_name(kmap->kmaps, map->type, dso_name);
999                         if (curr_map == NULL) {
1000                                 u64 start = sym.st_value;
1001
1002                                 if (kmodule)
1003                                         start += map->start + shdr.sh_offset;
1004
1005                                 curr_dso = dso__new(dso_name);
1006                                 if (curr_dso == NULL)
1007                                         goto out_elf_end;
1008                                 curr_map = map__new2(start, curr_dso,
1009                                                      map->type);
1010                                 if (curr_map == NULL) {
1011                                         dso__delete(curr_dso);
1012                                         goto out_elf_end;
1013                                 }
1014                                 curr_map->map_ip = identity__map_ip;
1015                                 curr_map->unmap_ip = identity__map_ip;
1016                                 curr_dso->origin = DSO__ORIG_KERNEL;
1017                                 map_groups__insert(kmap->kmaps, curr_map);
1018                                 dsos__add(&dsos__kernel, curr_dso);
1019                                 dso__set_loaded(curr_dso, map->type);
1020                         } else
1021                                 curr_dso = curr_map->dso;
1022
1023                         goto new_symbol;
1024                 }
1025
1026                 if (curr_dso->adjust_symbols) {
1027                         pr_debug4("%s: adjusting symbol: st_value: %#Lx "
1028                                   "sh_addr: %#Lx sh_offset: %#Lx\n", __func__,
1029                                   (u64)sym.st_value, (u64)shdr.sh_addr,
1030                                   (u64)shdr.sh_offset);
1031                         sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1032                 }
1033                 /*
1034                  * We need to figure out if the object was created from C++ sources
1035                  * DWARF DW_compile_unit has this, but we don't always have access
1036                  * to it...
1037                  */
1038                 demangled = bfd_demangle(NULL, elf_name, DMGL_PARAMS | DMGL_ANSI);
1039                 if (demangled != NULL)
1040                         elf_name = demangled;
1041 new_symbol:
1042                 f = symbol__new(sym.st_value, sym.st_size, elf_name);
1043                 free(demangled);
1044                 if (!f)
1045                         goto out_elf_end;
1046
1047                 if (filter && filter(curr_map, f))
1048                         symbol__delete(f);
1049                 else {
1050                         symbols__insert(&curr_dso->symbols[curr_map->type], f);
1051                         nr++;
1052                 }
1053         }
1054
1055         /*
1056          * For misannotated, zeroed, ASM function sizes.
1057          */
1058         if (nr > 0) {
1059                 symbols__fixup_end(&self->symbols[map->type]);
1060                 if (kmap) {
1061                         /*
1062                          * We need to fixup this here too because we create new
1063                          * maps here, for things like vsyscall sections.
1064                          */
1065                         __map_groups__fixup_end(kmap->kmaps, map->type);
1066                 }
1067         }
1068         err = nr;
1069 out_elf_end:
1070         elf_end(elf);
1071 out_close:
1072         return err;
1073 }
1074
1075 static bool dso__build_id_equal(const struct dso *self, u8 *build_id)
1076 {
1077         return memcmp(self->build_id, build_id, sizeof(self->build_id)) == 0;
1078 }
1079
1080 static bool __dsos__read_build_ids(struct list_head *head, bool with_hits)
1081 {
1082         bool have_build_id = false;
1083         struct dso *pos;
1084
1085         list_for_each_entry(pos, head, node) {
1086                 if (with_hits && !pos->hit)
1087                         continue;
1088                 if (filename__read_build_id(pos->long_name, pos->build_id,
1089                                             sizeof(pos->build_id)) > 0) {
1090                         have_build_id     = true;
1091                         pos->has_build_id = true;
1092                 }
1093         }
1094
1095         return have_build_id;
1096 }
1097
1098 bool dsos__read_build_ids(bool with_hits)
1099 {
1100         bool kbuildids = __dsos__read_build_ids(&dsos__kernel, with_hits),
1101              ubuildids = __dsos__read_build_ids(&dsos__user, with_hits);
1102         return kbuildids || ubuildids;
1103 }
1104
1105 /*
1106  * Align offset to 4 bytes as needed for note name and descriptor data.
1107  */
1108 #define NOTE_ALIGN(n) (((n) + 3) & -4U)
1109
1110 int filename__read_build_id(const char *filename, void *bf, size_t size)
1111 {
1112         int fd, err = -1;
1113         GElf_Ehdr ehdr;
1114         GElf_Shdr shdr;
1115         Elf_Data *data;
1116         Elf_Scn *sec;
1117         Elf_Kind ek;
1118         void *ptr;
1119         Elf *elf;
1120
1121         if (size < BUILD_ID_SIZE)
1122                 goto out;
1123
1124         fd = open(filename, O_RDONLY);
1125         if (fd < 0)
1126                 goto out;
1127
1128         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1129         if (elf == NULL) {
1130                 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
1131                 goto out_close;
1132         }
1133
1134         ek = elf_kind(elf);
1135         if (ek != ELF_K_ELF)
1136                 goto out_elf_end;
1137
1138         if (gelf_getehdr(elf, &ehdr) == NULL) {
1139                 pr_err("%s: cannot get elf header.\n", __func__);
1140                 goto out_elf_end;
1141         }
1142
1143         sec = elf_section_by_name(elf, &ehdr, &shdr,
1144                                   ".note.gnu.build-id", NULL);
1145         if (sec == NULL) {
1146                 sec = elf_section_by_name(elf, &ehdr, &shdr,
1147                                           ".notes", NULL);
1148                 if (sec == NULL)
1149                         goto out_elf_end;
1150         }
1151
1152         data = elf_getdata(sec, NULL);
1153         if (data == NULL)
1154                 goto out_elf_end;
1155
1156         ptr = data->d_buf;
1157         while (ptr < (data->d_buf + data->d_size)) {
1158                 GElf_Nhdr *nhdr = ptr;
1159                 int namesz = NOTE_ALIGN(nhdr->n_namesz),
1160                     descsz = NOTE_ALIGN(nhdr->n_descsz);
1161                 const char *name;
1162
1163                 ptr += sizeof(*nhdr);
1164                 name = ptr;
1165                 ptr += namesz;
1166                 if (nhdr->n_type == NT_GNU_BUILD_ID &&
1167                     nhdr->n_namesz == sizeof("GNU")) {
1168                         if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
1169                                 memcpy(bf, ptr, BUILD_ID_SIZE);
1170                                 err = BUILD_ID_SIZE;
1171                                 break;
1172                         }
1173                 }
1174                 ptr += descsz;
1175         }
1176 out_elf_end:
1177         elf_end(elf);
1178 out_close:
1179         close(fd);
1180 out:
1181         return err;
1182 }
1183
1184 int sysfs__read_build_id(const char *filename, void *build_id, size_t size)
1185 {
1186         int fd, err = -1;
1187
1188         if (size < BUILD_ID_SIZE)
1189                 goto out;
1190
1191         fd = open(filename, O_RDONLY);
1192         if (fd < 0)
1193                 goto out;
1194
1195         while (1) {
1196                 char bf[BUFSIZ];
1197                 GElf_Nhdr nhdr;
1198                 int namesz, descsz;
1199
1200                 if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
1201                         break;
1202
1203                 namesz = NOTE_ALIGN(nhdr.n_namesz);
1204                 descsz = NOTE_ALIGN(nhdr.n_descsz);
1205                 if (nhdr.n_type == NT_GNU_BUILD_ID &&
1206                     nhdr.n_namesz == sizeof("GNU")) {
1207                         if (read(fd, bf, namesz) != namesz)
1208                                 break;
1209                         if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
1210                                 if (read(fd, build_id,
1211                                     BUILD_ID_SIZE) == BUILD_ID_SIZE) {
1212                                         err = 0;
1213                                         break;
1214                                 }
1215                         } else if (read(fd, bf, descsz) != descsz)
1216                                 break;
1217                 } else {
1218                         int n = namesz + descsz;
1219                         if (read(fd, bf, n) != n)
1220                                 break;
1221                 }
1222         }
1223         close(fd);
1224 out:
1225         return err;
1226 }
1227
1228 char dso__symtab_origin(const struct dso *self)
1229 {
1230         static const char origin[] = {
1231                 [DSO__ORIG_KERNEL] =   'k',
1232                 [DSO__ORIG_JAVA_JIT] = 'j',
1233                 [DSO__ORIG_BUILD_ID_CACHE] = 'B',
1234                 [DSO__ORIG_FEDORA] =   'f',
1235                 [DSO__ORIG_UBUNTU] =   'u',
1236                 [DSO__ORIG_BUILDID] =  'b',
1237                 [DSO__ORIG_DSO] =      'd',
1238                 [DSO__ORIG_KMODULE] =  'K',
1239         };
1240
1241         if (self == NULL || self->origin == DSO__ORIG_NOT_FOUND)
1242                 return '!';
1243         return origin[self->origin];
1244 }
1245
1246 int dso__load(struct dso *self, struct map *map, symbol_filter_t filter)
1247 {
1248         int size = PATH_MAX;
1249         char *name;
1250         u8 build_id[BUILD_ID_SIZE];
1251         char build_id_hex[BUILD_ID_SIZE * 2 + 1];
1252         int ret = -1;
1253         int fd;
1254
1255         dso__set_loaded(self, map->type);
1256
1257         if (self->kernel)
1258                 return dso__load_kernel_sym(self, map, filter);
1259
1260         name = malloc(size);
1261         if (!name)
1262                 return -1;
1263
1264         self->adjust_symbols = 0;
1265
1266         if (strncmp(self->name, "/tmp/perf-", 10) == 0) {
1267                 ret = dso__load_perf_map(self, map, filter);
1268                 self->origin = ret > 0 ? DSO__ORIG_JAVA_JIT :
1269                                          DSO__ORIG_NOT_FOUND;
1270                 return ret;
1271         }
1272
1273         self->origin = DSO__ORIG_BUILD_ID_CACHE;
1274
1275         if (self->has_build_id) {
1276                 build_id__sprintf(self->build_id, sizeof(self->build_id),
1277                                   build_id_hex);
1278                 snprintf(name, size, "%s/%s/.build-id/%.2s/%s",
1279                          getenv("HOME"), DEBUG_CACHE_DIR,
1280                          build_id_hex, build_id_hex + 2);
1281                 goto open_file;
1282         }
1283 more:
1284         do {
1285                 self->origin++;
1286                 switch (self->origin) {
1287                 case DSO__ORIG_FEDORA:
1288                         snprintf(name, size, "/usr/lib/debug%s.debug",
1289                                  self->long_name);
1290                         break;
1291                 case DSO__ORIG_UBUNTU:
1292                         snprintf(name, size, "/usr/lib/debug%s",
1293                                  self->long_name);
1294                         break;
1295                 case DSO__ORIG_BUILDID:
1296                         if (filename__read_build_id(self->long_name, build_id,
1297                                                     sizeof(build_id))) {
1298                                 build_id__sprintf(build_id, sizeof(build_id),
1299                                                   build_id_hex);
1300                                 snprintf(name, size,
1301                                          "/usr/lib/debug/.build-id/%.2s/%s.debug",
1302                                         build_id_hex, build_id_hex + 2);
1303                                 if (self->has_build_id)
1304                                         goto compare_build_id;
1305                                 break;
1306                         }
1307                         self->origin++;
1308                         /* Fall thru */
1309                 case DSO__ORIG_DSO:
1310                         snprintf(name, size, "%s", self->long_name);
1311                         break;
1312
1313                 default:
1314                         goto out;
1315                 }
1316
1317                 if (self->has_build_id) {
1318                         if (filename__read_build_id(name, build_id,
1319                                                     sizeof(build_id)) < 0)
1320                                 goto more;
1321 compare_build_id:
1322                         if (!dso__build_id_equal(self, build_id))
1323                                 goto more;
1324                 }
1325 open_file:
1326                 fd = open(name, O_RDONLY);
1327         } while (fd < 0);
1328
1329         ret = dso__load_sym(self, map, name, fd, filter, 0);
1330         close(fd);
1331
1332         /*
1333          * Some people seem to have debuginfo files _WITHOUT_ debug info!?!?
1334          */
1335         if (!ret)
1336                 goto more;
1337
1338         if (ret > 0) {
1339                 int nr_plt = dso__synthesize_plt_symbols(self, map, filter);
1340                 if (nr_plt > 0)
1341                         ret += nr_plt;
1342         }
1343 out:
1344         free(name);
1345         if (ret < 0 && strstr(self->name, " (deleted)") != NULL)
1346                 return 0;
1347         return ret;
1348 }
1349
1350 struct map *map_groups__find_by_name(struct map_groups *self,
1351                                      enum map_type type, const char *name)
1352 {
1353         struct rb_node *nd;
1354
1355         for (nd = rb_first(&self->maps[type]); nd; nd = rb_next(nd)) {
1356                 struct map *map = rb_entry(nd, struct map, rb_node);
1357
1358                 if (map->dso && strcmp(map->dso->short_name, name) == 0)
1359                         return map;
1360         }
1361
1362         return NULL;
1363 }
1364
1365 static int dso__kernel_module_get_build_id(struct dso *self)
1366 {
1367         char filename[PATH_MAX];
1368         /*
1369          * kernel module short names are of the form "[module]" and
1370          * we need just "module" here.
1371          */
1372         const char *name = self->short_name + 1;
1373
1374         snprintf(filename, sizeof(filename),
1375                  "/sys/module/%.*s/notes/.note.gnu.build-id",
1376                  (int)strlen(name - 1), name);
1377
1378         if (sysfs__read_build_id(filename, self->build_id,
1379                                  sizeof(self->build_id)) == 0)
1380                 self->has_build_id = true;
1381
1382         return 0;
1383 }
1384
1385 static int map_groups__set_modules_path_dir(struct map_groups *self, char *dirname)
1386 {
1387         struct dirent *dent;
1388         DIR *dir = opendir(dirname);
1389
1390         if (!dir) {
1391                 pr_debug("%s: cannot open %s dir\n", __func__, dirname);
1392                 return -1;
1393         }
1394
1395         while ((dent = readdir(dir)) != NULL) {
1396                 char path[PATH_MAX];
1397
1398                 if (dent->d_type == DT_DIR) {
1399                         if (!strcmp(dent->d_name, ".") ||
1400                             !strcmp(dent->d_name, ".."))
1401                                 continue;
1402
1403                         snprintf(path, sizeof(path), "%s/%s",
1404                                  dirname, dent->d_name);
1405                         if (map_groups__set_modules_path_dir(self, path) < 0)
1406                                 goto failure;
1407                 } else {
1408                         char *dot = strrchr(dent->d_name, '.'),
1409                              dso_name[PATH_MAX];
1410                         struct map *map;
1411                         char *long_name;
1412
1413                         if (dot == NULL || strcmp(dot, ".ko"))
1414                                 continue;
1415                         snprintf(dso_name, sizeof(dso_name), "[%.*s]",
1416                                  (int)(dot - dent->d_name), dent->d_name);
1417
1418                         strxfrchar(dso_name, '-', '_');
1419                         map = map_groups__find_by_name(self, MAP__FUNCTION, dso_name);
1420                         if (map == NULL)
1421                                 continue;
1422
1423                         snprintf(path, sizeof(path), "%s/%s",
1424                                  dirname, dent->d_name);
1425
1426                         long_name = strdup(path);
1427                         if (long_name == NULL)
1428                                 goto failure;
1429                         dso__set_long_name(map->dso, long_name);
1430                         dso__kernel_module_get_build_id(map->dso);
1431                 }
1432         }
1433
1434         return 0;
1435 failure:
1436         closedir(dir);
1437         return -1;
1438 }
1439
1440 static int map_groups__set_modules_path(struct map_groups *self)
1441 {
1442         struct utsname uts;
1443         char modules_path[PATH_MAX];
1444
1445         if (uname(&uts) < 0)
1446                 return -1;
1447
1448         snprintf(modules_path, sizeof(modules_path), "/lib/modules/%s/kernel",
1449                  uts.release);
1450
1451         return map_groups__set_modules_path_dir(self, modules_path);
1452 }
1453
1454 /*
1455  * Constructor variant for modules (where we know from /proc/modules where
1456  * they are loaded) and for vmlinux, where only after we load all the
1457  * symbols we'll know where it starts and ends.
1458  */
1459 static struct map *map__new2(u64 start, struct dso *dso, enum map_type type)
1460 {
1461         struct map *self = zalloc(sizeof(*self) +
1462                                   (dso->kernel ? sizeof(struct kmap) : 0));
1463         if (self != NULL) {
1464                 /*
1465                  * ->end will be filled after we load all the symbols
1466                  */
1467                 map__init(self, type, start, 0, 0, dso);
1468         }
1469
1470         return self;
1471 }
1472
1473 struct map *map_groups__new_module(struct map_groups *self, u64 start,
1474                                    const char *filename)
1475 {
1476         struct map *map;
1477         struct dso *dso = __dsos__findnew(&dsos__kernel, filename);
1478
1479         if (dso == NULL)
1480                 return NULL;
1481
1482         map = map__new2(start, dso, MAP__FUNCTION);
1483         if (map == NULL)
1484                 return NULL;
1485
1486         dso->origin = DSO__ORIG_KMODULE;
1487         map_groups__insert(self, map);
1488         return map;
1489 }
1490
1491 static int map_groups__create_modules(struct map_groups *self)
1492 {
1493         char *line = NULL;
1494         size_t n;
1495         FILE *file = fopen("/proc/modules", "r");
1496         struct map *map;
1497
1498         if (file == NULL)
1499                 return -1;
1500
1501         while (!feof(file)) {
1502                 char name[PATH_MAX];
1503                 u64 start;
1504                 char *sep;
1505                 int line_len;
1506
1507                 line_len = getline(&line, &n, file);
1508                 if (line_len < 0)
1509                         break;
1510
1511                 if (!line)
1512                         goto out_failure;
1513
1514                 line[--line_len] = '\0'; /* \n */
1515
1516                 sep = strrchr(line, 'x');
1517                 if (sep == NULL)
1518                         continue;
1519
1520                 hex2u64(sep + 1, &start);
1521
1522                 sep = strchr(line, ' ');
1523                 if (sep == NULL)
1524                         continue;
1525
1526                 *sep = '\0';
1527
1528                 snprintf(name, sizeof(name), "[%s]", line);
1529                 map = map_groups__new_module(self, start, name);
1530                 if (map == NULL)
1531                         goto out_delete_line;
1532                 dso__kernel_module_get_build_id(map->dso);
1533         }
1534
1535         free(line);
1536         fclose(file);
1537
1538         return map_groups__set_modules_path(self);
1539
1540 out_delete_line:
1541         free(line);
1542 out_failure:
1543         return -1;
1544 }
1545
1546 static int dso__load_vmlinux(struct dso *self, struct map *map,
1547                              const char *vmlinux, symbol_filter_t filter)
1548 {
1549         int err = -1, fd;
1550
1551         if (self->has_build_id) {
1552                 u8 build_id[BUILD_ID_SIZE];
1553
1554                 if (filename__read_build_id(vmlinux, build_id,
1555                                             sizeof(build_id)) < 0) {
1556                         pr_debug("No build_id in %s, ignoring it\n", vmlinux);
1557                         return -1;
1558                 }
1559                 if (!dso__build_id_equal(self, build_id)) {
1560                         char expected_build_id[BUILD_ID_SIZE * 2 + 1],
1561                              vmlinux_build_id[BUILD_ID_SIZE * 2 + 1];
1562
1563                         build_id__sprintf(self->build_id,
1564                                           sizeof(self->build_id),
1565                                           expected_build_id);
1566                         build_id__sprintf(build_id, sizeof(build_id),
1567                                           vmlinux_build_id);
1568                         pr_debug("build_id in %s is %s while expected is %s, "
1569                                  "ignoring it\n", vmlinux, vmlinux_build_id,
1570                                  expected_build_id);
1571                         return -1;
1572                 }
1573         }
1574
1575         fd = open(vmlinux, O_RDONLY);
1576         if (fd < 0)
1577                 return -1;
1578
1579         dso__set_loaded(self, map->type);
1580         err = dso__load_sym(self, map, vmlinux, fd, filter, 0);
1581         close(fd);
1582
1583         return err;
1584 }
1585
1586 int dso__load_vmlinux_path(struct dso *self, struct map *map,
1587                            symbol_filter_t filter)
1588 {
1589         int i, err = 0;
1590
1591         pr_debug("Looking at the vmlinux_path (%d entries long)\n",
1592                  vmlinux_path__nr_entries);
1593
1594         for (i = 0; i < vmlinux_path__nr_entries; ++i) {
1595                 err = dso__load_vmlinux(self, map, vmlinux_path[i], filter);
1596                 if (err > 0) {
1597                         pr_debug("Using %s for symbols\n", vmlinux_path[i]);
1598                         dso__set_long_name(self, strdup(vmlinux_path[i]));
1599                         break;
1600                 }
1601         }
1602
1603         return err;
1604 }
1605
1606 static int dso__load_kernel_sym(struct dso *self, struct map *map,
1607                                 symbol_filter_t filter)
1608 {
1609         int err;
1610         const char *kallsyms_filename = NULL;
1611         char *kallsyms_allocated_filename = NULL;
1612         /*
1613          * Step 1: if the user specified a vmlinux filename, use it and only
1614          * it, reporting errors to the user if it cannot be used.
1615          *
1616          * For instance, try to analyse an ARM perf.data file _without_ a
1617          * build-id, or if the user specifies the wrong path to the right
1618          * vmlinux file, obviously we can't fallback to another vmlinux (a
1619          * x86_86 one, on the machine where analysis is being performed, say),
1620          * or worse, /proc/kallsyms.
1621          *
1622          * If the specified file _has_ a build-id and there is a build-id
1623          * section in the perf.data file, we will still do the expected
1624          * validation in dso__load_vmlinux and will bail out if they don't
1625          * match.
1626          */
1627         if (symbol_conf.vmlinux_name != NULL) {
1628                 err = dso__load_vmlinux(self, map,
1629                                         symbol_conf.vmlinux_name, filter);
1630                 goto out_try_fixup;
1631         }
1632
1633         if (vmlinux_path != NULL) {
1634                 err = dso__load_vmlinux_path(self, map, filter);
1635                 if (err > 0)
1636                         goto out_fixup;
1637         }
1638
1639         /*
1640          * Say the kernel DSO was created when processing the build-id header table,
1641          * we have a build-id, so check if it is the same as the running kernel,
1642          * using it if it is.
1643          */
1644         if (self->has_build_id) {
1645                 u8 kallsyms_build_id[BUILD_ID_SIZE];
1646                 char sbuild_id[BUILD_ID_SIZE * 2 + 1];
1647
1648                 if (sysfs__read_build_id("/sys/kernel/notes", kallsyms_build_id,
1649                                          sizeof(kallsyms_build_id)) == 0) {
1650                         if (dso__build_id_equal(self, kallsyms_build_id)) {
1651                                 kallsyms_filename = "/proc/kallsyms";
1652                                 goto do_kallsyms;
1653                         }
1654                 }
1655                 /*
1656                  * Now look if we have it on the build-id cache in
1657                  * $HOME/.debug/[kernel.kallsyms].
1658                  */
1659                 build_id__sprintf(self->build_id, sizeof(self->build_id),
1660                                   sbuild_id);
1661
1662                 if (asprintf(&kallsyms_allocated_filename,
1663                              "%s/.debug/[kernel.kallsyms]/%s",
1664                              getenv("HOME"), sbuild_id) == -1)
1665                         return -1;
1666
1667                 kallsyms_filename = kallsyms_allocated_filename;
1668
1669                 if (access(kallsyms_filename, F_OK)) {
1670                         free(kallsyms_allocated_filename);
1671                         return -1;
1672                 }
1673         } else {
1674                 /*
1675                  * Last resort, if we don't have a build-id and couldn't find
1676                  * any vmlinux file, try the running kernel kallsyms table.
1677                  */
1678                 kallsyms_filename = "/proc/kallsyms";
1679         }
1680
1681 do_kallsyms:
1682         err = dso__load_kallsyms(self, kallsyms_filename, map, filter);
1683         free(kallsyms_allocated_filename);
1684
1685 out_try_fixup:
1686         if (err > 0) {
1687 out_fixup:
1688                 if (kallsyms_filename != NULL)
1689                         dso__set_long_name(self, strdup("[kernel.kallsyms]"));
1690                 map__fixup_start(map);
1691                 map__fixup_end(map);
1692         }
1693
1694         return err;
1695 }
1696
1697 LIST_HEAD(dsos__user);
1698 LIST_HEAD(dsos__kernel);
1699
1700 static void dsos__add(struct list_head *head, struct dso *dso)
1701 {
1702         list_add_tail(&dso->node, head);
1703 }
1704
1705 static struct dso *dsos__find(struct list_head *head, const char *name)
1706 {
1707         struct dso *pos;
1708
1709         list_for_each_entry(pos, head, node)
1710                 if (strcmp(pos->long_name, name) == 0)
1711                         return pos;
1712         return NULL;
1713 }
1714
1715 struct dso *__dsos__findnew(struct list_head *head, const char *name)
1716 {
1717         struct dso *dso = dsos__find(head, name);
1718
1719         if (!dso) {
1720                 dso = dso__new(name);
1721                 if (dso != NULL) {
1722                         dsos__add(head, dso);
1723                         dso__set_basename(dso);
1724                 }
1725         }
1726
1727         return dso;
1728 }
1729
1730 static void __dsos__fprintf(struct list_head *head, FILE *fp)
1731 {
1732         struct dso *pos;
1733
1734         list_for_each_entry(pos, head, node) {
1735                 int i;
1736                 for (i = 0; i < MAP__NR_TYPES; ++i)
1737                         dso__fprintf(pos, i, fp);
1738         }
1739 }
1740
1741 void dsos__fprintf(FILE *fp)
1742 {
1743         __dsos__fprintf(&dsos__kernel, fp);
1744         __dsos__fprintf(&dsos__user, fp);
1745 }
1746
1747 static size_t __dsos__fprintf_buildid(struct list_head *head, FILE *fp,
1748                                       bool with_hits)
1749 {
1750         struct dso *pos;
1751         size_t ret = 0;
1752
1753         list_for_each_entry(pos, head, node) {
1754                 if (with_hits && !pos->hit)
1755                         continue;
1756                 ret += dso__fprintf_buildid(pos, fp);
1757                 ret += fprintf(fp, " %s\n", pos->long_name);
1758         }
1759         return ret;
1760 }
1761
1762 size_t dsos__fprintf_buildid(FILE *fp, bool with_hits)
1763 {
1764         return (__dsos__fprintf_buildid(&dsos__kernel, fp, with_hits) +
1765                 __dsos__fprintf_buildid(&dsos__user, fp, with_hits));
1766 }
1767
1768 struct dso *dso__new_kernel(const char *name)
1769 {
1770         struct dso *self = dso__new(name ?: "[kernel.kallsyms]");
1771
1772         if (self != NULL) {
1773                 self->short_name = "[kernel]";
1774                 self->kernel     = 1;
1775         }
1776
1777         return self;
1778 }
1779
1780 void dso__read_running_kernel_build_id(struct dso *self)
1781 {
1782         if (sysfs__read_build_id("/sys/kernel/notes", self->build_id,
1783                                  sizeof(self->build_id)) == 0)
1784                 self->has_build_id = true;
1785 }
1786
1787 static struct dso *dsos__create_kernel(const char *vmlinux)
1788 {
1789         struct dso *kernel = dso__new_kernel(vmlinux);
1790
1791         if (kernel != NULL) {
1792                 dso__read_running_kernel_build_id(kernel);
1793                 dsos__add(&dsos__kernel, kernel);
1794         }
1795
1796         return kernel;
1797 }
1798
1799 int __map_groups__create_kernel_maps(struct map_groups *self,
1800                                      struct map *vmlinux_maps[MAP__NR_TYPES],
1801                                      struct dso *kernel)
1802 {
1803         enum map_type type;
1804
1805         for (type = 0; type < MAP__NR_TYPES; ++type) {
1806                 struct kmap *kmap;
1807
1808                 vmlinux_maps[type] = map__new2(0, kernel, type);
1809                 if (vmlinux_maps[type] == NULL)
1810                         return -1;
1811
1812                 vmlinux_maps[type]->map_ip =
1813                         vmlinux_maps[type]->unmap_ip = identity__map_ip;
1814
1815                 kmap = map__kmap(vmlinux_maps[type]);
1816                 kmap->kmaps = self;
1817                 map_groups__insert(self, vmlinux_maps[type]);
1818         }
1819
1820         return 0;
1821 }
1822
1823 static void vmlinux_path__exit(void)
1824 {
1825         while (--vmlinux_path__nr_entries >= 0) {
1826                 free(vmlinux_path[vmlinux_path__nr_entries]);
1827                 vmlinux_path[vmlinux_path__nr_entries] = NULL;
1828         }
1829
1830         free(vmlinux_path);
1831         vmlinux_path = NULL;
1832 }
1833
1834 static int vmlinux_path__init(void)
1835 {
1836         struct utsname uts;
1837         char bf[PATH_MAX];
1838
1839         if (uname(&uts) < 0)
1840                 return -1;
1841
1842         vmlinux_path = malloc(sizeof(char *) * 5);
1843         if (vmlinux_path == NULL)
1844                 return -1;
1845
1846         vmlinux_path[vmlinux_path__nr_entries] = strdup("vmlinux");
1847         if (vmlinux_path[vmlinux_path__nr_entries] == NULL)
1848                 goto out_fail;
1849         ++vmlinux_path__nr_entries;
1850         vmlinux_path[vmlinux_path__nr_entries] = strdup("/boot/vmlinux");
1851         if (vmlinux_path[vmlinux_path__nr_entries] == NULL)
1852                 goto out_fail;
1853         ++vmlinux_path__nr_entries;
1854         snprintf(bf, sizeof(bf), "/boot/vmlinux-%s", uts.release);
1855         vmlinux_path[vmlinux_path__nr_entries] = strdup(bf);
1856         if (vmlinux_path[vmlinux_path__nr_entries] == NULL)
1857                 goto out_fail;
1858         ++vmlinux_path__nr_entries;
1859         snprintf(bf, sizeof(bf), "/lib/modules/%s/build/vmlinux", uts.release);
1860         vmlinux_path[vmlinux_path__nr_entries] = strdup(bf);
1861         if (vmlinux_path[vmlinux_path__nr_entries] == NULL)
1862                 goto out_fail;
1863         ++vmlinux_path__nr_entries;
1864         snprintf(bf, sizeof(bf), "/usr/lib/debug/lib/modules/%s/vmlinux",
1865                  uts.release);
1866         vmlinux_path[vmlinux_path__nr_entries] = strdup(bf);
1867         if (vmlinux_path[vmlinux_path__nr_entries] == NULL)
1868                 goto out_fail;
1869         ++vmlinux_path__nr_entries;
1870
1871         return 0;
1872
1873 out_fail:
1874         vmlinux_path__exit();
1875         return -1;
1876 }
1877
1878 static int setup_list(struct strlist **list, const char *list_str,
1879                       const char *list_name)
1880 {
1881         if (list_str == NULL)
1882                 return 0;
1883
1884         *list = strlist__new(true, list_str);
1885         if (!*list) {
1886                 pr_err("problems parsing %s list\n", list_name);
1887                 return -1;
1888         }
1889         return 0;
1890 }
1891
1892 int symbol__init(void)
1893 {
1894         elf_version(EV_CURRENT);
1895         if (symbol_conf.sort_by_name)
1896                 symbol_conf.priv_size += (sizeof(struct symbol_name_rb_node) -
1897                                           sizeof(struct symbol));
1898
1899         if (symbol_conf.try_vmlinux_path && vmlinux_path__init() < 0)
1900                 return -1;
1901
1902         if (symbol_conf.field_sep && *symbol_conf.field_sep == '.') {
1903                 pr_err("'.' is the only non valid --field-separator argument\n");
1904                 return -1;
1905         }
1906
1907         if (setup_list(&symbol_conf.dso_list,
1908                        symbol_conf.dso_list_str, "dso") < 0)
1909                 return -1;
1910
1911         if (setup_list(&symbol_conf.comm_list,
1912                        symbol_conf.comm_list_str, "comm") < 0)
1913                 goto out_free_dso_list;
1914
1915         if (setup_list(&symbol_conf.sym_list,
1916                        symbol_conf.sym_list_str, "symbol") < 0)
1917                 goto out_free_comm_list;
1918
1919         return 0;
1920
1921 out_free_dso_list:
1922         strlist__delete(symbol_conf.dso_list);
1923 out_free_comm_list:
1924         strlist__delete(symbol_conf.comm_list);
1925         return -1;
1926 }
1927
1928 int map_groups__create_kernel_maps(struct map_groups *self,
1929                                    struct map *vmlinux_maps[MAP__NR_TYPES])
1930 {
1931         struct dso *kernel = dsos__create_kernel(symbol_conf.vmlinux_name);
1932
1933         if (kernel == NULL)
1934                 return -1;
1935
1936         if (__map_groups__create_kernel_maps(self, vmlinux_maps, kernel) < 0)
1937                 return -1;
1938
1939         if (symbol_conf.use_modules && map_groups__create_modules(self) < 0)
1940                 pr_debug("Problems creating module maps, continuing anyway...\n");
1941         /*
1942          * Now that we have all the maps created, just set the ->end of them:
1943          */
1944         map_groups__fixup_end(self);
1945         return 0;
1946 }