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