Skip to main content

windows_headless/
media.rs

1//! Bootable USB installer media, built with pure Rust (no host tools).
2//!
3//! Proven design (spike-media, 2026-09-22): one FAT32 partition with the
4//! full ISO tree except `install.wim`, plus `wimlib-imagex split` output
5//! streamed into `sources/`. EDK2 boots it; Setup installs from it.
6//! macOS builds that partition as MBR (the layout the proving run used);
7//! Linux builds it as GPT + Microsoft Basic Data — see
8//! [`build_installer_media`].
9//! The only non-Rust input is the `wimlib-imagex` binary (vendored release
10//! asset); everything else is crates.io.
11use anyhow::{Context, Result};
12use hadris_fat::dir::FatDir;
13use hadris_fat::format::{FatFormatOptions, FatTypeSelection, FatVolumeFormatter};
14use hadris_fat::{FatVolume, FatVolumeWriteExt};
15use hadris_udf::{UdfDir, UdfVolume};
16use std::collections::HashSet;
17use std::fs::{File, OpenOptions};
18use std::io::{Read, Seek, SeekFrom, Write};
19use std::path::{Path, PathBuf};
20
21/// First data partition LBA (conventional 1 MiB alignment).
22pub const PART_LBA: u64 = 2048;
23
24/// Microsoft Basic Data partition type GUID (little-endian wire format).
25///
26/// Not the ESP type: WinPE mounts an ESP Hidden with no drive letter, so
27/// Setup never treats the volume as media ("Install driver to show
28/// hardware").  OVMF still boots `\EFI\BOOT\BOOTX64.EFI` from any FAT32
29/// volume regardless of partition type (Rufus rufus#461 did the same).
30const BASIC_DATA_TYPE_GUID: [u8; 16] = [
31    0xA2, 0xA0, 0xD0, 0xEB, 0xE5, 0xB9, 0x33, 0x44, 0x87, 0xC0, 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7,
32];
33
34/// GPT header signature "EFI PART".
35const GPT_SIG: [u8; 8] = *b"EFI PART";
36
37/// GPT header revision 1.0.
38const GPT_REV: u32 = 0x00010000;
39
40/// Number of partition entries (128 is standard).
41const GPT_NUM_ENTRIES: u32 = 128;
42
43/// Size of each partition entry (128 bytes is standard).
44const GPT_ENTRY_SIZE: u32 = 128;
45
46/// Write a GPT partition table + protective MBR for a UEFI-bootable image.
47/// Returns `(partition offset, partition size)` in bytes — the FAT32 volume
48/// must not exceed the size (the partition stops short of the disk end,
49/// where the backup GPT header and entries live).
50fn write_gpt_partition_table(
51    img: &mut File,
52    size_bytes: u64,
53    disk_guid: [u8; 16],
54) -> Result<(u64, u64)> {
55    let sector_size: u64 = 512;
56    let total_sectors = size_bytes / sector_size;
57    let part_start_lba = PART_LBA;
58    let entries_lba: u64 = 2;
59    let entries_bytes = GPT_NUM_ENTRIES as usize * GPT_ENTRY_SIZE as usize;
60    let entries_sectors = entries_bytes as u64 / sector_size; // 128
61    let backup_header_lba = total_sectors - 1;
62    let backup_entries_lba = backup_header_lba - entries_sectors;
63    let part_end_lba = backup_entries_lba - 1;
64
65    // --- Protective MBR (LBA 0) ---
66    let mut mbr = [0u8; 512];
67    mbr[446] = 0x00; // not bootable (GPT protective MBR)
68    mbr[447] = 0x00; // starting head
69    mbr[448] = 0x01; // starting sector
70    mbr[450] = 0xEE; // GPT protective
71    mbr[451] = 0xFF;
72    mbr[452] = 0xFF;
73    mbr[453] = 0xFF;
74    mbr[454..458].copy_from_slice(&1u32.to_le_bytes());
75    let mbr_size = (total_sectors - 1).min(u32::MAX as u64) as u32;
76    mbr[458..462].copy_from_slice(&mbr_size.to_le_bytes());
77    mbr[510] = 0x55;
78    mbr[511] = 0xAA;
79    img.seek(SeekFrom::Start(0))?;
80    img.write_all(&mbr)?;
81
82    // --- Partition entries (LBA 2) ---
83    // GPT entry layout (128 bytes each):
84    //   0..16   type GUID
85    //  16..32   unique partition GUID
86    //  32..40   starting LBA
87    //  40..48   ending LBA
88    //  48..56   attribute flags
89    //  56..128  partition name (UTF-16LE, 36 code units)
90    let mut entries = vec![0u8; entries_bytes];
91    {
92        let off = 0usize;
93        entries[off..off + 16].copy_from_slice(&BASIC_DATA_TYPE_GUID);
94        let part_guid = rand_guid();
95        entries[off + 16..off + 32].copy_from_slice(&part_guid);
96        entries[off + 32..off + 40].copy_from_slice(&part_start_lba.to_le_bytes());
97        entries[off + 40..off + 48].copy_from_slice(&part_end_lba.to_le_bytes());
98        // attributes: 0x5 = RequiredForFunctionality (0x1) + RequiredForBoot (0x4)
99        entries[off + 48..off + 56].copy_from_slice(&0x5u64.to_le_bytes());
100        let name = "Basic data partition";
101        for (i, ch) in name.encode_utf16().enumerate() {
102            let b = ch.to_le_bytes();
103            entries[off + 56 + 2 * i..off + 58 + 2 * i].copy_from_slice(&b);
104        }
105    }
106    img.seek(SeekFrom::Start(entries_lba * sector_size))?;
107    img.write_all(&entries)?;
108
109    let entries_crc = crc32fast::hash(&entries);
110
111    // --- Primary GPT header (LBA 1) ---
112    // Header layout (92 bytes used, rest zero):
113    //   0..8    signature
114    //   8..12   revision
115    //  12..16   header size (92)
116    //  16..20   CRC32 of header (computed last, with this field zeroed)
117    //  20..24   reserved
118    //  24..32   my LBA (primary header = 1)
119    //  32..40   alternate LBA (backup header)
120    //  40..48   first usable LBA
121    //  48..56   last usable LBA
122    //  56..72   disk GUID
123    //  72..80   partition entries start LBA
124    //  80..84   number of partition entries
125    //  84..88   size of partition entry
126    //  88..92   CRC32 of partition entries
127    let mut header = [0u8; 512];
128    header[0..8].copy_from_slice(&GPT_SIG);
129    header[8..12].copy_from_slice(&GPT_REV.to_le_bytes());
130    header[12..16].copy_from_slice(&92u32.to_le_bytes());
131    header[24..32].copy_from_slice(&1u64.to_le_bytes()); // my LBA
132    header[32..40].copy_from_slice(&backup_header_lba.to_le_bytes());
133    header[40..48].copy_from_slice(&(PART_LBA).to_le_bytes()); // first usable = part start
134    header[48..56].copy_from_slice(&part_end_lba.to_le_bytes());
135    header[56..72].copy_from_slice(&disk_guid);
136    header[72..80].copy_from_slice(&entries_lba.to_le_bytes());
137    header[80..84].copy_from_slice(&GPT_NUM_ENTRIES.to_le_bytes());
138    header[84..88].copy_from_slice(&GPT_ENTRY_SIZE.to_le_bytes());
139    header[88..92].copy_from_slice(&entries_crc.to_le_bytes());
140    let hdr_crc = crc32fast::hash(&header[0..92]);
141    header[16..20].copy_from_slice(&hdr_crc.to_le_bytes());
142    img.seek(SeekFrom::Start(sector_size))?;
143    img.write_all(&header)?;
144
145    // --- Backup partition entries (before backup header) ---
146    img.seek(SeekFrom::Start(backup_entries_lba * sector_size))?;
147    img.write_all(&entries)?;
148
149    // --- Backup GPT header (last LBA) ---
150    let mut backup = [0u8; 512];
151    backup[0..8].copy_from_slice(&GPT_SIG);
152    backup[8..12].copy_from_slice(&GPT_REV.to_le_bytes());
153    backup[12..16].copy_from_slice(&92u32.to_le_bytes());
154    backup[24..32].copy_from_slice(&backup_header_lba.to_le_bytes()); // my LBA
155    backup[32..40].copy_from_slice(&1u64.to_le_bytes()); // alternate = primary
156    backup[40..48].copy_from_slice(&PART_LBA.to_le_bytes());
157    backup[48..56].copy_from_slice(&part_end_lba.to_le_bytes());
158    backup[56..72].copy_from_slice(&disk_guid);
159    backup[72..80].copy_from_slice(&backup_entries_lba.to_le_bytes());
160    backup[80..84].copy_from_slice(&GPT_NUM_ENTRIES.to_le_bytes());
161    backup[84..88].copy_from_slice(&GPT_ENTRY_SIZE.to_le_bytes());
162    backup[88..92].copy_from_slice(&entries_crc.to_le_bytes());
163    let backup_crc = crc32fast::hash(&backup[0..92]);
164    backup[16..20].copy_from_slice(&backup_crc.to_le_bytes());
165    img.seek(SeekFrom::Start(backup_header_lba * sector_size))?;
166    img.write_all(&backup)?;
167
168    let part_off = part_start_lba * sector_size;
169    let part_size = (part_end_lba - part_start_lba + 1) * sector_size;
170    Ok((part_off, part_size))
171}
172
173/// Generate a random GUID (16 bytes, RFC 4122 v4).
174fn rand_guid() -> [u8; 16] {
175    use std::io::Read;
176    let mut buf = [0u8; 16];
177    if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
178        let _ = f.read_exact(&mut buf);
179    } else {
180        let t = std::time::SystemTime::now()
181            .duration_since(std::time::UNIX_EPOCH)
182            .unwrap_or_default()
183            .as_nanos();
184        buf[..16].copy_from_slice(&t.to_le_bytes());
185    }
186    buf[6] = (buf[6] & 0x0F) | 0x40;
187    buf[8] = (buf[8] & 0x3F) | 0x80;
188    buf
189}
190
191/// Write an MBR partition table (BIOS-bootable). Returns the partition data offset in bytes.
192fn write_mbr_partition_table(img: &mut File, size_bytes: u64) -> Result<u64> {
193    let part_off = PART_LBA * 512;
194    let part_sectors = ((size_bytes - part_off) / 512) as u32;
195    let mut mbr = vec![0u8; 512];
196    mbr[446] = 0x80;
197    mbr[450] = 0x0C;
198    mbr[454..458].copy_from_slice(&(PART_LBA as u32).to_le_bytes());
199    mbr[458..462].copy_from_slice(&part_sectors.to_le_bytes());
200    mbr[510] = 0x55;
201    mbr[511] = 0xAA;
202    img.seek(SeekFrom::Start(0))?;
203    img.write_all(&mbr)?;
204    Ok(part_off)
205}
206
207/// What to build: the retail Windows ISO in, a bootable raw image out.
208pub struct MediaSpec {
209    /// Source retail Windows ISO (UDF).
210    pub iso: PathBuf,
211    /// Output raw image path (created/truncated).
212    pub out: PathBuf,
213    /// Image size in bytes (10 GiB covers the ~8 GB tree + SWMs).
214    pub size_bytes: u64,
215    /// FAT32 volume label (`WINSETUP`).
216    pub label: String,
217    /// ISO file paths to stream into the image (one file at a time,
218    /// never all in RAM).  Pre-computed via [`list_iso_tree`].
219    pub iso_paths: Vec<String>,
220    /// Small files laid onto image (in-memory).
221    pub staged: Vec<(String, Vec<u8>)>,
222    /// SWM split-WIM parts (file paths, streamed).
223    pub swm_parts: Vec<PathBuf>,
224}
225
226/// Build the installer image: partition table + FAT32 + trees + staged + SWMs.
227///
228/// On Linux (pure UEFI via TianoCore/KVM), produces GPT + Basic Data FAT32.
229/// On macOS (HVF, Apple Silicon EDK2 — there is no CSM there), produces the
230/// proven MBR + FAT32 layout.
231///
232/// ISO tree files are streamed one at a time — never all in RAM — so peak
233/// memory is the size of the largest single file (~600 MB for boot.wim)
234/// instead of the entire tree (~6 GB).
235pub fn build_installer_media(spec: &MediaSpec) -> Result<()> {
236    let total: usize = spec.staged.iter().map(|(_, b)| b.len()).sum();
237    tracing::info!(
238        "media: {} staged ({total} bytes) + {} ISO paths + {} SWM parts",
239        spec.staged.len(),
240        spec.iso_paths.len(),
241        spec.swm_parts.len(),
242    );
243
244    let mut img = OpenOptions::new()
245        .read(true)
246        .write(true)
247        .create(true)
248        .truncate(true)
249        .open(&spec.out)
250        .with_context(|| format!("create {}", spec.out.display()))?;
251    img.set_len(spec.size_bytes)?;
252
253    // Partition table per host OS. macOS keeps the proven spike-media
254    // layout: one MBR/FAT32 partition. Linux writes GPT + Microsoft Basic
255    // Data — WinPE letters that volume, so Setup finds sources/install.swm
256    // (an ESP-typed or otherwise unlettered volume is mounted Hidden and
257    // Setup stops at "Install driver to show hardware"). EDK2 boots the
258    // same FAT32 tree from either table.
259    let (part_off, part_size) = match std::env::consts::OS {
260        "linux" => {
261            eprintln!("media: writing GPT + Basic Data partition ...");
262            write_gpt_partition_table(&mut img, spec.size_bytes, rand_guid())?
263        }
264        _ => {
265            eprintln!("media: writing MBR partition table ...");
266            let off = write_mbr_partition_table(&mut img, spec.size_bytes)?;
267            (off, spec.size_bytes - off)
268        }
269    };
270    let fat_size = part_size;
271
272    // FAT32 + full tree (dirs first, then files; writers finish() so
273    // directory-entry sizes commit — silent short files otherwise).
274    eprintln!(
275        "media: formatting {:.0} GB FAT32 ({}) ...",
276        fat_size as f64 / 1e9,
277        spec.label
278    );
279    let options = FatFormatOptions::new(fat_size)
280        .fat_type(FatTypeSelection::Fat32)
281        .volume_label(&spec.label)
282        .hidden_sectors(PART_LBA as u32);
283    let volume =
284        FatVolumeFormatter::format(PartitionView::new(img.try_clone()?, part_off), options)?;
285    tracing::info!("media: formatted {:?}", volume.fat_type());
286    drop(volume);
287    let f = OpenOptions::new().read(true).write(true).open(&spec.out)?;
288    let volume = FatVolume::open(PartitionView::new(f, part_off))?;
289
290    // --- Pass 1: create all directories (paths only, no content) ---
291    let mut created = HashSet::new();
292    created.insert(String::new());
293    let mut ordered: Vec<String> = spec
294        .iso_paths
295        .iter()
296        .chain(spec.staged.iter().map(|(p, _)| p))
297        .filter_map(|p| p.rsplit_once('/').map(|(d, _)| d.to_string()))
298        .collect();
299    ordered.sort_by_key(|d| d.len());
300    ordered.dedup();
301    for d in &ordered {
302        mkdir_p(&volume, d, &mut created)?;
303    }
304
305    // --- Pass 2: write staged files (small, in-memory) ---
306    let mut seen: HashSet<String> = HashSet::new();
307    for (path, data) in &spec.staged {
308        let key = path.to_lowercase();
309        if !seen.insert(key.clone()) {
310            eprintln!("media: duplicate staged entry skipped: {path}");
311            continue;
312        }
313        let (dir, name) = path.rsplit_once('/').unwrap_or(("", path.as_str()));
314        let parent = open_path(&volume, dir).with_context(|| format!("open parent for {path}"))?;
315        let file = volume
316            .create_file(&parent, name)
317            .with_context(|| format!("create {path}"))?;
318        let mut w = volume.write_file(&file)?;
319        let mut done = 0;
320        while done < data.len() {
321            let k = w.write(&data[done..])?;
322            if k == 0 {
323                anyhow::bail!("stalled write on {path}");
324            }
325            done += k;
326        }
327        w.finish()?;
328    }
329    let n_staged = spec.staged.len();
330    tracing::info!("media: {n_staged} staged files written");
331
332    // --- Pass 3: stream ISO tree files (one in RAM at a time) ---
333    //
334    // hadris_udf only offers `read_file() -> Result<Vec<u8>>` — no `Read`
335    // trait or streaming API.  We open the UDF volume once and read each
336    // file individually so at most one file's worth of bytes is live at a
337    // time (peak ≈ largest file, ~600 MB for boot.wim) instead of the
338    // entire tree (~6 GB) held simultaneously.
339    //
340    // hadris-udf rejects some images with `invalid Information Control
341    // Block` (observed inside an OrbStack Linux VM when extracting
342    // sources/install.wim from the ARM64 retail ISO; x86_64 Linux and macOS
343    // hosts parse with hadris).  isomage auto-detects ISO9660/UDF and
344    // tolerates those images, so every hadris failure falls back to it —
345    // per file when the volume opened, wholesale when even the open fails.
346    if !spec.iso_paths.is_empty() {
347        match UdfVolume::open(std::io::BufReader::new(File::open(&spec.iso)?)) {
348            Ok(udf) => {
349                eprintln!("media: streaming {} ISO files ...", spec.iso_paths.len());
350                // Lazily-parsed isomage tree, built on the first hadris
351                // per-file failure and reused for the rest.
352                let mut fallback: Option<(File, isomage::TreeNode)> = None;
353                for (i, path) in spec.iso_paths.iter().enumerate() {
354                    if seen.contains(&path.to_lowercase()) {
355                        eprintln!("media: duplicate ISO entry skipped: {path}");
356                        continue;
357                    }
358                    seen.insert(path.to_lowercase());
359                    let data = match read_file_from_udf(&udf, path)
360                        .with_context(|| format!("read {path} from ISO"))
361                    {
362                        Ok(d) => d,
363                        Err(e) => {
364                            eprintln!(
365                                "media: hadris read failed for {path} ({e:#}); isomage fallback ..."
366                            );
367                            read_iso_single_isomage_cached(&spec.iso, path, &mut fallback)?
368                        }
369                    };
370                    let (dir, name) = path.rsplit_once('/').unwrap_or(("", path.as_str()));
371                    let parent = open_path(&volume, dir)
372                        .with_context(|| format!("open parent for {path}"))?;
373                    let file = volume
374                        .create_file(&parent, name)
375                        .with_context(|| format!("create {path}"))?;
376                    let mut w = volume.write_file(&file)?;
377                    let mut done = 0;
378                    while done < data.len() {
379                        let k = w.write(&data[done..])?;
380                        if k == 0 {
381                            anyhow::bail!("stalled write on {path}");
382                        }
383                        done += k;
384                    }
385                    w.finish()?;
386                    let n = i + 1;
387                    if n % 250 == 0 || n == spec.iso_paths.len() {
388                        eprintln!("media: tree {n}/{} files ...", spec.iso_paths.len());
389                    }
390                }
391                tracing::info!("media: {} ISO files written", spec.iso_paths.len());
392            }
393            Err(e) => {
394                eprintln!(
395                    "media: hadris-udf open failed ({e:#}); falling back to isomage for {} files ...",
396                    spec.iso_paths.len()
397                );
398                stream_iso_paths_isomage(&spec.iso, &spec.iso_paths, &seen, &volume)?;
399                tracing::info!(
400                    "media: {} ISO files written (isomage)",
401                    spec.iso_paths.len()
402                );
403            }
404        }
405    }
406    drop(volume);
407
408    // Split-WIM parts, streamed (never whole in RAM).
409    if !spec.swm_parts.is_empty() {
410        let f = OpenOptions::new().read(true).write(true).open(&spec.out)?;
411        let volume = FatVolume::open(PartitionView::new(f, part_off))?;
412        let sources = open_path(&volume, "sources")?;
413        for src_path in &spec.swm_parts {
414            let name = src_path
415                .file_name()
416                .and_then(|n| n.to_str())
417                .with_context(|| format!("bad SWM name {}", src_path.display()))?;
418            let meta = std::fs::metadata(src_path)?;
419            let file = volume.create_file(&sources, name)?;
420            let mut w = volume.write_file(&file)?;
421            let mut src = File::open(src_path)?;
422            let mut chunk = vec![0u8; 64 * 1024 * 1024];
423            let mut total_w = 0u64;
424            loop {
425                let n = src.read(&mut chunk)?;
426                if n == 0 {
427                    break;
428                }
429                let mut done = 0;
430                while done < n {
431                    let k = w.write(&chunk[done..n])?;
432                    if k == 0 {
433                        anyhow::bail!("stall {name}");
434                    }
435                    done += k;
436                }
437                total_w += n as u64;
438                if total_w / (1024 * 1024 * 1024) != (total_w - n as u64) / (1024 * 1024 * 1024) {
439                    eprintln!("media: {name} ... {:.1} GB", total_w as f64 / 1e9);
440                }
441            }
442            w.finish()?;
443            tracing::info!("media: {name} streamed ({total_w} of {} bytes)", meta.len());
444            eprintln!("media: {name} done ({total_w} bytes)");
445        }
446        drop(volume);
447    }
448    Ok(())
449}
450
451/// Read ISO trees + extras + subtree-minus-skips into memory.
452/// `install.wim` (7 GB) must be in `skip`, never here — it arrives via
453/// `swm_parts` (split) instead.
454///
455/// Tries hadris-udf first; on failure (e.g. `invalid Information Control
456/// Block` on images hadris rejects) retries the same selection via
457/// isomage, which auto-detects ISO9660/UDF.
458pub fn read_iso_tree(
459    iso: &Path,
460    trees: &[String],
461    extra_files: &[String],
462    full_subtree: Option<&(String, Vec<String>)>,
463) -> Result<Vec<(String, Vec<u8>)>> {
464    match read_iso_tree_hadris(iso, trees, extra_files, full_subtree) {
465        Ok(v) => Ok(v),
466        Err(e) => {
467            eprintln!("media: hadris-udf failed ({e:#}); retrying with isomage fallback ...");
468            read_iso_tree_isomage(iso, trees, extra_files, full_subtree)
469        }
470    }
471}
472
473fn read_iso_tree_hadris(
474    iso: &Path,
475    trees: &[String],
476    extra_files: &[String],
477    full_subtree: Option<&(String, Vec<String>)>,
478) -> Result<Vec<(String, Vec<u8>)>> {
479    let udf = UdfVolume::open(std::io::BufReader::new(File::open(iso)?))
480        .with_context(|| format!("open UDF volume {}", iso.display()))?;
481    eprintln!("media: reading ISO tree from {} ...", iso.display());
482    let root = udf.root_dir()?;
483    let mut out = Vec::new();
484    for tree in trees {
485        let entry = find_dir(&root, tree)?.ok_or_else(|| anyhow::anyhow!("no /{tree} in ISO"))?;
486        let sub = udf.read_directory(&entry.icb)?;
487        collect(&udf, &sub, tree, &mut out)?;
488    }
489    for only in extra_files {
490        let parts: Vec<&str> = only.split('/').collect();
491        let dir = open_udf_path(&udf, &parts[..parts.len() - 1])?
492            .ok_or_else(|| anyhow::anyhow!("no dir for {only}"))?;
493        let file =
494            find_file(&dir, parts[parts.len() - 1])?.ok_or_else(|| anyhow::anyhow!("no {only}"))?;
495        out.push((only.clone(), udf.read_file(&file)?));
496    }
497    if let Some((tree, skip)) = full_subtree {
498        let dir = open_udf_path(&udf, &[tree])?.ok_or_else(|| anyhow::anyhow!("no /{tree}"))?;
499        collect_except(&udf, &dir, tree, &mut out, skip)?;
500    }
501    Ok(out)
502}
503
504/// List file paths in ISO trees + extras + subtree-minus-skips **without
505/// reading content**.  Use with [`read_file_from_udf`] to stream each file
506/// one at a time during FAT32 image building.
507///
508/// Same hadris-first / isomage-fallback policy as [`read_iso_tree`].
509pub fn list_iso_tree(
510    iso: &Path,
511    trees: &[String],
512    extra_files: &[String],
513    full_subtree: Option<&(String, Vec<String>)>,
514) -> Result<Vec<String>> {
515    match list_iso_tree_hadris(iso, trees, extra_files, full_subtree) {
516        Ok(v) => Ok(v),
517        Err(e) => {
518            eprintln!("media: hadris-udf listing failed ({e:#}); retrying with isomage ...");
519            list_iso_tree_isomage(iso, trees, extra_files, full_subtree)
520        }
521    }
522}
523
524fn list_iso_tree_hadris(
525    iso: &Path,
526    trees: &[String],
527    extra_files: &[String],
528    full_subtree: Option<&(String, Vec<String>)>,
529) -> Result<Vec<String>> {
530    let udf = UdfVolume::open(std::io::BufReader::new(File::open(iso)?))?;
531    eprintln!("media: listing ISO tree from {} ...", iso.display());
532    let root = udf.root_dir()?;
533    let mut paths = Vec::new();
534    for tree in trees {
535        let entry = find_dir(&root, tree)?.ok_or_else(|| anyhow::anyhow!("no /{tree} in ISO"))?;
536        let sub = udf.read_directory(&entry.icb)?;
537        list_collect(&udf, &sub, tree, &mut paths)?;
538    }
539    for only in extra_files {
540        paths.push(only.clone());
541    }
542    if let Some((tree, skip)) = full_subtree {
543        let dir = open_udf_path(&udf, &[tree])?.ok_or_else(|| anyhow::anyhow!("no /{tree}"))?;
544        list_collect_except(&udf, &dir, tree, &mut paths, skip)?;
545    }
546    eprintln!("media: listed {} files", paths.len());
547    Ok(paths)
548}
549
550fn list_collect(udf: &SyncUdf, dir: &UdfDir, prefix: &str, out: &mut Vec<String>) -> Result<()> {
551    for e in dir.all_entries() {
552        if e.is_parent() {
553            continue;
554        }
555        let p = format!("{prefix}/{}", e.name());
556        if e.is_dir() {
557            let sub = udf.read_directory(&e.icb)?;
558            list_collect(udf, &sub, &p, out)?;
559        } else {
560            out.push(p);
561        }
562    }
563    Ok(())
564}
565
566fn list_collect_except(
567    udf: &SyncUdf,
568    dir: &UdfDir,
569    prefix: &str,
570    out: &mut Vec<String>,
571    skip: &[String],
572) -> Result<()> {
573    for e in dir.all_entries() {
574        if e.is_parent() {
575            continue;
576        }
577        let p = format!("{prefix}/{}", e.name());
578        if e.is_dir() {
579            let sub = udf.read_directory(&e.icb)?;
580            list_collect_except(udf, &sub, &p, out, skip)?;
581        } else if !skip.iter().any(|s| e.name().eq_ignore_ascii_case(s)) {
582            out.push(p);
583        }
584    }
585    Ok(())
586}
587
588/// Read a single file from a UDF volume by relative path.
589/// The caller should open the UDF volume once and call this for each path
590/// to stream files without holding them all in RAM.
591pub fn read_file_from_udf(udf: &SyncUdf, rel_path: &str) -> Result<Vec<u8>> {
592    let parts: Vec<&str> = rel_path.split('/').collect();
593    let root = udf.root_dir()?;
594    navigate_and_read(udf, &root, &parts)
595}
596
597fn navigate_and_read(udf: &SyncUdf, dir: &UdfDir, parts: &[&str]) -> Result<Vec<u8>> {
598    if parts.is_empty() {
599        anyhow::bail!("empty path");
600    }
601    let part = parts[0];
602    let is_last = parts.len() == 1;
603    for e in dir.all_entries() {
604        if e.is_parent() {
605            continue;
606        }
607        if !e.name().eq_ignore_ascii_case(part) {
608            continue;
609        }
610        if is_last {
611            return udf.read_file(e).map_err(|e| anyhow::anyhow!("{e}"));
612        } else if e.is_dir() {
613            let sub = udf.read_directory(&e.icb)?;
614            return navigate_and_read(udf, &sub, &parts[1..]);
615        }
616    }
617    let full = parts.join("/");
618    anyhow::bail!("not found in ISO: {full}")
619}
620
621// ---------------------------------------------------------------------------
622// isomage fallback (ISO9660/UDF auto-detect)
623//
624// hadris-udf is strict UDF and rejects some genuine retail ISOs with
625// `invalid Information Control Block`.  isomage already parses those
626// (it is the reader used for the ISO9660 virtio-win image), so every
627// hadris entry point above retries here before surfacing an error.
628// Name matching stays case-insensitive to mirror the hadris helpers.
629// ---------------------------------------------------------------------------
630
631fn iso_find_ci<'a>(node: &'a isomage::TreeNode, comp: &str) -> Option<&'a isomage::TreeNode> {
632    node.children
633        .iter()
634        .find(|c| c.name.eq_ignore_ascii_case(comp))
635}
636
637fn iso_find_path<'a>(root: &'a isomage::TreeNode, rel: &str) -> Option<&'a isomage::TreeNode> {
638    let mut node = root;
639    for comp in rel.split('/').filter(|c| !c.is_empty()) {
640        node = iso_find_ci(node, comp)?;
641    }
642    Some(node)
643}
644
645fn iso_collect_files(
646    file: &mut File,
647    node: &isomage::TreeNode,
648    prefix: &str,
649    out: &mut Vec<(String, Vec<u8>)>,
650) -> Result<()> {
651    if node.is_directory {
652        for child in &node.children {
653            let p = if prefix.is_empty() {
654                child.name.clone()
655            } else {
656                format!("{prefix}/{}", child.name)
657            };
658            if child.is_directory {
659                iso_collect_files(file, child, &p, out)?;
660            } else {
661                let mut data = Vec::new();
662                isomage::cat_node(file, child, &mut data)
663                    .map_err(|e| anyhow::anyhow!("read {p}: {e}"))?;
664                out.push((p, data));
665            }
666        }
667        return Ok(());
668    }
669    let mut data = Vec::new();
670    isomage::cat_node(file, node, &mut data).map_err(|e| anyhow::anyhow!("read {prefix}: {e}"))?;
671    out.push((prefix.to_string(), data));
672    Ok(())
673}
674
675fn iso_collect_files_except(
676    file: &mut File,
677    node: &isomage::TreeNode,
678    prefix: &str,
679    out: &mut Vec<(String, Vec<u8>)>,
680    skip: &[String],
681) -> Result<()> {
682    if node.is_directory {
683        for child in &node.children {
684            let p = if prefix.is_empty() {
685                child.name.clone()
686            } else {
687                format!("{prefix}/{}", child.name)
688            };
689            if child.is_directory {
690                iso_collect_files_except(file, child, &p, out, skip)?;
691            } else if !skip.iter().any(|s| child.name.eq_ignore_ascii_case(s)) {
692                let mut data = Vec::new();
693                isomage::cat_node(file, child, &mut data)
694                    .map_err(|e| anyhow::anyhow!("read {p}: {e}"))?;
695                out.push((p, data));
696            }
697        }
698        return Ok(());
699    }
700    if !skip.iter().any(|s| node.name.eq_ignore_ascii_case(s)) {
701        let mut data = Vec::new();
702        isomage::cat_node(file, node, &mut data)
703            .map_err(|e| anyhow::anyhow!("read {prefix}: {e}"))?;
704        out.push((prefix.to_string(), data));
705    }
706    Ok(())
707}
708
709fn iso_list_paths(node: &isomage::TreeNode, prefix: &str, out: &mut Vec<String>) {
710    if node.is_directory {
711        for child in &node.children {
712            let p = if prefix.is_empty() {
713                child.name.clone()
714            } else {
715                format!("{prefix}/{}", child.name)
716            };
717            if child.is_directory {
718                iso_list_paths(child, &p, out);
719            } else {
720                out.push(p);
721            }
722        }
723    } else {
724        out.push(prefix.to_string());
725    }
726}
727
728fn iso_list_paths_except(
729    node: &isomage::TreeNode,
730    prefix: &str,
731    out: &mut Vec<String>,
732    skip: &[String],
733) {
734    if node.is_directory {
735        for child in &node.children {
736            let p = if prefix.is_empty() {
737                child.name.clone()
738            } else {
739                format!("{prefix}/{}", child.name)
740            };
741            if child.is_directory {
742                iso_list_paths_except(child, &p, out, skip);
743            } else if !skip.iter().any(|s| child.name.eq_ignore_ascii_case(s)) {
744                out.push(p);
745            }
746        }
747    } else if !skip.iter().any(|s| node.name.eq_ignore_ascii_case(s)) {
748        out.push(prefix.to_string());
749    }
750}
751
752fn read_iso_tree_isomage(
753    iso: &Path,
754    trees: &[String],
755    extra_files: &[String],
756    full_subtree: Option<&(String, Vec<String>)>,
757) -> Result<Vec<(String, Vec<u8>)>> {
758    let mut file = File::open(iso).with_context(|| format!("open {}", iso.display()))?;
759    let size = file.metadata().map(|m| m.len()).unwrap_or(0);
760    let root = isomage::detect_and_parse_filesystem(&mut file, &iso.to_string_lossy())
761        .map_err(|e| anyhow::anyhow!("isomage parse {} ({} bytes): {e}", iso.display(), size))?;
762    eprintln!(
763        "media: reading ISO tree via isomage from {} ...",
764        iso.display()
765    );
766    let mut out = Vec::new();
767    for tree in trees {
768        let node =
769            iso_find_path(&root, tree).ok_or_else(|| anyhow::anyhow!("no /{tree} in ISO"))?;
770        iso_collect_files(&mut file, node, tree, &mut out)?;
771    }
772    for only in extra_files {
773        let node = iso_find_path(&root, only).ok_or_else(|| anyhow::anyhow!("no {only} in ISO"))?;
774        if node.is_directory {
775            anyhow::bail!("{only} is a directory, not a file");
776        }
777        let mut data = Vec::new();
778        isomage::cat_node(&mut file, node, &mut data)
779            .map_err(|e| anyhow::anyhow!("read {only}: {e}"))?;
780        out.push((only.clone(), data));
781    }
782    if let Some((tree, skip)) = full_subtree {
783        let node = iso_find_path(&root, tree).ok_or_else(|| anyhow::anyhow!("no /{tree}"))?;
784        iso_collect_files_except(&mut file, node, tree, &mut out, skip)?;
785    }
786    Ok(out)
787}
788
789fn list_iso_tree_isomage(
790    iso: &Path,
791    trees: &[String],
792    extra_files: &[String],
793    full_subtree: Option<&(String, Vec<String>)>,
794) -> Result<Vec<String>> {
795    let mut file = File::open(iso).with_context(|| format!("open {}", iso.display()))?;
796    let size = file.metadata().map(|m| m.len()).unwrap_or(0);
797    let root = isomage::detect_and_parse_filesystem(&mut file, &iso.to_string_lossy())
798        .map_err(|e| anyhow::anyhow!("isomage parse {} ({} bytes): {e}", iso.display(), size))?;
799    eprintln!(
800        "media: listing ISO tree via isomage from {} ...",
801        iso.display()
802    );
803    let mut paths = Vec::new();
804    for tree in trees {
805        let node =
806            iso_find_path(&root, tree).ok_or_else(|| anyhow::anyhow!("no /{tree} in ISO"))?;
807        iso_list_paths(node, tree, &mut paths);
808    }
809    for only in extra_files {
810        paths.push(only.clone());
811    }
812    if let Some((tree, skip)) = full_subtree {
813        let node = iso_find_path(&root, tree).ok_or_else(|| anyhow::anyhow!("no /{tree}"))?;
814        iso_list_paths_except(node, tree, &mut paths, skip);
815    }
816    eprintln!("media: listed {} files (isomage)", paths.len());
817    Ok(paths)
818}
819
820/// Read one ISO file via a lazily-parsed isomage tree. The caller keeps
821/// `(File, TreeNode)` across files so a 1000-file tree parses once, not
822/// once per file.
823fn read_iso_single_isomage_cached(
824    iso: &Path,
825    rel_path: &str,
826    cached: &mut Option<(File, isomage::TreeNode)>,
827) -> Result<Vec<u8>> {
828    if cached.is_none() {
829        let mut file = File::open(iso).with_context(|| format!("open {}", iso.display()))?;
830        let root = isomage::detect_and_parse_filesystem(&mut file, &iso.to_string_lossy())
831            .map_err(|e| anyhow::anyhow!("isomage parse {}: {e}", iso.display()))?;
832        *cached = Some((file, root));
833    }
834    let (file, root) = cached.as_mut().expect("just populated");
835    let node = iso_find_path(root, rel_path)
836        .ok_or_else(|| anyhow::anyhow!("not found in ISO: {rel_path}"))?;
837    if node.is_directory {
838        anyhow::bail!("{rel_path} is a directory, not a file");
839    }
840    let mut data = Vec::new();
841    isomage::cat_node(file, node, &mut data)
842        .map_err(|e| anyhow::anyhow!("read {rel_path}: {e}"))?;
843    Ok(data)
844}
845
846/// Whole-tree isomage streaming for [`build_installer_media`] Pass 3: parse
847/// once, then `cat_node` each requested path straight into the FAT volume.
848/// `already_seen` mirrors the hadris path's duplicate suppression.
849fn stream_iso_paths_isomage<D: hadris_fat::Read + hadris_fat::Seek + hadris_fat::Write>(
850    iso: &Path,
851    iso_paths: &[String],
852    already_seen: &HashSet<String>,
853    volume: &FatVolume<D>,
854) -> Result<()> {
855    let mut file = File::open(iso).with_context(|| format!("open {}", iso.display()))?;
856    let root = isomage::detect_and_parse_filesystem(&mut file, &iso.to_string_lossy())
857        .map_err(|e| anyhow::anyhow!("isomage parse {}: {e}", iso.display()))?;
858    eprintln!(
859        "media: streaming {} ISO files (isomage) ...",
860        iso_paths.len()
861    );
862    let mut seen = already_seen.clone();
863    for (i, path) in iso_paths.iter().enumerate() {
864        if seen.contains(&path.to_lowercase()) {
865            eprintln!("media: duplicate ISO entry skipped: {path}");
866            continue;
867        }
868        seen.insert(path.to_lowercase());
869        let node = iso_find_path(&root, path).ok_or_else(|| anyhow::anyhow!("no {path} in ISO"))?;
870        if node.is_directory {
871            anyhow::bail!("{path} is a directory, not a file");
872        }
873        // One file in RAM at a time (same peak as the hadris path;
874        // the largest tree file is ~600 MB boot.wim).
875        let mut data = Vec::new();
876        isomage::cat_node(&mut file, node, &mut data)
877            .map_err(|e| anyhow::anyhow!("read {path}: {e}"))?;
878        let (dir, name) = path.rsplit_once('/').unwrap_or(("", path.as_str()));
879        let parent = open_path(volume, dir).with_context(|| format!("open parent for {path}"))?;
880        let out = volume
881            .create_file(&parent, name)
882            .with_context(|| format!("create {path}"))?;
883        let mut w = volume.write_file(&out)?;
884        let mut done = 0;
885        while done < data.len() {
886            let k = w.write(&data[done..])?;
887            if k == 0 {
888                anyhow::bail!("stalled write on {path}");
889            }
890            done += k;
891        }
892        w.finish()?;
893        let n = i + 1;
894        if n % 250 == 0 || n == iso_paths.len() {
895            eprintln!("media: tree {n}/{} files ...", iso_paths.len());
896        }
897    }
898    Ok(())
899}
900
901/// Stream one (possibly huge) ISO file straight to `out` on disk without
902/// ever holding it in RAM. Used for `sources/install.wim` (~7 GB): the old
903/// `read_iso_tree` + `fs::write` path needed that much RAM at once and
904/// OOMed small Linux VMs. isomage streams in 8 MiB chunks; hadris is the
905/// fallback (whole-file Vec) for images only it can parse.
906pub fn extract_iso_file_to_disk(iso: &Path, rel_path: &str, out: &Path) -> Result<()> {
907    // isomage first: streaming, no RAM spike, tolerates the ICB variants
908    // hadris rejects.
909    let stream = (|| -> Result<()> {
910        let mut file = File::open(iso).with_context(|| format!("open {}", iso.display()))?;
911        let root = isomage::detect_and_parse_filesystem(&mut file, &iso.to_string_lossy())
912            .map_err(|e| anyhow::anyhow!("isomage parse {}: {e}", iso.display()))?;
913        let node = iso_find_path(&root, rel_path)
914            .ok_or_else(|| anyhow::anyhow!("no {rel_path} in ISO"))?;
915        if node.is_directory {
916            anyhow::bail!("{rel_path} is a directory, not a file");
917        }
918        let out_file = File::create(out).with_context(|| format!("create {}", out.display()))?;
919        let mut writer = std::io::BufWriter::new(out_file);
920        isomage::cat_node(&mut file, node, &mut writer)
921            .map_err(|e| anyhow::anyhow!("read {rel_path}: {e}"))?;
922        writer.flush()?;
923        Ok(())
924    })();
925    if stream.is_ok() {
926        return stream;
927    }
928    eprintln!(
929        "media: isomage stream failed ({:#}); trying hadris-udf ...",
930        stream.as_ref().unwrap_err()
931    );
932    let data = read_iso_tree_hadris(iso, &[], &[rel_path.to_string()], None)?
933        .pop()
934        .map(|(_, b)| b)
935        .ok_or_else(|| anyhow::anyhow!("no {rel_path} in ISO"))?;
936    std::fs::write(out, &data).with_context(|| format!("write {}", out.display()))?;
937    Ok(())
938}
939
940/// NetKVM files out of virtio-win.iso (ISO9660 — hadris-udf rejects it;
941/// isomage auto-detects). Returns `drivers/NetKVM/w11/<arch>/*` entries
942/// ready for staging. Pure Rust, streamed, never whole in RAM.
943pub fn extract_virtio_netkvm(
944    iso: &Path,
945    arch: crate::unattend::Architecture,
946) -> Result<Vec<(String, Vec<u8>)>> {
947    let mut file = File::open(iso)?;
948    let root = isomage::detect_and_parse_filesystem(&mut file, crate::paths::VIRTIO_ISO)
949        .map_err(|e| anyhow::anyhow!("parse {}: {e}", crate::paths::VIRTIO_ISO))?;
950    fn find<'a>(node: &'a isomage::TreeNode, name: &str) -> Option<&'a isomage::TreeNode> {
951        node.children
952            .iter()
953            .find(|c| c.name.eq_ignore_ascii_case(name))
954    }
955    let mut node = &root;
956    let arch_dir = arch.netkvm_iso_dir();
957    for comp in ["NetKVM", "w11", arch_dir] {
958        node = find(node, comp)
959            .with_context(|| format!("{comp} missing in {}", crate::paths::VIRTIO_ISO))?;
960    }
961    let mut out = Vec::new();
962    for f in [
963        "netkvm.inf",
964        "netkvm.sys",
965        "netkvm.cat",
966        "netkvmco.exe",
967        "netkvmp.exe",
968    ] {
969        let child = find(node, f)
970            .with_context(|| format!("{f} missing in {}", crate::paths::VIRTIO_ISO))?;
971        let mut data = Vec::new();
972        isomage::cat_node(&mut file, child, &mut data)
973            .map_err(|e| anyhow::anyhow!("read {f}: {e}"))?;
974        out.push((
975            format!(
976                "{}/NetKVM/w11/{arch_dir}/{f}",
977                crate::paths::DRIVERS_STAGE_DIR
978            ),
979            data,
980        ));
981    }
982    Ok(out)
983}
984
985/// Run `wimlib-imagex split <wim> <out-prefix> 4000` (vendored binary).
986/// Produces `<prefix>` (`install.swm`) + `<stem>2.swm`.
987pub fn split_wim(wimlib_bin: &Path, wim: &Path, out_prefix: &Path) -> Result<Vec<PathBuf>> {
988    let st = std::process::Command::new(wimlib_bin)
989        .args([
990            "split",
991            &wim.to_string_lossy(),
992            &out_prefix.to_string_lossy(),
993            "4000",
994        ])
995        .status()
996        .with_context(|| format!("run {}", wimlib_bin.display()))?;
997    if !st.success() {
998        anyhow::bail!("wimlib-imagex split failed");
999    }
1000    let stem = out_prefix
1001        .file_stem()
1002        .and_then(|s| s.to_str())
1003        .unwrap_or("install");
1004    let parent = out_prefix.parent().unwrap_or(Path::new("."));
1005    let ext = out_prefix
1006        .extension()
1007        .and_then(|e| e.to_str())
1008        .unwrap_or("swm");
1009    let mut parts = vec![out_prefix.to_path_buf()];
1010    let second = parent.join(format!("{stem}2.{ext}"));
1011    if second.is_file() {
1012        parts.push(second);
1013    }
1014    Ok(parts)
1015}
1016
1017type SyncUdf = UdfVolume<std::io::BufReader<File>>;
1018
1019fn find_file(dir: &UdfDir, name: &str) -> Result<Option<hadris_udf::dir::UdfDirEntry>> {
1020    for e in dir.all_entries() {
1021        if e.is_parent() || !e.is_file() || !e.name().eq_ignore_ascii_case(name) {
1022            continue;
1023        }
1024        return Ok(Some(e.clone()));
1025    }
1026    Ok(None)
1027}
1028
1029fn open_udf_path(udf: &SyncUdf, comps: &[&str]) -> Result<Option<UdfDir>> {
1030    let mut cur = udf.root_dir()?;
1031    for c in comps {
1032        let Some(e) = find_dir(&cur, c)? else {
1033            return Ok(None);
1034        };
1035        cur = udf.read_directory(&e.icb)?;
1036    }
1037    Ok(Some(cur))
1038}
1039
1040fn find_dir(dir: &UdfDir, name: &str) -> Result<Option<hadris_udf::dir::UdfDirEntry>> {
1041    for e in dir.all_entries() {
1042        if e.is_parent() || !e.is_dir() || !e.name().eq_ignore_ascii_case(name) {
1043            continue;
1044        }
1045        return Ok(Some(e.clone()));
1046    }
1047    Ok(None)
1048}
1049
1050fn collect(
1051    udf: &SyncUdf,
1052    dir: &UdfDir,
1053    prefix: &str,
1054    out: &mut Vec<(String, Vec<u8>)>,
1055) -> Result<()> {
1056    for e in dir.all_entries() {
1057        if e.is_parent() {
1058            continue;
1059        }
1060        let p = format!("{prefix}/{}", e.name());
1061        if e.is_dir() {
1062            let sub = udf.read_directory(&e.icb)?;
1063            collect(udf, &sub, &p, out)?;
1064        } else {
1065            out.push((p, udf.read_file(e)?));
1066        }
1067    }
1068    Ok(())
1069}
1070
1071fn collect_except(
1072    udf: &SyncUdf,
1073    dir: &UdfDir,
1074    prefix: &str,
1075    out: &mut Vec<(String, Vec<u8>)>,
1076    skip: &[String],
1077) -> Result<()> {
1078    for e in dir.all_entries() {
1079        if e.is_parent() {
1080            continue;
1081        }
1082        let p = format!("{prefix}/{}", e.name());
1083        if e.is_dir() {
1084            let sub = udf.read_directory(&e.icb)?;
1085            collect_except(udf, &sub, &p, out, skip)?;
1086        } else if !skip.iter().any(|s| e.name().eq_ignore_ascii_case(s)) {
1087            out.push((p, udf.read_file(e)?));
1088        }
1089    }
1090    Ok(())
1091}
1092
1093fn mkdir_p<D: hadris_fat::Read + hadris_fat::Seek + hadris_fat::Write>(
1094    volume: &FatVolume<D>,
1095    path: &str,
1096    created: &mut HashSet<String>,
1097) -> Result<()> {
1098    let mut cur = String::new();
1099    for comp in path.split('/') {
1100        if comp.is_empty() {
1101            continue;
1102        }
1103        let parent_path = cur.clone();
1104        cur = if cur.is_empty() {
1105            comp.to_string()
1106        } else {
1107            format!("{cur}/{comp}")
1108        };
1109        if created.contains(&cur) {
1110            continue;
1111        }
1112        let parent = open_path(volume, &parent_path)?;
1113        volume.create_dir(&parent, comp)?;
1114        created.insert(cur.clone());
1115    }
1116    Ok(())
1117}
1118
1119fn open_path<'a, D: hadris_fat::Read + hadris_fat::Seek>(
1120    volume: &'a FatVolume<D>,
1121    path: &str,
1122) -> Result<FatDir<'a, D>> {
1123    let root = volume.root_dir();
1124    let mut stack: Vec<FatDir<D>> = vec![root];
1125    for comp in path.split('/').filter(|c| !c.is_empty()) {
1126        let top = stack.last().unwrap();
1127        let mut it = top.entries();
1128        let mut next = None;
1129        while let Some(entry) = it.next_entry() {
1130            let entry = entry?;
1131            if entry.name().eq_ignore_ascii_case(comp) {
1132                let e = entry
1133                    .as_entry()
1134                    .ok_or_else(|| anyhow::anyhow!("no entry"))?
1135                    .clone();
1136                next = Some(top.open_entry(&e)?);
1137                break;
1138            }
1139        }
1140        stack.push(next.ok_or_else(|| anyhow::anyhow!("{comp} missing in {path}"))?);
1141    }
1142    Ok(stack.pop().unwrap())
1143}
1144
1145/// File view at a byte offset (partition access without a loop device).
1146struct PartitionView {
1147    f: File,
1148    base: u64,
1149    pos: u64,
1150}
1151
1152impl PartitionView {
1153    fn new(f: File, base: u64) -> Self {
1154        Self { f, base, pos: 0 }
1155    }
1156}
1157
1158impl Read for PartitionView {
1159    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1160        self.f.seek(SeekFrom::Start(self.base + self.pos))?;
1161        let n = self.f.read(buf)?;
1162        self.pos += n as u64;
1163        Ok(n)
1164    }
1165}
1166
1167impl Write for PartitionView {
1168    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1169        self.f.seek(SeekFrom::Start(self.base + self.pos))?;
1170        let n = self.f.write(buf)?;
1171        self.pos += n as u64;
1172        Ok(n)
1173    }
1174    fn flush(&mut self) -> std::io::Result<()> {
1175        self.f.flush()
1176    }
1177}
1178
1179impl Seek for PartitionView {
1180    fn seek(&mut self, p: SeekFrom) -> std::io::Result<u64> {
1181        let base = self.pos as i64;
1182        let n = match p {
1183            SeekFrom::Start(o) => o as i64,
1184            SeekFrom::End(o) => self.f.metadata()?.len() as i64 - self.base as i64 + o,
1185            SeekFrom::Current(o) => base + o,
1186        };
1187        if n < 0 {
1188            return Err(std::io::Error::new(
1189                std::io::ErrorKind::InvalidInput,
1190                "seek before start",
1191            ));
1192        }
1193        self.pos = n as u64;
1194        Ok(self.pos)
1195    }
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200    use super::*;
1201
1202    /// Canonical (RFC-4122) text form of a GPT GUID stored in the on-disk
1203    /// wire layout: Data1/Data2/Data3 little-endian, Data4 in file order.
1204    fn guid_text(bytes: [u8; 16]) -> String {
1205        let d1 = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
1206        let d2 = u16::from_le_bytes([bytes[4], bytes[5]]);
1207        let d3 = u16::from_le_bytes([bytes[6], bytes[7]]);
1208        let tail: String = bytes[8..].iter().map(|b| format!("{b:02X}")).collect();
1209        format!(
1210            "{d1:08X}-{d2:04X}-{d3:04X}-{}-{}",
1211            &tail[0..4],
1212            &tail[4..16]
1213        )
1214    }
1215
1216    /// Windows mounts an ESP hidden with no drive letter, and refuses to
1217    /// mount a GUID it does not know at all — either way Setup never sees
1218    /// `sources/install.swm` as media ("Install driver to show hardware").
1219    /// A swapped byte pair here (c087 vs 87c0) produced exactly that.
1220    #[test]
1221    fn basic_data_type_guid_is_microsoft_basic_data() {
1222        assert_eq!(
1223            guid_text(BASIC_DATA_TYPE_GUID),
1224            "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7"
1225        );
1226    }
1227
1228    #[test]
1229    fn gpt_is_uefi_bootable_basic_data_that_fits_the_partition() {
1230        const SIZE: u64 = 64 * 1024 * 1024;
1231        let dir = tempfile::tempdir().unwrap();
1232        let mut img = OpenOptions::new()
1233            .read(true)
1234            .write(true)
1235            .create(true)
1236            .truncate(true)
1237            .open(dir.path().join("t.img"))
1238            .unwrap();
1239        img.set_len(SIZE).unwrap();
1240
1241        let (part_off, part_size) = write_gpt_partition_table(&mut img, SIZE, [0x11; 16]).unwrap();
1242
1243        let mut buf = vec![0u8; 4096];
1244        // Protective MBR: not bootable, type 0xEE, 0x55AA signature.
1245        img.seek(SeekFrom::Start(0)).unwrap();
1246        img.read_exact(&mut buf[..512]).unwrap();
1247        assert_eq!(buf[446], 0x00, "protective MBR must not be bootable");
1248        assert_eq!(buf[450], 0xEE, "protective MBR type");
1249        assert_eq!(&buf[510..512], &[0x55, 0xAA]);
1250
1251        // Partition entry 0.
1252        img.seek(SeekFrom::Start(2 * 512)).unwrap();
1253        img.read_exact(&mut buf[..128]).unwrap();
1254        assert_eq!(
1255            guid_text(buf[0..16].try_into().unwrap()),
1256            guid_text(BASIC_DATA_TYPE_GUID)
1257        );
1258        assert_eq!(
1259            &buf[48..56],
1260            &0x5u64.to_le_bytes(),
1261            "platform-required + legacy-bios-bootable"
1262        );
1263        let name = String::from_utf16_lossy(
1264            &buf[56..128]
1265                .as_chunks::<2>()
1266                .0
1267                .iter()
1268                .map(|c| u16::from_le_bytes(*c))
1269                .collect::<Vec<_>>(),
1270        );
1271        assert_eq!(name.trim_end_matches('\0'), "Basic data partition");
1272        let start = u64::from_le_bytes(buf[32..40].try_into().unwrap());
1273        let end = u64::from_le_bytes(buf[40..48].try_into().unwrap());
1274        assert_eq!(part_off, start * 512);
1275        assert_eq!(part_size, (end - start + 1) * 512);
1276        assert_eq!(
1277            part_size,
1278            SIZE - part_off - 33 * 512,
1279            "ends before backup GPT"
1280        );
1281
1282        // Backup GPT header lives at the last sector.
1283        img.seek(SeekFrom::Start(SIZE - 512)).unwrap();
1284        img.read_exact(&mut buf[..8]).unwrap();
1285        assert_eq!(&buf[..8], b"EFI PART");
1286    }
1287
1288    /// Requires the real virtio-win ISO in the dev cache (877 MB, not
1289    /// hermetic): `cargo test -- --ignored`.
1290    #[test]
1291    #[ignore]
1292    fn extracts_netkvm_from_virtio_iso() {
1293        let iso = Path::new(".cache/iso/virtio-win.iso");
1294        if !iso.is_file() {
1295            eprintln!("skipping: {iso:?} absent");
1296            return;
1297        }
1298        let files = extract_virtio_netkvm(iso, crate::unattend::Architecture::Arm64).unwrap();
1299        assert_eq!(files.len(), 5);
1300        for (p, data) in &files {
1301            assert!(p.starts_with("drivers/NetKVM/w11/arm64/"), "{p}");
1302            assert!(!data.is_empty(), "{p} empty");
1303        }
1304    }
1305}