1 // SPDX-License-Identifier: GPL-2.0
15 #include "demangle-cxx.h"
16 #include "demangle-ocaml.h"
17 #include "demangle-java.h"
18 #include "demangle-rust.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>
29 #ifdef HAVE_LIBBFD_SUPPORT
30 #define PACKAGE 'perf'
35 #define EM_AARCH64 183 /* ARM 64 bit */
38 #ifndef ELF32_ST_VISIBILITY
39 #define ELF32_ST_VISIBILITY(o) ((o) & 0x03)
42 /* For ELF64 the definitions are the same. */
43 #ifndef ELF64_ST_VISIBILITY
44 #define ELF64_ST_VISIBILITY(o) ELF32_ST_VISIBILITY (o)
47 /* How to extract information held in the st_other field. */
48 #ifndef GELF_ST_VISIBILITY
49 #define GELF_ST_VISIBILITY(val) ELF64_ST_VISIBILITY (val)
52 typedef Elf64_Nhdr GElf_Nhdr;
55 #ifndef HAVE_ELF_GETPHDRNUM_SUPPORT
56 static int elf_getphdrnum(Elf *elf, size_t *dst)
61 ehdr = gelf_getehdr(elf, &gehdr);
71 #ifndef HAVE_ELF_GETSHDRSTRNDX_SUPPORT
72 static int elf_getshdrstrndx(Elf *elf __maybe_unused, size_t *dst __maybe_unused)
74 pr_err("%s: update your libelf to > 0.140, this one lacks elf_getshdrstrndx().\n", __func__);
79 #ifndef NT_GNU_BUILD_ID
80 #define NT_GNU_BUILD_ID 3
84 * elf_symtab__for_each_symbol - iterate thru all the symbols
86 * @syms: struct elf_symtab instance to iterate
88 * @sym: GElf_Sym iterator
90 #define elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) \
91 for (idx = 0, gelf_getsym(syms, idx, &sym);\
93 idx++, gelf_getsym(syms, idx, &sym))
95 static inline uint8_t elf_sym__type(const GElf_Sym *sym)
97 return GELF_ST_TYPE(sym->st_info);
100 static inline uint8_t elf_sym__visibility(const GElf_Sym *sym)
102 return GELF_ST_VISIBILITY(sym->st_other);
105 #ifndef STT_GNU_IFUNC
106 #define STT_GNU_IFUNC 10
109 static inline int elf_sym__is_function(const GElf_Sym *sym)
111 return (elf_sym__type(sym) == STT_FUNC ||
112 elf_sym__type(sym) == STT_GNU_IFUNC) &&
114 sym->st_shndx != SHN_UNDEF;
117 static inline bool elf_sym__is_object(const GElf_Sym *sym)
119 return elf_sym__type(sym) == STT_OBJECT &&
121 sym->st_shndx != SHN_UNDEF;
124 static inline int elf_sym__is_label(const GElf_Sym *sym)
126 return elf_sym__type(sym) == STT_NOTYPE &&
128 sym->st_shndx != SHN_UNDEF &&
129 sym->st_shndx != SHN_ABS &&
130 elf_sym__visibility(sym) != STV_HIDDEN &&
131 elf_sym__visibility(sym) != STV_INTERNAL;
134 static bool elf_sym__filter(GElf_Sym *sym)
136 return elf_sym__is_function(sym) || elf_sym__is_object(sym);
139 static inline const char *elf_sym__name(const GElf_Sym *sym,
140 const Elf_Data *symstrs)
142 return symstrs->d_buf + sym->st_name;
145 static inline const char *elf_sec__name(const GElf_Shdr *shdr,
146 const Elf_Data *secstrs)
148 return secstrs->d_buf + shdr->sh_name;
151 static inline int elf_sec__is_text(const GElf_Shdr *shdr,
152 const Elf_Data *secstrs)
154 return strstr(elf_sec__name(shdr, secstrs), "text") != NULL;
157 static inline bool elf_sec__is_data(const GElf_Shdr *shdr,
158 const Elf_Data *secstrs)
160 return strstr(elf_sec__name(shdr, secstrs), "data") != NULL;
163 static bool elf_sec__filter(GElf_Shdr *shdr, Elf_Data *secstrs)
165 return elf_sec__is_text(shdr, secstrs) ||
166 elf_sec__is_data(shdr, secstrs);
169 static size_t elf_addr_to_index(Elf *elf, GElf_Addr addr)
175 while ((sec = elf_nextscn(elf, sec)) != NULL) {
176 gelf_getshdr(sec, &shdr);
178 if ((addr >= shdr.sh_addr) &&
179 (addr < (shdr.sh_addr + shdr.sh_size)))
188 Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
189 GElf_Shdr *shp, const char *name, size_t *idx)
194 /* ELF is corrupted/truncated, avoid calling elf_strptr. */
195 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL))
198 while ((sec = elf_nextscn(elf, sec)) != NULL) {
201 gelf_getshdr(sec, shp);
202 str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
203 if (str && !strcmp(name, str)) {
214 bool filename__has_section(const char *filename, const char *sec)
222 fd = open(filename, O_RDONLY);
226 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
230 if (gelf_getehdr(elf, &ehdr) == NULL)
233 found = !!elf_section_by_name(elf, &ehdr, &shdr, sec, NULL);
242 static int elf_read_program_header(Elf *elf, u64 vaddr, GElf_Phdr *phdr)
247 if (elf_getphdrnum(elf, &phdrnum))
250 for (i = 0; i < phdrnum; i++) {
251 if (gelf_getphdr(elf, i, phdr) == NULL)
254 if (phdr->p_type != PT_LOAD)
257 sz = max(phdr->p_memsz, phdr->p_filesz);
261 if (vaddr >= phdr->p_vaddr && (vaddr < phdr->p_vaddr + sz))
265 /* Not found any valid program header */
269 static bool want_demangle(bool is_kernel_sym)
271 return is_kernel_sym ? symbol_conf.demangle_kernel : symbol_conf.demangle;
274 static char *demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
276 char *demangled = NULL;
279 * We need to figure out if the object was created from C++ sources
280 * DWARF DW_compile_unit has this, but we don't always have access
283 if (!want_demangle(dso->kernel || kmodule))
286 demangled = cxx_demangle_sym(elf_name, verbose > 0, verbose > 0);
287 if (demangled == NULL) {
288 demangled = ocaml_demangle_sym(elf_name);
289 if (demangled == NULL) {
290 demangled = java_demangle_sym(elf_name, JAVA_DEMANGLE_NORET);
293 else if (rust_is_mangled(demangled))
295 * Input to Rust demangling is the BFD-demangled
296 * name which it Rust-demangles in place.
298 rust_demangle_sym(demangled);
312 static u32 get_rel_symidx(struct rel_info *ri, u32 idx)
314 idx = ri->sorted ? ri->sorted[idx] : idx;
316 gelf_getrela(ri->reldata, idx, &ri->rela);
317 return GELF_R_SYM(ri->rela.r_info);
319 gelf_getrel(ri->reldata, idx, &ri->rel);
320 return GELF_R_SYM(ri->rel.r_info);
323 static u64 get_rel_offset(struct rel_info *ri, u32 x)
328 gelf_getrela(ri->reldata, x, &rela);
329 return rela.r_offset;
333 gelf_getrel(ri->reldata, x, &rel);
338 static int rel_cmp(const void *a, const void *b, void *r)
340 struct rel_info *ri = r;
341 u64 a_offset = get_rel_offset(ri, *(const u32 *)a);
342 u64 b_offset = get_rel_offset(ri, *(const u32 *)b);
344 return a_offset < b_offset ? -1 : (a_offset > b_offset ? 1 : 0);
347 static int sort_rel(struct rel_info *ri)
349 size_t sz = sizeof(ri->sorted[0]);
352 ri->sorted = calloc(ri->nr_entries, sz);
355 for (i = 0; i < ri->nr_entries; i++)
357 qsort_r(ri->sorted, ri->nr_entries, sz, rel_cmp, ri);
362 * For x86_64, the GNU linker is putting IFUNC information in the relocation
365 static bool addend_may_be_ifunc(GElf_Ehdr *ehdr, struct rel_info *ri)
367 return ehdr->e_machine == EM_X86_64 && ri->is_rela &&
368 GELF_R_TYPE(ri->rela.r_info) == R_X86_64_IRELATIVE;
371 static bool get_ifunc_name(Elf *elf, struct dso *dso, GElf_Ehdr *ehdr,
372 struct rel_info *ri, char *buf, size_t buf_sz)
374 u64 addr = ri->rela.r_addend;
378 if (!addend_may_be_ifunc(ehdr, ri))
381 if (elf_read_program_header(elf, addr, &phdr))
384 addr -= phdr.p_vaddr - phdr.p_offset;
386 sym = dso__find_symbol_nocache(dso, addr);
388 /* Expecting the address to be an IFUNC or IFUNC alias */
389 if (!sym || sym->start != addr || (sym->type != STT_GNU_IFUNC && !sym->ifunc_alias))
392 snprintf(buf, buf_sz, "%s@plt", sym->name);
397 static void exit_rel(struct rel_info *ri)
402 static bool get_plt_sizes(struct dso *dso, GElf_Ehdr *ehdr, GElf_Shdr *shdr_plt,
403 u64 *plt_header_size, u64 *plt_entry_size)
405 switch (ehdr->e_machine) {
407 *plt_header_size = 20;
408 *plt_entry_size = 12;
411 *plt_header_size = 32;
412 *plt_entry_size = 16;
415 *plt_header_size = 48;
416 *plt_entry_size = 12;
419 *plt_header_size = 128;
420 *plt_entry_size = 32;
424 *plt_entry_size = shdr_plt->sh_entsize;
425 /* Size is 8 or 16, if not, assume alignment indicates size */
426 if (*plt_entry_size != 8 && *plt_entry_size != 16)
427 *plt_entry_size = shdr_plt->sh_addralign == 8 ? 8 : 16;
428 *plt_header_size = *plt_entry_size;
430 default: /* FIXME: s390/alpha/mips/parisc/poperpc/sh/xtensa need to be checked */
431 *plt_header_size = shdr_plt->sh_entsize;
432 *plt_entry_size = shdr_plt->sh_entsize;
437 pr_debug("Missing PLT entry size for %s\n", dso->long_name);
441 static bool machine_is_x86(GElf_Half e_machine)
443 return e_machine == EM_386 || e_machine == EM_X86_64;
451 struct rela_dyn_info {
453 Elf_Data *plt_got_data;
455 struct rela_dyn *sorted;
456 Elf_Data *dynsym_data;
457 Elf_Data *dynstr_data;
458 Elf_Data *rela_dyn_data;
461 static void exit_rela_dyn(struct rela_dyn_info *di)
466 static int cmp_offset(const void *a, const void *b)
468 const struct rela_dyn *va = a;
469 const struct rela_dyn *vb = b;
471 return va->offset < vb->offset ? -1 : (va->offset > vb->offset ? 1 : 0);
474 static int sort_rela_dyn(struct rela_dyn_info *di)
478 di->sorted = calloc(di->nr_entries, sizeof(di->sorted[0]));
482 /* Get data for sorting: the offset and symbol index */
483 for (i = 0, n = 0; i < di->nr_entries; i++) {
487 gelf_getrela(di->rela_dyn_data, i, &rela);
488 sym_idx = GELF_R_SYM(rela.r_info);
490 di->sorted[n].sym_idx = sym_idx;
491 di->sorted[n].offset = rela.r_offset;
498 qsort(di->sorted, n, sizeof(di->sorted[0]), cmp_offset);
503 static void get_rela_dyn_info(Elf *elf, GElf_Ehdr *ehdr, struct rela_dyn_info *di, Elf_Scn *scn)
505 GElf_Shdr rela_dyn_shdr;
508 di->plt_got_data = elf_getdata(scn, NULL);
510 scn = elf_section_by_name(elf, ehdr, &rela_dyn_shdr, ".rela.dyn", NULL);
511 if (!scn || !rela_dyn_shdr.sh_link || !rela_dyn_shdr.sh_entsize)
514 di->nr_entries = rela_dyn_shdr.sh_size / rela_dyn_shdr.sh_entsize;
515 di->rela_dyn_data = elf_getdata(scn, NULL);
517 scn = elf_getscn(elf, rela_dyn_shdr.sh_link);
518 if (!scn || !gelf_getshdr(scn, &shdr) || !shdr.sh_link)
521 di->dynsym_data = elf_getdata(scn, NULL);
522 di->dynstr_data = elf_getdata(elf_getscn(elf, shdr.sh_link), NULL);
524 if (!di->plt_got_data || !di->dynstr_data || !di->dynsym_data || !di->rela_dyn_data)
527 /* Sort into offset order */
531 /* Get instruction displacement from a plt entry for x86_64 */
532 static u32 get_x86_64_plt_disp(const u8 *p)
534 u8 endbr64[] = {0xf3, 0x0f, 0x1e, 0xfa};
538 if (!memcmp(p, endbr64, sizeof(endbr64)))
539 n += sizeof(endbr64);
540 /* Skip bnd prefix */
543 /* jmp with 4-byte displacement */
544 if (p[n] == 0xff && p[n + 1] == 0x25) {
548 /* Also add offset from start of entry to end of instruction */
549 memcpy(&disp, p + n, sizeof(disp));
550 return n + 4 + le32toh(disp);
555 static bool get_plt_got_name(GElf_Shdr *shdr, size_t i,
556 struct rela_dyn_info *di,
557 char *buf, size_t buf_sz)
559 struct rela_dyn vi, *vr;
560 const char *sym_name;
569 disp = get_x86_64_plt_disp(di->plt_got_data->d_buf + i);
573 /* Compute target offset of the .plt.got entry */
574 vi.offset = shdr->sh_offset + di->plt_got_data->d_off + i + disp;
576 /* Find that offset in .rela.dyn (sorted by offset) */
577 vr = bsearch(&vi, di->sorted, di->nr_entries, sizeof(di->sorted[0]), cmp_offset);
581 /* Get the associated symbol */
582 gelf_getsym(di->dynsym_data, vr->sym_idx, &sym);
583 sym_name = elf_sym__name(&sym, di->dynstr_data);
584 demangled = demangle_sym(di->dso, 0, sym_name);
585 if (demangled != NULL)
586 sym_name = demangled;
588 snprintf(buf, buf_sz, "%s@plt", sym_name);
597 static int dso__synthesize_plt_got_symbols(struct dso *dso, Elf *elf,
599 char *buf, size_t buf_sz)
601 struct rela_dyn_info di = { .dso = dso };
608 scn = elf_section_by_name(elf, ehdr, &shdr, ".plt.got", NULL);
609 if (!scn || !shdr.sh_entsize)
612 if (ehdr->e_machine == EM_X86_64)
613 get_rela_dyn_info(elf, ehdr, &di, scn);
615 for (i = 0; i < shdr.sh_size; i += shdr.sh_entsize) {
616 if (!get_plt_got_name(&shdr, i, &di, buf, buf_sz))
617 snprintf(buf, buf_sz, "offset_%#" PRIx64 "@plt", (u64)shdr.sh_offset + i);
618 sym = symbol__new(shdr.sh_offset + i, shdr.sh_entsize, STB_GLOBAL, STT_FUNC, buf);
621 symbols__insert(&dso->symbols, sym);
630 * We need to check if we have a .dynsym, so that we can handle the
631 * .plt, synthesizing its symbols, that aren't on the symtabs (be it
632 * .dynsym or .symtab).
633 * And always look at the original dso, not at debuginfo packages, that
634 * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
636 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss)
640 u64 plt_offset, plt_header_size, plt_entry_size;
641 GElf_Shdr shdr_plt, plt_sec_shdr;
642 struct symbol *f, *plt_sym;
643 GElf_Shdr shdr_rel_plt, shdr_dynsym;
644 Elf_Data *syms, *symstrs;
645 Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
647 char sympltname[1024];
649 int nr = 0, err = -1;
650 struct rel_info ri = { .is_rela = false };
656 if (!elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL))
660 * A symbol from a previous section (e.g. .init) can have been expanded
661 * by symbols__fixup_end() to overlap .plt. Truncate it before adding
662 * a symbol for .plt header.
664 f = dso__find_symbol_nocache(dso, shdr_plt.sh_offset);
665 if (f && f->start < shdr_plt.sh_offset && f->end > shdr_plt.sh_offset)
666 f->end = shdr_plt.sh_offset;
668 if (!get_plt_sizes(dso, &ehdr, &shdr_plt, &plt_header_size, &plt_entry_size))
671 /* Add a symbol for .plt header */
672 plt_sym = symbol__new(shdr_plt.sh_offset, plt_header_size, STB_GLOBAL, STT_FUNC, ".plt");
675 symbols__insert(&dso->symbols, plt_sym);
677 /* Only x86 has .plt.got */
678 if (machine_is_x86(ehdr.e_machine) &&
679 dso__synthesize_plt_got_symbols(dso, elf, &ehdr, sympltname, sizeof(sympltname)))
682 /* Only x86 has .plt.sec */
683 if (machine_is_x86(ehdr.e_machine) &&
684 elf_section_by_name(elf, &ehdr, &plt_sec_shdr, ".plt.sec", NULL)) {
685 if (!get_plt_sizes(dso, &ehdr, &plt_sec_shdr, &plt_header_size, &plt_entry_size))
687 /* Extend .plt symbol to entire .plt */
688 plt_sym->end = plt_sym->start + shdr_plt.sh_size;
689 /* Use .plt.sec offset */
690 plt_offset = plt_sec_shdr.sh_offset;
693 plt_offset = shdr_plt.sh_offset;
697 scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
699 if (scn_plt_rel == NULL) {
700 scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
702 if (scn_plt_rel == NULL)
706 if (shdr_rel_plt.sh_type != SHT_RELA &&
707 shdr_rel_plt.sh_type != SHT_REL)
710 if (!shdr_rel_plt.sh_link)
713 if (shdr_rel_plt.sh_link == ss->dynsym_idx) {
714 scn_dynsym = ss->dynsym;
715 shdr_dynsym = ss->dynshdr;
716 } else if (shdr_rel_plt.sh_link == ss->symtab_idx) {
718 * A static executable can have a .plt due to IFUNCs, in which
719 * case .symtab is used not .dynsym.
721 scn_dynsym = ss->symtab;
722 shdr_dynsym = ss->symshdr;
731 * Fetch the relocation section to find the idxes to the GOT
732 * and the symbols in the .dynsym they refer to.
734 ri.reldata = elf_getdata(scn_plt_rel, NULL);
738 syms = elf_getdata(scn_dynsym, NULL);
742 scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
743 if (scn_symstrs == NULL)
746 symstrs = elf_getdata(scn_symstrs, NULL);
750 if (symstrs->d_size == 0)
753 ri.nr_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
755 ri.is_rela = shdr_rel_plt.sh_type == SHT_RELA;
759 * Assume a .plt with the same number of entries as the number
760 * of relocation entries is not lazy and does not have a header.
762 if (ri.nr_entries * plt_entry_size == shdr_plt.sh_size)
763 dso__delete_symbol(dso, plt_sym);
765 plt_offset += plt_header_size;
769 * x86 doesn't insert IFUNC relocations in .plt order, so sort to get
772 if (machine_is_x86(ehdr.e_machine) && sort_rel(&ri))
775 for (idx = 0; idx < ri.nr_entries; idx++) {
776 const char *elf_name = NULL;
777 char *demangled = NULL;
779 gelf_getsym(syms, get_rel_symidx(&ri, idx), &sym);
781 elf_name = elf_sym__name(&sym, symstrs);
782 demangled = demangle_sym(dso, 0, elf_name);
784 elf_name = demangled;
786 snprintf(sympltname, sizeof(sympltname), "%s@plt", elf_name);
787 else if (!get_ifunc_name(elf, dso, &ehdr, &ri, sympltname, sizeof(sympltname)))
788 snprintf(sympltname, sizeof(sympltname),
789 "offset_%#" PRIx64 "@plt", plt_offset);
792 f = symbol__new(plt_offset, plt_entry_size, STB_GLOBAL, STT_FUNC, sympltname);
796 plt_offset += plt_entry_size;
797 symbols__insert(&dso->symbols, f);
806 pr_debug("%s: problems reading %s PLT info.\n",
807 __func__, dso->long_name);
811 char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
813 return demangle_sym(dso, kmodule, elf_name);
817 * Align offset to 4 bytes as needed for note name and descriptor data.
819 #define NOTE_ALIGN(n) (((n) + 3) & -4U)
821 static int elf_read_build_id(Elf *elf, void *bf, size_t size)
831 if (size < BUILD_ID_SIZE)
838 if (gelf_getehdr(elf, &ehdr) == NULL) {
839 pr_err("%s: cannot get elf header.\n", __func__);
844 * Check following sections for notes:
845 * '.note.gnu.build-id'
847 * '.note' (VDSO specific)
850 sec = elf_section_by_name(elf, &ehdr, &shdr,
851 ".note.gnu.build-id", NULL);
855 sec = elf_section_by_name(elf, &ehdr, &shdr,
860 sec = elf_section_by_name(elf, &ehdr, &shdr,
869 data = elf_getdata(sec, NULL);
874 while (ptr < (data->d_buf + data->d_size)) {
875 GElf_Nhdr *nhdr = ptr;
876 size_t namesz = NOTE_ALIGN(nhdr->n_namesz),
877 descsz = NOTE_ALIGN(nhdr->n_descsz);
880 ptr += sizeof(*nhdr);
883 if (nhdr->n_type == NT_GNU_BUILD_ID &&
884 nhdr->n_namesz == sizeof("GNU")) {
885 if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
886 size_t sz = min(size, descsz);
888 memset(bf + sz, 0, size - sz);
900 #ifdef HAVE_LIBBFD_BUILDID_SUPPORT
902 static int read_build_id(const char *filename, struct build_id *bid)
904 size_t size = sizeof(bid->data);
908 abfd = bfd_openr(filename, NULL);
912 if (!bfd_check_format(abfd, bfd_object)) {
913 pr_debug2("%s: cannot read %s bfd file.\n", __func__, filename);
917 if (!abfd->build_id || abfd->build_id->size > size)
920 memcpy(bid->data, abfd->build_id->data, abfd->build_id->size);
921 memset(bid->data + abfd->build_id->size, 0, size - abfd->build_id->size);
922 err = bid->size = abfd->build_id->size;
929 #else // HAVE_LIBBFD_BUILDID_SUPPORT
931 static int read_build_id(const char *filename, struct build_id *bid)
933 size_t size = sizeof(bid->data);
937 if (size < BUILD_ID_SIZE)
940 fd = open(filename, O_RDONLY);
944 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
946 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
950 err = elf_read_build_id(elf, bid->data, size);
961 #endif // HAVE_LIBBFD_BUILDID_SUPPORT
963 int filename__read_build_id(const char *filename, struct build_id *bid)
965 struct kmod_path m = { .name = NULL, };
972 err = kmod_path__parse(&m, filename);
979 fd = filename__decompress(filename, path, sizeof(path), m.comp, &error);
981 pr_debug("Failed to decompress (error %d) %s\n",
989 err = read_build_id(filename, bid);
996 int sysfs__read_build_id(const char *filename, struct build_id *bid)
998 size_t size = sizeof(bid->data);
1001 fd = open(filename, O_RDONLY);
1008 size_t namesz, descsz;
1010 if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
1013 namesz = NOTE_ALIGN(nhdr.n_namesz);
1014 descsz = NOTE_ALIGN(nhdr.n_descsz);
1015 if (nhdr.n_type == NT_GNU_BUILD_ID &&
1016 nhdr.n_namesz == sizeof("GNU")) {
1017 if (read(fd, bf, namesz) != (ssize_t)namesz)
1019 if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
1020 size_t sz = min(descsz, size);
1021 if (read(fd, bid->data, sz) == (ssize_t)sz) {
1022 memset(bid->data + sz, 0, size - sz);
1027 } else if (read(fd, bf, descsz) != (ssize_t)descsz)
1030 int n = namesz + descsz;
1032 if (n > (int)sizeof(bf)) {
1034 pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
1035 __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
1037 if (read(fd, bf, n) != n)
1046 #ifdef HAVE_LIBBFD_SUPPORT
1048 int filename__read_debuglink(const char *filename, char *debuglink,
1055 abfd = bfd_openr(filename, NULL);
1059 if (!bfd_check_format(abfd, bfd_object)) {
1060 pr_debug2("%s: cannot read %s bfd file.\n", __func__, filename);
1064 section = bfd_get_section_by_name(abfd, ".gnu_debuglink");
1068 if (section->size > size)
1071 if (!bfd_get_section_contents(abfd, section, debuglink, 0,
1084 int filename__read_debuglink(const char *filename, char *debuglink,
1095 fd = open(filename, O_RDONLY);
1099 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1101 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
1106 if (ek != ELF_K_ELF)
1109 if (gelf_getehdr(elf, &ehdr) == NULL) {
1110 pr_err("%s: cannot get elf header.\n", __func__);
1114 sec = elf_section_by_name(elf, &ehdr, &shdr,
1115 ".gnu_debuglink", NULL);
1119 data = elf_getdata(sec, NULL);
1123 /* the start of this section is a zero-terminated string */
1124 strncpy(debuglink, data->d_buf, size);
1138 static int dso__swap_init(struct dso *dso, unsigned char eidata)
1140 static unsigned int const endian = 1;
1142 dso->needs_swap = DSO_SWAP__NO;
1146 /* We are big endian, DSO is little endian. */
1147 if (*(unsigned char const *)&endian != 1)
1148 dso->needs_swap = DSO_SWAP__YES;
1152 /* We are little endian, DSO is big endian. */
1153 if (*(unsigned char const *)&endian != 0)
1154 dso->needs_swap = DSO_SWAP__YES;
1158 pr_err("unrecognized DSO data encoding %d\n", eidata);
1165 bool symsrc__possibly_runtime(struct symsrc *ss)
1167 return ss->dynsym || ss->opdsec;
1170 bool symsrc__has_symtab(struct symsrc *ss)
1172 return ss->symtab != NULL;
1175 void symsrc__destroy(struct symsrc *ss)
1182 bool elf__needs_adjust_symbols(GElf_Ehdr ehdr)
1185 * Usually vmlinux is an ELF file with type ET_EXEC for most
1186 * architectures; except Arm64 kernel is linked with option
1187 * '-share', so need to check type ET_DYN.
1189 return ehdr.e_type == ET_EXEC || ehdr.e_type == ET_REL ||
1190 ehdr.e_type == ET_DYN;
1193 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
1194 enum dso_binary_type type)
1200 if (dso__needs_decompress(dso)) {
1201 fd = dso__decompress_kmodule_fd(dso, name);
1205 type = dso->symtab_type;
1207 fd = open(name, O_RDONLY);
1209 dso->load_errno = errno;
1214 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1216 pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1217 dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
1221 if (gelf_getehdr(elf, &ehdr) == NULL) {
1222 dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
1223 pr_debug("%s: cannot get elf header.\n", __func__);
1227 if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
1228 dso->load_errno = DSO_LOAD_ERRNO__INTERNAL_ERROR;
1232 /* Always reject images with a mismatched build-id: */
1233 if (dso->has_build_id && !symbol_conf.ignore_vmlinux_buildid) {
1234 u8 build_id[BUILD_ID_SIZE];
1235 struct build_id bid;
1238 size = elf_read_build_id(elf, build_id, BUILD_ID_SIZE);
1240 dso->load_errno = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
1244 build_id__init(&bid, build_id, size);
1245 if (!dso__build_id_equal(dso, &bid)) {
1246 pr_debug("%s: build id mismatch for %s.\n", __func__, name);
1247 dso->load_errno = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
1252 ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1255 ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
1257 if (ss->symshdr.sh_type != SHT_SYMTAB)
1261 ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
1263 if (ss->dynshdr.sh_type != SHT_DYNSYM)
1267 ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
1269 if (ss->opdshdr.sh_type != SHT_PROGBITS)
1272 if (dso->kernel == DSO_SPACE__USER)
1273 ss->adjust_symbols = true;
1275 ss->adjust_symbols = elf__needs_adjust_symbols(ehdr);
1277 ss->name = strdup(name);
1279 dso->load_errno = errno;
1298 * ref_reloc_sym_not_found - has kernel relocation symbol been found.
1299 * @kmap: kernel maps and relocation reference symbol
1301 * This function returns %true if we are dealing with the kernel maps and the
1302 * relocation reference symbol has not yet been found. Otherwise %false is
1305 static bool ref_reloc_sym_not_found(struct kmap *kmap)
1307 return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
1308 !kmap->ref_reloc_sym->unrelocated_addr;
1312 * ref_reloc - kernel relocation offset.
1313 * @kmap: kernel maps and relocation reference symbol
1315 * This function returns the offset of kernel addresses as determined by using
1316 * the relocation reference symbol i.e. if the kernel has not been relocated
1317 * then the return value is zero.
1319 static u64 ref_reloc(struct kmap *kmap)
1321 if (kmap && kmap->ref_reloc_sym &&
1322 kmap->ref_reloc_sym->unrelocated_addr)
1323 return kmap->ref_reloc_sym->addr -
1324 kmap->ref_reloc_sym->unrelocated_addr;
1328 void __weak arch__sym_update(struct symbol *s __maybe_unused,
1329 GElf_Sym *sym __maybe_unused) { }
1331 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
1332 GElf_Sym *sym, GElf_Shdr *shdr,
1333 struct maps *kmaps, struct kmap *kmap,
1334 struct dso **curr_dsop, struct map **curr_mapp,
1335 const char *section_name,
1336 bool adjust_kernel_syms, bool kmodule, bool *remap_kernel)
1338 struct dso *curr_dso = *curr_dsop;
1339 struct map *curr_map;
1340 char dso_name[PATH_MAX];
1342 /* Adjust symbol to map to file offset */
1343 if (adjust_kernel_syms)
1344 sym->st_value -= shdr->sh_addr - shdr->sh_offset;
1346 if (strcmp(section_name, (curr_dso->short_name + dso->short_name_len)) == 0)
1349 if (strcmp(section_name, ".text") == 0) {
1351 * The initial kernel mapping is based on
1352 * kallsyms and identity maps. Overwrite it to
1353 * map to the kernel dso.
1355 if (*remap_kernel && dso->kernel && !kmodule) {
1356 *remap_kernel = false;
1357 map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
1358 map__set_end(map, map__start(map) + shdr->sh_size);
1359 map__set_pgoff(map, shdr->sh_offset);
1360 map__set_map_ip(map, map__dso_map_ip);
1361 map__set_unmap_ip(map, map__dso_unmap_ip);
1362 /* Ensure maps are correctly ordered */
1367 maps__remove(kmaps, map);
1368 err = maps__insert(kmaps, map);
1376 * The initial module mapping is based on
1377 * /proc/modules mapped to offset zero.
1378 * Overwrite it to map to the module dso.
1380 if (*remap_kernel && kmodule) {
1381 *remap_kernel = false;
1382 map__set_pgoff(map, shdr->sh_offset);
1393 snprintf(dso_name, sizeof(dso_name), "%s%s", dso->short_name, section_name);
1395 curr_map = maps__find_by_name(kmaps, dso_name);
1396 if (curr_map == NULL) {
1397 u64 start = sym->st_value;
1400 start += map__start(map) + shdr->sh_offset;
1402 curr_dso = dso__new(dso_name);
1403 if (curr_dso == NULL)
1405 curr_dso->kernel = dso->kernel;
1406 curr_dso->long_name = dso->long_name;
1407 curr_dso->long_name_len = dso->long_name_len;
1408 curr_map = map__new2(start, curr_dso);
1410 if (curr_map == NULL)
1413 if (curr_dso->kernel)
1414 map__kmap(curr_map)->kmaps = kmaps;
1416 if (adjust_kernel_syms) {
1417 map__set_start(curr_map, shdr->sh_addr + ref_reloc(kmap));
1418 map__set_end(curr_map, map__start(curr_map) + shdr->sh_size);
1419 map__set_pgoff(curr_map, shdr->sh_offset);
1421 map__set_map_ip(curr_map, identity__map_ip);
1422 map__set_unmap_ip(curr_map, identity__map_ip);
1424 curr_dso->symtab_type = dso->symtab_type;
1425 if (maps__insert(kmaps, curr_map))
1428 * Add it before we drop the reference to curr_map, i.e. while
1429 * we still are sure to have a reference to this DSO via
1432 dsos__add(&maps__machine(kmaps)->dsos, curr_dso);
1433 /* kmaps already got it */
1435 dso__set_loaded(curr_dso);
1436 *curr_mapp = curr_map;
1437 *curr_dsop = curr_dso;
1439 *curr_dsop = map__dso(curr_map);
1445 dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1446 struct symsrc *runtime_ss, int kmodule, int dynsym)
1448 struct kmap *kmap = dso->kernel ? map__kmap(map) : NULL;
1449 struct maps *kmaps = kmap ? map__kmaps(map) : NULL;
1450 struct map *curr_map = map;
1451 struct dso *curr_dso = dso;
1452 Elf_Data *symstrs, *secstrs, *secstrs_run, *secstrs_sym;
1459 Elf_Data *syms, *opddata = NULL;
1461 Elf_Scn *sec, *sec_strndx;
1464 bool remap_kernel = false, adjust_kernel_syms = false;
1470 ehdr = syms_ss->ehdr;
1472 sec = syms_ss->dynsym;
1473 shdr = syms_ss->dynshdr;
1475 sec = syms_ss->symtab;
1476 shdr = syms_ss->symshdr;
1479 if (elf_section_by_name(runtime_ss->elf, &runtime_ss->ehdr, &tshdr,
1481 dso->text_offset = tshdr.sh_addr - tshdr.sh_offset;
1483 if (runtime_ss->opdsec)
1484 opddata = elf_rawdata(runtime_ss->opdsec, NULL);
1486 syms = elf_getdata(sec, NULL);
1490 sec = elf_getscn(elf, shdr.sh_link);
1494 symstrs = elf_getdata(sec, NULL);
1495 if (symstrs == NULL)
1498 sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
1499 if (sec_strndx == NULL)
1502 secstrs_run = elf_getdata(sec_strndx, NULL);
1503 if (secstrs_run == NULL)
1506 sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
1507 if (sec_strndx == NULL)
1510 secstrs_sym = elf_getdata(sec_strndx, NULL);
1511 if (secstrs_sym == NULL)
1514 nr_syms = shdr.sh_size / shdr.sh_entsize;
1516 memset(&sym, 0, sizeof(sym));
1519 * The kernel relocation symbol is needed in advance in order to adjust
1520 * kernel maps correctly.
1522 if (ref_reloc_sym_not_found(kmap)) {
1523 elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1524 const char *elf_name = elf_sym__name(&sym, symstrs);
1526 if (strcmp(elf_name, kmap->ref_reloc_sym->name))
1528 kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
1529 map__set_reloc(map, kmap->ref_reloc_sym->addr - kmap->ref_reloc_sym->unrelocated_addr);
1535 * Handle any relocation of vdso necessary because older kernels
1536 * attempted to prelink vdso to its virtual address.
1538 if (dso__is_vdso(dso))
1539 map__set_reloc(map, map__start(map) - dso->text_offset);
1541 dso->adjust_symbols = runtime_ss->adjust_symbols || ref_reloc(kmap);
1543 * Initial kernel and module mappings do not map to the dso.
1547 remap_kernel = true;
1548 adjust_kernel_syms = dso->adjust_symbols;
1550 elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1552 const char *elf_name = elf_sym__name(&sym, symstrs);
1553 char *demangled = NULL;
1554 int is_label = elf_sym__is_label(&sym);
1555 const char *section_name;
1556 bool used_opd = false;
1558 if (!is_label && !elf_sym__filter(&sym))
1561 /* Reject ARM ELF "mapping symbols": these aren't unique and
1562 * don't identify functions, so will confuse the profile
1564 if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
1565 if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
1566 && (elf_name[2] == '\0' || elf_name[2] == '.'))
1570 if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
1571 u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
1572 u64 *opd = opddata->d_buf + offset;
1573 sym.st_value = DSO__SWAP(dso, u64, *opd);
1574 sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
1580 * When loading symbols in a data mapping, ABS symbols (which
1581 * has a value of SHN_ABS in its st_shndx) failed at
1582 * elf_getscn(). And it marks the loading as a failure so
1583 * already loaded symbols cannot be fixed up.
1585 * I'm not sure what should be done. Just ignore them for now.
1588 if (sym.st_shndx == SHN_ABS)
1591 sec = elf_getscn(syms_ss->elf, sym.st_shndx);
1595 gelf_getshdr(sec, &shdr);
1598 * If the attribute bit SHF_ALLOC is not set, the section
1599 * doesn't occupy memory during process execution.
1600 * E.g. ".gnu.warning.*" section is used by linker to generate
1601 * warnings when calling deprecated functions, the symbols in
1602 * the section aren't loaded to memory during process execution,
1605 if (!(shdr.sh_flags & SHF_ALLOC))
1608 secstrs = secstrs_sym;
1611 * We have to fallback to runtime when syms' section header has
1612 * NOBITS set. NOBITS results in file offset (sh_offset) not
1613 * being incremented. So sh_offset used below has different
1614 * values for syms (invalid) and runtime (valid).
1616 if (shdr.sh_type == SHT_NOBITS) {
1617 sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
1621 gelf_getshdr(sec, &shdr);
1622 secstrs = secstrs_run;
1625 if (is_label && !elf_sec__filter(&shdr, secstrs))
1628 section_name = elf_sec__name(&shdr, secstrs);
1630 /* On ARM, symbols for thumb functions have 1 added to
1631 * the symbol address as a flag - remove it */
1632 if ((ehdr.e_machine == EM_ARM) &&
1633 (GELF_ST_TYPE(sym.st_info) == STT_FUNC) &&
1638 if (dso__process_kernel_symbol(dso, map, &sym, &shdr, kmaps, kmap, &curr_dso, &curr_map,
1639 section_name, adjust_kernel_syms, kmodule, &remap_kernel))
1641 } else if ((used_opd && runtime_ss->adjust_symbols) ||
1642 (!used_opd && syms_ss->adjust_symbols)) {
1645 if (elf_read_program_header(runtime_ss->elf,
1646 (u64)sym.st_value, &phdr)) {
1647 pr_debug4("%s: failed to find program header for "
1648 "symbol: %s st_value: %#" PRIx64 "\n",
1649 __func__, elf_name, (u64)sym.st_value);
1650 pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1651 "sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n",
1652 __func__, (u64)sym.st_value, (u64)shdr.sh_addr,
1653 (u64)shdr.sh_offset);
1655 * Fail to find program header, let's rollback
1656 * to use shdr.sh_addr and shdr.sh_offset to
1657 * calibrate symbol's file address, though this
1658 * is not necessary for normal C ELF file, we
1659 * still need to handle java JIT symbols in this
1662 sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1664 pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1665 "p_vaddr: %#" PRIx64 " p_offset: %#" PRIx64 "\n",
1666 __func__, (u64)sym.st_value, (u64)phdr.p_vaddr,
1667 (u64)phdr.p_offset);
1668 sym.st_value -= phdr.p_vaddr - phdr.p_offset;
1672 demangled = demangle_sym(dso, kmodule, elf_name);
1673 if (demangled != NULL)
1674 elf_name = demangled;
1676 f = symbol__new(sym.st_value, sym.st_size,
1677 GELF_ST_BIND(sym.st_info),
1678 GELF_ST_TYPE(sym.st_info), elf_name);
1683 arch__sym_update(f, &sym);
1685 __symbols__insert(&curr_dso->symbols, f, dso->kernel);
1690 * For misannotated, zeroed, ASM function sizes.
1693 symbols__fixup_end(&dso->symbols, false);
1694 symbols__fixup_duplicate(&dso->symbols);
1697 * We need to fixup this here too because we create new
1698 * maps here, for things like vsyscall sections.
1700 maps__fixup_end(kmaps);
1708 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1709 struct symsrc *runtime_ss, int kmodule)
1714 dso->symtab_type = syms_ss->type;
1715 dso->is_64_bit = syms_ss->is_64_bit;
1716 dso->rel = syms_ss->ehdr.e_type == ET_REL;
1719 * Modules may already have symbols from kallsyms, but those symbols
1720 * have the wrong values for the dso maps, so remove them.
1722 if (kmodule && syms_ss->symtab)
1723 symbols__delete(&dso->symbols);
1725 if (!syms_ss->symtab) {
1727 * If the vmlinux is stripped, fail so we will fall back
1728 * to using kallsyms. The vmlinux runtime symbols aren't
1734 err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1741 if (syms_ss->dynsym) {
1742 err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1752 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1759 if (elf_getphdrnum(elf, &phdrnum))
1762 for (i = 0; i < phdrnum; i++) {
1763 if (gelf_getphdr(elf, i, &phdr) == NULL)
1765 if (phdr.p_type != PT_LOAD)
1768 if (!(phdr.p_flags & PF_X))
1771 if (!(phdr.p_flags & PF_R))
1774 sz = min(phdr.p_memsz, phdr.p_filesz);
1777 err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1784 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1790 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1795 *is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1797 err = elf_read_maps(elf, exe, mapfn, data);
1803 enum dso_type dso__type_fd(int fd)
1805 enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1810 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1815 if (ek != ELF_K_ELF)
1818 if (gelf_getclass(elf) == ELFCLASS64) {
1819 dso_type = DSO__TYPE_64BIT;
1823 if (gelf_getehdr(elf, &ehdr) == NULL)
1826 if (ehdr.e_machine == EM_X86_64)
1827 dso_type = DSO__TYPE_X32BIT;
1829 dso_type = DSO__TYPE_32BIT;
1836 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1841 char *buf = malloc(page_size);
1846 if (lseek(to, to_offs, SEEK_SET) != to_offs)
1849 if (lseek(from, from_offs, SEEK_SET) != from_offs)
1856 /* Use read because mmap won't work on proc files */
1857 r = read(from, buf, n);
1863 r = write(to, buf, n);
1884 static int kcore__open(struct kcore *kcore, const char *filename)
1888 kcore->fd = open(filename, O_RDONLY);
1889 if (kcore->fd == -1)
1892 kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1896 kcore->elfclass = gelf_getclass(kcore->elf);
1897 if (kcore->elfclass == ELFCLASSNONE)
1900 ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1907 elf_end(kcore->elf);
1913 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1916 kcore->elfclass = elfclass;
1919 kcore->fd = mkstemp(filename);
1921 kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0400);
1922 if (kcore->fd == -1)
1925 kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1929 if (!gelf_newehdr(kcore->elf, elfclass))
1932 memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
1937 elf_end(kcore->elf);
1944 static void kcore__close(struct kcore *kcore)
1946 elf_end(kcore->elf);
1950 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
1952 GElf_Ehdr *ehdr = &to->ehdr;
1953 GElf_Ehdr *kehdr = &from->ehdr;
1955 memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
1956 ehdr->e_type = kehdr->e_type;
1957 ehdr->e_machine = kehdr->e_machine;
1958 ehdr->e_version = kehdr->e_version;
1961 ehdr->e_flags = kehdr->e_flags;
1962 ehdr->e_phnum = count;
1963 ehdr->e_shentsize = 0;
1965 ehdr->e_shstrndx = 0;
1967 if (from->elfclass == ELFCLASS32) {
1968 ehdr->e_phoff = sizeof(Elf32_Ehdr);
1969 ehdr->e_ehsize = sizeof(Elf32_Ehdr);
1970 ehdr->e_phentsize = sizeof(Elf32_Phdr);
1972 ehdr->e_phoff = sizeof(Elf64_Ehdr);
1973 ehdr->e_ehsize = sizeof(Elf64_Ehdr);
1974 ehdr->e_phentsize = sizeof(Elf64_Phdr);
1977 if (!gelf_update_ehdr(to->elf, ehdr))
1980 if (!gelf_newphdr(to->elf, count))
1986 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
1991 .p_flags = PF_R | PF_W | PF_X,
1997 .p_align = page_size,
2000 if (!gelf_update_phdr(kcore->elf, idx, &phdr))
2006 static off_t kcore__write(struct kcore *kcore)
2008 return elf_update(kcore->elf, ELF_C_WRITE);
2016 struct list_head node;
2017 struct phdr_data *remaps;
2022 struct list_head node;
2025 struct kcore_copy_info {
2031 u64 first_module_symbol;
2032 u64 last_module_symbol;
2034 struct list_head phdrs;
2035 struct list_head syms;
2038 #define kcore_copy__for_each_phdr(k, p) \
2039 list_for_each_entry((p), &(k)->phdrs, node)
2041 static struct phdr_data *phdr_data__new(u64 addr, u64 len, off_t offset)
2043 struct phdr_data *p = zalloc(sizeof(*p));
2054 static struct phdr_data *kcore_copy_info__addnew(struct kcore_copy_info *kci,
2058 struct phdr_data *p = phdr_data__new(addr, len, offset);
2061 list_add_tail(&p->node, &kci->phdrs);
2066 static void kcore_copy__free_phdrs(struct kcore_copy_info *kci)
2068 struct phdr_data *p, *tmp;
2070 list_for_each_entry_safe(p, tmp, &kci->phdrs, node) {
2071 list_del_init(&p->node);
2076 static struct sym_data *kcore_copy__new_sym(struct kcore_copy_info *kci,
2079 struct sym_data *s = zalloc(sizeof(*s));
2083 list_add_tail(&s->node, &kci->syms);
2089 static void kcore_copy__free_syms(struct kcore_copy_info *kci)
2091 struct sym_data *s, *tmp;
2093 list_for_each_entry_safe(s, tmp, &kci->syms, node) {
2094 list_del_init(&s->node);
2099 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
2102 struct kcore_copy_info *kci = arg;
2104 if (!kallsyms__is_function(type))
2107 if (strchr(name, '[')) {
2108 if (!kci->first_module_symbol || start < kci->first_module_symbol)
2109 kci->first_module_symbol = start;
2110 if (start > kci->last_module_symbol)
2111 kci->last_module_symbol = start;
2115 if (!kci->first_symbol || start < kci->first_symbol)
2116 kci->first_symbol = start;
2118 if (!kci->last_symbol || start > kci->last_symbol)
2119 kci->last_symbol = start;
2121 if (!strcmp(name, "_stext")) {
2126 if (!strcmp(name, "_etext")) {
2131 if (is_entry_trampoline(name) && !kcore_copy__new_sym(kci, start))
2137 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
2140 char kallsyms_filename[PATH_MAX];
2142 scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
2144 if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
2147 if (kallsyms__parse(kallsyms_filename, kci,
2148 kcore_copy__process_kallsyms) < 0)
2154 static int kcore_copy__process_modules(void *arg,
2155 const char *name __maybe_unused,
2156 u64 start, u64 size __maybe_unused)
2158 struct kcore_copy_info *kci = arg;
2160 if (!kci->first_module || start < kci->first_module)
2161 kci->first_module = start;
2166 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
2169 char modules_filename[PATH_MAX];
2171 scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
2173 if (symbol__restricted_filename(modules_filename, "/proc/modules"))
2176 if (modules__parse(modules_filename, kci,
2177 kcore_copy__process_modules) < 0)
2183 static int kcore_copy__map(struct kcore_copy_info *kci, u64 start, u64 end,
2184 u64 pgoff, u64 s, u64 e)
2188 if (s < start || s >= end)
2191 offset = (s - start) + pgoff;
2192 len = e < end ? e - s : end - s;
2194 return kcore_copy_info__addnew(kci, s, len, offset) ? 0 : -1;
2197 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
2199 struct kcore_copy_info *kci = data;
2200 u64 end = start + len;
2201 struct sym_data *sdat;
2203 if (kcore_copy__map(kci, start, end, pgoff, kci->stext, kci->etext))
2206 if (kcore_copy__map(kci, start, end, pgoff, kci->first_module,
2207 kci->last_module_symbol))
2210 list_for_each_entry(sdat, &kci->syms, node) {
2211 u64 s = round_down(sdat->addr, page_size);
2213 if (kcore_copy__map(kci, start, end, pgoff, s, s + len))
2220 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
2222 if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
2228 static void kcore_copy__find_remaps(struct kcore_copy_info *kci)
2230 struct phdr_data *p, *k = NULL;
2236 /* Find phdr that corresponds to the kernel map (contains stext) */
2237 kcore_copy__for_each_phdr(kci, p) {
2238 u64 pend = p->addr + p->len - 1;
2240 if (p->addr <= kci->stext && pend >= kci->stext) {
2249 kend = k->offset + k->len;
2251 /* Find phdrs that remap the kernel */
2252 kcore_copy__for_each_phdr(kci, p) {
2253 u64 pend = p->offset + p->len;
2258 if (p->offset >= k->offset && pend <= kend)
2263 static void kcore_copy__layout(struct kcore_copy_info *kci)
2265 struct phdr_data *p;
2268 kcore_copy__find_remaps(kci);
2270 kcore_copy__for_each_phdr(kci, p) {
2278 kcore_copy__for_each_phdr(kci, p) {
2279 struct phdr_data *k = p->remaps;
2282 p->rel = p->offset - k->offset + k->rel;
2286 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
2289 if (kcore_copy__parse_kallsyms(kci, dir))
2292 if (kcore_copy__parse_modules(kci, dir))
2296 kci->stext = round_down(kci->stext, page_size);
2298 kci->stext = round_down(kci->first_symbol, page_size);
2301 kci->etext = round_up(kci->etext, page_size);
2302 } else if (kci->last_symbol) {
2303 kci->etext = round_up(kci->last_symbol, page_size);
2304 kci->etext += page_size;
2307 if (kci->first_module_symbol &&
2308 (!kci->first_module || kci->first_module_symbol < kci->first_module))
2309 kci->first_module = kci->first_module_symbol;
2311 kci->first_module = round_down(kci->first_module, page_size);
2313 if (kci->last_module_symbol) {
2314 kci->last_module_symbol = round_up(kci->last_module_symbol,
2316 kci->last_module_symbol += page_size;
2319 if (!kci->stext || !kci->etext)
2322 if (kci->first_module && !kci->last_module_symbol)
2325 if (kcore_copy__read_maps(kci, elf))
2328 kcore_copy__layout(kci);
2333 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
2336 char from_filename[PATH_MAX];
2337 char to_filename[PATH_MAX];
2339 scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2340 scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2342 return copyfile_mode(from_filename, to_filename, 0400);
2345 static int kcore_copy__unlink(const char *dir, const char *name)
2347 char filename[PATH_MAX];
2349 scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
2351 return unlink(filename);
2354 static int kcore_copy__compare_fds(int from, int to)
2362 buf_from = malloc(page_size);
2363 buf_to = malloc(page_size);
2364 if (!buf_from || !buf_to)
2368 /* Use read because mmap won't work on proc files */
2369 ret = read(from, buf_from, page_size);
2378 if (readn(to, buf_to, len) != (int)len)
2381 if (memcmp(buf_from, buf_to, len))
2392 static int kcore_copy__compare_files(const char *from_filename,
2393 const char *to_filename)
2395 int from, to, err = -1;
2397 from = open(from_filename, O_RDONLY);
2401 to = open(to_filename, O_RDONLY);
2403 goto out_close_from;
2405 err = kcore_copy__compare_fds(from, to);
2413 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
2416 char from_filename[PATH_MAX];
2417 char to_filename[PATH_MAX];
2419 scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2420 scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2422 return kcore_copy__compare_files(from_filename, to_filename);
2426 * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
2427 * @from_dir: from directory
2428 * @to_dir: to directory
2430 * This function copies kallsyms, modules and kcore files from one directory to
2431 * another. kallsyms and modules are copied entirely. Only code segments are
2432 * copied from kcore. It is assumed that two segments suffice: one for the
2433 * kernel proper and one for all the modules. The code segments are determined
2434 * from kallsyms and modules files. The kernel map starts at _stext or the
2435 * lowest function symbol, and ends at _etext or the highest function symbol.
2436 * The module map starts at the lowest module address and ends at the highest
2437 * module symbol. Start addresses are rounded down to the nearest page. End
2438 * addresses are rounded up to the nearest page. An extra page is added to the
2439 * highest kernel symbol and highest module symbol to, hopefully, encompass that
2440 * symbol too. Because it contains only code sections, the resulting kcore is
2441 * unusual. One significant peculiarity is that the mapping (start -> pgoff)
2442 * is not the same for the kernel map and the modules map. That happens because
2443 * the data is copied adjacently whereas the original kcore has gaps. Finally,
2444 * kallsyms file is compared with its copy to check that modules have not been
2445 * loaded or unloaded while the copies were taking place.
2447 * Return: %0 on success, %-1 on failure.
2449 int kcore_copy(const char *from_dir, const char *to_dir)
2452 struct kcore extract;
2453 int idx = 0, err = -1;
2455 struct kcore_copy_info kci = { .stext = 0, };
2456 char kcore_filename[PATH_MAX];
2457 char extract_filename[PATH_MAX];
2458 struct phdr_data *p;
2460 INIT_LIST_HEAD(&kci.phdrs);
2461 INIT_LIST_HEAD(&kci.syms);
2463 if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
2466 if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
2467 goto out_unlink_kallsyms;
2469 scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
2470 scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
2472 if (kcore__open(&kcore, kcore_filename))
2473 goto out_unlink_modules;
2475 if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
2476 goto out_kcore_close;
2478 if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
2479 goto out_kcore_close;
2481 if (kcore__copy_hdr(&kcore, &extract, kci.phnum))
2482 goto out_extract_close;
2484 offset = gelf_fsize(extract.elf, ELF_T_EHDR, 1, EV_CURRENT) +
2485 gelf_fsize(extract.elf, ELF_T_PHDR, kci.phnum, EV_CURRENT);
2486 offset = round_up(offset, page_size);
2488 kcore_copy__for_each_phdr(&kci, p) {
2489 off_t offs = p->rel + offset;
2491 if (kcore__add_phdr(&extract, idx++, offs, p->addr, p->len))
2492 goto out_extract_close;
2495 sz = kcore__write(&extract);
2496 if (sz < 0 || sz > offset)
2497 goto out_extract_close;
2499 kcore_copy__for_each_phdr(&kci, p) {
2500 off_t offs = p->rel + offset;
2504 if (copy_bytes(kcore.fd, p->offset, extract.fd, offs, p->len))
2505 goto out_extract_close;
2508 if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
2509 goto out_extract_close;
2514 kcore__close(&extract);
2516 unlink(extract_filename);
2518 kcore__close(&kcore);
2521 kcore_copy__unlink(to_dir, "modules");
2522 out_unlink_kallsyms:
2524 kcore_copy__unlink(to_dir, "kallsyms");
2526 kcore_copy__free_phdrs(&kci);
2527 kcore_copy__free_syms(&kci);
2532 int kcore_extract__create(struct kcore_extract *kce)
2535 struct kcore extract;
2537 int idx = 0, err = -1;
2538 off_t offset = page_size, sz;
2540 if (kcore__open(&kcore, kce->kcore_filename))
2543 strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
2544 if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
2545 goto out_kcore_close;
2547 if (kcore__copy_hdr(&kcore, &extract, count))
2548 goto out_extract_close;
2550 if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
2551 goto out_extract_close;
2553 sz = kcore__write(&extract);
2554 if (sz < 0 || sz > offset)
2555 goto out_extract_close;
2557 if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
2558 goto out_extract_close;
2563 kcore__close(&extract);
2565 unlink(kce->extract_filename);
2567 kcore__close(&kcore);
2572 void kcore_extract__delete(struct kcore_extract *kce)
2574 unlink(kce->extract_filename);
2577 #ifdef HAVE_GELF_GETNOTE_SUPPORT
2579 static void sdt_adjust_loc(struct sdt_note *tmp, GElf_Addr base_off)
2585 tmp->addr.a32[SDT_NOTE_IDX_LOC] =
2586 tmp->addr.a32[SDT_NOTE_IDX_LOC] + base_off -
2587 tmp->addr.a32[SDT_NOTE_IDX_BASE];
2589 tmp->addr.a64[SDT_NOTE_IDX_LOC] =
2590 tmp->addr.a64[SDT_NOTE_IDX_LOC] + base_off -
2591 tmp->addr.a64[SDT_NOTE_IDX_BASE];
2594 static void sdt_adjust_refctr(struct sdt_note *tmp, GElf_Addr base_addr,
2600 if (tmp->bit32 && tmp->addr.a32[SDT_NOTE_IDX_REFCTR])
2601 tmp->addr.a32[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2602 else if (tmp->addr.a64[SDT_NOTE_IDX_REFCTR])
2603 tmp->addr.a64[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2607 * populate_sdt_note : Parse raw data and identify SDT note
2608 * @elf: elf of the opened file
2609 * @data: raw data of a section with description offset applied
2610 * @len: note description size
2611 * @type: type of the note
2612 * @sdt_notes: List to add the SDT note
2614 * Responsible for parsing the @data in section .note.stapsdt in @elf and
2615 * if its an SDT note, it appends to @sdt_notes list.
2617 static int populate_sdt_note(Elf **elf, const char *data, size_t len,
2618 struct list_head *sdt_notes)
2620 const char *provider, *name, *args;
2621 struct sdt_note *tmp = NULL;
2627 Elf64_Addr a64[NR_ADDR];
2628 Elf32_Addr a32[NR_ADDR];
2632 .d_buf = &buf, .d_type = ELF_T_ADDR, .d_version = EV_CURRENT,
2633 .d_size = gelf_fsize((*elf), ELF_T_ADDR, NR_ADDR, EV_CURRENT),
2634 .d_off = 0, .d_align = 0
2637 .d_buf = (void *) data, .d_type = ELF_T_ADDR,
2638 .d_version = EV_CURRENT, .d_size = dst.d_size, .d_off = 0,
2642 tmp = (struct sdt_note *)calloc(1, sizeof(struct sdt_note));
2648 INIT_LIST_HEAD(&tmp->note_list);
2650 if (len < dst.d_size + 3)
2653 /* Translation from file representation to memory representation */
2654 if (gelf_xlatetom(*elf, &dst, &src,
2655 elf_getident(*elf, NULL)[EI_DATA]) == NULL) {
2656 pr_err("gelf_xlatetom : %s\n", elf_errmsg(-1));
2660 /* Populate the fields of sdt_note */
2661 provider = data + dst.d_size;
2663 name = (const char *)memchr(provider, '\0', data + len - provider);
2667 tmp->provider = strdup(provider);
2668 if (!tmp->provider) {
2672 tmp->name = strdup(name);
2678 args = memchr(name, '\0', data + len - name);
2681 * There is no argument if:
2682 * - We reached the end of the note;
2683 * - There is not enough room to hold a potential string;
2684 * - The argument string is empty or just contains ':'.
2686 if (args == NULL || data + len - args < 2 ||
2687 args[1] == ':' || args[1] == '\0')
2690 tmp->args = strdup(++args);
2697 if (gelf_getclass(*elf) == ELFCLASS32) {
2698 memcpy(&tmp->addr, &buf, 3 * sizeof(Elf32_Addr));
2701 memcpy(&tmp->addr, &buf, 3 * sizeof(Elf64_Addr));
2705 if (!gelf_getehdr(*elf, &ehdr)) {
2706 pr_debug("%s : cannot get elf header.\n", __func__);
2711 /* Adjust the prelink effect :
2712 * Find out the .stapsdt.base section.
2713 * This scn will help us to handle prelinking (if present).
2714 * Compare the retrieved file offset of the base section with the
2715 * base address in the description of the SDT note. If its different,
2716 * then accordingly, adjust the note location.
2718 if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_BASE_SCN, NULL))
2719 sdt_adjust_loc(tmp, shdr.sh_offset);
2721 /* Adjust reference counter offset */
2722 if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_PROBES_SCN, NULL))
2723 sdt_adjust_refctr(tmp, shdr.sh_addr, shdr.sh_offset);
2725 list_add_tail(&tmp->note_list, sdt_notes);
2733 zfree(&tmp->provider);
2741 * construct_sdt_notes_list : constructs a list of SDT notes
2742 * @elf : elf to look into
2743 * @sdt_notes : empty list_head
2745 * Scans the sections in 'elf' for the section
2746 * .note.stapsdt. It, then calls populate_sdt_note to find
2747 * out the SDT events and populates the 'sdt_notes'.
2749 static int construct_sdt_notes_list(Elf *elf, struct list_head *sdt_notes)
2752 Elf_Scn *scn = NULL;
2755 size_t shstrndx, next;
2757 size_t name_off, desc_off, offset;
2760 if (gelf_getehdr(elf, &ehdr) == NULL) {
2764 if (elf_getshdrstrndx(elf, &shstrndx) != 0) {
2769 /* Look for the required section */
2770 scn = elf_section_by_name(elf, &ehdr, &shdr, SDT_NOTE_SCN, NULL);
2776 if ((shdr.sh_type != SHT_NOTE) || (shdr.sh_flags & SHF_ALLOC)) {
2781 data = elf_getdata(scn, NULL);
2783 /* Get the SDT notes */
2784 for (offset = 0; (next = gelf_getnote(data, offset, &nhdr, &name_off,
2785 &desc_off)) > 0; offset = next) {
2786 if (nhdr.n_namesz == sizeof(SDT_NOTE_NAME) &&
2787 !memcmp(data->d_buf + name_off, SDT_NOTE_NAME,
2788 sizeof(SDT_NOTE_NAME))) {
2789 /* Check the type of the note */
2790 if (nhdr.n_type != SDT_NOTE_TYPE)
2793 ret = populate_sdt_note(&elf, ((data->d_buf) + desc_off),
2794 nhdr.n_descsz, sdt_notes);
2799 if (list_empty(sdt_notes))
2807 * get_sdt_note_list : Wrapper to construct a list of sdt notes
2808 * @head : empty list_head
2809 * @target : file to find SDT notes from
2811 * This opens the file, initializes
2812 * the ELF and then calls construct_sdt_notes_list.
2814 int get_sdt_note_list(struct list_head *head, const char *target)
2819 fd = open(target, O_RDONLY);
2823 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
2828 ret = construct_sdt_notes_list(elf, head);
2836 * cleanup_sdt_note_list : free the sdt notes' list
2837 * @sdt_notes: sdt notes' list
2839 * Free up the SDT notes in @sdt_notes.
2840 * Returns the number of SDT notes free'd.
2842 int cleanup_sdt_note_list(struct list_head *sdt_notes)
2844 struct sdt_note *tmp, *pos;
2847 list_for_each_entry_safe(pos, tmp, sdt_notes, note_list) {
2848 list_del_init(&pos->note_list);
2851 zfree(&pos->provider);
2859 * sdt_notes__get_count: Counts the number of sdt events
2860 * @start: list_head to sdt_notes list
2862 * Returns the number of SDT notes in a list
2864 int sdt_notes__get_count(struct list_head *start)
2866 struct sdt_note *sdt_ptr;
2869 list_for_each_entry(sdt_ptr, start, note_list)
2875 void symbol__elf_init(void)
2877 elf_version(EV_CURRENT);