xref: /freebsd/contrib/elftoolchain/elfcopy/binary.c (revision a812392203d7c4c3f0db9d8a0f3391374c49c71f)
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/cdefs.h>
28 #include <sys/param.h>
29 #include <sys/stat.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 2358 2011-12-19 18:22:32Z kaiwang27 $");
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 
145 	/* Reset internal section list. */
146 	if (!TAILQ_EMPTY(&ecp->v_sec))
147 		TAILQ_FOREACH_SAFE(sec, &ecp->v_sec, sec_list, sec_temp) {
148 			TAILQ_REMOVE(&ecp->v_sec, sec, sec_list);
149 			free(sec);
150 		}
151 
152 	if (fstat(ifd, &sb) == -1)
153 		err(EXIT_FAILURE, "fstat failed");
154 
155 	/* Read the input binary file to a internal buffer. */
156 	if ((content = malloc(sb.st_size)) == NULL)
157 		err(EXIT_FAILURE, "malloc failed");
158 	if (read(ifd, content, sb.st_size) != sb.st_size)
159 		err(EXIT_FAILURE, "read failed");
160 
161 	/*
162 	 * TODO: copy the input binary to output binary verbatim if -O is not
163 	 * specified.
164 	 */
165 
166 	/* Create EHDR for output .o file. */
167 	if (gelf_newehdr(ecp->eout, ecp->oec) == NULL)
168 		errx(EXIT_FAILURE, "gelf_newehdr failed: %s",
169 		    elf_errmsg(-1));
170 	if (gelf_getehdr(ecp->eout, &oeh) == NULL)
171 		errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
172 		    elf_errmsg(-1));
173 
174 	/* Initialise e_ident fields. */
175 	oeh.e_ident[EI_CLASS] = ecp->oec;
176 	oeh.e_ident[EI_DATA] = ecp->oed;
177 	/*
178 	 * TODO: Set OSABI according to the OS platform where elfcopy(1)
179 	 * was build. (probably)
180 	 */
181 	oeh.e_ident[EI_OSABI] = ELFOSABI_NONE;
182 	oeh.e_machine = ecp->oem;
183 	oeh.e_type = ET_REL;
184 	oeh.e_entry = 0;
185 
186 	ecp->flags |= RELOCATABLE;
187 
188 	/* Create .shstrtab section */
189 	init_shstrtab(ecp);
190 	ecp->shstrtab->off = 0;
191 
192 	/*
193 	 * Create `.data' section which contains the binary data. The
194 	 * section is inserted immediately after EHDR.
195 	 */
196 	off = gelf_fsize(ecp->eout, ELF_T_EHDR, 1, EV_CURRENT);
197 	if (off == 0)
198 		errx(EXIT_FAILURE, "gelf_fsize() failed: %s", elf_errmsg(-1));
199 	(void) create_external_section(ecp, ".data", NULL, content, sb.st_size,
200 	    off, SHT_PROGBITS, ELF_T_BYTE, SHF_ALLOC | SHF_WRITE, 1, 0, 1);
201 
202 	/* Insert .shstrtab after .data section. */
203 	if ((ecp->shstrtab->os = elf_newscn(ecp->eout)) == NULL)
204 		errx(EXIT_FAILURE, "elf_newscn failed: %s",
205 		    elf_errmsg(-1));
206 	insert_to_sec_list(ecp, ecp->shstrtab, 1);
207 
208 	/* Insert section header table here. */
209 	shtab = insert_shtab(ecp, 1);
210 
211 	/* Count in .symtab and .strtab section headers.  */
212 	shtab->sz += gelf_fsize(ecp->eout, ELF_T_SHDR, 2, EV_CURRENT);
213 
214 #define	_GEN_SYMNAME(S) do {						\
215 	snprintf(name, sizeof(name), "%s%s%s", "_binary_", ifn, S);	\
216 } while (0)
217 
218 	/*
219 	 * Create symbol table.
220 	 */
221 	create_external_symtab(ecp);
222 	data_start = 0;
223 	data_end = data_start + sb.st_size;
224 	data_size = sb.st_size;
225 	_GEN_SYMNAME("_start");
226 	add_to_symtab(ecp, name, data_start, 0, 1,
227 	    ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);
228 	_GEN_SYMNAME("_end");
229 	add_to_symtab(ecp, name, data_end, 0, 1,
230 	    ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);
231 	_GEN_SYMNAME("_size");
232 	add_to_symtab(ecp, name, data_size, 0, SHN_ABS,
233 	    ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0, 1);
234 	finalize_external_symtab(ecp);
235 	create_symtab_data(ecp);
236 #undef	_GEN_SYMNAME
237 
238 	/*
239 	 * Write the underlying ehdr. Note that it should be called
240 	 * before elf_setshstrndx() since it will overwrite e->e_shstrndx.
241 	 */
242 	if (gelf_update_ehdr(ecp->eout, &oeh) == 0)
243 		errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",
244 		    elf_errmsg(-1));
245 
246 	/* Generate section name string table (.shstrtab). */
247 	ecp->flags |= SYMTAB_EXIST;
248 	set_shstrtab(ecp);
249 
250 	/* Update sh_name pointer for each section header entry. */
251 	update_shdr(ecp, 0);
252 
253 	/* Properly set sh_link field of .symtab section. */
254 	if (gelf_getshdr(ecp->symtab->os, &sh) == NULL)
255 		errx(EXIT_FAILURE, "692 gelf_getshdr() failed: %s",
256 		    elf_errmsg(-1));
257 	sh.sh_link = elf_ndxscn(ecp->strtab->os);
258 	if (!gelf_update_shdr(ecp->symtab->os, &sh))
259 		errx(EXIT_FAILURE, "gelf_update_shdr() failed: %s",
260 		    elf_errmsg(-1));
261 
262 	/* Renew oeh to get the updated e_shstrndx. */
263 	if (gelf_getehdr(ecp->eout, &oeh) == NULL)
264 		errx(EXIT_FAILURE, "gelf_getehdr() failed: %s",
265 		    elf_errmsg(-1));
266 
267 	/* Resync section offsets. */
268 	resync_sections(ecp);
269 
270 	/* Store SHDR offset in EHDR. */
271 	oeh.e_shoff = shtab->off;
272 
273 	/* Update ehdr since we modified e_shoff. */
274 	if (gelf_update_ehdr(ecp->eout, &oeh) == 0)
275 		errx(EXIT_FAILURE, "gelf_update_ehdr() failed: %s",
276 		    elf_errmsg(-1));
277 
278 	/* Write out the output elf object. */
279 	if (elf_update(ecp->eout, ELF_C_WRITE) < 0)
280 		errx(EXIT_FAILURE, "elf_update() failed: %s",
281 		    elf_errmsg(-1));
282 
283 	/* Release allocated resource. */
284 	free(content);
285 	free_elf(ecp);
286 }
287