xref: /openbsd-src/usr.sbin/installboot/i386_installboot.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /*	$OpenBSD: i386_installboot.c,v 1.34 2020/02/28 12:26:30 otto Exp $	*/
2 /*	$NetBSD: installboot.c,v 1.5 1995/11/17 23:23:50 gwr Exp $ */
3 
4 /*
5  * Copyright (c) 2013 Pedro Martelletto
6  * Copyright (c) 2011 Joel Sing <jsing@openbsd.org>
7  * Copyright (c) 2003 Tom Cosgrove <tom.cosgrove@arches-consulting.com>
8  * Copyright (c) 1997 Michael Shalayeff
9  * Copyright (c) 1994 Paul Kranenburg
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *      This product includes software developed by Paul Kranenburg.
23  * 4. The name of the author may not be used to endorse or promote products
24  *    derived from this software without specific prior written permission
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #define ELFSIZE 32
39 
40 #include <sys/param.h>	/* DEV_BSIZE */
41 #include <sys/disklabel.h>
42 #include <sys/dkio.h>
43 #include <sys/ioctl.h>
44 #include <sys/mount.h>
45 #include <sys/reboot.h>
46 #include <sys/stat.h>
47 #include <sys/sysctl.h>
48 #include <sys/time.h>
49 
50 #include <ufs/ufs/dinode.h>
51 #include <ufs/ufs/dir.h>
52 #include <ufs/ffs/fs.h>
53 
54 #include <machine/cpu.h>
55 #include <machine/biosvar.h>
56 
57 #include <elf.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <nlist.h>
62 #include <stdlib.h>
63 #include <stdio.h>
64 #include <stdint.h>
65 #include <string.h>
66 #include <unistd.h>
67 #include <util.h>
68 #include <uuid.h>
69 
70 #include "installboot.h"
71 #include "i386_installboot.h"
72 
73 char	*bootldr;
74 
75 char	*blkstore;
76 size_t	blksize;
77 
78 struct sym_data pbr_symbols[] = {
79 	{"_fs_bsize_p",	2},
80 	{"_fs_bsize_s",	2},
81 	{"_fsbtodb",	1},
82 	{"_p_offset",	4},
83 	{"_inodeblk",	4},
84 	{"_inodedbl",	4},
85 	{"_nblocks",	2},
86 	{"_blkincr",	1},
87 	{NULL}
88 };
89 
90 static void	devread(int, void *, daddr_t, size_t, char *);
91 static u_int	findopenbsd(int, struct disklabel *);
92 static int	getbootparams(char *, int, struct disklabel *);
93 static char	*loadproto(char *, long *);
94 static int	gpt_chk_mbr(struct dos_partition *, u_int64_t);
95 static int	sbchk(struct fs *, daddr_t);
96 static void	sbread(int, daddr_t, struct fs **, char *);
97 
98 static const daddr_t sbtry[] = SBLOCKSEARCH;
99 
100 /*
101  * Read information about /boot's inode and filesystem parameters, then
102  * put biosboot (partition boot record) on the target drive with these
103  * parameters patched in.
104  */
105 
106 void
107 md_init(void)
108 {
109 	stages = 2;
110 	stage1 = "/usr/mdec/biosboot";
111 	stage2 = "/usr/mdec/boot";
112 
113 	bootldr = "/boot";
114 }
115 
116 void
117 md_loadboot(void)
118 {
119 	/* Load prototype boot blocks. */
120 	if ((blkstore = loadproto(stage1, &blksize)) == NULL)
121 		exit(1);
122 
123 	/* XXX - Paranoia: Make sure size is aligned! */
124 	if (blksize & (DEV_BSIZE - 1))
125 		errx(1, "proto %s bad size=%ld", stage1, blksize);
126 
127 	if (blksize > SBSIZE - DEV_BSIZE)
128 		errx(1, "proto bootblocks too big");
129 }
130 
131 void
132 md_installboot(int devfd, char *dev)
133 {
134 	struct disklabel dl;
135 	int part;
136 
137 	/* Get and check disklabel. */
138 	if (ioctl(devfd, DIOCGDINFO, &dl) == -1)
139 		err(1, "disklabel: %s", dev);
140 	if (dl.d_magic != DISKMAGIC)
141 		errx(1, "bad disklabel magic=0x%08x", dl.d_magic);
142 
143 	/* Warn on unknown disklabel types. */
144 	if (dl.d_type == 0)
145 		warnx("disklabel type unknown");
146 
147 	part = findgptefisys(devfd, &dl);
148 	if (part != -1) {
149 		write_efisystem(&dl, (char)part);
150 		return;
151 	}
152 
153 	bootldr = fileprefix(root, bootldr);
154 	if (bootldr == NULL)
155 		exit(1);
156 	if (verbose)
157 		fprintf(stderr, "%s %s to %s\n",
158 		    (nowrite ? "would copy" : "copying"), stage2, bootldr);
159 	if (!nowrite)
160 		if (filecopy(stage2, bootldr) == -1)
161 			exit(1);
162 
163 	/* Get bootstrap parameters to patch into proto. */
164 	if (getbootparams(bootldr, devfd, &dl) != 0)
165 		exit(1);
166 
167 	/* Write boot blocks to device. */
168 	write_bootblocks(devfd, dev, &dl);
169 }
170 
171 void
172 write_bootblocks(int devfd, char *dev, struct disklabel *dl)
173 {
174 	struct stat	sb;
175 	u_int8_t	*secbuf;
176 	u_int		start = 0;
177 
178 	/* Write patched proto bootblock(s) into the superblock. */
179 	if (fstat(devfd, &sb) == -1)
180 		err(1, "fstat: %s", dev);
181 
182 	if (!S_ISCHR(sb.st_mode))
183 		errx(1, "%s: not a character device", dev);
184 
185 	/* Patch the parameters into the proto bootstrap sector. */
186 	pbr_set_symbols(stage1, blkstore, pbr_symbols);
187 
188 	if (!nowrite) {
189 		/* Sync filesystems (to clean in-memory superblock?). */
190 		sync(); sleep(1);
191 	}
192 
193 	/*
194 	 * Find OpenBSD partition. Floppies are special, getting an
195 	 * everything-in-one /boot starting at sector 0.
196 	 */
197 	if (dl->d_type != DTYPE_FLOPPY) {
198 		start = findopenbsd(devfd, dl);
199 		if (start == (u_int)-1)
200 			errx(1, "no OpenBSD partition");
201 	}
202 
203 	if (verbose)
204 		fprintf(stderr, "%s will be written at sector %u\n",
205 		    stage1, start);
206 
207 	if (start + (blksize / dl->d_secsize) > BOOTBIOS_MAXSEC)
208 		warnx("%s extends beyond sector %u. OpenBSD might not boot.",
209 		    stage1, BOOTBIOS_MAXSEC);
210 
211 	if (!nowrite) {
212 		secbuf = calloc(1, dl->d_secsize);
213 		if (pread(devfd, secbuf, dl->d_secsize, (off_t)start *
214 		    dl->d_secsize) != dl->d_secsize)
215 			err(1, "pread boot sector");
216 		bcopy(blkstore, secbuf, blksize);
217 		if (pwrite(devfd, secbuf, dl->d_secsize, (off_t)start *
218 		    dl->d_secsize) != dl->d_secsize)
219 			err(1, "pwrite bootstrap");
220 		free(secbuf);
221 	}
222 }
223 
224 void
225 write_efisystem(struct disklabel *dl, char part)
226 {
227 	static char *fsckfmt = "/sbin/fsck_msdos %s >/dev/null";
228 	static char *newfsfmt ="/sbin/newfs_msdos %s >/dev/null";
229 	struct msdosfs_args args;
230 	char cmd[60];
231 	char dst[PATH_MAX];
232 	char *src;
233 	size_t mntlen, pathlen, srclen;
234 	int rslt;
235 
236 	src = NULL;
237 
238 	/* Create directory for temporary mount point. */
239 	strlcpy(dst, "/tmp/installboot.XXXXXXXXXX", sizeof(dst));
240 	if (mkdtemp(dst) == NULL)
241 		err(1, "mkdtemp('%s') failed", dst);
242 	mntlen = strlen(dst);
243 
244 	/* Mount <duid>.<part> as msdos filesystem. */
245 	memset(&args, 0, sizeof(args));
246 	rslt = asprintf(&args.fspec,
247 	    "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx.%c",
248             dl->d_uid[0], dl->d_uid[1], dl->d_uid[2], dl->d_uid[3],
249             dl->d_uid[4], dl->d_uid[5], dl->d_uid[6], dl->d_uid[7],
250 	    part);
251 	if (rslt == -1) {
252 		warn("bad special device");
253 		goto rmdir;
254 	}
255 
256 	args.export_info.ex_root = -2;	/* unchecked anyway on DOS fs */
257 	args.export_info.ex_flags = 0;
258 
259 	if (mount(MOUNT_MSDOS, dst, 0, &args) == -1) {
260 		/* Try fsck'ing it. */
261 		rslt = snprintf(cmd, sizeof(cmd), fsckfmt, args.fspec);
262 		if (rslt >= sizeof(cmd)) {
263 			warnx("can't build fsck command");
264 			rslt = -1;
265 			goto rmdir;
266 		}
267 		rslt = system(cmd);
268 		if (rslt == -1) {
269 			warn("system('%s') failed", cmd);
270 			goto rmdir;
271 		}
272 		if (mount(MOUNT_MSDOS, dst, 0, &args) == -1) {
273 			/* Try newfs'ing it. */
274 			rslt = snprintf(cmd, sizeof(cmd), newfsfmt,
275 			    args.fspec);
276 			if (rslt >= sizeof(cmd)) {
277 				warnx("can't build newfs command");
278 				rslt = -1;
279 				goto rmdir;
280 			}
281 			rslt = system(cmd);
282 			if (rslt == -1) {
283 				warn("system('%s') failed", cmd);
284 				goto rmdir;
285 			}
286 			rslt = mount(MOUNT_MSDOS, dst, 0, &args);
287 			if (rslt == -1) {
288 				warn("unable to mount EFI System partition");
289 				goto rmdir;
290 			}
291 		}
292 	}
293 
294 	/* Create "/efi/BOOT" directory in <duid>.<part>. */
295 	if (strlcat(dst, "/efi", sizeof(dst)) >= sizeof(dst)) {
296 		rslt = -1;
297 		warn("unable to build /efi directory");
298 		goto umount;
299 	}
300 	rslt = mkdir(dst, 0);
301 	if (rslt == -1 && errno != EEXIST) {
302 		warn("mkdir('%s') failed", dst);
303 		goto umount;
304 	}
305 	if (strlcat(dst, "/BOOT", sizeof(dst)) >= sizeof(dst)) {
306 		rslt = -1;
307 		warn("unable to build /BOOT directory");
308 		goto umount;
309 	}
310 	rslt = mkdir(dst, 0);
311 	if (rslt == -1 && errno != EEXIST) {
312 		warn("mkdir('%s') failed", dst);
313 		goto umount;
314 	}
315 
316 	/*
317 	 * Copy BOOTIA32.EFI and BOOTX64.EFI to /efi/BOOT/.
318 	 *
319 	 * N.B.: BOOTIA32.EFI is longer than BOOTX64.EFI, so src can be reused!
320 	 */
321 	pathlen = strlen(dst);
322 	if (strlcat(dst, "/BOOTIA32.EFI", sizeof(dst)) >= sizeof(dst)) {
323 		rslt = -1;
324 		warn("unable to build /BOOTIA32.EFI path");
325 		goto umount;
326 	}
327 	src = fileprefix(root, "/usr/mdec/BOOTIA32.EFI");
328 	if (src == NULL) {
329 		rslt = -1;
330 		goto umount;
331 	}
332 	srclen = strlen(src);
333 	if (verbose)
334 		fprintf(stderr, "%s %s to %s\n",
335 		    (nowrite ? "would copy" : "copying"), src, dst);
336 	if (!nowrite) {
337 		rslt = filecopy(src, dst);
338 		if (rslt == -1)
339 			goto umount;
340 	}
341 	src[srclen - strlen("/BOOTIA32.EFI")] = '\0';
342 
343 	dst[pathlen] = '\0';
344 	if (strlcat(dst, "/BOOTX64.EFI", sizeof(dst)) >= sizeof(dst)) {
345 		rslt = -1;
346 		warn("unable to build /BOOTX64.EFI dst path");
347 		goto umount;
348 	}
349 	if (strlcat(src, "/BOOTX64.EFI", srclen+1) >= srclen+1) {
350 		rslt = -1;
351 		warn("unable to build /BOOTX64.EFI src path");
352 		goto umount;
353 	}
354 	if (verbose)
355 		fprintf(stderr, "%s %s to %s\n",
356 		    (nowrite ? "would copy" : "copying"), src, dst);
357 	if (!nowrite) {
358 		rslt = filecopy(src, dst);
359 		if (rslt == -1)
360 			goto umount;
361 	}
362 
363 	rslt = 0;
364 
365 umount:
366 	dst[mntlen] = '\0';
367 	if (unmount(dst, MNT_FORCE) == -1)
368 		err(1, "unmount('%s') failed", dst);
369 
370 rmdir:
371 	free(args.fspec);
372 	dst[mntlen] = '\0';
373 	if (rmdir(dst) == -1)
374 		err(1, "rmdir('%s') failed", dst);
375 
376 	free(src);
377 
378 	if (rslt == -1)
379 		exit(1);
380 }
381 
382 u_int
383 findopenbsd(int devfd, struct disklabel *dl)
384 {
385 	struct		dos_mbr mbr;
386 	u_int		mbroff = DOSBBSECTOR;
387 	u_int		mbr_eoff = DOSBBSECTOR; /* Offset of extended part. */
388 	struct		dos_partition *dp;
389 	u_int8_t	*secbuf;
390 	u_int		maxebr = DOS_MAXEBR, nextebr;
391 	int		i;
392 
393 again:
394 	if (!maxebr--) {
395 		if (verbose)
396 			fprintf(stderr, "Traversed more than %d Extended Boot "
397 			    "Records (EBRs)\n", DOS_MAXEBR);
398 		return ((u_int)-1);
399 	}
400 
401 	if (verbose)
402 		fprintf(stderr, "%s boot record (%cBR) at sector %u\n",
403 		    (mbroff == DOSBBSECTOR) ? "master" : "extended",
404 		    (mbroff == DOSBBSECTOR) ? 'M' : 'E', mbroff);
405 
406 	if ((secbuf = malloc(dl->d_secsize)) == NULL)
407 		err(1, NULL);
408 	if (pread(devfd, secbuf, dl->d_secsize, (off_t)mbroff * dl->d_secsize)
409 	    < (ssize_t)sizeof(mbr))
410 		err(4, "can't pread boot record");
411 	bcopy(secbuf, &mbr, sizeof(mbr));
412 	free(secbuf);
413 
414 	if (mbr.dmbr_sign != DOSMBR_SIGNATURE)
415 		errx(1, "invalid boot record signature (0x%04X) @ sector %u",
416 		    mbr.dmbr_sign, mbroff);
417 
418 	nextebr = 0;
419 	for (i = 0; i < NDOSPART; i++) {
420 		dp = &mbr.dmbr_parts[i];
421 		if (!dp->dp_size)
422 			continue;
423 
424 		if (verbose)
425 			fprintf(stderr,
426 			    "\tpartition %d: type 0x%02X offset %u size %u\n",
427 			    i, dp->dp_typ, dp->dp_start, dp->dp_size);
428 
429 		if (dp->dp_typ == DOSPTYP_OPENBSD) {
430 			if (dp->dp_start > (dp->dp_start + mbroff))
431 				continue;
432 			return (dp->dp_start + mbroff);
433 		}
434 
435 		if (!nextebr && (dp->dp_typ == DOSPTYP_EXTEND ||
436 		    dp->dp_typ == DOSPTYP_EXTENDL)) {
437 			nextebr = dp->dp_start + mbr_eoff;
438 			if (nextebr < dp->dp_start)
439 				nextebr = (u_int)-1;
440 			if (mbr_eoff == DOSBBSECTOR)
441 				mbr_eoff = dp->dp_start;
442 		}
443 	}
444 
445 	if (nextebr && nextebr != (u_int)-1) {
446 		mbroff = nextebr;
447 		goto again;
448 	}
449 
450 	return ((u_int)-1);
451 }
452 
453 /*
454  * Returns 0 if the MBR with the provided partition array is a GPT protective
455  * MBR, and returns 1 otherwise. A GPT protective MBR would have one and only
456  * one MBR partition, an EFI partition that either covers the whole disk or as
457  * much of it as is possible with a 32bit size field.
458  *
459  * NOTE: MS always uses a size of UINT32_MAX for the EFI partition!**
460  */
461 static int
462 gpt_chk_mbr(struct dos_partition *dp, u_int64_t dsize)
463 {
464 	struct dos_partition *dp2;
465 	int efi, found, i;
466 	u_int32_t psize;
467 
468 	found = efi = 0;
469 	for (dp2=dp, i=0; i < NDOSPART; i++, dp2++) {
470 		if (dp2->dp_typ == DOSPTYP_UNUSED)
471 			continue;
472 		found++;
473 		if (dp2->dp_typ != DOSPTYP_EFI)
474 			continue;
475 		psize = letoh32(dp2->dp_size);
476 		if (psize == (dsize - 1) ||
477 		    psize == UINT32_MAX) {
478 			if (letoh32(dp2->dp_start) == 1)
479 				efi++;
480 		}
481 	}
482 	if (found == 1 && efi == 1)
483 		return (0);
484 
485 	return (1);
486 }
487 
488 int
489 findgptefisys(int devfd, struct disklabel *dl)
490 {
491 	struct gpt_partition	 gp[NGPTPARTITIONS];
492 	struct gpt_header	 gh;
493 	struct dos_partition	 dp[NDOSPART];
494 	struct uuid		 efisys_uuid;
495 	const char		 efisys_uuid_code[] = GPT_UUID_EFI_SYSTEM;
496 	off_t			 off;
497 	ssize_t			 len;
498 	u_int64_t		 start;
499 	int			 i;
500 	uint32_t		 orig_csum, new_csum;
501 	uint32_t		 ghsize, ghpartsize, ghpartnum, ghpartspersec;
502 	u_int8_t		*secbuf;
503 
504 	/* Prepare EFI System UUID */
505 	uuid_dec_be(efisys_uuid_code, &efisys_uuid);
506 
507 	if ((secbuf = malloc(dl->d_secsize)) == NULL)
508 		err(1, NULL);
509 
510 	/* Check that there is a protective MBR. */
511 	len = pread(devfd, secbuf, dl->d_secsize, 0);
512 	if (len != dl->d_secsize)
513 		err(4, "can't read mbr");
514 	memcpy(dp, &secbuf[DOSPARTOFF], sizeof(dp));
515 	if (gpt_chk_mbr(dp, DL_GETDSIZE(dl))) {
516 		free(secbuf);
517 		return (-1);
518 	}
519 
520 	/* Check GPT Header. */
521 	off = dl->d_secsize;	/* Read header from sector 1. */
522 	len = pread(devfd, secbuf, dl->d_secsize, off);
523 	if (len != dl->d_secsize)
524 		err(4, "can't pread gpt header");
525 
526 	memcpy(&gh, secbuf, sizeof(gh));
527 	free(secbuf);
528 
529 	/* Check signature */
530 	if (letoh64(gh.gh_sig) != GPTSIGNATURE)
531 		return (-1);
532 
533 	if (letoh32(gh.gh_rev) != GPTREVISION)
534 		return (-1);
535 
536 	ghsize = letoh32(gh.gh_size);
537 	if (ghsize < GPTMINHDRSIZE || ghsize > sizeof(struct gpt_header))
538 		return (-1);
539 
540 	/* Check checksum */
541 	orig_csum = gh.gh_csum;
542 	gh.gh_csum = 0;
543 	new_csum = crc32((unsigned char *)&gh, ghsize);
544 	gh.gh_csum = orig_csum;
545 	if (letoh32(orig_csum) != new_csum)
546 		return (-1);
547 
548 	off = letoh64(gh.gh_part_lba) * dl->d_secsize;
549 	ghpartsize = letoh32(gh.gh_part_size);
550 	ghpartspersec = dl->d_secsize / ghpartsize;
551 	ghpartnum = letoh32(gh.gh_part_num);
552 	if ((secbuf = malloc(dl->d_secsize)) == NULL)
553 		err(1, NULL);
554 	for (i = 0; i < (ghpartnum + ghpartspersec - 1) / ghpartspersec; i++) {
555 		len = pread(devfd, secbuf, dl->d_secsize, off);
556 		if (len != dl->d_secsize) {
557 			free(secbuf);
558 			return (-1);
559 		}
560 		memcpy(gp + i * ghpartspersec, secbuf,
561 		    ghpartspersec * sizeof(struct gpt_partition));
562 		off += dl->d_secsize;
563 	}
564 	free(secbuf);
565 	new_csum = crc32((unsigned char *)&gp, ghpartnum * ghpartsize);
566 	if (new_csum != letoh32(gh.gh_part_csum))
567 		return (-1);
568 
569 	start = 0;
570 	for (i = 0; i < ghpartnum && start == 0; i++) {
571 		if (memcmp(&gp[i].gp_type, &efisys_uuid,
572 		    sizeof(struct uuid)) == 0)
573 			start = letoh64(gp[i].gp_lba_start);
574 	}
575 
576 	if (start) {
577 		for (i = 0; i < MAXPARTITIONS; i++) {
578 			if (DL_GETPSIZE(&dl->d_partitions[i]) > 0 &&
579 			    DL_GETPOFFSET(&dl->d_partitions[i]) == start)
580 				return ('a' + i);
581 		}
582 	}
583 
584 	return (-1);
585 }
586 
587 /*
588  * Load the prototype boot sector (biosboot) into memory.
589  */
590 static char *
591 loadproto(char *fname, long *size)
592 {
593 	int	fd;
594 	size_t	tdsize;		/* text+data size */
595 	char	*bp;
596 	Elf_Ehdr eh;
597 	Elf_Word phsize;
598 	Elf_Phdr *ph;
599 
600 	if ((fd = open(fname, O_RDONLY)) == -1)
601 		err(1, "%s", fname);
602 
603 	if (read(fd, &eh, sizeof(eh)) != sizeof(eh))
604 		errx(1, "%s: read failed", fname);
605 
606 	if (!IS_ELF(eh))
607 		errx(1, "%s: bad magic: 0x%02x%02x%02x%02x", fname,
608 		    eh.e_ident[EI_MAG0], eh.e_ident[EI_MAG1],
609 		    eh.e_ident[EI_MAG2], eh.e_ident[EI_MAG3]);
610 
611 	/*
612 	 * We have to include the exec header in the beginning of
613 	 * the buffer, and leave extra space at the end in case
614 	 * the actual write to disk wants to skip the header.
615 	 */
616 
617 	/* Program load header. */
618 	if (eh.e_phnum != 1)
619 		errx(1, "%s: %u ELF load sections (only support 1)",
620 		    fname, eh.e_phnum);
621 
622 	ph = reallocarray(NULL, eh.e_phnum, sizeof(Elf_Phdr));
623 	if (ph == NULL)
624 		err(1, NULL);
625 	phsize = eh.e_phnum * sizeof(Elf_Phdr);
626 
627 	if (pread(fd, ph, phsize, eh.e_phoff) != phsize)
628 		errx(1, "%s: can't pread header", fname);
629 
630 	tdsize = ph->p_filesz;
631 
632 	/*
633 	 * Allocate extra space here because the caller may copy
634 	 * the boot block starting at the end of the exec header.
635 	 * This prevents reading beyond the end of the buffer.
636 	 */
637 	if ((bp = calloc(tdsize, 1)) == NULL)
638 		err(1, NULL);
639 
640 	/* Read the rest of the file. */
641 	if (pread(fd, bp, tdsize, ph->p_offset) != (ssize_t)tdsize)
642 		errx(1, "%s: pread failed", fname);
643 
644 	*size = tdsize;	/* not aligned to DEV_BSIZE */
645 
646 	close(fd);
647 	return bp;
648 }
649 
650 static void
651 devread(int fd, void *buf, daddr_t blk, size_t size, char *msg)
652 {
653 	if (pread(fd, buf, size, dbtob((off_t)blk)) != (ssize_t)size)
654 		err(1, "%s: devread: pread", msg);
655 }
656 
657 /*
658  * Read information about /boot's inode, then put this and filesystem
659  * parameters from the superblock into pbr_symbols.
660  */
661 static int
662 getbootparams(char *boot, int devfd, struct disklabel *dl)
663 {
664 	int		fd;
665 	struct stat	dsb, fsb;
666 	struct statfs	fssb;
667 	struct partition *pp;
668 	struct fs	*fs;
669 	char		*sblock, *buf;
670 	u_int		blk, *ap;
671 	int		ndb;
672 	int		mib[3];
673 	size_t		size;
674 	dev_t		dev;
675 	int		incr;
676 
677 	/*
678 	 * Open 2nd-level boot program and record enough details about
679 	 * where it is on the filesystem represented by `devfd'
680 	 * (inode block, offset within that block, and various filesystem
681 	 * parameters essentially taken from the superblock) for biosboot
682 	 * to be able to load it later.
683 	 */
684 
685 	/* Make sure the (probably new) boot file is on disk. */
686 	sync(); sleep(1);
687 
688 	if ((fd = open(boot, O_RDONLY)) == -1)
689 		err(1, "open: %s", boot);
690 
691 	if (fstatfs(fd, &fssb) == -1)
692 		err(1, "statfs: %s", boot);
693 
694 	if (strncmp(fssb.f_fstypename, "ffs", MFSNAMELEN) &&
695 	    strncmp(fssb.f_fstypename, "ufs", MFSNAMELEN) )
696 		errx(1, "%s: not on an FFS filesystem", boot);
697 
698 #if 0
699 	if (read(fd, &eh, sizeof(eh)) != sizeof(eh))
700 		errx(1, "read: %s", boot);
701 
702 	if (!IS_ELF(eh)) {
703 		errx(1, "%s: bad magic: 0x%02x%02x%02x%02x",
704 		    boot,
705 		    eh.e_ident[EI_MAG0], eh.e_ident[EI_MAG1],
706 		    eh.e_ident[EI_MAG2], eh.e_ident[EI_MAG3]);
707 	}
708 #endif
709 
710 	if (fsync(fd) != 0)
711 		err(1, "fsync: %s", boot);
712 
713 	if (fstat(fd, &fsb) != 0)
714 		err(1, "fstat: %s", boot);
715 
716 	if (fstat(devfd, &dsb) != 0)
717 		err(1, "fstat: %d", devfd);
718 
719 	/* Check devices. */
720 	mib[0] = CTL_MACHDEP;
721 	mib[1] = CPU_CHR2BLK;
722 	mib[2] = dsb.st_rdev;
723 	size = sizeof(dev);
724 	if (sysctl(mib, 3, &dev, &size, NULL, 0) >= 0) {
725 		if (fsb.st_dev / MAXPARTITIONS != dev / MAXPARTITIONS)
726 			errx(1, "cross-device install");
727 	}
728 
729 	pp = &dl->d_partitions[DISKPART(fsb.st_dev)];
730 	close(fd);
731 
732 	if ((sblock = malloc(SBSIZE)) == NULL)
733 		err(1, NULL);
734 
735 	sbread(devfd, DL_SECTOBLK(dl, pp->p_offset), &fs, sblock);
736 
737 	/* Read inode. */
738 	if ((buf = malloc(fs->fs_bsize)) == NULL)
739 		err(1, NULL);
740 
741 	blk = fsbtodb(fs, ino_to_fsba(fs, fsb.st_ino));
742 
743 	/*
744 	 * Have the inode.  Figure out how many filesystem blocks (not disk
745 	 * sectors) there are for biosboot to load.
746 	 */
747 	devread(devfd, buf, DL_SECTOBLK(dl, pp->p_offset) + blk,
748 	    fs->fs_bsize, "inode");
749 	if (fs->fs_magic == FS_UFS2_MAGIC) {
750 		struct ufs2_dinode *ip2 = (struct ufs2_dinode *)(buf) +
751 		    ino_to_fsbo(fs, fsb.st_ino);
752 		ndb = howmany(ip2->di_size, fs->fs_bsize);
753 		ap = (u_int *)ip2->di_db;
754 		incr = sizeof(u_int32_t);
755 	} else {
756 		struct ufs1_dinode *ip1 = (struct ufs1_dinode *)(buf) +
757 		    ino_to_fsbo(fs, fsb.st_ino);
758 		ndb = howmany(ip1->di_size, fs->fs_bsize);
759 		ap = (u_int *)ip1->di_db;
760 		incr = 0;
761 	}
762 
763 	if (ndb <= 0)
764 		errx(1, "No blocks to load");
765 
766 	/*
767 	 * Now set the values that will need to go into biosboot
768 	 * (the partition boot record, a.k.a. the PBR).
769 	 */
770 	sym_set_value(pbr_symbols, "_fs_bsize_p", (fs->fs_bsize / 16));
771 	sym_set_value(pbr_symbols, "_fs_bsize_s", (fs->fs_bsize /
772 	    dl->d_secsize));
773 
774 	/*
775 	 * fs_fsbtodb is the shift to convert fs_fsize to DEV_BSIZE. The
776 	 * ino_to_fsba() return value is the number of fs_fsize units.
777 	 * Calculate the shift to convert fs_fsize into physical sectors,
778 	 * which are added to p_offset to get the sector address BIOS
779 	 * will use.
780 	 *
781 	 * N.B.: ASSUMES fs_fsize is a power of 2 of d_secsize.
782 	 */
783 	sym_set_value(pbr_symbols, "_fsbtodb",
784 	    ffs(fs->fs_fsize / dl->d_secsize) - 1);
785 
786 	sym_set_value(pbr_symbols, "_p_offset", pp->p_offset);
787 	sym_set_value(pbr_symbols, "_inodeblk",
788 	    ino_to_fsba(fs, fsb.st_ino));
789 	sym_set_value(pbr_symbols, "_inodedbl",
790 	    ((((char *)ap) - buf) + INODEOFF));
791 	sym_set_value(pbr_symbols, "_nblocks", ndb);
792 	sym_set_value(pbr_symbols, "_blkincr", incr);
793 
794 	if (verbose) {
795 		fprintf(stderr, "%s is %d blocks x %d bytes\n",
796 		    boot, ndb, fs->fs_bsize);
797 		fprintf(stderr, "fs block shift %u; part offset %u; "
798 		    "inode block %lld, offset %u\n",
799 		    ffs(fs->fs_fsize / dl->d_secsize) - 1,
800 		    pp->p_offset,
801 		    ino_to_fsba(fs, fsb.st_ino),
802 		    (unsigned int)((((char *)ap) - buf) + INODEOFF));
803 		fprintf(stderr, "expecting %d-bit fs blocks (incr %d)\n",
804 		    incr ? 64 : 32, incr);
805 	}
806 
807 	free (sblock);
808 	free (buf);
809 
810 	return 0;
811 }
812 
813 void
814 sym_set_value(struct sym_data *sym_list, char *sym, u_int32_t value)
815 {
816 	struct sym_data *p;
817 
818 	for (p = sym_list; p->sym_name != NULL; p++) {
819 		if (strcmp(p->sym_name, sym) == 0)
820 			break;
821 	}
822 
823 	if (p->sym_name == NULL)
824 		errx(1, "%s: no such symbol", sym);
825 
826 	p->sym_value = value;
827 	p->sym_set = 1;
828 }
829 
830 /*
831  * Write the parameters stored in sym_list into the in-memory copy of
832  * the prototype biosboot (proto), ready for it to be written to disk.
833  */
834 void
835 pbr_set_symbols(char *fname, char *proto, struct sym_data *sym_list)
836 {
837 	struct sym_data *sym;
838 	struct nlist	*nl;
839 	char		*vp;
840 	u_int32_t	*lp;
841 	u_int16_t	*wp;
842 	u_int8_t	*bp;
843 
844 	for (sym = sym_list; sym->sym_name != NULL; sym++) {
845 		if (!sym->sym_set)
846 			errx(1, "%s not set", sym->sym_name);
847 
848 		/* Allocate space for 2; second is null-terminator for list. */
849 		nl = calloc(2, sizeof(struct nlist));
850 		if (nl == NULL)
851 			err(1, NULL);
852 
853 		nl->n_name = sym->sym_name;
854 
855 		if (nlist_elf32(fname, nl) != 0)
856 			errx(1, "%s: symbol %s not found",
857 			    fname, sym->sym_name);
858 
859 		if (nl->n_type != (N_TEXT))
860 			errx(1, "%s: %s: wrong type (%x)",
861 			    fname, sym->sym_name, nl->n_type);
862 
863 		/* Get a pointer to where the symbol's value needs to go. */
864 		vp = proto + nl->n_value;
865 
866 		switch (sym->sym_size) {
867 		case 4:					/* u_int32_t */
868 			lp = (u_int32_t *) vp;
869 			*lp = sym->sym_value;
870 			break;
871 		case 2:					/* u_int16_t */
872 			if (sym->sym_value >= 0x10000)	/* out of range */
873 				errx(1, "%s: symbol out of range (%u)",
874 				    sym->sym_name, sym->sym_value);
875 			wp = (u_int16_t *) vp;
876 			*wp = (u_int16_t) sym->sym_value;
877 			break;
878 		case 1:					/* u_int16_t */
879 			if (sym->sym_value >= 0x100)	/* out of range */
880 				errx(1, "%s: symbol out of range (%u)",
881 				    sym->sym_name, sym->sym_value);
882 			bp = (u_int8_t *) vp;
883 			*bp = (u_int8_t) sym->sym_value;
884 			break;
885 		default:
886 			errx(1, "%s: bad symbol size %d",
887 			    sym->sym_name, sym->sym_size);
888 			/* NOTREACHED */
889 		}
890 
891 		free(nl);
892 	}
893 }
894 
895 static int
896 sbchk(struct fs *fs, daddr_t sbloc)
897 {
898 	if (verbose)
899 		fprintf(stderr, "looking for superblock at %lld\n", sbloc);
900 
901 	if (fs->fs_magic != FS_UFS2_MAGIC && fs->fs_magic != FS_UFS1_MAGIC) {
902 		if (verbose)
903 			fprintf(stderr, "bad superblock magic 0x%x\n",
904 			    fs->fs_magic);
905 		return (0);
906 	}
907 
908 	/*
909 	 * Looking for an FFS1 file system at SBLOCK_UFS2 will find the
910 	 * wrong superblock for file systems with 64k block size.
911 	 */
912 	if (fs->fs_magic == FS_UFS1_MAGIC && sbloc == SBLOCK_UFS2) {
913 		if (verbose)
914 			fprintf(stderr, "skipping ffs1 superblock at %lld\n",
915 			    sbloc);
916 		return (0);
917 	}
918 
919 	if (fs->fs_bsize <= 0 || fs->fs_bsize < sizeof(struct fs) ||
920 	    fs->fs_bsize > MAXBSIZE) {
921 		if (verbose)
922 			fprintf(stderr, "invalid superblock block size %d\n",
923 			    fs->fs_bsize);
924 		return (0);
925 	}
926 
927 	if (fs->fs_sbsize <= 0 || fs->fs_sbsize > SBSIZE) {
928 		if (verbose)
929 			fprintf(stderr, "invalid superblock size %d\n",
930 			    fs->fs_sbsize);
931 		return (0);
932 	}
933 
934 	if (fs->fs_inopb <= 0) {
935 		if (verbose)
936 			fprintf(stderr, "invalid superblock inodes/block %d\n",
937 			    fs->fs_inopb);
938 		return (0);
939 	}
940 
941 	if (verbose)
942 		fprintf(stderr, "found valid %s superblock\n",
943 		    fs->fs_magic == FS_UFS2_MAGIC ? "ffs2" : "ffs1");
944 
945 	return (1);
946 }
947 
948 static void
949 sbread(int fd, daddr_t poffset, struct fs **fs, char *sblock)
950 {
951 	int i;
952 	daddr_t sboff;
953 
954 	for (i = 0; sbtry[i] != -1; i++) {
955 		sboff = sbtry[i] / DEV_BSIZE;
956 		devread(fd, sblock, poffset + sboff, SBSIZE, "superblock");
957 		*fs = (struct fs *)sblock;
958 		if (sbchk(*fs, sbtry[i]))
959 			break;
960 	}
961 
962 	if (sbtry[i] == -1)
963 		errx(1, "couldn't find ffs superblock");
964 }
965