xref: /openbmc/linux/tools/perf/util/symbol-elf.c (revision c2d066c090c9fec5de99ae051e97e0f448cbc229)
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 static void get_plt_sizes(GElf_Ehdr *ehdr, GElf_Shdr *shdr_plt,
327 			  u64 *plt_header_size, u64 *plt_entry_size)
328 {
329 	switch (ehdr->e_machine) {
330 	case EM_ARM:
331 		*plt_header_size = 20;
332 		*plt_entry_size = 12;
333 		return;
334 	case EM_AARCH64:
335 		*plt_header_size = 32;
336 		*plt_entry_size = 16;
337 		return;
338 	case EM_SPARC:
339 		*plt_header_size = 48;
340 		*plt_entry_size = 12;
341 		return;
342 	case EM_SPARCV9:
343 		*plt_header_size = 128;
344 		*plt_entry_size = 32;
345 		return;
346 	default: /* FIXME: s390/alpha/mips/parisc/poperpc/sh/xtensa need to be checked */
347 		*plt_header_size = shdr_plt->sh_entsize;
348 		*plt_entry_size = shdr_plt->sh_entsize;
349 		return;
350 	}
351 }
352 
353 #define elf_section__for_each_rel(reldata, pos, pos_mem, idx, nr_entries) \
354 	for (idx = 0, pos = gelf_getrel(reldata, 0, &pos_mem); \
355 	     idx < nr_entries; \
356 	     ++idx, pos = gelf_getrel(reldata, idx, &pos_mem))
357 
358 #define elf_section__for_each_rela(reldata, pos, pos_mem, idx, nr_entries) \
359 	for (idx = 0, pos = gelf_getrela(reldata, 0, &pos_mem); \
360 	     idx < nr_entries; \
361 	     ++idx, pos = gelf_getrela(reldata, idx, &pos_mem))
362 
363 /*
364  * We need to check if we have a .dynsym, so that we can handle the
365  * .plt, synthesizing its symbols, that aren't on the symtabs (be it
366  * .dynsym or .symtab).
367  * And always look at the original dso, not at debuginfo packages, that
368  * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
369  */
370 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss)
371 {
372 	uint32_t nr_rel_entries, idx;
373 	GElf_Sym sym;
374 	u64 plt_offset, plt_header_size, plt_entry_size;
375 	GElf_Shdr shdr_plt;
376 	struct symbol *f;
377 	GElf_Shdr shdr_rel_plt, shdr_dynsym;
378 	Elf_Data *reldata, *syms, *symstrs;
379 	Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
380 	size_t dynsym_idx;
381 	GElf_Ehdr ehdr;
382 	char sympltname[1024];
383 	Elf *elf;
384 	int nr = 0, symidx, err = 0;
385 
386 	if (!ss->dynsym)
387 		return 0;
388 
389 	elf = ss->elf;
390 	ehdr = ss->ehdr;
391 
392 	scn_dynsym = ss->dynsym;
393 	shdr_dynsym = ss->dynshdr;
394 	dynsym_idx = ss->dynsym_idx;
395 
396 	if (scn_dynsym == NULL)
397 		goto out_elf_end;
398 
399 	scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
400 					  ".rela.plt", NULL);
401 	if (scn_plt_rel == NULL) {
402 		scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
403 						  ".rel.plt", NULL);
404 		if (scn_plt_rel == NULL)
405 			goto out_elf_end;
406 	}
407 
408 	err = -1;
409 
410 	if (shdr_rel_plt.sh_link != dynsym_idx)
411 		goto out_elf_end;
412 
413 	if (elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL) == NULL)
414 		goto out_elf_end;
415 
416 	/*
417 	 * Fetch the relocation section to find the idxes to the GOT
418 	 * and the symbols in the .dynsym they refer to.
419 	 */
420 	reldata = elf_getdata(scn_plt_rel, NULL);
421 	if (reldata == NULL)
422 		goto out_elf_end;
423 
424 	syms = elf_getdata(scn_dynsym, NULL);
425 	if (syms == NULL)
426 		goto out_elf_end;
427 
428 	scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
429 	if (scn_symstrs == NULL)
430 		goto out_elf_end;
431 
432 	symstrs = elf_getdata(scn_symstrs, NULL);
433 	if (symstrs == NULL)
434 		goto out_elf_end;
435 
436 	if (symstrs->d_size == 0)
437 		goto out_elf_end;
438 
439 	nr_rel_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
440 	plt_offset = shdr_plt.sh_offset;
441 	get_plt_sizes(&ehdr, &shdr_plt, &plt_header_size, &plt_entry_size);
442 	plt_offset += plt_header_size;
443 
444 	if (shdr_rel_plt.sh_type == SHT_RELA) {
445 		GElf_Rela pos_mem, *pos;
446 
447 		elf_section__for_each_rela(reldata, pos, pos_mem, idx,
448 					   nr_rel_entries) {
449 			const char *elf_name = NULL;
450 			char *demangled = NULL;
451 			symidx = GELF_R_SYM(pos->r_info);
452 			gelf_getsym(syms, symidx, &sym);
453 
454 			elf_name = elf_sym__name(&sym, symstrs);
455 			demangled = demangle_sym(dso, 0, elf_name);
456 			if (demangled != NULL)
457 				elf_name = demangled;
458 			snprintf(sympltname, sizeof(sympltname),
459 				 "%s@plt", elf_name);
460 			free(demangled);
461 
462 			f = symbol__new(plt_offset, plt_entry_size,
463 					STB_GLOBAL, STT_FUNC, sympltname);
464 			if (!f)
465 				goto out_elf_end;
466 
467 			plt_offset += plt_entry_size;
468 			symbols__insert(&dso->symbols, f);
469 			++nr;
470 		}
471 	} else if (shdr_rel_plt.sh_type == SHT_REL) {
472 		GElf_Rel pos_mem, *pos;
473 		elf_section__for_each_rel(reldata, pos, pos_mem, idx,
474 					  nr_rel_entries) {
475 			const char *elf_name = NULL;
476 			char *demangled = NULL;
477 			symidx = GELF_R_SYM(pos->r_info);
478 			gelf_getsym(syms, symidx, &sym);
479 
480 			elf_name = elf_sym__name(&sym, symstrs);
481 			demangled = demangle_sym(dso, 0, elf_name);
482 			if (demangled != NULL)
483 				elf_name = demangled;
484 			snprintf(sympltname, sizeof(sympltname),
485 				 "%s@plt", elf_name);
486 			free(demangled);
487 
488 			f = symbol__new(plt_offset, plt_entry_size,
489 					STB_GLOBAL, STT_FUNC, sympltname);
490 			if (!f)
491 				goto out_elf_end;
492 
493 			plt_offset += plt_entry_size;
494 			symbols__insert(&dso->symbols, f);
495 			++nr;
496 		}
497 	}
498 
499 	err = 0;
500 out_elf_end:
501 	if (err == 0)
502 		return nr;
503 	pr_debug("%s: problems reading %s PLT info.\n",
504 		 __func__, dso->long_name);
505 	return 0;
506 }
507 
508 char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
509 {
510 	return demangle_sym(dso, kmodule, elf_name);
511 }
512 
513 /*
514  * Align offset to 4 bytes as needed for note name and descriptor data.
515  */
516 #define NOTE_ALIGN(n) (((n) + 3) & -4U)
517 
518 static int elf_read_build_id(Elf *elf, void *bf, size_t size)
519 {
520 	int err = -1;
521 	GElf_Ehdr ehdr;
522 	GElf_Shdr shdr;
523 	Elf_Data *data;
524 	Elf_Scn *sec;
525 	Elf_Kind ek;
526 	void *ptr;
527 
528 	if (size < BUILD_ID_SIZE)
529 		goto out;
530 
531 	ek = elf_kind(elf);
532 	if (ek != ELF_K_ELF)
533 		goto out;
534 
535 	if (gelf_getehdr(elf, &ehdr) == NULL) {
536 		pr_err("%s: cannot get elf header.\n", __func__);
537 		goto out;
538 	}
539 
540 	/*
541 	 * Check following sections for notes:
542 	 *   '.note.gnu.build-id'
543 	 *   '.notes'
544 	 *   '.note' (VDSO specific)
545 	 */
546 	do {
547 		sec = elf_section_by_name(elf, &ehdr, &shdr,
548 					  ".note.gnu.build-id", NULL);
549 		if (sec)
550 			break;
551 
552 		sec = elf_section_by_name(elf, &ehdr, &shdr,
553 					  ".notes", NULL);
554 		if (sec)
555 			break;
556 
557 		sec = elf_section_by_name(elf, &ehdr, &shdr,
558 					  ".note", NULL);
559 		if (sec)
560 			break;
561 
562 		return err;
563 
564 	} while (0);
565 
566 	data = elf_getdata(sec, NULL);
567 	if (data == NULL)
568 		goto out;
569 
570 	ptr = data->d_buf;
571 	while (ptr < (data->d_buf + data->d_size)) {
572 		GElf_Nhdr *nhdr = ptr;
573 		size_t namesz = NOTE_ALIGN(nhdr->n_namesz),
574 		       descsz = NOTE_ALIGN(nhdr->n_descsz);
575 		const char *name;
576 
577 		ptr += sizeof(*nhdr);
578 		name = ptr;
579 		ptr += namesz;
580 		if (nhdr->n_type == NT_GNU_BUILD_ID &&
581 		    nhdr->n_namesz == sizeof("GNU")) {
582 			if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
583 				size_t sz = min(size, descsz);
584 				memcpy(bf, ptr, sz);
585 				memset(bf + sz, 0, size - sz);
586 				err = descsz;
587 				break;
588 			}
589 		}
590 		ptr += descsz;
591 	}
592 
593 out:
594 	return err;
595 }
596 
597 #ifdef HAVE_LIBBFD_BUILDID_SUPPORT
598 
599 static int read_build_id(const char *filename, struct build_id *bid)
600 {
601 	size_t size = sizeof(bid->data);
602 	int err = -1;
603 	bfd *abfd;
604 
605 	abfd = bfd_openr(filename, NULL);
606 	if (!abfd)
607 		return -1;
608 
609 	if (!bfd_check_format(abfd, bfd_object)) {
610 		pr_debug2("%s: cannot read %s bfd file.\n", __func__, filename);
611 		goto out_close;
612 	}
613 
614 	if (!abfd->build_id || abfd->build_id->size > size)
615 		goto out_close;
616 
617 	memcpy(bid->data, abfd->build_id->data, abfd->build_id->size);
618 	memset(bid->data + abfd->build_id->size, 0, size - abfd->build_id->size);
619 	err = bid->size = abfd->build_id->size;
620 
621 out_close:
622 	bfd_close(abfd);
623 	return err;
624 }
625 
626 #else // HAVE_LIBBFD_BUILDID_SUPPORT
627 
628 static int read_build_id(const char *filename, struct build_id *bid)
629 {
630 	size_t size = sizeof(bid->data);
631 	int fd, err = -1;
632 	Elf *elf;
633 
634 	if (size < BUILD_ID_SIZE)
635 		goto out;
636 
637 	fd = open(filename, O_RDONLY);
638 	if (fd < 0)
639 		goto out;
640 
641 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
642 	if (elf == NULL) {
643 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
644 		goto out_close;
645 	}
646 
647 	err = elf_read_build_id(elf, bid->data, size);
648 	if (err > 0)
649 		bid->size = err;
650 
651 	elf_end(elf);
652 out_close:
653 	close(fd);
654 out:
655 	return err;
656 }
657 
658 #endif // HAVE_LIBBFD_BUILDID_SUPPORT
659 
660 int filename__read_build_id(const char *filename, struct build_id *bid)
661 {
662 	struct kmod_path m = { .name = NULL, };
663 	char path[PATH_MAX];
664 	int err;
665 
666 	if (!filename)
667 		return -EFAULT;
668 
669 	err = kmod_path__parse(&m, filename);
670 	if (err)
671 		return -1;
672 
673 	if (m.comp) {
674 		int error = 0, fd;
675 
676 		fd = filename__decompress(filename, path, sizeof(path), m.comp, &error);
677 		if (fd < 0) {
678 			pr_debug("Failed to decompress (error %d) %s\n",
679 				 error, filename);
680 			return -1;
681 		}
682 		close(fd);
683 		filename = path;
684 	}
685 
686 	err = read_build_id(filename, bid);
687 
688 	if (m.comp)
689 		unlink(filename);
690 	return err;
691 }
692 
693 int sysfs__read_build_id(const char *filename, struct build_id *bid)
694 {
695 	size_t size = sizeof(bid->data);
696 	int fd, err = -1;
697 
698 	fd = open(filename, O_RDONLY);
699 	if (fd < 0)
700 		goto out;
701 
702 	while (1) {
703 		char bf[BUFSIZ];
704 		GElf_Nhdr nhdr;
705 		size_t namesz, descsz;
706 
707 		if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
708 			break;
709 
710 		namesz = NOTE_ALIGN(nhdr.n_namesz);
711 		descsz = NOTE_ALIGN(nhdr.n_descsz);
712 		if (nhdr.n_type == NT_GNU_BUILD_ID &&
713 		    nhdr.n_namesz == sizeof("GNU")) {
714 			if (read(fd, bf, namesz) != (ssize_t)namesz)
715 				break;
716 			if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
717 				size_t sz = min(descsz, size);
718 				if (read(fd, bid->data, sz) == (ssize_t)sz) {
719 					memset(bid->data + sz, 0, size - sz);
720 					bid->size = sz;
721 					err = 0;
722 					break;
723 				}
724 			} else if (read(fd, bf, descsz) != (ssize_t)descsz)
725 				break;
726 		} else {
727 			int n = namesz + descsz;
728 
729 			if (n > (int)sizeof(bf)) {
730 				n = sizeof(bf);
731 				pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
732 					 __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
733 			}
734 			if (read(fd, bf, n) != n)
735 				break;
736 		}
737 	}
738 	close(fd);
739 out:
740 	return err;
741 }
742 
743 #ifdef HAVE_LIBBFD_SUPPORT
744 
745 int filename__read_debuglink(const char *filename, char *debuglink,
746 			     size_t size)
747 {
748 	int err = -1;
749 	asection *section;
750 	bfd *abfd;
751 
752 	abfd = bfd_openr(filename, NULL);
753 	if (!abfd)
754 		return -1;
755 
756 	if (!bfd_check_format(abfd, bfd_object)) {
757 		pr_debug2("%s: cannot read %s bfd file.\n", __func__, filename);
758 		goto out_close;
759 	}
760 
761 	section = bfd_get_section_by_name(abfd, ".gnu_debuglink");
762 	if (!section)
763 		goto out_close;
764 
765 	if (section->size > size)
766 		goto out_close;
767 
768 	if (!bfd_get_section_contents(abfd, section, debuglink, 0,
769 				      section->size))
770 		goto out_close;
771 
772 	err = 0;
773 
774 out_close:
775 	bfd_close(abfd);
776 	return err;
777 }
778 
779 #else
780 
781 int filename__read_debuglink(const char *filename, char *debuglink,
782 			     size_t size)
783 {
784 	int fd, err = -1;
785 	Elf *elf;
786 	GElf_Ehdr ehdr;
787 	GElf_Shdr shdr;
788 	Elf_Data *data;
789 	Elf_Scn *sec;
790 	Elf_Kind ek;
791 
792 	fd = open(filename, O_RDONLY);
793 	if (fd < 0)
794 		goto out;
795 
796 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
797 	if (elf == NULL) {
798 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
799 		goto out_close;
800 	}
801 
802 	ek = elf_kind(elf);
803 	if (ek != ELF_K_ELF)
804 		goto out_elf_end;
805 
806 	if (gelf_getehdr(elf, &ehdr) == NULL) {
807 		pr_err("%s: cannot get elf header.\n", __func__);
808 		goto out_elf_end;
809 	}
810 
811 	sec = elf_section_by_name(elf, &ehdr, &shdr,
812 				  ".gnu_debuglink", NULL);
813 	if (sec == NULL)
814 		goto out_elf_end;
815 
816 	data = elf_getdata(sec, NULL);
817 	if (data == NULL)
818 		goto out_elf_end;
819 
820 	/* the start of this section is a zero-terminated string */
821 	strncpy(debuglink, data->d_buf, size);
822 
823 	err = 0;
824 
825 out_elf_end:
826 	elf_end(elf);
827 out_close:
828 	close(fd);
829 out:
830 	return err;
831 }
832 
833 #endif
834 
835 static int dso__swap_init(struct dso *dso, unsigned char eidata)
836 {
837 	static unsigned int const endian = 1;
838 
839 	dso->needs_swap = DSO_SWAP__NO;
840 
841 	switch (eidata) {
842 	case ELFDATA2LSB:
843 		/* We are big endian, DSO is little endian. */
844 		if (*(unsigned char const *)&endian != 1)
845 			dso->needs_swap = DSO_SWAP__YES;
846 		break;
847 
848 	case ELFDATA2MSB:
849 		/* We are little endian, DSO is big endian. */
850 		if (*(unsigned char const *)&endian != 0)
851 			dso->needs_swap = DSO_SWAP__YES;
852 		break;
853 
854 	default:
855 		pr_err("unrecognized DSO data encoding %d\n", eidata);
856 		return -EINVAL;
857 	}
858 
859 	return 0;
860 }
861 
862 bool symsrc__possibly_runtime(struct symsrc *ss)
863 {
864 	return ss->dynsym || ss->opdsec;
865 }
866 
867 bool symsrc__has_symtab(struct symsrc *ss)
868 {
869 	return ss->symtab != NULL;
870 }
871 
872 void symsrc__destroy(struct symsrc *ss)
873 {
874 	zfree(&ss->name);
875 	elf_end(ss->elf);
876 	close(ss->fd);
877 }
878 
879 bool elf__needs_adjust_symbols(GElf_Ehdr ehdr)
880 {
881 	/*
882 	 * Usually vmlinux is an ELF file with type ET_EXEC for most
883 	 * architectures; except Arm64 kernel is linked with option
884 	 * '-share', so need to check type ET_DYN.
885 	 */
886 	return ehdr.e_type == ET_EXEC || ehdr.e_type == ET_REL ||
887 	       ehdr.e_type == ET_DYN;
888 }
889 
890 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
891 		 enum dso_binary_type type)
892 {
893 	GElf_Ehdr ehdr;
894 	Elf *elf;
895 	int fd;
896 
897 	if (dso__needs_decompress(dso)) {
898 		fd = dso__decompress_kmodule_fd(dso, name);
899 		if (fd < 0)
900 			return -1;
901 
902 		type = dso->symtab_type;
903 	} else {
904 		fd = open(name, O_RDONLY);
905 		if (fd < 0) {
906 			dso->load_errno = errno;
907 			return -1;
908 		}
909 	}
910 
911 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
912 	if (elf == NULL) {
913 		pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
914 		dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
915 		goto out_close;
916 	}
917 
918 	if (gelf_getehdr(elf, &ehdr) == NULL) {
919 		dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
920 		pr_debug("%s: cannot get elf header.\n", __func__);
921 		goto out_elf_end;
922 	}
923 
924 	if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
925 		dso->load_errno = DSO_LOAD_ERRNO__INTERNAL_ERROR;
926 		goto out_elf_end;
927 	}
928 
929 	/* Always reject images with a mismatched build-id: */
930 	if (dso->has_build_id && !symbol_conf.ignore_vmlinux_buildid) {
931 		u8 build_id[BUILD_ID_SIZE];
932 		struct build_id bid;
933 		int size;
934 
935 		size = elf_read_build_id(elf, build_id, BUILD_ID_SIZE);
936 		if (size <= 0) {
937 			dso->load_errno = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
938 			goto out_elf_end;
939 		}
940 
941 		build_id__init(&bid, build_id, size);
942 		if (!dso__build_id_equal(dso, &bid)) {
943 			pr_debug("%s: build id mismatch for %s.\n", __func__, name);
944 			dso->load_errno = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
945 			goto out_elf_end;
946 		}
947 	}
948 
949 	ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
950 
951 	ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
952 			NULL);
953 	if (ss->symshdr.sh_type != SHT_SYMTAB)
954 		ss->symtab = NULL;
955 
956 	ss->dynsym_idx = 0;
957 	ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
958 			&ss->dynsym_idx);
959 	if (ss->dynshdr.sh_type != SHT_DYNSYM)
960 		ss->dynsym = NULL;
961 
962 	ss->opdidx = 0;
963 	ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
964 			&ss->opdidx);
965 	if (ss->opdshdr.sh_type != SHT_PROGBITS)
966 		ss->opdsec = NULL;
967 
968 	if (dso->kernel == DSO_SPACE__USER)
969 		ss->adjust_symbols = true;
970 	else
971 		ss->adjust_symbols = elf__needs_adjust_symbols(ehdr);
972 
973 	ss->name   = strdup(name);
974 	if (!ss->name) {
975 		dso->load_errno = errno;
976 		goto out_elf_end;
977 	}
978 
979 	ss->elf    = elf;
980 	ss->fd     = fd;
981 	ss->ehdr   = ehdr;
982 	ss->type   = type;
983 
984 	return 0;
985 
986 out_elf_end:
987 	elf_end(elf);
988 out_close:
989 	close(fd);
990 	return -1;
991 }
992 
993 /**
994  * ref_reloc_sym_not_found - has kernel relocation symbol been found.
995  * @kmap: kernel maps and relocation reference symbol
996  *
997  * This function returns %true if we are dealing with the kernel maps and the
998  * relocation reference symbol has not yet been found.  Otherwise %false is
999  * returned.
1000  */
1001 static bool ref_reloc_sym_not_found(struct kmap *kmap)
1002 {
1003 	return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
1004 	       !kmap->ref_reloc_sym->unrelocated_addr;
1005 }
1006 
1007 /**
1008  * ref_reloc - kernel relocation offset.
1009  * @kmap: kernel maps and relocation reference symbol
1010  *
1011  * This function returns the offset of kernel addresses as determined by using
1012  * the relocation reference symbol i.e. if the kernel has not been relocated
1013  * then the return value is zero.
1014  */
1015 static u64 ref_reloc(struct kmap *kmap)
1016 {
1017 	if (kmap && kmap->ref_reloc_sym &&
1018 	    kmap->ref_reloc_sym->unrelocated_addr)
1019 		return kmap->ref_reloc_sym->addr -
1020 		       kmap->ref_reloc_sym->unrelocated_addr;
1021 	return 0;
1022 }
1023 
1024 void __weak arch__sym_update(struct symbol *s __maybe_unused,
1025 		GElf_Sym *sym __maybe_unused) { }
1026 
1027 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
1028 				      GElf_Sym *sym, GElf_Shdr *shdr,
1029 				      struct maps *kmaps, struct kmap *kmap,
1030 				      struct dso **curr_dsop, struct map **curr_mapp,
1031 				      const char *section_name,
1032 				      bool adjust_kernel_syms, bool kmodule, bool *remap_kernel)
1033 {
1034 	struct dso *curr_dso = *curr_dsop;
1035 	struct map *curr_map;
1036 	char dso_name[PATH_MAX];
1037 
1038 	/* Adjust symbol to map to file offset */
1039 	if (adjust_kernel_syms)
1040 		sym->st_value -= shdr->sh_addr - shdr->sh_offset;
1041 
1042 	if (strcmp(section_name, (curr_dso->short_name + dso->short_name_len)) == 0)
1043 		return 0;
1044 
1045 	if (strcmp(section_name, ".text") == 0) {
1046 		/*
1047 		 * The initial kernel mapping is based on
1048 		 * kallsyms and identity maps.  Overwrite it to
1049 		 * map to the kernel dso.
1050 		 */
1051 		if (*remap_kernel && dso->kernel && !kmodule) {
1052 			*remap_kernel = false;
1053 			map->start = shdr->sh_addr + ref_reloc(kmap);
1054 			map->end = map->start + shdr->sh_size;
1055 			map->pgoff = shdr->sh_offset;
1056 			map->map_ip = map__map_ip;
1057 			map->unmap_ip = map__unmap_ip;
1058 			/* Ensure maps are correctly ordered */
1059 			if (kmaps) {
1060 				map__get(map);
1061 				maps__remove(kmaps, map);
1062 				maps__insert(kmaps, map);
1063 				map__put(map);
1064 			}
1065 		}
1066 
1067 		/*
1068 		 * The initial module mapping is based on
1069 		 * /proc/modules mapped to offset zero.
1070 		 * Overwrite it to map to the module dso.
1071 		 */
1072 		if (*remap_kernel && kmodule) {
1073 			*remap_kernel = false;
1074 			map->pgoff = shdr->sh_offset;
1075 		}
1076 
1077 		*curr_mapp = map;
1078 		*curr_dsop = dso;
1079 		return 0;
1080 	}
1081 
1082 	if (!kmap)
1083 		return 0;
1084 
1085 	snprintf(dso_name, sizeof(dso_name), "%s%s", dso->short_name, section_name);
1086 
1087 	curr_map = maps__find_by_name(kmaps, dso_name);
1088 	if (curr_map == NULL) {
1089 		u64 start = sym->st_value;
1090 
1091 		if (kmodule)
1092 			start += map->start + shdr->sh_offset;
1093 
1094 		curr_dso = dso__new(dso_name);
1095 		if (curr_dso == NULL)
1096 			return -1;
1097 		curr_dso->kernel = dso->kernel;
1098 		curr_dso->long_name = dso->long_name;
1099 		curr_dso->long_name_len = dso->long_name_len;
1100 		curr_map = map__new2(start, curr_dso);
1101 		dso__put(curr_dso);
1102 		if (curr_map == NULL)
1103 			return -1;
1104 
1105 		if (curr_dso->kernel)
1106 			map__kmap(curr_map)->kmaps = kmaps;
1107 
1108 		if (adjust_kernel_syms) {
1109 			curr_map->start  = shdr->sh_addr + ref_reloc(kmap);
1110 			curr_map->end	 = curr_map->start + shdr->sh_size;
1111 			curr_map->pgoff	 = shdr->sh_offset;
1112 		} else {
1113 			curr_map->map_ip = curr_map->unmap_ip = identity__map_ip;
1114 		}
1115 		curr_dso->symtab_type = dso->symtab_type;
1116 		maps__insert(kmaps, curr_map);
1117 		/*
1118 		 * Add it before we drop the reference to curr_map, i.e. while
1119 		 * we still are sure to have a reference to this DSO via
1120 		 * *curr_map->dso.
1121 		 */
1122 		dsos__add(&kmaps->machine->dsos, curr_dso);
1123 		/* kmaps already got it */
1124 		map__put(curr_map);
1125 		dso__set_loaded(curr_dso);
1126 		*curr_mapp = curr_map;
1127 		*curr_dsop = curr_dso;
1128 	} else
1129 		*curr_dsop = curr_map->dso;
1130 
1131 	return 0;
1132 }
1133 
1134 static int
1135 dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1136 		       struct symsrc *runtime_ss, int kmodule, int dynsym)
1137 {
1138 	struct kmap *kmap = dso->kernel ? map__kmap(map) : NULL;
1139 	struct maps *kmaps = kmap ? map__kmaps(map) : NULL;
1140 	struct map *curr_map = map;
1141 	struct dso *curr_dso = dso;
1142 	Elf_Data *symstrs, *secstrs, *secstrs_run, *secstrs_sym;
1143 	uint32_t nr_syms;
1144 	int err = -1;
1145 	uint32_t idx;
1146 	GElf_Ehdr ehdr;
1147 	GElf_Shdr shdr;
1148 	GElf_Shdr tshdr;
1149 	Elf_Data *syms, *opddata = NULL;
1150 	GElf_Sym sym;
1151 	Elf_Scn *sec, *sec_strndx;
1152 	Elf *elf;
1153 	int nr = 0;
1154 	bool remap_kernel = false, adjust_kernel_syms = false;
1155 
1156 	if (kmap && !kmaps)
1157 		return -1;
1158 
1159 	elf = syms_ss->elf;
1160 	ehdr = syms_ss->ehdr;
1161 	if (dynsym) {
1162 		sec  = syms_ss->dynsym;
1163 		shdr = syms_ss->dynshdr;
1164 	} else {
1165 		sec =  syms_ss->symtab;
1166 		shdr = syms_ss->symshdr;
1167 	}
1168 
1169 	if (elf_section_by_name(runtime_ss->elf, &runtime_ss->ehdr, &tshdr,
1170 				".text", NULL))
1171 		dso->text_offset = tshdr.sh_addr - tshdr.sh_offset;
1172 
1173 	if (runtime_ss->opdsec)
1174 		opddata = elf_rawdata(runtime_ss->opdsec, NULL);
1175 
1176 	syms = elf_getdata(sec, NULL);
1177 	if (syms == NULL)
1178 		goto out_elf_end;
1179 
1180 	sec = elf_getscn(elf, shdr.sh_link);
1181 	if (sec == NULL)
1182 		goto out_elf_end;
1183 
1184 	symstrs = elf_getdata(sec, NULL);
1185 	if (symstrs == NULL)
1186 		goto out_elf_end;
1187 
1188 	sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
1189 	if (sec_strndx == NULL)
1190 		goto out_elf_end;
1191 
1192 	secstrs_run = elf_getdata(sec_strndx, NULL);
1193 	if (secstrs_run == NULL)
1194 		goto out_elf_end;
1195 
1196 	sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
1197 	if (sec_strndx == NULL)
1198 		goto out_elf_end;
1199 
1200 	secstrs_sym = elf_getdata(sec_strndx, NULL);
1201 	if (secstrs_sym == NULL)
1202 		goto out_elf_end;
1203 
1204 	nr_syms = shdr.sh_size / shdr.sh_entsize;
1205 
1206 	memset(&sym, 0, sizeof(sym));
1207 
1208 	/*
1209 	 * The kernel relocation symbol is needed in advance in order to adjust
1210 	 * kernel maps correctly.
1211 	 */
1212 	if (ref_reloc_sym_not_found(kmap)) {
1213 		elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1214 			const char *elf_name = elf_sym__name(&sym, symstrs);
1215 
1216 			if (strcmp(elf_name, kmap->ref_reloc_sym->name))
1217 				continue;
1218 			kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
1219 			map->reloc = kmap->ref_reloc_sym->addr -
1220 				     kmap->ref_reloc_sym->unrelocated_addr;
1221 			break;
1222 		}
1223 	}
1224 
1225 	/*
1226 	 * Handle any relocation of vdso necessary because older kernels
1227 	 * attempted to prelink vdso to its virtual address.
1228 	 */
1229 	if (dso__is_vdso(dso))
1230 		map->reloc = map->start - dso->text_offset;
1231 
1232 	dso->adjust_symbols = runtime_ss->adjust_symbols || ref_reloc(kmap);
1233 	/*
1234 	 * Initial kernel and module mappings do not map to the dso.
1235 	 * Flag the fixups.
1236 	 */
1237 	if (dso->kernel) {
1238 		remap_kernel = true;
1239 		adjust_kernel_syms = dso->adjust_symbols;
1240 	}
1241 	elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1242 		struct symbol *f;
1243 		const char *elf_name = elf_sym__name(&sym, symstrs);
1244 		char *demangled = NULL;
1245 		int is_label = elf_sym__is_label(&sym);
1246 		const char *section_name;
1247 		bool used_opd = false;
1248 
1249 		if (!is_label && !elf_sym__filter(&sym))
1250 			continue;
1251 
1252 		/* Reject ARM ELF "mapping symbols": these aren't unique and
1253 		 * don't identify functions, so will confuse the profile
1254 		 * output: */
1255 		if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
1256 			if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
1257 			    && (elf_name[2] == '\0' || elf_name[2] == '.'))
1258 				continue;
1259 		}
1260 
1261 		if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
1262 			u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
1263 			u64 *opd = opddata->d_buf + offset;
1264 			sym.st_value = DSO__SWAP(dso, u64, *opd);
1265 			sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
1266 					sym.st_value);
1267 			used_opd = true;
1268 		}
1269 
1270 		/*
1271 		 * When loading symbols in a data mapping, ABS symbols (which
1272 		 * has a value of SHN_ABS in its st_shndx) failed at
1273 		 * elf_getscn().  And it marks the loading as a failure so
1274 		 * already loaded symbols cannot be fixed up.
1275 		 *
1276 		 * I'm not sure what should be done. Just ignore them for now.
1277 		 * - Namhyung Kim
1278 		 */
1279 		if (sym.st_shndx == SHN_ABS)
1280 			continue;
1281 
1282 		sec = elf_getscn(syms_ss->elf, sym.st_shndx);
1283 		if (!sec)
1284 			goto out_elf_end;
1285 
1286 		gelf_getshdr(sec, &shdr);
1287 
1288 		/*
1289 		 * If the attribute bit SHF_ALLOC is not set, the section
1290 		 * doesn't occupy memory during process execution.
1291 		 * E.g. ".gnu.warning.*" section is used by linker to generate
1292 		 * warnings when calling deprecated functions, the symbols in
1293 		 * the section aren't loaded to memory during process execution,
1294 		 * so skip them.
1295 		 */
1296 		if (!(shdr.sh_flags & SHF_ALLOC))
1297 			continue;
1298 
1299 		secstrs = secstrs_sym;
1300 
1301 		/*
1302 		 * We have to fallback to runtime when syms' section header has
1303 		 * NOBITS set. NOBITS results in file offset (sh_offset) not
1304 		 * being incremented. So sh_offset used below has different
1305 		 * values for syms (invalid) and runtime (valid).
1306 		 */
1307 		if (shdr.sh_type == SHT_NOBITS) {
1308 			sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
1309 			if (!sec)
1310 				goto out_elf_end;
1311 
1312 			gelf_getshdr(sec, &shdr);
1313 			secstrs = secstrs_run;
1314 		}
1315 
1316 		if (is_label && !elf_sec__filter(&shdr, secstrs))
1317 			continue;
1318 
1319 		section_name = elf_sec__name(&shdr, secstrs);
1320 
1321 		/* On ARM, symbols for thumb functions have 1 added to
1322 		 * the symbol address as a flag - remove it */
1323 		if ((ehdr.e_machine == EM_ARM) &&
1324 		    (GELF_ST_TYPE(sym.st_info) == STT_FUNC) &&
1325 		    (sym.st_value & 1))
1326 			--sym.st_value;
1327 
1328 		if (dso->kernel) {
1329 			if (dso__process_kernel_symbol(dso, map, &sym, &shdr, kmaps, kmap, &curr_dso, &curr_map,
1330 						       section_name, adjust_kernel_syms, kmodule, &remap_kernel))
1331 				goto out_elf_end;
1332 		} else if ((used_opd && runtime_ss->adjust_symbols) ||
1333 			   (!used_opd && syms_ss->adjust_symbols)) {
1334 			GElf_Phdr phdr;
1335 
1336 			if (elf_read_program_header(runtime_ss->elf,
1337 						    (u64)sym.st_value, &phdr)) {
1338 				pr_debug4("%s: failed to find program header for "
1339 					   "symbol: %s st_value: %#" PRIx64 "\n",
1340 					   __func__, elf_name, (u64)sym.st_value);
1341 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1342 					"sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n",
1343 					__func__, (u64)sym.st_value, (u64)shdr.sh_addr,
1344 					(u64)shdr.sh_offset);
1345 				/*
1346 				 * Fail to find program header, let's rollback
1347 				 * to use shdr.sh_addr and shdr.sh_offset to
1348 				 * calibrate symbol's file address, though this
1349 				 * is not necessary for normal C ELF file, we
1350 				 * still need to handle java JIT symbols in this
1351 				 * case.
1352 				 */
1353 				sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1354 			} else {
1355 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1356 					"p_vaddr: %#" PRIx64 " p_offset: %#" PRIx64 "\n",
1357 					__func__, (u64)sym.st_value, (u64)phdr.p_vaddr,
1358 					(u64)phdr.p_offset);
1359 				sym.st_value -= phdr.p_vaddr - phdr.p_offset;
1360 			}
1361 		}
1362 
1363 		demangled = demangle_sym(dso, kmodule, elf_name);
1364 		if (demangled != NULL)
1365 			elf_name = demangled;
1366 
1367 		f = symbol__new(sym.st_value, sym.st_size,
1368 				GELF_ST_BIND(sym.st_info),
1369 				GELF_ST_TYPE(sym.st_info), elf_name);
1370 		free(demangled);
1371 		if (!f)
1372 			goto out_elf_end;
1373 
1374 		arch__sym_update(f, &sym);
1375 
1376 		__symbols__insert(&curr_dso->symbols, f, dso->kernel);
1377 		nr++;
1378 	}
1379 
1380 	/*
1381 	 * For misannotated, zeroed, ASM function sizes.
1382 	 */
1383 	if (nr > 0) {
1384 		symbols__fixup_end(&dso->symbols, false);
1385 		symbols__fixup_duplicate(&dso->symbols);
1386 		if (kmap) {
1387 			/*
1388 			 * We need to fixup this here too because we create new
1389 			 * maps here, for things like vsyscall sections.
1390 			 */
1391 			maps__fixup_end(kmaps);
1392 		}
1393 	}
1394 	err = nr;
1395 out_elf_end:
1396 	return err;
1397 }
1398 
1399 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1400 		  struct symsrc *runtime_ss, int kmodule)
1401 {
1402 	int nr = 0;
1403 	int err = -1;
1404 
1405 	dso->symtab_type = syms_ss->type;
1406 	dso->is_64_bit = syms_ss->is_64_bit;
1407 	dso->rel = syms_ss->ehdr.e_type == ET_REL;
1408 
1409 	/*
1410 	 * Modules may already have symbols from kallsyms, but those symbols
1411 	 * have the wrong values for the dso maps, so remove them.
1412 	 */
1413 	if (kmodule && syms_ss->symtab)
1414 		symbols__delete(&dso->symbols);
1415 
1416 	if (!syms_ss->symtab) {
1417 		/*
1418 		 * If the vmlinux is stripped, fail so we will fall back
1419 		 * to using kallsyms. The vmlinux runtime symbols aren't
1420 		 * of much use.
1421 		 */
1422 		if (dso->kernel)
1423 			return err;
1424 	} else  {
1425 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1426 					     kmodule, 0);
1427 		if (err < 0)
1428 			return err;
1429 		nr = err;
1430 	}
1431 
1432 	if (syms_ss->dynsym) {
1433 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1434 					     kmodule, 1);
1435 		if (err < 0)
1436 			return err;
1437 		err += nr;
1438 	}
1439 
1440 	return err;
1441 }
1442 
1443 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1444 {
1445 	GElf_Phdr phdr;
1446 	size_t i, phdrnum;
1447 	int err;
1448 	u64 sz;
1449 
1450 	if (elf_getphdrnum(elf, &phdrnum))
1451 		return -1;
1452 
1453 	for (i = 0; i < phdrnum; i++) {
1454 		if (gelf_getphdr(elf, i, &phdr) == NULL)
1455 			return -1;
1456 		if (phdr.p_type != PT_LOAD)
1457 			continue;
1458 		if (exe) {
1459 			if (!(phdr.p_flags & PF_X))
1460 				continue;
1461 		} else {
1462 			if (!(phdr.p_flags & PF_R))
1463 				continue;
1464 		}
1465 		sz = min(phdr.p_memsz, phdr.p_filesz);
1466 		if (!sz)
1467 			continue;
1468 		err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1469 		if (err)
1470 			return err;
1471 	}
1472 	return 0;
1473 }
1474 
1475 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1476 		    bool *is_64_bit)
1477 {
1478 	int err;
1479 	Elf *elf;
1480 
1481 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1482 	if (elf == NULL)
1483 		return -1;
1484 
1485 	if (is_64_bit)
1486 		*is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1487 
1488 	err = elf_read_maps(elf, exe, mapfn, data);
1489 
1490 	elf_end(elf);
1491 	return err;
1492 }
1493 
1494 enum dso_type dso__type_fd(int fd)
1495 {
1496 	enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1497 	GElf_Ehdr ehdr;
1498 	Elf_Kind ek;
1499 	Elf *elf;
1500 
1501 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1502 	if (elf == NULL)
1503 		goto out;
1504 
1505 	ek = elf_kind(elf);
1506 	if (ek != ELF_K_ELF)
1507 		goto out_end;
1508 
1509 	if (gelf_getclass(elf) == ELFCLASS64) {
1510 		dso_type = DSO__TYPE_64BIT;
1511 		goto out_end;
1512 	}
1513 
1514 	if (gelf_getehdr(elf, &ehdr) == NULL)
1515 		goto out_end;
1516 
1517 	if (ehdr.e_machine == EM_X86_64)
1518 		dso_type = DSO__TYPE_X32BIT;
1519 	else
1520 		dso_type = DSO__TYPE_32BIT;
1521 out_end:
1522 	elf_end(elf);
1523 out:
1524 	return dso_type;
1525 }
1526 
1527 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1528 {
1529 	ssize_t r;
1530 	size_t n;
1531 	int err = -1;
1532 	char *buf = malloc(page_size);
1533 
1534 	if (buf == NULL)
1535 		return -1;
1536 
1537 	if (lseek(to, to_offs, SEEK_SET) != to_offs)
1538 		goto out;
1539 
1540 	if (lseek(from, from_offs, SEEK_SET) != from_offs)
1541 		goto out;
1542 
1543 	while (len) {
1544 		n = page_size;
1545 		if (len < n)
1546 			n = len;
1547 		/* Use read because mmap won't work on proc files */
1548 		r = read(from, buf, n);
1549 		if (r < 0)
1550 			goto out;
1551 		if (!r)
1552 			break;
1553 		n = r;
1554 		r = write(to, buf, n);
1555 		if (r < 0)
1556 			goto out;
1557 		if ((size_t)r != n)
1558 			goto out;
1559 		len -= n;
1560 	}
1561 
1562 	err = 0;
1563 out:
1564 	free(buf);
1565 	return err;
1566 }
1567 
1568 struct kcore {
1569 	int fd;
1570 	int elfclass;
1571 	Elf *elf;
1572 	GElf_Ehdr ehdr;
1573 };
1574 
1575 static int kcore__open(struct kcore *kcore, const char *filename)
1576 {
1577 	GElf_Ehdr *ehdr;
1578 
1579 	kcore->fd = open(filename, O_RDONLY);
1580 	if (kcore->fd == -1)
1581 		return -1;
1582 
1583 	kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1584 	if (!kcore->elf)
1585 		goto out_close;
1586 
1587 	kcore->elfclass = gelf_getclass(kcore->elf);
1588 	if (kcore->elfclass == ELFCLASSNONE)
1589 		goto out_end;
1590 
1591 	ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1592 	if (!ehdr)
1593 		goto out_end;
1594 
1595 	return 0;
1596 
1597 out_end:
1598 	elf_end(kcore->elf);
1599 out_close:
1600 	close(kcore->fd);
1601 	return -1;
1602 }
1603 
1604 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1605 		       bool temp)
1606 {
1607 	kcore->elfclass = elfclass;
1608 
1609 	if (temp)
1610 		kcore->fd = mkstemp(filename);
1611 	else
1612 		kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0400);
1613 	if (kcore->fd == -1)
1614 		return -1;
1615 
1616 	kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1617 	if (!kcore->elf)
1618 		goto out_close;
1619 
1620 	if (!gelf_newehdr(kcore->elf, elfclass))
1621 		goto out_end;
1622 
1623 	memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
1624 
1625 	return 0;
1626 
1627 out_end:
1628 	elf_end(kcore->elf);
1629 out_close:
1630 	close(kcore->fd);
1631 	unlink(filename);
1632 	return -1;
1633 }
1634 
1635 static void kcore__close(struct kcore *kcore)
1636 {
1637 	elf_end(kcore->elf);
1638 	close(kcore->fd);
1639 }
1640 
1641 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
1642 {
1643 	GElf_Ehdr *ehdr = &to->ehdr;
1644 	GElf_Ehdr *kehdr = &from->ehdr;
1645 
1646 	memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
1647 	ehdr->e_type      = kehdr->e_type;
1648 	ehdr->e_machine   = kehdr->e_machine;
1649 	ehdr->e_version   = kehdr->e_version;
1650 	ehdr->e_entry     = 0;
1651 	ehdr->e_shoff     = 0;
1652 	ehdr->e_flags     = kehdr->e_flags;
1653 	ehdr->e_phnum     = count;
1654 	ehdr->e_shentsize = 0;
1655 	ehdr->e_shnum     = 0;
1656 	ehdr->e_shstrndx  = 0;
1657 
1658 	if (from->elfclass == ELFCLASS32) {
1659 		ehdr->e_phoff     = sizeof(Elf32_Ehdr);
1660 		ehdr->e_ehsize    = sizeof(Elf32_Ehdr);
1661 		ehdr->e_phentsize = sizeof(Elf32_Phdr);
1662 	} else {
1663 		ehdr->e_phoff     = sizeof(Elf64_Ehdr);
1664 		ehdr->e_ehsize    = sizeof(Elf64_Ehdr);
1665 		ehdr->e_phentsize = sizeof(Elf64_Phdr);
1666 	}
1667 
1668 	if (!gelf_update_ehdr(to->elf, ehdr))
1669 		return -1;
1670 
1671 	if (!gelf_newphdr(to->elf, count))
1672 		return -1;
1673 
1674 	return 0;
1675 }
1676 
1677 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
1678 			   u64 addr, u64 len)
1679 {
1680 	GElf_Phdr phdr = {
1681 		.p_type		= PT_LOAD,
1682 		.p_flags	= PF_R | PF_W | PF_X,
1683 		.p_offset	= offset,
1684 		.p_vaddr	= addr,
1685 		.p_paddr	= 0,
1686 		.p_filesz	= len,
1687 		.p_memsz	= len,
1688 		.p_align	= page_size,
1689 	};
1690 
1691 	if (!gelf_update_phdr(kcore->elf, idx, &phdr))
1692 		return -1;
1693 
1694 	return 0;
1695 }
1696 
1697 static off_t kcore__write(struct kcore *kcore)
1698 {
1699 	return elf_update(kcore->elf, ELF_C_WRITE);
1700 }
1701 
1702 struct phdr_data {
1703 	off_t offset;
1704 	off_t rel;
1705 	u64 addr;
1706 	u64 len;
1707 	struct list_head node;
1708 	struct phdr_data *remaps;
1709 };
1710 
1711 struct sym_data {
1712 	u64 addr;
1713 	struct list_head node;
1714 };
1715 
1716 struct kcore_copy_info {
1717 	u64 stext;
1718 	u64 etext;
1719 	u64 first_symbol;
1720 	u64 last_symbol;
1721 	u64 first_module;
1722 	u64 first_module_symbol;
1723 	u64 last_module_symbol;
1724 	size_t phnum;
1725 	struct list_head phdrs;
1726 	struct list_head syms;
1727 };
1728 
1729 #define kcore_copy__for_each_phdr(k, p) \
1730 	list_for_each_entry((p), &(k)->phdrs, node)
1731 
1732 static struct phdr_data *phdr_data__new(u64 addr, u64 len, off_t offset)
1733 {
1734 	struct phdr_data *p = zalloc(sizeof(*p));
1735 
1736 	if (p) {
1737 		p->addr   = addr;
1738 		p->len    = len;
1739 		p->offset = offset;
1740 	}
1741 
1742 	return p;
1743 }
1744 
1745 static struct phdr_data *kcore_copy_info__addnew(struct kcore_copy_info *kci,
1746 						 u64 addr, u64 len,
1747 						 off_t offset)
1748 {
1749 	struct phdr_data *p = phdr_data__new(addr, len, offset);
1750 
1751 	if (p)
1752 		list_add_tail(&p->node, &kci->phdrs);
1753 
1754 	return p;
1755 }
1756 
1757 static void kcore_copy__free_phdrs(struct kcore_copy_info *kci)
1758 {
1759 	struct phdr_data *p, *tmp;
1760 
1761 	list_for_each_entry_safe(p, tmp, &kci->phdrs, node) {
1762 		list_del_init(&p->node);
1763 		free(p);
1764 	}
1765 }
1766 
1767 static struct sym_data *kcore_copy__new_sym(struct kcore_copy_info *kci,
1768 					    u64 addr)
1769 {
1770 	struct sym_data *s = zalloc(sizeof(*s));
1771 
1772 	if (s) {
1773 		s->addr = addr;
1774 		list_add_tail(&s->node, &kci->syms);
1775 	}
1776 
1777 	return s;
1778 }
1779 
1780 static void kcore_copy__free_syms(struct kcore_copy_info *kci)
1781 {
1782 	struct sym_data *s, *tmp;
1783 
1784 	list_for_each_entry_safe(s, tmp, &kci->syms, node) {
1785 		list_del_init(&s->node);
1786 		free(s);
1787 	}
1788 }
1789 
1790 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
1791 					u64 start)
1792 {
1793 	struct kcore_copy_info *kci = arg;
1794 
1795 	if (!kallsyms__is_function(type))
1796 		return 0;
1797 
1798 	if (strchr(name, '[')) {
1799 		if (!kci->first_module_symbol || start < kci->first_module_symbol)
1800 			kci->first_module_symbol = start;
1801 		if (start > kci->last_module_symbol)
1802 			kci->last_module_symbol = start;
1803 		return 0;
1804 	}
1805 
1806 	if (!kci->first_symbol || start < kci->first_symbol)
1807 		kci->first_symbol = start;
1808 
1809 	if (!kci->last_symbol || start > kci->last_symbol)
1810 		kci->last_symbol = start;
1811 
1812 	if (!strcmp(name, "_stext")) {
1813 		kci->stext = start;
1814 		return 0;
1815 	}
1816 
1817 	if (!strcmp(name, "_etext")) {
1818 		kci->etext = start;
1819 		return 0;
1820 	}
1821 
1822 	if (is_entry_trampoline(name) && !kcore_copy__new_sym(kci, start))
1823 		return -1;
1824 
1825 	return 0;
1826 }
1827 
1828 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
1829 				      const char *dir)
1830 {
1831 	char kallsyms_filename[PATH_MAX];
1832 
1833 	scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
1834 
1835 	if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
1836 		return -1;
1837 
1838 	if (kallsyms__parse(kallsyms_filename, kci,
1839 			    kcore_copy__process_kallsyms) < 0)
1840 		return -1;
1841 
1842 	return 0;
1843 }
1844 
1845 static int kcore_copy__process_modules(void *arg,
1846 				       const char *name __maybe_unused,
1847 				       u64 start, u64 size __maybe_unused)
1848 {
1849 	struct kcore_copy_info *kci = arg;
1850 
1851 	if (!kci->first_module || start < kci->first_module)
1852 		kci->first_module = start;
1853 
1854 	return 0;
1855 }
1856 
1857 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
1858 				     const char *dir)
1859 {
1860 	char modules_filename[PATH_MAX];
1861 
1862 	scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
1863 
1864 	if (symbol__restricted_filename(modules_filename, "/proc/modules"))
1865 		return -1;
1866 
1867 	if (modules__parse(modules_filename, kci,
1868 			   kcore_copy__process_modules) < 0)
1869 		return -1;
1870 
1871 	return 0;
1872 }
1873 
1874 static int kcore_copy__map(struct kcore_copy_info *kci, u64 start, u64 end,
1875 			   u64 pgoff, u64 s, u64 e)
1876 {
1877 	u64 len, offset;
1878 
1879 	if (s < start || s >= end)
1880 		return 0;
1881 
1882 	offset = (s - start) + pgoff;
1883 	len = e < end ? e - s : end - s;
1884 
1885 	return kcore_copy_info__addnew(kci, s, len, offset) ? 0 : -1;
1886 }
1887 
1888 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
1889 {
1890 	struct kcore_copy_info *kci = data;
1891 	u64 end = start + len;
1892 	struct sym_data *sdat;
1893 
1894 	if (kcore_copy__map(kci, start, end, pgoff, kci->stext, kci->etext))
1895 		return -1;
1896 
1897 	if (kcore_copy__map(kci, start, end, pgoff, kci->first_module,
1898 			    kci->last_module_symbol))
1899 		return -1;
1900 
1901 	list_for_each_entry(sdat, &kci->syms, node) {
1902 		u64 s = round_down(sdat->addr, page_size);
1903 
1904 		if (kcore_copy__map(kci, start, end, pgoff, s, s + len))
1905 			return -1;
1906 	}
1907 
1908 	return 0;
1909 }
1910 
1911 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
1912 {
1913 	if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
1914 		return -1;
1915 
1916 	return 0;
1917 }
1918 
1919 static void kcore_copy__find_remaps(struct kcore_copy_info *kci)
1920 {
1921 	struct phdr_data *p, *k = NULL;
1922 	u64 kend;
1923 
1924 	if (!kci->stext)
1925 		return;
1926 
1927 	/* Find phdr that corresponds to the kernel map (contains stext) */
1928 	kcore_copy__for_each_phdr(kci, p) {
1929 		u64 pend = p->addr + p->len - 1;
1930 
1931 		if (p->addr <= kci->stext && pend >= kci->stext) {
1932 			k = p;
1933 			break;
1934 		}
1935 	}
1936 
1937 	if (!k)
1938 		return;
1939 
1940 	kend = k->offset + k->len;
1941 
1942 	/* Find phdrs that remap the kernel */
1943 	kcore_copy__for_each_phdr(kci, p) {
1944 		u64 pend = p->offset + p->len;
1945 
1946 		if (p == k)
1947 			continue;
1948 
1949 		if (p->offset >= k->offset && pend <= kend)
1950 			p->remaps = k;
1951 	}
1952 }
1953 
1954 static void kcore_copy__layout(struct kcore_copy_info *kci)
1955 {
1956 	struct phdr_data *p;
1957 	off_t rel = 0;
1958 
1959 	kcore_copy__find_remaps(kci);
1960 
1961 	kcore_copy__for_each_phdr(kci, p) {
1962 		if (!p->remaps) {
1963 			p->rel = rel;
1964 			rel += p->len;
1965 		}
1966 		kci->phnum += 1;
1967 	}
1968 
1969 	kcore_copy__for_each_phdr(kci, p) {
1970 		struct phdr_data *k = p->remaps;
1971 
1972 		if (k)
1973 			p->rel = p->offset - k->offset + k->rel;
1974 	}
1975 }
1976 
1977 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
1978 				 Elf *elf)
1979 {
1980 	if (kcore_copy__parse_kallsyms(kci, dir))
1981 		return -1;
1982 
1983 	if (kcore_copy__parse_modules(kci, dir))
1984 		return -1;
1985 
1986 	if (kci->stext)
1987 		kci->stext = round_down(kci->stext, page_size);
1988 	else
1989 		kci->stext = round_down(kci->first_symbol, page_size);
1990 
1991 	if (kci->etext) {
1992 		kci->etext = round_up(kci->etext, page_size);
1993 	} else if (kci->last_symbol) {
1994 		kci->etext = round_up(kci->last_symbol, page_size);
1995 		kci->etext += page_size;
1996 	}
1997 
1998 	if (kci->first_module_symbol &&
1999 	    (!kci->first_module || kci->first_module_symbol < kci->first_module))
2000 		kci->first_module = kci->first_module_symbol;
2001 
2002 	kci->first_module = round_down(kci->first_module, page_size);
2003 
2004 	if (kci->last_module_symbol) {
2005 		kci->last_module_symbol = round_up(kci->last_module_symbol,
2006 						   page_size);
2007 		kci->last_module_symbol += page_size;
2008 	}
2009 
2010 	if (!kci->stext || !kci->etext)
2011 		return -1;
2012 
2013 	if (kci->first_module && !kci->last_module_symbol)
2014 		return -1;
2015 
2016 	if (kcore_copy__read_maps(kci, elf))
2017 		return -1;
2018 
2019 	kcore_copy__layout(kci);
2020 
2021 	return 0;
2022 }
2023 
2024 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
2025 				 const char *name)
2026 {
2027 	char from_filename[PATH_MAX];
2028 	char to_filename[PATH_MAX];
2029 
2030 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2031 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2032 
2033 	return copyfile_mode(from_filename, to_filename, 0400);
2034 }
2035 
2036 static int kcore_copy__unlink(const char *dir, const char *name)
2037 {
2038 	char filename[PATH_MAX];
2039 
2040 	scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
2041 
2042 	return unlink(filename);
2043 }
2044 
2045 static int kcore_copy__compare_fds(int from, int to)
2046 {
2047 	char *buf_from;
2048 	char *buf_to;
2049 	ssize_t ret;
2050 	size_t len;
2051 	int err = -1;
2052 
2053 	buf_from = malloc(page_size);
2054 	buf_to = malloc(page_size);
2055 	if (!buf_from || !buf_to)
2056 		goto out;
2057 
2058 	while (1) {
2059 		/* Use read because mmap won't work on proc files */
2060 		ret = read(from, buf_from, page_size);
2061 		if (ret < 0)
2062 			goto out;
2063 
2064 		if (!ret)
2065 			break;
2066 
2067 		len = ret;
2068 
2069 		if (readn(to, buf_to, len) != (int)len)
2070 			goto out;
2071 
2072 		if (memcmp(buf_from, buf_to, len))
2073 			goto out;
2074 	}
2075 
2076 	err = 0;
2077 out:
2078 	free(buf_to);
2079 	free(buf_from);
2080 	return err;
2081 }
2082 
2083 static int kcore_copy__compare_files(const char *from_filename,
2084 				     const char *to_filename)
2085 {
2086 	int from, to, err = -1;
2087 
2088 	from = open(from_filename, O_RDONLY);
2089 	if (from < 0)
2090 		return -1;
2091 
2092 	to = open(to_filename, O_RDONLY);
2093 	if (to < 0)
2094 		goto out_close_from;
2095 
2096 	err = kcore_copy__compare_fds(from, to);
2097 
2098 	close(to);
2099 out_close_from:
2100 	close(from);
2101 	return err;
2102 }
2103 
2104 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
2105 				    const char *name)
2106 {
2107 	char from_filename[PATH_MAX];
2108 	char to_filename[PATH_MAX];
2109 
2110 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2111 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2112 
2113 	return kcore_copy__compare_files(from_filename, to_filename);
2114 }
2115 
2116 /**
2117  * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
2118  * @from_dir: from directory
2119  * @to_dir: to directory
2120  *
2121  * This function copies kallsyms, modules and kcore files from one directory to
2122  * another.  kallsyms and modules are copied entirely.  Only code segments are
2123  * copied from kcore.  It is assumed that two segments suffice: one for the
2124  * kernel proper and one for all the modules.  The code segments are determined
2125  * from kallsyms and modules files.  The kernel map starts at _stext or the
2126  * lowest function symbol, and ends at _etext or the highest function symbol.
2127  * The module map starts at the lowest module address and ends at the highest
2128  * module symbol.  Start addresses are rounded down to the nearest page.  End
2129  * addresses are rounded up to the nearest page.  An extra page is added to the
2130  * highest kernel symbol and highest module symbol to, hopefully, encompass that
2131  * symbol too.  Because it contains only code sections, the resulting kcore is
2132  * unusual.  One significant peculiarity is that the mapping (start -> pgoff)
2133  * is not the same for the kernel map and the modules map.  That happens because
2134  * the data is copied adjacently whereas the original kcore has gaps.  Finally,
2135  * kallsyms file is compared with its copy to check that modules have not been
2136  * loaded or unloaded while the copies were taking place.
2137  *
2138  * Return: %0 on success, %-1 on failure.
2139  */
2140 int kcore_copy(const char *from_dir, const char *to_dir)
2141 {
2142 	struct kcore kcore;
2143 	struct kcore extract;
2144 	int idx = 0, err = -1;
2145 	off_t offset, sz;
2146 	struct kcore_copy_info kci = { .stext = 0, };
2147 	char kcore_filename[PATH_MAX];
2148 	char extract_filename[PATH_MAX];
2149 	struct phdr_data *p;
2150 
2151 	INIT_LIST_HEAD(&kci.phdrs);
2152 	INIT_LIST_HEAD(&kci.syms);
2153 
2154 	if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
2155 		return -1;
2156 
2157 	if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
2158 		goto out_unlink_kallsyms;
2159 
2160 	scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
2161 	scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
2162 
2163 	if (kcore__open(&kcore, kcore_filename))
2164 		goto out_unlink_modules;
2165 
2166 	if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
2167 		goto out_kcore_close;
2168 
2169 	if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
2170 		goto out_kcore_close;
2171 
2172 	if (kcore__copy_hdr(&kcore, &extract, kci.phnum))
2173 		goto out_extract_close;
2174 
2175 	offset = gelf_fsize(extract.elf, ELF_T_EHDR, 1, EV_CURRENT) +
2176 		 gelf_fsize(extract.elf, ELF_T_PHDR, kci.phnum, EV_CURRENT);
2177 	offset = round_up(offset, page_size);
2178 
2179 	kcore_copy__for_each_phdr(&kci, p) {
2180 		off_t offs = p->rel + offset;
2181 
2182 		if (kcore__add_phdr(&extract, idx++, offs, p->addr, p->len))
2183 			goto out_extract_close;
2184 	}
2185 
2186 	sz = kcore__write(&extract);
2187 	if (sz < 0 || sz > offset)
2188 		goto out_extract_close;
2189 
2190 	kcore_copy__for_each_phdr(&kci, p) {
2191 		off_t offs = p->rel + offset;
2192 
2193 		if (p->remaps)
2194 			continue;
2195 		if (copy_bytes(kcore.fd, p->offset, extract.fd, offs, p->len))
2196 			goto out_extract_close;
2197 	}
2198 
2199 	if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
2200 		goto out_extract_close;
2201 
2202 	err = 0;
2203 
2204 out_extract_close:
2205 	kcore__close(&extract);
2206 	if (err)
2207 		unlink(extract_filename);
2208 out_kcore_close:
2209 	kcore__close(&kcore);
2210 out_unlink_modules:
2211 	if (err)
2212 		kcore_copy__unlink(to_dir, "modules");
2213 out_unlink_kallsyms:
2214 	if (err)
2215 		kcore_copy__unlink(to_dir, "kallsyms");
2216 
2217 	kcore_copy__free_phdrs(&kci);
2218 	kcore_copy__free_syms(&kci);
2219 
2220 	return err;
2221 }
2222 
2223 int kcore_extract__create(struct kcore_extract *kce)
2224 {
2225 	struct kcore kcore;
2226 	struct kcore extract;
2227 	size_t count = 1;
2228 	int idx = 0, err = -1;
2229 	off_t offset = page_size, sz;
2230 
2231 	if (kcore__open(&kcore, kce->kcore_filename))
2232 		return -1;
2233 
2234 	strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
2235 	if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
2236 		goto out_kcore_close;
2237 
2238 	if (kcore__copy_hdr(&kcore, &extract, count))
2239 		goto out_extract_close;
2240 
2241 	if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
2242 		goto out_extract_close;
2243 
2244 	sz = kcore__write(&extract);
2245 	if (sz < 0 || sz > offset)
2246 		goto out_extract_close;
2247 
2248 	if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
2249 		goto out_extract_close;
2250 
2251 	err = 0;
2252 
2253 out_extract_close:
2254 	kcore__close(&extract);
2255 	if (err)
2256 		unlink(kce->extract_filename);
2257 out_kcore_close:
2258 	kcore__close(&kcore);
2259 
2260 	return err;
2261 }
2262 
2263 void kcore_extract__delete(struct kcore_extract *kce)
2264 {
2265 	unlink(kce->extract_filename);
2266 }
2267 
2268 #ifdef HAVE_GELF_GETNOTE_SUPPORT
2269 
2270 static void sdt_adjust_loc(struct sdt_note *tmp, GElf_Addr base_off)
2271 {
2272 	if (!base_off)
2273 		return;
2274 
2275 	if (tmp->bit32)
2276 		tmp->addr.a32[SDT_NOTE_IDX_LOC] =
2277 			tmp->addr.a32[SDT_NOTE_IDX_LOC] + base_off -
2278 			tmp->addr.a32[SDT_NOTE_IDX_BASE];
2279 	else
2280 		tmp->addr.a64[SDT_NOTE_IDX_LOC] =
2281 			tmp->addr.a64[SDT_NOTE_IDX_LOC] + base_off -
2282 			tmp->addr.a64[SDT_NOTE_IDX_BASE];
2283 }
2284 
2285 static void sdt_adjust_refctr(struct sdt_note *tmp, GElf_Addr base_addr,
2286 			      GElf_Addr base_off)
2287 {
2288 	if (!base_off)
2289 		return;
2290 
2291 	if (tmp->bit32 && tmp->addr.a32[SDT_NOTE_IDX_REFCTR])
2292 		tmp->addr.a32[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2293 	else if (tmp->addr.a64[SDT_NOTE_IDX_REFCTR])
2294 		tmp->addr.a64[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2295 }
2296 
2297 /**
2298  * populate_sdt_note : Parse raw data and identify SDT note
2299  * @elf: elf of the opened file
2300  * @data: raw data of a section with description offset applied
2301  * @len: note description size
2302  * @type: type of the note
2303  * @sdt_notes: List to add the SDT note
2304  *
2305  * Responsible for parsing the @data in section .note.stapsdt in @elf and
2306  * if its an SDT note, it appends to @sdt_notes list.
2307  */
2308 static int populate_sdt_note(Elf **elf, const char *data, size_t len,
2309 			     struct list_head *sdt_notes)
2310 {
2311 	const char *provider, *name, *args;
2312 	struct sdt_note *tmp = NULL;
2313 	GElf_Ehdr ehdr;
2314 	GElf_Shdr shdr;
2315 	int ret = -EINVAL;
2316 
2317 	union {
2318 		Elf64_Addr a64[NR_ADDR];
2319 		Elf32_Addr a32[NR_ADDR];
2320 	} buf;
2321 
2322 	Elf_Data dst = {
2323 		.d_buf = &buf, .d_type = ELF_T_ADDR, .d_version = EV_CURRENT,
2324 		.d_size = gelf_fsize((*elf), ELF_T_ADDR, NR_ADDR, EV_CURRENT),
2325 		.d_off = 0, .d_align = 0
2326 	};
2327 	Elf_Data src = {
2328 		.d_buf = (void *) data, .d_type = ELF_T_ADDR,
2329 		.d_version = EV_CURRENT, .d_size = dst.d_size, .d_off = 0,
2330 		.d_align = 0
2331 	};
2332 
2333 	tmp = (struct sdt_note *)calloc(1, sizeof(struct sdt_note));
2334 	if (!tmp) {
2335 		ret = -ENOMEM;
2336 		goto out_err;
2337 	}
2338 
2339 	INIT_LIST_HEAD(&tmp->note_list);
2340 
2341 	if (len < dst.d_size + 3)
2342 		goto out_free_note;
2343 
2344 	/* Translation from file representation to memory representation */
2345 	if (gelf_xlatetom(*elf, &dst, &src,
2346 			  elf_getident(*elf, NULL)[EI_DATA]) == NULL) {
2347 		pr_err("gelf_xlatetom : %s\n", elf_errmsg(-1));
2348 		goto out_free_note;
2349 	}
2350 
2351 	/* Populate the fields of sdt_note */
2352 	provider = data + dst.d_size;
2353 
2354 	name = (const char *)memchr(provider, '\0', data + len - provider);
2355 	if (name++ == NULL)
2356 		goto out_free_note;
2357 
2358 	tmp->provider = strdup(provider);
2359 	if (!tmp->provider) {
2360 		ret = -ENOMEM;
2361 		goto out_free_note;
2362 	}
2363 	tmp->name = strdup(name);
2364 	if (!tmp->name) {
2365 		ret = -ENOMEM;
2366 		goto out_free_prov;
2367 	}
2368 
2369 	args = memchr(name, '\0', data + len - name);
2370 
2371 	/*
2372 	 * There is no argument if:
2373 	 * - We reached the end of the note;
2374 	 * - There is not enough room to hold a potential string;
2375 	 * - The argument string is empty or just contains ':'.
2376 	 */
2377 	if (args == NULL || data + len - args < 2 ||
2378 		args[1] == ':' || args[1] == '\0')
2379 		tmp->args = NULL;
2380 	else {
2381 		tmp->args = strdup(++args);
2382 		if (!tmp->args) {
2383 			ret = -ENOMEM;
2384 			goto out_free_name;
2385 		}
2386 	}
2387 
2388 	if (gelf_getclass(*elf) == ELFCLASS32) {
2389 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf32_Addr));
2390 		tmp->bit32 = true;
2391 	} else {
2392 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf64_Addr));
2393 		tmp->bit32 = false;
2394 	}
2395 
2396 	if (!gelf_getehdr(*elf, &ehdr)) {
2397 		pr_debug("%s : cannot get elf header.\n", __func__);
2398 		ret = -EBADF;
2399 		goto out_free_args;
2400 	}
2401 
2402 	/* Adjust the prelink effect :
2403 	 * Find out the .stapsdt.base section.
2404 	 * This scn will help us to handle prelinking (if present).
2405 	 * Compare the retrieved file offset of the base section with the
2406 	 * base address in the description of the SDT note. If its different,
2407 	 * then accordingly, adjust the note location.
2408 	 */
2409 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_BASE_SCN, NULL))
2410 		sdt_adjust_loc(tmp, shdr.sh_offset);
2411 
2412 	/* Adjust reference counter offset */
2413 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_PROBES_SCN, NULL))
2414 		sdt_adjust_refctr(tmp, shdr.sh_addr, shdr.sh_offset);
2415 
2416 	list_add_tail(&tmp->note_list, sdt_notes);
2417 	return 0;
2418 
2419 out_free_args:
2420 	zfree(&tmp->args);
2421 out_free_name:
2422 	zfree(&tmp->name);
2423 out_free_prov:
2424 	zfree(&tmp->provider);
2425 out_free_note:
2426 	free(tmp);
2427 out_err:
2428 	return ret;
2429 }
2430 
2431 /**
2432  * construct_sdt_notes_list : constructs a list of SDT notes
2433  * @elf : elf to look into
2434  * @sdt_notes : empty list_head
2435  *
2436  * Scans the sections in 'elf' for the section
2437  * .note.stapsdt. It, then calls populate_sdt_note to find
2438  * out the SDT events and populates the 'sdt_notes'.
2439  */
2440 static int construct_sdt_notes_list(Elf *elf, struct list_head *sdt_notes)
2441 {
2442 	GElf_Ehdr ehdr;
2443 	Elf_Scn *scn = NULL;
2444 	Elf_Data *data;
2445 	GElf_Shdr shdr;
2446 	size_t shstrndx, next;
2447 	GElf_Nhdr nhdr;
2448 	size_t name_off, desc_off, offset;
2449 	int ret = 0;
2450 
2451 	if (gelf_getehdr(elf, &ehdr) == NULL) {
2452 		ret = -EBADF;
2453 		goto out_ret;
2454 	}
2455 	if (elf_getshdrstrndx(elf, &shstrndx) != 0) {
2456 		ret = -EBADF;
2457 		goto out_ret;
2458 	}
2459 
2460 	/* Look for the required section */
2461 	scn = elf_section_by_name(elf, &ehdr, &shdr, SDT_NOTE_SCN, NULL);
2462 	if (!scn) {
2463 		ret = -ENOENT;
2464 		goto out_ret;
2465 	}
2466 
2467 	if ((shdr.sh_type != SHT_NOTE) || (shdr.sh_flags & SHF_ALLOC)) {
2468 		ret = -ENOENT;
2469 		goto out_ret;
2470 	}
2471 
2472 	data = elf_getdata(scn, NULL);
2473 
2474 	/* Get the SDT notes */
2475 	for (offset = 0; (next = gelf_getnote(data, offset, &nhdr, &name_off,
2476 					      &desc_off)) > 0; offset = next) {
2477 		if (nhdr.n_namesz == sizeof(SDT_NOTE_NAME) &&
2478 		    !memcmp(data->d_buf + name_off, SDT_NOTE_NAME,
2479 			    sizeof(SDT_NOTE_NAME))) {
2480 			/* Check the type of the note */
2481 			if (nhdr.n_type != SDT_NOTE_TYPE)
2482 				goto out_ret;
2483 
2484 			ret = populate_sdt_note(&elf, ((data->d_buf) + desc_off),
2485 						nhdr.n_descsz, sdt_notes);
2486 			if (ret < 0)
2487 				goto out_ret;
2488 		}
2489 	}
2490 	if (list_empty(sdt_notes))
2491 		ret = -ENOENT;
2492 
2493 out_ret:
2494 	return ret;
2495 }
2496 
2497 /**
2498  * get_sdt_note_list : Wrapper to construct a list of sdt notes
2499  * @head : empty list_head
2500  * @target : file to find SDT notes from
2501  *
2502  * This opens the file, initializes
2503  * the ELF and then calls construct_sdt_notes_list.
2504  */
2505 int get_sdt_note_list(struct list_head *head, const char *target)
2506 {
2507 	Elf *elf;
2508 	int fd, ret;
2509 
2510 	fd = open(target, O_RDONLY);
2511 	if (fd < 0)
2512 		return -EBADF;
2513 
2514 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
2515 	if (!elf) {
2516 		ret = -EBADF;
2517 		goto out_close;
2518 	}
2519 	ret = construct_sdt_notes_list(elf, head);
2520 	elf_end(elf);
2521 out_close:
2522 	close(fd);
2523 	return ret;
2524 }
2525 
2526 /**
2527  * cleanup_sdt_note_list : free the sdt notes' list
2528  * @sdt_notes: sdt notes' list
2529  *
2530  * Free up the SDT notes in @sdt_notes.
2531  * Returns the number of SDT notes free'd.
2532  */
2533 int cleanup_sdt_note_list(struct list_head *sdt_notes)
2534 {
2535 	struct sdt_note *tmp, *pos;
2536 	int nr_free = 0;
2537 
2538 	list_for_each_entry_safe(pos, tmp, sdt_notes, note_list) {
2539 		list_del_init(&pos->note_list);
2540 		zfree(&pos->args);
2541 		zfree(&pos->name);
2542 		zfree(&pos->provider);
2543 		free(pos);
2544 		nr_free++;
2545 	}
2546 	return nr_free;
2547 }
2548 
2549 /**
2550  * sdt_notes__get_count: Counts the number of sdt events
2551  * @start: list_head to sdt_notes list
2552  *
2553  * Returns the number of SDT notes in a list
2554  */
2555 int sdt_notes__get_count(struct list_head *start)
2556 {
2557 	struct sdt_note *sdt_ptr;
2558 	int count = 0;
2559 
2560 	list_for_each_entry(sdt_ptr, start, note_list)
2561 		count++;
2562 	return count;
2563 }
2564 #endif
2565 
2566 void symbol__elf_init(void)
2567 {
2568 	elf_version(EV_CURRENT);
2569 }
2570