GNU Linux-libre 4.4.292-gnu1
[releases.git] / tools / perf / util / symbol-elf.c
1 #include <fcntl.h>
2 #include <stdio.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <inttypes.h>
7
8 #include "symbol.h"
9 #include "machine.h"
10 #include "vdso.h"
11 #include <symbol/kallsyms.h>
12 #include "debug.h"
13
14 #ifndef EM_AARCH64
15 #define EM_AARCH64      183  /* ARM 64 bit */
16 #endif
17
18
19 #ifdef HAVE_CPLUS_DEMANGLE_SUPPORT
20 extern char *cplus_demangle(const char *, int);
21
22 static inline char *bfd_demangle(void __maybe_unused *v, const char *c, int i)
23 {
24         return cplus_demangle(c, i);
25 }
26 #else
27 #ifdef NO_DEMANGLE
28 static inline char *bfd_demangle(void __maybe_unused *v,
29                                  const char __maybe_unused *c,
30                                  int __maybe_unused i)
31 {
32         return NULL;
33 }
34 #else
35 #define PACKAGE 'perf'
36 #include <bfd.h>
37 #endif
38 #endif
39
40 #ifndef HAVE_ELF_GETPHDRNUM_SUPPORT
41 static int elf_getphdrnum(Elf *elf, size_t *dst)
42 {
43         GElf_Ehdr gehdr;
44         GElf_Ehdr *ehdr;
45
46         ehdr = gelf_getehdr(elf, &gehdr);
47         if (!ehdr)
48                 return -1;
49
50         *dst = ehdr->e_phnum;
51
52         return 0;
53 }
54 #endif
55
56 #ifndef NT_GNU_BUILD_ID
57 #define NT_GNU_BUILD_ID 3
58 #endif
59
60 /**
61  * elf_symtab__for_each_symbol - iterate thru all the symbols
62  *
63  * @syms: struct elf_symtab instance to iterate
64  * @idx: uint32_t idx
65  * @sym: GElf_Sym iterator
66  */
67 #define elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) \
68         for (idx = 0, gelf_getsym(syms, idx, &sym);\
69              idx < nr_syms; \
70              idx++, gelf_getsym(syms, idx, &sym))
71
72 static inline uint8_t elf_sym__type(const GElf_Sym *sym)
73 {
74         return GELF_ST_TYPE(sym->st_info);
75 }
76
77 static inline uint8_t elf_sym__visibility(const GElf_Sym *sym)
78 {
79         return GELF_ST_VISIBILITY(sym->st_other);
80 }
81
82 #ifndef STT_GNU_IFUNC
83 #define STT_GNU_IFUNC 10
84 #endif
85
86 static inline int elf_sym__is_function(const GElf_Sym *sym)
87 {
88         return (elf_sym__type(sym) == STT_FUNC ||
89                 elf_sym__type(sym) == STT_GNU_IFUNC) &&
90                sym->st_name != 0 &&
91                sym->st_shndx != SHN_UNDEF;
92 }
93
94 static inline bool elf_sym__is_object(const GElf_Sym *sym)
95 {
96         return elf_sym__type(sym) == STT_OBJECT &&
97                 sym->st_name != 0 &&
98                 sym->st_shndx != SHN_UNDEF;
99 }
100
101 static inline int elf_sym__is_label(const GElf_Sym *sym)
102 {
103         return elf_sym__type(sym) == STT_NOTYPE &&
104                 sym->st_name != 0 &&
105                 sym->st_shndx != SHN_UNDEF &&
106                 sym->st_shndx != SHN_ABS &&
107                 elf_sym__visibility(sym) != STV_HIDDEN &&
108                 elf_sym__visibility(sym) != STV_INTERNAL;
109 }
110
111 static bool elf_sym__is_a(GElf_Sym *sym, enum map_type type)
112 {
113         switch (type) {
114         case MAP__FUNCTION:
115                 return elf_sym__is_function(sym);
116         case MAP__VARIABLE:
117                 return elf_sym__is_object(sym);
118         default:
119                 return false;
120         }
121 }
122
123 static inline const char *elf_sym__name(const GElf_Sym *sym,
124                                         const Elf_Data *symstrs)
125 {
126         return symstrs->d_buf + sym->st_name;
127 }
128
129 static inline const char *elf_sec__name(const GElf_Shdr *shdr,
130                                         const Elf_Data *secstrs)
131 {
132         return secstrs->d_buf + shdr->sh_name;
133 }
134
135 static inline int elf_sec__is_text(const GElf_Shdr *shdr,
136                                         const Elf_Data *secstrs)
137 {
138         return strstr(elf_sec__name(shdr, secstrs), "text") != NULL;
139 }
140
141 static inline bool elf_sec__is_data(const GElf_Shdr *shdr,
142                                     const Elf_Data *secstrs)
143 {
144         return strstr(elf_sec__name(shdr, secstrs), "data") != NULL;
145 }
146
147 static bool elf_sec__is_a(GElf_Shdr *shdr, Elf_Data *secstrs,
148                           enum map_type type)
149 {
150         switch (type) {
151         case MAP__FUNCTION:
152                 return elf_sec__is_text(shdr, secstrs);
153         case MAP__VARIABLE:
154                 return elf_sec__is_data(shdr, secstrs);
155         default:
156                 return false;
157         }
158 }
159
160 static size_t elf_addr_to_index(Elf *elf, GElf_Addr addr)
161 {
162         Elf_Scn *sec = NULL;
163         GElf_Shdr shdr;
164         size_t cnt = 1;
165
166         while ((sec = elf_nextscn(elf, sec)) != NULL) {
167                 gelf_getshdr(sec, &shdr);
168
169                 if ((addr >= shdr.sh_addr) &&
170                     (addr < (shdr.sh_addr + shdr.sh_size)))
171                         return cnt;
172
173                 ++cnt;
174         }
175
176         return -1;
177 }
178
179 Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
180                              GElf_Shdr *shp, const char *name, size_t *idx)
181 {
182         Elf_Scn *sec = NULL;
183         size_t cnt = 1;
184
185         /* Elf is corrupted/truncated, avoid calling elf_strptr. */
186         if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL))
187                 return NULL;
188
189         while ((sec = elf_nextscn(elf, sec)) != NULL) {
190                 char *str;
191
192                 gelf_getshdr(sec, shp);
193                 str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
194                 if (str && !strcmp(name, str)) {
195                         if (idx)
196                                 *idx = cnt;
197                         return sec;
198                 }
199                 ++cnt;
200         }
201
202         return NULL;
203 }
204
205 #define elf_section__for_each_rel(reldata, pos, pos_mem, idx, nr_entries) \
206         for (idx = 0, pos = gelf_getrel(reldata, 0, &pos_mem); \
207              idx < nr_entries; \
208              ++idx, pos = gelf_getrel(reldata, idx, &pos_mem))
209
210 #define elf_section__for_each_rela(reldata, pos, pos_mem, idx, nr_entries) \
211         for (idx = 0, pos = gelf_getrela(reldata, 0, &pos_mem); \
212              idx < nr_entries; \
213              ++idx, pos = gelf_getrela(reldata, idx, &pos_mem))
214
215 /*
216  * We need to check if we have a .dynsym, so that we can handle the
217  * .plt, synthesizing its symbols, that aren't on the symtabs (be it
218  * .dynsym or .symtab).
219  * And always look at the original dso, not at debuginfo packages, that
220  * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
221  */
222 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss, struct map *map,
223                                 symbol_filter_t filter)
224 {
225         uint32_t nr_rel_entries, idx;
226         GElf_Sym sym;
227         u64 plt_offset;
228         GElf_Shdr shdr_plt;
229         struct symbol *f;
230         GElf_Shdr shdr_rel_plt, shdr_dynsym;
231         Elf_Data *reldata, *syms, *symstrs;
232         Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
233         size_t dynsym_idx;
234         GElf_Ehdr ehdr;
235         char sympltname[1024];
236         Elf *elf;
237         int nr = 0, symidx, err = 0;
238
239         if (!ss->dynsym)
240                 return 0;
241
242         elf = ss->elf;
243         ehdr = ss->ehdr;
244
245         scn_dynsym = ss->dynsym;
246         shdr_dynsym = ss->dynshdr;
247         dynsym_idx = ss->dynsym_idx;
248
249         if (scn_dynsym == NULL)
250                 goto out_elf_end;
251
252         scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
253                                           ".rela.plt", NULL);
254         if (scn_plt_rel == NULL) {
255                 scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
256                                                   ".rel.plt", NULL);
257                 if (scn_plt_rel == NULL)
258                         goto out_elf_end;
259         }
260
261         err = -1;
262
263         if (shdr_rel_plt.sh_link != dynsym_idx)
264                 goto out_elf_end;
265
266         if (elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL) == NULL)
267                 goto out_elf_end;
268
269         /*
270          * Fetch the relocation section to find the idxes to the GOT
271          * and the symbols in the .dynsym they refer to.
272          */
273         reldata = elf_getdata(scn_plt_rel, NULL);
274         if (reldata == NULL)
275                 goto out_elf_end;
276
277         syms = elf_getdata(scn_dynsym, NULL);
278         if (syms == NULL)
279                 goto out_elf_end;
280
281         scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
282         if (scn_symstrs == NULL)
283                 goto out_elf_end;
284
285         symstrs = elf_getdata(scn_symstrs, NULL);
286         if (symstrs == NULL)
287                 goto out_elf_end;
288
289         if (symstrs->d_size == 0)
290                 goto out_elf_end;
291
292         nr_rel_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
293         plt_offset = shdr_plt.sh_offset;
294
295         if (shdr_rel_plt.sh_type == SHT_RELA) {
296                 GElf_Rela pos_mem, *pos;
297
298                 elf_section__for_each_rela(reldata, pos, pos_mem, idx,
299                                            nr_rel_entries) {
300                         symidx = GELF_R_SYM(pos->r_info);
301                         plt_offset += shdr_plt.sh_entsize;
302                         gelf_getsym(syms, symidx, &sym);
303                         snprintf(sympltname, sizeof(sympltname),
304                                  "%s@plt", elf_sym__name(&sym, symstrs));
305
306                         f = symbol__new(plt_offset, shdr_plt.sh_entsize,
307                                         STB_GLOBAL, sympltname);
308                         if (!f)
309                                 goto out_elf_end;
310
311                         if (filter && filter(map, f))
312                                 symbol__delete(f);
313                         else {
314                                 symbols__insert(&dso->symbols[map->type], f);
315                                 ++nr;
316                         }
317                 }
318         } else if (shdr_rel_plt.sh_type == SHT_REL) {
319                 GElf_Rel pos_mem, *pos;
320                 elf_section__for_each_rel(reldata, pos, pos_mem, idx,
321                                           nr_rel_entries) {
322                         symidx = GELF_R_SYM(pos->r_info);
323                         plt_offset += shdr_plt.sh_entsize;
324                         gelf_getsym(syms, symidx, &sym);
325                         snprintf(sympltname, sizeof(sympltname),
326                                  "%s@plt", elf_sym__name(&sym, symstrs));
327
328                         f = symbol__new(plt_offset, shdr_plt.sh_entsize,
329                                         STB_GLOBAL, sympltname);
330                         if (!f)
331                                 goto out_elf_end;
332
333                         if (filter && filter(map, f))
334                                 symbol__delete(f);
335                         else {
336                                 symbols__insert(&dso->symbols[map->type], f);
337                                 ++nr;
338                         }
339                 }
340         }
341
342         err = 0;
343 out_elf_end:
344         if (err == 0)
345                 return nr;
346         pr_debug("%s: problems reading %s PLT info.\n",
347                  __func__, dso->long_name);
348         return 0;
349 }
350
351 /*
352  * Align offset to 4 bytes as needed for note name and descriptor data.
353  */
354 #define NOTE_ALIGN(n) (((n) + 3) & -4U)
355
356 static int elf_read_build_id(Elf *elf, void *bf, size_t size)
357 {
358         int err = -1;
359         GElf_Ehdr ehdr;
360         GElf_Shdr shdr;
361         Elf_Data *data;
362         Elf_Scn *sec;
363         Elf_Kind ek;
364         void *ptr;
365
366         if (size < BUILD_ID_SIZE)
367                 goto out;
368
369         ek = elf_kind(elf);
370         if (ek != ELF_K_ELF)
371                 goto out;
372
373         if (gelf_getehdr(elf, &ehdr) == NULL) {
374                 pr_err("%s: cannot get elf header.\n", __func__);
375                 goto out;
376         }
377
378         /*
379          * Check following sections for notes:
380          *   '.note.gnu.build-id'
381          *   '.notes'
382          *   '.note' (VDSO specific)
383          */
384         do {
385                 sec = elf_section_by_name(elf, &ehdr, &shdr,
386                                           ".note.gnu.build-id", NULL);
387                 if (sec)
388                         break;
389
390                 sec = elf_section_by_name(elf, &ehdr, &shdr,
391                                           ".notes", NULL);
392                 if (sec)
393                         break;
394
395                 sec = elf_section_by_name(elf, &ehdr, &shdr,
396                                           ".note", NULL);
397                 if (sec)
398                         break;
399
400                 return err;
401
402         } while (0);
403
404         data = elf_getdata(sec, NULL);
405         if (data == NULL)
406                 goto out;
407
408         ptr = data->d_buf;
409         while (ptr < (data->d_buf + data->d_size)) {
410                 GElf_Nhdr *nhdr = ptr;
411                 size_t namesz = NOTE_ALIGN(nhdr->n_namesz),
412                        descsz = NOTE_ALIGN(nhdr->n_descsz);
413                 const char *name;
414
415                 ptr += sizeof(*nhdr);
416                 name = ptr;
417                 ptr += namesz;
418                 if (nhdr->n_type == NT_GNU_BUILD_ID &&
419                     nhdr->n_namesz == sizeof("GNU")) {
420                         if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
421                                 size_t sz = min(size, descsz);
422                                 memcpy(bf, ptr, sz);
423                                 memset(bf + sz, 0, size - sz);
424                                 err = descsz;
425                                 break;
426                         }
427                 }
428                 ptr += descsz;
429         }
430
431 out:
432         return err;
433 }
434
435 int filename__read_build_id(const char *filename, void *bf, size_t size)
436 {
437         int fd, err = -1;
438         Elf *elf;
439
440         if (size < BUILD_ID_SIZE)
441                 goto out;
442
443         fd = open(filename, O_RDONLY);
444         if (fd < 0)
445                 goto out;
446
447         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
448         if (elf == NULL) {
449                 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
450                 goto out_close;
451         }
452
453         err = elf_read_build_id(elf, bf, size);
454
455         elf_end(elf);
456 out_close:
457         close(fd);
458 out:
459         return err;
460 }
461
462 int sysfs__read_build_id(const char *filename, void *build_id, size_t size)
463 {
464         int fd, err = -1;
465
466         if (size < BUILD_ID_SIZE)
467                 goto out;
468
469         fd = open(filename, O_RDONLY);
470         if (fd < 0)
471                 goto out;
472
473         while (1) {
474                 char bf[BUFSIZ];
475                 GElf_Nhdr nhdr;
476                 size_t namesz, descsz;
477
478                 if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
479                         break;
480
481                 namesz = NOTE_ALIGN(nhdr.n_namesz);
482                 descsz = NOTE_ALIGN(nhdr.n_descsz);
483                 if (nhdr.n_type == NT_GNU_BUILD_ID &&
484                     nhdr.n_namesz == sizeof("GNU")) {
485                         if (read(fd, bf, namesz) != (ssize_t)namesz)
486                                 break;
487                         if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
488                                 size_t sz = min(descsz, size);
489                                 if (read(fd, build_id, sz) == (ssize_t)sz) {
490                                         memset(build_id + sz, 0, size - sz);
491                                         err = 0;
492                                         break;
493                                 }
494                         } else if (read(fd, bf, descsz) != (ssize_t)descsz)
495                                 break;
496                 } else {
497                         int n = namesz + descsz;
498
499                         if (n > (int)sizeof(bf)) {
500                                 n = sizeof(bf);
501                                 pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
502                                          __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
503                         }
504                         if (read(fd, bf, n) != n)
505                                 break;
506                 }
507         }
508         close(fd);
509 out:
510         return err;
511 }
512
513 int filename__read_debuglink(const char *filename, char *debuglink,
514                              size_t size)
515 {
516         int fd, err = -1;
517         Elf *elf;
518         GElf_Ehdr ehdr;
519         GElf_Shdr shdr;
520         Elf_Data *data;
521         Elf_Scn *sec;
522         Elf_Kind ek;
523
524         fd = open(filename, O_RDONLY);
525         if (fd < 0)
526                 goto out;
527
528         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
529         if (elf == NULL) {
530                 pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
531                 goto out_close;
532         }
533
534         ek = elf_kind(elf);
535         if (ek != ELF_K_ELF)
536                 goto out_elf_end;
537
538         if (gelf_getehdr(elf, &ehdr) == NULL) {
539                 pr_err("%s: cannot get elf header.\n", __func__);
540                 goto out_elf_end;
541         }
542
543         sec = elf_section_by_name(elf, &ehdr, &shdr,
544                                   ".gnu_debuglink", NULL);
545         if (sec == NULL)
546                 goto out_elf_end;
547
548         data = elf_getdata(sec, NULL);
549         if (data == NULL)
550                 goto out_elf_end;
551
552         /* the start of this section is a zero-terminated string */
553         strncpy(debuglink, data->d_buf, size);
554
555         err = 0;
556
557 out_elf_end:
558         elf_end(elf);
559 out_close:
560         close(fd);
561 out:
562         return err;
563 }
564
565 static int dso__swap_init(struct dso *dso, unsigned char eidata)
566 {
567         static unsigned int const endian = 1;
568
569         dso->needs_swap = DSO_SWAP__NO;
570
571         switch (eidata) {
572         case ELFDATA2LSB:
573                 /* We are big endian, DSO is little endian. */
574                 if (*(unsigned char const *)&endian != 1)
575                         dso->needs_swap = DSO_SWAP__YES;
576                 break;
577
578         case ELFDATA2MSB:
579                 /* We are little endian, DSO is big endian. */
580                 if (*(unsigned char const *)&endian != 0)
581                         dso->needs_swap = DSO_SWAP__YES;
582                 break;
583
584         default:
585                 pr_err("unrecognized DSO data encoding %d\n", eidata);
586                 return -EINVAL;
587         }
588
589         return 0;
590 }
591
592 static int decompress_kmodule(struct dso *dso, const char *name,
593                               enum dso_binary_type type)
594 {
595         int fd = -1;
596         char tmpbuf[] = "/tmp/perf-kmod-XXXXXX";
597         struct kmod_path m;
598
599         if (type != DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP &&
600             type != DSO_BINARY_TYPE__GUEST_KMODULE_COMP &&
601             type != DSO_BINARY_TYPE__BUILD_ID_CACHE)
602                 return -1;
603
604         if (type == DSO_BINARY_TYPE__BUILD_ID_CACHE)
605                 name = dso->long_name;
606
607         if (kmod_path__parse_ext(&m, name) || !m.comp)
608                 return -1;
609
610         fd = mkstemp(tmpbuf);
611         if (fd < 0) {
612                 dso->load_errno = errno;
613                 goto out;
614         }
615
616         if (!decompress_to_file(m.ext, name, fd)) {
617                 dso->load_errno = DSO_LOAD_ERRNO__DECOMPRESSION_FAILURE;
618                 close(fd);
619                 fd = -1;
620         }
621
622         unlink(tmpbuf);
623
624 out:
625         free(m.ext);
626         return fd;
627 }
628
629 bool symsrc__possibly_runtime(struct symsrc *ss)
630 {
631         return ss->dynsym || ss->opdsec;
632 }
633
634 bool symsrc__has_symtab(struct symsrc *ss)
635 {
636         return ss->symtab != NULL;
637 }
638
639 void symsrc__destroy(struct symsrc *ss)
640 {
641         zfree(&ss->name);
642         elf_end(ss->elf);
643         close(ss->fd);
644 }
645
646 bool __weak elf__needs_adjust_symbols(GElf_Ehdr ehdr)
647 {
648         return ehdr.e_type == ET_EXEC || ehdr.e_type == ET_REL;
649 }
650
651 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
652                  enum dso_binary_type type)
653 {
654         int err = -1;
655         GElf_Ehdr ehdr;
656         Elf *elf;
657         int fd;
658
659         if (dso__needs_decompress(dso)) {
660                 fd = decompress_kmodule(dso, name, type);
661                 if (fd < 0)
662                         return -1;
663         } else {
664                 fd = open(name, O_RDONLY);
665                 if (fd < 0) {
666                         dso->load_errno = errno;
667                         return -1;
668                 }
669         }
670
671         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
672         if (elf == NULL) {
673                 pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
674                 dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
675                 goto out_close;
676         }
677
678         if (gelf_getehdr(elf, &ehdr) == NULL) {
679                 dso->load_errno = DSO_LOAD_ERRNO__INVALID_ELF;
680                 pr_debug("%s: cannot get elf header.\n", __func__);
681                 goto out_elf_end;
682         }
683
684         if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
685                 dso->load_errno = DSO_LOAD_ERRNO__INTERNAL_ERROR;
686                 goto out_elf_end;
687         }
688
689         /* Always reject images with a mismatched build-id: */
690         if (dso->has_build_id) {
691                 u8 build_id[BUILD_ID_SIZE];
692
693                 if (elf_read_build_id(elf, build_id, BUILD_ID_SIZE) < 0) {
694                         dso->load_errno = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
695                         goto out_elf_end;
696                 }
697
698                 if (!dso__build_id_equal(dso, build_id)) {
699                         pr_debug("%s: build id mismatch for %s.\n", __func__, name);
700                         dso->load_errno = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
701                         goto out_elf_end;
702                 }
703         }
704
705         ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
706
707         ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
708                         NULL);
709         if (ss->symshdr.sh_type != SHT_SYMTAB)
710                 ss->symtab = NULL;
711
712         ss->dynsym_idx = 0;
713         ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
714                         &ss->dynsym_idx);
715         if (ss->dynshdr.sh_type != SHT_DYNSYM)
716                 ss->dynsym = NULL;
717
718         ss->opdidx = 0;
719         ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
720                         &ss->opdidx);
721         if (ss->opdshdr.sh_type != SHT_PROGBITS)
722                 ss->opdsec = NULL;
723
724         if (dso->kernel == DSO_TYPE_USER) {
725                 GElf_Shdr shdr;
726                 ss->adjust_symbols = (ehdr.e_type == ET_EXEC ||
727                                 ehdr.e_type == ET_REL ||
728                                 dso__is_vdso(dso) ||
729                                 elf_section_by_name(elf, &ehdr, &shdr,
730                                                      ".gnu.prelink_undo",
731                                                      NULL) != NULL);
732         } else {
733                 ss->adjust_symbols = elf__needs_adjust_symbols(ehdr);
734         }
735
736         ss->name   = strdup(name);
737         if (!ss->name) {
738                 dso->load_errno = errno;
739                 goto out_elf_end;
740         }
741
742         ss->elf    = elf;
743         ss->fd     = fd;
744         ss->ehdr   = ehdr;
745         ss->type   = type;
746
747         return 0;
748
749 out_elf_end:
750         elf_end(elf);
751 out_close:
752         close(fd);
753         return err;
754 }
755
756 /**
757  * ref_reloc_sym_not_found - has kernel relocation symbol been found.
758  * @kmap: kernel maps and relocation reference symbol
759  *
760  * This function returns %true if we are dealing with the kernel maps and the
761  * relocation reference symbol has not yet been found.  Otherwise %false is
762  * returned.
763  */
764 static bool ref_reloc_sym_not_found(struct kmap *kmap)
765 {
766         return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
767                !kmap->ref_reloc_sym->unrelocated_addr;
768 }
769
770 /**
771  * ref_reloc - kernel relocation offset.
772  * @kmap: kernel maps and relocation reference symbol
773  *
774  * This function returns the offset of kernel addresses as determined by using
775  * the relocation reference symbol i.e. if the kernel has not been relocated
776  * then the return value is zero.
777  */
778 static u64 ref_reloc(struct kmap *kmap)
779 {
780         if (kmap && kmap->ref_reloc_sym &&
781             kmap->ref_reloc_sym->unrelocated_addr)
782                 return kmap->ref_reloc_sym->addr -
783                        kmap->ref_reloc_sym->unrelocated_addr;
784         return 0;
785 }
786
787 static bool want_demangle(bool is_kernel_sym)
788 {
789         return is_kernel_sym ? symbol_conf.demangle_kernel : symbol_conf.demangle;
790 }
791
792 void __weak arch__elf_sym_adjust(GElf_Sym *sym __maybe_unused) { }
793
794 int dso__load_sym(struct dso *dso, struct map *map,
795                   struct symsrc *syms_ss, struct symsrc *runtime_ss,
796                   symbol_filter_t filter, int kmodule)
797 {
798         struct kmap *kmap = dso->kernel ? map__kmap(map) : NULL;
799         struct map_groups *kmaps = kmap ? map__kmaps(map) : NULL;
800         struct map *curr_map = map;
801         struct dso *curr_dso = dso;
802         Elf_Data *symstrs, *secstrs;
803         uint32_t nr_syms;
804         int err = -1;
805         uint32_t idx;
806         GElf_Ehdr ehdr;
807         GElf_Shdr shdr;
808         Elf_Data *syms, *opddata = NULL;
809         GElf_Sym sym;
810         Elf_Scn *sec, *sec_strndx;
811         Elf *elf;
812         int nr = 0;
813         bool remap_kernel = false, adjust_kernel_syms = false;
814
815         if (kmap && !kmaps)
816                 return -1;
817
818         dso->symtab_type = syms_ss->type;
819         dso->is_64_bit = syms_ss->is_64_bit;
820         dso->rel = syms_ss->ehdr.e_type == ET_REL;
821
822         /*
823          * Modules may already have symbols from kallsyms, but those symbols
824          * have the wrong values for the dso maps, so remove them.
825          */
826         if (kmodule && syms_ss->symtab)
827                 symbols__delete(&dso->symbols[map->type]);
828
829         if (!syms_ss->symtab) {
830                 /*
831                  * If the vmlinux is stripped, fail so we will fall back
832                  * to using kallsyms. The vmlinux runtime symbols aren't
833                  * of much use.
834                  */
835                 if (dso->kernel)
836                         goto out_elf_end;
837
838                 syms_ss->symtab  = syms_ss->dynsym;
839                 syms_ss->symshdr = syms_ss->dynshdr;
840         }
841
842         elf = syms_ss->elf;
843         ehdr = syms_ss->ehdr;
844         sec = syms_ss->symtab;
845         shdr = syms_ss->symshdr;
846
847         if (runtime_ss->opdsec)
848                 opddata = elf_rawdata(runtime_ss->opdsec, NULL);
849
850         syms = elf_getdata(sec, NULL);
851         if (syms == NULL)
852                 goto out_elf_end;
853
854         sec = elf_getscn(elf, shdr.sh_link);
855         if (sec == NULL)
856                 goto out_elf_end;
857
858         symstrs = elf_getdata(sec, NULL);
859         if (symstrs == NULL)
860                 goto out_elf_end;
861
862         sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
863         if (sec_strndx == NULL)
864                 goto out_elf_end;
865
866         secstrs = elf_getdata(sec_strndx, NULL);
867         if (secstrs == NULL)
868                 goto out_elf_end;
869
870         nr_syms = shdr.sh_size / shdr.sh_entsize;
871
872         memset(&sym, 0, sizeof(sym));
873
874         /*
875          * The kernel relocation symbol is needed in advance in order to adjust
876          * kernel maps correctly.
877          */
878         if (ref_reloc_sym_not_found(kmap)) {
879                 elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
880                         const char *elf_name = elf_sym__name(&sym, symstrs);
881
882                         if (strcmp(elf_name, kmap->ref_reloc_sym->name))
883                                 continue;
884                         kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
885                         map->reloc = kmap->ref_reloc_sym->addr -
886                                      kmap->ref_reloc_sym->unrelocated_addr;
887                         break;
888                 }
889         }
890
891         /*
892          * Handle any relocation of vdso necessary because older kernels
893          * attempted to prelink vdso to its virtual address.
894          */
895         if (dso__is_vdso(dso)) {
896                 GElf_Shdr tshdr;
897
898                 if (elf_section_by_name(elf, &ehdr, &tshdr, ".text", NULL))
899                         map->reloc = map->start - tshdr.sh_addr + tshdr.sh_offset;
900         }
901
902         dso->adjust_symbols = runtime_ss->adjust_symbols || ref_reloc(kmap);
903         /*
904          * Initial kernel and module mappings do not map to the dso.  For
905          * function mappings, flag the fixups.
906          */
907         if (map->type == MAP__FUNCTION && (dso->kernel || kmodule)) {
908                 remap_kernel = true;
909                 adjust_kernel_syms = dso->adjust_symbols;
910         }
911         elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
912                 struct symbol *f;
913                 const char *elf_name = elf_sym__name(&sym, symstrs);
914                 char *demangled = NULL;
915                 int is_label = elf_sym__is_label(&sym);
916                 const char *section_name;
917                 bool used_opd = false;
918
919                 if (!is_label && !elf_sym__is_a(&sym, map->type))
920                         continue;
921
922                 /* Reject ARM ELF "mapping symbols": these aren't unique and
923                  * don't identify functions, so will confuse the profile
924                  * output: */
925                 if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
926                         if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
927                             && (elf_name[2] == '\0' || elf_name[2] == '.'))
928                                 continue;
929                 }
930
931                 if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
932                         u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
933                         u64 *opd = opddata->d_buf + offset;
934                         sym.st_value = DSO__SWAP(dso, u64, *opd);
935                         sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
936                                         sym.st_value);
937                         used_opd = true;
938                 }
939                 /*
940                  * When loading symbols in a data mapping, ABS symbols (which
941                  * has a value of SHN_ABS in its st_shndx) failed at
942                  * elf_getscn().  And it marks the loading as a failure so
943                  * already loaded symbols cannot be fixed up.
944                  *
945                  * I'm not sure what should be done. Just ignore them for now.
946                  * - Namhyung Kim
947                  */
948                 if (sym.st_shndx == SHN_ABS)
949                         continue;
950
951                 sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
952                 if (!sec)
953                         goto out_elf_end;
954
955                 gelf_getshdr(sec, &shdr);
956
957                 if (is_label && !elf_sec__is_a(&shdr, secstrs, map->type))
958                         continue;
959
960                 section_name = elf_sec__name(&shdr, secstrs);
961
962                 /* On ARM, symbols for thumb functions have 1 added to
963                  * the symbol address as a flag - remove it */
964                 if ((ehdr.e_machine == EM_ARM) &&
965                     (map->type == MAP__FUNCTION) &&
966                     (sym.st_value & 1))
967                         --sym.st_value;
968
969                 arch__elf_sym_adjust(&sym);
970
971                 if (dso->kernel || kmodule) {
972                         char dso_name[PATH_MAX];
973
974                         /* Adjust symbol to map to file offset */
975                         if (adjust_kernel_syms)
976                                 sym.st_value -= shdr.sh_addr - shdr.sh_offset;
977
978                         if (strcmp(section_name,
979                                    (curr_dso->short_name +
980                                     dso->short_name_len)) == 0)
981                                 goto new_symbol;
982
983                         if (strcmp(section_name, ".text") == 0) {
984                                 /*
985                                  * The initial kernel mapping is based on
986                                  * kallsyms and identity maps.  Overwrite it to
987                                  * map to the kernel dso.
988                                  */
989                                 if (remap_kernel && dso->kernel) {
990                                         remap_kernel = false;
991                                         map->start = shdr.sh_addr +
992                                                      ref_reloc(kmap);
993                                         map->end = map->start + shdr.sh_size;
994                                         map->pgoff = shdr.sh_offset;
995                                         map->map_ip = map__map_ip;
996                                         map->unmap_ip = map__unmap_ip;
997                                         /* Ensure maps are correctly ordered */
998                                         if (kmaps) {
999                                                 map__get(map);
1000                                                 map_groups__remove(kmaps, map);
1001                                                 map_groups__insert(kmaps, map);
1002                                                 map__put(map);
1003                                         }
1004                                 }
1005
1006                                 /*
1007                                  * The initial module mapping is based on
1008                                  * /proc/modules mapped to offset zero.
1009                                  * Overwrite it to map to the module dso.
1010                                  */
1011                                 if (remap_kernel && kmodule) {
1012                                         remap_kernel = false;
1013                                         map->pgoff = shdr.sh_offset;
1014                                 }
1015
1016                                 curr_map = map;
1017                                 curr_dso = dso;
1018                                 goto new_symbol;
1019                         }
1020
1021                         if (!kmap)
1022                                 goto new_symbol;
1023
1024                         snprintf(dso_name, sizeof(dso_name),
1025                                  "%s%s", dso->short_name, section_name);
1026
1027                         curr_map = map_groups__find_by_name(kmaps, map->type, dso_name);
1028                         if (curr_map == NULL) {
1029                                 u64 start = sym.st_value;
1030
1031                                 if (kmodule)
1032                                         start += map->start + shdr.sh_offset;
1033
1034                                 curr_dso = dso__new(dso_name);
1035                                 if (curr_dso == NULL)
1036                                         goto out_elf_end;
1037                                 curr_dso->kernel = dso->kernel;
1038                                 curr_dso->long_name = dso->long_name;
1039                                 curr_dso->long_name_len = dso->long_name_len;
1040                                 curr_map = map__new2(start, curr_dso,
1041                                                      map->type);
1042                                 if (curr_map == NULL) {
1043                                         dso__put(curr_dso);
1044                                         goto out_elf_end;
1045                                 }
1046                                 if (adjust_kernel_syms) {
1047                                         curr_map->start = shdr.sh_addr +
1048                                                           ref_reloc(kmap);
1049                                         curr_map->end = curr_map->start +
1050                                                         shdr.sh_size;
1051                                         curr_map->pgoff = shdr.sh_offset;
1052                                 } else {
1053                                         curr_map->map_ip = identity__map_ip;
1054                                         curr_map->unmap_ip = identity__map_ip;
1055                                 }
1056                                 curr_dso->symtab_type = dso->symtab_type;
1057                                 map_groups__insert(kmaps, curr_map);
1058                                 dsos__add(&map->groups->machine->dsos, curr_dso);
1059                                 dso__set_loaded(curr_dso, map->type);
1060                         } else
1061                                 curr_dso = curr_map->dso;
1062
1063                         goto new_symbol;
1064                 }
1065
1066                 if ((used_opd && runtime_ss->adjust_symbols)
1067                                 || (!used_opd && syms_ss->adjust_symbols)) {
1068                         pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1069                                   "sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n", __func__,
1070                                   (u64)sym.st_value, (u64)shdr.sh_addr,
1071                                   (u64)shdr.sh_offset);
1072                         sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1073                 }
1074 new_symbol:
1075                 /*
1076                  * We need to figure out if the object was created from C++ sources
1077                  * DWARF DW_compile_unit has this, but we don't always have access
1078                  * to it...
1079                  */
1080                 if (want_demangle(dso->kernel || kmodule)) {
1081                         int demangle_flags = DMGL_NO_OPTS;
1082                         if (verbose)
1083                                 demangle_flags = DMGL_PARAMS | DMGL_ANSI;
1084
1085                         demangled = bfd_demangle(NULL, elf_name, demangle_flags);
1086                         if (demangled != NULL)
1087                                 elf_name = demangled;
1088                 }
1089                 f = symbol__new(sym.st_value, sym.st_size,
1090                                 GELF_ST_BIND(sym.st_info), elf_name);
1091                 free(demangled);
1092                 if (!f)
1093                         goto out_elf_end;
1094
1095                 if (filter && filter(curr_map, f))
1096                         symbol__delete(f);
1097                 else {
1098                         symbols__insert(&curr_dso->symbols[curr_map->type], f);
1099                         nr++;
1100                 }
1101         }
1102
1103         /*
1104          * For misannotated, zeroed, ASM function sizes.
1105          */
1106         if (nr > 0) {
1107                 symbols__fixup_end(&dso->symbols[map->type]);
1108                 symbols__fixup_duplicate(&dso->symbols[map->type]);
1109                 if (kmap) {
1110                         /*
1111                          * We need to fixup this here too because we create new
1112                          * maps here, for things like vsyscall sections.
1113                          */
1114                         __map_groups__fixup_end(kmaps, map->type);
1115                 }
1116         }
1117         err = nr;
1118 out_elf_end:
1119         return err;
1120 }
1121
1122 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1123 {
1124         GElf_Phdr phdr;
1125         size_t i, phdrnum;
1126         int err;
1127         u64 sz;
1128
1129         if (elf_getphdrnum(elf, &phdrnum))
1130                 return -1;
1131
1132         for (i = 0; i < phdrnum; i++) {
1133                 if (gelf_getphdr(elf, i, &phdr) == NULL)
1134                         return -1;
1135                 if (phdr.p_type != PT_LOAD)
1136                         continue;
1137                 if (exe) {
1138                         if (!(phdr.p_flags & PF_X))
1139                                 continue;
1140                 } else {
1141                         if (!(phdr.p_flags & PF_R))
1142                                 continue;
1143                 }
1144                 sz = min(phdr.p_memsz, phdr.p_filesz);
1145                 if (!sz)
1146                         continue;
1147                 err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1148                 if (err)
1149                         return err;
1150         }
1151         return 0;
1152 }
1153
1154 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1155                     bool *is_64_bit)
1156 {
1157         int err;
1158         Elf *elf;
1159
1160         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1161         if (elf == NULL)
1162                 return -1;
1163
1164         if (is_64_bit)
1165                 *is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1166
1167         err = elf_read_maps(elf, exe, mapfn, data);
1168
1169         elf_end(elf);
1170         return err;
1171 }
1172
1173 enum dso_type dso__type_fd(int fd)
1174 {
1175         enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1176         GElf_Ehdr ehdr;
1177         Elf_Kind ek;
1178         Elf *elf;
1179
1180         elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1181         if (elf == NULL)
1182                 goto out;
1183
1184         ek = elf_kind(elf);
1185         if (ek != ELF_K_ELF)
1186                 goto out_end;
1187
1188         if (gelf_getclass(elf) == ELFCLASS64) {
1189                 dso_type = DSO__TYPE_64BIT;
1190                 goto out_end;
1191         }
1192
1193         if (gelf_getehdr(elf, &ehdr) == NULL)
1194                 goto out_end;
1195
1196         if (ehdr.e_machine == EM_X86_64)
1197                 dso_type = DSO__TYPE_X32BIT;
1198         else
1199                 dso_type = DSO__TYPE_32BIT;
1200 out_end:
1201         elf_end(elf);
1202 out:
1203         return dso_type;
1204 }
1205
1206 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1207 {
1208         ssize_t r;
1209         size_t n;
1210         int err = -1;
1211         char *buf = malloc(page_size);
1212
1213         if (buf == NULL)
1214                 return -1;
1215
1216         if (lseek(to, to_offs, SEEK_SET) != to_offs)
1217                 goto out;
1218
1219         if (lseek(from, from_offs, SEEK_SET) != from_offs)
1220                 goto out;
1221
1222         while (len) {
1223                 n = page_size;
1224                 if (len < n)
1225                         n = len;
1226                 /* Use read because mmap won't work on proc files */
1227                 r = read(from, buf, n);
1228                 if (r < 0)
1229                         goto out;
1230                 if (!r)
1231                         break;
1232                 n = r;
1233                 r = write(to, buf, n);
1234                 if (r < 0)
1235                         goto out;
1236                 if ((size_t)r != n)
1237                         goto out;
1238                 len -= n;
1239         }
1240
1241         err = 0;
1242 out:
1243         free(buf);
1244         return err;
1245 }
1246
1247 struct kcore {
1248         int fd;
1249         int elfclass;
1250         Elf *elf;
1251         GElf_Ehdr ehdr;
1252 };
1253
1254 static int kcore__open(struct kcore *kcore, const char *filename)
1255 {
1256         GElf_Ehdr *ehdr;
1257
1258         kcore->fd = open(filename, O_RDONLY);
1259         if (kcore->fd == -1)
1260                 return -1;
1261
1262         kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1263         if (!kcore->elf)
1264                 goto out_close;
1265
1266         kcore->elfclass = gelf_getclass(kcore->elf);
1267         if (kcore->elfclass == ELFCLASSNONE)
1268                 goto out_end;
1269
1270         ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1271         if (!ehdr)
1272                 goto out_end;
1273
1274         return 0;
1275
1276 out_end:
1277         elf_end(kcore->elf);
1278 out_close:
1279         close(kcore->fd);
1280         return -1;
1281 }
1282
1283 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1284                        bool temp)
1285 {
1286         kcore->elfclass = elfclass;
1287
1288         if (temp)
1289                 kcore->fd = mkstemp(filename);
1290         else
1291                 kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0400);
1292         if (kcore->fd == -1)
1293                 return -1;
1294
1295         kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1296         if (!kcore->elf)
1297                 goto out_close;
1298
1299         if (!gelf_newehdr(kcore->elf, elfclass))
1300                 goto out_end;
1301
1302         memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
1303
1304         return 0;
1305
1306 out_end:
1307         elf_end(kcore->elf);
1308 out_close:
1309         close(kcore->fd);
1310         unlink(filename);
1311         return -1;
1312 }
1313
1314 static void kcore__close(struct kcore *kcore)
1315 {
1316         elf_end(kcore->elf);
1317         close(kcore->fd);
1318 }
1319
1320 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
1321 {
1322         GElf_Ehdr *ehdr = &to->ehdr;
1323         GElf_Ehdr *kehdr = &from->ehdr;
1324
1325         memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
1326         ehdr->e_type      = kehdr->e_type;
1327         ehdr->e_machine   = kehdr->e_machine;
1328         ehdr->e_version   = kehdr->e_version;
1329         ehdr->e_entry     = 0;
1330         ehdr->e_shoff     = 0;
1331         ehdr->e_flags     = kehdr->e_flags;
1332         ehdr->e_phnum     = count;
1333         ehdr->e_shentsize = 0;
1334         ehdr->e_shnum     = 0;
1335         ehdr->e_shstrndx  = 0;
1336
1337         if (from->elfclass == ELFCLASS32) {
1338                 ehdr->e_phoff     = sizeof(Elf32_Ehdr);
1339                 ehdr->e_ehsize    = sizeof(Elf32_Ehdr);
1340                 ehdr->e_phentsize = sizeof(Elf32_Phdr);
1341         } else {
1342                 ehdr->e_phoff     = sizeof(Elf64_Ehdr);
1343                 ehdr->e_ehsize    = sizeof(Elf64_Ehdr);
1344                 ehdr->e_phentsize = sizeof(Elf64_Phdr);
1345         }
1346
1347         if (!gelf_update_ehdr(to->elf, ehdr))
1348                 return -1;
1349
1350         if (!gelf_newphdr(to->elf, count))
1351                 return -1;
1352
1353         return 0;
1354 }
1355
1356 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
1357                            u64 addr, u64 len)
1358 {
1359         GElf_Phdr phdr = {
1360                 .p_type         = PT_LOAD,
1361                 .p_flags        = PF_R | PF_W | PF_X,
1362                 .p_offset       = offset,
1363                 .p_vaddr        = addr,
1364                 .p_paddr        = 0,
1365                 .p_filesz       = len,
1366                 .p_memsz        = len,
1367                 .p_align        = page_size,
1368         };
1369
1370         if (!gelf_update_phdr(kcore->elf, idx, &phdr))
1371                 return -1;
1372
1373         return 0;
1374 }
1375
1376 static off_t kcore__write(struct kcore *kcore)
1377 {
1378         return elf_update(kcore->elf, ELF_C_WRITE);
1379 }
1380
1381 struct phdr_data {
1382         off_t offset;
1383         u64 addr;
1384         u64 len;
1385 };
1386
1387 struct kcore_copy_info {
1388         u64 stext;
1389         u64 etext;
1390         u64 first_symbol;
1391         u64 last_symbol;
1392         u64 first_module;
1393         u64 first_module_symbol;
1394         u64 last_module_symbol;
1395         struct phdr_data kernel_map;
1396         struct phdr_data modules_map;
1397 };
1398
1399 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
1400                                         u64 start)
1401 {
1402         struct kcore_copy_info *kci = arg;
1403
1404         if (!symbol_type__is_a(type, MAP__FUNCTION))
1405                 return 0;
1406
1407         if (strchr(name, '[')) {
1408                 if (!kci->first_module_symbol || start < kci->first_module_symbol)
1409                         kci->first_module_symbol = start;
1410                 if (start > kci->last_module_symbol)
1411                         kci->last_module_symbol = start;
1412                 return 0;
1413         }
1414
1415         if (!kci->first_symbol || start < kci->first_symbol)
1416                 kci->first_symbol = start;
1417
1418         if (!kci->last_symbol || start > kci->last_symbol)
1419                 kci->last_symbol = start;
1420
1421         if (!strcmp(name, "_stext")) {
1422                 kci->stext = start;
1423                 return 0;
1424         }
1425
1426         if (!strcmp(name, "_etext")) {
1427                 kci->etext = start;
1428                 return 0;
1429         }
1430
1431         return 0;
1432 }
1433
1434 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
1435                                       const char *dir)
1436 {
1437         char kallsyms_filename[PATH_MAX];
1438
1439         scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
1440
1441         if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
1442                 return -1;
1443
1444         if (kallsyms__parse(kallsyms_filename, kci,
1445                             kcore_copy__process_kallsyms) < 0)
1446                 return -1;
1447
1448         return 0;
1449 }
1450
1451 static int kcore_copy__process_modules(void *arg,
1452                                        const char *name __maybe_unused,
1453                                        u64 start)
1454 {
1455         struct kcore_copy_info *kci = arg;
1456
1457         if (!kci->first_module || start < kci->first_module)
1458                 kci->first_module = start;
1459
1460         return 0;
1461 }
1462
1463 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
1464                                      const char *dir)
1465 {
1466         char modules_filename[PATH_MAX];
1467
1468         scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
1469
1470         if (symbol__restricted_filename(modules_filename, "/proc/modules"))
1471                 return -1;
1472
1473         if (modules__parse(modules_filename, kci,
1474                            kcore_copy__process_modules) < 0)
1475                 return -1;
1476
1477         return 0;
1478 }
1479
1480 static void kcore_copy__map(struct phdr_data *p, u64 start, u64 end, u64 pgoff,
1481                             u64 s, u64 e)
1482 {
1483         if (p->addr || s < start || s >= end)
1484                 return;
1485
1486         p->addr = s;
1487         p->offset = (s - start) + pgoff;
1488         p->len = e < end ? e - s : end - s;
1489 }
1490
1491 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
1492 {
1493         struct kcore_copy_info *kci = data;
1494         u64 end = start + len;
1495
1496         kcore_copy__map(&kci->kernel_map, start, end, pgoff, kci->stext,
1497                         kci->etext);
1498
1499         kcore_copy__map(&kci->modules_map, start, end, pgoff, kci->first_module,
1500                         kci->last_module_symbol);
1501
1502         return 0;
1503 }
1504
1505 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
1506 {
1507         if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
1508                 return -1;
1509
1510         return 0;
1511 }
1512
1513 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
1514                                  Elf *elf)
1515 {
1516         if (kcore_copy__parse_kallsyms(kci, dir))
1517                 return -1;
1518
1519         if (kcore_copy__parse_modules(kci, dir))
1520                 return -1;
1521
1522         if (kci->stext)
1523                 kci->stext = round_down(kci->stext, page_size);
1524         else
1525                 kci->stext = round_down(kci->first_symbol, page_size);
1526
1527         if (kci->etext) {
1528                 kci->etext = round_up(kci->etext, page_size);
1529         } else if (kci->last_symbol) {
1530                 kci->etext = round_up(kci->last_symbol, page_size);
1531                 kci->etext += page_size;
1532         }
1533
1534         if (kci->first_module_symbol &&
1535             (!kci->first_module || kci->first_module_symbol < kci->first_module))
1536                 kci->first_module = kci->first_module_symbol;
1537
1538         kci->first_module = round_down(kci->first_module, page_size);
1539
1540         if (kci->last_module_symbol) {
1541                 kci->last_module_symbol = round_up(kci->last_module_symbol,
1542                                                    page_size);
1543                 kci->last_module_symbol += page_size;
1544         }
1545
1546         if (!kci->stext || !kci->etext)
1547                 return -1;
1548
1549         if (kci->first_module && !kci->last_module_symbol)
1550                 return -1;
1551
1552         return kcore_copy__read_maps(kci, elf);
1553 }
1554
1555 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
1556                                  const char *name)
1557 {
1558         char from_filename[PATH_MAX];
1559         char to_filename[PATH_MAX];
1560
1561         scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
1562         scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
1563
1564         return copyfile_mode(from_filename, to_filename, 0400);
1565 }
1566
1567 static int kcore_copy__unlink(const char *dir, const char *name)
1568 {
1569         char filename[PATH_MAX];
1570
1571         scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
1572
1573         return unlink(filename);
1574 }
1575
1576 static int kcore_copy__compare_fds(int from, int to)
1577 {
1578         char *buf_from;
1579         char *buf_to;
1580         ssize_t ret;
1581         size_t len;
1582         int err = -1;
1583
1584         buf_from = malloc(page_size);
1585         buf_to = malloc(page_size);
1586         if (!buf_from || !buf_to)
1587                 goto out;
1588
1589         while (1) {
1590                 /* Use read because mmap won't work on proc files */
1591                 ret = read(from, buf_from, page_size);
1592                 if (ret < 0)
1593                         goto out;
1594
1595                 if (!ret)
1596                         break;
1597
1598                 len = ret;
1599
1600                 if (readn(to, buf_to, len) != (int)len)
1601                         goto out;
1602
1603                 if (memcmp(buf_from, buf_to, len))
1604                         goto out;
1605         }
1606
1607         err = 0;
1608 out:
1609         free(buf_to);
1610         free(buf_from);
1611         return err;
1612 }
1613
1614 static int kcore_copy__compare_files(const char *from_filename,
1615                                      const char *to_filename)
1616 {
1617         int from, to, err = -1;
1618
1619         from = open(from_filename, O_RDONLY);
1620         if (from < 0)
1621                 return -1;
1622
1623         to = open(to_filename, O_RDONLY);
1624         if (to < 0)
1625                 goto out_close_from;
1626
1627         err = kcore_copy__compare_fds(from, to);
1628
1629         close(to);
1630 out_close_from:
1631         close(from);
1632         return err;
1633 }
1634
1635 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
1636                                     const char *name)
1637 {
1638         char from_filename[PATH_MAX];
1639         char to_filename[PATH_MAX];
1640
1641         scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
1642         scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
1643
1644         return kcore_copy__compare_files(from_filename, to_filename);
1645 }
1646
1647 /**
1648  * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
1649  * @from_dir: from directory
1650  * @to_dir: to directory
1651  *
1652  * This function copies kallsyms, modules and kcore files from one directory to
1653  * another.  kallsyms and modules are copied entirely.  Only code segments are
1654  * copied from kcore.  It is assumed that two segments suffice: one for the
1655  * kernel proper and one for all the modules.  The code segments are determined
1656  * from kallsyms and modules files.  The kernel map starts at _stext or the
1657  * lowest function symbol, and ends at _etext or the highest function symbol.
1658  * The module map starts at the lowest module address and ends at the highest
1659  * module symbol.  Start addresses are rounded down to the nearest page.  End
1660  * addresses are rounded up to the nearest page.  An extra page is added to the
1661  * highest kernel symbol and highest module symbol to, hopefully, encompass that
1662  * symbol too.  Because it contains only code sections, the resulting kcore is
1663  * unusual.  One significant peculiarity is that the mapping (start -> pgoff)
1664  * is not the same for the kernel map and the modules map.  That happens because
1665  * the data is copied adjacently whereas the original kcore has gaps.  Finally,
1666  * kallsyms and modules files are compared with their copies to check that
1667  * modules have not been loaded or unloaded while the copies were taking place.
1668  *
1669  * Return: %0 on success, %-1 on failure.
1670  */
1671 int kcore_copy(const char *from_dir, const char *to_dir)
1672 {
1673         struct kcore kcore;
1674         struct kcore extract;
1675         size_t count = 2;
1676         int idx = 0, err = -1;
1677         off_t offset = page_size, sz, modules_offset = 0;
1678         struct kcore_copy_info kci = { .stext = 0, };
1679         char kcore_filename[PATH_MAX];
1680         char extract_filename[PATH_MAX];
1681
1682         if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
1683                 return -1;
1684
1685         if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
1686                 goto out_unlink_kallsyms;
1687
1688         scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
1689         scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
1690
1691         if (kcore__open(&kcore, kcore_filename))
1692                 goto out_unlink_modules;
1693
1694         if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
1695                 goto out_kcore_close;
1696
1697         if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
1698                 goto out_kcore_close;
1699
1700         if (!kci.modules_map.addr)
1701                 count -= 1;
1702
1703         if (kcore__copy_hdr(&kcore, &extract, count))
1704                 goto out_extract_close;
1705
1706         if (kcore__add_phdr(&extract, idx++, offset, kci.kernel_map.addr,
1707                             kci.kernel_map.len))
1708                 goto out_extract_close;
1709
1710         if (kci.modules_map.addr) {
1711                 modules_offset = offset + kci.kernel_map.len;
1712                 if (kcore__add_phdr(&extract, idx, modules_offset,
1713                                     kci.modules_map.addr, kci.modules_map.len))
1714                         goto out_extract_close;
1715         }
1716
1717         sz = kcore__write(&extract);
1718         if (sz < 0 || sz > offset)
1719                 goto out_extract_close;
1720
1721         if (copy_bytes(kcore.fd, kci.kernel_map.offset, extract.fd, offset,
1722                        kci.kernel_map.len))
1723                 goto out_extract_close;
1724
1725         if (modules_offset && copy_bytes(kcore.fd, kci.modules_map.offset,
1726                                          extract.fd, modules_offset,
1727                                          kci.modules_map.len))
1728                 goto out_extract_close;
1729
1730         if (kcore_copy__compare_file(from_dir, to_dir, "modules"))
1731                 goto out_extract_close;
1732
1733         if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
1734                 goto out_extract_close;
1735
1736         err = 0;
1737
1738 out_extract_close:
1739         kcore__close(&extract);
1740         if (err)
1741                 unlink(extract_filename);
1742 out_kcore_close:
1743         kcore__close(&kcore);
1744 out_unlink_modules:
1745         if (err)
1746                 kcore_copy__unlink(to_dir, "modules");
1747 out_unlink_kallsyms:
1748         if (err)
1749                 kcore_copy__unlink(to_dir, "kallsyms");
1750
1751         return err;
1752 }
1753
1754 int kcore_extract__create(struct kcore_extract *kce)
1755 {
1756         struct kcore kcore;
1757         struct kcore extract;
1758         size_t count = 1;
1759         int idx = 0, err = -1;
1760         off_t offset = page_size, sz;
1761
1762         if (kcore__open(&kcore, kce->kcore_filename))
1763                 return -1;
1764
1765         strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
1766         if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
1767                 goto out_kcore_close;
1768
1769         if (kcore__copy_hdr(&kcore, &extract, count))
1770                 goto out_extract_close;
1771
1772         if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
1773                 goto out_extract_close;
1774
1775         sz = kcore__write(&extract);
1776         if (sz < 0 || sz > offset)
1777                 goto out_extract_close;
1778
1779         if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
1780                 goto out_extract_close;
1781
1782         err = 0;
1783
1784 out_extract_close:
1785         kcore__close(&extract);
1786         if (err)
1787                 unlink(kce->extract_filename);
1788 out_kcore_close:
1789         kcore__close(&kcore);
1790
1791         return err;
1792 }
1793
1794 void kcore_extract__delete(struct kcore_extract *kce)
1795 {
1796         unlink(kce->extract_filename);
1797 }
1798
1799 void symbol__elf_init(void)
1800 {
1801         elf_version(EV_CURRENT);
1802 }