xref: /linux/tools/perf/util/symbol-elf.c (revision d5312a7ef79f5de574bce7b140ea1e48ce7e9262)
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 = NOTE_ALIGN(nhdr->n_namesz),
839 		       descsz = NOTE_ALIGN(nhdr->n_descsz);
840 		const char *name;
841 
842 		ptr += sizeof(*nhdr);
843 		name = ptr;
844 		ptr += namesz;
845 		if (nhdr->n_type == NT_GNU_BUILD_ID &&
846 		    nhdr->n_namesz == sizeof("GNU")) {
847 			if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
848 				size_t sz = min(size, descsz);
849 				memcpy(bf, ptr, sz);
850 				memset(bf + sz, 0, size - sz);
851 				err = sz;
852 				break;
853 			}
854 		}
855 		ptr += descsz;
856 	}
857 
858 out:
859 	return err;
860 }
861 
862 static int read_build_id(const char *filename, struct build_id *bid)
863 {
864 	size_t size = sizeof(bid->data);
865 	int fd, err;
866 	Elf *elf;
867 
868 	err = libbfd__read_build_id(filename, bid);
869 	if (err >= 0)
870 		goto out;
871 
872 	if (size < BUILD_ID_SIZE)
873 		goto out;
874 
875 	fd = open(filename, O_RDONLY | O_CLOEXEC);
876 	if (fd < 0)
877 		goto out;
878 
879 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
880 	if (elf == NULL) {
881 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
882 		goto out_close;
883 	}
884 
885 	err = elf_read_build_id(elf, bid->data, size);
886 	if (err > 0)
887 		bid->size = err;
888 
889 	elf_end(elf);
890 out_close:
891 	close(fd);
892 out:
893 	return err;
894 }
895 
896 int filename__read_build_id(const char *filename, struct build_id *bid)
897 {
898 	struct kmod_path m = { .name = NULL, };
899 	char path[PATH_MAX];
900 	int err;
901 
902 	if (!filename)
903 		return -EFAULT;
904 
905 	errno = 0;
906 	if (!is_regular_file(filename))
907 		return errno == 0 ? -EWOULDBLOCK : -errno;
908 
909 	err = kmod_path__parse(&m, filename);
910 	if (err)
911 		return -1;
912 
913 	if (m.comp) {
914 		int error = 0, fd;
915 
916 		fd = filename__decompress(filename, path, sizeof(path), m.comp, &error);
917 		if (fd < 0) {
918 			pr_debug("Failed to decompress (error %d) %s\n",
919 				 error, filename);
920 			return -1;
921 		}
922 		close(fd);
923 		filename = path;
924 	}
925 
926 	err = read_build_id(filename, bid);
927 
928 	if (m.comp)
929 		unlink(filename);
930 	return err;
931 }
932 
933 int sysfs__read_build_id(const char *filename, struct build_id *bid)
934 {
935 	size_t size = sizeof(bid->data);
936 	int fd, err = -1;
937 
938 	fd = open(filename, O_RDONLY | O_CLOEXEC);
939 	if (fd < 0)
940 		goto out;
941 
942 	while (1) {
943 		char bf[BUFSIZ];
944 		GElf_Nhdr nhdr;
945 		size_t namesz, descsz;
946 
947 		if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
948 			break;
949 
950 		namesz = NOTE_ALIGN(nhdr.n_namesz);
951 		descsz = NOTE_ALIGN(nhdr.n_descsz);
952 		if (nhdr.n_type == NT_GNU_BUILD_ID &&
953 		    nhdr.n_namesz == sizeof("GNU")) {
954 			if (read(fd, bf, namesz) != (ssize_t)namesz)
955 				break;
956 			if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
957 				size_t sz = min(descsz, size);
958 				if (read(fd, bid->data, sz) == (ssize_t)sz) {
959 					memset(bid->data + sz, 0, size - sz);
960 					bid->size = sz;
961 					err = 0;
962 					break;
963 				}
964 			} else if (read(fd, bf, descsz) != (ssize_t)descsz)
965 				break;
966 		} else {
967 			int n = namesz + descsz;
968 
969 			if (n > (int)sizeof(bf)) {
970 				n = sizeof(bf);
971 				pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
972 					 __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
973 			}
974 			if (read(fd, bf, n) != n)
975 				break;
976 		}
977 	}
978 	close(fd);
979 out:
980 	return err;
981 }
982 
983 int filename__read_debuglink(const char *filename, char *debuglink,
984 			     size_t size)
985 {
986 	int fd, err = -1;
987 	Elf *elf;
988 	GElf_Ehdr ehdr;
989 	GElf_Shdr shdr;
990 	Elf_Data *data;
991 	Elf_Scn *sec;
992 	Elf_Kind ek;
993 
994 	err = libbfd_filename__read_debuglink(filename, debuglink, size);
995 	if (err >= 0)
996 		goto out;
997 
998 	fd = open(filename, O_RDONLY | O_CLOEXEC);
999 	if (fd < 0)
1000 		goto out;
1001 
1002 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1003 	if (elf == NULL) {
1004 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
1005 		goto out_close;
1006 	}
1007 
1008 	ek = elf_kind(elf);
1009 	if (ek != ELF_K_ELF)
1010 		goto out_elf_end;
1011 
1012 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1013 		pr_err("%s: cannot get elf header.\n", __func__);
1014 		goto out_elf_end;
1015 	}
1016 
1017 	sec = elf_section_by_name(elf, &ehdr, &shdr,
1018 				  ".gnu_debuglink", NULL);
1019 	if (sec == NULL)
1020 		goto out_elf_end;
1021 
1022 	data = elf_getdata(sec, NULL);
1023 	if (data == NULL)
1024 		goto out_elf_end;
1025 
1026 	/* the start of this section is a zero-terminated string */
1027 	strncpy(debuglink, data->d_buf, size);
1028 
1029 	err = 0;
1030 
1031 out_elf_end:
1032 	elf_end(elf);
1033 out_close:
1034 	close(fd);
1035 out:
1036 	return err;
1037 }
1038 
1039 bool symsrc__possibly_runtime(struct symsrc *ss)
1040 {
1041 	return ss->dynsym || ss->opdsec;
1042 }
1043 
1044 bool symsrc__has_symtab(struct symsrc *ss)
1045 {
1046 	return ss->symtab != NULL;
1047 }
1048 
1049 void symsrc__destroy(struct symsrc *ss)
1050 {
1051 	zfree(&ss->name);
1052 	elf_end(ss->elf);
1053 	close(ss->fd);
1054 }
1055 
1056 static bool elf__needs_adjust_symbols(const GElf_Ehdr *ehdr)
1057 {
1058 	/*
1059 	 * Usually vmlinux is an ELF file with type ET_EXEC for most
1060 	 * architectures; except Arm64 kernel is linked with option
1061 	 * '-share', so need to check type ET_DYN.
1062 	 */
1063 	return ehdr->e_type == ET_EXEC || ehdr->e_type == ET_REL ||
1064 	       ehdr->e_type == ET_DYN;
1065 }
1066 
1067 static Elf *read_gnu_debugdata(struct dso *dso, Elf *elf, const char *name, int *fd_ret)
1068 {
1069 	Elf *elf_embedded;
1070 	GElf_Ehdr ehdr;
1071 	GElf_Shdr shdr;
1072 	Elf_Scn *scn;
1073 	Elf_Data *scn_data;
1074 	FILE *wrapped;
1075 	size_t shndx;
1076 	char temp_filename[] = "/tmp/perf.gnu_debugdata.elf.XXXXXX";
1077 	int ret, temp_fd;
1078 
1079 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1080 		pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1081 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1082 		return NULL;
1083 	}
1084 
1085 	scn = elf_section_by_name(elf, &ehdr, &shdr, ".gnu_debugdata", &shndx);
1086 	if (!scn) {
1087 		*dso__load_errno(dso) = -ENOENT;
1088 		return NULL;
1089 	}
1090 
1091 	if (shdr.sh_type == SHT_NOBITS) {
1092 		pr_debug("%s: .gnu_debugdata of ELF file %s has no data.\n", __func__, name);
1093 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1094 		return NULL;
1095 	}
1096 
1097 	scn_data = elf_rawdata(scn, NULL);
1098 	if (!scn_data) {
1099 		pr_debug("%s: error reading .gnu_debugdata of %s: %s\n", __func__,
1100 			 name, elf_errmsg(-1));
1101 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1102 		return NULL;
1103 	}
1104 
1105 	wrapped = fmemopen(scn_data->d_buf, scn_data->d_size, "r");
1106 	if (!wrapped) {
1107 		pr_debug("%s: fmemopen: %m\n", __func__);
1108 		*dso__load_errno(dso) = -errno;
1109 		return NULL;
1110 	}
1111 
1112 	temp_fd = mkstemp(temp_filename);
1113 	if (temp_fd < 0) {
1114 		pr_debug("%s: mkstemp: %m\n", __func__);
1115 		*dso__load_errno(dso) = -errno;
1116 		fclose(wrapped);
1117 		return NULL;
1118 	}
1119 	unlink(temp_filename);
1120 
1121 	ret = lzma_decompress_stream_to_file(wrapped, temp_fd);
1122 	fclose(wrapped);
1123 	if (ret < 0) {
1124 		*dso__load_errno(dso) = -errno;
1125 		close(temp_fd);
1126 		return NULL;
1127 	}
1128 
1129 	elf_embedded = elf_begin(temp_fd, PERF_ELF_C_READ_MMAP, NULL);
1130 	if (!elf_embedded) {
1131 		pr_debug("%s: error reading .gnu_debugdata of %s: %s\n", __func__,
1132 			 name, elf_errmsg(-1));
1133 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1134 		close(temp_fd);
1135 		return NULL;
1136 	}
1137 	pr_debug("%s: using .gnu_debugdata of %s\n", __func__, name);
1138 	*fd_ret = temp_fd;
1139 	return elf_embedded;
1140 }
1141 
1142 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
1143 		 enum dso_binary_type type)
1144 {
1145 	GElf_Ehdr ehdr;
1146 	Elf *elf;
1147 	int fd;
1148 
1149 	if (dso__needs_decompress(dso)) {
1150 		fd = dso__decompress_kmodule_fd(dso, name);
1151 		if (fd < 0)
1152 			return -1;
1153 
1154 		type = dso__symtab_type(dso);
1155 	} else {
1156 		fd = open(name, O_RDONLY | O_CLOEXEC);
1157 		if (fd < 0) {
1158 			*dso__load_errno(dso) = errno;
1159 			return -1;
1160 		}
1161 	}
1162 
1163 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1164 	if (elf == NULL) {
1165 		pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1166 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1167 		goto out_close;
1168 	}
1169 
1170 	if (type == DSO_BINARY_TYPE__GNU_DEBUGDATA) {
1171 		int new_fd;
1172 		Elf *embedded = read_gnu_debugdata(dso, elf, name, &new_fd);
1173 
1174 		if (!embedded)
1175 			goto out_elf_end;
1176 
1177 		elf_end(elf);
1178 		close(fd);
1179 		fd = new_fd;
1180 		elf = embedded;
1181 	}
1182 
1183 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1184 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1185 		pr_debug("%s: cannot get elf header.\n", __func__);
1186 		goto out_elf_end;
1187 	}
1188 
1189 	if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
1190 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INTERNAL_ERROR;
1191 		goto out_elf_end;
1192 	}
1193 
1194 	/* Always reject images with a mismatched build-id: */
1195 	if (dso__has_build_id(dso) && !symbol_conf.ignore_vmlinux_buildid) {
1196 		u8 build_id[BUILD_ID_SIZE];
1197 		struct build_id bid;
1198 		int size;
1199 
1200 		size = elf_read_build_id(elf, build_id, BUILD_ID_SIZE);
1201 		if (size <= 0) {
1202 			*dso__load_errno(dso) = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
1203 			goto out_elf_end;
1204 		}
1205 
1206 		build_id__init(&bid, build_id, size);
1207 		if (!dso__build_id_equal(dso, &bid)) {
1208 			pr_debug("%s: build id mismatch for %s.\n", __func__, name);
1209 			*dso__load_errno(dso) = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
1210 			goto out_elf_end;
1211 		}
1212 	}
1213 
1214 	ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1215 
1216 	ss->symtab_idx = 0;
1217 	ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
1218 			&ss->symtab_idx);
1219 	if (ss->symshdr.sh_type != SHT_SYMTAB)
1220 		ss->symtab = NULL;
1221 
1222 	ss->dynsym_idx = 0;
1223 	ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
1224 			&ss->dynsym_idx);
1225 	if (ss->dynshdr.sh_type != SHT_DYNSYM)
1226 		ss->dynsym = NULL;
1227 
1228 	ss->opdidx = 0;
1229 	ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
1230 			&ss->opdidx);
1231 	if (ss->opdshdr.sh_type != SHT_PROGBITS)
1232 		ss->opdsec = NULL;
1233 
1234 	if (dso__kernel(dso) == DSO_SPACE__USER)
1235 		ss->adjust_symbols = true;
1236 	else
1237 		ss->adjust_symbols = elf__needs_adjust_symbols(&ehdr);
1238 
1239 	ss->name   = strdup(name);
1240 	if (!ss->name) {
1241 		*dso__load_errno(dso) = errno;
1242 		goto out_elf_end;
1243 	}
1244 
1245 	ss->elf    = elf;
1246 	ss->fd     = fd;
1247 	ss->ehdr   = ehdr;
1248 	ss->type   = type;
1249 
1250 	return 0;
1251 
1252 out_elf_end:
1253 	elf_end(elf);
1254 out_close:
1255 	close(fd);
1256 	return -1;
1257 }
1258 
1259 static bool is_exe_text(int flags)
1260 {
1261 	return (flags & (SHF_ALLOC | SHF_EXECINSTR)) == (SHF_ALLOC | SHF_EXECINSTR);
1262 }
1263 
1264 /*
1265  * Some executable module sections like .noinstr.text might be laid out with
1266  * .text so they can use the same mapping (memory address to file offset).
1267  * Check if that is the case. Refer to kernel layout_sections(). Return the
1268  * maximum offset.
1269  */
1270 static u64 max_text_section(Elf *elf, GElf_Ehdr *ehdr)
1271 {
1272 	Elf_Scn *sec = NULL;
1273 	GElf_Shdr shdr;
1274 	u64 offs = 0;
1275 
1276 	/* Doesn't work for some arch */
1277 	if (ehdr->e_machine == EM_PARISC ||
1278 	    ehdr->e_machine == EM_ALPHA)
1279 		return 0;
1280 
1281 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1282 	if (!elf_rawdata(elf_getscn(elf, ehdr->e_shstrndx), NULL))
1283 		return 0;
1284 
1285 	while ((sec = elf_nextscn(elf, sec)) != NULL) {
1286 		char *sec_name;
1287 
1288 		if (!gelf_getshdr(sec, &shdr))
1289 			break;
1290 
1291 		if (!is_exe_text(shdr.sh_flags))
1292 			continue;
1293 
1294 		/* .init and .exit sections are not placed with .text */
1295 		sec_name = elf_strptr(elf, ehdr->e_shstrndx, shdr.sh_name);
1296 		if (!sec_name ||
1297 		    strstarts(sec_name, ".init") ||
1298 		    strstarts(sec_name, ".exit"))
1299 			break;
1300 
1301 		/* Must be next to previous, assumes .text is first */
1302 		if (offs && PERF_ALIGN(offs, shdr.sh_addralign ?: 1) != shdr.sh_offset)
1303 			break;
1304 
1305 		offs = shdr.sh_offset + shdr.sh_size;
1306 	}
1307 
1308 	return offs;
1309 }
1310 
1311 /**
1312  * ref_reloc_sym_not_found - has kernel relocation symbol been found.
1313  * @kmap: kernel maps and relocation reference symbol
1314  *
1315  * This function returns %true if we are dealing with the kernel maps and the
1316  * relocation reference symbol has not yet been found.  Otherwise %false is
1317  * returned.
1318  */
1319 static bool ref_reloc_sym_not_found(struct kmap *kmap)
1320 {
1321 	return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
1322 	       !kmap->ref_reloc_sym->unrelocated_addr;
1323 }
1324 
1325 /**
1326  * ref_reloc - kernel relocation offset.
1327  * @kmap: kernel maps and relocation reference symbol
1328  *
1329  * This function returns the offset of kernel addresses as determined by using
1330  * the relocation reference symbol i.e. if the kernel has not been relocated
1331  * then the return value is zero.
1332  */
1333 static u64 ref_reloc(struct kmap *kmap)
1334 {
1335 	if (kmap && kmap->ref_reloc_sym &&
1336 	    kmap->ref_reloc_sym->unrelocated_addr)
1337 		return kmap->ref_reloc_sym->addr -
1338 		       kmap->ref_reloc_sym->unrelocated_addr;
1339 	return 0;
1340 }
1341 
1342 void __weak arch__sym_update(struct symbol *s __maybe_unused,
1343 		GElf_Sym *sym __maybe_unused) { }
1344 
1345 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
1346 				      GElf_Sym *sym, GElf_Shdr *shdr,
1347 				      struct maps *kmaps, struct kmap *kmap,
1348 				      struct dso **curr_dsop,
1349 				      const char *section_name,
1350 				      bool adjust_kernel_syms, bool kmodule, bool *remap_kernel,
1351 				      u64 max_text_sh_offset)
1352 {
1353 	struct dso *curr_dso = *curr_dsop;
1354 	struct map *curr_map;
1355 	char dso_name[PATH_MAX];
1356 
1357 	/* Adjust symbol to map to file offset */
1358 	if (adjust_kernel_syms) {
1359 		if (dso__rel(dso))
1360 			sym->st_value += shdr->sh_offset;
1361 		else
1362 			sym->st_value -= shdr->sh_addr - shdr->sh_offset;
1363 	}
1364 
1365 	if (strcmp(section_name, (dso__short_name(curr_dso) + dso__short_name_len(dso))) == 0)
1366 		return 0;
1367 
1368 	if (strcmp(section_name, ".text") == 0) {
1369 		/*
1370 		 * The initial kernel mapping is based on
1371 		 * kallsyms and identity maps.  Overwrite it to
1372 		 * map to the kernel dso.
1373 		 */
1374 		if (*remap_kernel && dso__kernel(dso) && !kmodule) {
1375 			*remap_kernel = false;
1376 			map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
1377 			map__set_end(map, map__start(map) + shdr->sh_size);
1378 			map__set_pgoff(map, shdr->sh_offset);
1379 			map__set_mapping_type(map, MAPPING_TYPE__DSO);
1380 			/* Ensure maps are correctly ordered */
1381 			if (kmaps) {
1382 				int err;
1383 				struct map *tmp = map__get(map);
1384 
1385 				maps__remove(kmaps, map);
1386 				err = maps__insert(kmaps, map);
1387 				map__put(tmp);
1388 				if (err)
1389 					return err;
1390 			}
1391 		}
1392 
1393 		/*
1394 		 * The initial module mapping is based on
1395 		 * /proc/modules mapped to offset zero.
1396 		 * Overwrite it to map to the module dso.
1397 		 */
1398 		if (*remap_kernel && kmodule) {
1399 			*remap_kernel = false;
1400 			map__set_pgoff(map, shdr->sh_offset);
1401 		}
1402 
1403 		dso__put(*curr_dsop);
1404 		*curr_dsop = dso__get(dso);
1405 		return 0;
1406 	}
1407 
1408 	if (!kmap)
1409 		return 0;
1410 
1411 	/*
1412 	 * perf does not record module section addresses except for .text, but
1413 	 * some sections can use the same mapping as .text.
1414 	 */
1415 	if (kmodule && adjust_kernel_syms && is_exe_text(shdr->sh_flags) &&
1416 	    shdr->sh_offset <= max_text_sh_offset) {
1417 		dso__put(*curr_dsop);
1418 		*curr_dsop = dso__get(dso);
1419 		return 0;
1420 	}
1421 
1422 	snprintf(dso_name, sizeof(dso_name), "%s%s", dso__short_name(dso), section_name);
1423 
1424 	curr_map = maps__find_by_name(kmaps, dso_name);
1425 	if (curr_map == NULL) {
1426 		u64 start = sym->st_value;
1427 
1428 		if (kmodule)
1429 			start += map__start(map) + shdr->sh_offset;
1430 
1431 		curr_dso = dso__new(dso_name);
1432 		if (curr_dso == NULL)
1433 			return -1;
1434 		dso__set_kernel(curr_dso, dso__kernel(dso));
1435 		RC_CHK_ACCESS(curr_dso)->long_name = dso__long_name(dso);
1436 		RC_CHK_ACCESS(curr_dso)->long_name_len = dso__long_name_len(dso);
1437 		dso__set_binary_type(curr_dso, dso__binary_type(dso));
1438 		dso__set_adjust_symbols(curr_dso, dso__adjust_symbols(dso));
1439 		curr_map = map__new2(start, curr_dso);
1440 		if (curr_map == NULL) {
1441 			dso__put(curr_dso);
1442 			return -1;
1443 		}
1444 		if (dso__kernel(curr_dso))
1445 			map__kmap(curr_map)->kmaps = kmaps;
1446 
1447 		if (adjust_kernel_syms) {
1448 			map__set_start(curr_map, shdr->sh_addr + ref_reloc(kmap));
1449 			map__set_end(curr_map, map__start(curr_map) + shdr->sh_size);
1450 			map__set_pgoff(curr_map, shdr->sh_offset);
1451 		} else {
1452 			map__set_mapping_type(curr_map, MAPPING_TYPE__IDENTITY);
1453 		}
1454 		dso__set_symtab_type(curr_dso, dso__symtab_type(dso));
1455 		if (maps__insert(kmaps, curr_map)) {
1456 			dso__put(curr_dso);
1457 			map__put(curr_map);
1458 			return -1;
1459 		}
1460 		dsos__add(&maps__machine(kmaps)->dsos, curr_dso);
1461 		dso__set_loaded(curr_dso);
1462 		dso__put(*curr_dsop);
1463 		*curr_dsop = curr_dso;
1464 	} else {
1465 		dso__put(*curr_dsop);
1466 		*curr_dsop = dso__get(map__dso(curr_map));
1467 	}
1468 	map__put(curr_map);
1469 
1470 	return 0;
1471 }
1472 
1473 static int
1474 dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1475 		       struct symsrc *runtime_ss, int kmodule, int dynsym)
1476 {
1477 	struct kmap *kmap = dso__kernel(dso) ? map__kmap(map) : NULL;
1478 	struct maps *kmaps = kmap ? map__kmaps(map) : NULL;
1479 	struct dso *curr_dso = NULL;
1480 	Elf_Data *symstrs, *secstrs, *secstrs_run, *secstrs_sym;
1481 	uint32_t nr_syms;
1482 	uint32_t idx;
1483 	GElf_Ehdr ehdr;
1484 	GElf_Shdr shdr;
1485 	GElf_Shdr tshdr;
1486 	Elf_Data *syms, *opddata = NULL;
1487 	GElf_Sym sym;
1488 	Elf_Scn *sec, *sec_strndx;
1489 	Elf *elf;
1490 	int nr = 0;
1491 	bool remap_kernel = false, adjust_kernel_syms = false;
1492 	u64 max_text_sh_offset = 0;
1493 
1494 	if (kmap && !kmaps)
1495 		return -1;
1496 
1497 	elf = syms_ss->elf;
1498 	ehdr = syms_ss->ehdr;
1499 	if (dynsym) {
1500 		sec  = syms_ss->dynsym;
1501 		shdr = syms_ss->dynshdr;
1502 	} else {
1503 		sec =  syms_ss->symtab;
1504 		shdr = syms_ss->symshdr;
1505 	}
1506 
1507 	if (elf_section_by_name(runtime_ss->elf, &runtime_ss->ehdr, &tshdr,
1508 				".text", NULL)) {
1509 		dso__set_text_offset(dso, tshdr.sh_addr - tshdr.sh_offset);
1510 		dso__set_text_end(dso, tshdr.sh_offset + tshdr.sh_size);
1511 	}
1512 
1513 	if (runtime_ss->opdsec)
1514 		opddata = elf_rawdata(runtime_ss->opdsec, NULL);
1515 
1516 	syms = elf_getdata(sec, NULL);
1517 	if (syms == NULL)
1518 		goto out_elf_end;
1519 
1520 	sec = elf_getscn(elf, shdr.sh_link);
1521 	if (sec == NULL)
1522 		goto out_elf_end;
1523 
1524 	symstrs = elf_getdata(sec, NULL);
1525 	if (symstrs == NULL)
1526 		goto out_elf_end;
1527 
1528 	sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
1529 	if (sec_strndx == NULL)
1530 		goto out_elf_end;
1531 
1532 	secstrs_run = elf_getdata(sec_strndx, NULL);
1533 	if (secstrs_run == NULL)
1534 		goto out_elf_end;
1535 
1536 	sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
1537 	if (sec_strndx == NULL)
1538 		goto out_elf_end;
1539 
1540 	secstrs_sym = elf_getdata(sec_strndx, NULL);
1541 	if (secstrs_sym == NULL)
1542 		goto out_elf_end;
1543 
1544 	nr_syms = shdr.sh_size / shdr.sh_entsize;
1545 
1546 	memset(&sym, 0, sizeof(sym));
1547 
1548 	/*
1549 	 * The kernel relocation symbol is needed in advance in order to adjust
1550 	 * kernel maps correctly.
1551 	 */
1552 	if (ref_reloc_sym_not_found(kmap)) {
1553 		elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1554 			const char *elf_name = elf_sym__name(&sym, symstrs);
1555 
1556 			if (strcmp(elf_name, kmap->ref_reloc_sym->name))
1557 				continue;
1558 			kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
1559 			map__set_reloc(map, kmap->ref_reloc_sym->addr - kmap->ref_reloc_sym->unrelocated_addr);
1560 			break;
1561 		}
1562 	}
1563 
1564 	/*
1565 	 * Handle any relocation of vdso necessary because older kernels
1566 	 * attempted to prelink vdso to its virtual address.
1567 	 */
1568 	if (dso__is_vdso(dso))
1569 		map__set_reloc(map, map__start(map) - dso__text_offset(dso));
1570 
1571 	dso__set_adjust_symbols(dso, runtime_ss->adjust_symbols || ref_reloc(kmap));
1572 	/*
1573 	 * Initial kernel and module mappings do not map to the dso.
1574 	 * Flag the fixups.
1575 	 */
1576 	if (dso__kernel(dso)) {
1577 		remap_kernel = true;
1578 		adjust_kernel_syms = dso__adjust_symbols(dso);
1579 	}
1580 
1581 	if (kmodule && adjust_kernel_syms)
1582 		max_text_sh_offset = max_text_section(runtime_ss->elf, &runtime_ss->ehdr);
1583 
1584 	curr_dso = dso__get(dso);
1585 	elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1586 		struct symbol *f;
1587 		const char *elf_name = elf_sym__name(&sym, symstrs);
1588 		char *demangled = NULL;
1589 		int is_label = elf_sym__is_label(&sym);
1590 		const char *section_name;
1591 		bool used_opd = false;
1592 
1593 		if (!is_label && !elf_sym__filter(&sym))
1594 			continue;
1595 
1596 		/*
1597 		 * Reject ARM ELF "mapping symbols": these aren't unique and
1598 		 * don't identify functions, so will confuse the profile
1599 		 * output:
1600 		 */
1601 		if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
1602 			if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
1603 			    && (elf_name[2] == '\0' || elf_name[2] == '.'))
1604 				continue;
1605 		}
1606 
1607 		/* Reject RISCV ELF "mapping symbols" */
1608 		if (ehdr.e_machine == EM_RISCV) {
1609 			if (elf_name[0] == '$' && strchr("dx", elf_name[1]))
1610 				continue;
1611 		}
1612 
1613 		/* Reject kernel mapping symbols for kernel DSOs only */
1614 		if (dso__kernel(dso) && is_ignored_kernel_symbol(elf_name))
1615 			continue;
1616 
1617 		if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
1618 			u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
1619 			u64 *opd = opddata->d_buf + offset;
1620 			sym.st_value = DSO__SWAP(dso, u64, *opd);
1621 			sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
1622 					sym.st_value);
1623 			used_opd = true;
1624 		}
1625 
1626 		/*
1627 		 * When loading symbols in a data mapping, ABS symbols (which
1628 		 * has a value of SHN_ABS in its st_shndx) failed at
1629 		 * elf_getscn().  And it marks the loading as a failure so
1630 		 * already loaded symbols cannot be fixed up.
1631 		 *
1632 		 * I'm not sure what should be done. Just ignore them for now.
1633 		 * - Namhyung Kim
1634 		 */
1635 		if (sym.st_shndx == SHN_ABS)
1636 			continue;
1637 
1638 		sec = elf_getscn(syms_ss->elf, sym.st_shndx);
1639 		if (!sec)
1640 			goto out_elf_end;
1641 
1642 		gelf_getshdr(sec, &shdr);
1643 
1644 		/*
1645 		 * If the attribute bit SHF_ALLOC is not set, the section
1646 		 * doesn't occupy memory during process execution.
1647 		 * E.g. ".gnu.warning.*" section is used by linker to generate
1648 		 * warnings when calling deprecated functions, the symbols in
1649 		 * the section aren't loaded to memory during process execution,
1650 		 * so skip them.
1651 		 */
1652 		if (!(shdr.sh_flags & SHF_ALLOC))
1653 			continue;
1654 
1655 		secstrs = secstrs_sym;
1656 
1657 		/*
1658 		 * We have to fallback to runtime when syms' section header has
1659 		 * NOBITS set. NOBITS results in file offset (sh_offset) not
1660 		 * being incremented. So sh_offset used below has different
1661 		 * values for syms (invalid) and runtime (valid).
1662 		 */
1663 		if (shdr.sh_type == SHT_NOBITS) {
1664 			sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
1665 			if (!sec)
1666 				goto out_elf_end;
1667 
1668 			gelf_getshdr(sec, &shdr);
1669 			secstrs = secstrs_run;
1670 		}
1671 
1672 		if (is_label && !elf_sec__filter(&shdr, secstrs))
1673 			continue;
1674 
1675 		section_name = elf_sec__name(&shdr, secstrs);
1676 
1677 		/* On ARM, symbols for thumb functions have 1 added to
1678 		 * the symbol address as a flag - remove it */
1679 		if ((ehdr.e_machine == EM_ARM) &&
1680 		    (GELF_ST_TYPE(sym.st_info) == STT_FUNC) &&
1681 		    (sym.st_value & 1))
1682 			--sym.st_value;
1683 
1684 		if (dso__kernel(dso)) {
1685 			if (dso__process_kernel_symbol(dso, map, &sym, &shdr,
1686 						       kmaps, kmap, &curr_dso,
1687 						       section_name,
1688 						       adjust_kernel_syms,
1689 						       kmodule,
1690 						       &remap_kernel,
1691 						       max_text_sh_offset))
1692 				goto out_elf_end;
1693 		} else if ((used_opd && runtime_ss->adjust_symbols) ||
1694 			   (!used_opd && syms_ss->adjust_symbols)) {
1695 			GElf_Phdr phdr;
1696 
1697 			if (elf_read_program_header(runtime_ss->elf,
1698 						    (u64)sym.st_value, &phdr)) {
1699 				pr_debug4("%s: failed to find program header for "
1700 					   "symbol: %s st_value: %#" PRIx64 "\n",
1701 					   __func__, elf_name, (u64)sym.st_value);
1702 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1703 					"sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n",
1704 					__func__, (u64)sym.st_value, (u64)shdr.sh_addr,
1705 					(u64)shdr.sh_offset);
1706 				/*
1707 				 * Fail to find program header, let's rollback
1708 				 * to use shdr.sh_addr and shdr.sh_offset to
1709 				 * calibrate symbol's file address, though this
1710 				 * is not necessary for normal C ELF file, we
1711 				 * still need to handle java JIT symbols in this
1712 				 * case.
1713 				 */
1714 				sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1715 			} else {
1716 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1717 					"p_vaddr: %#" PRIx64 " p_offset: %#" PRIx64 "\n",
1718 					__func__, (u64)sym.st_value, (u64)phdr.p_vaddr,
1719 					(u64)phdr.p_offset);
1720 				sym.st_value -= phdr.p_vaddr - phdr.p_offset;
1721 			}
1722 		}
1723 
1724 		demangled = dso__demangle_sym(dso, kmodule, elf_name);
1725 		if (demangled != NULL)
1726 			elf_name = demangled;
1727 
1728 		f = symbol__new(sym.st_value, sym.st_size,
1729 				GELF_ST_BIND(sym.st_info),
1730 				GELF_ST_TYPE(sym.st_info), elf_name);
1731 		free(demangled);
1732 		if (!f)
1733 			goto out_elf_end;
1734 
1735 		arch__sym_update(f, &sym);
1736 
1737 		__symbols__insert(dso__symbols(curr_dso), f);
1738 		nr++;
1739 	}
1740 	dso__put(curr_dso);
1741 
1742 	/*
1743 	 * For misannotated, zeroed, ASM function sizes.
1744 	 */
1745 	if (nr > 0) {
1746 		symbols__fixup_end(dso__symbols(dso), false);
1747 		symbols__fixup_duplicate(dso__symbols(dso));
1748 		if (kmap) {
1749 			/*
1750 			 * We need to fixup this here too because we create new
1751 			 * maps here, for things like vsyscall sections.
1752 			 */
1753 			maps__fixup_end(kmaps);
1754 		}
1755 	}
1756 	return nr;
1757 out_elf_end:
1758 	dso__put(curr_dso);
1759 	return -1;
1760 }
1761 
1762 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1763 		  struct symsrc *runtime_ss, int kmodule)
1764 {
1765 	int nr = 0;
1766 	int err = -1;
1767 
1768 	dso__set_symtab_type(dso, syms_ss->type);
1769 	dso__set_is_64_bit(dso, syms_ss->is_64_bit);
1770 	dso__set_rel(dso, syms_ss->ehdr.e_type == ET_REL);
1771 
1772 	/*
1773 	 * Modules may already have symbols from kallsyms, but those symbols
1774 	 * have the wrong values for the dso maps, so remove them.
1775 	 */
1776 	if (kmodule && syms_ss->symtab)
1777 		symbols__delete(dso__symbols(dso));
1778 
1779 	if (!syms_ss->symtab) {
1780 		/*
1781 		 * If the vmlinux is stripped, fail so we will fall back
1782 		 * to using kallsyms. The vmlinux runtime symbols aren't
1783 		 * of much use.
1784 		 */
1785 		if (dso__kernel(dso))
1786 			return err;
1787 	} else  {
1788 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1789 					     kmodule, 0);
1790 		if (err < 0)
1791 			return err;
1792 		nr = err;
1793 	}
1794 
1795 	if (syms_ss->dynsym) {
1796 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1797 					     kmodule, 1);
1798 		if (err < 0)
1799 			return err;
1800 		nr += err;
1801 	}
1802 
1803 	/*
1804 	 * The .gnu_debugdata is a special situation: it contains a symbol
1805 	 * table, but the runtime file may also contain dynsym entries which are
1806 	 * not present there. We need to load both.
1807 	 */
1808 	if (syms_ss->type == DSO_BINARY_TYPE__GNU_DEBUGDATA && runtime_ss->dynsym) {
1809 		err = dso__load_sym_internal(dso, map, runtime_ss, runtime_ss,
1810 					     kmodule, 1);
1811 		if (err < 0)
1812 			return err;
1813 		nr += err;
1814 	}
1815 
1816 	return nr;
1817 }
1818 
1819 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1820 {
1821 	GElf_Phdr phdr;
1822 	size_t i, phdrnum;
1823 	int err;
1824 	u64 sz;
1825 
1826 	if (elf_getphdrnum(elf, &phdrnum))
1827 		return -1;
1828 
1829 	for (i = 0; i < phdrnum; i++) {
1830 		if (gelf_getphdr(elf, i, &phdr) == NULL)
1831 			return -1;
1832 		if (phdr.p_type != PT_LOAD)
1833 			continue;
1834 		if (exe) {
1835 			if (!(phdr.p_flags & PF_X))
1836 				continue;
1837 		} else {
1838 			if (!(phdr.p_flags & PF_R))
1839 				continue;
1840 		}
1841 		sz = min(phdr.p_memsz, phdr.p_filesz);
1842 		if (!sz)
1843 			continue;
1844 		err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1845 		if (err)
1846 			return err;
1847 	}
1848 	return 0;
1849 }
1850 
1851 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1852 		    bool *is_64_bit)
1853 {
1854 	int err;
1855 	Elf *elf;
1856 
1857 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1858 	if (elf == NULL)
1859 		return -1;
1860 
1861 	if (is_64_bit)
1862 		*is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1863 
1864 	err = elf_read_maps(elf, exe, mapfn, data);
1865 
1866 	elf_end(elf);
1867 	return err;
1868 }
1869 
1870 enum dso_type dso__type_fd(int fd)
1871 {
1872 	enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1873 	GElf_Ehdr ehdr;
1874 	Elf_Kind ek;
1875 	Elf *elf;
1876 
1877 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1878 	if (elf == NULL)
1879 		goto out;
1880 
1881 	ek = elf_kind(elf);
1882 	if (ek != ELF_K_ELF)
1883 		goto out_end;
1884 
1885 	if (gelf_getclass(elf) == ELFCLASS64) {
1886 		dso_type = DSO__TYPE_64BIT;
1887 		goto out_end;
1888 	}
1889 
1890 	if (gelf_getehdr(elf, &ehdr) == NULL)
1891 		goto out_end;
1892 
1893 	if (ehdr.e_machine == EM_X86_64)
1894 		dso_type = DSO__TYPE_X32BIT;
1895 	else
1896 		dso_type = DSO__TYPE_32BIT;
1897 out_end:
1898 	elf_end(elf);
1899 out:
1900 	return dso_type;
1901 }
1902 
1903 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1904 {
1905 	ssize_t r;
1906 	size_t n;
1907 	int err = -1;
1908 	char *buf = malloc(page_size);
1909 
1910 	if (buf == NULL)
1911 		return -1;
1912 
1913 	if (lseek(to, to_offs, SEEK_SET) != to_offs)
1914 		goto out;
1915 
1916 	if (lseek(from, from_offs, SEEK_SET) != from_offs)
1917 		goto out;
1918 
1919 	while (len) {
1920 		n = page_size;
1921 		if (len < n)
1922 			n = len;
1923 		/* Use read because mmap won't work on proc files */
1924 		r = read(from, buf, n);
1925 		if (r < 0)
1926 			goto out;
1927 		if (!r)
1928 			break;
1929 		n = r;
1930 		r = write(to, buf, n);
1931 		if (r < 0)
1932 			goto out;
1933 		if ((size_t)r != n)
1934 			goto out;
1935 		len -= n;
1936 	}
1937 
1938 	err = 0;
1939 out:
1940 	free(buf);
1941 	return err;
1942 }
1943 
1944 struct kcore {
1945 	int fd;
1946 	int elfclass;
1947 	Elf *elf;
1948 	GElf_Ehdr ehdr;
1949 };
1950 
1951 static int kcore__open(struct kcore *kcore, const char *filename)
1952 {
1953 	GElf_Ehdr *ehdr;
1954 
1955 	kcore->fd = open(filename, O_RDONLY | O_CLOEXEC);
1956 	if (kcore->fd == -1)
1957 		return -1;
1958 
1959 	kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1960 	if (!kcore->elf)
1961 		goto out_close;
1962 
1963 	kcore->elfclass = gelf_getclass(kcore->elf);
1964 	if (kcore->elfclass == ELFCLASSNONE)
1965 		goto out_end;
1966 
1967 	ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1968 	if (!ehdr)
1969 		goto out_end;
1970 
1971 	return 0;
1972 
1973 out_end:
1974 	elf_end(kcore->elf);
1975 out_close:
1976 	close(kcore->fd);
1977 	return -1;
1978 }
1979 
1980 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1981 		       bool temp)
1982 {
1983 	kcore->elfclass = elfclass;
1984 
1985 	if (temp)
1986 		kcore->fd = mkstemp(filename);
1987 	else
1988 		kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0400);
1989 	if (kcore->fd == -1)
1990 		return -1;
1991 
1992 	kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1993 	if (!kcore->elf)
1994 		goto out_close;
1995 
1996 	if (!gelf_newehdr(kcore->elf, elfclass))
1997 		goto out_end;
1998 
1999 	memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
2000 
2001 	return 0;
2002 
2003 out_end:
2004 	elf_end(kcore->elf);
2005 out_close:
2006 	close(kcore->fd);
2007 	unlink(filename);
2008 	return -1;
2009 }
2010 
2011 static void kcore__close(struct kcore *kcore)
2012 {
2013 	elf_end(kcore->elf);
2014 	close(kcore->fd);
2015 }
2016 
2017 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
2018 {
2019 	GElf_Ehdr *ehdr = &to->ehdr;
2020 	GElf_Ehdr *kehdr = &from->ehdr;
2021 
2022 	memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
2023 	ehdr->e_type      = kehdr->e_type;
2024 	ehdr->e_machine   = kehdr->e_machine;
2025 	ehdr->e_version   = kehdr->e_version;
2026 	ehdr->e_entry     = 0;
2027 	ehdr->e_shoff     = 0;
2028 	ehdr->e_flags     = kehdr->e_flags;
2029 	ehdr->e_phnum     = count;
2030 	ehdr->e_shentsize = 0;
2031 	ehdr->e_shnum     = 0;
2032 	ehdr->e_shstrndx  = 0;
2033 
2034 	if (from->elfclass == ELFCLASS32) {
2035 		ehdr->e_phoff     = sizeof(Elf32_Ehdr);
2036 		ehdr->e_ehsize    = sizeof(Elf32_Ehdr);
2037 		ehdr->e_phentsize = sizeof(Elf32_Phdr);
2038 	} else {
2039 		ehdr->e_phoff     = sizeof(Elf64_Ehdr);
2040 		ehdr->e_ehsize    = sizeof(Elf64_Ehdr);
2041 		ehdr->e_phentsize = sizeof(Elf64_Phdr);
2042 	}
2043 
2044 	if (!gelf_update_ehdr(to->elf, ehdr))
2045 		return -1;
2046 
2047 	if (!gelf_newphdr(to->elf, count))
2048 		return -1;
2049 
2050 	return 0;
2051 }
2052 
2053 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
2054 			   u64 addr, u64 len)
2055 {
2056 	GElf_Phdr phdr = {
2057 		.p_type		= PT_LOAD,
2058 		.p_flags	= PF_R | PF_W | PF_X,
2059 		.p_offset	= offset,
2060 		.p_vaddr	= addr,
2061 		.p_paddr	= 0,
2062 		.p_filesz	= len,
2063 		.p_memsz	= len,
2064 		.p_align	= page_size,
2065 	};
2066 
2067 	if (!gelf_update_phdr(kcore->elf, idx, &phdr))
2068 		return -1;
2069 
2070 	return 0;
2071 }
2072 
2073 static off_t kcore__write(struct kcore *kcore)
2074 {
2075 	return elf_update(kcore->elf, ELF_C_WRITE);
2076 }
2077 
2078 struct phdr_data {
2079 	off_t offset;
2080 	off_t rel;
2081 	u64 addr;
2082 	u64 len;
2083 	struct list_head node;
2084 	struct phdr_data *remaps;
2085 };
2086 
2087 struct sym_data {
2088 	u64 addr;
2089 	struct list_head node;
2090 };
2091 
2092 struct kcore_copy_info {
2093 	u64 stext;
2094 	u64 etext;
2095 	u64 first_symbol;
2096 	u64 last_symbol;
2097 	u64 first_module;
2098 	u64 first_module_symbol;
2099 	u64 last_module_symbol;
2100 	size_t phnum;
2101 	struct list_head phdrs;
2102 	struct list_head syms;
2103 };
2104 
2105 #define kcore_copy__for_each_phdr(k, p) \
2106 	list_for_each_entry((p), &(k)->phdrs, node)
2107 
2108 static struct phdr_data *phdr_data__new(u64 addr, u64 len, off_t offset)
2109 {
2110 	struct phdr_data *p = zalloc(sizeof(*p));
2111 
2112 	if (p) {
2113 		p->addr   = addr;
2114 		p->len    = len;
2115 		p->offset = offset;
2116 	}
2117 
2118 	return p;
2119 }
2120 
2121 static struct phdr_data *kcore_copy_info__addnew(struct kcore_copy_info *kci,
2122 						 u64 addr, u64 len,
2123 						 off_t offset)
2124 {
2125 	struct phdr_data *p = phdr_data__new(addr, len, offset);
2126 
2127 	if (p)
2128 		list_add_tail(&p->node, &kci->phdrs);
2129 
2130 	return p;
2131 }
2132 
2133 static void kcore_copy__free_phdrs(struct kcore_copy_info *kci)
2134 {
2135 	struct phdr_data *p, *tmp;
2136 
2137 	list_for_each_entry_safe(p, tmp, &kci->phdrs, node) {
2138 		list_del_init(&p->node);
2139 		free(p);
2140 	}
2141 }
2142 
2143 static struct sym_data *kcore_copy__new_sym(struct kcore_copy_info *kci,
2144 					    u64 addr)
2145 {
2146 	struct sym_data *s = zalloc(sizeof(*s));
2147 
2148 	if (s) {
2149 		s->addr = addr;
2150 		list_add_tail(&s->node, &kci->syms);
2151 	}
2152 
2153 	return s;
2154 }
2155 
2156 static void kcore_copy__free_syms(struct kcore_copy_info *kci)
2157 {
2158 	struct sym_data *s, *tmp;
2159 
2160 	list_for_each_entry_safe(s, tmp, &kci->syms, node) {
2161 		list_del_init(&s->node);
2162 		free(s);
2163 	}
2164 }
2165 
2166 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
2167 					u64 start)
2168 {
2169 	struct kcore_copy_info *kci = arg;
2170 
2171 	if (!kallsyms__is_function(type))
2172 		return 0;
2173 
2174 	if (strchr(name, '[')) {
2175 		if (!kci->first_module_symbol || start < kci->first_module_symbol)
2176 			kci->first_module_symbol = start;
2177 		if (start > kci->last_module_symbol)
2178 			kci->last_module_symbol = start;
2179 		return 0;
2180 	}
2181 
2182 	if (!kci->first_symbol || start < kci->first_symbol)
2183 		kci->first_symbol = start;
2184 
2185 	if (!kci->last_symbol || start > kci->last_symbol)
2186 		kci->last_symbol = start;
2187 
2188 	if (!strcmp(name, "_stext")) {
2189 		kci->stext = start;
2190 		return 0;
2191 	}
2192 
2193 	if (!strcmp(name, "_etext")) {
2194 		kci->etext = start;
2195 		return 0;
2196 	}
2197 
2198 	if (is_entry_trampoline(name) && !kcore_copy__new_sym(kci, start))
2199 		return -1;
2200 
2201 	return 0;
2202 }
2203 
2204 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
2205 				      const char *dir)
2206 {
2207 	char kallsyms_filename[PATH_MAX];
2208 
2209 	scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
2210 
2211 	if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
2212 		return -1;
2213 
2214 	if (kallsyms__parse(kallsyms_filename, kci,
2215 			    kcore_copy__process_kallsyms) < 0)
2216 		return -1;
2217 
2218 	return 0;
2219 }
2220 
2221 static int kcore_copy__process_modules(void *arg,
2222 				       const char *name __maybe_unused,
2223 				       u64 start, u64 size __maybe_unused)
2224 {
2225 	struct kcore_copy_info *kci = arg;
2226 
2227 	if (!kci->first_module || start < kci->first_module)
2228 		kci->first_module = start;
2229 
2230 	return 0;
2231 }
2232 
2233 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
2234 				     const char *dir)
2235 {
2236 	char modules_filename[PATH_MAX];
2237 
2238 	scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
2239 
2240 	if (symbol__restricted_filename(modules_filename, "/proc/modules"))
2241 		return -1;
2242 
2243 	if (modules__parse(modules_filename, kci,
2244 			   kcore_copy__process_modules) < 0)
2245 		return -1;
2246 
2247 	return 0;
2248 }
2249 
2250 static int kcore_copy__map(struct kcore_copy_info *kci, u64 start, u64 end,
2251 			   u64 pgoff, u64 s, u64 e)
2252 {
2253 	u64 len, offset;
2254 
2255 	if (s < start || s >= end)
2256 		return 0;
2257 
2258 	offset = (s - start) + pgoff;
2259 	len = e < end ? e - s : end - s;
2260 
2261 	return kcore_copy_info__addnew(kci, s, len, offset) ? 0 : -1;
2262 }
2263 
2264 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
2265 {
2266 	struct kcore_copy_info *kci = data;
2267 	u64 end = start + len;
2268 	struct sym_data *sdat;
2269 
2270 	if (kcore_copy__map(kci, start, end, pgoff, kci->stext, kci->etext))
2271 		return -1;
2272 
2273 	if (kcore_copy__map(kci, start, end, pgoff, kci->first_module,
2274 			    kci->last_module_symbol))
2275 		return -1;
2276 
2277 	list_for_each_entry(sdat, &kci->syms, node) {
2278 		u64 s = round_down(sdat->addr, page_size);
2279 
2280 		if (kcore_copy__map(kci, start, end, pgoff, s, s + len))
2281 			return -1;
2282 	}
2283 
2284 	return 0;
2285 }
2286 
2287 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
2288 {
2289 	if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
2290 		return -1;
2291 
2292 	return 0;
2293 }
2294 
2295 static void kcore_copy__find_remaps(struct kcore_copy_info *kci)
2296 {
2297 	struct phdr_data *p, *k = NULL;
2298 	u64 kend;
2299 
2300 	if (!kci->stext)
2301 		return;
2302 
2303 	/* Find phdr that corresponds to the kernel map (contains stext) */
2304 	kcore_copy__for_each_phdr(kci, p) {
2305 		u64 pend = p->addr + p->len - 1;
2306 
2307 		if (p->addr <= kci->stext && pend >= kci->stext) {
2308 			k = p;
2309 			break;
2310 		}
2311 	}
2312 
2313 	if (!k)
2314 		return;
2315 
2316 	kend = k->offset + k->len;
2317 
2318 	/* Find phdrs that remap the kernel */
2319 	kcore_copy__for_each_phdr(kci, p) {
2320 		u64 pend = p->offset + p->len;
2321 
2322 		if (p == k)
2323 			continue;
2324 
2325 		if (p->offset >= k->offset && pend <= kend)
2326 			p->remaps = k;
2327 	}
2328 }
2329 
2330 static void kcore_copy__layout(struct kcore_copy_info *kci)
2331 {
2332 	struct phdr_data *p;
2333 	off_t rel = 0;
2334 
2335 	kcore_copy__find_remaps(kci);
2336 
2337 	kcore_copy__for_each_phdr(kci, p) {
2338 		if (!p->remaps) {
2339 			p->rel = rel;
2340 			rel += p->len;
2341 		}
2342 		kci->phnum += 1;
2343 	}
2344 
2345 	kcore_copy__for_each_phdr(kci, p) {
2346 		struct phdr_data *k = p->remaps;
2347 
2348 		if (k)
2349 			p->rel = p->offset - k->offset + k->rel;
2350 	}
2351 }
2352 
2353 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
2354 				 Elf *elf)
2355 {
2356 	if (kcore_copy__parse_kallsyms(kci, dir))
2357 		return -1;
2358 
2359 	if (kcore_copy__parse_modules(kci, dir))
2360 		return -1;
2361 
2362 	if (kci->stext)
2363 		kci->stext = round_down(kci->stext, page_size);
2364 	else
2365 		kci->stext = round_down(kci->first_symbol, page_size);
2366 
2367 	if (kci->etext) {
2368 		kci->etext = round_up(kci->etext, page_size);
2369 	} else if (kci->last_symbol) {
2370 		kci->etext = round_up(kci->last_symbol, page_size);
2371 		kci->etext += page_size;
2372 	}
2373 
2374 	if (kci->first_module_symbol &&
2375 	    (!kci->first_module || kci->first_module_symbol < kci->first_module))
2376 		kci->first_module = kci->first_module_symbol;
2377 
2378 	kci->first_module = round_down(kci->first_module, page_size);
2379 
2380 	if (kci->last_module_symbol) {
2381 		kci->last_module_symbol = round_up(kci->last_module_symbol,
2382 						   page_size);
2383 		kci->last_module_symbol += page_size;
2384 	}
2385 
2386 	if (!kci->stext || !kci->etext)
2387 		return -1;
2388 
2389 	if (kci->first_module && !kci->last_module_symbol)
2390 		return -1;
2391 
2392 	if (kcore_copy__read_maps(kci, elf))
2393 		return -1;
2394 
2395 	kcore_copy__layout(kci);
2396 
2397 	return 0;
2398 }
2399 
2400 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
2401 				 const char *name)
2402 {
2403 	char from_filename[PATH_MAX];
2404 	char to_filename[PATH_MAX];
2405 
2406 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2407 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2408 
2409 	return copyfile_mode(from_filename, to_filename, 0400);
2410 }
2411 
2412 static int kcore_copy__unlink(const char *dir, const char *name)
2413 {
2414 	char filename[PATH_MAX];
2415 
2416 	scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
2417 
2418 	return unlink(filename);
2419 }
2420 
2421 static int kcore_copy__compare_fds(int from, int to)
2422 {
2423 	char *buf_from;
2424 	char *buf_to;
2425 	ssize_t ret;
2426 	size_t len;
2427 	int err = -1;
2428 
2429 	buf_from = malloc(page_size);
2430 	buf_to = malloc(page_size);
2431 	if (!buf_from || !buf_to)
2432 		goto out;
2433 
2434 	while (1) {
2435 		/* Use read because mmap won't work on proc files */
2436 		ret = read(from, buf_from, page_size);
2437 		if (ret < 0)
2438 			goto out;
2439 
2440 		if (!ret)
2441 			break;
2442 
2443 		len = ret;
2444 
2445 		if (readn(to, buf_to, len) != (int)len)
2446 			goto out;
2447 
2448 		if (memcmp(buf_from, buf_to, len))
2449 			goto out;
2450 	}
2451 
2452 	err = 0;
2453 out:
2454 	free(buf_to);
2455 	free(buf_from);
2456 	return err;
2457 }
2458 
2459 static int kcore_copy__compare_files(const char *from_filename,
2460 				     const char *to_filename)
2461 {
2462 	int from, to, err = -1;
2463 
2464 	from = open(from_filename, O_RDONLY | O_CLOEXEC);
2465 	if (from < 0)
2466 		return -1;
2467 
2468 	to = open(to_filename, O_RDONLY | O_CLOEXEC);
2469 	if (to < 0)
2470 		goto out_close_from;
2471 
2472 	err = kcore_copy__compare_fds(from, to);
2473 
2474 	close(to);
2475 out_close_from:
2476 	close(from);
2477 	return err;
2478 }
2479 
2480 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
2481 				    const char *name)
2482 {
2483 	char from_filename[PATH_MAX];
2484 	char to_filename[PATH_MAX];
2485 
2486 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2487 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2488 
2489 	return kcore_copy__compare_files(from_filename, to_filename);
2490 }
2491 
2492 /**
2493  * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
2494  * @from_dir: from directory
2495  * @to_dir: to directory
2496  *
2497  * This function copies kallsyms, modules and kcore files from one directory to
2498  * another.  kallsyms and modules are copied entirely.  Only code segments are
2499  * copied from kcore.  It is assumed that two segments suffice: one for the
2500  * kernel proper and one for all the modules.  The code segments are determined
2501  * from kallsyms and modules files.  The kernel map starts at _stext or the
2502  * lowest function symbol, and ends at _etext or the highest function symbol.
2503  * The module map starts at the lowest module address and ends at the highest
2504  * module symbol.  Start addresses are rounded down to the nearest page.  End
2505  * addresses are rounded up to the nearest page.  An extra page is added to the
2506  * highest kernel symbol and highest module symbol to, hopefully, encompass that
2507  * symbol too.  Because it contains only code sections, the resulting kcore is
2508  * unusual.  One significant peculiarity is that the mapping (start -> pgoff)
2509  * is not the same for the kernel map and the modules map.  That happens because
2510  * the data is copied adjacently whereas the original kcore has gaps.  Finally,
2511  * kallsyms file is compared with its copy to check that modules have not been
2512  * loaded or unloaded while the copies were taking place.
2513  *
2514  * Return: %0 on success, %-1 on failure.
2515  */
2516 int kcore_copy(const char *from_dir, const char *to_dir)
2517 {
2518 	struct kcore kcore;
2519 	struct kcore extract;
2520 	int idx = 0, err = -1;
2521 	off_t offset, sz;
2522 	struct kcore_copy_info kci = { .stext = 0, };
2523 	char kcore_filename[PATH_MAX];
2524 	char extract_filename[PATH_MAX];
2525 	struct phdr_data *p;
2526 
2527 	INIT_LIST_HEAD(&kci.phdrs);
2528 	INIT_LIST_HEAD(&kci.syms);
2529 
2530 	if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
2531 		return -1;
2532 
2533 	if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
2534 		goto out_unlink_kallsyms;
2535 
2536 	scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
2537 	scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
2538 
2539 	if (kcore__open(&kcore, kcore_filename))
2540 		goto out_unlink_modules;
2541 
2542 	if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
2543 		goto out_kcore_close;
2544 
2545 	if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
2546 		goto out_kcore_close;
2547 
2548 	if (kcore__copy_hdr(&kcore, &extract, kci.phnum))
2549 		goto out_extract_close;
2550 
2551 	offset = gelf_fsize(extract.elf, ELF_T_EHDR, 1, EV_CURRENT) +
2552 		 gelf_fsize(extract.elf, ELF_T_PHDR, kci.phnum, EV_CURRENT);
2553 	offset = round_up(offset, page_size);
2554 
2555 	kcore_copy__for_each_phdr(&kci, p) {
2556 		off_t offs = p->rel + offset;
2557 
2558 		if (kcore__add_phdr(&extract, idx++, offs, p->addr, p->len))
2559 			goto out_extract_close;
2560 	}
2561 
2562 	sz = kcore__write(&extract);
2563 	if (sz < 0 || sz > offset)
2564 		goto out_extract_close;
2565 
2566 	kcore_copy__for_each_phdr(&kci, p) {
2567 		off_t offs = p->rel + offset;
2568 
2569 		if (p->remaps)
2570 			continue;
2571 		if (copy_bytes(kcore.fd, p->offset, extract.fd, offs, p->len))
2572 			goto out_extract_close;
2573 	}
2574 
2575 	if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
2576 		goto out_extract_close;
2577 
2578 	err = 0;
2579 
2580 out_extract_close:
2581 	kcore__close(&extract);
2582 	if (err)
2583 		unlink(extract_filename);
2584 out_kcore_close:
2585 	kcore__close(&kcore);
2586 out_unlink_modules:
2587 	if (err)
2588 		kcore_copy__unlink(to_dir, "modules");
2589 out_unlink_kallsyms:
2590 	if (err)
2591 		kcore_copy__unlink(to_dir, "kallsyms");
2592 
2593 	kcore_copy__free_phdrs(&kci);
2594 	kcore_copy__free_syms(&kci);
2595 
2596 	return err;
2597 }
2598 
2599 int kcore_extract__create(struct kcore_extract *kce)
2600 {
2601 	struct kcore kcore;
2602 	struct kcore extract;
2603 	size_t count = 1;
2604 	int idx = 0, err = -1;
2605 	off_t offset = page_size, sz;
2606 
2607 	if (kcore__open(&kcore, kce->kcore_filename))
2608 		return -1;
2609 
2610 	strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
2611 	if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
2612 		goto out_kcore_close;
2613 
2614 	if (kcore__copy_hdr(&kcore, &extract, count))
2615 		goto out_extract_close;
2616 
2617 	if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
2618 		goto out_extract_close;
2619 
2620 	sz = kcore__write(&extract);
2621 	if (sz < 0 || sz > offset)
2622 		goto out_extract_close;
2623 
2624 	if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
2625 		goto out_extract_close;
2626 
2627 	err = 0;
2628 
2629 out_extract_close:
2630 	kcore__close(&extract);
2631 	if (err)
2632 		unlink(kce->extract_filename);
2633 out_kcore_close:
2634 	kcore__close(&kcore);
2635 
2636 	return err;
2637 }
2638 
2639 void kcore_extract__delete(struct kcore_extract *kce)
2640 {
2641 	unlink(kce->extract_filename);
2642 }
2643 
2644 #ifdef HAVE_GELF_GETNOTE_SUPPORT
2645 
2646 static void sdt_adjust_loc(struct sdt_note *tmp, GElf_Addr base_off)
2647 {
2648 	if (!base_off)
2649 		return;
2650 
2651 	if (tmp->bit32)
2652 		tmp->addr.a32[SDT_NOTE_IDX_LOC] =
2653 			tmp->addr.a32[SDT_NOTE_IDX_LOC] + base_off -
2654 			tmp->addr.a32[SDT_NOTE_IDX_BASE];
2655 	else
2656 		tmp->addr.a64[SDT_NOTE_IDX_LOC] =
2657 			tmp->addr.a64[SDT_NOTE_IDX_LOC] + base_off -
2658 			tmp->addr.a64[SDT_NOTE_IDX_BASE];
2659 }
2660 
2661 static void sdt_adjust_refctr(struct sdt_note *tmp, GElf_Addr base_addr,
2662 			      GElf_Addr base_off)
2663 {
2664 	if (!base_off)
2665 		return;
2666 
2667 	if (tmp->bit32 && tmp->addr.a32[SDT_NOTE_IDX_REFCTR])
2668 		tmp->addr.a32[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2669 	else if (tmp->addr.a64[SDT_NOTE_IDX_REFCTR])
2670 		tmp->addr.a64[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2671 }
2672 
2673 /**
2674  * populate_sdt_note : Parse raw data and identify SDT note
2675  * @elf: elf of the opened file
2676  * @data: raw data of a section with description offset applied
2677  * @len: note description size
2678  * @type: type of the note
2679  * @sdt_notes: List to add the SDT note
2680  *
2681  * Responsible for parsing the @data in section .note.stapsdt in @elf and
2682  * if its an SDT note, it appends to @sdt_notes list.
2683  */
2684 static int populate_sdt_note(Elf **elf, const char *data, size_t len,
2685 			     struct list_head *sdt_notes)
2686 {
2687 	const char *provider, *name, *args;
2688 	struct sdt_note *tmp = NULL;
2689 	GElf_Ehdr ehdr;
2690 	GElf_Shdr shdr;
2691 	int ret = -EINVAL;
2692 
2693 	union {
2694 		Elf64_Addr a64[NR_ADDR];
2695 		Elf32_Addr a32[NR_ADDR];
2696 	} buf;
2697 
2698 	Elf_Data dst = {
2699 		.d_buf = &buf, .d_type = ELF_T_ADDR, .d_version = EV_CURRENT,
2700 		.d_size = gelf_fsize((*elf), ELF_T_ADDR, NR_ADDR, EV_CURRENT),
2701 		.d_off = 0, .d_align = 0
2702 	};
2703 	Elf_Data src = {
2704 		.d_buf = (void *) data, .d_type = ELF_T_ADDR,
2705 		.d_version = EV_CURRENT, .d_size = dst.d_size, .d_off = 0,
2706 		.d_align = 0
2707 	};
2708 
2709 	tmp = (struct sdt_note *)calloc(1, sizeof(struct sdt_note));
2710 	if (!tmp) {
2711 		ret = -ENOMEM;
2712 		goto out_err;
2713 	}
2714 
2715 	INIT_LIST_HEAD(&tmp->note_list);
2716 
2717 	if (len < dst.d_size + 3)
2718 		goto out_free_note;
2719 
2720 	/* Translation from file representation to memory representation */
2721 	if (gelf_xlatetom(*elf, &dst, &src,
2722 			  elf_getident(*elf, NULL)[EI_DATA]) == NULL) {
2723 		pr_err("gelf_xlatetom : %s\n", elf_errmsg(-1));
2724 		goto out_free_note;
2725 	}
2726 
2727 	/* Populate the fields of sdt_note */
2728 	provider = data + dst.d_size;
2729 
2730 	name = (const char *)memchr(provider, '\0', data + len - provider);
2731 	if (name++ == NULL)
2732 		goto out_free_note;
2733 
2734 	tmp->provider = strdup(provider);
2735 	if (!tmp->provider) {
2736 		ret = -ENOMEM;
2737 		goto out_free_note;
2738 	}
2739 	tmp->name = strdup(name);
2740 	if (!tmp->name) {
2741 		ret = -ENOMEM;
2742 		goto out_free_prov;
2743 	}
2744 
2745 	args = memchr(name, '\0', data + len - name);
2746 
2747 	/*
2748 	 * There is no argument if:
2749 	 * - We reached the end of the note;
2750 	 * - There is not enough room to hold a potential string;
2751 	 * - The argument string is empty or just contains ':'.
2752 	 */
2753 	if (args == NULL || data + len - args < 2 ||
2754 		args[1] == ':' || args[1] == '\0')
2755 		tmp->args = NULL;
2756 	else {
2757 		tmp->args = strdup(++args);
2758 		if (!tmp->args) {
2759 			ret = -ENOMEM;
2760 			goto out_free_name;
2761 		}
2762 	}
2763 
2764 	if (gelf_getclass(*elf) == ELFCLASS32) {
2765 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf32_Addr));
2766 		tmp->bit32 = true;
2767 	} else {
2768 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf64_Addr));
2769 		tmp->bit32 = false;
2770 	}
2771 
2772 	if (!gelf_getehdr(*elf, &ehdr)) {
2773 		pr_debug("%s : cannot get elf header.\n", __func__);
2774 		ret = -EBADF;
2775 		goto out_free_args;
2776 	}
2777 
2778 	/* Adjust the prelink effect :
2779 	 * Find out the .stapsdt.base section.
2780 	 * This scn will help us to handle prelinking (if present).
2781 	 * Compare the retrieved file offset of the base section with the
2782 	 * base address in the description of the SDT note. If its different,
2783 	 * then accordingly, adjust the note location.
2784 	 */
2785 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_BASE_SCN, NULL))
2786 		sdt_adjust_loc(tmp, shdr.sh_offset);
2787 
2788 	/* Adjust reference counter offset */
2789 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_PROBES_SCN, NULL))
2790 		sdt_adjust_refctr(tmp, shdr.sh_addr, shdr.sh_offset);
2791 
2792 	list_add_tail(&tmp->note_list, sdt_notes);
2793 	return 0;
2794 
2795 out_free_args:
2796 	zfree(&tmp->args);
2797 out_free_name:
2798 	zfree(&tmp->name);
2799 out_free_prov:
2800 	zfree(&tmp->provider);
2801 out_free_note:
2802 	free(tmp);
2803 out_err:
2804 	return ret;
2805 }
2806 
2807 /**
2808  * construct_sdt_notes_list : constructs a list of SDT notes
2809  * @elf : elf to look into
2810  * @sdt_notes : empty list_head
2811  *
2812  * Scans the sections in 'elf' for the section
2813  * .note.stapsdt. It, then calls populate_sdt_note to find
2814  * out the SDT events and populates the 'sdt_notes'.
2815  */
2816 static int construct_sdt_notes_list(Elf *elf, struct list_head *sdt_notes)
2817 {
2818 	GElf_Ehdr ehdr;
2819 	Elf_Scn *scn = NULL;
2820 	Elf_Data *data;
2821 	GElf_Shdr shdr;
2822 	size_t shstrndx, next;
2823 	GElf_Nhdr nhdr;
2824 	size_t name_off, desc_off, offset;
2825 	int ret = 0;
2826 
2827 	if (gelf_getehdr(elf, &ehdr) == NULL) {
2828 		ret = -EBADF;
2829 		goto out_ret;
2830 	}
2831 	if (elf_getshdrstrndx(elf, &shstrndx) != 0) {
2832 		ret = -EBADF;
2833 		goto out_ret;
2834 	}
2835 
2836 	/* Look for the required section */
2837 	scn = elf_section_by_name(elf, &ehdr, &shdr, SDT_NOTE_SCN, NULL);
2838 	if (!scn) {
2839 		ret = -ENOENT;
2840 		goto out_ret;
2841 	}
2842 
2843 	if ((shdr.sh_type != SHT_NOTE) || (shdr.sh_flags & SHF_ALLOC)) {
2844 		ret = -ENOENT;
2845 		goto out_ret;
2846 	}
2847 
2848 	data = elf_getdata(scn, NULL);
2849 
2850 	/* Get the SDT notes */
2851 	for (offset = 0; (next = gelf_getnote(data, offset, &nhdr, &name_off,
2852 					      &desc_off)) > 0; offset = next) {
2853 		if (nhdr.n_namesz == sizeof(SDT_NOTE_NAME) &&
2854 		    !memcmp(data->d_buf + name_off, SDT_NOTE_NAME,
2855 			    sizeof(SDT_NOTE_NAME))) {
2856 			/* Check the type of the note */
2857 			if (nhdr.n_type != SDT_NOTE_TYPE)
2858 				goto out_ret;
2859 
2860 			ret = populate_sdt_note(&elf, ((data->d_buf) + desc_off),
2861 						nhdr.n_descsz, sdt_notes);
2862 			if (ret < 0)
2863 				goto out_ret;
2864 		}
2865 	}
2866 	if (list_empty(sdt_notes))
2867 		ret = -ENOENT;
2868 
2869 out_ret:
2870 	return ret;
2871 }
2872 
2873 /**
2874  * get_sdt_note_list : Wrapper to construct a list of sdt notes
2875  * @head : empty list_head
2876  * @target : file to find SDT notes from
2877  *
2878  * This opens the file, initializes
2879  * the ELF and then calls construct_sdt_notes_list.
2880  */
2881 int get_sdt_note_list(struct list_head *head, const char *target)
2882 {
2883 	Elf *elf;
2884 	int fd, ret;
2885 
2886 	fd = open(target, O_RDONLY | O_CLOEXEC);
2887 	if (fd < 0)
2888 		return -EBADF;
2889 
2890 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
2891 	if (!elf) {
2892 		ret = -EBADF;
2893 		goto out_close;
2894 	}
2895 	ret = construct_sdt_notes_list(elf, head);
2896 	elf_end(elf);
2897 out_close:
2898 	close(fd);
2899 	return ret;
2900 }
2901 
2902 /**
2903  * cleanup_sdt_note_list : free the sdt notes' list
2904  * @sdt_notes: sdt notes' list
2905  *
2906  * Free up the SDT notes in @sdt_notes.
2907  * Returns the number of SDT notes free'd.
2908  */
2909 int cleanup_sdt_note_list(struct list_head *sdt_notes)
2910 {
2911 	struct sdt_note *tmp, *pos;
2912 	int nr_free = 0;
2913 
2914 	list_for_each_entry_safe(pos, tmp, sdt_notes, note_list) {
2915 		list_del_init(&pos->note_list);
2916 		zfree(&pos->args);
2917 		zfree(&pos->name);
2918 		zfree(&pos->provider);
2919 		free(pos);
2920 		nr_free++;
2921 	}
2922 	return nr_free;
2923 }
2924 
2925 /**
2926  * sdt_notes__get_count: Counts the number of sdt events
2927  * @start: list_head to sdt_notes list
2928  *
2929  * Returns the number of SDT notes in a list
2930  */
2931 int sdt_notes__get_count(struct list_head *start)
2932 {
2933 	struct sdt_note *sdt_ptr;
2934 	int count = 0;
2935 
2936 	list_for_each_entry(sdt_ptr, start, note_list)
2937 		count++;
2938 	return count;
2939 }
2940 #endif
2941 
2942 void symbol__elf_init(void)
2943 {
2944 	elf_version(EV_CURRENT);
2945 }
2946