60c12c972c8ef2979beaac73486ce4d23ff763c0
[openwrt/openwrt.git] / openwrt / toolchain / sstrip / src / sstrip.c
1 /* http://www.muppetlabs.com/~breadbox/software/elfkickers.html */
2
3 /* sstrip: Copyright (C) 1999-2001 by Brian Raiter, under the GNU
4 * General Public License. No warranty. See COPYING for details.
5 *
6 * Aug 23, 2004 Hacked by Manuel Novoa III <mjn3@codepoet.org> to
7 * handle targets of different endianness and/or elf class, making
8 * it more useful in a cross-devel environment.
9 */
10
11 /* ============== original README ===================
12 *
13 * sstrip is a small utility that removes the contents at the end of an
14 * ELF file that are not part of the program's memory image.
15 *
16 * Most ELF executables are built with both a program header table and a
17 * section header table. However, only the former is required in order
18 * for the OS to load, link and execute a program. sstrip attempts to
19 * extract the ELF header, the program header table, and its contents,
20 * leaving everything else in the bit bucket. It can only remove parts of
21 * the file that occur at the end, after the parts to be saved. However,
22 * this almost always includes the section header table, and occasionally
23 * a few random sections that are not used when running a program.
24 *
25 * It should be noted that the GNU bfd library is (understandably)
26 * dependent on the section header table as an index to the file's
27 * contents. Thus, an executable file that has no section header table
28 * cannot be used with gdb, objdump, or any other program based upon the
29 * bfd library, at all. In fact, the program will not even recognize the
30 * file as a valid executable. (This limitation is noted in the source
31 * code comments for bfd, and is marked "FIXME", so this may change at
32 * some future date. However, I would imagine that it is a pretty
33 * low-priority item, as executables without a section header table are
34 * rare in the extreme.) This probably also explains why strip doesn't
35 * offer the option to do this.
36 *
37 * Shared library files may also have their section header table removed.
38 * Such a library will still function; however, it will no longer be
39 * possible for a compiler to link a new program against it.
40 *
41 * As an added bonus, sstrip also tries to removes trailing zero bytes
42 * from the end of the file. (This normally cannot be done with an
43 * executable that has a section header table.)
44 *
45 * sstrip is a very simplistic program. It depends upon the common
46 * practice of putting the parts of the file that contribute to the
47 * memory image at the front, and the remaining material at the end. This
48 * permits it to discard the latter material without affecting file
49 * offsets and memory addresses in what remains. Of course, the ELF
50 * standard permits files to be organized in almost any order, so if a
51 * pathological linker decided to put its section headers at the top,
52 * sstrip would be useless on such executables.
53 */
54
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <errno.h>
59 #include <unistd.h>
60 #include <fcntl.h>
61 #include <elf.h>
62
63 #ifdef __FreeBSD__
64 /**
65 * This seems to work on FreeBSD 5.3, should
66 * work on all newer versions as well. I have
67 * no idea if it will work on versions < 5.3
68 *
69 * Joe Estock (guru) <jestock at nutextonline.com>
70 */
71 #include <sys/endian.h>
72 #define bswap_64 __bswap64
73 #define bswap_32 __bswap32
74 #define bswap_16 __bswap16
75 #elif defined(__APPLE__)
76 #include <machine/endian.h>
77 #include <machine/byte_order.h>
78 #define __BYTE_ORDER BYTE_ORDER
79 #define __BIG_ENDIAN BIG_ENDIAN
80 #define bswap_16(x) NXSwapShort(x)
81 #define bswap_32(x) NXSwapInt(x)
82 #define bswap_64(x) NXSwapLongLong(x)
83 #else
84 #include <endian.h>
85 #include <byteswap.h>
86 #endif
87
88
89 #ifndef TRUE
90 #define TRUE 1
91 #define FALSE 0
92 #endif
93
94 /* The name of the program.
95 */
96 static char const *progname;
97
98 /* The name of the current file.
99 */
100 static char const *filename;
101
102
103 /* A simple error-handling function. FALSE is always returned for the
104 * convenience of the caller.
105 */
106 static int err(char const *errmsg)
107 {
108 fprintf(stderr, "%s: %s: %s\n", progname, filename, errmsg);
109 return FALSE;
110 }
111
112 /* A flag to signal the need for endian reversal.
113 */
114 static int do_reverse_endian;
115
116 /* Get a value from the elf header, compensating for endianness.
117 */
118 #define EGET(X) \
119 (__extension__ ({ \
120 uint64_t __res; \
121 if (!do_reverse_endian) { \
122 __res = (X); \
123 } else if (sizeof(X) == 1) { \
124 __res = (X); \
125 } else if (sizeof(X) == 2) { \
126 __res = bswap_16((X)); \
127 } else if (sizeof(X) == 4) { \
128 __res = bswap_32((X)); \
129 } else if (sizeof(X) == 8) { \
130 __res = bswap_64((X)); \
131 } else { \
132 fprintf(stderr, "%s: %s: EGET failed for size %d\n", \
133 progname, filename, sizeof(X)); \
134 exit(EXIT_FAILURE); \
135 } \
136 __res; \
137 }))
138
139 /* Set a value 'Y' in the elf header to 'X', compensating for endianness.
140 */
141 #define ESET(Y,X) \
142 do if (!do_reverse_endian) { \
143 Y = (X); \
144 } else if (sizeof(Y) == 1) { \
145 Y = (X); \
146 } else if (sizeof(Y) == 2) { \
147 Y = bswap_16((uint16_t)(X)); \
148 } else if (sizeof(Y) == 4) { \
149 Y = bswap_32((uint32_t)(X)); \
150 } else if (sizeof(Y) == 8) { \
151 Y = bswap_64((uint64_t)(X)); \
152 } else { \
153 fprintf(stderr, "%s: %s: ESET failed for size %d\n", \
154 progname, filename, sizeof(Y)); \
155 exit(EXIT_FAILURE); \
156 } while (0)
157
158
159 /* A macro for I/O errors: The given error message is used only when
160 * errno is not set.
161 */
162 #define ferr(msg) (err(errno ? strerror(errno) : (msg)))
163
164
165
166 #define HEADER_FUNCTIONS(CLASS) \
167 \
168 /* readelfheader() reads the ELF header into our global variable, and \
169 * checks to make sure that this is in fact a file that we should be \
170 * munging. \
171 */ \
172 static int readelfheader ## CLASS (int fd, Elf ## CLASS ## _Ehdr *ehdr) \
173 { \
174 if (read(fd, ((char *)ehdr)+EI_NIDENT, sizeof(*ehdr) - EI_NIDENT) \
175 != sizeof(*ehdr) - EI_NIDENT) \
176 return ferr("missing or incomplete ELF header."); \
177 \
178 /* Verify the sizes of the ELF header and the program segment \
179 * header table entries. \
180 */ \
181 if (EGET(ehdr->e_ehsize) != sizeof(Elf ## CLASS ## _Ehdr)) \
182 return err("unrecognized ELF header size."); \
183 if (EGET(ehdr->e_phentsize) != sizeof(Elf ## CLASS ## _Phdr)) \
184 return err("unrecognized program segment header size."); \
185 \
186 /* Finally, check the file type. \
187 */ \
188 if (EGET(ehdr->e_type) != ET_EXEC && EGET(ehdr->e_type) != ET_DYN) \
189 return err("not an executable or shared-object library."); \
190 \
191 return TRUE; \
192 } \
193 \
194 /* readphdrtable() loads the program segment header table into memory. \
195 */ \
196 static int readphdrtable ## CLASS (int fd, Elf ## CLASS ## _Ehdr const *ehdr, \
197 Elf ## CLASS ## _Phdr **phdrs) \
198 { \
199 size_t size; \
200 \
201 if (!EGET(ehdr->e_phoff) || !EGET(ehdr->e_phnum) \
202 ) return err("ELF file has no program header table."); \
203 \
204 size = EGET(ehdr->e_phnum) * sizeof **phdrs; \
205 if (!(*phdrs = malloc(size))) \
206 return err("Out of memory!"); \
207 \
208 errno = 0; \
209 if (read(fd, *phdrs, size) != (ssize_t)size) \
210 return ferr("missing or incomplete program segment header table."); \
211 \
212 return TRUE; \
213 } \
214 \
215 /* getmemorysize() determines the offset of the last byte of the file \
216 * that is referenced by an entry in the program segment header table. \
217 * (Anything in the file after that point is not used when the program \
218 * is executing, and thus can be safely discarded.) \
219 */ \
220 static int getmemorysize ## CLASS (Elf ## CLASS ## _Ehdr const *ehdr, \
221 Elf ## CLASS ## _Phdr const *phdrs, \
222 unsigned long *newsize) \
223 { \
224 Elf ## CLASS ## _Phdr const *phdr; \
225 unsigned long size, n; \
226 int i; \
227 \
228 /* Start by setting the size to include the ELF header and the \
229 * complete program segment header table. \
230 */ \
231 size = EGET(ehdr->e_phoff) + EGET(ehdr->e_phnum) * sizeof *phdrs; \
232 if (size < sizeof *ehdr) \
233 size = sizeof *ehdr; \
234 \
235 /* Then keep extending the size to include whatever data the \
236 * program segment header table references. \
237 */ \
238 for (i = 0, phdr = phdrs ; i < EGET(ehdr->e_phnum) ; ++i, ++phdr) { \
239 if (EGET(phdr->p_type) != PT_NULL) { \
240 n = EGET(phdr->p_offset) + EGET(phdr->p_filesz); \
241 if (n > size) \
242 size = n; \
243 } \
244 } \
245 \
246 *newsize = size; \
247 return TRUE; \
248 } \
249 \
250 /* modifyheaders() removes references to the section header table if \
251 * it was stripped, and reduces program header table entries that \
252 * included truncated bytes at the end of the file. \
253 */ \
254 static int modifyheaders ## CLASS (Elf ## CLASS ## _Ehdr *ehdr, \
255 Elf ## CLASS ## _Phdr *phdrs, \
256 unsigned long newsize) \
257 { \
258 Elf ## CLASS ## _Phdr *phdr; \
259 int i; \
260 \
261 /* If the section header table is gone, then remove all references \
262 * to it in the ELF header. \
263 */ \
264 if (EGET(ehdr->e_shoff) >= newsize) { \
265 ESET(ehdr->e_shoff,0); \
266 ESET(ehdr->e_shnum,0); \
267 ESET(ehdr->e_shentsize,0); \
268 ESET(ehdr->e_shstrndx,0); \
269 } \
270 \
271 /* The program adjusts the file size of any segment that was \
272 * truncated. The case of a segment being completely stripped out \
273 * is handled separately. \
274 */ \
275 for (i = 0, phdr = phdrs ; i < EGET(ehdr->e_phnum) ; ++i, ++phdr) { \
276 if (EGET(phdr->p_offset) >= newsize) { \
277 ESET(phdr->p_offset,newsize); \
278 ESET(phdr->p_filesz,0); \
279 } else if (EGET(phdr->p_offset) + EGET(phdr->p_filesz) > newsize) { \
280 newsize -= EGET(phdr->p_offset); \
281 ESET(phdr->p_filesz, newsize); \
282 } \
283 } \
284 \
285 return TRUE; \
286 } \
287 \
288 /* commitchanges() writes the new headers back to the original file \
289 * and sets the file to its new size. \
290 */ \
291 static int commitchanges ## CLASS (int fd, Elf ## CLASS ## _Ehdr const *ehdr, \
292 Elf ## CLASS ## _Phdr *phdrs, \
293 unsigned long newsize) \
294 { \
295 size_t n; \
296 \
297 /* Save the changes to the ELF header, if any. \
298 */ \
299 if (lseek(fd, 0, SEEK_SET)) \
300 return ferr("could not rewind file"); \
301 errno = 0; \
302 if (write(fd, ehdr, sizeof *ehdr) != sizeof *ehdr) \
303 return err("could not modify file"); \
304 \
305 /* Save the changes to the program segment header table, if any. \
306 */ \
307 if (lseek(fd, EGET(ehdr->e_phoff), SEEK_SET) == (off_t)-1) { \
308 err("could not seek in file."); \
309 goto warning; \
310 } \
311 n = EGET(ehdr->e_phnum) * sizeof *phdrs; \
312 if (write(fd, phdrs, n) != (ssize_t)n) { \
313 err("could not write to file"); \
314 goto warning; \
315 } \
316 \
317 /* Eleventh-hour sanity check: don't truncate before the end of \
318 * the program segment header table. \
319 */ \
320 if (newsize < EGET(ehdr->e_phoff) + n) \
321 newsize = EGET(ehdr->e_phoff) + n; \
322 \
323 /* Chop off the end of the file. \
324 */ \
325 if (ftruncate(fd, newsize)) { \
326 err("could not resize file"); \
327 goto warning; \
328 } \
329 \
330 return TRUE; \
331 \
332 warning: \
333 return err("ELF file may have been corrupted!"); \
334 }
335
336
337 /* First elements of Elf32_Ehdr and Elf64_Ehdr are common.
338 */
339 static int readelfheaderident(int fd, Elf32_Ehdr *ehdr)
340 {
341 errno = 0;
342 if (read(fd, ehdr, EI_NIDENT) != EI_NIDENT)
343 return ferr("missing or incomplete ELF header.");
344
345 /* Check the ELF signature.
346 */
347 if (!(ehdr->e_ident[EI_MAG0] == ELFMAG0 &&
348 ehdr->e_ident[EI_MAG1] == ELFMAG1 &&
349 ehdr->e_ident[EI_MAG2] == ELFMAG2 &&
350 ehdr->e_ident[EI_MAG3] == ELFMAG3))
351 {
352 err("missing ELF signature.");
353 return -1;
354 }
355
356 /* Compare the file's class and endianness with the program's.
357 */
358 #if __BYTE_ORDER == __LITTLE_ENDIAN
359 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
360 do_reverse_endian = 0;
361 } else if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
362 /* fprintf(stderr, "ELF file has different endianness.\n"); */
363 do_reverse_endian = 1;
364 }
365 #elif __BYTE_ORDER == __BIG_ENDIAN
366 if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB) {
367 /* fprintf(stderr, "ELF file has different endianness.\n"); */
368 do_reverse_endian = 1;
369 } else if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
370 do_reverse_endian = 0;
371 }
372 #else
373 #error unkown endianness
374 #endif
375 else {
376 err("Unsupported endianness");
377 return -1;
378 }
379
380 /* Check the target architecture.
381 */
382 /* if (EGET(ehdr->e_machine) != ELF_ARCH) { */
383 /* /\* return err("ELF file created for different architecture."); *\/ */
384 /* fprintf(stderr, "ELF file created for different architecture.\n"); */
385 /* } */
386 return ehdr->e_ident[EI_CLASS];
387 }
388
389
390 HEADER_FUNCTIONS(32)
391
392 HEADER_FUNCTIONS(64)
393
394 /* truncatezeros() examines the bytes at the end of the file's
395 * size-to-be, and reduces the size to exclude any trailing zero
396 * bytes.
397 */
398 static int truncatezeros(int fd, unsigned long *newsize)
399 {
400 unsigned char contents[1024];
401 unsigned long size, n;
402
403 size = *newsize;
404 do {
405 n = sizeof contents;
406 if (n > size)
407 n = size;
408 if (lseek(fd, size - n, SEEK_SET) == (off_t)-1)
409 return ferr("cannot seek in file.");
410 if (read(fd, contents, n) != (ssize_t)n)
411 return ferr("cannot read file contents");
412 while (n && !contents[--n])
413 --size;
414 } while (size && !n);
415
416 /* Sanity check.
417 */
418 if (!size)
419 return err("ELF file is completely blank!");
420
421 *newsize = size;
422 return TRUE;
423 }
424
425 /* main() loops over the cmdline arguments, leaving all the real work
426 * to the other functions.
427 */
428 int main(int argc, char *argv[])
429 {
430 int fd;
431 union {
432 Elf32_Ehdr ehdr32;
433 Elf64_Ehdr ehdr64;
434 } e;
435 union {
436 Elf32_Phdr *phdrs32;
437 Elf64_Phdr *phdrs64;
438 } p;
439 unsigned long newsize;
440 char **arg;
441 int failures = 0;
442
443 if (argc < 2 || argv[1][0] == '-') {
444 printf("Usage: sstrip FILE...\n"
445 "sstrip discards all nonessential bytes from an executable.\n\n"
446 "Version 2.0-X Copyright (C) 2000,2001 Brian Raiter.\n"
447 "Cross-devel hacks Copyright (C) 2004 Manuel Novoa III.\n"
448 "This program is free software, licensed under the GNU\n"
449 "General Public License. There is absolutely no warranty.\n");
450 return EXIT_SUCCESS;
451 }
452
453 progname = argv[0];
454
455 for (arg = argv + 1 ; *arg != NULL ; ++arg) {
456 filename = *arg;
457
458 fd = open(*arg, O_RDWR);
459 if (fd < 0) {
460 ferr("can't open");
461 ++failures;
462 continue;
463 }
464
465 switch (readelfheaderident(fd, &e.ehdr32)) {
466 case ELFCLASS32:
467 if (!(readelfheader32(fd, &e.ehdr32) &&
468 readphdrtable32(fd, &e.ehdr32, &p.phdrs32) &&
469 getmemorysize32(&e.ehdr32, p.phdrs32, &newsize) &&
470 truncatezeros(fd, &newsize) &&
471 modifyheaders32(&e.ehdr32, p.phdrs32, newsize) &&
472 commitchanges32(fd, &e.ehdr32, p.phdrs32, newsize)))
473 ++failures;
474 break;
475 case ELFCLASS64:
476 if (!(readelfheader64(fd, &e.ehdr64) &&
477 readphdrtable64(fd, &e.ehdr64, &p.phdrs64) &&
478 getmemorysize64(&e.ehdr64, p.phdrs64, &newsize) &&
479 truncatezeros(fd, &newsize) &&
480 modifyheaders64(&e.ehdr64, p.phdrs64, newsize) &&
481 commitchanges64(fd, &e.ehdr64, p.phdrs64, newsize)))
482 ++failures;
483 break;
484 default:
485 ++failures;
486 break;
487 }
488 close(fd);
489 }
490
491 return failures ? EXIT_FAILURE : EXIT_SUCCESS;
492 }