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