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