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