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