elf_update.c revision 276371
1/*-
2 * Copyright (c) 2006-2011 Joseph Koshy
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include <sys/param.h>
28#include <sys/stat.h>
29
30#include <assert.h>
31#include <errno.h>
32#include <gelf.h>
33#include <libelf.h>
34#include <stdlib.h>
35#include <string.h>
36#include <unistd.h>
37
38#include "_libelf.h"
39
40#if	ELFTC_HAVE_MMAP
41#include <sys/mman.h>
42#endif
43
44ELFTC_VCSID("$Id: elf_update.c 3013 2014-03-23 06:16:59Z jkoshy $");
45
46/*
47 * Layout strategy:
48 *
49 * - Case 1: ELF_F_LAYOUT is asserted
50 *     In this case the application has full control over where the
51 *     section header table, program header table, and section data
52 *     will reside.   The library only perform error checks.
53 *
54 * - Case 2: ELF_F_LAYOUT is not asserted
55 *
56 *     The library will do the object layout using the following
57 *     ordering:
58 *     - The executable header is placed first, are required by the
59 *     	 ELF specification.
60 *     - The program header table is placed immediately following the
61 *       executable header.
62 *     - Section data, if any, is placed after the program header
63 *       table, aligned appropriately.
64 *     - The section header table, if needed, is placed last.
65 *
66 *     There are two sub-cases to be taken care of:
67 *
68 *     - Case 2a: e->e_cmd == ELF_C_READ or ELF_C_RDWR
69 *
70 *       In this sub-case, the underlying ELF object may already have
71 *       content in it, which the application may have modified.  The
72 *       library will retrieve content from the existing object as
73 *       needed.
74 *
75 *     - Case 2b: e->e_cmd == ELF_C_WRITE
76 *
77 *       The ELF object is being created afresh in this sub-case;
78 *       there is no pre-existing content in the underlying ELF
79 *       object.
80 */
81
82/*
83 * The types of extents in an ELF object.
84 */
85enum elf_extent {
86	ELF_EXTENT_EHDR,
87	ELF_EXTENT_PHDR,
88	ELF_EXTENT_SECTION,
89	ELF_EXTENT_SHDR
90};
91
92/*
93 * A extent descriptor, used when laying out an ELF object.
94 */
95struct _Elf_Extent {
96	SLIST_ENTRY(_Elf_Extent) ex_next;
97	uint64_t	ex_start; /* Start of the region. */
98	uint64_t	ex_size;  /* The size of the region. */
99	enum elf_extent	ex_type;  /* Type of region. */
100	void		*ex_desc; /* Associated descriptor. */
101};
102
103SLIST_HEAD(_Elf_Extent_List, _Elf_Extent);
104
105/*
106 * Compute the extents of a section, by looking at the data
107 * descriptors associated with it.  The function returns 1
108 * if successful, or zero if an error was detected.
109 */
110static int
111_libelf_compute_section_extents(Elf *e, Elf_Scn *s, off_t rc)
112{
113	Elf_Data *d;
114	size_t fsz, msz;
115	int ec, elftype;
116	uint32_t sh_type;
117	uint64_t d_align;
118	Elf32_Shdr *shdr32;
119	Elf64_Shdr *shdr64;
120	struct _Libelf_Data *ld;
121	uint64_t scn_size, scn_alignment;
122	uint64_t sh_align, sh_entsize, sh_offset, sh_size;
123
124	ec = e->e_class;
125
126	shdr32 = &s->s_shdr.s_shdr32;
127	shdr64 = &s->s_shdr.s_shdr64;
128	if (ec == ELFCLASS32) {
129		sh_type    = shdr32->sh_type;
130		sh_align   = (uint64_t) shdr32->sh_addralign;
131		sh_entsize = (uint64_t) shdr32->sh_entsize;
132		sh_offset  = (uint64_t) shdr32->sh_offset;
133		sh_size    = (uint64_t) shdr32->sh_size;
134	} else {
135		sh_type    = shdr64->sh_type;
136		sh_align   = shdr64->sh_addralign;
137		sh_entsize = shdr64->sh_entsize;
138		sh_offset  = shdr64->sh_offset;
139		sh_size    = shdr64->sh_size;
140	}
141
142	assert(sh_type != SHT_NULL && sh_type != SHT_NOBITS);
143
144	elftype = _libelf_xlate_shtype(sh_type);
145	if (elftype > ELF_T_LAST) {
146		LIBELF_SET_ERROR(SECTION, 0);
147		return (0);
148	}
149
150	if (sh_align == 0)
151		sh_align = _libelf_falign(elftype, ec);
152
153	/*
154	 * Compute the section's size and alignment using the data
155	 * descriptors associated with the section.
156	 */
157	if (STAILQ_EMPTY(&s->s_data)) {
158		/*
159		 * The section's content (if any) has not been read in
160		 * yet.  If section is not dirty marked dirty, we can
161		 * reuse the values in the 'sh_size' and 'sh_offset'
162		 * fields of the section header.
163		 */
164		if ((s->s_flags & ELF_F_DIRTY) == 0) {
165			/*
166			 * If the library is doing the layout, then we
167			 * compute the new start offset for the
168			 * section based on the current offset and the
169			 * section's alignment needs.
170			 *
171			 * If the application is doing the layout, we
172			 * can use the value in the 'sh_offset' field
173			 * in the section header directly.
174			 */
175			if (e->e_flags & ELF_F_LAYOUT)
176				goto updatedescriptor;
177			else
178				goto computeoffset;
179		}
180
181		/*
182		 * Otherwise, we need to bring in the section's data
183		 * from the underlying ELF object.
184		 */
185		if (e->e_cmd != ELF_C_WRITE && elf_getdata(s, NULL) == NULL)
186			return (0);
187	}
188
189	/*
190	 * Loop through the section's data descriptors.
191	 */
192	scn_size = 0L;
193	scn_alignment = 0;
194	STAILQ_FOREACH(ld, &s->s_data, d_next)  {
195
196		d = &ld->d_data;
197
198		/*
199		 * The data buffer's type is known.
200		 */
201		if (d->d_type >= ELF_T_NUM) {
202			LIBELF_SET_ERROR(DATA, 0);
203			return (0);
204		}
205
206		/*
207		 * The data buffer's version is supported.
208		 */
209		if (d->d_version != e->e_version) {
210			LIBELF_SET_ERROR(VERSION, 0);
211			return (0);
212		}
213
214		/*
215		 * The buffer's alignment is non-zero and a power of
216		 * two.
217		 */
218		if ((d_align = d->d_align) == 0 ||
219		    (d_align & (d_align - 1))) {
220			LIBELF_SET_ERROR(DATA, 0);
221			return (0);
222		}
223
224		/*
225		 * The buffer's size should be a multiple of the
226		 * memory size of the underlying type.
227		 */
228		msz = _libelf_msize(d->d_type, ec, e->e_version);
229		if (d->d_size % msz) {
230			LIBELF_SET_ERROR(DATA, 0);
231			return (0);
232		}
233
234		/*
235		 * If the application is controlling layout, then the
236		 * d_offset field should be compatible with the
237		 * buffer's specified alignment.
238		 */
239		if ((e->e_flags & ELF_F_LAYOUT) &&
240		    (d->d_off & (d_align - 1))) {
241			LIBELF_SET_ERROR(LAYOUT, 0);
242			return (0);
243		}
244
245		/*
246		 * Compute the section's size.
247		 */
248		if (e->e_flags & ELF_F_LAYOUT) {
249			if ((uint64_t) d->d_off + d->d_size > scn_size)
250				scn_size = d->d_off + d->d_size;
251		} else {
252			scn_size = roundup2(scn_size, d->d_align);
253			d->d_off = scn_size;
254			fsz = _libelf_fsize(d->d_type, ec, d->d_version,
255			    (size_t) d->d_size / msz);
256			scn_size += fsz;
257		}
258
259		/*
260		 * The section's alignment is the maximum alignment
261		 * needed for its data buffers.
262		 */
263		if (d_align > scn_alignment)
264			scn_alignment = d_align;
265	}
266
267
268	/*
269	 * If the application is requesting full control over the
270	 * layout of the section, check the section's specified size,
271	 * offsets and alignment for sanity.
272	 */
273	if (e->e_flags & ELF_F_LAYOUT) {
274		if (scn_alignment > sh_align || sh_offset % sh_align ||
275		    sh_size < scn_size) {
276			LIBELF_SET_ERROR(LAYOUT, 0);
277			return (0);
278		}
279		goto updatedescriptor;
280	}
281
282	/*
283	 * Otherwise, compute the values in the section header.
284	 *
285	 * The section alignment is the maximum alignment for any of
286	 * its contained data descriptors.
287	 */
288	if (scn_alignment > sh_align)
289		sh_align = scn_alignment;
290
291	/*
292	 * If the section entry size is zero, try and fill in an
293	 * appropriate entry size.  Per the elf(5) manual page
294	 * sections without fixed-size entries should have their
295	 * 'sh_entsize' field set to zero.
296	 */
297	if (sh_entsize == 0 &&
298	    (sh_entsize = _libelf_fsize(elftype, ec, e->e_version,
299		(size_t) 1)) == 1)
300		sh_entsize = 0;
301
302	sh_size = scn_size;
303
304computeoffset:
305	/*
306	 * Compute the new offset for the section based on
307	 * the section's alignment needs.
308	 */
309	sh_offset = roundup((uint64_t) rc, sh_align);
310
311	/*
312	 * Update the section header.
313	 */
314	if (ec == ELFCLASS32) {
315		shdr32->sh_addralign = (uint32_t) sh_align;
316		shdr32->sh_entsize   = (uint32_t) sh_entsize;
317		shdr32->sh_offset    = (uint32_t) sh_offset;
318		shdr32->sh_size      = (uint32_t) sh_size;
319	} else {
320		shdr64->sh_addralign = sh_align;
321		shdr64->sh_entsize   = sh_entsize;
322		shdr64->sh_offset    = sh_offset;
323		shdr64->sh_size      = sh_size;
324	}
325
326updatedescriptor:
327	/*
328	 * Update the section descriptor.
329	 */
330	s->s_size = sh_size;
331	s->s_offset = sh_offset;
332
333	return (1);
334}
335
336/*
337 * Free a list of extent descriptors.
338 */
339
340static void
341_libelf_release_extents(struct _Elf_Extent_List *extents)
342{
343	struct _Elf_Extent *ex;
344
345	while ((ex = SLIST_FIRST(extents)) != NULL) {
346		SLIST_REMOVE_HEAD(extents, ex_next);
347		free(ex);
348	}
349}
350
351/*
352 * Check if an extent 's' defined by [start..start+size) is free.
353 * This routine assumes that the given extent list is sorted in order
354 * of ascending extent offsets.
355 */
356
357static int
358_libelf_extent_is_unused(struct _Elf_Extent_List *extents,
359    const uint64_t start, const uint64_t size, struct _Elf_Extent **prevt)
360{
361	uint64_t tmax, tmin;
362	struct _Elf_Extent *t, *pt;
363	const uint64_t smax = start + size;
364
365	/* First, look for overlaps with existing extents. */
366	pt = NULL;
367	SLIST_FOREACH(t, extents, ex_next) {
368		tmin = t->ex_start;
369		tmax = tmin + t->ex_size;
370
371		if (tmax <= start) {
372			/*
373			 * 't' lies entirely before 's': ...| t |...| s |...
374			 */
375			pt = t;
376			continue;
377		} else if (smax <= tmin) {
378			/*
379			 * 's' lies entirely before 't', and after 'pt':
380			 *      ...| pt |...| s |...| t |...
381			 */
382			assert(pt == NULL ||
383			    pt->ex_start + pt->ex_size <= start);
384			break;
385		} else
386			/* 's' and 't' overlap. */
387			return (0);
388	}
389
390	if (prevt)
391		*prevt = pt;
392	return (1);
393}
394
395/*
396 * Insert an extent into the list of extents.
397 */
398
399static int
400_libelf_insert_extent(struct _Elf_Extent_List *extents, int type,
401    uint64_t start, uint64_t size, void *desc)
402{
403	struct _Elf_Extent *ex, *prevt;
404
405	assert(type >= ELF_EXTENT_EHDR && type <= ELF_EXTENT_SHDR);
406
407	prevt = NULL;
408
409	/*
410	 * If the requested range overlaps with an existing extent,
411	 * signal an error.
412	 */
413	if (!_libelf_extent_is_unused(extents, start, size, &prevt)) {
414		LIBELF_SET_ERROR(LAYOUT, 0);
415		return (0);
416	}
417
418	/* Allocate and fill in a new extent descriptor. */
419	if ((ex = malloc(sizeof(struct _Elf_Extent))) == NULL) {
420		LIBELF_SET_ERROR(RESOURCE, errno);
421		return (0);
422	}
423	ex->ex_start = start;
424	ex->ex_size = size;
425	ex->ex_desc = desc;
426	ex->ex_type = type;
427
428	/* Insert the region descriptor into the list. */
429	if (prevt)
430		SLIST_INSERT_AFTER(prevt, ex, ex_next);
431	else
432		SLIST_INSERT_HEAD(extents, ex, ex_next);
433	return (1);
434}
435
436/*
437 * Recompute section layout.
438 */
439
440static off_t
441_libelf_resync_sections(Elf *e, off_t rc, struct _Elf_Extent_List *extents)
442{
443	int ec;
444	Elf_Scn *s;
445	size_t sh_type;
446
447	ec = e->e_class;
448
449	/*
450	 * Make a pass through sections, computing the extent of each
451	 * section.
452	 */
453	STAILQ_FOREACH(s, &e->e_u.e_elf.e_scn, s_next) {
454		if (ec == ELFCLASS32)
455			sh_type = s->s_shdr.s_shdr32.sh_type;
456		else
457			sh_type = s->s_shdr.s_shdr64.sh_type;
458
459		if (sh_type == SHT_NOBITS || sh_type == SHT_NULL)
460			continue;
461
462		if (_libelf_compute_section_extents(e, s, rc) == 0)
463			return ((off_t) -1);
464
465		if (s->s_size == 0)
466			continue;
467
468		if (!_libelf_insert_extent(extents, ELF_EXTENT_SECTION,
469		    s->s_offset, s->s_size, s))
470			return ((off_t) -1);
471
472		if ((size_t) rc < s->s_offset + s->s_size)
473			rc = (off_t) (s->s_offset + s->s_size);
474	}
475
476	return (rc);
477}
478
479/*
480 * Recompute the layout of the ELF object and update the internal data
481 * structures associated with the ELF descriptor.
482 *
483 * Returns the size in bytes the ELF object would occupy in its file
484 * representation.
485 *
486 * After a successful call to this function, the following structures
487 * are updated:
488 *
489 * - The ELF header is updated.
490 * - All extents in the ELF object are sorted in order of ascending
491 *   addresses.  Sections have their section header table entries
492 *   updated.  An error is signalled if an overlap was detected among
493 *   extents.
494 * - Data descriptors associated with sections are checked for valid
495 *   types, offsets and alignment.
496 *
497 * After a resync_elf() successfully returns, the ELF descriptor is
498 * ready for being handed over to _libelf_write_elf().
499 */
500
501static off_t
502_libelf_resync_elf(Elf *e, struct _Elf_Extent_List *extents)
503{
504	int ec, eh_class;
505	unsigned int eh_byteorder, eh_version;
506	size_t align, fsz;
507	size_t phnum, shnum;
508	off_t rc, phoff, shoff;
509	void *ehdr, *phdr;
510	Elf32_Ehdr *eh32;
511	Elf64_Ehdr *eh64;
512
513	rc = 0;
514
515	ec = e->e_class;
516
517	assert(ec == ELFCLASS32 || ec == ELFCLASS64);
518
519	/*
520	 * Prepare the EHDR.
521	 */
522	if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL)
523		return ((off_t) -1);
524
525	eh32 = ehdr;
526	eh64 = ehdr;
527
528	if (ec == ELFCLASS32) {
529		eh_byteorder = eh32->e_ident[EI_DATA];
530		eh_class     = eh32->e_ident[EI_CLASS];
531		phoff        = (off_t) eh32->e_phoff;
532		shoff        = (off_t) eh32->e_shoff;
533		eh_version   = eh32->e_version;
534	} else {
535		eh_byteorder = eh64->e_ident[EI_DATA];
536		eh_class     = eh64->e_ident[EI_CLASS];
537		phoff        = (off_t) eh64->e_phoff;
538		shoff        = (off_t) eh64->e_shoff;
539		eh_version   = eh64->e_version;
540	}
541
542	if (phoff < 0 || shoff < 0) {
543		LIBELF_SET_ERROR(HEADER, 0);
544		return ((off_t) -1);
545	}
546
547	if (eh_version == EV_NONE)
548		eh_version = EV_CURRENT;
549
550	if (eh_version != e->e_version) {	/* always EV_CURRENT */
551		LIBELF_SET_ERROR(VERSION, 0);
552		return ((off_t) -1);
553	}
554
555	if (eh_class != e->e_class) {
556		LIBELF_SET_ERROR(CLASS, 0);
557		return ((off_t) -1);
558	}
559
560	if (e->e_cmd != ELF_C_WRITE && eh_byteorder != e->e_byteorder) {
561		LIBELF_SET_ERROR(HEADER, 0);
562		return ((off_t) -1);
563	}
564
565	shnum = e->e_u.e_elf.e_nscn;
566	phnum = e->e_u.e_elf.e_nphdr;
567
568	e->e_byteorder = eh_byteorder;
569
570#define	INITIALIZE_EHDR(E,EC,V)	do {					\
571		unsigned int _version = (unsigned int) (V);		\
572		(E)->e_ident[EI_MAG0] = ELFMAG0;			\
573		(E)->e_ident[EI_MAG1] = ELFMAG1;			\
574		(E)->e_ident[EI_MAG2] = ELFMAG2;			\
575		(E)->e_ident[EI_MAG3] = ELFMAG3;			\
576		(E)->e_ident[EI_CLASS] = (unsigned char) (EC);		\
577		(E)->e_ident[EI_VERSION] = (_version & 0xFFU);		\
578		(E)->e_ehsize = (uint16_t) _libelf_fsize(ELF_T_EHDR,	\
579		    (EC), _version, (size_t) 1);			\
580		(E)->e_phentsize = (uint16_t) ((phnum == 0) ? 0 :	\
581		    _libelf_fsize(ELF_T_PHDR, (EC), _version,		\
582			(size_t) 1));					\
583		(E)->e_shentsize = (uint16_t) _libelf_fsize(ELF_T_SHDR,	\
584		    (EC), _version, (size_t) 1);			\
585	} while (0)
586
587	if (ec == ELFCLASS32)
588		INITIALIZE_EHDR(eh32, ec, eh_version);
589	else
590		INITIALIZE_EHDR(eh64, ec, eh_version);
591
592	(void) elf_flagehdr(e, ELF_C_SET, ELF_F_DIRTY);
593
594	rc += (off_t) _libelf_fsize(ELF_T_EHDR, ec, eh_version, (size_t) 1);
595
596	if (!_libelf_insert_extent(extents, ELF_EXTENT_EHDR, 0, (uint64_t) rc,
597		ehdr))
598		return ((off_t) -1);
599
600	/*
601	 * Compute the layout the program header table, if one is
602	 * present.  The program header table needs to be aligned to a
603	 * `natural' boundary.
604	 */
605	if (phnum) {
606		fsz = _libelf_fsize(ELF_T_PHDR, ec, eh_version, phnum);
607		align = _libelf_falign(ELF_T_PHDR, ec);
608
609		if (e->e_flags & ELF_F_LAYOUT) {
610			/*
611			 * Check offsets for sanity.
612			 */
613			if (rc > phoff) {
614				LIBELF_SET_ERROR(LAYOUT, 0);
615				return ((off_t) -1);
616			}
617
618			if (phoff % (off_t) align) {
619				LIBELF_SET_ERROR(LAYOUT, 0);
620				return ((off_t) -1);
621			}
622
623		} else
624			phoff = roundup(rc, (off_t) align);
625
626		rc = phoff + (off_t) fsz;
627
628		phdr = _libelf_getphdr(e, ec);
629
630		if (!_libelf_insert_extent(extents, ELF_EXTENT_PHDR,
631			(uint64_t) phoff, fsz, phdr))
632			return ((off_t) -1);
633	} else
634		phoff = 0;
635
636	/*
637	 * Compute the layout of the sections associated with the
638	 * file.
639	 */
640
641	if (e->e_cmd != ELF_C_WRITE &&
642	    (e->e_flags & LIBELF_F_SHDRS_LOADED) == 0 &&
643	    _libelf_load_section_headers(e, ehdr) == 0)
644		return ((off_t) -1);
645
646	if ((rc = _libelf_resync_sections(e, rc, extents)) < 0)
647		return ((off_t) -1);
648
649	/*
650	 * Compute the space taken up by the section header table, if
651	 * one is needed.
652	 *
653	 * If ELF_F_LAYOUT has been asserted, the application may have
654	 * placed the section header table in between existing
655	 * sections, so the net size of the file need not increase due
656	 * to the presence of the section header table.
657	 *
658	 * If the library is responsible for laying out the object,
659	 * the section header table is placed after section data.
660	 */
661	if (shnum) {
662		fsz = _libelf_fsize(ELF_T_SHDR, ec, eh_version, shnum);
663		align = _libelf_falign(ELF_T_SHDR, ec);
664
665		if (e->e_flags & ELF_F_LAYOUT) {
666			if (shoff % (off_t) align) {
667				LIBELF_SET_ERROR(LAYOUT, 0);
668				return ((off_t) -1);
669			}
670		} else
671			shoff = roundup(rc, (off_t) align);
672
673		if (shoff + (off_t) fsz > rc)
674			rc = shoff + (off_t) fsz;
675
676		if (!_libelf_insert_extent(extents, ELF_EXTENT_SHDR,
677			(uint64_t) shoff, fsz, NULL))
678			return ((off_t) -1);
679	} else
680		shoff = 0;
681
682	/*
683	 * Set the fields of the Executable Header that could potentially use
684	 * extended numbering.
685	 */
686	_libelf_setphnum(e, ehdr, ec, phnum);
687	_libelf_setshnum(e, ehdr, ec, shnum);
688
689	/*
690	 * Update the `e_phoff' and `e_shoff' fields if the library is
691	 * doing the layout.
692	 */
693	if ((e->e_flags & ELF_F_LAYOUT) == 0) {
694		if (ec == ELFCLASS32) {
695			eh32->e_phoff = (uint32_t) phoff;
696			eh32->e_shoff = (uint32_t) shoff;
697		} else {
698			eh64->e_phoff = (uint64_t) phoff;
699			eh64->e_shoff = (uint64_t) shoff;
700		}
701	}
702
703	return (rc);
704}
705
706/*
707 * Write out the contents of an ELF section.
708 */
709
710static off_t
711_libelf_write_scn(Elf *e, unsigned char *nf, struct _Elf_Extent *ex)
712{
713	int ec;
714	off_t rc;
715	Elf_Scn *s;
716	int elftype;
717	Elf_Data *d, dst;
718	uint32_t sh_type;
719	struct _Libelf_Data *ld;
720	uint64_t sh_off, sh_size;
721	size_t fsz, msz, nobjects;
722
723	assert(ex->ex_type == ELF_EXTENT_SECTION);
724
725	s = ex->ex_desc;
726	rc = (off_t) ex->ex_start;
727
728	if ((ec = e->e_class) == ELFCLASS32) {
729		sh_type = s->s_shdr.s_shdr32.sh_type;
730		sh_size = (uint64_t) s->s_shdr.s_shdr32.sh_size;
731	} else {
732		sh_type = s->s_shdr.s_shdr64.sh_type;
733		sh_size = s->s_shdr.s_shdr64.sh_size;
734	}
735
736	/*
737	 * Ignore sections that do not allocate space in the file.
738	 */
739	if (sh_type == SHT_NOBITS || sh_type == SHT_NULL || sh_size == 0)
740		return (rc);
741
742	elftype = _libelf_xlate_shtype(sh_type);
743	assert(elftype >= ELF_T_FIRST && elftype <= ELF_T_LAST);
744
745	sh_off = s->s_offset;
746	assert(sh_off % _libelf_falign(elftype, ec) == 0);
747
748	/*
749	 * If the section has a `rawdata' descriptor, and the section
750	 * contents have not been modified, use its contents directly.
751	 * The `s_rawoff' member contains the offset into the original
752	 * file, while `s_offset' contains its new location in the
753	 * destination.
754	 */
755
756	if (STAILQ_EMPTY(&s->s_data)) {
757
758		if ((d = elf_rawdata(s, NULL)) == NULL)
759			return ((off_t) -1);
760
761		STAILQ_FOREACH(ld, &s->s_rawdata, d_next) {
762
763			d = &ld->d_data;
764
765			if ((uint64_t) rc < sh_off + d->d_off)
766				(void) memset(nf + rc,
767				    LIBELF_PRIVATE(fillchar),
768				    (size_t) (sh_off + d->d_off -
769					(uint64_t) rc));
770			rc = (off_t) (sh_off + d->d_off);
771
772			assert(d->d_buf != NULL);
773			assert(d->d_type == ELF_T_BYTE);
774			assert(d->d_version == e->e_version);
775
776			(void) memcpy(nf + rc,
777			    e->e_rawfile + s->s_rawoff + d->d_off,
778			    (size_t) d->d_size);
779
780			rc += (off_t) d->d_size;
781		}
782
783		return (rc);
784	}
785
786	/*
787	 * Iterate over the set of data descriptors for this section.
788	 * The prior call to _libelf_resync_elf() would have setup the
789	 * descriptors for this step.
790	 */
791
792	dst.d_version = e->e_version;
793
794	STAILQ_FOREACH(ld, &s->s_data, d_next) {
795
796		d = &ld->d_data;
797
798		msz = _libelf_msize(d->d_type, ec, e->e_version);
799
800		if ((uint64_t) rc < sh_off + d->d_off)
801			(void) memset(nf + rc,
802			    LIBELF_PRIVATE(fillchar),
803			    (size_t) (sh_off + d->d_off - (uint64_t) rc));
804
805		rc = (off_t) (sh_off + d->d_off);
806
807		assert(d->d_buf != NULL);
808		assert(d->d_version == e->e_version);
809		assert(d->d_size % msz == 0);
810
811		nobjects = (size_t) (d->d_size / msz);
812
813		fsz = _libelf_fsize(d->d_type, ec, e->e_version, nobjects);
814
815		dst.d_buf    = nf + rc;
816		dst.d_size   = fsz;
817
818		if (_libelf_xlate(&dst, d, e->e_byteorder, ec, ELF_TOFILE) ==
819		    NULL)
820			return ((off_t) -1);
821
822		rc += (off_t) fsz;
823	}
824
825	return (rc);
826}
827
828/*
829 * Write out an ELF Executable Header.
830 */
831
832static off_t
833_libelf_write_ehdr(Elf *e, unsigned char *nf, struct _Elf_Extent *ex)
834{
835	int ec;
836	void *ehdr;
837	size_t fsz, msz;
838	Elf_Data dst, src;
839
840	assert(ex->ex_type == ELF_EXTENT_EHDR);
841	assert(ex->ex_start == 0); /* Ehdr always comes first. */
842
843	ec = e->e_class;
844
845	ehdr = _libelf_ehdr(e, ec, 0);
846	assert(ehdr != NULL);
847
848	fsz = _libelf_fsize(ELF_T_EHDR, ec, e->e_version, (size_t) 1);
849	msz = _libelf_msize(ELF_T_EHDR, ec, e->e_version);
850
851	(void) memset(&dst, 0, sizeof(dst));
852	(void) memset(&src, 0, sizeof(src));
853
854	src.d_buf     = ehdr;
855	src.d_size    = msz;
856	src.d_type    = ELF_T_EHDR;
857	src.d_version = dst.d_version = e->e_version;
858
859	dst.d_buf     = nf;
860	dst.d_size    = fsz;
861
862	if (_libelf_xlate(&dst, &src, e->e_byteorder, ec, ELF_TOFILE) ==
863	    NULL)
864		return ((off_t) -1);
865
866	return ((off_t) fsz);
867}
868
869/*
870 * Write out an ELF program header table.
871 */
872
873static off_t
874_libelf_write_phdr(Elf *e, unsigned char *nf, struct _Elf_Extent *ex)
875{
876	int ec;
877	void *ehdr;
878	Elf32_Ehdr *eh32;
879	Elf64_Ehdr *eh64;
880	Elf_Data dst, src;
881	size_t fsz, phnum;
882	uint64_t phoff;
883
884	assert(ex->ex_type == ELF_EXTENT_PHDR);
885
886	ec = e->e_class;
887	ehdr = _libelf_ehdr(e, ec, 0);
888	phnum = e->e_u.e_elf.e_nphdr;
889
890	assert(phnum > 0);
891
892	if (ec == ELFCLASS32) {
893		eh32 = (Elf32_Ehdr *) ehdr;
894		phoff = (uint64_t) eh32->e_phoff;
895	} else {
896		eh64 = (Elf64_Ehdr *) ehdr;
897		phoff = eh64->e_phoff;
898	}
899
900	assert(phoff > 0);
901	assert(ex->ex_start == phoff);
902	assert(phoff % _libelf_falign(ELF_T_PHDR, ec) == 0);
903
904	(void) memset(&dst, 0, sizeof(dst));
905	(void) memset(&src, 0, sizeof(src));
906
907	fsz = _libelf_fsize(ELF_T_PHDR, ec, e->e_version, phnum);
908	assert(fsz > 0);
909
910	src.d_buf = _libelf_getphdr(e, ec);
911	src.d_version = dst.d_version = e->e_version;
912	src.d_type = ELF_T_PHDR;
913	src.d_size = phnum * _libelf_msize(ELF_T_PHDR, ec,
914	    e->e_version);
915
916	dst.d_size = fsz;
917	dst.d_buf = nf + ex->ex_start;
918
919	if (_libelf_xlate(&dst, &src, e->e_byteorder, ec, ELF_TOFILE) ==
920	    NULL)
921		return ((off_t) -1);
922
923	return ((off_t) (phoff + fsz));
924}
925
926/*
927 * Write out an ELF section header table.
928 */
929
930static off_t
931_libelf_write_shdr(Elf *e, unsigned char *nf, struct _Elf_Extent *ex)
932{
933	int ec;
934	void *ehdr;
935	Elf_Scn *scn;
936	uint64_t shoff;
937	Elf32_Ehdr *eh32;
938	Elf64_Ehdr *eh64;
939	size_t fsz, nscn;
940	Elf_Data dst, src;
941
942	assert(ex->ex_type == ELF_EXTENT_SHDR);
943
944	ec = e->e_class;
945	ehdr = _libelf_ehdr(e, ec, 0);
946	nscn = e->e_u.e_elf.e_nscn;
947
948	if (ec == ELFCLASS32) {
949		eh32 = (Elf32_Ehdr *) ehdr;
950		shoff = (uint64_t) eh32->e_shoff;
951	} else {
952		eh64 = (Elf64_Ehdr *) ehdr;
953		shoff = eh64->e_shoff;
954	}
955
956	assert(nscn > 0);
957	assert(shoff % _libelf_falign(ELF_T_SHDR, ec) == 0);
958	assert(ex->ex_start == shoff);
959
960	(void) memset(&dst, 0, sizeof(dst));
961	(void) memset(&src, 0, sizeof(src));
962
963	src.d_type = ELF_T_SHDR;
964	src.d_size = _libelf_msize(ELF_T_SHDR, ec, e->e_version);
965	src.d_version = dst.d_version = e->e_version;
966
967	fsz = _libelf_fsize(ELF_T_SHDR, ec, e->e_version, (size_t) 1);
968
969	STAILQ_FOREACH(scn, &e->e_u.e_elf.e_scn, s_next) {
970		if (ec == ELFCLASS32)
971			src.d_buf = &scn->s_shdr.s_shdr32;
972		else
973			src.d_buf = &scn->s_shdr.s_shdr64;
974
975		dst.d_size = fsz;
976		dst.d_buf = nf + ex->ex_start + scn->s_ndx * fsz;
977
978		if (_libelf_xlate(&dst, &src, e->e_byteorder, ec,
979		    ELF_TOFILE) == NULL)
980			return ((off_t) -1);
981	}
982
983	return ((off_t) (ex->ex_start + nscn * fsz));
984}
985
986/*
987 * Write out the file image.
988 *
989 * The original file could have been mapped in with an ELF_C_RDWR
990 * command and the application could have added new content or
991 * re-arranged its sections before calling elf_update().  Consequently
992 * its not safe to work `in place' on the original file.  So we
993 * malloc() the required space for the updated ELF object and build
994 * the object there and write it out to the underlying file at the
995 * end.  Note that the application may have opened the underlying file
996 * in ELF_C_RDWR and only retrieved/modified a few sections.  We take
997 * care to avoid translating file sections unnecessarily.
998 *
999 * Gaps in the coverage of the file by the file's sections will be
1000 * filled with the fill character set by elf_fill(3).
1001 */
1002
1003static off_t
1004_libelf_write_elf(Elf *e, off_t newsize, struct _Elf_Extent_List *extents)
1005{
1006	off_t nrc, rc;
1007	Elf_Scn *scn, *tscn;
1008	struct _Elf_Extent *ex;
1009	unsigned char *newfile;
1010
1011	assert(e->e_kind == ELF_K_ELF);
1012	assert(e->e_cmd == ELF_C_RDWR || e->e_cmd == ELF_C_WRITE);
1013	assert(e->e_fd >= 0);
1014
1015	if ((newfile = malloc((size_t) newsize)) == NULL) {
1016		LIBELF_SET_ERROR(RESOURCE, errno);
1017		return ((off_t) -1);
1018	}
1019
1020	nrc = rc = 0;
1021	SLIST_FOREACH(ex, extents, ex_next) {
1022
1023		/* Fill inter-extent gaps. */
1024		if (ex->ex_start > (size_t) rc)
1025			(void) memset(newfile + rc, LIBELF_PRIVATE(fillchar),
1026			    (size_t) (ex->ex_start - (uint64_t) rc));
1027
1028		switch (ex->ex_type) {
1029		case ELF_EXTENT_EHDR:
1030			if ((nrc = _libelf_write_ehdr(e, newfile, ex)) < 0)
1031				goto error;
1032			break;
1033
1034		case ELF_EXTENT_PHDR:
1035			if ((nrc = _libelf_write_phdr(e, newfile, ex)) < 0)
1036				goto error;
1037			break;
1038
1039		case ELF_EXTENT_SECTION:
1040			if ((nrc = _libelf_write_scn(e, newfile, ex)) < 0)
1041				goto error;
1042			break;
1043
1044		case ELF_EXTENT_SHDR:
1045			if ((nrc = _libelf_write_shdr(e, newfile, ex)) < 0)
1046				goto error;
1047			break;
1048
1049		default:
1050			assert(0);
1051			break;
1052		}
1053
1054		assert(ex->ex_start + ex->ex_size == (size_t) nrc);
1055		assert(rc < nrc);
1056
1057		rc = nrc;
1058	}
1059
1060	assert(rc == newsize);
1061
1062	/*
1063	 * For regular files, throw away existing file content and
1064	 * unmap any existing mappings.
1065	 */
1066	if ((e->e_flags & LIBELF_F_SPECIAL_FILE) == 0) {
1067		if (ftruncate(e->e_fd, (off_t) 0) < 0 ||
1068		    lseek(e->e_fd, (off_t) 0, SEEK_SET)) {
1069			LIBELF_SET_ERROR(IO, errno);
1070			goto error;
1071		}
1072#if	ELFTC_HAVE_MMAP
1073		if (e->e_flags & LIBELF_F_RAWFILE_MMAP) {
1074			assert(e->e_rawfile != NULL);
1075			assert(e->e_cmd == ELF_C_RDWR);
1076			if (munmap(e->e_rawfile, e->e_rawsize) < 0) {
1077				LIBELF_SET_ERROR(IO, errno);
1078				goto error;
1079			}
1080		}
1081#endif
1082	}
1083
1084	/*
1085	 * Write out the new contents.
1086	 */
1087	if (write(e->e_fd, newfile, (size_t) newsize) != newsize) {
1088		LIBELF_SET_ERROR(IO, errno);
1089		goto error;
1090	}
1091
1092	/*
1093	 * For files opened in ELF_C_RDWR mode, set up the new 'raw'
1094	 * contents.
1095	 */
1096	if (e->e_cmd == ELF_C_RDWR) {
1097		assert(e->e_rawfile != NULL);
1098		assert((e->e_flags & LIBELF_F_RAWFILE_MALLOC) ||
1099		    (e->e_flags & LIBELF_F_RAWFILE_MMAP));
1100		if (e->e_flags & LIBELF_F_RAWFILE_MALLOC) {
1101			free(e->e_rawfile);
1102			e->e_rawfile = newfile;
1103			newfile = NULL;
1104		}
1105#if	ELFTC_HAVE_MMAP
1106		else if (e->e_flags & LIBELF_F_RAWFILE_MMAP) {
1107			if ((e->e_rawfile = mmap(NULL, (size_t) newsize,
1108			    PROT_READ, MAP_PRIVATE, e->e_fd, (off_t) 0)) ==
1109			    MAP_FAILED) {
1110				LIBELF_SET_ERROR(IO, errno);
1111				goto error;
1112			}
1113		}
1114#endif	/* ELFTC_HAVE_MMAP */
1115
1116		/* Record the new size of the file. */
1117		e->e_rawsize = (size_t) newsize;
1118	} else {
1119		/* File opened in ELF_C_WRITE mode. */
1120		assert(e->e_rawfile == NULL);
1121	}
1122
1123	/*
1124	 * Reset flags, remove existing section descriptors and
1125	 * {E,P}HDR pointers so that a subsequent elf_get{e,p}hdr()
1126	 * and elf_getscn() will function correctly.
1127	 */
1128
1129	e->e_flags &= ~ELF_F_DIRTY;
1130
1131	STAILQ_FOREACH_SAFE(scn, &e->e_u.e_elf.e_scn, s_next, tscn)
1132		_libelf_release_scn(scn);
1133
1134	if (e->e_class == ELFCLASS32) {
1135		free(e->e_u.e_elf.e_ehdr.e_ehdr32);
1136		if (e->e_u.e_elf.e_phdr.e_phdr32)
1137			free(e->e_u.e_elf.e_phdr.e_phdr32);
1138
1139		e->e_u.e_elf.e_ehdr.e_ehdr32 = NULL;
1140		e->e_u.e_elf.e_phdr.e_phdr32 = NULL;
1141	} else {
1142		free(e->e_u.e_elf.e_ehdr.e_ehdr64);
1143		if (e->e_u.e_elf.e_phdr.e_phdr64)
1144			free(e->e_u.e_elf.e_phdr.e_phdr64);
1145
1146		e->e_u.e_elf.e_ehdr.e_ehdr64 = NULL;
1147		e->e_u.e_elf.e_phdr.e_phdr64 = NULL;
1148	}
1149
1150	/* Free the temporary buffer. */
1151	if (newfile)
1152		free(newfile);
1153
1154	return (rc);
1155
1156 error:
1157	free(newfile);
1158
1159	return ((off_t) -1);
1160}
1161
1162/*
1163 * Update an ELF object.
1164 */
1165
1166off_t
1167elf_update(Elf *e, Elf_Cmd c)
1168{
1169	int ec;
1170	off_t rc;
1171	struct _Elf_Extent_List extents;
1172
1173	rc = (off_t) -1;
1174
1175	if (e == NULL || e->e_kind != ELF_K_ELF ||
1176	    (c != ELF_C_NULL && c != ELF_C_WRITE)) {
1177		LIBELF_SET_ERROR(ARGUMENT, 0);
1178		return (rc);
1179	}
1180
1181	if ((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64) {
1182		LIBELF_SET_ERROR(CLASS, 0);
1183		return (rc);
1184	}
1185
1186	if (e->e_version == EV_NONE)
1187		e->e_version = EV_CURRENT;
1188
1189	if (c == ELF_C_WRITE && e->e_cmd == ELF_C_READ) {
1190		LIBELF_SET_ERROR(MODE, 0);
1191		return (rc);
1192	}
1193
1194	SLIST_INIT(&extents);
1195
1196	if ((rc = _libelf_resync_elf(e, &extents)) < 0)
1197		goto done;
1198
1199	if (c == ELF_C_NULL)
1200		goto done;
1201
1202	if (e->e_fd < 0) {
1203		rc = (off_t) -1;
1204		LIBELF_SET_ERROR(SEQUENCE, 0);
1205		goto done;
1206	}
1207
1208	rc = _libelf_write_elf(e, rc, &extents);
1209
1210done:
1211	_libelf_release_extents(&extents);
1212	return (rc);
1213}
1214