xref: /freebsd/usr.sbin/crunch/crunchide/exec_elf32.c (revision 51a9219f5780e61e1437d25220bf8750d9df7f8b)
1 /*
2  * Copyright (c) 1997 Christopher G. Demetriou.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. All advertising materials mentioning features or use of this software
13  *    must display the following acknowledgement:
14  *      This product includes software developed by Christopher G. Demetriou
15  *	for the NetBSD Project.
16  * 4. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 #ifndef lint
33 #if 0
34 __RCSID("$NetBSD: exec_elf32.c,v 1.4 1997/08/12 06:07:24 mikel Exp $");
35 #endif
36 static const char rcsid[] =
37   "$FreeBSD$";
38 #endif
39 
40 #ifndef ELFSIZE
41 #define ELFSIZE         32
42 #endif
43 
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 
47 #include <errno.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 
53 #include "endian.h"
54 #include "extern.h"
55 
56 #if (defined(NLIST_ELF32) && (ELFSIZE == 32)) || \
57     (defined(NLIST_ELF64) && (ELFSIZE == 64))
58 
59 #define	__ELF_WORD_SIZE ELFSIZE
60 #if (ELFSIZE == 32)
61 #include <sys/elf32.h>
62 #define	xewtoh(x)	((data == ELFDATA2MSB) ? be32toh(x) : le32toh(x))
63 #elif (ELFSIZE == 64)
64 #include <sys/elf64.h>
65 #define	xewtoh(x)	((data == ELFDATA2MSB) ? be64toh(x) : le64toh(x))
66 #endif
67 #include <sys/elf_generic.h>
68 
69 #define CONCAT(x,y)     __CONCAT(x,y)
70 #define ELFNAME(x)      CONCAT(elf,CONCAT(ELFSIZE,CONCAT(_,x)))
71 #define ELFNAME2(x,y)   CONCAT(x,CONCAT(_elf,CONCAT(ELFSIZE,CONCAT(_,y))))
72 #define ELFNAMEEND(x)   CONCAT(x,CONCAT(_elf,ELFSIZE))
73 #define ELFDEFNNAME(x)  CONCAT(ELF,CONCAT(ELFSIZE,CONCAT(_,x)))
74 
75 #define	xe16toh(x)	((data == ELFDATA2MSB) ? be16toh(x) : le16toh(x))
76 #define	xe32toh(x)	((data == ELFDATA2MSB) ? be32toh(x) : le32toh(x))
77 #define	htoxe32(x)	((data == ELFDATA2MSB) ? htobe32(x) : htole32(x))
78 
79 struct listelem {
80 	struct listelem *next;
81 	void *mem;
82 	off_t file;
83 	size_t size;
84 };
85 
86 static ssize_t
87 xreadatoff(int fd, void *buf, off_t off, size_t size, const char *fn)
88 {
89 	ssize_t rv;
90 
91 	if (lseek(fd, off, SEEK_SET) != off) {
92 		perror(fn);
93 		return -1;
94 	}
95 	if ((rv = read(fd, buf, size)) != size) {
96 		fprintf(stderr, "%s: read error: %s\n", fn,
97 		    rv == -1 ? strerror(errno) : "short read");
98 		return -1;
99 	}
100 	return size;
101 }
102 
103 static ssize_t
104 xwriteatoff(int fd, void *buf, off_t off, size_t size, const char *fn)
105 {
106 	ssize_t rv;
107 
108 	if (lseek(fd, off, SEEK_SET) != off) {
109 		perror(fn);
110 		return -1;
111 	}
112 	if ((rv = write(fd, buf, size)) != size) {
113 		fprintf(stderr, "%s: write error: %s\n", fn,
114 		    rv == -1 ? strerror(errno) : "short write");
115 		return -1;
116 	}
117 	return size;
118 }
119 
120 static void *
121 xmalloc(size_t size, const char *fn, const char *use)
122 {
123 	void *rv;
124 
125 	rv = malloc(size);
126 	if (rv == NULL)
127 		fprintf(stderr, "%s: out of memory (allocating for %s)\n",
128 		    fn, use);
129 	return (rv);
130 }
131 
132 int
133 ELFNAMEEND(check)(int fd, const char *fn)
134 {
135 	Elf_Ehdr eh;
136 	struct stat sb;
137 	unsigned char data;
138 
139 	/*
140 	 * Check the header to maek sure it's an ELF file (of the
141 	 * appropriate size).
142 	 */
143 	if (fstat(fd, &sb) == -1)
144 		return 0;
145 	if (sb.st_size < sizeof eh)
146 		return 0;
147 	if (read(fd, &eh, sizeof eh) != sizeof eh)
148 		return 0;
149 
150 	if (IS_ELF(eh) == 0)
151                 return 0;
152 
153 	data = eh.e_ident[EI_DATA];
154 
155 	switch (xe16toh(eh.e_machine)) {
156 	case EM_386: break;
157 	case EM_ALPHA: break;
158 	case EM_IA_64: break;
159 	case EM_SPARCV9: break;
160 /*        ELFDEFNNAME(MACHDEP_ID_CASES) */
161 
162         default:
163                 return 0;
164         }
165 
166 	return 1;
167 }
168 
169 int
170 ELFNAMEEND(hide)(int fd, const char *fn)
171 {
172 	Elf_Ehdr ehdr;
173 	Elf_Shdr *shdrp = NULL, *symtabshdr, *strtabshdr;
174 	Elf_Sym *symtabp = NULL;
175 	char *strtabp = NULL;
176 	Elf_Word *symfwmap = NULL, *symrvmap = NULL, nsyms, nlocalsyms, ewi;
177 	struct listelem *relalist = NULL, *rellist = NULL, *tmpl;
178 	ssize_t shdrsize;
179 	int rv, i, weird;
180 	unsigned char data;
181 
182 	rv = 0;
183 	if (xreadatoff(fd, &ehdr, 0, sizeof ehdr, fn) != sizeof ehdr)
184 		goto bad;
185 
186 	data = ehdr.e_ident[EI_DATA];
187 
188 	shdrsize = xe16toh(ehdr.e_shnum) * xe16toh(ehdr.e_shentsize);
189 	if ((shdrp = xmalloc(shdrsize, fn, "section header table")) == NULL)
190 		goto bad;
191 	if (xreadatoff(fd, shdrp, xewtoh(ehdr.e_shoff), shdrsize, fn) !=
192 	    shdrsize)
193 		goto bad;
194 
195 	symtabshdr = strtabshdr = NULL;
196 	weird = 0;
197 	for (i = 0; i < xe16toh(ehdr.e_shnum); i++) {
198 		switch (xe32toh(shdrp[i].sh_type)) {
199 		case SHT_SYMTAB:
200 			if (symtabshdr != NULL)
201 				weird = 1;
202 			symtabshdr = &shdrp[i];
203 			strtabshdr = &shdrp[xe32toh(shdrp[i].sh_link)];
204 			break;
205 		case SHT_RELA:
206 			tmpl = xmalloc(sizeof *tmpl, fn, "rela list element");
207 			if (tmpl == NULL)
208 				goto bad;
209 			tmpl->mem = NULL;
210 			tmpl->file = shdrp[i].sh_offset;
211 			tmpl->size = shdrp[i].sh_size;
212 			tmpl->next = relalist;
213 			relalist = tmpl;
214 			break;
215 		case SHT_REL:
216 			tmpl = xmalloc(sizeof *tmpl, fn, "rel list element");
217 			if (tmpl == NULL)
218 				goto bad;
219 			tmpl->mem = NULL;
220 			tmpl->file = shdrp[i].sh_offset;
221 			tmpl->size = shdrp[i].sh_size;
222 			tmpl->next = rellist;
223 			rellist = tmpl;
224 			break;
225 		}
226 	}
227 	if (symtabshdr == NULL)
228 		goto out;
229 	if (strtabshdr == NULL)
230 		weird = 1;
231 	if (weird) {
232 		fprintf(stderr, "%s: weird executable (unsupported)\n", fn);
233 		goto bad;
234 	}
235 
236 	/*
237 	 * load up everything we need
238 	 */
239 
240 	/* symbol table */
241 	if ((symtabp = xmalloc(xewtoh(symtabshdr->sh_size), fn, "symbol table"))
242 	    == NULL)
243 		goto bad;
244 	if (xreadatoff(fd, symtabp, xewtoh(symtabshdr->sh_offset),
245 	    xewtoh(symtabshdr->sh_size), fn) != xewtoh(symtabshdr->sh_size))
246 		goto bad;
247 
248 	/* string table */
249 	if ((strtabp = xmalloc(xewtoh(strtabshdr->sh_size), fn, "string table"))
250 	    == NULL)
251 		goto bad;
252 	if (xreadatoff(fd, strtabp, xewtoh(strtabshdr->sh_offset),
253 	    xewtoh(strtabshdr->sh_size), fn) != xewtoh(strtabshdr->sh_size))
254 		goto bad;
255 
256 	/* any rela tables */
257 	for (tmpl = relalist; tmpl != NULL; tmpl = tmpl->next) {
258 		if ((tmpl->mem = xmalloc(xewtoh(tmpl->size), fn, "rela table"))
259 		    == NULL)
260 			goto bad;
261 		if (xreadatoff(fd, tmpl->mem, xewtoh(tmpl->file),
262 		    xewtoh(tmpl->size), fn) != xewtoh(tmpl->size))
263 			goto bad;
264 	}
265 
266 	/* any rel tables */
267 	for (tmpl = rellist; tmpl != NULL; tmpl = tmpl->next) {
268 		if ((tmpl->mem = xmalloc(xewtoh(tmpl->size), fn, "rel table"))
269 		    == NULL)
270 			goto bad;
271 		if (xreadatoff(fd, tmpl->mem, xewtoh(tmpl->file),
272 		    xewtoh(tmpl->size), fn) != xewtoh(tmpl->size))
273 			goto bad;
274 	}
275 
276 	/* Prepare data structures for symbol movement. */
277 	nsyms = xewtoh(symtabshdr->sh_size) / xewtoh(symtabshdr->sh_entsize);
278 	nlocalsyms = xe32toh(symtabshdr->sh_info);
279 	if ((symfwmap = xmalloc(nsyms * sizeof (Elf_Word), fn,
280 	    "symbol forward mapping table")) == NULL)
281 		goto bad;
282 	if ((symrvmap = xmalloc(nsyms * sizeof (Elf_Word), fn,
283 	    "symbol reverse mapping table")) == NULL)
284 		goto bad;
285 
286 	/* init location -> symbol # table */
287 	for (ewi = 0; ewi < nsyms; ewi++)
288 		symrvmap[ewi] = ewi;
289 
290 	/* move symbols, making them local */
291 	for (ewi = nlocalsyms; ewi < nsyms; ewi++) {
292 		Elf_Sym *sp, symswap;
293 		Elf_Word mapswap;
294 
295 		sp = &symtabp[ewi];
296 
297 		/* if it's on our keep list, don't move it */
298 		if (in_keep_list(strtabp + xe32toh(sp->st_name)))
299 			continue;
300 
301 		/* if it's an undefined symbol, keep it */
302 		if (xe16toh(sp->st_shndx) == SHN_UNDEF)
303 			continue;
304 
305 		/* adjust the symbol so that it's local */
306 		sp->st_info =
307 		    ELF_ST_INFO(STB_LOCAL, sp->st_info);
308 /*		    (STB_LOCAL << 4) | ELF_SYM_TYPE(sp->st_info); *//* XXX */
309 
310 		/*
311 		 * move the symbol to its new location
312 		 */
313 
314 		/* note that symbols in those locations have been swapped */
315 		mapswap = symrvmap[ewi];
316 		symrvmap[ewi] = symrvmap[nlocalsyms];
317 		symrvmap[nlocalsyms] = mapswap;
318 
319 		/* and swap the symbols */
320 		symswap = *sp;
321 		*sp = symtabp[nlocalsyms];
322 		symtabp[nlocalsyms] = symswap;
323 
324 		nlocalsyms++;			/* note new local sym */
325 	}
326 	symtabshdr->sh_info = htoxe32(nlocalsyms);
327 
328 	/* set up symbol # -> location mapping table */
329 	for (ewi = 0; ewi < nsyms; ewi++)
330 		symfwmap[symrvmap[ewi]] = ewi;
331 
332 	/* any rela tables */
333 	for (tmpl = relalist; tmpl != NULL; tmpl = tmpl->next) {
334 		Elf_Rela *relap = tmpl->mem;
335 
336 		for (ewi = 0; ewi < xewtoh(tmpl->size) / sizeof(*relap); ewi++) {
337 			relap[ewi].r_info =
338 #if (ELFSIZE == 32)					/* XXX */
339 			    symfwmap[ELF_R_SYM(xe32toh(relap[ewi].r_info))] << 8 |
340 			    ELF_R_TYPE(xe32toh(relap[ewi].r_info));
341 #elif (ELFSIZE == 64)					/* XXX */
342 			    symfwmap[ELF_R_SYM(xewtoh(relap[ewi].r_info))] << 32 |
343 			    ELF_R_TYPE(xewtoh(relap[ewi].r_info));
344 #endif							/* XXX */
345 		}
346 	}
347 
348 	/* any rel tables */
349 	for (tmpl = rellist; tmpl != NULL; tmpl = tmpl->next) {
350 		Elf_Rel *relp = tmpl->mem;
351 
352 		for (ewi = 0; ewi < xewtoh(tmpl->size) / sizeof *relp; ewi++) {
353 			relp[ewi].r_info =
354 #if (ELFSIZE == 32)					/* XXX */
355 			    symfwmap[ELF_R_SYM(xe32toh(relp[ewi].r_info))] << 8 |
356 			    ELF_R_TYPE(xe32toh(relp[ewi].r_info));
357 #elif (ELFSIZE == 64)					/* XXX */
358 			    symfwmap[ELF_R_SYM(xewtoh(relp[ewi].r_info))] << 32 |
359 			    ELF_R_TYPE(xewtoh(relp[ewi].r_info));
360 #endif							/* XXX */
361 		}
362 	}
363 
364 	/*
365 	 * write new tables to the file
366 	 */
367 	if (xwriteatoff(fd, shdrp, xewtoh(ehdr.e_shoff), shdrsize, fn) !=
368 	    shdrsize)
369 		goto bad;
370 	if (xwriteatoff(fd, symtabp, xewtoh(symtabshdr->sh_offset),
371 	    xewtoh(symtabshdr->sh_size), fn) != xewtoh(symtabshdr->sh_size))
372 		goto bad;
373 	for (tmpl = relalist; tmpl != NULL; tmpl = tmpl->next) {
374 		if (xwriteatoff(fd, tmpl->mem, xewtoh(tmpl->file),
375 		    xewtoh(tmpl->size), fn) != xewtoh(tmpl->size))
376 			goto bad;
377 	}
378 	for (tmpl = rellist; tmpl != NULL; tmpl = tmpl->next) {
379 		if (xwriteatoff(fd, tmpl->mem, xewtoh(tmpl->file),
380 		    xewtoh(tmpl->size), fn) != xewtoh(tmpl->size))
381 			goto bad;
382 	}
383 
384 out:
385 	if (shdrp != NULL)
386 		free(shdrp);
387 	if (symtabp != NULL)
388 		free(symtabp);
389 	if (strtabp != NULL)
390 		free(strtabp);
391 	if (symfwmap != NULL)
392 		free(symfwmap);
393 	if (symrvmap != NULL)
394 		free(symrvmap);
395 	while ((tmpl = relalist) != NULL) {
396 		relalist = tmpl->next;
397 		if (tmpl->mem != NULL)
398 			free(tmpl->mem);
399 		free(tmpl);
400 	}
401 	while ((tmpl = rellist) != NULL) {
402 		rellist = tmpl->next;
403 		if (tmpl->mem != NULL)
404 			free(tmpl->mem);
405 		free(tmpl);
406 	}
407 	return (rv);
408 
409 bad:
410 	rv = 1;
411 	goto out;
412 }
413 
414 #endif /* include this size of ELF */
415