ltrace-elf.c revision 3c636fb789a29cac0c8f7f0982fb17afeee489dc
1/*
2 * This file is part of ltrace.
3 * Copyright (C) 2006,2010,2011,2012,2013 Petr Machata, Red Hat Inc.
4 * Copyright (C) 2010 Zachary T Welch, CodeSourcery
5 * Copyright (C) 2010 Joe Damato
6 * Copyright (C) 1997,1998,2001,2004,2007,2008,2009 Juan Cespedes
7 * Copyright (C) 2006 Olaf Hering, SUSE Linux GmbH
8 * Copyright (C) 2006 Eric Vaitl, Cisco Systems, Inc.
9 * Copyright (C) 2006 Paul Gilliam, IBM Corporation
10 * Copyright (C) 2006 Ian Wienand
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 * 02110-1301 USA
26 */
27
28#include "config.h"
29
30#include <assert.h>
31#ifdef	__linux__
32#include <endian.h>
33#endif
34#include <errno.h>
35#include <fcntl.h>
36#include <gelf.h>
37#include <inttypes.h>
38#include <search.h>
39#include <stdint.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <strings.h>
44#include <unistd.h>
45
46#include "backend.h"
47#include "filter.h"
48#include "library.h"
49#include "ltrace-elf.h"
50#include "proc.h"
51#include "debug.h"
52#include "options.h"
53
54#ifndef ARCH_HAVE_LTELF_DATA
55int
56arch_elf_init(struct ltelf *lte, struct library *lib)
57{
58	return 0;
59}
60
61void
62arch_elf_destroy(struct ltelf *lte)
63{
64}
65#endif
66
67int
68default_elf_add_plt_entry(struct process *proc, struct ltelf *lte,
69			  const char *a_name, GElf_Rela *rela, size_t ndx,
70			  struct library_symbol **ret)
71{
72	char *name = strdup(a_name);
73	if (name == NULL) {
74	fail_message:
75		fprintf(stderr, "Couldn't create symbol for PLT entry: %s\n",
76			strerror(errno));
77	fail:
78		free(name);
79		return -1;
80	}
81
82	GElf_Addr addr = arch_plt_sym_val(lte, ndx, rela);
83
84	struct library_symbol *libsym = malloc(sizeof(*libsym));
85	if (libsym == NULL)
86		goto fail_message;
87
88	/* XXX The double cast should be removed when
89	 * arch_addr_t becomes integral type.  */
90	arch_addr_t taddr = (arch_addr_t)
91		(uintptr_t)(addr + lte->bias);
92
93	if (library_symbol_init(libsym, taddr, name, 1, LS_TOPLT_EXEC) < 0) {
94		free(libsym);
95		goto fail;
96	}
97
98	libsym->next = *ret;
99	*ret = libsym;
100	return 0;
101}
102
103#ifndef ARCH_HAVE_ADD_PLT_ENTRY
104enum plt_status
105arch_elf_add_plt_entry(struct process *proc, struct ltelf *lte,
106		       const char *a_name, GElf_Rela *rela, size_t ndx,
107		       struct library_symbol **ret)
108{
109	return PLT_DEFAULT;
110}
111#endif
112
113Elf_Data *
114elf_loaddata(Elf_Scn *scn, GElf_Shdr *shdr)
115{
116	Elf_Data *data = elf_getdata(scn, NULL);
117	if (data == NULL || elf_getdata(scn, data) != NULL
118	    || data->d_off || data->d_size != shdr->sh_size)
119		return NULL;
120	return data;
121}
122
123static int
124elf_get_section_if(struct ltelf *lte, Elf_Scn **tgt_sec, GElf_Shdr *tgt_shdr,
125		   int (*predicate)(Elf_Scn *, GElf_Shdr *, void *data),
126		   void *data)
127{
128	int i;
129	for (i = 1; i < lte->ehdr.e_shnum; ++i) {
130		Elf_Scn *scn;
131		GElf_Shdr shdr;
132
133		scn = elf_getscn(lte->elf, i);
134		if (scn == NULL || gelf_getshdr(scn, &shdr) == NULL) {
135			debug(1, "Couldn't read section or header.");
136			return -1;
137		}
138		if (predicate(scn, &shdr, data)) {
139			*tgt_sec = scn;
140			*tgt_shdr = shdr;
141			return 0;
142		}
143	}
144
145	*tgt_sec = NULL;
146	return 0;
147}
148
149static int
150inside_p(Elf_Scn *scn, GElf_Shdr *shdr, void *data)
151{
152	GElf_Addr addr = *(GElf_Addr *)data;
153	return addr >= shdr->sh_addr
154		&& addr < shdr->sh_addr + shdr->sh_size;
155}
156
157int
158elf_get_section_covering(struct ltelf *lte, GElf_Addr addr,
159			 Elf_Scn **tgt_sec, GElf_Shdr *tgt_shdr)
160{
161	return elf_get_section_if(lte, tgt_sec, tgt_shdr,
162				  &inside_p, &addr);
163}
164
165static int
166type_p(Elf_Scn *scn, GElf_Shdr *shdr, void *data)
167{
168	GElf_Word type = *(GElf_Word *)data;
169	return shdr->sh_type == type;
170}
171
172int
173elf_get_section_type(struct ltelf *lte, GElf_Word type,
174		     Elf_Scn **tgt_sec, GElf_Shdr *tgt_shdr)
175{
176	return elf_get_section_if(lte, tgt_sec, tgt_shdr,
177				  &type_p, &type);
178}
179
180struct section_named_data {
181	struct ltelf *lte;
182	const char *name;
183};
184
185static int
186name_p(Elf_Scn *scn, GElf_Shdr *shdr, void *d)
187{
188	struct section_named_data *data = d;
189	const char *name = elf_strptr(data->lte->elf,
190				      data->lte->ehdr.e_shstrndx,
191				      shdr->sh_name);
192	return strcmp(name, data->name) == 0;
193}
194
195int
196elf_get_section_named(struct ltelf *lte, const char *name,
197		     Elf_Scn **tgt_sec, GElf_Shdr *tgt_shdr)
198{
199	struct section_named_data data = {
200		.lte = lte,
201		.name = name,
202	};
203	return elf_get_section_if(lte, tgt_sec, tgt_shdr,
204				  &name_p, &data);
205}
206
207static int
208need_data(Elf_Data *data, GElf_Xword offset, GElf_Xword size)
209{
210	assert(data != NULL);
211	if (data->d_size < size || offset > data->d_size - size) {
212		debug(1, "Not enough data to read %"PRId64"-byte value"
213		      " at offset %"PRId64".", size, offset);
214		return -1;
215	}
216	return 0;
217}
218
219#define DEF_READER(NAME, SIZE)						\
220	int								\
221	NAME(Elf_Data *data, GElf_Xword offset, uint##SIZE##_t *retp)	\
222	{								\
223		if (need_data(data, offset, SIZE / 8) < 0)		\
224			return -1;					\
225									\
226		if (data->d_buf == NULL) /* NODATA section */ {		\
227			*retp = 0;					\
228			return 0;					\
229		}							\
230									\
231		union {							\
232			uint##SIZE##_t dst;				\
233			char buf[0];					\
234		} u;							\
235		memcpy(u.buf, data->d_buf + offset, sizeof(u.dst));	\
236		*retp = u.dst;						\
237		return 0;						\
238	}
239
240DEF_READER(elf_read_u8, 8)
241DEF_READER(elf_read_u16, 16)
242DEF_READER(elf_read_u32, 32)
243DEF_READER(elf_read_u64, 64)
244
245#undef DEF_READER
246
247int
248open_elf(struct ltelf *lte, const char *filename)
249{
250	lte->fd = open(filename, O_RDONLY);
251	if (lte->fd == -1)
252		return 1;
253
254	elf_version(EV_CURRENT);
255
256#ifdef HAVE_ELF_C_READ_MMAP
257	lte->elf = elf_begin(lte->fd, ELF_C_READ_MMAP, NULL);
258#else
259	lte->elf = elf_begin(lte->fd, ELF_C_READ, NULL);
260#endif
261
262	if (lte->elf == NULL || elf_kind(lte->elf) != ELF_K_ELF) {
263		fprintf(stderr, "\"%s\" is not an ELF file\n", filename);
264		exit(EXIT_FAILURE);
265	}
266
267	if (gelf_getehdr(lte->elf, &lte->ehdr) == NULL) {
268		fprintf(stderr, "can't read ELF header of \"%s\": %s\n",
269			filename, elf_errmsg(-1));
270		exit(EXIT_FAILURE);
271	}
272
273	if (lte->ehdr.e_type != ET_EXEC && lte->ehdr.e_type != ET_DYN) {
274		fprintf(stderr, "\"%s\" is neither an ELF executable"
275			" nor a shared library\n", filename);
276		exit(EXIT_FAILURE);
277	}
278
279	if (1
280#ifdef LT_ELF_MACHINE
281	    && (lte->ehdr.e_ident[EI_CLASS] != LT_ELFCLASS
282		|| lte->ehdr.e_machine != LT_ELF_MACHINE)
283#endif
284#ifdef LT_ELF_MACHINE2
285	    && (lte->ehdr.e_ident[EI_CLASS] != LT_ELFCLASS2
286		|| lte->ehdr.e_machine != LT_ELF_MACHINE2)
287#endif
288#ifdef LT_ELF_MACHINE3
289	    && (lte->ehdr.e_ident[EI_CLASS] != LT_ELFCLASS3
290		|| lte->ehdr.e_machine != LT_ELF_MACHINE3)
291#endif
292		) {
293		fprintf(stderr,
294			"\"%s\" is ELF from incompatible architecture\n",
295			filename);
296		exit(EXIT_FAILURE);
297	}
298
299	return 0;
300}
301
302static void
303read_symbol_table(struct ltelf *lte, const char *filename,
304		  Elf_Scn *scn, GElf_Shdr *shdr, const char *name,
305		  Elf_Data **datap, size_t *countp, const char **strsp)
306{
307	*datap = elf_getdata(scn, NULL);
308	*countp = shdr->sh_size / shdr->sh_entsize;
309	if ((*datap == NULL || elf_getdata(scn, *datap) != NULL)
310	    && options.static_filter != NULL) {
311		fprintf(stderr, "Couldn't get data of section"
312			" %s from \"%s\": %s\n",
313			name, filename, elf_errmsg(-1));
314		exit(EXIT_FAILURE);
315	}
316
317	scn = elf_getscn(lte->elf, shdr->sh_link);
318	GElf_Shdr shdr2;
319	if (scn == NULL || gelf_getshdr(scn, &shdr2) == NULL) {
320		fprintf(stderr, "Couldn't get header of section"
321			" #%d from \"%s\": %s\n",
322			shdr->sh_link, filename, elf_errmsg(-1));
323		exit(EXIT_FAILURE);
324	}
325
326	Elf_Data *data = elf_getdata(scn, NULL);
327	if (data == NULL || elf_getdata(scn, data) != NULL
328	    || shdr2.sh_size != data->d_size || data->d_off) {
329		fprintf(stderr, "Couldn't get data of section"
330			" #%d from \"%s\": %s\n",
331			shdr2.sh_link, filename, elf_errmsg(-1));
332		exit(EXIT_FAILURE);
333	}
334
335	*strsp = data->d_buf;
336}
337
338static int
339do_init_elf(struct ltelf *lte, const char *filename)
340{
341	int i;
342	GElf_Addr relplt_addr = 0;
343	GElf_Addr soname_offset = 0;
344
345	debug(DEBUG_FUNCTION, "do_init_elf(filename=%s)", filename);
346	debug(1, "Reading ELF from %s...", filename);
347
348	for (i = 1; i < lte->ehdr.e_shnum; ++i) {
349		Elf_Scn *scn;
350		GElf_Shdr shdr;
351		const char *name;
352
353		scn = elf_getscn(lte->elf, i);
354		if (scn == NULL || gelf_getshdr(scn, &shdr) == NULL) {
355			fprintf(stderr,	"Couldn't get section #%d from"
356				" \"%s\": %s\n", i, filename, elf_errmsg(-1));
357			exit(EXIT_FAILURE);
358		}
359
360		name = elf_strptr(lte->elf, lte->ehdr.e_shstrndx, shdr.sh_name);
361		if (name == NULL) {
362			fprintf(stderr,	"Couldn't get name of section #%d from"
363				" \"%s\": %s\n", i, filename, elf_errmsg(-1));
364			exit(EXIT_FAILURE);
365		}
366
367		if (shdr.sh_type == SHT_SYMTAB) {
368			read_symbol_table(lte, filename,
369					  scn, &shdr, name, &lte->symtab,
370					  &lte->symtab_count, &lte->strtab);
371
372		} else if (shdr.sh_type == SHT_DYNSYM) {
373			read_symbol_table(lte, filename,
374					  scn, &shdr, name, &lte->dynsym,
375					  &lte->dynsym_count, &lte->dynstr);
376
377		} else if (shdr.sh_type == SHT_DYNAMIC) {
378			Elf_Data *data;
379			size_t j;
380
381			lte->dyn_addr = shdr.sh_addr + lte->bias;
382			lte->dyn_sz = shdr.sh_size;
383
384			data = elf_getdata(scn, NULL);
385			if (data == NULL || elf_getdata(scn, data) != NULL) {
386				fprintf(stderr, "Couldn't get .dynamic data"
387					" from \"%s\": %s\n",
388					filename, strerror(errno));
389				exit(EXIT_FAILURE);
390			}
391
392			for (j = 0; j < shdr.sh_size / shdr.sh_entsize; ++j) {
393				GElf_Dyn dyn;
394
395				if (gelf_getdyn(data, j, &dyn) == NULL) {
396					fprintf(stderr, "Couldn't get .dynamic"
397						" data from \"%s\": %s\n",
398						filename, strerror(errno));
399					exit(EXIT_FAILURE);
400				}
401				if (dyn.d_tag == DT_JMPREL)
402					relplt_addr = dyn.d_un.d_ptr;
403				else if (dyn.d_tag == DT_PLTRELSZ)
404					lte->relplt_size = dyn.d_un.d_val;
405				else if (dyn.d_tag == DT_SONAME)
406					soname_offset = dyn.d_un.d_val;
407			}
408		} else if (shdr.sh_type == SHT_PROGBITS
409			   || shdr.sh_type == SHT_NOBITS) {
410			if (strcmp(name, ".plt") == 0) {
411				lte->plt_addr = shdr.sh_addr;
412				lte->plt_size = shdr.sh_size;
413				lte->plt_data = elf_loaddata(scn, &shdr);
414				if (lte->plt_data == NULL)
415					fprintf(stderr,
416						"Can't load .plt data\n");
417				lte->plt_flags = shdr.sh_flags;
418			}
419#ifdef ARCH_SUPPORTS_OPD
420			else if (strcmp(name, ".opd") == 0) {
421				lte->opd_addr = (GElf_Addr *) (long) shdr.sh_addr;
422				lte->opd_size = shdr.sh_size;
423				lte->opd = elf_rawdata(scn, NULL);
424			}
425#endif
426		}
427	}
428
429	if (lte->dynsym == NULL || lte->dynstr == NULL) {
430		fprintf(stderr, "Couldn't find .dynsym or .dynstr in \"%s\"\n",
431			filename);
432		exit(EXIT_FAILURE);
433	}
434
435	if (!relplt_addr || !lte->plt_addr) {
436		debug(1, "%s has no PLT relocations", filename);
437		lte->relplt = NULL;
438		lte->relplt_count = 0;
439	} else if (lte->relplt_size == 0) {
440		debug(1, "%s has unknown PLT size", filename);
441		lte->relplt = NULL;
442		lte->relplt_count = 0;
443	} else {
444
445		for (i = 1; i < lte->ehdr.e_shnum; ++i) {
446			Elf_Scn *scn;
447			GElf_Shdr shdr;
448
449			scn = elf_getscn(lte->elf, i);
450			if (scn == NULL || gelf_getshdr(scn, &shdr) == NULL) {
451				fprintf(stderr, "Couldn't get section header"
452					" from \"%s\": %s\n",
453					filename, elf_errmsg(-1));
454				exit(EXIT_FAILURE);
455			}
456			if (shdr.sh_addr == relplt_addr
457			    && shdr.sh_size == lte->relplt_size) {
458				lte->relplt = elf_getdata(scn, NULL);
459				lte->relplt_count =
460				    shdr.sh_size / shdr.sh_entsize;
461				if (lte->relplt == NULL
462				    || elf_getdata(scn, lte->relplt) != NULL) {
463					fprintf(stderr, "Couldn't get .rel*.plt"
464						" data from \"%s\": %s\n",
465						filename, elf_errmsg(-1));
466					exit(EXIT_FAILURE);
467				}
468				break;
469			}
470		}
471
472		if (i == lte->ehdr.e_shnum) {
473			fprintf(stderr,
474				"Couldn't find .rel*.plt section in \"%s\"\n",
475				filename);
476			exit(EXIT_FAILURE);
477		}
478
479		debug(1, "%s %zd PLT relocations", filename, lte->relplt_count);
480	}
481
482	if (soname_offset != 0)
483		lte->soname = lte->dynstr + soname_offset;
484
485	return 0;
486}
487
488void
489do_close_elf(struct ltelf *lte)
490{
491	debug(DEBUG_FUNCTION, "do_close_elf()");
492	arch_elf_destroy(lte);
493	elf_end(lte->elf);
494	close(lte->fd);
495}
496
497int
498elf_get_sym_info(struct ltelf *lte, const char *filename,
499		 size_t sym_index, GElf_Rela *rela, GElf_Sym *sym)
500{
501	int i = sym_index;
502	GElf_Rel rel;
503	void *ret;
504
505	if (lte->relplt->d_type == ELF_T_REL) {
506		ret = gelf_getrel(lte->relplt, i, &rel);
507		rela->r_offset = rel.r_offset;
508		rela->r_info = rel.r_info;
509		rela->r_addend = 0;
510	} else {
511		ret = gelf_getrela(lte->relplt, i, rela);
512	}
513
514	if (ret == NULL
515	    || ELF64_R_SYM(rela->r_info) >= lte->dynsym_count
516	    || gelf_getsym(lte->dynsym, ELF64_R_SYM(rela->r_info),
517			   sym) == NULL) {
518		fprintf(stderr,
519			"Couldn't get relocation from \"%s\": %s\n",
520			filename, elf_errmsg(-1));
521		exit(EXIT_FAILURE);
522	}
523
524	return 0;
525}
526
527#ifndef ARCH_HAVE_GET_SYMINFO
528int
529arch_get_sym_info(struct ltelf *lte, const char *filename,
530		  size_t sym_index, GElf_Rela *rela, GElf_Sym *sym)
531{
532	return elf_get_sym_info(lte, filename, sym_index, rela, sym);
533}
534#endif
535
536static void
537mark_chain_latent(struct library_symbol *libsym)
538{
539	for (; libsym != NULL; libsym = libsym->next) {
540		debug(DEBUG_FUNCTION, "marking %s latent", libsym->name);
541		libsym->latent = 1;
542	}
543}
544
545static int
546populate_plt(struct process *proc, const char *filename,
547	     struct ltelf *lte, struct library *lib,
548	     int latent_plts)
549{
550	size_t i;
551	for (i = 0; i < lte->relplt_count; ++i) {
552		GElf_Rela rela;
553		GElf_Sym sym;
554
555		if (arch_get_sym_info(lte, filename, i, &rela, &sym) < 0)
556			continue; /* Skip this entry.  */
557
558		char const *name = lte->dynstr + sym.st_name;
559
560		/* If the symbol wasn't matched, reject it, unless we
561		 * need to keep latent PLT breakpoints for tracing
562		 * exports.  */
563		int matched = filter_matches_symbol(options.plt_filter,
564						    name, lib);
565		if (!matched && !latent_plts)
566			continue;
567
568		struct library_symbol *libsym = NULL;
569		switch (arch_elf_add_plt_entry(proc, lte, name,
570					       &rela, i, &libsym)) {
571		case PLT_DEFAULT:
572			if (default_elf_add_plt_entry(proc, lte, name,
573						      &rela, i, &libsym) < 0)
574			/* fall-through */
575		case PLT_FAIL:
576				return -1;
577			/* fall-through */
578		case PLT_OK:
579			if (libsym != NULL) {
580				/* If we are adding those symbols just
581				 * for tracing exports, mark them all
582				 * latent.  */
583				if (!matched)
584					mark_chain_latent(libsym);
585				library_add_symbol(lib, libsym);
586			}
587		}
588	}
589	return 0;
590}
591
592/* When -x rules result in request to trace several aliases, we only
593 * want to add such symbol once.  The only way that those symbols
594 * differ in is their name, e.g. in glibc you have __GI___libc_free,
595 * __cfree, __free, __libc_free, cfree and free all defined on the
596 * same address.  So instead we keep this unique symbol struct for
597 * each address, and replace name in libsym with a shorter variant if
598 * we find it.  */
599struct unique_symbol {
600	arch_addr_t addr;
601	struct library_symbol *libsym;
602};
603
604static int
605unique_symbol_cmp(const void *key, const void *val)
606{
607	const struct unique_symbol *sym_key = key;
608	const struct unique_symbol *sym_val = val;
609	return sym_key->addr != sym_val->addr;
610}
611
612static enum callback_status
613symbol_with_address(struct library_symbol *sym, void *addrptr)
614{
615	return sym->enter_addr == *(arch_addr_t *)addrptr
616		? CBS_STOP : CBS_CONT;
617}
618
619static int
620populate_this_symtab(struct process *proc, const char *filename,
621		     struct ltelf *lte, struct library *lib,
622		     Elf_Data *symtab, const char *strtab, size_t size,
623		     struct library_exported_name **names)
624{
625	/* If a valid NAMES is passed, we pass in *NAMES a list of
626	 * symbol names that this library exports.  */
627	if (names != NULL)
628		*names = NULL;
629
630	/* Using sorted array would be arguably better, but this
631	 * should be well enough for the number of symbols that we
632	 * typically deal with.  */
633	size_t num_symbols = 0;
634	struct unique_symbol *symbols = malloc(sizeof(*symbols) * size);
635	if (symbols == NULL) {
636		fprintf(stderr, "couldn't insert symbols for -x: %s\n",
637			strerror(errno));
638		return -1;
639	}
640
641	GElf_Word secflags[lte->ehdr.e_shnum];
642	size_t i;
643	for (i = 1; i < lte->ehdr.e_shnum; ++i) {
644		Elf_Scn *scn = elf_getscn(lte->elf, i);
645		GElf_Shdr shdr;
646		if (scn == NULL || gelf_getshdr(scn, &shdr) == NULL)
647			secflags[i] = 0;
648		else
649			secflags[i] = shdr.sh_flags;
650	}
651
652	for (i = 0; i < size; ++i) {
653		GElf_Sym sym;
654		if (gelf_getsym(symtab, i, &sym) == NULL) {
655		fail:
656			fprintf(stderr,
657				"couldn't get symbol #%zd from %s: %s\n",
658				i, filename, elf_errmsg(-1));
659			continue;
660		}
661
662		/* XXX support IFUNC as well.  */
663		if (GELF_ST_TYPE(sym.st_info) != STT_FUNC
664		    || sym.st_value == 0
665		    || sym.st_shndx == STN_UNDEF)
666			continue;
667
668		/* Find symbol name and snip version.  */
669		const char *orig_name = strtab + sym.st_name;
670		const char *version = strchr(orig_name, '@');
671		size_t len = version != NULL ? (assert(version > orig_name),
672						(size_t)(version - orig_name))
673			: strlen(orig_name);
674		char name[len + 1];
675		memcpy(name, orig_name, len);
676		name[len] = 0;
677
678		/* If we are interested in exports, store this name.  */
679		char *name_copy = NULL;
680		if (names != NULL) {
681			struct library_exported_name *export = NULL;
682			name_copy = strdup(name);
683
684			if (name_copy == NULL
685			    || (export = malloc(sizeof(*export))) == NULL) {
686				free(name_copy);
687				fprintf(stderr, "Couldn't store symbol %s.  "
688					"Tracing may be incomplete.\n", name);
689			} else {
690				export->name = name_copy;
691				export->own_name = 1;
692				export->next = *names;
693				*names = export;
694			}
695		}
696
697		/* If the symbol is not matched, skip it.  We already
698		 * stored it to export list above.  */
699		if (!filter_matches_symbol(options.static_filter, name, lib))
700			continue;
701
702		arch_addr_t addr = (arch_addr_t)
703			(uintptr_t)(sym.st_value + lte->bias);
704		arch_addr_t naddr;
705
706		/* On arches that support OPD, the value of typical
707		 * function symbol will be a pointer to .opd, but some
708		 * will point directly to .text.  We don't want to
709		 * translate those.  */
710		if (secflags[sym.st_shndx] & SHF_EXECINSTR) {
711			naddr = addr;
712		} else if (arch_translate_address(lte, addr, &naddr) < 0) {
713			fprintf(stderr,
714				"couldn't translate address of %s@%s: %s\n",
715				name, lib->soname, strerror(errno));
716			continue;
717		}
718
719		char *full_name;
720		int own_full_name = 1;
721		if (name_copy == NULL) {
722			full_name = strdup(name);
723			if (full_name == NULL)
724				goto fail;
725		} else {
726			full_name = name_copy;
727			own_full_name = 0;
728		}
729
730		/* Look whether we already have a symbol for this
731		 * address.  If not, add this one.  */
732		struct unique_symbol key = { naddr, NULL };
733		struct unique_symbol *unique
734			= lsearch(&key, symbols, &num_symbols,
735				  sizeof(*symbols), &unique_symbol_cmp);
736
737		if (unique->libsym == NULL) {
738			struct library_symbol *libsym = malloc(sizeof(*libsym));
739			if (libsym == NULL
740			    || library_symbol_init(libsym, naddr,
741						   full_name, own_full_name,
742						   LS_TOPLT_NONE) < 0) {
743				--num_symbols;
744				goto fail;
745			}
746			unique->libsym = libsym;
747			unique->addr = naddr;
748
749		} else if (strlen(full_name) < strlen(unique->libsym->name)) {
750			library_symbol_set_name(unique->libsym,
751						full_name, own_full_name);
752
753		} else if (own_full_name) {
754			free(full_name);
755		}
756	}
757
758	/* Now we do the union of this set of unique symbols with
759	 * what's already in the library.  */
760	for (i = 0; i < num_symbols; ++i) {
761		struct library_symbol *this_sym = symbols[i].libsym;
762		assert(this_sym != NULL);
763		struct library_symbol *other
764			= library_each_symbol(lib, NULL, symbol_with_address,
765					      &this_sym->enter_addr);
766		if (other != NULL) {
767			library_symbol_destroy(this_sym);
768			free(this_sym);
769			symbols[i].libsym = NULL;
770		}
771	}
772
773	for (i = 0; i < num_symbols; ++i)
774		if (symbols[i].libsym != NULL)
775			library_add_symbol(lib, symbols[i].libsym);
776
777	free(symbols);
778	return 0;
779}
780
781static int
782populate_symtab(struct process *proc, const char *filename,
783		struct ltelf *lte, struct library *lib,
784		int symtabs, int exports)
785{
786	int status;
787	if (symtabs && lte->symtab != NULL && lte->strtab != NULL
788	    && (status = populate_this_symtab(proc, filename, lte, lib,
789					      lte->symtab, lte->strtab,
790					      lte->symtab_count, NULL)) < 0)
791		return status;
792
793	/* Check whether we want to trace symbols implemented by this
794	 * library (-l).  */
795	struct library_exported_name **names = NULL;
796	if (exports) {
797		debug(DEBUG_FUNCTION, "-l matches %s", lib->soname);
798		names = &lib->exported_names;
799	}
800
801	return populate_this_symtab(proc, filename, lte, lib,
802				    lte->dynsym, lte->dynstr,
803				    lte->dynsym_count, names);
804}
805
806static int
807read_module(struct library *lib, struct process *proc,
808	    const char *filename, GElf_Addr bias, int main)
809{
810	struct ltelf lte = {};
811	if (open_elf(&lte, filename) < 0)
812		return -1;
813
814	/* XXX When we abstract ABI into a module, this should instead
815	 * become something like
816	 *
817	 *    proc->abi = arch_get_abi(lte.ehdr);
818	 *
819	 * The code in open_elf needs to be replaced by this logic.
820	 * Be warned that libltrace.c calls open_elf as well to
821	 * determine whether ABI is supported.  This is to get
822	 * reasonable error messages when trying to run 64-bit binary
823	 * with 32-bit ltrace.  It is desirable to preserve this.  */
824	proc->e_machine = lte.ehdr.e_machine;
825	proc->e_class = lte.ehdr.e_ident[EI_CLASS];
826	get_arch_dep(proc);
827
828	/* Find out the base address.  For PIE main binaries we look
829	 * into auxv, otherwise we scan phdrs.  */
830	if (main && lte.ehdr.e_type == ET_DYN) {
831		arch_addr_t entry;
832		if (process_get_entry(proc, &entry, NULL) < 0) {
833			fprintf(stderr, "Couldn't find entry of PIE %s\n",
834				filename);
835			return -1;
836		}
837		/* XXX The double cast should be removed when
838		 * arch_addr_t becomes integral type.  */
839		lte.entry_addr = (GElf_Addr)(uintptr_t)entry;
840		lte.bias = (GElf_Addr)(uintptr_t)entry - lte.ehdr.e_entry;
841
842	} else {
843		GElf_Phdr phdr;
844		size_t i;
845		for (i = 0; gelf_getphdr (lte.elf, i, &phdr) != NULL; ++i) {
846			if (phdr.p_type == PT_LOAD) {
847				lte.base_addr = phdr.p_vaddr + bias;
848				break;
849			}
850		}
851
852		lte.bias = bias;
853		lte.entry_addr = lte.ehdr.e_entry + lte.bias;
854
855		if (lte.base_addr == 0) {
856			fprintf(stderr,
857				"Couldn't determine base address of %s\n",
858				filename);
859			return -1;
860		}
861	}
862
863	if (do_init_elf(&lte, filename) < 0)
864		return -1;
865
866	if (arch_elf_init(&lte, lib) < 0) {
867		fprintf(stderr, "Backend initialization failed.\n");
868		return -1;
869	}
870
871	int status = 0;
872	if (lib == NULL)
873		goto fail;
874
875	/* Note that we set soname and pathname as soon as they are
876	 * allocated, so in case of further errors, this get released
877	 * when LIB is released, which should happen in the caller
878	 * when we return error.  */
879
880	if (lib->pathname == NULL) {
881		char *pathname = strdup(filename);
882		if (pathname == NULL)
883			goto fail;
884		library_set_pathname(lib, pathname, 1);
885	}
886
887	if (lte.soname != NULL) {
888		char *soname = strdup(lte.soname);
889		if (soname == NULL)
890			goto fail;
891		library_set_soname(lib, soname, 1);
892	} else {
893		const char *soname = rindex(lib->pathname, '/');
894		if (soname != NULL)
895			soname += 1;
896		else
897			soname = lib->pathname;
898		library_set_soname(lib, soname, 0);
899	}
900
901	/* XXX The double cast should be removed when
902	 * arch_addr_t becomes integral type.  */
903	arch_addr_t entry = (arch_addr_t)(uintptr_t)lte.entry_addr;
904	if (arch_translate_address(&lte, entry, &entry) < 0)
905		goto fail;
906
907	/* XXX The double cast should be removed when
908	 * arch_addr_t becomes integral type.  */
909	lib->base = (arch_addr_t)(uintptr_t)lte.base_addr;
910	lib->entry = entry;
911	/* XXX The double cast should be removed when
912	 * arch_addr_t becomes integral type.  */
913	lib->dyn_addr = (arch_addr_t)(uintptr_t)lte.dyn_addr;
914
915	/* There are two reasons that we need to inspect symbol tables
916	 * or populate PLT entries.  Either the user requested
917	 * corresponding tracing features (respectively -x and -e), or
918	 * they requested tracing exported symbols (-l).
919	 *
920	 * In the latter case we need to keep even those PLT slots
921	 * that are not requested by -e (but we keep them latent).  We
922	 * also need to inspect .dynsym to find what exports this
923	 * library provide, to turn on existing latent PLT
924	 * entries.  */
925
926	int plts = filter_matches_library(options.plt_filter, lib);
927	if ((plts || options.export_filter != NULL)
928	    && populate_plt(proc, filename, &lte, lib,
929			    options.export_filter != NULL) < 0)
930		goto fail;
931
932	int exports = filter_matches_library(options.export_filter, lib);
933	int symtabs = filter_matches_library(options.static_filter, lib);
934	if ((symtabs || exports)
935	    && populate_symtab(proc, filename, &lte, lib,
936			       symtabs, exports) < 0)
937		goto fail;
938
939done:
940	do_close_elf(&lte);
941	return status;
942
943fail:
944	status = -1;
945	goto done;
946}
947
948int
949ltelf_read_library(struct library *lib, struct process *proc,
950		   const char *filename, GElf_Addr bias)
951{
952	return read_module(lib, proc, filename, bias, 0);
953}
954
955
956struct library *
957ltelf_read_main_binary(struct process *proc, const char *path)
958{
959	struct library *lib = malloc(sizeof(*lib));
960	if (lib == NULL)
961		return NULL;
962	library_init(lib, LT_LIBTYPE_MAIN);
963	library_set_pathname(lib, path, 0);
964
965	/* There is a race between running the process and reading its
966	 * binary for internal consumption.  So open the binary from
967	 * the /proc filesystem.  XXX Note that there is similar race
968	 * for libraries, but there we don't have a nice answer like
969	 * that.  Presumably we could read the DSOs from the process
970	 * memory image, but that's not currently done.  */
971	char *fname = pid2name(proc->pid);
972	if (fname == NULL
973	    || read_module(lib, proc, fname, 0, 1) < 0) {
974		library_destroy(lib);
975		free(lib);
976		lib = NULL;
977	}
978
979	free(fname);
980	return lib;
981}
982