1/*	$NetBSD: cd9660_eltorito.c,v 1.23 2018/03/28 06:48:55 nonaka Exp $	*/
2
3/*-
4 * SPDX-License-Identifier: BSD-2-Clause-NetBSD
5 *
6 * Copyright (c) 2005 Daniel Watt, Walter Deignan, Ryan Gabrys, Alan
7 * Perez-Rathke and Ram Vedam.  All rights reserved.
8 *
9 * This code was written by Daniel Watt, Walter Deignan, Ryan Gabrys,
10 * Alan Perez-Rathke and Ram Vedam.
11 *
12 * Redistribution and use in source and binary forms, with or
13 * without modification, are permitted provided that the following
14 * conditions 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
18 *    copyright notice, this list of conditions and the following
19 *    disclaimer in the documentation and/or other materials provided
20 *    with the distribution.
21 *
22 * THIS SOFTWARE IS PROVIDED BY DANIEL WATT, WALTER DEIGNAN, RYAN
23 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED.  IN NO EVENT SHALL DANIEL WATT, WALTER DEIGNAN, RYAN
27 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM 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
30 * USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
34 * OF SUCH DAMAGE.
35 */
36
37#include "cd9660.h"
38#include "cd9660_eltorito.h"
39#include <util.h>
40
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD$");
43
44#ifdef DEBUG
45#define	ELTORITO_DPRINTF(__x)	printf __x
46#else
47#define	ELTORITO_DPRINTF(__x)
48#endif
49
50#include <util.h>
51
52static struct boot_catalog_entry *cd9660_init_boot_catalog_entry(void);
53static struct boot_catalog_entry *cd9660_boot_setup_validation_entry(char);
54static struct boot_catalog_entry *cd9660_boot_setup_default_entry(
55    struct cd9660_boot_image *);
56static struct boot_catalog_entry *cd9660_boot_setup_section_head(char);
57#if 0
58static u_char cd9660_boot_get_system_type(struct cd9660_boot_image *);
59#endif
60
61static struct cd9660_boot_image *default_boot_image;
62
63int
64cd9660_add_boot_disk(iso9660_disk *diskStructure, const char *boot_info)
65{
66	struct stat stbuf;
67	const char *mode_msg;
68	char *temp;
69	char *sysname;
70	char *filename;
71	struct cd9660_boot_image *new_image, *tmp_image;
72
73	assert(boot_info != NULL);
74
75	if (*boot_info == '\0') {
76		warnx("Error: Boot disk information must be in the "
77		      "format 'system;filename'");
78		return 0;
79	}
80
81	/* First decode the boot information */
82	temp = estrdup(boot_info);
83
84	sysname = temp;
85	filename = strchr(sysname, ';');
86	if (filename == NULL) {
87		warnx("supply boot disk information in the format "
88		    "'system;filename'");
89		free(temp);
90		return 0;
91	}
92
93	*filename++ = '\0';
94
95	if (diskStructure->verbose_level > 0) {
96		printf("Found bootdisk with system %s, and filename %s\n",
97		    sysname, filename);
98	}
99	new_image = ecalloc(1, sizeof(*new_image));
100	new_image->loadSegment = 0;	/* default for now */
101
102	/* Decode System */
103	if (strcmp(sysname, "i386") == 0)
104		new_image->system = ET_SYS_X86;
105	else if (strcmp(sysname, "powerpc") == 0)
106		new_image->system = ET_SYS_PPC;
107	else if (strcmp(sysname, "macppc") == 0 ||
108	         strcmp(sysname, "mac68k") == 0)
109		new_image->system = ET_SYS_MAC;
110	else if (strcmp(sysname, "efi") == 0)
111		new_image->system = ET_SYS_EFI;
112	else {
113		warnx("boot disk system must be "
114		      "i386, powerpc, macppc, mac68k, or efi");
115		free(temp);
116		free(new_image);
117		return 0;
118	}
119
120
121	new_image->filename = estrdup(filename);
122
123	free(temp);
124
125	/* Get information about the file */
126	if (lstat(new_image->filename, &stbuf) == -1)
127		err(EXIT_FAILURE, "%s: lstat(\"%s\")", __func__,
128		    new_image->filename);
129
130	switch (stbuf.st_size) {
131	case 1440 * 1024:
132		new_image->targetMode = ET_MEDIA_144FDD;
133		mode_msg = "Assigned boot image to 1.44 emulation mode";
134		break;
135	case 1200 * 1024:
136		new_image->targetMode = ET_MEDIA_12FDD;
137		mode_msg = "Assigned boot image to 1.2 emulation mode";
138		break;
139	case 2880 * 1024:
140		new_image->targetMode = ET_MEDIA_288FDD;
141		mode_msg = "Assigned boot image to 2.88 emulation mode";
142		break;
143	default:
144		new_image->targetMode = ET_MEDIA_NOEM;
145		mode_msg = "Assigned boot image to no emulation mode";
146		break;
147	}
148
149	if (diskStructure->verbose_level > 0)
150		printf("%s\n", mode_msg);
151
152	new_image->size = stbuf.st_size;
153	new_image->num_sectors =
154	    howmany(new_image->size, diskStructure->sectorSize) *
155	    howmany(diskStructure->sectorSize, 512);
156	if (diskStructure->verbose_level > 0) {
157		printf("New image has size %d, uses %d 512-byte sectors\n",
158		    new_image->size, new_image->num_sectors);
159	}
160	new_image->sector = -1;
161	/* Bootable by default */
162	new_image->bootable = ET_BOOTABLE;
163	/* Add boot disk */
164
165	/* Group images for the same platform together. */
166	TAILQ_FOREACH(tmp_image, &diskStructure->boot_images, image_list) {
167		if (tmp_image->system != new_image->system)
168			break;
169	}
170
171	if (tmp_image == NULL) {
172		TAILQ_INSERT_HEAD(&diskStructure->boot_images, new_image,
173		    image_list);
174	} else
175		TAILQ_INSERT_BEFORE(tmp_image, new_image, image_list);
176
177	new_image->serialno = diskStructure->image_serialno++;
178
179	new_image->platform_id = new_image->system;
180
181	/* TODO : Need to do anything about the boot image in the tree? */
182	diskStructure->is_bootable = 1;
183
184	/* First boot image is initial/default entry. */
185	if (default_boot_image == NULL)
186		default_boot_image = new_image;
187
188	return 1;
189}
190
191int
192cd9660_eltorito_add_boot_option(iso9660_disk *diskStructure,
193    const char *option_string, const char *value)
194{
195	char *eptr;
196	struct cd9660_boot_image *image;
197
198	assert(option_string != NULL);
199
200	/* Find the last image added */
201	TAILQ_FOREACH(image, &diskStructure->boot_images, image_list) {
202		if (image->serialno + 1 == diskStructure->image_serialno)
203			break;
204	}
205	if (image == NULL)
206		errx(EXIT_FAILURE, "Attempted to add boot option, "
207		    "but no boot images have been specified");
208
209	if (strcmp(option_string, "no-emul-boot") == 0) {
210		image->targetMode = ET_MEDIA_NOEM;
211	} else if (strcmp(option_string, "no-boot") == 0) {
212		image->bootable = ET_NOT_BOOTABLE;
213	} else if (strcmp(option_string, "hard-disk-boot") == 0) {
214		image->targetMode = ET_MEDIA_HDD;
215	} else if (strcmp(option_string, "boot-load-segment") == 0) {
216		image->loadSegment = strtoul(value, &eptr, 16);
217		if (eptr == value || *eptr != '\0' || errno != ERANGE) {
218			warn("%s: strtoul", __func__);
219			return 0;
220		}
221	} else if (strcmp(option_string, "platformid") == 0) {
222		if (strcmp(value, "efi") == 0)
223			image->platform_id = ET_SYS_EFI;
224		else {
225			warn("%s: unknown platform: %s", __func__, value);
226			return 0;
227		}
228	} else {
229		return 0;
230	}
231	return 1;
232}
233
234static struct boot_catalog_entry *
235cd9660_init_boot_catalog_entry(void)
236{
237	return ecalloc(1, sizeof(struct boot_catalog_entry));
238}
239
240static struct boot_catalog_entry *
241cd9660_boot_setup_validation_entry(char sys)
242{
243	struct boot_catalog_entry *entry;
244	boot_catalog_validation_entry *ve;
245	int16_t checksum;
246	unsigned char *csptr;
247	size_t i;
248	entry = cd9660_init_boot_catalog_entry();
249
250	entry->entry_type = ET_ENTRY_VE;
251	ve = &entry->entry_data.VE;
252
253	ve->header_id[0] = 1;
254	ve->platform_id[0] = sys;
255	ve->key[0] = 0x55;
256	ve->key[1] = 0xAA;
257
258	/* Calculate checksum */
259	checksum = 0;
260	cd9660_721(0, ve->checksum);
261	csptr = (unsigned char*)ve;
262	for (i = 0; i < sizeof(*ve); i += 2) {
263		checksum += (int16_t)csptr[i];
264		checksum += 256 * (int16_t)csptr[i + 1];
265	}
266	checksum = -checksum;
267	cd9660_721(checksum, ve->checksum);
268
269        ELTORITO_DPRINTF(("%s: header_id %d, platform_id %d, key[0] %d, key[1] %d, "
270	    "checksum %04x\n", __func__, ve->header_id[0], ve->platform_id[0],
271	    ve->key[0], ve->key[1], checksum));
272	return entry;
273}
274
275static struct boot_catalog_entry *
276cd9660_boot_setup_default_entry(struct cd9660_boot_image *disk)
277{
278	struct boot_catalog_entry *default_entry;
279	boot_catalog_initial_entry *ie;
280
281	default_entry = cd9660_init_boot_catalog_entry();
282	if (default_entry == NULL)
283		return NULL;
284
285	default_entry->entry_type = ET_ENTRY_IE;
286	ie = &default_entry->entry_data.IE;
287
288	ie->boot_indicator[0] = disk->bootable;
289	ie->media_type[0] = disk->targetMode;
290	cd9660_721(disk->loadSegment, ie->load_segment);
291	ie->system_type[0] = disk->system;
292	cd9660_721(disk->num_sectors, ie->sector_count);
293	cd9660_731(disk->sector, ie->load_rba);
294
295	ELTORITO_DPRINTF(("%s: boot indicator %d, media type %d, "
296	    "load segment %04x, system type %d, sector count %d, "
297	    "load rba %d\n", __func__, ie->boot_indicator[0],
298	    ie->media_type[0], disk->loadSegment, ie->system_type[0],
299	    disk->num_sectors, disk->sector));
300	return default_entry;
301}
302
303static struct boot_catalog_entry *
304cd9660_boot_setup_section_head(char platform)
305{
306	struct boot_catalog_entry *entry;
307	boot_catalog_section_header *sh;
308
309	entry = cd9660_init_boot_catalog_entry();
310	if (entry == NULL)
311		return NULL;
312
313	entry->entry_type = ET_ENTRY_SH;
314	sh = &entry->entry_data.SH;
315	/*
316	 * More by default.
317	 * The last one will manually be set to ET_SECTION_HEADER_LAST
318	 */
319	sh->header_indicator[0] = ET_SECTION_HEADER_MORE;
320	sh->platform_id[0] = platform;
321	sh->num_section_entries[0] = 0;
322	return entry;
323}
324
325static struct boot_catalog_entry *
326cd9660_boot_setup_section_entry(struct cd9660_boot_image *disk)
327{
328	struct boot_catalog_entry *entry;
329	boot_catalog_section_entry *se;
330	if ((entry = cd9660_init_boot_catalog_entry()) == NULL)
331		return NULL;
332
333	entry->entry_type = ET_ENTRY_SE;
334	se = &entry->entry_data.SE;
335
336	se->boot_indicator[0] = ET_BOOTABLE;
337	se->media_type[0] = disk->targetMode;
338	cd9660_721(disk->loadSegment, se->load_segment);
339	cd9660_721(disk->num_sectors, se->sector_count);
340	cd9660_731(disk->sector, se->load_rba);
341	return entry;
342}
343
344#if 0
345static u_char
346cd9660_boot_get_system_type(struct cd9660_boot_image *disk)
347{
348	/*
349		For hard drive booting, we need to examine the MBR to figure
350		out what the partition type is
351	*/
352	return 0;
353}
354#endif
355
356/*
357 * Set up the BVD, Boot catalog, and the boot entries, but do no writing
358 */
359int
360cd9660_setup_boot(iso9660_disk *diskStructure, int first_sector)
361{
362	int sector;
363	int used_sectors;
364	int num_entries = 0;
365	int catalog_sectors;
366	struct boot_catalog_entry *x86_head, *mac_head, *ppc_head, *efi_head,
367		*valid_entry, *default_entry, *temp, *head, **headp, *next;
368	struct cd9660_boot_image *tmp_disk;
369
370	headp = NULL;
371	x86_head = mac_head = ppc_head = efi_head = NULL;
372
373	/* If there are no boot disks, don't bother building boot information */
374	if (TAILQ_EMPTY(&diskStructure->boot_images))
375		return 0;
376
377	/* Point to catalog: For now assume it consumes one sector */
378	ELTORITO_DPRINTF(("Boot catalog will go in sector %d\n", first_sector));
379	diskStructure->boot_catalog_sector = first_sector;
380	cd9660_bothendian_dword(first_sector,
381		diskStructure->boot_descriptor->boot_catalog_pointer);
382
383	/* Step 1: Generate boot catalog */
384	/* Step 1a: Validation entry */
385	valid_entry = cd9660_boot_setup_validation_entry(ET_SYS_X86);
386	if (valid_entry == NULL)
387		return -1;
388
389	/*
390	 * Count how many boot images there are,
391	 * and how many sectors they consume.
392	 */
393	num_entries = 1;
394	used_sectors = 0;
395
396	TAILQ_FOREACH(tmp_disk, &diskStructure->boot_images, image_list) {
397		used_sectors += tmp_disk->num_sectors;
398
399		/* One default entry per image */
400		num_entries++;
401	}
402	catalog_sectors = howmany(num_entries * 0x20, diskStructure->sectorSize);
403	used_sectors += catalog_sectors;
404
405	if (diskStructure->verbose_level > 0) {
406		printf("%s: there will be %i entries consuming %i sectors. "
407		       "Catalog is %i sectors\n", __func__, num_entries,
408		       used_sectors, catalog_sectors);
409	}
410
411	/* Populate sector numbers */
412	sector = first_sector + catalog_sectors;
413	TAILQ_FOREACH(tmp_disk, &diskStructure->boot_images, image_list) {
414		tmp_disk->sector = sector;
415		sector += tmp_disk->num_sectors /
416		    (diskStructure->sectorSize / 512);
417	}
418
419	LIST_INSERT_HEAD(&diskStructure->boot_entries, valid_entry, ll_struct);
420
421	/* Step 1b: Initial/default entry */
422	/* TODO : PARAM */
423	if (default_boot_image != NULL) {
424		struct cd9660_boot_image *tcbi;
425		TAILQ_FOREACH(tcbi, &diskStructure->boot_images, image_list) {
426			if (tcbi == default_boot_image) {
427				tmp_disk = tcbi;
428				break;
429			}
430		}
431	}
432	if (tmp_disk == NULL)
433		tmp_disk = TAILQ_FIRST(&diskStructure->boot_images);
434	default_entry = cd9660_boot_setup_default_entry(tmp_disk);
435	if (default_entry == NULL) {
436		warnx("Error: memory allocation failed in cd9660_setup_boot");
437		return -1;
438	}
439
440	LIST_INSERT_AFTER(valid_entry, default_entry, ll_struct);
441
442	/* Todo: multiple default entries? */
443
444	tmp_disk = TAILQ_FIRST(&diskStructure->boot_images);
445
446	head = NULL;
447	temp = default_entry;
448
449	/* If multiple boot images are given : */
450	for (; tmp_disk != NULL; tmp_disk = TAILQ_NEXT(tmp_disk, image_list)) {
451		if (tmp_disk == default_boot_image)
452			continue;
453
454		/* Step 2: Section header */
455		switch (tmp_disk->platform_id) {
456		case ET_SYS_X86:
457			headp = &x86_head;
458			break;
459		case ET_SYS_PPC:
460			headp = &ppc_head;
461			break;
462		case ET_SYS_MAC:
463			headp = &mac_head;
464			break;
465		case ET_SYS_EFI:
466			headp = &efi_head;
467			break;
468		default:
469			warnx("%s: internal error: unknown system type",
470			    __func__);
471			return -1;
472		}
473
474		if (*headp == NULL) {
475			head =
476			  cd9660_boot_setup_section_head(tmp_disk->platform_id);
477			if (head == NULL) {
478				warnx("Error: memory allocation failed in "
479				      "cd9660_setup_boot");
480				return -1;
481			}
482			LIST_INSERT_AFTER(default_entry, head, ll_struct);
483			*headp = head;
484		} else
485			head = *headp;
486
487		head->entry_data.SH.num_section_entries[0]++;
488
489		/* Step 2a: Section entry and extensions */
490		temp = cd9660_boot_setup_section_entry(tmp_disk);
491		if (temp == NULL) {
492			warn("%s: cd9660_boot_setup_section_entry", __func__);
493			return -1;
494		}
495
496		while ((next = LIST_NEXT(head, ll_struct)) != NULL &&
497		       next->entry_type == ET_ENTRY_SE)
498			head = next;
499
500		LIST_INSERT_AFTER(head, temp, ll_struct);
501	}
502
503	/* Find the last Section Header entry and mark it as the last. */
504	head = NULL;
505	LIST_FOREACH(next, &diskStructure->boot_entries, ll_struct) {
506		if (next->entry_type == ET_ENTRY_SH)
507			head = next;
508	}
509	if (head != NULL)
510		head->entry_data.SH.header_indicator[0] = ET_SECTION_HEADER_LAST;
511
512	/* TODO: Remaining boot disks when implemented */
513
514	return first_sector + used_sectors;
515}
516
517int
518cd9660_setup_boot_volume_descriptor(iso9660_disk *diskStructure,
519    volume_descriptor *bvd)
520{
521	boot_volume_descriptor *bvdData =
522	    (boot_volume_descriptor*)bvd->volumeDescriptorData;
523
524	bvdData->boot_record_indicator[0] = ISO_VOLUME_DESCRIPTOR_BOOT;
525	memcpy(bvdData->identifier, ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
526	bvdData->version[0] = 1;
527	memcpy(bvdData->boot_system_identifier, ET_ID, 23);
528	memcpy(bvdData->identifier, ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
529	diskStructure->boot_descriptor =
530	    (boot_volume_descriptor*) bvd->volumeDescriptorData;
531	return 1;
532}
533
534static int
535cd9660_write_mbr_partition_entry(FILE *fd, int idx, off_t sector_start,
536    off_t nsectors, int type)
537{
538	uint8_t val;
539	uint32_t lba;
540
541	if (fseeko(fd, (off_t)(idx) * 16 + 0x1be, SEEK_SET) == -1)
542		err(1, "fseeko");
543
544	val = 0x80; /* Bootable */
545	fwrite(&val, sizeof(val), 1, fd);
546
547	val = 0xff; /* CHS begin */
548	fwrite(&val, sizeof(val), 1, fd);
549	fwrite(&val, sizeof(val), 1, fd);
550	fwrite(&val, sizeof(val), 1, fd);
551
552	val = type; /* Part type */
553	fwrite(&val, sizeof(val), 1, fd);
554
555	val = 0xff; /* CHS end */
556	fwrite(&val, sizeof(val), 1, fd);
557	fwrite(&val, sizeof(val), 1, fd);
558	fwrite(&val, sizeof(val), 1, fd);
559
560	/* LBA extent */
561	lba = htole32(sector_start);
562	fwrite(&lba, sizeof(lba), 1, fd);
563	lba = htole32(nsectors);
564	fwrite(&lba, sizeof(lba), 1, fd);
565
566	return 0;
567}
568
569static int
570cd9660_write_apm_partition_entry(FILE *fd, int idx, int total_partitions,
571    off_t sector_start, off_t nsectors, off_t sector_size,
572    const char *part_name, const char *part_type)
573{
574	uint32_t apm32, part_status;
575	uint16_t apm16;
576
577	/* See Apple Tech Note 1189 for the details about the pmPartStatus
578	 * flags.
579	 * Below the flags which are default:
580	 * - IsValid     0x01
581	 * - IsAllocated 0x02
582	 * - IsReadable  0x10
583	 * - IsWritable  0x20
584	 */
585	part_status = 0x01 | 0x02 | 0x10 | 0x20;
586
587	if (fseeko(fd, (off_t)(idx + 1) * sector_size, SEEK_SET) == -1)
588		err(1, "fseeko");
589
590	/* Signature */
591	apm16 = htobe16(0x504d);
592	fwrite(&apm16, sizeof(apm16), 1, fd);
593	apm16 = 0;
594	fwrite(&apm16, sizeof(apm16), 1, fd);
595
596	/* Total number of partitions */
597	apm32 = htobe32(total_partitions);
598	fwrite(&apm32, sizeof(apm32), 1, fd);
599	/* Bounds */
600	apm32 = htobe32(sector_start);
601	fwrite(&apm32, sizeof(apm32), 1, fd);
602	apm32 = htobe32(nsectors);
603	fwrite(&apm32, sizeof(apm32), 1, fd);
604
605	fwrite(part_name, strlen(part_name) + 1, 1, fd);
606	fseek(fd, 32 - strlen(part_name) - 1, SEEK_CUR);
607	fwrite(part_type, strlen(part_type) + 1, 1, fd);
608	fseek(fd, 32 - strlen(part_type) - 1, SEEK_CUR);
609
610	apm32 = 0;
611	/* pmLgDataStart */
612	fwrite(&apm32, sizeof(apm32), 1, fd);
613	/* pmDataCnt */
614	apm32 = htobe32(nsectors);
615	fwrite(&apm32, sizeof(apm32), 1, fd);
616	/* pmPartStatus */
617	apm32 = htobe32(part_status);
618	fwrite(&apm32, sizeof(apm32), 1, fd);
619
620	return 0;
621}
622
623int
624cd9660_write_boot(iso9660_disk *diskStructure, FILE *fd)
625{
626	struct boot_catalog_entry *e;
627	struct cd9660_boot_image *t;
628	int apm_partitions = 0;
629	int mbr_partitions = 0;
630
631	/* write boot catalog */
632	if (fseeko(fd, (off_t)diskStructure->boot_catalog_sector *
633	    diskStructure->sectorSize, SEEK_SET) == -1)
634		err(1, "fseeko");
635
636	if (diskStructure->verbose_level > 0) {
637		printf("Writing boot catalog to sector %" PRId64 "\n",
638		    diskStructure->boot_catalog_sector);
639	}
640	LIST_FOREACH(e, &diskStructure->boot_entries, ll_struct) {
641		if (diskStructure->verbose_level > 0) {
642			printf("Writing catalog entry of type %d\n",
643			    e->entry_type);
644		}
645		/*
646		 * It doesn't matter which one gets written
647		 * since they are the same size
648		 */
649		fwrite(&(e->entry_data.VE), 1, 32, fd);
650	}
651	if (diskStructure->verbose_level > 0)
652		printf("Finished writing boot catalog\n");
653
654	/* copy boot images */
655	TAILQ_FOREACH(t, &diskStructure->boot_images, image_list) {
656		if (diskStructure->verbose_level > 0) {
657			printf("Writing boot image from %s to sectors %d\n",
658			    t->filename, t->sector);
659		}
660		cd9660_copy_file(diskStructure, fd, t->sector, t->filename);
661
662		if (t->system == ET_SYS_MAC)
663			apm_partitions++;
664		if (t->system == ET_SYS_PPC)
665			mbr_partitions++;
666	}
667
668	/* some systems need partition tables as well */
669	if (mbr_partitions > 0 || diskStructure->chrp_boot) {
670		uint16_t sig;
671
672		fseek(fd, 0x1fe, SEEK_SET);
673		sig = htole16(0xaa55);
674		fwrite(&sig, sizeof(sig), 1, fd);
675
676		mbr_partitions = 0;
677
678		/* Write ISO9660 descriptor, enclosing the whole disk */
679		if (diskStructure->chrp_boot)
680			cd9660_write_mbr_partition_entry(fd, mbr_partitions++,
681			    0, diskStructure->totalSectors *
682			    (diskStructure->sectorSize / 512), 0x96);
683
684		/* Write all partition entries */
685		TAILQ_FOREACH(t, &diskStructure->boot_images, image_list) {
686			if (t->system != ET_SYS_PPC)
687				continue;
688			cd9660_write_mbr_partition_entry(fd, mbr_partitions++,
689			    t->sector * (diskStructure->sectorSize / 512),
690			    t->num_sectors * (diskStructure->sectorSize / 512),
691			    0x41 /* PReP Boot */);
692		}
693	}
694
695	if (apm_partitions > 0) {
696		/* Write DDR and global APM info */
697		uint32_t apm32;
698		uint16_t apm16;
699		int total_parts;
700
701		fseek(fd, 0, SEEK_SET);
702		apm16 = htobe16(0x4552);
703		fwrite(&apm16, sizeof(apm16), 1, fd);
704		/* Device block size */
705		apm16 = htobe16(512);
706		fwrite(&apm16, sizeof(apm16), 1, fd);
707		/* Device block count */
708		apm32 = htobe32(diskStructure->totalSectors *
709		    (diskStructure->sectorSize / 512));
710		fwrite(&apm32, sizeof(apm32), 1, fd);
711		/* Device type/id */
712		apm16 = htobe16(1);
713		fwrite(&apm16, sizeof(apm16), 1, fd);
714		fwrite(&apm16, sizeof(apm16), 1, fd);
715
716		/* Count total needed entries */
717		total_parts = 2 + apm_partitions; /* Self + ISO9660 */
718
719		/* Write self-descriptor */
720		cd9660_write_apm_partition_entry(fd, 0, total_parts, 1,
721		    total_parts, 512, "Apple", "Apple_partition_map");
722
723		/* Write all partition entries */
724		apm_partitions = 0;
725		TAILQ_FOREACH(t, &diskStructure->boot_images, image_list) {
726			if (t->system != ET_SYS_MAC)
727				continue;
728
729			cd9660_write_apm_partition_entry(fd,
730			    1 + apm_partitions++, total_parts,
731			    t->sector * (diskStructure->sectorSize / 512),
732			    t->num_sectors * (diskStructure->sectorSize / 512),
733			    512, "CD Boot", "Apple_Bootstrap");
734		}
735
736		/* Write ISO9660 descriptor, enclosing the whole disk */
737		cd9660_write_apm_partition_entry(fd, 2 + apm_partitions,
738		    total_parts, 0, diskStructure->totalSectors *
739		    (diskStructure->sectorSize / 512), 512, "ISO9660",
740		    "CD_ROM_Mode_1");
741	}
742
743	return 0;
744}
745