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