xref: /freebsd/usr.sbin/crunch/crunchide/exec_elf32.c (revision 8be96e101f2691b80ff9562b72f874da82e735aa)
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 #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 <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 
53 #include "extern.h"
54 
55 #if (defined(NLIST_ELF32) && (ELFSIZE == 32)) || \
56     (defined(NLIST_ELF64) && (ELFSIZE == 64))
57 
58 #define	__ELF_WORD_SIZE ELFSIZE
59 #if (ELFSIZE == 32)
60 #include <sys/elf32.h>
61 #define	xewtoh(x)	((data == ELFDATA2MSB) ? be32toh(x) : le32toh(x))
62 #define	htoxew(x)	((data == ELFDATA2MSB) ? htobe32(x) : htole32(x))
63 #elif (ELFSIZE == 64)
64 #include <sys/elf64.h>
65 #define	xewtoh(x)	((data == ELFDATA2MSB) ? be64toh(x) : le64toh(x))
66 #define	htoxew(x)	((data == ELFDATA2MSB) ? htobe64(x) : htole64(x))
67 #endif
68 #include <sys/elf_generic.h>
69 
70 #define CONCAT(x,y)     __CONCAT(x,y)
71 #define ELFNAME(x)      CONCAT(elf,CONCAT(ELFSIZE,CONCAT(_,x)))
72 #define ELFNAME2(x,y)   CONCAT(x,CONCAT(_elf,CONCAT(ELFSIZE,CONCAT(_,y))))
73 #define ELFNAMEEND(x)   CONCAT(x,CONCAT(_elf,ELFSIZE))
74 #define ELFDEFNNAME(x)  CONCAT(ELF,CONCAT(ELFSIZE,CONCAT(_,x)))
75 
76 #define	xe16toh(x)	((data == ELFDATA2MSB) ? be16toh(x) : le16toh(x))
77 #define	xe32toh(x)	((data == ELFDATA2MSB) ? be32toh(x) : le32toh(x))
78 #define	htoxe32(x)	((data == ELFDATA2MSB) ? htobe32(x) : htole32(x))
79 
80 struct listelem {
81 	struct listelem *next;
82 	void *mem;
83 	off_t file;
84 	size_t size;
85 };
86 
87 static ssize_t
88 xreadatoff(int fd, void *buf, off_t off, size_t size, const char *fn)
89 {
90 	ssize_t rv;
91 
92 	if (lseek(fd, off, SEEK_SET) != off) {
93 		perror(fn);
94 		return -1;
95 	}
96 	if ((rv = read(fd, buf, size)) != size) {
97 		fprintf(stderr, "%s: read error: %s\n", fn,
98 		    rv == -1 ? strerror(errno) : "short read");
99 		return -1;
100 	}
101 	return size;
102 }
103 
104 static ssize_t
105 xwriteatoff(int fd, void *buf, off_t off, size_t size, const char *fn)
106 {
107 	ssize_t rv;
108 
109 	if (lseek(fd, off, SEEK_SET) != off) {
110 		perror(fn);
111 		return -1;
112 	}
113 	if ((rv = write(fd, buf, size)) != size) {
114 		fprintf(stderr, "%s: write error: %s\n", fn,
115 		    rv == -1 ? strerror(errno) : "short write");
116 		return -1;
117 	}
118 	return size;
119 }
120 
121 static void *
122 xmalloc(size_t size, const char *fn, const char *use)
123 {
124 	void *rv;
125 
126 	rv = malloc(size);
127 	if (rv == NULL)
128 		fprintf(stderr, "%s: out of memory (allocating for %s)\n",
129 		    fn, use);
130 	return (rv);
131 }
132 
133 static void *
134 xrealloc(void *ptr, size_t size, const char *fn, const char *use)
135 {
136 	void *rv;
137 
138 	rv = realloc(ptr, size);
139 	if (rv == NULL) {
140 		free(ptr);
141 		fprintf(stderr, "%s: out of memory (reallocating for %s)\n",
142 		    fn, use);
143 	}
144 	return (rv);
145 }
146 
147 int
148 ELFNAMEEND(check)(int fd, const char *fn)
149 {
150 	Elf_Ehdr eh;
151 	struct stat sb;
152 	unsigned char data;
153 
154 	/*
155 	 * Check the header to maek sure it's an ELF file (of the
156 	 * appropriate size).
157 	 */
158 	if (fstat(fd, &sb) == -1)
159 		return 0;
160 	if (sb.st_size < sizeof eh)
161 		return 0;
162 	if (read(fd, &eh, sizeof eh) != sizeof eh)
163 		return 0;
164 
165 	if (IS_ELF(eh) == 0)
166                 return 0;
167 
168 	data = eh.e_ident[EI_DATA];
169 
170 	switch (xe16toh(eh.e_machine)) {
171 	case EM_386: break;
172 	case EM_ALPHA: break;
173 #ifndef EM_ARM
174 #define EM_ARM		40
175 #endif
176 	case EM_ARM: break;
177 #ifndef EM_MIPS
178 #define EM_MIPS		8
179 #endif
180 #ifndef EM_MIPS_RS4_BE		/* same as EM_MIPS_RS3_LE */
181 #define EM_MIPS_RS4_BE	10
182 #endif
183 	case EM_MIPS: break;
184 	case /* EM_MIPS_RS3_LE */ EM_MIPS_RS4_BE: break;
185 #ifndef EM_IA_64
186 #define	EM_IA_64	50
187 #endif
188 	case EM_IA_64: 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 	Elf_Shdr *shdrp = NULL, *symtabshdr, *strtabshdr;
234 	Elf_Sym *symtabp = NULL;
235 	char *strtabp = NULL;
236 	Elf_Size  nsyms, nlocalsyms, ewi;
237 	ssize_t shdrsize;
238 	int rv, i, weird;
239 	size_t nstrtab_size, nstrtab_nextoff, fn_size;
240 	char *nstrtabp = NULL;
241 	unsigned char data;
242 	Elf_Off maxoff, stroff;
243 	const char *weirdreason = NULL;
244 
245 	rv = 0;
246 	if (xreadatoff(fd, &ehdr, 0, sizeof ehdr, fn) != sizeof ehdr)
247 		goto bad;
248 
249 	data = ehdr.e_ident[EI_DATA];
250 
251 	shdrsize = xe16toh(ehdr.e_shnum) * xe16toh(ehdr.e_shentsize);
252 	if ((shdrp = xmalloc(shdrsize, fn, "section header table")) == NULL)
253 		goto bad;
254 	if (xreadatoff(fd, shdrp, xewtoh(ehdr.e_shoff), shdrsize, fn) !=
255 	    shdrsize)
256 		goto bad;
257 
258 	symtabshdr = strtabshdr = NULL;
259 	weird = 0;
260 	maxoff = stroff = 0;
261 	for (i = 0; i < xe16toh(ehdr.e_shnum); i++) {
262 		if (xewtoh(shdrp[i].sh_offset) > maxoff)
263 			maxoff = xewtoh(shdrp[i].sh_offset);
264 		switch (xe32toh(shdrp[i].sh_type)) {
265 		case SHT_SYMTAB:
266 			if (symtabshdr != NULL)
267 				weird = 1;
268 			symtabshdr = &shdrp[i];
269 			strtabshdr = &shdrp[xe32toh(shdrp[i].sh_link)];
270 
271 			/* Check whether the string table is the last section */
272 			stroff = xewtoh(shdrp[xe32toh(shdrp[i].sh_link)].sh_offset);
273 			if (!weird && xe32toh(shdrp[i].sh_link) != (xe16toh(ehdr.e_shnum) - 1)) {
274 				weird = 1;
275 				weirdreason = "string table not last section";
276 			}
277 			break;
278 		}
279 	}
280 	if (! weirdreason)
281 		weirdreason = "unsupported";
282 	if (symtabshdr == NULL)
283 		goto out;
284 	if (strtabshdr == NULL)
285 		weird = 1;
286 	if (!weird && stroff != maxoff) {
287 		weird = 1;
288 		weirdreason = "string table section not last in file";
289 	}
290 	if (weird) {
291 		fprintf(stderr, "%s: weird executable (%s)\n", fn, weirdreason);
292 		goto bad;
293 	}
294 
295 	/*
296 	 * load up everything we need
297 	 */
298 
299 	/* symbol table */
300 	if ((symtabp = xmalloc(xewtoh(symtabshdr->sh_size), fn, "symbol table"))
301 	    == NULL)
302 		goto bad;
303 	if (xreadatoff(fd, symtabp, xewtoh(symtabshdr->sh_offset),
304 	    xewtoh(symtabshdr->sh_size), fn) != xewtoh(symtabshdr->sh_size))
305 		goto bad;
306 
307 	/* string table */
308 	if ((strtabp = xmalloc(xewtoh(strtabshdr->sh_size), fn, "string table"))
309 	    == NULL)
310 		goto bad;
311 	if (xreadatoff(fd, strtabp, xewtoh(strtabshdr->sh_offset),
312 	    xewtoh(strtabshdr->sh_size), fn) != xewtoh(strtabshdr->sh_size))
313 		goto bad;
314 
315 	nstrtab_size = 256;
316 	nstrtabp = xmalloc(nstrtab_size, fn, "new string table");
317 	if (nstrtabp == NULL)
318 		goto bad;
319 	nstrtab_nextoff = 0;
320 
321 	fn_size = strlen(fn);
322 
323 	/* Prepare data structures for symbol movement. */
324 	nsyms = xewtoh(symtabshdr->sh_size) / xewtoh(symtabshdr->sh_entsize);
325 	nlocalsyms = xe32toh(symtabshdr->sh_info);
326 
327 	/* move symbols, making them local */
328 	for (ewi = 0; ewi < nsyms; ewi++) {
329 		Elf_Sym *sp = &symtabp[ewi];
330 		const char *symname = strtabp + xe32toh(sp->st_name);
331 		size_t newent_len;
332 		/*
333 		 * make sure there's size for the next entry, even if it's
334 		 * as large as it can be.
335 		 *
336 		 * "_$$hide$$ <filename> <symname><NUL>" ->
337 		 *    9 + 3 + sizes of fn and sym name
338 		 */
339 		while ((nstrtab_size - nstrtab_nextoff) <
340 		    strlen(symname) + fn_size + 12) {
341 			nstrtab_size *= 2;
342 			nstrtabp = xrealloc(nstrtabp, nstrtab_size, fn,
343 			    "new string table");
344 			if (nstrtabp == NULL)
345 				goto bad;
346 		}
347 
348 		sp->st_name = htoxew(nstrtab_nextoff);
349 
350 		/* if it's a keeper or is undefined, don't rename it. */
351 		if (in_keep_list(symname) ||
352 		    (xe16toh(sp->st_shndx) == SHN_UNDEF)) {
353 			newent_len = sprintf(nstrtabp + nstrtab_nextoff,
354 			    "%s", symname) + 1;
355 		} else {
356 			newent_len = sprintf(nstrtabp + nstrtab_nextoff,
357 			    "_$$hide$$ %s %s", fn, symname) + 1;
358 		}
359 		nstrtab_nextoff += newent_len;
360 	}
361 	strtabshdr->sh_size = htoxew(nstrtab_nextoff);
362 
363 	/*
364 	 * write new tables to the file
365 	 */
366 	if (xwriteatoff(fd, shdrp, xewtoh(ehdr.e_shoff), shdrsize, fn) !=
367 	    shdrsize)
368 		goto bad;
369 	if (xwriteatoff(fd, symtabp, xewtoh(symtabshdr->sh_offset),
370 	    xewtoh(symtabshdr->sh_size), fn) != xewtoh(symtabshdr->sh_size))
371 		goto bad;
372 	/* write new symbol table strings */
373 	if ((size_t)xwriteatoff(fd, nstrtabp, xewtoh(strtabshdr->sh_offset),
374 	    xewtoh(strtabshdr->sh_size), fn) != xewtoh(strtabshdr->sh_size))
375 		goto bad;
376 
377 out:
378 	if (shdrp != NULL)
379 		free(shdrp);
380 	if (symtabp != NULL)
381 		free(symtabp);
382 	if (strtabp != NULL)
383 		free(strtabp);
384 	return (rv);
385 
386 bad:
387 	rv = 1;
388 	goto out;
389 }
390 
391 #endif /* include this size of ELF */
392