Home | History | Annotate | Line # | Download | only in mkbootimage
mkbootimage.c revision 1.1
      1 /*	$NetBSD: mkbootimage.c,v 1.1 2007/12/18 18:19:07 garbled Exp $	*/
      2 
      3 /*-
      4  * Copyright (C) 2006 Tim Rightnour
      5  * Copyright (C) 1999, 2000 NONAKA Kimihiro (nonaka (at) NetBSD.org)
      6  * Copyright (C) 1996, 1997, 1998, 1999 Cort Dougan (cort (at) fsmlasb.com)
      7  * Copyright (C) 1996, 1997, 1998, 1999 Paul Mackeras (paulus (at) linuxcare.com)
      8  * All rights reserved.
      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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *      This product includes software developed by Gary Thomas.
     21  * 4. The name of the author may not be used to endorse or promote products
     22  *    derived from this software without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     27  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     29  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     33  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     34  */
     35 
     36 #if HAVE_NBTOOL_CONFIG_H
     37 #include "nbtool_config.h"
     38 #include "../../sys/sys/bootblock.h"
     39 #else
     40 #include <sys/bootblock.h>
     41 #endif
     42 
     43 #include <stdio.h>
     44 #include <stdlib.h>
     45 #include <string.h>
     46 #include <fcntl.h>
     47 #include <unistd.h>
     48 #include <errno.h>
     49 #include <zlib.h>
     50 #include <err.h>
     51 #include <sys/stat.h>
     52 #include <sys/types.h>
     53 #include <sys/uio.h>
     54 
     55 /* BFD ELF headers */
     56 #include <elf/common.h>
     57 #include <elf/external.h>
     58 
     59 #include "byteorder.h"
     60 #include "magic.h"
     61 
     62 /* Globals */
     63 
     64 int saloneflag = 0;
     65 Elf32_External_Ehdr hdr, khdr;
     66 struct stat elf_stat;
     67 unsigned char mbr[512];
     68 
     69 /*
     70  * Macros to get values from multi-byte ELF header fields.  These assume
     71  * a big-endian image.
     72  */
     73 #define	ELFGET16(x)	(((x)[0] << 8) | (x)[1])
     74 
     75 #define	ELFGET32(x)	(((x)[0] << 24) | ((x)[1] << 16) |		\
     76 			 ((x)[2] <<  8) |  (x)[3])
     77 
     78 static void usage(void);
     79 static int open_file(const char *, char *, Elf32_External_Ehdr *,
     80     struct stat *);
     81 static void check_mbr(int, int, char *);
     82 int main(int, char **);
     83 
     84 static void
     85 usage(void)
     86 {
     87 	fprintf(stderr, "usage: %s [-ls] [-b bootfile] [-k kernel] [-r rawdev]"
     88 	    " bootimage\n", getprogname());
     89 	exit(1);
     90 }
     91 
     92 /* verify the file is ELF and ppc, and open it up */
     93 static int
     94 open_file(const char *ftype, char *file, Elf32_External_Ehdr *hdr,
     95 	struct stat *f_stat)
     96 {
     97 	int fd;
     98 
     99 	if ((fd = open(file, 0)) < 0)
    100 		errx(2, "Can't open %s '%s': %s", ftype, file, strerror(errno));
    101 	fstat(fd, f_stat);
    102 
    103 	if (read(fd, hdr, sizeof(Elf32_External_Ehdr)) !=
    104 	    sizeof(Elf32_External_Ehdr))
    105 		errx(3, "Can't read input '%s': %s", file, strerror(errno));
    106 
    107 	if (hdr->e_ident[EI_MAG0] != ELFMAG0 ||
    108 	    hdr->e_ident[EI_MAG1] != ELFMAG1 ||
    109 	    hdr->e_ident[EI_MAG2] != ELFMAG2 ||
    110 	    hdr->e_ident[EI_MAG3] != ELFMAG3 ||
    111 	    hdr->e_ident[EI_CLASS] != ELFCLASS32)
    112 		errx(3, "input '%s' is not ELF32 format", file);
    113 
    114 	if (hdr->e_ident[EI_DATA] != ELFDATA2MSB)
    115 		errx(3, "input '%s' is not big-endian", file);
    116 
    117 	if (ELFGET16(hdr->e_machine) != EM_PPC)
    118 		errx(3, "input '%s' is not PowerPC exec binary", file);
    119 
    120 	return(fd);
    121 }
    122 
    123 static void
    124 check_mbr(int prep_fd, int lfloppyflag, char *rawdev)
    125 {
    126 	int raw_fd;
    127 	unsigned long entry, length;
    128 	struct mbr_partition *mbrp;
    129 	struct stat raw_stat;
    130 
    131 	/* If we are building a standalone image, do not write an MBR, just
    132 	 * set entry point and boot image size skipping over elf header
    133 	 */
    134 	if (saloneflag) {
    135 		entry  = sa_htole32(0x400);
    136 		length = sa_htole32(elf_stat.st_size - sizeof(hdr) + 0x400);
    137 		lseek(prep_fd, sizeof(mbr), SEEK_SET);
    138 		write(prep_fd, &entry, sizeof(entry));
    139 		write(prep_fd, &length, sizeof(length));
    140 		return;
    141 	}
    142 
    143 	/*
    144 	 * if we have a raw device, we need to check to see if it already
    145 	 * has a partition table, and if so, read it in and check for
    146 	 * suitability.
    147 	 */
    148 	if (rawdev != NULL) {
    149 		raw_fd = open(rawdev, O_RDONLY, 0);
    150 		if (raw_fd == -1)
    151 			errx(3, "couldn't open raw device %s: %s", rawdev,
    152 			    strerror(errno));
    153 
    154 		fstat(raw_fd, &raw_stat);
    155 		if (!S_ISCHR(raw_stat.st_mode))
    156 			errx(3, "%s is not a raw device", rawdev);
    157 
    158 		if (read(raw_fd, mbr, 512) != 512)
    159 			errx(3, "MBR Read Failed: %s", strerror(errno));
    160 
    161 		mbrp = (struct mbr_partition *)&mbr[MBR_PART_OFFSET];
    162 		if (mbrp->mbrp_type != MBR_PTYPE_PREP)
    163 			errx(3, "First partition is not of type 0x%x.",
    164 			    MBR_PTYPE_PREP);
    165 		if (mbrp->mbrp_start != 0)
    166 			errx(3, "Use of the raw device is intended for"
    167 			    " upgrading of legacy installations.  Your"
    168 			    " install does not have a PReP boot partition"
    169 			    " starting at sector 0.  Use the -s option"
    170 			    " to build an image instead.");
    171 
    172 		/* if we got this far, we are fine, write back the partition
    173 		 * and write the entry points and get outta here */
    174 	/* Set entry point and boot image size skipping over elf header */
    175 		lseek(prep_fd, 0, SEEK_SET);
    176 		entry  = sa_htole32(0x400);
    177 		length = sa_htole32(elf_stat.st_size - sizeof(hdr) + 0x400);
    178 		write(prep_fd, mbr, sizeof(mbr));
    179 		write(prep_fd, &entry, sizeof(entry));
    180 		write(prep_fd, &length, sizeof(length));
    181 		close(raw_fd);
    182 		return;
    183 	}
    184 
    185 	/* if we get to here, we want to build a standard floppy or netboot
    186 	 * image to file, so just build it */
    187 
    188 	memset(mbr, 0, sizeof(mbr));
    189 	mbrp = (struct mbr_partition *)&mbr[MBR_PART_OFFSET];
    190 
    191 	/* Set entry point and boot image size skipping over elf header */
    192 	entry  = sa_htole32(0x400);
    193 	length = sa_htole32(elf_stat.st_size - sizeof(hdr) + 0x400);
    194 
    195 	/*
    196 	 * Set magic number for msdos partition
    197 	 */
    198 	*(unsigned short *)&mbr[MBR_MAGIC_OFFSET] = sa_htole16(MBR_MAGIC);
    199 
    200 	/*
    201 	 * Build a "PReP" partition table entry in the boot record
    202 	 *  - "PReP" may only look at the system_indicator
    203 	 */
    204 	mbrp->mbrp_flag = MBR_PFLAG_ACTIVE;
    205 	mbrp->mbrp_type  = MBR_PTYPE_PREP;
    206 
    207 	/*
    208 	 * The first block of the diskette is used by this "boot record" which
    209 	 * actually contains the partition table. (The first block of the
    210 	 * partition contains the boot image, but I digress...)  We'll set up
    211 	 * one partition on the diskette and it shall contain the rest of the
    212 	 * diskette.
    213 	 */
    214 	mbrp->mbrp_shd   = 0;	/* zero-based			     */
    215 	mbrp->mbrp_ssect = 2;	/* one-based			     */
    216 	mbrp->mbrp_scyl  = 0;	/* zero-based			     */
    217 	mbrp->mbrp_ehd   = 1;	/* assumes two heads		     */
    218 	if (lfloppyflag)
    219 		mbrp->mbrp_esect = 36;  /* 2.88MB floppy	     */
    220 	else
    221 		mbrp->mbrp_esect = 18;	/* assumes 18 sectors/track  */
    222 	mbrp->mbrp_ecyl  = 79;	/* assumes 80 cylinders/diskette     */
    223 
    224 	/*
    225 	 * The "PReP" software ignores the above fields and just looks at
    226 	 * the next two.
    227 	 *   - size of the diskette is (assumed to be)
    228 	 *     (2 tracks/cylinder)(18 sectors/tracks)(80 cylinders/diskette)
    229 	 *   - unlike the above sector numbers,
    230 	 *     the beginning sector is zero-based!
    231 	 */
    232 
    233 	/* This has to be 0 on the PowerStack? */
    234 	mbrp->mbrp_start = sa_htole32(0);
    235 	mbrp->mbrp_size  = sa_htole32(2 * 18 * 80 - 1);
    236 
    237 	write(prep_fd, mbr, sizeof(mbr));
    238 	write(prep_fd, &entry, sizeof(entry));
    239 	write(prep_fd, &length, sizeof(length));
    240 }
    241 
    242 int
    243 main(int argc, char **argv)
    244 {
    245 	unsigned char *elf_img = NULL, *kern_img = NULL;
    246 	int i, ch, tmp, kgzlen, err, lfloppyflag=0;
    247 	int elf_fd, prep_fd, kern_fd, elf_img_len = 0;
    248 	off_t lenpos, kstart, kend;
    249 	unsigned long length;
    250 	long flength;
    251 	gzFile gzf;
    252 	struct stat kern_stat;
    253 	char *kernel = NULL, *boot = NULL, *rawdev = NULL;
    254 	Elf32_External_Phdr phdr;
    255 
    256 	setprogname(argv[0]);
    257 	kern_len = 0;
    258 
    259 	while ((ch = getopt(argc, argv, "b:k:lr:s")) != -1)
    260 		switch (ch) {
    261 		case 'b':
    262 			boot = optarg;
    263 			break;
    264 		case 'k':
    265 			kernel = optarg;
    266 			break;
    267 		case 'l':
    268 			lfloppyflag = 1;
    269 			break;
    270 		case 'r':
    271 			rawdev = optarg;
    272 			break;
    273 		case 's':
    274 			saloneflag = 1;
    275 			break;
    276 		case '?':
    277 		default:
    278 			usage();
    279 			/* NOTREACHED */
    280 		}
    281 	argc -= optind;
    282 	argv += optind;
    283 
    284 	if (argc < 1)
    285 		usage();
    286 
    287 	if (kernel == NULL)
    288 		kernel = "/netbsd";
    289 
    290 	if (boot == NULL)
    291 		boot = "/usr/mdec/boot";
    292 
    293 	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
    294 	kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
    295 	kern_len = kern_stat.st_size + MAGICSIZE + KERNLENSIZE;
    296 
    297 	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
    298 		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
    299 			SEEK_SET);
    300 		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
    301 			errx(3, "Can't read input '%s' phdr : %s", boot,
    302 			    strerror(errno));
    303 
    304 		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
    305 		    !(ELFGET32(phdr.p_flags) & PF_X))
    306 			continue;
    307 
    308 		fstat(elf_fd, &elf_stat);
    309 		elf_img_len = elf_stat.st_size - ELFGET32(phdr.p_offset);
    310 		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);
    311 
    312 		break;
    313 	}
    314 	if ((prep_fd = open(argv[0], O_RDWR|O_TRUNC, 0)) < 0) {
    315 		/* we couldn't open it, it must be new */
    316 		prep_fd = creat(argv[0], 0644);
    317 		if (prep_fd < 0)
    318 			errx(2, "Can't open output '%s': %s", argv[0],
    319 			    strerror(errno));
    320 	}
    321 
    322 	check_mbr(prep_fd, lfloppyflag, rawdev);
    323 
    324 	/* Set file pos. to 2nd sector where image will be written */
    325 	lseek(prep_fd, 0x400, SEEK_SET);
    326 
    327 	/* Copy boot image */
    328 	elf_img = (unsigned char *)malloc(elf_img_len);
    329 	if (!elf_img)
    330 		errx(3, "Can't malloc: %s", strerror(errno));
    331 	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
    332 		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));
    333 
    334 	write(prep_fd, elf_img, elf_img_len);
    335 	free(elf_img);
    336 
    337 	/* Copy kernel */
    338 	kern_img = (unsigned char *)malloc(kern_stat.st_size);
    339 
    340 	if (kern_img == NULL)
    341 		errx(3, "Can't malloc: %s", strerror(errno));
    342 
    343 	/* we need to jump back after having read the headers */
    344 	lseek(kern_fd, 0, SEEK_SET);
    345 	if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
    346 	    kern_stat.st_size)
    347 		errx(3, "Can't read kernel '%s' : %s", kernel, strerror(errno));
    348 
    349 	gzf = gzdopen(dup(prep_fd), "a");
    350 	if (gzf == NULL)
    351 		errx(3, "Can't init compression: %s", strerror(errno));
    352 	if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) != Z_OK)
    353 		errx(3, "%s", gzerror(gzf, &err));
    354 
    355 	/* write a magic number and size before the kernel */
    356 	write(prep_fd, (void *)magic, MAGICSIZE);
    357 	lenpos = lseek(prep_fd, 0, SEEK_CUR);
    358 	tmp = sa_htobe32(0);
    359 	write(prep_fd, (void *)&tmp, KERNLENSIZE);
    360 
    361 	/* write in the compressed kernel */
    362 	kstart = lseek(prep_fd, 0, SEEK_CUR);
    363 	kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
    364 	gzclose(gzf);
    365 	kend = lseek(prep_fd, 0, SEEK_CUR);
    366 
    367 	/* jump back to the length position now that we know the length */
    368 	lseek(prep_fd, lenpos, SEEK_SET);
    369 	kgzlen = kend - kstart;
    370 	tmp = sa_htobe32(kgzlen);
    371 	write(prep_fd, (void *)&tmp, KERNLENSIZE);
    372 
    373 	length = sa_htole32(0x400 + elf_img_len + 8 + kgzlen);
    374 	lseek(prep_fd, sizeof(mbr) + 4, SEEK_SET);
    375 	write(prep_fd, &length, sizeof(length));
    376 
    377 	flength = 0x400 + elf_img_len + 8 + kgzlen;
    378 	if (lfloppyflag)
    379 		flength -= (5760 * 512);
    380 	else
    381 		flength -= (2880 * 512);
    382 	if (flength > 0 && !saloneflag)
    383 		fprintf(stderr, "%s: Image %s is %d bytes larger than single"
    384 		    " floppy. Can only be used for netboot.\n", getprogname(),
    385 		    argv[0], flength);
    386 
    387 	free(kern_img);
    388 	close(kern_fd);
    389 	close(prep_fd);
    390 	close(elf_fd);
    391 
    392 	return 0;
    393 }
    394