]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - lib/libelf/elf_update.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / lib / libelf / elf_update.c
1 /*-
2  * Copyright (c) 2006-2008 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/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/mman.h>
31 #include <sys/param.h>
32
33 #include <assert.h>
34 #include <errno.h>
35 #include <gelf.h>
36 #include <libelf.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40
41 #include "_libelf.h"
42
43 /*
44  * Update the internal data structures associated with an ELF object.
45  * Returns the size in bytes the ELF object would occupy in its file
46  * representation.
47  *
48  * After a successful call to this function, the following structures
49  * are updated:
50  *
51  * - The ELF header is updated.
52  * - All sections are sorted in order of ascending addresses and their
53  *   section header table entries updated.   An error is signalled
54  *   if an overlap was detected among sections.
55  * - All data descriptors associated with a section are sorted in order
56  *   of ascending addresses.  Overlaps, if detected, are signalled as
57  *   errors.  Other sanity checks for alignments, section types etc. are
58  *   made.
59  *
60  * After a resync_elf() successfully returns, the ELF descriptor is
61  * ready for being handed over to _libelf_write_elf().
62  *
63  * File alignments:
64  * PHDR - Addr
65  * SHDR - Addr
66  *
67  * XXX: how do we handle 'flags'.
68  */
69
70 /*
71  * Compute the extents of a section, by looking at the data
72  * descriptors associated with it.  The function returns zero if an
73  * error was detected.  `*rc' holds the maximum file extent seen so
74  * far.
75  */
76 static int
77 _libelf_compute_section_extents(Elf *e, Elf_Scn *s, off_t *rc)
78 {
79         int ec;
80         Elf_Data *d, *td;
81         unsigned int elftype;
82         uint32_t sh_type;
83         uint64_t d_align;
84         uint64_t sh_align, sh_entsize, sh_offset, sh_size;
85         uint64_t scn_size, scn_alignment;
86
87         /*
88          * We need to recompute library private data structures if one
89          * or more of the following is true:
90          * - The underlying Shdr structure has been marked `dirty'.  Significant
91          *   fields include: `sh_offset', `sh_type', `sh_size', `sh_addralign'.
92          * - The Elf_Data structures part of this section have been marked
93          *   `dirty'.  Affected members include `d_align', `d_offset', `d_type',
94          *   and `d_size'.
95          * - The section as a whole is `dirty', e.g., it has been allocated
96          *   using elf_newscn(), or if a new Elf_Data structure was added using
97          *   elf_newdata().
98          *
99          * Each of these conditions would result in the ELF_F_DIRTY bit being
100          * set on the section descriptor's `s_flags' field.
101          */
102
103         ec = e->e_class;
104
105         if (ec == ELFCLASS32) {
106                 sh_type    = s->s_shdr.s_shdr32.sh_type;
107                 sh_align   = (uint64_t) s->s_shdr.s_shdr32.sh_addralign;
108                 sh_entsize = (uint64_t) s->s_shdr.s_shdr32.sh_entsize;
109                 sh_offset  = (uint64_t) s->s_shdr.s_shdr32.sh_offset;
110                 sh_size    = (uint64_t) s->s_shdr.s_shdr32.sh_size;
111         } else {
112                 sh_type    = s->s_shdr.s_shdr64.sh_type;
113                 sh_align   = s->s_shdr.s_shdr64.sh_addralign;
114                 sh_entsize = s->s_shdr.s_shdr64.sh_entsize;
115                 sh_offset  = s->s_shdr.s_shdr64.sh_offset;
116                 sh_size    = s->s_shdr.s_shdr64.sh_size;
117         }
118
119         if (sh_type == SHT_NULL || sh_type == SHT_NOBITS)
120                 return (1);
121
122         if ((s->s_flags & ELF_F_DIRTY) == 0) {
123                 if ((size_t) *rc < sh_offset + sh_size)
124                         *rc = sh_offset + sh_size;
125                 return (1);
126         }
127
128         elftype = _libelf_xlate_shtype(sh_type);
129         if (elftype > ELF_T_LAST) {
130                 LIBELF_SET_ERROR(SECTION, 0);
131                 return (0);
132         }
133
134         /*
135          * Compute the extent of the data descriptors associated with
136          * this section.
137          */
138         scn_alignment = 0;
139         if (sh_align == 0)
140                 sh_align = _libelf_falign(elftype, ec);
141
142         /* Compute the section alignment. */
143         STAILQ_FOREACH(d, &s->s_data, d_next)  {
144                 if (d->d_type > ELF_T_LAST) {
145                         LIBELF_SET_ERROR(DATA, 0);
146                         return (0);
147                 }
148                 if (d->d_version != e->e_version) {
149                         LIBELF_SET_ERROR(VERSION, 0);
150                         return (0);
151                 }
152                 if ((d_align = d->d_align) == 0 || (d_align & (d_align - 1))) {
153                         LIBELF_SET_ERROR(DATA, 0);
154                         return (0);
155                 }
156                 if (d_align > scn_alignment)
157                         scn_alignment = d_align;
158         }
159
160         scn_size = 0L;
161
162         STAILQ_FOREACH_SAFE(d, &s->s_data, d_next, td) {
163                 if (e->e_flags & ELF_F_LAYOUT) {
164                         if ((uint64_t) d->d_off + d->d_size > scn_size)
165                                 scn_size = d->d_off + d->d_size;
166                 } else {
167                         scn_size = roundup2(scn_size, d->d_align);
168                         d->d_off = scn_size;
169                         scn_size += d->d_size;
170                 }
171         }
172
173         /*
174          * If the application is requesting full control over the layout
175          * of the section, check its values for sanity.
176          */
177         if (e->e_flags & ELF_F_LAYOUT) {
178                 if (scn_alignment > sh_align || sh_offset % sh_align ||
179                     sh_size < scn_size) {
180                         LIBELF_SET_ERROR(LAYOUT, 0);
181                         return (0);
182                 }
183         } else {
184                 /*
185                  * Otherwise compute the values in the section header.
186                  */
187
188                 if (scn_alignment > sh_align)
189                         sh_align = scn_alignment;
190
191                 /*
192                  * If the section entry size is zero, try and fill in an
193                  * appropriate entry size.  Per the elf(5) manual page
194                  * sections without fixed-size entries should have their
195                  * 'sh_entsize' field set to zero.
196                  */
197                 if (sh_entsize == 0 &&
198                     (sh_entsize = _libelf_fsize(elftype, ec, e->e_version,
199                     (size_t) 1)) == 1)
200                         sh_entsize = 0;
201
202                 sh_size = scn_size;
203                 sh_offset = roundup(*rc, sh_align);
204
205                 if (ec == ELFCLASS32) {
206                         s->s_shdr.s_shdr32.sh_addralign = (uint32_t) sh_align;
207                         s->s_shdr.s_shdr32.sh_entsize   = (uint32_t) sh_entsize;
208                         s->s_shdr.s_shdr32.sh_offset    = (uint32_t) sh_offset;
209                         s->s_shdr.s_shdr32.sh_size      = (uint32_t) sh_size;
210                 } else {
211                         s->s_shdr.s_shdr64.sh_addralign = sh_align;
212                         s->s_shdr.s_shdr64.sh_entsize   = sh_entsize;
213                         s->s_shdr.s_shdr64.sh_offset    = sh_offset;
214                         s->s_shdr.s_shdr64.sh_size      = sh_size;
215                 }
216         }
217
218         if ((size_t) *rc < sh_offset + sh_size)
219                 *rc = sh_offset + sh_size;
220
221         s->s_size = sh_size;
222         s->s_offset = sh_offset;
223         return (1);
224 }
225
226
227 /*
228  * Insert a section in ascending order in the list
229  */
230
231 static int
232 _libelf_insert_section(Elf *e, Elf_Scn *s)
233 {
234         Elf_Scn *t, *prevt;
235         uint64_t smax, smin, tmax, tmin;
236
237         smin = s->s_offset;
238         smax = smin + s->s_size;
239
240         prevt = NULL;
241         STAILQ_FOREACH(t, &e->e_u.e_elf.e_scn, s_next) {
242                 tmin = t->s_offset;
243                 tmax = tmin + t->s_size;
244
245                 if (tmax <= smin) {
246                         /*
247                          * 't' lies entirely before 's': ...| t |...| s |...
248                          */
249                         prevt = t;
250                         continue;
251                 } else if (smax <= tmin)
252                         /*
253                          * 's' lies entirely before 't', and after 'prevt':
254                          *      ...| prevt |...| s |...| t |...
255                          */
256                         break;
257                 else {  /* 's' and 't' overlap. */
258                         LIBELF_SET_ERROR(LAYOUT, 0);
259                         return (0);
260                 }
261         }
262
263         if (prevt)
264                 STAILQ_INSERT_AFTER(&e->e_u.e_elf.e_scn, prevt, s, s_next);
265         else
266                 STAILQ_INSERT_HEAD(&e->e_u.e_elf.e_scn, s, s_next);
267         return (1);
268 }
269
270 static off_t
271 _libelf_resync_sections(Elf *e, off_t rc)
272 {
273         int ec;
274         off_t nrc;
275         size_t sh_type, shdr_start, shdr_end;
276         Elf_Scn *s, *ts;
277
278         ec = e->e_class;
279
280         /*
281          * Make a pass through sections, computing the extent of each
282          * section. Order in increasing order of addresses.
283          */
284
285         nrc = rc;
286         STAILQ_FOREACH(s, &e->e_u.e_elf.e_scn, s_next)
287                 if (_libelf_compute_section_extents(e, s, &nrc) == 0)
288                         return ((off_t) -1);
289
290         STAILQ_FOREACH_SAFE(s, &e->e_u.e_elf.e_scn, s_next, ts) {
291                 if (ec == ELFCLASS32)
292                         sh_type = s->s_shdr.s_shdr32.sh_type;
293                 else
294                         sh_type = s->s_shdr.s_shdr64.sh_type;
295
296                 if (sh_type == SHT_NOBITS || sh_type == SHT_NULL)
297                         continue;
298
299                 if (s->s_offset < (uint64_t) rc) {
300                         if (s->s_offset + s->s_size < (uint64_t) rc) {
301                                 /*
302                                  * Try insert this section in the
303                                  * correct place in the list,
304                                  * detecting overlaps if any.
305                                  */
306                                 STAILQ_REMOVE(&e->e_u.e_elf.e_scn, s, _Elf_Scn,
307                                     s_next);
308                                 if (_libelf_insert_section(e, s) == 0)
309                                         return ((off_t) -1);
310                         } else {
311                                 LIBELF_SET_ERROR(LAYOUT, 0);
312                                 return ((off_t) -1);
313                         }
314                 } else
315                         rc = s->s_offset + s->s_size;
316         }
317
318         /*
319          * If the application is controlling file layout, check for an
320          * overlap between this section's extents and the SHDR table.
321          */
322         if (e->e_flags & ELF_F_LAYOUT) {
323
324                 if (e->e_class == ELFCLASS32)
325                         shdr_start = e->e_u.e_elf.e_ehdr.e_ehdr32->e_shoff;
326                 else
327                         shdr_start = e->e_u.e_elf.e_ehdr.e_ehdr64->e_shoff;
328
329                 shdr_end = shdr_start + _libelf_fsize(ELF_T_SHDR, e->e_class,
330                     e->e_version, e->e_u.e_elf.e_nscn);
331
332                 STAILQ_FOREACH(s, &e->e_u.e_elf.e_scn, s_next) {
333                         if (s->s_offset >= shdr_end ||
334                             s->s_offset + s->s_size <= shdr_start)
335                                 continue;
336                         LIBELF_SET_ERROR(LAYOUT, 0);
337                         return ((off_t) -1);
338                 }
339         }
340
341         assert(nrc == rc);
342
343         return (rc);
344 }
345
346 static off_t
347 _libelf_resync_elf(Elf *e)
348 {
349         int ec, eh_class, eh_type;
350         unsigned int eh_byteorder, eh_version;
351         size_t align, fsz;
352         size_t phnum, shnum;
353         off_t rc, phoff, shoff;
354         void *ehdr;
355         Elf32_Ehdr *eh32;
356         Elf64_Ehdr *eh64;
357
358         rc = 0;
359
360         ec = e->e_class;
361
362         assert(ec == ELFCLASS32 || ec == ELFCLASS64);
363
364         /*
365          * Prepare the EHDR.
366          */
367         if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL)
368                 return ((off_t) -1);
369
370         eh32 = ehdr;
371         eh64 = ehdr;
372
373         if (ec == ELFCLASS32) {
374                 eh_byteorder = eh32->e_ident[EI_DATA];
375                 eh_class     = eh32->e_ident[EI_CLASS];
376                 phoff        = (uint64_t) eh32->e_phoff;
377                 shoff        = (uint64_t) eh32->e_shoff;
378                 eh_type      = eh32->e_type;
379                 eh_version   = eh32->e_version;
380         } else {
381                 eh_byteorder = eh64->e_ident[EI_DATA];
382                 eh_class     = eh64->e_ident[EI_CLASS];
383                 phoff        = eh64->e_phoff;
384                 shoff        = eh64->e_shoff;
385                 eh_type      = eh64->e_type;
386                 eh_version   = eh64->e_version;
387         }
388
389         if (eh_version == EV_NONE)
390                 eh_version = EV_CURRENT;
391
392         if (eh_version != e->e_version) {       /* always EV_CURRENT */
393                 LIBELF_SET_ERROR(VERSION, 0);
394                 return ((off_t) -1);
395         }
396
397         if (eh_class != e->e_class) {
398                 LIBELF_SET_ERROR(CLASS, 0);
399                 return ((off_t) -1);
400         }
401
402         if (e->e_cmd != ELF_C_WRITE && eh_byteorder != e->e_byteorder) {
403                 LIBELF_SET_ERROR(HEADER, 0);
404                 return ((off_t) -1);
405         }
406
407         shnum = e->e_u.e_elf.e_nscn;
408         phnum = e->e_u.e_elf.e_nphdr;
409
410         e->e_byteorder = eh_byteorder;
411
412 #define INITIALIZE_EHDR(E,EC,V) do {                                    \
413                 (E)->e_ident[EI_MAG0] = ELFMAG0;                        \
414                 (E)->e_ident[EI_MAG1] = ELFMAG1;                        \
415                 (E)->e_ident[EI_MAG2] = ELFMAG2;                        \
416                 (E)->e_ident[EI_MAG3] = ELFMAG3;                        \
417                 (E)->e_ident[EI_CLASS] = (EC);                          \
418                 (E)->e_ident[EI_VERSION] = (V);                         \
419                 (E)->e_ehsize = _libelf_fsize(ELF_T_EHDR, (EC), (V),    \
420                     (size_t) 1);                                        \
421                 (E)->e_phentsize = (phnum == 0) ? 0 : _libelf_fsize(    \
422                     ELF_T_PHDR, (EC), (V), (size_t) 1);                 \
423                 (E)->e_shentsize = _libelf_fsize(ELF_T_SHDR, (EC), (V), \
424                     (size_t) 1);                                        \
425         } while (0)
426
427         if (ec == ELFCLASS32)
428                 INITIALIZE_EHDR(eh32, ec, eh_version);
429         else
430                 INITIALIZE_EHDR(eh64, ec, eh_version);
431
432         (void) elf_flagehdr(e, ELF_C_SET, ELF_F_DIRTY);
433
434         rc += _libelf_fsize(ELF_T_EHDR, ec, eh_version, (size_t) 1);
435
436         /*
437          * Compute the layout the program header table, if one is
438          * present.  The program header table needs to be aligned to a
439          * `natural' boundary.
440          */
441         if (phnum) {
442                 fsz = _libelf_fsize(ELF_T_PHDR, ec, eh_version, phnum);
443                 align = _libelf_falign(ELF_T_PHDR, ec);
444
445                 if (e->e_flags & ELF_F_LAYOUT) {
446                         /*
447                          * Check offsets for sanity.
448                          */
449                         if (rc > phoff) {
450                                 LIBELF_SET_ERROR(HEADER, 0);
451                                 return ((off_t) -1);
452                         }
453
454                         if (phoff % align) {
455                                 LIBELF_SET_ERROR(LAYOUT, 0);
456                                 return ((off_t) -1);
457                         }
458
459                 } else
460                         phoff = roundup(rc, align);
461
462                 rc = phoff + fsz;
463         } else
464                 phoff = 0;
465
466         /*
467          * Compute the layout of the sections associated with the
468          * file.
469          */
470
471         if (e->e_cmd != ELF_C_WRITE &&
472             (e->e_flags & LIBELF_F_SHDRS_LOADED) == 0 &&
473             _libelf_load_scn(e, ehdr) == 0)
474                 return ((off_t) -1);
475
476         if ((rc = _libelf_resync_sections(e, rc)) < 0)
477                 return ((off_t) -1);
478
479         /*
480          * Compute the space taken up by the section header table, if
481          * one is needed.  If ELF_F_LAYOUT is asserted, the
482          * application may have placed the section header table in
483          * between existing sections, so the net size of the file need
484          * not increase due to the presence of the section header
485          * table.
486          */
487         if (shnum) {
488                 fsz = _libelf_fsize(ELF_T_SHDR, ec, eh_version, (size_t) 1);
489                 align = _libelf_falign(ELF_T_SHDR, ec);
490
491                 if (e->e_flags & ELF_F_LAYOUT) {
492                         if (shoff % align) {
493                                 LIBELF_SET_ERROR(LAYOUT, 0);
494                                 return ((off_t) -1);
495                         }
496                 } else
497                         shoff = roundup(rc, align);
498
499                 if (shoff + fsz * shnum > (size_t) rc)
500                         rc = shoff + fsz * shnum;
501         } else
502                 shoff = 0;
503
504         /*
505          * Set the fields of the Executable Header that could potentially use
506          * extended numbering.
507          */
508         _libelf_setphnum(e, ehdr, ec, phnum);
509         _libelf_setshnum(e, ehdr, ec, shnum);
510
511         /*
512          * Update the `e_phoff' and `e_shoff' fields if the library is
513          * doing the layout.
514          */
515         if ((e->e_flags & ELF_F_LAYOUT) == 0) {
516                 if (ec == ELFCLASS32) {
517                         eh32->e_phoff = (uint32_t) phoff;
518                         eh32->e_shoff = (uint32_t) shoff;
519                 } else {
520                         eh64->e_phoff = (uint64_t) phoff;
521                         eh64->e_shoff = (uint64_t) shoff;
522                 }
523         }
524
525         return (rc);
526 }
527
528 /*
529  * Write out the contents of a section.
530  */
531
532 static off_t
533 _libelf_write_scn(Elf *e, char *nf, Elf_Scn *s, off_t rc)
534 {
535         int ec;
536         size_t fsz, msz, nobjects;
537         uint32_t sh_type;
538         uint64_t sh_off, sh_size;
539         int elftype;
540         Elf_Data *d, dst;
541
542         if ((ec = e->e_class) == ELFCLASS32) {
543                 sh_type = s->s_shdr.s_shdr32.sh_type;
544                 sh_size = (uint64_t) s->s_shdr.s_shdr32.sh_size;
545         } else {
546                 sh_type = s->s_shdr.s_shdr64.sh_type;
547                 sh_size = s->s_shdr.s_shdr64.sh_size;
548         }
549
550         /*
551          * Ignore sections that do not allocate space in the file.
552          */
553         if (sh_type == SHT_NOBITS || sh_type == SHT_NULL || sh_size == 0)
554                 return (rc);
555
556         elftype = _libelf_xlate_shtype(sh_type);
557         assert(elftype >= ELF_T_FIRST && elftype <= ELF_T_LAST);
558
559         sh_off = s->s_offset;
560         assert(sh_off % _libelf_falign(elftype, ec) == 0);
561
562         /*
563          * If the section has a `rawdata' descriptor, and the section
564          * contents have not been modified, use its contents directly.
565          * The `s_rawoff' member contains the offset into the original
566          * file, while `s_offset' contains its new location in the
567          * destination.
568          */
569
570         if (STAILQ_EMPTY(&s->s_data)) {
571
572                 if ((d = elf_rawdata(s, NULL)) == NULL)
573                         return ((off_t) -1);
574
575                 STAILQ_FOREACH(d, &s->s_rawdata, d_next) {
576                         if ((uint64_t) rc < sh_off + d->d_off)
577                                 (void) memset(nf + rc,
578                                     LIBELF_PRIVATE(fillchar), sh_off +
579                                     d->d_off - rc);
580                         rc = sh_off + d->d_off;
581
582                         assert(d->d_buf != NULL);
583                         assert(d->d_type == ELF_T_BYTE);
584                         assert(d->d_version == e->e_version);
585
586                         (void) memcpy(nf + rc,
587                             e->e_rawfile + s->s_rawoff + d->d_off, d->d_size);
588
589                         rc += d->d_size;
590                 }
591
592                 return (rc);
593         }
594
595         /*
596          * Iterate over the set of data descriptors for this section.
597          * The prior call to _libelf_resync_elf() would have setup the
598          * descriptors for this step.
599          */
600
601         dst.d_version = e->e_version;
602
603         STAILQ_FOREACH(d, &s->s_data, d_next) {
604
605                 msz = _libelf_msize(d->d_type, ec, e->e_version);
606
607                 if ((uint64_t) rc < sh_off + d->d_off)
608                         (void) memset(nf + rc,
609                             LIBELF_PRIVATE(fillchar), sh_off + d->d_off - rc);
610
611                 rc = sh_off + d->d_off;
612
613                 assert(d->d_buf != NULL);
614                 assert(d->d_version == e->e_version);
615                 assert(d->d_size % msz == 0);
616
617                 nobjects = d->d_size / msz;
618
619                 fsz = _libelf_fsize(d->d_type, ec, e->e_version, nobjects);
620
621                 dst.d_buf    = nf + rc;
622                 dst.d_size   = fsz;
623
624                 if (_libelf_xlate(&dst, d, e->e_byteorder, ec, ELF_TOFILE) ==
625                     NULL)
626                         return ((off_t) -1);
627
628                 rc += fsz;
629         }
630
631         return ((off_t) rc);
632 }
633
634 /*
635  * Write out the file image.
636  *
637  * The original file could have been mapped in with an ELF_C_RDWR
638  * command and the application could have added new content or
639  * re-arranged its sections before calling elf_update().  Consequently
640  * its not safe to work `in place' on the original file.  So we
641  * malloc() the required space for the updated ELF object and build
642  * the object there and write it out to the underlying file at the
643  * end.  Note that the application may have opened the underlying file
644  * in ELF_C_RDWR and only retrieved/modified a few sections.  We take
645  * care to avoid translating file sections unnecessarily.
646  *
647  * Gaps in the coverage of the file by the file's sections will be
648  * filled with the fill character set by elf_fill(3).
649  */
650
651 static off_t
652 _libelf_write_elf(Elf *e, off_t newsize)
653 {
654         int ec;
655         off_t maxrc, rc;
656         size_t fsz, msz, phnum, shnum;
657         uint64_t phoff, shoff;
658         void *ehdr;
659         char *newfile;
660         Elf_Data dst, src;
661         Elf_Scn *scn, *tscn;
662         Elf32_Ehdr *eh32;
663         Elf64_Ehdr *eh64;
664
665         assert(e->e_kind == ELF_K_ELF);
666         assert(e->e_cmd != ELF_C_READ);
667         assert(e->e_fd >= 0);
668
669         if ((newfile = malloc((size_t) newsize)) == NULL) {
670                 LIBELF_SET_ERROR(RESOURCE, errno);
671                 return ((off_t) -1);
672         }
673
674         ec = e->e_class;
675
676         ehdr = _libelf_ehdr(e, ec, 0);
677         assert(ehdr != NULL);
678
679         phnum = e->e_u.e_elf.e_nphdr;
680
681         if (ec == ELFCLASS32) {
682                 eh32 = (Elf32_Ehdr *) ehdr;
683
684                 phoff = (uint64_t) eh32->e_phoff;
685                 shnum = eh32->e_shnum;
686                 shoff = (uint64_t) eh32->e_shoff;
687         } else {
688                 eh64 = (Elf64_Ehdr *) ehdr;
689
690                 phoff = eh64->e_phoff;
691                 shnum = eh64->e_shnum;
692                 shoff = eh64->e_shoff;
693         }
694
695         fsz = _libelf_fsize(ELF_T_EHDR, ec, e->e_version, (size_t) 1);
696         msz = _libelf_msize(ELF_T_EHDR, ec, e->e_version);
697
698         (void) memset(&dst, 0, sizeof(dst));
699         (void) memset(&src, 0, sizeof(src));
700
701         src.d_buf     = ehdr;
702         src.d_size    = msz;
703         src.d_type    = ELF_T_EHDR;
704         src.d_version = dst.d_version = e->e_version;
705
706         rc = 0;
707
708         dst.d_buf     = newfile + rc;
709         dst.d_size    = fsz;
710
711         if (_libelf_xlate(&dst, &src, e->e_byteorder, ec, ELF_TOFILE) ==
712             NULL)
713                 goto error;
714
715         rc += fsz;
716
717         /*
718          * Write the program header table if present.
719          */
720
721         if (phnum != 0 && phoff != 0) {
722                 assert((unsigned) rc <= phoff);
723
724                 fsz = _libelf_fsize(ELF_T_PHDR, ec, e->e_version, phnum);
725
726                 assert(phoff % _libelf_falign(ELF_T_PHDR, ec) == 0);
727                 assert(fsz > 0);
728
729                 src.d_buf = _libelf_getphdr(e, ec);
730                 src.d_version = dst.d_version = e->e_version;
731                 src.d_type = ELF_T_PHDR;
732                 src.d_size = phnum * _libelf_msize(ELF_T_PHDR, ec,
733                     e->e_version);
734
735                 dst.d_size = fsz;
736
737                 if ((uint64_t) rc < phoff)
738                         (void) memset(newfile + rc,
739                             LIBELF_PRIVATE(fillchar), phoff - rc);
740
741                 dst.d_buf = newfile + rc;
742
743                 if (_libelf_xlate(&dst, &src, e->e_byteorder, ec, ELF_TOFILE) ==
744                     NULL)
745                         goto error;
746
747                 rc = phoff + fsz;
748         }
749
750         /*
751          * Write out individual sections.
752          */
753
754         STAILQ_FOREACH(scn, &e->e_u.e_elf.e_scn, s_next)
755                 if ((rc = _libelf_write_scn(e, newfile, scn, rc)) < 0)
756                         goto error;
757
758         /*
759          * Write out the section header table, if required.  Note that
760          * if flag ELF_F_LAYOUT has been set the section header table
761          * could reside in between byte ranges mapped by section
762          * descriptors.
763          */
764         if (shnum != 0 && shoff != 0) {
765                 if ((uint64_t) rc < shoff)
766                         (void) memset(newfile + rc,
767                             LIBELF_PRIVATE(fillchar), shoff - rc);
768
769                 maxrc = rc;
770                 rc = shoff;
771
772                 assert(rc % _libelf_falign(ELF_T_SHDR, ec) == 0);
773
774                 src.d_type = ELF_T_SHDR;
775                 src.d_size = _libelf_msize(ELF_T_SHDR, ec, e->e_version);
776                 src.d_version = dst.d_version = e->e_version;
777
778                 fsz = _libelf_fsize(ELF_T_SHDR, ec, e->e_version, (size_t) 1);
779
780                 STAILQ_FOREACH(scn, &e->e_u.e_elf.e_scn, s_next) {
781                         if (ec == ELFCLASS32)
782                                 src.d_buf = &scn->s_shdr.s_shdr32;
783                         else
784                                 src.d_buf = &scn->s_shdr.s_shdr64;
785
786                         dst.d_size = fsz;
787                         dst.d_buf = newfile + rc + scn->s_ndx * fsz;
788
789                         if (_libelf_xlate(&dst, &src, e->e_byteorder, ec,
790                                 ELF_TOFILE) != &dst)
791                                 goto error;
792                 }
793
794                 rc += e->e_u.e_elf.e_nscn * fsz;
795                 if (maxrc > rc)
796                         rc = maxrc;
797         }
798
799         assert(rc == newsize);
800
801         /*
802          * Write out the constructed contents and remap the file in
803          * read-only.
804          */
805
806         if (e->e_rawfile && munmap(e->e_rawfile, e->e_rawsize) < 0) {
807                 LIBELF_SET_ERROR(IO, errno);
808                 goto error;
809         }
810
811         if (write(e->e_fd, newfile, (size_t) newsize) != newsize ||
812             lseek(e->e_fd, (off_t) 0, SEEK_SET) < 0) {
813                 LIBELF_SET_ERROR(IO, errno);
814                 goto error;
815         }
816
817         if (e->e_cmd != ELF_C_WRITE) {
818                 if ((e->e_rawfile = mmap(NULL, (size_t) newsize, PROT_READ,
819                     MAP_PRIVATE, e->e_fd, (off_t) 0)) == MAP_FAILED) {
820                         LIBELF_SET_ERROR(IO, errno);
821                         goto error;
822                 }
823                 e->e_rawsize = newsize;
824         }
825
826         /*
827          * Reset flags, remove existing section descriptors and
828          * {E,P}HDR pointers so that a subsequent elf_get{e,p}hdr()
829          * and elf_getscn() will function correctly.
830          */
831
832         e->e_flags &= ~ELF_F_DIRTY;
833
834         STAILQ_FOREACH_SAFE(scn, &e->e_u.e_elf.e_scn, s_next, tscn)
835                 _libelf_release_scn(scn);
836
837         if (ec == ELFCLASS32) {
838                 free(e->e_u.e_elf.e_ehdr.e_ehdr32);
839                 if (e->e_u.e_elf.e_phdr.e_phdr32)
840                         free(e->e_u.e_elf.e_phdr.e_phdr32);
841
842                 e->e_u.e_elf.e_ehdr.e_ehdr32 = NULL;
843                 e->e_u.e_elf.e_phdr.e_phdr32 = NULL;
844         } else {
845                 free(e->e_u.e_elf.e_ehdr.e_ehdr64);
846                 if (e->e_u.e_elf.e_phdr.e_phdr64)
847                         free(e->e_u.e_elf.e_phdr.e_phdr64);
848
849                 e->e_u.e_elf.e_ehdr.e_ehdr64 = NULL;
850                 e->e_u.e_elf.e_phdr.e_phdr64 = NULL;
851         }
852
853         free(newfile);
854
855         return (rc);
856
857  error:
858         free(newfile);
859
860         return ((off_t) -1);
861 }
862
863 off_t
864 elf_update(Elf *e, Elf_Cmd c)
865 {
866         int ec;
867         off_t rc;
868
869         rc = (off_t) -1;
870
871         if (e == NULL || e->e_kind != ELF_K_ELF ||
872             (c != ELF_C_NULL && c != ELF_C_WRITE)) {
873                 LIBELF_SET_ERROR(ARGUMENT, 0);
874                 return (rc);
875         }
876
877         if ((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64) {
878                 LIBELF_SET_ERROR(CLASS, 0);
879                 return (rc);
880         }
881
882         if (e->e_version == EV_NONE)
883                 e->e_version = EV_CURRENT;
884
885         if (c == ELF_C_WRITE && e->e_cmd == ELF_C_READ) {
886                 LIBELF_SET_ERROR(MODE, 0);
887                 return (rc);
888         }
889
890         if ((rc = _libelf_resync_elf(e)) < 0)
891                 return (rc);
892
893         if (c == ELF_C_NULL)
894                 return (rc);
895
896         if (e->e_cmd == ELF_C_READ) {
897                 /*
898                  * This descriptor was opened in read-only mode or by
899                  * elf_memory().
900                  */
901                 if (e->e_fd)
902                         LIBELF_SET_ERROR(MODE, 0);
903                 else
904                         LIBELF_SET_ERROR(ARGUMENT, 0);
905                 return ((off_t) -1);
906         }
907
908         if (e->e_fd < 0) {
909                 LIBELF_SET_ERROR(SEQUENCE, 0);
910                 return ((off_t) -1);
911         }
912
913         return (_libelf_write_elf(e, rc));
914 }