isobemak 0.4.3

Create bootable ISO images with FAT32 and UEFI (El Torito) support in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# API Documentation

This document outlines the API for `isobemak`, a Rust crate for creating bootable ISO 9660 images with UEFI and BIOS support.

## Main Functions

### `build_iso(iso_path: &Path, image: &IsoImage, is_isohybrid: bool) -> io::Result<(PathBuf, Option<NamedTempFile>, File, Option<u32>)>`

**Description:** Builds a bootable ISO 9660 image at the specified path. The boot information table (`-boot-info-table`) is automatically patched into the BIOS boot image (if configured), providing bootloaders such as ISOLINUX and Limine with the PVD LBA, boot image LBA, file length, and checksum. For hybrid isohybrid images that can boot from both optical media and USB drives, set `is_isohybrid` to `true`.

**Parameters:**
- `iso_path`: The path where the ISO image will be created
- `image`: Configuration object defining the files and boot information for the ISO image
- `is_isohybrid`: Whether to create a hybrid isohybrid image that can boot from USB drives

**Returns:**
A tuple containing:
- `PathBuf`: The path to the created ISO file
- `Option<NamedTempFile>`: Temporary FAT image file (if created for isohybrid)
- `File`: Open file handle to the ISO
- `Option<u32>`: FAT image size in 512-byte sectors (if created)

## Configuration Structures

### `IsoImage`

Top-level configuration structure for ISO images.

```rust
pub struct IsoImage {
    pub volume_id: Option<String>,
    pub files: Vec<IsoImageFile>,
    pub boot_info: BootInfo,
    /// ISO layout profile for firmware compatibility.
    /// Default: [IsoLayoutProfile::hardware] (GPT enabled, 2 MiB ESP alignment).
    /// For QEMU/OVMF, use [IsoLayoutProfile::emulator].
    pub layout_profile: IsoLayoutProfile,
}
```

**`layout_profile`**: Controls GPT/MBR partitioning, El Torito mode, ESP alignment, and UEFI boot strategy. Defaults to `IsoLayoutProfile::hardware()` (GPT enabled, 2 MiB ESP alignment, `HiddenSectorMode::Zero`). Use `IsoLayoutProfile::emulator()` for QEMU/OVMF compatibility (GPT enabled, `HiddenSectorMode::PartitionOffset`).

### `IsoImageFile`

Represents a file to be included in the ISO.

```rust
pub struct IsoImageFile {
    pub source: PathBuf,
    pub destination: String,
}
```

### `BootInfo`

Contains boot configuration for BIOS and/or UEFI booting.

```rust
pub struct BootInfo {
    pub bios_boot: Option<BiosBootInfo>,
    pub uefi_boot: Option<UefiBootInfo>,
}
```

### `BiosBootInfo`

Configuration for BIOS/El Torito boot support.

```rust
pub struct BiosBootInfo {
    pub boot_image: PathBuf,
    pub destination_in_iso: String,
}
```

### `UefiBootInfo`

Configuration for UEFI booting. For isohybrid images, this will create an EFI System Partition with the specified boot and kernel images.

```rust
pub struct UefiBootInfo {
    pub boot_image: PathBuf,
    pub kernel_image: PathBuf,
    pub destination_in_iso: String,
    pub additional_efi_boot_files: Vec<(String, PathBuf)>,
    pub grub_cfg_content: Option<String>,
}
```

**`additional_efi_boot_files`**: A list of (destination_filename, source_path) pairs for additional EFI boot files to include in the FAT ESP image (isohybrid only). For example, to add GRUBX64.EFI, set `additional_efi_boot_files: vec![("GRUBX64.EFI".to_string(), PathBuf::from("path/to/grubx64.efi"))]`.

**`grub_cfg_content`**: Optional string content for an auto-generated `grub.cfg` file placed at `EFI/BOOT/grub.cfg` in the FAT ESP image. When set, a grub.cfg with the specified content is automatically created in the ESP. Set to `None` to skip.

## Builder API

### `IsoBuilder`

Provides a builder pattern interface for more advanced ISO creation.

```rust
pub struct IsoBuilder { /* ... */ }
```

