Home | History | Annotate | Line # | Download | only in mkbootimage
mkbootimage.c revision 1.18
      1 /*	$NetBSD: mkbootimage.c,v 1.18 2014/04/22 21:37:52 phx Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Tim Rightnour and NONAKA Kimihiro
      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 #include "../../sys/sys/bootblock.h"
     35 #else
     36 #include <sys/bootblock.h>
     37 #endif
     38 
     39 #include <stdio.h>
     40 #include <stdlib.h>
     41 #include <string.h>
     42 #include <fcntl.h>
     43 #include <unistd.h>
     44 #include <errno.h>
     45 #include <zlib.h>
     46 #include <err.h>
     47 #include <sys/stat.h>
     48 #include <sys/types.h>
     49 #include <sys/uio.h>
     50 #include <sys/signal.h>
     51 
     52 #undef USE_SYSCTL
     53 
     54 #if defined(__NetBSD__) && !defined(HAVE_NBTOOL_CONFIG_H)
     55 #define USE_SYSCTL 1
     56 #include <sys/param.h>
     57 #include <sys/sysctl.h>
     58 #include <sys/utsname.h>
     59 #endif
     60 
     61 /* BFD ELF headers */
     62 #include <elf/common.h>
     63 #include <elf/external.h>
     64 
     65 #include "bebox_bootrec.h"
     66 #include "byteorder.h"
     67 #include "magic.h"
     68 #include "pef.h"
     69 #include "rs6000_bootrec.h"
     70 
     71 /* Globals */
     72 
     73 int inkernflag = 1;
     74 int saloneflag = 0;
     75 int verboseflag = 0;
     76 int lfloppyflag = 0;
     77 Elf32_External_Ehdr hdr, khdr;
     78 struct stat elf_stat;
     79 unsigned char mbr[512];
     80 
     81 /* the boot and config records for rs6000 */
     82 rs6000_boot_record_t bootrec;
     83 rs6000_config_record_t confrec;
     84 
     85 /* supported platforms */
     86 char *sup_plats[] = {
     87 	"bebox",
     88 	"prep",
     89 	"rs6000",
     90 	NULL,
     91 };
     92 
     93 /*
     94  * Macros to get values from multi-byte ELF header fields.  These assume
     95  * a big-endian image.
     96  */
     97 #define	ELFGET16(x)	(((x)[0] << 8) | (x)[1])
     98 
     99 #define	ELFGET32(x)	(((x)[0] << 24) | ((x)[1] << 16) |		\
    100 			 ((x)[2] <<  8) |  (x)[3])
    101 
    102 #define ULALIGN(x)	((x + 0x0f) & 0xfffffff0)
    103 
    104 static void usage(int);
    105 static int open_file(const char *, char *, Elf32_External_Ehdr *,
    106     struct stat *);
    107 static void check_mbr(int, char *);
    108 static int prep_build_image(char *, char *, char *, char *);
    109 static void rs6000_build_records(int);
    110 static int rs6000_build_image(char *, char *, char *, char *);
    111 int main(int, char **);
    112 
    113 
    114 static void
    115 usage(int extended)
    116 {
    117 	int i;
    118 
    119 	if (extended) {
    120 		fprintf(stderr, "You are not running this program on"
    121 		    " the target machine.  You must supply the\n"
    122 		    "machine architecture with the -m flag\n");
    123 		fprintf(stderr, "Supported architectures: ");
    124 		for (i=0; sup_plats[i] != NULL; i++)
    125 			fprintf(stderr, " %s", sup_plats[i]);
    126 		fprintf(stderr, "\n\n");
    127 	}
    128 #ifdef USE_SYSCTL
    129 	fprintf(stderr, "usage: %s [-Ilsv] [-m machine] [-b bootfile] "
    130 	    "[-k kernel] [-r rawdev] bootimage\n", getprogname());
    131 #else
    132 	fprintf(stderr, "usage: %s [-Ilsv] -m machine [-b bootfile] "
    133 	    "[-k kernel] [-r rawdev] bootimage\n", getprogname());
    134 #endif
    135 	exit(1);
    136 }
    137 
    138 /* verify the file is ELF and ppc, and open it up */
    139 static int
    140 open_file(const char *ftype, char *file, Elf32_External_Ehdr *hdr,
    141 	struct stat *f_stat)
    142 {
    143 	int fd;
    144 
    145 	if ((fd = open(file, 0)) < 0)
    146 		errx(2, "Can't open %s '%s': %s", ftype, file, strerror(errno));
    147 	fstat(fd, f_stat);
    148 
    149 	if (read(fd, hdr, sizeof(Elf32_External_Ehdr)) !=
    150 	    sizeof(Elf32_External_Ehdr))
    151 		errx(3, "Can't read input '%s': %s", file, strerror(errno));
    152 
    153 	if (hdr->e_ident[EI_MAG0] != ELFMAG0 ||
    154 	    hdr->e_ident[EI_MAG1] != ELFMAG1 ||
    155 	    hdr->e_ident[EI_MAG2] != ELFMAG2 ||
    156 	    hdr->e_ident[EI_MAG3] != ELFMAG3 ||
    157 	    hdr->e_ident[EI_CLASS] != ELFCLASS32)
    158 		errx(3, "input '%s' is not ELF32 format", file);
    159 
    160 	if (hdr->e_ident[EI_DATA] != ELFDATA2MSB)
    161 		errx(3, "input '%s' is not big-endian", file);
    162 
    163 	if (ELFGET16(hdr->e_machine) != EM_PPC)
    164 		errx(3, "input '%s' is not PowerPC exec binary", file);
    165 
    166 	return(fd);
    167 }
    168 
    169 static void
    170 prep_check_mbr(int prep_fd, char *rawdev)
    171 {
    172 	int raw_fd;
    173 	unsigned long entry, length;
    174 	struct mbr_partition *mbrp;
    175 	struct stat raw_stat;
    176 
    177 	/* If we are building a standalone image, do not write an MBR, just
    178 	 * set entry point and boot image size skipping over elf header
    179 	 */
    180 	if (saloneflag) {
    181 		entry  = sa_htole32(0x400);
    182 		length = sa_htole32(elf_stat.st_size - sizeof(hdr) + 0x400);
    183 		lseek(prep_fd, sizeof(mbr), SEEK_SET);
    184 		write(prep_fd, &entry, sizeof(entry));
    185 		write(prep_fd, &length, sizeof(length));
    186 		return;
    187 	}
    188 
    189 	/*
    190 	 * if we have a raw device, we need to check to see if it already
    191 	 * has a partition table, and if so, read it in and check for
    192 	 * suitability.
    193 	 */
    194 	if (rawdev != NULL) {
    195 		raw_fd = open(rawdev, O_RDONLY, 0);
    196 		if (raw_fd == -1)
    197 			errx(3, "couldn't open raw device %s: %s", rawdev,
    198 			    strerror(errno));
    199 
    200 		fstat(raw_fd, &raw_stat);
    201 		if (!S_ISCHR(raw_stat.st_mode))
    202 			errx(3, "%s is not a raw device", rawdev);
    203 
    204 		if (read(raw_fd, mbr, 512) != 512)
    205 			errx(3, "MBR Read Failed: %s", strerror(errno));
    206 
    207 		mbrp = (struct mbr_partition *)&mbr[MBR_PART_OFFSET];
    208 		if (mbrp->mbrp_type != MBR_PTYPE_PREP)
    209 			errx(3, "First partition is not of type 0x%x.",
    210 			    MBR_PTYPE_PREP);
    211 		if (mbrp->mbrp_start != 0)
    212 			errx(3, "Use of the raw device is intended for"
    213 			    " upgrading of legacy installations.  Your"
    214 			    " install does not have a PReP boot partition"
    215 			    " starting at sector 0.  Use the -s option"
    216 			    " to build an image instead.");
    217 
    218 		/* if we got this far, we are fine, write back the partition
    219 		 * and write the entry points and get outta here */
    220 	/* Set entry point and boot image size skipping over elf header */
    221 		lseek(prep_fd, 0, SEEK_SET);
    222 		entry  = sa_htole32(0x400);
    223 		length = sa_htole32(elf_stat.st_size - sizeof(hdr) + 0x400);
    224 		write(prep_fd, mbr, sizeof(mbr));
    225 		write(prep_fd, &entry, sizeof(entry));
    226 		write(prep_fd, &length, sizeof(length));
    227 		close(raw_fd);
    228 		return;
    229 	}
    230 
    231 	/* if we get to here, we want to build a standard floppy or netboot
    232 	 * image to file, so just build it */
    233 
    234 	memset(mbr, 0, sizeof(mbr));
    235 	mbrp = (struct mbr_partition *)&mbr[MBR_PART_OFFSET];
    236 
    237 	/* Set entry point and boot image size skipping over elf header */
    238 	entry  = sa_htole32(0x400);
    239 	length = sa_htole32(elf_stat.st_size - sizeof(hdr) + 0x400);
    240 
    241 	/*
    242 	 * Set magic number for msdos partition
    243 	 */
    244 	*(unsigned short *)&mbr[MBR_MAGIC_OFFSET] = sa_htole16(MBR_MAGIC);
    245 
    246 	/*
    247 	 * Build a "PReP" partition table entry in the boot record
    248 	 *  - "PReP" may only look at the system_indicator
    249 	 */
    250 	mbrp->mbrp_flag = MBR_PFLAG_ACTIVE;
    251 	mbrp->mbrp_type  = MBR_PTYPE_PREP;
    252 
    253 	/*
    254 	 * The first block of the diskette is used by this "boot record" which
    255 	 * actually contains the partition table. (The first block of the
    256 	 * partition contains the boot image, but I digress...)  We'll set up
    257 	 * one partition on the diskette and it shall contain the rest of the
    258 	 * diskette.
    259 	 */
    260 	mbrp->mbrp_shd   = 0;	/* zero-based */
    261 	mbrp->mbrp_ssect = 2;	/* one-based */
    262 	mbrp->mbrp_scyl  = 0;	/* zero-based */
    263 	mbrp->mbrp_ehd   = 1;	/* assumes two heads */
    264 	if (lfloppyflag)
    265 		mbrp->mbrp_esect = 36;  /* 2.88MB floppy */
    266 	else
    267 		mbrp->mbrp_esect = 18;	/* assumes 18 sectors/track */
    268 	mbrp->mbrp_ecyl  = 79;	/* assumes 80 cylinders/diskette */
    269 
    270 	/*
    271 	 * The "PReP" software ignores the above fields and just looks at
    272 	 * the next two.
    273 	 *   - size of the diskette is (assumed to be)
    274 	 *     (2 tracks/cylinder)(18 sectors/tracks)(80 cylinders/diskette)
    275 	 *   - unlike the above sector numbers,
    276 	 *     the beginning sector is zero-based!
    277 	 */
    278 
    279 	/* This has to be 0 on the PowerStack? */
    280 	mbrp->mbrp_start = sa_htole32(0);
    281 	mbrp->mbrp_size  = sa_htole32(2 * 18 * 80 - 1);
    282 
    283 	write(prep_fd, mbr, sizeof(mbr));
    284 	write(prep_fd, &entry, sizeof(entry));
    285 	write(prep_fd, &length, sizeof(length));
    286 }
    287 
    288 static int
    289 prep_build_image(char *kernel, char *boot, char *rawdev, char *outname)
    290 {
    291 	unsigned char *elf_img = NULL, *kern_img = NULL;
    292 	int i, ch, tmp, kgzlen, err;
    293 	int elf_fd, prep_fd, kern_fd, elf_img_len = 0;
    294 	off_t lenpos, kstart, kend;
    295 	unsigned long length;
    296 	long flength;
    297 	gzFile gzf;
    298 	struct stat kern_stat;
    299 	Elf32_External_Phdr phdr;
    300 
    301 	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
    302 	if (inkernflag) {
    303 		kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
    304 		kern_len = kern_stat.st_size + PREP_MAGICSIZE + KERNLENSIZE;
    305 	} else
    306 		kern_len = PREP_MAGICSIZE + KERNLENSIZE;
    307 
    308 	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
    309 		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
    310 			SEEK_SET);
    311 		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
    312 			errx(3, "Can't read input '%s' phdr : %s", boot,
    313 			    strerror(errno));
    314 
    315 		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
    316 		    !(ELFGET32(phdr.p_flags) & PF_X))
    317 			continue;
    318 
    319 		fstat(elf_fd, &elf_stat);
    320 		elf_img_len = elf_stat.st_size - ELFGET32(phdr.p_offset);
    321 		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);
    322 
    323 		break;
    324 	}
    325 	if ((prep_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
    326 		/* we couldn't open it, it must be new */
    327 		prep_fd = creat(outname, 0644);
    328 		if (prep_fd < 0)
    329 			errx(2, "Can't open output '%s': %s", outname,
    330 			    strerror(errno));
    331 	}
    332 
    333 	prep_check_mbr(prep_fd, rawdev);
    334 
    335 	/* Set file pos. to 2nd sector where image will be written */
    336 	lseek(prep_fd, 0x400, SEEK_SET);
    337 
    338 	/* Copy boot image */
    339 	elf_img = (unsigned char *)malloc(elf_img_len);
    340 	if (!elf_img)
    341 		errx(3, "Can't malloc: %s", strerror(errno));
    342 	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
    343 		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));
    344 
    345 	write(prep_fd, elf_img, elf_img_len);
    346 	free(elf_img);
    347 
    348 	if (inkernflag) {
    349 		/* Copy kernel */
    350 		kern_img = (unsigned char *)malloc(kern_stat.st_size);
    351 
    352 		if (kern_img == NULL)
    353 			errx(3, "Can't malloc: %s", strerror(errno));
    354 
    355 		/* we need to jump back after having read the headers */
    356 		lseek(kern_fd, 0, SEEK_SET);
    357 		if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
    358 		    kern_stat.st_size)
    359 			errx(3, "Can't read kernel '%s' : %s",
    360 			    kernel, strerror(errno));
    361 	}
    362 
    363 	gzf = gzdopen(dup(prep_fd), "a");
    364 	if (gzf == NULL)
    365 		errx(3, "Can't init compression: %s", strerror(errno));
    366 	if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) != Z_OK)
    367 		errx(3, "%s", gzerror(gzf, &err));
    368 
    369 	/* write a magic number and size before the kernel */
    370 	write(prep_fd, (void *)prep_magic, PREP_MAGICSIZE);
    371 	lenpos = lseek(prep_fd, 0, SEEK_CUR);
    372 	tmp = sa_htobe32(0);
    373 	write(prep_fd, (void *)&tmp, KERNLENSIZE);
    374 
    375 	/* write in the compressed kernel */
    376 	kstart = lseek(prep_fd, 0, SEEK_CUR);
    377 	if (inkernflag) {
    378 		kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
    379 		gzclose(gzf);
    380 	}
    381 	kend = lseek(prep_fd, 0, SEEK_CUR);
    382 
    383 	/* jump back to the length position now that we know the length */
    384 	lseek(prep_fd, lenpos, SEEK_SET);
    385 	kgzlen = kend - kstart;
    386 	tmp = sa_htobe32(kgzlen);
    387 	write(prep_fd, (void *)&tmp, KERNLENSIZE);
    388 
    389 	length = sa_htole32(0x400 + elf_img_len + 8 + kgzlen);
    390 	lseek(prep_fd, sizeof(mbr) + 4, SEEK_SET);
    391 	write(prep_fd, &length, sizeof(length));
    392 
    393 	flength = 0x400 + elf_img_len + 8 + kgzlen;
    394 	if (lfloppyflag)
    395 		flength -= (5760 * 512);
    396 	else
    397 		flength -= (2880 * 512);
    398 	if (flength > 0 && !saloneflag)
    399 		fprintf(stderr, "%s: Image %s is %ld bytes larger than single"
    400 		    " floppy. Can only be used for netboot.\n", getprogname(),
    401 		    outname, flength);
    402 
    403 	if (inkernflag) {
    404 		free(kern_img);
    405 		close(kern_fd);
    406 	}
    407 	close(prep_fd);
    408 	close(elf_fd);
    409 
    410 	return 0;
    411 }
    412 
    413 /* Fill in the needed information on the boot and config records.  Most of
    414  * this is just AIX garbage that we don't really need to boot.
    415  */
    416 static void
    417 rs6000_build_records(int img_len)
    418 {
    419 	int bcl;
    420 
    421 	/* zero out all the fields, so we only have to set the ones
    422 	 * we care about, which are rather few.
    423 	 */
    424 	memset(&bootrec, 0, sizeof(rs6000_boot_record_t));
    425 	memset(&confrec, 0, sizeof(rs6000_config_record_t));
    426 
    427 	bootrec.ipl_record = IPLRECID;
    428 	bcl = img_len/512;
    429 	if (img_len%512 != 0)
    430 		bcl++;
    431 	bootrec.bootcode_len = bcl;
    432 	bootrec.bootcode_off = 0; /* XXX */
    433 	bootrec.bootpart_start = 2; /* skip bootrec and confrec */
    434 	bootrec.bootprg_start = 2;
    435 	bootrec.bootpart_len = bcl;
    436 	bootrec.boot_load_addr = 0x800000; /* XXX? */
    437 	bootrec.boot_frag = 1;
    438 	bootrec.boot_emul = 0x02; /* ?? */
    439 	/* service mode is a repeat of normal mode */
    440 	bootrec.servcode_len = bootrec.bootcode_len;
    441 	bootrec.servcode_off = bootrec.bootcode_off;
    442 	bootrec.servpart_start = bootrec.bootpart_start;
    443 	bootrec.servprg_start = bootrec.bootprg_start;
    444 	bootrec.servpart_len = bootrec.bootpart_len;
    445 	bootrec.serv_load_addr = bootrec.boot_load_addr;
    446 	bootrec.serv_frag = bootrec.boot_frag;
    447 	bootrec.serv_emul = bootrec.boot_emul;
    448 
    449 	/* now the config record */
    450 	confrec.conf_rec = CONFRECID;
    451 	confrec.sector_size = 0x02; /* 512 bytes */
    452 	confrec.last_cyl = 0x4f; /* 79 cyl, emulates floppy */
    453 }
    454 
    455 static int
    456 rs6000_build_image(char *kernel, char *boot, char *rawdev, char *outname)
    457 {
    458 	unsigned char *elf_img = NULL, *kern_img = NULL;
    459 	int i, ch, tmp, kgzlen, err;
    460 	int elf_fd, rs6000_fd, kern_fd, elf_img_len = 0, elf_pad;
    461 	uint32_t swapped[128];
    462 	off_t lenpos, kstart, kend;
    463 	unsigned long length;
    464 	long flength;
    465 	gzFile gzf;
    466 	struct stat kern_stat;
    467 	Elf32_External_Phdr phdr;
    468 
    469 	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
    470 	kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
    471 	kern_len = kern_stat.st_size + RS6000_MAGICSIZE + KERNLENSIZE;
    472 
    473 	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
    474 		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
    475 			SEEK_SET);
    476 		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
    477 			errx(3, "Can't read input '%s' phdr : %s", boot,
    478 			    strerror(errno));
    479 
    480 		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
    481 		    !(ELFGET32(phdr.p_flags) & PF_X))
    482 			continue;
    483 
    484 		fstat(elf_fd, &elf_stat);
    485 		elf_img_len = elf_stat.st_size - ELFGET32(phdr.p_offset);
    486 		elf_pad = ELFGET32(phdr.p_memsz) - ELFGET32(phdr.p_filesz);
    487 		if (verboseflag)
    488 			printf("Padding %d\n", elf_pad);
    489 		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);
    490 
    491 		break;
    492 	}
    493 	if ((rs6000_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
    494 		/* we couldn't open it, it must be new */
    495 		rs6000_fd = creat(outname, 0644);
    496 		if (rs6000_fd < 0)
    497 			errx(2, "Can't open output '%s': %s", outname,
    498 			    strerror(errno));
    499 	}
    500 
    501 	/* Set file pos. to 2nd sector where image will be written */
    502 	lseek(rs6000_fd, 0x400, SEEK_SET);
    503 
    504 	/* Copy boot image */
    505 	elf_img = (unsigned char *)malloc(elf_img_len);
    506 	if (!elf_img)
    507 		errx(3, "Can't malloc: %s", strerror(errno));
    508 	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
    509 		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));
    510 
    511 	write(rs6000_fd, elf_img, elf_img_len);
    512 	free(elf_img);
    513 
    514 	/* now dump in the padding space for the BSS */
    515 	elf_pad += 100; /* just a little extra for good luck */
    516 	lseek(rs6000_fd, elf_pad, SEEK_CUR);
    517 
    518 	/* Copy kernel */
    519 	kern_img = (unsigned char *)malloc(kern_stat.st_size);
    520 
    521 	if (kern_img == NULL)
    522 		errx(3, "Can't malloc: %s", strerror(errno));
    523 
    524 	/* we need to jump back after having read the headers */
    525 	lseek(kern_fd, 0, SEEK_SET);
    526 	if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
    527 	    kern_stat.st_size)
    528 		errx(3, "Can't read kernel '%s' : %s", kernel, strerror(errno));
    529 
    530 	gzf = gzdopen(dup(rs6000_fd), "a");
    531 	if (gzf == NULL)
    532 		errx(3, "Can't init compression: %s", strerror(errno));
    533 	if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) != Z_OK)
    534 		errx(3, "%s", gzerror(gzf, &err));
    535 
    536 	/* write a magic number and size before the kernel */
    537 	write(rs6000_fd, (void *)rs6000_magic, RS6000_MAGICSIZE);
    538 	lenpos = lseek(rs6000_fd, 0, SEEK_CUR);
    539 	if (verboseflag)
    540 		printf("wrote magic at pos 0x%lx\n", (unsigned long)lenpos);
    541 	tmp = sa_htobe32(0);
    542 	write(rs6000_fd, (void *)&tmp, KERNLENSIZE);
    543 
    544 	/* write in the compressed kernel */
    545 	kstart = lseek(rs6000_fd, 0, SEEK_CUR);
    546 	if (verboseflag)
    547 		printf("kernel start at pos 0x%lx\n", (unsigned long)kstart);
    548 	kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
    549 	gzclose(gzf);
    550 	kend = lseek(rs6000_fd, 0, SEEK_CUR);
    551 	if (verboseflag)
    552 		printf("kernel end at pos 0x%lx\n", (unsigned long)kend);
    553 
    554 	/* jump back to the length position now that we know the length */
    555 	lseek(rs6000_fd, lenpos, SEEK_SET);
    556 	kgzlen = kend - kstart;
    557 	tmp = sa_htobe32(kgzlen);
    558 	if (verboseflag)
    559 		printf("kernel len = 0x%x tmp = 0x%x\n", kgzlen, tmp);
    560 	write(rs6000_fd, (void *)&tmp, KERNLENSIZE);
    561 
    562 #if 0
    563 	lseek(rs6000_fd, sizeof(boot_record_t) + sizeof(config_record_t),
    564 	    SEEK_SET);
    565 	/* set entry and length */
    566 	length = sa_htole32(0x400);
    567 	write(rs6000_fd, &length, sizeof(length));
    568 	length = sa_htole32(0x400 + elf_img_len + 8 + kgzlen);
    569 	write(rs6000_fd, &length, sizeof(length));
    570 #endif
    571 
    572 	/* generate the header now that we know the kernel length */
    573 	if (verboseflag)
    574 		printf("building records\n");
    575 	rs6000_build_records(elf_img_len + 8 + kgzlen);
    576 	lseek(rs6000_fd, 0, SEEK_SET);
    577 	/* ROM wants it byteswapped in 32bit chunks */
    578 	if (verboseflag)
    579 		printf("writing records\n");
    580 	memcpy(swapped, &bootrec, sizeof(rs6000_boot_record_t));
    581 	for (i=0; i < 128; i++)
    582 		swapped[i] = htonl(swapped[i]);
    583 	write(rs6000_fd, swapped, sizeof(rs6000_boot_record_t));
    584 	memcpy(swapped, &confrec, sizeof(rs6000_config_record_t));
    585 	for (i=0; i < 128; i++)
    586 		swapped[i] = htonl(swapped[i]);
    587 	write(rs6000_fd, swapped, sizeof(rs6000_config_record_t));
    588 
    589 	free(kern_img);
    590 	close(kern_fd);
    591 	close(rs6000_fd);
    592 	close(elf_fd);
    593 
    594 	return 0;
    595 }
    596 
    597 static int
    598 bebox_write_header(int bebox_fd, int elf_image_len, int kern_img_len)
    599 {
    600 	int hsize = BEBOX_HEADER_SIZE;
    601 	unsigned long textOffset, dataOffset, ldrOffset;
    602 	unsigned long entry_vector[3];
    603 	struct FileHeader fileHdr;
    604 	struct SectionHeader textHdr, dataHdr, ldrHdr;
    605 	struct LoaderHeader lh;
    606 
    607 
    608 	ldrOffset = ULALIGN(sizeof (fileHdr) + sizeof (textHdr) +
    609 	    sizeof (dataHdr) + sizeof (ldrHdr));
    610 	dataOffset = ULALIGN(ldrOffset + sizeof (lh));
    611 	textOffset = ULALIGN(dataOffset + sizeof (entry_vector) + kern_img_len);
    612 
    613 	/* Create the File Header */
    614 	memset(&fileHdr, 0, sizeof (fileHdr));
    615 	fileHdr.magic = sa_htobe32(PEF_MAGIC);
    616 	fileHdr.fileTypeID = sa_htobe32(PEF_FILE);
    617 	fileHdr.archID = sa_htobe32(PEF_PPC);
    618 	fileHdr.versionNumber = sa_htobe32(1);
    619 	fileHdr.numSections = sa_htobe16(3);
    620 	fileHdr.loadableSections = sa_htobe16(2);
    621 	write(bebox_fd, &fileHdr, sizeof (fileHdr));
    622 
    623 	/* Create the Section Header for TEXT */
    624 	memset(&textHdr, 0, sizeof (textHdr));
    625 	textHdr.sectionName = sa_htobe32(-1);
    626 	textHdr.sectionAddress = sa_htobe32(0);
    627 	textHdr.execSize = sa_htobe32(elf_image_len);
    628 	textHdr.initSize = sa_htobe32(elf_image_len);
    629 	textHdr.rawSize = sa_htobe32(elf_image_len);
    630 	textHdr.fileOffset = sa_htobe32(textOffset);
    631 	textHdr.regionKind = CodeSection;
    632 	textHdr.shareKind = ContextShare;
    633 	textHdr.alignment = 4;  /* 16 byte alignment */
    634 	write(bebox_fd, &textHdr, sizeof (textHdr));
    635 
    636 	/* Create the Section Header for DATA */
    637 	memset(&dataHdr, 0, sizeof (dataHdr));
    638 	dataHdr.sectionName = sa_htobe32(-1);
    639 	dataHdr.sectionAddress = sa_htobe32(0);
    640 	dataHdr.execSize = sa_htobe32(sizeof (entry_vector) + kern_img_len);
    641 	dataHdr.initSize = sa_htobe32(sizeof (entry_vector) + kern_img_len);
    642 	dataHdr.rawSize = sa_htobe32(sizeof (entry_vector) + kern_img_len);
    643 	dataHdr.fileOffset = sa_htobe32(dataOffset);
    644 	dataHdr.regionKind = DataSection;
    645 	dataHdr.shareKind = ContextShare;
    646 	dataHdr.alignment = 4;  /* 16 byte alignment */
    647 	write(bebox_fd, &dataHdr, sizeof (dataHdr));
    648 
    649 	/* Create the Section Header for loader stuff */
    650 	memset(&ldrHdr, 0, sizeof (ldrHdr));
    651 	ldrHdr.sectionName = sa_htobe32(-1);
    652 	ldrHdr.sectionAddress = sa_htobe32(0);
    653 	ldrHdr.execSize = sa_htobe32(sizeof (lh));
    654 	ldrHdr.initSize = sa_htobe32(sizeof (lh));
    655 	ldrHdr.rawSize = sa_htobe32(sizeof (lh));
    656 	ldrHdr.fileOffset = sa_htobe32(ldrOffset);
    657 	ldrHdr.regionKind = LoaderSection;
    658 	ldrHdr.shareKind = GlobalShare;
    659 	ldrHdr.alignment = 4;  /* 16 byte alignment */
    660 	write(bebox_fd, &ldrHdr, sizeof (ldrHdr));
    661 
    662 	/* Create the Loader Header */
    663 	memset(&lh, 0, sizeof (lh));
    664 	lh.entryPointSection = sa_htobe32(1);		/* Data */
    665 	lh.entryPointOffset = sa_htobe32(0);
    666 	lh.initPointSection = sa_htobe32(-1);
    667 	lh.initPointOffset = sa_htobe32(0);
    668 	lh.termPointSection = sa_htobe32(-1);
    669 	lh.termPointOffset = sa_htobe32(0);
    670 	lseek(bebox_fd, ldrOffset + hsize, SEEK_SET);
    671 	write(bebox_fd, &lh, sizeof (lh));
    672 
    673 	/* Copy the pseudo-DATA */
    674 	memset(entry_vector, 0, sizeof (entry_vector));
    675 	entry_vector[0] = sa_htobe32(BEBOX_ENTRY);	/* Magic */
    676 	lseek(bebox_fd, dataOffset + hsize, SEEK_SET);
    677 	write(bebox_fd, entry_vector, sizeof (entry_vector));
    678 
    679 	return textOffset;
    680 }
    681 
    682 static int
    683 bebox_build_image(char *kernel, char *boot, char *rawdev, char *outname)
    684 {
    685 	unsigned char *elf_img = NULL, *kern_img = NULL, *header_img = NULL;
    686 	int i, ch, tmp, kgzlen, err, hsize = BEBOX_HEADER_SIZE;
    687 	int elf_fd, bebox_fd, kern_fd, elf_img_len = 0;
    688 	off_t lenpos, kstart, kend, toff, endoff, flength;
    689 	uint32_t swapped[128];
    690 	int32_t *offset;
    691 	gzFile gzf;
    692 	struct stat kern_stat;
    693 	struct bebox_image_block *p;
    694 	struct timeval tp;
    695 	Elf32_External_Phdr phdr;
    696 
    697 	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
    698 	if (inkernflag) {
    699 		kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
    700 		kern_len = kern_stat.st_size + BEBOX_MAGICSIZE + KERNLENSIZE;
    701 	} else
    702 		kern_len = BEBOX_MAGICSIZE + KERNLENSIZE;
    703 
    704 	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
    705 		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
    706 			SEEK_SET);
    707 		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
    708 			errx(3, "Can't read input '%s' phdr : %s", boot,
    709 			    strerror(errno));
    710 
    711 		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
    712 		    !(ELFGET32(phdr.p_flags) & PF_X))
    713 			continue;
    714 
    715 		fstat(elf_fd, &elf_stat);
    716 		elf_img_len = ELFGET32(phdr.p_filesz);
    717 		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);
    718 
    719 		break;
    720 	}
    721 	if ((bebox_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
    722 		/* we couldn't open it, it must be new */
    723 		bebox_fd = creat(outname, 0644);
    724 		if (bebox_fd < 0)
    725 			errx(2, "Can't open output '%s': %s", outname,
    726 			    strerror(errno));
    727 	}
    728 	lseek(bebox_fd, hsize, SEEK_SET);
    729 
    730 	if (inkernflag) {
    731 		/*
    732 		 * write the header with the wrong values to get the offset
    733 		 * right
    734 		 */
    735 		bebox_write_header(bebox_fd, elf_img_len, kern_stat.st_size);
    736 
    737 		/* Copy kernel */
    738 		kern_img = (unsigned char *)malloc(kern_stat.st_size);
    739 
    740 		if (kern_img == NULL)
    741 			errx(3, "Can't malloc: %s", strerror(errno));
    742 
    743 		/* we need to jump back after having read the headers */
    744 		lseek(kern_fd, 0, SEEK_SET);
    745 		if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
    746 		    kern_stat.st_size)
    747 			errx(3, "Can't read kernel '%s' : %s",
    748 			    kernel, strerror(errno));
    749 
    750 		gzf = gzdopen(dup(bebox_fd), "a");
    751 		if (gzf == NULL)
    752 			errx(3, "Can't init compression: %s", strerror(errno));
    753 		if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) !=
    754 		    Z_OK)
    755 			errx(3, "%s", gzerror(gzf, &err));
    756 	} else
    757 		bebox_write_header(bebox_fd, elf_img_len, 0);
    758 
    759 	/* write a magic number and size before the kernel */
    760 	write(bebox_fd, (void *)bebox_magic, BEBOX_MAGICSIZE);
    761 	lenpos = lseek(bebox_fd, 0, SEEK_CUR);
    762 	tmp = sa_htobe32(0);
    763 	write(bebox_fd, (void *)&tmp, KERNLENSIZE);
    764 
    765 	if (inkernflag) {
    766 		/* write in the compressed kernel */
    767 		kstart = lseek(bebox_fd, 0, SEEK_CUR);
    768 		kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
    769 		gzclose(gzf);
    770 		kend = lseek(bebox_fd, 0, SEEK_CUR);
    771 		free(kern_img);
    772 	} else {
    773 		kstart = kend = lseek(bebox_fd, 0, SEEK_CUR);
    774 		kgzlen = 0;
    775 	}
    776 
    777 	/* jump back to the length position now that we know the length */
    778 	lseek(bebox_fd, lenpos, SEEK_SET);
    779 	kgzlen = kend - kstart;
    780 	tmp = sa_htobe32(kgzlen);
    781 	write(bebox_fd, (void *)&tmp, KERNLENSIZE);
    782 
    783 	/* now rewrite the header correctly */
    784 	lseek(bebox_fd, hsize, SEEK_SET);
    785 	tmp = kgzlen + BEBOX_MAGICSIZE + KERNLENSIZE;
    786 	toff = bebox_write_header(bebox_fd, elf_img_len, tmp);
    787 
    788 	/* Copy boot image */
    789 	elf_img = (unsigned char *)malloc(elf_img_len);
    790 	if (!elf_img)
    791 		errx(3, "Can't malloc: %s", strerror(errno));
    792 	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
    793 		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));
    794 	lseek(bebox_fd, toff + hsize, SEEK_SET);
    795 	write(bebox_fd, elf_img, elf_img_len);
    796 	free(elf_img);
    797 
    798 	if (inkernflag)
    799 		close(kern_fd);
    800 	close(elf_fd);
    801 
    802 	/* Now go back and write in the block header */
    803 	endoff = lseek(bebox_fd, 0, SEEK_END);
    804 	lseek(bebox_fd, 0, SEEK_SET);
    805 	header_img = (unsigned char *)malloc(BEBOX_HEADER_SIZE);
    806 	if (!header_img)
    807 		errx(3, "Can't malloc: %s", strerror(errno));
    808 	memset(header_img, 0, BEBOX_HEADER_SIZE);
    809 
    810 	/* copy the boot image into the buffer */
    811 	for (p = bebox_image_block; p->offset != -1; p++)
    812 		memcpy(header_img + p->offset, p->data, p->size);
    813 
    814 	/* fill used block bitmap */
    815 	memset(header_img + BEBOX_FILE_BLOCK_MAP_START, 0xff,
    816 	    BEBOX_FILE_BLOCK_MAP_END - BEBOX_FILE_BLOCK_MAP_START);
    817 
    818 	/* fix the file size in the header */
    819 	tmp = endoff - BEBOX_HEADER_SIZE;
    820 	*(int32_t *)(header_img + BEBOX_FILE_SIZE_OFFSET) =
    821 	    (int32_t)sa_htobe32(tmp);
    822 	*(int32_t *)(header_img + BEBOX_FILE_SIZE_ALIGN_OFFSET) =
    823 	    (int32_t)sa_htobe32(roundup(tmp, BEBOX_FILE_BLOCK_SIZE));
    824 
    825 	gettimeofday(&tp, 0);
    826 	for (offset = bebox_mtime_offset; *offset != -1; offset++)
    827 		*(int32_t *)(header_img + *offset) =
    828 		    (int32_t)sa_htobe32(tp.tv_sec);
    829 
    830 	write(bebox_fd, header_img, BEBOX_HEADER_SIZE);
    831 
    832 	/* now pad the end */
    833 	flength = roundup(endoff, BEBOX_BLOCK_SIZE);
    834 	/* refill the header_img with zeros */
    835 	memset(header_img, 0, BEBOX_BLOCK_SIZE * 2);
    836 	lseek(bebox_fd, 0, SEEK_END);
    837 	write(bebox_fd, header_img, flength - endoff);
    838 
    839 	close(bebox_fd);
    840 
    841 	return 0;
    842 }
    843 
    844 int
    845 main(int argc, char **argv)
    846 {
    847 	int ch, lfloppyflag=0;
    848 	char *kernel = NULL, *boot = NULL, *rawdev = NULL, *outname = NULL;
    849 	char *march = NULL;
    850 #ifdef USE_SYSCTL
    851 	char machine[SYS_NMLN];
    852 	int mib[2] = { CTL_HW, HW_MACHINE };
    853 #endif
    854 
    855 	setprogname(argv[0]);
    856 	kern_len = 0;
    857 
    858 	while ((ch = getopt(argc, argv, "b:Ik:lm:r:sv")) != -1)
    859 		switch (ch) {
    860 		case 'b':
    861 			boot = optarg;
    862 			break;
    863 		case 'I':
    864 			inkernflag = 0;
    865 			break;
    866 		case 'k':
    867 			kernel = optarg;
    868 			inkernflag = 1;
    869 			break;
    870 		case 'l':
    871 			lfloppyflag = 1;
    872 			break;
    873 		case 'm':
    874 			march = optarg;
    875 			break;
    876 		case 'r':
    877 			rawdev = optarg;
    878 			break;
    879 		case 's':
    880 			saloneflag = 1;
    881 			break;
    882 		case 'v':
    883 			verboseflag = 1;
    884 			break;
    885 		case '?':
    886 		default:
    887 			usage(0);
    888 			/* NOTREACHED */
    889 		}
    890 	argc -= optind;
    891 	argv += optind;
    892 
    893 	if (argc < 1)
    894 		usage(0);
    895 
    896 	if (kernel == NULL && inkernflag)
    897 		kernel = "/netbsd";
    898 
    899 	if (boot == NULL)
    900 		boot = "/usr/mdec/boot";
    901 
    902 	if (march != NULL && strcmp(march, "") == 0)
    903 		march = NULL;
    904 	if (march == NULL) {
    905 		int i;
    906 #ifdef USE_SYSCTL
    907 		size_t len = sizeof(machine);
    908 
    909 		if (sysctl(mib, sizeof (mib) / sizeof (mib[0]), machine,
    910 			&len, NULL, 0) != -1) {
    911 			for (i=0; sup_plats[i] != NULL; i++) {
    912 				if (strcmp(sup_plats[i], machine) == 0) {
    913 					march = strdup(sup_plats[i]);
    914 					break;
    915 				}
    916 			}
    917 		}
    918 		if (march == NULL)
    919 #endif
    920 			usage(1);
    921 	}
    922 
    923 	outname = argv[0];
    924 
    925 	if (strcmp(march, "prep") == 0)
    926 		return(prep_build_image(kernel, boot, rawdev, outname));
    927 	if (strcmp(march, "rs6000") == 0)
    928 		return(rs6000_build_image(kernel, boot, rawdev, outname));
    929 	if (strcmp(march, "bebox") == 0)
    930 		return(bebox_build_image(kernel, boot, rawdev, outname));
    931 
    932 	usage(1);
    933 	return(0);
    934 }
    935