GNU Linux-libre 4.9.330-gnu1
[releases.git] / tools / perf / util / symbol.c
1 #include <dirent.h>
2 #include <errno.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <sys/param.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <inttypes.h>
12 #include "annotate.h"
13 #include "build-id.h"
14 #include "util.h"
15 #include "debug.h"
16 #include "machine.h"
17 #include "symbol.h"
18 #include "strlist.h"
19 #include "intlist.h"
20 #include "header.h"
21
22 #include <elf.h>
23 #include <limits.h>
24 #include <symbol/kallsyms.h>
25 #include <sys/utsname.h>
26
27 static int dso__load_kernel_sym(struct dso *dso, struct map *map);
28 static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map);
29 static bool symbol__is_idle(const char *name);
30
31 int vmlinux_path__nr_entries;
32 char **vmlinux_path;
33
34 struct symbol_conf symbol_conf = {
35         .use_modules            = true,
36         .try_vmlinux_path       = true,
37         .annotate_src           = true,
38         .demangle               = true,
39         .demangle_kernel        = false,
40         .cumulate_callchain     = true,
41         .show_hist_headers      = true,
42         .symfs                  = "",
43         .event_group            = true,
44 };
45
46 static enum dso_binary_type binary_type_symtab[] = {
47         DSO_BINARY_TYPE__KALLSYMS,
48         DSO_BINARY_TYPE__GUEST_KALLSYMS,
49         DSO_BINARY_TYPE__JAVA_JIT,
50         DSO_BINARY_TYPE__DEBUGLINK,
51         DSO_BINARY_TYPE__BUILD_ID_CACHE,
52         DSO_BINARY_TYPE__FEDORA_DEBUGINFO,
53         DSO_BINARY_TYPE__UBUNTU_DEBUGINFO,
54         DSO_BINARY_TYPE__BUILDID_DEBUGINFO,
55         DSO_BINARY_TYPE__SYSTEM_PATH_DSO,
56         DSO_BINARY_TYPE__GUEST_KMODULE,
57         DSO_BINARY_TYPE__GUEST_KMODULE_COMP,
58         DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE,
59         DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP,
60         DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO,
61         DSO_BINARY_TYPE__MIXEDUP_UBUNTU_DEBUGINFO,
62         DSO_BINARY_TYPE__NOT_FOUND,
63 };
64
65 #define DSO_BINARY_TYPE__SYMTAB_CNT ARRAY_SIZE(binary_type_symtab)
66
67 bool symbol_type__is_a(char symbol_type, enum map_type map_type)
68 {
69         symbol_type = toupper(symbol_type);
70
71         switch (map_type) {
72         case MAP__FUNCTION:
73                 return symbol_type == 'T' || symbol_type == 'W';
74         case MAP__VARIABLE:
75                 return symbol_type == 'D';
76         default:
77                 return false;
78         }
79 }
80
81 static int prefix_underscores_count(const char *str)
82 {
83         const char *tail = str;
84
85         while (*tail == '_')
86                 tail++;
87
88         return tail - str;
89 }
90
91 int __weak arch__choose_best_symbol(struct symbol *syma,
92                                     struct symbol *symb __maybe_unused)
93 {
94         /* Avoid "SyS" kernel syscall aliases */
95         if (strlen(syma->name) >= 3 && !strncmp(syma->name, "SyS", 3))
96                 return SYMBOL_B;
97         if (strlen(syma->name) >= 10 && !strncmp(syma->name, "compat_SyS", 10))
98                 return SYMBOL_B;
99
100         return SYMBOL_A;
101 }
102
103 static int choose_best_symbol(struct symbol *syma, struct symbol *symb)
104 {
105         s64 a;
106         s64 b;
107         size_t na, nb;
108
109         /* Prefer a symbol with non zero length */
110         a = syma->end - syma->start;
111         b = symb->end - symb->start;
112         if ((b == 0) && (a > 0))
113                 return SYMBOL_A;
114         else if ((a == 0) && (b > 0))
115                 return SYMBOL_B;
116
117         /* Prefer a non weak symbol over a weak one */
118         a = syma->binding == STB_WEAK;
119         b = symb->binding == STB_WEAK;
120         if (b && !a)
121                 return SYMBOL_A;
122         if (a && !b)
123                 return SYMBOL_B;
124
125         /* Prefer a global symbol over a non global one */
126         a = syma->binding == STB_GLOBAL;
127         b = symb->binding == STB_GLOBAL;
128         if (a && !b)
129                 return SYMBOL_A;
130         if (b && !a)
131                 return SYMBOL_B;
132
133         /* Prefer a symbol with less underscores */
134         a = prefix_underscores_count(syma->name);
135         b = prefix_underscores_count(symb->name);
136         if (b > a)
137                 return SYMBOL_A;
138         else if (a > b)
139                 return SYMBOL_B;
140
141         /* Choose the symbol with the longest name */
142         na = strlen(syma->name);
143         nb = strlen(symb->name);
144         if (na > nb)
145                 return SYMBOL_A;
146         else if (na < nb)
147                 return SYMBOL_B;
148
149         return arch__choose_best_symbol(syma, symb);
150 }
151
152 void symbols__fixup_duplicate(struct rb_root *symbols)
153 {
154         struct rb_node *nd;
155         struct symbol *curr, *next;
156
157         if (symbol_conf.allow_aliases)
158                 return;
159
160         nd = rb_first(symbols);
161
162         while (nd) {
163                 curr = rb_entry(nd, struct symbol, rb_node);
164 again:
165                 nd = rb_next(&curr->rb_node);
166                 next = rb_entry(nd, struct symbol, rb_node);
167
168                 if (!nd)
169                         break;
170
171                 if (curr->start != next->start)
172                         continue;
173
174                 if (choose_best_symbol(curr, next) == SYMBOL_A) {
175                         rb_erase(&next->rb_node, symbols);
176                         symbol__delete(next);
177                         goto again;
178                 } else {
179                         nd = rb_next(&curr->rb_node);
180                         rb_erase(&curr->rb_node, symbols);
181                         symbol__delete(curr);
182                 }
183         }
184 }
185
186 void symbols__fixup_end(struct rb_root *symbols)
187 {
188         struct rb_node *nd, *prevnd = rb_first(symbols);
189         struct symbol *curr, *prev;
190
191         if (prevnd == NULL)
192                 return;
193
194         curr = rb_entry(prevnd, struct symbol, rb_node);
195
196         for (nd = rb_next(prevnd); nd; nd = rb_next(nd)) {
197                 prev = curr;
198                 curr = rb_entry(nd, struct symbol, rb_node);
199
200                 if (prev->end == prev->start && prev->end != curr->start)
201                         prev->end = curr->start;
202         }
203
204         /* Last entry */
205         if (curr->end == curr->start)
206                 curr->end = roundup(curr->start, 4096) + 4096;
207 }
208
209 void __map_groups__fixup_end(struct map_groups *mg, enum map_type type)
210 {
211         struct maps *maps = &mg->maps[type];
212         struct map *next, *curr;
213
214         pthread_rwlock_wrlock(&maps->lock);
215
216         curr = maps__first(maps);
217         if (curr == NULL)
218                 goto out_unlock;
219
220         for (next = map__next(curr); next; next = map__next(curr)) {
221                 if (!curr->end)
222                         curr->end = next->start;
223                 curr = next;
224         }
225
226         /*
227          * We still haven't the actual symbols, so guess the
228          * last map final address.
229          */
230         if (!curr->end)
231                 curr->end = ~0ULL;
232
233 out_unlock:
234         pthread_rwlock_unlock(&maps->lock);
235 }
236
237 struct symbol *symbol__new(u64 start, u64 len, u8 binding, const char *name)
238 {
239         size_t namelen = strlen(name) + 1;
240         struct symbol *sym = calloc(1, (symbol_conf.priv_size +
241                                         sizeof(*sym) + namelen));
242         if (sym == NULL)
243                 return NULL;
244
245         if (symbol_conf.priv_size) {
246                 if (symbol_conf.init_annotation) {
247                         struct annotation *notes = (void *)sym;
248                         pthread_mutex_init(&notes->lock, NULL);
249                 }
250                 sym = ((void *)sym) + symbol_conf.priv_size;
251         }
252
253         sym->start   = start;
254         sym->end     = len ? start + len : start;
255         sym->binding = binding;
256         sym->namelen = namelen - 1;
257
258         pr_debug4("%s: %s %#" PRIx64 "-%#" PRIx64 "\n",
259                   __func__, name, start, sym->end);
260         memcpy(sym->name, name, namelen);
261
262         return sym;
263 }
264
265 void symbol__delete(struct symbol *sym)
266 {
267         free(((void *)sym) - symbol_conf.priv_size);
268 }
269
270 void symbols__delete(struct rb_root *symbols)
271 {
272         struct symbol *pos;
273         struct rb_node *next = rb_first(symbols);
274
275         while (next) {
276                 pos = rb_entry(next, struct symbol, rb_node);
277                 next = rb_next(&pos->rb_node);
278                 rb_erase(&pos->rb_node, symbols);
279                 symbol__delete(pos);
280         }
281 }
282
283 void __symbols__insert(struct rb_root *symbols, struct symbol *sym, bool kernel)
284 {
285         struct rb_node **p = &symbols->rb_node;
286         struct rb_node *parent = NULL;
287         const u64 ip = sym->start;
288         struct symbol *s;
289
290         if (kernel) {
291                 const char *name = sym->name;
292                 /*
293                  * ppc64 uses function descriptors and appends a '.' to the
294                  * start of every instruction address. Remove it.
295                  */
296                 if (name[0] == '.')
297                         name++;
298                 sym->idle = symbol__is_idle(name);
299         }
300
301         while (*p != NULL) {
302                 parent = *p;
303                 s = rb_entry(parent, struct symbol, rb_node);
304                 if (ip < s->start)
305                         p = &(*p)->rb_left;
306                 else
307                         p = &(*p)->rb_right;
308         }
309         rb_link_node(&sym->rb_node, parent, p);
310         rb_insert_color(&sym->rb_node, symbols);
311 }
312
313 void symbols__insert(struct rb_root *symbols, struct symbol *sym)
314 {
315         __symbols__insert(symbols, sym, false);
316 }
317
318 static struct symbol *symbols__find(struct rb_root *symbols, u64 ip)
319 {
320         struct rb_node *n;
321
322         if (symbols == NULL)
323                 return NULL;
324
325         n = symbols->rb_node;
326
327         while (n) {
328                 struct symbol *s = rb_entry(n, struct symbol, rb_node);
329
330                 if (ip < s->start)
331                         n = n->rb_left;
332                 else if (ip > s->end || (ip == s->end && ip != s->start))
333                         n = n->rb_right;
334                 else
335                         return s;
336         }
337
338         return NULL;
339 }
340
341 static struct symbol *symbols__first(struct rb_root *symbols)
342 {
343         struct rb_node *n = rb_first(symbols);
344
345         if (n)
346                 return rb_entry(n, struct symbol, rb_node);
347
348         return NULL;
349 }
350
351 static struct symbol *symbols__last(struct rb_root *symbols)
352 {
353         struct rb_node *n = rb_last(symbols);
354
355         if (n)
356                 return rb_entry(n, struct symbol, rb_node);
357
358         return NULL;
359 }
360
361 static struct symbol *symbols__next(struct symbol *sym)
362 {
363         struct rb_node *n = rb_next(&sym->rb_node);
364
365         if (n)
366                 return rb_entry(n, struct symbol, rb_node);
367
368         return NULL;
369 }
370
371 static void symbols__insert_by_name(struct rb_root *symbols, struct symbol *sym)
372 {
373         struct rb_node **p = &symbols->rb_node;
374         struct rb_node *parent = NULL;
375         struct symbol_name_rb_node *symn, *s;
376
377         symn = container_of(sym, struct symbol_name_rb_node, sym);
378
379         while (*p != NULL) {
380                 parent = *p;
381                 s = rb_entry(parent, struct symbol_name_rb_node, rb_node);
382                 if (strcmp(sym->name, s->sym.name) < 0)
383                         p = &(*p)->rb_left;
384                 else
385                         p = &(*p)->rb_right;
386         }
387         rb_link_node(&symn->rb_node, parent, p);
388         rb_insert_color(&symn->rb_node, symbols);
389 }
390
391 static void symbols__sort_by_name(struct rb_root *symbols,
392                                   struct rb_root *source)
393 {
394         struct rb_node *nd;
395
396         for (nd = rb_first(source); nd; nd = rb_next(nd)) {
397                 struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
398                 symbols__insert_by_name(symbols, pos);
399         }
400 }
401
402 static struct symbol *symbols__find_by_name(struct rb_root *symbols,
403                                             const char *name)
404 {
405         struct rb_node *n;
406         struct symbol_name_rb_node *s = NULL;
407
408         if (symbols == NULL)
409                 return NULL;
410
411         n = symbols->rb_node;
412
413         while (n) {
414                 int cmp;
415
416                 s = rb_entry(n, struct symbol_name_rb_node, rb_node);
417                 cmp = arch__compare_symbol_names(name, s->sym.name);
418
419                 if (cmp < 0)
420                         n = n->rb_left;
421                 else if (cmp > 0)
422                         n = n->rb_right;
423                 else
424                         break;
425         }
426
427         if (n == NULL)
428                 return NULL;
429
430         /* return first symbol that has same name (if any) */
431         for (n = rb_prev(n); n; n = rb_prev(n)) {
432                 struct symbol_name_rb_node *tmp;
433
434                 tmp = rb_entry(n, struct symbol_name_rb_node, rb_node);
435                 if (arch__compare_symbol_names(tmp->sym.name, s->sym.name))
436                         break;
437
438                 s = tmp;
439         }
440
441         return &s->sym;
442 }
443
444 void dso__reset_find_symbol_cache(struct dso *dso)
445 {
446         enum map_type type;
447
448         for (type = MAP__FUNCTION; type <= MAP__VARIABLE; ++type) {
449                 dso->last_find_result[type].addr   = 0;
450                 dso->last_find_result[type].symbol = NULL;
451         }
452 }
453
454 void dso__insert_symbol(struct dso *dso, enum map_type type, struct symbol *sym)
455 {
456         __symbols__insert(&dso->symbols[type], sym, dso->kernel);
457
458         /* update the symbol cache if necessary */
459         if (dso->last_find_result[type].addr >= sym->start &&
460             (dso->last_find_result[type].addr < sym->end ||
461             sym->start == sym->end)) {
462                 dso->last_find_result[type].symbol = sym;
463         }
464 }
465
466 struct symbol *dso__find_symbol(struct dso *dso,
467                                 enum map_type type, u64 addr)
468 {
469         if (dso->last_find_result[type].addr != addr) {
470                 dso->last_find_result[type].addr   = addr;
471                 dso->last_find_result[type].symbol = symbols__find(&dso->symbols[type], addr);
472         }
473
474         return dso->last_find_result[type].symbol;
475 }
476
477 struct symbol *dso__first_symbol(struct dso *dso, enum map_type type)
478 {
479         return symbols__first(&dso->symbols[type]);
480 }
481
482 struct symbol *dso__last_symbol(struct dso *dso, enum map_type type)
483 {
484         return symbols__last(&dso->symbols[type]);
485 }
486
487 struct symbol *dso__next_symbol(struct symbol *sym)
488 {
489         return symbols__next(sym);
490 }
491
492 struct symbol *symbol__next_by_name(struct symbol *sym)
493 {
494         struct symbol_name_rb_node *s = container_of(sym, struct symbol_name_rb_node, sym);
495         struct rb_node *n = rb_next(&s->rb_node);
496
497         return n ? &rb_entry(n, struct symbol_name_rb_node, rb_node)->sym : NULL;
498 }
499
500  /*
501   * Teturns first symbol that matched with @name.
502   */
503 struct symbol *dso__find_symbol_by_name(struct dso *dso, enum map_type type,
504                                         const char *name)
505 {
506         return symbols__find_by_name(&dso->symbol_names[type], name);
507 }
508
509 void dso__sort_by_name(struct dso *dso, enum map_type type)
510 {
511         dso__set_sorted_by_name(dso, type);
512         return symbols__sort_by_name(&dso->symbol_names[type],
513                                      &dso->symbols[type]);
514 }
515
516 int modules__parse(const char *filename, void *arg,
517                    int (*process_module)(void *arg, const char *name,
518                                          u64 start, u64 size))
519 {
520         char *line = NULL;
521         size_t n;
522         FILE *file;
523         int err = 0;
524
525         file = fopen(filename, "r");
526         if (file == NULL)
527                 return -1;
528
529         while (1) {
530                 char name[PATH_MAX];
531                 u64 start, size;
532                 char *sep, *endptr;
533                 ssize_t line_len;
534
535                 line_len = getline(&line, &n, file);
536                 if (line_len < 0) {
537                         if (feof(file))
538                                 break;
539                         err = -1;
540                         goto out;
541                 }
542
543                 if (!line) {
544                         err = -1;
545                         goto out;
546                 }
547
548                 line[--line_len] = '\0'; /* \n */
549
550                 sep = strrchr(line, 'x');
551                 if (sep == NULL)
552                         continue;
553
554                 hex2u64(sep + 1, &start);
555
556                 sep = strchr(line, ' ');
557                 if (sep == NULL)
558                         continue;
559
560                 *sep = '\0';
561
562                 scnprintf(name, sizeof(name), "[%s]", line);
563
564                 size = strtoul(sep + 1, &endptr, 0);
565                 if (*endptr != ' ' && *endptr != '\t')
566                         continue;
567
568                 err = process_module(arg, name, start, size);
569                 if (err)
570                         break;
571         }
572 out:
573         free(line);
574         fclose(file);
575         return err;
576 }
577
578 struct process_kallsyms_args {
579         struct map *map;
580         struct dso *dso;
581 };
582
583 /*
584  * These are symbols in the kernel image, so make sure that
585  * sym is from a kernel DSO.
586  */
587 static bool symbol__is_idle(const char *name)
588 {
589         const char * const idle_symbols[] = {
590                 "cpu_idle",
591                 "cpu_startup_entry",
592                 "intel_idle",
593                 "default_idle",
594                 "native_safe_halt",
595                 "enter_idle",
596                 "exit_idle",
597                 "mwait_idle",
598                 "mwait_idle_with_hints",
599                 "poll_idle",
600                 "ppc64_runlatch_off",
601                 "pseries_dedicated_idle_sleep",
602                 NULL
603         };
604         int i;
605
606         for (i = 0; idle_symbols[i]; i++) {
607                 if (!strcmp(idle_symbols[i], name))
608                         return true;
609         }
610
611         return false;
612 }
613
614 static int map__process_kallsym_symbol(void *arg, const char *name,
615                                        char type, u64 start)
616 {
617         struct symbol *sym;
618         struct process_kallsyms_args *a = arg;
619         struct rb_root *root = &a->dso->symbols[a->map->type];
620
621         if (!symbol_type__is_a(type, a->map->type))
622                 return 0;
623
624         /*
625          * module symbols are not sorted so we add all
626          * symbols, setting length to 0, and rely on
627          * symbols__fixup_end() to fix it up.
628          */
629         sym = symbol__new(start, 0, kallsyms2elf_binding(type), name);
630         if (sym == NULL)
631                 return -ENOMEM;
632         /*
633          * We will pass the symbols to the filter later, in
634          * map__split_kallsyms, when we have split the maps per module
635          */
636         __symbols__insert(root, sym, !strchr(name, '['));
637
638         return 0;
639 }
640
641 /*
642  * Loads the function entries in /proc/kallsyms into kernel_map->dso,
643  * so that we can in the next step set the symbol ->end address and then
644  * call kernel_maps__split_kallsyms.
645  */
646 static int dso__load_all_kallsyms(struct dso *dso, const char *filename,
647                                   struct map *map)
648 {
649         struct process_kallsyms_args args = { .map = map, .dso = dso, };
650         return kallsyms__parse(filename, &args, map__process_kallsym_symbol);
651 }
652
653 static int dso__split_kallsyms_for_kcore(struct dso *dso, struct map *map)
654 {
655         struct map_groups *kmaps = map__kmaps(map);
656         struct map *curr_map;
657         struct symbol *pos;
658         int count = 0;
659         struct rb_root old_root = dso->symbols[map->type];
660         struct rb_root *root = &dso->symbols[map->type];
661         struct rb_node *next = rb_first(root);
662
663         if (!kmaps)
664                 return -1;
665
666         *root = RB_ROOT;
667
668         while (next) {
669                 char *module;
670
671                 pos = rb_entry(next, struct symbol, rb_node);
672                 next = rb_next(&pos->rb_node);
673
674                 rb_erase_init(&pos->rb_node, &old_root);
675
676                 module = strchr(pos->name, '\t');
677                 if (module)
678                         *module = '\0';
679
680                 curr_map = map_groups__find(kmaps, map->type, pos->start);
681
682                 if (!curr_map) {
683                         symbol__delete(pos);
684                         continue;
685                 }
686
687                 pos->start -= curr_map->start - curr_map->pgoff;
688                 if (pos->end)
689                         pos->end -= curr_map->start - curr_map->pgoff;
690                 symbols__insert(&curr_map->dso->symbols[curr_map->type], pos);
691                 ++count;
692         }
693
694         /* Symbols have been adjusted */
695         dso->adjust_symbols = 1;
696
697         return count;
698 }
699
700 /*
701  * Split the symbols into maps, making sure there are no overlaps, i.e. the
702  * kernel range is broken in several maps, named [kernel].N, as we don't have
703  * the original ELF section names vmlinux have.
704  */
705 static int dso__split_kallsyms(struct dso *dso, struct map *map, u64 delta)
706 {
707         struct map_groups *kmaps = map__kmaps(map);
708         struct machine *machine;
709         struct map *curr_map = map;
710         struct symbol *pos;
711         int count = 0, moved = 0;
712         struct rb_root *root = &dso->symbols[map->type];
713         struct rb_node *next = rb_first(root);
714         int kernel_range = 0;
715
716         if (!kmaps)
717                 return -1;
718
719         machine = kmaps->machine;
720
721         while (next) {
722                 char *module;
723
724                 pos = rb_entry(next, struct symbol, rb_node);
725                 next = rb_next(&pos->rb_node);
726
727                 module = strchr(pos->name, '\t');
728                 if (module) {
729                         if (!symbol_conf.use_modules)
730                                 goto discard_symbol;
731
732                         *module++ = '\0';
733
734                         if (strcmp(curr_map->dso->short_name, module)) {
735                                 if (curr_map != map &&
736                                     dso->kernel == DSO_TYPE_GUEST_KERNEL &&
737                                     machine__is_default_guest(machine)) {
738                                         /*
739                                          * We assume all symbols of a module are
740                                          * continuous in * kallsyms, so curr_map
741                                          * points to a module and all its
742                                          * symbols are in its kmap. Mark it as
743                                          * loaded.
744                                          */
745                                         dso__set_loaded(curr_map->dso,
746                                                         curr_map->type);
747                                 }
748
749                                 curr_map = map_groups__find_by_name(kmaps,
750                                                         map->type, module);
751                                 if (curr_map == NULL) {
752                                         pr_debug("%s/proc/{kallsyms,modules} "
753                                                  "inconsistency while looking "
754                                                  "for \"%s\" module!\n",
755                                                  machine->root_dir, module);
756                                         curr_map = map;
757                                         goto discard_symbol;
758                                 }
759
760                                 if (curr_map->dso->loaded &&
761                                     !machine__is_default_guest(machine))
762                                         goto discard_symbol;
763                         }
764                         /*
765                          * So that we look just like we get from .ko files,
766                          * i.e. not prelinked, relative to map->start.
767                          */
768                         pos->start = curr_map->map_ip(curr_map, pos->start);
769                         pos->end   = curr_map->map_ip(curr_map, pos->end);
770                 } else if (curr_map != map) {
771                         char dso_name[PATH_MAX];
772                         struct dso *ndso;
773
774                         if (delta) {
775                                 /* Kernel was relocated at boot time */
776                                 pos->start -= delta;
777                                 pos->end -= delta;
778                         }
779
780                         if (count == 0) {
781                                 curr_map = map;
782                                 goto add_symbol;
783                         }
784
785                         if (dso->kernel == DSO_TYPE_GUEST_KERNEL)
786                                 snprintf(dso_name, sizeof(dso_name),
787                                         "[guest.kernel].%d",
788                                         kernel_range++);
789                         else
790                                 snprintf(dso_name, sizeof(dso_name),
791                                         "[kernel].%d",
792                                         kernel_range++);
793
794                         ndso = dso__new(dso_name);
795                         if (ndso == NULL)
796                                 return -1;
797
798                         ndso->kernel = dso->kernel;
799
800                         curr_map = map__new2(pos->start, ndso, map->type);
801                         if (curr_map == NULL) {
802                                 dso__put(ndso);
803                                 return -1;
804                         }
805
806                         curr_map->map_ip = curr_map->unmap_ip = identity__map_ip;
807                         map_groups__insert(kmaps, curr_map);
808                         ++kernel_range;
809                 } else if (delta) {
810                         /* Kernel was relocated at boot time */
811                         pos->start -= delta;
812                         pos->end -= delta;
813                 }
814 add_symbol:
815                 if (curr_map != map) {
816                         rb_erase(&pos->rb_node, root);
817                         symbols__insert(&curr_map->dso->symbols[curr_map->type], pos);
818                         ++moved;
819                 } else
820                         ++count;
821
822                 continue;
823 discard_symbol:
824                 rb_erase(&pos->rb_node, root);
825                 symbol__delete(pos);
826         }
827
828         if (curr_map != map &&
829             dso->kernel == DSO_TYPE_GUEST_KERNEL &&
830             machine__is_default_guest(kmaps->machine)) {
831                 dso__set_loaded(curr_map->dso, curr_map->type);
832         }
833
834         return count + moved;
835 }
836
837 bool symbol__restricted_filename(const char *filename,
838                                  const char *restricted_filename)
839 {
840         bool restricted = false;
841
842         if (symbol_conf.kptr_restrict) {
843                 char *r = realpath(filename, NULL);
844
845                 if (r != NULL) {
846                         restricted = strcmp(r, restricted_filename) == 0;
847                         free(r);
848                         return restricted;
849                 }
850         }
851
852         return restricted;
853 }
854
855 struct module_info {
856         struct rb_node rb_node;
857         char *name;
858         u64 start;
859 };
860
861 static void add_module(struct module_info *mi, struct rb_root *modules)
862 {
863         struct rb_node **p = &modules->rb_node;
864         struct rb_node *parent = NULL;
865         struct module_info *m;
866
867         while (*p != NULL) {
868                 parent = *p;
869                 m = rb_entry(parent, struct module_info, rb_node);
870                 if (strcmp(mi->name, m->name) < 0)
871                         p = &(*p)->rb_left;
872                 else
873                         p = &(*p)->rb_right;
874         }
875         rb_link_node(&mi->rb_node, parent, p);
876         rb_insert_color(&mi->rb_node, modules);
877 }
878
879 static void delete_modules(struct rb_root *modules)
880 {
881         struct module_info *mi;
882         struct rb_node *next = rb_first(modules);
883
884         while (next) {
885                 mi = rb_entry(next, struct module_info, rb_node);
886                 next = rb_next(&mi->rb_node);
887                 rb_erase(&mi->rb_node, modules);
888                 zfree(&mi->name);
889                 free(mi);
890         }
891 }
892
893 static struct module_info *find_module(const char *name,
894                                        struct rb_root *modules)
895 {
896         struct rb_node *n = modules->rb_node;
897
898         while (n) {
899                 struct module_info *m;
900                 int cmp;
901
902                 m = rb_entry(n, struct module_info, rb_node);
903                 cmp = strcmp(name, m->name);
904                 if (cmp < 0)
905                         n = n->rb_left;
906                 else if (cmp > 0)
907                         n = n->rb_right;
908                 else
909                         return m;
910         }
911
912         return NULL;
913 }
914
915 static int __read_proc_modules(void *arg, const char *name, u64 start,
916                                u64 size __maybe_unused)
917 {
918         struct rb_root *modules = arg;
919         struct module_info *mi;
920
921         mi = zalloc(sizeof(struct module_info));
922         if (!mi)
923                 return -ENOMEM;
924
925         mi->name = strdup(name);
926         mi->start = start;
927
928         if (!mi->name) {
929                 free(mi);
930                 return -ENOMEM;
931         }
932
933         add_module(mi, modules);
934
935         return 0;
936 }
937
938 static int read_proc_modules(const char *filename, struct rb_root *modules)
939 {
940         if (symbol__restricted_filename(filename, "/proc/modules"))
941                 return -1;
942
943         if (modules__parse(filename, modules, __read_proc_modules)) {
944                 delete_modules(modules);
945                 return -1;
946         }
947
948         return 0;
949 }
950
951 int compare_proc_modules(const char *from, const char *to)
952 {
953         struct rb_root from_modules = RB_ROOT;
954         struct rb_root to_modules = RB_ROOT;
955         struct rb_node *from_node, *to_node;
956         struct module_info *from_m, *to_m;
957         int ret = -1;
958
959         if (read_proc_modules(from, &from_modules))
960                 return -1;
961
962         if (read_proc_modules(to, &to_modules))
963                 goto out_delete_from;
964
965         from_node = rb_first(&from_modules);
966         to_node = rb_first(&to_modules);
967         while (from_node) {
968                 if (!to_node)
969                         break;
970
971                 from_m = rb_entry(from_node, struct module_info, rb_node);
972                 to_m = rb_entry(to_node, struct module_info, rb_node);
973
974                 if (from_m->start != to_m->start ||
975                     strcmp(from_m->name, to_m->name))
976                         break;
977
978                 from_node = rb_next(from_node);
979                 to_node = rb_next(to_node);
980         }
981
982         if (!from_node && !to_node)
983                 ret = 0;
984
985         delete_modules(&to_modules);
986 out_delete_from:
987         delete_modules(&from_modules);
988
989         return ret;
990 }
991
992 static int do_validate_kcore_modules(const char *filename, struct map *map,
993                                   struct map_groups *kmaps)
994 {
995         struct rb_root modules = RB_ROOT;
996         struct map *old_map;
997         int err;
998
999         err = read_proc_modules(filename, &modules);
1000         if (err)
1001                 return err;
1002
1003         old_map = map_groups__first(kmaps, map->type);
1004         while (old_map) {
1005                 struct map *next = map_groups__next(old_map);
1006                 struct module_info *mi;
1007
1008                 if (old_map == map || old_map->start == map->start) {
1009                         /* The kernel map */
1010                         old_map = next;
1011                         continue;
1012                 }
1013
1014                 /* Module must be in memory at the same address */
1015                 mi = find_module(old_map->dso->short_name, &modules);
1016                 if (!mi || mi->start != old_map->start) {
1017                         err = -EINVAL;
1018                         goto out;
1019                 }
1020
1021                 old_map = next;
1022         }
1023 out:
1024         delete_modules(&modules);
1025         return err;
1026 }
1027
1028 /*
1029  * If kallsyms is referenced by name then we look for filename in the same
1030  * directory.
1031  */
1032 static bool filename_from_kallsyms_filename(char *filename,
1033                                             const char *base_name,
1034                                             const char *kallsyms_filename)
1035 {
1036         char *name;
1037
1038         strcpy(filename, kallsyms_filename);
1039         name = strrchr(filename, '/');
1040         if (!name)
1041                 return false;
1042
1043         name += 1;
1044
1045         if (!strcmp(name, "kallsyms")) {
1046                 strcpy(name, base_name);
1047                 return true;
1048         }
1049
1050         return false;
1051 }
1052
1053 static int validate_kcore_modules(const char *kallsyms_filename,
1054                                   struct map *map)
1055 {
1056         struct map_groups *kmaps = map__kmaps(map);
1057         char modules_filename[PATH_MAX];
1058
1059         if (!kmaps)
1060                 return -EINVAL;
1061
1062         if (!filename_from_kallsyms_filename(modules_filename, "modules",
1063                                              kallsyms_filename))
1064                 return -EINVAL;
1065
1066         if (do_validate_kcore_modules(modules_filename, map, kmaps))
1067                 return -EINVAL;
1068
1069         return 0;
1070 }
1071
1072 static int validate_kcore_addresses(const char *kallsyms_filename,
1073                                     struct map *map)
1074 {
1075         struct kmap *kmap = map__kmap(map);
1076
1077         if (!kmap)
1078                 return -EINVAL;
1079
1080         if (kmap->ref_reloc_sym && kmap->ref_reloc_sym->name) {
1081                 u64 start;
1082
1083                 start = kallsyms__get_function_start(kallsyms_filename,
1084                                                      kmap->ref_reloc_sym->name);
1085                 if (start != kmap->ref_reloc_sym->addr)
1086                         return -EINVAL;
1087         }
1088
1089         return validate_kcore_modules(kallsyms_filename, map);
1090 }
1091
1092 struct kcore_mapfn_data {
1093         struct dso *dso;
1094         enum map_type type;
1095         struct list_head maps;
1096 };
1097
1098 static int kcore_mapfn(u64 start, u64 len, u64 pgoff, void *data)
1099 {
1100         struct kcore_mapfn_data *md = data;
1101         struct map *map;
1102
1103         map = map__new2(start, md->dso, md->type);
1104         if (map == NULL)
1105                 return -ENOMEM;
1106
1107         map->end = map->start + len;
1108         map->pgoff = pgoff;
1109
1110         list_add(&map->node, &md->maps);
1111
1112         return 0;
1113 }
1114
1115 static int dso__load_kcore(struct dso *dso, struct map *map,
1116                            const char *kallsyms_filename)
1117 {
1118         struct map_groups *kmaps = map__kmaps(map);
1119         struct machine *machine;
1120         struct kcore_mapfn_data md;
1121         struct map *old_map, *new_map, *replacement_map = NULL;
1122         bool is_64_bit;
1123         int err, fd;
1124         char kcore_filename[PATH_MAX];
1125         struct symbol *sym;
1126
1127         if (!kmaps)
1128                 return -EINVAL;
1129
1130         machine = kmaps->machine;
1131
1132         /* This function requires that the map is the kernel map */
1133         if (map != machine->vmlinux_maps[map->type])
1134                 return -EINVAL;
1135
1136         if (!filename_from_kallsyms_filename(kcore_filename, "kcore",
1137                                              kallsyms_filename))
1138                 return -EINVAL;
1139
1140         /* Modules and kernel must be present at their original addresses */
1141         if (validate_kcore_addresses(kallsyms_filename, map))
1142                 return -EINVAL;
1143
1144         md.dso = dso;
1145         md.type = map->type;
1146         INIT_LIST_HEAD(&md.maps);
1147
1148         fd = open(kcore_filename, O_RDONLY);
1149         if (fd < 0) {
1150                 pr_debug("Failed to open %s. Note /proc/kcore requires CAP_SYS_RAWIO capability to access.\n",
1151                          kcore_filename);
1152                 return -EINVAL;
1153         }
1154
1155         /* Read new maps into temporary lists */
1156         err = file__read_maps(fd, md.type == MAP__FUNCTION, kcore_mapfn, &md,
1157                               &is_64_bit);
1158         if (err)
1159                 goto out_err;
1160         dso->is_64_bit = is_64_bit;
1161
1162         if (list_empty(&md.maps)) {
1163                 err = -EINVAL;
1164                 goto out_err;
1165         }
1166
1167         /* Remove old maps */
1168         old_map = map_groups__first(kmaps, map->type);
1169         while (old_map) {
1170                 struct map *next = map_groups__next(old_map);
1171
1172                 if (old_map != map)
1173                         map_groups__remove(kmaps, old_map);
1174                 old_map = next;
1175         }
1176
1177         /* Find the kernel map using the first symbol */
1178         sym = dso__first_symbol(dso, map->type);
1179         list_for_each_entry(new_map, &md.maps, node) {
1180                 if (sym && sym->start >= new_map->start &&
1181                     sym->start < new_map->end) {
1182                         replacement_map = new_map;
1183                         break;
1184                 }
1185         }
1186
1187         if (!replacement_map)
1188                 replacement_map = list_entry(md.maps.next, struct map, node);
1189
1190         /* Add new maps */
1191         while (!list_empty(&md.maps)) {
1192                 new_map = list_entry(md.maps.next, struct map, node);
1193                 list_del_init(&new_map->node);
1194                 if (new_map == replacement_map) {
1195                         map->start      = new_map->start;
1196                         map->end        = new_map->end;
1197                         map->pgoff      = new_map->pgoff;
1198                         map->map_ip     = new_map->map_ip;
1199                         map->unmap_ip   = new_map->unmap_ip;
1200                         /* Ensure maps are correctly ordered */
1201                         map__get(map);
1202                         map_groups__remove(kmaps, map);
1203                         map_groups__insert(kmaps, map);
1204                         map__put(map);
1205                 } else {
1206                         map_groups__insert(kmaps, new_map);
1207                 }
1208
1209                 map__put(new_map);
1210         }
1211
1212         /*
1213          * Set the data type and long name so that kcore can be read via
1214          * dso__data_read_addr().
1215          */
1216         if (dso->kernel == DSO_TYPE_GUEST_KERNEL)
1217                 dso->binary_type = DSO_BINARY_TYPE__GUEST_KCORE;
1218         else
1219                 dso->binary_type = DSO_BINARY_TYPE__KCORE;
1220         dso__set_long_name(dso, strdup(kcore_filename), true);
1221
1222         close(fd);
1223
1224         if (map->type == MAP__FUNCTION)
1225                 pr_debug("Using %s for kernel object code\n", kcore_filename);
1226         else
1227                 pr_debug("Using %s for kernel data\n", kcore_filename);
1228
1229         return 0;
1230
1231 out_err:
1232         while (!list_empty(&md.maps)) {
1233                 map = list_entry(md.maps.next, struct map, node);
1234                 list_del_init(&map->node);
1235                 map__put(map);
1236         }
1237         close(fd);
1238         return -EINVAL;
1239 }
1240
1241 /*
1242  * If the kernel is relocated at boot time, kallsyms won't match.  Compute the
1243  * delta based on the relocation reference symbol.
1244  */
1245 static int kallsyms__delta(struct map *map, const char *filename, u64 *delta)
1246 {
1247         struct kmap *kmap = map__kmap(map);
1248         u64 addr;
1249
1250         if (!kmap)
1251                 return -1;
1252
1253         if (!kmap->ref_reloc_sym || !kmap->ref_reloc_sym->name)
1254                 return 0;
1255
1256         addr = kallsyms__get_function_start(filename,
1257                                             kmap->ref_reloc_sym->name);
1258         if (!addr)
1259                 return -1;
1260
1261         *delta = addr - kmap->ref_reloc_sym->addr;
1262         return 0;
1263 }
1264
1265 int __dso__load_kallsyms(struct dso *dso, const char *filename,
1266                          struct map *map, bool no_kcore)
1267 {
1268         u64 delta = 0;
1269
1270         if (symbol__restricted_filename(filename, "/proc/kallsyms"))
1271                 return -1;
1272
1273         if (dso__load_all_kallsyms(dso, filename, map) < 0)
1274                 return -1;
1275
1276         if (kallsyms__delta(map, filename, &delta))
1277                 return -1;
1278
1279         symbols__fixup_end(&dso->symbols[map->type]);
1280         symbols__fixup_duplicate(&dso->symbols[map->type]);
1281
1282         if (dso->kernel == DSO_TYPE_GUEST_KERNEL)
1283                 dso->symtab_type = DSO_BINARY_TYPE__GUEST_KALLSYMS;
1284         else
1285                 dso->symtab_type = DSO_BINARY_TYPE__KALLSYMS;
1286
1287         if (!no_kcore && !dso__load_kcore(dso, map, filename))
1288                 return dso__split_kallsyms_for_kcore(dso, map);
1289         else
1290                 return dso__split_kallsyms(dso, map, delta);
1291 }
1292
1293 int dso__load_kallsyms(struct dso *dso, const char *filename,
1294                        struct map *map)
1295 {
1296         return __dso__load_kallsyms(dso, filename, map, false);
1297 }
1298
1299 static int dso__load_perf_map(struct dso *dso, struct map *map)
1300 {
1301         char *line = NULL;
1302         size_t n;
1303         FILE *file;
1304         int nr_syms = 0;
1305
1306         file = fopen(dso->long_name, "r");
1307         if (file == NULL)
1308                 goto out_failure;
1309
1310         while (!feof(file)) {
1311                 u64 start, size;
1312                 struct symbol *sym;
1313                 int line_len, len;
1314
1315                 line_len = getline(&line, &n, file);
1316                 if (line_len < 0)
1317                         break;
1318
1319                 if (!line)
1320                         goto out_failure;
1321
1322                 line[--line_len] = '\0'; /* \n */
1323
1324                 len = hex2u64(line, &start);
1325
1326                 len++;
1327                 if (len + 2 >= line_len)
1328                         continue;
1329
1330                 len += hex2u64(line + len, &size);
1331
1332                 len++;
1333                 if (len + 2 >= line_len)
1334                         continue;
1335
1336                 sym = symbol__new(start, size, STB_GLOBAL, line + len);
1337
1338                 if (sym == NULL)
1339                         goto out_delete_line;
1340
1341                 symbols__insert(&dso->symbols[map->type], sym);
1342                 nr_syms++;
1343         }
1344
1345         free(line);
1346         fclose(file);
1347
1348         return nr_syms;
1349
1350 out_delete_line:
1351         free(line);
1352 out_failure:
1353         return -1;
1354 }
1355
1356 static bool dso__is_compatible_symtab_type(struct dso *dso, bool kmod,
1357                                            enum dso_binary_type type)
1358 {
1359         switch (type) {
1360         case DSO_BINARY_TYPE__JAVA_JIT:
1361         case DSO_BINARY_TYPE__DEBUGLINK:
1362         case DSO_BINARY_TYPE__SYSTEM_PATH_DSO:
1363         case DSO_BINARY_TYPE__FEDORA_DEBUGINFO:
1364         case DSO_BINARY_TYPE__UBUNTU_DEBUGINFO:
1365         case DSO_BINARY_TYPE__MIXEDUP_UBUNTU_DEBUGINFO:
1366         case DSO_BINARY_TYPE__BUILDID_DEBUGINFO:
1367         case DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO:
1368                 return !kmod && dso->kernel == DSO_TYPE_USER;
1369
1370         case DSO_BINARY_TYPE__KALLSYMS:
1371         case DSO_BINARY_TYPE__VMLINUX:
1372         case DSO_BINARY_TYPE__KCORE:
1373                 return dso->kernel == DSO_TYPE_KERNEL;
1374
1375         case DSO_BINARY_TYPE__GUEST_KALLSYMS:
1376         case DSO_BINARY_TYPE__GUEST_VMLINUX:
1377         case DSO_BINARY_TYPE__GUEST_KCORE:
1378                 return dso->kernel == DSO_TYPE_GUEST_KERNEL;
1379
1380         case DSO_BINARY_TYPE__GUEST_KMODULE:
1381         case DSO_BINARY_TYPE__GUEST_KMODULE_COMP:
1382         case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE:
1383         case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP:
1384                 /*
1385                  * kernel modules know their symtab type - it's set when
1386                  * creating a module dso in machine__findnew_module_map().
1387                  */
1388                 return kmod && dso->symtab_type == type;
1389
1390         case DSO_BINARY_TYPE__BUILD_ID_CACHE:
1391                 return true;
1392
1393         case DSO_BINARY_TYPE__NOT_FOUND:
1394         default:
1395                 return false;
1396         }
1397 }
1398
1399 int dso__load(struct dso *dso, struct map *map)
1400 {
1401         char *name;
1402         int ret = -1;
1403         u_int i;
1404         struct machine *machine;
1405         char *root_dir = (char *) "";
1406         int ss_pos = 0;
1407         struct symsrc ss_[2];
1408         struct symsrc *syms_ss = NULL, *runtime_ss = NULL;
1409         bool kmod;
1410         unsigned char build_id[BUILD_ID_SIZE];
1411
1412         pthread_mutex_lock(&dso->lock);
1413
1414         /* check again under the dso->lock */
1415         if (dso__loaded(dso, map->type)) {
1416                 ret = 1;
1417                 goto out;
1418         }
1419
1420         if (dso->kernel) {
1421                 if (dso->kernel == DSO_TYPE_KERNEL)
1422                         ret = dso__load_kernel_sym(dso, map);
1423                 else if (dso->kernel == DSO_TYPE_GUEST_KERNEL)
1424                         ret = dso__load_guest_kernel_sym(dso, map);
1425
1426                 goto out;
1427         }
1428
1429         if (map->groups && map->groups->machine)
1430                 machine = map->groups->machine;
1431         else
1432                 machine = NULL;
1433
1434         dso->adjust_symbols = 0;
1435
1436         if (strncmp(dso->name, "/tmp/perf-", 10) == 0) {
1437                 struct stat st;
1438
1439                 if (lstat(dso->name, &st) < 0)
1440                         goto out;
1441
1442                 if (!symbol_conf.force && st.st_uid && (st.st_uid != geteuid())) {
1443                         pr_warning("File %s not owned by current user or root, "
1444                                    "ignoring it (use -f to override).\n", dso->name);
1445                         goto out;
1446                 }
1447
1448                 ret = dso__load_perf_map(dso, map);
1449                 dso->symtab_type = ret > 0 ? DSO_BINARY_TYPE__JAVA_JIT :
1450                                              DSO_BINARY_TYPE__NOT_FOUND;
1451                 goto out;
1452         }
1453
1454         if (machine)
1455                 root_dir = machine->root_dir;
1456
1457         name = malloc(PATH_MAX);
1458         if (!name)
1459                 goto out;
1460
1461         kmod = dso->symtab_type == DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE ||
1462                 dso->symtab_type == DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP ||
1463                 dso->symtab_type == DSO_BINARY_TYPE__GUEST_KMODULE ||
1464                 dso->symtab_type == DSO_BINARY_TYPE__GUEST_KMODULE_COMP;
1465
1466
1467         /*
1468          * Read the build id if possible. This is required for
1469          * DSO_BINARY_TYPE__BUILDID_DEBUGINFO to work
1470          */
1471         if (!dso->has_build_id &&
1472             is_regular_file(dso->long_name) &&
1473             filename__read_build_id(dso->long_name, build_id, BUILD_ID_SIZE) > 0)
1474                 dso__set_build_id(dso, build_id);
1475
1476         /*
1477          * Iterate over candidate debug images.
1478          * Keep track of "interesting" ones (those which have a symtab, dynsym,
1479          * and/or opd section) for processing.
1480          */
1481         for (i = 0; i < DSO_BINARY_TYPE__SYMTAB_CNT; i++) {
1482                 struct symsrc *ss = &ss_[ss_pos];
1483                 bool next_slot = false;
1484
1485                 enum dso_binary_type symtab_type = binary_type_symtab[i];
1486
1487                 if (!dso__is_compatible_symtab_type(dso, kmod, symtab_type))
1488                         continue;
1489
1490                 if (dso__read_binary_type_filename(dso, symtab_type,
1491                                                    root_dir, name, PATH_MAX))
1492                         continue;
1493
1494                 if (!is_regular_file(name))
1495                         continue;
1496
1497                 /* Name is now the name of the next image to try */
1498                 if (symsrc__init(ss, dso, name, symtab_type) < 0)
1499                         continue;
1500
1501                 if (!syms_ss && symsrc__has_symtab(ss)) {
1502                         syms_ss = ss;
1503                         next_slot = true;
1504                         if (!dso->symsrc_filename)
1505                                 dso->symsrc_filename = strdup(name);
1506                 }
1507
1508                 if (!runtime_ss && symsrc__possibly_runtime(ss)) {
1509                         runtime_ss = ss;
1510                         next_slot = true;
1511                 }
1512
1513                 if (next_slot) {
1514                         ss_pos++;
1515
1516                         if (syms_ss && runtime_ss)
1517                                 break;
1518                 } else {
1519                         symsrc__destroy(ss);
1520                 }
1521
1522         }
1523
1524         if (!runtime_ss && !syms_ss)
1525                 goto out_free;
1526
1527         if (runtime_ss && !syms_ss) {
1528                 syms_ss = runtime_ss;
1529         }
1530
1531         /* We'll have to hope for the best */
1532         if (!runtime_ss && syms_ss)
1533                 runtime_ss = syms_ss;
1534
1535         if (syms_ss && syms_ss->type == DSO_BINARY_TYPE__BUILD_ID_CACHE)
1536                 if (dso__build_id_is_kmod(dso, name, PATH_MAX))
1537                         kmod = true;
1538
1539         if (syms_ss)
1540                 ret = dso__load_sym(dso, map, syms_ss, runtime_ss, kmod);
1541         else
1542                 ret = -1;
1543
1544         if (ret > 0) {
1545                 int nr_plt;
1546
1547                 nr_plt = dso__synthesize_plt_symbols(dso, runtime_ss, map);
1548                 if (nr_plt > 0)
1549                         ret += nr_plt;
1550         }
1551
1552         for (; ss_pos > 0; ss_pos--)
1553                 symsrc__destroy(&ss_[ss_pos - 1]);
1554 out_free:
1555         free(name);
1556         if (ret < 0 && strstr(dso->name, " (deleted)") != NULL)
1557                 ret = 0;
1558 out:
1559         dso__set_loaded(dso, map->type);
1560         pthread_mutex_unlock(&dso->lock);
1561
1562         return ret;
1563 }
1564
1565 struct map *map_groups__find_by_name(struct map_groups *mg,
1566                                      enum map_type type, const char *name)
1567 {
1568         struct maps *maps = &mg->maps[type];
1569         struct map *map;
1570
1571         pthread_rwlock_rdlock(&maps->lock);
1572
1573         for (map = maps__first(maps); map; map = map__next(map)) {
1574                 if (map->dso && strcmp(map->dso->short_name, name) == 0)
1575                         goto out_unlock;
1576         }
1577
1578         map = NULL;
1579
1580 out_unlock:
1581         pthread_rwlock_unlock(&maps->lock);
1582         return map;
1583 }
1584
1585 int dso__load_vmlinux(struct dso *dso, struct map *map,
1586                       const char *vmlinux, bool vmlinux_allocated)
1587 {
1588         int err = -1;
1589         struct symsrc ss;
1590         char symfs_vmlinux[PATH_MAX];
1591         enum dso_binary_type symtab_type;
1592
1593         if (vmlinux[0] == '/')
1594                 snprintf(symfs_vmlinux, sizeof(symfs_vmlinux), "%s", vmlinux);
1595         else
1596                 symbol__join_symfs(symfs_vmlinux, vmlinux);
1597
1598         if (dso->kernel == DSO_TYPE_GUEST_KERNEL)
1599                 symtab_type = DSO_BINARY_TYPE__GUEST_VMLINUX;
1600         else
1601                 symtab_type = DSO_BINARY_TYPE__VMLINUX;
1602
1603         if (symsrc__init(&ss, dso, symfs_vmlinux, symtab_type))
1604                 return -1;
1605
1606         err = dso__load_sym(dso, map, &ss, &ss, 0);
1607         symsrc__destroy(&ss);
1608
1609         if (err > 0) {
1610                 if (dso->kernel == DSO_TYPE_GUEST_KERNEL)
1611                         dso->binary_type = DSO_BINARY_TYPE__GUEST_VMLINUX;
1612                 else
1613                         dso->binary_type = DSO_BINARY_TYPE__VMLINUX;
1614                 dso__set_long_name(dso, vmlinux, vmlinux_allocated);
1615                 dso__set_loaded(dso, map->type);
1616                 pr_debug("Using %s for symbols\n", symfs_vmlinux);
1617         }
1618
1619         return err;
1620 }
1621
1622 int dso__load_vmlinux_path(struct dso *dso, struct map *map)
1623 {
1624         int i, err = 0;
1625         char *filename = NULL;
1626
1627         pr_debug("Looking at the vmlinux_path (%d entries long)\n",
1628                  vmlinux_path__nr_entries + 1);
1629
1630         for (i = 0; i < vmlinux_path__nr_entries; ++i) {
1631                 err = dso__load_vmlinux(dso, map, vmlinux_path[i], false);
1632                 if (err > 0)
1633                         goto out;
1634         }
1635
1636         if (!symbol_conf.ignore_vmlinux_buildid)
1637                 filename = dso__build_id_filename(dso, NULL, 0);
1638         if (filename != NULL) {
1639                 err = dso__load_vmlinux(dso, map, filename, true);
1640                 if (err > 0)
1641                         goto out;
1642                 free(filename);
1643         }
1644 out:
1645         return err;
1646 }
1647
1648 static bool visible_dir_filter(const char *name, struct dirent *d)
1649 {
1650         if (d->d_type != DT_DIR)
1651                 return false;
1652         return lsdir_no_dot_filter(name, d);
1653 }
1654
1655 static int find_matching_kcore(struct map *map, char *dir, size_t dir_sz)
1656 {
1657         char kallsyms_filename[PATH_MAX];
1658         int ret = -1;
1659         struct strlist *dirs;
1660         struct str_node *nd;
1661
1662         dirs = lsdir(dir, visible_dir_filter);
1663         if (!dirs)
1664                 return -1;
1665
1666         strlist__for_each_entry(nd, dirs) {
1667                 scnprintf(kallsyms_filename, sizeof(kallsyms_filename),
1668                           "%s/%s/kallsyms", dir, nd->s);
1669                 if (!validate_kcore_addresses(kallsyms_filename, map)) {
1670                         strlcpy(dir, kallsyms_filename, dir_sz);
1671                         ret = 0;
1672                         break;
1673                 }
1674         }
1675
1676         strlist__delete(dirs);
1677
1678         return ret;
1679 }
1680
1681 /*
1682  * Use open(O_RDONLY) to check readability directly instead of access(R_OK)
1683  * since access(R_OK) only checks with real UID/GID but open() use effective
1684  * UID/GID and actual capabilities (e.g. /proc/kcore requires CAP_SYS_RAWIO).
1685  */
1686 static bool filename__readable(const char *file)
1687 {
1688         int fd = open(file, O_RDONLY);
1689         if (fd < 0)
1690                 return false;
1691         close(fd);
1692         return true;
1693 }
1694
1695 static char *dso__find_kallsyms(struct dso *dso, struct map *map)
1696 {
1697         u8 host_build_id[BUILD_ID_SIZE];
1698         char sbuild_id[SBUILD_ID_SIZE];
1699         bool is_host = false;
1700         char path[PATH_MAX];
1701
1702         if (!dso->has_build_id) {
1703                 /*
1704                  * Last resort, if we don't have a build-id and couldn't find
1705                  * any vmlinux file, try the running kernel kallsyms table.
1706                  */
1707                 goto proc_kallsyms;
1708         }
1709
1710         if (sysfs__read_build_id("/sys/kernel/notes", host_build_id,
1711                                  sizeof(host_build_id)) == 0)
1712                 is_host = dso__build_id_equal(dso, host_build_id);
1713
1714         /* Try a fast path for /proc/kallsyms if possible */
1715         if (is_host) {
1716                 /*
1717                  * Do not check the build-id cache, unless we know we cannot use
1718                  * /proc/kcore or module maps don't match to /proc/kallsyms.
1719                  * To check readability of /proc/kcore, do not use access(R_OK)
1720                  * since /proc/kcore requires CAP_SYS_RAWIO to read and access
1721                  * can't check it.
1722                  */
1723                 if (filename__readable("/proc/kcore") &&
1724                     !validate_kcore_addresses("/proc/kallsyms", map))
1725                         goto proc_kallsyms;
1726         }
1727
1728         build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
1729
1730         /* Find kallsyms in build-id cache with kcore */
1731         scnprintf(path, sizeof(path), "%s/%s/%s",
1732                   buildid_dir, DSO__NAME_KCORE, sbuild_id);
1733
1734         if (!find_matching_kcore(map, path, sizeof(path)))
1735                 return strdup(path);
1736
1737         /* Use current /proc/kallsyms if possible */
1738         if (is_host) {
1739 proc_kallsyms:
1740                 return strdup("/proc/kallsyms");
1741         }
1742
1743         /* Finally, find a cache of kallsyms */
1744         if (!build_id_cache__kallsyms_path(sbuild_id, path, sizeof(path))) {
1745                 pr_err("No kallsyms or vmlinux with build-id %s was found\n",
1746                        sbuild_id);
1747                 return NULL;
1748         }
1749
1750         return strdup(path);
1751 }
1752
1753 static int dso__load_kernel_sym(struct dso *dso, struct map *map)
1754 {
1755         int err;
1756         const char *kallsyms_filename = NULL;
1757         char *kallsyms_allocated_filename = NULL;
1758         /*
1759          * Step 1: if the user specified a kallsyms or vmlinux filename, use
1760          * it and only it, reporting errors to the user if it cannot be used.
1761          *
1762          * For instance, try to analyse an ARM perf.data file _without_ a
1763          * build-id, or if the user specifies the wrong path to the right
1764          * vmlinux file, obviously we can't fallback to another vmlinux (a
1765          * x86_86 one, on the machine where analysis is being performed, say),
1766          * or worse, /proc/kallsyms.
1767          *
1768          * If the specified file _has_ a build-id and there is a build-id
1769          * section in the perf.data file, we will still do the expected
1770          * validation in dso__load_vmlinux and will bail out if they don't
1771          * match.
1772          */
1773         if (symbol_conf.kallsyms_name != NULL) {
1774                 kallsyms_filename = symbol_conf.kallsyms_name;
1775                 goto do_kallsyms;
1776         }
1777
1778         if (!symbol_conf.ignore_vmlinux && symbol_conf.vmlinux_name != NULL) {
1779                 return dso__load_vmlinux(dso, map, symbol_conf.vmlinux_name, false);
1780         }
1781
1782         if (!symbol_conf.ignore_vmlinux && vmlinux_path != NULL) {
1783                 err = dso__load_vmlinux_path(dso, map);
1784                 if (err > 0)
1785                         return err;
1786         }
1787
1788         /* do not try local files if a symfs was given */
1789         if (symbol_conf.symfs[0] != 0)
1790                 return -1;
1791
1792         kallsyms_allocated_filename = dso__find_kallsyms(dso, map);
1793         if (!kallsyms_allocated_filename)
1794                 return -1;
1795
1796         kallsyms_filename = kallsyms_allocated_filename;
1797
1798 do_kallsyms:
1799         err = dso__load_kallsyms(dso, kallsyms_filename, map);
1800         if (err > 0)
1801                 pr_debug("Using %s for symbols\n", kallsyms_filename);
1802         free(kallsyms_allocated_filename);
1803
1804         if (err > 0 && !dso__is_kcore(dso)) {
1805                 dso->binary_type = DSO_BINARY_TYPE__KALLSYMS;
1806                 dso__set_long_name(dso, DSO__NAME_KALLSYMS, false);
1807                 map__fixup_start(map);
1808                 map__fixup_end(map);
1809         }
1810
1811         return err;
1812 }
1813
1814 static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map)
1815 {
1816         int err;
1817         const char *kallsyms_filename = NULL;
1818         struct machine *machine;
1819         char path[PATH_MAX];
1820
1821         if (!map->groups) {
1822                 pr_debug("Guest kernel map hasn't the point to groups\n");
1823                 return -1;
1824         }
1825         machine = map->groups->machine;
1826
1827         if (machine__is_default_guest(machine)) {
1828                 /*
1829                  * if the user specified a vmlinux filename, use it and only
1830                  * it, reporting errors to the user if it cannot be used.
1831                  * Or use file guest_kallsyms inputted by user on commandline
1832                  */
1833                 if (symbol_conf.default_guest_vmlinux_name != NULL) {
1834                         err = dso__load_vmlinux(dso, map,
1835                                                 symbol_conf.default_guest_vmlinux_name,
1836                                                 false);
1837                         return err;
1838                 }
1839
1840                 kallsyms_filename = symbol_conf.default_guest_kallsyms;
1841                 if (!kallsyms_filename)
1842                         return -1;
1843         } else {
1844                 sprintf(path, "%s/proc/kallsyms", machine->root_dir);
1845                 kallsyms_filename = path;
1846         }
1847
1848         err = dso__load_kallsyms(dso, kallsyms_filename, map);
1849         if (err > 0)
1850                 pr_debug("Using %s for symbols\n", kallsyms_filename);
1851         if (err > 0 && !dso__is_kcore(dso)) {
1852                 dso->binary_type = DSO_BINARY_TYPE__GUEST_KALLSYMS;
1853                 machine__mmap_name(machine, path, sizeof(path));
1854                 dso__set_long_name(dso, strdup(path), true);
1855                 map__fixup_start(map);
1856                 map__fixup_end(map);
1857         }
1858
1859         return err;
1860 }
1861
1862 static void vmlinux_path__exit(void)
1863 {
1864         while (--vmlinux_path__nr_entries >= 0)
1865                 zfree(&vmlinux_path[vmlinux_path__nr_entries]);
1866         vmlinux_path__nr_entries = 0;
1867
1868         zfree(&vmlinux_path);
1869 }
1870
1871 static const char * const vmlinux_paths[] = {
1872         "vmlinux",
1873         "/boot/vmlinux"
1874 };
1875
1876 static const char * const vmlinux_paths_upd[] = {
1877         "/boot/vmlinux-%s",
1878         "/usr/lib/debug/boot/vmlinux-%s",
1879         "/lib/modules/%s/build/vmlinux",
1880         "/usr/lib/debug/lib/modules/%s/vmlinux",
1881         "/usr/lib/debug/boot/vmlinux-%s.debug"
1882 };
1883
1884 static int vmlinux_path__add(const char *new_entry)
1885 {
1886         vmlinux_path[vmlinux_path__nr_entries] = strdup(new_entry);
1887         if (vmlinux_path[vmlinux_path__nr_entries] == NULL)
1888                 return -1;
1889         ++vmlinux_path__nr_entries;
1890
1891         return 0;
1892 }
1893
1894 static int vmlinux_path__init(struct perf_env *env)
1895 {
1896         struct utsname uts;
1897         char bf[PATH_MAX];
1898         char *kernel_version;
1899         unsigned int i;
1900
1901         vmlinux_path = malloc(sizeof(char *) * (ARRAY_SIZE(vmlinux_paths) +
1902                               ARRAY_SIZE(vmlinux_paths_upd)));
1903         if (vmlinux_path == NULL)
1904                 return -1;
1905
1906         for (i = 0; i < ARRAY_SIZE(vmlinux_paths); i++)
1907                 if (vmlinux_path__add(vmlinux_paths[i]) < 0)
1908                         goto out_fail;
1909
1910         /* only try kernel version if no symfs was given */
1911         if (symbol_conf.symfs[0] != 0)
1912                 return 0;
1913
1914         if (env) {
1915                 kernel_version = env->os_release;
1916         } else {
1917                 if (uname(&uts) < 0)
1918                         goto out_fail;
1919
1920                 kernel_version = uts.release;
1921         }
1922
1923         for (i = 0; i < ARRAY_SIZE(vmlinux_paths_upd); i++) {
1924                 snprintf(bf, sizeof(bf), vmlinux_paths_upd[i], kernel_version);
1925                 if (vmlinux_path__add(bf) < 0)
1926                         goto out_fail;
1927         }
1928
1929         return 0;
1930
1931 out_fail:
1932         vmlinux_path__exit();
1933         return -1;
1934 }
1935
1936 int setup_list(struct strlist **list, const char *list_str,
1937                       const char *list_name)
1938 {
1939         if (list_str == NULL)
1940                 return 0;
1941
1942         *list = strlist__new(list_str, NULL);
1943         if (!*list) {
1944                 pr_err("problems parsing %s list\n", list_name);
1945                 return -1;
1946         }
1947
1948         symbol_conf.has_filter = true;
1949         return 0;
1950 }
1951
1952 int setup_intlist(struct intlist **list, const char *list_str,
1953                   const char *list_name)
1954 {
1955         if (list_str == NULL)
1956                 return 0;
1957
1958         *list = intlist__new(list_str);
1959         if (!*list) {
1960                 pr_err("problems parsing %s list\n", list_name);
1961                 return -1;
1962         }
1963         return 0;
1964 }
1965
1966 static bool symbol__read_kptr_restrict(void)
1967 {
1968         bool value = false;
1969         FILE *fp = fopen("/proc/sys/kernel/kptr_restrict", "r");
1970
1971         if (fp != NULL) {
1972                 char line[8];
1973
1974                 if (fgets(line, sizeof(line), fp) != NULL)
1975                         value = (geteuid() != 0) ?
1976                                         (atoi(line) != 0) :
1977                                         (atoi(line) == 2);
1978
1979                 fclose(fp);
1980         }
1981
1982         return value;
1983 }
1984
1985 int symbol__annotation_init(void)
1986 {
1987         if (symbol_conf.initialized) {
1988                 pr_err("Annotation needs to be init before symbol__init()\n");
1989                 return -1;
1990         }
1991
1992         if (symbol_conf.init_annotation) {
1993                 pr_warning("Annotation being initialized multiple times\n");
1994                 return 0;
1995         }
1996
1997         symbol_conf.priv_size += sizeof(struct annotation);
1998         symbol_conf.init_annotation = true;
1999         return 0;
2000 }
2001
2002 int symbol__init(struct perf_env *env)
2003 {
2004         const char *symfs;
2005
2006         if (symbol_conf.initialized)
2007                 return 0;
2008
2009         symbol_conf.priv_size = PERF_ALIGN(symbol_conf.priv_size, sizeof(u64));
2010
2011         symbol__elf_init();
2012
2013         if (symbol_conf.sort_by_name)
2014                 symbol_conf.priv_size += (sizeof(struct symbol_name_rb_node) -
2015                                           sizeof(struct symbol));
2016
2017         if (symbol_conf.try_vmlinux_path && vmlinux_path__init(env) < 0)
2018                 return -1;
2019
2020         if (symbol_conf.field_sep && *symbol_conf.field_sep == '.') {
2021                 pr_err("'.' is the only non valid --field-separator argument\n");
2022                 return -1;
2023         }
2024
2025         if (setup_list(&symbol_conf.dso_list,
2026                        symbol_conf.dso_list_str, "dso") < 0)
2027                 return -1;
2028
2029         if (setup_list(&symbol_conf.comm_list,
2030                        symbol_conf.comm_list_str, "comm") < 0)
2031                 goto out_free_dso_list;
2032
2033         if (setup_intlist(&symbol_conf.pid_list,
2034                        symbol_conf.pid_list_str, "pid") < 0)
2035                 goto out_free_comm_list;
2036
2037         if (setup_intlist(&symbol_conf.tid_list,
2038                        symbol_conf.tid_list_str, "tid") < 0)
2039                 goto out_free_pid_list;
2040
2041         if (setup_list(&symbol_conf.sym_list,
2042                        symbol_conf.sym_list_str, "symbol") < 0)
2043                 goto out_free_tid_list;
2044
2045         /*
2046          * A path to symbols of "/" is identical to ""
2047          * reset here for simplicity.
2048          */
2049         symfs = realpath(symbol_conf.symfs, NULL);
2050         if (symfs == NULL)
2051                 symfs = symbol_conf.symfs;
2052         if (strcmp(symfs, "/") == 0)
2053                 symbol_conf.symfs = "";
2054         if (symfs != symbol_conf.symfs)
2055                 free((void *)symfs);
2056
2057         symbol_conf.kptr_restrict = symbol__read_kptr_restrict();
2058
2059         symbol_conf.initialized = true;
2060         return 0;
2061
2062 out_free_tid_list:
2063         intlist__delete(symbol_conf.tid_list);
2064 out_free_pid_list:
2065         intlist__delete(symbol_conf.pid_list);
2066 out_free_comm_list:
2067         strlist__delete(symbol_conf.comm_list);
2068 out_free_dso_list:
2069         strlist__delete(symbol_conf.dso_list);
2070         return -1;
2071 }
2072
2073 void symbol__exit(void)
2074 {
2075         if (!symbol_conf.initialized)
2076                 return;
2077         strlist__delete(symbol_conf.sym_list);
2078         strlist__delete(symbol_conf.dso_list);
2079         strlist__delete(symbol_conf.comm_list);
2080         intlist__delete(symbol_conf.tid_list);
2081         intlist__delete(symbol_conf.pid_list);
2082         vmlinux_path__exit();
2083         symbol_conf.sym_list = symbol_conf.dso_list = symbol_conf.comm_list = NULL;
2084         symbol_conf.initialized = false;
2085 }
2086
2087 int symbol__config_symfs(const struct option *opt __maybe_unused,
2088                          const char *dir, int unset __maybe_unused)
2089 {
2090         char *bf = NULL;
2091         int ret;
2092
2093         symbol_conf.symfs = strdup(dir);
2094         if (symbol_conf.symfs == NULL)
2095                 return -ENOMEM;
2096
2097         /* skip the locally configured cache if a symfs is given, and
2098          * config buildid dir to symfs/.debug
2099          */
2100         ret = asprintf(&bf, "%s/%s", dir, ".debug");
2101         if (ret < 0)
2102                 return -ENOMEM;
2103
2104         set_buildid_dir(bf);
2105
2106         free(bf);
2107         return 0;
2108 }