1 // SPDX-License-Identifier: GPL-2.0
15 #include "demangle-ocaml.h"
16 #include "demangle-java.h"
17 #include "demangle-rust.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>
29 #define EM_AARCH64 183 /* ARM 64 bit */
32 #ifndef ELF32_ST_VISIBILITY
33 #define ELF32_ST_VISIBILITY(o) ((o) & 0x03)
36 /* For ELF64 the definitions are the same. */
37 #ifndef ELF64_ST_VISIBILITY
38 #define ELF64_ST_VISIBILITY(o) ELF32_ST_VISIBILITY (o)
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)
46 typedef Elf64_Nhdr GElf_Nhdr;
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 */
54 #ifdef HAVE_LIBBFD_SUPPORT
55 #define PACKAGE 'perf'
58 #ifdef HAVE_CPLUS_DEMANGLE_SUPPORT
59 extern char *cplus_demangle(const char *, int);
61 static inline char *bfd_demangle(void __maybe_unused *v, const char *c, int i)
63 return cplus_demangle(c, i);
67 static inline char *bfd_demangle(void __maybe_unused *v,
68 const char __maybe_unused *c,
77 #ifndef HAVE_ELF_GETPHDRNUM_SUPPORT
78 static int elf_getphdrnum(Elf *elf, size_t *dst)
83 ehdr = gelf_getehdr(elf, &gehdr);
93 #ifndef HAVE_ELF_GETSHDRSTRNDX_SUPPORT
94 static int elf_getshdrstrndx(Elf *elf __maybe_unused, size_t *dst __maybe_unused)
96 pr_err("%s: update your libelf to > 0.140, this one lacks elf_getshdrstrndx().\n", __func__);
101 #ifndef NT_GNU_BUILD_ID
102 #define NT_GNU_BUILD_ID 3
106 * elf_symtab__for_each_symbol - iterate thru all the symbols
108 * @syms: struct elf_symtab instance to iterate
110 * @sym: GElf_Sym iterator
112 #define elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) \
113 for (idx = 0, gelf_getsym(syms, idx, &sym);\
115 idx++, gelf_getsym(syms, idx, &sym))
117 static inline uint8_t elf_sym__type(const GElf_Sym *sym)
119 return GELF_ST_TYPE(sym->st_info);
122 static inline uint8_t elf_sym__visibility(const GElf_Sym *sym)
124 return GELF_ST_VISIBILITY(sym->st_other);
127 #ifndef STT_GNU_IFUNC
128 #define STT_GNU_IFUNC 10
131 static inline int elf_sym__is_function(const GElf_Sym *sym)
133 return (elf_sym__type(sym) == STT_FUNC ||
134 elf_sym__type(sym) == STT_GNU_IFUNC) &&
136 sym->st_shndx != SHN_UNDEF;
139 static inline bool elf_sym__is_object(const GElf_Sym *sym)
141 return elf_sym__type(sym) == STT_OBJECT &&
143 sym->st_shndx != SHN_UNDEF;
146 static inline int elf_sym__is_label(const GElf_Sym *sym)
148 return elf_sym__type(sym) == STT_NOTYPE &&
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;
156 static bool elf_sym__filter(GElf_Sym *sym)
158 return elf_sym__is_function(sym) || elf_sym__is_object(sym);
161 static inline const char *elf_sym__name(const GElf_Sym *sym,
162 const Elf_Data *symstrs)
164 return symstrs->d_buf + sym->st_name;
167 static inline const char *elf_sec__name(const GElf_Shdr *shdr,
168 const Elf_Data *secstrs)
170 return secstrs->d_buf + shdr->sh_name;
173 static inline int elf_sec__is_text(const GElf_Shdr *shdr,
174 const Elf_Data *secstrs)
176 return strstr(elf_sec__name(shdr, secstrs), "text") != NULL;
179 static inline bool elf_sec__is_data(const GElf_Shdr *shdr,
180 const Elf_Data *secstrs)
182 return strstr(elf_sec__name(shdr, secstrs), "data") != NULL;
185 static bool elf_sec__filter(GElf_Shdr *shdr, Elf_Data *secstrs)
187 return elf_sec__is_text(shdr, secstrs) ||
188 elf_sec__is_data(shdr, secstrs);
191 static size_t elf_addr_to_index(Elf *elf, GElf_Addr addr)
197 while ((sec = elf_nextscn(elf, sec)) != NULL) {
198 gelf_getshdr(sec, &shdr);
200 if ((addr >= shdr.sh_addr) &&
201 (addr < (shdr.sh_addr + shdr.sh_size)))
210 Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
211 GElf_Shdr *shp, const char *name, size_t *idx)
216 /* ELF is corrupted/truncated, avoid calling elf_strptr. */
217 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL))
220 while ((sec = elf_nextscn(elf, sec)) != NULL) {
223 gelf_getshdr(sec, shp);
224 str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
225 if (str && !strcmp(name, str)) {
236 bool filename__has_section(const char *filename, const char *sec)
244 fd = open(filename, O_RDONLY);
248 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
252 if (gelf_getehdr(elf, &ehdr) == NULL)
255 found = !!elf_section_by_name(elf, &ehdr, &shdr, sec, NULL);
264 static int elf_read_program_header(Elf *elf, u64 vaddr, GElf_Phdr *phdr)
269 if (elf_getphdrnum(elf, &phdrnum))
272 for (i = 0; i < phdrnum; i++) {
273 if (gelf_getphdr(elf, i, phdr) == NULL)
276 if (phdr->p_type != PT_LOAD)
279 sz = max(phdr->p_memsz, phdr->p_filesz);
283 if (vaddr >= phdr->p_vaddr && (vaddr < phdr->p_vaddr + sz))
287 /* Not found any valid program header */
291 static bool want_demangle(bool is_kernel_sym)
293 return is_kernel_sym ? symbol_conf.demangle_kernel : symbol_conf.demangle;
296 static char *demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
298 int demangle_flags = verbose > 0 ? (DMGL_PARAMS | DMGL_ANSI) : DMGL_NO_OPTS;
299 char *demangled = NULL;
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
306 if (!want_demangle(dso->kernel || kmodule))
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);
316 else if (rust_is_mangled(demangled))
318 * Input to Rust demangling is the BFD-demangled
319 * name which it Rust-demangles in place.
321 rust_demangle_sym(demangled);
335 static u32 get_rel_symidx(struct rel_info *ri, u32 idx)
337 idx = ri->sorted ? ri->sorted[idx] : idx;
339 gelf_getrela(ri->reldata, idx, &ri->rela);
340 return GELF_R_SYM(ri->rela.r_info);
342 gelf_getrel(ri->reldata, idx, &ri->rel);
343 return GELF_R_SYM(ri->rel.r_info);
346 static u64 get_rel_offset(struct rel_info *ri, u32 x)
351 gelf_getrela(ri->reldata, x, &rela);
352 return rela.r_offset;
356 gelf_getrel(ri->reldata, x, &rel);
361 static int rel_cmp(const void *a, const void *b, void *r)
363 struct rel_info *ri = r;
364 u64 a_offset = get_rel_offset(ri, *(const u32 *)a);
365 u64 b_offset = get_rel_offset(ri, *(const u32 *)b);
367 return a_offset < b_offset ? -1 : (a_offset > b_offset ? 1 : 0);
370 static int sort_rel(struct rel_info *ri)
372 size_t sz = sizeof(ri->sorted[0]);
375 ri->sorted = calloc(ri->nr_entries, sz);
378 for (i = 0; i < ri->nr_entries; i++)
380 qsort_r(ri->sorted, ri->nr_entries, sz, rel_cmp, ri);
385 * For x86_64, the GNU linker is putting IFUNC information in the relocation
388 static bool addend_may_be_ifunc(GElf_Ehdr *ehdr, struct rel_info *ri)
390 return ehdr->e_machine == EM_X86_64 && ri->is_rela &&
391 GELF_R_TYPE(ri->rela.r_info) == R_X86_64_IRELATIVE;
394 static bool get_ifunc_name(Elf *elf, struct dso *dso, GElf_Ehdr *ehdr,
395 struct rel_info *ri, char *buf, size_t buf_sz)
397 u64 addr = ri->rela.r_addend;
401 if (!addend_may_be_ifunc(ehdr, ri))
404 if (elf_read_program_header(elf, addr, &phdr))
407 addr -= phdr.p_vaddr - phdr.p_offset;
409 sym = dso__find_symbol_nocache(dso, addr);
411 /* Expecting the address to be an IFUNC or IFUNC alias */
412 if (!sym || sym->start != addr || (sym->type != STT_GNU_IFUNC && !sym->ifunc_alias))
415 snprintf(buf, buf_sz, "%s@plt", sym->name);
420 static void exit_rel(struct rel_info *ri)
425 static bool get_plt_sizes(struct dso *dso, GElf_Ehdr *ehdr, GElf_Shdr *shdr_plt,
426 u64 *plt_header_size, u64 *plt_entry_size)
428 switch (ehdr->e_machine) {
430 *plt_header_size = 20;
431 *plt_entry_size = 12;
434 *plt_header_size = 32;
435 *plt_entry_size = 16;
438 *plt_header_size = 48;
439 *plt_entry_size = 12;
442 *plt_header_size = 128;
443 *plt_entry_size = 32;
447 *plt_entry_size = shdr_plt->sh_entsize;
448 /* Size is 8 or 16, if not, assume alignment indicates size */
449 if (*plt_entry_size != 8 && *plt_entry_size != 16)
450 *plt_entry_size = shdr_plt->sh_addralign == 8 ? 8 : 16;
451 *plt_header_size = *plt_entry_size;
453 default: /* FIXME: s390/alpha/mips/parisc/poperpc/sh/xtensa need to be checked */
454 *plt_header_size = shdr_plt->sh_entsize;
455 *plt_entry_size = shdr_plt->sh_entsize;
460 pr_debug("Missing PLT entry size for %s\n", dso->long_name);
464 static bool machine_is_x86(GElf_Half e_machine)
466 return e_machine == EM_386 || e_machine == EM_X86_64;
474 struct rela_dyn_info {
476 Elf_Data *plt_got_data;
478 struct rela_dyn *sorted;
479 Elf_Data *dynsym_data;
480 Elf_Data *dynstr_data;
481 Elf_Data *rela_dyn_data;
484 static void exit_rela_dyn(struct rela_dyn_info *di)
489 static int cmp_offset(const void *a, const void *b)
491 const struct rela_dyn *va = a;
492 const struct rela_dyn *vb = b;
494 return va->offset < vb->offset ? -1 : (va->offset > vb->offset ? 1 : 0);
497 static int sort_rela_dyn(struct rela_dyn_info *di)
501 di->sorted = calloc(di->nr_entries, sizeof(di->sorted[0]));
505 /* Get data for sorting: the offset and symbol index */
506 for (i = 0, n = 0; i < di->nr_entries; i++) {
510 gelf_getrela(di->rela_dyn_data, i, &rela);
511 sym_idx = GELF_R_SYM(rela.r_info);
513 di->sorted[n].sym_idx = sym_idx;
514 di->sorted[n].offset = rela.r_offset;
521 qsort(di->sorted, n, sizeof(di->sorted[0]), cmp_offset);
526 static void get_rela_dyn_info(Elf *elf, GElf_Ehdr *ehdr, struct rela_dyn_info *di, Elf_Scn *scn)
528 GElf_Shdr rela_dyn_shdr;
531 di->plt_got_data = elf_getdata(scn, NULL);
533 scn = elf_section_by_name(elf, ehdr, &rela_dyn_shdr, ".rela.dyn", NULL);
534 if (!scn || !rela_dyn_shdr.sh_link || !rela_dyn_shdr.sh_entsize)
537 di->nr_entries = rela_dyn_shdr.sh_size / rela_dyn_shdr.sh_entsize;
538 di->rela_dyn_data = elf_getdata(scn, NULL);
540 scn = elf_getscn(elf, rela_dyn_shdr.sh_link);
541 if (!scn || !gelf_getshdr(scn, &shdr) || !shdr.sh_link)
544 di->dynsym_data = elf_getdata(scn, NULL);
545 di->dynstr_data = elf_getdata(elf_getscn(elf, shdr.sh_link), NULL);
547 if (!di->plt_got_data || !di->dynstr_data || !di->dynsym_data || !di->rela_dyn_data)
550 /* Sort into offset order */
554 /* Get instruction displacement from a plt entry for x86_64 */
555 static u32 get_x86_64_plt_disp(const u8 *p)
557 u8 endbr64[] = {0xf3, 0x0f, 0x1e, 0xfa};
561 if (!memcmp(p, endbr64, sizeof(endbr64)))
562 n += sizeof(endbr64);
563 /* Skip bnd prefix */
566 /* jmp with 4-byte displacement */
567 if (p[n] == 0xff && p[n + 1] == 0x25) {
569 /* Also add offset from start of entry to end of instruction */
570 return n + 4 + le32toh(*(const u32 *)(p + n));
575 static bool get_plt_got_name(GElf_Shdr *shdr, size_t i,
576 struct rela_dyn_info *di,
577 char *buf, size_t buf_sz)
579 struct rela_dyn vi, *vr;
580 const char *sym_name;
588 disp = get_x86_64_plt_disp(di->plt_got_data->d_buf + i);
592 /* Compute target offset of the .plt.got entry */
593 vi.offset = shdr->sh_offset + di->plt_got_data->d_off + i + disp;
595 /* Find that offset in .rela.dyn (sorted by offset) */
596 vr = bsearch(&vi, di->sorted, di->nr_entries, sizeof(di->sorted[0]), cmp_offset);
600 /* Get the associated symbol */
601 gelf_getsym(di->dynsym_data, vr->sym_idx, &sym);
602 sym_name = elf_sym__name(&sym, di->dynstr_data);
603 demangled = demangle_sym(di->dso, 0, sym_name);
604 if (demangled != NULL)
605 sym_name = demangled;
607 snprintf(buf, buf_sz, "%s@plt", sym_name);
614 static int dso__synthesize_plt_got_symbols(struct dso *dso, Elf *elf,
616 char *buf, size_t buf_sz)
618 struct rela_dyn_info di = { .dso = dso };
625 scn = elf_section_by_name(elf, ehdr, &shdr, ".plt.got", NULL);
626 if (!scn || !shdr.sh_entsize)
629 if (ehdr->e_machine == EM_X86_64)
630 get_rela_dyn_info(elf, ehdr, &di, scn);
632 for (i = 0; i < shdr.sh_size; i += shdr.sh_entsize) {
633 if (!get_plt_got_name(&shdr, i, &di, buf, buf_sz))
634 snprintf(buf, buf_sz, "offset_%#" PRIx64 "@plt", (u64)shdr.sh_offset + i);
635 sym = symbol__new(shdr.sh_offset + i, shdr.sh_entsize, STB_GLOBAL, STT_FUNC, buf);
638 symbols__insert(&dso->symbols, sym);
647 * We need to check if we have a .dynsym, so that we can handle the
648 * .plt, synthesizing its symbols, that aren't on the symtabs (be it
649 * .dynsym or .symtab).
650 * And always look at the original dso, not at debuginfo packages, that
651 * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
653 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss)
657 u64 plt_offset, plt_header_size, plt_entry_size;
658 GElf_Shdr shdr_plt, plt_sec_shdr;
659 struct symbol *f, *plt_sym;
660 GElf_Shdr shdr_rel_plt, shdr_dynsym;
661 Elf_Data *syms, *symstrs;
662 Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
664 char sympltname[1024];
666 int nr = 0, err = -1;
667 struct rel_info ri = { .is_rela = false };
673 if (!elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL))
677 * A symbol from a previous section (e.g. .init) can have been expanded
678 * by symbols__fixup_end() to overlap .plt. Truncate it before adding
679 * a symbol for .plt header.
681 f = dso__find_symbol_nocache(dso, shdr_plt.sh_offset);
682 if (f && f->start < shdr_plt.sh_offset && f->end > shdr_plt.sh_offset)
683 f->end = shdr_plt.sh_offset;
685 if (!get_plt_sizes(dso, &ehdr, &shdr_plt, &plt_header_size, &plt_entry_size))
688 /* Add a symbol for .plt header */
689 plt_sym = symbol__new(shdr_plt.sh_offset, plt_header_size, STB_GLOBAL, STT_FUNC, ".plt");
692 symbols__insert(&dso->symbols, plt_sym);
694 /* Only x86 has .plt.got */
695 if (machine_is_x86(ehdr.e_machine) &&
696 dso__synthesize_plt_got_symbols(dso, elf, &ehdr, sympltname, sizeof(sympltname)))
699 /* Only x86 has .plt.sec */
700 if (machine_is_x86(ehdr.e_machine) &&
701 elf_section_by_name(elf, &ehdr, &plt_sec_shdr, ".plt.sec", NULL)) {
702 if (!get_plt_sizes(dso, &ehdr, &plt_sec_shdr, &plt_header_size, &plt_entry_size))
704 /* Extend .plt symbol to entire .plt */
705 plt_sym->end = plt_sym->start + shdr_plt.sh_size;
706 /* Use .plt.sec offset */
707 plt_offset = plt_sec_shdr.sh_offset;
710 plt_offset = shdr_plt.sh_offset;
714 scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
716 if (scn_plt_rel == NULL) {
717 scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
719 if (scn_plt_rel == NULL)
723 if (shdr_rel_plt.sh_type != SHT_RELA &&
724 shdr_rel_plt.sh_type != SHT_REL)
727 if (!shdr_rel_plt.sh_link)
730 if (shdr_rel_plt.sh_link == ss->dynsym_idx) {
731 scn_dynsym = ss->dynsym;
732 shdr_dynsym = ss->dynshdr;
733 } else if (shdr_rel_plt.sh_link == ss->symtab_idx) {
735 * A static executable can have a .plt due to IFUNCs, in which
736 * case .symtab is used not .dynsym.
738 scn_dynsym = ss->symtab;
739 shdr_dynsym = ss->symshdr;
748 * Fetch the relocation section to find the idxes to the GOT
749 * and the symbols in the .dynsym they refer to.
751 ri.reldata = elf_getdata(scn_plt_rel, NULL);
755 syms = elf_getdata(scn_dynsym, NULL);
759 scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
760 if (scn_symstrs == NULL)
763 symstrs = elf_getdata(scn_symstrs, NULL);
767 if (symstrs->d_size == 0)
770 ri.nr_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
772 ri.is_rela = shdr_rel_plt.sh_type == SHT_RELA;
776 * Assume a .plt with the same number of entries as the number
777 * of relocation entries is not lazy and does not have a header.
779 if (ri.nr_entries * plt_entry_size == shdr_plt.sh_size)
780 dso__delete_symbol(dso, plt_sym);
782 plt_offset += plt_header_size;
786 * x86 doesn't insert IFUNC relocations in .plt order, so sort to get
789 if (machine_is_x86(ehdr.e_machine) && sort_rel(&ri))
792 for (idx = 0; idx < ri.nr_entries; idx++) {
793 const char *elf_name = NULL;
794 char *demangled = NULL;
796 gelf_getsym(syms, get_rel_symidx(&ri, idx), &sym);
798 elf_name = elf_sym__name(&sym, symstrs);
799 demangled = demangle_sym(dso, 0, elf_name);
801 elf_name = demangled;
803 snprintf(sympltname, sizeof(sympltname), "%s@plt", elf_name);
804 else if (!get_ifunc_name(elf, dso, &ehdr, &ri, sympltname, sizeof(sympltname)))
805 snprintf(sympltname, sizeof(sympltname),
806 "offset_%#" PRIx64 "@plt", plt_offset);
809 f = symbol__new(plt_offset, plt_entry_size, STB_GLOBAL, STT_FUNC, sympltname);
813 plt_offset += plt_entry_size;
814 symbols__insert(&dso->symbols, f);
823 pr_debug("%s: problems reading %s PLT info.\n",
824 __func__, dso->long_name);
828 char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
830 return demangle_sym(dso, kmodule, elf_name);
834 * Align offset to 4 bytes as needed for note name and descriptor data.
836 #define NOTE_ALIGN(n) (((n) + 3) & -4U)
838 static int elf_read_build_id(Elf *elf, void *bf, size_t size)
848 if (size < BUILD_ID_SIZE)
855 if (gelf_getehdr(elf, &ehdr) == NULL) {
856 pr_err("%s: cannot get elf header.\n", __func__);
861 * Check following sections for notes:
862 * '.note.gnu.build-id'
864 * '.note' (VDSO specific)
867 sec = elf_section_by_name(elf, &ehdr, &shdr,
868 ".note.gnu.build-id", NULL);
872 sec = elf_section_by_name(elf, &ehdr, &shdr,
877 sec = elf_section_by_name(elf, &ehdr, &shdr,
886 data = elf_getdata(sec, NULL);
891 while (ptr < (data->d_buf + data->d_size)) {
892 GElf_Nhdr *nhdr = ptr;
893 size_t namesz = NOTE_ALIGN(nhdr->n_namesz),
894 descsz = NOTE_ALIGN(nhdr->n_descsz);
897 ptr += sizeof(*nhdr);
900 if (nhdr->n_type == NT_GNU_BUILD_ID &&
901 nhdr->n_namesz == sizeof("GNU")) {
902 if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
903 size_t sz = min(size, descsz);
905 memset(bf + sz, 0, size - sz);
917 #ifdef HAVE_LIBBFD_BUILDID_SUPPORT
919 static int read_build_id(const char *filename, struct build_id *bid)
921 size_t size = sizeof(bid->data);
925 abfd = bfd_openr(filename, NULL);
929 if (!bfd_check_format(abfd, bfd_object)) {
930 pr_debug2("%s: cannot read %s bfd file.\n", __func__, filename);
934 if (!abfd->build_id || abfd->build_id->size > size)
937 memcpy(bid->data, abfd->build_id->data, abfd->build_id->size);
938 memset(bid->data + abfd->build_id->size, 0, size - abfd->build_id->size);
939 err = bid->size = abfd->build_id->size;
946 #else // HAVE_LIBBFD_BUILDID_SUPPORT
948 static int read_build_id(const char *filename, struct build_id *bid)
950 size_t size = sizeof(bid->data);
954 if (size < BUILD_ID_SIZE)
957 fd = open(filename, O_RDONLY);
961 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
963 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
967 err = elf_read_build_id(elf, bid->data, size);
978 #endif // HAVE_LIBBFD_BUILDID_SUPPORT
980 int filename__read_build_id(const char *filename, struct build_id *bid)
982 struct kmod_path m = { .name = NULL, };
989 err = kmod_path__parse(&m, filename);
996 fd = filename__decompress(filename, path, sizeof(path), m.comp, &error);
998 pr_debug("Failed to decompress (error %d) %s\n",
1006 err = read_build_id(filename, bid);
1013 int sysfs__read_build_id(const char *filename, struct build_id *bid)
1015 size_t size = sizeof(bid->data);
1018 fd = open(filename, O_RDONLY);
1025 size_t namesz, descsz;
1027 if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
1030 namesz = NOTE_ALIGN(nhdr.n_namesz);
1031 descsz = NOTE_ALIGN(nhdr.n_descsz);
1032 if (nhdr.n_type == NT_GNU_BUILD_ID &&
1033 nhdr.n_namesz == sizeof("GNU")) {
1034 if (read(fd, bf, namesz) != (ssize_t)namesz)
1036 if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
1037 size_t sz = min(descsz, size);
1038 if (read(fd, bid->data, sz) == (ssize_t)sz) {
1039 memset(bid->data + sz, 0, size - sz);
1044 } else if (read(fd, bf, descsz) != (ssize_t)descsz)
1047 int n = namesz + descsz;
1049 if (n > (int)sizeof(bf)) {
1051 pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
1052 __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
1054 if (read(fd, bf, n) != n)
1063 #ifdef HAVE_LIBBFD_SUPPORT
1065 int filename__read_debuglink(const char *filename, char *debuglink,
1072 abfd = bfd_openr(filename, NULL);
1076 if (!bfd_check_format(abfd, bfd_object)) {
1077 pr_debug2("%s: cannot read %s bfd file.\n", __func__, filename);
1081 section = bfd_get_section_by_name(abfd, ".gnu_debuglink");
1085 if (section->size > size)
1088 if (!bfd_get_section_contents(abfd, section, debuglink, 0,
1101 int filename__read_debuglink(const char *filename, char *debuglink,
1112 fd = open(filename, O_RDONLY);
1116 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1118 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
1123 if (ek != ELF_K_ELF)
1126 if (gelf_getehdr(elf, &ehdr) == NULL) {
1127 pr_err("%s: cannot get elf header.\n", __func__);
1131 sec = elf_section_by_name(elf, &ehdr, &shdr,
1132 ".gnu_debuglink", NULL);
1136 data = elf_getdata(sec, NULL);
1140 /* the start of this section is a zero-terminated string */
1141 strncpy(debuglink, data->d_buf, size);
1155 static int dso__swap_init(struct dso *dso, unsigned char eidata)
1157 static unsigned int const endian = 1;
1159 dso->needs_swap = DSO_SWAP__NO;
1163 /* We are big endian, DSO is little endian. */
1164 if (*(unsigned char const *)&endian != 1)
1165 dso->needs_swap = DSO_SWAP__YES;
1169 /* We are little endian, DSO is big endian. */
1170 if (*(unsigned char const *)&endian != 0)
1171 dso->needs_swap = DSO_SWAP__YES;
1175 pr_err("unrecognized DSO data encoding %d\n", eidata);
1182 bool symsrc__possibly_runtime(struct symsrc *ss)
1184 return ss->dynsym || ss->opdsec;
1187 bool symsrc__has_symtab(struct symsrc *ss)
1189 return ss->symtab != NULL;
1192 void symsrc__destroy(struct symsrc *ss)
1199 bool elf__needs_adjust_symbols(GElf_Ehdr ehdr)
1202 * Usually vmlinux is an ELF file with type ET_EXEC for most
1203 * architectures; except Arm64 kernel is linked with option
1204 * '-share', so need to check type ET_DYN.
1206 return ehdr.e_type == ET_EXEC || ehdr.e_type == ET_REL ||
1207 ehdr.e_type == ET_DYN;
1210 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
1211 enum dso_binary_type type)
1217 if (dso__needs_decompress(dso)) {
1218 fd = dso__decompress_kmodule_fd(dso, name);
1222 type = dso->symtab_type;
1224 fd = open(name, O_RDONLY);
1226 dso->load_errno = errno;
1231 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1233 pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1234 dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
1238 if (gelf_getehdr(elf, &ehdr) == NULL) {
1239 dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
1240 pr_debug("%s: cannot get elf header.\n", __func__);
1244 if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
1245 dso->load_errno = DSO_LOAD_ERRNO__INTERNAL_ERROR;
1249 /* Always reject images with a mismatched build-id: */
1250 if (dso->has_build_id && !symbol_conf.ignore_vmlinux_buildid) {
1251 u8 build_id[BUILD_ID_SIZE];
1252 struct build_id bid;
1255 size = elf_read_build_id(elf, build_id, BUILD_ID_SIZE);
1257 dso->load_errno = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
1261 build_id__init(&bid, build_id, size);
1262 if (!dso__build_id_equal(dso, &bid)) {
1263 pr_debug("%s: build id mismatch for %s.\n", __func__, name);
1264 dso->load_errno = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
1269 ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1272 ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
1274 if (ss->symshdr.sh_type != SHT_SYMTAB)
1278 ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
1280 if (ss->dynshdr.sh_type != SHT_DYNSYM)
1284 ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
1286 if (ss->opdshdr.sh_type != SHT_PROGBITS)
1289 if (dso->kernel == DSO_SPACE__USER)
1290 ss->adjust_symbols = true;
1292 ss->adjust_symbols = elf__needs_adjust_symbols(ehdr);
1294 ss->name = strdup(name);
1296 dso->load_errno = errno;
1315 * ref_reloc_sym_not_found - has kernel relocation symbol been found.
1316 * @kmap: kernel maps and relocation reference symbol
1318 * This function returns %true if we are dealing with the kernel maps and the
1319 * relocation reference symbol has not yet been found. Otherwise %false is
1322 static bool ref_reloc_sym_not_found(struct kmap *kmap)
1324 return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
1325 !kmap->ref_reloc_sym->unrelocated_addr;
1329 * ref_reloc - kernel relocation offset.
1330 * @kmap: kernel maps and relocation reference symbol
1332 * This function returns the offset of kernel addresses as determined by using
1333 * the relocation reference symbol i.e. if the kernel has not been relocated
1334 * then the return value is zero.
1336 static u64 ref_reloc(struct kmap *kmap)
1338 if (kmap && kmap->ref_reloc_sym &&
1339 kmap->ref_reloc_sym->unrelocated_addr)
1340 return kmap->ref_reloc_sym->addr -
1341 kmap->ref_reloc_sym->unrelocated_addr;
1345 void __weak arch__sym_update(struct symbol *s __maybe_unused,
1346 GElf_Sym *sym __maybe_unused) { }
1348 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
1349 GElf_Sym *sym, GElf_Shdr *shdr,
1350 struct maps *kmaps, struct kmap *kmap,
1351 struct dso **curr_dsop, struct map **curr_mapp,
1352 const char *section_name,
1353 bool adjust_kernel_syms, bool kmodule, bool *remap_kernel)
1355 struct dso *curr_dso = *curr_dsop;
1356 struct map *curr_map;
1357 char dso_name[PATH_MAX];
1359 /* Adjust symbol to map to file offset */
1360 if (adjust_kernel_syms)
1361 sym->st_value -= shdr->sh_addr - shdr->sh_offset;
1363 if (strcmp(section_name, (curr_dso->short_name + dso->short_name_len)) == 0)
1366 if (strcmp(section_name, ".text") == 0) {
1368 * The initial kernel mapping is based on
1369 * kallsyms and identity maps. Overwrite it to
1370 * map to the kernel dso.
1372 if (*remap_kernel && dso->kernel && !kmodule) {
1373 *remap_kernel = false;
1374 map->start = shdr->sh_addr + ref_reloc(kmap);
1375 map->end = map->start + shdr->sh_size;
1376 map->pgoff = shdr->sh_offset;
1377 map->map_ip = map__map_ip;
1378 map->unmap_ip = map__unmap_ip;
1379 /* Ensure maps are correctly ordered */
1382 maps__remove(kmaps, map);
1383 maps__insert(kmaps, map);
1389 * The initial module mapping is based on
1390 * /proc/modules mapped to offset zero.
1391 * Overwrite it to map to the module dso.
1393 if (*remap_kernel && kmodule) {
1394 *remap_kernel = false;
1395 map->pgoff = shdr->sh_offset;
1406 snprintf(dso_name, sizeof(dso_name), "%s%s", dso->short_name, section_name);
1408 curr_map = maps__find_by_name(kmaps, dso_name);
1409 if (curr_map == NULL) {
1410 u64 start = sym->st_value;
1413 start += map->start + shdr->sh_offset;
1415 curr_dso = dso__new(dso_name);
1416 if (curr_dso == NULL)
1418 curr_dso->kernel = dso->kernel;
1419 curr_dso->long_name = dso->long_name;
1420 curr_dso->long_name_len = dso->long_name_len;
1421 curr_map = map__new2(start, curr_dso);
1423 if (curr_map == NULL)
1426 if (curr_dso->kernel)
1427 map__kmap(curr_map)->kmaps = kmaps;
1429 if (adjust_kernel_syms) {
1430 curr_map->start = shdr->sh_addr + ref_reloc(kmap);
1431 curr_map->end = curr_map->start + shdr->sh_size;
1432 curr_map->pgoff = shdr->sh_offset;
1434 curr_map->map_ip = curr_map->unmap_ip = identity__map_ip;
1436 curr_dso->symtab_type = dso->symtab_type;
1437 maps__insert(kmaps, curr_map);
1439 * Add it before we drop the reference to curr_map, i.e. while
1440 * we still are sure to have a reference to this DSO via
1443 dsos__add(&kmaps->machine->dsos, curr_dso);
1444 /* kmaps already got it */
1446 dso__set_loaded(curr_dso);
1447 *curr_mapp = curr_map;
1448 *curr_dsop = curr_dso;
1450 *curr_dsop = curr_map->dso;
1456 dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1457 struct symsrc *runtime_ss, int kmodule, int dynsym)
1459 struct kmap *kmap = dso->kernel ? map__kmap(map) : NULL;
1460 struct maps *kmaps = kmap ? map__kmaps(map) : NULL;
1461 struct map *curr_map = map;
1462 struct dso *curr_dso = dso;
1463 Elf_Data *symstrs, *secstrs, *secstrs_run, *secstrs_sym;
1470 Elf_Data *syms, *opddata = NULL;
1472 Elf_Scn *sec, *sec_strndx;
1475 bool remap_kernel = false, adjust_kernel_syms = false;
1481 ehdr = syms_ss->ehdr;
1483 sec = syms_ss->dynsym;
1484 shdr = syms_ss->dynshdr;
1486 sec = syms_ss->symtab;
1487 shdr = syms_ss->symshdr;
1490 if (elf_section_by_name(runtime_ss->elf, &runtime_ss->ehdr, &tshdr,
1492 dso->text_offset = tshdr.sh_addr - tshdr.sh_offset;
1494 if (runtime_ss->opdsec)
1495 opddata = elf_rawdata(runtime_ss->opdsec, NULL);
1497 syms = elf_getdata(sec, NULL);
1501 sec = elf_getscn(elf, shdr.sh_link);
1505 symstrs = elf_getdata(sec, NULL);
1506 if (symstrs == NULL)
1509 sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
1510 if (sec_strndx == NULL)
1513 secstrs_run = elf_getdata(sec_strndx, NULL);
1514 if (secstrs_run == NULL)
1517 sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
1518 if (sec_strndx == NULL)
1521 secstrs_sym = elf_getdata(sec_strndx, NULL);
1522 if (secstrs_sym == NULL)
1525 nr_syms = shdr.sh_size / shdr.sh_entsize;
1527 memset(&sym, 0, sizeof(sym));
1530 * The kernel relocation symbol is needed in advance in order to adjust
1531 * kernel maps correctly.
1533 if (ref_reloc_sym_not_found(kmap)) {
1534 elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1535 const char *elf_name = elf_sym__name(&sym, symstrs);
1537 if (strcmp(elf_name, kmap->ref_reloc_sym->name))
1539 kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
1540 map->reloc = kmap->ref_reloc_sym->addr -
1541 kmap->ref_reloc_sym->unrelocated_addr;
1547 * Handle any relocation of vdso necessary because older kernels
1548 * attempted to prelink vdso to its virtual address.
1550 if (dso__is_vdso(dso))
1551 map->reloc = map->start - dso->text_offset;
1553 dso->adjust_symbols = runtime_ss->adjust_symbols || ref_reloc(kmap);
1555 * Initial kernel and module mappings do not map to the dso.
1559 remap_kernel = true;
1560 adjust_kernel_syms = dso->adjust_symbols;
1562 elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1564 const char *elf_name = elf_sym__name(&sym, symstrs);
1565 char *demangled = NULL;
1566 int is_label = elf_sym__is_label(&sym);
1567 const char *section_name;
1568 bool used_opd = false;
1570 if (!is_label && !elf_sym__filter(&sym))
1573 /* Reject ARM ELF "mapping symbols": these aren't unique and
1574 * don't identify functions, so will confuse the profile
1576 if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
1577 if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
1578 && (elf_name[2] == '\0' || elf_name[2] == '.'))
1582 if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
1583 u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
1584 u64 *opd = opddata->d_buf + offset;
1585 sym.st_value = DSO__SWAP(dso, u64, *opd);
1586 sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
1592 * When loading symbols in a data mapping, ABS symbols (which
1593 * has a value of SHN_ABS in its st_shndx) failed at
1594 * elf_getscn(). And it marks the loading as a failure so
1595 * already loaded symbols cannot be fixed up.
1597 * I'm not sure what should be done. Just ignore them for now.
1600 if (sym.st_shndx == SHN_ABS)
1603 sec = elf_getscn(syms_ss->elf, sym.st_shndx);
1607 gelf_getshdr(sec, &shdr);
1610 * If the attribute bit SHF_ALLOC is not set, the section
1611 * doesn't occupy memory during process execution.
1612 * E.g. ".gnu.warning.*" section is used by linker to generate
1613 * warnings when calling deprecated functions, the symbols in
1614 * the section aren't loaded to memory during process execution,
1617 if (!(shdr.sh_flags & SHF_ALLOC))
1620 secstrs = secstrs_sym;
1623 * We have to fallback to runtime when syms' section header has
1624 * NOBITS set. NOBITS results in file offset (sh_offset) not
1625 * being incremented. So sh_offset used below has different
1626 * values for syms (invalid) and runtime (valid).
1628 if (shdr.sh_type == SHT_NOBITS) {
1629 sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
1633 gelf_getshdr(sec, &shdr);
1634 secstrs = secstrs_run;
1637 if (is_label && !elf_sec__filter(&shdr, secstrs))
1640 section_name = elf_sec__name(&shdr, secstrs);
1642 /* On ARM, symbols for thumb functions have 1 added to
1643 * the symbol address as a flag - remove it */
1644 if ((ehdr.e_machine == EM_ARM) &&
1645 (GELF_ST_TYPE(sym.st_info) == STT_FUNC) &&
1650 if (dso__process_kernel_symbol(dso, map, &sym, &shdr, kmaps, kmap, &curr_dso, &curr_map,
1651 section_name, adjust_kernel_syms, kmodule, &remap_kernel))
1653 } else if ((used_opd && runtime_ss->adjust_symbols) ||
1654 (!used_opd && syms_ss->adjust_symbols)) {
1657 if (elf_read_program_header(runtime_ss->elf,
1658 (u64)sym.st_value, &phdr)) {
1659 pr_debug4("%s: failed to find program header for "
1660 "symbol: %s st_value: %#" PRIx64 "\n",
1661 __func__, elf_name, (u64)sym.st_value);
1662 pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1663 "sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n",
1664 __func__, (u64)sym.st_value, (u64)shdr.sh_addr,
1665 (u64)shdr.sh_offset);
1667 * Fail to find program header, let's rollback
1668 * to use shdr.sh_addr and shdr.sh_offset to
1669 * calibrate symbol's file address, though this
1670 * is not necessary for normal C ELF file, we
1671 * still need to handle java JIT symbols in this
1674 sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1676 pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1677 "p_vaddr: %#" PRIx64 " p_offset: %#" PRIx64 "\n",
1678 __func__, (u64)sym.st_value, (u64)phdr.p_vaddr,
1679 (u64)phdr.p_offset);
1680 sym.st_value -= phdr.p_vaddr - phdr.p_offset;
1684 demangled = demangle_sym(dso, kmodule, elf_name);
1685 if (demangled != NULL)
1686 elf_name = demangled;
1688 f = symbol__new(sym.st_value, sym.st_size,
1689 GELF_ST_BIND(sym.st_info),
1690 GELF_ST_TYPE(sym.st_info), elf_name);
1695 arch__sym_update(f, &sym);
1697 __symbols__insert(&curr_dso->symbols, f, dso->kernel);
1702 * For misannotated, zeroed, ASM function sizes.
1705 symbols__fixup_end(&dso->symbols, false);
1706 symbols__fixup_duplicate(&dso->symbols);
1709 * We need to fixup this here too because we create new
1710 * maps here, for things like vsyscall sections.
1712 maps__fixup_end(kmaps);
1720 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1721 struct symsrc *runtime_ss, int kmodule)
1726 dso->symtab_type = syms_ss->type;
1727 dso->is_64_bit = syms_ss->is_64_bit;
1728 dso->rel = syms_ss->ehdr.e_type == ET_REL;
1731 * Modules may already have symbols from kallsyms, but those symbols
1732 * have the wrong values for the dso maps, so remove them.
1734 if (kmodule && syms_ss->symtab)
1735 symbols__delete(&dso->symbols);
1737 if (!syms_ss->symtab) {
1739 * If the vmlinux is stripped, fail so we will fall back
1740 * to using kallsyms. The vmlinux runtime symbols aren't
1746 err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1753 if (syms_ss->dynsym) {
1754 err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1764 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1771 if (elf_getphdrnum(elf, &phdrnum))
1774 for (i = 0; i < phdrnum; i++) {
1775 if (gelf_getphdr(elf, i, &phdr) == NULL)
1777 if (phdr.p_type != PT_LOAD)
1780 if (!(phdr.p_flags & PF_X))
1783 if (!(phdr.p_flags & PF_R))
1786 sz = min(phdr.p_memsz, phdr.p_filesz);
1789 err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1796 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1802 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1807 *is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1809 err = elf_read_maps(elf, exe, mapfn, data);
1815 enum dso_type dso__type_fd(int fd)
1817 enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1822 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1827 if (ek != ELF_K_ELF)
1830 if (gelf_getclass(elf) == ELFCLASS64) {
1831 dso_type = DSO__TYPE_64BIT;
1835 if (gelf_getehdr(elf, &ehdr) == NULL)
1838 if (ehdr.e_machine == EM_X86_64)
1839 dso_type = DSO__TYPE_X32BIT;
1841 dso_type = DSO__TYPE_32BIT;
1848 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1853 char *buf = malloc(page_size);
1858 if (lseek(to, to_offs, SEEK_SET) != to_offs)
1861 if (lseek(from, from_offs, SEEK_SET) != from_offs)
1868 /* Use read because mmap won't work on proc files */
1869 r = read(from, buf, n);
1875 r = write(to, buf, n);
1896 static int kcore__open(struct kcore *kcore, const char *filename)
1900 kcore->fd = open(filename, O_RDONLY);
1901 if (kcore->fd == -1)
1904 kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1908 kcore->elfclass = gelf_getclass(kcore->elf);
1909 if (kcore->elfclass == ELFCLASSNONE)
1912 ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1919 elf_end(kcore->elf);
1925 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1928 kcore->elfclass = elfclass;
1931 kcore->fd = mkstemp(filename);
1933 kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0400);
1934 if (kcore->fd == -1)
1937 kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1941 if (!gelf_newehdr(kcore->elf, elfclass))
1944 memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
1949 elf_end(kcore->elf);
1956 static void kcore__close(struct kcore *kcore)
1958 elf_end(kcore->elf);
1962 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
1964 GElf_Ehdr *ehdr = &to->ehdr;
1965 GElf_Ehdr *kehdr = &from->ehdr;
1967 memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
1968 ehdr->e_type = kehdr->e_type;
1969 ehdr->e_machine = kehdr->e_machine;
1970 ehdr->e_version = kehdr->e_version;
1973 ehdr->e_flags = kehdr->e_flags;
1974 ehdr->e_phnum = count;
1975 ehdr->e_shentsize = 0;
1977 ehdr->e_shstrndx = 0;
1979 if (from->elfclass == ELFCLASS32) {
1980 ehdr->e_phoff = sizeof(Elf32_Ehdr);
1981 ehdr->e_ehsize = sizeof(Elf32_Ehdr);
1982 ehdr->e_phentsize = sizeof(Elf32_Phdr);
1984 ehdr->e_phoff = sizeof(Elf64_Ehdr);
1985 ehdr->e_ehsize = sizeof(Elf64_Ehdr);
1986 ehdr->e_phentsize = sizeof(Elf64_Phdr);
1989 if (!gelf_update_ehdr(to->elf, ehdr))
1992 if (!gelf_newphdr(to->elf, count))
1998 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
2003 .p_flags = PF_R | PF_W | PF_X,
2009 .p_align = page_size,
2012 if (!gelf_update_phdr(kcore->elf, idx, &phdr))
2018 static off_t kcore__write(struct kcore *kcore)
2020 return elf_update(kcore->elf, ELF_C_WRITE);
2028 struct list_head node;
2029 struct phdr_data *remaps;
2034 struct list_head node;
2037 struct kcore_copy_info {
2043 u64 first_module_symbol;
2044 u64 last_module_symbol;
2046 struct list_head phdrs;
2047 struct list_head syms;
2050 #define kcore_copy__for_each_phdr(k, p) \
2051 list_for_each_entry((p), &(k)->phdrs, node)
2053 static struct phdr_data *phdr_data__new(u64 addr, u64 len, off_t offset)
2055 struct phdr_data *p = zalloc(sizeof(*p));
2066 static struct phdr_data *kcore_copy_info__addnew(struct kcore_copy_info *kci,
2070 struct phdr_data *p = phdr_data__new(addr, len, offset);
2073 list_add_tail(&p->node, &kci->phdrs);
2078 static void kcore_copy__free_phdrs(struct kcore_copy_info *kci)
2080 struct phdr_data *p, *tmp;
2082 list_for_each_entry_safe(p, tmp, &kci->phdrs, node) {
2083 list_del_init(&p->node);
2088 static struct sym_data *kcore_copy__new_sym(struct kcore_copy_info *kci,
2091 struct sym_data *s = zalloc(sizeof(*s));
2095 list_add_tail(&s->node, &kci->syms);
2101 static void kcore_copy__free_syms(struct kcore_copy_info *kci)
2103 struct sym_data *s, *tmp;
2105 list_for_each_entry_safe(s, tmp, &kci->syms, node) {
2106 list_del_init(&s->node);
2111 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
2114 struct kcore_copy_info *kci = arg;
2116 if (!kallsyms__is_function(type))
2119 if (strchr(name, '[')) {
2120 if (!kci->first_module_symbol || start < kci->first_module_symbol)
2121 kci->first_module_symbol = start;
2122 if (start > kci->last_module_symbol)
2123 kci->last_module_symbol = start;
2127 if (!kci->first_symbol || start < kci->first_symbol)
2128 kci->first_symbol = start;
2130 if (!kci->last_symbol || start > kci->last_symbol)
2131 kci->last_symbol = start;
2133 if (!strcmp(name, "_stext")) {
2138 if (!strcmp(name, "_etext")) {
2143 if (is_entry_trampoline(name) && !kcore_copy__new_sym(kci, start))
2149 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
2152 char kallsyms_filename[PATH_MAX];
2154 scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
2156 if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
2159 if (kallsyms__parse(kallsyms_filename, kci,
2160 kcore_copy__process_kallsyms) < 0)
2166 static int kcore_copy__process_modules(void *arg,
2167 const char *name __maybe_unused,
2168 u64 start, u64 size __maybe_unused)
2170 struct kcore_copy_info *kci = arg;
2172 if (!kci->first_module || start < kci->first_module)
2173 kci->first_module = start;
2178 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
2181 char modules_filename[PATH_MAX];
2183 scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
2185 if (symbol__restricted_filename(modules_filename, "/proc/modules"))
2188 if (modules__parse(modules_filename, kci,
2189 kcore_copy__process_modules) < 0)
2195 static int kcore_copy__map(struct kcore_copy_info *kci, u64 start, u64 end,
2196 u64 pgoff, u64 s, u64 e)
2200 if (s < start || s >= end)
2203 offset = (s - start) + pgoff;
2204 len = e < end ? e - s : end - s;
2206 return kcore_copy_info__addnew(kci, s, len, offset) ? 0 : -1;
2209 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
2211 struct kcore_copy_info *kci = data;
2212 u64 end = start + len;
2213 struct sym_data *sdat;
2215 if (kcore_copy__map(kci, start, end, pgoff, kci->stext, kci->etext))
2218 if (kcore_copy__map(kci, start, end, pgoff, kci->first_module,
2219 kci->last_module_symbol))
2222 list_for_each_entry(sdat, &kci->syms, node) {
2223 u64 s = round_down(sdat->addr, page_size);
2225 if (kcore_copy__map(kci, start, end, pgoff, s, s + len))
2232 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
2234 if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
2240 static void kcore_copy__find_remaps(struct kcore_copy_info *kci)
2242 struct phdr_data *p, *k = NULL;
2248 /* Find phdr that corresponds to the kernel map (contains stext) */
2249 kcore_copy__for_each_phdr(kci, p) {
2250 u64 pend = p->addr + p->len - 1;
2252 if (p->addr <= kci->stext && pend >= kci->stext) {
2261 kend = k->offset + k->len;
2263 /* Find phdrs that remap the kernel */
2264 kcore_copy__for_each_phdr(kci, p) {
2265 u64 pend = p->offset + p->len;
2270 if (p->offset >= k->offset && pend <= kend)
2275 static void kcore_copy__layout(struct kcore_copy_info *kci)
2277 struct phdr_data *p;
2280 kcore_copy__find_remaps(kci);
2282 kcore_copy__for_each_phdr(kci, p) {
2290 kcore_copy__for_each_phdr(kci, p) {
2291 struct phdr_data *k = p->remaps;
2294 p->rel = p->offset - k->offset + k->rel;
2298 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
2301 if (kcore_copy__parse_kallsyms(kci, dir))
2304 if (kcore_copy__parse_modules(kci, dir))
2308 kci->stext = round_down(kci->stext, page_size);
2310 kci->stext = round_down(kci->first_symbol, page_size);
2313 kci->etext = round_up(kci->etext, page_size);
2314 } else if (kci->last_symbol) {
2315 kci->etext = round_up(kci->last_symbol, page_size);
2316 kci->etext += page_size;
2319 if (kci->first_module_symbol &&
2320 (!kci->first_module || kci->first_module_symbol < kci->first_module))
2321 kci->first_module = kci->first_module_symbol;
2323 kci->first_module = round_down(kci->first_module, page_size);
2325 if (kci->last_module_symbol) {
2326 kci->last_module_symbol = round_up(kci->last_module_symbol,
2328 kci->last_module_symbol += page_size;
2331 if (!kci->stext || !kci->etext)
2334 if (kci->first_module && !kci->last_module_symbol)
2337 if (kcore_copy__read_maps(kci, elf))
2340 kcore_copy__layout(kci);
2345 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
2348 char from_filename[PATH_MAX];
2349 char to_filename[PATH_MAX];
2351 scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2352 scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2354 return copyfile_mode(from_filename, to_filename, 0400);
2357 static int kcore_copy__unlink(const char *dir, const char *name)
2359 char filename[PATH_MAX];
2361 scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
2363 return unlink(filename);
2366 static int kcore_copy__compare_fds(int from, int to)
2374 buf_from = malloc(page_size);
2375 buf_to = malloc(page_size);
2376 if (!buf_from || !buf_to)
2380 /* Use read because mmap won't work on proc files */
2381 ret = read(from, buf_from, page_size);
2390 if (readn(to, buf_to, len) != (int)len)
2393 if (memcmp(buf_from, buf_to, len))
2404 static int kcore_copy__compare_files(const char *from_filename,
2405 const char *to_filename)
2407 int from, to, err = -1;
2409 from = open(from_filename, O_RDONLY);
2413 to = open(to_filename, O_RDONLY);
2415 goto out_close_from;
2417 err = kcore_copy__compare_fds(from, to);
2425 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
2428 char from_filename[PATH_MAX];
2429 char to_filename[PATH_MAX];
2431 scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2432 scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2434 return kcore_copy__compare_files(from_filename, to_filename);
2438 * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
2439 * @from_dir: from directory
2440 * @to_dir: to directory
2442 * This function copies kallsyms, modules and kcore files from one directory to
2443 * another. kallsyms and modules are copied entirely. Only code segments are
2444 * copied from kcore. It is assumed that two segments suffice: one for the
2445 * kernel proper and one for all the modules. The code segments are determined
2446 * from kallsyms and modules files. The kernel map starts at _stext or the
2447 * lowest function symbol, and ends at _etext or the highest function symbol.
2448 * The module map starts at the lowest module address and ends at the highest
2449 * module symbol. Start addresses are rounded down to the nearest page. End
2450 * addresses are rounded up to the nearest page. An extra page is added to the
2451 * highest kernel symbol and highest module symbol to, hopefully, encompass that
2452 * symbol too. Because it contains only code sections, the resulting kcore is
2453 * unusual. One significant peculiarity is that the mapping (start -> pgoff)
2454 * is not the same for the kernel map and the modules map. That happens because
2455 * the data is copied adjacently whereas the original kcore has gaps. Finally,
2456 * kallsyms file is compared with its copy to check that modules have not been
2457 * loaded or unloaded while the copies were taking place.
2459 * Return: %0 on success, %-1 on failure.
2461 int kcore_copy(const char *from_dir, const char *to_dir)
2464 struct kcore extract;
2465 int idx = 0, err = -1;
2467 struct kcore_copy_info kci = { .stext = 0, };
2468 char kcore_filename[PATH_MAX];
2469 char extract_filename[PATH_MAX];
2470 struct phdr_data *p;
2472 INIT_LIST_HEAD(&kci.phdrs);
2473 INIT_LIST_HEAD(&kci.syms);
2475 if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
2478 if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
2479 goto out_unlink_kallsyms;
2481 scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
2482 scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
2484 if (kcore__open(&kcore, kcore_filename))
2485 goto out_unlink_modules;
2487 if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
2488 goto out_kcore_close;
2490 if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
2491 goto out_kcore_close;
2493 if (kcore__copy_hdr(&kcore, &extract, kci.phnum))
2494 goto out_extract_close;
2496 offset = gelf_fsize(extract.elf, ELF_T_EHDR, 1, EV_CURRENT) +
2497 gelf_fsize(extract.elf, ELF_T_PHDR, kci.phnum, EV_CURRENT);
2498 offset = round_up(offset, page_size);
2500 kcore_copy__for_each_phdr(&kci, p) {
2501 off_t offs = p->rel + offset;
2503 if (kcore__add_phdr(&extract, idx++, offs, p->addr, p->len))
2504 goto out_extract_close;
2507 sz = kcore__write(&extract);
2508 if (sz < 0 || sz > offset)
2509 goto out_extract_close;
2511 kcore_copy__for_each_phdr(&kci, p) {
2512 off_t offs = p->rel + offset;
2516 if (copy_bytes(kcore.fd, p->offset, extract.fd, offs, p->len))
2517 goto out_extract_close;
2520 if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
2521 goto out_extract_close;
2526 kcore__close(&extract);
2528 unlink(extract_filename);
2530 kcore__close(&kcore);
2533 kcore_copy__unlink(to_dir, "modules");
2534 out_unlink_kallsyms:
2536 kcore_copy__unlink(to_dir, "kallsyms");
2538 kcore_copy__free_phdrs(&kci);
2539 kcore_copy__free_syms(&kci);
2544 int kcore_extract__create(struct kcore_extract *kce)
2547 struct kcore extract;
2549 int idx = 0, err = -1;
2550 off_t offset = page_size, sz;
2552 if (kcore__open(&kcore, kce->kcore_filename))
2555 strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
2556 if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
2557 goto out_kcore_close;
2559 if (kcore__copy_hdr(&kcore, &extract, count))
2560 goto out_extract_close;
2562 if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
2563 goto out_extract_close;
2565 sz = kcore__write(&extract);
2566 if (sz < 0 || sz > offset)
2567 goto out_extract_close;
2569 if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
2570 goto out_extract_close;
2575 kcore__close(&extract);
2577 unlink(kce->extract_filename);
2579 kcore__close(&kcore);
2584 void kcore_extract__delete(struct kcore_extract *kce)
2586 unlink(kce->extract_filename);
2589 #ifdef HAVE_GELF_GETNOTE_SUPPORT
2591 static void sdt_adjust_loc(struct sdt_note *tmp, GElf_Addr base_off)
2597 tmp->addr.a32[SDT_NOTE_IDX_LOC] =
2598 tmp->addr.a32[SDT_NOTE_IDX_LOC] + base_off -
2599 tmp->addr.a32[SDT_NOTE_IDX_BASE];
2601 tmp->addr.a64[SDT_NOTE_IDX_LOC] =
2602 tmp->addr.a64[SDT_NOTE_IDX_LOC] + base_off -
2603 tmp->addr.a64[SDT_NOTE_IDX_BASE];
2606 static void sdt_adjust_refctr(struct sdt_note *tmp, GElf_Addr base_addr,
2612 if (tmp->bit32 && tmp->addr.a32[SDT_NOTE_IDX_REFCTR])
2613 tmp->addr.a32[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2614 else if (tmp->addr.a64[SDT_NOTE_IDX_REFCTR])
2615 tmp->addr.a64[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2619 * populate_sdt_note : Parse raw data and identify SDT note
2620 * @elf: elf of the opened file
2621 * @data: raw data of a section with description offset applied
2622 * @len: note description size
2623 * @type: type of the note
2624 * @sdt_notes: List to add the SDT note
2626 * Responsible for parsing the @data in section .note.stapsdt in @elf and
2627 * if its an SDT note, it appends to @sdt_notes list.
2629 static int populate_sdt_note(Elf **elf, const char *data, size_t len,
2630 struct list_head *sdt_notes)
2632 const char *provider, *name, *args;
2633 struct sdt_note *tmp = NULL;
2639 Elf64_Addr a64[NR_ADDR];
2640 Elf32_Addr a32[NR_ADDR];
2644 .d_buf = &buf, .d_type = ELF_T_ADDR, .d_version = EV_CURRENT,
2645 .d_size = gelf_fsize((*elf), ELF_T_ADDR, NR_ADDR, EV_CURRENT),
2646 .d_off = 0, .d_align = 0
2649 .d_buf = (void *) data, .d_type = ELF_T_ADDR,
2650 .d_version = EV_CURRENT, .d_size = dst.d_size, .d_off = 0,
2654 tmp = (struct sdt_note *)calloc(1, sizeof(struct sdt_note));
2660 INIT_LIST_HEAD(&tmp->note_list);
2662 if (len < dst.d_size + 3)
2665 /* Translation from file representation to memory representation */
2666 if (gelf_xlatetom(*elf, &dst, &src,
2667 elf_getident(*elf, NULL)[EI_DATA]) == NULL) {
2668 pr_err("gelf_xlatetom : %s\n", elf_errmsg(-1));
2672 /* Populate the fields of sdt_note */
2673 provider = data + dst.d_size;
2675 name = (const char *)memchr(provider, '\0', data + len - provider);
2679 tmp->provider = strdup(provider);
2680 if (!tmp->provider) {
2684 tmp->name = strdup(name);
2690 args = memchr(name, '\0', data + len - name);
2693 * There is no argument if:
2694 * - We reached the end of the note;
2695 * - There is not enough room to hold a potential string;
2696 * - The argument string is empty or just contains ':'.
2698 if (args == NULL || data + len - args < 2 ||
2699 args[1] == ':' || args[1] == '\0')
2702 tmp->args = strdup(++args);
2709 if (gelf_getclass(*elf) == ELFCLASS32) {
2710 memcpy(&tmp->addr, &buf, 3 * sizeof(Elf32_Addr));
2713 memcpy(&tmp->addr, &buf, 3 * sizeof(Elf64_Addr));
2717 if (!gelf_getehdr(*elf, &ehdr)) {
2718 pr_debug("%s : cannot get elf header.\n", __func__);
2723 /* Adjust the prelink effect :
2724 * Find out the .stapsdt.base section.
2725 * This scn will help us to handle prelinking (if present).
2726 * Compare the retrieved file offset of the base section with the
2727 * base address in the description of the SDT note. If its different,
2728 * then accordingly, adjust the note location.
2730 if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_BASE_SCN, NULL))
2731 sdt_adjust_loc(tmp, shdr.sh_offset);
2733 /* Adjust reference counter offset */
2734 if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_PROBES_SCN, NULL))
2735 sdt_adjust_refctr(tmp, shdr.sh_addr, shdr.sh_offset);
2737 list_add_tail(&tmp->note_list, sdt_notes);
2745 zfree(&tmp->provider);
2753 * construct_sdt_notes_list : constructs a list of SDT notes
2754 * @elf : elf to look into
2755 * @sdt_notes : empty list_head
2757 * Scans the sections in 'elf' for the section
2758 * .note.stapsdt. It, then calls populate_sdt_note to find
2759 * out the SDT events and populates the 'sdt_notes'.
2761 static int construct_sdt_notes_list(Elf *elf, struct list_head *sdt_notes)
2764 Elf_Scn *scn = NULL;
2767 size_t shstrndx, next;
2769 size_t name_off, desc_off, offset;
2772 if (gelf_getehdr(elf, &ehdr) == NULL) {
2776 if (elf_getshdrstrndx(elf, &shstrndx) != 0) {
2781 /* Look for the required section */
2782 scn = elf_section_by_name(elf, &ehdr, &shdr, SDT_NOTE_SCN, NULL);
2788 if ((shdr.sh_type != SHT_NOTE) || (shdr.sh_flags & SHF_ALLOC)) {
2793 data = elf_getdata(scn, NULL);
2795 /* Get the SDT notes */
2796 for (offset = 0; (next = gelf_getnote(data, offset, &nhdr, &name_off,
2797 &desc_off)) > 0; offset = next) {
2798 if (nhdr.n_namesz == sizeof(SDT_NOTE_NAME) &&
2799 !memcmp(data->d_buf + name_off, SDT_NOTE_NAME,
2800 sizeof(SDT_NOTE_NAME))) {
2801 /* Check the type of the note */
2802 if (nhdr.n_type != SDT_NOTE_TYPE)
2805 ret = populate_sdt_note(&elf, ((data->d_buf) + desc_off),
2806 nhdr.n_descsz, sdt_notes);
2811 if (list_empty(sdt_notes))
2819 * get_sdt_note_list : Wrapper to construct a list of sdt notes
2820 * @head : empty list_head
2821 * @target : file to find SDT notes from
2823 * This opens the file, initializes
2824 * the ELF and then calls construct_sdt_notes_list.
2826 int get_sdt_note_list(struct list_head *head, const char *target)
2831 fd = open(target, O_RDONLY);
2835 elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
2840 ret = construct_sdt_notes_list(elf, head);
2848 * cleanup_sdt_note_list : free the sdt notes' list
2849 * @sdt_notes: sdt notes' list
2851 * Free up the SDT notes in @sdt_notes.
2852 * Returns the number of SDT notes free'd.
2854 int cleanup_sdt_note_list(struct list_head *sdt_notes)
2856 struct sdt_note *tmp, *pos;
2859 list_for_each_entry_safe(pos, tmp, sdt_notes, note_list) {
2860 list_del_init(&pos->note_list);
2863 zfree(&pos->provider);
2871 * sdt_notes__get_count: Counts the number of sdt events
2872 * @start: list_head to sdt_notes list
2874 * Returns the number of SDT notes in a list
2876 int sdt_notes__get_count(struct list_head *start)
2878 struct sdt_note *sdt_ptr;
2881 list_for_each_entry(sdt_ptr, start, note_list)
2887 void symbol__elf_init(void)
2889 elf_version(EV_CURRENT);