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