xref: /linux/tools/perf/util/symbol-elf.c (revision ec714e371f22f716a04e6ecb2a24988c92b26911)
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,bool block)863 static int read_build_id(const char *filename, struct build_id *bid, bool block)
864 {
865 	size_t size = sizeof(bid->data);
866 	int fd, err;
867 	Elf *elf;
868 
869 	err = libbfd__read_build_id(filename, bid, block);
870 	if (err >= 0)
871 		goto out;
872 
873 	if (size < BUILD_ID_SIZE)
874 		goto out;
875 
876 	fd = open(filename, block ? O_RDONLY : (O_RDONLY | O_NONBLOCK));
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,bool block)897 int filename__read_build_id(const char *filename, struct build_id *bid, bool block)
898 {
899 	struct kmod_path m = { .name = NULL, };
900 	char path[PATH_MAX];
901 	int err;
902 
903 	if (!filename)
904 		return -EFAULT;
905 
906 	err = kmod_path__parse(&m, filename);
907 	if (err)
908 		return -1;
909 
910 	if (m.comp) {
911 		int error = 0, fd;
912 
913 		fd = filename__decompress(filename, path, sizeof(path), m.comp, &error);
914 		if (fd < 0) {
915 			pr_debug("Failed to decompress (error %d) %s\n",
916 				 error, filename);
917 			return -1;
918 		}
919 		close(fd);
920 		filename = path;
921 		block = true;
922 	}
923 
924 	err = read_build_id(filename, bid, block);
925 
926 	if (m.comp)
927 		unlink(filename);
928 	return err;
929 }
930 
sysfs__read_build_id(const char * filename,struct build_id * bid)931 int sysfs__read_build_id(const char *filename, struct build_id *bid)
932 {
933 	size_t size = sizeof(bid->data);
934 	int fd, err = -1;
935 
936 	fd = open(filename, O_RDONLY);
937 	if (fd < 0)
938 		goto out;
939 
940 	while (1) {
941 		char bf[BUFSIZ];
942 		GElf_Nhdr nhdr;
943 		size_t namesz, descsz;
944 
945 		if (read(fd, &nhdr, sizeof(nhdr)) != sizeof(nhdr))
946 			break;
947 
948 		namesz = NOTE_ALIGN(nhdr.n_namesz);
949 		descsz = NOTE_ALIGN(nhdr.n_descsz);
950 		if (nhdr.n_type == NT_GNU_BUILD_ID &&
951 		    nhdr.n_namesz == sizeof("GNU")) {
952 			if (read(fd, bf, namesz) != (ssize_t)namesz)
953 				break;
954 			if (memcmp(bf, "GNU", sizeof("GNU")) == 0) {
955 				size_t sz = min(descsz, size);
956 				if (read(fd, bid->data, sz) == (ssize_t)sz) {
957 					memset(bid->data + sz, 0, size - sz);
958 					bid->size = sz;
959 					err = 0;
960 					break;
961 				}
962 			} else if (read(fd, bf, descsz) != (ssize_t)descsz)
963 				break;
964 		} else {
965 			int n = namesz + descsz;
966 
967 			if (n > (int)sizeof(bf)) {
968 				n = sizeof(bf);
969 				pr_debug("%s: truncating reading of build id in sysfs file %s: n_namesz=%u, n_descsz=%u.\n",
970 					 __func__, filename, nhdr.n_namesz, nhdr.n_descsz);
971 			}
972 			if (read(fd, bf, n) != n)
973 				break;
974 		}
975 	}
976 	close(fd);
977 out:
978 	return err;
979 }
980 
filename__read_debuglink(const char * filename,char * debuglink,size_t size)981 int filename__read_debuglink(const char *filename, char *debuglink,
982 			     size_t size)
983 {
984 	int fd, err = -1;
985 	Elf *elf;
986 	GElf_Ehdr ehdr;
987 	GElf_Shdr shdr;
988 	Elf_Data *data;
989 	Elf_Scn *sec;
990 	Elf_Kind ek;
991 
992 	err = libbfd_filename__read_debuglink(filename, debuglink, size);
993 	if (err >= 0)
994 		goto out;
995 
996 	fd = open(filename, O_RDONLY);
997 	if (fd < 0)
998 		goto out;
999 
1000 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1001 	if (elf == NULL) {
1002 		pr_debug2("%s: cannot read %s ELF file.\n", __func__, filename);
1003 		goto out_close;
1004 	}
1005 
1006 	ek = elf_kind(elf);
1007 	if (ek != ELF_K_ELF)
1008 		goto out_elf_end;
1009 
1010 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1011 		pr_err("%s: cannot get elf header.\n", __func__);
1012 		goto out_elf_end;
1013 	}
1014 
1015 	sec = elf_section_by_name(elf, &ehdr, &shdr,
1016 				  ".gnu_debuglink", NULL);
1017 	if (sec == NULL)
1018 		goto out_elf_end;
1019 
1020 	data = elf_getdata(sec, NULL);
1021 	if (data == NULL)
1022 		goto out_elf_end;
1023 
1024 	/* the start of this section is a zero-terminated string */
1025 	strncpy(debuglink, data->d_buf, size);
1026 
1027 	err = 0;
1028 
1029 out_elf_end:
1030 	elf_end(elf);
1031 out_close:
1032 	close(fd);
1033 out:
1034 	return err;
1035 }
1036 
symsrc__possibly_runtime(struct symsrc * ss)1037 bool symsrc__possibly_runtime(struct symsrc *ss)
1038 {
1039 	return ss->dynsym || ss->opdsec;
1040 }
1041 
symsrc__has_symtab(struct symsrc * ss)1042 bool symsrc__has_symtab(struct symsrc *ss)
1043 {
1044 	return ss->symtab != NULL;
1045 }
1046 
symsrc__destroy(struct symsrc * ss)1047 void symsrc__destroy(struct symsrc *ss)
1048 {
1049 	zfree(&ss->name);
1050 	elf_end(ss->elf);
1051 	close(ss->fd);
1052 }
1053 
elf__needs_adjust_symbols(GElf_Ehdr ehdr)1054 bool elf__needs_adjust_symbols(GElf_Ehdr ehdr)
1055 {
1056 	/*
1057 	 * Usually vmlinux is an ELF file with type ET_EXEC for most
1058 	 * architectures; except Arm64 kernel is linked with option
1059 	 * '-share', so need to check type ET_DYN.
1060 	 */
1061 	return ehdr.e_type == ET_EXEC || ehdr.e_type == ET_REL ||
1062 	       ehdr.e_type == ET_DYN;
1063 }
1064 
read_gnu_debugdata(struct dso * dso,Elf * elf,const char * name,int * fd_ret)1065 static Elf *read_gnu_debugdata(struct dso *dso, Elf *elf, const char *name, int *fd_ret)
1066 {
1067 	Elf *elf_embedded;
1068 	GElf_Ehdr ehdr;
1069 	GElf_Shdr shdr;
1070 	Elf_Scn *scn;
1071 	Elf_Data *scn_data;
1072 	FILE *wrapped;
1073 	size_t shndx;
1074 	char temp_filename[] = "/tmp/perf.gnu_debugdata.elf.XXXXXX";
1075 	int ret, temp_fd;
1076 
1077 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1078 		pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1079 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1080 		return NULL;
1081 	}
1082 
1083 	scn = elf_section_by_name(elf, &ehdr, &shdr, ".gnu_debugdata", &shndx);
1084 	if (!scn) {
1085 		*dso__load_errno(dso) = -ENOENT;
1086 		return NULL;
1087 	}
1088 
1089 	if (shdr.sh_type == SHT_NOBITS) {
1090 		pr_debug("%s: .gnu_debugdata of ELF file %s has no data.\n", __func__, name);
1091 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1092 		return NULL;
1093 	}
1094 
1095 	scn_data = elf_rawdata(scn, NULL);
1096 	if (!scn_data) {
1097 		pr_debug("%s: error reading .gnu_debugdata of %s: %s\n", __func__,
1098 			 name, elf_errmsg(-1));
1099 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1100 		return NULL;
1101 	}
1102 
1103 	wrapped = fmemopen(scn_data->d_buf, scn_data->d_size, "r");
1104 	if (!wrapped) {
1105 		pr_debug("%s: fmemopen: %s\n", __func__, strerror(errno));
1106 		*dso__load_errno(dso) = -errno;
1107 		return NULL;
1108 	}
1109 
1110 	temp_fd = mkstemp(temp_filename);
1111 	if (temp_fd < 0) {
1112 		pr_debug("%s: mkstemp: %s\n", __func__, strerror(errno));
1113 		*dso__load_errno(dso) = -errno;
1114 		fclose(wrapped);
1115 		return NULL;
1116 	}
1117 	unlink(temp_filename);
1118 
1119 	ret = lzma_decompress_stream_to_file(wrapped, temp_fd);
1120 	fclose(wrapped);
1121 	if (ret < 0) {
1122 		*dso__load_errno(dso) = -errno;
1123 		close(temp_fd);
1124 		return NULL;
1125 	}
1126 
1127 	elf_embedded = elf_begin(temp_fd, PERF_ELF_C_READ_MMAP, NULL);
1128 	if (!elf_embedded) {
1129 		pr_debug("%s: error reading .gnu_debugdata of %s: %s\n", __func__,
1130 			 name, elf_errmsg(-1));
1131 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1132 		close(temp_fd);
1133 		return NULL;
1134 	}
1135 	pr_debug("%s: using .gnu_debugdata of %s\n", __func__, name);
1136 	*fd_ret = temp_fd;
1137 	return elf_embedded;
1138 }
1139 
symsrc__init(struct symsrc * ss,struct dso * dso,const char * name,enum dso_binary_type type)1140 int symsrc__init(struct symsrc *ss, struct dso *dso, const char *name,
1141 		 enum dso_binary_type type)
1142 {
1143 	GElf_Ehdr ehdr;
1144 	Elf *elf;
1145 	int fd;
1146 
1147 	if (dso__needs_decompress(dso)) {
1148 		fd = dso__decompress_kmodule_fd(dso, name);
1149 		if (fd < 0)
1150 			return -1;
1151 
1152 		type = dso__symtab_type(dso);
1153 	} else {
1154 		fd = open(name, O_RDONLY);
1155 		if (fd < 0) {
1156 			*dso__load_errno(dso) = errno;
1157 			return -1;
1158 		}
1159 	}
1160 
1161 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1162 	if (elf == NULL) {
1163 		pr_debug("%s: cannot read %s ELF file.\n", __func__, name);
1164 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1165 		goto out_close;
1166 	}
1167 
1168 	if (type == DSO_BINARY_TYPE__GNU_DEBUGDATA) {
1169 		int new_fd;
1170 		Elf *embedded = read_gnu_debugdata(dso, elf, name, &new_fd);
1171 
1172 		if (!embedded)
1173 			goto out_close;
1174 
1175 		elf_end(elf);
1176 		close(fd);
1177 		fd = new_fd;
1178 		elf = embedded;
1179 	}
1180 
1181 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1182 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INVALID_ELF;
1183 		pr_debug("%s: cannot get elf header.\n", __func__);
1184 		goto out_elf_end;
1185 	}
1186 
1187 	if (dso__swap_init(dso, ehdr.e_ident[EI_DATA])) {
1188 		*dso__load_errno(dso) = DSO_LOAD_ERRNO__INTERNAL_ERROR;
1189 		goto out_elf_end;
1190 	}
1191 
1192 	/* Always reject images with a mismatched build-id: */
1193 	if (dso__has_build_id(dso) && !symbol_conf.ignore_vmlinux_buildid) {
1194 		u8 build_id[BUILD_ID_SIZE];
1195 		struct build_id bid;
1196 		int size;
1197 
1198 		size = elf_read_build_id(elf, build_id, BUILD_ID_SIZE);
1199 		if (size <= 0) {
1200 			*dso__load_errno(dso) = DSO_LOAD_ERRNO__CANNOT_READ_BUILDID;
1201 			goto out_elf_end;
1202 		}
1203 
1204 		build_id__init(&bid, build_id, size);
1205 		if (!dso__build_id_equal(dso, &bid)) {
1206 			pr_debug("%s: build id mismatch for %s.\n", __func__, name);
1207 			*dso__load_errno(dso) = DSO_LOAD_ERRNO__MISMATCHING_BUILDID;
1208 			goto out_elf_end;
1209 		}
1210 	}
1211 
1212 	ss->is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1213 
1214 	ss->symtab_idx = 0;
1215 	ss->symtab = elf_section_by_name(elf, &ehdr, &ss->symshdr, ".symtab",
1216 			&ss->symtab_idx);
1217 	if (ss->symshdr.sh_type != SHT_SYMTAB)
1218 		ss->symtab = NULL;
1219 
1220 	ss->dynsym_idx = 0;
1221 	ss->dynsym = elf_section_by_name(elf, &ehdr, &ss->dynshdr, ".dynsym",
1222 			&ss->dynsym_idx);
1223 	if (ss->dynshdr.sh_type != SHT_DYNSYM)
1224 		ss->dynsym = NULL;
1225 
1226 	ss->opdidx = 0;
1227 	ss->opdsec = elf_section_by_name(elf, &ehdr, &ss->opdshdr, ".opd",
1228 			&ss->opdidx);
1229 	if (ss->opdshdr.sh_type != SHT_PROGBITS)
1230 		ss->opdsec = NULL;
1231 
1232 	if (dso__kernel(dso) == DSO_SPACE__USER)
1233 		ss->adjust_symbols = true;
1234 	else
1235 		ss->adjust_symbols = elf__needs_adjust_symbols(ehdr);
1236 
1237 	ss->name   = strdup(name);
1238 	if (!ss->name) {
1239 		*dso__load_errno(dso) = errno;
1240 		goto out_elf_end;
1241 	}
1242 
1243 	ss->elf    = elf;
1244 	ss->fd     = fd;
1245 	ss->ehdr   = ehdr;
1246 	ss->type   = type;
1247 
1248 	return 0;
1249 
1250 out_elf_end:
1251 	elf_end(elf);
1252 out_close:
1253 	close(fd);
1254 	return -1;
1255 }
1256 
is_exe_text(int flags)1257 static bool is_exe_text(int flags)
1258 {
1259 	return (flags & (SHF_ALLOC | SHF_EXECINSTR)) == (SHF_ALLOC | SHF_EXECINSTR);
1260 }
1261 
1262 /*
1263  * Some executable module sections like .noinstr.text might be laid out with
1264  * .text so they can use the same mapping (memory address to file offset).
1265  * Check if that is the case. Refer to kernel layout_sections(). Return the
1266  * maximum offset.
1267  */
max_text_section(Elf * elf,GElf_Ehdr * ehdr)1268 static u64 max_text_section(Elf *elf, GElf_Ehdr *ehdr)
1269 {
1270 	Elf_Scn *sec = NULL;
1271 	GElf_Shdr shdr;
1272 	u64 offs = 0;
1273 
1274 	/* Doesn't work for some arch */
1275 	if (ehdr->e_machine == EM_PARISC ||
1276 	    ehdr->e_machine == EM_ALPHA)
1277 		return 0;
1278 
1279 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1280 	if (!elf_rawdata(elf_getscn(elf, ehdr->e_shstrndx), NULL))
1281 		return 0;
1282 
1283 	while ((sec = elf_nextscn(elf, sec)) != NULL) {
1284 		char *sec_name;
1285 
1286 		if (!gelf_getshdr(sec, &shdr))
1287 			break;
1288 
1289 		if (!is_exe_text(shdr.sh_flags))
1290 			continue;
1291 
1292 		/* .init and .exit sections are not placed with .text */
1293 		sec_name = elf_strptr(elf, ehdr->e_shstrndx, shdr.sh_name);
1294 		if (!sec_name ||
1295 		    strstarts(sec_name, ".init") ||
1296 		    strstarts(sec_name, ".exit"))
1297 			break;
1298 
1299 		/* Must be next to previous, assumes .text is first */
1300 		if (offs && PERF_ALIGN(offs, shdr.sh_addralign ?: 1) != shdr.sh_offset)
1301 			break;
1302 
1303 		offs = shdr.sh_offset + shdr.sh_size;
1304 	}
1305 
1306 	return offs;
1307 }
1308 
1309 /**
1310  * ref_reloc_sym_not_found - has kernel relocation symbol been found.
1311  * @kmap: kernel maps and relocation reference symbol
1312  *
1313  * This function returns %true if we are dealing with the kernel maps and the
1314  * relocation reference symbol has not yet been found.  Otherwise %false is
1315  * returned.
1316  */
ref_reloc_sym_not_found(struct kmap * kmap)1317 static bool ref_reloc_sym_not_found(struct kmap *kmap)
1318 {
1319 	return kmap && kmap->ref_reloc_sym && kmap->ref_reloc_sym->name &&
1320 	       !kmap->ref_reloc_sym->unrelocated_addr;
1321 }
1322 
1323 /**
1324  * ref_reloc - kernel relocation offset.
1325  * @kmap: kernel maps and relocation reference symbol
1326  *
1327  * This function returns the offset of kernel addresses as determined by using
1328  * the relocation reference symbol i.e. if the kernel has not been relocated
1329  * then the return value is zero.
1330  */
ref_reloc(struct kmap * kmap)1331 static u64 ref_reloc(struct kmap *kmap)
1332 {
1333 	if (kmap && kmap->ref_reloc_sym &&
1334 	    kmap->ref_reloc_sym->unrelocated_addr)
1335 		return kmap->ref_reloc_sym->addr -
1336 		       kmap->ref_reloc_sym->unrelocated_addr;
1337 	return 0;
1338 }
1339 
arch__sym_update(struct symbol * s __maybe_unused,GElf_Sym * sym __maybe_unused)1340 void __weak arch__sym_update(struct symbol *s __maybe_unused,
1341 		GElf_Sym *sym __maybe_unused) { }
1342 
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)1343 static int dso__process_kernel_symbol(struct dso *dso, struct map *map,
1344 				      GElf_Sym *sym, GElf_Shdr *shdr,
1345 				      struct maps *kmaps, struct kmap *kmap,
1346 				      struct dso **curr_dsop,
1347 				      const char *section_name,
1348 				      bool adjust_kernel_syms, bool kmodule, bool *remap_kernel,
1349 				      u64 max_text_sh_offset)
1350 {
1351 	struct dso *curr_dso = *curr_dsop;
1352 	struct map *curr_map;
1353 	char dso_name[PATH_MAX];
1354 
1355 	/* Adjust symbol to map to file offset */
1356 	if (adjust_kernel_syms)
1357 		sym->st_value -= shdr->sh_addr - shdr->sh_offset;
1358 
1359 	if (strcmp(section_name, (dso__short_name(curr_dso) + dso__short_name_len(dso))) == 0)
1360 		return 0;
1361 
1362 	if (strcmp(section_name, ".text") == 0) {
1363 		/*
1364 		 * The initial kernel mapping is based on
1365 		 * kallsyms and identity maps.  Overwrite it to
1366 		 * map to the kernel dso.
1367 		 */
1368 		if (*remap_kernel && dso__kernel(dso) && !kmodule) {
1369 			*remap_kernel = false;
1370 			map__set_start(map, shdr->sh_addr + ref_reloc(kmap));
1371 			map__set_end(map, map__start(map) + shdr->sh_size);
1372 			map__set_pgoff(map, shdr->sh_offset);
1373 			map__set_mapping_type(map, MAPPING_TYPE__DSO);
1374 			/* Ensure maps are correctly ordered */
1375 			if (kmaps) {
1376 				int err;
1377 				struct map *tmp = map__get(map);
1378 
1379 				maps__remove(kmaps, map);
1380 				err = maps__insert(kmaps, map);
1381 				map__put(tmp);
1382 				if (err)
1383 					return err;
1384 			}
1385 		}
1386 
1387 		/*
1388 		 * The initial module mapping is based on
1389 		 * /proc/modules mapped to offset zero.
1390 		 * Overwrite it to map to the module dso.
1391 		 */
1392 		if (*remap_kernel && kmodule) {
1393 			*remap_kernel = false;
1394 			map__set_pgoff(map, shdr->sh_offset);
1395 		}
1396 
1397 		dso__put(*curr_dsop);
1398 		*curr_dsop = dso__get(dso);
1399 		return 0;
1400 	}
1401 
1402 	if (!kmap)
1403 		return 0;
1404 
1405 	/*
1406 	 * perf does not record module section addresses except for .text, but
1407 	 * some sections can use the same mapping as .text.
1408 	 */
1409 	if (kmodule && adjust_kernel_syms && is_exe_text(shdr->sh_flags) &&
1410 	    shdr->sh_offset <= max_text_sh_offset) {
1411 		dso__put(*curr_dsop);
1412 		*curr_dsop = dso__get(dso);
1413 		return 0;
1414 	}
1415 
1416 	snprintf(dso_name, sizeof(dso_name), "%s%s", dso__short_name(dso), section_name);
1417 
1418 	curr_map = maps__find_by_name(kmaps, dso_name);
1419 	if (curr_map == NULL) {
1420 		u64 start = sym->st_value;
1421 
1422 		if (kmodule)
1423 			start += map__start(map) + shdr->sh_offset;
1424 
1425 		curr_dso = dso__new(dso_name);
1426 		if (curr_dso == NULL)
1427 			return -1;
1428 		dso__set_kernel(curr_dso, dso__kernel(dso));
1429 		RC_CHK_ACCESS(curr_dso)->long_name = dso__long_name(dso);
1430 		RC_CHK_ACCESS(curr_dso)->long_name_len = dso__long_name_len(dso);
1431 		dso__set_binary_type(curr_dso, dso__binary_type(dso));
1432 		dso__set_adjust_symbols(curr_dso, dso__adjust_symbols(dso));
1433 		curr_map = map__new2(start, curr_dso);
1434 		if (curr_map == NULL) {
1435 			dso__put(curr_dso);
1436 			return -1;
1437 		}
1438 		if (dso__kernel(curr_dso))
1439 			map__kmap(curr_map)->kmaps = kmaps;
1440 
1441 		if (adjust_kernel_syms) {
1442 			map__set_start(curr_map, shdr->sh_addr + ref_reloc(kmap));
1443 			map__set_end(curr_map, map__start(curr_map) + shdr->sh_size);
1444 			map__set_pgoff(curr_map, shdr->sh_offset);
1445 		} else {
1446 			map__set_mapping_type(curr_map, MAPPING_TYPE__IDENTITY);
1447 		}
1448 		dso__set_symtab_type(curr_dso, dso__symtab_type(dso));
1449 		if (maps__insert(kmaps, curr_map))
1450 			return -1;
1451 		dsos__add(&maps__machine(kmaps)->dsos, curr_dso);
1452 		dso__set_loaded(curr_dso);
1453 		dso__put(*curr_dsop);
1454 		*curr_dsop = curr_dso;
1455 	} else {
1456 		dso__put(*curr_dsop);
1457 		*curr_dsop = dso__get(map__dso(curr_map));
1458 	}
1459 	map__put(curr_map);
1460 
1461 	return 0;
1462 }
1463 
1464 static int
dso__load_sym_internal(struct dso * dso,struct map * map,struct symsrc * syms_ss,struct symsrc * runtime_ss,int kmodule,int dynsym)1465 dso__load_sym_internal(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1466 		       struct symsrc *runtime_ss, int kmodule, int dynsym)
1467 {
1468 	struct kmap *kmap = dso__kernel(dso) ? map__kmap(map) : NULL;
1469 	struct maps *kmaps = kmap ? map__kmaps(map) : NULL;
1470 	struct dso *curr_dso = NULL;
1471 	Elf_Data *symstrs, *secstrs, *secstrs_run, *secstrs_sym;
1472 	uint32_t nr_syms;
1473 	uint32_t idx;
1474 	GElf_Ehdr ehdr;
1475 	GElf_Shdr shdr;
1476 	GElf_Shdr tshdr;
1477 	Elf_Data *syms, *opddata = NULL;
1478 	GElf_Sym sym;
1479 	Elf_Scn *sec, *sec_strndx;
1480 	Elf *elf;
1481 	int nr = 0;
1482 	bool remap_kernel = false, adjust_kernel_syms = false;
1483 	u64 max_text_sh_offset = 0;
1484 
1485 	if (kmap && !kmaps)
1486 		return -1;
1487 
1488 	elf = syms_ss->elf;
1489 	ehdr = syms_ss->ehdr;
1490 	if (dynsym) {
1491 		sec  = syms_ss->dynsym;
1492 		shdr = syms_ss->dynshdr;
1493 	} else {
1494 		sec =  syms_ss->symtab;
1495 		shdr = syms_ss->symshdr;
1496 	}
1497 
1498 	if (elf_section_by_name(runtime_ss->elf, &runtime_ss->ehdr, &tshdr,
1499 				".text", NULL)) {
1500 		dso__set_text_offset(dso, tshdr.sh_addr - tshdr.sh_offset);
1501 		dso__set_text_end(dso, tshdr.sh_offset + tshdr.sh_size);
1502 	}
1503 
1504 	if (runtime_ss->opdsec)
1505 		opddata = elf_rawdata(runtime_ss->opdsec, NULL);
1506 
1507 	syms = elf_getdata(sec, NULL);
1508 	if (syms == NULL)
1509 		goto out_elf_end;
1510 
1511 	sec = elf_getscn(elf, shdr.sh_link);
1512 	if (sec == NULL)
1513 		goto out_elf_end;
1514 
1515 	symstrs = elf_getdata(sec, NULL);
1516 	if (symstrs == NULL)
1517 		goto out_elf_end;
1518 
1519 	sec_strndx = elf_getscn(runtime_ss->elf, runtime_ss->ehdr.e_shstrndx);
1520 	if (sec_strndx == NULL)
1521 		goto out_elf_end;
1522 
1523 	secstrs_run = elf_getdata(sec_strndx, NULL);
1524 	if (secstrs_run == NULL)
1525 		goto out_elf_end;
1526 
1527 	sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
1528 	if (sec_strndx == NULL)
1529 		goto out_elf_end;
1530 
1531 	secstrs_sym = elf_getdata(sec_strndx, NULL);
1532 	if (secstrs_sym == NULL)
1533 		goto out_elf_end;
1534 
1535 	nr_syms = shdr.sh_size / shdr.sh_entsize;
1536 
1537 	memset(&sym, 0, sizeof(sym));
1538 
1539 	/*
1540 	 * The kernel relocation symbol is needed in advance in order to adjust
1541 	 * kernel maps correctly.
1542 	 */
1543 	if (ref_reloc_sym_not_found(kmap)) {
1544 		elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1545 			const char *elf_name = elf_sym__name(&sym, symstrs);
1546 
1547 			if (strcmp(elf_name, kmap->ref_reloc_sym->name))
1548 				continue;
1549 			kmap->ref_reloc_sym->unrelocated_addr = sym.st_value;
1550 			map__set_reloc(map, kmap->ref_reloc_sym->addr - kmap->ref_reloc_sym->unrelocated_addr);
1551 			break;
1552 		}
1553 	}
1554 
1555 	/*
1556 	 * Handle any relocation of vdso necessary because older kernels
1557 	 * attempted to prelink vdso to its virtual address.
1558 	 */
1559 	if (dso__is_vdso(dso))
1560 		map__set_reloc(map, map__start(map) - dso__text_offset(dso));
1561 
1562 	dso__set_adjust_symbols(dso, runtime_ss->adjust_symbols || ref_reloc(kmap));
1563 	/*
1564 	 * Initial kernel and module mappings do not map to the dso.
1565 	 * Flag the fixups.
1566 	 */
1567 	if (dso__kernel(dso)) {
1568 		remap_kernel = true;
1569 		adjust_kernel_syms = dso__adjust_symbols(dso);
1570 	}
1571 
1572 	if (kmodule && adjust_kernel_syms)
1573 		max_text_sh_offset = max_text_section(runtime_ss->elf, &runtime_ss->ehdr);
1574 
1575 	curr_dso = dso__get(dso);
1576 	elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
1577 		struct symbol *f;
1578 		const char *elf_name = elf_sym__name(&sym, symstrs);
1579 		char *demangled = NULL;
1580 		int is_label = elf_sym__is_label(&sym);
1581 		const char *section_name;
1582 		bool used_opd = false;
1583 
1584 		if (!is_label && !elf_sym__filter(&sym))
1585 			continue;
1586 
1587 		/* Reject ARM ELF "mapping symbols": these aren't unique and
1588 		 * don't identify functions, so will confuse the profile
1589 		 * output: */
1590 		if (ehdr.e_machine == EM_ARM || ehdr.e_machine == EM_AARCH64) {
1591 			if (elf_name[0] == '$' && strchr("adtx", elf_name[1])
1592 			    && (elf_name[2] == '\0' || elf_name[2] == '.'))
1593 				continue;
1594 		}
1595 
1596 		/* Reject RISCV ELF "mapping symbols" */
1597 		if (ehdr.e_machine == EM_RISCV) {
1598 			if (elf_name[0] == '$' && strchr("dx", elf_name[1]))
1599 				continue;
1600 		}
1601 
1602 		if (runtime_ss->opdsec && sym.st_shndx == runtime_ss->opdidx) {
1603 			u32 offset = sym.st_value - syms_ss->opdshdr.sh_addr;
1604 			u64 *opd = opddata->d_buf + offset;
1605 			sym.st_value = DSO__SWAP(dso, u64, *opd);
1606 			sym.st_shndx = elf_addr_to_index(runtime_ss->elf,
1607 					sym.st_value);
1608 			used_opd = true;
1609 		}
1610 
1611 		/*
1612 		 * When loading symbols in a data mapping, ABS symbols (which
1613 		 * has a value of SHN_ABS in its st_shndx) failed at
1614 		 * elf_getscn().  And it marks the loading as a failure so
1615 		 * already loaded symbols cannot be fixed up.
1616 		 *
1617 		 * I'm not sure what should be done. Just ignore them for now.
1618 		 * - Namhyung Kim
1619 		 */
1620 		if (sym.st_shndx == SHN_ABS)
1621 			continue;
1622 
1623 		sec = elf_getscn(syms_ss->elf, sym.st_shndx);
1624 		if (!sec)
1625 			goto out_elf_end;
1626 
1627 		gelf_getshdr(sec, &shdr);
1628 
1629 		/*
1630 		 * If the attribute bit SHF_ALLOC is not set, the section
1631 		 * doesn't occupy memory during process execution.
1632 		 * E.g. ".gnu.warning.*" section is used by linker to generate
1633 		 * warnings when calling deprecated functions, the symbols in
1634 		 * the section aren't loaded to memory during process execution,
1635 		 * so skip them.
1636 		 */
1637 		if (!(shdr.sh_flags & SHF_ALLOC))
1638 			continue;
1639 
1640 		secstrs = secstrs_sym;
1641 
1642 		/*
1643 		 * We have to fallback to runtime when syms' section header has
1644 		 * NOBITS set. NOBITS results in file offset (sh_offset) not
1645 		 * being incremented. So sh_offset used below has different
1646 		 * values for syms (invalid) and runtime (valid).
1647 		 */
1648 		if (shdr.sh_type == SHT_NOBITS) {
1649 			sec = elf_getscn(runtime_ss->elf, sym.st_shndx);
1650 			if (!sec)
1651 				goto out_elf_end;
1652 
1653 			gelf_getshdr(sec, &shdr);
1654 			secstrs = secstrs_run;
1655 		}
1656 
1657 		if (is_label && !elf_sec__filter(&shdr, secstrs))
1658 			continue;
1659 
1660 		section_name = elf_sec__name(&shdr, secstrs);
1661 
1662 		/* On ARM, symbols for thumb functions have 1 added to
1663 		 * the symbol address as a flag - remove it */
1664 		if ((ehdr.e_machine == EM_ARM) &&
1665 		    (GELF_ST_TYPE(sym.st_info) == STT_FUNC) &&
1666 		    (sym.st_value & 1))
1667 			--sym.st_value;
1668 
1669 		if (dso__kernel(dso)) {
1670 			if (dso__process_kernel_symbol(dso, map, &sym, &shdr,
1671 						       kmaps, kmap, &curr_dso,
1672 						       section_name,
1673 						       adjust_kernel_syms,
1674 						       kmodule,
1675 						       &remap_kernel,
1676 						       max_text_sh_offset))
1677 				goto out_elf_end;
1678 		} else if ((used_opd && runtime_ss->adjust_symbols) ||
1679 			   (!used_opd && syms_ss->adjust_symbols)) {
1680 			GElf_Phdr phdr;
1681 
1682 			if (elf_read_program_header(runtime_ss->elf,
1683 						    (u64)sym.st_value, &phdr)) {
1684 				pr_debug4("%s: failed to find program header for "
1685 					   "symbol: %s st_value: %#" PRIx64 "\n",
1686 					   __func__, elf_name, (u64)sym.st_value);
1687 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1688 					"sh_addr: %#" PRIx64 " sh_offset: %#" PRIx64 "\n",
1689 					__func__, (u64)sym.st_value, (u64)shdr.sh_addr,
1690 					(u64)shdr.sh_offset);
1691 				/*
1692 				 * Fail to find program header, let's rollback
1693 				 * to use shdr.sh_addr and shdr.sh_offset to
1694 				 * calibrate symbol's file address, though this
1695 				 * is not necessary for normal C ELF file, we
1696 				 * still need to handle java JIT symbols in this
1697 				 * case.
1698 				 */
1699 				sym.st_value -= shdr.sh_addr - shdr.sh_offset;
1700 			} else {
1701 				pr_debug4("%s: adjusting symbol: st_value: %#" PRIx64 " "
1702 					"p_vaddr: %#" PRIx64 " p_offset: %#" PRIx64 "\n",
1703 					__func__, (u64)sym.st_value, (u64)phdr.p_vaddr,
1704 					(u64)phdr.p_offset);
1705 				sym.st_value -= phdr.p_vaddr - phdr.p_offset;
1706 			}
1707 		}
1708 
1709 		demangled = dso__demangle_sym(dso, kmodule, elf_name);
1710 		if (demangled != NULL)
1711 			elf_name = demangled;
1712 
1713 		f = symbol__new(sym.st_value, sym.st_size,
1714 				GELF_ST_BIND(sym.st_info),
1715 				GELF_ST_TYPE(sym.st_info), elf_name);
1716 		free(demangled);
1717 		if (!f)
1718 			goto out_elf_end;
1719 
1720 		arch__sym_update(f, &sym);
1721 
1722 		__symbols__insert(dso__symbols(curr_dso), f, dso__kernel(dso));
1723 		nr++;
1724 	}
1725 	dso__put(curr_dso);
1726 
1727 	/*
1728 	 * For misannotated, zeroed, ASM function sizes.
1729 	 */
1730 	if (nr > 0) {
1731 		symbols__fixup_end(dso__symbols(dso), false);
1732 		symbols__fixup_duplicate(dso__symbols(dso));
1733 		if (kmap) {
1734 			/*
1735 			 * We need to fixup this here too because we create new
1736 			 * maps here, for things like vsyscall sections.
1737 			 */
1738 			maps__fixup_end(kmaps);
1739 		}
1740 	}
1741 	return nr;
1742 out_elf_end:
1743 	dso__put(curr_dso);
1744 	return -1;
1745 }
1746 
dso__load_sym(struct dso * dso,struct map * map,struct symsrc * syms_ss,struct symsrc * runtime_ss,int kmodule)1747 int dso__load_sym(struct dso *dso, struct map *map, struct symsrc *syms_ss,
1748 		  struct symsrc *runtime_ss, int kmodule)
1749 {
1750 	int nr = 0;
1751 	int err = -1;
1752 
1753 	dso__set_symtab_type(dso, syms_ss->type);
1754 	dso__set_is_64_bit(dso, syms_ss->is_64_bit);
1755 	dso__set_rel(dso, syms_ss->ehdr.e_type == ET_REL);
1756 
1757 	/*
1758 	 * Modules may already have symbols from kallsyms, but those symbols
1759 	 * have the wrong values for the dso maps, so remove them.
1760 	 */
1761 	if (kmodule && syms_ss->symtab)
1762 		symbols__delete(dso__symbols(dso));
1763 
1764 	if (!syms_ss->symtab) {
1765 		/*
1766 		 * If the vmlinux is stripped, fail so we will fall back
1767 		 * to using kallsyms. The vmlinux runtime symbols aren't
1768 		 * of much use.
1769 		 */
1770 		if (dso__kernel(dso))
1771 			return err;
1772 	} else  {
1773 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1774 					     kmodule, 0);
1775 		if (err < 0)
1776 			return err;
1777 		nr = err;
1778 	}
1779 
1780 	if (syms_ss->dynsym) {
1781 		err = dso__load_sym_internal(dso, map, syms_ss, runtime_ss,
1782 					     kmodule, 1);
1783 		if (err < 0)
1784 			return err;
1785 		nr += err;
1786 	}
1787 
1788 	/*
1789 	 * The .gnu_debugdata is a special situation: it contains a symbol
1790 	 * table, but the runtime file may also contain dynsym entries which are
1791 	 * not present there. We need to load both.
1792 	 */
1793 	if (syms_ss->type == DSO_BINARY_TYPE__GNU_DEBUGDATA && runtime_ss->dynsym) {
1794 		err = dso__load_sym_internal(dso, map, runtime_ss, runtime_ss,
1795 					     kmodule, 1);
1796 		if (err < 0)
1797 			return err;
1798 		nr += err;
1799 	}
1800 
1801 	return nr;
1802 }
1803 
elf_read_maps(Elf * elf,bool exe,mapfn_t mapfn,void * data)1804 static int elf_read_maps(Elf *elf, bool exe, mapfn_t mapfn, void *data)
1805 {
1806 	GElf_Phdr phdr;
1807 	size_t i, phdrnum;
1808 	int err;
1809 	u64 sz;
1810 
1811 	if (elf_getphdrnum(elf, &phdrnum))
1812 		return -1;
1813 
1814 	for (i = 0; i < phdrnum; i++) {
1815 		if (gelf_getphdr(elf, i, &phdr) == NULL)
1816 			return -1;
1817 		if (phdr.p_type != PT_LOAD)
1818 			continue;
1819 		if (exe) {
1820 			if (!(phdr.p_flags & PF_X))
1821 				continue;
1822 		} else {
1823 			if (!(phdr.p_flags & PF_R))
1824 				continue;
1825 		}
1826 		sz = min(phdr.p_memsz, phdr.p_filesz);
1827 		if (!sz)
1828 			continue;
1829 		err = mapfn(phdr.p_vaddr, sz, phdr.p_offset, data);
1830 		if (err)
1831 			return err;
1832 	}
1833 	return 0;
1834 }
1835 
file__read_maps(int fd,bool exe,mapfn_t mapfn,void * data,bool * is_64_bit)1836 int file__read_maps(int fd, bool exe, mapfn_t mapfn, void *data,
1837 		    bool *is_64_bit)
1838 {
1839 	int err;
1840 	Elf *elf;
1841 
1842 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1843 	if (elf == NULL)
1844 		return -1;
1845 
1846 	if (is_64_bit)
1847 		*is_64_bit = (gelf_getclass(elf) == ELFCLASS64);
1848 
1849 	err = elf_read_maps(elf, exe, mapfn, data);
1850 
1851 	elf_end(elf);
1852 	return err;
1853 }
1854 
dso__type_fd(int fd)1855 enum dso_type dso__type_fd(int fd)
1856 {
1857 	enum dso_type dso_type = DSO__TYPE_UNKNOWN;
1858 	GElf_Ehdr ehdr;
1859 	Elf_Kind ek;
1860 	Elf *elf;
1861 
1862 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
1863 	if (elf == NULL)
1864 		goto out;
1865 
1866 	ek = elf_kind(elf);
1867 	if (ek != ELF_K_ELF)
1868 		goto out_end;
1869 
1870 	if (gelf_getclass(elf) == ELFCLASS64) {
1871 		dso_type = DSO__TYPE_64BIT;
1872 		goto out_end;
1873 	}
1874 
1875 	if (gelf_getehdr(elf, &ehdr) == NULL)
1876 		goto out_end;
1877 
1878 	if (ehdr.e_machine == EM_X86_64)
1879 		dso_type = DSO__TYPE_X32BIT;
1880 	else
1881 		dso_type = DSO__TYPE_32BIT;
1882 out_end:
1883 	elf_end(elf);
1884 out:
1885 	return dso_type;
1886 }
1887 
copy_bytes(int from,off_t from_offs,int to,off_t to_offs,u64 len)1888 static int copy_bytes(int from, off_t from_offs, int to, off_t to_offs, u64 len)
1889 {
1890 	ssize_t r;
1891 	size_t n;
1892 	int err = -1;
1893 	char *buf = malloc(page_size);
1894 
1895 	if (buf == NULL)
1896 		return -1;
1897 
1898 	if (lseek(to, to_offs, SEEK_SET) != to_offs)
1899 		goto out;
1900 
1901 	if (lseek(from, from_offs, SEEK_SET) != from_offs)
1902 		goto out;
1903 
1904 	while (len) {
1905 		n = page_size;
1906 		if (len < n)
1907 			n = len;
1908 		/* Use read because mmap won't work on proc files */
1909 		r = read(from, buf, n);
1910 		if (r < 0)
1911 			goto out;
1912 		if (!r)
1913 			break;
1914 		n = r;
1915 		r = write(to, buf, n);
1916 		if (r < 0)
1917 			goto out;
1918 		if ((size_t)r != n)
1919 			goto out;
1920 		len -= n;
1921 	}
1922 
1923 	err = 0;
1924 out:
1925 	free(buf);
1926 	return err;
1927 }
1928 
1929 struct kcore {
1930 	int fd;
1931 	int elfclass;
1932 	Elf *elf;
1933 	GElf_Ehdr ehdr;
1934 };
1935 
kcore__open(struct kcore * kcore,const char * filename)1936 static int kcore__open(struct kcore *kcore, const char *filename)
1937 {
1938 	GElf_Ehdr *ehdr;
1939 
1940 	kcore->fd = open(filename, O_RDONLY);
1941 	if (kcore->fd == -1)
1942 		return -1;
1943 
1944 	kcore->elf = elf_begin(kcore->fd, ELF_C_READ, NULL);
1945 	if (!kcore->elf)
1946 		goto out_close;
1947 
1948 	kcore->elfclass = gelf_getclass(kcore->elf);
1949 	if (kcore->elfclass == ELFCLASSNONE)
1950 		goto out_end;
1951 
1952 	ehdr = gelf_getehdr(kcore->elf, &kcore->ehdr);
1953 	if (!ehdr)
1954 		goto out_end;
1955 
1956 	return 0;
1957 
1958 out_end:
1959 	elf_end(kcore->elf);
1960 out_close:
1961 	close(kcore->fd);
1962 	return -1;
1963 }
1964 
kcore__init(struct kcore * kcore,char * filename,int elfclass,bool temp)1965 static int kcore__init(struct kcore *kcore, char *filename, int elfclass,
1966 		       bool temp)
1967 {
1968 	kcore->elfclass = elfclass;
1969 
1970 	if (temp)
1971 		kcore->fd = mkstemp(filename);
1972 	else
1973 		kcore->fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0400);
1974 	if (kcore->fd == -1)
1975 		return -1;
1976 
1977 	kcore->elf = elf_begin(kcore->fd, ELF_C_WRITE, NULL);
1978 	if (!kcore->elf)
1979 		goto out_close;
1980 
1981 	if (!gelf_newehdr(kcore->elf, elfclass))
1982 		goto out_end;
1983 
1984 	memset(&kcore->ehdr, 0, sizeof(GElf_Ehdr));
1985 
1986 	return 0;
1987 
1988 out_end:
1989 	elf_end(kcore->elf);
1990 out_close:
1991 	close(kcore->fd);
1992 	unlink(filename);
1993 	return -1;
1994 }
1995 
kcore__close(struct kcore * kcore)1996 static void kcore__close(struct kcore *kcore)
1997 {
1998 	elf_end(kcore->elf);
1999 	close(kcore->fd);
2000 }
2001 
kcore__copy_hdr(struct kcore * from,struct kcore * to,size_t count)2002 static int kcore__copy_hdr(struct kcore *from, struct kcore *to, size_t count)
2003 {
2004 	GElf_Ehdr *ehdr = &to->ehdr;
2005 	GElf_Ehdr *kehdr = &from->ehdr;
2006 
2007 	memcpy(ehdr->e_ident, kehdr->e_ident, EI_NIDENT);
2008 	ehdr->e_type      = kehdr->e_type;
2009 	ehdr->e_machine   = kehdr->e_machine;
2010 	ehdr->e_version   = kehdr->e_version;
2011 	ehdr->e_entry     = 0;
2012 	ehdr->e_shoff     = 0;
2013 	ehdr->e_flags     = kehdr->e_flags;
2014 	ehdr->e_phnum     = count;
2015 	ehdr->e_shentsize = 0;
2016 	ehdr->e_shnum     = 0;
2017 	ehdr->e_shstrndx  = 0;
2018 
2019 	if (from->elfclass == ELFCLASS32) {
2020 		ehdr->e_phoff     = sizeof(Elf32_Ehdr);
2021 		ehdr->e_ehsize    = sizeof(Elf32_Ehdr);
2022 		ehdr->e_phentsize = sizeof(Elf32_Phdr);
2023 	} else {
2024 		ehdr->e_phoff     = sizeof(Elf64_Ehdr);
2025 		ehdr->e_ehsize    = sizeof(Elf64_Ehdr);
2026 		ehdr->e_phentsize = sizeof(Elf64_Phdr);
2027 	}
2028 
2029 	if (!gelf_update_ehdr(to->elf, ehdr))
2030 		return -1;
2031 
2032 	if (!gelf_newphdr(to->elf, count))
2033 		return -1;
2034 
2035 	return 0;
2036 }
2037 
kcore__add_phdr(struct kcore * kcore,int idx,off_t offset,u64 addr,u64 len)2038 static int kcore__add_phdr(struct kcore *kcore, int idx, off_t offset,
2039 			   u64 addr, u64 len)
2040 {
2041 	GElf_Phdr phdr = {
2042 		.p_type		= PT_LOAD,
2043 		.p_flags	= PF_R | PF_W | PF_X,
2044 		.p_offset	= offset,
2045 		.p_vaddr	= addr,
2046 		.p_paddr	= 0,
2047 		.p_filesz	= len,
2048 		.p_memsz	= len,
2049 		.p_align	= page_size,
2050 	};
2051 
2052 	if (!gelf_update_phdr(kcore->elf, idx, &phdr))
2053 		return -1;
2054 
2055 	return 0;
2056 }
2057 
kcore__write(struct kcore * kcore)2058 static off_t kcore__write(struct kcore *kcore)
2059 {
2060 	return elf_update(kcore->elf, ELF_C_WRITE);
2061 }
2062 
2063 struct phdr_data {
2064 	off_t offset;
2065 	off_t rel;
2066 	u64 addr;
2067 	u64 len;
2068 	struct list_head node;
2069 	struct phdr_data *remaps;
2070 };
2071 
2072 struct sym_data {
2073 	u64 addr;
2074 	struct list_head node;
2075 };
2076 
2077 struct kcore_copy_info {
2078 	u64 stext;
2079 	u64 etext;
2080 	u64 first_symbol;
2081 	u64 last_symbol;
2082 	u64 first_module;
2083 	u64 first_module_symbol;
2084 	u64 last_module_symbol;
2085 	size_t phnum;
2086 	struct list_head phdrs;
2087 	struct list_head syms;
2088 };
2089 
2090 #define kcore_copy__for_each_phdr(k, p) \
2091 	list_for_each_entry((p), &(k)->phdrs, node)
2092 
phdr_data__new(u64 addr,u64 len,off_t offset)2093 static struct phdr_data *phdr_data__new(u64 addr, u64 len, off_t offset)
2094 {
2095 	struct phdr_data *p = zalloc(sizeof(*p));
2096 
2097 	if (p) {
2098 		p->addr   = addr;
2099 		p->len    = len;
2100 		p->offset = offset;
2101 	}
2102 
2103 	return p;
2104 }
2105 
kcore_copy_info__addnew(struct kcore_copy_info * kci,u64 addr,u64 len,off_t offset)2106 static struct phdr_data *kcore_copy_info__addnew(struct kcore_copy_info *kci,
2107 						 u64 addr, u64 len,
2108 						 off_t offset)
2109 {
2110 	struct phdr_data *p = phdr_data__new(addr, len, offset);
2111 
2112 	if (p)
2113 		list_add_tail(&p->node, &kci->phdrs);
2114 
2115 	return p;
2116 }
2117 
kcore_copy__free_phdrs(struct kcore_copy_info * kci)2118 static void kcore_copy__free_phdrs(struct kcore_copy_info *kci)
2119 {
2120 	struct phdr_data *p, *tmp;
2121 
2122 	list_for_each_entry_safe(p, tmp, &kci->phdrs, node) {
2123 		list_del_init(&p->node);
2124 		free(p);
2125 	}
2126 }
2127 
kcore_copy__new_sym(struct kcore_copy_info * kci,u64 addr)2128 static struct sym_data *kcore_copy__new_sym(struct kcore_copy_info *kci,
2129 					    u64 addr)
2130 {
2131 	struct sym_data *s = zalloc(sizeof(*s));
2132 
2133 	if (s) {
2134 		s->addr = addr;
2135 		list_add_tail(&s->node, &kci->syms);
2136 	}
2137 
2138 	return s;
2139 }
2140 
kcore_copy__free_syms(struct kcore_copy_info * kci)2141 static void kcore_copy__free_syms(struct kcore_copy_info *kci)
2142 {
2143 	struct sym_data *s, *tmp;
2144 
2145 	list_for_each_entry_safe(s, tmp, &kci->syms, node) {
2146 		list_del_init(&s->node);
2147 		free(s);
2148 	}
2149 }
2150 
kcore_copy__process_kallsyms(void * arg,const char * name,char type,u64 start)2151 static int kcore_copy__process_kallsyms(void *arg, const char *name, char type,
2152 					u64 start)
2153 {
2154 	struct kcore_copy_info *kci = arg;
2155 
2156 	if (!kallsyms__is_function(type))
2157 		return 0;
2158 
2159 	if (strchr(name, '[')) {
2160 		if (!kci->first_module_symbol || start < kci->first_module_symbol)
2161 			kci->first_module_symbol = start;
2162 		if (start > kci->last_module_symbol)
2163 			kci->last_module_symbol = start;
2164 		return 0;
2165 	}
2166 
2167 	if (!kci->first_symbol || start < kci->first_symbol)
2168 		kci->first_symbol = start;
2169 
2170 	if (!kci->last_symbol || start > kci->last_symbol)
2171 		kci->last_symbol = start;
2172 
2173 	if (!strcmp(name, "_stext")) {
2174 		kci->stext = start;
2175 		return 0;
2176 	}
2177 
2178 	if (!strcmp(name, "_etext")) {
2179 		kci->etext = start;
2180 		return 0;
2181 	}
2182 
2183 	if (is_entry_trampoline(name) && !kcore_copy__new_sym(kci, start))
2184 		return -1;
2185 
2186 	return 0;
2187 }
2188 
kcore_copy__parse_kallsyms(struct kcore_copy_info * kci,const char * dir)2189 static int kcore_copy__parse_kallsyms(struct kcore_copy_info *kci,
2190 				      const char *dir)
2191 {
2192 	char kallsyms_filename[PATH_MAX];
2193 
2194 	scnprintf(kallsyms_filename, PATH_MAX, "%s/kallsyms", dir);
2195 
2196 	if (symbol__restricted_filename(kallsyms_filename, "/proc/kallsyms"))
2197 		return -1;
2198 
2199 	if (kallsyms__parse(kallsyms_filename, kci,
2200 			    kcore_copy__process_kallsyms) < 0)
2201 		return -1;
2202 
2203 	return 0;
2204 }
2205 
kcore_copy__process_modules(void * arg,const char * name __maybe_unused,u64 start,u64 size __maybe_unused)2206 static int kcore_copy__process_modules(void *arg,
2207 				       const char *name __maybe_unused,
2208 				       u64 start, u64 size __maybe_unused)
2209 {
2210 	struct kcore_copy_info *kci = arg;
2211 
2212 	if (!kci->first_module || start < kci->first_module)
2213 		kci->first_module = start;
2214 
2215 	return 0;
2216 }
2217 
kcore_copy__parse_modules(struct kcore_copy_info * kci,const char * dir)2218 static int kcore_copy__parse_modules(struct kcore_copy_info *kci,
2219 				     const char *dir)
2220 {
2221 	char modules_filename[PATH_MAX];
2222 
2223 	scnprintf(modules_filename, PATH_MAX, "%s/modules", dir);
2224 
2225 	if (symbol__restricted_filename(modules_filename, "/proc/modules"))
2226 		return -1;
2227 
2228 	if (modules__parse(modules_filename, kci,
2229 			   kcore_copy__process_modules) < 0)
2230 		return -1;
2231 
2232 	return 0;
2233 }
2234 
kcore_copy__map(struct kcore_copy_info * kci,u64 start,u64 end,u64 pgoff,u64 s,u64 e)2235 static int kcore_copy__map(struct kcore_copy_info *kci, u64 start, u64 end,
2236 			   u64 pgoff, u64 s, u64 e)
2237 {
2238 	u64 len, offset;
2239 
2240 	if (s < start || s >= end)
2241 		return 0;
2242 
2243 	offset = (s - start) + pgoff;
2244 	len = e < end ? e - s : end - s;
2245 
2246 	return kcore_copy_info__addnew(kci, s, len, offset) ? 0 : -1;
2247 }
2248 
kcore_copy__read_map(u64 start,u64 len,u64 pgoff,void * data)2249 static int kcore_copy__read_map(u64 start, u64 len, u64 pgoff, void *data)
2250 {
2251 	struct kcore_copy_info *kci = data;
2252 	u64 end = start + len;
2253 	struct sym_data *sdat;
2254 
2255 	if (kcore_copy__map(kci, start, end, pgoff, kci->stext, kci->etext))
2256 		return -1;
2257 
2258 	if (kcore_copy__map(kci, start, end, pgoff, kci->first_module,
2259 			    kci->last_module_symbol))
2260 		return -1;
2261 
2262 	list_for_each_entry(sdat, &kci->syms, node) {
2263 		u64 s = round_down(sdat->addr, page_size);
2264 
2265 		if (kcore_copy__map(kci, start, end, pgoff, s, s + len))
2266 			return -1;
2267 	}
2268 
2269 	return 0;
2270 }
2271 
kcore_copy__read_maps(struct kcore_copy_info * kci,Elf * elf)2272 static int kcore_copy__read_maps(struct kcore_copy_info *kci, Elf *elf)
2273 {
2274 	if (elf_read_maps(elf, true, kcore_copy__read_map, kci) < 0)
2275 		return -1;
2276 
2277 	return 0;
2278 }
2279 
kcore_copy__find_remaps(struct kcore_copy_info * kci)2280 static void kcore_copy__find_remaps(struct kcore_copy_info *kci)
2281 {
2282 	struct phdr_data *p, *k = NULL;
2283 	u64 kend;
2284 
2285 	if (!kci->stext)
2286 		return;
2287 
2288 	/* Find phdr that corresponds to the kernel map (contains stext) */
2289 	kcore_copy__for_each_phdr(kci, p) {
2290 		u64 pend = p->addr + p->len - 1;
2291 
2292 		if (p->addr <= kci->stext && pend >= kci->stext) {
2293 			k = p;
2294 			break;
2295 		}
2296 	}
2297 
2298 	if (!k)
2299 		return;
2300 
2301 	kend = k->offset + k->len;
2302 
2303 	/* Find phdrs that remap the kernel */
2304 	kcore_copy__for_each_phdr(kci, p) {
2305 		u64 pend = p->offset + p->len;
2306 
2307 		if (p == k)
2308 			continue;
2309 
2310 		if (p->offset >= k->offset && pend <= kend)
2311 			p->remaps = k;
2312 	}
2313 }
2314 
kcore_copy__layout(struct kcore_copy_info * kci)2315 static void kcore_copy__layout(struct kcore_copy_info *kci)
2316 {
2317 	struct phdr_data *p;
2318 	off_t rel = 0;
2319 
2320 	kcore_copy__find_remaps(kci);
2321 
2322 	kcore_copy__for_each_phdr(kci, p) {
2323 		if (!p->remaps) {
2324 			p->rel = rel;
2325 			rel += p->len;
2326 		}
2327 		kci->phnum += 1;
2328 	}
2329 
2330 	kcore_copy__for_each_phdr(kci, p) {
2331 		struct phdr_data *k = p->remaps;
2332 
2333 		if (k)
2334 			p->rel = p->offset - k->offset + k->rel;
2335 	}
2336 }
2337 
kcore_copy__calc_maps(struct kcore_copy_info * kci,const char * dir,Elf * elf)2338 static int kcore_copy__calc_maps(struct kcore_copy_info *kci, const char *dir,
2339 				 Elf *elf)
2340 {
2341 	if (kcore_copy__parse_kallsyms(kci, dir))
2342 		return -1;
2343 
2344 	if (kcore_copy__parse_modules(kci, dir))
2345 		return -1;
2346 
2347 	if (kci->stext)
2348 		kci->stext = round_down(kci->stext, page_size);
2349 	else
2350 		kci->stext = round_down(kci->first_symbol, page_size);
2351 
2352 	if (kci->etext) {
2353 		kci->etext = round_up(kci->etext, page_size);
2354 	} else if (kci->last_symbol) {
2355 		kci->etext = round_up(kci->last_symbol, page_size);
2356 		kci->etext += page_size;
2357 	}
2358 
2359 	if (kci->first_module_symbol &&
2360 	    (!kci->first_module || kci->first_module_symbol < kci->first_module))
2361 		kci->first_module = kci->first_module_symbol;
2362 
2363 	kci->first_module = round_down(kci->first_module, page_size);
2364 
2365 	if (kci->last_module_symbol) {
2366 		kci->last_module_symbol = round_up(kci->last_module_symbol,
2367 						   page_size);
2368 		kci->last_module_symbol += page_size;
2369 	}
2370 
2371 	if (!kci->stext || !kci->etext)
2372 		return -1;
2373 
2374 	if (kci->first_module && !kci->last_module_symbol)
2375 		return -1;
2376 
2377 	if (kcore_copy__read_maps(kci, elf))
2378 		return -1;
2379 
2380 	kcore_copy__layout(kci);
2381 
2382 	return 0;
2383 }
2384 
kcore_copy__copy_file(const char * from_dir,const char * to_dir,const char * name)2385 static int kcore_copy__copy_file(const char *from_dir, const char *to_dir,
2386 				 const char *name)
2387 {
2388 	char from_filename[PATH_MAX];
2389 	char to_filename[PATH_MAX];
2390 
2391 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2392 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2393 
2394 	return copyfile_mode(from_filename, to_filename, 0400);
2395 }
2396 
kcore_copy__unlink(const char * dir,const char * name)2397 static int kcore_copy__unlink(const char *dir, const char *name)
2398 {
2399 	char filename[PATH_MAX];
2400 
2401 	scnprintf(filename, PATH_MAX, "%s/%s", dir, name);
2402 
2403 	return unlink(filename);
2404 }
2405 
kcore_copy__compare_fds(int from,int to)2406 static int kcore_copy__compare_fds(int from, int to)
2407 {
2408 	char *buf_from;
2409 	char *buf_to;
2410 	ssize_t ret;
2411 	size_t len;
2412 	int err = -1;
2413 
2414 	buf_from = malloc(page_size);
2415 	buf_to = malloc(page_size);
2416 	if (!buf_from || !buf_to)
2417 		goto out;
2418 
2419 	while (1) {
2420 		/* Use read because mmap won't work on proc files */
2421 		ret = read(from, buf_from, page_size);
2422 		if (ret < 0)
2423 			goto out;
2424 
2425 		if (!ret)
2426 			break;
2427 
2428 		len = ret;
2429 
2430 		if (readn(to, buf_to, len) != (int)len)
2431 			goto out;
2432 
2433 		if (memcmp(buf_from, buf_to, len))
2434 			goto out;
2435 	}
2436 
2437 	err = 0;
2438 out:
2439 	free(buf_to);
2440 	free(buf_from);
2441 	return err;
2442 }
2443 
kcore_copy__compare_files(const char * from_filename,const char * to_filename)2444 static int kcore_copy__compare_files(const char *from_filename,
2445 				     const char *to_filename)
2446 {
2447 	int from, to, err = -1;
2448 
2449 	from = open(from_filename, O_RDONLY);
2450 	if (from < 0)
2451 		return -1;
2452 
2453 	to = open(to_filename, O_RDONLY);
2454 	if (to < 0)
2455 		goto out_close_from;
2456 
2457 	err = kcore_copy__compare_fds(from, to);
2458 
2459 	close(to);
2460 out_close_from:
2461 	close(from);
2462 	return err;
2463 }
2464 
kcore_copy__compare_file(const char * from_dir,const char * to_dir,const char * name)2465 static int kcore_copy__compare_file(const char *from_dir, const char *to_dir,
2466 				    const char *name)
2467 {
2468 	char from_filename[PATH_MAX];
2469 	char to_filename[PATH_MAX];
2470 
2471 	scnprintf(from_filename, PATH_MAX, "%s/%s", from_dir, name);
2472 	scnprintf(to_filename, PATH_MAX, "%s/%s", to_dir, name);
2473 
2474 	return kcore_copy__compare_files(from_filename, to_filename);
2475 }
2476 
2477 /**
2478  * kcore_copy - copy kallsyms, modules and kcore from one directory to another.
2479  * @from_dir: from directory
2480  * @to_dir: to directory
2481  *
2482  * This function copies kallsyms, modules and kcore files from one directory to
2483  * another.  kallsyms and modules are copied entirely.  Only code segments are
2484  * copied from kcore.  It is assumed that two segments suffice: one for the
2485  * kernel proper and one for all the modules.  The code segments are determined
2486  * from kallsyms and modules files.  The kernel map starts at _stext or the
2487  * lowest function symbol, and ends at _etext or the highest function symbol.
2488  * The module map starts at the lowest module address and ends at the highest
2489  * module symbol.  Start addresses are rounded down to the nearest page.  End
2490  * addresses are rounded up to the nearest page.  An extra page is added to the
2491  * highest kernel symbol and highest module symbol to, hopefully, encompass that
2492  * symbol too.  Because it contains only code sections, the resulting kcore is
2493  * unusual.  One significant peculiarity is that the mapping (start -> pgoff)
2494  * is not the same for the kernel map and the modules map.  That happens because
2495  * the data is copied adjacently whereas the original kcore has gaps.  Finally,
2496  * kallsyms file is compared with its copy to check that modules have not been
2497  * loaded or unloaded while the copies were taking place.
2498  *
2499  * Return: %0 on success, %-1 on failure.
2500  */
kcore_copy(const char * from_dir,const char * to_dir)2501 int kcore_copy(const char *from_dir, const char *to_dir)
2502 {
2503 	struct kcore kcore;
2504 	struct kcore extract;
2505 	int idx = 0, err = -1;
2506 	off_t offset, sz;
2507 	struct kcore_copy_info kci = { .stext = 0, };
2508 	char kcore_filename[PATH_MAX];
2509 	char extract_filename[PATH_MAX];
2510 	struct phdr_data *p;
2511 
2512 	INIT_LIST_HEAD(&kci.phdrs);
2513 	INIT_LIST_HEAD(&kci.syms);
2514 
2515 	if (kcore_copy__copy_file(from_dir, to_dir, "kallsyms"))
2516 		return -1;
2517 
2518 	if (kcore_copy__copy_file(from_dir, to_dir, "modules"))
2519 		goto out_unlink_kallsyms;
2520 
2521 	scnprintf(kcore_filename, PATH_MAX, "%s/kcore", from_dir);
2522 	scnprintf(extract_filename, PATH_MAX, "%s/kcore", to_dir);
2523 
2524 	if (kcore__open(&kcore, kcore_filename))
2525 		goto out_unlink_modules;
2526 
2527 	if (kcore_copy__calc_maps(&kci, from_dir, kcore.elf))
2528 		goto out_kcore_close;
2529 
2530 	if (kcore__init(&extract, extract_filename, kcore.elfclass, false))
2531 		goto out_kcore_close;
2532 
2533 	if (kcore__copy_hdr(&kcore, &extract, kci.phnum))
2534 		goto out_extract_close;
2535 
2536 	offset = gelf_fsize(extract.elf, ELF_T_EHDR, 1, EV_CURRENT) +
2537 		 gelf_fsize(extract.elf, ELF_T_PHDR, kci.phnum, EV_CURRENT);
2538 	offset = round_up(offset, page_size);
2539 
2540 	kcore_copy__for_each_phdr(&kci, p) {
2541 		off_t offs = p->rel + offset;
2542 
2543 		if (kcore__add_phdr(&extract, idx++, offs, p->addr, p->len))
2544 			goto out_extract_close;
2545 	}
2546 
2547 	sz = kcore__write(&extract);
2548 	if (sz < 0 || sz > offset)
2549 		goto out_extract_close;
2550 
2551 	kcore_copy__for_each_phdr(&kci, p) {
2552 		off_t offs = p->rel + offset;
2553 
2554 		if (p->remaps)
2555 			continue;
2556 		if (copy_bytes(kcore.fd, p->offset, extract.fd, offs, p->len))
2557 			goto out_extract_close;
2558 	}
2559 
2560 	if (kcore_copy__compare_file(from_dir, to_dir, "kallsyms"))
2561 		goto out_extract_close;
2562 
2563 	err = 0;
2564 
2565 out_extract_close:
2566 	kcore__close(&extract);
2567 	if (err)
2568 		unlink(extract_filename);
2569 out_kcore_close:
2570 	kcore__close(&kcore);
2571 out_unlink_modules:
2572 	if (err)
2573 		kcore_copy__unlink(to_dir, "modules");
2574 out_unlink_kallsyms:
2575 	if (err)
2576 		kcore_copy__unlink(to_dir, "kallsyms");
2577 
2578 	kcore_copy__free_phdrs(&kci);
2579 	kcore_copy__free_syms(&kci);
2580 
2581 	return err;
2582 }
2583 
kcore_extract__create(struct kcore_extract * kce)2584 int kcore_extract__create(struct kcore_extract *kce)
2585 {
2586 	struct kcore kcore;
2587 	struct kcore extract;
2588 	size_t count = 1;
2589 	int idx = 0, err = -1;
2590 	off_t offset = page_size, sz;
2591 
2592 	if (kcore__open(&kcore, kce->kcore_filename))
2593 		return -1;
2594 
2595 	strcpy(kce->extract_filename, PERF_KCORE_EXTRACT);
2596 	if (kcore__init(&extract, kce->extract_filename, kcore.elfclass, true))
2597 		goto out_kcore_close;
2598 
2599 	if (kcore__copy_hdr(&kcore, &extract, count))
2600 		goto out_extract_close;
2601 
2602 	if (kcore__add_phdr(&extract, idx, offset, kce->addr, kce->len))
2603 		goto out_extract_close;
2604 
2605 	sz = kcore__write(&extract);
2606 	if (sz < 0 || sz > offset)
2607 		goto out_extract_close;
2608 
2609 	if (copy_bytes(kcore.fd, kce->offs, extract.fd, offset, kce->len))
2610 		goto out_extract_close;
2611 
2612 	err = 0;
2613 
2614 out_extract_close:
2615 	kcore__close(&extract);
2616 	if (err)
2617 		unlink(kce->extract_filename);
2618 out_kcore_close:
2619 	kcore__close(&kcore);
2620 
2621 	return err;
2622 }
2623 
kcore_extract__delete(struct kcore_extract * kce)2624 void kcore_extract__delete(struct kcore_extract *kce)
2625 {
2626 	unlink(kce->extract_filename);
2627 }
2628 
2629 #ifdef HAVE_GELF_GETNOTE_SUPPORT
2630 
sdt_adjust_loc(struct sdt_note * tmp,GElf_Addr base_off)2631 static void sdt_adjust_loc(struct sdt_note *tmp, GElf_Addr base_off)
2632 {
2633 	if (!base_off)
2634 		return;
2635 
2636 	if (tmp->bit32)
2637 		tmp->addr.a32[SDT_NOTE_IDX_LOC] =
2638 			tmp->addr.a32[SDT_NOTE_IDX_LOC] + base_off -
2639 			tmp->addr.a32[SDT_NOTE_IDX_BASE];
2640 	else
2641 		tmp->addr.a64[SDT_NOTE_IDX_LOC] =
2642 			tmp->addr.a64[SDT_NOTE_IDX_LOC] + base_off -
2643 			tmp->addr.a64[SDT_NOTE_IDX_BASE];
2644 }
2645 
sdt_adjust_refctr(struct sdt_note * tmp,GElf_Addr base_addr,GElf_Addr base_off)2646 static void sdt_adjust_refctr(struct sdt_note *tmp, GElf_Addr base_addr,
2647 			      GElf_Addr base_off)
2648 {
2649 	if (!base_off)
2650 		return;
2651 
2652 	if (tmp->bit32 && tmp->addr.a32[SDT_NOTE_IDX_REFCTR])
2653 		tmp->addr.a32[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2654 	else if (tmp->addr.a64[SDT_NOTE_IDX_REFCTR])
2655 		tmp->addr.a64[SDT_NOTE_IDX_REFCTR] -= (base_addr - base_off);
2656 }
2657 
2658 /**
2659  * populate_sdt_note : Parse raw data and identify SDT note
2660  * @elf: elf of the opened file
2661  * @data: raw data of a section with description offset applied
2662  * @len: note description size
2663  * @type: type of the note
2664  * @sdt_notes: List to add the SDT note
2665  *
2666  * Responsible for parsing the @data in section .note.stapsdt in @elf and
2667  * if its an SDT note, it appends to @sdt_notes list.
2668  */
populate_sdt_note(Elf ** elf,const char * data,size_t len,struct list_head * sdt_notes)2669 static int populate_sdt_note(Elf **elf, const char *data, size_t len,
2670 			     struct list_head *sdt_notes)
2671 {
2672 	const char *provider, *name, *args;
2673 	struct sdt_note *tmp = NULL;
2674 	GElf_Ehdr ehdr;
2675 	GElf_Shdr shdr;
2676 	int ret = -EINVAL;
2677 
2678 	union {
2679 		Elf64_Addr a64[NR_ADDR];
2680 		Elf32_Addr a32[NR_ADDR];
2681 	} buf;
2682 
2683 	Elf_Data dst = {
2684 		.d_buf = &buf, .d_type = ELF_T_ADDR, .d_version = EV_CURRENT,
2685 		.d_size = gelf_fsize((*elf), ELF_T_ADDR, NR_ADDR, EV_CURRENT),
2686 		.d_off = 0, .d_align = 0
2687 	};
2688 	Elf_Data src = {
2689 		.d_buf = (void *) data, .d_type = ELF_T_ADDR,
2690 		.d_version = EV_CURRENT, .d_size = dst.d_size, .d_off = 0,
2691 		.d_align = 0
2692 	};
2693 
2694 	tmp = (struct sdt_note *)calloc(1, sizeof(struct sdt_note));
2695 	if (!tmp) {
2696 		ret = -ENOMEM;
2697 		goto out_err;
2698 	}
2699 
2700 	INIT_LIST_HEAD(&tmp->note_list);
2701 
2702 	if (len < dst.d_size + 3)
2703 		goto out_free_note;
2704 
2705 	/* Translation from file representation to memory representation */
2706 	if (gelf_xlatetom(*elf, &dst, &src,
2707 			  elf_getident(*elf, NULL)[EI_DATA]) == NULL) {
2708 		pr_err("gelf_xlatetom : %s\n", elf_errmsg(-1));
2709 		goto out_free_note;
2710 	}
2711 
2712 	/* Populate the fields of sdt_note */
2713 	provider = data + dst.d_size;
2714 
2715 	name = (const char *)memchr(provider, '\0', data + len - provider);
2716 	if (name++ == NULL)
2717 		goto out_free_note;
2718 
2719 	tmp->provider = strdup(provider);
2720 	if (!tmp->provider) {
2721 		ret = -ENOMEM;
2722 		goto out_free_note;
2723 	}
2724 	tmp->name = strdup(name);
2725 	if (!tmp->name) {
2726 		ret = -ENOMEM;
2727 		goto out_free_prov;
2728 	}
2729 
2730 	args = memchr(name, '\0', data + len - name);
2731 
2732 	/*
2733 	 * There is no argument if:
2734 	 * - We reached the end of the note;
2735 	 * - There is not enough room to hold a potential string;
2736 	 * - The argument string is empty or just contains ':'.
2737 	 */
2738 	if (args == NULL || data + len - args < 2 ||
2739 		args[1] == ':' || args[1] == '\0')
2740 		tmp->args = NULL;
2741 	else {
2742 		tmp->args = strdup(++args);
2743 		if (!tmp->args) {
2744 			ret = -ENOMEM;
2745 			goto out_free_name;
2746 		}
2747 	}
2748 
2749 	if (gelf_getclass(*elf) == ELFCLASS32) {
2750 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf32_Addr));
2751 		tmp->bit32 = true;
2752 	} else {
2753 		memcpy(&tmp->addr, &buf, 3 * sizeof(Elf64_Addr));
2754 		tmp->bit32 = false;
2755 	}
2756 
2757 	if (!gelf_getehdr(*elf, &ehdr)) {
2758 		pr_debug("%s : cannot get elf header.\n", __func__);
2759 		ret = -EBADF;
2760 		goto out_free_args;
2761 	}
2762 
2763 	/* Adjust the prelink effect :
2764 	 * Find out the .stapsdt.base section.
2765 	 * This scn will help us to handle prelinking (if present).
2766 	 * Compare the retrieved file offset of the base section with the
2767 	 * base address in the description of the SDT note. If its different,
2768 	 * then accordingly, adjust the note location.
2769 	 */
2770 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_BASE_SCN, NULL))
2771 		sdt_adjust_loc(tmp, shdr.sh_offset);
2772 
2773 	/* Adjust reference counter offset */
2774 	if (elf_section_by_name(*elf, &ehdr, &shdr, SDT_PROBES_SCN, NULL))
2775 		sdt_adjust_refctr(tmp, shdr.sh_addr, shdr.sh_offset);
2776 
2777 	list_add_tail(&tmp->note_list, sdt_notes);
2778 	return 0;
2779 
2780 out_free_args:
2781 	zfree(&tmp->args);
2782 out_free_name:
2783 	zfree(&tmp->name);
2784 out_free_prov:
2785 	zfree(&tmp->provider);
2786 out_free_note:
2787 	free(tmp);
2788 out_err:
2789 	return ret;
2790 }
2791 
2792 /**
2793  * construct_sdt_notes_list : constructs a list of SDT notes
2794  * @elf : elf to look into
2795  * @sdt_notes : empty list_head
2796  *
2797  * Scans the sections in 'elf' for the section
2798  * .note.stapsdt. It, then calls populate_sdt_note to find
2799  * out the SDT events and populates the 'sdt_notes'.
2800  */
construct_sdt_notes_list(Elf * elf,struct list_head * sdt_notes)2801 static int construct_sdt_notes_list(Elf *elf, struct list_head *sdt_notes)
2802 {
2803 	GElf_Ehdr ehdr;
2804 	Elf_Scn *scn = NULL;
2805 	Elf_Data *data;
2806 	GElf_Shdr shdr;
2807 	size_t shstrndx, next;
2808 	GElf_Nhdr nhdr;
2809 	size_t name_off, desc_off, offset;
2810 	int ret = 0;
2811 
2812 	if (gelf_getehdr(elf, &ehdr) == NULL) {
2813 		ret = -EBADF;
2814 		goto out_ret;
2815 	}
2816 	if (elf_getshdrstrndx(elf, &shstrndx) != 0) {
2817 		ret = -EBADF;
2818 		goto out_ret;
2819 	}
2820 
2821 	/* Look for the required section */
2822 	scn = elf_section_by_name(elf, &ehdr, &shdr, SDT_NOTE_SCN, NULL);
2823 	if (!scn) {
2824 		ret = -ENOENT;
2825 		goto out_ret;
2826 	}
2827 
2828 	if ((shdr.sh_type != SHT_NOTE) || (shdr.sh_flags & SHF_ALLOC)) {
2829 		ret = -ENOENT;
2830 		goto out_ret;
2831 	}
2832 
2833 	data = elf_getdata(scn, NULL);
2834 
2835 	/* Get the SDT notes */
2836 	for (offset = 0; (next = gelf_getnote(data, offset, &nhdr, &name_off,
2837 					      &desc_off)) > 0; offset = next) {
2838 		if (nhdr.n_namesz == sizeof(SDT_NOTE_NAME) &&
2839 		    !memcmp(data->d_buf + name_off, SDT_NOTE_NAME,
2840 			    sizeof(SDT_NOTE_NAME))) {
2841 			/* Check the type of the note */
2842 			if (nhdr.n_type != SDT_NOTE_TYPE)
2843 				goto out_ret;
2844 
2845 			ret = populate_sdt_note(&elf, ((data->d_buf) + desc_off),
2846 						nhdr.n_descsz, sdt_notes);
2847 			if (ret < 0)
2848 				goto out_ret;
2849 		}
2850 	}
2851 	if (list_empty(sdt_notes))
2852 		ret = -ENOENT;
2853 
2854 out_ret:
2855 	return ret;
2856 }
2857 
2858 /**
2859  * get_sdt_note_list : Wrapper to construct a list of sdt notes
2860  * @head : empty list_head
2861  * @target : file to find SDT notes from
2862  *
2863  * This opens the file, initializes
2864  * the ELF and then calls construct_sdt_notes_list.
2865  */
get_sdt_note_list(struct list_head * head,const char * target)2866 int get_sdt_note_list(struct list_head *head, const char *target)
2867 {
2868 	Elf *elf;
2869 	int fd, ret;
2870 
2871 	fd = open(target, O_RDONLY);
2872 	if (fd < 0)
2873 		return -EBADF;
2874 
2875 	elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
2876 	if (!elf) {
2877 		ret = -EBADF;
2878 		goto out_close;
2879 	}
2880 	ret = construct_sdt_notes_list(elf, head);
2881 	elf_end(elf);
2882 out_close:
2883 	close(fd);
2884 	return ret;
2885 }
2886 
2887 /**
2888  * cleanup_sdt_note_list : free the sdt notes' list
2889  * @sdt_notes: sdt notes' list
2890  *
2891  * Free up the SDT notes in @sdt_notes.
2892  * Returns the number of SDT notes free'd.
2893  */
cleanup_sdt_note_list(struct list_head * sdt_notes)2894 int cleanup_sdt_note_list(struct list_head *sdt_notes)
2895 {
2896 	struct sdt_note *tmp, *pos;
2897 	int nr_free = 0;
2898 
2899 	list_for_each_entry_safe(pos, tmp, sdt_notes, note_list) {
2900 		list_del_init(&pos->note_list);
2901 		zfree(&pos->args);
2902 		zfree(&pos->name);
2903 		zfree(&pos->provider);
2904 		free(pos);
2905 		nr_free++;
2906 	}
2907 	return nr_free;
2908 }
2909 
2910 /**
2911  * sdt_notes__get_count: Counts the number of sdt events
2912  * @start: list_head to sdt_notes list
2913  *
2914  * Returns the number of SDT notes in a list
2915  */
sdt_notes__get_count(struct list_head * start)2916 int sdt_notes__get_count(struct list_head *start)
2917 {
2918 	struct sdt_note *sdt_ptr;
2919 	int count = 0;
2920 
2921 	list_for_each_entry(sdt_ptr, start, note_list)
2922 		count++;
2923 	return count;
2924 }
2925 #endif
2926 
symbol__elf_init(void)2927 void symbol__elf_init(void)
2928 {
2929 	elf_version(EV_CURRENT);
2930 }
2931