Home | History | Annotate | Line # | Download | only in elf2bb
elf2bb.c revision 1.13
      1 /*	$NetBSD: elf2bb.c,v 1.13 2006/06/15 23:06:48 gdamore Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996,2006 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Ignatios Souvatzis.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #if HAVE_NBTOOL_CONFIG_H
     40 #include "nbtool_config.h"
     41 #endif
     42 
     43 #include <sys/types.h>
     44 
     45 #include <err.h>
     46 #include <fcntl.h>
     47 #include <stdio.h>
     48 #include <stdlib.h>
     49 #include <string.h>
     50 #include <unistd.h>
     51 
     52 #include <sys/mman.h>		/* of the machine we're running on */
     53 
     54 #ifndef HAVE_NBTOOL_CONFIG_H
     55 #include <sys/endian.h>		/* of the machine we're running on */
     56 #endif
     57 
     58 #include <sys/exec_elf.h>	/* TARGET */
     59 #ifndef R_68K_32		/* XXX host not m68k XXX */
     60 #define	R_68K_32	1
     61 #define	R_68K_PC32	4
     62 #define	R_68K_PC16	5
     63 #endif
     64 
     65 #include "elf2bb.h"
     66 #include "chksum.h"
     67 
     68 void usage(void);
     69 int intcmp(const void *, const void *);
     70 int main(int argc, char *argv[]);
     71 
     72 #ifdef DEBUG
     73 #define dprintf(x) if (debug) printf x
     74 #else
     75 #define dprintf(x)
     76 #endif
     77 int debug;
     78 
     79 #define BBSIZE 8192
     80 
     81 char *progname;
     82 int bbsize = BBSIZE;
     83 u_int8_t *buffer;
     84 u_int32_t *relbuf;
     85 	/* can't have more relocs than that*/
     86 
     87 int
     88 intcmp(const void *i, const void *j)
     89 {
     90 	int r;
     91 
     92 	r = (*(u_int32_t *)i) < (*(u_int32_t *)j);
     93 
     94 	return 2*r-1;
     95 }
     96 
     97 int
     98 main(int argc, char *argv[])
     99 {
    100 	int ifd, ofd;
    101 	u_int mid, flags, magic;
    102 	caddr_t image;
    103 	Elf32_Ehdr *eh;
    104 	Elf32_Shdr *sh;
    105 	char *shstrtab;
    106 	Elf32_Sym *symtab;
    107 	char *strtab;
    108 	int eval(Elf32_Sym *, u_int32_t *);
    109 	u_int32_t *lptr;
    110 	int i, l, delta;
    111 	u_int8_t *rpo;
    112 	u_int32_t oldaddr, addrdiff;
    113 	u_int32_t tsz, dsz, bsz, trsz, drsz, entry, relver;
    114 	u_int32_t pcrelsz, r32sz;
    115 	int sumsize = 16;
    116 	int c;
    117 	u_int32_t *sect_offset;
    118 	int undefsyms;
    119 	uint32_t tmp32;
    120 	uint16_t tmp16;
    121 
    122 	progname = argv[0];
    123 
    124 	/* insert getopt here, if needed */
    125 	while ((c = getopt(argc, argv, "dFS")) != -1)
    126 	switch(c) {
    127 	case 'F':
    128 		sumsize = 2;
    129 		break;
    130 	case 'S':
    131 		/* Dynamically size second-stage boot */
    132 		sumsize = 0;
    133 		break;
    134 	case 'd':
    135 		debug = 1;
    136 		break;
    137 	default:
    138 		usage();
    139 	}
    140 	argv += optind;
    141 	argc -= optind;
    142 
    143 	if (argc < 2)
    144 		usage();
    145 
    146 	ifd = open(argv[0], O_RDONLY, 0);
    147 	if (ifd < 0)
    148 		err(1, "Can't open %s", argv[0]);
    149 
    150 	image = mmap(0, 65536, PROT_READ, MAP_FILE|MAP_PRIVATE, ifd, 0);
    151 	if (image == 0)
    152 		err(1, "Can't mmap %s", argv[1]);
    153 
    154 	eh = (Elf32_Ehdr *)image; /* XXX endianness */
    155 
    156 	dprintf(("%04x sections, offset %08x\n", htobe16(eh->e_shnum), htobe32(eh->e_shoff)));
    157 	if (htobe16(eh->e_type) != ET_REL)
    158 		errx(1, "%s isn't a relocatable file, type=%d",
    159 		    argv[0], htobe16(eh->e_type));
    160 	if (htobe16(eh->e_machine) != EM_68K)
    161 		errx(1, "%s isn't M68K, machine=%d", argv[0],
    162 		    htobe16(eh->e_machine));
    163 
    164 	/* Calculate sizes from section headers. */
    165 	tsz = dsz = bsz = trsz = pcrelsz = r32sz = 0;
    166 	sh = (Elf32_Shdr *)(image + htobe32(eh->e_shoff));
    167 	shstrtab = (char *)(image + htobe32(sh[htobe16(eh->e_shstrndx)].sh_offset));
    168 	symtab = NULL;	/*XXX*/
    169 	strtab = NULL;	/*XXX*/
    170 	dprintf(("    name                      type     flags    addr     offset   size     align\n"));
    171 	for (i = 0; i < htobe16(eh->e_shnum); ++i) {
    172 		u_int32_t sh_size;
    173 
    174 		dprintf( ("%2d: %08x %-16s %08x %08x %08x %08x %08x %08x\n", i,
    175 		    htobe32(sh[i].sh_name), shstrtab + htobe32(sh[i].sh_name),
    176 		    htobe32(sh[i].sh_type),
    177 		    htobe32(sh[i].sh_flags), htobe32(sh[i].sh_addr),
    178 		    htobe32(sh[i].sh_offset), htobe32(sh[i].sh_size),
    179 		    htobe32(sh[i].sh_addralign)));
    180 		sh_size = (htobe32(sh[i].sh_size) + htobe32(sh[i].sh_addralign) - 1) &
    181 		    -htobe32(sh[i].sh_addralign);
    182 		/* If section allocates memory, add to text, data, or bss size. */
    183 		if (htobe32(sh[i].sh_flags) & SHF_ALLOC) {
    184 			if (htobe32(sh[i].sh_type) == SHT_PROGBITS) {
    185 				if (htobe32(sh[i].sh_flags) & SHF_WRITE)
    186 					dsz += sh_size;
    187 				else
    188 					tsz += sh_size;
    189 			} else
    190 				bsz += sh_size;
    191 		/* If it's relocations, add to relocation count */
    192 		} else if (htobe32(sh[i].sh_type) == SHT_RELA) {
    193 			trsz += htobe32(sh[i].sh_size);
    194 		}
    195 		/* Check for SHT_REL? */
    196 		/* Get symbol table location. */
    197 		else if (htobe32(sh[i].sh_type) == SHT_SYMTAB) {
    198 			symtab = (Elf32_Sym *)(image + htobe32(sh[i].sh_offset));
    199 		} else if (strcmp(".strtab", shstrtab + htobe32(sh[i].sh_name)) == 0) {
    200 			strtab = image + htobe32(sh[i].sh_offset);
    201 		}
    202 	}
    203 	dprintf(("tsz = 0x%x, dsz = 0x%x, bsz = 0x%x, total 0x%x\n",
    204 	    tsz, dsz, bsz, tsz + dsz + bsz));
    205 
    206 	if (trsz == 0)
    207 		errx(1, "%s has no relocation records.", argv[0]);
    208 
    209 	dprintf(("%d relocs\n", trsz/12));
    210 
    211 	if (sumsize == 0) {
    212 		/*
    213 		 * XXX overly cautious, but this guarantees that 16bit
    214 		 * pc offsets and our relocs always work.
    215 		 */
    216 		bbsize = 32768;
    217 		if (bbsize < (tsz + dsz + bsz)) {
    218 			err(1, "%s: too big.", argv[0]);
    219 		}
    220 		sumsize = bbsize / 512;
    221 	}
    222 
    223 	buffer = malloc(bbsize);
    224 	relbuf = (u_int32_t *)malloc(bbsize);
    225 	if (buffer == NULL || relbuf == NULL)
    226 		err(1, "Unable to allocate memory\n");
    227 
    228 	/*
    229 	 * We have one contiguous area allocated by the ROM to us.
    230 	 */
    231 	if (tsz+dsz+bsz > bbsize)
    232 		errx(1, "%s: resulting image too big %d+%d+%d=%d", argv[0],
    233 		    tsz, dsz, bsz, tsz + dsz + bsz);
    234 
    235 	memset(buffer, 0, bbsize);
    236 
    237 	/* Allocate and load loadable sections */
    238 	sect_offset = (u_int32_t *)malloc(htobe16(eh->e_shnum) * sizeof(u_int32_t));
    239 	for (i = 0, l = 0; i < htobe16(eh->e_shnum); ++i) {
    240 		if (htobe32(sh[i].sh_flags) & SHF_ALLOC) {
    241 			dprintf(("vaddr 0x%04x size 0x%04x offset 0x%04x section %s\n",
    242 			    l, htobe32(sh[i].sh_size), htobe32(sh[i].sh_offset),
    243 			    shstrtab + htobe32(sh[i].sh_name)));
    244 			if (htobe32(sh[i].sh_type) == SHT_PROGBITS)
    245 				memcpy(buffer + l, image + htobe32(sh[i].sh_offset),
    246 				    htobe32(sh[i].sh_size));
    247 			sect_offset[i] = l;
    248 			l += (htobe32(sh[i].sh_size) + htobe32(sh[i].sh_addralign) - 1) &
    249 			    -htobe32(sh[i].sh_addralign);
    250 		}
    251 	}
    252 
    253 	/*
    254 	 * Hm. This tool REALLY should understand more than one
    255 	 * relocator version. For now, check that the relocator at
    256 	 * the image start does understand what we output.
    257 	 */
    258 	relver = htobe32(*(u_int32_t *)(buffer + 4));
    259 	switch (relver) {
    260 	default:
    261 		errx(1, "%s: unrecognized relocator version %d",
    262 			argv[0], relver);
    263 		/*NOTREACHED*/
    264 
    265 	case RELVER_RELATIVE_BYTES:
    266 		rpo = buffer + bbsize - 1;
    267 		delta = -1;
    268 		break;
    269 
    270 	case RELVER_RELATIVE_BYTES_FORWARD:
    271 		rpo = buffer + tsz + dsz;
    272 		delta = +1;
    273 		*(u_int16_t *)(buffer + 14) = htobe16(tsz + dsz);
    274 		break;
    275 	}
    276 
    277 	if (symtab == NULL)
    278 		errx(1, "No symbol table found");
    279 	/*
    280 	 * Link sections and generate relocation data
    281 	 * Nasty:  .text, .rodata, .data, .bss sections are not linked
    282 	 *         Symbol table values relative to start of sections.
    283 	 * For each relocation entry:
    284 	 *    Symbol value needs to be calculated: value + section offset
    285 	 *    Image data adjusted to calculated value of symbol + addend
    286 	 *    Add relocation table entry for 32-bit relocatable values
    287 	 *    PC-relative entries will be absolute and don't need relocation
    288 	 */
    289 	undefsyms = 0;
    290 	for (i = 0; i < htobe16(eh->e_shnum); ++i) {
    291 		int n;
    292 		Elf32_Rela *ra;
    293 		u_int8_t *base;
    294 
    295 		if (htobe32(sh[i].sh_type) != SHT_RELA)
    296 			continue;
    297 		base = NULL;
    298 		if (strncmp(shstrtab + htobe32(sh[i].sh_name), ".rela", 5) != 0)
    299 			err(1, "bad relocation section name %s", shstrtab +
    300 			    htobe32(sh[i].sh_name));
    301 		for (n = 0; n < htobe16(eh->e_shnum); ++n) {
    302 			if (strcmp(shstrtab + htobe32(sh[i].sh_name) + 5, shstrtab +
    303 			    htobe32(sh[n].sh_name)) != 0)
    304 				continue;
    305 			base = buffer + sect_offset[n];
    306 			break;
    307 		}
    308 		if (base == NULL)
    309 			errx(1, "Can't find section for reloc %s", shstrtab +
    310 			    htobe32(sh[i].sh_name));
    311 		ra = (Elf32_Rela *)(image + htobe32(sh[i].sh_offset));
    312 		for (n = 0; n < htobe32(sh[i].sh_size); n += sizeof(Elf32_Rela), ++ra) {
    313 			Elf32_Sym *s;
    314 			int value;
    315 
    316 			s = &symtab[ELF32_R_SYM(htobe32(ra->r_info))];
    317 			if (s->st_shndx == ELF_SYM_UNDEFINED) {
    318 				fprintf(stderr, "Undefined symbol: %s\n",
    319 				    strtab + s->st_name);
    320 				++undefsyms;
    321 			}
    322 			value = htobe32(ra->r_addend) + eval(s, sect_offset);
    323 			dprintf(("reloc %04x info %04x (type %d sym %d) add 0x%x val %x\n",
    324 			    htobe32(ra->r_offset), htobe32(ra->r_info),
    325 			    ELF32_R_TYPE(htobe32(ra->r_info)),
    326 			    ELF32_R_SYM(htobe32(ra->r_info)),
    327 			    htobe32(ra->r_addend), value));
    328 			switch (ELF32_R_TYPE(htobe32(ra->r_info))) {
    329 			case R_68K_32:
    330 				tmp32 = htobe32(value);
    331 				memcpy(base + htobe32(ra->r_offset), &tmp32,
    332 				       sizeof(tmp32));
    333 				relbuf[r32sz++] = (base - buffer) + htobe32(ra->r_offset);
    334 				break;
    335 			case R_68K_PC32:
    336 				++pcrelsz;
    337 				tmp32 = htobe32(value - htobe32(ra->r_offset));
    338 				memcpy(base + htobe32(ra->r_offset), &tmp32,
    339 				       sizeof(tmp32));
    340 				break;
    341 			case R_68K_PC16:
    342 				++pcrelsz;
    343 				value -= htobe32(ra->r_offset);
    344 				if (value < -0x8000 || value > 0x7fff)
    345 					errx(1,  "PC-relative offset out of range: %x\n",
    346 					    value);
    347 				tmp16 = htobe16(value);
    348 				memcpy(base + htobe32(ra->r_offset), &tmp16,
    349 				       sizeof(tmp16));
    350 				break;
    351 			default:
    352 				errx(1, "Relocation type %d not supported",
    353 				    ELF32_R_TYPE(htobe32(ra->r_info)));
    354 			}
    355 		}
    356 	}
    357 	dprintf(("%d PC-relative relocations, %d 32-bit relocations\n",
    358 	    pcrelsz, r32sz));
    359 	printf("%d absolute reloc%s found, ", r32sz, r32sz==1?"":"s");
    360 
    361 	i = r32sz;
    362 	if (i > 1)
    363 		heapsort(relbuf, r32sz, 4, intcmp);
    364 
    365 	oldaddr = 0;
    366 
    367 	for (--i; i>=0; --i) {
    368 		dprintf(("0x%04x: ", relbuf[i]));
    369 		lptr = (u_int32_t *)&buffer[relbuf[i]];
    370 		addrdiff = relbuf[i] - oldaddr;
    371 		dprintf(("(0x%04x, 0x%04x): ", *lptr, addrdiff));
    372 		if (addrdiff > 255) {
    373 			*rpo = 0;
    374 			if (delta > 0) {
    375 				++rpo;
    376 				*rpo++ = (relbuf[i] >> 8) & 0xff;
    377 				*rpo++ = relbuf[i] & 0xff;
    378 				dprintf(("%02x%02x%02x\n",
    379 				    rpo[-3], rpo[-2], rpo[-1]));
    380 			} else {
    381 				*--rpo = relbuf[i] & 0xff;
    382 				*--rpo = (relbuf[i] >> 8) & 0xff;
    383 				--rpo;
    384 				dprintf(("%02x%02x%02x\n",
    385 				    rpo[0], rpo[1], rpo[2]));
    386 			}
    387 		} else {
    388 			*rpo = addrdiff;
    389 			dprintf(("%02x\n", *rpo));
    390 			rpo += delta;
    391 		}
    392 
    393 		oldaddr = relbuf[i];
    394 
    395 		if (delta < 0 ? rpo <= buffer+tsz+dsz
    396 		    : rpo >= buffer + bbsize)
    397 			errx(1, "Relocs don't fit.");
    398 	}
    399 	*rpo = 0; rpo += delta;
    400 	*rpo = 0; rpo += delta;
    401 	*rpo = 0; rpo += delta;
    402 
    403 	printf("using %d bytes, %d bytes remaining.\n", delta > 0 ?
    404 	    rpo-buffer-tsz-dsz : buffer+bbsize-rpo, delta > 0 ?
    405 	    buffer + bbsize - rpo : rpo - buffer - tsz - dsz);
    406 	/*
    407 	 * RELOCs must fit into the bss area.
    408 	 */
    409 	if (delta < 0 ? rpo <= buffer+tsz+dsz
    410 	    : rpo >= buffer + bbsize)
    411 		errx(1, "Relocs don't fit.");
    412 
    413 	if (undefsyms > 0)
    414 		errx(1, "Undefined symbols referenced");
    415 
    416 	((u_int32_t *)buffer)[1] = 0;
    417 	((u_int32_t *)buffer)[1] =
    418 	    htobe32((0xffffffff - chksum((u_int32_t *)buffer, sumsize * 512 / 4)));
    419 
    420 	ofd = open(argv[1], O_CREAT|O_WRONLY, 0644);
    421 	if (ofd < 0)
    422 		err(1, "Can't open %s", argv[1]);
    423 
    424 	if (write(ofd, buffer, bbsize) != bbsize)
    425 		err(1, "Writing output file");
    426 
    427 	exit(0);
    428 }
    429 
    430 void
    431 usage(void)
    432 {
    433 	fprintf(stderr, "Usage: %s [-F] bootprog bootprog.bin\n",
    434 	    progname);
    435 	exit(1);
    436 	/* NOTREACHED */
    437 }
    438 
    439 int
    440 eval(Elf32_Sym *s, u_int32_t *o)
    441 {
    442 	int value;
    443 
    444 	value = htobe32(s->st_value);
    445 	if (htobe16(s->st_shndx) < 0xf000)
    446 		value += o[htobe16(s->st_shndx)];
    447 	else
    448 		printf("eval: %x\n", htobe16(s->st_shndx));
    449 	return value;
    450 }
    451