GNU Linux-libre 4.19.245-gnu1
[releases.git] / tools / perf / util / symbol-elf.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <inttypes.h>
8
9 #include "symbol.h"
10 #include "demangle-java.h"
11 #include "demangle-rust.h"
12 #include "machine.h"
13 #include "vdso.h"
14 #include "debug.h"
15 #include "sane_ctype.h"
16 #include <symbol/kallsyms.h>
17
18 #ifndef EM_AARCH64
19 #define EM_AARCH64      183  /* ARM 64 bit */
20 #endif
21
22 typedef Elf64_Nhdr GElf_Nhdr;
23
24 #ifdef HAVE_CPLUS_DEMANGLE_SUPPORT
25 extern char *cplus_demangle(const char *, int);
26
27 static inline char *bfd_demangle(void __maybe_unused *v, const char *c, int i)
28 {
29         return cplus_demangle(c, i);
30 }
31 #else
32 #ifdef NO_DEMANGLE
33 static inline char *bfd_demangle(void __maybe_unused *v,
34                                  const char __maybe_unused *c,
35                                  int __maybe_unused i)
36 {
37         return NULL;
38 }
39 #else
40 #define PACKAGE 'perf'
41 #include <bfd.h>
42 #endif
43 #endif
44
45 #ifndef HAVE_ELF_GETPHDRNUM_SUPPORT
46 static int elf_getphdrnum(Elf *elf, size_t *dst)
47 {
48         GElf_Ehdr gehdr;
49         GElf_Ehdr *ehdr;
50
51         ehdr = gelf_getehdr(elf, &gehdr);
52         if (!ehdr)
53                 return -1;
54
55         *dst = ehdr->e_phnum;
56
57         return 0;
58 }
59 #endif
60
61 #ifndef HAVE_ELF_GETSHDRSTRNDX_SUPPORT
62 static int elf_getshdrstrndx(Elf *elf __maybe_unused, size_t *dst __maybe_unused)
63 {
64         pr_err("%s: update your libelf to > 0.140, this one lacks elf_getshdrstrndx().\n", __func__);
65         return -1;
66 }
67 #endif
68
69 #ifndef NT_GNU_BUILD_ID
70 #define NT_GNU_BUILD_ID 3
71 #endif
72
73 /**
74  * elf_symtab__for_each_symbol - iterate thru all the symbols
75  *
76  * @syms: struct elf_symtab instance to iterate
77  * @idx: uint32_t idx
78  * @sym: GElf_Sym iterator
79  */
80 #define elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) \
81         for (idx = 0, gelf_getsym(syms, idx, &sym);\
82              idx < nr_syms; \
83              idx++, gelf_getsym(syms, idx, &sym))
84
85 static inline uint8_t elf_sym__type(const GElf_Sym *sym)
86 {
87         return GELF_ST_TYPE(sym->st_info);
88 }
89
90 static inline uint8_t elf_sym__visibility(const GElf_Sym *sym)
91 {
92         return GELF_ST_VISIBILITY(sym->st_other);
93 }
94
95 #ifndef STT_GNU_IFUNC
96 #define STT_GNU_IFUNC 10
97 #endif
98
99 static inline int elf_sym__is_function(const GElf_Sym *sym)
100 {
101         return (elf_sym__type(sym) == STT_FUNC ||
102                 elf_sym__type(sym) == STT_GNU_IFUNC) &&
103                sym->st_name != 0 &&
104                sym->st_shndx != SHN_UNDEF;
105 }
106
107 static inline bool elf_sym__is_object(const GElf_Sym *sym)
108 {
109         return elf_sym__type(sym) == STT_OBJECT &&
110                 sym->st_name != 0 &&
111                 sym->st_shndx != SHN_UNDEF;
112 }
113
114 static inline int elf_sym__is_label(const GElf_Sym *sym)
115 {
116         return elf_sym__type(sym) == STT_NOTYPE &&
117                 sym->st_name != 0 &&
118                 sym->st_shndx != SHN_UNDEF &&
119                 sym->st_shndx != SHN_ABS &&
120                 elf_sym__visibility(sym) != STV_HIDDEN &&
121                 elf_sym__visibility(sym) != STV_INTERNAL;
122 }
123
124 static bool elf_sym__filter(GElf_Sym *sym)
125 {
126         return elf_sym__is_function(sym) || elf_sym__is_object(sym);
127 }
128
129 static inline const char *elf_sym__name(const GElf_Sym *sym,
130                                         const Elf_Data *symstrs)
131 {
132         return symstrs->d_buf + sym->st_name;
133 }
134
135 static inline const char *elf_sec__name(const GElf_Shdr *shdr,
136                                         const Elf_Data *secstrs)
137 {
138         return secstrs->d_buf + shdr->sh_name;
139 }
140
141 static inline int elf_sec__is_text(const GElf_Shdr *shdr,
142                                         const Elf_Data *secstrs)
143 {
144         return strstr(elf_sec__name(shdr, secstrs), "text") != NULL;
145 }
146
147 static inline bool elf_sec__is_data(const GElf_Shdr *shdr,
148                                     const Elf_Data *secstrs)
149 {
150         return strstr(elf_sec__name(shdr, secstrs), "data") != NULL;
151 }
152
153 static bool elf_sec__filter(GElf_Shdr *shdr, Elf_Data *secstrs)
154 {
155         return elf_sec__is_text(shdr, secstrs) || 
156                elf_sec__is_data(shdr, secstrs);
157 }
158
159 static size_t elf_addr_to_index(Elf *elf, GElf_Addr addr)
160 {
161         Elf_Scn *sec = NULL;
162         GElf_Shdr shdr;
163         size_t cnt = 1;
164
165         while ((sec = elf_nextscn(elf, sec)) != NULL) {
166                 gelf_getshdr(sec, &shdr);
167
168                 if ((addr >= shdr.sh_addr) &&
169                     (addr < (shdr.sh_addr + shdr.sh_size)))
170                         return cnt;
171
172                 ++cnt;
173         }
174
175         return -1;
176 }
177
178 Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
179                              GElf_Shdr *shp, const char *name, size_t *idx)
180 {
181         Elf_Scn *sec = NULL;
182         size_t cnt = 1;
183
184         /* Elf is corrupted/truncated, avoid calling elf_strptr. */
185         if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL))
186                 return NULL;
187
188         while ((sec = elf_nextscn(elf, sec)) != NULL) {
189                 char *str;
190
191                 gelf_getshdr(sec, shp);
192                 str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
193                 if (str && !strcmp(name, str)) {
194                         if (idx)
195                                 *idx = cnt;
196                         return sec;
197                 }
198                 ++cnt;
199         }
200
201         return NULL;
202 }
203
204 static bool want_demangle(bool is_kernel_sym)
205 {
206         return is_kernel_sym ? symbol_conf.demangle_kernel : symbol_conf.demangle;
207 }
208
209 static char *demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
210 {
211         int demangle_flags = verbose > 0 ? (DMGL_PARAMS | DMGL_ANSI) : DMGL_NO_OPTS;
212         char *demangled = NULL;
213
214         /*
215          * We need to figure out if the object was created from C++ sources
216          * DWARF DW_compile_unit has this, but we don't always have access
217          * to it...
218          */
219         if (!want_demangle(dso->kernel || kmodule))
220             return demangled;
221
222         demangled = bfd_demangle(NULL, elf_name, demangle_flags);
223         if (demangled == NULL)
224                 demangled = java_demangle_sym(elf_name, JAVA_DEMANGLE_NORET);
225         else if (rust_is_mangled(demangled))
226                 /*
227                     * Input to Rust demangling is the BFD-demangled
228                     * name which it Rust-demangles in place.
229                     */
230                 rust_demangle_sym(demangled);
231
232         return demangled;
233 }
234
235 #define elf_section__for_each_rel(reldata, pos, pos_mem, idx, nr_entries) \
236         for (idx = 0, pos = gelf_getrel(reldata, 0, &pos_mem); \
237              idx < nr_entries; \
238              ++idx, pos = gelf_getrel(reldata, idx, &pos_mem))
239
240 #define elf_section__for_each_rela(reldata, pos, pos_mem, idx, nr_entries) \
241         for (idx = 0, pos = gelf_getrela(reldata, 0, &pos_mem); \
242              idx < nr_entries; \
243              ++idx, pos = gelf_getrela(reldata, idx, &pos_mem))
244
245 /*
246  * We need to check if we have a .dynsym, so that we can handle the
247  * .plt, synthesizing its symbols, that aren't on the symtabs (be it
248  * .dynsym or .symtab).
249  * And always look at the original dso, not at debuginfo packages, that
250  * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
251  */
252 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss)
253 {
254         uint32_t nr_rel_entries, idx;
255         GElf_Sym sym;
256         u64 plt_offset, plt_header_size, plt_entry_size;
257         GElf_Shdr shdr_plt;
258         struct symbol *f;
259         GElf_Shdr shdr_rel_plt, shdr_dynsym;
260         Elf_Data *reldata, *syms, *symstrs;
261         Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
262         size_t dynsym_idx;
263         GElf_Ehdr ehdr;
264         char sympltname[1024];
265         Elf *elf;
266         int nr = 0, symidx, err = 0;
267
268         if (!ss->dynsym)
269                 return 0;
270
271         elf = ss->elf;
272         ehdr = ss->ehdr;
273
274         scn_dynsym = ss->dynsym;
275         shdr_dynsym = ss->dynshdr;
276         dynsym_idx = ss->dynsym_idx;
277
278         if (scn_dynsym == NULL)
279                 goto out_elf_end;
280
281         scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
282                                           ".rela.plt", NULL);
283         if (scn_plt_rel == NULL) {
284                 scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
285                                                   ".rel.plt", NULL);
286                 if (scn_plt_rel == NULL)
287                         goto out_elf_end;
288         }
289
290         err = -1;
291
292         if (shdr_rel_plt.sh_link != dynsym_idx)
293                 goto out_elf_end;
294
295         if (elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL) == NULL)
296                 goto out_elf_end;
297
298         /*
299          * Fetch the relocation section to find the idxes to the GOT
300          * and the symbols in the .dynsym they refer to.
301          */
302         reldata = elf_getdata(scn_plt_rel, NULL);
303         if (reldata == NULL)
304                 goto out_elf_end;
305
306         syms = elf_getdata(scn_dynsym, NULL);
307         if (syms == NULL)
308                 goto out_elf_end;
309
310         scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
311         if (scn_symstrs == NULL)
312                 goto out_elf_end;
313
314         symstrs = elf_getdata(scn_symstrs, NULL);
315         if (symstrs == NULL)
316                 goto out_elf_end;
317
318         if (symstrs->d_size == 0)
319                 goto out_elf_end;
320
321         nr_rel_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
322         plt_offset = shdr_plt.sh_offset;
323         switch (ehdr.e_machine) {
324                 case EM_ARM:
325                         plt_header_size = 20;
326                         plt_entry_size = 12;
327                         break;
328
329                 case EM_AARCH64:
330                         plt_header_size = 32;
331                         plt_entry_size = 16;
332                         break;
333
334                 case EM_SPARC:
335                         plt_header_size = 48;
336                         plt_entry_size = 12;
337                         break;
338
339                 case EM_SPARCV9:
340                         plt_header_size = 128;
341                         plt_entry_size = 32;
342                         break;
343
344                 default: /* FIXME: s390/alpha/mips/parisc/poperpc/sh/xtensa need to be checked */
345                         plt_header_size = shdr_plt.sh_entsize;
346                         plt_entry_size = shdr_plt.sh_entsize;
347                         break;
348         }
349         plt_offset += plt_header_size;
350
351         if (shdr_rel_plt.sh_type == SHT_RELA) {
352                 GElf_Rela pos_mem, *pos;
353
354                 elf_section__for_each_rela(reldata, pos, pos_mem, idx,
355                                            nr_rel_entries) {
356                         const char *elf_name = NULL;
357                         char *demangled = NULL;
358                         symidx = GELF_R_SYM(pos->r_info);
359                         gelf_getsym(syms, symidx, &sym);
360
361                         elf_name = elf_sym__name(&sym, symstrs);
362                         demangled = demangle_sym(dso, 0, elf_name);
363                         if (demangled != NULL)
364                                 elf_name = demangled;
365                         snprintf(sympltname, sizeof(sympltname),
366                                  "%s@plt", elf_name);
367                         free(demangled);
368
369                         f = symbol__new(plt_offset, plt_entry_size,
370                                         STB_GLOBAL, STT_FUNC, sympltname);
371                         if (!f)
372                                 goto out_elf_end;
373
374                         plt_offset += plt_entry_size;
375                         symbols__insert(&dso->symbols, f);
376                         ++nr;
377                 }
378         } else if (shdr_rel_plt.sh_type == SHT_REL) {
379                 GElf_Rel pos_mem, *pos;
380                 elf_section__for_each_rel(reldata, pos, pos_mem, idx,
381                                           nr_rel_entries) {
382                         const char *elf_name = NULL;
383                         char *demangled = NULL;
384                         symidx = GELF_R_SYM(pos->r_info);
385                         gelf_getsym(syms, symidx, &sym);
386
387                         elf_name = elf_sym__name(&sym, symstrs);
388                         demangled = demangle_sym(dso, 0, elf_name);
389                         if (demangled != NULL)
390                                 elf_name = demangled;
391                         snprintf(sympltname, sizeof(sympltname),
392                                  "%s@plt", elf_name);
393                         free(demangled);
394
395                         f = symbol__new(plt_offset, plt_entry_size,
396                                         STB_GLOBAL, STT_FUNC, sympltname);
397                         if (!f)
398                                 goto out_elf_end;
399
400                         plt_offset += plt_entry_size;
401                         symbols__insert(&dso->symbols, f);
402                         ++nr;
403                 }
404         }
405
406         err = 0;
407 out_elf_end:
408         if (err == 0)
409                 return nr;
410         pr_debug("%s: problems reading %s PLT info.\n",
411                  __func__, dso->long_name);
412         return 0;
413 }
414
415 char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name)
416 {
417         return demangle_sym(dso, kmodule, elf_name);
418 }
419
420 /*
421  * Align offset to 4 bytes as needed for note name and descriptor data.
422  */
423 #define NOTE_ALIGN(n) (((n) + 3) & -4U)
424
425 static int elf_read_build_id(Elf *elf, void *bf, size_t size)
426 {
427         int err = -1;
428         GElf_Ehdr ehdr;
429         GElf_Shdr shdr;
430         Elf_Data *data;
431         Elf_Scn *sec;
432         Elf_Kind ek;
433         void *ptr;
434
435         if (size < BUILD_ID_SIZE)
436                 goto out;
437
438         ek = elf_kind(elf);
439         if (ek != ELF_K_ELF)
440                 goto out;
441
442         if (gelf_getehdr(elf, &ehdr) == NULL) {
443                 pr_err("%s: cannot get elf header.\n", __func__);
444                 goto out;
445         }
446
447         /*
448          * Check following sections for notes:
449          *   '.note.gnu.build-id'
450          *   '.notes'
451          *   '.note' (VDSO specific)
452          */
453         do {
454                 sec = elf_section_by_name(elf, &ehdr, &shdr,
455                                           ".note.gnu.build-id", NULL);
456                 if (sec)
457                         break;
458
459                 sec = elf_section_by_name(elf, &ehdr, &shdr,
460                                           ".notes", NULL);
461                 if (sec)
462                         break;
463
464                 sec = elf_section_by_name(elf, &ehdr, &shdr,
465                                           ".note", NULL);
466                 if (sec)
467                         break;
468
469                 return err;
470
471         } while (0);
472
473         data = elf_getdata(sec, NULL);
474         if (data == NULL)
475                 goto out;
476
477         ptr = data->d_buf;
478         while (ptr < (data->d_buf + data->d_size)) {
479                 GElf_Nhdr *nhdr = ptr;
480                 size_t namesz = NOTE_ALIGN(nhdr->n_namesz),
481                        descsz = NOTE_ALIGN(nhdr->n_descsz);
482                 const char *name;
483
484                 ptr += sizeof(*nhdr);
485                 name = ptr;
486                 ptr += namesz;
487                 if (nhdr->n_type == NT_GNU_BUILD_ID &&
488                     nhdr->n_namesz == sizeof("GNU")) {
489                         if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
490                                 size_t sz = min(size, descsz);
491                                 memcpy(bf, ptr, sz);
492                                 memset(bf + sz, 0, size - sz);
493                                 err = descsz;
494                                 break;
495                         }
496                 }
497                 ptr += descsz;
498         }
499
500 out:
501         return err;
502 }
503
504 int filename__read_build_id(const char *filename, void *bf, size_t size)
505 {
506         int fd, err = -1;
507         Elf *elf;
508
509         if (size < BUILD_ID_SIZE)
510                 goto out;
511
512         fd = open(filename, O_RDONLY);
513         if (fd < 0)
514                 goto out;
515
516         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
517         if (elf == NULL) {
518                 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
519                 goto out_close;
520         }
521
522         err = elf_read_build_id(elf, bf, size);
523
524         elf_end(elf);
525 out_close:
526         close(fd);
527 out:
528         return err;
529 }
530
531 int sysfs__read_build_id(const char *filename, void *build_id, size_t size)
532 {
533         int fd, err = -1;
534
535         if (size < BUILD_ID_SIZE)
536                 goto out;
537
538         fd = open(filename, O_RDONLY);
539         if (fd < 0)
540                 goto out;
541
542         while (1) {
543                 char bf[BUFSIZ];
544                 GElf_Nhdr nhdr;
545                 size_t namesz, descsz;
546
547                 if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
548                         break;
549
550                 namesz = NOTE_ALIGN(nhdr.n_namesz);
551                 descsz = NOTE_ALIGN(nhdr.n_descsz);
552                 if (nhdr.n_type == NT_GNU_BUILD_ID &&
553                     nhdr.n_namesz == sizeof("GNU")) {
554                         if (read(fd, bf, namesz) != (ssize_t)namesz)
555                                 break;
556                         if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
557                                 size_t sz = min(descsz, size);
558                                 if (read(fd, build_id, sz) == (ssize_t)sz) {
559                                         memset(build_id + sz, 0, size - sz);
560                                         err = 0;
561                                         break;
562                                 }
563                         } else if (read(fd, bf, descsz) != (ssize_t)descsz)
564                                 break;
565                 } else {
566                         int n = namesz + descsz;
567
568                         if (n > (int)sizeof(bf)) {
569                                 n = sizeof(bf);
570                                 pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
571                                          __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
572                         }
573                         if (read(fd, bf, n) != n)
574                                 break;
575                 }
576         }
577         close(fd);
578 out:
579         return err;
580 }
581
582 int filename__read_debuglink(const char *filename, char *debuglink,
583                              size_t size)
584 {
585         int fd, err = -1;
586         Elf *elf;
587         GElf_Ehdr ehdr;
588         GElf_Shdr shdr;
589         Elf_Data *data;
590         Elf_Scn *sec;
591         Elf_Kind ek;
592
593         fd = open(filename, O_RDONLY);
594         if (fd < 0)
595                 goto out;
596
597         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
598         if (elf == NULL) {
599                 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
600                 goto out_close;
601         }
602
603         ek = elf_kind(elf);
604         if (ek != ELF_K_ELF)
605                 goto out_elf_end;
606
607         if (gelf_getehdr(elf, &ehdr) == NULL) {
608                 pr_err("%s: cannot get elf header.\n", __func__);
609                 goto out_elf_end;
610         }
611
612         sec = elf_section_by_name(elf, &ehdr, &shdr,
613                                   ".gnu_debuglink", NULL);
614         if (sec == NULL)
615                 goto out_elf_end;
616
617         data = elf_getdata(sec, NULL);
618         if (data == NULL)
619                 goto out_elf_end;
620
621         /* the start of this section is a zero-terminated string */
622         strncpy(debuglink, data->d_buf, size);
623
624         err = 0;
625
626 out_elf_end:
627         elf_end(elf);
628 out_close:
629         close(fd);
630 out:
631         return err;
632 }
633
634 static int dso__swap_init(struct dso *dso, unsigned char eidata)
635 {
636         static unsigned int const endian = 1;
637
638         dso->needs_swap = DSO_SWAP__NO;
639
640         switch (eidata) {
641         case ELFDATA2LSB:
642                 /* We are big endian, DSO is little endian. */
643                 if (*(unsigned char const *)&endian != 1)
644                         dso->needs_swap = DSO_SWAP__YES;
645                 break;
646
647         case ELFDATA2MSB:
648                 /* We are little endian, DSO is big endian. */
649                 if (*(unsigned char const *)&endian != 0)
650                         dso->needs_swap = DSO_SWAP__YES;
651                 break;
652
653         default:
654                 pr_err("unrecognized DSO data encoding %d\n", eidata);
655                 return -EINVAL;
656         }
657
658         return 0;
659 }
660
661 bool symsrc__possibly_runtime(struct symsrc *ss)
662 {
663         return ss->dynsym || ss->opdsec;
664 }
665
666 bool symsrc__has_symtab(struct symsrc *ss)
667 {
668         return ss->symtab != NULL;
669 }
670
671 void symsrc__destroy(struct symsrc *ss)
672 {
673         zfree(&ss->name);
674         elf_end(ss->elf);
675         close(ss->fd);
676 }
677
678 bool __weak elf__needs_adjust_symbols(GElf_Ehdr ehdr)
679 {
680         return ehdr.e_type == ET_EXEC || ehdr.e_type == ET_REL;
681 }
682
683 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
684                  enum dso_binary_type type)
685 {
686         int err = -1;
687         GElf_Ehdr ehdr;
688         Elf *elf;
689         int fd;
690
691         if (dso__needs_decompress(dso)) {
692                 fd = dso__decompress_kmodule_fd(dso, name);
693                 if (fd < 0)
694                         return -1;
695
696                 type = dso->symtab_type;
697         } else {
698                 fd = open(name, O_RDONLY);
699                 if (fd < 0) {
700                         dso->load_errno = errno;
701                         return -1;
702                 }
703         }
704
705         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
706         if (elf == NULL) {
707                 pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
708                 dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
709                 goto out_close;
710         }
711
712         if (gelf_getehdr(elf, &ehdr) == NULL) {
713                 dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
714                 pr_debug("%s: cannot get elf header.\n", __func__);
715                 goto out_elf_end;
716         }
717
718         if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
719                 dso->load_errno = DSO_LOAD_ERRNO__INTERNAL_ERROR;
720                 goto out_elf_end;
721         }
722
723         /* Always reject images with a mismatched build-id: */
724         if (dso->has_build_id && !symbol_conf.ignore_vmlinux_buildid) {
725                 u8 build_id[BUILD_ID_SIZE];
726
727                 if (elf_read_build_id(elf, build_id, BUILD_ID_SIZE) < 0) {
728                         dso->load_errno = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
729                         goto out_elf_end;
730                 }
731
732                 if (!dso__build_id_equal(dso, build_id)) {
733                         pr_debug("%s: build id mismatch for %s.\n", __func__, name);
734                         dso->load_errno = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
735                         goto out_elf_end;
736                 }
737         }
738
739         ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
740
741         ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
742                         NULL);
743         if (ss->symshdr.sh_type != SHT_SYMTAB)
744                 ss->symtab = NULL;
745
746         ss->dynsym_idx = 0;
747         ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
748                         &ss->dynsym_idx);
749         if (ss->dynshdr.sh_type != SHT_DYNSYM)
750                 ss->dynsym = NULL;
751
752         ss->opdidx = 0;
753         ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
754                         &ss->opdidx);
755         if (ss->opdshdr.sh_type != SHT_PROGBITS)
756                 ss->opdsec = NULL;
757
758         if (dso->kernel == DSO_TYPE_USER)
759                 ss->adjust_symbols = true;
760         else
761                 ss->adjust_symbols = elf__needs_adjust_symbols(ehdr);
762
763         ss->name   = strdup(name);
764         if (!ss->name) {
765                 dso->load_errno = errno;
766                 goto out_elf_end;
767         }
768
769         ss->elf    = elf;
770         ss->fd     = fd;
771         ss->ehdr   = ehdr;
772         ss->type   = type;
773
774         return 0;
775
776 out_elf_end:
777         elf_end(elf);
778 out_close:
779         close(fd);
780         return err;
781 }
782
783 /**
784  * ref_reloc_sym_not_found - has kernel relocation symbol been found.
785  * @kmap: kernel maps and relocation reference symbol
786  *
787  * This function returns %true if we are dealing with the kernel maps and the
788  * relocation reference symbol has not yet been found.  Otherwise %false is
789  * returned.
790  */
791 static bool ref_reloc_sym_not_found(struct kmap *kmap)
792 {
793         return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
794                !kmap->ref_reloc_sym->unrelocated_addr;
795 }
796
797 /**
798  * ref_reloc - kernel relocation offset.
799  * @kmap: kernel maps and relocation reference symbol
800  *
801  * This function returns the offset of kernel addresses as determined by using
802  * the relocation reference symbol i.e. if the kernel has not been relocated
803  * then the return value is zero.
804  */
805 static u64 ref_reloc(struct kmap *kmap)
806 {
807         if (kmap && kmap->ref_reloc_sym &&
808             kmap->ref_reloc_sym->unrelocated_addr)
809                 return kmap->ref_reloc_sym->addr -
810                        kmap->ref_reloc_sym->unrelocated_addr;
811         return 0;
812 }
813
814 void __weak arch__sym_update(struct symbol *s __maybe_unused,
815                 GElf_Sym *sym __maybe_unused) { }
816
817 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
818                                       GElf_Sym *sym, GElf_Shdr *shdr,
819                                       struct map_groups *kmaps, struct kmap *kmap,
820                                       struct dso **curr_dsop, struct map **curr_mapp,
821                                       const char *section_name,
822                                       bool adjust_kernel_syms, bool kmodule, bool *remap_kernel)
823 {
824         struct dso *curr_dso = *curr_dsop;
825         struct map *curr_map;
826         char dso_name[PATH_MAX];
827
828         /* Adjust symbol to map to file offset */
829         if (adjust_kernel_syms)
830                 sym->st_value -= shdr->sh_addr - shdr->sh_offset;
831
832         if (strcmp(section_name, (curr_dso->short_name + dso->short_name_len)) == 0)
833                 return 0;
834
835         if (strcmp(section_name, ".text") == 0) {
836                 /*
837                  * The initial kernel mapping is based on
838                  * kallsyms and identity maps.  Overwrite it to
839                  * map to the kernel dso.
840                  */
841                 if (*remap_kernel && dso->kernel) {
842                         *remap_kernel = false;
843                         map->start = shdr->sh_addr + ref_reloc(kmap);
844                         map->end = map->start + shdr->sh_size;
845                         map->pgoff = shdr->sh_offset;
846                         map->map_ip = map__map_ip;
847                         map->unmap_ip = map__unmap_ip;
848                         /* Ensure maps are correctly ordered */
849                         if (kmaps) {
850                                 map__get(map);
851                                 map_groups__remove(kmaps, map);
852                                 map_groups__insert(kmaps, map);
853                                 map__put(map);
854                         }
855                 }
856
857                 /*
858                  * The initial module mapping is based on
859                  * /proc/modules mapped to offset zero.
860                  * Overwrite it to map to the module dso.
861                  */
862                 if (*remap_kernel && kmodule) {
863                         *remap_kernel = false;
864                         map->pgoff = shdr->sh_offset;
865                 }
866
867                 *curr_mapp = map;
868                 *curr_dsop = dso;
869                 return 0;
870         }
871
872         if (!kmap)
873                 return 0;
874
875         snprintf(dso_name, sizeof(dso_name), "%s%s", dso->short_name, section_name);
876
877         curr_map = map_groups__find_by_name(kmaps, dso_name);
878         if (curr_map == NULL) {
879                 u64 start = sym->st_value;
880
881                 if (kmodule)
882                         start += map->start + shdr->sh_offset;
883
884                 curr_dso = dso__new(dso_name);
885                 if (curr_dso == NULL)
886                         return -1;
887                 curr_dso->kernel = dso->kernel;
888                 curr_dso->long_name = dso->long_name;
889                 curr_dso->long_name_len = dso->long_name_len;
890                 curr_map = map__new2(start, curr_dso);
891                 dso__put(curr_dso);
892                 if (curr_map == NULL)
893                         return -1;
894
895                 if (adjust_kernel_syms) {
896                         curr_map->start  = shdr->sh_addr + ref_reloc(kmap);
897                         curr_map->end    = curr_map->start + shdr->sh_size;
898                         curr_map->pgoff  = shdr->sh_offset;
899                 } else {
900                         curr_map->map_ip = curr_map->unmap_ip = identity__map_ip;
901                 }
902                 curr_dso->symtab_type = dso->symtab_type;
903                 map_groups__insert(kmaps, curr_map);
904                 /*
905                  * Add it before we drop the referece to curr_map, i.e. while
906                  * we still are sure to have a reference to this DSO via
907                  * *curr_map->dso.
908                  */
909                 dsos__add(&map->groups->machine->dsos, curr_dso);
910                 /* kmaps already got it */
911                 map__put(curr_map);
912                 dso__set_loaded(curr_dso);
913                 *curr_mapp = curr_map;
914                 *curr_dsop = curr_dso;
915         } else
916                 *curr_dsop = curr_map->dso;
917
918         return 0;
919 }
920
921 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
922                   struct symsrc *runtime_ss, int kmodule)
923 {
924         struct kmap *kmap = dso->kernel ? map__kmap(map) : NULL;
925         struct map_groups *kmaps = kmap ? map__kmaps(map) : NULL;
926         struct map *curr_map = map;
927         struct dso *curr_dso = dso;
928         Elf_Data *symstrs, *secstrs;
929         uint32_t nr_syms;
930         int err = -1;
931         uint32_t idx;
932         GElf_Ehdr ehdr;
933         GElf_Shdr shdr;
934         GElf_Shdr tshdr;
935         Elf_Data *syms, *opddata = NULL;
936         GElf_Sym sym;
937         Elf_Scn *sec, *sec_strndx;
938         Elf *elf;
939         int nr = 0;
940         bool remap_kernel = false, adjust_kernel_syms = false;
941
942         if (kmap && !kmaps)
943                 return -1;
944
945         dso->symtab_type = syms_ss->type;
946         dso->is_64_bit = syms_ss->is_64_bit;
947         dso->rel = syms_ss->ehdr.e_type == ET_REL;
948
949         /*
950          * Modules may already have symbols from kallsyms, but those symbols
951          * have the wrong values for the dso maps, so remove them.
952          */
953         if (kmodule && syms_ss->symtab)
954                 symbols__delete(&dso->symbols);
955
956         if (!syms_ss->symtab) {
957                 /*
958                  * If the vmlinux is stripped, fail so we will fall back
959                  * to using kallsyms. The vmlinux runtime symbols aren't
960                  * of much use.
961                  */
962                 if (dso->kernel)
963                         goto out_elf_end;
964
965                 syms_ss->symtab  = syms_ss->dynsym;
966                 syms_ss->symshdr = syms_ss->dynshdr;
967         }
968
969         elf = syms_ss->elf;
970         ehdr = syms_ss->ehdr;
971         sec = syms_ss->symtab;
972         shdr = syms_ss->symshdr;
973
974         if (elf_section_by_name(runtime_ss->elf, &runtime_ss->ehdr, &tshdr,
975                                 ".text", NULL))
976                 dso->text_offset = tshdr.sh_addr - tshdr.sh_offset;
977
978         if (runtime_ss->opdsec)
979                 opddata = elf_rawdata(runtime_ss->opdsec, NULL);
980
981         syms = elf_getdata(sec, NULL);
982         if (syms == NULL)
983                 goto out_elf_end;
984
985         sec = elf_getscn(elf, shdr.sh_link);
986         if (sec == NULL)
987                 goto out_elf_end;
988
989         symstrs = elf_getdata(sec, NULL);
990         if (symstrs == NULL)
991                 goto out_elf_end;
992
993         sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
994         if (sec_strndx == NULL)
995                 goto out_elf_end;
996
997         secstrs = elf_getdata(sec_strndx, NULL);
998         if (secstrs == NULL)
999                 goto out_elf_end;
1000
1001         nr_syms = shdr.sh_size / shdr.sh_entsize;
1002
1003         memset(&sym, 0, sizeof(sym));
1004
1005         /*
1006          * The kernel relocation symbol is needed in advance in order to adjust
1007          * kernel maps correctly.
1008          */
1009         if (ref_reloc_sym_not_found(kmap)) {
1010                 elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1011                         const char *elf_name = elf_sym__name(&sym, symstrs);
1012
1013                         if (strcmp(elf_name, kmap->ref_reloc_sym->name))
1014                                 continue;
1015                         kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
1016                         map->reloc = kmap->ref_reloc_sym->addr -
1017                                      kmap->ref_reloc_sym->unrelocated_addr;
1018                         break;
1019                 }
1020         }
1021
1022         /*
1023          * Handle any relocation of vdso necessary because older kernels
1024          * attempted to prelink vdso to its virtual address.
1025          */
1026         if (dso__is_vdso(dso))
1027                 map->reloc = map->start - dso->text_offset;
1028
1029         dso->adjust_symbols = runtime_ss->adjust_symbols || ref_reloc(kmap);
1030         /*
1031          * Initial kernel and module mappings do not map to the dso.
1032          * Flag the fixups.
1033          */
1034         if (dso->kernel || kmodule) {
1035                 remap_kernel = true;
1036                 adjust_kernel_syms = dso->adjust_symbols;
1037         }
1038         elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1039                 struct symbol *f;
1040                 const char *elf_name = elf_sym__name(&sym, symstrs);
1041                 char *demangled = NULL;
1042                 int is_label = elf_sym__is_label(&sym);
1043                 const char *section_name;
1044                 bool used_opd = false;
1045
1046                 if (!is_label && !elf_sym__filter(&sym))
1047                         continue;
1048
1049                 /* Reject ARM ELF "mapping symbols": these aren't unique and
1050                  * don't identify functions, so will confuse the profile
1051                  * output: */
1052                 if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
1053                         if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
1054                             && (elf_name[2] == '\0' || elf_name[2] == '.'))
1055                                 continue;
1056                 }
1057
1058                 if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
1059                         u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
1060                         u64 *opd = opddata->d_buf + offset;
1061                         sym.st_value = DSO__SWAP(dso, u64, *opd);
1062                         sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
1063                                         sym.st_value);
1064                         used_opd = true;
1065                 }
1066                 /*
1067                  * When loading symbols in a data mapping, ABS symbols (which
1068                  * has a value of SHN_ABS in its st_shndx) failed at
1069                  * elf_getscn().  And it marks the loading as a failure so
1070                  * already loaded symbols cannot be fixed up.
1071                  *
1072                  * I'm not sure what should be done. Just ignore them for now.
1073                  * - Namhyung Kim
1074                  */
1075                 if (sym.st_shndx == SHN_ABS)
1076                         continue;
1077
1078                 sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
1079                 if (!sec)
1080                         goto out_elf_end;
1081
1082                 gelf_getshdr(sec, &shdr);
1083
1084                 if (is_label && !elf_sec__filter(&shdr, secstrs))
1085                         continue;
1086
1087                 section_name = elf_sec__name(&shdr, secstrs);
1088
1089                 /* On ARM, symbols for thumb functions have 1 added to
1090                  * the symbol address as a flag - remove it */
1091                 if ((ehdr.e_machine == EM_ARM) &&
1092                     (GELF_ST_TYPE(sym.st_info) == STT_FUNC) &&
1093                     (sym.st_value & 1))
1094                         --sym.st_value;
1095
1096                 if (dso->kernel || kmodule) {
1097                         if (dso__process_kernel_symbol(dso, map, &sym, &shdr, kmaps, kmap, &curr_dso, &curr_map,
1098                                                        section_name, adjust_kernel_syms, kmodule, &remap_kernel))
1099                                 goto out_elf_end;
1100                 } else if ((used_opd && runtime_ss->adjust_symbols) ||
1101                            (!used_opd && syms_ss->adjust_symbols)) {
1102                         pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1103                                   "sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n", __func__,
1104                                   (u64)sym.st_value, (u64)shdr.sh_addr,
1105                                   (u64)shdr.sh_offset);
1106                         sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1107                 }
1108
1109                 demangled = demangle_sym(dso, kmodule, elf_name);
1110                 if (demangled != NULL)
1111                         elf_name = demangled;
1112
1113                 f = symbol__new(sym.st_value, sym.st_size,
1114                                 GELF_ST_BIND(sym.st_info),
1115                                 GELF_ST_TYPE(sym.st_info), elf_name);
1116                 free(demangled);
1117                 if (!f)
1118                         goto out_elf_end;
1119
1120                 arch__sym_update(f, &sym);
1121
1122                 __symbols__insert(&curr_dso->symbols, f, dso->kernel);
1123                 nr++;
1124         }
1125
1126         /*
1127          * For misannotated, zeroed, ASM function sizes.
1128          */
1129         if (nr > 0) {
1130                 symbols__fixup_end(&dso->symbols);
1131                 symbols__fixup_duplicate(&dso->symbols);
1132                 if (kmap) {
1133                         /*
1134                          * We need to fixup this here too because we create new
1135                          * maps here, for things like vsyscall sections.
1136                          */
1137                         map_groups__fixup_end(kmaps);
1138                 }
1139         }
1140         err = nr;
1141 out_elf_end:
1142         return err;
1143 }
1144
1145 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1146 {
1147         GElf_Phdr phdr;
1148         size_t i, phdrnum;
1149         int err;
1150         u64 sz;
1151
1152         if (elf_getphdrnum(elf, &phdrnum))
1153                 return -1;
1154
1155         for (i = 0; i < phdrnum; i++) {
1156                 if (gelf_getphdr(elf, i, &phdr) == NULL)
1157                         return -1;
1158                 if (phdr.p_type != PT_LOAD)
1159                         continue;
1160                 if (exe) {
1161                         if (!(phdr.p_flags & PF_X))
1162                                 continue;
1163                 } else {
1164                         if (!(phdr.p_flags & PF_R))
1165                                 continue;
1166                 }
1167                 sz = min(phdr.p_memsz, phdr.p_filesz);
1168                 if (!sz)
1169                         continue;
1170                 err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1171                 if (err)
1172                         return err;
1173         }
1174         return 0;
1175 }
1176
1177 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1178                     bool *is_64_bit)
1179 {
1180         int err;
1181         Elf *elf;
1182
1183         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1184         if (elf == NULL)
1185                 return -1;
1186
1187         if (is_64_bit)
1188                 *is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1189
1190         err = elf_read_maps(elf, exe, mapfn, data);
1191
1192         elf_end(elf);
1193         return err;
1194 }
1195
1196 enum dso_type dso__type_fd(int fd)
1197 {
1198         enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1199         GElf_Ehdr ehdr;
1200         Elf_Kind ek;
1201         Elf *elf;
1202
1203         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1204         if (elf == NULL)
1205                 goto out;
1206
1207         ek = elf_kind(elf);
1208         if (ek != ELF_K_ELF)
1209                 goto out_end;
1210
1211         if (gelf_getclass(elf) == ELFCLASS64) {
1212                 dso_type = DSO__TYPE_64BIT;
1213                 goto out_end;
1214         }
1215
1216         if (gelf_getehdr(elf, &ehdr) == NULL)
1217                 goto out_end;
1218
1219         if (ehdr.e_machine == EM_X86_64)
1220                 dso_type = DSO__TYPE_X32BIT;
1221         else
1222                 dso_type = DSO__TYPE_32BIT;
1223 out_end:
1224         elf_end(elf);
1225 out:
1226         return dso_type;
1227 }
1228
1229 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1230 {
1231         ssize_t r;
1232         size_t n;
1233         int err = -1;
1234         char *buf = malloc(page_size);
1235
1236         if (buf == NULL)
1237                 return -1;
1238
1239         if (lseek(to, to_offs, SEEK_SET) != to_offs)
1240                 goto out;
1241
1242         if (lseek(from, from_offs, SEEK_SET) != from_offs)
1243                 goto out;
1244
1245         while (len) {
1246                 n = page_size;
1247                 if (len < n)
1248                         n = len;
1249                 /* Use read because mmap won't work on proc files */
1250                 r = read(from, buf, n);
1251                 if (r < 0)
1252                         goto out;
1253                 if (!r)
1254                         break;
1255                 n = r;
1256                 r = write(to, buf, n);
1257                 if (r < 0)
1258                         goto out;
1259                 if ((size_t)r != n)
1260                         goto out;
1261                 len -= n;
1262         }
1263
1264         err = 0;
1265 out:
1266         free(buf);
1267         return err;
1268 }
1269
1270 struct kcore {
1271         int fd;
1272         int elfclass;
1273         Elf *elf;
1274         GElf_Ehdr ehdr;
1275 };
1276
1277 static int kcore__open(struct kcore *kcore, const char *filename)
1278 {
1279         GElf_Ehdr *ehdr;
1280
1281         kcore->fd = open(filename, O_RDONLY);
1282         if (kcore->fd == -1)
1283                 return -1;
1284
1285         kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1286         if (!kcore->elf)
1287                 goto out_close;
1288
1289         kcore->elfclass = gelf_getclass(kcore->elf);
1290         if (kcore->elfclass == ELFCLASSNONE)
1291                 goto out_end;
1292
1293         ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1294         if (!ehdr)
1295                 goto out_end;
1296
1297         return 0;
1298
1299 out_end:
1300         elf_end(kcore->elf);
1301 out_close:
1302         close(kcore->fd);
1303         return -1;
1304 }
1305
1306 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1307                        bool temp)
1308 {
1309         kcore->elfclass = elfclass;
1310
1311         if (temp)
1312                 kcore->fd = mkstemp(filename);
1313         else
1314                 kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0400);
1315         if (kcore->fd == -1)
1316                 return -1;
1317
1318         kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1319         if (!kcore->elf)
1320                 goto out_close;
1321
1322         if (!gelf_newehdr(kcore->elf, elfclass))
1323                 goto out_end;
1324
1325         memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
1326
1327         return 0;
1328
1329 out_end:
1330         elf_end(kcore->elf);
1331 out_close:
1332         close(kcore->fd);
1333         unlink(filename);
1334         return -1;
1335 }
1336
1337 static void kcore__close(struct kcore *kcore)
1338 {
1339         elf_end(kcore->elf);
1340         close(kcore->fd);
1341 }
1342
1343 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
1344 {
1345         GElf_Ehdr *ehdr = &to->ehdr;
1346         GElf_Ehdr *kehdr = &from->ehdr;
1347
1348         memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
1349         ehdr->e_type      = kehdr->e_type;
1350         ehdr->e_machine   = kehdr->e_machine;
1351         ehdr->e_version   = kehdr->e_version;
1352         ehdr->e_entry     = 0;
1353         ehdr->e_shoff     = 0;
1354         ehdr->e_flags     = kehdr->e_flags;
1355         ehdr->e_phnum     = count;
1356         ehdr->e_shentsize = 0;
1357         ehdr->e_shnum     = 0;
1358         ehdr->e_shstrndx  = 0;
1359
1360         if (from->elfclass == ELFCLASS32) {
1361                 ehdr->e_phoff     = sizeof(Elf32_Ehdr);
1362                 ehdr->e_ehsize    = sizeof(Elf32_Ehdr);
1363                 ehdr->e_phentsize = sizeof(Elf32_Phdr);
1364         } else {
1365                 ehdr->e_phoff     = sizeof(Elf64_Ehdr);
1366                 ehdr->e_ehsize    = sizeof(Elf64_Ehdr);
1367                 ehdr->e_phentsize = sizeof(Elf64_Phdr);
1368         }
1369
1370         if (!gelf_update_ehdr(to->elf, ehdr))
1371                 return -1;
1372
1373         if (!gelf_newphdr(to->elf, count))
1374                 return -1;
1375
1376         return 0;
1377 }
1378
1379 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
1380                            u64 addr, u64 len)
1381 {
1382         GElf_Phdr phdr = {
1383                 .p_type         = PT_LOAD,
1384                 .p_flags        = PF_R | PF_W | PF_X,
1385                 .p_offset       = offset,
1386                 .p_vaddr        = addr,
1387                 .p_paddr        = 0,
1388                 .p_filesz       = len,
1389                 .p_memsz        = len,
1390                 .p_align        = page_size,
1391         };
1392
1393         if (!gelf_update_phdr(kcore->elf, idx, &phdr))
1394                 return -1;
1395
1396         return 0;
1397 }
1398
1399 static off_t kcore__write(struct kcore *kcore)
1400 {
1401         return elf_update(kcore->elf, ELF_C_WRITE);
1402 }
1403
1404 struct phdr_data {
1405         off_t offset;
1406         off_t rel;
1407         u64 addr;
1408         u64 len;
1409         struct list_head node;
1410         struct phdr_data *remaps;
1411 };
1412
1413 struct sym_data {
1414         u64 addr;
1415         struct list_head node;
1416 };
1417
1418 struct kcore_copy_info {
1419         u64 stext;
1420         u64 etext;
1421         u64 first_symbol;
1422         u64 last_symbol;
1423         u64 first_module;
1424         u64 first_module_symbol;
1425         u64 last_module_symbol;
1426         size_t phnum;
1427         struct list_head phdrs;
1428         struct list_head syms;
1429 };
1430
1431 #define kcore_copy__for_each_phdr(k, p) \
1432         list_for_each_entry((p), &(k)->phdrs, node)
1433
1434 static struct phdr_data *phdr_data__new(u64 addr, u64 len, off_t offset)
1435 {
1436         struct phdr_data *p = zalloc(sizeof(*p));
1437
1438         if (p) {
1439                 p->addr   = addr;
1440                 p->len    = len;
1441                 p->offset = offset;
1442         }
1443
1444         return p;
1445 }
1446
1447 static struct phdr_data *kcore_copy_info__addnew(struct kcore_copy_info *kci,
1448                                                  u64 addr, u64 len,
1449                                                  off_t offset)
1450 {
1451         struct phdr_data *p = phdr_data__new(addr, len, offset);
1452
1453         if (p)
1454                 list_add_tail(&p->node, &kci->phdrs);
1455
1456         return p;
1457 }
1458
1459 static void kcore_copy__free_phdrs(struct kcore_copy_info *kci)
1460 {
1461         struct phdr_data *p, *tmp;
1462
1463         list_for_each_entry_safe(p, tmp, &kci->phdrs, node) {
1464                 list_del(&p->node);
1465                 free(p);
1466         }
1467 }
1468
1469 static struct sym_data *kcore_copy__new_sym(struct kcore_copy_info *kci,
1470                                             u64 addr)
1471 {
1472         struct sym_data *s = zalloc(sizeof(*s));
1473
1474         if (s) {
1475                 s->addr = addr;
1476                 list_add_tail(&s->node, &kci->syms);
1477         }
1478
1479         return s;
1480 }
1481
1482 static void kcore_copy__free_syms(struct kcore_copy_info *kci)
1483 {
1484         struct sym_data *s, *tmp;
1485
1486         list_for_each_entry_safe(s, tmp, &kci->syms, node) {
1487                 list_del(&s->node);
1488                 free(s);
1489         }
1490 }
1491
1492 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
1493                                         u64 start)
1494 {
1495         struct kcore_copy_info *kci = arg;
1496
1497         if (!kallsyms__is_function(type))
1498                 return 0;
1499
1500         if (strchr(name, '[')) {
1501                 if (!kci->first_module_symbol || start < kci->first_module_symbol)
1502                         kci->first_module_symbol = start;
1503                 if (start > kci->last_module_symbol)
1504                         kci->last_module_symbol = start;
1505                 return 0;
1506         }
1507
1508         if (!kci->first_symbol || start < kci->first_symbol)
1509                 kci->first_symbol = start;
1510
1511         if (!kci->last_symbol || start > kci->last_symbol)
1512                 kci->last_symbol = start;
1513
1514         if (!strcmp(name, "_stext")) {
1515                 kci->stext = start;
1516                 return 0;
1517         }
1518
1519         if (!strcmp(name, "_etext")) {
1520                 kci->etext = start;
1521                 return 0;
1522         }
1523
1524         if (is_entry_trampoline(name) && !kcore_copy__new_sym(kci, start))
1525                 return -1;
1526
1527         return 0;
1528 }
1529
1530 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
1531                                       const char *dir)
1532 {
1533         char kallsyms_filename[PATH_MAX];
1534
1535         scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
1536
1537         if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
1538                 return -1;
1539
1540         if (kallsyms__parse(kallsyms_filename, kci,
1541                             kcore_copy__process_kallsyms) < 0)
1542                 return -1;
1543
1544         return 0;
1545 }
1546
1547 static int kcore_copy__process_modules(void *arg,
1548                                        const char *name __maybe_unused,
1549                                        u64 start, u64 size __maybe_unused)
1550 {
1551         struct kcore_copy_info *kci = arg;
1552
1553         if (!kci->first_module || start < kci->first_module)
1554                 kci->first_module = start;
1555
1556         return 0;
1557 }
1558
1559 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
1560                                      const char *dir)
1561 {
1562         char modules_filename[PATH_MAX];
1563
1564         scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
1565
1566         if (symbol__restricted_filename(modules_filename, "/proc/modules"))
1567                 return -1;
1568
1569         if (modules__parse(modules_filename, kci,
1570                            kcore_copy__process_modules) < 0)
1571                 return -1;
1572
1573         return 0;
1574 }
1575
1576 static int kcore_copy__map(struct kcore_copy_info *kci, u64 start, u64 end,
1577                            u64 pgoff, u64 s, u64 e)
1578 {
1579         u64 len, offset;
1580
1581         if (s < start || s >= end)
1582                 return 0;
1583
1584         offset = (s - start) + pgoff;
1585         len = e < end ? e - s : end - s;
1586
1587         return kcore_copy_info__addnew(kci, s, len, offset) ? 0 : -1;
1588 }
1589
1590 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
1591 {
1592         struct kcore_copy_info *kci = data;
1593         u64 end = start + len;
1594         struct sym_data *sdat;
1595
1596         if (kcore_copy__map(kci, start, end, pgoff, kci->stext, kci->etext))
1597                 return -1;
1598
1599         if (kcore_copy__map(kci, start, end, pgoff, kci->first_module,
1600                             kci->last_module_symbol))
1601                 return -1;
1602
1603         list_for_each_entry(sdat, &kci->syms, node) {
1604                 u64 s = round_down(sdat->addr, page_size);
1605
1606                 if (kcore_copy__map(kci, start, end, pgoff, s, s + len))
1607                         return -1;
1608         }
1609
1610         return 0;
1611 }
1612
1613 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
1614 {
1615         if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
1616                 return -1;
1617
1618         return 0;
1619 }
1620
1621 static void kcore_copy__find_remaps(struct kcore_copy_info *kci)
1622 {
1623         struct phdr_data *p, *k = NULL;
1624         u64 kend;
1625
1626         if (!kci->stext)
1627                 return;
1628
1629         /* Find phdr that corresponds to the kernel map (contains stext) */
1630         kcore_copy__for_each_phdr(kci, p) {
1631                 u64 pend = p->addr + p->len - 1;
1632
1633                 if (p->addr <= kci->stext && pend >= kci->stext) {
1634                         k = p;
1635                         break;
1636                 }
1637         }
1638
1639         if (!k)
1640                 return;
1641
1642         kend = k->offset + k->len;
1643
1644         /* Find phdrs that remap the kernel */
1645         kcore_copy__for_each_phdr(kci, p) {
1646                 u64 pend = p->offset + p->len;
1647
1648                 if (p == k)
1649                         continue;
1650
1651                 if (p->offset >= k->offset && pend <= kend)
1652                         p->remaps = k;
1653         }
1654 }
1655
1656 static void kcore_copy__layout(struct kcore_copy_info *kci)
1657 {
1658         struct phdr_data *p;
1659         off_t rel = 0;
1660
1661         kcore_copy__find_remaps(kci);
1662
1663         kcore_copy__for_each_phdr(kci, p) {
1664                 if (!p->remaps) {
1665                         p->rel = rel;
1666                         rel += p->len;
1667                 }
1668                 kci->phnum += 1;
1669         }
1670
1671         kcore_copy__for_each_phdr(kci, p) {
1672                 struct phdr_data *k = p->remaps;
1673
1674                 if (k)
1675                         p->rel = p->offset - k->offset + k->rel;
1676         }
1677 }
1678
1679 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
1680                                  Elf *elf)
1681 {
1682         if (kcore_copy__parse_kallsyms(kci, dir))
1683                 return -1;
1684
1685         if (kcore_copy__parse_modules(kci, dir))
1686                 return -1;
1687
1688         if (kci->stext)
1689                 kci->stext = round_down(kci->stext, page_size);
1690         else
1691                 kci->stext = round_down(kci->first_symbol, page_size);
1692
1693         if (kci->etext) {
1694                 kci->etext = round_up(kci->etext, page_size);
1695         } else if (kci->last_symbol) {
1696                 kci->etext = round_up(kci->last_symbol, page_size);
1697                 kci->etext += page_size;
1698         }
1699
1700         if (kci->first_module_symbol &&
1701             (!kci->first_module || kci->first_module_symbol < kci->first_module))
1702                 kci->first_module = kci->first_module_symbol;
1703
1704         kci->first_module = round_down(kci->first_module, page_size);
1705
1706         if (kci->last_module_symbol) {
1707                 kci->last_module_symbol = round_up(kci->last_module_symbol,
1708                                                    page_size);
1709                 kci->last_module_symbol += page_size;
1710         }
1711
1712         if (!kci->stext || !kci->etext)
1713                 return -1;
1714
1715         if (kci->first_module && !kci->last_module_symbol)
1716                 return -1;
1717
1718         if (kcore_copy__read_maps(kci, elf))
1719                 return -1;
1720
1721         kcore_copy__layout(kci);
1722
1723         return 0;
1724 }
1725
1726 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
1727                                  const char *name)
1728 {
1729         char from_filename[PATH_MAX];
1730         char to_filename[PATH_MAX];
1731
1732         scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
1733         scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
1734
1735         return copyfile_mode(from_filename, to_filename, 0400);
1736 }
1737
1738 static int kcore_copy__unlink(const char *dir, const char *name)
1739 {
1740         char filename[PATH_MAX];
1741
1742         scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
1743
1744         return unlink(filename);
1745 }
1746
1747 static int kcore_copy__compare_fds(int from, int to)
1748 {
1749         char *buf_from;
1750         char *buf_to;
1751         ssize_t ret;
1752         size_t len;
1753         int err = -1;
1754
1755         buf_from = malloc(page_size);
1756         buf_to = malloc(page_size);
1757         if (!buf_from || !buf_to)
1758                 goto out;
1759
1760         while (1) {
1761                 /* Use read because mmap won't work on proc files */
1762                 ret = read(from, buf_from, page_size);
1763                 if (ret < 0)
1764                         goto out;
1765
1766                 if (!ret)
1767                         break;
1768
1769                 len = ret;
1770
1771                 if (readn(to, buf_to, len) != (int)len)
1772                         goto out;
1773
1774                 if (memcmp(buf_from, buf_to, len))
1775                         goto out;
1776         }
1777
1778         err = 0;
1779 out:
1780         free(buf_to);
1781         free(buf_from);
1782         return err;
1783 }
1784
1785 static int kcore_copy__compare_files(const char *from_filename,
1786                                      const char *to_filename)
1787 {
1788         int from, to, err = -1;
1789
1790         from = open(from_filename, O_RDONLY);
1791         if (from < 0)
1792                 return -1;
1793
1794         to = open(to_filename, O_RDONLY);
1795         if (to < 0)
1796                 goto out_close_from;
1797
1798         err = kcore_copy__compare_fds(from, to);
1799
1800         close(to);
1801 out_close_from:
1802         close(from);
1803         return err;
1804 }
1805
1806 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
1807                                     const char *name)
1808 {
1809         char from_filename[PATH_MAX];
1810         char to_filename[PATH_MAX];
1811
1812         scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
1813         scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
1814
1815         return kcore_copy__compare_files(from_filename, to_filename);
1816 }
1817
1818 /**
1819  * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
1820  * @from_dir: from directory
1821  * @to_dir: to directory
1822  *
1823  * This function copies kallsyms, modules and kcore files from one directory to
1824  * another.  kallsyms and modules are copied entirely.  Only code segments are
1825  * copied from kcore.  It is assumed that two segments suffice: one for the
1826  * kernel proper and one for all the modules.  The code segments are determined
1827  * from kallsyms and modules files.  The kernel map starts at _stext or the
1828  * lowest function symbol, and ends at _etext or the highest function symbol.
1829  * The module map starts at the lowest module address and ends at the highest
1830  * module symbol.  Start addresses are rounded down to the nearest page.  End
1831  * addresses are rounded up to the nearest page.  An extra page is added to the
1832  * highest kernel symbol and highest module symbol to, hopefully, encompass that
1833  * symbol too.  Because it contains only code sections, the resulting kcore is
1834  * unusual.  One significant peculiarity is that the mapping (start -> pgoff)
1835  * is not the same for the kernel map and the modules map.  That happens because
1836  * the data is copied adjacently whereas the original kcore has gaps.  Finally,
1837  * kallsyms and modules files are compared with their copies to check that
1838  * modules have not been loaded or unloaded while the copies were taking place.
1839  *
1840  * Return: %0 on success, %-1 on failure.
1841  */
1842 int kcore_copy(const char *from_dir, const char *to_dir)
1843 {
1844         struct kcore kcore;
1845         struct kcore extract;
1846         int idx = 0, err = -1;
1847         off_t offset, sz;
1848         struct kcore_copy_info kci = { .stext = 0, };
1849         char kcore_filename[PATH_MAX];
1850         char extract_filename[PATH_MAX];
1851         struct phdr_data *p;
1852
1853         INIT_LIST_HEAD(&kci.phdrs);
1854         INIT_LIST_HEAD(&kci.syms);
1855
1856         if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
1857                 return -1;
1858
1859         if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
1860                 goto out_unlink_kallsyms;
1861
1862         scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
1863         scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
1864
1865         if (kcore__open(&kcore, kcore_filename))
1866                 goto out_unlink_modules;
1867
1868         if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
1869                 goto out_kcore_close;
1870
1871         if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
1872                 goto out_kcore_close;
1873
1874         if (kcore__copy_hdr(&kcore, &extract, kci.phnum))
1875                 goto out_extract_close;
1876
1877         offset = gelf_fsize(extract.elf, ELF_T_EHDR, 1, EV_CURRENT) +
1878                  gelf_fsize(extract.elf, ELF_T_PHDR, kci.phnum, EV_CURRENT);
1879         offset = round_up(offset, page_size);
1880
1881         kcore_copy__for_each_phdr(&kci, p) {
1882                 off_t offs = p->rel + offset;
1883
1884                 if (kcore__add_phdr(&extract, idx++, offs, p->addr, p->len))
1885                         goto out_extract_close;
1886         }
1887
1888         sz = kcore__write(&extract);
1889         if (sz < 0 || sz > offset)
1890                 goto out_extract_close;
1891
1892         kcore_copy__for_each_phdr(&kci, p) {
1893                 off_t offs = p->rel + offset;
1894
1895                 if (p->remaps)
1896                         continue;
1897                 if (copy_bytes(kcore.fd, p->offset, extract.fd, offs, p->len))
1898                         goto out_extract_close;
1899         }
1900
1901         if (kcore_copy__compare_file(from_dir, to_dir, "modules"))
1902                 goto out_extract_close;
1903
1904         if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
1905                 goto out_extract_close;
1906
1907         err = 0;
1908
1909 out_extract_close:
1910         kcore__close(&extract);
1911         if (err)
1912                 unlink(extract_filename);
1913 out_kcore_close:
1914         kcore__close(&kcore);
1915 out_unlink_modules:
1916         if (err)
1917                 kcore_copy__unlink(to_dir, "modules");
1918 out_unlink_kallsyms:
1919         if (err)
1920                 kcore_copy__unlink(to_dir, "kallsyms");
1921
1922         kcore_copy__free_phdrs(&kci);
1923         kcore_copy__free_syms(&kci);
1924
1925         return err;
1926 }
1927
1928 int kcore_extract__create(struct kcore_extract *kce)
1929 {
1930         struct kcore kcore;
1931         struct kcore extract;
1932         size_t count = 1;
1933         int idx = 0, err = -1;
1934         off_t offset = page_size, sz;
1935
1936         if (kcore__open(&kcore, kce->kcore_filename))
1937                 return -1;
1938
1939         strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
1940         if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
1941                 goto out_kcore_close;
1942
1943         if (kcore__copy_hdr(&kcore, &extract, count))
1944                 goto out_extract_close;
1945
1946         if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
1947                 goto out_extract_close;
1948
1949         sz = kcore__write(&extract);
1950         if (sz < 0 || sz > offset)
1951                 goto out_extract_close;
1952
1953         if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
1954                 goto out_extract_close;
1955
1956         err = 0;
1957
1958 out_extract_close:
1959         kcore__close(&extract);
1960         if (err)
1961                 unlink(kce->extract_filename);
1962 out_kcore_close:
1963         kcore__close(&kcore);
1964
1965         return err;
1966 }
1967
1968 void kcore_extract__delete(struct kcore_extract *kce)
1969 {
1970         unlink(kce->extract_filename);
1971 }
1972
1973 #ifdef HAVE_GELF_GETNOTE_SUPPORT
1974 /**
1975  * populate_sdt_note : Parse raw data and identify SDT note
1976  * @elf: elf of the opened file
1977  * @data: raw data of a section with description offset applied
1978  * @len: note description size
1979  * @type: type of the note
1980  * @sdt_notes: List to add the SDT note
1981  *
1982  * Responsible for parsing the @data in section .note.stapsdt in @elf and
1983  * if its an SDT note, it appends to @sdt_notes list.
1984  */
1985 static int populate_sdt_note(Elf **elf, const char *data, size_t len,
1986                              struct list_head *sdt_notes)
1987 {
1988         const char *provider, *name, *args;
1989         struct sdt_note *tmp = NULL;
1990         GElf_Ehdr ehdr;
1991         GElf_Addr base_off = 0;
1992         GElf_Shdr shdr;
1993         int ret = -EINVAL;
1994
1995         union {
1996                 Elf64_Addr a64[NR_ADDR];
1997                 Elf32_Addr a32[NR_ADDR];
1998         } buf;
1999
2000         Elf_Data dst = {
2001                 .d_buf = &buf, .d_type = ELF_T_ADDR, .d_version = EV_CURRENT,
2002                 .d_size = gelf_fsize((*elf), ELF_T_ADDR, NR_ADDR, EV_CURRENT),
2003                 .d_off = 0, .d_align = 0
2004         };
2005         Elf_Data src = {
2006                 .d_buf = (void *) data, .d_type = ELF_T_ADDR,
2007                 .d_version = EV_CURRENT, .d_size = dst.d_size, .d_off = 0,
2008                 .d_align = 0
2009         };
2010
2011         tmp = (struct sdt_note *)calloc(1, sizeof(struct sdt_note));
2012         if (!tmp) {
2013                 ret = -ENOMEM;
2014                 goto out_err;
2015         }
2016
2017         INIT_LIST_HEAD(&tmp->note_list);
2018
2019         if (len < dst.d_size + 3)
2020                 goto out_free_note;
2021
2022         /* Translation from file representation to memory representation */
2023         if (gelf_xlatetom(*elf, &dst, &src,
2024                           elf_getident(*elf, NULL)[EI_DATA]) == NULL) {
2025                 pr_err("gelf_xlatetom : %s\n", elf_errmsg(-1));
2026                 goto out_free_note;
2027         }
2028
2029         /* Populate the fields of sdt_note */
2030         provider = data + dst.d_size;
2031
2032         name = (const char *)memchr(provider, '\0', data + len - provider);
2033         if (name++ == NULL)
2034                 goto out_free_note;
2035
2036         tmp->provider = strdup(provider);
2037         if (!tmp->provider) {
2038                 ret = -ENOMEM;
2039                 goto out_free_note;
2040         }
2041         tmp->name = strdup(name);
2042         if (!tmp->name) {
2043                 ret = -ENOMEM;
2044                 goto out_free_prov;
2045         }
2046
2047         args = memchr(name, '\0', data + len - name);
2048
2049         /*
2050          * There is no argument if:
2051          * - We reached the end of the note;
2052          * - There is not enough room to hold a potential string;
2053          * - The argument string is empty or just contains ':'.
2054          */
2055         if (args == NULL || data + len - args < 2 ||
2056                 args[1] == ':' || args[1] == '\0')
2057                 tmp->args = NULL;
2058         else {
2059                 tmp->args = strdup(++args);
2060                 if (!tmp->args) {
2061                         ret = -ENOMEM;
2062                         goto out_free_name;
2063                 }
2064         }
2065
2066         if (gelf_getclass(*elf) == ELFCLASS32) {
2067                 memcpy(&tmp->addr, &buf, 3 * sizeof(Elf32_Addr));
2068                 tmp->bit32 = true;
2069         } else {
2070                 memcpy(&tmp->addr, &buf, 3 * sizeof(Elf64_Addr));
2071                 tmp->bit32 = false;
2072         }
2073
2074         if (!gelf_getehdr(*elf, &ehdr)) {
2075                 pr_debug("%s : cannot get elf header.\n", __func__);
2076                 ret = -EBADF;
2077                 goto out_free_args;
2078         }
2079
2080         /* Adjust the prelink effect :
2081          * Find out the .stapsdt.base section.
2082          * This scn will help us to handle prelinking (if present).
2083          * Compare the retrieved file offset of the base section with the
2084          * base address in the description of the SDT note. If its different,
2085          * then accordingly, adjust the note location.
2086          */
2087         if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_BASE_SCN, NULL)) {
2088                 base_off = shdr.sh_offset;
2089                 if (base_off) {
2090                         if (tmp->bit32)
2091                                 tmp->addr.a32[0] = tmp->addr.a32[0] + base_off -
2092                                         tmp->addr.a32[1];
2093                         else
2094                                 tmp->addr.a64[0] = tmp->addr.a64[0] + base_off -
2095                                         tmp->addr.a64[1];
2096                 }
2097         }
2098
2099         list_add_tail(&tmp->note_list, sdt_notes);
2100         return 0;
2101
2102 out_free_args:
2103         free(tmp->args);
2104 out_free_name:
2105         free(tmp->name);
2106 out_free_prov:
2107         free(tmp->provider);
2108 out_free_note:
2109         free(tmp);
2110 out_err:
2111         return ret;
2112 }
2113
2114 /**
2115  * construct_sdt_notes_list : constructs a list of SDT notes
2116  * @elf : elf to look into
2117  * @sdt_notes : empty list_head
2118  *
2119  * Scans the sections in 'elf' for the section
2120  * .note.stapsdt. It, then calls populate_sdt_note to find
2121  * out the SDT events and populates the 'sdt_notes'.
2122  */
2123 static int construct_sdt_notes_list(Elf *elf, struct list_head *sdt_notes)
2124 {
2125         GElf_Ehdr ehdr;
2126         Elf_Scn *scn = NULL;
2127         Elf_Data *data;
2128         GElf_Shdr shdr;
2129         size_t shstrndx, next;
2130         GElf_Nhdr nhdr;
2131         size_t name_off, desc_off, offset;
2132         int ret = 0;
2133
2134         if (gelf_getehdr(elf, &ehdr) == NULL) {
2135                 ret = -EBADF;
2136                 goto out_ret;
2137         }
2138         if (elf_getshdrstrndx(elf, &shstrndx) != 0) {
2139                 ret = -EBADF;
2140                 goto out_ret;
2141         }
2142
2143         /* Look for the required section */
2144         scn = elf_section_by_name(elf, &ehdr, &shdr, SDT_NOTE_SCN, NULL);
2145         if (!scn) {
2146                 ret = -ENOENT;
2147                 goto out_ret;
2148         }
2149
2150         if ((shdr.sh_type != SHT_NOTE) || (shdr.sh_flags & SHF_ALLOC)) {
2151                 ret = -ENOENT;
2152                 goto out_ret;
2153         }
2154
2155         data = elf_getdata(scn, NULL);
2156
2157         /* Get the SDT notes */
2158         for (offset = 0; (next = gelf_getnote(data, offset, &nhdr, &name_off,
2159                                               &desc_off)) > 0; offset = next) {
2160                 if (nhdr.n_namesz == sizeof(SDT_NOTE_NAME) &&
2161                     !memcmp(data->d_buf + name_off, SDT_NOTE_NAME,
2162                             sizeof(SDT_NOTE_NAME))) {
2163                         /* Check the type of the note */
2164                         if (nhdr.n_type != SDT_NOTE_TYPE)
2165                                 goto out_ret;
2166
2167                         ret = populate_sdt_note(&elf, ((data->d_buf) + desc_off),
2168                                                 nhdr.n_descsz, sdt_notes);
2169                         if (ret < 0)
2170                                 goto out_ret;
2171                 }
2172         }
2173         if (list_empty(sdt_notes))
2174                 ret = -ENOENT;
2175
2176 out_ret:
2177         return ret;
2178 }
2179
2180 /**
2181  * get_sdt_note_list : Wrapper to construct a list of sdt notes
2182  * @head : empty list_head
2183  * @target : file to find SDT notes from
2184  *
2185  * This opens the file, initializes
2186  * the ELF and then calls construct_sdt_notes_list.
2187  */
2188 int get_sdt_note_list(struct list_head *head, const char *target)
2189 {
2190         Elf *elf;
2191         int fd, ret;
2192
2193         fd = open(target, O_RDONLY);
2194         if (fd < 0)
2195                 return -EBADF;
2196
2197         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
2198         if (!elf) {
2199                 ret = -EBADF;
2200                 goto out_close;
2201         }
2202         ret = construct_sdt_notes_list(elf, head);
2203         elf_end(elf);
2204 out_close:
2205         close(fd);
2206         return ret;
2207 }
2208
2209 /**
2210  * cleanup_sdt_note_list : free the sdt notes' list
2211  * @sdt_notes: sdt notes' list
2212  *
2213  * Free up the SDT notes in @sdt_notes.
2214  * Returns the number of SDT notes free'd.
2215  */
2216 int cleanup_sdt_note_list(struct list_head *sdt_notes)
2217 {
2218         struct sdt_note *tmp, *pos;
2219         int nr_free = 0;
2220
2221         list_for_each_entry_safe(pos, tmp, sdt_notes, note_list) {
2222                 list_del(&pos->note_list);
2223                 free(pos->name);
2224                 free(pos->provider);
2225                 free(pos);
2226                 nr_free++;
2227         }
2228         return nr_free;
2229 }
2230
2231 /**
2232  * sdt_notes__get_count: Counts the number of sdt events
2233  * @start: list_head to sdt_notes list
2234  *
2235  * Returns the number of SDT notes in a list
2236  */
2237 int sdt_notes__get_count(struct list_head *start)
2238 {
2239         struct sdt_note *sdt_ptr;
2240         int count = 0;
2241
2242         list_for_each_entry(sdt_ptr, start, note_list)
2243                 count++;
2244         return count;
2245 }
2246 #endif
2247
2248 void symbol__elf_init(void)
2249 {
2250         elf_version(EV_CURRENT);
2251 }