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