/*-
* Copyright (c) 2006-2011 Joseph Koshy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if HAVE_NBTOOL_CONFIG_H
# include "nbtool_config.h"
#endif
/*
* Layout strategy:
*
* - Case 1: ELF_F_LAYOUT is asserted
* In this case the application has full control over where the
* section header table, program header table, and section data
* will reside. The library only perform error checks.
*
* - Case 2: ELF_F_LAYOUT is not asserted
*
* The library will do the object layout using the following
* ordering:
* - The executable header is placed first, are required by the
* ELF specification.
* - The program header table is placed immediately following the
* executable header.
* - Section data, if any, is placed after the program header
* table, aligned appropriately.
* - The section header table, if needed, is placed last.
*
* There are two sub-cases to be taken care of:
*
* - Case 2a: e->e_cmd == ELF_C_READ or ELF_C_RDWR
*
* In this sub-case, the underlying ELF object may already have
* content in it, which the application may have modified. The
* library will retrieve content from the existing object as
* needed.
*
* - Case 2b: e->e_cmd == ELF_C_WRITE
*
* The ELF object is being created afresh in this sub-case;
* there is no pre-existing content in the underlying ELF
* object.
*/
/*
* The types of extents in an ELF object.
*/
enum elf_extent {
ELF_EXTENT_EHDR,
ELF_EXTENT_PHDR,
ELF_EXTENT_SECTION,
ELF_EXTENT_SHDR
};
/*
* A extent descriptor, used when laying out an ELF object.
*/
struct _Elf_Extent {
SLIST_ENTRY(_Elf_Extent) ex_next;
uint64_t ex_start; /* Start of the region. */
uint64_t ex_size; /* The size of the region. */
enum elf_extent ex_type; /* Type of region. */
void *ex_desc; /* Associated descriptor. */
};
SLIST_HEAD(_Elf_Extent_List, _Elf_Extent);
/*
* Compute the extents of a section, by looking at the data
* descriptors associated with it. The function returns 1
* if successful, or zero if an error was detected.
*/
static int
_libelf_compute_section_extents(Elf *e, Elf_Scn *s, off_t rc)
{
Elf_Data *d;
size_t fsz, msz;
int ec, elftype;
uint32_t sh_type;
uint64_t d_align;
Elf32_Shdr *shdr32;
Elf64_Shdr *shdr64;
struct _Libelf_Data *ld;
uint64_t scn_size, scn_alignment;
uint64_t sh_align, sh_entsize, sh_offset, sh_size;
if (sh_align == 0)
sh_align = _libelf_falign(elftype, ec);
/*
* Compute the section's size and alignment using the data
* descriptors associated with the section.
*/
if (STAILQ_EMPTY(&s->s_data)) {
/*
* The section's content (if any) has not been read in
* yet. If section is not dirty marked dirty, we can
* reuse the values in the 'sh_size' and 'sh_offset'
* fields of the section header.
*/
if ((s->s_flags & ELF_F_DIRTY) == 0) {
/*
* If the library is doing the layout, then we
* compute the new start offset for the
* section based on the current offset and the
* section's alignment needs.
*
* If the application is doing the layout, we
* can use the value in the 'sh_offset' field
* in the section header directly.
*/
if (e->e_flags & ELF_F_LAYOUT)
goto updatedescriptor;
else
goto computeoffset;
}
/*
* Otherwise, we need to bring in the section's data
* from the underlying ELF object.
*/
if (e->e_cmd != ELF_C_WRITE && elf_getdata(s, NULL) == NULL)
return (0);
}
/*
* Loop through the section's data descriptors.
*/
scn_size = 0L;
scn_alignment = 0;
STAILQ_FOREACH(ld, &s->s_data, d_next) {
d = &ld->d_data;
/*
* The data buffer's type is known.
*/
if (d->d_type >= ELF_T_NUM) {
LIBELF_SET_ERROR(DATA, 0);
return (0);
}
/*
* The data buffer's version is supported.
*/
if (d->d_version != e->e_version) {
LIBELF_SET_ERROR(VERSION, 0);
return (0);
}
/*
* The buffer's alignment is non-zero and a power of
* two.
*/
if ((d_align = d->d_align) == 0 ||
(d_align & (d_align - 1))) {
LIBELF_SET_ERROR(DATA, 0);
return (0);
}
/*
* The data buffer's ELF type, ELF class and ELF version
* should be supported.
*/
if ((msz = _libelf_msize(d->d_type, ec, e->e_version)) == 0)
return (0);
/*
* The buffer's size should be a multiple of the
* memory size of the underlying type.
*/
if (d->d_size % msz) {
LIBELF_SET_ERROR(DATA, 0);
return (0);
}
/*
* If the application is controlling layout, then the
* d_offset field should be compatible with the
* buffer's specified alignment.
*/
if ((e->e_flags & ELF_F_LAYOUT) &&
(d->d_off & (d_align - 1))) {
LIBELF_SET_ERROR(LAYOUT, 0);
return (0);
}
/*
* The section's alignment is the maximum alignment
* needed for its data buffers.
*/
if (d_align > scn_alignment)
scn_alignment = d_align;
}
/*
* If the application is requesting full control over the
* layout of the section, check the section's specified size,
* offsets and alignment for sanity.
*/
if (e->e_flags & ELF_F_LAYOUT) {
if (scn_alignment > sh_align ||
sh_offset % sh_align ||
sh_size < scn_size ||
sh_offset % _libelf_falign(elftype, ec)) {
LIBELF_SET_ERROR(LAYOUT, 0);
return (0);
}
goto updatedescriptor;
}
/*
* Otherwise, compute the values in the section header.
*
* The section alignment is the maximum alignment for any of
* its contained data descriptors.
*/
if (scn_alignment > sh_align)
sh_align = scn_alignment;
/*
* If the section entry size is zero, try and fill in an
* appropriate entry size. Per the elf(5) manual page
* sections without fixed-size entries should have their
* 'sh_entsize' field set to zero.
*/
if (sh_entsize == 0 &&
(sh_entsize = _libelf_fsize(elftype, ec, e->e_version,
(size_t) 1)) == 1)
sh_entsize = 0;
sh_size = scn_size;
computeoffset:
/*
* Compute the new offset for the section based on
* the section's alignment needs.
*/
sh_offset = roundup((uint64_t) rc, sh_align);
/*
* Check if an extent 's' defined by [start..start+size) is free.
* This routine assumes that the given extent list is sorted in order
* of ascending extent offsets.
*/
if (tmax <= start) {
/*
* 't' lies entirely before 's': ...| t |...| s |...
*/
pt = t;
continue;
} else if (smax <= tmin) {
/*
* 's' lies entirely before 't', and after 'pt':
* ...| pt |...| s |...| t |...
*/
assert(pt == NULL ||
pt->ex_start + pt->ex_size <= start);
break;
} else
/* 's' and 't' overlap. */
return (0);
}
if (prevt)
*prevt = pt;
return (1);
}
/*
* Insert an extent into the list of extents.
*/
static int
_libelf_insert_extent(struct _Elf_Extent_List *extents, int type,
uint64_t start, uint64_t size, void *desc)
{
struct _Elf_Extent *ex, *prevt;
assert(type >= ELF_EXTENT_EHDR && type <= ELF_EXTENT_SHDR);
prevt = NULL;
/*
* If the requested range overlaps with an existing extent,
* signal an error.
*/
if (!_libelf_extent_is_unused(extents, start, size, &prevt)) {
LIBELF_SET_ERROR(LAYOUT, 0);
return (0);
}
/* Allocate and fill in a new extent descriptor. */
if ((ex = malloc(sizeof(struct _Elf_Extent))) == NULL) {
LIBELF_SET_ERROR(RESOURCE, errno);
return (0);
}
ex->ex_start = start;
ex->ex_size = size;
ex->ex_desc = desc;
ex->ex_type = type;
/* Insert the region descriptor into the list. */
if (prevt)
SLIST_INSERT_AFTER(prevt, ex, ex_next);
else
SLIST_INSERT_HEAD(extents, ex, ex_next);
return (1);
}
/*
* Make a pass through sections, computing the extent of each
* section.
*/
STAILQ_FOREACH(s, &e->e_u.e_elf.e_scn, s_next) {
if (ec == ELFCLASS32)
sh_type = s->s_shdr.s_shdr32.sh_type;
else
sh_type = s->s_shdr.s_shdr64.sh_type;
if (sh_type == SHT_NOBITS || sh_type == SHT_NULL)
continue;
if (_libelf_compute_section_extents(e, s, rc) == 0)
return ((off_t) -1);
if (s->s_size == 0)
continue;
if (!_libelf_insert_extent(extents, ELF_EXTENT_SECTION,
s->s_offset, s->s_size, s))
return ((off_t) -1);
/*
* Recompute the layout of the ELF object and update the internal data
* structures associated with the ELF descriptor.
*
* Returns the size in bytes the ELF object would occupy in its file
* representation.
*
* After a successful call to this function, the following structures
* are updated:
*
* - The ELF header is updated.
* - All extents in the ELF object are sorted in order of ascending
* addresses. Sections have their section header table entries
* updated. An error is signalled if an overlap was detected among
* extents.
* - Data descriptors associated with sections are checked for valid
* types, offsets and alignment.
*
* After a resync_elf() successfully returns, the ELF descriptor is
* ready for being handed over to _libelf_write_elf().
*/
if (!_libelf_insert_extent(extents, ELF_EXTENT_EHDR, 0, (uint64_t) rc,
ehdr))
return ((off_t) -1);
/*
* Compute the layout the program header table, if one is
* present. The program header table needs to be aligned to a
* `natural' boundary.
*/
if (phnum) {
fsz = _libelf_fsize(ELF_T_PHDR, ec, eh_version, phnum);
align = _libelf_falign(ELF_T_PHDR, ec);
if (e->e_flags & ELF_F_LAYOUT) {
/*
* Check offsets for sanity.
*/
if (rc > phoff) {
LIBELF_SET_ERROR(LAYOUT, 0);
return ((off_t) -1);
}
/*
* Compute the space taken up by the section header table, if
* one is needed.
*
* If ELF_F_LAYOUT has been asserted, the application may have
* placed the section header table in between existing
* sections, so the net size of the file need not increase due
* to the presence of the section header table.
*
* If the library is responsible for laying out the object,
* the section header table is placed after section data.
*/
if (shnum) {
fsz = _libelf_fsize(ELF_T_SHDR, ec, eh_version, shnum);
align = _libelf_falign(ELF_T_SHDR, ec);
/*
* Set the fields of the Executable Header that could potentially use
* extended numbering.
*/
_libelf_setphnum(e, ehdr, ec, phnum);
_libelf_setshnum(e, ehdr, ec, shnum);
/*
* Update the `e_phoff' and `e_shoff' fields if the library is
* doing the layout.
*/
if ((e->e_flags & ELF_F_LAYOUT) == 0) {
if (ec == ELFCLASS32) {
eh32->e_phoff = (uint32_t) phoff;
eh32->e_shoff = (uint32_t) shoff;
} else {
eh64->e_phoff = (uint64_t) phoff;
eh64->e_shoff = (uint64_t) shoff;
}
}
/*
* If the section has a `rawdata' descriptor, and the section
* contents have not been modified, use its contents directly.
* The `s_rawoff' member contains the offset into the original
* file, while `s_offset' contains its new location in the
* destination.
*/
if (STAILQ_EMPTY(&s->s_data)) {
if ((d = elf_rawdata(s, NULL)) == NULL)
return ((off_t) -1);
/*
* Iterate over the set of data descriptors for this section.
* The prior call to _libelf_resync_elf() would have setup the
* descriptors for this step.
*/
/*
* Write out the file image.
*
* The original file could have been mapped in with an ELF_C_RDWR
* command and the application could have added new content or
* re-arranged its sections before calling elf_update(). Consequently
* its not safe to work `in place' on the original file. So we
* malloc() the required space for the updated ELF object and build
* the object there and write it out to the underlying file at the
* end. Note that the application may have opened the underlying file
* in ELF_C_RDWR and only retrieved/modified a few sections. We take
* care to avoid translating file sections unnecessarily.
*
* Gaps in the coverage of the file by the file's sections will be
* filled with the fill character set by elf_fill(3).
*/
/*
* For regular files, throw away existing file content and
* unmap any existing mappings.
*/
if ((e->e_flags & LIBELF_F_SPECIAL_FILE) == 0) {
if (ftruncate(e->e_fd, (off_t) 0) < 0 ||
lseek(e->e_fd, (off_t) 0, SEEK_SET)) {
LIBELF_SET_ERROR(IO, errno);
goto error;
}
#if ELFTC_HAVE_MMAP
if (e->e_flags & LIBELF_F_RAWFILE_MMAP) {
assert(e->e_rawfile != NULL);
assert(e->e_cmd == ELF_C_RDWR);
if (munmap(e->e_rawfile, (size_t) e->e_rawsize) < 0) {
LIBELF_SET_ERROR(IO, errno);
goto error;
}
}
#endif
}
/*
* Write out the new contents.
*/
if (write(e->e_fd, newfile, (size_t) newsize) != newsize) {
LIBELF_SET_ERROR(IO, errno);
goto error;
}
/*
* For files opened in ELF_C_RDWR mode, set up the new 'raw'
* contents.
*/
if (e->e_cmd == ELF_C_RDWR) {
assert(e->e_rawfile != NULL);
assert((e->e_flags & LIBELF_F_RAWFILE_MALLOC) ||
(e->e_flags & LIBELF_F_RAWFILE_MMAP));
if (e->e_flags & LIBELF_F_RAWFILE_MALLOC) {
assert((e->e_flags & LIBELF_F_RAWFILE_MMAP) == 0);
free(e->e_rawfile);
e->e_rawfile = newfile;
newfile = NULL;
}
#if ELFTC_HAVE_MMAP
else if (e->e_flags & LIBELF_F_RAWFILE_MMAP) {
assert((e->e_flags & LIBELF_F_RAWFILE_MALLOC) == 0);
if ((e->e_rawfile = mmap(NULL, (size_t) newsize,
PROT_READ, MAP_PRIVATE, e->e_fd, (off_t) 0)) ==
MAP_FAILED) {
LIBELF_SET_ERROR(IO, errno);
goto error;
}
}
#endif /* ELFTC_HAVE_MMAP */
/* Record the new size of the file. */
e->e_rawsize = newsize;
} else {
/* File opened in ELF_C_WRITE mode. */
assert(e->e_rawfile == NULL);
}
/*
* Reset flags, remove existing section descriptors and
* {E,P}HDR pointers so that a subsequent elf_get{e,p}hdr()
* and elf_getscn() will function correctly.
*/