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