**Methods:**
- `new() -> Self`: Creates a new builder
- `set_volume_id(&mut self, v: Option<String>)`: Sets the volume ID
- `add_file(&mut self, path_in_iso: &str, real_path: &Path) -> io::Result<()>`: Adds a file to the ISO
- `set_boot_info(&mut self, boot_info: BootInfo)`: Sets boot configuration
- `set_profile(&mut self, profile: IsoLayoutProfile)`: Sets the layout profile
- `set_isohybrid(&mut self, is_isohybrid: bool)`: Enables hybrid isohybrid creation
- `set_disk_layout(&mut self, layout: DiskLayout)`: Sets a manual disk layout
- `build(&mut self, iso_file: &mut File, iso_path: &Path, esp_lba: Option<u32>, esp_size_sectors: Option<u32>) -> io::Result<()>`: Builds the ISO. **Note:** The `iso_file` must be opened with **read + write** access (e.g., `OpenOptions::new().read(true).write(true).create(true).truncate(true)`) because the builder reads back boot image data to compute the boot information table checksum. Using `File::create()` (write-only) will cause `EBADF` errors

**Public fields:**
- `esp_lba: Option<u32>` — ESP partition starting LBA (set automatically during build if not specified)
- `esp_size_sectors: Option<u32>` — ESP partition size in sectors (set automatically during build if not specified)

## Filesystem Nodes

### `IsoFsNode`

Represents a filesystem node in the ISO.

```rust
pub enum IsoFsNode {
    File(IsoFile),
    Directory(IsoDirectory),
}
```

### `IsoFile`

Represents a file in the ISO filesystem.

```rust
pub struct IsoFile {
    pub path: PathBuf,
    pub size: u64,
    pub lba: u32,
}
```

### `IsoDirectory`

Represents a directory in the ISO filesystem.

```rust
pub struct IsoDirectory {
    pub lba: u32,
    pub children: HashMap<String, IsoFsNode>,
}
```

## Constants

### `ISO_SECTOR_SIZE`

Size of one ISO 9660 sector (logical block) in bytes.

```rust
pub const ISO_SECTOR_SIZE: u64 = 2048;
```

### `DISK_SECTOR_SIZE`

Size of one disk sector (used by GPT, MBR, FAT BPB) in bytes.

```rust
pub const DISK_SECTOR_SIZE: u64 = 512;
```

### `ESP_START_LBA_ISO`

The starting LBA for the EFI System Partition in **ISO 2048-byte sectors** (LBA 1024 = 2 MiB). Used for El Torito catalog entries and ISO filesystem layout.

```rust
pub const ESP_START_LBA_ISO: u32 = 1024;
```

### `ESP_START_LBA_512`

The starting LBA for the EFI System Partition in **512-byte sectors** (LBA 4096 = 2 MiB). Used only for GPT partition entries and MBR partition table.

```rust
pub const ESP_START_LBA_512: u32 = 4096;
```

### `GPT_RESERVED_512_SECTORS`

Number of 512-byte sectors reserved at the start of the disk for the GPT protective area (MBR + GPT header + partition entry array = 34 sectors).

```rust
pub const GPT_RESERVED_512_SECTORS: u32 = 34;
```

### `BACKUP_GPT_RESERVED_512`

Number of 512-byte sectors needed for the backup GPT structures (1 header + 32 partition entries).

```rust
pub const BACKUP_GPT_RESERVED_512: u64 = 33;
```

### `iso_to_512(lba: u32) -> u32`

Converts an ISO 2048-byte sector LBA to the equivalent 512-byte sector LBA (multiply by 4).

### `disk512_to_iso(lba: u32) -> u32`

Converts a 512-byte disk sector LBA to the equivalent ISO 2048-byte sector LBA (divide by 4, rounding down).

## Layout Configuration

### `IsoLayoutProfile`

Controls multiple aspects of the ISO layout for firmware compatibility.

```rust
pub struct IsoLayoutProfile {
    pub use_gpt: bool,
    pub eltorito_mode: ElToritoMode,
    pub esp_mode: EspMode,
    pub esp_alignment_lba_512: u32,
    pub mbr_mode: MbrMode,
    pub hidden_sectors_mode: HiddenSectorMode,
    pub uefi_boot_strategy: UefiBootStrategy,
}
```

**Factory methods:**
- `IsoLayoutProfile::hardware()` — The default. GPT enabled, 2 MiB ESP alignment, `HiddenSectorMode::Zero`, `UefiBootStrategy::EspPartition`. Best for real hardware (NEC, Insyde, older Lenovo).
- `IsoLayoutProfile::emulator()` — GPT enabled, 2 MiB ESP alignment, `HiddenSectorMode::PartitionOffset`, `UefiBootStrategy::ElToritoDirectEfi`. Best for QEMU/OVMF.

### `ElToritoMode`

```rust
pub enum ElToritoMode {
    Both,
    DirectEfiOnly,
}
```

### `EspMode`

```rust
pub enum EspMode {
    AppendedPartition,
}
```

### `MbrMode`

