Ejemplo n.º 1
0
static void
_dwarf_elf_apply_reloc(Dwarf_Debug dbg, void *buf, Elf_Data *rel_data,
    Elf_Data *symtab_data, int endian)
{
	Dwarf_Unsigned type;
	GElf_Rela rela;
	GElf_Sym sym;
	size_t symndx;
	uint64_t offset;
	int size, j;

	j = 0;
	while (gelf_getrela(rel_data, j++, &rela) != NULL) {
		symndx = GELF_R_SYM(rela.r_info);
		type = GELF_R_TYPE(rela.r_info);

		if (gelf_getsym(symtab_data, symndx, &sym) == NULL)
			continue;

		offset = rela.r_offset;
		size = _dwarf_get_reloc_size(dbg, type);

		if (endian == ELFDATA2MSB)
			_dwarf_write_msb(buf, &offset, rela.r_addend, size);
		else
			_dwarf_write_lsb(buf, &offset, rela.r_addend, size);
	}
}
Ejemplo n.º 2
0
static void
_dwarf_elf_write_reloc(Dwarf_Debug dbg, Elf_Data *symtab_data, int endian,
    void *buf, uint64_t offset, GElf_Xword r_info, GElf_Sxword r_addend,
    int is_rel)
{
	GElf_Sym sym;
	int size;

	if (gelf_getsym(symtab_data, GELF_R_SYM(r_info), &sym) == NULL)
		return;
	if ((size = _dwarf_get_reloc_size(dbg, GELF_R_TYPE(r_info))) == 0)
		return; /* Unknown or non-absolute relocation. */
	if (is_rel) {
		uint64_t roffset = offset;

		if (endian == ELFDATA2MSB)
			r_addend = _dwarf_read_msb(buf, &roffset, size);
		else
			r_addend = _dwarf_read_lsb(buf, &roffset, size);
	}
	if (endian == ELFDATA2MSB)
		_dwarf_write_msb(buf, &offset, sym.st_value + r_addend, size);
	else
		_dwarf_write_lsb(buf, &offset, sym.st_value + r_addend, size);
}
Ejemplo n.º 3
0
static int parse_relo_and_apply(Elf_Data *data, Elf_Data *symbols,
				GElf_Shdr *shdr, struct bpf_insn *insn)
{
	int i, nrels;

	nrels = shdr->sh_size / shdr->sh_entsize;

	for (i = 0; i < nrels; i++) {
		GElf_Sym sym;
		GElf_Rel rel;
		unsigned int insn_idx;

		gelf_getrel(data, i, &rel);

		insn_idx = rel.r_offset / sizeof(struct bpf_insn);

		gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym);

		if (insn[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
			printf("invalid relo for insn[%d].code 0x%x\n",
			       insn_idx, insn[insn_idx].code);
			return 1;
		}
		insn[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
		insn[insn_idx].imm = map_fd[sym.st_value / sizeof(struct bpf_map_def)];
	}

	return 0;
}
Ejemplo n.º 4
0
static void parse_relocs(Elf *elf, Elf_Data *relocs, Elf_Data *symbols,
			unsigned symbol_sh_link,
			struct radeon_shader_binary *binary)
{
	unsigned i;

	if (!relocs || !symbols || !binary->reloc_count) {
		return;
	}
	binary->relocs = CALLOC(binary->reloc_count,
			sizeof(struct radeon_shader_reloc));
	for (i = 0; i < binary->reloc_count; i++) {
		GElf_Sym symbol;
		GElf_Rel rel;
		char *symbol_name;
		struct radeon_shader_reloc *reloc = &binary->relocs[i];

		gelf_getrel(relocs, i, &rel);
		gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &symbol);
		symbol_name = elf_strptr(elf, symbol_sh_link, symbol.st_name);

		reloc->offset = rel.r_offset;
		reloc->name = strdup(symbol_name);
	}
}
Ejemplo n.º 5
0
static int
mips_prelink_rel (struct prelink_info *info, GElf_Rel *rel, GElf_Addr reladdr)
{
  DSO *dso;

  /* Convert R_MIPS_REL32 relocations against global symbols into
     R_MIPS_GLOB_DAT if the addend is zero.  */
  dso = info->dso;
  if (GELF_R_TYPE (rel->r_info) == R_MIPS_REL32
      && GELF_R_SYM (rel->r_info) >= dso->info_DT_MIPS_GOTSYM
      && read_une32 (dso, rel->r_offset) == 0)
    {
      rel->r_info = GELF_R_INFO (GELF_R_SYM (rel->r_info), R_MIPS_GLOB_DAT);
      write_ne32 (dso, rel->r_offset,
		  info->resolve (info, GELF_R_SYM (rel->r_info),
				 GELF_R_TYPE (rel->r_info)));
      return 2;
    }
  return mips_prelink_reloc (info, rel->r_offset, rel->r_info, NULL);
}
Ejemplo n.º 6
0
static int
mips_adjust_reloc (DSO *dso, GElf_Addr r_offset, GElf_Xword r_info,
		   GElf_Addr start, GElf_Addr adjust, GElf_Rela *rela)
{
  GElf_Addr value;
  GElf_Word r_sym;

  if (GELF_R_TYPE (r_info) == R_MIPS_REL32)
    {
      r_sym = GELF_R_SYM (r_info);
      if (r_sym < dso->info_DT_MIPS_GOTSYM)
	{
	  /* glibc's dynamic linker adds the symbol's st_value and the
	     base address to the addend.  It therefore treats all symbols
	     as being relative, even if they would normally be considered
	     absolute.  For example, the special null symbol should always
	     have the value zero, even when the base address is nonzero,
	     but R_MIPS_REL32 relocations against the null symbol must
	     nevertheles be adjusted as if that symbol were relative.
	     The same would apply to SHN_ABS symbols too.

	     Thus the result of the relocation calculation must always
	     be adjusted by ADJUST.  (We do not need to check START because
	     every adjustment requested by the caller will affect all
	     legitimate local relocation values.)  This means that we
	     should add ADJUST to the addend if and only if the symbol's
	     value is not being adjusted.

	     In general, we can only check whether a symbol's value is
	     being adjusted by reading its entry in the dynamic symbol
	     table and then querying adjust_symbol_p.  However, this
	     generality is fortunately not needed.  Modern versions
	     of binutils will never generate R_MIPS_REL32 relocations
	     against symbols in the range [1, DT_MIPS_GOTSYM), so we
	     only need to handle relocations against the null symbol.  */
	  if (r_sym != 0)
	    {
	      error (0, 0, "%s: The prelinker does not support R_MIPS_REL32"
		     " relocs against local symbols", dso->filename);
	      return 1;
	    }
	  value = mips_read_addend (dso, r_offset, rela);
	  mips_write_addend (dso, r_offset, rela, value + adjust);
	}
    }
  return 0;
}
Ejemplo n.º 7
0
static int
mips_undo_prelink_rel (DSO *dso, GElf_Rel *rel, GElf_Addr reladdr)
{
  /* Convert R_MIPS_GLOB_DAT relocations back into R_MIPS_REL32
     relocations.  Ideally we'd have some mechanism for recording
     these changes in the undo section, but in the absence of that,
     it's better to assume that the original relocation was
     R_MIPS_REL32; R_MIPS_GLOB_DAT was added specifically for the
     prelinker and shouldn't be used in non-prelinked binaries.  */
  if (GELF_R_TYPE (rel->r_info) == R_MIPS_GLOB_DAT)
    {
      write_ne32 (dso, rel->r_offset, 0);
      rel->r_info = GELF_R_INFO (GELF_R_SYM (rel->r_info), R_MIPS_REL32);
      return 2;
    }
  return 0;
}
Ejemplo n.º 8
0
static int
mips_apply_reloc (struct prelink_info *info, GElf_Xword r_info,
		  GElf_Rela *rela, char *buf)
{
  DSO *dso;

  dso = info->dso;
  switch (GELF_R_TYPE (r_info))
    {
    case R_MIPS_NONE:
      break;

    case R_MIPS_REL32:
      mips_apply_adjustment (dso, rela, buf,
			     info->resolve (info, GELF_R_SYM (r_info),
					    GELF_R_TYPE (r_info)));
      break;

    default:
      return 1;
    }
  return 0;
}
Ejemplo n.º 9
0
/*
 * We need to check if we have a .dynsym, so that we can handle the
 * .plt, synthesizing its symbols, that aren't on the symtabs (be it
 * .dynsym or .symtab).
 * And always look at the original dso, not at debuginfo packages, that
 * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
 */
