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