```rust
pub enum MbrMode {
    HybridLinuxEsp,
}
```

### `HiddenSectorMode`

Controls the `hidden_sectors` field in the FAT BPB.

```rust
pub enum HiddenSectorMode {
    Zero,
    PartitionOffset,
}
```

### `UefiBootStrategy`

```rust
pub enum UefiBootStrategy {
    ElToritoDirectEfi,
    EspPartition,
}
```

## Disk Layout Structures

### `DiskLayout`

Manually-specified disk layout for the ISO image. Use `DiskLayout::from_partition_params` to construct.

```rust
pub struct DiskLayout {
    pub partitions: Vec<Partition>,
    pub iso_region: IsoRegion,
}
```

**Methods:**
- `from_partition_params(esp_align: u32, esp_size: Option<u32>, iso_data_lba: u32) -> Self`: Creates a `DiskLayout` with an optional ESP partition
- `esp_partition(&self) -> Option<&Partition>`: Returns the ESP partition if present
- `has_esp(&self) -> bool`: Returns `true` if the layout includes an ESP partition

### `Partition`

```rust
pub struct Partition {
    pub start_lba_512: u64,
    pub size_lba_512: u64,
}
```

### `IsoRegion`

```rust
pub struct IsoRegion {
    pub data_start_lba: u32,
    pub total_sectors: u32,
}
```

## Examples

### Basic UEFI-Bootable ISO

```rust
use isobemak::{build_iso, IsoImage, IsoImageFile, BootInfo, UefiBootInfo};
use std::path::PathBuf;

let kernel_path = PathBuf::from("path/to/kernel");
let bootx64_efi_path = PathBuf::from("path/to/BOOTX64.EFI");
let iso_output_path = PathBuf::from("bootable.iso");

let iso_image = IsoImage {
    volume_id: Some("label".to_string()),
    files: vec![
        IsoImageFile {
            source: kernel_path.clone(),
            destination: "kernel".to_string(),
        },
    ],
    boot_info: BootInfo {
        bios_boot: None,
        uefi_boot: Some(UefiBootInfo {
            boot_image: bootx64_efi_path.clone(),
            kernel_image: kernel_path.clone(),
            destination_in_iso: "EFI/BOOT/BOOTX64.EFI".to_string(),
            additional_efi_boot_files: Vec::new(),
            grub_cfg_content: None,
        }),
    },
    layout_profile: IsoLayoutProfile::default(),
};

// Create standard UEFI-bootable ISO
let (_iso_path, _temp_fat, _iso_file, _fat_size) = build_iso(&iso_output_path, &iso_image, false)?;
```

### Hybrid Isohybrid ISO (BIOS + UEFI)

```rust
use isobemak::{build_iso, IsoImage, IsoImageFile, BootInfo, BiosBootInfo, UefiBootInfo};
use std::path::PathBuf;

let isolinux_bin_path = PathBuf::from("path/to/isolinux.bin");
let kernel_path = PathBuf::from("path/to/kernel");
let bootx64_efi_path = PathBuf::from("path/to/BOOTX64.EFI");
let iso_output_path = PathBuf::from("hybrid.iso");

let iso_image = IsoImage {
    volume_id: Some("label".to_string()),
    files: vec![
        IsoImageFile {
            source: kernel_path.clone(),
            destination: "kernel".to_string(),
        },
    ],
    boot_info: BootInfo {
        bios_boot: Some(BiosBootInfo {
            boot_image: isolinux_bin_path.clone(),
            destination_in_iso: "isolinux/isolinux.bin".to_string(),
        }),
        uefi_boot: Some(UefiBootInfo {
            boot_image: bootx64_efi_path.clone(),
            kernel_image: kernel_path.clone(),
            destination_in_iso: "EFI/BOOT/BOOTX64.EFI".to_string(),
            additional_efi_boot_files: Vec::new(),
            grub_cfg_content: None,
        }),
    },
    layout_profile: IsoLayoutProfile::default(),
};

// Create hybrid isohybrid ISO
let (_iso_path, _temp_fat, _iso_file, _fat_size) = build_iso(&iso_output_path, &iso_image, true)?;
```

### Isohybrid ISO with GRUBX64.EFI

