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