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