Home | History | Annotate | Line # | Download | only in mkbootimage
mkbootimage.c revision 1.14
      1 /*	$NetBSD: mkbootimage.c,v 1.14 2011/01/26 21:35:14 joerg 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 	kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
    303 	kern_len = kern_stat.st_size + PREP_MAGICSIZE + KERNLENSIZE;
    304 
    305 	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
    306 		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
    307 			SEEK_SET);
    308 		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
    309 			errx(3, "Can't read input '%s' phdr : %s", boot,
    310 			    strerror(errno));
    311 
    312 		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
    313 		    !(ELFGET32(phdr.p_flags) & PF_X))
    314 			continue;
    315 
    316 		fstat(elf_fd, &elf_stat);
    317 		elf_img_len = elf_stat.st_size - ELFGET32(phdr.p_offset);
    318 		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);
    319 
    320 		break;
    321 	}
    322 	if ((prep_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
    323 		/* we couldn't open it, it must be new */
    324 		prep_fd = creat(outname, 0644);
    325 		if (prep_fd < 0)
    326 			errx(2, "Can't open output '%s': %s", outname,
    327 			    strerror(errno));
    328 	}
    329 
    330 	prep_check_mbr(prep_fd, rawdev);
    331 
    332 	/* Set file pos. to 2nd sector where image will be written */
    333 	lseek(prep_fd, 0x400, SEEK_SET);
    334 
    335 	/* Copy boot image */
    336 	elf_img = (unsigned char *)malloc(elf_img_len);
    337 	if (!elf_img)
    338 		errx(3, "Can't malloc: %s", strerror(errno));
    339 	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
    340 		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));
    341 
    342 	write(prep_fd, elf_img, elf_img_len);
    343 	free(elf_img);
    344 
    345 	/* Copy kernel */
    346 	kern_img = (unsigned char *)malloc(kern_stat.st_size);
    347 
    348 	if (kern_img == NULL)
    349 		errx(3, "Can't malloc: %s", strerror(errno));
    350 
    351 	/* we need to jump back after having read the headers */
    352 	lseek(kern_fd, 0, SEEK_SET);
    353 	if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
    354 	    kern_stat.st_size)
    355 		errx(3, "Can't read kernel '%s' : %s", kernel, strerror(errno));
    356 
    357 	gzf = gzdopen(dup(prep_fd), "a");
    358 	if (gzf == NULL)
    359 		errx(3, "Can't init compression: %s", strerror(errno));
    360 	if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) != Z_OK)
    361 		errx(3, "%s", gzerror(gzf, &err));
    362 
    363 	/* write a magic number and size before the kernel */
    364 	write(prep_fd, (void *)prep_magic, PREP_MAGICSIZE);
    365 	lenpos = lseek(prep_fd, 0, SEEK_CUR);
    366 	tmp = sa_htobe32(0);
    367 	write(prep_fd, (void *)&tmp, KERNLENSIZE);
    368 
    369 	/* write in the compressed kernel */
    370 	kstart = lseek(prep_fd, 0, SEEK_CUR);
    371 	kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
    372 	gzclose(gzf);
    373 	kend = lseek(prep_fd, 0, SEEK_CUR);
    374 
    375 	/* jump back to the length position now that we know the length */
    376 	lseek(prep_fd, lenpos, SEEK_SET);
    377 	kgzlen = kend - kstart;
    378 	tmp = sa_htobe32(kgzlen);
    379 	write(prep_fd, (void *)&tmp, KERNLENSIZE);
    380 
    381 	length = sa_htole32(0x400 + elf_img_len + 8 + kgzlen);
    382 	lseek(prep_fd, sizeof(mbr) + 4, SEEK_SET);
    383 	write(prep_fd, &length, sizeof(length));
    384 
    385 	flength = 0x400 + elf_img_len + 8 + kgzlen;
    386 	if (lfloppyflag)
    387 		flength -= (5760 * 512);
    388 	else
    389 		flength -= (2880 * 512);
    390 	if (flength > 0 && !saloneflag)
    391 		fprintf(stderr, "%s: Image %s is %d bytes larger than single"
    392 		    " floppy. Can only be used for netboot.\n", getprogname(),
    393 		    outname, flength);
    394 
    395 	free(kern_img);
    396 	close(kern_fd);
    397 	close(prep_fd);
    398 	close(elf_fd);
    399 
    400 	return 0;
    401 }
    402 
    403 /* Fill in the needed information on the boot and config records.  Most of
    404  * this is just AIX garbage that we don't really need to boot.
    405  */
    406 static void
    407 rs6000_build_records(int img_len)
    408 {
    409 	int bcl;
    410 
    411 	/* zero out all the fields, so we only have to set the ones
    412 	 * we care about, which are rather few.
    413 	 */
    414 	memset(&bootrec, 0, sizeof(rs6000_boot_record_t));
    415 	memset(&confrec, 0, sizeof(rs6000_config_record_t));
    416 
    417 	bootrec.ipl_record = IPLRECID;
    418 	bcl = img_len/512;
    419 	if (img_len%512 != 0)
    420 		bcl++;
    421 	bootrec.bootcode_len = bcl;
    422 	bootrec.bootcode_off = 0; /* XXX */
    423 	bootrec.bootpart_start = 2; /* skip bootrec and confrec */
    424 	bootrec.bootprg_start = 2;
    425 	bootrec.bootpart_len = bcl;
    426 	bootrec.boot_load_addr = 0x800000; /* XXX? */
    427 	bootrec.boot_frag = 1;
    428 	bootrec.boot_emul = 0x02; /* ?? */
    429 	/* service mode is a repeat of normal mode */
    430 	bootrec.servcode_len = bootrec.bootcode_len;
    431 	bootrec.servcode_off = bootrec.bootcode_off;
    432 	bootrec.servpart_start = bootrec.bootpart_start;
    433 	bootrec.servprg_start = bootrec.bootprg_start;
    434 	bootrec.servpart_len = bootrec.bootpart_len;
    435 	bootrec.serv_load_addr = bootrec.boot_load_addr;
    436 	bootrec.serv_frag = bootrec.boot_frag;
    437 	bootrec.serv_emul = bootrec.boot_emul;
    438 
    439 	/* now the config record */
    440 	confrec.conf_rec = CONFRECID;
    441 	confrec.sector_size = 0x02; /* 512 bytes */
    442 	confrec.last_cyl = 0x4f; /* 79 cyl, emulates floppy */
    443 }
    444 
    445 static int
    446 rs6000_build_image(char *kernel, char *boot, char *rawdev, char *outname)
    447 {
    448 	unsigned char *elf_img = NULL, *kern_img = NULL;
    449 	int i, ch, tmp, kgzlen, err;
    450 	int elf_fd, rs6000_fd, kern_fd, elf_img_len = 0, elf_pad;
    451 	uint32_t swapped[128];
    452 	off_t lenpos, kstart, kend;
    453 	unsigned long length;
    454 	long flength;
    455 	gzFile gzf;
    456 	struct stat kern_stat;
    457 	Elf32_External_Phdr phdr;
    458 
    459 	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
    460 	kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
    461 	kern_len = kern_stat.st_size + RS6000_MAGICSIZE + KERNLENSIZE;
    462 
    463 	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
    464 		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
    465 			SEEK_SET);
    466 		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
    467 			errx(3, "Can't read input '%s' phdr : %s", boot,
    468 			    strerror(errno));
    469 
    470 		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
    471 		    !(ELFGET32(phdr.p_flags) & PF_X))
    472 			continue;
    473 
    474 		fstat(elf_fd, &elf_stat);
    475 		elf_img_len = elf_stat.st_size - ELFGET32(phdr.p_offset);
    476 		elf_pad = ELFGET32(phdr.p_memsz) - ELFGET32(phdr.p_filesz);
    477 		if (verboseflag)
    478 			printf("Padding %d\n", elf_pad);
    479 		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);
    480 
    481 		break;
    482 	}
    483 	if ((rs6000_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
    484 		/* we couldn't open it, it must be new */
    485 		rs6000_fd = creat(outname, 0644);
    486 		if (rs6000_fd < 0)
    487 			errx(2, "Can't open output '%s': %s", outname,
    488 			    strerror(errno));
    489 	}
    490 
    491 	/* Set file pos. to 2nd sector where image will be written */
    492 	lseek(rs6000_fd, 0x400, SEEK_SET);
    493 
    494 	/* Copy boot image */
    495 	elf_img = (unsigned char *)malloc(elf_img_len);
    496 	if (!elf_img)
    497 		errx(3, "Can't malloc: %s", strerror(errno));
    498 	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
    499 		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));
    500 
    501 	write(rs6000_fd, elf_img, elf_img_len);
    502 	free(elf_img);
    503 
    504 	/* now dump in the padding space for the BSS */
    505 	elf_pad += 100; /* just a little extra for good luck */
    506 	lseek(rs6000_fd, elf_pad, SEEK_CUR);
    507 
    508 	/* Copy kernel */
    509 	kern_img = (unsigned char *)malloc(kern_stat.st_size);
    510 
    511 	if (kern_img == NULL)
    512 		errx(3, "Can't malloc: %s", strerror(errno));
    513 
    514 	/* we need to jump back after having read the headers */
    515 	lseek(kern_fd, 0, SEEK_SET);
    516 	if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
    517 	    kern_stat.st_size)
    518 		errx(3, "Can't read kernel '%s' : %s", kernel, strerror(errno));
    519 
    520 	gzf = gzdopen(dup(rs6000_fd), "a");
    521 	if (gzf == NULL)
    522 		errx(3, "Can't init compression: %s", strerror(errno));
    523 	if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) != Z_OK)
    524 		errx(3, "%s", gzerror(gzf, &err));
    525 
    526 	/* write a magic number and size before the kernel */
    527 	write(rs6000_fd, (void *)rs6000_magic, RS6000_MAGICSIZE);
    528 	lenpos = lseek(rs6000_fd, 0, SEEK_CUR);
    529 	if (verboseflag)
    530 		printf("wrote magic at pos 0x%lx\n", (unsigned long)lenpos);
    531 	tmp = sa_htobe32(0);
    532 	write(rs6000_fd, (void *)&tmp, KERNLENSIZE);
    533 
    534 	/* write in the compressed kernel */
    535 	kstart = lseek(rs6000_fd, 0, SEEK_CUR);
    536 	if (verboseflag)
    537 		printf("kernel start at pos 0x%lx\n", (unsigned long)kstart);
    538 	kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
    539 	gzclose(gzf);
    540 	kend = lseek(rs6000_fd, 0, SEEK_CUR);
    541 	if (verboseflag)
    542 		printf("kernel end at pos 0x%lx\n", (unsigned long)kend);
    543 
    544 	/* jump back to the length position now that we know the length */
    545 	lseek(rs6000_fd, lenpos, SEEK_SET);
    546 	kgzlen = kend - kstart;
    547 	tmp = sa_htobe32(kgzlen);
    548 	if (verboseflag)
    549 		printf("kernel len = 0x%x tmp = 0x%x\n", kgzlen, tmp);
    550 	write(rs6000_fd, (void *)&tmp, KERNLENSIZE);
    551 
    552 #if 0
    553 	lseek(rs6000_fd, sizeof(boot_record_t) + sizeof(config_record_t),
    554 	    SEEK_SET);
    555 	/* set entry and length */
    556 	length = sa_htole32(0x400);
    557 	write(rs6000_fd, &length, sizeof(length));
    558 	length = sa_htole32(0x400 + elf_img_len + 8 + kgzlen);
    559 	write(rs6000_fd, &length, sizeof(length));
    560 #endif
    561 
    562 	/* generate the header now that we know the kernel length */
    563 	if (verboseflag)
    564 		printf("building records\n");
    565 	rs6000_build_records(elf_img_len + 8 + kgzlen);
    566 	lseek(rs6000_fd, 0, SEEK_SET);
    567 	/* ROM wants it byteswapped in 32bit chunks */
    568 	if (verboseflag)
    569 		printf("writing records\n");
    570 	memcpy(swapped, &bootrec, sizeof(rs6000_boot_record_t));
    571 	for (i=0; i < 128; i++)
    572 		swapped[i] = htonl(swapped[i]);
    573 	write(rs6000_fd, swapped, sizeof(rs6000_boot_record_t));
    574 	memcpy(swapped, &confrec, sizeof(rs6000_config_record_t));
    575 	for (i=0; i < 128; i++)
    576 		swapped[i] = htonl(swapped[i]);
    577 	write(rs6000_fd, swapped, sizeof(rs6000_config_record_t));
    578 
    579 	free(kern_img);
    580 	close(kern_fd);
    581 	close(rs6000_fd);
    582 	close(elf_fd);
    583 
    584 	return 0;
    585 }
    586 
    587 static int
    588 bebox_write_header(int bebox_fd, int elf_image_len, int kern_img_len)
    589 {
    590 	int hsize = BEBOX_HEADER_SIZE;
    591 	unsigned long textOffset, dataOffset, ldrOffset;
    592 	unsigned long entry_vector[3];
    593 	struct FileHeader fileHdr;
    594 	struct SectionHeader textHdr, dataHdr, ldrHdr;
    595 	struct LoaderHeader lh;
    596 
    597 	if (saloneflag)
    598 		hsize = 0;
    599 
    600 	ldrOffset = ULALIGN(sizeof (fileHdr) + sizeof (textHdr) +
    601 	    sizeof (dataHdr) + sizeof (ldrHdr));
    602 	dataOffset = ULALIGN(ldrOffset + sizeof (lh));
    603 	textOffset = ULALIGN(dataOffset + sizeof (entry_vector) + kern_img_len);
    604 
    605 	/* Create the File Header */
    606 	memset(&fileHdr, 0, sizeof (fileHdr));
    607 	fileHdr.magic = sa_htobe32(PEF_MAGIC);
    608 	fileHdr.fileTypeID = sa_htobe32(PEF_FILE);
    609 	fileHdr.archID = sa_htobe32(PEF_PPC);
    610 	fileHdr.versionNumber = sa_htobe32(1);
    611 	fileHdr.numSections = sa_htobe16(3);
    612 	fileHdr.loadableSections = sa_htobe16(2);
    613 	write(bebox_fd, &fileHdr, sizeof (fileHdr));
    614 
    615 	/* Create the Section Header for TEXT */
    616 	memset(&textHdr, 0, sizeof (textHdr));
    617 	textHdr.sectionName = sa_htobe32(-1);
    618 	textHdr.sectionAddress = sa_htobe32(0);
    619 	textHdr.execSize = sa_htobe32(elf_image_len);
    620 	textHdr.initSize = sa_htobe32(elf_image_len);
    621 	textHdr.rawSize = sa_htobe32(elf_image_len);
    622 	textHdr.fileOffset = sa_htobe32(textOffset);
    623 	textHdr.regionKind = CodeSection;
    624 	textHdr.shareKind = ContextShare;
    625 	textHdr.alignment = 4;  /* 16 byte alignment */
    626 	write(bebox_fd, &textHdr, sizeof (textHdr));
    627 
    628 	/* Create the Section Header for DATA */
    629 	memset(&dataHdr, 0, sizeof (dataHdr));
    630 	dataHdr.sectionName = sa_htobe32(-1);
    631 	dataHdr.sectionAddress = sa_htobe32(0);
    632 	dataHdr.execSize = sa_htobe32(sizeof (entry_vector) + kern_img_len);
    633 	dataHdr.initSize = sa_htobe32(sizeof (entry_vector) + kern_img_len);
    634 	dataHdr.rawSize = sa_htobe32(sizeof (entry_vector) + kern_img_len);
    635 	dataHdr.fileOffset = sa_htobe32(dataOffset);
    636 	dataHdr.regionKind = DataSection;
    637 	dataHdr.shareKind = ContextShare;
    638 	dataHdr.alignment = 4;  /* 16 byte alignment */
    639 	write(bebox_fd, &dataHdr, sizeof (dataHdr));
    640 
    641 	/* Create the Section Header for loader stuff */
    642 	memset(&ldrHdr, 0, sizeof (ldrHdr));
    643 	ldrHdr.sectionName = sa_htobe32(-1);
    644 	ldrHdr.sectionAddress = sa_htobe32(0);
    645 	ldrHdr.execSize = sa_htobe32(sizeof (lh));
    646 	ldrHdr.initSize = sa_htobe32(sizeof (lh));
    647 	ldrHdr.rawSize = sa_htobe32(sizeof (lh));
    648 	ldrHdr.fileOffset = sa_htobe32(ldrOffset);
    649 	ldrHdr.regionKind = LoaderSection;
    650 	ldrHdr.shareKind = GlobalShare;
    651 	ldrHdr.alignment = 4;  /* 16 byte alignment */
    652 	write(bebox_fd, &ldrHdr, sizeof (ldrHdr));
    653 
    654 	/* Create the Loader Header */
    655 	memset(&lh, 0, sizeof (lh));
    656 	lh.entryPointSection = sa_htobe32(1);		/* Data */
    657 	lh.entryPointOffset = sa_htobe32(0);
    658 	lh.initPointSection = sa_htobe32(-1);
    659 	lh.initPointOffset = sa_htobe32(0);
    660 	lh.termPointSection = sa_htobe32(-1);
    661 	lh.termPointOffset = sa_htobe32(0);
    662 	lseek(bebox_fd, ldrOffset + hsize, SEEK_SET);
    663 	write(bebox_fd, &lh, sizeof (lh));
    664 
    665 	/* Copy the pseudo-DATA */
    666 	memset(entry_vector, 0, sizeof (entry_vector));
    667 	entry_vector[0] = sa_htobe32(BEBOX_ENTRY);	/* Magic */
    668 	lseek(bebox_fd, dataOffset + hsize, SEEK_SET);
    669 	write(bebox_fd, entry_vector, sizeof (entry_vector));
    670 
    671 	return textOffset;
    672 }
    673 
    674 static int
    675 bebox_build_image(char *kernel, char *boot, char *rawdev, char *outname)
    676 {
    677 	unsigned char *elf_img = NULL, *kern_img = NULL, *header_img = NULL;
    678 	int i, ch, tmp, kgzlen, err, hsize = BEBOX_HEADER_SIZE;
    679 	int elf_fd, bebox_fd, kern_fd, elf_img_len = 0;
    680 	uint32_t swapped[128];
    681 	off_t lenpos, kstart, kend, toff, endoff;
    682 	unsigned long length;
    683 	long flength, *offset;
    684 	gzFile gzf;
    685 	struct stat kern_stat;
    686 	struct bebox_image_block *p;
    687 	struct timeval tp;
    688 	Elf32_External_Phdr phdr;
    689 
    690 	if (saloneflag)
    691 		hsize = 0;
    692 
    693 	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
    694 	if (inkernflag) {
    695 		kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
    696 		kern_len = kern_stat.st_size + BEBOX_MAGICSIZE + KERNLENSIZE;
    697 	} else
    698 		kern_len = BEBOX_MAGICSIZE + KERNLENSIZE;
    699 
    700 	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
    701 		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
    702 			SEEK_SET);
    703 		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
    704 			errx(3, "Can't read input '%s' phdr : %s", boot,
    705 			    strerror(errno));
    706 
    707 		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
    708 		    !(ELFGET32(phdr.p_flags) & PF_X))
    709 			continue;
    710 
    711 		fstat(elf_fd, &elf_stat);
    712 		elf_img_len = ELFGET32(phdr.p_filesz);
    713 		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);
    714 
    715 		break;
    716 	}
    717 	if ((bebox_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
    718 		/* we couldn't open it, it must be new */
    719 		bebox_fd = creat(outname, 0644);
    720 		if (bebox_fd < 0)
    721 			errx(2, "Can't open output '%s': %s", outname,
    722 			    strerror(errno));
    723 	}
    724 	lseek(bebox_fd, hsize, SEEK_SET);
    725 
    726 	if (inkernflag) {
    727 		/*
    728 		 * write the header with the wrong values to get the offset
    729 		 * right
    730 		 */
    731 		bebox_write_header(bebox_fd, elf_img_len, kern_stat.st_size);
    732 
    733 		/* Copy kernel */
    734 		kern_img = (unsigned char *)malloc(kern_stat.st_size);
    735 
    736 		if (kern_img == NULL)
    737 			errx(3, "Can't malloc: %s", strerror(errno));
    738 
    739 		/* we need to jump back after having read the headers */
    740 		lseek(kern_fd, 0, SEEK_SET);
    741 		if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
    742 		    kern_stat.st_size)
    743 			errx(3, "Can't read kernel '%s' : %s",
    744 			    kernel, strerror(errno));
    745 
    746 		gzf = gzdopen(dup(bebox_fd), "a");
    747 		if (gzf == NULL)
    748 			errx(3, "Can't init compression: %s", strerror(errno));
    749 		if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) !=
    750 		    Z_OK)
    751 			errx(3, "%s", gzerror(gzf, &err));
    752 	} else
    753 		bebox_write_header(bebox_fd, elf_img_len, 0);
    754 
    755 	/* write a magic number and size before the kernel */
    756 	write(bebox_fd, (void *)bebox_magic, BEBOX_MAGICSIZE);
    757 	lenpos = lseek(bebox_fd, 0, SEEK_CUR);
    758 	tmp = sa_htobe32(0);
    759 	write(bebox_fd, (void *)&tmp, KERNLENSIZE);
    760 
    761 	if (inkernflag) {
    762 		/* write in the compressed kernel */
    763 		kstart = lseek(bebox_fd, 0, SEEK_CUR);
    764 		kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
    765 		gzclose(gzf);
    766 		kend = lseek(bebox_fd, 0, SEEK_CUR);
    767 		free(kern_img);
    768 	} else {
    769 		kstart = kend = lseek(bebox_fd, 0, SEEK_CUR);
    770 		kgzlen = 0;
    771 	}
    772 
    773 	/* jump back to the length position now that we know the length */
    774 	lseek(bebox_fd, lenpos, SEEK_SET);
    775 	kgzlen = kend - kstart;
    776 	tmp = sa_htobe32(kgzlen);
    777 	write(bebox_fd, (void *)&tmp, KERNLENSIZE);
    778 
    779 	/* now rewrite the header correctly */
    780 	lseek(bebox_fd, hsize, SEEK_SET);
    781 	tmp = kgzlen + BEBOX_MAGICSIZE + KERNLENSIZE;
    782 	toff = bebox_write_header(bebox_fd, elf_img_len, tmp);
    783 
    784 	/* Copy boot image */
    785 	elf_img = (unsigned char *)malloc(elf_img_len);
    786 	if (!elf_img)
    787 		errx(3, "Can't malloc: %s", strerror(errno));
    788 	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
    789 		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));
    790 	lseek(bebox_fd, toff + hsize, SEEK_SET);
    791 	write(bebox_fd, elf_img, elf_img_len);
    792 	free(elf_img);
    793 
    794 	if (inkernflag)
    795 		close(kern_fd);
    796 	close(elf_fd);
    797 
    798 	if (saloneflag) {
    799 		close(bebox_fd);
    800 		return 0;
    801 	}
    802 
    803 	/* Now go back and write in the block header */
    804 	endoff = lseek(bebox_fd, 0, SEEK_END);
    805 	lseek(bebox_fd, 0, SEEK_SET);
    806 	header_img = (unsigned char *)malloc(BEBOX_HEADER_SIZE);
    807 	if (!header_img)
    808 		errx(3, "Can't malloc: %s", strerror(errno));
    809 	memset(header_img, 0, BEBOX_HEADER_SIZE);
    810 
    811 	/* copy the boot image into the buffer */
    812 	for (p = bebox_image_block; p->offset != -1; p++)
    813 		memcpy(header_img + p->offset, p->data, p->size);
    814 
    815 	/* fill used block bitmap */
    816 	memset(header_img + BEBOX_FILE_BLOCK_MAP_START, 0xff,
    817 	    BEBOX_FILE_BLOCK_MAP_END - BEBOX_FILE_BLOCK_MAP_START);
    818 
    819 	/* fix the file size in the header */
    820 	tmp = endoff - BEBOX_HEADER_SIZE;
    821 	*(long *)(header_img + BEBOX_FILE_SIZE_OFFSET) =
    822 	    (long)sa_htobe32(tmp);
    823 	*(long *)(header_img + BEBOX_FILE_SIZE_ALIGN_OFFSET) =
    824 	    (long)sa_htobe32(roundup(tmp, BEBOX_FILE_BLOCK_SIZE));
    825 
    826 	gettimeofday(&tp, 0);
    827 	for (offset = bebox_mtime_offset; *offset != -1; offset++)
    828 		*(long *)(header_img + *offset) = (long)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