xref: /freebsd/usr.sbin/crunch/crunchide/exec_elf32.c (revision 0e97acdf58fe27b09c4824a474b0344daf997c5f)
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.6 1999/09/20 04:12:16 christos Exp $");
35 #endif
36 #endif
37 __FBSDID("$FreeBSD$");
38 
39 #ifndef ELFSIZE
40 #define ELFSIZE         32
41 #endif
42 
43 #include <sys/types.h>
44 #include <sys/endian.h>
45 #include <sys/stat.h>
46 
47 #include <errno.h>
48 #include <limits.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 
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 #define	htoxew(x)	((data == ELFDATA2MSB) ? htobe32(x) : htole32(x))
64 #define	wewtoh(x)	((data == ELFDATA2MSB) ? be32toh(x) : le32toh(x))
65 #define	htowew(x)	((data == ELFDATA2MSB) ? htobe32(x) : htole32(x))
66 #elif (ELFSIZE == 64)
67 #include <sys/elf64.h>
68 #define	xewtoh(x)	((data == ELFDATA2MSB) ? be64toh(x) : le64toh(x))
69 #define	htoxew(x)	((data == ELFDATA2MSB) ? htobe64(x) : htole64(x))
70 /* elf64 Elf64_Word are 32 bits */
71 #define	wewtoh(x)	((data == ELFDATA2MSB) ? be32toh(x) : le32toh(x))
72 #define	htowew(x)	((data == ELFDATA2MSB) ? htobe32(x) : htole32(x))
73 #endif
74 #include <sys/elf_generic.h>
75 
76 #define CONCAT(x,y)     __CONCAT(x,y)
77 #define ELFNAME(x)      CONCAT(elf,CONCAT(ELFSIZE,CONCAT(_,x)))
78 #define ELFNAME2(x,y)   CONCAT(x,CONCAT(_elf,CONCAT(ELFSIZE,CONCAT(_,y))))
79 #define ELFNAMEEND(x)   CONCAT(x,CONCAT(_elf,ELFSIZE))
80 #define ELFDEFNNAME(x)  CONCAT(ELF,CONCAT(ELFSIZE,CONCAT(_,x)))
81 
82 #define	xe16toh(x)	((data == ELFDATA2MSB) ? be16toh(x) : le16toh(x))
83 #define	xe32toh(x)	((data == ELFDATA2MSB) ? be32toh(x) : le32toh(x))
84 #define	htoxe32(x)	((data == ELFDATA2MSB) ? htobe32(x) : htole32(x))
85 
86 struct shlayout {
87 	Elf_Shdr *shdr;
88 	void *bufp;
89 };
90 
91 static ssize_t
92 xreadatoff(int fd, void *buf, off_t off, size_t size, const char *fn)
93 {
94 	ssize_t rv;
95 
96 	if (lseek(fd, off, SEEK_SET) != off) {
97 		perror(fn);
98 		return -1;
99 	}
100 	if ((size_t)(rv = read(fd, buf, size)) != size) {
101 		fprintf(stderr, "%s: read error: %s\n", fn,
102 		    rv == -1 ? strerror(errno) : "short read");
103 		return -1;
104 	}
105 	return size;
106 }
107 
108 static ssize_t
109 xwriteatoff(int fd, void *buf, off_t off, size_t size, const char *fn)
110 {
111 	ssize_t rv;
112 
113 	if (lseek(fd, off, SEEK_SET) != off) {
114 		perror(fn);
115 		return -1;
116 	}
117 	if ((size_t)(rv = write(fd, buf, size)) != size) {
118 		fprintf(stderr, "%s: write error: %s\n", fn,
119 		    rv == -1 ? strerror(errno) : "short write");
120 		return -1;
121 	}
122 	return size;
123 }
124 
125 static void *
126 xmalloc(size_t size, const char *fn, const char *use)
127 {
128 	void *rv;
129 
130 	rv = malloc(size);
131 	if (rv == NULL)
132 		fprintf(stderr, "%s: out of memory (allocating for %s)\n",
133 		    fn, use);
134 	return (rv);
135 }
136 
137 static void *
138 xrealloc(void *ptr, size_t size, const char *fn, const char *use)
139 {
140 	void *rv;
141 
142 	rv = realloc(ptr, size);
143 	if (rv == NULL) {
144 		free(ptr);
145 		fprintf(stderr, "%s: out of memory (reallocating for %s)\n",
146 		    fn, use);
147 	}
148 	return (rv);
149 }
150 
151 int
152 ELFNAMEEND(check)(int fd, const char *fn)
153 {
154 	Elf_Ehdr eh;
155 	struct stat sb;
156 	unsigned char data;
157 
158 	/*
159 	 * Check the header to maek sure it's an ELF file (of the
160 	 * appropriate size).
161 	 */
162 	if (fstat(fd, &sb) == -1)
163 		return 0;
164 	if (sb.st_size < (off_t)(sizeof eh))
165 		return 0;
166 	if (read(fd, &eh, sizeof eh) != sizeof eh)
167 		return 0;
168 
169 	if (IS_ELF(eh) == 0)
170                 return 0;
171 
172 	data = eh.e_ident[EI_DATA];
173 
174 	switch (xe16toh(eh.e_machine)) {
175 	case EM_386: break;
176 	case EM_ALPHA: break;
177 #ifndef EM_ARM
178 #define EM_ARM		40
179 #endif
180 	case EM_ARM: break;
181 #ifndef EM_MIPS
182 #define EM_MIPS		8
183 #endif
184 #ifndef EM_MIPS_RS4_BE		/* same as EM_MIPS_RS3_LE */
185 #define EM_MIPS_RS4_BE	10
186 #endif
187 	case EM_MIPS: break;
188 	case /* EM_MIPS_RS3_LE */ EM_MIPS_RS4_BE: break;
189 #ifndef EM_PPC
190 #define	EM_PPC		20
191 #endif
192 	case EM_PPC: break;
193 #ifndef EM_PPC64
194 #define	EM_PPC64	21
195 #endif
196 	case EM_PPC64: break;
197 #ifndef EM_SPARCV9
198 #define	EM_SPARCV9	43
199 #endif
200 	case EM_SPARCV9: break;
201 #ifndef EM_X86_64
202 #define	EM_X86_64	62
203 #endif
204 	case EM_X86_64: break;
205 /*        ELFDEFNNAME(MACHDEP_ID_CASES) */
206 
207         default:
208                 return 0;
209         }
210 
211 	return 1;
212 }
213 
214 /*
215  * This function 'hides' (some of) ELF executable file's symbols.
216  * It hides them by renaming them to "_$$hide$$ <filename> <symbolname>".
217  * Symbols in the global keep list, or which are marked as being undefined,
218  * are left alone.
219  *
220  * An old version of this code shuffled various tables around, turning
221  * global symbols to be hidden into local symbols.  That lost on the
222  * mips, because CALL16 relocs must reference global symbols, and, if
223  * those symbols were being hidden, they were no longer global.
224  *
225  * The new renaming behaviour doesn't take global symbols out of the
226  * namespace.  However, it's ... unlikely that there will ever be
227  * any collisions in practice because of the new method.
228  */
229 int
230 ELFNAMEEND(hide)(int fd, const char *fn)
231 {
232 	Elf_Ehdr ehdr;
233 	struct shlayout *layoutp = NULL;
234 	Elf_Shdr *shdrp = NULL, *symtabshdr, *strtabshdr, *shstrtabshdr;
235 	Elf_Shdr shdrshdr;
236 	Elf_Sym *symtabp = NULL;
237 	char *shstrtabp = NULL, *strtabp = NULL;
238 	Elf_Size nsyms, ewi;
239 	Elf_Off off;
240 	ssize_t shdrsize;
241 	int rv, i, weird, l, m, r, strtabidx;
242 	size_t nstrtab_size, nstrtab_nextoff, fn_size, size;
243 	char *nstrtabp = NULL;
244 	unsigned char data;
245 	const char *weirdreason = NULL;
246 	void *buf;
247 	Elf_Half shnum;
248 
249 	rv = 0;
250 	if (xreadatoff(fd, &ehdr, 0, sizeof ehdr, fn) != sizeof ehdr)
251 		goto bad;
252 
253 	data = ehdr.e_ident[EI_DATA];
254 	shnum = xe16toh(ehdr.e_shnum);
255 
256 	shdrsize = shnum * xe16toh(ehdr.e_shentsize);
257 	if ((shdrp = xmalloc(shdrsize, fn, "section header table")) == NULL)
258 		goto bad;
259 	if (xreadatoff(fd, shdrp, xewtoh(ehdr.e_shoff), shdrsize, fn) !=
260 	    shdrsize)
261 		goto bad;
262 
263 	symtabshdr = strtabshdr = shstrtabshdr = NULL;
264 	weird = 0;
265 	for (i = 0; i < shnum; i++) {
266 		switch (xe32toh(shdrp[i].sh_type)) {
267 		case SHT_SYMTAB:
268 			if (symtabshdr != NULL) {
269 				weird = 1;
270 				weirdreason = "multiple symbol tables";
271 			}
272 			symtabshdr = &shdrp[i];
273 			strtabshdr = &shdrp[xe32toh(shdrp[i].sh_link)];
274 			break;
275 		case SHT_STRTAB:
276 			if (i == xe16toh(ehdr.e_shstrndx))
277 				shstrtabshdr = &shdrp[i];
278 			break;
279 		}
280 	}
281 	if (symtabshdr == NULL)
282 		goto out;
283 	if (strtabshdr == NULL) {
284 		weird = 1;
285 		weirdreason = "string table does not exist";
286 	}
287 	if (shstrtabshdr == NULL) {
288 		weird = 1;
289 		weirdreason = "section header string table does not exist";
290 	}
291 	if (weirdreason == NULL)
292 		weirdreason = "unsupported";
293 	if (weird) {
294 		fprintf(stderr, "%s: weird executable (%s)\n", fn, weirdreason);
295 		goto bad;
296 	}
297 
298 	/*
299 	 * sort section layout table by offset
300 	 */
301 	layoutp = xmalloc((shnum + 1) * sizeof(struct shlayout),
302 	    fn, "layout table");
303 	if (layoutp == NULL)
304 		goto bad;
305 
306 	/* add a pseudo entry to represent the section header table */
307 	shdrshdr.sh_offset = ehdr.e_shoff;
308 	shdrshdr.sh_size = htoxew(shdrsize);
309 	shdrshdr.sh_addralign = htoxew(ELFSIZE / 8);
310 	layoutp[shnum].shdr = &shdrshdr;
311 
312 	/* insert and sort normal section headers */
313 	for (i = shnum; i-- != 0;) {
314 		l = i + 1;
315 		r = shnum;
316 		while (l <= r) {
317 			m = ( l + r) / 2;
318 			if (xewtoh(shdrp[i].sh_offset) >
319 			    xewtoh(layoutp[m].shdr->sh_offset))
320 				l = m + 1;
321 			else
322 				r = m - 1;
323 		}
324 
325 		if (r != i) {
326 			memmove(&layoutp[i], &layoutp[i + 1],
327 			    sizeof(struct shlayout) * (r - i));
328 		}
329 
330 		layoutp[r].shdr = &shdrp[i];
331 		layoutp[r].bufp = NULL;
332 	}
333 	++shnum;
334 
335 	/*
336 	 * load up everything we need
337 	 */
338 
339 	/* load section string table for debug use */
340 	if ((shstrtabp = xmalloc(xewtoh(shstrtabshdr->sh_size), fn,
341 	    "section string table")) == NULL)
342 		goto bad;
343 	if ((size_t)xreadatoff(fd, shstrtabp, xewtoh(shstrtabshdr->sh_offset),
344 	    xewtoh(shstrtabshdr->sh_size), fn) != xewtoh(shstrtabshdr->sh_size))
345 		goto bad;
346 
347 	/* we need symtab, strtab, and everything behind strtab */
348 	strtabidx = INT_MAX;
349 	for (i = 0; i < shnum; i++) {
350 		if (layoutp[i].shdr == &shdrshdr) {
351 			/* not load section header again */
352 			layoutp[i].bufp = shdrp;
353 			continue;
354 		}
355 		if (layoutp[i].shdr == shstrtabshdr) {
356 			/* not load section string table again */
357 			layoutp[i].bufp = shstrtabp;
358 			continue;
359 		}
360 
361 		if (layoutp[i].shdr == strtabshdr)
362 			strtabidx = i;
363 		if (layoutp[i].shdr == symtabshdr || i >= strtabidx) {
364 			off = xewtoh(layoutp[i].shdr->sh_offset);
365 			size = xewtoh(layoutp[i].shdr->sh_size);
366 			layoutp[i].bufp = xmalloc(size, fn,
367 			    shstrtabp + xewtoh(layoutp[i].shdr->sh_name));
368 			if (layoutp[i].bufp == NULL)
369 				goto bad;
370 			if ((size_t)xreadatoff(fd, layoutp[i].bufp, off, size, fn) !=
371 			    size)
372 				goto bad;
373 
374 			/* set symbol table and string table */
375 			if (layoutp[i].shdr == symtabshdr)
376 				symtabp = layoutp[i].bufp;
377 			else if (layoutp[i].shdr == strtabshdr)
378 				strtabp = layoutp[i].bufp;
379 		}
380 	}
381 
382 	nstrtab_size = 256;
383 	nstrtabp = xmalloc(nstrtab_size, fn, "new string table");
384 	if (nstrtabp == NULL)
385 		goto bad;
386 	nstrtab_nextoff = 0;
387 
388 	fn_size = strlen(fn);
389 
390 	/* Prepare data structures for symbol movement. */
391 	nsyms = xewtoh(symtabshdr->sh_size) / xewtoh(symtabshdr->sh_entsize);
392 
393 	/* move symbols, making them local */
394 	for (ewi = 0; ewi < nsyms; ewi++) {
395 		Elf_Sym *sp = &symtabp[ewi];
396 		const char *symname = strtabp + xe32toh(sp->st_name);
397 		size_t newent_len;
398 		/*
399 		 * make sure there's size for the next entry, even if it's
400 		 * as large as it can be.
401 		 *
402 		 * "_$$hide$$ <filename> <symname><NUL>" ->
403 		 *    9 + 3 + sizes of fn and sym name
404 		 */
405 		while ((nstrtab_size - nstrtab_nextoff) <
406 		    strlen(symname) + fn_size + 12) {
407 			nstrtab_size *= 2;
408 			nstrtabp = xrealloc(nstrtabp, nstrtab_size, fn,
409 			    "new string table");
410 			if (nstrtabp == NULL)
411 				goto bad;
412 		}
413 
414 		sp->st_name = htowew(nstrtab_nextoff);
415 
416 		/* if it's a keeper or is undefined, don't rename it. */
417 		if (in_keep_list(symname) ||
418 		    (xe16toh(sp->st_shndx) == SHN_UNDEF)) {
419 			newent_len = sprintf(nstrtabp + nstrtab_nextoff,
420 			    "%s", symname) + 1;
421 		} else {
422 			newent_len = sprintf(nstrtabp + nstrtab_nextoff,
423 			    "_$$hide$$ %s %s", fn, symname) + 1;
424 		}
425 		nstrtab_nextoff += newent_len;
426 	}
427 	strtabshdr->sh_size = htoxew(nstrtab_nextoff);
428 
429 	/*
430 	 * update section header table in ascending order of offset
431 	 */
432 	for (i = strtabidx + 1; i < shnum; i++) {
433 		Elf_Off off, align;
434 		off = xewtoh(layoutp[i - 1].shdr->sh_offset) +
435 		    xewtoh(layoutp[i - 1].shdr->sh_size);
436 		align = xewtoh(layoutp[i].shdr->sh_addralign);
437 		off = (off + (align - 1)) & ~(align - 1);
438 		layoutp[i].shdr->sh_offset = htoxew(off);
439 	}
440 
441 	/*
442 	 * write data to the file in descending order of offset
443 	 */
444 	for (i = shnum; i-- != 0;) {
445 		if (layoutp[i].shdr == strtabshdr) {
446 			/* new string table */
447 			buf = nstrtabp;
448 		} else
449 			buf = layoutp[i].bufp;
450 
451 		if (layoutp[i].shdr == &shdrshdr ||
452 		    layoutp[i].shdr == symtabshdr || i >= strtabidx) {
453 			if (buf == NULL)
454 				goto bad;
455 
456 			/*
457 			 * update the offset of section header table in elf
458 			 * header if needed.
459 			 */
460 			if (layoutp[i].shdr == &shdrshdr &&
461 			    ehdr.e_shoff != shdrshdr.sh_offset) {
462 				ehdr.e_shoff = shdrshdr.sh_offset;
463 				off = (ELFSIZE == 32) ? 32 : 44;
464 				size = sizeof(Elf_Off);
465 				if ((size_t)xwriteatoff(fd, &ehdr.e_shoff, off, size,
466 				    fn) != size)
467 					goto bad;
468 			}
469 
470 			off = xewtoh(layoutp[i].shdr->sh_offset);
471 			size = xewtoh(layoutp[i].shdr->sh_size);
472 			if ((size_t)xwriteatoff(fd, buf, off, size, fn) != size)
473 				goto bad;
474 		}
475 	}
476 
477 out:
478 	if (layoutp != NULL) {
479 		for (i = 0; i < shnum; i++) {
480 			if (layoutp[i].bufp != NULL)
481 				free(layoutp[i].bufp);
482 		}
483 		free(layoutp);
484 	}
485 	free(nstrtabp);
486 	return (rv);
487 
488 bad:
489 	rv = 1;
490 	goto out;
491 }
492 
493 #endif /* include this size of ELF */
494