🐛 Put the offline installer on an HFS+ volume every Recovery mounts
The installer image's Installer volume was exFAT. The Recovery that the installers of macOS 14.8.9 and 15.8.2 boot (14.6.1 and 15.6.1) mounts no exFAT or FAT32 volume by itself, not even ones macOS made, and there `diskutil mount` refuses them, so `sh /Volumes/Installer/install-macos.sh` found no script. The installer Recovery of 11.7.11, 12.7.6, 13.7.8, 14.8.9, 15.8.2 and 26.7.2 each mounts this image's HFS+ volume by itself, so the Installer volume is now HFS+, written by reims-util as the exFAT one was: the two files, each in one extent, no journal, in an Apple HFS partition. The typed command stays the same.
This commit is contained in:
1 parent
25777776f7
commit
0dcd362100
7 files changed
+721
-521
No files matched your search
@@ -145,7 +145,9 @@ Recovery always installs the newest release of its macOS, downloaded as it goes.
|
||||
particular one, such as 26.6.2 when 26.7.1 is out, or to install with no network, make an offline
|
||||
installer: a disk image, `macOS-<name>-<version>-<build>-offline-installer.img`, of 13 to 20 GB.
|
||||
It holds the recovery image of that macOS, which OpenCore boots as it would from a USB stick, and
|
||||
Apple's full installer for that release, with a script that installs it.
|
||||
Apple's full installer for that release, with a script that installs it, on an HFS+ volume named
|
||||
Installer: Recovery mounts HFS+ by itself on every macOS from 11 to 26, while the Recovery of
|
||||
macOS 14 and 15 mounts no exFAT or FAT32 volume by itself.
|
||||
|
||||
`offline-installer list` shows the releases Apple's software update catalog has for Intel Macs;
|
||||
macOS 27 runs on Apple silicon only, so it isn't there. Name one by version (`26.6.2`, or `26` for
|
||||
|
||||
+1
-1
@@ -156,7 +156,7 @@ VERSION is a version (26.7.1, or 26 for the newest 26), a build (25G241), Apple'
|
||||
a name (tahoe, for the newest Tahoe) or latest. The installer is
|
||||
macOS-<name>-<version>-<build>-offline-installer.img, a disk image of two volumes: the
|
||||
recovery image of the same macOS, which OpenCore boots, and Apple's full installer, with a
|
||||
script that installs it.
|
||||
script that installs it, on an HFS+ volume Recovery mounts by itself.
|
||||
|
||||
reims-util offline-installer 26.7.1
|
||||
reims-ctl create mac --opencore OpenCore.qcow2 \\
|
||||
|
||||
@@ -1,499 +0,0 @@
|
||||
//! An exFAT volume holding files in its root folder, as Microsoft's exFAT File System
|
||||
//! Specification lays it out:
|
||||
//! - the main boot region, sectors 0 to 11: the boot sector, eight extended boot sectors, the
|
||||
//! OEM parameters, a reserved sector, and the boot checksum; its backup, sectors 12 to 23;
|
||||
//! - one FAT;
|
||||
//! - the cluster heap, from cluster 2: the allocation bitmap, the up-case table, the root
|
||||
//! folder, then each file in consecutive clusters, with its FAT chain written.
|
||||
//!
|
||||
//! exFAT is here for what FAT32 cannot hold: a file of 4 GiB or more, such as a macOS installer
|
||||
//! package (12 to 18 GB). macOS reads it, macOS Recovery included.
|
||||
|
||||
use super::Data;
|
||||
use anyhow::{Result, ensure};
|
||||
|
||||
const SECTOR: u64 = 512;
|
||||
/// Where the FAT starts: past both boot regions, 64 KiB in.
|
||||
const FAT_OFFSET: u64 = 128;
|
||||
const EOC: u32 = 0xffff_ffff;
|
||||
const ENTRY: usize = 32;
|
||||
|
||||
/// A volume of `size` bytes (a whole partition) holding `files` in its root folder, as byte
|
||||
/// ranges from the volume's start. `partition_offset` is the sector the partition starts at on
|
||||
/// its disk; `label` is up to 11 characters; `serial` the volume serial number; `now` a FAT
|
||||
/// (date, time), which every file is given.
|
||||
pub fn make(
|
||||
size: u64,
|
||||
partition_offset: u64,
|
||||
label: &str,
|
||||
serial: u32,
|
||||
files: &[(String, Data)],
|
||||
now: (u16, u16),
|
||||
) -> Result<Vec<(u64, Data)>> {
|
||||
ensure!(
|
||||
size.is_multiple_of(SECTOR) && size >= 1 << 20,
|
||||
"an exFAT volume is 1 MiB at least, in whole sectors"
|
||||
);
|
||||
let label: Vec<u16> = label.encode_utf16().collect();
|
||||
ensure!(label.len() <= 11, "an exFAT label is 11 characters at most");
|
||||
let volume_sectors = size / SECTOR;
|
||||
let shift = cluster_shift(size);
|
||||
let per_cluster = 1u64 << shift;
|
||||
let cluster_bytes = per_cluster * SECTOR;
|
||||
|
||||
// The FAT is sized for every cluster the volume could have; the heap starts on a cluster
|
||||
// boundary after it.
|
||||
let fat_len = ((volume_sectors / per_cluster + 2) * 4).div_ceil(SECTOR);
|
||||
let heap = (FAT_OFFSET + fat_len).next_multiple_of(per_cluster);
|
||||
ensure!(heap < volume_sectors, "the volume is too small");
|
||||
let clusters = u32::try_from((volume_sectors - heap) / per_cluster)?;
|
||||
ensure!(clusters <= 0xffff_fff5, "the volume has too many clusters");
|
||||
|
||||
let mut fat = vec![0u32; clusters as usize + 2];
|
||||
fat[0] = 0xffff_fff8;
|
||||
fat[1] = EOC;
|
||||
let mut next = 2u32;
|
||||
let mut alloc = |bytes: u64| -> Result<u32> {
|
||||
let n = u32::try_from(bytes.div_ceil(cluster_bytes).max(1))?;
|
||||
let first = next;
|
||||
ensure!(
|
||||
u64::from(first) + u64::from(n) <= u64::from(clusters) + 2,
|
||||
"the files do not fit the volume"
|
||||
);
|
||||
for c in first..first + n {
|
||||
fat[c as usize] = if c + 1 == first + n { EOC } else { c + 1 };
|
||||
}
|
||||
next += n;
|
||||
Ok(first)
|
||||
};
|
||||
|
||||
let bitmap_len = u64::from(clusters).div_ceil(8);
|
||||
let bitmap_at = alloc(bitmap_len)?;
|
||||
let upcase = upcase_table();
|
||||
let upcase_at = alloc(upcase.len() as u64)?;
|
||||
let upcase_map = expand_upcase(&upcase);
|
||||
|
||||
let mut entries: Vec<[u8; ENTRY]> = Vec::new();
|
||||
let mut e = [0u8; ENTRY];
|
||||
e[0] = 0x83;
|
||||
e[1] = label.len() as u8;
|
||||
for (i, c) in label.iter().enumerate() {
|
||||
e[2 + i * 2..4 + i * 2].copy_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
entries.push(e);
|
||||
let mut e = [0u8; ENTRY];
|
||||
e[0] = 0x81;
|
||||
e[20..24].copy_from_slice(&bitmap_at.to_le_bytes());
|
||||
e[24..32].copy_from_slice(&bitmap_len.to_le_bytes());
|
||||
entries.push(e);
|
||||
let mut e = [0u8; ENTRY];
|
||||
e[0] = 0x82;
|
||||
e[4..8].copy_from_slice(&checksum32(&upcase).to_le_bytes());
|
||||
e[20..24].copy_from_slice(&upcase_at.to_le_bytes());
|
||||
e[24..32].copy_from_slice(&(upcase.len() as u64).to_le_bytes());
|
||||
entries.push(e);
|
||||
|
||||
let names: Vec<Vec<u16>> = files
|
||||
.iter()
|
||||
.map(|(name, _)| name.encode_utf16().collect())
|
||||
.collect();
|
||||
for ((name, _), units) in files.iter().zip(&names) {
|
||||
ensure!(
|
||||
!units.is_empty()
|
||||
&& units.len() <= 255
|
||||
&& !name.chars().any(|c| c < ' ' || "\"*/:<>?\\|".contains(c)),
|
||||
"bad exFAT file name {name:?}"
|
||||
);
|
||||
}
|
||||
let set_entries: usize = names.iter().map(|n| 2 + n.len().div_ceil(15)).sum();
|
||||
// One entry more, unused, ends the folder.
|
||||
let root_at = alloc(((entries.len() + set_entries + 1) * ENTRY) as u64)?;
|
||||
|
||||
let mut pieces = Vec::new();
|
||||
let stamp = (u32::from(now.0) << 16) | u32::from(now.1);
|
||||
for ((_, data), name) in files.iter().zip(&names) {
|
||||
let first = if data.size() == 0 {
|
||||
0
|
||||
} else {
|
||||
alloc(data.size())?
|
||||
};
|
||||
if data.size() != 0 {
|
||||
pieces.push((first, data.clone()));
|
||||
}
|
||||
entries.extend(file_set(name, &upcase_map, first, data.size(), stamp));
|
||||
}
|
||||
let used = next - 2;
|
||||
|
||||
let mut bitmap = vec![0u8; bitmap_len as usize];
|
||||
for i in 0..used as usize {
|
||||
bitmap[i / 8] |= 1 << (i % 8);
|
||||
}
|
||||
|
||||
let boot = boot_region(&BootSector {
|
||||
partition_offset,
|
||||
volume_sectors,
|
||||
fat_len: fat_len as u32,
|
||||
heap: heap as u32,
|
||||
clusters,
|
||||
root: root_at,
|
||||
serial,
|
||||
shift,
|
||||
percent_in_use: (u64::from(used) * 100 / u64::from(clusters)) as u8,
|
||||
});
|
||||
let cluster_at = |c: u32| (heap + u64::from(c - 2) * per_cluster) * SECTOR;
|
||||
// Each structure fills its sectors or clusters, so none keeps what an earlier image left.
|
||||
let whole = |mut b: Vec<u8>, unit: u64| {
|
||||
b.resize(b.len().next_multiple_of(unit as usize), 0);
|
||||
Data::Bytes(b)
|
||||
};
|
||||
let mut out = vec![
|
||||
(0, Data::Bytes(boot.clone())),
|
||||
(12 * SECTOR, Data::Bytes(boot)),
|
||||
(
|
||||
FAT_OFFSET * SECTOR,
|
||||
whole(
|
||||
fat.iter().flat_map(|v| v.to_le_bytes()).collect(),
|
||||
fat_len * SECTOR,
|
||||
),
|
||||
),
|
||||
(cluster_at(bitmap_at), whole(bitmap, cluster_bytes)),
|
||||
(cluster_at(upcase_at), whole(upcase, cluster_bytes)),
|
||||
(cluster_at(root_at), whole(entries.concat(), cluster_bytes)),
|
||||
];
|
||||
out.extend(pieces.into_iter().map(|(c, d)| {
|
||||
let d = match d {
|
||||
Data::Bytes(b) => whole(b, cluster_bytes),
|
||||
reserved => reserved,
|
||||
};
|
||||
(cluster_at(c), d)
|
||||
}));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sectors per cluster, as a power of two, by Microsoft's defaults for the volume's size: 4 KiB
|
||||
/// clusters up to 256 MiB, 32 KiB up to 32 GiB, 128 KiB above.
|
||||
fn cluster_shift(size: u64) -> u8 {
|
||||
if size <= 256 << 20 {
|
||||
3
|
||||
} else if size <= 32 << 30 {
|
||||
6
|
||||
} else {
|
||||
8
|
||||
}
|
||||
}
|
||||
|
||||
/// A file's directory entry set: the file entry, its stream extension, and its name in entries
|
||||
/// of 15 characters.
|
||||
fn file_set(name: &[u16], upcase: &[u16], first: u32, len: u64, stamp: u32) -> Vec<[u8; ENTRY]> {
|
||||
let name_entries = name.len().div_ceil(15);
|
||||
let mut set = Vec::with_capacity(2 + name_entries);
|
||||
let mut e = [0u8; ENTRY];
|
||||
e[0] = 0x85;
|
||||
e[1] = (1 + name_entries) as u8;
|
||||
e[4..6].copy_from_slice(&0x20u16.to_le_bytes()); // archive
|
||||
for at in [8, 12, 16] {
|
||||
e[at..at + 4].copy_from_slice(&stamp.to_le_bytes());
|
||||
}
|
||||
// The times are UTC: a valid offset of 0.
|
||||
e[22..25].fill(0x80);
|
||||
set.push(e);
|
||||
let mut e = [0u8; ENTRY];
|
||||
e[0] = 0xc0;
|
||||
e[1] = 0x01; // allocation possible; the FAT holds the chain
|
||||
e[3] = name.len() as u8;
|
||||
let hashed: Vec<u16> = name
|
||||
.iter()
|
||||
.map(|&c| upcase.get(c as usize).copied().unwrap_or(c))
|
||||
.collect();
|
||||
e[4..6].copy_from_slice(&name_hash(&hashed).to_le_bytes());
|
||||
e[8..16].copy_from_slice(&len.to_le_bytes());
|
||||
e[20..24].copy_from_slice(&first.to_le_bytes());
|
||||
e[24..32].copy_from_slice(&len.to_le_bytes());
|
||||
set.push(e);
|
||||
for part in name.chunks(15) {
|
||||
let mut e = [0u8; ENTRY];
|
||||
e[0] = 0xc1;
|
||||
for (i, c) in part.iter().enumerate() {
|
||||
e[2 + i * 2..4 + i * 2].copy_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
set.push(e);
|
||||
}
|
||||
let sum = set_checksum(&set.concat());
|
||||
set[0][2..4].copy_from_slice(&sum.to_le_bytes());
|
||||
set
|
||||
}
|
||||
|
||||
struct BootSector {
|
||||
partition_offset: u64,
|
||||
volume_sectors: u64,
|
||||
fat_len: u32,
|
||||
heap: u32,
|
||||
clusters: u32,
|
||||
root: u32,
|
||||
serial: u32,
|
||||
shift: u8,
|
||||
percent_in_use: u8,
|
||||
}
|
||||
|
||||
/// The 12 sectors of a boot region: the boot sector, the extended boot sectors, the OEM
|
||||
/// parameters and the reserved sector (both empty), and the checksum of the 11 before it.
|
||||
fn boot_region(b: &BootSector) -> Vec<u8> {
|
||||
let mut r = vec![0u8; 12 * SECTOR as usize];
|
||||
let s = &mut r[..SECTOR as usize];
|
||||
s[0..3].copy_from_slice(&[0xeb, 0x76, 0x90]);
|
||||
s[3..11].copy_from_slice(b"EXFAT ");
|
||||
s[64..72].copy_from_slice(&b.partition_offset.to_le_bytes());
|
||||
s[72..80].copy_from_slice(&b.volume_sectors.to_le_bytes());
|
||||
s[80..84].copy_from_slice(&(FAT_OFFSET as u32).to_le_bytes());
|
||||
s[84..88].copy_from_slice(&b.fat_len.to_le_bytes());
|
||||
s[88..92].copy_from_slice(&b.heap.to_le_bytes());
|
||||
s[92..96].copy_from_slice(&b.clusters.to_le_bytes());
|
||||
s[96..100].copy_from_slice(&b.root.to_le_bytes());
|
||||
s[100..104].copy_from_slice(&b.serial.to_le_bytes());
|
||||
s[104..106].copy_from_slice(&[0x00, 0x01]); // revision 1.00
|
||||
s[108] = 9; // 512-byte sectors
|
||||
s[109] = b.shift;
|
||||
s[110] = 1; // one FAT
|
||||
s[111] = 0x80;
|
||||
s[112] = b.percent_in_use;
|
||||
// No boot code: halt.
|
||||
s[120..510].fill(0xf4);
|
||||
s[510] = 0x55;
|
||||
s[511] = 0xaa;
|
||||
for i in 1..=8 {
|
||||
let end = (i + 1) * SECTOR as usize;
|
||||
r[end - 2] = 0x55;
|
||||
r[end - 1] = 0xaa;
|
||||
}
|
||||
let sum = boot_checksum(&r[..11 * SECTOR as usize]);
|
||||
for c in r[11 * SECTOR as usize..].chunks_mut(4) {
|
||||
c.copy_from_slice(&sum.to_le_bytes());
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The boot checksum, which leaves out the boot sector's volume flags and percent in use.
|
||||
fn boot_checksum(sectors: &[u8]) -> u32 {
|
||||
sectors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| !matches!(i, 106 | 107 | 112))
|
||||
.fold(0u32, |s, (_, b)| {
|
||||
s.rotate_right(1).wrapping_add(u32::from(*b))
|
||||
})
|
||||
}
|
||||
|
||||
/// An entry set's checksum, which leaves out the checksum's own two bytes.
|
||||
fn set_checksum(set: &[u8]) -> u16 {
|
||||
set.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| !matches!(i, 2 | 3))
|
||||
.fold(0u16, |s, (_, b)| {
|
||||
s.rotate_right(1).wrapping_add(u16::from(*b))
|
||||
})
|
||||
}
|
||||
|
||||
/// The hash of an up-cased name, over its UTF-16 code units' bytes.
|
||||
fn name_hash(upcased: &[u16]) -> u16 {
|
||||
upcased
|
||||
.iter()
|
||||
.flat_map(|c| c.to_le_bytes())
|
||||
.fold(0u16, |s, b| s.rotate_right(1).wrapping_add(u16::from(b)))
|
||||
}
|
||||
|
||||
/// The up-case table's checksum.
|
||||
fn checksum32(bytes: &[u8]) -> u32 {
|
||||
bytes
|
||||
.iter()
|
||||
.fold(0u32, |s, b| s.rotate_right(1).wrapping_add(u32::from(*b)))
|
||||
}
|
||||
|
||||
/// The up-case table, compressed as the specification allows: each code unit's upper case in
|
||||
/// turn, with a run of ones that map to themselves written as 0xFFFF and the run's length. The
|
||||
/// mapping is Unicode's simple upper case of each BMP character.
|
||||
fn upcase_table() -> Vec<u8> {
|
||||
let up = |c: u32| -> u32 {
|
||||
let Some(ch) = char::from_u32(c) else {
|
||||
return c;
|
||||
};
|
||||
let mut u = ch.to_uppercase();
|
||||
match (u.next(), u.next()) {
|
||||
(Some(x), None) if (x as u32) < 0x1_0000 => x as u32,
|
||||
_ => c,
|
||||
}
|
||||
};
|
||||
let mut table: Vec<u16> = Vec::new();
|
||||
let mut c = 0u32;
|
||||
while c < 0x1_0000 {
|
||||
if up(c) != c {
|
||||
table.push(up(c) as u16);
|
||||
c += 1;
|
||||
continue;
|
||||
}
|
||||
let start = c;
|
||||
while c < 0x1_0000 && up(c) == c {
|
||||
c += 1;
|
||||
}
|
||||
// A run that reaches 0xFFFF is always compressed, so 0xFFFF is never a mapping.
|
||||
if c - start > 2 || c == 0x1_0000 {
|
||||
table.push(0xffff);
|
||||
table.push((c - start) as u16);
|
||||
} else {
|
||||
table.extend((start..c).map(|k| k as u16));
|
||||
}
|
||||
}
|
||||
table.iter().flat_map(|u| u.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// A compressed up-case table as a code unit's upper case, by index.
|
||||
fn expand_upcase(table: &[u8]) -> Vec<u16> {
|
||||
let units: Vec<u16> = table
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|b| u16::from_le_bytes(*b))
|
||||
.collect();
|
||||
let mut map = Vec::with_capacity(0x1_0000);
|
||||
let mut i = 0;
|
||||
while i < units.len() {
|
||||
if units[i] == 0xffff && i + 1 < units.len() {
|
||||
let n = units[i + 1];
|
||||
for _ in 0..n {
|
||||
map.push(map.len() as u16);
|
||||
}
|
||||
i += 2;
|
||||
} else {
|
||||
map.push(units[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The files in the root folder of a volume `make` wrote, read back through its structures.
|
||||
fn list(vol: &[u8]) -> Vec<(String, Vec<u8>)> {
|
||||
let u32_at = |o: usize| u32::from_le_bytes(vol[o..o + 4].try_into().unwrap());
|
||||
let fat_at = u32_at(80) as usize * 512;
|
||||
let heap = u32_at(88) as usize * 512;
|
||||
let cluster = 512usize << vol[109];
|
||||
let chain = |first: u32, len: usize| -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut c = first;
|
||||
while (2..0xffff_fff7).contains(&c) {
|
||||
let at = heap + (c as usize - 2) * cluster;
|
||||
out.extend_from_slice(&vol[at..at + cluster]);
|
||||
c = u32_at(fat_at + c as usize * 4);
|
||||
}
|
||||
out.truncate(len);
|
||||
out
|
||||
};
|
||||
let root = chain(u32_at(96), usize::MAX);
|
||||
let mut files = Vec::new();
|
||||
let mut i = 0;
|
||||
while root[i * 32] != 0 {
|
||||
let e = &root[i * 32..i * 32 + 32];
|
||||
if e[0] != 0x85 {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let n = e[1] as usize;
|
||||
let set = &root[i * 32..(i + 1 + n) * 32];
|
||||
assert_eq!(
|
||||
set_checksum(set),
|
||||
u16::from_le_bytes([e[2], e[3]]),
|
||||
"the set checksum"
|
||||
);
|
||||
let s = &set[32..64];
|
||||
let name_len = s[3] as usize;
|
||||
let mut name: Vec<u16> = Vec::new();
|
||||
for k in 0..n - 1 {
|
||||
let f = &set[64 + k * 32..96 + k * 32];
|
||||
for j in 0..15 {
|
||||
name.push(u16::from_le_bytes([f[2 + j * 2], f[3 + j * 2]]));
|
||||
}
|
||||
}
|
||||
name.truncate(name_len);
|
||||
let len = u64::from_le_bytes(s[24..32].try_into().unwrap()) as usize;
|
||||
let first = u32::from_le_bytes(s[20..24].try_into().unwrap());
|
||||
files.push((String::from_utf16(&name).unwrap(), chain(first, len)));
|
||||
i += 1 + n;
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
fn volume(size: u64, files: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
let files: Vec<(String, Data)> = files
|
||||
.iter()
|
||||
.map(|(n, d)| (n.to_string(), Data::Bytes(d.clone())))
|
||||
.collect();
|
||||
let pieces = make(size, 2048, "Installer", 7, &files, (0x5b4c, 0)).unwrap();
|
||||
super::super::Disk { size, pieces }.to_bytes().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_files_that_read_back() {
|
||||
let big: Vec<u8> = (0..200_000u32).map(|i| (i % 253) as u8).collect();
|
||||
let vol = volume(
|
||||
64 << 20,
|
||||
&[
|
||||
("InstallAssistant.pkg", big.clone()),
|
||||
("install-macos.sh", b"#!/bin/sh\n".to_vec()),
|
||||
("empty", Vec::new()),
|
||||
],
|
||||
);
|
||||
let got = list(&vol);
|
||||
assert_eq!(got[0], ("InstallAssistant.pkg".to_string(), big));
|
||||
assert_eq!(got[1].1, b"#!/bin/sh\n");
|
||||
assert_eq!(got[2], ("empty".to_string(), Vec::new()));
|
||||
// The backup boot region is the main one.
|
||||
assert_eq!(vol[..12 * 512], vol[12 * 512..24 * 512]);
|
||||
assert_eq!(&vol[64..72], &2048u64.to_le_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_checksum_covers_the_region() {
|
||||
let vol = volume(64 << 20, &[("a", vec![1])]);
|
||||
let sum = boot_checksum(&vol[..11 * 512]);
|
||||
for c in vol[11 * 512..12 * 512].chunks(4) {
|
||||
assert_eq!(c, sum.to_le_bytes());
|
||||
}
|
||||
// Volume flags and percent in use are left out.
|
||||
let mut v = vol[..11 * 512].to_vec();
|
||||
v[106] ^= 1;
|
||||
v[112] ^= 0x7f;
|
||||
assert_eq!(boot_checksum(&v), sum);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upcase_table_maps_letters() {
|
||||
let map = expand_upcase(&upcase_table());
|
||||
assert_eq!(map.len(), 0x1_0000);
|
||||
assert_eq!(map['a' as usize], 'A' as u16);
|
||||
assert_eq!(map['z' as usize], 'Z' as u16);
|
||||
assert_eq!(map['A' as usize], 'A' as u16);
|
||||
assert_eq!(map['é' as usize], 'É' as u16);
|
||||
assert_eq!(map['1' as usize], '1' as u16);
|
||||
assert_eq!(map[0xffff], 0xffff);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hashes_names_as_the_specification_does() {
|
||||
// NameHash = ((NameHash & 1) ? 0x8000 : 0) + (NameHash >> 1) + byte, over each byte.
|
||||
let mut h = 0u16;
|
||||
for b in "ABC".encode_utf16().flat_map(|c| c.to_le_bytes()) {
|
||||
h = (if h & 1 != 0 { 0x8000 } else { 0 }) + (h >> 1) + u16::from(b);
|
||||
}
|
||||
assert_eq!(name_hash(&"ABC".encode_utf16().collect::<Vec<_>>()), h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_cluster_sizes() {
|
||||
assert_eq!(cluster_shift(64 << 20), 3);
|
||||
assert_eq!(cluster_shift(18 << 30), 6);
|
||||
assert_eq!(cluster_shift(40 << 30), 8);
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -18,7 +18,7 @@ pub const ESP_TYPE: [u8; 16] = guid(
|
||||
);
|
||||
|
||||
/// Microsoft's basic data partition type, EBD0A0A2-B9E5-4433-87C0-68B6B72699C7, which FAT32
|
||||
/// and exFAT volumes that are not EFI system partitions take.
|
||||
/// volumes that are not EFI system partitions take.
|
||||
pub const BASIC_DATA_TYPE: [u8; 16] = guid(
|
||||
0xEBD0A0A2,
|
||||
0xB9E5,
|
||||
@@ -26,6 +26,14 @@ pub const BASIC_DATA_TYPE: [u8; 16] = guid(
|
||||
[0x87, 0xC0, 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7],
|
||||
);
|
||||
|
||||
/// Apple's HFS Plus partition type, 48465300-0000-11AA-AA11-00306543ECAC.
|
||||
pub const HFS_PLUS_TYPE: [u8; 16] = guid(
|
||||
0x48465300,
|
||||
0x0000,
|
||||
0x11AA,
|
||||
[0xAA, 0x11, 0x00, 0x30, 0x65, 0x43, 0xEC, 0xAC],
|
||||
);
|
||||
|
||||
/// A GUID in its on-disk form: the first three fields little-endian.
|
||||
pub const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] {
|
||||
let a = a.to_le_bytes();
|
||||
|
||||
@@ -0,0 +1,674 @@
|
||||
//! An HFS Plus volume holding files in its root folder, as Apple's Technical Note TN1150 lays it
|
||||
//! out, with no journal:
|
||||
//! - block 0: the boot blocks (zero) and, 1024 bytes in, the volume header;
|
||||
//! - the allocation file, one bit a block;
|
||||
//! - the extents overflow and attributes files, B-trees of a header node only;
|
||||
//! - the catalog file, a B-tree of a header node and one leaf: the root folder and its thread,
|
||||
//! then each file and its thread;
|
||||
//! - each file in consecutive blocks, one extent each;
|
||||
//! - the alternate volume header, 1024 bytes before the volume's end.
|
||||
//!
|
||||
//! HFS Plus holds files of 4 GiB or more, such as a macOS installer package (12 to 18 GB), and
|
||||
//! macOS Recovery mounts it by itself on every release from 11 to 26, where the Recovery that
|
||||
//! macOS 14's and 15's installer images boot mounts neither exFAT nor FAT32.
|
||||
|
||||
use super::Data;
|
||||
use anyhow::{Result, ensure};
|
||||
|
||||
const BLOCK: u64 = 4096;
|
||||
const VOLUME_HEADER: u64 = 1024;
|
||||
/// The catalog's and the extents file's node size; the attributes file's is twice it, as
|
||||
/// newfs_hfs makes them.
|
||||
const NODE: usize = 4096;
|
||||
/// Each B-tree's nodes: room for what macOS adds when it mounts the volume writable (its
|
||||
/// private folders, .fseventsd), as newfs_hfs gives a small volume.
|
||||
const CATALOG_NODES: u32 = 128;
|
||||
const EXTENTS_NODES: u32 = 128;
|
||||
const ATTRIBUTES_NODES: u32 = 64;
|
||||
|
||||
const ROOT_PARENT: u32 = 1;
|
||||
const ROOT_FOLDER: u32 = 2;
|
||||
const FIRST_USER_ID: u32 = 16;
|
||||
|
||||
const UNMOUNTED: u32 = 1 << 8;
|
||||
/// The B-trees' unused nodes are zero.
|
||||
const UNUSED_NODES_ZEROED: u32 = 1 << 31;
|
||||
const BIG_KEYS: u32 = 2;
|
||||
const VARIABLE_INDEX_KEYS: u32 = 4;
|
||||
const CASE_FOLDING: u8 = 0xcf;
|
||||
|
||||
const FOLDER_RECORD: u16 = 1;
|
||||
const FILE_RECORD: u16 = 2;
|
||||
const FOLDER_THREAD: u16 = 3;
|
||||
const FILE_THREAD: u16 = 4;
|
||||
const THREAD_EXISTS: u16 = 2;
|
||||
/// Seconds from HFS Plus's epoch, 1904-01-01 UTC, to the Unix epoch.
|
||||
const EPOCH_1904: u64 = 2_082_844_800;
|
||||
/// The owner and group of files on removable media: unknown.
|
||||
const UNKNOWN_ID: u32 = 99;
|
||||
|
||||
/// A volume of `size` bytes (a whole partition) holding `files` in its root folder, as byte
|
||||
/// ranges from the volume's start. `label` is the volume's name; `id` the 64-bit identifier
|
||||
/// macOS takes its volume UUID from; `now` the time every date is set to.
|
||||
pub fn make(
|
||||
size: u64,
|
||||
label: &str,
|
||||
id: [u8; 8],
|
||||
files: &[(String, Data)],
|
||||
now: std::time::SystemTime,
|
||||
) -> Result<Vec<(u64, Data)>> {
|
||||
ensure!(
|
||||
size.is_multiple_of(BLOCK) && size >= 4 << 20,
|
||||
"an HFS Plus volume is 4 MiB at least, in whole blocks"
|
||||
);
|
||||
let total =
|
||||
u32::try_from(size / BLOCK).map_err(|_| anyhow::anyhow!("the volume is too big"))?;
|
||||
let label = name(label, "volume")?;
|
||||
let mut names = Vec::with_capacity(files.len());
|
||||
for (n, _) in files {
|
||||
names.push(name(n, "file")?);
|
||||
}
|
||||
for (i, a) in names.iter().enumerate() {
|
||||
ensure!(
|
||||
names[..i].iter().all(|b| fold(b) != fold(a)),
|
||||
"two files are named {:?} but for case",
|
||||
files[i].0
|
||||
);
|
||||
}
|
||||
let date = u32::try_from(
|
||||
now.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
+ EPOCH_1904,
|
||||
)
|
||||
.unwrap_or(u32::MAX);
|
||||
|
||||
// Blocks in order from 1: the allocation file, the three B-trees, then the files.
|
||||
let mut next = 1u32;
|
||||
let mut alloc = |bytes: u64| -> Result<(u32, u32)> {
|
||||
let n = u32::try_from(bytes.div_ceil(BLOCK))?;
|
||||
let first = next;
|
||||
// The last block holds the alternate volume header.
|
||||
ensure!(
|
||||
u64::from(first) + u64::from(n) < u64::from(total),
|
||||
"the files do not fit the volume"
|
||||
);
|
||||
next += n;
|
||||
Ok((first, n))
|
||||
};
|
||||
let bitmap_bytes = u64::from(total).div_ceil(8).next_multiple_of(BLOCK);
|
||||
let allocation = alloc(bitmap_bytes)?;
|
||||
let extents_bytes = u64::from(EXTENTS_NODES) * NODE as u64;
|
||||
let extents = alloc(extents_bytes)?;
|
||||
let attributes_bytes = u64::from(ATTRIBUTES_NODES) * 2 * NODE as u64;
|
||||
let attributes = alloc(attributes_bytes)?;
|
||||
let catalog_bytes = u64::from(CATALOG_NODES) * NODE as u64;
|
||||
let catalog = alloc(catalog_bytes)?;
|
||||
|
||||
// The files, each in its blocks, given IDs in their order here.
|
||||
let mut pieces = Vec::new();
|
||||
let mut entries = Vec::new();
|
||||
for (i, ((_, data), n)) in files.iter().zip(&names).enumerate() {
|
||||
let len = data.size();
|
||||
let (first, count) = if len == 0 { (0, 0) } else { alloc(len)? };
|
||||
if len != 0 {
|
||||
let d = match data {
|
||||
Data::Bytes(b) => whole(b.clone(), BLOCK),
|
||||
reserved => reserved.clone(),
|
||||
};
|
||||
pieces.push((u64::from(first) * BLOCK, d));
|
||||
}
|
||||
let fork = Fork {
|
||||
len,
|
||||
blocks: count,
|
||||
first,
|
||||
};
|
||||
entries.push((FIRST_USER_ID + i as u32, n, fork));
|
||||
}
|
||||
let used = next + 1;
|
||||
|
||||
// The catalog's leaf, its records in key order: by parent ID, then by name, case folded.
|
||||
let mut records = vec![
|
||||
(key(ROOT_PARENT, &label), folder(files.len() as u32, date)),
|
||||
(
|
||||
key(ROOT_FOLDER, &[]),
|
||||
thread(FOLDER_THREAD, ROOT_PARENT, &label),
|
||||
),
|
||||
];
|
||||
let mut by_name: Vec<_> = entries.iter().collect();
|
||||
by_name.sort_by_key(|(_, n, _)| fold(n));
|
||||
for (id, n, fork) in &by_name {
|
||||
records.push((key(ROOT_FOLDER, n), file(*id, date, fork)));
|
||||
}
|
||||
for (id, n, _) in &entries {
|
||||
records.push((key(*id, &[]), thread(FILE_THREAD, ROOT_FOLDER, n)));
|
||||
}
|
||||
let leaf_records = records.len() as u32;
|
||||
let leaf = leaf_node(
|
||||
&records
|
||||
.into_iter()
|
||||
.map(|(k, r)| [k, r].concat())
|
||||
.collect::<Vec<_>>(),
|
||||
)?;
|
||||
|
||||
let mut catalog_file = header_node(&Tree {
|
||||
node_size: NODE,
|
||||
nodes: CATALOG_NODES,
|
||||
max_key: 516,
|
||||
attributes: BIG_KEYS | VARIABLE_INDEX_KEYS,
|
||||
compare: CASE_FOLDING,
|
||||
leaf_records,
|
||||
});
|
||||
catalog_file.extend(leaf);
|
||||
catalog_file.resize(catalog_bytes as usize, 0);
|
||||
let mut extents_file = header_node(&Tree {
|
||||
node_size: NODE,
|
||||
nodes: EXTENTS_NODES,
|
||||
max_key: 10,
|
||||
attributes: BIG_KEYS,
|
||||
compare: 0,
|
||||
leaf_records: 0,
|
||||
});
|
||||
extents_file.resize(extents_bytes as usize, 0);
|
||||
let mut attributes_file = header_node(&Tree {
|
||||
node_size: 2 * NODE,
|
||||
nodes: ATTRIBUTES_NODES,
|
||||
max_key: 266,
|
||||
attributes: BIG_KEYS | VARIABLE_INDEX_KEYS,
|
||||
compare: 0,
|
||||
leaf_records: 0,
|
||||
});
|
||||
attributes_file.resize(attributes_bytes as usize, 0);
|
||||
|
||||
let mut bitmap = vec![0u8; bitmap_bytes as usize];
|
||||
for b in (0..next).chain([total - 1]) {
|
||||
bitmap[b as usize / 8] |= 0x80 >> (b % 8);
|
||||
}
|
||||
|
||||
let header = volume_header(&Header {
|
||||
date,
|
||||
files: files.len() as u32,
|
||||
total,
|
||||
free: total - used,
|
||||
next_allocation: next,
|
||||
next_id: FIRST_USER_ID + files.len() as u32,
|
||||
id,
|
||||
allocation: fork_of(allocation, bitmap_bytes),
|
||||
extents: fork_of(extents, extents_bytes),
|
||||
catalog: fork_of(catalog, catalog_bytes),
|
||||
attributes: fork_of(attributes, attributes_bytes),
|
||||
});
|
||||
let at = |(first, _): (u32, u32)| u64::from(first) * BLOCK;
|
||||
// Block 0 whole, boot blocks zero, so no earlier image's bytes stay in it.
|
||||
let mut block0 = vec![0u8; BLOCK as usize];
|
||||
block0[VOLUME_HEADER as usize..VOLUME_HEADER as usize + header.len()].copy_from_slice(&header);
|
||||
let mut last = vec![0u8; BLOCK as usize];
|
||||
last[(BLOCK - VOLUME_HEADER) as usize..(BLOCK - VOLUME_HEADER) as usize + header.len()]
|
||||
.copy_from_slice(&header);
|
||||
let mut out = vec![
|
||||
(0, Data::Bytes(block0)),
|
||||
(at(allocation), Data::Bytes(bitmap)),
|
||||
(at(extents), Data::Bytes(extents_file)),
|
||||
(at(attributes), Data::Bytes(attributes_file)),
|
||||
(at(catalog), Data::Bytes(catalog_file)),
|
||||
(size - BLOCK, Data::Bytes(last)),
|
||||
];
|
||||
out.extend(pieces);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A name as HFS Plus stores it, UTF-16: printable ASCII but `:` and `/`, which are the same
|
||||
/// in decomposed form, as names must be. That is every name an installer image holds.
|
||||
fn name(s: &str, what: &str) -> Result<Vec<u16>> {
|
||||
ensure!(
|
||||
!s.is_empty()
|
||||
&& s.len() <= 255
|
||||
&& s.chars()
|
||||
.all(|c| (' '..='~').contains(&c) && c != ':' && c != '/'),
|
||||
"bad HFS Plus {what} name {s:?}"
|
||||
);
|
||||
Ok(s.encode_utf16().collect())
|
||||
}
|
||||
|
||||
/// A name as HFS Plus orders names: case folded (for ASCII, A to Z as a to z).
|
||||
fn fold(name: &[u16]) -> Vec<u16> {
|
||||
name.iter()
|
||||
.map(|&c| {
|
||||
if (0x41..=0x5a).contains(&c) {
|
||||
c + 0x20
|
||||
} else {
|
||||
c
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn whole(mut b: Vec<u8>, unit: u64) -> Data {
|
||||
b.resize(b.len().next_multiple_of(unit as usize), 0);
|
||||
Data::Bytes(b)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Fork {
|
||||
len: u64,
|
||||
blocks: u32,
|
||||
first: u32,
|
||||
}
|
||||
|
||||
fn fork_of((first, blocks): (u32, u32), len: u64) -> Fork {
|
||||
Fork { len, blocks, first }
|
||||
}
|
||||
|
||||
/// HFSPlusForkData: the size, clump size, blocks, and eight extents, the first holding all.
|
||||
fn fork_data(f: &Fork, clump: u32) -> [u8; 80] {
|
||||
let mut d = [0u8; 80];
|
||||
d[0..8].copy_from_slice(&f.len.to_be_bytes());
|
||||
d[8..12].copy_from_slice(&clump.to_be_bytes());
|
||||
d[12..16].copy_from_slice(&f.blocks.to_be_bytes());
|
||||
if f.blocks != 0 {
|
||||
d[16..20].copy_from_slice(&f.first.to_be_bytes());
|
||||
d[20..24].copy_from_slice(&f.blocks.to_be_bytes());
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
struct Header {
|
||||
date: u32,
|
||||
files: u32,
|
||||
total: u32,
|
||||
free: u32,
|
||||
next_allocation: u32,
|
||||
next_id: u32,
|
||||
id: [u8; 8],
|
||||
allocation: Fork,
|
||||
extents: Fork,
|
||||
catalog: Fork,
|
||||
attributes: Fork,
|
||||
}
|
||||
|
||||
/// HFSPlusVolumeHeader, 512 bytes.
|
||||
fn volume_header(h: &Header) -> Vec<u8> {
|
||||
let mut v = vec![0u8; 512];
|
||||
let mut put = |at: usize, b: &[u8]| v[at..at + b.len()].copy_from_slice(b);
|
||||
put(0, b"H+");
|
||||
put(2, &4u16.to_be_bytes());
|
||||
put(4, &(UNMOUNTED | UNUSED_NODES_ZEROED).to_be_bytes());
|
||||
put(8, b"10.0");
|
||||
// createDate (local time; here UTC), modifyDate, backupDate (never), checkedDate.
|
||||
put(16, &h.date.to_be_bytes());
|
||||
put(20, &h.date.to_be_bytes());
|
||||
put(28, &h.date.to_be_bytes());
|
||||
put(32, &h.files.to_be_bytes());
|
||||
// folderCount, the root not counted: 0.
|
||||
put(40, &(BLOCK as u32).to_be_bytes());
|
||||
put(44, &h.total.to_be_bytes());
|
||||
put(48, &h.free.to_be_bytes());
|
||||
put(52, &h.next_allocation.to_be_bytes());
|
||||
put(56, &65536u32.to_be_bytes());
|
||||
put(60, &65536u32.to_be_bytes());
|
||||
put(64, &h.next_id.to_be_bytes());
|
||||
put(68, &1u32.to_be_bytes());
|
||||
// encodingsBitmap: MacRoman.
|
||||
put(72, &1u64.to_be_bytes());
|
||||
// finderInfo[6..8]: the volume's identifier.
|
||||
put(104, &h.id);
|
||||
put(112, &fork_data(&h.allocation, BLOCK as u32));
|
||||
put(192, &fork_data(&h.extents, h.extents.len as u32));
|
||||
put(272, &fork_data(&h.catalog, h.catalog.len as u32));
|
||||
put(352, &fork_data(&h.attributes, h.attributes.len as u32));
|
||||
v
|
||||
}
|
||||
|
||||
struct Tree {
|
||||
node_size: usize,
|
||||
nodes: u32,
|
||||
max_key: u16,
|
||||
attributes: u32,
|
||||
compare: u8,
|
||||
/// Records in its one leaf, node 1; none for a tree of its header node only.
|
||||
leaf_records: u32,
|
||||
}
|
||||
|
||||
/// A B-tree's header node: its node descriptor, header record, user data record, and map
|
||||
/// record, which marks the nodes in use.
|
||||
fn header_node(t: &Tree) -> Vec<u8> {
|
||||
let size = t.node_size;
|
||||
let mut n = vec![0u8; size];
|
||||
n[8] = 1; // kBTHeaderNode
|
||||
n[10..12].copy_from_slice(&3u16.to_be_bytes());
|
||||
let has_leaf = t.leaf_records != 0;
|
||||
let used = if has_leaf { 2 } else { 1 };
|
||||
let mut put = |at: usize, b: &[u8]| n[at..at + b.len()].copy_from_slice(b);
|
||||
if has_leaf {
|
||||
put(14, &1u16.to_be_bytes()); // treeDepth
|
||||
put(16, &1u32.to_be_bytes()); // rootNode
|
||||
put(20, &t.leaf_records.to_be_bytes());
|
||||
put(24, &1u32.to_be_bytes()); // firstLeafNode
|
||||
put(28, &1u32.to_be_bytes()); // lastLeafNode
|
||||
}
|
||||
put(32, &(size as u16).to_be_bytes());
|
||||
put(34, &t.max_key.to_be_bytes());
|
||||
put(36, &t.nodes.to_be_bytes());
|
||||
put(40, &(t.nodes - used).to_be_bytes());
|
||||
put(46, &(t.nodes * size as u32).to_be_bytes());
|
||||
// btreeType 0 (an HFS B-tree), then keyCompareType.
|
||||
n[51] = t.compare;
|
||||
n[52..56].copy_from_slice(&t.attributes.to_be_bytes());
|
||||
// The map record, from 248: node 0, and the leaf.
|
||||
n[248] = if has_leaf { 0xc0 } else { 0x80 };
|
||||
for (i, off) in [14u16, 120, 248, size as u16 - 8].into_iter().enumerate() {
|
||||
n[size - 2 - 2 * i..size - 2 * i].copy_from_slice(&off.to_be_bytes());
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// A leaf node of `records`, each a key and its data, with the offsets of each and of the free
|
||||
/// space after them at the node's end.
|
||||
fn leaf_node(records: &[Vec<u8>]) -> Result<Vec<u8>> {
|
||||
let mut n = vec![0u8; NODE];
|
||||
n[8] = 0xff; // kBTLeafNode, -1
|
||||
n[9] = 1; // height
|
||||
n[10..12].copy_from_slice(&(records.len() as u16).to_be_bytes());
|
||||
let mut offsets = Vec::with_capacity(records.len() + 1);
|
||||
let mut at = 14;
|
||||
for r in records {
|
||||
ensure!(
|
||||
at + r.len() + 2 * (records.len() + 1) <= NODE,
|
||||
"the catalog's records do not fit one node"
|
||||
);
|
||||
offsets.push(at as u16);
|
||||
n[at..at + r.len()].copy_from_slice(r);
|
||||
at += r.len();
|
||||
}
|
||||
offsets.push(at as u16);
|
||||
for (i, off) in offsets.into_iter().enumerate() {
|
||||
n[NODE - 2 - 2 * i..NODE - 2 * i].copy_from_slice(&off.to_be_bytes());
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// HFSPlusCatalogKey: its length, the parent's ID, and the name.
|
||||
fn key(parent: u32, name: &[u16]) -> Vec<u8> {
|
||||
let mut k = Vec::with_capacity(8 + 2 * name.len());
|
||||
k.extend((6 + 2 * name.len() as u16).to_be_bytes());
|
||||
k.extend(parent.to_be_bytes());
|
||||
k.extend((name.len() as u16).to_be_bytes());
|
||||
k.extend(name.iter().flat_map(|c| c.to_be_bytes()));
|
||||
k
|
||||
}
|
||||
|
||||
/// HFSPlusBSDInfo: owner, group, flags, mode, and the link count.
|
||||
fn bsd(mode: u16) -> [u8; 16] {
|
||||
let mut b = [0u8; 16];
|
||||
b[0..4].copy_from_slice(&UNKNOWN_ID.to_be_bytes());
|
||||
b[4..8].copy_from_slice(&UNKNOWN_ID.to_be_bytes());
|
||||
b[10..12].copy_from_slice(&mode.to_be_bytes());
|
||||
b[12..16].copy_from_slice(&1u32.to_be_bytes());
|
||||
b
|
||||
}
|
||||
|
||||
/// The four dates a catalog record gives first (created, content and attributes modified,
|
||||
/// accessed); the backup date after them stays 0.
|
||||
fn dates(date: u32) -> [u8; 20] {
|
||||
let mut d = [0u8; 20];
|
||||
for i in 0..4 {
|
||||
d[i * 4..i * 4 + 4].copy_from_slice(&date.to_be_bytes());
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// HFSPlusCatalogFolder for the root folder, 88 bytes.
|
||||
fn folder(valence: u32, date: u32) -> Vec<u8> {
|
||||
let mut r = vec![0u8; 88];
|
||||
r[0..2].copy_from_slice(&FOLDER_RECORD.to_be_bytes());
|
||||
r[4..8].copy_from_slice(&valence.to_be_bytes());
|
||||
r[8..12].copy_from_slice(&ROOT_FOLDER.to_be_bytes());
|
||||
r[12..32].copy_from_slice(&dates(date));
|
||||
r[32..48].copy_from_slice(&bsd(0o40755));
|
||||
r
|
||||
}
|
||||
|
||||
/// HFSPlusCatalogFile, 248 bytes: its data fork in one extent, no resource fork.
|
||||
fn file(id: u32, date: u32, fork: &Fork) -> Vec<u8> {
|
||||
let mut r = vec![0u8; 248];
|
||||
r[0..2].copy_from_slice(&FILE_RECORD.to_be_bytes());
|
||||
r[2..4].copy_from_slice(&THREAD_EXISTS.to_be_bytes());
|
||||
r[8..12].copy_from_slice(&id.to_be_bytes());
|
||||
r[12..32].copy_from_slice(&dates(date));
|
||||
r[32..48].copy_from_slice(&bsd(0o100644));
|
||||
r[88..168].copy_from_slice(&fork_data(fork, 0));
|
||||
r
|
||||
}
|
||||
|
||||
/// HFSPlusCatalogThread: the record type, the parent's ID, and the name.
|
||||
fn thread(kind: u16, parent: u32, name: &[u16]) -> Vec<u8> {
|
||||
let mut r = Vec::with_capacity(10 + 2 * name.len());
|
||||
r.extend(kind.to_be_bytes());
|
||||
r.extend([0, 0]);
|
||||
r.extend(parent.to_be_bytes());
|
||||
r.extend((name.len() as u16).to_be_bytes());
|
||||
r.extend(name.iter().flat_map(|c| c.to_be_bytes()));
|
||||
r
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn be16(b: &[u8], at: usize) -> u16 {
|
||||
u16::from_be_bytes(b[at..at + 2].try_into().unwrap())
|
||||
}
|
||||
fn be32(b: &[u8], at: usize) -> u32 {
|
||||
u32::from_be_bytes(b[at..at + 4].try_into().unwrap())
|
||||
}
|
||||
fn be64(b: &[u8], at: usize) -> u64 {
|
||||
u64::from_be_bytes(b[at..at + 8].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn volume(size: u64, files: &[(&str, Data)]) -> Vec<u8> {
|
||||
let files: Vec<_> = files
|
||||
.iter()
|
||||
.map(|(n, d)| (n.to_string(), d.clone()))
|
||||
.collect();
|
||||
let pieces = make(
|
||||
size,
|
||||
"Installer",
|
||||
[1, 2, 3, 4, 5, 6, 7, 8],
|
||||
&files,
|
||||
std::time::UNIX_EPOCH,
|
||||
)
|
||||
.unwrap();
|
||||
let mut v = vec![0u8; size as usize];
|
||||
for (at, d) in pieces {
|
||||
assert!(
|
||||
at.is_multiple_of(BLOCK),
|
||||
"a piece at {at} is not on a block"
|
||||
);
|
||||
if let Data::Bytes(b) = d {
|
||||
assert!(
|
||||
(b.len() as u64).is_multiple_of(BLOCK),
|
||||
"a piece at {at} is not whole blocks"
|
||||
);
|
||||
v[at as usize..at as usize + b.len()].copy_from_slice(&b);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The files of a volume `make` wrote, read as macOS would: from the catalog's leaf
|
||||
/// through each file record's extent; and checks of the structures on the way.
|
||||
fn list(v: &[u8]) -> Vec<(String, Vec<u8>)> {
|
||||
let h = &v[1024..1536];
|
||||
assert_eq!(&h[0..2], b"H+");
|
||||
assert_eq!(
|
||||
h,
|
||||
&v[v.len() - 1024..v.len() - 512],
|
||||
"the alternate header differs"
|
||||
);
|
||||
let total = be32(h, 44);
|
||||
assert_eq!(u64::from(total) * BLOCK, v.len() as u64);
|
||||
// The bitmap marks exactly the blocks in use: the header says how many are free.
|
||||
let alloc = be32(h, 112 + 16) as usize * BLOCK as usize;
|
||||
let bitmap = &v[alloc..alloc + total.div_ceil(8) as usize];
|
||||
let used: u32 = (0..total)
|
||||
.filter(|b| bitmap[*b as usize / 8] & (0x80 >> (b % 8)) != 0)
|
||||
.count() as u32;
|
||||
assert_eq!(total - be32(h, 48), used);
|
||||
assert!(
|
||||
bitmap[0] & 0x80 != 0
|
||||
&& bitmap[(total as usize - 1) / 8] & (0x80 >> ((total - 1) % 8)) != 0
|
||||
);
|
||||
let cat = be32(h, 272 + 16) as usize * BLOCK as usize;
|
||||
let header = &v[cat..cat + NODE];
|
||||
assert_eq!(header[8], 1);
|
||||
assert_eq!(be16(header, 32) as usize, NODE);
|
||||
assert_eq!(be32(header, 16), 1);
|
||||
let leaf = &v[cat + NODE..cat + 2 * NODE];
|
||||
assert_eq!(leaf[8], 0xff);
|
||||
let n = be16(leaf, 10) as usize;
|
||||
assert_eq!(be32(header, 20) as usize, n);
|
||||
let offset = |i: usize| be16(leaf, NODE - 2 - 2 * i) as usize;
|
||||
let mut keys = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for i in 0..n {
|
||||
let at = offset(i);
|
||||
let klen = be16(leaf, at) as usize;
|
||||
let parent = be32(leaf, at + 2);
|
||||
let len = be16(leaf, at + 6) as usize;
|
||||
let name: Vec<u16> = (0..len).map(|j| be16(leaf, at + 8 + 2 * j)).collect();
|
||||
assert_eq!(klen, 6 + 2 * len);
|
||||
keys.push((parent, fold(&name)));
|
||||
let r = at + 2 + klen;
|
||||
if be16(leaf, r) == FILE_RECORD {
|
||||
let size = be64(leaf, r + 88) as usize;
|
||||
let start = be32(leaf, r + 88 + 16) as usize * BLOCK as usize;
|
||||
assert_eq!(
|
||||
u64::from(be32(leaf, r + 88 + 20)),
|
||||
(size as u64).div_ceil(BLOCK)
|
||||
);
|
||||
out.push((
|
||||
String::from_utf16(&name).unwrap(),
|
||||
v[start..start + size].to_vec(),
|
||||
));
|
||||
}
|
||||
}
|
||||
assert_eq!(offset(n), {
|
||||
let last = offset(n - 1);
|
||||
let r = last + 2 + be16(leaf, last) as usize;
|
||||
r + 10 + 2 * be16(leaf, r + 8) as usize
|
||||
});
|
||||
let mut sorted = keys.clone();
|
||||
sorted.sort();
|
||||
assert_eq!(keys, sorted, "the catalog's keys are out of order");
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_files_that_read_back() {
|
||||
let script = b"#!/bin/sh\necho hi\n".to_vec();
|
||||
let pkg: Vec<u8> = (0..70_000u32).map(|i| i as u8).collect();
|
||||
let v = volume(
|
||||
8 << 20,
|
||||
&[
|
||||
("InstallAssistant.pkg", Data::Bytes(pkg.clone())),
|
||||
("install-macos.sh", Data::Bytes(script.clone())),
|
||||
],
|
||||
);
|
||||
let files = list(&v);
|
||||
// In catalog order: "install-macos.sh" sorts before "InstallAssistant.pkg", case
|
||||
// folded ('-' before 'a').
|
||||
assert_eq!(
|
||||
files,
|
||||
vec![
|
||||
("install-macos.sh".to_string(), script),
|
||||
("InstallAssistant.pkg".to_string(), pkg)
|
||||
]
|
||||
);
|
||||
assert_eq!(be32(&v[1024..], 32), 2);
|
||||
assert_eq!(be32(&v[1024..], 64), FIRST_USER_ID + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn places_a_big_reserved_file_in_one_extent() {
|
||||
let len = 17u64 << 30;
|
||||
let files = vec![(
|
||||
"InstallAssistant.pkg".to_string(),
|
||||
Data::Reserved {
|
||||
name: "InstallAssistant.pkg",
|
||||
len,
|
||||
},
|
||||
)];
|
||||
let size = (len + (64 << 20)).next_multiple_of(1 << 20);
|
||||
let pieces = make(size, "Installer", [0; 8], &files, std::time::UNIX_EPOCH).unwrap();
|
||||
let (at, _) = pieces
|
||||
.iter()
|
||||
.find(|(_, d)| matches!(d, Data::Reserved { .. }))
|
||||
.unwrap();
|
||||
assert!(at.is_multiple_of(BLOCK) && at + len <= size - BLOCK);
|
||||
// The catalog: the B-tree whose keys are up to 516 bytes.
|
||||
let catalog = pieces
|
||||
.iter()
|
||||
.find_map(|(a, d)| match d {
|
||||
Data::Bytes(b) if *a > 0 && b.len() >= NODE && b[8] == 1 && be16(b, 34) == 516 => {
|
||||
Some(b)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let leaf = &catalog[NODE..2 * NODE];
|
||||
let r = be16(leaf, NODE - 2 - 2 * 2) as usize;
|
||||
let r = r + 2 + be16(leaf, r) as usize;
|
||||
assert_eq!(be16(leaf, r), FILE_RECORD);
|
||||
assert_eq!(be64(leaf, r + 88), len);
|
||||
assert_eq!(u64::from(be32(leaf, r + 88 + 16)) * BLOCK, *at);
|
||||
assert_eq!(u64::from(be32(leaf, r + 88 + 20)), len / BLOCK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_names_hfs_plus_would_store_otherwise() {
|
||||
let f = |n: &str| vec![(n.to_string(), Data::Bytes(vec![1]))];
|
||||
let now = std::time::UNIX_EPOCH;
|
||||
assert!(make(8 << 20, "Installer", [0; 8], &f("a:b"), now).is_err());
|
||||
assert!(make(8 << 20, "Installer", [0; 8], &f("é"), now).is_err());
|
||||
let twins = vec![
|
||||
("A.pkg".to_string(), Data::Bytes(vec![1])),
|
||||
("a.pkg".to_string(), Data::Bytes(vec![1])),
|
||||
];
|
||||
assert!(make(8 << 20, "Installer", [0; 8], &twins, now).is_err());
|
||||
assert!(
|
||||
make(
|
||||
8 << 20,
|
||||
"Installer",
|
||||
[0; 8],
|
||||
&f("x".repeat(9000).as_str()),
|
||||
now
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_files_that_do_not_fit() {
|
||||
let files = vec![("big".to_string(), Data::Bytes(vec![0; 8 << 20]))];
|
||||
assert!(make(8 << 20, "Installer", [0; 8], &files, std::time::UNIX_EPOCH).is_err());
|
||||
}
|
||||
|
||||
/// Writes a sample volume where REIMS_UTIL_HFS_SAMPLE names, for macOS's fsck_hfs.
|
||||
#[test]
|
||||
fn sample_for_fsck() {
|
||||
let Some(path) = std::env::var_os("REIMS_UTIL_HFS_SAMPLE") else {
|
||||
return;
|
||||
};
|
||||
let v = volume(
|
||||
64 << 20,
|
||||
&[
|
||||
("InstallAssistant.pkg", Data::Bytes(vec![0x5a; 3 << 20])),
|
||||
(
|
||||
"install-macos.sh",
|
||||
Data::Bytes(b"#!/bin/sh\necho installed\n".to_vec()),
|
||||
),
|
||||
],
|
||||
);
|
||||
std::fs::write(path, v).unwrap();
|
||||
}
|
||||
}
|
||||
+30
-16
@@ -1,14 +1,14 @@
|
||||
//! Disk images: GPT disks of FAT32 and exFAT volumes holding given files, written as a raw image
|
||||
//! or as qcow2.
|
||||
//! Disk images: GPT disks of FAT32 and HFS Plus volumes holding given files, written as a raw
|
||||
//! image or as qcow2.
|
||||
//!
|
||||
//! A disk is made as the byte ranges it holds ([`Disk`]): the volumes' structures and small files
|
||||
//! in memory, and room for big files that are downloaded into the image where they belong
|
||||
//! ([`Data::Reserved`], [`open_raw`]), so an installer image of up to 20 GB is never in memory,
|
||||
//! or on disk twice.
|
||||
|
||||
pub mod exfat;
|
||||
pub mod fat32;
|
||||
pub mod gpt;
|
||||
pub mod hfsplus;
|
||||
pub mod qcow2;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
@@ -139,7 +139,7 @@ pub fn esp_disk(size: u64, label: &str, files: &[(String, Data)]) -> Result<Disk
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Fs {
|
||||
Fat32,
|
||||
Exfat,
|
||||
HfsPlus,
|
||||
}
|
||||
|
||||
/// A volume for [`data_disk`]: its file system, volume label, partition name, and files.
|
||||
@@ -150,14 +150,15 @@ pub struct Volume<'a> {
|
||||
pub files: &'a [(String, Data)],
|
||||
}
|
||||
|
||||
/// A GPT disk of `volumes`, in order, each a basic data partition just big enough for its files
|
||||
/// and starting on a MiB boundary.
|
||||
/// A GPT disk of `volumes`, in order, each a partition just big enough for its files and
|
||||
/// starting on a MiB boundary: a basic data partition for FAT32, an Apple HFS one for HFS Plus.
|
||||
pub fn data_disk(volumes: &[Volume]) -> Result<Disk> {
|
||||
const MIB: u64 = 1 << 20;
|
||||
let sizes: Vec<u64> = volumes.iter().map(|v| fit(v.files)).collect();
|
||||
// The first MiB for the primary table, and one at the end for the backup.
|
||||
let size = MIB + sizes.iter().sum::<u64>() + MIB;
|
||||
let now = fat32::dos_time(std::time::SystemTime::now());
|
||||
let clock = std::time::SystemTime::now();
|
||||
let now = fat32::dos_time(clock);
|
||||
let mut pieces = Vec::new();
|
||||
let mut parts = Vec::new();
|
||||
let mut at = MIB;
|
||||
@@ -165,11 +166,14 @@ pub fn data_disk(volumes: &[Volume]) -> Result<Disk> {
|
||||
let first = at / gpt::SECTOR;
|
||||
let volume = match v.fs {
|
||||
Fs::Fat32 => fat32::make(len, u32::try_from(first)?, v.label, serial()?, v.files, now)?,
|
||||
Fs::Exfat => exfat::make(len, first, v.label, serial()?, v.files, now)?,
|
||||
Fs::HfsPlus => hfsplus::make(len, v.label, volume_id()?, v.files, clock)?,
|
||||
};
|
||||
pieces.extend(volume.into_iter().map(|(o, d)| (at + o, d)));
|
||||
parts.push(gpt::Partition {
|
||||
type_guid: gpt::BASIC_DATA_TYPE,
|
||||
type_guid: match v.fs {
|
||||
Fs::Fat32 => gpt::BASIC_DATA_TYPE,
|
||||
Fs::HfsPlus => gpt::HFS_PLUS_TYPE,
|
||||
},
|
||||
guid: gpt::random_guid()?,
|
||||
first_lba: first,
|
||||
last_lba: first + len / gpt::SECTOR - 1,
|
||||
@@ -181,9 +185,10 @@ pub fn data_disk(volumes: &[Volume]) -> Result<Disk> {
|
||||
Ok(Disk { size, pieces })
|
||||
}
|
||||
|
||||
/// A volume size that holds `files`: their bytes, each rounded up to the largest cluster either
|
||||
/// file system here uses (128 KiB), plus 1/64 for the FATs (FAT32's two, of 512-byte clusters,
|
||||
/// take 1/64 of a small volume) and 16 MiB for the rest, in whole MiB, 64 MiB at least.
|
||||
/// A volume size that holds `files`: their bytes, each rounded up to 128 KiB (more than either
|
||||
/// file system here rounds a file to), plus 1/64 for the FATs (FAT32's two, of 512-byte
|
||||
/// clusters, take 1/64 of a small volume) and 16 MiB for the rest (HFS Plus's B-trees take
|
||||
/// 1.5 MiB), in whole MiB, 64 MiB at least.
|
||||
fn fit(files: &[(String, Data)]) -> u64 {
|
||||
let data: u64 = files
|
||||
.iter()
|
||||
@@ -194,6 +199,13 @@ fn fit(files: &[(String, Data)]) -> u64 {
|
||||
.next_multiple_of(1 << 20)
|
||||
}
|
||||
|
||||
/// A random identifier for an HFS Plus volume, which macOS makes its volume UUID from.
|
||||
fn volume_id() -> Result<[u8; 8]> {
|
||||
let mut id = [0u8; 8];
|
||||
getrandom::fill(&mut id).map_err(|e| anyhow::anyhow!("random: {e}"))?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn serial() -> Result<u32> {
|
||||
let mut s = [0u8; 4];
|
||||
getrandom::fill(&mut s).map_err(|e| anyhow::anyhow!("random: {e}"))?;
|
||||
@@ -277,7 +289,7 @@ mod tests {
|
||||
#[test]
|
||||
fn data_disk_lays_volumes_end_to_end() {
|
||||
let fat_files = vec![("a/b.txt".to_string(), Data::Bytes(vec![1; 100]))];
|
||||
let ex_files = vec![("c.bin".to_string(), Data::Bytes(vec![2; 70_000]))];
|
||||
let hfs_files = vec![("c.bin".to_string(), Data::Bytes(vec![2; 70_000]))];
|
||||
let disk = data_disk(&[
|
||||
Volume {
|
||||
fs: Fs::Fat32,
|
||||
@@ -286,10 +298,10 @@ mod tests {
|
||||
files: &fat_files,
|
||||
},
|
||||
Volume {
|
||||
fs: Fs::Exfat,
|
||||
fs: Fs::HfsPlus,
|
||||
label: "Installer",
|
||||
name: "two",
|
||||
files: &ex_files,
|
||||
files: &hfs_files,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
@@ -297,12 +309,14 @@ mod tests {
|
||||
assert_eq!(disk.size, 130 << 20);
|
||||
let bytes = disk.to_bytes().unwrap();
|
||||
assert_eq!(&bytes[(1 << 20) + 82..(1 << 20) + 90], b"FAT32 ");
|
||||
assert_eq!(&bytes[(65 << 20) + 3..(65 << 20) + 11], b"EXFAT ");
|
||||
assert_eq!(&bytes[(65 << 20) + 1024..(65 << 20) + 1026], b"H+");
|
||||
let entry = |i: usize| &bytes[1024 + i * 128..1024 + (i + 1) * 128];
|
||||
let u64_at = |e: &[u8], o: usize| u64::from_le_bytes(e[o..o + 8].try_into().unwrap());
|
||||
assert_eq!(u64_at(entry(0), 32), 2048);
|
||||
assert_eq!(u64_at(entry(1), 32), 65 << 11);
|
||||
assert_eq!(u64_at(entry(1), 40), (129 << 11) - 1);
|
||||
assert_eq!(&entry(0)[..16], &gpt::BASIC_DATA_TYPE);
|
||||
assert_eq!(&entry(1)[..16], &gpt::HFS_PLUS_TYPE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+4
-3
@@ -308,7 +308,7 @@ fn check_toc(f: &mut File, offset: u64, digest: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
/// The command that installs macOS from an installer image, in Recovery's Terminal: the image's
|
||||
/// exFAT volume, labelled `Installer`, mounts at `/Volumes/Installer`.
|
||||
/// HFS Plus volume, labelled `Installer`, mounts at `/Volumes/Installer`.
|
||||
pub const IMAGE_COMMAND: &str = "sh /Volumes/Installer/install-macos.sh";
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
@@ -325,7 +325,8 @@ const BASE_SYSTEM: &str = "BaseSystem.dmg";
|
||||
|
||||
/// Makes `inst`'s offline installer in `dir`: a disk image, which reims-ctl attaches as the VM's
|
||||
/// installer, named `macOS-<name>-<version>-<build>-offline-installer.img`, of two volumes:
|
||||
/// - exFAT `Installer` (FAT32 holds no file of 4 GiB): `InstallAssistant.pkg`, and
|
||||
/// - HFS Plus `Installer` (FAT32 holds no file of 4 GiB, and the Recovery of macOS 14 and 15
|
||||
/// mounts no exFAT volume by itself): `InstallAssistant.pkg`, and
|
||||
/// `install-macos.sh`, which Recovery's Terminal runs to put the package's Install macOS app on
|
||||
/// the VM's disk and start the app's `startosinstall`;
|
||||
/// - FAT32 `RECOVERY`: the recovery image of the same macOS (major version), as
|
||||
@@ -389,7 +390,7 @@ pub fn offline_installer(inst: &Installer, dir: &Path, r: &dyn Reporter) -> Resu
|
||||
// changes size between runs.
|
||||
let disk = image::data_disk(&[
|
||||
Volume {
|
||||
fs: Fs::Exfat,
|
||||
fs: Fs::HfsPlus,
|
||||
label: "Installer",
|
||||
name: "macOS Installer",
|
||||
files: &install_files,
|
||||
|
||||
Reference in new issue
Block a user