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