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