xref: /linux/tools/perf/util/symbol-elf.c (revision 9e906a9dead17d81d6c2687f65e159231d0e3286)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <errno.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <inttypes.h>
9 
10 #include "compress.h"
11 #include "dso.h"
12 #include "libbfd.h"
13 #include "map.h"
14 #include "maps.h"
15 #include "symbol.h"
16 #include "symsrc.h"
17 #include "machine.h"
18 #include "vdso.h"
19 #include "debug.h"
20 #include "util/copyfile.h"
21 #include <linux/ctype.h>
22 #include <linux/kernel.h>
23 #include <linux/zalloc.h>
24 #include <linux/string.h>
25 #include <symbol/kallsyms.h>
26 #include <internal/lib.h>
27 
28 #ifndef EM_AARCH64
29 #define EM_AARCH64	183  /* ARM 64 bit */
30 #endif
31 
32 #ifndef EM_LOONGARCH
33 #define EM_LOONGARCH	258
34 #endif
35 
36 #ifndef ELF32_ST_VISIBILITY
37 #define ELF32_ST_VISIBILITY(o)	((o) & 0x03)
38 #endif
39 
40 /* For ELF64 the definitions are the same.  */
41 #ifndef ELF64_ST_VISIBILITY
42 #define ELF64_ST_VISIBILITY(o)	ELF32_ST_VISIBILITY (o)
43 #endif
44 
45 /* How to extract information held in the st_other field.  */
46 #ifndef GELF_ST_VISIBILITY
47 #define GELF_ST_VISIBILITY(val)	ELF64_ST_VISIBILITY (val)
48 #endif
49 
50 typedef Elf64_Nhdr GElf_Nhdr;
51 
52 
53 #ifndef HAVE_ELF_GETPHDRNUM_SUPPORT
elf_getphdrnum(Elf * elf,size_t * dst)54 static int elf_getphdrnum(Elf *elf, size_t *dst)
55 {
56 	GElf_Ehdr gehdr;
57 	GElf_Ehdr *ehdr;
58 
59 	ehdr = gelf_getehdr(elf, &gehdr);
60 	if (!ehdr)
61 		return -1;
62 
63 	*dst = ehdr->e_phnum;
64 
65 	return 0;
66 }
67 #endif
68 
69 #ifndef HAVE_ELF_GETSHDRSTRNDX_SUPPORT
elf_getshdrstrndx(Elf * elf __maybe_unused,size_t * dst __maybe_unused)70 static int elf_getshdrstrndx(Elf *elf __maybe_unused, size_t *dst __maybe_unused)
71 {
72 	pr_err("%s: update your libelf to > 0.140, this one lacks elf_getshdrstrndx().\n", __func__);
73 	return -1;
74 }
75 #endif
76 
77 #ifndef NT_GNU_BUILD_ID
78 #define NT_GNU_BUILD_ID 3
79 #endif
80 
81 /**
82  * elf_symtab__for_each_symbol - iterate thru all the symbols
83  *
84  * @syms: struct elf_symtab instance to iterate
85  * @idx: uint32_t idx
86  * @sym: GElf_Sym iterator
87  */
88 #define elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) \
89 	for (idx = 0, gelf_getsym(syms, idx, &sym);\
90 	     idx < nr_syms; \
91 	     idx++, gelf_getsym(syms, idx, &sym))
92 
elf_sym__type(const GElf_Sym * sym)93 static inline uint8_t elf_sym__type(const GElf_Sym *sym)
94 {
95 	return GELF_ST_TYPE(sym->st_info);
96 }
97 
elf_sym__visibility(const GElf_Sym * sym)98 static inline uint8_t elf_sym__visibility(const GElf_Sym *sym)
99 {
100 	return GELF_ST_VISIBILITY(sym->st_other);
101 }
102 
103 #ifndef STT_GNU_IFUNC
104 #define STT_GNU_IFUNC 10
105 #endif
106 
elf_sym__is_function(const GElf_Sym * sym)107 static inline int elf_sym__is_function(const GElf_Sym *sym)
108 {
109 	return (elf_sym__type(sym) == STT_FUNC ||
110 		elf_sym__type(sym) == STT_GNU_IFUNC) &&
111 	       sym->st_name != 0 &&
112 	       sym->st_shndx != SHN_UNDEF;
113 }
114 
elf_sym__is_object(const GElf_Sym * sym)115 static inline bool elf_sym__is_object(const GElf_Sym *sym)
116 {
117 	return elf_sym__type(sym) == STT_OBJECT &&
118 		sym->st_name != 0 &&
119 		sym->st_shndx != SHN_UNDEF;
120 }
121 
elf_sym__is_label(const GElf_Sym * sym)122 static inline int elf_sym__is_label(const GElf_Sym *sym)
123 {
124 	return elf_sym__type(sym) == STT_NOTYPE &&
125 		sym->st_name != 0 &&
126 		sym->st_shndx != SHN_UNDEF &&
127 		sym->st_shndx != SHN_ABS &&
128 		elf_sym__visibility(sym) != STV_HIDDEN &&
129 		elf_sym__visibility(sym) != STV_INTERNAL;
130 }
131 
elf_sym__filter(GElf_Sym * sym)132 static bool elf_sym__filter(GElf_Sym *sym)
133 {
134 	return elf_sym__is_function(sym) || elf_sym__is_object(sym);
135 }
136 
elf_sym__name(const GElf_Sym * sym,const Elf_Data * symstrs)137 static inline const char *elf_sym__name(const GElf_Sym *sym,
138 					const Elf_Data *symstrs)
139 {
140 	return symstrs->d_buf + sym->st_name;
141 }
142 
elf_sec__name(const GElf_Shdr * shdr,const Elf_Data * secstrs)143 static inline const char *elf_sec__name(const GElf_Shdr *shdr,
144 					const Elf_Data *secstrs)
145 {
146 	return secstrs->d_buf + shdr->sh_name;
147 }
148 
elf_sec__is_text(const GElf_Shdr * shdr,const Elf_Data * secstrs)149 static inline int elf_sec__is_text(const GElf_Shdr *shdr,
150 					const Elf_Data *secstrs)
151 {
152 	return strstr(elf_sec__name(shdr, secstrs), "text") != NULL;
153 }
154 
elf_sec__is_data(const GElf_Shdr * shdr,const Elf_Data * secstrs)155 static inline bool elf_sec__is_data(const GElf_Shdr *shdr,
156 				    const Elf_Data *secstrs)
157 {
158 	return strstr(elf_sec__name(shdr, secstrs), "data") != NULL;
159 }
160 
elf_sec__filter(GElf_Shdr * shdr,Elf_Data * secstrs)161 static bool elf_sec__filter(GElf_Shdr *shdr, Elf_Data *secstrs)
162 {
163 	return elf_sec__is_text(shdr, secstrs) ||
164 	       elf_sec__is_data(shdr, secstrs);
165 }
166 
elf_addr_to_index(Elf * elf,GElf_Addr addr)167 static size_t elf_addr_to_index(Elf *elf, GElf_Addr addr)
168 {
169 	Elf_Scn *sec = NULL;
170 	GElf_Shdr shdr;
171 	size_t cnt = 1;
172 
173 	while ((sec = elf_nextscn(elf, sec)) != NULL) {
174 		gelf_getshdr(sec, &shdr);
175 
176 		if ((addr >= shdr.sh_addr) &&
177 		    (addr < (shdr.sh_addr + shdr.sh_size)))
178 			return cnt;
179 
180 		++cnt;
181 	}
182 
183 	return -1;
184 }
185 
elf_section_by_name(Elf * elf,GElf_Ehdr * ep,GElf_Shdr * shp,const char * name,size_t * idx)186 Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
187 			     GElf_Shdr *shp, const char *name, size_t *idx)
188 {
189 	Elf_Scn *sec = NULL;
190 	size_t cnt = 1;
191 
192 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
193 	if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL))
194 		return NULL;
195 
196 	while ((sec = elf_nextscn(elf, sec)) != NULL) {
197 		char *str;
198 
199 		gelf_getshdr(sec, shp);
200 		str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
201 		if (str && !strcmp(name, str)) {
202 			if (idx)
203 				*idx = cnt;
204 			return sec;
205 		}
206 		++cnt;
207 	}
208 
209 	return NULL;
210 }
211 
filename__has_section(const char * filename,const char * sec)212 bool filename__has_section(const char *filename, const char *sec)
213 {
214 	int fd;
215 	Elf *elf;
216 	GElf_Ehdr ehdr;
217 	GElf_Shdr shdr;
218 	bool found = false;
219 
220 	fd = open(filename, O_RDONLY);
221 	if (fd < 0)
222 		return false;
223 
224 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
225 	if (elf == NULL)
226 		goto out;
227 
228 	if (gelf_getehdr(elf, &ehdr) == NULL)
229 		goto elf_out;
230 
231 	found = !!elf_section_by_name(elf, &ehdr, &shdr, sec, NULL);
232 
233 elf_out:
234 	elf_end(elf);
235 out:
236 	close(fd);
237 	return found;
238 }
239 
elf_read_program_header(Elf * elf,u64 vaddr,GElf_Phdr * phdr)240 static int elf_read_program_header(Elf *elf, u64 vaddr, GElf_Phdr *phdr)
241 {
242 	size_t i, phdrnum;
243 	u64 sz;
244 
245 	if (elf_getphdrnum(elf, &phdrnum))
246 		return -1;
247 
248 	for (i = 0; i < phdrnum; i++) {
249 		if (gelf_getphdr(elf, i, phdr) == NULL)
250 			return -1;
251 
252 		if (phdr->p_type != PT_LOAD)
253 			continue;
254 
255 		sz = max(phdr->p_memsz, phdr->p_filesz);
256 		if (!sz)
257 			continue;
258 
259 		if (vaddr >= phdr->p_vaddr && (vaddr < phdr->p_vaddr + sz))
260 			return 0;
261 	}
262 
263 	/* Not found any valid program header */
264 	return -1;
265 }
266 
267 struct rel_info {
268 	u32		nr_entries;
269 	u32		*sorted;
270 	bool		is_rela;
271 	Elf_Data	*reldata;
272 	GElf_Rela	rela;
273 	GElf_Rel	rel;
274 };
275 
get_rel_symidx(struct rel_info * ri,u32 idx)276 static u32 get_rel_symidx(struct rel_info *ri, u32 idx)
277 {
278 	idx = ri->sorted ? ri->sorted[idx] : idx;
279 	if (ri->is_rela) {
280 		gelf_getrela(ri->reldata, idx, &ri->rela);
281 		return GELF_R_SYM(ri->rela.r_info);
282 	}
283 	gelf_getrel(ri->reldata, idx, &ri->rel);
284 	return GELF_R_SYM(ri->rel.r_info);
285 }
286 
get_rel_offset(struct rel_info * ri,u32 x)287 static u64 get_rel_offset(struct rel_info *ri, u32 x)
288 {
289 	if (ri->is_rela) {
290 		GElf_Rela rela;
291 
292 		gelf_getrela(ri->reldata, x, &rela);
293 		return rela.r_offset;
294 	} else {
295 		GElf_Rel rel;
296 
297 		gelf_getrel(ri->reldata, x, &rel);
298 		return rel.r_offset;
299 	}
300 }
301 
rel_cmp(const void * a,const void * b,void * r)302 static int rel_cmp(const void *a, const void *b, void *r)
303 {
304 	struct rel_info *ri = r;
305 	u64 a_offset = get_rel_offset(ri, *(const u32 *)a);
306 	u64 b_offset = get_rel_offset(ri, *(const u32 *)b);
307 
308 	return a_offset < b_offset ? -1 : (a_offset > b_offset ? 1 : 0);
309 }
310 
sort_rel(struct rel_info * ri)311 static int sort_rel(struct rel_info *ri)
312 {
313 	size_t sz = sizeof(ri->sorted[0]);
314 	u32 i;
315 
316 	ri->sorted = calloc(ri->nr_entries, sz);
317 	if (!ri->sorted)
318 		return -1;
319 	for (i = 0; i < ri->nr_entries; i++)
320 		ri->sorted[i] = i;
321 	qsort_r(ri->sorted, ri->nr_entries, sz, rel_cmp, ri);
322 	return 0;
323 }
324 
325 /*
326  * For x86_64, the GNU linker is putting IFUNC information in the relocation
327  * addend.
328  */
addend_may_be_ifunc(GElf_Ehdr * ehdr,struct rel_info * ri)329 static bool addend_may_be_ifunc(GElf_Ehdr *ehdr, struct rel_info *ri)
330 {
331 	return ehdr->e_machine == EM_X86_64 && ri->is_rela &&
332 	       GELF_R_TYPE(ri->rela.r_info) == R_X86_64_IRELATIVE;
333 }
334 
get_ifunc_name(Elf * elf,struct dso * dso,GElf_Ehdr * ehdr,struct rel_info * ri,char * buf,size_t buf_sz)335 static bool get_ifunc_name(Elf *elf, struct dso *dso, GElf_Ehdr *ehdr,
336 			   struct rel_info *ri, char *buf, size_t buf_sz)
337 {
338 	u64 addr = ri->rela.r_addend;
339 	struct symbol *sym;
340 	GElf_Phdr phdr;
341 
342 	if (!addend_may_be_ifunc(ehdr, ri))
343 		return false;
344 
345 	if (elf_read_program_header(elf, addr, &phdr))
346 		return false;
347 
348 	addr -= phdr.p_vaddr - phdr.p_offset;
349 
350 	sym = dso__find_symbol_nocache(dso, addr);
351 
352 	/* Expecting the address to be an IFUNC or IFUNC alias */
353 	if (!sym || sym->start != addr || (sym->type != STT_GNU_IFUNC && !sym->ifunc_alias))
354 		return false;
355 
356 	snprintf(buf, buf_sz, "%s@plt", sym->name);
357 
358 	return true;
359 }
360 
exit_rel(struct rel_info * ri)361 static void exit_rel(struct rel_info *ri)
362 {
363 	zfree(&ri->sorted);
364 }
365 
get_plt_sizes(struct dso * dso,GElf_Ehdr * ehdr,GElf_Shdr * shdr_plt,u64 * plt_header_size,u64 * plt_entry_size)366 static bool get_plt_sizes(struct dso *dso, GElf_Ehdr *ehdr, GElf_Shdr *shdr_plt,
367 			  u64 *plt_header_size, u64 *plt_entry_size)
368 {
369 	switch (ehdr->e_machine) {
370 	case EM_ARM:
371 		*plt_header_size = 20;
372 		*plt_entry_size = 12;
373 		return true;
374 	case EM_AARCH64:
375 		*plt_header_size = 32;
376 		*plt_entry_size = 16;
377 		return true;
378 	case EM_LOONGARCH:
379 		*plt_header_size = 32;
380 		*plt_entry_size = 16;
381 		return true;
382 	case EM_SPARC:
383 		*plt_header_size = 48;
384 		*plt_entry_size = 12;
385 		return true;
386 	case EM_SPARCV9:
387 		*plt_header_size = 128;
388 		*plt_entry_size = 32;
389 		return true;
390 	case EM_386:
391 	case EM_X86_64:
392 		*plt_entry_size = shdr_plt->sh_entsize;
393 		/* Size is 8 or 16, if not, assume alignment indicates size */
394 		if (*plt_entry_size != 8 && *plt_entry_size != 16)
395 			*plt_entry_size = shdr_plt->sh_addralign == 8 ? 8 : 16;
396 		*plt_header_size = *plt_entry_size;
397 		break;
398 	default: /* FIXME: s390/alpha/mips/parisc/poperpc/sh/xtensa need to be checked */
399 		*plt_header_size = shdr_plt->sh_entsize;
400 		*plt_entry_size = shdr_plt->sh_entsize;
401 		break;
402 	}
403 	if (*plt_entry_size)
404 		return true;
405 	pr_debug("Missing PLT entry size for %s\n", dso__long_name(dso));
406 	return false;
407 }
408 
machine_is_x86(GElf_Half e_machine)409 static bool machine_is_x86(GElf_Half e_machine)
410 {
411 	return e_machine == EM_386 || e_machine == EM_X86_64;
412 }
413 
414 struct rela_dyn {
415 	GElf_Addr	offset;
416 	u32		sym_idx;
417 };
418 
419 struct rela_dyn_info {
420 	struct dso	*dso;
421 	Elf_Data	*plt_got_data;
422 	u32		nr_entries;
423 	struct rela_dyn	*sorted;
424 	Elf_Data	*dynsym_data;
425 	Elf_Data	*dynstr_data;
426 	Elf_Data	*rela_dyn_data;
427 };
428 
exit_rela_dyn(struct rela_dyn_info * di)429 static void exit_rela_dyn(struct rela_dyn_info *di)
430 {
431 	zfree(&di->sorted);
432 }
433 
cmp_offset(const void * a,const void * b)434 static int cmp_offset(const void *a, const void *b)
435 {
436 	const struct rela_dyn *va = a;
437 	const struct rela_dyn *vb = b;
438 
439 	return va->offset < vb->offset ? -1 : (va->offset > vb->offset ? 1 : 0);
440 }
441 
sort_rela_dyn(struct rela_dyn_info * di)442 static int sort_rela_dyn(struct rela_dyn_info *di)
443 {
444 	u32 i, n;
445 
446 	di->sorted = calloc(di->nr_entries, sizeof(di->sorted[0]));
447 	if (!di->sorted)
448 		return -1;
449 
450 	/* Get data for sorting: the offset and symbol index */
451 	for (i = 0, n = 0; i < di->nr_entries; i++) {
452 		GElf_Rela rela;
453 		u32 sym_idx;
454 
455 		gelf_getrela(di->rela_dyn_data, i, &rela);
456 		sym_idx = GELF_R_SYM(rela.r_info);
457 		if (sym_idx) {
458 			di->sorted[n].sym_idx = sym_idx;
459 			di->sorted[n].offset = rela.r_offset;
460 			n += 1;
461 		}
462 	}
463 
464 	/* Sort by offset */
465 	di->nr_entries = n;
466 	qsort(di->sorted, n, sizeof(di->sorted[0]), cmp_offset);
467 
468 	return 0;
469 }
470 
get_rela_dyn_info(Elf * elf,GElf_Ehdr * ehdr,struct rela_dyn_info * di,Elf_Scn * scn)471 static void get_rela_dyn_info(Elf *elf, GElf_Ehdr *ehdr, struct rela_dyn_info *di, Elf_Scn *scn)
472 {
473 	GElf_Shdr rela_dyn_shdr;
474 	GElf_Shdr shdr;
475 
476 	di->plt_got_data = elf_getdata(scn, NULL);
477 
478 	scn = elf_section_by_name(elf, ehdr, &rela_dyn_shdr, ".rela.dyn", NULL);
479 	if (!scn || !rela_dyn_shdr.sh_link || !rela_dyn_shdr.sh_entsize)
480 		return;
481 
482 	di->nr_entries = rela_dyn_shdr.sh_size / rela_dyn_shdr.sh_entsize;
483 	di->rela_dyn_data = elf_getdata(scn, NULL);
484 
485 	scn = elf_getscn(elf, rela_dyn_shdr.sh_link);
486 	if (!scn || !gelf_getshdr(scn, &shdr) || !shdr.sh_link)
487 		return;
488 
489 	di->dynsym_data = elf_getdata(scn, NULL);
490 	di->dynstr_data = elf_getdata(elf_getscn(elf, shdr.sh_link), NULL);
491 
492 	if (!di->plt_got_data || !di->dynstr_data || !di->dynsym_data || !di->rela_dyn_data)
493 		return;
494 
495 	/* Sort into offset order */
496 	sort_rela_dyn(di);
497 }
498 
499 /* Get instruction displacement from a plt entry for x86_64 */
get_x86_64_plt_disp(const u8 * p)500 static u32 get_x86_64_plt_disp(const u8 *p)
501 {
502 	u8 endbr64[] = {0xf3, 0x0f, 0x1e, 0xfa};
503 	int n = 0;
504 
505 	/* Skip endbr64 */
506 	if (!memcmp(p, endbr64, sizeof(endbr64)))
507 		n += sizeof(endbr64);
508 	/* Skip bnd prefix */
509 	if (p[n] == 0xf2)
510 		n += 1;
511 	/* jmp with 4-byte displacement */
512 	if (p[n] == 0xff && p[n + 1] == 0x25) {
513 		u32 disp;
514 
515 		n += 2;
516 		/* Also add offset from start of entry to end of instruction */
517 		memcpy(&disp, p + n, sizeof(disp));
518 		return n + 4 + le32toh(disp);
519 	}
520 	return 0;
521 }
522 
get_plt_got_name(GElf_Shdr * shdr,size_t i,struct rela_dyn_info * di,char * buf,size_t buf_sz)523 static bool get_plt_got_name(GElf_Shdr *shdr, size_t i,
524 			     struct rela_dyn_info *di,
525 			     char *buf, size_t buf_sz)
526 {
527 	struct rela_dyn vi, *vr;
528 	const char *sym_name;
529 	char *demangled;
530 	GElf_Sym sym;
531 	bool result;
532 	u32 disp;
533 
534 	if (!di->sorted)
535 		return false;
536 
537 	disp = get_x86_64_plt_disp(di->plt_got_data->d_buf + i);
538 	if (!disp)
539 		return false;
540 
541 	/* Compute target offset of the .plt.got entry */
542 	vi.offset = shdr->sh_offset + di->plt_got_data->d_off + i + disp;
543 
544 	/* Find that offset in .rela.dyn (sorted by offset) */
545 	vr = bsearch(&vi, di->sorted, di->nr_entries, sizeof(di->sorted[0]), cmp_offset);
546 	if (!vr)
547 		return false;
548 
549 	/* Get the associated symbol */
550 	gelf_getsym(di->dynsym_data, vr->sym_idx, &sym);
551 	sym_name = elf_sym__name(&sym, di->dynstr_data);
552 	demangled = dso__demangle_sym(di->dso, /*kmodule=*/0, sym_name);
553 	if (demangled != NULL)
554 		sym_name = demangled;
555 
556 	snprintf(buf, buf_sz, "%s@plt", sym_name);
557 
558 	result = *sym_name;
559 
560 	free(demangled);
561 
562 	return result;
563 }
564 
dso__synthesize_plt_got_symbols(struct dso * dso,Elf * elf,GElf_Ehdr * ehdr,char * buf,size_t buf_sz)565 static int dso__synthesize_plt_got_symbols(struct dso *dso, Elf *elf,
566 					   GElf_Ehdr *ehdr,
567 					   char *buf, size_t buf_sz)
568 {
569 	struct rela_dyn_info di = { .dso = dso };
570 	struct symbol *sym;
571 	GElf_Shdr shdr;
572 	Elf_Scn *scn;
573 	int err = -1;
574 	size_t i;
575 
576 	scn = elf_section_by_name(elf, ehdr, &shdr, ".plt.got", NULL);
577 	if (!scn || !shdr.sh_entsize)
578 		return 0;
579 
580 	if (ehdr->e_machine == EM_X86_64)
581 		get_rela_dyn_info(elf, ehdr, &di, scn);
582 
583 	for (i = 0; i < shdr.sh_size; i += shdr.sh_entsize) {
584 		if (!get_plt_got_name(&shdr, i, &di, buf, buf_sz))
585 			snprintf(buf, buf_sz, "offset_%#" PRIx64 "@plt", (u64)shdr.sh_offset + i);
586 		sym = symbol__new(shdr.sh_offset + i, shdr.sh_entsize, STB_GLOBAL, STT_FUNC, buf);
587 		if (!sym)
588 			goto out;
589 		symbols__insert(dso__symbols(dso), sym);
590 	}
591 	err = 0;
592 out:
593 	exit_rela_dyn(&di);
594 	return err;
595 }
596 
597 /*
598  * We need to check if we have a .dynsym, so that we can handle the
599  * .plt, synthesizing its symbols, that aren't on the symtabs (be it
600  * .dynsym or .symtab).
601  * And always look at the original dso, not at debuginfo packages, that
602  * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
603  */
dso__synthesize_plt_symbols(struct dso * dso,struct symsrc * ss)604 int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss)
605 {
606 	uint32_t idx;
607 	GElf_Sym sym;
608 	u64 plt_offset, plt_header_size, plt_entry_size;
609 	GElf_Shdr shdr_plt, plt_sec_shdr;
610 	struct symbol *f, *plt_sym;
611 	GElf_Shdr shdr_rel_plt, shdr_dynsym;
612 	Elf_Data *syms, *symstrs;
613 	Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
614 	GElf_Ehdr ehdr;
615 	char sympltname[1024];
616 	Elf *elf;
617 	int nr = 0, err = -1;
618 	struct rel_info ri = { .is_rela = false };
619 	bool lazy_plt;
620 
621 	elf = ss->elf;
622 	ehdr = ss->ehdr;
623 
624 	if (!elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL))
625 		return 0;
626 
627 	/*
628 	 * A symbol from a previous section (e.g. .init) can have been expanded
629 	 * by symbols__fixup_end() to overlap .plt. Truncate it before adding
630 	 * a symbol for .plt header.
631 	 */
632 	f = dso__find_symbol_nocache(dso, shdr_plt.sh_offset);
633 	if (f && f->start < shdr_plt.sh_offset && f->end > shdr_plt.sh_offset)
634 		f->end = shdr_plt.sh_offset;
635 
636 	if (!get_plt_sizes(dso, &ehdr, &shdr_plt, &plt_header_size, &plt_entry_size))
637 		return 0;
638 
639 	/* Add a symbol for .plt header */
640 	plt_sym = symbol__new(shdr_plt.sh_offset, plt_header_size, STB_GLOBAL, STT_FUNC, ".plt");
641 	if (!plt_sym)
642 		goto out_elf_end;
643 	symbols__insert(dso__symbols(dso), plt_sym);
644 
645 	/* Only x86 has .plt.got */
646 	if (machine_is_x86(ehdr.e_machine) &&
647 	    dso__synthesize_plt_got_symbols(dso, elf, &ehdr, sympltname, sizeof(sympltname)))
648 		goto out_elf_end;
649 
650 	/* Only x86 has .plt.sec */
651 	if (machine_is_x86(ehdr.e_machine) &&
652 	    elf_section_by_name(elf, &ehdr, &plt_sec_shdr, ".plt.sec", NULL)) {
653 		if (!get_plt_sizes(dso, &ehdr, &plt_sec_shdr, &plt_header_size, &plt_entry_size))
654 			return 0;
655 		/* Extend .plt symbol to entire .plt */
656 		plt_sym->end = plt_sym->start + shdr_plt.sh_size;
657 		/* Use .plt.sec offset */
658 		plt_offset = plt_sec_shdr.sh_offset;
659 		lazy_plt = false;
660 	} else {
661 		plt_offset = shdr_plt.sh_offset;
662 		lazy_plt = true;
663 	}
664 
665 	scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
666 					  ".rela.plt", NULL);
667 	if (scn_plt_rel == NULL) {
668 		scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
669 						  ".rel.plt", NULL);
670 		if (scn_plt_rel == NULL)
671 			return 0;
672 	}
673 
674 	if (shdr_rel_plt.sh_type != SHT_RELA &&
675 	    shdr_rel_plt.sh_type != SHT_REL)
676 		return 0;
677 
678 	if (!shdr_rel_plt.sh_link)
679 		return 0;
680 
681 	if (shdr_rel_plt.sh_link == ss->dynsym_idx) {
682 		scn_dynsym = ss->dynsym;
683 		shdr_dynsym = ss->dynshdr;
684 	} else if (shdr_rel_plt.sh_link == ss->symtab_idx) {
685 		/*
686 		 * A static executable can have a .plt due to IFUNCs, in which
687 		 * case .symtab is used not .dynsym.
688 		 */
689 		scn_dynsym = ss->symtab;
690 		shdr_dynsym = ss->symshdr;
691 	} else {
692 		goto out_elf_end;
693 	}
694 
695 	if (!scn_dynsym)
696 		return 0;
697 
698 	/*
699 	 * Fetch the relocation section to find the idxes to the GOT
700 	 * and the symbols in the .dynsym they refer to.
701 	 */
702 	ri.reldata = elf_getdata(scn_plt_rel, NULL);
703 	if (!ri.reldata)
704 		goto out_elf_end;
705 
706 	syms = elf_getdata(scn_dynsym, NULL);
707 	if (syms == NULL)
708 		goto out_elf_end;
709 
710 	scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
711 	if (scn_symstrs == NULL)
712 		goto out_elf_end;
713 
714 	symstrs = elf_getdata(scn_symstrs, NULL);
715 	if (symstrs == NULL)
716 		goto out_elf_end;
717 
718 	if (symstrs->d_size == 0)
719 		goto out_elf_end;
720 
721 	ri.nr_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
722 
723 	ri.is_rela = shdr_rel_plt.sh_type == SHT_RELA;
724 
725 	if (lazy_plt) {
726 		/*
727 		 * Assume a .plt with the same number of entries as the number
728 		 * of relocation entries is not lazy and does not have a header.
729 		 */
730 		if (ri.nr_entries * plt_entry_size == shdr_plt.sh_size)
731 			dso__delete_symbol(dso, plt_sym);
732 		else
733 			plt_offset += plt_header_size;
734 	}
735 
736 	/*
737 	 * x86 doesn't insert IFUNC relocations in .plt order, so sort to get
738 	 * back in order.
739 	 */
740 	if (machine_is_x86(ehdr.e_machine) && sort_rel(&ri))
741 		goto out_elf_end;
742 
743 	for (idx = 0; idx < ri.nr_entries; idx++) {
744 		const char *elf_name = NULL;
745 		char *demangled = NULL;
746 
747 		gelf_getsym(syms, get_rel_symidx(&ri, idx), &sym);
748 
749 		elf_name = elf_sym__name(&sym, symstrs);
750 		demangled = dso__demangle_sym(dso, /*kmodule=*/0, elf_name);
751 		if (demangled)
752 			elf_name = demangled;
753 		if (*elf_name)
754 			snprintf(sympltname, sizeof(sympltname), "%s@plt", elf_name);
755 		else if (!get_ifunc_name(elf, dso, &ehdr, &ri, sympltname, sizeof(sympltname)))
756 			snprintf(sympltname, sizeof(sympltname),
757 				 "offset_%#" PRIx64 "@plt", plt_offset);
758 		free(demangled);
759 
760 		f = symbol__new(plt_offset, plt_entry_size, STB_GLOBAL, STT_FUNC, sympltname);
761 		if (!f)
762 			goto out_elf_end;
763 
764 		plt_offset += plt_entry_size;
765 		symbols__insert(dso__symbols(dso), f);
766 		++nr;
767 	}
768 
769 	err = 0;
770 out_elf_end:
771 	exit_rel(&ri);
772 	if (err == 0)
773 		return nr;
774 	pr_debug("%s: problems reading %s PLT info.\n",
775 		 __func__, dso__long_name(dso));
776 	return 0;
777 }
778 
779 /*
780  * Align offset to 4 bytes as needed for note name and descriptor data.
781  */
782 #define NOTE_ALIGN(n) (((n) + 3) & -4U)
783 
elf_read_build_id(Elf * elf,void * bf,size_t size)784 static int elf_read_build_id(Elf *elf, void *bf, size_t size)
785 {
786 	int err = -1;
787 	GElf_Ehdr ehdr;
788 	GElf_Shdr shdr;
789 	Elf_Data *data;
790 	Elf_Scn *sec;
791 	Elf_Kind ek;
792 	void *ptr;
793 
794 	if (size < BUILD_ID_SIZE)
795 		goto out;
796 
797 	ek = elf_kind(elf);
798 	if (ek != ELF_K_ELF)
799 		goto out;
800 
801 	if (gelf_getehdr(elf, &ehdr) == NULL) {
802 		pr_err("%s: cannot get elf header.\n", __func__);
803 		goto out;
804 	}
805 
806 	/*
807 	 * Check following sections for notes:
808 	 *   '.note.gnu.build-id'
809 	 *   '.notes'
810 	 *   '.note' (VDSO specific)
811 	 */
812 	do {
813 		sec = elf_section_by_name(elf, &ehdr, &shdr,
814 					  ".note.gnu.build-id", NULL);
815 		if (sec)
816 			break;
817 
818 		sec = elf_section_by_name(elf, &ehdr, &shdr,
819 					  ".notes", NULL);
820 		if (sec)
821 			break;
822 
823 		sec = elf_section_by_name(elf, &ehdr, &shdr,
824 					  ".note", NULL);
825 		if (sec)
826 			break;
827 
828 		return err;
829 
830 	} while (0);
831 
832 	data = elf_getdata(sec, NULL);
833 	if (data == NULL)
834 		goto out;
835 
836 	ptr = data->d_buf;
837 	while (ptr < (data->d_buf + data->d_size)) {
838 		GElf_Nhdr *nhdr = ptr;
839 		size_t namesz = NOTE_ALIGN(nhdr->n_namesz),
840 		       descsz = NOTE_ALIGN(nhdr->n_descsz);
841 		const char *name;
842 
843 		ptr += sizeof(*nhdr);
844 		name = ptr;
845 		ptr += namesz;
846 		if (nhdr->n_type == NT_GNU_BUILD_ID &&
847 		    nhdr->n_namesz == sizeof("GNU")) {
848 			if (memcmp(name, "GNU", sizeof("GNU")) == 0) {
849 				size_t sz = min(size, descsz);
850 				memcpy(bf, ptr, sz);
851 				memset(bf + sz, 0, size - sz);
852 				err = sz;
853 				break;
854 			}
855 		}
856 		ptr += descsz;
857 	}
858 
859 out:
860 	return err;
861 }
862 
read_build_id(const char * filename,struct build_id * bid)863 static int read_build_id(const char *filename, struct build_id *bid)
864 {
865 	size_t size = sizeof(bid->data);
866 	int fd, err;
867 	Elf *elf;
868 
869 	err = libbfd__read_build_id(filename, bid);
870 	if (err >= 0)
871 		goto out;
872 
873 	if (size < BUILD_ID_SIZE)
874 		goto out;
875 
876 	fd = open(filename, O_RDONLY);
877 	if (fd < 0)
878 		goto out;
879 
880 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
881 	if (elf == NULL) {
882 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
883 		goto out_close;
884 	}
885 
886 	err = elf_read_build_id(elf, bid->data, size);
887 	if (err > 0)
888 		bid->size = err;
889 
890 	elf_end(elf);
891 out_close:
892 	close(fd);
893 out:
894 	return err;
895 }
896 
filename__read_build_id(const char * filename,struct build_id * bid)897 int filename__read_build_id(const char *filename, struct build_id *bid)
898 {
899 	struct kmod_path m = { .name = NULL, };
900 	char path[PATH_MAX];
901 	int err;
902 
903 	if (!filename)
904 		return -EFAULT;
905 	if (!is_regular_file(filename))
906 		return -EWOULDBLOCK;
907 
908 	err = kmod_path__parse(&m, filename);
909 	if (err)
910 		return -1;
911 
912 	if (m.comp) {
913 		int error = 0, fd;
914 
915 		fd = filename__decompress(filename, path, sizeof(path), m.comp, &error);
916 		if (fd < 0) {
917 			pr_debug("Failed to decompress (error %d) %s\n",
918 				 error, filename);
919 			return -1;
920 		}
921 		close(fd);
922 		filename = path;
923 	}
924 
925 	err = read_build_id(filename, bid);
926 
927 	if (m.comp)
928 		unlink(filename);
929 	return err;
930 }
931 
sysfs__read_build_id(const char * filename,struct build_id * bid)932 int sysfs__read_build_id(const char *filename, struct build_id *bid)
933 {
934 	size_t size = sizeof(bid->data);
935 	int fd, err = -1;
936 
937 	fd = open(filename, O_RDONLY);
938 	if (fd < 0)
939 		goto out;
940 
941 	while (1) {
942 		char bf[BUFSIZ];
943 		GElf_Nhdr nhdr;
944 		size_t namesz, descsz;
945 
946 		if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
947 			break;
948 
949 		namesz = NOTE_ALIGN(nhdr.n_namesz);
950 		descsz = NOTE_ALIGN(nhdr.n_descsz);
951 		if (nhdr.n_type == NT_GNU_BUILD_ID &&
952 		    nhdr.n_namesz == sizeof("GNU")) {
953 			if (read(fd, bf, namesz) != (ssize_t)namesz)
954 				break;
955 			if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
956 				size_t sz = min(descsz, size);
957 				if (read(fd, bid->data, sz) == (ssize_t)sz) {
958 					memset(bid->data + sz, 0, size - sz);
959 					bid->size = sz;
960 					err = 0;
961 					break;
962 				}
963 			} else if (read(fd, bf, descsz) != (ssize_t)descsz)
964 				break;
965 		} else {
966 			int n = namesz + descsz;
967 
968 			if (n > (int)sizeof(bf)) {
969 				n = sizeof(bf);
970 				pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
971 					 __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
972 			}
973 			if (read(fd, bf, n) != n)
974 				break;
975 		}
976 	}
977 	close(fd);
978 out:
979 	return err;
980 }
981 
filename__read_debuglink(const char * filename,char * debuglink,size_t size)982 int filename__read_debuglink(const char *filename, char *debuglink,
983 			     size_t size)
984 {
985 	int fd, err = -1;
986 	Elf *elf;
987 	GElf_Ehdr ehdr;
988 	GElf_Shdr shdr;
989 	Elf_Data *data;
990 	Elf_Scn *sec;
991 	Elf_Kind ek;
992 
993 	err = libbfd_filename__read_debuglink(filename, debuglink, size);
994 	if (err >= 0)
995 		goto out;
996 
997 	fd = open(filename, O_RDONLY);
998 	if (fd < 0)
999 		goto out;
1000 
1001 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1002 	if (elf == NULL) {
1003 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
1004 		goto out_close;
1005 	}
1006 
1007 	ek = elf_kind(elf);
1008 	if (ek != ELF_K_ELF)
1009 		goto out_elf_end;
1010 
1011 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1012 		pr_err("%s: cannot get elf header.\n", __func__);
1013 		goto out_elf_end;
1014 	}
1015 
1016 	sec = elf_section_by_name(elf, &ehdr, &shdr,
1017 				  ".gnu_debuglink", NULL);
1018 	if (sec == NULL)
1019 		goto out_elf_end;
1020 
1021 	data = elf_getdata(sec, NULL);
1022 	if (data == NULL)
1023 		goto out_elf_end;
1024 
1025 	/* the start of this section is a zero-terminated string */
1026 	strncpy(debuglink, data->d_buf, size);
1027 
1028 	err = 0;
1029 
1030 out_elf_end:
1031 	elf_end(elf);
1032 out_close:
1033 	close(fd);
1034 out:
1035 	return err;
1036 }
1037 
symsrc__possibly_runtime(struct symsrc * ss)1038 bool symsrc__possibly_runtime(struct symsrc *ss)
1039 {
1040 	return ss->dynsym || ss->opdsec;
1041 }
1042 
symsrc__has_symtab(struct symsrc * ss)1043 bool symsrc__has_symtab(struct symsrc *ss)
1044 {
1045 	return ss->symtab != NULL;
1046 }
1047 
symsrc__destroy(struct symsrc * ss)1048 void symsrc__destroy(struct symsrc *ss)
1049 {
1050 	zfree(&ss->name);
1051 	elf_end(ss->elf);
1052 	close(ss->fd);
1053 }
1054 
elf__needs_adjust_symbols(GElf_Ehdr ehdr)1055 bool elf__needs_adjust_symbols(GElf_Ehdr ehdr)
1056 {
1057 	/*
1058 	 * Usually vmlinux is an ELF file with type ET_EXEC for most
1059 	 * architectures; except Arm64 kernel is linked with option
1060 	 * '-share', so need to check type ET_DYN.
1061 	 */
1062 	return ehdr.e_type == ET_EXEC || ehdr.e_type == ET_REL ||
1063 	       ehdr.e_type == ET_DYN;
1064 }
1065 
read_gnu_debugdata(struct dso * dso,Elf * elf,const char * name,int * fd_ret)1066 static Elf *read_gnu_debugdata(struct dso *dso, Elf *elf, const char *name, int *fd_ret)
1067 {
1068 	Elf *elf_embedded;
1069 	GElf_Ehdr ehdr;
1070 	GElf_Shdr shdr;
1071 	Elf_Scn *scn;
1072 	Elf_Data *scn_data;
1073 	FILE *wrapped;
1074 	size_t shndx;
1075 	char temp_filename[] = "/tmp/perf.gnu_debugdata.elf.XXXXXX";
1076 	int ret, temp_fd;
1077 
1078 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1079 		pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1080 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1081 		return NULL;
1082 	}
1083 
1084 	scn = elf_section_by_name(elf, &ehdr, &shdr, ".gnu_debugdata", &shndx);
1085 	if (!scn) {
1086 		*dso__load_errno(dso) = -ENOENT;
1087 		return NULL;
1088 	}
1089 
1090 	if (shdr.sh_type == SHT_NOBITS) {
1091 		pr_debug("%s: .gnu_debugdata of ELF file %s has no data.\n", __func__, name);
1092 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1093 		return NULL;
1094 	}
1095 
1096 	scn_data = elf_rawdata(scn, NULL);
1097 	if (!scn_data) {
1098 		pr_debug("%s: error reading .gnu_debugdata of %s: %s\n", __func__,
1099 			 name, elf_errmsg(-1));
1100 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1101 		return NULL;
1102 	}
1103 
1104 	wrapped = fmemopen(scn_data->d_buf, scn_data->d_size, "r");
1105 	if (!wrapped) {
1106 		pr_debug("%s: fmemopen: %s\n", __func__, strerror(errno));
1107 		*dso__load_errno(dso) = -errno;
1108 		return NULL;
1109 	}
1110 
1111 	temp_fd = mkstemp(temp_filename);
1112 	if (temp_fd < 0) {
1113 		pr_debug("%s: mkstemp: %s\n", __func__, strerror(errno));
1114 		*dso__load_errno(dso) = -errno;
1115 		fclose(wrapped);
1116 		return NULL;
1117 	}
1118 	unlink(temp_filename);
1119 
1120 	ret = lzma_decompress_stream_to_file(wrapped, temp_fd);
1121 	fclose(wrapped);
1122 	if (ret < 0) {
1123 		*dso__load_errno(dso) = -errno;
1124 		close(temp_fd);
1125 		return NULL;
1126 	}
1127 
1128 	elf_embedded = elf_begin(temp_fd, PERF_ELF_C_READ_MMAP, NULL);
1129 	if (!elf_embedded) {
1130 		pr_debug("%s: error reading .gnu_debugdata of %s: %s\n", __func__,
1131 			 name, elf_errmsg(-1));
1132 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1133 		close(temp_fd);
1134 		return NULL;
1135 	}
1136 	pr_debug("%s: using .gnu_debugdata of %s\n", __func__, name);
1137 	*fd_ret = temp_fd;
1138 	return elf_embedded;
1139 }
1140 
symsrc__init(struct symsrc * ss,struct dso * dso,const char * name,enum dso_binary_type type)1141 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
1142 		 enum dso_binary_type type)
1143 {
1144 	GElf_Ehdr ehdr;
1145 	Elf *elf;
1146 	int fd;
1147 
1148 	if (dso__needs_decompress(dso)) {
1149 		fd = dso__decompress_kmodule_fd(dso, name);
1150 		if (fd < 0)
1151 			return -1;
1152 
1153 		type = dso__symtab_type(dso);
1154 	} else {
1155 		fd = open(name, O_RDONLY);
1156 		if (fd < 0) {
1157 			*dso__load_errno(dso) = errno;
1158 			return -1;
1159 		}
1160 	}
1161 
1162 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1163 	if (elf == NULL) {
1164 		pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1165 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1166 		goto out_close;
1167 	}
1168 
1169 	if (type == DSO_BINARY_TYPE__GNU_DEBUGDATA) {
1170 		int new_fd;
1171 		Elf *embedded = read_gnu_debugdata(dso, elf, name, &new_fd);
1172 
1173 		if (!embedded)
1174 			goto out_close;
1175 
1176 		elf_end(elf);
1177 		close(fd);
1178 		fd = new_fd;
1179 		elf = embedded;
1180 	}
1181 
1182 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1183 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1184 		pr_debug("%s: cannot get elf header.\n", __func__);
1185 		goto out_elf_end;
1186 	}
1187 
1188 	if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
1189 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INTERNAL_ERROR;
1190 		goto out_elf_end;
1191 	}
1192 
1193 	/* Always reject images with a mismatched build-id: */
1194 	if (dso__has_build_id(dso) && !symbol_conf.ignore_vmlinux_buildid) {
1195 		u8 build_id[BUILD_ID_SIZE];
1196 		struct build_id bid;
1197 		int size;
1198 
1199 		size = elf_read_build_id(elf, build_id, BUILD_ID_SIZE);
1200 		if (size <= 0) {
1201 			*dso__load_errno(dso) = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
1202 			goto out_elf_end;
1203 		}
1204 
1205 		build_id__init(&bid, build_id, size);
1206 		if (!dso__build_id_equal(dso, &bid)) {
1207 			pr_debug("%s: build id mismatch for %s.\n", __func__, name);
1208 			*dso__load_errno(dso) = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
1209 			goto out_elf_end;
1210 		}
1211 	}
1212 
1213 	ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1214 
1215 	ss->symtab_idx = 0;
1216 	ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
1217 			&ss->symtab_idx);
1218 	if (ss->symshdr.sh_type != SHT_SYMTAB)
1219 		ss->symtab = NULL;
1220 
1221 	ss->dynsym_idx = 0;
1222 	ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
1223 			&ss->dynsym_idx);
1224 	if (ss->dynshdr.sh_type != SHT_DYNSYM)
1225 		ss->dynsym = NULL;
1226 
1227 	ss->opdidx = 0;
1228 	ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
1229 			&ss->opdidx);
1230 	if (ss->opdshdr.sh_type != SHT_PROGBITS)
1231 		ss->opdsec = NULL;
1232 
1233 	if (dso__kernel(dso) == DSO_SPACE__USER)
1234 		ss->adjust_symbols = true;
1235 	else
1236 		ss->adjust_symbols = elf__needs_adjust_symbols(ehdr);
1237 
1238 	ss->name   = strdup(name);
1239 	if (!ss->name) {
1240 		*dso__load_errno(dso) = errno;
1241 		goto out_elf_end;
1242 	}
1243 
1244 	ss->elf    = elf;
1245 	ss->fd     = fd;
1246 	ss->ehdr   = ehdr;
1247 	ss->type   = type;
1248 
1249 	return 0;
1250 
1251 out_elf_end:
1252 	elf_end(elf);
1253 out_close:
1254 	close(fd);
1255 	return -1;
1256 }
1257 
is_exe_text(int flags)1258 static bool is_exe_text(int flags)
1259 {
1260 	return (flags & (SHF_ALLOC | SHF_EXECINSTR)) == (SHF_ALLOC | SHF_EXECINSTR);
1261 }
1262 
1263 /*
1264  * Some executable module sections like .noinstr.text might be laid out with
1265  * .text so they can use the same mapping (memory address to file offset).
1266  * Check if that is the case. Refer to kernel layout_sections(). Return the
1267  * maximum offset.
1268  */
max_text_section(Elf * elf,GElf_Ehdr * ehdr)1269 static u64 max_text_section(Elf *elf, GElf_Ehdr *ehdr)
1270 {
1271 	Elf_Scn *sec = NULL;
1272 	GElf_Shdr shdr;
1273 	u64 offs = 0;
1274 
1275 	/* Doesn't work for some arch */
1276 	if (ehdr->e_machine == EM_PARISC ||
1277 	    ehdr->e_machine == EM_ALPHA)
1278 		return 0;
1279 
1280 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1281 	if (!elf_rawdata(elf_getscn(elf, ehdr->e_shstrndx), NULL))
1282 		return 0;
1283 
1284 	while ((sec = elf_nextscn(elf, sec)) != NULL) {
1285 		char *sec_name;
1286 
1287 		if (!gelf_getshdr(sec, &shdr))
1288 			break;
1289 
1290 		if (!is_exe_text(shdr.sh_flags))
1291 			continue;
1292 
1293 		/* .init and .exit sections are not placed with .text */
1294 		sec_name = elf_strptr(elf, ehdr->e_shstrndx, shdr.sh_name);
1295 		if (!sec_name ||
1296 		    strstarts(sec_name, ".init") ||
1297 		    strstarts(sec_name, ".exit"))
1298 			break;
1299 
1300 		/* Must be next to previous, assumes .text is first */
1301 		if (offs && PERF_ALIGN(offs, shdr.sh_addralign ?: 1) != shdr.sh_offset)
1302 			break;
1303 
1304 		offs = shdr.sh_offset + shdr.sh_size;
1305 	}
1306 
1307 	return offs;
1308 }
1309 
1310 /**
1311  * ref_reloc_sym_not_found - has kernel relocation symbol been found.
1312  * @kmap: kernel maps and relocation reference symbol
1313  *
1314  * This function returns %true if we are dealing with the kernel maps and the
1315  * relocation reference symbol has not yet been found.  Otherwise %false is
1316  * returned.
1317  */
ref_reloc_sym_not_found(struct kmap * kmap)1318 static bool ref_reloc_sym_not_found(struct kmap *kmap)
1319 {
1320 	return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
1321 	       !kmap->ref_reloc_sym->unrelocated_addr;
1322 }
1323 
1324 /**
1325  * ref_reloc - kernel relocation offset.
1326  * @kmap: kernel maps and relocation reference symbol
1327  *
1328  * This function returns the offset of kernel addresses as determined by using
1329  * the relocation reference symbol i.e. if the kernel has not been relocated
1330  * then the return value is zero.
1331  */
ref_reloc(struct kmap * kmap)1332 static u64 ref_reloc(struct kmap *kmap)
1333 {
1334 	if (kmap && kmap->ref_reloc_sym &&
1335 	    kmap->ref_reloc_sym->unrelocated_addr)
1336 		return kmap->ref_reloc_sym->addr -
1337 		       kmap->ref_reloc_sym->unrelocated_addr;
1338 	return 0;
1339 }
1340 
arch__sym_update(struct symbol * s __maybe_unused,GElf_Sym * sym __maybe_unused)1341 void __weak arch__sym_update(struct symbol *s __maybe_unused,
1342 		GElf_Sym *sym __maybe_unused) { }
1343 
dso__process_kernel_symbol(struct dso * dso,struct map * map,GElf_Sym * sym,GElf_Shdr * shdr,struct maps * kmaps,struct kmap * kmap,struct dso ** curr_dsop,const char * section_name,bool adjust_kernel_syms,bool kmodule,bool * remap_kernel,u64 max_text_sh_offset)1344 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
1345 				      GElf_Sym *sym, GElf_Shdr *shdr,
1346 				      struct maps *kmaps, struct kmap *kmap,
1347 				      struct dso **curr_dsop,
1348 				      const char *section_name,
1349 				      bool adjust_kernel_syms, bool kmodule, bool *remap_kernel,
1350 				      u64 max_text_sh_offset)
1351 {
1352 	struct dso *curr_dso = *curr_dsop;
1353 	struct map *curr_map;
1354 	char dso_name[PATH_MAX];
1355 
1356 	/* Adjust symbol to map to file offset */
1357 	if (adjust_kernel_syms)
1358 		sym->st_value -= shdr->sh_addr - shdr->sh_offset;
1359 
1360 	if (strcmp(section_name, (dso__short_name(curr_dso) + dso__short_name_len(dso))) == 0)
1361 		return 0;
1362 
1363 	if (strcmp(section_name, ".text") == 0) {
1364 		/*
1365 		 * The initial kernel mapping is based on
1366 		 * kallsyms and identity maps.  Overwrite it to
1367 		 * map to the kernel dso.
1368 		 */
1369 		if (*remap_kernel && dso__kernel(dso) && !kmodule) {
1370 			*remap_kernel = false;
1371 			map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
1372 			map__set_end(map, map__start(map) + shdr->sh_size);
1373 			map__set_pgoff(map, shdr->sh_offset);
1374 			map__set_mapping_type(map, MAPPING_TYPE__DSO);
1375 			/* Ensure maps are correctly ordered */
1376 			if (kmaps) {
1377 				int err;
1378 				struct map *tmp = map__get(map);
1379 
1380 				maps__remove(kmaps, map);
1381 				err = maps__insert(kmaps, map);
1382 				map__put(tmp);
1383 				if (err)
1384 					return err;
1385 			}
1386 		}
1387 
1388 		/*
1389 		 * The initial module mapping is based on
1390 		 * /proc/modules mapped to offset zero.
1391 		 * Overwrite it to map to the module dso.
1392 		 */
1393 		if (*remap_kernel && kmodule) {
1394 			*remap_kernel = false;
1395 			map__set_pgoff(map, shdr->sh_offset);
1396 		}
1397 
1398 		dso__put(*curr_dsop);
1399 		*curr_dsop = dso__get(dso);
1400 		return 0;
1401 	}
1402 
1403 	if (!kmap)
1404 		return 0;
1405 
1406 	/*
1407 	 * perf does not record module section addresses except for .text, but
1408 	 * some sections can use the same mapping as .text.
1409 	 */
1410 	if (kmodule && adjust_kernel_syms && is_exe_text(shdr->sh_flags) &&
1411 	    shdr->sh_offset <= max_text_sh_offset) {
1412 		dso__put(*curr_dsop);
1413 		*curr_dsop = dso__get(dso);
1414 		return 0;
1415 	}
1416 
1417 	snprintf(dso_name, sizeof(dso_name), "%s%s", dso__short_name(dso), section_name);
1418 
1419 	curr_map = maps__find_by_name(kmaps, dso_name);
1420 	if (curr_map == NULL) {
1421 		u64 start = sym->st_value;
1422 
1423 		if (kmodule)
1424 			start += map__start(map) + shdr->sh_offset;
1425 
1426 		curr_dso = dso__new(dso_name);
1427 		if (curr_dso == NULL)
1428 			return -1;
1429 		dso__set_kernel(curr_dso, dso__kernel(dso));
1430 		RC_CHK_ACCESS(curr_dso)->long_name = dso__long_name(dso);
1431 		RC_CHK_ACCESS(curr_dso)->long_name_len = dso__long_name_len(dso);
1432 		dso__set_binary_type(curr_dso, dso__binary_type(dso));
1433 		dso__set_adjust_symbols(curr_dso, dso__adjust_symbols(dso));
1434 		curr_map = map__new2(start, curr_dso);
1435 		if (curr_map == NULL) {
1436 			dso__put(curr_dso);
1437 			return -1;
1438 		}
1439 		if (dso__kernel(curr_dso))
1440 			map__kmap(curr_map)->kmaps = kmaps;
1441 
1442 		if (adjust_kernel_syms) {
1443 			map__set_start(curr_map, shdr->sh_addr + ref_reloc(kmap));
1444 			map__set_end(curr_map, map__start(curr_map) + shdr->sh_size);
1445 			map__set_pgoff(curr_map, shdr->sh_offset);
1446 		} else {
1447 			map__set_mapping_type(curr_map, MAPPING_TYPE__IDENTITY);
1448 		}
1449 		dso__set_symtab_type(curr_dso, dso__symtab_type(dso));
1450 		if (maps__insert(kmaps, curr_map)) {
1451 			dso__put(curr_dso);
1452 			map__put(curr_map);
1453 			return -1;
1454 		}
1455 		dsos__add(&maps__machine(kmaps)->dsos, curr_dso);
1456 		dso__set_loaded(curr_dso);
1457 		dso__put(*curr_dsop);
1458 		*curr_dsop = curr_dso;
1459 	} else {
1460 		dso__put(*curr_dsop);
1461 		*curr_dsop = dso__get(map__dso(curr_map));
1462 	}
1463 	map__put(curr_map);
1464 
1465 	return 0;
1466 }
1467 
1468 static int
dso__load_sym_internal(struct dso * dso,struct map * map,struct symsrc * syms_ss,struct symsrc * runtime_ss,int kmodule,int dynsym)1469 dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1470 		       struct symsrc *runtime_ss, int kmodule, int dynsym)
1471 {
1472 	struct kmap *kmap = dso__kernel(dso) ? map__kmap(map) : NULL;
1473 	struct maps *kmaps = kmap ? map__kmaps(map) : NULL;
1474 	struct dso *curr_dso = NULL;
1475 	Elf_Data *symstrs, *secstrs, *secstrs_run, *secstrs_sym;
1476 	uint32_t nr_syms;
1477 	uint32_t idx;
1478 	GElf_Ehdr ehdr;
1479 	GElf_Shdr shdr;
1480 	GElf_Shdr tshdr;
1481 	Elf_Data *syms, *opddata = NULL;
1482 	GElf_Sym sym;
1483 	Elf_Scn *sec, *sec_strndx;
1484 	Elf *elf;
1485 	int nr = 0;
1486 	bool remap_kernel = false, adjust_kernel_syms = false;
1487 	u64 max_text_sh_offset = 0;
1488 
1489 	if (kmap && !kmaps)
1490 		return -1;
1491 
1492 	elf = syms_ss->elf;
1493 	ehdr = syms_ss->ehdr;
1494 	if (dynsym) {
1495 		sec  = syms_ss->dynsym;
1496 		shdr = syms_ss->dynshdr;
1497 	} else {
1498 		sec =  syms_ss->symtab;
1499 		shdr = syms_ss->symshdr;
1500 	}
1501 
1502 	if (elf_section_by_name(runtime_ss->elf, &runtime_ss->ehdr, &tshdr,
1503 				".text", NULL)) {
1504 		dso__set_text_offset(dso, tshdr.sh_addr - tshdr.sh_offset);
1505 		dso__set_text_end(dso, tshdr.sh_offset + tshdr.sh_size);
1506 	}
1507 
1508 	if (runtime_ss->opdsec)
1509 		opddata = elf_rawdata(runtime_ss->opdsec, NULL);
1510 
1511 	syms = elf_getdata(sec, NULL);
1512 	if (syms == NULL)
1513 		goto out_elf_end;
1514 
1515 	sec = elf_getscn(elf, shdr.sh_link);
1516 	if (sec == NULL)
1517 		goto out_elf_end;
1518 
1519 	symstrs = elf_getdata(sec, NULL);
1520 	if (symstrs == NULL)
1521 		goto out_elf_end;
1522 
1523 	sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
1524 	if (sec_strndx == NULL)
1525 		goto out_elf_end;
1526 
1527 	secstrs_run = elf_getdata(sec_strndx, NULL);
1528 	if (secstrs_run == NULL)
1529 		goto out_elf_end;
1530 
1531 	sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
1532 	if (sec_strndx == NULL)
1533 		goto out_elf_end;
1534 
1535 	secstrs_sym = elf_getdata(sec_strndx, NULL);
1536 	if (secstrs_sym == NULL)
1537 		goto out_elf_end;
1538 
1539 	nr_syms = shdr.sh_size / shdr.sh_entsize;
1540 
1541 	memset(&sym, 0, sizeof(sym));
1542 
1543 	/*
1544 	 * The kernel relocation symbol is needed in advance in order to adjust
1545 	 * kernel maps correctly.
1546 	 */
1547 	if (ref_reloc_sym_not_found(kmap)) {
1548 		elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1549 			const char *elf_name = elf_sym__name(&sym, symstrs);
1550 
1551 			if (strcmp(elf_name, kmap->ref_reloc_sym->name))
1552 				continue;
1553 			kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
1554 			map__set_reloc(map, kmap->ref_reloc_sym->addr - kmap->ref_reloc_sym->unrelocated_addr);
1555 			break;
1556 		}
1557 	}
1558 
1559 	/*
1560 	 * Handle any relocation of vdso necessary because older kernels
1561 	 * attempted to prelink vdso to its virtual address.
1562 	 */
1563 	if (dso__is_vdso(dso))
1564 		map__set_reloc(map, map__start(map) - dso__text_offset(dso));
1565 
1566 	dso__set_adjust_symbols(dso, runtime_ss->adjust_symbols || ref_reloc(kmap));
1567 	/*
1568 	 * Initial kernel and module mappings do not map to the dso.
1569 	 * Flag the fixups.
1570 	 */
1571 	if (dso__kernel(dso)) {
1572 		remap_kernel = true;
1573 		adjust_kernel_syms = dso__adjust_symbols(dso);
1574 	}
1575 
1576 	if (kmodule && adjust_kernel_syms)
1577 		max_text_sh_offset = max_text_section(runtime_ss->elf, &runtime_ss->ehdr);
1578 
1579 	curr_dso = dso__get(dso);
1580 	elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1581 		struct symbol *f;
1582 		const char *elf_name = elf_sym__name(&sym, symstrs);
1583 		char *demangled = NULL;
1584 		int is_label = elf_sym__is_label(&sym);
1585 		const char *section_name;
1586 		bool used_opd = false;
1587 
1588 		if (!is_label && !elf_sym__filter(&sym))
1589 			continue;
1590 
1591 		/* Reject ARM ELF "mapping symbols": these aren't unique and
1592 		 * don't identify functions, so will confuse the profile
1593 		 * output: */
1594 		if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
1595 			if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
1596 			    && (elf_name[2] == '\0' || elf_name[2] == '.'))
1597 				continue;
1598 		}
1599 
1600 		/* Reject RISCV ELF "mapping symbols" */
1601 		if (ehdr.e_machine == EM_RISCV) {
1602 			if (elf_name[0] == '$' && strchr("dx", elf_name[1]))
1603 				continue;
1604 		}
1605 
1606 		if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
1607 			u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
1608 			u64 *opd = opddata->d_buf + offset;
1609 			sym.st_value = DSO__SWAP(dso, u64, *opd);
1610 			sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
1611 					sym.st_value);
1612 			used_opd = true;
1613 		}
1614 
1615 		/*
1616 		 * When loading symbols in a data mapping, ABS symbols (which
1617 		 * has a value of SHN_ABS in its st_shndx) failed at
1618 		 * elf_getscn().  And it marks the loading as a failure so
1619 		 * already loaded symbols cannot be fixed up.
1620 		 *
1621 		 * I'm not sure what should be done. Just ignore them for now.
1622 		 * - Namhyung Kim
1623 		 */
1624 		if (sym.st_shndx == SHN_ABS)
1625 			continue;
1626 
1627 		sec = elf_getscn(syms_ss->elf, sym.st_shndx);
1628 		if (!sec)
1629 			goto out_elf_end;
1630 
1631 		gelf_getshdr(sec, &shdr);
1632 
1633 		/*
1634 		 * If the attribute bit SHF_ALLOC is not set, the section
1635 		 * doesn't occupy memory during process execution.
1636 		 * E.g. ".gnu.warning.*" section is used by linker to generate
1637 		 * warnings when calling deprecated functions, the symbols in
1638 		 * the section aren't loaded to memory during process execution,
1639 		 * so skip them.
1640 		 */
1641 		if (!(shdr.sh_flags & SHF_ALLOC))
1642 			continue;
1643 
1644 		secstrs = secstrs_sym;
1645 
1646 		/*
1647 		 * We have to fallback to runtime when syms' section header has
1648 		 * NOBITS set. NOBITS results in file offset (sh_offset) not
1649 		 * being incremented. So sh_offset used below has different
1650 		 * values for syms (invalid) and runtime (valid).
1651 		 */
1652 		if (shdr.sh_type == SHT_NOBITS) {
1653 			sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
1654 			if (!sec)
1655 				goto out_elf_end;
1656 
1657 			gelf_getshdr(sec, &shdr);
1658 			secstrs = secstrs_run;
1659 		}
1660 
1661 		if (is_label && !elf_sec__filter(&shdr, secstrs))
1662 			continue;
1663 
1664 		section_name = elf_sec__name(&shdr, secstrs);
1665 
1666 		/* On ARM, symbols for thumb functions have 1 added to
1667 		 * the symbol address as a flag - remove it */
1668 		if ((ehdr.e_machine == EM_ARM) &&
1669 		    (GELF_ST_TYPE(sym.st_info) == STT_FUNC) &&
1670 		    (sym.st_value & 1))
1671 			--sym.st_value;
1672 
1673 		if (dso__kernel(dso)) {
1674 			if (dso__process_kernel_symbol(dso, map, &sym, &shdr,
1675 						       kmaps, kmap, &curr_dso,
1676 						       section_name,
1677 						       adjust_kernel_syms,
1678 						       kmodule,
1679 						       &remap_kernel,
1680 						       max_text_sh_offset))
1681 				goto out_elf_end;
1682 		} else if ((used_opd && runtime_ss->adjust_symbols) ||
1683 			   (!used_opd && syms_ss->adjust_symbols)) {
1684 			GElf_Phdr phdr;
1685 
1686 			if (elf_read_program_header(runtime_ss->elf,
1687 						    (u64)sym.st_value, &phdr)) {
1688 				pr_debug4("%s: failed to find program header for "
1689 					   "symbol: %s st_value: %#" PRIx64 "\n",
1690 					   __func__, elf_name, (u64)sym.st_value);
1691 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1692 					"sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n",
1693 					__func__, (u64)sym.st_value, (u64)shdr.sh_addr,
1694 					(u64)shdr.sh_offset);
1695 				/*
1696 				 * Fail to find program header, let's rollback
1697 				 * to use shdr.sh_addr and shdr.sh_offset to
1698 				 * calibrate symbol's file address, though this
1699 				 * is not necessary for normal C ELF file, we
1700 				 * still need to handle java JIT symbols in this
1701 				 * case.
1702 				 */
1703 				sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1704 			} else {
1705 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1706 					"p_vaddr: %#" PRIx64 " p_offset: %#" PRIx64 "\n",
1707 					__func__, (u64)sym.st_value, (u64)phdr.p_vaddr,
1708 					(u64)phdr.p_offset);
1709 				sym.st_value -= phdr.p_vaddr - phdr.p_offset;
1710 			}
1711 		}
1712 
1713 		demangled = dso__demangle_sym(dso, kmodule, elf_name);
1714 		if (demangled != NULL)
1715 			elf_name = demangled;
1716 
1717 		f = symbol__new(sym.st_value, sym.st_size,
1718 				GELF_ST_BIND(sym.st_info),
1719 				GELF_ST_TYPE(sym.st_info), elf_name);
1720 		free(demangled);
1721 		if (!f)
1722 			goto out_elf_end;
1723 
1724 		arch__sym_update(f, &sym);
1725 
1726 		__symbols__insert(dso__symbols(curr_dso), f, dso__kernel(dso));
1727 		nr++;
1728 	}
1729 	dso__put(curr_dso);
1730 
1731 	/*
1732 	 * For misannotated, zeroed, ASM function sizes.
1733 	 */
1734 	if (nr > 0) {
1735 		symbols__fixup_end(dso__symbols(dso), false);
1736 		symbols__fixup_duplicate(dso__symbols(dso));
1737 		if (kmap) {
1738 			/*
1739 			 * We need to fixup this here too because we create new
1740 			 * maps here, for things like vsyscall sections.
1741 			 */
1742 			maps__fixup_end(kmaps);
1743 		}
1744 	}
1745 	return nr;
1746 out_elf_end:
1747 	dso__put(curr_dso);
1748 	return -1;
1749 }
1750 
dso__load_sym(struct dso * dso,struct map * map,struct symsrc * syms_ss,struct symsrc * runtime_ss,int kmodule)1751 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1752 		  struct symsrc *runtime_ss, int kmodule)
1753 {
1754 	int nr = 0;
1755 	int err = -1;
1756 
1757 	dso__set_symtab_type(dso, syms_ss->type);
1758 	dso__set_is_64_bit(dso, syms_ss->is_64_bit);
1759 	dso__set_rel(dso, syms_ss->ehdr.e_type == ET_REL);
1760 
1761 	/*
1762 	 * Modules may already have symbols from kallsyms, but those symbols
1763 	 * have the wrong values for the dso maps, so remove them.
1764 	 */
1765 	if (kmodule && syms_ss->symtab)
1766 		symbols__delete(dso__symbols(dso));
1767 
1768 	if (!syms_ss->symtab) {
1769 		/*
1770 		 * If the vmlinux is stripped, fail so we will fall back
1771 		 * to using kallsyms. The vmlinux runtime symbols aren't
1772 		 * of much use.
1773 		 */
1774 		if (dso__kernel(dso))
1775 			return err;
1776 	} else  {
1777 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1778 					     kmodule, 0);
1779 		if (err < 0)
1780 			return err;
1781 		nr = err;
1782 	}
1783 
1784 	if (syms_ss->dynsym) {
1785 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1786 					     kmodule, 1);
1787 		if (err < 0)
1788 			return err;
1789 		nr += err;
1790 	}
1791 
1792 	/*
1793 	 * The .gnu_debugdata is a special situation: it contains a symbol
1794 	 * table, but the runtime file may also contain dynsym entries which are
1795 	 * not present there. We need to load both.
1796 	 */
1797 	if (syms_ss->type == DSO_BINARY_TYPE__GNU_DEBUGDATA && runtime_ss->dynsym) {
1798 		err = dso__load_sym_internal(dso, map, runtime_ss, runtime_ss,
1799 					     kmodule, 1);
1800 		if (err < 0)
1801 			return err;
1802 		nr += err;
1803 	}
1804 
1805 	return nr;
1806 }
1807 
elf_read_maps(Elf * elf,bool exe,mapfn_t mapfn,void * data)1808 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1809 {
1810 	GElf_Phdr phdr;
1811 	size_t i, phdrnum;
1812 	int err;
1813 	u64 sz;
1814 
1815 	if (elf_getphdrnum(elf, &phdrnum))
1816 		return -1;
1817 
1818 	for (i = 0; i < phdrnum; i++) {
1819 		if (gelf_getphdr(elf, i, &phdr) == NULL)
1820 			return -1;
1821 		if (phdr.p_type != PT_LOAD)
1822 			continue;
1823 		if (exe) {
1824 			if (!(phdr.p_flags & PF_X))
1825 				continue;
1826 		} else {
1827 			if (!(phdr.p_flags & PF_R))
1828 				continue;
1829 		}
1830 		sz = min(phdr.p_memsz, phdr.p_filesz);
1831 		if (!sz)
1832 			continue;
1833 		err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1834 		if (err)
1835 			return err;
1836 	}
1837 	return 0;
1838 }
1839 
file__read_maps(int fd,bool exe,mapfn_t mapfn,void * data,bool * is_64_bit)1840 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1841 		    bool *is_64_bit)
1842 {
1843 	int err;
1844 	Elf *elf;
1845 
1846 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1847 	if (elf == NULL)
1848 		return -1;
1849 
1850 	if (is_64_bit)
1851 		*is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1852 
1853 	err = elf_read_maps(elf, exe, mapfn, data);
1854 
1855 	elf_end(elf);
1856 	return err;
1857 }
1858 
dso__type_fd(int fd)1859 enum dso_type dso__type_fd(int fd)
1860 {
1861 	enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1862 	GElf_Ehdr ehdr;
1863 	Elf_Kind ek;
1864 	Elf *elf;
1865 
1866 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1867 	if (elf == NULL)
1868 		goto out;
1869 
1870 	ek = elf_kind(elf);
1871 	if (ek != ELF_K_ELF)
1872 		goto out_end;
1873 
1874 	if (gelf_getclass(elf) == ELFCLASS64) {
1875 		dso_type = DSO__TYPE_64BIT;
1876 		goto out_end;
1877 	}
1878 
1879 	if (gelf_getehdr(elf, &ehdr) == NULL)
1880 		goto out_end;
1881 
1882 	if (ehdr.e_machine == EM_X86_64)
1883 		dso_type = DSO__TYPE_X32BIT;
1884 	else
1885 		dso_type = DSO__TYPE_32BIT;
1886 out_end:
1887 	elf_end(elf);
1888 out:
1889 	return dso_type;
1890 }
1891 
copy_bytes(int from,off_t from_offs,int to,off_t to_offs,u64 len)1892 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1893 {
1894 	ssize_t r;
1895 	size_t n;
1896 	int err = -1;
1897 	char *buf = malloc(page_size);
1898 
1899 	if (buf == NULL)
1900 		return -1;
1901 
1902 	if (lseek(to, to_offs, SEEK_SET) != to_offs)
1903 		goto out;
1904 
1905 	if (lseek(from, from_offs, SEEK_SET) != from_offs)
1906 		goto out;
1907 
1908 	while (len) {
1909 		n = page_size;
1910 		if (len < n)
1911 			n = len;
1912 		/* Use read because mmap won't work on proc files */
1913 		r = read(from, buf, n);
1914 		if (r < 0)
1915 			goto out;
1916 		if (!r)
1917 			break;
1918 		n = r;
1919 		r = write(to, buf, n);
1920 		if (r < 0)
1921 			goto out;
1922 		if ((size_t)r != n)
1923 			goto out;
1924 		len -= n;
1925 	}
1926 
1927 	err = 0;
1928 out:
1929 	free(buf);
1930 	return err;
1931 }
1932 
1933 struct kcore {
1934 	int fd;
1935 	int elfclass;
1936 	Elf *elf;
1937 	GElf_Ehdr ehdr;
1938 };
1939 
kcore__open(struct kcore * kcore,const char * filename)1940 static int kcore__open(struct kcore *kcore, const char *filename)
1941 {
1942 	GElf_Ehdr *ehdr;
1943 
1944 	kcore->fd = open(filename, O_RDONLY);
1945 	if (kcore->fd == -1)
1946 		return -1;
1947 
1948 	kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1949 	if (!kcore->elf)
1950 		goto out_close;
1951 
1952 	kcore->elfclass = gelf_getclass(kcore->elf);
1953 	if (kcore->elfclass == ELFCLASSNONE)
1954 		goto out_end;
1955 
1956 	ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1957 	if (!ehdr)
1958 		goto out_end;
1959 
1960 	return 0;
1961 
1962 out_end:
1963 	elf_end(kcore->elf);
1964 out_close:
1965 	close(kcore->fd);
1966 	return -1;
1967 }
1968 
kcore__init(struct kcore * kcore,char * filename,int elfclass,bool temp)1969 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1970 		       bool temp)
1971 {
1972 	kcore->elfclass = elfclass;
1973 
1974 	if (temp)
1975 		kcore->fd = mkstemp(filename);
1976 	else
1977 		kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0400);
1978 	if (kcore->fd == -1)
1979 		return -1;
1980 
1981 	kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1982 	if (!kcore->elf)
1983 		goto out_close;
1984 
1985 	if (!gelf_newehdr(kcore->elf, elfclass))
1986 		goto out_end;
1987 
1988 	memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
1989 
1990 	return 0;
1991 
1992 out_end:
1993 	elf_end(kcore->elf);
1994 out_close:
1995 	close(kcore->fd);
1996 	unlink(filename);
1997 	return -1;
1998 }
1999 
kcore__close(struct kcore * kcore)2000 static void kcore__close(struct kcore *kcore)
2001 {
2002 	elf_end(kcore->elf);
2003 	close(kcore->fd);
2004 }
2005 
kcore__copy_hdr(struct kcore * from,struct kcore * to,size_t count)2006 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
2007 {
2008 	GElf_Ehdr *ehdr = &to->ehdr;
2009 	GElf_Ehdr *kehdr = &from->ehdr;
2010 
2011 	memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
2012 	ehdr->e_type      = kehdr->e_type;
2013 	ehdr->e_machine   = kehdr->e_machine;
2014 	ehdr->e_version   = kehdr->e_version;
2015 	ehdr->e_entry     = 0;
2016 	ehdr->e_shoff     = 0;
2017 	ehdr->e_flags     = kehdr->e_flags;
2018 	ehdr->e_phnum     = count;
2019 	ehdr->e_shentsize = 0;
2020 	ehdr->e_shnum     = 0;
2021 	ehdr->e_shstrndx  = 0;
2022 
2023 	if (from->elfclass == ELFCLASS32) {
2024 		ehdr->e_phoff     = sizeof(Elf32_Ehdr);
2025 		ehdr->e_ehsize    = sizeof(Elf32_Ehdr);
2026 		ehdr->e_phentsize = sizeof(Elf32_Phdr);
2027 	} else {
2028 		ehdr->e_phoff     = sizeof(Elf64_Ehdr);
2029 		ehdr->e_ehsize    = sizeof(Elf64_Ehdr);
2030 		ehdr->e_phentsize = sizeof(Elf64_Phdr);
2031 	}
2032 
2033 	if (!gelf_update_ehdr(to->elf, ehdr))
2034 		return -1;
2035 
2036 	if (!gelf_newphdr(to->elf, count))
2037 		return -1;
2038 
2039 	return 0;
2040 }
2041 
kcore__add_phdr(struct kcore * kcore,int idx,off_t offset,u64 addr,u64 len)2042 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
2043 			   u64 addr, u64 len)
2044 {
2045 	GElf_Phdr phdr = {
2046 		.p_type		= PT_LOAD,
2047 		.p_flags	= PF_R | PF_W | PF_X,
2048 		.p_offset	= offset,
2049 		.p_vaddr	= addr,
2050 		.p_paddr	= 0,
2051 		.p_filesz	= len,
2052 		.p_memsz	= len,
2053 		.p_align	= page_size,
2054 	};
2055 
2056 	if (!gelf_update_phdr(kcore->elf, idx, &phdr))
2057 		return -1;
2058 
2059 	return 0;
2060 }
2061 
kcore__write(struct kcore * kcore)2062 static off_t kcore__write(struct kcore *kcore)
2063 {
2064 	return elf_update(kcore->elf, ELF_C_WRITE);
2065 }
2066 
2067 struct phdr_data {
2068 	off_t offset;
2069 	off_t rel;
2070 	u64 addr;
2071 	u64 len;
2072 	struct list_head node;
2073 	struct phdr_data *remaps;
2074 };
2075 
2076 struct sym_data {
2077 	u64 addr;
2078 	struct list_head node;
2079 };
2080 
2081 struct kcore_copy_info {
2082 	u64 stext;
2083 	u64 etext;
2084 	u64 first_symbol;
2085 	u64 last_symbol;
2086 	u64 first_module;
2087 	u64 first_module_symbol;
2088 	u64 last_module_symbol;
2089 	size_t phnum;
2090 	struct list_head phdrs;
2091 	struct list_head syms;
2092 };
2093 
2094 #define kcore_copy__for_each_phdr(k, p) \
2095 	list_for_each_entry((p), &(k)->phdrs, node)
2096 
phdr_data__new(u64 addr,u64 len,off_t offset)2097 static struct phdr_data *phdr_data__new(u64 addr, u64 len, off_t offset)
2098 {
2099 	struct phdr_data *p = zalloc(sizeof(*p));
2100 
2101 	if (p) {
2102 		p->addr   = addr;
2103 		p->len    = len;
2104 		p->offset = offset;
2105 	}
2106 
2107 	return p;
2108 }
2109 
kcore_copy_info__addnew(struct kcore_copy_info * kci,u64 addr,u64 len,off_t offset)2110 static struct phdr_data *kcore_copy_info__addnew(struct kcore_copy_info *kci,
2111 						 u64 addr, u64 len,
2112 						 off_t offset)
2113 {
2114 	struct phdr_data *p = phdr_data__new(addr, len, offset);
2115 
2116 	if (p)
2117 		list_add_tail(&p->node, &kci->phdrs);
2118 
2119 	return p;
2120 }
2121 
kcore_copy__free_phdrs(struct kcore_copy_info * kci)2122 static void kcore_copy__free_phdrs(struct kcore_copy_info *kci)
2123 {
2124 	struct phdr_data *p, *tmp;
2125 
2126 	list_for_each_entry_safe(p, tmp, &kci->phdrs, node) {
2127 		list_del_init(&p->node);
2128 		free(p);
2129 	}
2130 }
2131 
kcore_copy__new_sym(struct kcore_copy_info * kci,u64 addr)2132 static struct sym_data *kcore_copy__new_sym(struct kcore_copy_info *kci,
2133 					    u64 addr)
2134 {
2135 	struct sym_data *s = zalloc(sizeof(*s));
2136 
2137 	if (s) {
2138 		s->addr = addr;
2139 		list_add_tail(&s->node, &kci->syms);
2140 	}
2141 
2142 	return s;
2143 }
2144 
kcore_copy__free_syms(struct kcore_copy_info * kci)2145 static void kcore_copy__free_syms(struct kcore_copy_info *kci)
2146 {
2147 	struct sym_data *s, *tmp;
2148 
2149 	list_for_each_entry_safe(s, tmp, &kci->syms, node) {
2150 		list_del_init(&s->node);
2151 		free(s);
2152 	}
2153 }
2154 
kcore_copy__process_kallsyms(void * arg,const char * name,char type,u64 start)2155 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
2156 					u64 start)
2157 {
2158 	struct kcore_copy_info *kci = arg;
2159 
2160 	if (!kallsyms__is_function(type))
2161 		return 0;
2162 
2163 	if (strchr(name, '[')) {
2164 		if (!kci->first_module_symbol || start < kci->first_module_symbol)
2165 			kci->first_module_symbol = start;
2166 		if (start > kci->last_module_symbol)
2167 			kci->last_module_symbol = start;
2168 		return 0;
2169 	}
2170 
2171 	if (!kci->first_symbol || start < kci->first_symbol)
2172 		kci->first_symbol = start;
2173 
2174 	if (!kci->last_symbol || start > kci->last_symbol)
2175 		kci->last_symbol = start;
2176 
2177 	if (!strcmp(name, "_stext")) {
2178 		kci->stext = start;
2179 		return 0;
2180 	}
2181 
2182 	if (!strcmp(name, "_etext")) {
2183 		kci->etext = start;
2184 		return 0;
2185 	}
2186 
2187 	if (is_entry_trampoline(name) && !kcore_copy__new_sym(kci, start))
2188 		return -1;
2189 
2190 	return 0;
2191 }
2192 
kcore_copy__parse_kallsyms(struct kcore_copy_info * kci,const char * dir)2193 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
2194 				      const char *dir)
2195 {
2196 	char kallsyms_filename[PATH_MAX];
2197 
2198 	scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
2199 
2200 	if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
2201 		return -1;
2202 
2203 	if (kallsyms__parse(kallsyms_filename, kci,
2204 			    kcore_copy__process_kallsyms) < 0)
2205 		return -1;
2206 
2207 	return 0;
2208 }
2209 
kcore_copy__process_modules(void * arg,const char * name __maybe_unused,u64 start,u64 size __maybe_unused)2210 static int kcore_copy__process_modules(void *arg,
2211 				       const char *name __maybe_unused,
2212 				       u64 start, u64 size __maybe_unused)
2213 {
2214 	struct kcore_copy_info *kci = arg;
2215 
2216 	if (!kci->first_module || start < kci->first_module)
2217 		kci->first_module = start;
2218 
2219 	return 0;
2220 }
2221 
kcore_copy__parse_modules(struct kcore_copy_info * kci,const char * dir)2222 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
2223 				     const char *dir)
2224 {
2225 	char modules_filename[PATH_MAX];
2226 
2227 	scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
2228 
2229 	if (symbol__restricted_filename(modules_filename, "/proc/modules"))
2230 		return -1;
2231 
2232 	if (modules__parse(modules_filename, kci,
2233 			   kcore_copy__process_modules) < 0)
2234 		return -1;
2235 
2236 	return 0;
2237 }
2238 
kcore_copy__map(struct kcore_copy_info * kci,u64 start,u64 end,u64 pgoff,u64 s,u64 e)2239 static int kcore_copy__map(struct kcore_copy_info *kci, u64 start, u64 end,
2240 			   u64 pgoff, u64 s, u64 e)
2241 {
2242 	u64 len, offset;
2243 
2244 	if (s < start || s >= end)
2245 		return 0;
2246 
2247 	offset = (s - start) + pgoff;
2248 	len = e < end ? e - s : end - s;
2249 
2250 	return kcore_copy_info__addnew(kci, s, len, offset) ? 0 : -1;
2251 }
2252 
kcore_copy__read_map(u64 start,u64 len,u64 pgoff,void * data)2253 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
2254 {
2255 	struct kcore_copy_info *kci = data;
2256 	u64 end = start + len;
2257 	struct sym_data *sdat;
2258 
2259 	if (kcore_copy__map(kci, start, end, pgoff, kci->stext, kci->etext))
2260 		return -1;
2261 
2262 	if (kcore_copy__map(kci, start, end, pgoff, kci->first_module,
2263 			    kci->last_module_symbol))
2264 		return -1;
2265 
2266 	list_for_each_entry(sdat, &kci->syms, node) {
2267 		u64 s = round_down(sdat->addr, page_size);
2268 
2269 		if (kcore_copy__map(kci, start, end, pgoff, s, s + len))
2270 			return -1;
2271 	}
2272 
2273 	return 0;
2274 }
2275 
kcore_copy__read_maps(struct kcore_copy_info * kci,Elf * elf)2276 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
2277 {
2278 	if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
2279 		return -1;
2280 
2281 	return 0;
2282 }
2283 
kcore_copy__find_remaps(struct kcore_copy_info * kci)2284 static void kcore_copy__find_remaps(struct kcore_copy_info *kci)
2285 {
2286 	struct phdr_data *p, *k = NULL;
2287 	u64 kend;
2288 
2289 	if (!kci->stext)
2290 		return;
2291 
2292 	/* Find phdr that corresponds to the kernel map (contains stext) */
2293 	kcore_copy__for_each_phdr(kci, p) {
2294 		u64 pend = p->addr + p->len - 1;
2295 
2296 		if (p->addr <= kci->stext && pend >= kci->stext) {
2297 			k = p;
2298 			break;
2299 		}
2300 	}
2301 
2302 	if (!k)
2303 		return;
2304 
2305 	kend = k->offset + k->len;
2306 
2307 	/* Find phdrs that remap the kernel */
2308 	kcore_copy__for_each_phdr(kci, p) {
2309 		u64 pend = p->offset + p->len;
2310 
2311 		if (p == k)
2312 			continue;
2313 
2314 		if (p->offset >= k->offset && pend <= kend)
2315 			p->remaps = k;
2316 	}
2317 }
2318 
kcore_copy__layout(struct kcore_copy_info * kci)2319 static void kcore_copy__layout(struct kcore_copy_info *kci)
2320 {
2321 	struct phdr_data *p;
2322 	off_t rel = 0;
2323 
2324 	kcore_copy__find_remaps(kci);
2325 
2326 	kcore_copy__for_each_phdr(kci, p) {
2327 		if (!p->remaps) {
2328 			p->rel = rel;
2329 			rel += p->len;
2330 		}
2331 		kci->phnum += 1;
2332 	}
2333 
2334 	kcore_copy__for_each_phdr(kci, p) {
2335 		struct phdr_data *k = p->remaps;
2336 
2337 		if (k)
2338 			p->rel = p->offset - k->offset + k->rel;
2339 	}
2340 }
2341 
kcore_copy__calc_maps(struct kcore_copy_info * kci,const char * dir,Elf * elf)2342 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
2343 				 Elf *elf)
2344 {
2345 	if (kcore_copy__parse_kallsyms(kci, dir))
2346 		return -1;
2347 
2348 	if (kcore_copy__parse_modules(kci, dir))
2349 		return -1;
2350 
2351 	if (kci->stext)
2352 		kci->stext = round_down(kci->stext, page_size);
2353 	else
2354 		kci->stext = round_down(kci->first_symbol, page_size);
2355 
2356 	if (kci->etext) {
2357 		kci->etext = round_up(kci->etext, page_size);
2358 	} else if (kci->last_symbol) {
2359 		kci->etext = round_up(kci->last_symbol, page_size);
2360 		kci->etext += page_size;
2361 	}
2362 
2363 	if (kci->first_module_symbol &&
2364 	    (!kci->first_module || kci->first_module_symbol < kci->first_module))
2365 		kci->first_module = kci->first_module_symbol;
2366 
2367 	kci->first_module = round_down(kci->first_module, page_size);
2368 
2369 	if (kci->last_module_symbol) {
2370 		kci->last_module_symbol = round_up(kci->last_module_symbol,
2371 						   page_size);
2372 		kci->last_module_symbol += page_size;
2373 	}
2374 
2375 	if (!kci->stext || !kci->etext)
2376 		return -1;
2377 
2378 	if (kci->first_module && !kci->last_module_symbol)
2379 		return -1;
2380 
2381 	if (kcore_copy__read_maps(kci, elf))
2382 		return -1;
2383 
2384 	kcore_copy__layout(kci);
2385 
2386 	return 0;
2387 }
2388 
kcore_copy__copy_file(const char * from_dir,const char * to_dir,const char * name)2389 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
2390 				 const char *name)
2391 {
2392 	char from_filename[PATH_MAX];
2393 	char to_filename[PATH_MAX];
2394 
2395 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2396 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2397 
2398 	return copyfile_mode(from_filename, to_filename, 0400);
2399 }
2400 
kcore_copy__unlink(const char * dir,const char * name)2401 static int kcore_copy__unlink(const char *dir, const char *name)
2402 {
2403 	char filename[PATH_MAX];
2404 
2405 	scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
2406 
2407 	return unlink(filename);
2408 }
2409 
kcore_copy__compare_fds(int from,int to)2410 static int kcore_copy__compare_fds(int from, int to)
2411 {
2412 	char *buf_from;
2413 	char *buf_to;
2414 	ssize_t ret;
2415 	size_t len;
2416 	int err = -1;
2417 
2418 	buf_from = malloc(page_size);
2419 	buf_to = malloc(page_size);
2420 	if (!buf_from || !buf_to)
2421 		goto out;
2422 
2423 	while (1) {
2424 		/* Use read because mmap won't work on proc files */
2425 		ret = read(from, buf_from, page_size);
2426 		if (ret < 0)
2427 			goto out;
2428 
2429 		if (!ret)
2430 			break;
2431 
2432 		len = ret;
2433 
2434 		if (readn(to, buf_to, len) != (int)len)
2435 			goto out;
2436 
2437 		if (memcmp(buf_from, buf_to, len))
2438 			goto out;
2439 	}
2440 
2441 	err = 0;
2442 out:
2443 	free(buf_to);
2444 	free(buf_from);
2445 	return err;
2446 }
2447 
kcore_copy__compare_files(const char * from_filename,const char * to_filename)2448 static int kcore_copy__compare_files(const char *from_filename,
2449 				     const char *to_filename)
2450 {
2451 	int from, to, err = -1;
2452 
2453 	from = open(from_filename, O_RDONLY);
2454 	if (from < 0)
2455 		return -1;
2456 
2457 	to = open(to_filename, O_RDONLY);
2458 	if (to < 0)
2459 		goto out_close_from;
2460 
2461 	err = kcore_copy__compare_fds(from, to);
2462 
2463 	close(to);
2464 out_close_from:
2465 	close(from);
2466 	return err;
2467 }
2468 
kcore_copy__compare_file(const char * from_dir,const char * to_dir,const char * name)2469 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
2470 				    const char *name)
2471 {
2472 	char from_filename[PATH_MAX];
2473 	char to_filename[PATH_MAX];
2474 
2475 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2476 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2477 
2478 	return kcore_copy__compare_files(from_filename, to_filename);
2479 }
2480 
2481 /**
2482  * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
2483  * @from_dir: from directory
2484  * @to_dir: to directory
2485  *
2486  * This function copies kallsyms, modules and kcore files from one directory to
2487  * another.  kallsyms and modules are copied entirely.  Only code segments are
2488  * copied from kcore.  It is assumed that two segments suffice: one for the
2489  * kernel proper and one for all the modules.  The code segments are determined
2490  * from kallsyms and modules files.  The kernel map starts at _stext or the
2491  * lowest function symbol, and ends at _etext or the highest function symbol.
2492  * The module map starts at the lowest module address and ends at the highest
2493  * module symbol.  Start addresses are rounded down to the nearest page.  End
2494  * addresses are rounded up to the nearest page.  An extra page is added to the
2495  * highest kernel symbol and highest module symbol to, hopefully, encompass that
2496  * symbol too.  Because it contains only code sections, the resulting kcore is
2497  * unusual.  One significant peculiarity is that the mapping (start -> pgoff)
2498  * is not the same for the kernel map and the modules map.  That happens because
2499  * the data is copied adjacently whereas the original kcore has gaps.  Finally,
2500  * kallsyms file is compared with its copy to check that modules have not been
2501  * loaded or unloaded while the copies were taking place.
2502  *
2503  * Return: %0 on success, %-1 on failure.
2504  */
kcore_copy(const char * from_dir,const char * to_dir)2505 int kcore_copy(const char *from_dir, const char *to_dir)
2506 {
2507 	struct kcore kcore;
2508 	struct kcore extract;
2509 	int idx = 0, err = -1;
2510 	off_t offset, sz;
2511 	struct kcore_copy_info kci = { .stext = 0, };
2512 	char kcore_filename[PATH_MAX];
2513 	char extract_filename[PATH_MAX];
2514 	struct phdr_data *p;
2515 
2516 	INIT_LIST_HEAD(&kci.phdrs);
2517 	INIT_LIST_HEAD(&kci.syms);
2518 
2519 	if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
2520 		return -1;
2521 
2522 	if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
2523 		goto out_unlink_kallsyms;
2524 
2525 	scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
2526 	scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
2527 
2528 	if (kcore__open(&kcore, kcore_filename))
2529 		goto out_unlink_modules;
2530 
2531 	if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
2532 		goto out_kcore_close;
2533 
2534 	if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
2535 		goto out_kcore_close;
2536 
2537 	if (kcore__copy_hdr(&kcore, &extract, kci.phnum))
2538 		goto out_extract_close;
2539 
2540 	offset = gelf_fsize(extract.elf, ELF_T_EHDR, 1, EV_CURRENT) +
2541 		 gelf_fsize(extract.elf, ELF_T_PHDR, kci.phnum, EV_CURRENT);
2542 	offset = round_up(offset, page_size);
2543 
2544 	kcore_copy__for_each_phdr(&kci, p) {
2545 		off_t offs = p->rel + offset;
2546 
2547 		if (kcore__add_phdr(&extract, idx++, offs, p->addr, p->len))
2548 			goto out_extract_close;
2549 	}
2550 
2551 	sz = kcore__write(&extract);
2552 	if (sz < 0 || sz > offset)
2553 		goto out_extract_close;
2554 
2555 	kcore_copy__for_each_phdr(&kci, p) {
2556 		off_t offs = p->rel + offset;
2557 
2558 		if (p->remaps)
2559 			continue;
2560 		if (copy_bytes(kcore.fd, p->offset, extract.fd, offs, p->len))
2561 			goto out_extract_close;
2562 	}
2563 
2564 	if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
2565 		goto out_extract_close;
2566 
2567 	err = 0;
2568 
2569 out_extract_close:
2570 	kcore__close(&extract);
2571 	if (err)
2572 		unlink(extract_filename);
2573 out_kcore_close:
2574 	kcore__close(&kcore);
2575 out_unlink_modules:
2576 	if (err)
2577 		kcore_copy__unlink(to_dir, "modules");
2578 out_unlink_kallsyms:
2579 	if (err)
2580 		kcore_copy__unlink(to_dir, "kallsyms");
2581 
2582 	kcore_copy__free_phdrs(&kci);
2583 	kcore_copy__free_syms(&kci);
2584 
2585 	return err;
2586 }
2587 
kcore_extract__create(struct kcore_extract * kce)2588 int kcore_extract__create(struct kcore_extract *kce)
2589 {
2590 	struct kcore kcore;
2591 	struct kcore extract;
2592 	size_t count = 1;
2593 	int idx = 0, err = -1;
2594 	off_t offset = page_size, sz;
2595 
2596 	if (kcore__open(&kcore, kce->kcore_filename))
2597 		return -1;
2598 
2599 	strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
2600 	if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
2601 		goto out_kcore_close;
2602 
2603 	if (kcore__copy_hdr(&kcore, &extract, count))
2604 		goto out_extract_close;
2605 
2606 	if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
2607 		goto out_extract_close;
2608 
2609 	sz = kcore__write(&extract);
2610 	if (sz < 0 || sz > offset)
2611 		goto out_extract_close;
2612 
2613 	if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
2614 		goto out_extract_close;
2615 
2616 	err = 0;
2617 
2618 out_extract_close:
2619 	kcore__close(&extract);
2620 	if (err)
2621 		unlink(kce->extract_filename);
2622 out_kcore_close:
2623 	kcore__close(&kcore);
2624 
2625 	return err;
2626 }
2627 
kcore_extract__delete(struct kcore_extract * kce)2628 void kcore_extract__delete(struct kcore_extract *kce)
2629 {
2630 	unlink(kce->extract_filename);
2631 }
2632 
2633 #ifdef HAVE_GELF_GETNOTE_SUPPORT
2634 
sdt_adjust_loc(struct sdt_note * tmp,GElf_Addr base_off)2635 static void sdt_adjust_loc(struct sdt_note *tmp, GElf_Addr base_off)
2636 {
2637 	if (!base_off)
2638 		return;
2639 
2640 	if (tmp->bit32)
2641 		tmp->addr.a32[SDT_NOTE_IDX_LOC] =
2642 			tmp->addr.a32[SDT_NOTE_IDX_LOC] + base_off -
2643 			tmp->addr.a32[SDT_NOTE_IDX_BASE];
2644 	else
2645 		tmp->addr.a64[SDT_NOTE_IDX_LOC] =
2646 			tmp->addr.a64[SDT_NOTE_IDX_LOC] + base_off -
2647 			tmp->addr.a64[SDT_NOTE_IDX_BASE];
2648 }
2649 
sdt_adjust_refctr(struct sdt_note * tmp,GElf_Addr base_addr,GElf_Addr base_off)2650 static void sdt_adjust_refctr(struct sdt_note *tmp, GElf_Addr base_addr,
2651 			      GElf_Addr base_off)
2652 {
2653 	if (!base_off)
2654 		return;
2655 
2656 	if (tmp->bit32 && tmp->addr.a32[SDT_NOTE_IDX_REFCTR])
2657 		tmp->addr.a32[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2658 	else if (tmp->addr.a64[SDT_NOTE_IDX_REFCTR])
2659 		tmp->addr.a64[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2660 }
2661 
2662 /**
2663  * populate_sdt_note : Parse raw data and identify SDT note
2664  * @elf: elf of the opened file
2665  * @data: raw data of a section with description offset applied
2666  * @len: note description size
2667  * @type: type of the note
2668  * @sdt_notes: List to add the SDT note
2669  *
2670  * Responsible for parsing the @data in section .note.stapsdt in @elf and
2671  * if its an SDT note, it appends to @sdt_notes list.
2672  */
populate_sdt_note(Elf ** elf,const char * data,size_t len,struct list_head * sdt_notes)2673 static int populate_sdt_note(Elf **elf, const char *data, size_t len,
2674 			     struct list_head *sdt_notes)
2675 {
2676 	const char *provider, *name, *args;
2677 	struct sdt_note *tmp = NULL;
2678 	GElf_Ehdr ehdr;
2679 	GElf_Shdr shdr;
2680 	int ret = -EINVAL;
2681 
2682 	union {
2683 		Elf64_Addr a64[NR_ADDR];
2684 		Elf32_Addr a32[NR_ADDR];
2685 	} buf;
2686 
2687 	Elf_Data dst = {
2688 		.d_buf = &buf, .d_type = ELF_T_ADDR, .d_version = EV_CURRENT,
2689 		.d_size = gelf_fsize((*elf), ELF_T_ADDR, NR_ADDR, EV_CURRENT),
2690 		.d_off = 0, .d_align = 0
2691 	};
2692 	Elf_Data src = {
2693 		.d_buf = (void *) data, .d_type = ELF_T_ADDR,
2694 		.d_version = EV_CURRENT, .d_size = dst.d_size, .d_off = 0,
2695 		.d_align = 0
2696 	};
2697 
2698 	tmp = (struct sdt_note *)calloc(1, sizeof(struct sdt_note));
2699 	if (!tmp) {
2700 		ret = -ENOMEM;
2701 		goto out_err;
2702 	}
2703 
2704 	INIT_LIST_HEAD(&tmp->note_list);
2705 
2706 	if (len < dst.d_size + 3)
2707 		goto out_free_note;
2708 
2709 	/* Translation from file representation to memory representation */
2710 	if (gelf_xlatetom(*elf, &dst, &src,
2711 			  elf_getident(*elf, NULL)[EI_DATA]) == NULL) {
2712 		pr_err("gelf_xlatetom : %s\n", elf_errmsg(-1));
2713 		goto out_free_note;
2714 	}
2715 
2716 	/* Populate the fields of sdt_note */
2717 	provider = data + dst.d_size;
2718 
2719 	name = (const char *)memchr(provider, '\0', data + len - provider);
2720 	if (name++ == NULL)
2721 		goto out_free_note;
2722 
2723 	tmp->provider = strdup(provider);
2724 	if (!tmp->provider) {
2725 		ret = -ENOMEM;
2726 		goto out_free_note;
2727 	}
2728 	tmp->name = strdup(name);
2729 	if (!tmp->name) {
2730 		ret = -ENOMEM;
2731 		goto out_free_prov;
2732 	}
2733 
2734 	args = memchr(name, '\0', data + len - name);
2735 
2736 	/*
2737 	 * There is no argument if:
2738 	 * - We reached the end of the note;
2739 	 * - There is not enough room to hold a potential string;
2740 	 * - The argument string is empty or just contains ':'.
2741 	 */
2742 	if (args == NULL || data + len - args < 2 ||
2743 		args[1] == ':' || args[1] == '\0')
2744 		tmp->args = NULL;
2745 	else {
2746 		tmp->args = strdup(++args);
2747 		if (!tmp->args) {
2748 			ret = -ENOMEM;
2749 			goto out_free_name;
2750 		}
2751 	}
2752 
2753 	if (gelf_getclass(*elf) == ELFCLASS32) {
2754 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf32_Addr));
2755 		tmp->bit32 = true;
2756 	} else {
2757 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf64_Addr));
2758 		tmp->bit32 = false;
2759 	}
2760 
2761 	if (!gelf_getehdr(*elf, &ehdr)) {
2762 		pr_debug("%s : cannot get elf header.\n", __func__);
2763 		ret = -EBADF;
2764 		goto out_free_args;
2765 	}
2766 
2767 	/* Adjust the prelink effect :
2768 	 * Find out the .stapsdt.base section.
2769 	 * This scn will help us to handle prelinking (if present).
2770 	 * Compare the retrieved file offset of the base section with the
2771 	 * base address in the description of the SDT note. If its different,
2772 	 * then accordingly, adjust the note location.
2773 	 */
2774 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_BASE_SCN, NULL))
2775 		sdt_adjust_loc(tmp, shdr.sh_offset);
2776 
2777 	/* Adjust reference counter offset */
2778 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_PROBES_SCN, NULL))
2779 		sdt_adjust_refctr(tmp, shdr.sh_addr, shdr.sh_offset);
2780 
2781 	list_add_tail(&tmp->note_list, sdt_notes);
2782 	return 0;
2783 
2784 out_free_args:
2785 	zfree(&tmp->args);
2786 out_free_name:
2787 	zfree(&tmp->name);
2788 out_free_prov:
2789 	zfree(&tmp->provider);
2790 out_free_note:
2791 	free(tmp);
2792 out_err:
2793 	return ret;
2794 }
2795 
2796 /**
2797  * construct_sdt_notes_list : constructs a list of SDT notes
2798  * @elf : elf to look into
2799  * @sdt_notes : empty list_head
2800  *
2801  * Scans the sections in 'elf' for the section
2802  * .note.stapsdt. It, then calls populate_sdt_note to find
2803  * out the SDT events and populates the 'sdt_notes'.
2804  */
construct_sdt_notes_list(Elf * elf,struct list_head * sdt_notes)2805 static int construct_sdt_notes_list(Elf *elf, struct list_head *sdt_notes)
2806 {
2807 	GElf_Ehdr ehdr;
2808 	Elf_Scn *scn = NULL;
2809 	Elf_Data *data;
2810 	GElf_Shdr shdr;
2811 	size_t shstrndx, next;
2812 	GElf_Nhdr nhdr;
2813 	size_t name_off, desc_off, offset;
2814 	int ret = 0;
2815 
2816 	if (gelf_getehdr(elf, &ehdr) == NULL) {
2817 		ret = -EBADF;
2818 		goto out_ret;
2819 	}
2820 	if (elf_getshdrstrndx(elf, &shstrndx) != 0) {
2821 		ret = -EBADF;
2822 		goto out_ret;
2823 	}
2824 
2825 	/* Look for the required section */
2826 	scn = elf_section_by_name(elf, &ehdr, &shdr, SDT_NOTE_SCN, NULL);
2827 	if (!scn) {
2828 		ret = -ENOENT;
2829 		goto out_ret;
2830 	}
2831 
2832 	if ((shdr.sh_type != SHT_NOTE) || (shdr.sh_flags & SHF_ALLOC)) {
2833 		ret = -ENOENT;
2834 		goto out_ret;
2835 	}
2836 
2837 	data = elf_getdata(scn, NULL);
2838 
2839 	/* Get the SDT notes */
2840 	for (offset = 0; (next = gelf_getnote(data, offset, &nhdr, &name_off,
2841 					      &desc_off)) > 0; offset = next) {
2842 		if (nhdr.n_namesz == sizeof(SDT_NOTE_NAME) &&
2843 		    !memcmp(data->d_buf + name_off, SDT_NOTE_NAME,
2844 			    sizeof(SDT_NOTE_NAME))) {
2845 			/* Check the type of the note */
2846 			if (nhdr.n_type != SDT_NOTE_TYPE)
2847 				goto out_ret;
2848 
2849 			ret = populate_sdt_note(&elf, ((data->d_buf) + desc_off),
2850 						nhdr.n_descsz, sdt_notes);
2851 			if (ret < 0)
2852 				goto out_ret;
2853 		}
2854 	}
2855 	if (list_empty(sdt_notes))
2856 		ret = -ENOENT;
2857 
2858 out_ret:
2859 	return ret;
2860 }
2861 
2862 /**
2863  * get_sdt_note_list : Wrapper to construct a list of sdt notes
2864  * @head : empty list_head
2865  * @target : file to find SDT notes from
2866  *
2867  * This opens the file, initializes
2868  * the ELF and then calls construct_sdt_notes_list.
2869  */
get_sdt_note_list(struct list_head * head,const char * target)2870 int get_sdt_note_list(struct list_head *head, const char *target)
2871 {
2872 	Elf *elf;
2873 	int fd, ret;
2874 
2875 	fd = open(target, O_RDONLY);
2876 	if (fd < 0)
2877 		return -EBADF;
2878 
2879 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
2880 	if (!elf) {
2881 		ret = -EBADF;
2882 		goto out_close;
2883 	}
2884 	ret = construct_sdt_notes_list(elf, head);
2885 	elf_end(elf);
2886 out_close:
2887 	close(fd);
2888 	return ret;
2889 }
2890 
2891 /**
2892  * cleanup_sdt_note_list : free the sdt notes' list
2893  * @sdt_notes: sdt notes' list
2894  *
2895  * Free up the SDT notes in @sdt_notes.
2896  * Returns the number of SDT notes free'd.
2897  */
cleanup_sdt_note_list(struct list_head * sdt_notes)2898 int cleanup_sdt_note_list(struct list_head *sdt_notes)
2899 {
2900 	struct sdt_note *tmp, *pos;
2901 	int nr_free = 0;
2902 
2903 	list_for_each_entry_safe(pos, tmp, sdt_notes, note_list) {
2904 		list_del_init(&pos->note_list);
2905 		zfree(&pos->args);
2906 		zfree(&pos->name);
2907 		zfree(&pos->provider);
2908 		free(pos);
2909 		nr_free++;
2910 	}
2911 	return nr_free;
2912 }
2913 
2914 /**
2915  * sdt_notes__get_count: Counts the number of sdt events
2916  * @start: list_head to sdt_notes list
2917  *
2918  * Returns the number of SDT notes in a list
2919  */
sdt_notes__get_count(struct list_head * start)2920 int sdt_notes__get_count(struct list_head *start)
2921 {
2922 	struct sdt_note *sdt_ptr;
2923 	int count = 0;
2924 
2925 	list_for_each_entry(sdt_ptr, start, note_list)
2926 		count++;
2927 	return count;
2928 }
2929 #endif
2930 
symbol__elf_init(void)2931 void symbol__elf_init(void)
2932 {
2933 	elf_version(EV_CURRENT);
2934 }
2935