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