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