xref: /freebsd/contrib/elftoolchain/elfcopy/binary.c (revision 1c05a6ea6b849ff95e539c31adea887c644a6a01)
1 /*-
2  * Copyright (c) 2010,2011 Kai Wang
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 #include <ctype.h>
30 #include <err.h>
31 #include <gelf.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 
37 #include "elfcopy.h"
38 
39 ELFTC_VCSID("$Id: binary.c 3445 2016-04-20 19:08:30Z emaste $");
40 
41 /*
42  * Convert ELF object to `binary'. Sections with SHF_ALLOC flag set
43  * are copied to the result binary. The relative offsets for each section
44  * are retained, so the result binary file might contain "holes".
45  */
46 void
47 create_binary(int ifd, int ofd)
48 {
49 	Elf *e;
50 	Elf_Scn *scn;
51 	Elf_Data *d;
52 	GElf_Shdr sh;
53 	off_t base, off;
54 	int elferr;
55 
56 	if ((e = elf_begin(ifd, ELF_C_READ, NULL)) == NULL)
57 		errx(EXIT_FAILURE, "elf_begin() failed: %s",
58 		    elf_errmsg(-1));
59 
60 	base = 0;
61 	if (lseek(ofd, base, SEEK_SET) < 0)
62 		err(EXIT_FAILURE, "lseek failed");
63 
64 	/*
65 	 * Find base offset in the first iteration.
66 	 */
67 	base = -1;
68 	scn = NULL;
69 	while ((scn = elf_nextscn(e, scn)) != NULL) {
70 		if (gelf_getshdr(scn, &sh) == NULL) {
71 			warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
72 			(void) elf_errno();
73 			continue;
74 		}
75 		if ((sh.sh_flags & SHF_ALLOC) == 0 ||
76 		    sh.sh_type == SHT_NOBITS ||
77 		    sh.sh_size == 0)
78 			continue;
79 		if (base == -1 || (off_t) sh.sh_offset < base)
80 			base = sh.sh_offset;
81 	}
82 	elferr = elf_errno();
83 	if (elferr != 0)
84 		warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
85 
86 	if (base == -1)
87 		return;
88 
89 	/*
90 	 * Write out sections in the second iteration.
91 	 */
92 	scn = NULL;
93 	while ((scn = elf_nextscn(e, scn)) != NULL) {
94 		if (gelf_getshdr(scn, &sh) == NULL) {
95 			warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
96 			(void) elf_errno();
97 			continue;
98 		}
99 		if ((sh.sh_flags & SHF_ALLOC) == 0 ||
100 		    sh.sh_type == SHT_NOBITS ||
101 		    sh.sh_size == 0)
102 			continue;
103 		(void) elf_errno();
104 		if ((d = elf_getdata(scn, NULL)) == NULL) {
105 			elferr = elf_errno();
106 			if (elferr != 0)
107 				warnx("elf_getdata failed: %s", elf_errmsg(-1));
108 			continue;
109 		}
110 		if (d->d_buf == NULL || d->d_size == 0)
111 			continue;
112 
113 		/* lseek to section offset relative to `base'. */
114 		off = sh.sh_offset - base;
115 		if (lseek(ofd, off, SEEK_SET) < 0)
116 			err(EXIT_FAILURE, "lseek failed");
117 
118 		/* Write out section contents. */
119 		if (write(ofd, d->d_buf, d->d_size) != (ssize_t) d->d_size)
120 			err(EXIT_FAILURE, "write failed");
121 	}
122 	elferr = elf_errno();
123 	if (elferr != 0)
124 		warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
125 }
126 
127 #define	_SYMBOL_NAMSZ	1024
128 
129 /*
130  * Convert `binary' to ELF object. The input `binary' is converted to
131  * a relocatable (.o) file, a few symbols will also be created to make
132  * it easier to access the binary data in other compilation units.
133  */
134 void
135 create_elf_from_binary(struct elfcopy *ecp, int ifd, const char *ifn)
136 {
137 	char name[_SYMBOL_NAMSZ];
138 	struct section *sec, *sec_temp, *shtab;
139 	struct stat sb;
140 	GElf_Ehdr oeh;
141 	GElf_Shdr sh;
142 	void *content;
143 	uint64_t off, data_start, data_end, data_size;
144 	char *sym_basename, *p;
145 
146 	/* Reset internal section list. */
147 	if (!TAILQ_EMPTY(&ecp->v_sec))
148 		TAILQ_FOREACH_SAFE(sec, &ecp->v_sec, sec_list, sec_temp) {
149 			TAILQ_REMOVE(&ecp->v_sec, sec, sec_list);
150 			free(sec);
151 		}
152 
153 	if (fstat(ifd, &sb) == -1)
154 		err(EXIT_FAILURE, "fstat failed");
155 
156 	/* Read the input binary file to a internal buffer. */
157 	if ((content = malloc(sb.st_size)) == NULL)
158 		err(EXIT_FAILURE, "malloc failed");
159 	if (read(ifd, content, sb.st_size) != sb.st_size)
160 		err(EXIT_FAILURE, "read failed");
161 
162 	/*
163 	 * TODO: copy the input binary to output binary verbatim if -O is not
164 	 * specified.
165 	 */
166 
167 	/* Create EHDR for output .o file. */
168 	if (gelf_newehdr(ecp->eout, ecp->oec) == NULL)
169 		errx(EXIT_FAILURE, "gelf_newehdr failed: %s",
170 		    elf_errmsg(-1));
171 	if (gelf_getehdr(ecp->eout, &oeh) == NULL)
172 		errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
173 		    elf_errmsg(-1));
174 
175 	/* Initialise e_ident fields. */
176 	oeh.e_ident[EI_CLASS] = ecp->oec;
177 	oeh.e_ident[EI_DATA] = ecp->oed;
178 	/*
179 	 * TODO: Set OSABI according to the OS platform where elfcopy(1)
180 	 * was build. (probably)
181 	 */
182 	oeh.e_ident[EI_OSABI] = ELFOSABI_NONE;
183 	oeh.e_machine = ecp->oem;
184 	oeh.e_type = ET_REL;
185 	oeh.e_entry = 0;
186 
187 	ecp->flags |= RELOCATABLE;
188 
189 	/* Create .shstrtab section */
190 	init_shstrtab(ecp);
191 	ecp->shstrtab->off = 0;
192 
193 	/*
194 	 * Create `.data' section which contains the binary data. The
195 	 * section is inserted immediately after EHDR.
196 	 */
197 	off = gelf_fsize(ecp->eout, ELF_T_EHDR, 1, EV_CURRENT);
198 	if (off == 0)
199 		errx(EXIT_FAILURE, "gelf_fsize() failed: %s", elf_errmsg(-1));
200 	(void) create_external_section(ecp, ".data", NULL, content, sb.st_size,
201 	    off, SHT_PROGBITS, ELF_T_BYTE, SHF_ALLOC | SHF_WRITE, 1, 0, 1);
202 
203 	/* Insert .shstrtab after .data section. */
204 	if ((ecp->shstrtab->os = elf_newscn(ecp->eout)) == NULL)
205 		errx(EXIT_FAILURE, "elf_newscn failed: %s",
206 		    elf_errmsg(-1));
207 	insert_to_sec_list(ecp, ecp->shstrtab, 1);
208 
209 	/* Insert section header table here. */
210 	shtab = insert_shtab(ecp, 1);
211 
212 	/* Count in .symtab and .strtab section headers.  */
213 	shtab->sz += gelf_fsize(ecp->eout, ELF_T_SHDR, 2, EV_CURRENT);
214 
215 	if ((sym_basename = strdup(ifn)) == NULL)
216 		err(1, "strdup");
217 	for (p = sym_basename; *p != '\0'; p++)
218 		if (!isalnum(*p))
219 			*p = '_';
220 #define	_GEN_SYMNAME(S) do {						\
221 	snprintf(name, sizeof(name), "%s%s%s", "_binary_", sym_basename, S); \
222 } while (0)
223 
224 	/*
225 	 * Create symbol table.
226 	 */
227 	create_external_symtab(ecp);
228 	data_start = 0;
229 	data_end = data_start + sb.st_size;
230 	data_size = sb.st_size;
231 	_GEN_SYMNAME("_start");
232 	add_to_symtab(ecp, name, data_start, 0, 1,
233 	    ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);
234 	_GEN_SYMNAME("_end");
235 	add_to_symtab(ecp, name, data_end, 0, 1,
236 	    ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);
237 	_GEN_SYMNAME("_size");
238 	add_to_symtab(ecp, name, data_size, 0, SHN_ABS,
239 	    ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);
240 	finalize_external_symtab(ecp);
241 	create_symtab_data(ecp);
242 #undef	_GEN_SYMNAME
243 	free(sym_basename);
244 
245 	/*
246 	 * Write the underlying ehdr. Note that it should be called
247 	 * before elf_setshstrndx() since it will overwrite e->e_shstrndx.
248 	 */
249 	if (gelf_update_ehdr(ecp->eout, &oeh) == 0)
250 		errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",
251 		    elf_errmsg(-1));
252 
253 	/* Generate section name string table (.shstrtab). */
254 	ecp->flags |= SYMTAB_EXIST;
255 	set_shstrtab(ecp);
256 
257 	/* Update sh_name pointer for each section header entry. */
258 	update_shdr(ecp, 0);
259 
260 	/* Properly set sh_link field of .symtab section. */
261 	if (gelf_getshdr(ecp->symtab->os, &sh) == NULL)
262 		errx(EXIT_FAILURE, "692 gelf_getshdr() failed: %s",
263 		    elf_errmsg(-1));
264 	sh.sh_link = elf_ndxscn(ecp->strtab->os);
265 	if (!gelf_update_shdr(ecp->symtab->os, &sh))
266 		errx(EXIT_FAILURE, "gelf_update_shdr() failed: %s",
267 		    elf_errmsg(-1));
268 
269 	/* Renew oeh to get the updated e_shstrndx. */
270 	if (gelf_getehdr(ecp->eout, &oeh) == NULL)
271 		errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
272 		    elf_errmsg(-1));
273 
274 	/* Resync section offsets. */
275 	resync_sections(ecp);
276 
277 	/* Store SHDR offset in EHDR. */
278 	oeh.e_shoff = shtab->off;
279 
280 	/* Update ehdr since we modified e_shoff. */
281 	if (gelf_update_ehdr(ecp->eout, &oeh) == 0)
282 		errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",
283 		    elf_errmsg(-1));
284 
285 	/* Write out the output elf object. */
286 	if (elf_update(ecp->eout, ELF_C_WRITE) < 0)
287 		errx(EXIT_FAILURE, "elf_update() failed: %s",
288 		    elf_errmsg(-1));
289 
290 	/* Release allocated resource. */
291 	free(content);
292 	free_elf(ecp);
293 }
294