```rust
use isobemak::{build_iso, IsoImage, IsoImageFile, BootInfo, UefiBootInfo};
use std::path::PathBuf;

let bootx64_path = PathBuf::from("path/to/BOOTX64.EFI");
let grubx64_path = PathBuf::from("path/to/GRUBX64.EFI");
let kernel_path = PathBuf::from("path/to/kernel");
let iso_output_path = PathBuf::from("hybrid_grub.iso");

let iso_image = IsoImage {
    volume_id: Some("hybrid".to_string()),
    files: vec![
        IsoImageFile {
            source: kernel_path.clone(),
            destination: "kernel".to_string(),
        },
    ],
    boot_info: BootInfo {
        bios_boot: None,
        uefi_boot: Some(UefiBootInfo {
            boot_image: bootx64_path.clone(),
            kernel_image: kernel_path.clone(),
            destination_in_iso: "EFI/BOOT/BOOTX64.EFI".to_string(),
            additional_efi_boot_files: vec![
                ("GRUBX64.EFI".to_string(), grubx64_path.clone()),
            ],
            grub_cfg_content: None,
        }),
    },
    layout_profile: IsoLayoutProfile::default(),
};

// Create hybrid isohybrid ISO with GRUBX64.EFI in the ESP
let (_iso_path, _temp_fat, _iso_file, _fat_size) = build_iso(&iso_output_path, &iso_image, true)?;
```

### Isohybrid ISO with Auto-Generated grub.cfg

```rust
use isobemak::{build_iso, IsoImage, IsoImageFile, BootInfo, UefiBootInfo};
use std::path::PathBuf;

let bootx64_path = PathBuf::from("path/to/BOOTX64.EFI");
let kernel_path = PathBuf::from("path/to/kernel");
let iso_output_path = PathBuf::from("hybrid_grub_cfg.iso");

let grub_config = r#"set default=0
set timeout=5

menuentry "Boot from ISO" {
    chainloader /EFI/BOOT/BOOTX64.EFI
}

menuentry "Kernel" {
    linuxefi /EFI/BOOT/KERNEL.EFI
}
"#;

let iso_image = IsoImage {
    volume_id: Some("hybrid".to_string()),
    files: vec![
        IsoImageFile {
            source: kernel_path.clone(),
            destination: "kernel".to_string(),
        },
    ],
    boot_info: BootInfo {
        bios_boot: None,
        uefi_boot: Some(UefiBootInfo {
            boot_image: bootx64_path.clone(),
            kernel_image: kernel_path.clone(),
            destination_in_iso: "EFI/BOOT/BOOTX64.EFI".to_string(),
            additional_efi_boot_files: Vec::new(),
            grub_cfg_content: Some(grub_config.to_string()),
        }),
    },
    layout_profile: IsoLayoutProfile::default(),
};

// Create hybrid isohybrid ISO with auto-generated EFI/BOOT/grub.cfg in the ESP
let (_iso_path, _temp_fat, _iso_file, _fat_size) = build_iso(&iso_output_path, &iso_image, true)?;
```

### Using the Builder Pattern

```rust
use isobemak::{IsoBuilder, BootInfo, BiosBootInfo, UefiBootInfo};
use std::fs::OpenOptions;
use std::path::{Path, PathBuf};

let mut builder = IsoBuilder::new();
builder.set_isohybrid(true);

builder.add_file("kernel", PathBuf::from("my_kernel"))?;
builder.add_file("initrd.img", PathBuf::from("my_initrd"))?;

let boot_info = BootInfo {
    bios_boot: Some(BiosBootInfo {
        boot_image: PathBuf::from("isolinux.bin"),
        destination_in_iso: "isolinux/isolinux.bin".to_string(),
    }),
    uefi_boot: Some(UefiBootInfo {
        boot_image: PathBuf::from("BOOTX64.EFI"),
        kernel_image: PathBuf::from("kernel"),
        destination_in_iso: "EFI/BOOT/BOOTX64.EFI".to_string(),
        additional_efi_boot_files: vec![
            ("GRUBX64.EFI".to_string(), PathBuf::from("grubx64.efi")),
        ],
        grub_cfg_content: Some("set default=0\nset timeout=5\nmenuentry \"Boot\" {\n  chainloader /EFI/BOOT/BOOTX64.EFI\n}".to_string()),
    }),
};

builder.set_boot_info(boot_info);
builder.set_profile(IsoLayoutProfile::default());

// NOTE: Must use read+write access (the builder reads back boot image data
// to compute the boot information table checksum).
let mut iso_file = OpenOptions::new()
    .read(true)
    .write(true)
    .create(true)
    .truncate(true)
    .open("output.iso")?;
builder.build(&mut iso_file, Path::new("output.iso"), None, None)?;
```

## Error Handling

All functions return `io::Result<T>`, so handle `std::io::Error` for file I/O and validation errors.

Common errors:
- Invalid file paths
- Insufficient disk space
- Unsupported image sizes for hybrid ISOs (minimum 69 sectors)
- Missing boot files