xref: /openbmc/linux/tools/perf/util/symbol-elf.c (revision 60fbb3e4)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <errno.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <inttypes.h>
9 
10 #include "dso.h"
11 #include "map.h"
12 #include "maps.h"
13 #include "symbol.h"
14 #include "symsrc.h"
15 #include "demangle-ocaml.h"
16 #include "demangle-java.h"
17 #include "demangle-rust.h"
18 #include "machine.h"
19 #include "vdso.h"
20 #include "debug.h"
21 #include "util/copyfile.h"
22 #include <linux/ctype.h>
23 #include <linux/kernel.h>
24 #include <linux/zalloc.h>
25 #include <symbol/kallsyms.h>
26 #include <internal/lib.h>
27 
28 #ifndef EM_AARCH64
29 #define EM_AARCH64	183  /* ARM 64 bit */
30 #endif
31 
32 #ifndef ELF32_ST_VISIBILITY
33 #define ELF32_ST_VISIBILITY(o)	((o) & 0x03)
34 #endif
35 
36 /* For ELF64 the definitions are the same.  */
37 #ifndef ELF64_ST_VISIBILITY
38 #define ELF64_ST_VISIBILITY(o)	ELF32_ST_VISIBILITY (o)
39 #endif
40 
41 /* How to extract information held in the st_other field.  */
42 #ifndef GELF_ST_VISIBILITY
43 #define GELF_ST_VISIBILITY(val)	ELF64_ST_VISIBILITY (val)
44 #endif
45 
46 typedef Elf64_Nhdr GElf_Nhdr;
47 
48 #ifndef DMGL_PARAMS
49 #define DMGL_NO_OPTS     0              /* For readability... */
50 #define DMGL_PARAMS      (1 << 0)       /* Include function args */
51 #define DMGL_ANSI        (1 << 1)       /* Include const, volatile, etc */
52 #endif
53 
54 #ifdef HAVE_LIBBFD_SUPPORT
55 #define PACKAGE 'perf'
56 #include <bfd.h>
57 #else
58 #ifdef HAVE_CPLUS_DEMANGLE_SUPPORT
59 extern char *cplus_demangle(const char *, int);
60 
61 static inline char *bfd_demangle(void __maybe_unused *v, const char *c, int i)
62 {
63 	return cplus_demangle(c, i);
64 }
65 #else
66 #ifdef NO_DEMANGLE
67 static inline char *bfd_demangle(void __maybe_unused *v,
68 				 const char __maybe_unused *c,
69 				 int __maybe_unused i)
70 {
71 	return NULL;
72 }
73 #endif
74 #endif
75 #endif
76 
77 #ifndef HAVE_ELF_GETPHDRNUM_SUPPORT
78 static int elf_getphdrnum(Elf *elf, size_t *dst)
79 {
80 	GElf_Ehdr gehdr;
81 	GElf_Ehdr *ehdr;
82 
83 	ehdr = gelf_getehdr(elf, &gehdr);
84 	if (!ehdr)
85 		return -1;
86 
87 	*dst = ehdr->e_phnum;
88 
89 	return 0;
90 }
91 #endif
92 
93 #ifndef HAVE_ELF_GETSHDRSTRNDX_SUPPORT
94 static int elf_getshdrstrndx(Elf *elf __maybe_unused, size_t *dst __maybe_unused)
95 {
96 	pr_err("%s: update your libelf to > 0.140, this one lacks elf_getshdrstrndx().\n", __func__);
97 	return -1;
98 }
99 #endif
100 
101 #ifndef NT_GNU_BUILD_ID
102 #define NT_GNU_BUILD_ID 3
103 #endif
104 
105 /**
106  * elf_symtab__for_each_symbol - iterate thru all the symbols
107  *
108  * @syms: struct elf_symtab instance to iterate
109  * @idx: uint32_t idx
110  * @sym: GElf_Sym iterator
111  */
112 #define elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) \
113 	for (idx = 0, gelf_getsym(syms, idx, &sym);\
114 	     idx < nr_syms; \
115 	     idx++, gelf_getsym(syms, idx, &sym))
116 
117 static inline uint8_t elf_sym__type(const GElf_Sym *sym)
118 {
119 	return GELF_ST_TYPE(sym->st_info);
120 }
121 
122 static inline uint8_t elf_sym__visibility(const GElf_Sym *sym)
123 {
124 	return GELF_ST_VISIBILITY(sym->st_other);
125 }
126 
127 #ifndef STT_GNU_IFUNC
128 #define STT_GNU_IFUNC 10
129 #endif
130 
131 static inline int elf_sym__is_function(const GElf_Sym *sym)
132 {
133 	return (elf_sym__type(sym) == STT_FUNC ||
134 		elf_sym__type(sym) == STT_GNU_IFUNC) &&
135 	       sym->st_name != 0 &&
136 	       sym->st_shndx != SHN_UNDEF;
137 }
138 
139 static inline bool elf_sym__is_object(const GElf_Sym *sym)
140 {
141 	return elf_sym__type(sym) == STT_OBJECT &&
142 		sym->st_name != 0 &&
143 		sym->st_shndx != SHN_UNDEF;
144 }
145 
146 static inline int elf_sym__is_label(const GElf_Sym *sym)
147 {
148 	return elf_sym__type(sym) == STT_NOTYPE &&
149 		sym->st_name != 0 &&
150 		sym->st_shndx != SHN_UNDEF &&
151 		sym->st_shndx != SHN_ABS &&
152 		elf_sym__visibility(sym) != STV_HIDDEN &&
153 		elf_sym__visibility(sym) != STV_INTERNAL;
154 }
155 
156 static bool elf_sym__filter(GElf_Sym *sym)
157 {
158 	return elf_sym__is_function(sym) || elf_sym__is_object(sym);
159 }
160 
161 static inline const char *elf_sym__name(const GElf_Sym *sym,
162 					const Elf_Data *symstrs)
163 {
164 	return symstrs->d_buf + sym->st_name;
165 }
166 
167 static inline const char *elf_sec__name(const GElf_Shdr *shdr,
168 					const Elf_Data *secstrs)
169 {
170 	return secstrs->d_buf + shdr->sh_name;
171 }
172 
173 static inline int elf_sec__is_text(const GElf_Shdr *shdr,
174 					const Elf_Data *secstrs)
175 {
176 	return strstr(elf_sec__name(shdr, secstrs), "text") != NULL;
177 }
178 
179 static inline bool elf_sec__is_data(const GElf_Shdr *shdr,
180 				    const Elf_Data *secstrs)
181 {
182 	return strstr(elf_sec__name(shdr, secstrs), "data") != NULL;
183 }
184 
185 static bool elf_sec__filter(GElf_Shdr *shdr, Elf_Data *secstrs)
186 {
187 	return elf_sec__is_text(shdr, secstrs) ||
188 	       elf_sec__is_data(shdr, secstrs);
189 }
190 
191 static size_t elf_addr_to_index(Elf *elf, GElf_Addr addr)
192 {
193 	Elf_Scn *sec = NULL;
194 	GElf_Shdr shdr;
195 	size_t cnt = 1;
196 
197 	while ((sec = elf_nextscn(elf, sec)) != NULL) {
198 		gelf_getshdr(sec, &shdr);
199 
200 		if ((addr >= shdr.sh_addr) &&
201 		    (addr < (shdr.sh_addr + shdr.sh_size)))
202 			return cnt;
203 
204 		++cnt;
205 	}
206 
207 	return -1;
208 }
209 
210 Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
211 			     GElf_Shdr *shp, const char *name, size_t *idx)
212 {
213 	Elf_Scn *sec = NULL;
214 	size_t cnt = 1;
215 
216 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
217 	if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL))
218 		return NULL;
219 
220 	while ((sec = elf_nextscn(elf, sec)) != NULL) {
221 		char *str;
222 
223 		gelf_getshdr(sec, shp);
224 		str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
225 		if (str && !strcmp(name, str)) {
226 			if (idx)
227 				*idx = cnt;
228 			return sec;
229 		}
230 		++cnt;
231 	}
232 
233 	return NULL;
234 }
235 
236 bool filename__has_section(const char *filename, const char *sec)
237 {
238 	int fd;
239 	Elf *elf;
240 	GElf_Ehdr ehdr;
241 	GElf_Shdr shdr;
242 	bool found = false;
243 
244 	fd = open(filename, O_RDONLY);
245 	if (fd < 0)
246 		return false;
247 
248 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
249 	if (elf == NULL)
250 		goto out;
251 
252 	if (gelf_getehdr(elf, &ehdr) == NULL)
253 		goto elf_out;
254 
255 	found = !!elf_section_by_name(elf, &ehdr, &shdr, sec, NULL);
256 
257 elf_out:
258 	elf_end(elf);
259 out:
260 	close(fd);
261 	return found;
262 }
263 
264 static int elf_read_program_header(Elf *elf, u64 vaddr, GElf_Phdr *phdr)
265 {
266 	size_t i, phdrnum;
267 	u64 sz;
268 
269 	if (elf_getphdrnum(elf, &phdrnum))
270 		return -1;
271 
272 	for (i = 0; i < phdrnum; i++) {
273 		if (gelf_getphdr(elf, i, phdr) == NULL)
274 			return -1;
275 
276 		if (phdr->p_type != PT_LOAD)
277 			continue;
278 
279 		sz = max(phdr->p_memsz, phdr->p_filesz);
280 		if (!sz)
281 			continue;
282 
283 		if (vaddr >= phdr->p_vaddr && (vaddr < phdr->p_vaddr + sz))
284 			return 0;
285 	}
286 
287 	/* Not found any valid program header */
288 	return -1;
289 }
290 
291 static bool want_demangle(bool is_kernel_sym)
292 {
293 	return is_kernel_sym ? symbol_conf.demangle_kernel : symbol_conf.demangle;
294 }
295 
296 static char *demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
297 {
298 	int demangle_flags = verbose > 0 ? (DMGL_PARAMS | DMGL_ANSI) : DMGL_NO_OPTS;
299 	char *demangled = NULL;
300 
301 	/*
302 	 * We need to figure out if the object was created from C++ sources
303 	 * DWARF DW_compile_unit has this, but we don't always have access
304 	 * to it...
305 	 */
306 	if (!want_demangle(dso->kernel || kmodule))
307 	    return demangled;
308 
309 	demangled = bfd_demangle(NULL, elf_name, demangle_flags);
310 	if (demangled == NULL) {
311 		demangled = ocaml_demangle_sym(elf_name);
312 		if (demangled == NULL) {
313 			demangled = java_demangle_sym(elf_name, JAVA_DEMANGLE_NORET);
314 		}
315 	}
316 	else if (rust_is_mangled(demangled))
317 		/*
318 		    * Input to Rust demangling is the BFD-demangled
319 		    * name which it Rust-demangles in place.
320 		    */
321 		rust_demangle_sym(demangled);
322 
323 	return demangled;
324 }
325 
326 struct rel_info {
327 	u32		nr_entries;
328 	u32		*sorted;
329 	bool		is_rela;
330 	Elf_Data	*reldata;
331 	GElf_Rela	rela;
332 	GElf_Rel	rel;
333 };
334 
335 static u32 get_rel_symidx(struct rel_info *ri, u32 idx)
336 {
337 	idx = ri->sorted ? ri->sorted[idx] : idx;
338 	if (ri->is_rela) {
339 		gelf_getrela(ri->reldata, idx, &ri->rela);
340 		return GELF_R_SYM(ri->rela.r_info);
341 	}
342 	gelf_getrel(ri->reldata, idx, &ri->rel);
343 	return GELF_R_SYM(ri->rel.r_info);
344 }
345 
346 static u64 get_rel_offset(struct rel_info *ri, u32 x)
347 {
348 	if (ri->is_rela) {
349 		GElf_Rela rela;
350 
351 		gelf_getrela(ri->reldata, x, &rela);
352 		return rela.r_offset;
353 	} else {
354 		GElf_Rel rel;
355 
356 		gelf_getrel(ri->reldata, x, &rel);
357 		return rel.r_offset;
358 	}
359 }
360 
361 static int rel_cmp(const void *a, const void *b, void *r)
362 {
363 	struct rel_info *ri = r;
364 	u64 a_offset = get_rel_offset(ri, *(const u32 *)a);
365 	u64 b_offset = get_rel_offset(ri, *(const u32 *)b);
366 
367 	return a_offset < b_offset ? -1 : (a_offset > b_offset ? 1 : 0);
368 }
369 
370 static int sort_rel(struct rel_info *ri)
371 {
372 	size_t sz = sizeof(ri->sorted[0]);
373 	u32 i;
374 
375 	ri->sorted = calloc(ri->nr_entries, sz);
376 	if (!ri->sorted)
377 		return -1;
378 	for (i = 0; i < ri->nr_entries; i++)
379 		ri->sorted[i] = i;
380 	qsort_r(ri->sorted, ri->nr_entries, sz, rel_cmp, ri);
381 	return 0;
382 }
383 
384 /*
385  * For x86_64, the GNU linker is putting IFUNC information in the relocation
386  * addend.
387  */
388 static bool addend_may_be_ifunc(GElf_Ehdr *ehdr, struct rel_info *ri)
389 {
390 	return ehdr->e_machine == EM_X86_64 && ri->is_rela &&
391 	       GELF_R_TYPE(ri->rela.r_info) == R_X86_64_IRELATIVE;
392 }
393 
394 static bool get_ifunc_name(Elf *elf, struct dso *dso, GElf_Ehdr *ehdr,
395 			   struct rel_info *ri, char *buf, size_t buf_sz)
396 {
397 	u64 addr = ri->rela.r_addend;
398 	struct symbol *sym;
399 	GElf_Phdr phdr;
400 
401 	if (!addend_may_be_ifunc(ehdr, ri))
402 		return false;
403 
404 	if (elf_read_program_header(elf, addr, &phdr))
405 		return false;
406 
407 	addr -= phdr.p_vaddr - phdr.p_offset;
408 
409 	sym = dso__find_symbol_nocache(dso, addr);
410 
411 	/* Expecting the address to be an IFUNC or IFUNC alias */
412 	if (!sym || sym->start != addr || (sym->type != STT_GNU_IFUNC && !sym->ifunc_alias))
413 		return false;
414 
415 	snprintf(buf, buf_sz, "%s@plt", sym->name);
416 
417 	return true;
418 }
419 
420 static void exit_rel(struct rel_info *ri)
421 {
422 	free(ri->sorted);
423 }
424 
425 static bool get_plt_sizes(struct dso *dso, GElf_Ehdr *ehdr, GElf_Shdr *shdr_plt,
426 			  u64 *plt_header_size, u64 *plt_entry_size)
427 {
428 	switch (ehdr->e_machine) {
429 	case EM_ARM:
430 		*plt_header_size = 20;
431 		*plt_entry_size = 12;
432 		return true;
433 	case EM_AARCH64:
434 		*plt_header_size = 32;
435 		*plt_entry_size = 16;
436 		return true;
437 	case EM_SPARC:
438 		*plt_header_size = 48;
439 		*plt_entry_size = 12;
440 		return true;
441 	case EM_SPARCV9:
442 		*plt_header_size = 128;
443 		*plt_entry_size = 32;
444 		return true;
445 	case EM_386:
446 	case EM_X86_64:
447 		*plt_entry_size = shdr_plt->sh_entsize;
448 		/* Size is 8 or 16, if not, assume alignment indicates size */
449 		if (*plt_entry_size != 8 && *plt_entry_size != 16)
450 			*plt_entry_size = shdr_plt->sh_addralign == 8 ? 8 : 16;
451 		*plt_header_size = *plt_entry_size;
452 		break;
453 	default: /* FIXME: s390/alpha/mips/parisc/poperpc/sh/xtensa need to be checked */
454 		*plt_header_size = shdr_plt->sh_entsize;
455 		*plt_entry_size = shdr_plt->sh_entsize;
456 		break;
457 	}
458 	if (*plt_entry_size)
459 		return true;
460 	pr_debug("Missing PLT entry size for %s\n", dso->long_name);
461 	return false;
462 }
463 
464 static bool machine_is_x86(GElf_Half e_machine)
465 {
466 	return e_machine == EM_386 || e_machine == EM_X86_64;
467 }
468 
469 /*
470  * We need to check if we have a .dynsym, so that we can handle the
471  * .plt, synthesizing its symbols, that aren't on the symtabs (be it
472  * .dynsym or .symtab).
473  * And always look at the original dso, not at debuginfo packages, that
474  * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
475  */
476 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss)
477 {
478 	uint32_t idx;
479 	GElf_Sym sym;
480 	u64 plt_offset, plt_header_size, plt_entry_size;
481 	GElf_Shdr shdr_plt, plt_sec_shdr;
482 	struct symbol *f, *plt_sym;
483 	GElf_Shdr shdr_rel_plt, shdr_dynsym;
484 	Elf_Data *syms, *symstrs;
485 	Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
486 	size_t dynsym_idx;
487 	GElf_Ehdr ehdr;
488 	char sympltname[1024];
489 	Elf *elf;
490 	int nr = 0, err = -1;
491 	struct rel_info ri = { .is_rela = false };
492 	bool lazy_plt;
493 
494 	elf = ss->elf;
495 	ehdr = ss->ehdr;
496 
497 	if (!elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL))
498 		return 0;
499 
500 	/*
501 	 * A symbol from a previous section (e.g. .init) can have been expanded
502 	 * by symbols__fixup_end() to overlap .plt. Truncate it before adding
503 	 * a symbol for .plt header.
504 	 */
505 	f = dso__find_symbol_nocache(dso, shdr_plt.sh_offset);
506 	if (f && f->start < shdr_plt.sh_offset && f->end > shdr_plt.sh_offset)
507 		f->end = shdr_plt.sh_offset;
508 
509 	if (!get_plt_sizes(dso, &ehdr, &shdr_plt, &plt_header_size, &plt_entry_size))
510 		return 0;
511 
512 	/* Add a symbol for .plt header */
513 	plt_sym = symbol__new(shdr_plt.sh_offset, plt_header_size, STB_GLOBAL, STT_FUNC, ".plt");
514 	if (!plt_sym)
515 		goto out_elf_end;
516 	symbols__insert(&dso->symbols, plt_sym);
517 
518 	/* Only x86 has .plt.sec */
519 	if (machine_is_x86(ehdr.e_machine) &&
520 	    elf_section_by_name(elf, &ehdr, &plt_sec_shdr, ".plt.sec", NULL)) {
521 		if (!get_plt_sizes(dso, &ehdr, &plt_sec_shdr, &plt_header_size, &plt_entry_size))
522 			return 0;
523 		/* Extend .plt symbol to entire .plt */
524 		plt_sym->end = plt_sym->start + shdr_plt.sh_size;
525 		/* Use .plt.sec offset */
526 		plt_offset = plt_sec_shdr.sh_offset;
527 		lazy_plt = false;
528 	} else {
529 		plt_offset = shdr_plt.sh_offset;
530 		lazy_plt = true;
531 	}
532 
533 	scn_dynsym = ss->dynsym;
534 	shdr_dynsym = ss->dynshdr;
535 	dynsym_idx = ss->dynsym_idx;
536 
537 	if (scn_dynsym == NULL)
538 		return 0;
539 
540 	scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
541 					  ".rela.plt", NULL);
542 	if (scn_plt_rel == NULL) {
543 		scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
544 						  ".rel.plt", NULL);
545 		if (scn_plt_rel == NULL)
546 			return 0;
547 	}
548 
549 	if (shdr_rel_plt.sh_type != SHT_RELA &&
550 	    shdr_rel_plt.sh_type != SHT_REL)
551 		return 0;
552 
553 	if (shdr_rel_plt.sh_link != dynsym_idx)
554 		goto out_elf_end;
555 
556 	/*
557 	 * Fetch the relocation section to find the idxes to the GOT
558 	 * and the symbols in the .dynsym they refer to.
559 	 */
560 	ri.reldata = elf_getdata(scn_plt_rel, NULL);
561 	if (!ri.reldata)
562 		goto out_elf_end;
563 
564 	syms = elf_getdata(scn_dynsym, NULL);
565 	if (syms == NULL)
566 		goto out_elf_end;
567 
568 	scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
569 	if (scn_symstrs == NULL)
570 		goto out_elf_end;
571 
572 	symstrs = elf_getdata(scn_symstrs, NULL);
573 	if (symstrs == NULL)
574 		goto out_elf_end;
575 
576 	if (symstrs->d_size == 0)
577 		goto out_elf_end;
578 
579 	ri.nr_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
580 
581 	ri.is_rela = shdr_rel_plt.sh_type == SHT_RELA;
582 
583 	if (lazy_plt) {
584 		/*
585 		 * Assume a .plt with the same number of entries as the number
586 		 * of relocation entries is not lazy and does not have a header.
587 		 */
588 		if (ri.nr_entries * plt_entry_size == shdr_plt.sh_size)
589 			dso__delete_symbol(dso, plt_sym);
590 		else
591 			plt_offset += plt_header_size;
592 	}
593 
594 	/*
595 	 * x86 doesn't insert IFUNC relocations in .plt order, so sort to get
596 	 * back in order.
597 	 */
598 	if (machine_is_x86(ehdr.e_machine) && sort_rel(&ri))
599 		goto out_elf_end;
600 
601 	for (idx = 0; idx < ri.nr_entries; idx++) {
602 		const char *elf_name = NULL;
603 		char *demangled = NULL;
604 
605 		gelf_getsym(syms, get_rel_symidx(&ri, idx), &sym);
606 
607 		elf_name = elf_sym__name(&sym, symstrs);
608 		demangled = demangle_sym(dso, 0, elf_name);
609 		if (demangled)
610 			elf_name = demangled;
611 		if (*elf_name)
612 			snprintf(sympltname, sizeof(sympltname), "%s@plt", elf_name);
613 		else if (!get_ifunc_name(elf, dso, &ehdr, &ri, sympltname, sizeof(sympltname)))
614 			snprintf(sympltname, sizeof(sympltname),
615 				 "offset_%#" PRIx64 "@plt", plt_offset);
616 		free(demangled);
617 
618 		f = symbol__new(plt_offset, plt_entry_size, STB_GLOBAL, STT_FUNC, sympltname);
619 		if (!f)
620 			goto out_elf_end;
621 
622 		plt_offset += plt_entry_size;
623 		symbols__insert(&dso->symbols, f);
624 		++nr;
625 	}
626 
627 	err = 0;
628 out_elf_end:
629 	exit_rel(&ri);
630 	if (err == 0)
631 		return nr;
632 	pr_debug("%s: problems reading %s PLT info.\n",
633 		 __func__, dso->long_name);
634 	return 0;
635 }
636 
637 char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
638 {
639 	return demangle_sym(dso, kmodule, elf_name);
640 }
641 
642 /*
643  * Align offset to 4 bytes as needed for note name and descriptor data.
644  */
645 #define NOTE_ALIGN(n) (((n) + 3) & -4U)
646 
647 static int elf_read_build_id(Elf *elf, void *bf, size_t size)
648 {
649 	int err = -1;
650 	GElf_Ehdr ehdr;
651 	GElf_Shdr shdr;
652 	Elf_Data *data;
653 	Elf_Scn *sec;
654 	Elf_Kind ek;
655 	void *ptr;
656 
657 	if (size < BUILD_ID_SIZE)
658 		goto out;
659 
660 	ek = elf_kind(elf);
661 	if (ek != ELF_K_ELF)
662 		goto out;
663 
664 	if (gelf_getehdr(elf, &ehdr) == NULL) {
665 		pr_err("%s: cannot get elf header.\n", __func__);
666 		goto out;
667 	}
668 
669 	/*
670 	 * Check following sections for notes:
671 	 *   '.note.gnu.build-id'
672 	 *   '.notes'
673 	 *   '.note' (VDSO specific)
674 	 */
675 	do {
676 		sec = elf_section_by_name(elf, &ehdr, &shdr,
677 					  ".note.gnu.build-id", NULL);
678 		if (sec)
679 			break;
680 
681 		sec = elf_section_by_name(elf, &ehdr, &shdr,
682 					  ".notes", NULL);
683 		if (sec)
684 			break;
685 
686 		sec = elf_section_by_name(elf, &ehdr, &shdr,
687 					  ".note", NULL);
688 		if (sec)
689 			break;
690 
691 		return err;
692 
693 	} while (0);
694 
695 	data = elf_getdata(sec, NULL);
696 	if (data == NULL)
697 		goto out;
698 
699 	ptr = data->d_buf;
700 	while (ptr < (data->d_buf + data->d_size)) {
701 		GElf_Nhdr *nhdr = ptr;
702 		size_t namesz = NOTE_ALIGN(nhdr->n_namesz),
703 		       descsz = NOTE_ALIGN(nhdr->n_descsz);
704 		const char *name;
705 
706 		ptr += sizeof(*nhdr);
707 		name = ptr;
708 		ptr += namesz;
709 		if (nhdr->n_type == NT_GNU_BUILD_ID &&
710 		    nhdr->n_namesz == sizeof("GNU")) {
711 			if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
712 				size_t sz = min(size, descsz);
713 				memcpy(bf, ptr, sz);
714 				memset(bf + sz, 0, size - sz);
715 				err = descsz;
716 				break;
717 			}
718 		}
719 		ptr += descsz;
720 	}
721 
722 out:
723 	return err;
724 }
725 
726 #ifdef HAVE_LIBBFD_BUILDID_SUPPORT
727 
728 static int read_build_id(const char *filename, struct build_id *bid)
729 {
730 	size_t size = sizeof(bid->data);
731 	int err = -1;
732 	bfd *abfd;
733 
734 	abfd = bfd_openr(filename, NULL);
735 	if (!abfd)
736 		return -1;
737 
738 	if (!bfd_check_format(abfd, bfd_object)) {
739 		pr_debug2("%s: cannot read %s bfd file.\n", __func__, filename);
740 		goto out_close;
741 	}
742 
743 	if (!abfd->build_id || abfd->build_id->size > size)
744 		goto out_close;
745 
746 	memcpy(bid->data, abfd->build_id->data, abfd->build_id->size);
747 	memset(bid->data + abfd->build_id->size, 0, size - abfd->build_id->size);
748 	err = bid->size = abfd->build_id->size;
749 
750 out_close:
751 	bfd_close(abfd);
752 	return err;
753 }
754 
755 #else // HAVE_LIBBFD_BUILDID_SUPPORT
756 
757 static int read_build_id(const char *filename, struct build_id *bid)
758 {
759 	size_t size = sizeof(bid->data);
760 	int fd, err = -1;
761 	Elf *elf;
762 
763 	if (size < BUILD_ID_SIZE)
764 		goto out;
765 
766 	fd = open(filename, O_RDONLY);
767 	if (fd < 0)
768 		goto out;
769 
770 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
771 	if (elf == NULL) {
772 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
773 		goto out_close;
774 	}
775 
776 	err = elf_read_build_id(elf, bid->data, size);
777 	if (err > 0)
778 		bid->size = err;
779 
780 	elf_end(elf);
781 out_close:
782 	close(fd);
783 out:
784 	return err;
785 }
786 
787 #endif // HAVE_LIBBFD_BUILDID_SUPPORT
788 
789 int filename__read_build_id(const char *filename, struct build_id *bid)
790 {
791 	struct kmod_path m = { .name = NULL, };
792 	char path[PATH_MAX];
793 	int err;
794 
795 	if (!filename)
796 		return -EFAULT;
797 
798 	err = kmod_path__parse(&m, filename);
799 	if (err)
800 		return -1;
801 
802 	if (m.comp) {
803 		int error = 0, fd;
804 
805 		fd = filename__decompress(filename, path, sizeof(path), m.comp, &error);
806 		if (fd < 0) {
807 			pr_debug("Failed to decompress (error %d) %s\n",
808 				 error, filename);
809 			return -1;
810 		}
811 		close(fd);
812 		filename = path;
813 	}
814 
815 	err = read_build_id(filename, bid);
816 
817 	if (m.comp)
818 		unlink(filename);
819 	return err;
820 }
821 
822 int sysfs__read_build_id(const char *filename, struct build_id *bid)
823 {
824 	size_t size = sizeof(bid->data);
825 	int fd, err = -1;
826 
827 	fd = open(filename, O_RDONLY);
828 	if (fd < 0)
829 		goto out;
830 
831 	while (1) {
832 		char bf[BUFSIZ];
833 		GElf_Nhdr nhdr;
834 		size_t namesz, descsz;
835 
836 		if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
837 			break;
838 
839 		namesz = NOTE_ALIGN(nhdr.n_namesz);
840 		descsz = NOTE_ALIGN(nhdr.n_descsz);
841 		if (nhdr.n_type == NT_GNU_BUILD_ID &&
842 		    nhdr.n_namesz == sizeof("GNU")) {
843 			if (read(fd, bf, namesz) != (ssize_t)namesz)
844 				break;
845 			if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
846 				size_t sz = min(descsz, size);
847 				if (read(fd, bid->data, sz) == (ssize_t)sz) {
848 					memset(bid->data + sz, 0, size - sz);
849 					bid->size = sz;
850 					err = 0;
851 					break;
852 				}
853 			} else if (read(fd, bf, descsz) != (ssize_t)descsz)
854 				break;
855 		} else {
856 			int n = namesz + descsz;
857 
858 			if (n > (int)sizeof(bf)) {
859 				n = sizeof(bf);
860 				pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
861 					 __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
862 			}
863 			if (read(fd, bf, n) != n)
864 				break;
865 		}
866 	}
867 	close(fd);
868 out:
869 	return err;
870 }
871 
872 #ifdef HAVE_LIBBFD_SUPPORT
873 
874 int filename__read_debuglink(const char *filename, char *debuglink,
875 			     size_t size)
876 {
877 	int err = -1;
878 	asection *section;
879 	bfd *abfd;
880 
881 	abfd = bfd_openr(filename, NULL);
882 	if (!abfd)
883 		return -1;
884 
885 	if (!bfd_check_format(abfd, bfd_object)) {
886 		pr_debug2("%s: cannot read %s bfd file.\n", __func__, filename);
887 		goto out_close;
888 	}
889 
890 	section = bfd_get_section_by_name(abfd, ".gnu_debuglink");
891 	if (!section)
892 		goto out_close;
893 
894 	if (section->size > size)
895 		goto out_close;
896 
897 	if (!bfd_get_section_contents(abfd, section, debuglink, 0,
898 				      section->size))
899 		goto out_close;
900 
901 	err = 0;
902 
903 out_close:
904 	bfd_close(abfd);
905 	return err;
906 }
907 
908 #else
909 
910 int filename__read_debuglink(const char *filename, char *debuglink,
911 			     size_t size)
912 {
913 	int fd, err = -1;
914 	Elf *elf;
915 	GElf_Ehdr ehdr;
916 	GElf_Shdr shdr;
917 	Elf_Data *data;
918 	Elf_Scn *sec;
919 	Elf_Kind ek;
920 
921 	fd = open(filename, O_RDONLY);
922 	if (fd < 0)
923 		goto out;
924 
925 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
926 	if (elf == NULL) {
927 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
928 		goto out_close;
929 	}
930 
931 	ek = elf_kind(elf);
932 	if (ek != ELF_K_ELF)
933 		goto out_elf_end;
934 
935 	if (gelf_getehdr(elf, &ehdr) == NULL) {
936 		pr_err("%s: cannot get elf header.\n", __func__);
937 		goto out_elf_end;
938 	}
939 
940 	sec = elf_section_by_name(elf, &ehdr, &shdr,
941 				  ".gnu_debuglink", NULL);
942 	if (sec == NULL)
943 		goto out_elf_end;
944 
945 	data = elf_getdata(sec, NULL);
946 	if (data == NULL)
947 		goto out_elf_end;
948 
949 	/* the start of this section is a zero-terminated string */
950 	strncpy(debuglink, data->d_buf, size);
951 
952 	err = 0;
953 
954 out_elf_end:
955 	elf_end(elf);
956 out_close:
957 	close(fd);
958 out:
959 	return err;
960 }
961 
962 #endif
963 
964 static int dso__swap_init(struct dso *dso, unsigned char eidata)
965 {
966 	static unsigned int const endian = 1;
967 
968 	dso->needs_swap = DSO_SWAP__NO;
969 
970 	switch (eidata) {
971 	case ELFDATA2LSB:
972 		/* We are big endian, DSO is little endian. */
973 		if (*(unsigned char const *)&endian != 1)
974 			dso->needs_swap = DSO_SWAP__YES;
975 		break;
976 
977 	case ELFDATA2MSB:
978 		/* We are little endian, DSO is big endian. */
979 		if (*(unsigned char const *)&endian != 0)
980 			dso->needs_swap = DSO_SWAP__YES;
981 		break;
982 
983 	default:
984 		pr_err("unrecognized DSO data encoding %d\n", eidata);
985 		return -EINVAL;
986 	}
987 
988 	return 0;
989 }
990 
991 bool symsrc__possibly_runtime(struct symsrc *ss)
992 {
993 	return ss->dynsym || ss->opdsec;
994 }
995 
996 bool symsrc__has_symtab(struct symsrc *ss)
997 {
998 	return ss->symtab != NULL;
999 }
1000 
1001 void symsrc__destroy(struct symsrc *ss)
1002 {
1003 	zfree(&ss->name);
1004 	elf_end(ss->elf);
1005 	close(ss->fd);
1006 }
1007 
1008 bool elf__needs_adjust_symbols(GElf_Ehdr ehdr)
1009 {
1010 	/*
1011 	 * Usually vmlinux is an ELF file with type ET_EXEC for most
1012 	 * architectures; except Arm64 kernel is linked with option
1013 	 * '-share', so need to check type ET_DYN.
1014 	 */
1015 	return ehdr.e_type == ET_EXEC || ehdr.e_type == ET_REL ||
1016 	       ehdr.e_type == ET_DYN;
1017 }
1018 
1019 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
1020 		 enum dso_binary_type type)
1021 {
1022 	GElf_Ehdr ehdr;
1023 	Elf *elf;
1024 	int fd;
1025 
1026 	if (dso__needs_decompress(dso)) {
1027 		fd = dso__decompress_kmodule_fd(dso, name);
1028 		if (fd < 0)
1029 			return -1;
1030 
1031 		type = dso->symtab_type;
1032 	} else {
1033 		fd = open(name, O_RDONLY);
1034 		if (fd < 0) {
1035 			dso->load_errno = errno;
1036 			return -1;
1037 		}
1038 	}
1039 
1040 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1041 	if (elf == NULL) {
1042 		pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1043 		dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
1044 		goto out_close;
1045 	}
1046 
1047 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1048 		dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
1049 		pr_debug("%s: cannot get elf header.\n", __func__);
1050 		goto out_elf_end;
1051 	}
1052 
1053 	if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
1054 		dso->load_errno = DSO_LOAD_ERRNO__INTERNAL_ERROR;
1055 		goto out_elf_end;
1056 	}
1057 
1058 	/* Always reject images with a mismatched build-id: */
1059 	if (dso->has_build_id && !symbol_conf.ignore_vmlinux_buildid) {
1060 		u8 build_id[BUILD_ID_SIZE];
1061 		struct build_id bid;
1062 		int size;
1063 
1064 		size = elf_read_build_id(elf, build_id, BUILD_ID_SIZE);
1065 		if (size <= 0) {
1066 			dso->load_errno = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
1067 			goto out_elf_end;
1068 		}
1069 
1070 		build_id__init(&bid, build_id, size);
1071 		if (!dso__build_id_equal(dso, &bid)) {
1072 			pr_debug("%s: build id mismatch for %s.\n", __func__, name);
1073 			dso->load_errno = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
1074 			goto out_elf_end;
1075 		}
1076 	}
1077 
1078 	ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1079 
1080 	ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
1081 			NULL);
1082 	if (ss->symshdr.sh_type != SHT_SYMTAB)
1083 		ss->symtab = NULL;
1084 
1085 	ss->dynsym_idx = 0;
1086 	ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
1087 			&ss->dynsym_idx);
1088 	if (ss->dynshdr.sh_type != SHT_DYNSYM)
1089 		ss->dynsym = NULL;
1090 
1091 	ss->opdidx = 0;
1092 	ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
1093 			&ss->opdidx);
1094 	if (ss->opdshdr.sh_type != SHT_PROGBITS)
1095 		ss->opdsec = NULL;
1096 
1097 	if (dso->kernel == DSO_SPACE__USER)
1098 		ss->adjust_symbols = true;
1099 	else
1100 		ss->adjust_symbols = elf__needs_adjust_symbols(ehdr);
1101 
1102 	ss->name   = strdup(name);
1103 	if (!ss->name) {
1104 		dso->load_errno = errno;
1105 		goto out_elf_end;
1106 	}
1107 
1108 	ss->elf    = elf;
1109 	ss->fd     = fd;
1110 	ss->ehdr   = ehdr;
1111 	ss->type   = type;
1112 
1113 	return 0;
1114 
1115 out_elf_end:
1116 	elf_end(elf);
1117 out_close:
1118 	close(fd);
1119 	return -1;
1120 }
1121 
1122 /**
1123  * ref_reloc_sym_not_found - has kernel relocation symbol been found.
1124  * @kmap: kernel maps and relocation reference symbol
1125  *
1126  * This function returns %true if we are dealing with the kernel maps and the
1127  * relocation reference symbol has not yet been found.  Otherwise %false is
1128  * returned.
1129  */
1130 static bool ref_reloc_sym_not_found(struct kmap *kmap)
1131 {
1132 	return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
1133 	       !kmap->ref_reloc_sym->unrelocated_addr;
1134 }
1135 
1136 /**
1137  * ref_reloc - kernel relocation offset.
1138  * @kmap: kernel maps and relocation reference symbol
1139  *
1140  * This function returns the offset of kernel addresses as determined by using
1141  * the relocation reference symbol i.e. if the kernel has not been relocated
1142  * then the return value is zero.
1143  */
1144 static u64 ref_reloc(struct kmap *kmap)
1145 {
1146 	if (kmap && kmap->ref_reloc_sym &&
1147 	    kmap->ref_reloc_sym->unrelocated_addr)
1148 		return kmap->ref_reloc_sym->addr -
1149 		       kmap->ref_reloc_sym->unrelocated_addr;
1150 	return 0;
1151 }
1152 
1153 void __weak arch__sym_update(struct symbol *s __maybe_unused,
1154 		GElf_Sym *sym __maybe_unused) { }
1155 
1156 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
1157 				      GElf_Sym *sym, GElf_Shdr *shdr,
1158 				      struct maps *kmaps, struct kmap *kmap,
1159 				      struct dso **curr_dsop, struct map **curr_mapp,
1160 				      const char *section_name,
1161 				      bool adjust_kernel_syms, bool kmodule, bool *remap_kernel)
1162 {
1163 	struct dso *curr_dso = *curr_dsop;
1164 	struct map *curr_map;
1165 	char dso_name[PATH_MAX];
1166 
1167 	/* Adjust symbol to map to file offset */
1168 	if (adjust_kernel_syms)
1169 		sym->st_value -= shdr->sh_addr - shdr->sh_offset;
1170 
1171 	if (strcmp(section_name, (curr_dso->short_name + dso->short_name_len)) == 0)
1172 		return 0;
1173 
1174 	if (strcmp(section_name, ".text") == 0) {
1175 		/*
1176 		 * The initial kernel mapping is based on
1177 		 * kallsyms and identity maps.  Overwrite it to
1178 		 * map to the kernel dso.
1179 		 */
1180 		if (*remap_kernel && dso->kernel && !kmodule) {
1181 			*remap_kernel = false;
1182 			map->start = shdr->sh_addr + ref_reloc(kmap);
1183 			map->end = map->start + shdr->sh_size;
1184 			map->pgoff = shdr->sh_offset;
1185 			map->map_ip = map__map_ip;
1186 			map->unmap_ip = map__unmap_ip;
1187 			/* Ensure maps are correctly ordered */
1188 			if (kmaps) {
1189 				map__get(map);
1190 				maps__remove(kmaps, map);
1191 				maps__insert(kmaps, map);
1192 				map__put(map);
1193 			}
1194 		}
1195 
1196 		/*
1197 		 * The initial module mapping is based on
1198 		 * /proc/modules mapped to offset zero.
1199 		 * Overwrite it to map to the module dso.
1200 		 */
1201 		if (*remap_kernel && kmodule) {
1202 			*remap_kernel = false;
1203 			map->pgoff = shdr->sh_offset;
1204 		}
1205 
1206 		*curr_mapp = map;
1207 		*curr_dsop = dso;
1208 		return 0;
1209 	}
1210 
1211 	if (!kmap)
1212 		return 0;
1213 
1214 	snprintf(dso_name, sizeof(dso_name), "%s%s", dso->short_name, section_name);
1215 
1216 	curr_map = maps__find_by_name(kmaps, dso_name);
1217 	if (curr_map == NULL) {
1218 		u64 start = sym->st_value;
1219 
1220 		if (kmodule)
1221 			start += map->start + shdr->sh_offset;
1222 
1223 		curr_dso = dso__new(dso_name);
1224 		if (curr_dso == NULL)
1225 			return -1;
1226 		curr_dso->kernel = dso->kernel;
1227 		curr_dso->long_name = dso->long_name;
1228 		curr_dso->long_name_len = dso->long_name_len;
1229 		curr_map = map__new2(start, curr_dso);
1230 		dso__put(curr_dso);
1231 		if (curr_map == NULL)
1232 			return -1;
1233 
1234 		if (curr_dso->kernel)
1235 			map__kmap(curr_map)->kmaps = kmaps;
1236 
1237 		if (adjust_kernel_syms) {
1238 			curr_map->start  = shdr->sh_addr + ref_reloc(kmap);
1239 			curr_map->end	 = curr_map->start + shdr->sh_size;
1240 			curr_map->pgoff	 = shdr->sh_offset;
1241 		} else {
1242 			curr_map->map_ip = curr_map->unmap_ip = identity__map_ip;
1243 		}
1244 		curr_dso->symtab_type = dso->symtab_type;
1245 		maps__insert(kmaps, curr_map);
1246 		/*
1247 		 * Add it before we drop the reference to curr_map, i.e. while
1248 		 * we still are sure to have a reference to this DSO via
1249 		 * *curr_map->dso.
1250 		 */
1251 		dsos__add(&kmaps->machine->dsos, curr_dso);
1252 		/* kmaps already got it */
1253 		map__put(curr_map);
1254 		dso__set_loaded(curr_dso);
1255 		*curr_mapp = curr_map;
1256 		*curr_dsop = curr_dso;
1257 	} else
1258 		*curr_dsop = curr_map->dso;
1259 
1260 	return 0;
1261 }
1262 
1263 static int
1264 dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1265 		       struct symsrc *runtime_ss, int kmodule, int dynsym)
1266 {
1267 	struct kmap *kmap = dso->kernel ? map__kmap(map) : NULL;
1268 	struct maps *kmaps = kmap ? map__kmaps(map) : NULL;
1269 	struct map *curr_map = map;
1270 	struct dso *curr_dso = dso;
1271 	Elf_Data *symstrs, *secstrs, *secstrs_run, *secstrs_sym;
1272 	uint32_t nr_syms;
1273 	int err = -1;
1274 	uint32_t idx;
1275 	GElf_Ehdr ehdr;
1276 	GElf_Shdr shdr;
1277 	GElf_Shdr tshdr;
1278 	Elf_Data *syms, *opddata = NULL;
1279 	GElf_Sym sym;
1280 	Elf_Scn *sec, *sec_strndx;
1281 	Elf *elf;
1282 	int nr = 0;
1283 	bool remap_kernel = false, adjust_kernel_syms = false;
1284 
1285 	if (kmap && !kmaps)
1286 		return -1;
1287 
1288 	elf = syms_ss->elf;
1289 	ehdr = syms_ss->ehdr;
1290 	if (dynsym) {
1291 		sec  = syms_ss->dynsym;
1292 		shdr = syms_ss->dynshdr;
1293 	} else {
1294 		sec =  syms_ss->symtab;
1295 		shdr = syms_ss->symshdr;
1296 	}
1297 
1298 	if (elf_section_by_name(runtime_ss->elf, &runtime_ss->ehdr, &tshdr,
1299 				".text", NULL))
1300 		dso->text_offset = tshdr.sh_addr - tshdr.sh_offset;
1301 
1302 	if (runtime_ss->opdsec)
1303 		opddata = elf_rawdata(runtime_ss->opdsec, NULL);
1304 
1305 	syms = elf_getdata(sec, NULL);
1306 	if (syms == NULL)
1307 		goto out_elf_end;
1308 
1309 	sec = elf_getscn(elf, shdr.sh_link);
1310 	if (sec == NULL)
1311 		goto out_elf_end;
1312 
1313 	symstrs = elf_getdata(sec, NULL);
1314 	if (symstrs == NULL)
1315 		goto out_elf_end;
1316 
1317 	sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
1318 	if (sec_strndx == NULL)
1319 		goto out_elf_end;
1320 
1321 	secstrs_run = elf_getdata(sec_strndx, NULL);
1322 	if (secstrs_run == NULL)
1323 		goto out_elf_end;
1324 
1325 	sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
1326 	if (sec_strndx == NULL)
1327 		goto out_elf_end;
1328 
1329 	secstrs_sym = elf_getdata(sec_strndx, NULL);
1330 	if (secstrs_sym == NULL)
1331 		goto out_elf_end;
1332 
1333 	nr_syms = shdr.sh_size / shdr.sh_entsize;
1334 
1335 	memset(&sym, 0, sizeof(sym));
1336 
1337 	/*
1338 	 * The kernel relocation symbol is needed in advance in order to adjust
1339 	 * kernel maps correctly.
1340 	 */
1341 	if (ref_reloc_sym_not_found(kmap)) {
1342 		elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1343 			const char *elf_name = elf_sym__name(&sym, symstrs);
1344 
1345 			if (strcmp(elf_name, kmap->ref_reloc_sym->name))
1346 				continue;
1347 			kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
1348 			map->reloc = kmap->ref_reloc_sym->addr -
1349 				     kmap->ref_reloc_sym->unrelocated_addr;
1350 			break;
1351 		}
1352 	}
1353 
1354 	/*
1355 	 * Handle any relocation of vdso necessary because older kernels
1356 	 * attempted to prelink vdso to its virtual address.
1357 	 */
1358 	if (dso__is_vdso(dso))
1359 		map->reloc = map->start - dso->text_offset;
1360 
1361 	dso->adjust_symbols = runtime_ss->adjust_symbols || ref_reloc(kmap);
1362 	/*
1363 	 * Initial kernel and module mappings do not map to the dso.
1364 	 * Flag the fixups.
1365 	 */
1366 	if (dso->kernel) {
1367 		remap_kernel = true;
1368 		adjust_kernel_syms = dso->adjust_symbols;
1369 	}
1370 	elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1371 		struct symbol *f;
1372 		const char *elf_name = elf_sym__name(&sym, symstrs);
1373 		char *demangled = NULL;
1374 		int is_label = elf_sym__is_label(&sym);
1375 		const char *section_name;
1376 		bool used_opd = false;
1377 
1378 		if (!is_label && !elf_sym__filter(&sym))
1379 			continue;
1380 
1381 		/* Reject ARM ELF "mapping symbols": these aren't unique and
1382 		 * don't identify functions, so will confuse the profile
1383 		 * output: */
1384 		if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
1385 			if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
1386 			    && (elf_name[2] == '\0' || elf_name[2] == '.'))
1387 				continue;
1388 		}
1389 
1390 		if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
1391 			u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
1392 			u64 *opd = opddata->d_buf + offset;
1393 			sym.st_value = DSO__SWAP(dso, u64, *opd);
1394 			sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
1395 					sym.st_value);
1396 			used_opd = true;
1397 		}
1398 
1399 		/*
1400 		 * When loading symbols in a data mapping, ABS symbols (which
1401 		 * has a value of SHN_ABS in its st_shndx) failed at
1402 		 * elf_getscn().  And it marks the loading as a failure so
1403 		 * already loaded symbols cannot be fixed up.
1404 		 *
1405 		 * I'm not sure what should be done. Just ignore them for now.
1406 		 * - Namhyung Kim
1407 		 */
1408 		if (sym.st_shndx == SHN_ABS)
1409 			continue;
1410 
1411 		sec = elf_getscn(syms_ss->elf, sym.st_shndx);
1412 		if (!sec)
1413 			goto out_elf_end;
1414 
1415 		gelf_getshdr(sec, &shdr);
1416 
1417 		/*
1418 		 * If the attribute bit SHF_ALLOC is not set, the section
1419 		 * doesn't occupy memory during process execution.
1420 		 * E.g. ".gnu.warning.*" section is used by linker to generate
1421 		 * warnings when calling deprecated functions, the symbols in
1422 		 * the section aren't loaded to memory during process execution,
1423 		 * so skip them.
1424 		 */
1425 		if (!(shdr.sh_flags & SHF_ALLOC))
1426 			continue;
1427 
1428 		secstrs = secstrs_sym;
1429 
1430 		/*
1431 		 * We have to fallback to runtime when syms' section header has
1432 		 * NOBITS set. NOBITS results in file offset (sh_offset) not
1433 		 * being incremented. So sh_offset used below has different
1434 		 * values for syms (invalid) and runtime (valid).
1435 		 */
1436 		if (shdr.sh_type == SHT_NOBITS) {
1437 			sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
1438 			if (!sec)
1439 				goto out_elf_end;
1440 
1441 			gelf_getshdr(sec, &shdr);
1442 			secstrs = secstrs_run;
1443 		}
1444 
1445 		if (is_label && !elf_sec__filter(&shdr, secstrs))
1446 			continue;
1447 
1448 		section_name = elf_sec__name(&shdr, secstrs);
1449 
1450 		/* On ARM, symbols for thumb functions have 1 added to
1451 		 * the symbol address as a flag - remove it */
1452 		if ((ehdr.e_machine == EM_ARM) &&
1453 		    (GELF_ST_TYPE(sym.st_info) == STT_FUNC) &&
1454 		    (sym.st_value & 1))
1455 			--sym.st_value;
1456 
1457 		if (dso->kernel) {
1458 			if (dso__process_kernel_symbol(dso, map, &sym, &shdr, kmaps, kmap, &curr_dso, &curr_map,
1459 						       section_name, adjust_kernel_syms, kmodule, &remap_kernel))
1460 				goto out_elf_end;
1461 		} else if ((used_opd && runtime_ss->adjust_symbols) ||
1462 			   (!used_opd && syms_ss->adjust_symbols)) {
1463 			GElf_Phdr phdr;
1464 
1465 			if (elf_read_program_header(runtime_ss->elf,
1466 						    (u64)sym.st_value, &phdr)) {
1467 				pr_debug4("%s: failed to find program header for "
1468 					   "symbol: %s st_value: %#" PRIx64 "\n",
1469 					   __func__, elf_name, (u64)sym.st_value);
1470 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1471 					"sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n",
1472 					__func__, (u64)sym.st_value, (u64)shdr.sh_addr,
1473 					(u64)shdr.sh_offset);
1474 				/*
1475 				 * Fail to find program header, let's rollback
1476 				 * to use shdr.sh_addr and shdr.sh_offset to
1477 				 * calibrate symbol's file address, though this
1478 				 * is not necessary for normal C ELF file, we
1479 				 * still need to handle java JIT symbols in this
1480 				 * case.
1481 				 */
1482 				sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1483 			} else {
1484 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1485 					"p_vaddr: %#" PRIx64 " p_offset: %#" PRIx64 "\n",
1486 					__func__, (u64)sym.st_value, (u64)phdr.p_vaddr,
1487 					(u64)phdr.p_offset);
1488 				sym.st_value -= phdr.p_vaddr - phdr.p_offset;
1489 			}
1490 		}
1491 
1492 		demangled = demangle_sym(dso, kmodule, elf_name);
1493 		if (demangled != NULL)
1494 			elf_name = demangled;
1495 
1496 		f = symbol__new(sym.st_value, sym.st_size,
1497 				GELF_ST_BIND(sym.st_info),
1498 				GELF_ST_TYPE(sym.st_info), elf_name);
1499 		free(demangled);
1500 		if (!f)
1501 			goto out_elf_end;
1502 
1503 		arch__sym_update(f, &sym);
1504 
1505 		__symbols__insert(&curr_dso->symbols, f, dso->kernel);
1506 		nr++;
1507 	}
1508 
1509 	/*
1510 	 * For misannotated, zeroed, ASM function sizes.
1511 	 */
1512 	if (nr > 0) {
1513 		symbols__fixup_end(&dso->symbols, false);
1514 		symbols__fixup_duplicate(&dso->symbols);
1515 		if (kmap) {
1516 			/*
1517 			 * We need to fixup this here too because we create new
1518 			 * maps here, for things like vsyscall sections.
1519 			 */
1520 			maps__fixup_end(kmaps);
1521 		}
1522 	}
1523 	err = nr;
1524 out_elf_end:
1525 	return err;
1526 }
1527 
1528 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1529 		  struct symsrc *runtime_ss, int kmodule)
1530 {
1531 	int nr = 0;
1532 	int err = -1;
1533 
1534 	dso->symtab_type = syms_ss->type;
1535 	dso->is_64_bit = syms_ss->is_64_bit;
1536 	dso->rel = syms_ss->ehdr.e_type == ET_REL;
1537 
1538 	/*
1539 	 * Modules may already have symbols from kallsyms, but those symbols
1540 	 * have the wrong values for the dso maps, so remove them.
1541 	 */
1542 	if (kmodule && syms_ss->symtab)
1543 		symbols__delete(&dso->symbols);
1544 
1545 	if (!syms_ss->symtab) {
1546 		/*
1547 		 * If the vmlinux is stripped, fail so we will fall back
1548 		 * to using kallsyms. The vmlinux runtime symbols aren't
1549 		 * of much use.
1550 		 */
1551 		if (dso->kernel)
1552 			return err;
1553 	} else  {
1554 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1555 					     kmodule, 0);
1556 		if (err < 0)
1557 			return err;
1558 		nr = err;
1559 	}
1560 
1561 	if (syms_ss->dynsym) {
1562 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1563 					     kmodule, 1);
1564 		if (err < 0)
1565 			return err;
1566 		err += nr;
1567 	}
1568 
1569 	return err;
1570 }
1571 
1572 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1573 {
1574 	GElf_Phdr phdr;
1575 	size_t i, phdrnum;
1576 	int err;
1577 	u64 sz;
1578 
1579 	if (elf_getphdrnum(elf, &phdrnum))
1580 		return -1;
1581 
1582 	for (i = 0; i < phdrnum; i++) {
1583 		if (gelf_getphdr(elf, i, &phdr) == NULL)
1584 			return -1;
1585 		if (phdr.p_type != PT_LOAD)
1586 			continue;
1587 		if (exe) {
1588 			if (!(phdr.p_flags & PF_X))
1589 				continue;
1590 		} else {
1591 			if (!(phdr.p_flags & PF_R))
1592 				continue;
1593 		}
1594 		sz = min(phdr.p_memsz, phdr.p_filesz);
1595 		if (!sz)
1596 			continue;
1597 		err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1598 		if (err)
1599 			return err;
1600 	}
1601 	return 0;
1602 }
1603 
1604 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1605 		    bool *is_64_bit)
1606 {
1607 	int err;
1608 	Elf *elf;
1609 
1610 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1611 	if (elf == NULL)
1612 		return -1;
1613 
1614 	if (is_64_bit)
1615 		*is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1616 
1617 	err = elf_read_maps(elf, exe, mapfn, data);
1618 
1619 	elf_end(elf);
1620 	return err;
1621 }
1622 
1623 enum dso_type dso__type_fd(int fd)
1624 {
1625 	enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1626 	GElf_Ehdr ehdr;
1627 	Elf_Kind ek;
1628 	Elf *elf;
1629 
1630 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1631 	if (elf == NULL)
1632 		goto out;
1633 
1634 	ek = elf_kind(elf);
1635 	if (ek != ELF_K_ELF)
1636 		goto out_end;
1637 
1638 	if (gelf_getclass(elf) == ELFCLASS64) {
1639 		dso_type = DSO__TYPE_64BIT;
1640 		goto out_end;
1641 	}
1642 
1643 	if (gelf_getehdr(elf, &ehdr) == NULL)
1644 		goto out_end;
1645 
1646 	if (ehdr.e_machine == EM_X86_64)
1647 		dso_type = DSO__TYPE_X32BIT;
1648 	else
1649 		dso_type = DSO__TYPE_32BIT;
1650 out_end:
1651 	elf_end(elf);
1652 out:
1653 	return dso_type;
1654 }
1655 
1656 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1657 {
1658 	ssize_t r;
1659 	size_t n;
1660 	int err = -1;
1661 	char *buf = malloc(page_size);
1662 
1663 	if (buf == NULL)
1664 		return -1;
1665 
1666 	if (lseek(to, to_offs, SEEK_SET) != to_offs)
1667 		goto out;
1668 
1669 	if (lseek(from, from_offs, SEEK_SET) != from_offs)
1670 		goto out;
1671 
1672 	while (len) {
1673 		n = page_size;
1674 		if (len < n)
1675 			n = len;
1676 		/* Use read because mmap won't work on proc files */
1677 		r = read(from, buf, n);
1678 		if (r < 0)
1679 			goto out;
1680 		if (!r)
1681 			break;
1682 		n = r;
1683 		r = write(to, buf, n);
1684 		if (r < 0)
1685 			goto out;
1686 		if ((size_t)r != n)
1687 			goto out;
1688 		len -= n;
1689 	}
1690 
1691 	err = 0;
1692 out:
1693 	free(buf);
1694 	return err;
1695 }
1696 
1697 struct kcore {
1698 	int fd;
1699 	int elfclass;
1700 	Elf *elf;
1701 	GElf_Ehdr ehdr;
1702 };
1703 
1704 static int kcore__open(struct kcore *kcore, const char *filename)
1705 {
1706 	GElf_Ehdr *ehdr;
1707 
1708 	kcore->fd = open(filename, O_RDONLY);
1709 	if (kcore->fd == -1)
1710 		return -1;
1711 
1712 	kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1713 	if (!kcore->elf)
1714 		goto out_close;
1715 
1716 	kcore->elfclass = gelf_getclass(kcore->elf);
1717 	if (kcore->elfclass == ELFCLASSNONE)
1718 		goto out_end;
1719 
1720 	ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1721 	if (!ehdr)
1722 		goto out_end;
1723 
1724 	return 0;
1725 
1726 out_end:
1727 	elf_end(kcore->elf);
1728 out_close:
1729 	close(kcore->fd);
1730 	return -1;
1731 }
1732 
1733 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1734 		       bool temp)
1735 {
1736 	kcore->elfclass = elfclass;
1737 
1738 	if (temp)
1739 		kcore->fd = mkstemp(filename);
1740 	else
1741 		kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0400);
1742 	if (kcore->fd == -1)
1743 		return -1;
1744 
1745 	kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1746 	if (!kcore->elf)
1747 		goto out_close;
1748 
1749 	if (!gelf_newehdr(kcore->elf, elfclass))
1750 		goto out_end;
1751 
1752 	memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
1753 
1754 	return 0;
1755 
1756 out_end:
1757 	elf_end(kcore->elf);
1758 out_close:
1759 	close(kcore->fd);
1760 	unlink(filename);
1761 	return -1;
1762 }
1763 
1764 static void kcore__close(struct kcore *kcore)
1765 {
1766 	elf_end(kcore->elf);
1767 	close(kcore->fd);
1768 }
1769 
1770 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
1771 {
1772 	GElf_Ehdr *ehdr = &to->ehdr;
1773 	GElf_Ehdr *kehdr = &from->ehdr;
1774 
1775 	memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
1776 	ehdr->e_type      = kehdr->e_type;
1777 	ehdr->e_machine   = kehdr->e_machine;
1778 	ehdr->e_version   = kehdr->e_version;
1779 	ehdr->e_entry     = 0;
1780 	ehdr->e_shoff     = 0;
1781 	ehdr->e_flags     = kehdr->e_flags;
1782 	ehdr->e_phnum     = count;
1783 	ehdr->e_shentsize = 0;
1784 	ehdr->e_shnum     = 0;
1785 	ehdr->e_shstrndx  = 0;
1786 
1787 	if (from->elfclass == ELFCLASS32) {
1788 		ehdr->e_phoff     = sizeof(Elf32_Ehdr);
1789 		ehdr->e_ehsize    = sizeof(Elf32_Ehdr);
1790 		ehdr->e_phentsize = sizeof(Elf32_Phdr);
1791 	} else {
1792 		ehdr->e_phoff     = sizeof(Elf64_Ehdr);
1793 		ehdr->e_ehsize    = sizeof(Elf64_Ehdr);
1794 		ehdr->e_phentsize = sizeof(Elf64_Phdr);
1795 	}
1796 
1797 	if (!gelf_update_ehdr(to->elf, ehdr))
1798 		return -1;
1799 
1800 	if (!gelf_newphdr(to->elf, count))
1801 		return -1;
1802 
1803 	return 0;
1804 }
1805 
1806 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
1807 			   u64 addr, u64 len)
1808 {
1809 	GElf_Phdr phdr = {
1810 		.p_type		= PT_LOAD,
1811 		.p_flags	= PF_R | PF_W | PF_X,
1812 		.p_offset	= offset,
1813 		.p_vaddr	= addr,
1814 		.p_paddr	= 0,
1815 		.p_filesz	= len,
1816 		.p_memsz	= len,
1817 		.p_align	= page_size,
1818 	};
1819 
1820 	if (!gelf_update_phdr(kcore->elf, idx, &phdr))
1821 		return -1;
1822 
1823 	return 0;
1824 }
1825 
1826 static off_t kcore__write(struct kcore *kcore)
1827 {
1828 	return elf_update(kcore->elf, ELF_C_WRITE);
1829 }
1830 
1831 struct phdr_data {
1832 	off_t offset;
1833 	off_t rel;
1834 	u64 addr;
1835 	u64 len;
1836 	struct list_head node;
1837 	struct phdr_data *remaps;
1838 };
1839 
1840 struct sym_data {
1841 	u64 addr;
1842 	struct list_head node;
1843 };
1844 
1845 struct kcore_copy_info {
1846 	u64 stext;
1847 	u64 etext;
1848 	u64 first_symbol;
1849 	u64 last_symbol;
1850 	u64 first_module;
1851 	u64 first_module_symbol;
1852 	u64 last_module_symbol;
1853 	size_t phnum;
1854 	struct list_head phdrs;
1855 	struct list_head syms;
1856 };
1857 
1858 #define kcore_copy__for_each_phdr(k, p) \
1859 	list_for_each_entry((p), &(k)->phdrs, node)
1860 
1861 static struct phdr_data *phdr_data__new(u64 addr, u64 len, off_t offset)
1862 {
1863 	struct phdr_data *p = zalloc(sizeof(*p));
1864 
1865 	if (p) {
1866 		p->addr   = addr;
1867 		p->len    = len;
1868 		p->offset = offset;
1869 	}
1870 
1871 	return p;
1872 }
1873 
1874 static struct phdr_data *kcore_copy_info__addnew(struct kcore_copy_info *kci,
1875 						 u64 addr, u64 len,
1876 						 off_t offset)
1877 {
1878 	struct phdr_data *p = phdr_data__new(addr, len, offset);
1879 
1880 	if (p)
1881 		list_add_tail(&p->node, &kci->phdrs);
1882 
1883 	return p;
1884 }
1885 
1886 static void kcore_copy__free_phdrs(struct kcore_copy_info *kci)
1887 {
1888 	struct phdr_data *p, *tmp;
1889 
1890 	list_for_each_entry_safe(p, tmp, &kci->phdrs, node) {
1891 		list_del_init(&p->node);
1892 		free(p);
1893 	}
1894 }
1895 
1896 static struct sym_data *kcore_copy__new_sym(struct kcore_copy_info *kci,
1897 					    u64 addr)
1898 {
1899 	struct sym_data *s = zalloc(sizeof(*s));
1900 
1901 	if (s) {
1902 		s->addr = addr;
1903 		list_add_tail(&s->node, &kci->syms);
1904 	}
1905 
1906 	return s;
1907 }
1908 
1909 static void kcore_copy__free_syms(struct kcore_copy_info *kci)
1910 {
1911 	struct sym_data *s, *tmp;
1912 
1913 	list_for_each_entry_safe(s, tmp, &kci->syms, node) {
1914 		list_del_init(&s->node);
1915 		free(s);
1916 	}
1917 }
1918 
1919 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
1920 					u64 start)
1921 {
1922 	struct kcore_copy_info *kci = arg;
1923 
1924 	if (!kallsyms__is_function(type))
1925 		return 0;
1926 
1927 	if (strchr(name, '[')) {
1928 		if (!kci->first_module_symbol || start < kci->first_module_symbol)
1929 			kci->first_module_symbol = start;
1930 		if (start > kci->last_module_symbol)
1931 			kci->last_module_symbol = start;
1932 		return 0;
1933 	}
1934 
1935 	if (!kci->first_symbol || start < kci->first_symbol)
1936 		kci->first_symbol = start;
1937 
1938 	if (!kci->last_symbol || start > kci->last_symbol)
1939 		kci->last_symbol = start;
1940 
1941 	if (!strcmp(name, "_stext")) {
1942 		kci->stext = start;
1943 		return 0;
1944 	}
1945 
1946 	if (!strcmp(name, "_etext")) {
1947 		kci->etext = start;
1948 		return 0;
1949 	}
1950 
1951 	if (is_entry_trampoline(name) && !kcore_copy__new_sym(kci, start))
1952 		return -1;
1953 
1954 	return 0;
1955 }
1956 
1957 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
1958 				      const char *dir)
1959 {
1960 	char kallsyms_filename[PATH_MAX];
1961 
1962 	scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
1963 
1964 	if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
1965 		return -1;
1966 
1967 	if (kallsyms__parse(kallsyms_filename, kci,
1968 			    kcore_copy__process_kallsyms) < 0)
1969 		return -1;
1970 
1971 	return 0;
1972 }
1973 
1974 static int kcore_copy__process_modules(void *arg,
1975 				       const char *name __maybe_unused,
1976 				       u64 start, u64 size __maybe_unused)
1977 {
1978 	struct kcore_copy_info *kci = arg;
1979 
1980 	if (!kci->first_module || start < kci->first_module)
1981 		kci->first_module = start;
1982 
1983 	return 0;
1984 }
1985 
1986 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
1987 				     const char *dir)
1988 {
1989 	char modules_filename[PATH_MAX];
1990 
1991 	scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
1992 
1993 	if (symbol__restricted_filename(modules_filename, "/proc/modules"))
1994 		return -1;
1995 
1996 	if (modules__parse(modules_filename, kci,
1997 			   kcore_copy__process_modules) < 0)
1998 		return -1;
1999 
2000 	return 0;
2001 }
2002 
2003 static int kcore_copy__map(struct kcore_copy_info *kci, u64 start, u64 end,
2004 			   u64 pgoff, u64 s, u64 e)
2005 {
2006 	u64 len, offset;
2007 
2008 	if (s < start || s >= end)
2009 		return 0;
2010 
2011 	offset = (s - start) + pgoff;
2012 	len = e < end ? e - s : end - s;
2013 
2014 	return kcore_copy_info__addnew(kci, s, len, offset) ? 0 : -1;
2015 }
2016 
2017 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
2018 {
2019 	struct kcore_copy_info *kci = data;
2020 	u64 end = start + len;
2021 	struct sym_data *sdat;
2022 
2023 	if (kcore_copy__map(kci, start, end, pgoff, kci->stext, kci->etext))
2024 		return -1;
2025 
2026 	if (kcore_copy__map(kci, start, end, pgoff, kci->first_module,
2027 			    kci->last_module_symbol))
2028 		return -1;
2029 
2030 	list_for_each_entry(sdat, &kci->syms, node) {
2031 		u64 s = round_down(sdat->addr, page_size);
2032 
2033 		if (kcore_copy__map(kci, start, end, pgoff, s, s + len))
2034 			return -1;
2035 	}
2036 
2037 	return 0;
2038 }
2039 
2040 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
2041 {
2042 	if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
2043 		return -1;
2044 
2045 	return 0;
2046 }
2047 
2048 static void kcore_copy__find_remaps(struct kcore_copy_info *kci)
2049 {
2050 	struct phdr_data *p, *k = NULL;
2051 	u64 kend;
2052 
2053 	if (!kci->stext)
2054 		return;
2055 
2056 	/* Find phdr that corresponds to the kernel map (contains stext) */
2057 	kcore_copy__for_each_phdr(kci, p) {
2058 		u64 pend = p->addr + p->len - 1;
2059 
2060 		if (p->addr <= kci->stext && pend >= kci->stext) {
2061 			k = p;
2062 			break;
2063 		}
2064 	}
2065 
2066 	if (!k)
2067 		return;
2068 
2069 	kend = k->offset + k->len;
2070 
2071 	/* Find phdrs that remap the kernel */
2072 	kcore_copy__for_each_phdr(kci, p) {
2073 		u64 pend = p->offset + p->len;
2074 
2075 		if (p == k)
2076 			continue;
2077 
2078 		if (p->offset >= k->offset && pend <= kend)
2079 			p->remaps = k;
2080 	}
2081 }
2082 
2083 static void kcore_copy__layout(struct kcore_copy_info *kci)
2084 {
2085 	struct phdr_data *p;
2086 	off_t rel = 0;
2087 
2088 	kcore_copy__find_remaps(kci);
2089 
2090 	kcore_copy__for_each_phdr(kci, p) {
2091 		if (!p->remaps) {
2092 			p->rel = rel;
2093 			rel += p->len;
2094 		}
2095 		kci->phnum += 1;
2096 	}
2097 
2098 	kcore_copy__for_each_phdr(kci, p) {
2099 		struct phdr_data *k = p->remaps;
2100 
2101 		if (k)
2102 			p->rel = p->offset - k->offset + k->rel;
2103 	}
2104 }
2105 
2106 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
2107 				 Elf *elf)
2108 {
2109 	if (kcore_copy__parse_kallsyms(kci, dir))
2110 		return -1;
2111 
2112 	if (kcore_copy__parse_modules(kci, dir))
2113 		return -1;
2114 
2115 	if (kci->stext)
2116 		kci->stext = round_down(kci->stext, page_size);
2117 	else
2118 		kci->stext = round_down(kci->first_symbol, page_size);
2119 
2120 	if (kci->etext) {
2121 		kci->etext = round_up(kci->etext, page_size);
2122 	} else if (kci->last_symbol) {
2123 		kci->etext = round_up(kci->last_symbol, page_size);
2124 		kci->etext += page_size;
2125 	}
2126 
2127 	if (kci->first_module_symbol &&
2128 	    (!kci->first_module || kci->first_module_symbol < kci->first_module))
2129 		kci->first_module = kci->first_module_symbol;
2130 
2131 	kci->first_module = round_down(kci->first_module, page_size);
2132 
2133 	if (kci->last_module_symbol) {
2134 		kci->last_module_symbol = round_up(kci->last_module_symbol,
2135 						   page_size);
2136 		kci->last_module_symbol += page_size;
2137 	}
2138 
2139 	if (!kci->stext || !kci->etext)
2140 		return -1;
2141 
2142 	if (kci->first_module && !kci->last_module_symbol)
2143 		return -1;
2144 
2145 	if (kcore_copy__read_maps(kci, elf))
2146 		return -1;
2147 
2148 	kcore_copy__layout(kci);
2149 
2150 	return 0;
2151 }
2152 
2153 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
2154 				 const char *name)
2155 {
2156 	char from_filename[PATH_MAX];
2157 	char to_filename[PATH_MAX];
2158 
2159 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2160 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2161 
2162 	return copyfile_mode(from_filename, to_filename, 0400);
2163 }
2164 
2165 static int kcore_copy__unlink(const char *dir, const char *name)
2166 {
2167 	char filename[PATH_MAX];
2168 
2169 	scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
2170 
2171 	return unlink(filename);
2172 }
2173 
2174 static int kcore_copy__compare_fds(int from, int to)
2175 {
2176 	char *buf_from;
2177 	char *buf_to;
2178 	ssize_t ret;
2179 	size_t len;
2180 	int err = -1;
2181 
2182 	buf_from = malloc(page_size);
2183 	buf_to = malloc(page_size);
2184 	if (!buf_from || !buf_to)
2185 		goto out;
2186 
2187 	while (1) {
2188 		/* Use read because mmap won't work on proc files */
2189 		ret = read(from, buf_from, page_size);
2190 		if (ret < 0)
2191 			goto out;
2192 
2193 		if (!ret)
2194 			break;
2195 
2196 		len = ret;
2197 
2198 		if (readn(to, buf_to, len) != (int)len)
2199 			goto out;
2200 
2201 		if (memcmp(buf_from, buf_to, len))
2202 			goto out;
2203 	}
2204 
2205 	err = 0;
2206 out:
2207 	free(buf_to);
2208 	free(buf_from);
2209 	return err;
2210 }
2211 
2212 static int kcore_copy__compare_files(const char *from_filename,
2213 				     const char *to_filename)
2214 {
2215 	int from, to, err = -1;
2216 
2217 	from = open(from_filename, O_RDONLY);
2218 	if (from < 0)
2219 		return -1;
2220 
2221 	to = open(to_filename, O_RDONLY);
2222 	if (to < 0)
2223 		goto out_close_from;
2224 
2225 	err = kcore_copy__compare_fds(from, to);
2226 
2227 	close(to);
2228 out_close_from:
2229 	close(from);
2230 	return err;
2231 }
2232 
2233 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
2234 				    const char *name)
2235 {
2236 	char from_filename[PATH_MAX];
2237 	char to_filename[PATH_MAX];
2238 
2239 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2240 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2241 
2242 	return kcore_copy__compare_files(from_filename, to_filename);
2243 }
2244 
2245 /**
2246  * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
2247  * @from_dir: from directory
2248  * @to_dir: to directory
2249  *
2250  * This function copies kallsyms, modules and kcore files from one directory to
2251  * another.  kallsyms and modules are copied entirely.  Only code segments are
2252  * copied from kcore.  It is assumed that two segments suffice: one for the
2253  * kernel proper and one for all the modules.  The code segments are determined
2254  * from kallsyms and modules files.  The kernel map starts at _stext or the
2255  * lowest function symbol, and ends at _etext or the highest function symbol.
2256  * The module map starts at the lowest module address and ends at the highest
2257  * module symbol.  Start addresses are rounded down to the nearest page.  End
2258  * addresses are rounded up to the nearest page.  An extra page is added to the
2259  * highest kernel symbol and highest module symbol to, hopefully, encompass that
2260  * symbol too.  Because it contains only code sections, the resulting kcore is
2261  * unusual.  One significant peculiarity is that the mapping (start -> pgoff)
2262  * is not the same for the kernel map and the modules map.  That happens because
2263  * the data is copied adjacently whereas the original kcore has gaps.  Finally,
2264  * kallsyms file is compared with its copy to check that modules have not been
2265  * loaded or unloaded while the copies were taking place.
2266  *
2267  * Return: %0 on success, %-1 on failure.
2268  */
2269 int kcore_copy(const char *from_dir, const char *to_dir)
2270 {
2271 	struct kcore kcore;
2272 	struct kcore extract;
2273 	int idx = 0, err = -1;
2274 	off_t offset, sz;
2275 	struct kcore_copy_info kci = { .stext = 0, };
2276 	char kcore_filename[PATH_MAX];
2277 	char extract_filename[PATH_MAX];
2278 	struct phdr_data *p;
2279 
2280 	INIT_LIST_HEAD(&kci.phdrs);
2281 	INIT_LIST_HEAD(&kci.syms);
2282 
2283 	if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
2284 		return -1;
2285 
2286 	if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
2287 		goto out_unlink_kallsyms;
2288 
2289 	scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
2290 	scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
2291 
2292 	if (kcore__open(&kcore, kcore_filename))
2293 		goto out_unlink_modules;
2294 
2295 	if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
2296 		goto out_kcore_close;
2297 
2298 	if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
2299 		goto out_kcore_close;
2300 
2301 	if (kcore__copy_hdr(&kcore, &extract, kci.phnum))
2302 		goto out_extract_close;
2303 
2304 	offset = gelf_fsize(extract.elf, ELF_T_EHDR, 1, EV_CURRENT) +
2305 		 gelf_fsize(extract.elf, ELF_T_PHDR, kci.phnum, EV_CURRENT);
2306 	offset = round_up(offset, page_size);
2307 
2308 	kcore_copy__for_each_phdr(&kci, p) {
2309 		off_t offs = p->rel + offset;
2310 
2311 		if (kcore__add_phdr(&extract, idx++, offs, p->addr, p->len))
2312 			goto out_extract_close;
2313 	}
2314 
2315 	sz = kcore__write(&extract);
2316 	if (sz < 0 || sz > offset)
2317 		goto out_extract_close;
2318 
2319 	kcore_copy__for_each_phdr(&kci, p) {
2320 		off_t offs = p->rel + offset;
2321 
2322 		if (p->remaps)
2323 			continue;
2324 		if (copy_bytes(kcore.fd, p->offset, extract.fd, offs, p->len))
2325 			goto out_extract_close;
2326 	}
2327 
2328 	if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
2329 		goto out_extract_close;
2330 
2331 	err = 0;
2332 
2333 out_extract_close:
2334 	kcore__close(&extract);
2335 	if (err)
2336 		unlink(extract_filename);
2337 out_kcore_close:
2338 	kcore__close(&kcore);
2339 out_unlink_modules:
2340 	if (err)
2341 		kcore_copy__unlink(to_dir, "modules");
2342 out_unlink_kallsyms:
2343 	if (err)
2344 		kcore_copy__unlink(to_dir, "kallsyms");
2345 
2346 	kcore_copy__free_phdrs(&kci);
2347 	kcore_copy__free_syms(&kci);
2348 
2349 	return err;
2350 }
2351 
2352 int kcore_extract__create(struct kcore_extract *kce)
2353 {
2354 	struct kcore kcore;
2355 	struct kcore extract;
2356 	size_t count = 1;
2357 	int idx = 0, err = -1;
2358 	off_t offset = page_size, sz;
2359 
2360 	if (kcore__open(&kcore, kce->kcore_filename))
2361 		return -1;
2362 
2363 	strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
2364 	if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
2365 		goto out_kcore_close;
2366 
2367 	if (kcore__copy_hdr(&kcore, &extract, count))
2368 		goto out_extract_close;
2369 
2370 	if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
2371 		goto out_extract_close;
2372 
2373 	sz = kcore__write(&extract);
2374 	if (sz < 0 || sz > offset)
2375 		goto out_extract_close;
2376 
2377 	if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
2378 		goto out_extract_close;
2379 
2380 	err = 0;
2381 
2382 out_extract_close:
2383 	kcore__close(&extract);
2384 	if (err)
2385 		unlink(kce->extract_filename);
2386 out_kcore_close:
2387 	kcore__close(&kcore);
2388 
2389 	return err;
2390 }
2391 
2392 void kcore_extract__delete(struct kcore_extract *kce)
2393 {
2394 	unlink(kce->extract_filename);
2395 }
2396 
2397 #ifdef HAVE_GELF_GETNOTE_SUPPORT
2398 
2399 static void sdt_adjust_loc(struct sdt_note *tmp, GElf_Addr base_off)
2400 {
2401 	if (!base_off)
2402 		return;
2403 
2404 	if (tmp->bit32)
2405 		tmp->addr.a32[SDT_NOTE_IDX_LOC] =
2406 			tmp->addr.a32[SDT_NOTE_IDX_LOC] + base_off -
2407 			tmp->addr.a32[SDT_NOTE_IDX_BASE];
2408 	else
2409 		tmp->addr.a64[SDT_NOTE_IDX_LOC] =
2410 			tmp->addr.a64[SDT_NOTE_IDX_LOC] + base_off -
2411 			tmp->addr.a64[SDT_NOTE_IDX_BASE];
2412 }
2413 
2414 static void sdt_adjust_refctr(struct sdt_note *tmp, GElf_Addr base_addr,
2415 			      GElf_Addr base_off)
2416 {
2417 	if (!base_off)
2418 		return;
2419 
2420 	if (tmp->bit32 && tmp->addr.a32[SDT_NOTE_IDX_REFCTR])
2421 		tmp->addr.a32[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2422 	else if (tmp->addr.a64[SDT_NOTE_IDX_REFCTR])
2423 		tmp->addr.a64[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2424 }
2425 
2426 /**
2427  * populate_sdt_note : Parse raw data and identify SDT note
2428  * @elf: elf of the opened file
2429  * @data: raw data of a section with description offset applied
2430  * @len: note description size
2431  * @type: type of the note
2432  * @sdt_notes: List to add the SDT note
2433  *
2434  * Responsible for parsing the @data in section .note.stapsdt in @elf and
2435  * if its an SDT note, it appends to @sdt_notes list.
2436  */
2437 static int populate_sdt_note(Elf **elf, const char *data, size_t len,
2438 			     struct list_head *sdt_notes)
2439 {
2440 	const char *provider, *name, *args;
2441 	struct sdt_note *tmp = NULL;
2442 	GElf_Ehdr ehdr;
2443 	GElf_Shdr shdr;
2444 	int ret = -EINVAL;
2445 
2446 	union {
2447 		Elf64_Addr a64[NR_ADDR];
2448 		Elf32_Addr a32[NR_ADDR];
2449 	} buf;
2450 
2451 	Elf_Data dst = {
2452 		.d_buf = &buf, .d_type = ELF_T_ADDR, .d_version = EV_CURRENT,
2453 		.d_size = gelf_fsize((*elf), ELF_T_ADDR, NR_ADDR, EV_CURRENT),
2454 		.d_off = 0, .d_align = 0
2455 	};
2456 	Elf_Data src = {
2457 		.d_buf = (void *) data, .d_type = ELF_T_ADDR,
2458 		.d_version = EV_CURRENT, .d_size = dst.d_size, .d_off = 0,
2459 		.d_align = 0
2460 	};
2461 
2462 	tmp = (struct sdt_note *)calloc(1, sizeof(struct sdt_note));
2463 	if (!tmp) {
2464 		ret = -ENOMEM;
2465 		goto out_err;
2466 	}
2467 
2468 	INIT_LIST_HEAD(&tmp->note_list);
2469 
2470 	if (len < dst.d_size + 3)
2471 		goto out_free_note;
2472 
2473 	/* Translation from file representation to memory representation */
2474 	if (gelf_xlatetom(*elf, &dst, &src,
2475 			  elf_getident(*elf, NULL)[EI_DATA]) == NULL) {
2476 		pr_err("gelf_xlatetom : %s\n", elf_errmsg(-1));
2477 		goto out_free_note;
2478 	}
2479 
2480 	/* Populate the fields of sdt_note */
2481 	provider = data + dst.d_size;
2482 
2483 	name = (const char *)memchr(provider, '\0', data + len - provider);
2484 	if (name++ == NULL)
2485 		goto out_free_note;
2486 
2487 	tmp->provider = strdup(provider);
2488 	if (!tmp->provider) {
2489 		ret = -ENOMEM;
2490 		goto out_free_note;
2491 	}
2492 	tmp->name = strdup(name);
2493 	if (!tmp->name) {
2494 		ret = -ENOMEM;
2495 		goto out_free_prov;
2496 	}
2497 
2498 	args = memchr(name, '\0', data + len - name);
2499 
2500 	/*
2501 	 * There is no argument if:
2502 	 * - We reached the end of the note;
2503 	 * - There is not enough room to hold a potential string;
2504 	 * - The argument string is empty or just contains ':'.
2505 	 */
2506 	if (args == NULL || data + len - args < 2 ||
2507 		args[1] == ':' || args[1] == '\0')
2508 		tmp->args = NULL;
2509 	else {
2510 		tmp->args = strdup(++args);
2511 		if (!tmp->args) {
2512 			ret = -ENOMEM;
2513 			goto out_free_name;
2514 		}
2515 	}
2516 
2517 	if (gelf_getclass(*elf) == ELFCLASS32) {
2518 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf32_Addr));
2519 		tmp->bit32 = true;
2520 	} else {
2521 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf64_Addr));
2522 		tmp->bit32 = false;
2523 	}
2524 
2525 	if (!gelf_getehdr(*elf, &ehdr)) {
2526 		pr_debug("%s : cannot get elf header.\n", __func__);
2527 		ret = -EBADF;
2528 		goto out_free_args;
2529 	}
2530 
2531 	/* Adjust the prelink effect :
2532 	 * Find out the .stapsdt.base section.
2533 	 * This scn will help us to handle prelinking (if present).
2534 	 * Compare the retrieved file offset of the base section with the
2535 	 * base address in the description of the SDT note. If its different,
2536 	 * then accordingly, adjust the note location.
2537 	 */
2538 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_BASE_SCN, NULL))
2539 		sdt_adjust_loc(tmp, shdr.sh_offset);
2540 
2541 	/* Adjust reference counter offset */
2542 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_PROBES_SCN, NULL))
2543 		sdt_adjust_refctr(tmp, shdr.sh_addr, shdr.sh_offset);
2544 
2545 	list_add_tail(&tmp->note_list, sdt_notes);
2546 	return 0;
2547 
2548 out_free_args:
2549 	zfree(&tmp->args);
2550 out_free_name:
2551 	zfree(&tmp->name);
2552 out_free_prov:
2553 	zfree(&tmp->provider);
2554 out_free_note:
2555 	free(tmp);
2556 out_err:
2557 	return ret;
2558 }
2559 
2560 /**
2561  * construct_sdt_notes_list : constructs a list of SDT notes
2562  * @elf : elf to look into
2563  * @sdt_notes : empty list_head
2564  *
2565  * Scans the sections in 'elf' for the section
2566  * .note.stapsdt. It, then calls populate_sdt_note to find
2567  * out the SDT events and populates the 'sdt_notes'.
2568  */
2569 static int construct_sdt_notes_list(Elf *elf, struct list_head *sdt_notes)
2570 {
2571 	GElf_Ehdr ehdr;
2572 	Elf_Scn *scn = NULL;
2573 	Elf_Data *data;
2574 	GElf_Shdr shdr;
2575 	size_t shstrndx, next;
2576 	GElf_Nhdr nhdr;
2577 	size_t name_off, desc_off, offset;
2578 	int ret = 0;
2579 
2580 	if (gelf_getehdr(elf, &ehdr) == NULL) {
2581 		ret = -EBADF;
2582 		goto out_ret;
2583 	}
2584 	if (elf_getshdrstrndx(elf, &shstrndx) != 0) {
2585 		ret = -EBADF;
2586 		goto out_ret;
2587 	}
2588 
2589 	/* Look for the required section */
2590 	scn = elf_section_by_name(elf, &ehdr, &shdr, SDT_NOTE_SCN, NULL);
2591 	if (!scn) {
2592 		ret = -ENOENT;
2593 		goto out_ret;
2594 	}
2595 
2596 	if ((shdr.sh_type != SHT_NOTE) || (shdr.sh_flags & SHF_ALLOC)) {
2597 		ret = -ENOENT;
2598 		goto out_ret;
2599 	}
2600 
2601 	data = elf_getdata(scn, NULL);
2602 
2603 	/* Get the SDT notes */
2604 	for (offset = 0; (next = gelf_getnote(data, offset, &nhdr, &name_off,
2605 					      &desc_off)) > 0; offset = next) {
2606 		if (nhdr.n_namesz == sizeof(SDT_NOTE_NAME) &&
2607 		    !memcmp(data->d_buf + name_off, SDT_NOTE_NAME,
2608 			    sizeof(SDT_NOTE_NAME))) {
2609 			/* Check the type of the note */
2610 			if (nhdr.n_type != SDT_NOTE_TYPE)
2611 				goto out_ret;
2612 
2613 			ret = populate_sdt_note(&elf, ((data->d_buf) + desc_off),
2614 						nhdr.n_descsz, sdt_notes);
2615 			if (ret < 0)
2616 				goto out_ret;
2617 		}
2618 	}
2619 	if (list_empty(sdt_notes))
2620 		ret = -ENOENT;
2621 
2622 out_ret:
2623 	return ret;
2624 }
2625 
2626 /**
2627  * get_sdt_note_list : Wrapper to construct a list of sdt notes
2628  * @head : empty list_head
2629  * @target : file to find SDT notes from
2630  *
2631  * This opens the file, initializes
2632  * the ELF and then calls construct_sdt_notes_list.
2633  */
2634 int get_sdt_note_list(struct list_head *head, const char *target)
2635 {
2636 	Elf *elf;
2637 	int fd, ret;
2638 
2639 	fd = open(target, O_RDONLY);
2640 	if (fd < 0)
2641 		return -EBADF;
2642 
2643 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
2644 	if (!elf) {
2645 		ret = -EBADF;
2646 		goto out_close;
2647 	}
2648 	ret = construct_sdt_notes_list(elf, head);
2649 	elf_end(elf);
2650 out_close:
2651 	close(fd);
2652 	return ret;
2653 }
2654 
2655 /**
2656  * cleanup_sdt_note_list : free the sdt notes' list
2657  * @sdt_notes: sdt notes' list
2658  *
2659  * Free up the SDT notes in @sdt_notes.
2660  * Returns the number of SDT notes free'd.
2661  */
2662 int cleanup_sdt_note_list(struct list_head *sdt_notes)
2663 {
2664 	struct sdt_note *tmp, *pos;
2665 	int nr_free = 0;
2666 
2667 	list_for_each_entry_safe(pos, tmp, sdt_notes, note_list) {
2668 		list_del_init(&pos->note_list);
2669 		zfree(&pos->args);
2670 		zfree(&pos->name);
2671 		zfree(&pos->provider);
2672 		free(pos);
2673 		nr_free++;
2674 	}
2675 	return nr_free;
2676 }
2677 
2678 /**
2679  * sdt_notes__get_count: Counts the number of sdt events
2680  * @start: list_head to sdt_notes list
2681  *
2682  * Returns the number of SDT notes in a list
2683  */
2684 int sdt_notes__get_count(struct list_head *start)
2685 {
2686 	struct sdt_note *sdt_ptr;
2687 	int count = 0;
2688 
2689 	list_for_each_entry(sdt_ptr, start, note_list)
2690 		count++;
2691 	return count;
2692 }
2693 #endif
2694 
2695 void symbol__elf_init(void)
2696 {
2697 	elf_version(EV_CURRENT);
2698 }
2699