Home | History | Annotate | Line # | Download | only in elf2bb
elf2bb.c revision 1.12
      1 /*	$NetBSD: elf2bb.c,v 1.12 2006/01/24 20:04:05 is 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 #include <sys/endian.h>		/* of the machine we're running on */
     54 
     55 #include <sys/exec_elf.h>	/* TARGET */
     56 #ifndef R_68K_32		/* XXX host not m68k XXX */
     57 #define	R_68K_32	1
     58 #define	R_68K_PC32	4
     59 #define	R_68K_PC16	5
     60 #endif
     61 
     62 #include "elf2bb.h"
     63 #include "chksum.h"
     64 
     65 void usage(void);
     66 int intcmp(const void *, const void *);
     67 int main(int argc, char *argv[]);
     68 
     69 #ifdef DEBUG
     70 #define dprintf(x) if (debug) printf x
     71 #else
     72 #define dprintf(x)
     73 #endif
     74 int debug;
     75 
     76 #define BBSIZE 8192
     77 
     78 char *progname;
     79 int bbsize = BBSIZE;
     80 u_int8_t *buffer;
     81 u_int32_t *relbuf;
     82 	/* can't have more relocs than that*/
     83 
     84 int
     85 intcmp(const void *i, const void *j)
     86 {
     87 	int r;
     88 
     89 	r = (*(u_int32_t *)i) < (*(u_int32_t *)j);
     90 
     91 	return 2*r-1;
     92 }
     93 
     94 int
     95 main(int argc, char *argv[])
     96 {
     97 	int ifd, ofd;
     98 	u_int mid, flags, magic;
     99 	caddr_t image;
    100 	Elf32_Ehdr *eh;
    101 	Elf32_Shdr *sh;
    102 	char *shstrtab;
    103 	Elf32_Sym *symtab;
    104 	char *strtab;
    105 	int eval(Elf32_Sym *, u_int32_t *);
    106 	u_int32_t *lptr;
    107 	int i, l, delta;
    108 	u_int8_t *rpo;
    109 	u_int32_t oldaddr, addrdiff;
    110 	u_int32_t tsz, dsz, bsz, trsz, drsz, entry, relver;
    111 	u_int32_t pcrelsz, r32sz;
    112 	int sumsize = 16;
    113 	int c;
    114 	u_int32_t *sect_offset;
    115 	int undefsyms;
    116 	uint32_t tmp32;
    117 	uint16_t tmp16;
    118 
    119 	progname = argv[0];
    120 
    121 	/* insert getopt here, if needed */
    122 	while ((c = getopt(argc, argv, "dFS")) != -1)
    123 	switch(c) {
    124 	case 'F':
    125 		sumsize = 2;
    126 		break;
    127 	case 'S':
    128 		/* Dynamically size second-stage boot */
    129 		sumsize = 0;
    130 		break;
    131 	case 'd':
    132 		debug = 1;
    133 		break;
    134 	default:
    135 		usage();
    136 	}
    137 	argv += optind;
    138 	argc -= optind;
    139 
    140 	if (argc < 2)
    141 		usage();
    142 
    143 	ifd = open(argv[0], O_RDONLY, 0);
    144 	if (ifd < 0)
    145 		err(1, "Can't open %s", argv[0]);
    146 
    147 	image = mmap(0, 65536, PROT_READ, MAP_FILE|MAP_PRIVATE, ifd, 0);
    148 	if (image == 0)
    149 		err(1, "Can't mmap %s", argv[1]);
    150 
    151 	eh = (Elf32_Ehdr *)image; /* XXX endianness */
    152 
    153 	dprintf(("%04x sections, offset %08x\n", htobe16(eh->e_shnum), htobe32(eh->e_shoff)));
    154 	if (htobe16(eh->e_type) != ET_REL)
    155 		errx(1, "%s isn't a relocatable file, type=%d",
    156 		    argv[0], htobe16(eh->e_type));
    157 	if (htobe16(eh->e_machine) != EM_68K)
    158 		errx(1, "%s isn't M68K, machine=%d", argv[0],
    159 		    htobe16(eh->e_machine));
    160 
    161 	/* Calculate sizes from section headers. */
    162 	tsz = dsz = bsz = trsz = pcrelsz = r32sz = 0;
    163 	sh = (Elf32_Shdr *)(image + htobe32(eh->e_shoff));
    164 	shstrtab = (char *)(image + htobe32(sh[htobe16(eh->e_shstrndx)].sh_offset));
    165 	symtab = NULL;	/*XXX*/
    166 	strtab = NULL;	/*XXX*/
    167 	dprintf(("    name                      type     flags    addr     offset   size     align\n"));
    168 	for (i = 0; i < htobe16(eh->e_shnum); ++i) {
    169 		u_int32_t sh_size;
    170 
    171 		dprintf( ("%2d: %08x %-16s %08x %08x %08x %08x %08x %08x\n", i,
    172 		    htobe32(sh[i].sh_name), shstrtab + htobe32(sh[i].sh_name),
    173 		    htobe32(sh[i].sh_type),
    174 		    htobe32(sh[i].sh_flags), htobe32(sh[i].sh_addr),
    175 		    htobe32(sh[i].sh_offset), htobe32(sh[i].sh_size),
    176 		    htobe32(sh[i].sh_addralign)));
    177 		sh_size = (htobe32(sh[i].sh_size) + htobe32(sh[i].sh_addralign) - 1) &
    178 		    -htobe32(sh[i].sh_addralign);
    179 		/* If section allocates memory, add to text, data, or bss size. */
    180 		if (htobe32(sh[i].sh_flags) & SHF_ALLOC) {
    181 			if (htobe32(sh[i].sh_type) == SHT_PROGBITS) {
    182 				if (htobe32(sh[i].sh_flags) & SHF_WRITE)
    183 					dsz += sh_size;
    184 				else
    185 					tsz += sh_size;
    186 			} else
    187 				bsz += sh_size;
    188 		/* If it's relocations, add to relocation count */
    189 		} else if (htobe32(sh[i].sh_type) == SHT_RELA) {
    190 			trsz += htobe32(sh[i].sh_size);
    191 		}
    192 		/* Check for SHT_REL? */
    193 		/* Get symbol table location. */
    194 		else if (htobe32(sh[i].sh_type) == SHT_SYMTAB) {
    195 			symtab = (Elf32_Sym *)(image + htobe32(sh[i].sh_offset));
    196 		} else if (strcmp(".strtab", shstrtab + htobe32(sh[i].sh_name)) == 0) {
    197 			strtab = image + htobe32(sh[i].sh_offset);
    198 		}
    199 	}
    200 	dprintf(("tsz = 0x%x, dsz = 0x%x, bsz = 0x%x, total 0x%x\n",
    201 	    tsz, dsz, bsz, tsz + dsz + bsz));
    202 
    203 	if (trsz == 0)
    204 		errx(1, "%s has no relocation records.", argv[0]);
    205 
    206 	dprintf(("%d relocs\n", trsz/12));
    207 
    208 	if (sumsize == 0) {
    209 		/*
    210 		 * XXX overly cautious, but this guarantees that 16bit
    211 		 * pc offsets and our relocs always work.
    212 		 */
    213 		bbsize = 32768;
    214 		if (bbsize < (tsz + dsz + bsz)) {
    215 			err(1, "%s: too big.", argv[0]);
    216 		}
    217 		sumsize = bbsize / 512;
    218 	}
    219 
    220 	buffer = malloc(bbsize);
    221 	relbuf = (u_int32_t *)malloc(bbsize);
    222 	if (buffer == NULL || relbuf == NULL)
    223 		err(1, "Unable to allocate memory\n");
    224 
    225 	/*
    226 	 * We have one contiguous area allocated by the ROM to us.
    227 	 */
    228 	if (tsz+dsz+bsz > bbsize)
    229 		errx(1, "%s: resulting image too big %d+%d+%d=%d", argv[0],
    230 		    tsz, dsz, bsz, tsz + dsz + bsz);
    231 
    232 	memset(buffer, 0, bbsize);
    233 
    234 	/* Allocate and load loadable sections */
    235 	sect_offset = (u_int32_t *)malloc(htobe16(eh->e_shnum) * sizeof(u_int32_t));
    236 	for (i = 0, l = 0; i < htobe16(eh->e_shnum); ++i) {
    237 		if (htobe32(sh[i].sh_flags) & SHF_ALLOC) {
    238 			dprintf(("vaddr 0x%04x size 0x%04x offset 0x%04x section %s\n",
    239 			    l, htobe32(sh[i].sh_size), htobe32(sh[i].sh_offset),
    240 			    shstrtab + htobe32(sh[i].sh_name)));
    241 			if (htobe32(sh[i].sh_type) == SHT_PROGBITS)
    242 				memcpy(buffer + l, image + htobe32(sh[i].sh_offset),
    243 				    htobe32(sh[i].sh_size));
    244 			sect_offset[i] = l;
    245 			l += (htobe32(sh[i].sh_size) + htobe32(sh[i].sh_addralign) - 1) &
    246 			    -htobe32(sh[i].sh_addralign);
    247 		}
    248 	}
    249 
    250 	/*
    251 	 * Hm. This tool REALLY should understand more than one
    252 	 * relocator version. For now, check that the relocator at
    253 	 * the image start does understand what we output.
    254 	 */
    255 	relver = htobe32(*(u_int32_t *)(buffer + 4));
    256 	switch (relver) {
    257 	default:
    258 		errx(1, "%s: unrecognized relocator version %d",
    259 			argv[0], relver);
    260 		/*NOTREACHED*/
    261 
    262 	case RELVER_RELATIVE_BYTES:
    263 		rpo = buffer + bbsize - 1;
    264 		delta = -1;
    265 		break;
    266 
    267 	case RELVER_RELATIVE_BYTES_FORWARD:
    268 		rpo = buffer + tsz + dsz;
    269 		delta = +1;
    270 		*(u_int16_t *)(buffer + 14) = htobe16(tsz + dsz);
    271 		break;
    272 	}
    273 
    274 	if (symtab == NULL)
    275 		errx(1, "No symbol table found");
    276 	/*
    277 	 * Link sections and generate relocation data
    278 	 * Nasty:  .text, .rodata, .data, .bss sections are not linked
    279 	 *         Symbol table values relative to start of sections.
    280 	 * For each relocation entry:
    281 	 *    Symbol value needs to be calculated: value + section offset
    282 	 *    Image data adjusted to calculated value of symbol + addend
    283 	 *    Add relocation table entry for 32-bit relocatable values
    284 	 *    PC-relative entries will be absolute and don't need relocation
    285 	 */
    286 	undefsyms = 0;
    287 	for (i = 0; i < htobe16(eh->e_shnum); ++i) {
    288 		int n;
    289 		Elf32_Rela *ra;
    290 		u_int8_t *base;
    291 
    292 		if (htobe32(sh[i].sh_type) != SHT_RELA)
    293 			continue;
    294 		base = NULL;
    295 		if (strncmp(shstrtab + htobe32(sh[i].sh_name), ".rela", 5) != 0)
    296 			err(1, "bad relocation section name %s", shstrtab +
    297 			    htobe32(sh[i].sh_name));
    298 		for (n = 0; n < htobe16(eh->e_shnum); ++n) {
    299 			if (strcmp(shstrtab + htobe32(sh[i].sh_name) + 5, shstrtab +
    300 			    htobe32(sh[n].sh_name)) != 0)
    301 				continue;
    302 			base = buffer + sect_offset[n];
    303 			break;
    304 		}
    305 		if (base == NULL)
    306 			errx(1, "Can't find section for reloc %s", shstrtab +
    307 			    htobe32(sh[i].sh_name));
    308 		ra = (Elf32_Rela *)(image + htobe32(sh[i].sh_offset));
    309 		for (n = 0; n < htobe32(sh[i].sh_size); n += sizeof(Elf32_Rela), ++ra) {
    310 			Elf32_Sym *s;
    311 			int value;
    312 
    313 			s = &symtab[ELF32_R_SYM(htobe32(ra->r_info))];
    314 			if (s->st_shndx == ELF_SYM_UNDEFINED) {
    315 				fprintf(stderr, "Undefined symbol: %s\n",
    316 				    strtab + s->st_name);
    317 				++undefsyms;
    318 			}
    319 			value = htobe32(ra->r_addend) + eval(s, sect_offset);
    320 			dprintf(("reloc %04x info %04x (type %d sym %d) add 0x%x val %x\n",
    321 			    htobe32(ra->r_offset), htobe32(ra->r_info),
    322 			    ELF32_R_TYPE(htobe32(ra->r_info)),
    323 			    ELF32_R_SYM(htobe32(ra->r_info)),
    324 			    htobe32(ra->r_addend), value));
    325 			switch (ELF32_R_TYPE(htobe32(ra->r_info))) {
    326 			case R_68K_32:
    327 				tmp32 = htobe32(value);
    328 				memcpy(base + htobe32(ra->r_offset), &tmp32,
    329 				       sizeof(tmp32));
    330 				relbuf[r32sz++] = (base - buffer) + htobe32(ra->r_offset);
    331 				break;
    332 			case R_68K_PC32:
    333 				++pcrelsz;
    334 				tmp32 = htobe32(value - htobe32(ra->r_offset));
    335 				memcpy(base + htobe32(ra->r_offset), &tmp32,
    336 				       sizeof(tmp32));
    337 				break;
    338 			case R_68K_PC16:
    339 				++pcrelsz;
    340 				value -= htobe32(ra->r_offset);
    341 				if (value < -0x8000 || value > 0x7fff)
    342 					errx(1,  "PC-relative offset out of range: %x\n",
    343 					    value);
    344 				tmp16 = htobe16(value);
    345 				memcpy(base + htobe32(ra->r_offset), &tmp16,
    346 				       sizeof(tmp16));
    347 				break;
    348 			default:
    349 				errx(1, "Relocation type %d not supported",
    350 				    ELF32_R_TYPE(htobe32(ra->r_info)));
    351 			}
    352 		}
    353 	}
    354 	dprintf(("%d PC-relative relocations, %d 32-bit relocations\n",
    355 	    pcrelsz, r32sz));
    356 	printf("%d absolute reloc%s found, ", r32sz, r32sz==1?"":"s");
    357 
    358 	i = r32sz;
    359 	if (i > 1)
    360 		heapsort(relbuf, r32sz, 4, intcmp);
    361 
    362 	oldaddr = 0;
    363 
    364 	for (--i; i>=0; --i) {
    365 		dprintf(("0x%04x: ", relbuf[i]));
    366 		lptr = (u_int32_t *)&buffer[relbuf[i]];
    367 		addrdiff = relbuf[i] - oldaddr;
    368 		dprintf(("(0x%04x, 0x%04x): ", *lptr, addrdiff));
    369 		if (addrdiff > 255) {
    370 			*rpo = 0;
    371 			if (delta > 0) {
    372 				++rpo;
    373 				*rpo++ = (relbuf[i] >> 8) & 0xff;
    374 				*rpo++ = relbuf[i] & 0xff;
    375 				dprintf(("%02x%02x%02x\n",
    376 				    rpo[-3], rpo[-2], rpo[-1]));
    377 			} else {
    378 				*--rpo = relbuf[i] & 0xff;
    379 				*--rpo = (relbuf[i] >> 8) & 0xff;
    380 				--rpo;
    381 				dprintf(("%02x%02x%02x\n",
    382 				    rpo[0], rpo[1], rpo[2]));
    383 			}
    384 		} else {
    385 			*rpo = addrdiff;
    386 			dprintf(("%02x\n", *rpo));
    387 			rpo += delta;
    388 		}
    389 
    390 		oldaddr = relbuf[i];
    391 
    392 		if (delta < 0 ? rpo <= buffer+tsz+dsz
    393 		    : rpo >= buffer + bbsize)
    394 			errx(1, "Relocs don't fit.");
    395 	}
    396 	*rpo = 0; rpo += delta;
    397 	*rpo = 0; rpo += delta;
    398 	*rpo = 0; rpo += delta;
    399 
    400 	printf("using %d bytes, %d bytes remaining.\n", delta > 0 ?
    401 	    rpo-buffer-tsz-dsz : buffer+bbsize-rpo, delta > 0 ?
    402 	    buffer + bbsize - rpo : rpo - buffer - tsz - dsz);
    403 	/*
    404 	 * RELOCs must fit into the bss area.
    405 	 */
    406 	if (delta < 0 ? rpo <= buffer+tsz+dsz
    407 	    : rpo >= buffer + bbsize)
    408 		errx(1, "Relocs don't fit.");
    409 
    410 	if (undefsyms > 0)
    411 		errx(1, "Undefined symbols referenced");
    412 
    413 	((u_int32_t *)buffer)[1] = 0;
    414 	((u_int32_t *)buffer)[1] =
    415 	    htobe32((0xffffffff - chksum((u_int32_t *)buffer, sumsize * 512 / 4)));
    416 
    417 	ofd = open(argv[1], O_CREAT|O_WRONLY, 0644);
    418 	if (ofd < 0)
    419 		err(1, "Can't open %s", argv[1]);
    420 
    421 	if (write(ofd, buffer, bbsize) != bbsize)
    422 		err(1, "Writing output file");
    423 
    424 	exit(0);
    425 }
    426 
    427 void
    428 usage(void)
    429 {
    430 	fprintf(stderr, "Usage: %s [-F] bootprog bootprog.bin\n",
    431 	    progname);
    432 	exit(1);
    433 	/* NOTREACHED */
    434 }
    435 
    436 int
    437 eval(Elf32_Sym *s, u_int32_t *o)
    438 {
    439 	int value;
    440 
    441 	value = htobe32(s->st_value);
    442 	if (htobe16(s->st_shndx) < 0xf000)
    443 		value += o[htobe16(s->st_shndx)];
    444 	else
    445 		printf("eval: %x\n", htobe16(s->st_shndx));
    446 	return value;
    447 }
    448