int dso__synthesize_plt_symbols(struct dso *dso, struct symsrc *ss, struct map *map,
				symbol_filter_t filter)
{
	uint32_t nr_rel_entries, idx;
	GElf_Sym sym;
	u64 plt_offset;
	GElf_Shdr shdr_plt;
	struct symbol *f;
	GElf_Shdr shdr_rel_plt, shdr_dynsym;
	Elf_Data *reldata, *syms, *symstrs;
	Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
	size_t dynsym_idx;
	GElf_Ehdr ehdr;
	char sympltname[1024];
	Elf *elf;
	int nr = 0, symidx, err = 0;

	if (!ss->dynsym)
		return 0;

	elf = ss->elf;
	ehdr = ss->ehdr;

	scn_dynsym = ss->dynsym;
	shdr_dynsym = ss->dynshdr;
	dynsym_idx = ss->dynsym_idx;

	if (scn_dynsym == NULL)
		goto out_elf_end;

	scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
					  ".rela.plt", NULL);
	if (scn_plt_rel == NULL) {
		scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
						  ".rel.plt", NULL);
		if (scn_plt_rel == NULL)
			goto out_elf_end;
	}

	err = -1;

	if (shdr_rel_plt.sh_link != dynsym_idx)
		goto out_elf_end;

	if (elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL) == NULL)
		goto out_elf_end;

	/*
	 * Fetch the relocation section to find the idxes to the GOT
	 * and the symbols in the .dynsym they refer to.
	 */
	reldata = elf_getdata(scn_plt_rel, NULL);
	if (reldata == NULL)
		goto out_elf_end;

	syms = elf_getdata(scn_dynsym, NULL);
	if (syms == NULL)
		goto out_elf_end;

	scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
	if (scn_symstrs == NULL)
		goto out_elf_end;

	symstrs = elf_getdata(scn_symstrs, NULL);
	if (symstrs == NULL)
		goto out_elf_end;

	if (symstrs->d_size == 0)
		goto out_elf_end;

	nr_rel_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
	plt_offset = shdr_plt.sh_offset;

	if (shdr_rel_plt.sh_type == SHT_RELA) {
		GElf_Rela pos_mem, *pos;

		elf_section__for_each_rela(reldata, pos, pos_mem, idx,
					   nr_rel_entries) {
			symidx = GELF_R_SYM(pos->r_info);
			plt_offset += shdr_plt.sh_entsize;
			gelf_getsym(syms, symidx, &sym);
			snprintf(sympltname, sizeof(sympltname),
				 "%s@plt", elf_sym__name(&sym, symstrs));

			f = symbol__new(plt_offset, shdr_plt.sh_entsize,
					STB_GLOBAL, sympltname);
			if (!f)
				goto out_elf_end;

			if (filter && filter(map, f))
				symbol__delete(f);
			else {
				symbols__insert(&dso->symbols[map->type], f);
				++nr;
			}
		}
Ejemplo n.º 10
0
Archivo: elves.c Proyecto: abrt/satyr
struct sr_elf_plt_entry *
sr_elf_get_procedure_linkage_table(const char *filename,
                                   char **error_message)
{
#ifdef WITH_ELFUTILS
    /* Open the input file. */
    int fd = open(filename, O_RDONLY);
    if (fd < 0)
    {
        *error_message = sr_asprintf("Failed to open file %s: %s",
                                     filename,
                                     strerror(errno));

        return NULL;
    }

    /* Initialize libelf on the opened file. */
    Elf *elf = elf_begin(fd, ELF_C_READ, NULL);
    if (!elf)
    {
        *error_message = sr_asprintf("Failed to run elf_begin on file %s: %s",
                                     filename,
                                     elf_errmsg(-1));

        close(fd);
        return NULL;
    }

    /* Find the .plt section. */
    GElf_Shdr shdr;
    Elf_Data *plt_data;
    char *find_section_error_message;
    size_t plt_section_index = find_elf_section_by_name(elf,
                                                        ".plt",
                                                        &plt_data,
                                                        &shdr,
                                                        &find_section_error_message);
    if (0 == plt_section_index)
    {
        *error_message = sr_asprintf("Failed to find .plt section for %s: %s",
                                     filename,
                                     find_section_error_message);

        free(find_section_error_message);
        elf_end(elf);
        close(fd);
        return NULL;
    }

    /* Find the relocation section for .plt (typically .rela.plt), together
     * with its symbol and string table
     */
    uint64_t plt_base = shdr.sh_addr;
    Elf_Data *rela_plt_data = NULL;
    Elf_Data *plt_symbols = NULL;
    size_t stringtable = 0;
    Elf_Scn *section = NULL;
    while ((section = elf_nextscn(elf, section)) != NULL)
    {
        if (gelf_getshdr(section, &shdr) != &shdr)
        {
            *error_message = sr_asprintf("gelf_getshdr failed for %s: %s",
                                         filename,
                                         elf_errmsg(-1));

            elf_end(elf);
            close(fd);
            return NULL;
        }

        if (shdr.sh_type == SHT_RELA &&
            shdr.sh_info == plt_section_index)
        {
            rela_plt_data = elf_getdata(section, NULL);
            if (!rela_plt_data)
            {
                *error_message = sr_asprintf("elf_getdata failed for %s: %s",
                                             filename,
                                             elf_errmsg(-1));

                elf_end(elf);
                close(fd);
                return NULL;
            }

            /* Get symbol section for .rela.plt */
            Elf_Scn *symbol_section = elf_getscn(elf, shdr.sh_link);
            if (!symbol_section)
            {
                *error_message = sr_asprintf("elf_getscn failed for %s: %s",
                                             filename,
                                             elf_errmsg(-1));

                elf_end(elf);
                close(fd);
                return NULL;
            }

            plt_symbols = elf_getdata(symbol_section, NULL);
            if (!plt_symbols)
            {
                *error_message = sr_asprintf("elf_getdata failed for %s: %s",
                                             filename,
                                             elf_errmsg(-1));

                elf_end(elf);
                close(fd);
                return NULL;
            }

            /* Get string table for the symbol table. */
            if (gelf_getshdr(symbol_section, &shdr) != &shdr)
            {
                *error_message = sr_asprintf("gelf_getshdr failed for %s: %s",
                                             filename,
                                             elf_errmsg(-1));

                elf_end(elf);
                close(fd);
                return NULL;
            }

            stringtable = shdr.sh_link;
            break;
        }
    }

    if (0 == stringtable)
    {
        *error_message = sr_asprintf("Unable to read symbol table for .plt for file %s",
                                     filename);

        elf_end(elf);
        close(fd);
        return NULL;
    }

    /* PLT looks like this (see also AMD64 ABI, page 78):
     *
     * Disassembly of section .plt:
     *
     * 0000003463e01010 <attr_removef@plt-0x10>:
     *   3463e01010:   ff 35 2a 2c 20 00       pushq  0x202c2a(%rip)         <-- here is plt_base
     *   3463e01016:   ff 25 2c 2c 20 00       jmpq   *0x202c2c(%rip)            each "slot" is 16B wide
     *   3463e0101c:   0f 1f 40 00             nopl   0x0(%rax)                  0-th slot is skipped
     *
     * 0000003463e01020 <attr_removef@plt>:
     *   3463e01020:   ff 25 2a 2c 20 00       jmpq   *0x202c2a(%rip)
     *   3463e01026:   68 00 00 00 00          pushq  $0x0                   <-- this is the number we want
     *   3463e0102b:   e9 e0 ff ff ff          jmpq   3463e01010 <_init+0x18>
     *
     * 0000003463e01030 <fgetxattr@plt>:
     *   3463e01030:   ff 25 22 2c 20 00       jmpq   *0x202c22(%rip)
     *   3463e01036:   68 01 00 00 00          pushq  $0x1
     *   3463e0103b:   e9 d0 ff ff ff          jmpq   3463e01010 <_init+0x18>
     */
    struct sr_elf_plt_entry *result = NULL, *last = NULL;
    for (unsigned plt_offset = 16; plt_offset < plt_data->d_size; plt_offset += 16)
    {
        uint32_t *plt_index = (uint32_t*)(plt_data->d_buf + plt_offset + 7);

        GElf_Rela rela;
        if (gelf_getrela(rela_plt_data, *plt_index, &rela) != &rela)
        {
            *error_message = sr_asprintf("gelf_getrela failed for %s: %s",
                                         filename,
                                         elf_errmsg(-1));

            sr_elf_procedure_linkage_table_free(result);
            elf_end(elf);
            close(fd);
            return NULL;
        }

        GElf_Sym symb;
        if (gelf_getsym(plt_symbols, GELF_R_SYM(rela.r_info), &symb) != &symb)
        {
            *error_message = sr_asprintf("gelf_getsym failed for %s: %s",
                                         filename,
                                         elf_errmsg(-1));

            sr_elf_procedure_linkage_table_free(result);
            elf_end(elf);
            close(fd);
            return NULL;
        }

        struct sr_elf_plt_entry *entry = sr_malloc(sizeof(struct sr_elf_plt_entry));
        entry->symbol_name = sr_strdup(elf_strptr(elf, stringtable,
                                                  symb.st_name));

        entry->address = (uint64_t)(plt_base + plt_offset);
        entry->next = NULL;

        if (result)
        {
            last->next = entry;
            last = entry;
        }
        else
            result = last = entry;
    }

    elf_end(elf);
    close(fd);
    return result;
#else /* WITH_ELFUTILS */
    *error_message = sr_asprintf("satyr compiled without elfutils");
    return NULL;
#endif /* WITH_ELFUTILS */
}
Ejemplo n.º 11
0
static int
mips_prelink_conflict_reloc (DSO *dso, struct prelink_info *info,
			     GElf_Addr r_offset, GElf_Xword r_info,
			     GElf_Rela *rela)
{
  GElf_Addr value;
  struct prelink_conflict *conflict;
  struct prelink_tls *tls = NULL;
  GElf_Rela *entry;

  if (info->dso == dso)
    return 0;

  conflict = prelink_conflict (info, GELF_R_SYM (r_info),
			       GELF_R_TYPE (r_info));
  if (conflict == NULL)
    {
      switch (GELF_R_TYPE (r_info))
	{
	case R_MIPS_TLS_DTPMOD32:
	case R_MIPS_TLS_TPREL32:
	  tls = info->curtls;
	  if (tls == NULL)
	    return 0;
	  /* A relocation against symbol 0.  A shared library cannot
	     know what the final module IDs or TP-relative offsets are,
	     so the executable must always have a conflict for them.  */
	  value = 0;
	  break;
	default:
	  return 0;
	}
    }
  else if (conflict->ifunc)
    {
      error (0, 0, "%s: STT_GNU_IFUNC not handled on MIPS yet",
	     dso->filename);
      return 1;
    }
  else
    {
      /* DTPREL32 relocations just involve the symbol value; no other
	 TLS information is needed.  Ignore conflicts created from a
	 lookup of type RTYPE_CLASS_TLS if no real conflict exists.  */
      if (GELF_R_TYPE (r_info) == R_MIPS_TLS_DTPREL32
	  && conflict->lookup.tls == conflict->conflict.tls
	  && conflict->lookupval == conflict->conflictval)
	return 0;

      value = conflict_lookup_value (conflict);
    }
  /* VALUE now contains the final symbol value.  Change it to the
     value we want to store at R_OFFSET.  */
  switch (GELF_R_TYPE (r_info))
    {
    case R_MIPS_REL32:
      value += mips_read_addend (dso, r_offset, rela);
      break;

    case R_MIPS_GLOB_DAT:
      break;

    case R_MIPS_TLS_DTPMOD32:
      if (conflict != NULL && mips_get_tls (dso, conflict, &tls) == 1)
	return 1;
      value = tls->modid;
      break;

    case R_MIPS_TLS_DTPREL32:
      value += mips_read_addend (dso, r_offset, rela) - TLS_DTV_OFFSET;
      break;

    case R_MIPS_TLS_TPREL32:
      if (conflict != NULL && mips_get_tls (dso, conflict, &tls) == 1)
	return 1;
      value += (mips_read_addend (dso, r_offset, rela)
		+ tls->offset - TLS_TP_OFFSET);
      break;

    default:
      error (0, 0, "%s: Unknown MIPS relocation type %d", dso->filename,
	     (int) GELF_R_TYPE (r_info));
      return 1;
    }
  /* Create and initialize a conflict entry.  */
  entry = prelink_conflict_add_rela (info);
  if (entry == NULL)
    return 1;
  entry->r_addend = (int32_t) value;
  entry->r_offset = r_offset;
  entry->r_info = GELF_R_INFO (0, R_MIPS_REL32);
  return 0;
}
Ejemplo n.º 12
0
static int
bpf_program__collect_reloc(struct bpf_program *prog,
			   size_t nr_maps, GElf_Shdr *shdr,
			   Elf_Data *data, Elf_Data *symbols,
			   int maps_shndx)
{
	int i, nrels;

	pr_debug("collecting relocating info for: '%s'\n",
		 prog->section_name);
	nrels = shdr->sh_size / shdr->sh_entsize;

	prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
	if (!prog->reloc_desc) {
		pr_warning("failed to alloc memory in relocation\n");
		return -ENOMEM;
	}
	prog->nr_reloc = nrels;

	for (i = 0; i < nrels; i++) {
		GElf_Sym sym;
		GElf_Rel rel;
		unsigned int insn_idx;
		struct bpf_insn *insns = prog->insns;
		size_t map_idx;

		if (!gelf_getrel(data, i, &rel)) {
			pr_warning("relocation: failed to get %d reloc\n", i);
			return -LIBBPF_ERRNO__FORMAT;
		}

		if (!gelf_getsym(symbols,
				 GELF_R_SYM(rel.r_info),
				 &sym)) {
			pr_warning("relocation: symbol %"PRIx64" not found\n",
				   GELF_R_SYM(rel.r_info));
			return -LIBBPF_ERRNO__FORMAT;
		}

		if (sym.st_shndx != maps_shndx) {
			pr_warning("Program '%s' contains non-map related relo data pointing to section %u\n",
				   prog->section_name, sym.st_shndx);
			return -LIBBPF_ERRNO__RELOC;
		}

		insn_idx = rel.r_offset / sizeof(struct bpf_insn);
		pr_debug("relocation: insn_idx=%u\n", insn_idx);

		if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
			pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
				   insn_idx, insns[insn_idx].code);
			return -LIBBPF_ERRNO__RELOC;
		}

		map_idx = sym.st_value / sizeof(struct bpf_map_def);
		if (map_idx >= nr_maps) {
			pr_warning("bpf relocation: map_idx %d large than %d\n",
				   (int)map_idx, (int)nr_maps - 1);
			return -LIBBPF_ERRNO__RELOC;
		}

		prog->reloc_desc[i].insn_idx = insn_idx;
		prog->reloc_desc[i].map_idx = map_idx;
	}
	return 0;
}
Ejemplo n.º 13
0
static Dwfl_Error
relocate_section (Dwfl_Module *mod, Elf *relocated, const GElf_Ehdr *ehdr,
		  size_t shstrndx, struct reloc_symtab_cache *reloc_symtab,
		  Elf_Scn *scn, GElf_Shdr *shdr,
		  Elf_Scn *tscn, bool debugscn, bool partial)
{
  /* First, fetch the name of the section these relocations apply to.  */
  GElf_Shdr tshdr_mem;
  GElf_Shdr *tshdr = gelf_getshdr (tscn, &tshdr_mem);
  const char *tname = elf_strptr (relocated, shstrndx, tshdr->sh_name);
  if (tname == NULL)
    return DWFL_E_LIBELF;

  if (unlikely (tshdr->sh_type == SHT_NOBITS) || unlikely (tshdr->sh_size == 0))
    /* No contents to relocate.  */
    return DWFL_E_NOERROR;

  if (debugscn && ! ebl_debugscn_p (mod->ebl, tname))
    /* This relocation section is not for a debugging section.
       Nothing to do here.  */
    return DWFL_E_NOERROR;

  /* Fetch the section data that needs the relocations applied.  */
  Elf_Data *tdata = elf_rawdata (tscn, NULL);
  if (tdata == NULL)
    return DWFL_E_LIBELF;

  /* Apply one relocation.  Returns true for any invalid data.  */
  Dwfl_Error relocate (GElf_Addr offset, const GElf_Sxword *addend,
		       int rtype, int symndx)
  {
    /* First see if this is a reloc we can handle.
       If we are skipping it, don't bother resolving the symbol.  */

    if (unlikely (rtype == 0))
      /* In some odd situations, the linker can leave R_*_NONE relocs
	 behind.  This is probably bogus ld -r behavior, but the only
	 cases it's known to appear in are harmless: DWARF data
	 referring to addresses in a section that has been discarded.
	 So we just pretend it's OK without further relocation.  */
      return DWFL_E_NOERROR;

    Elf_Type type = ebl_reloc_simple_type (mod->ebl, rtype);
    if (unlikely (type == ELF_T_NUM))
      return DWFL_E_BADRELTYPE;

    /* First, resolve the symbol to an absolute value.  */
    GElf_Addr value;

    if (symndx == STN_UNDEF)
      /* When strip removes a section symbol referring to a
	 section moved into the debuginfo file, it replaces
	 that symbol index in relocs with STN_UNDEF.  We
	 don't actually need the symbol, because those relocs
	 are always references relative to the nonallocated
	 debugging sections, which start at zero.  */
      value = 0;
    else
      {
	GElf_Sym sym;
	GElf_Word shndx;
	Dwfl_Error error = relocate_getsym (mod, relocated, reloc_symtab,
					    symndx, &sym, &shndx);
	if (unlikely (error != DWFL_E_NOERROR))
	  return error;

	if (shndx == SHN_UNDEF || shndx == SHN_COMMON)
	  {
	    /* Maybe we can figure it out anyway.  */
	    error = resolve_symbol (mod, reloc_symtab, &sym, shndx);
	    if (error != DWFL_E_NOERROR
		&& !(error == DWFL_E_RELUNDEF && shndx == SHN_COMMON))
	      return error;
	  }

	value = sym.st_value;
      }

    /* These are the types we can relocate.  */
#define TYPES		DO_TYPE (BYTE, Byte); DO_TYPE (HALF, Half);	\
    DO_TYPE (WORD, Word); DO_TYPE (SWORD, Sword);			\
    DO_TYPE (XWORD, Xword); DO_TYPE (SXWORD, Sxword)
    size_t size;
    switch (type)
      {
#define DO_TYPE(NAME, Name)			\
	case ELF_T_##NAME:			\
	  size = sizeof (GElf_##Name);		\
	break
	TYPES;
#undef DO_TYPE
      default:
	return DWFL_E_BADRELTYPE;
      }

    if (offset + size > tdata->d_size)
      return DWFL_E_BADRELOFF;

#define DO_TYPE(NAME, Name) GElf_##Name Name;
    union { TYPES; } tmpbuf;
#undef DO_TYPE
    Elf_Data tmpdata =
      {
	.d_type = type,
	.d_buf = &tmpbuf,
	.d_size = size,
	.d_version = EV_CURRENT,
      };
    Elf_Data rdata =
      {
	.d_type = type,
	.d_buf = tdata->d_buf + offset,
	.d_size = size,
	.d_version = EV_CURRENT,
      };

    /* XXX check for overflow? */
    if (addend)
      {
	/* For the addend form, we have the value already.  */
	value += *addend;
	switch (type)
	  {
#define DO_TYPE(NAME, Name)			\
	    case ELF_T_##NAME:			\
	      tmpbuf.Name = value;		\
	    break
	    TYPES;
#undef DO_TYPE
	  default:
	    abort ();
	  }
      }
    else
      {
	/* Extract the original value and apply the reloc.  */
	Elf_Data *d = gelf_xlatetom (relocated, &tmpdata, &rdata,
				     ehdr->e_ident[EI_DATA]);
	if (d == NULL)
	  return DWFL_E_LIBELF;
	assert (d == &tmpdata);
	switch (type)
	  {
#define DO_TYPE(NAME, Name)				\
	    case ELF_T_##NAME:				\
	      tmpbuf.Name += (GElf_##Name) value;	\
	    break
	    TYPES;
#undef DO_TYPE
	  default:
	    abort ();
	  }
      }

    /* Now convert the relocated datum back to the target
       format.  This will write into rdata.d_buf, which
       points into the raw section data being relocated.  */
    Elf_Data *s = gelf_xlatetof (relocated, &rdata, &tmpdata,
				 ehdr->e_ident[EI_DATA]);
    if (s == NULL)
      return DWFL_E_LIBELF;
    assert (s == &rdata);

    /* We have applied this relocation!  */
    return DWFL_E_NOERROR;
  }

  /* Fetch the relocation section and apply each reloc in it.  */
  Elf_Data *reldata = elf_getdata (scn, NULL);
  if (reldata == NULL)
    return DWFL_E_LIBELF;

  Dwfl_Error result = DWFL_E_NOERROR;
  bool first_badreltype = true;
  inline void check_badreltype (void)
  {
    if (first_badreltype)
      {
	first_badreltype = false;
	if (ebl_get_elfmachine (mod->ebl) == EM_NONE)
	  /* This might be because ebl_openbackend failed to find
	     any libebl_CPU.so library.  Diagnose that clearly.  */
	  result = DWFL_E_UNKNOWN_MACHINE;
      }
  }

  size_t nrels = shdr->sh_size / shdr->sh_entsize;
  size_t complete = 0;
  if (shdr->sh_type == SHT_REL)
    for (size_t relidx = 0; !result && relidx < nrels; ++relidx)
      {
	GElf_Rel rel_mem, *r = gelf_getrel (reldata, relidx, &rel_mem);
	if (r == NULL)
	  return DWFL_E_LIBELF;
	result = relocate (r->r_offset, NULL,
			   GELF_R_TYPE (r->r_info),
			   GELF_R_SYM (r->r_info));
	check_badreltype ();
	if (partial)
	  switch (result)
	    {
	    case DWFL_E_NOERROR:
	      /* We applied the relocation.  Elide it.  */
	      memset (&rel_mem, 0, sizeof rel_mem);
	      gelf_update_rel (reldata, relidx, &rel_mem);
	      ++complete;
	      break;
	    case DWFL_E_BADRELTYPE:
	    case DWFL_E_RELUNDEF:
	      /* We couldn't handle this relocation.  Skip it.  */
	      result = DWFL_E_NOERROR;
	      break;
	    default:
	      break;
	    }
      }
  else
    for (size_t relidx = 0; !result && relidx < nrels; ++relidx)
      {
	GElf_Rela rela_mem, *r = gelf_getrela (reldata, relidx,
					       &rela_mem);
	if (r == NULL)
	  return DWFL_E_LIBELF;
	result = relocate (r->r_offset, &r->r_addend,
			   GELF_R_TYPE (r->r_info),
			   GELF_R_SYM (r->r_info));
	check_badreltype ();
	if (partial)
	  switch (result)
	    {
	    case DWFL_E_NOERROR:
	      /* We applied the relocation.  Elide it.  */
	      memset (&rela_mem, 0, sizeof rela_mem);
	      gelf_update_rela (reldata, relidx, &rela_mem);
	      ++complete;
	      break;
	    case DWFL_E_BADRELTYPE:
	    case DWFL_E_RELUNDEF:
	      /* We couldn't handle this relocation.  Skip it.  */
	      result = DWFL_E_NOERROR;
	      break;
	    default:
	      break;
	    }
      }

  if (likely (result == DWFL_E_NOERROR))
    {
      if (!partial || complete == nrels)
	/* Mark this relocation section as being empty now that we have
	   done its work.  This affects unstrip -R, so e.g. it emits an
	   empty .rela.debug_info along with a .debug_info that has
	   already been fully relocated.  */
	nrels = 0;
      else if (complete != 0)
	{
	  /* We handled some of the relocations but not all.
	     We've zeroed out the ones we processed.
	     Now remove them from the section.  */

	  size_t next = 0;
	  if (shdr->sh_type == SHT_REL)
	    for (size_t relidx = 0; relidx < nrels; ++relidx)
	      {
		GElf_Rel rel_mem;
		GElf_Rel *r = gelf_getrel (reldata, relidx, &rel_mem);
		if (r->r_info != 0 || r->r_offset != 0)
		  {
		    if (next != relidx)
		      gelf_update_rel (reldata, next, r);
		    ++next;
		  }
	      }
	  else
	    for (size_t relidx = 0; relidx < nrels; ++relidx)
	      {
		GElf_Rela rela_mem;
		GElf_Rela *r = gelf_getrela (reldata, relidx, &rela_mem);
		if (r->r_info != 0 || r->r_offset != 0 || r->r_addend != 0)
		  {
		    if (next != relidx)
		      gelf_update_rela (reldata, next, r);
		    ++next;
		  }
	      }
	  nrels = next;
	}

      shdr->sh_size = reldata->d_size = nrels * shdr->sh_entsize;
      gelf_update_shdr (scn, shdr);
    }

  return result;
}

Dwfl_Error
internal_function
__libdwfl_relocate (Dwfl_Module *mod, Elf *debugfile, bool debug)
{
  assert (mod->e_type == ET_REL);

  GElf_Ehdr ehdr_mem;
  const GElf_Ehdr *ehdr = gelf_getehdr (debugfile, &ehdr_mem);
  if (ehdr == NULL)
    return DWFL_E_LIBELF;

  size_t d_shstrndx;
  if (elf_getshdrstrndx (debugfile, &d_shstrndx) < 0)
    return DWFL_E_LIBELF;

  RELOC_SYMTAB_CACHE (reloc_symtab);

  /* Look at each section in the debuginfo file, and process the
     relocation sections for debugging sections.  */
  Dwfl_Error result = DWFL_E_NOERROR;
  Elf_Scn *scn = NULL;
  while (result == DWFL_E_NOERROR
	 && (scn = elf_nextscn (debugfile, scn)) != NULL)
    {
      GElf_Shdr shdr_mem;
      GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);

      if ((shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
	  && shdr->sh_size != 0)
	{
	  /* It's a relocation section.  */

	  Elf_Scn *tscn = elf_getscn (debugfile, shdr->sh_info);
	  if (unlikely (tscn == NULL))
	    result = DWFL_E_LIBELF;
	  else
	    result = relocate_section (mod, debugfile, ehdr, d_shstrndx,
				       &reloc_symtab, scn, shdr, tscn,
				       debug, !debug);
	}
    }

  return result;
}
Ejemplo n.º 14
0
static int symb_synthesize_plt_symbols(struct symb_arr *arr, Elf *elf) {
   uint32_t nr_rel_entries, idx;
   GElf_Sym sym;
   uint64_t plt_offset;
   GElf_Shdr shdr_plt;
   GElf_Shdr shdr_rel_plt, shdr_dynsym;
   Elf_Data *reldata, *syms, *symstrs;
   Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
   size_t dynsym_idx;
   GElf_Ehdr ehdr;
   char sympltname[1024];
   int nr = 0, symidx, err = 0;

   if (gelf_getehdr(elf, &ehdr) == NULL)
      goto out_elf_end;

   scn_dynsym
            = elf_section_by_name(elf, &ehdr, &shdr_dynsym, ".dynsym", &dynsym_idx);
   if (scn_dynsym == NULL)
      goto out_elf_end;

   scn_plt_rel
            = elf_section_by_name(elf, &ehdr, &shdr_rel_plt, ".rela.plt", NULL);
   if (scn_plt_rel == NULL) {
      scn_plt_rel
               = elf_section_by_name(elf, &ehdr, &shdr_rel_plt, ".rel.plt", NULL);
      if (scn_plt_rel == NULL)
         goto out_elf_end;
   }

   err = -1;

   if (shdr_rel_plt.sh_link != dynsym_idx)
      goto out_elf_end;

   if (elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL) == NULL)
      goto out_elf_end;

   /*
    * Fetch the relocation section to find the idxes to the GOT
    * and the symbols in the .dynsym they refer to.
    */
   reldata = elf_getdata(scn_plt_rel, NULL);
   if (reldata == NULL)
      goto out_elf_end;

   syms = elf_getdata(scn_dynsym, NULL);
   if (syms == NULL)
      goto out_elf_end;

   scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
   if (scn_symstrs == NULL)
      goto out_elf_end;

   symstrs = elf_getdata(scn_symstrs, NULL);
   if (symstrs == NULL)
      goto out_elf_end;

   nr_rel_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
   plt_offset = shdr_plt.sh_offset;

   if (shdr_rel_plt.sh_type == SHT_RELA) {
      GElf_Rela pos_mem, *pos;

      elf_section__for_each_rela(reldata, pos, pos_mem, idx,
               nr_rel_entries) {
         symidx = GELF_R_SYM(pos->r_info);
         plt_offset += shdr_plt.sh_entsize;
         gelf_getsym(syms, symidx, &sym);
         snprintf(sympltname, sizeof(sympltname), "%s@plt", elf_sym__name(&sym, symstrs));
         struct symb *s = symb_new();
         s->hex = plt_offset;
         s->name = strdup(sympltname);
         symb_insert(s, arr);
         ++nr;
      }
Ejemplo n.º 15
0
static GHashTable* parse_plt(Elf *e, const char *filename)
{
    GElf_Shdr shdr;

    Elf_Data *plt_data;
    uintptr_t plt_base;
    size_t plt_section_index = xelf_section_by_name(e, ".plt", filename, &plt_data, &shdr);
    if (plt_section_index == 0)
    {
        VERB1 log("No .plt section found for %s", filename);
        return NULL;
    }
    plt_base = shdr.sh_addr;

    /* Find the relocation section for .plt (typically .rela.plt), together
     * with its symbol and string table
     */
    Elf_Data *rela_plt_data = NULL;
    Elf_Data *plt_symbols = NULL;
    size_t stringtable = 0;
    Elf_Scn *scn = NULL;
    while ((scn = elf_nextscn(e, scn)) != NULL)
    {
        if (gelf_getshdr(scn, &shdr) != &shdr)
        {
            VERB1 log_elf_error("gelf_getshdr", filename);
            continue;
        }

        if (shdr.sh_type == SHT_RELA && shdr.sh_info == plt_section_index)
        {
            rela_plt_data = elf_getdata(scn, NULL);
            if (rela_plt_data == NULL)
            {
                VERB1 log_elf_error("elf_getdata", filename);
                break;
            }

            /* Get symbol section for .rela.plt */
            Elf_Scn *symscn = elf_getscn(e, shdr.sh_link);
            if (symscn == NULL)
            {
                VERB1 log_elf_error("elf_getscn", filename);
                break;
            }

            plt_symbols = elf_getdata(symscn, NULL);
            if (plt_symbols == NULL)
            {
                VERB1 log_elf_error("elf_getdata", filename);
                break;
            }

            /* Get string table for the symbol table. */
            if (gelf_getshdr(symscn, &shdr) != &shdr)
            {
                VERB1 log_elf_error("gelf_getshdr", filename);
                break;
            }

            stringtable = shdr.sh_link;
            break;
        }
    }

    if (stringtable == 0)
    {
        VERB1 log("Unable to read symbol table for .plt for file %s", filename);
        return NULL;
    }

    /* Init hash table
     * keys are pointers to integers which we allocate with malloc
     * values are owned by libelf, so we don't need to free them */
    GHashTable *hash = g_hash_table_new_full(g_int64_hash, g_int64_equal, free, NULL);

    /* PLT looks like this (see also AMD64 ABI, page 78):
     *
     * Disassembly of section .plt:
     *
     * 0000003463e01010 <attr_removef@plt-0x10>:
     *   3463e01010:   ff 35 2a 2c 20 00       pushq  0x202c2a(%rip)         <-- here is plt_base
     *   3463e01016:   ff 25 2c 2c 20 00       jmpq   *0x202c2c(%rip)            each "slot" is 16B wide
     *   3463e0101c:   0f 1f 40 00             nopl   0x0(%rax)                  0-th slot is skipped
     *
     * 0000003463e01020 <attr_removef@plt>:
     *   3463e01020:   ff 25 2a 2c 20 00       jmpq   *0x202c2a(%rip)
     *   3463e01026:   68 00 00 00 00          pushq  $0x0                   <-- this is the number we want
     *   3463e0102b:   e9 e0 ff ff ff          jmpq   3463e01010 <_init+0x18>
     *
     * 0000003463e01030 <fgetxattr@plt>:
     *   3463e01030:   ff 25 22 2c 20 00       jmpq   *0x202c22(%rip)
     *   3463e01036:   68 01 00 00 00          pushq  $0x1
     *   3463e0103b:   e9 d0 ff ff ff          jmpq   3463e01010 <_init+0x18>
     */

    unsigned plt_offset;
    uint32_t *plt_index;
    GElf_Rela rela;
    GElf_Sym symb;
    for (plt_offset = 16; plt_offset < plt_data->d_size; plt_offset += 16)
    {
        plt_index = (uint32_t*)(plt_data->d_buf + plt_offset + 7);

        if(gelf_getrela(rela_plt_data, *plt_index, &rela) != &rela)
        {
            VERB1 log_elf_error("gelf_getrela", filename);
            continue;
        }

        if(gelf_getsym(plt_symbols, GELF_R_SYM(rela.r_info), &symb) != &symb)
        {
            VERB1 log_elf_error("gelf_getsym", filename);
            continue;
        }

        char *symbol = elf_strptr(e, stringtable, symb.st_name);
        uintptr_t *addr = addr_alloc((uintptr_t)(plt_base + plt_offset));

        VERB3 log("[%02x] %jx: %s", *plt_index, (uintptr_t)(*addr), symbol);
        g_hash_table_insert(hash, addr, symbol);
    }

    return hash;
}
Ejemplo n.º 16
0
static int
mips_prelink_reloc (struct prelink_info *info, GElf_Addr r_offset,
		    GElf_Xword r_info, GElf_Rela *rela)
{
  DSO *dso;
  GElf_Addr value;
  GElf_Word r_sym;
  int r_type;

  dso = info->dso;
  r_sym = GELF_R_SYM (r_info);
  r_type = GELF_R_TYPE (r_info);
  switch (r_type)
    {
    case R_MIPS_NONE:
      break;

    case R_MIPS_REL32:
      /* An in-place R_MIPS_REL32 relocation against symbol 0 needs no
	 adjustment.  */
      if (rela != NULL || GELF_R_SYM (r_info) != 0)
	{
	  value = info->resolve (info, r_sym, r_type);
	  mips_prelink_32bit_reloc (dso, rela, value);
	}
      break;

    case R_MIPS_GLOB_DAT:
      write_ne32 (dso, r_offset, info->resolve (info, r_sym, r_type));
      break;

    case R_MIPS_TLS_DTPMOD32:
      if (dso->ehdr.e_type == ET_EXEC)
	{
	  error (0, 0, "%s: R_MIPS_TLS_DTPMOD32 reloc in executable?",
		 dso->filename);
	  return 1;
	}
      /* These relocations will be resolved using a conflict.  We need
	 not change the field value here.  */
      break;

    case R_MIPS_TLS_DTPREL32:
      value = info->resolve (info, r_sym, r_type);
      mips_prelink_32bit_reloc (dso, rela, value - TLS_DTV_OFFSET);
      break;

    case R_MIPS_TLS_TPREL32:
      /* Relocations in a shared library will be resolved using a conflict.
	 We need not change the relocation field here.  */
      if (dso->ehdr.e_type == ET_EXEC)
	{
	  value = info->resolve (info, r_sym, r_type);
	  value += info->resolvetls->offset - TLS_TP_OFFSET;
	  mips_prelink_32bit_reloc (dso, rela, value);
	}
      break;

    default:
      error (0, 0, "%s: Unknown MIPS relocation type %d",
	     dso->filename, (int) GELF_R_TYPE (r_info));
      return 1;
    }
  return 0;
}
Ejemplo n.º 17
0
/*
 * We need to check if we have a .dynsym, so that we can handle the
 * .plt, synthesizing its symbols, that aren't on the symtabs (be it
 * .dynsym or .symtab).
 * And always look at the original dso, not at debuginfo packages, that
 * have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
 */
static int dso__synthesize_plt_symbols(struct  dso *self, int verbose)
{
	uint32_t nr_rel_entries, idx;
	GElf_Sym sym;
	u64 plt_offset;
	GElf_Shdr shdr_plt;
	struct symbol *f;
	GElf_Shdr shdr_rel_plt, shdr_dynsym;
	Elf_Data *reldata, *syms, *symstrs;
	Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
	size_t dynsym_idx;
	GElf_Ehdr ehdr;
	char sympltname[1024];
	Elf *elf;
	int nr = 0, symidx, fd, err = 0;

	fd = open(self->name, O_RDONLY);
	if (fd < 0)
		goto out;

	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
	if (elf == NULL)
		goto out_close;

	if (gelf_getehdr(elf, &ehdr) == NULL)
		goto out_elf_end;

	scn_dynsym = elf_section_by_name(elf, &ehdr, &shdr_dynsym,
					 ".dynsym", &dynsym_idx);
	if (scn_dynsym == NULL)
		goto out_elf_end;

	scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
					  ".rela.plt", NULL);
	if (scn_plt_rel == NULL) {
		scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
						  ".rel.plt", NULL);
		if (scn_plt_rel == NULL)
			goto out_elf_end;
	}

	err = -1;

	if (shdr_rel_plt.sh_link != dynsym_idx)
		goto out_elf_end;

	if (elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL) == NULL)
		goto out_elf_end;

	/*
	 * Fetch the relocation section to find the indexes to the GOT
	 * and the symbols in the .dynsym they refer to.
	 */
	reldata = elf_getdata(scn_plt_rel, NULL);
	if (reldata == NULL)
		goto out_elf_end;

	syms = elf_getdata(scn_dynsym, NULL);
	if (syms == NULL)
		goto out_elf_end;

	scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
	if (scn_symstrs == NULL)
		goto out_elf_end;

	symstrs = elf_getdata(scn_symstrs, NULL);
	if (symstrs == NULL)
		goto out_elf_end;

	nr_rel_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
	plt_offset = shdr_plt.sh_offset;

	if (shdr_rel_plt.sh_type == SHT_RELA) {
		GElf_Rela pos_mem, *pos;

		elf_section__for_each_rela(reldata, pos, pos_mem, idx,
					   nr_rel_entries) {
			symidx = GELF_R_SYM(pos->r_info);
			plt_offset += shdr_plt.sh_entsize;
			gelf_getsym(syms, symidx, &sym);
			snprintf(sympltname, sizeof(sympltname),
				 "%s@plt", elf_sym__name(&sym, symstrs));

			f = symbol__new(plt_offset, shdr_plt.sh_entsize,
					sympltname, self->sym_priv_size, 0, verbose);
			if (!f)
				goto out_elf_end;

			dso__insert_symbol(self, f);
			++nr;
		}