diff --git a/crates/stela-boot/src/installer.rs b/crates/stela-boot/src/installer.rs
index b8bc98e2fd..6a17b766cf 100644
--- a/crates/stela-boot/src/installer.rs
+++ b/crates/stela-boot/src/installer.rs
@@ -72,6 +72,10 @@ struct Disk {
bus: &'static str,
/// Its GPT; `None` on a blank disk or one with another scheme.
table: Option
,
+ /// The blocks its GPT's headers give partitions, `first` to `end`;
+ /// `None` without a table. Another tool may give fewer than the
+ /// geometry's: Linux's fdisk starts them at 1 MiB.
+ usable: Option<(u64, u64)>,
/// Data without a GPT, which only erasing the disk replaces.
foreign: bool,
/// Why it cannot take macOS, when it cannot.
@@ -154,6 +158,18 @@ impl Disk {
})
}
+ /// The blocks the disk's GPT headers give partitions, `first` to `end`,
+ /// from the primary's, or the backup's when the primary does not parse;
+ /// `None` when neither does.
+ fn header_usable(&mut self) -> Option<(u64, u64)> {
+ let last = self.geometry.blocks.checked_sub(1)?;
+ [1, last].into_iter().find_map(|lba| {
+ let block = self.read(lba, 1).ok()?;
+ let info = gpt::parse_header(self.geometry, lba, &block).ok()??;
+ Some((info.first_usable, info.last_usable.checked_add(1)?))
+ })
+ }
+
/// GUIDs for a new partition or table on this disk.
fn entropy(&self) -> impl FnMut() -> Guid + use<> {
let serial = self.serial.clone().unwrap_or_default();
@@ -657,6 +673,7 @@ fn disks() -> Vec {
bus: bus(&path),
serial,
table: None,
+ usable: None,
foreign: false,
refusal: None,
rotation,
@@ -677,6 +694,9 @@ fn disks() -> Vec {
// Why Stela's own drivers cannot reach the disk, if they cannot.
disk.refusal = crate::pci_io::disk_controller(handle)
.and_then(|function| stela_drivers::probe::disk_refusal(&function));
+ if disk.table.is_some() {
+ disk.usable = disk.header_usable();
+ }
disks.push(disk);
}
// Stela's own drivers must reach each disk, and find it again by a
@@ -1230,6 +1250,12 @@ fn segments_of(disk: &Disk) -> Vec {
content: Content::Foreign,
}];
}
+ // Only the blocks the GPT's own headers give partitions, which may be
+ // fewer than the geometry's: the plan's check refuses a partition
+ // outside them.
+ let (first, end) = disk
+ .usable
+ .map_or((first, end), |(low, high)| (first.max(low), end.min(high)));
let mut kept: Vec<(usize, &gpt::Partition)> = match &disk.table {
Some(table) => table.partitions.iter().enumerate().collect(),
None => Vec::new(),
diff --git a/crates/stela-formats/src/payload/gpt.rs b/crates/stela-formats/src/payload/gpt.rs
index e089f98e9e..16b623684d 100644
--- a/crates/stela-formats/src/payload/gpt.rs
+++ b/crates/stela-formats/src/payload/gpt.rs
@@ -340,6 +340,10 @@ pub struct HeaderInfo {
pub entries_lba: u64,
pub entry_count: u32,
pub entry_bytes: u32,
+ /// The bytes the header's checksum covers.
+ pub header_bytes: u32,
+ /// The block of the other copy's header.
+ pub alternate_lba: u64,
entries_crc: u32,
}
@@ -377,6 +381,8 @@ pub fn parse_header(
entries_lba: le64(block, 72),
entry_count: le32(block, 80),
entry_bytes: le32(block, 84),
+ header_bytes: size,
+ alternate_lba: le64(block, 32),
entries_crc: le32(block, 88),
};
if le64(block, 24) != lba
@@ -440,6 +446,174 @@ pub fn parse_entries(info: &HeaderInfo, bytes: &[u8]) -> Result) -> fmt::Result {
+ match self {
+ Self::Exactly(value) => write!(f, "{value}"),
+ Self::AtLeast(value) => write!(f, "{value} or more"),
+ Self::AtMost(value) => write!(f, "{value} or less"),
+ }
+ }
+}
+
+/// Why a disk's GPT headers are not ones [`encode_keeping`] keeps.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Unkept {
+ /// The block holds no GPT header.
+ Missing,
+ /// The header does not parse: why.
+ Damaged(&'static str),
+ /// A field of the header holds `found`, where a rewrite keeps `kept`.
+ Field {
+ field: &'static str,
+ found: u64,
+ kept: Kept,
+ },
+ /// The two headers name different usable blocks.
+ Disagree {
+ field: &'static str,
+ primary: u64,
+ backup: u64,
+ },
+ /// The two headers name different disk GUIDs.
+ OtherDisk,
+}
+
+impl fmt::Display for Unkept {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Missing => f.write_str("a GPT header is missing"),
+ Self::Damaged(why) => write!(f, "a GPT header is damaged: {why}"),
+ Self::Field { field, found, kept } => write!(
+ f,
+ "a GPT header names another layout than the one a rewrite keeps: its {field} is \
+ {found}, where a rewrite keeps {kept}"
+ ),
+ Self::Disagree {
+ field,
+ primary,
+ backup,
+ } => write!(
+ f,
+ "the GPT's two headers name different layouts: the primary's {field} is \
+ {primary}, the backup's {backup}"
+ ),
+ Self::OtherDisk => f.write_str("the GPT's two headers name different disk GUIDs"),
+ }
+ }
+}
+
+/// The header in `block`, read from `lba`, the primary (1) or the backup
+/// (the last), when [`encode_keeping`] keeps it: its every field but the
+/// usable blocks [`encode`]'s, so its revision is 1.0, the entry array is 128 entries of 128
+/// bytes just after the primary header and just before the backup, and
+/// the other copy's header at the other end of the disk; and the usable
+/// blocks within [`encode`]'s, so none of them is a GPT's own. Windows,
+/// gdisk, parted and macOS start the usable blocks at [`encode`]'s, and
+/// Linux's fdisk (libfdisk) at 1 MiB.
+pub fn keepable(disk: Disk, lba: u64, block: &[u8]) -> Result {
+ let last = disk
+ .blocks
+ .checked_sub(1)
+ .ok_or(Unkept::Damaged("no blocks"))?;
+ if block.len() as u64 != disk.block_bytes {
+ return Err(Unkept::Damaged("not one block"));
+ }
+ let info = match parse_header(disk, lba, block) {
+ Ok(Some(info)) => info,
+ Ok(None) => return Err(Unkept::Missing),
+ Err(PayloadError::Disk(why)) => return Err(Unkept::Damaged(why)),
+ Err(_) => return Err(Unkept::Damaged("unreadable")),
+ };
+ let (entries_lba, other) = match lba {
+ 1 => (2, last),
+ lba if lba == last => (last - disk.entry_blocks(), 1),
+ _ => return Err(Unkept::Damaged("a GPT header is at block 1 or the last")),
+ };
+ let exactly = |field, found: u64, kept: u64| {
+ (found != kept).then_some(Unkept::Field {
+ field,
+ found,
+ kept: Kept::Exactly(kept),
+ })
+ };
+ let unkept = exactly("revision", le32(block, 8).into(), REVISION.into())
+ .or_else(|| exactly("header size", info.header_bytes.into(), HEADER_BYTES.into()))
+ .or_else(|| exactly("entry array LBA", info.entries_lba, entries_lba))
+ .or_else(|| exactly("entry count", info.entry_count.into(), ENTRY_COUNT.into()))
+ .or_else(|| exactly("entry size", info.entry_bytes.into(), ENTRY_BYTES.into()))
+ .or_else(|| exactly("other copy's LBA", info.alternate_lba, other))
+ .or_else(|| {
+ (info.first_usable < disk.first_usable()).then_some(Unkept::Field {
+ field: "first usable LBA",
+ found: info.first_usable,
+ kept: Kept::AtLeast(disk.first_usable()),
+ })
+ })
+ .or_else(|| {
+ (info.last_usable > disk.last_usable()).then_some(Unkept::Field {
+ field: "last usable LBA",
+ found: info.last_usable,
+ kept: Kept::AtMost(disk.last_usable()),
+ })
+ });
+ match unkept {
+ Some(unkept) => Err(unkept),
+ None => Ok(info),
+ }
+}
+
+/// The usable blocks both of a disk's headers name, `primary` read from
+/// LBA 1 and `backup` from the last, when [`encode_keeping`] keeps them:
+/// each [`keepable`], and the two alike in usable blocks and disk GUID.
+/// The error names the block of the header that is not.
+pub fn kept_layout(disk: Disk, primary: &[u8], backup: &[u8]) -> Result {
+ let last = disk
+ .blocks
+ .checked_sub(1)
+ .ok_or((0, Unkept::Damaged("no blocks")))?;
+ let first = keepable(disk, 1, primary).map_err(|why| (1, why))?;
+ let second = keepable(disk, last, backup).map_err(|why| (last, why))?;
+ for (field, primary, backup) in [
+ ("first usable LBA", first.first_usable, second.first_usable),
+ ("last usable LBA", first.last_usable, second.last_usable),
+ ] {
+ if primary != backup {
+ return Err((
+ last,
+ Unkept::Disagree {
+ field,
+ primary,
+ backup,
+ },
+ ));
+ }
+ }
+ if first.disk_guid != second.disk_guid {
+ return Err((last, Unkept::OtherDisk));
+ }
+ Ok(Usable {
+ first: first.first_usable,
+ last: first.last_usable,
+ })
+}
+
/// Sizes of the partitions Stela adds.
#[derive(Debug, Clone, Copy)]
pub struct Request {
@@ -605,10 +779,82 @@ pub struct Write {
/// never leaves a valid primary header that names unwritten entries.
pub fn encode(disk: Disk, table: &Table) -> Result, PayloadError> {
disk.validate()?;
+ let usable = Usable {
+ first: disk.first_usable(),
+ last: disk.last_usable(),
+ };
+ let (entries, entries_crc) = entry_array(table, usable)?;
+ let block = disk.block_bytes as usize;
+ let last = disk.blocks - 1;
+ let header = |current: u64, backup: u64, entries_lba: u64| {
+ let mut h = vec![0u8; block];
+ h[0..8].copy_from_slice(SIGNATURE);
+ h[8..12].copy_from_slice(&REVISION.to_le_bytes());
+ h[12..16].copy_from_slice(&HEADER_BYTES.to_le_bytes());
+ h[24..32].copy_from_slice(¤t.to_le_bytes());
+ h[32..40].copy_from_slice(&backup.to_le_bytes());
+ h[40..48].copy_from_slice(&usable.first.to_le_bytes());
+ h[48..56].copy_from_slice(&usable.last.to_le_bytes());
+ h[56..72].copy_from_slice(&table.disk_guid.0);
+ h[72..80].copy_from_slice(&entries_lba.to_le_bytes());
+ h[80..84].copy_from_slice(&ENTRY_COUNT.to_le_bytes());
+ h[84..88].copy_from_slice(&ENTRY_BYTES.to_le_bytes());
+ h[88..92].copy_from_slice(&entries_crc.to_le_bytes());
+ let crc = crc32(&h[..HEADER_BYTES as usize]);
+ h[16..20].copy_from_slice(&crc.to_le_bytes());
+ h
+ };
+ let entry_blocks = disk.entry_blocks();
+ Ok(writes(
+ disk,
+ entries,
+ header(last, 1, last - entry_blocks),
+ header(1, last, 2),
+ ))
+}
+
+/// [`encode`]'s writes for `table` on a disk whose GPT another tool may
+/// have laid out, keeping it: each header written is the disk's own,
+/// `primary` read from LBA 1 and `backup` from the last, with only its
+/// entries' checksum and its own made anew. The headers must be ones a
+/// rewrite keeps ([`kept_layout`]), and every partition of `table` must
+/// lie in the usable blocks they name, which may be fewer than
+/// [`encode`]'s: a GPT Linux's fdisk made gives partitions the blocks
+/// from 1 MiB. On a disk [`encode`] laid out, the writes are [`encode`]'s
+/// byte for byte.
+pub fn encode_keeping(
+ disk: Disk,
+ table: &Table,
+ primary: &[u8],
+ backup: &[u8],
+) -> Result, PayloadError> {
+ disk.validate()?;
+ let usable = kept_layout(disk, primary, backup)
+ .map_err(|_| PayloadError::Disk("the disk's GPT headers are not ones a rewrite keeps"))?;
+ let disk_guid = guid_at(primary, 56);
+ if table.disk_guid != disk_guid {
+ return Err(PayloadError::Disk(
+ "the table's disk GUID is not the one its headers name",
+ ));
+ }
+ let (entries, entries_crc) = entry_array(table, usable)?;
+ let keep = |was: &[u8]| {
+ let mut h = was.to_vec();
+ h[88..92].copy_from_slice(&entries_crc.to_le_bytes());
+ h[16..20].fill(0);
+ let crc = crc32(&h[..HEADER_BYTES as usize]);
+ h[16..20].copy_from_slice(&crc.to_le_bytes());
+ h
+ };
+ Ok(writes(disk, entries, keep(backup), keep(primary)))
+}
+
+/// The entry array holding `table`, each partition in its entry and in
+/// `usable`, and its checksum.
+fn entry_array(table: &Table, usable: Usable) -> Result<(Vec, u32), PayloadError> {
if table.partitions.len() > ENTRY_COUNT as usize {
return Err(PayloadError::Disk("too many partitions"));
}
- let block = disk.block_bytes as usize;
let mut entries = vec![0u8; ENTRY_ARRAY_BYTES as usize];
let mut taken = [false; ENTRY_COUNT as usize];
for (index, partition) in table.partitions.iter().enumerate() {
@@ -622,8 +868,8 @@ pub fn encode(disk: Disk, table: &Table) -> Result, PayloadError> {
return Err(PayloadError::Disk("two partitions in one entry"));
}
let slot = &mut entries[number * ENTRY_BYTES as usize..][..ENTRY_BYTES as usize];
- if partition.first_lba < disk.first_usable()
- || partition.last_lba > disk.last_usable()
+ if partition.first_lba < usable.first
+ || partition.last_lba > usable.last
|| partition.first_lba > partition.last_lba
{
return Err(PayloadError::Disk("partition outside the usable range"));
@@ -645,26 +891,15 @@ pub fn encode(disk: Disk, table: &Table) -> Result, PayloadError> {
}
}
let entries_crc = crc32(&entries);
+ Ok((entries, entries_crc))
+}
+
+/// The writes of a GPT of `entries` with these headers: the backup entries
+/// and header, the primary entries and header, then a protective MBR.
+fn writes(disk: Disk, entries: Vec, backup: Vec, primary: Vec) -> Vec {
+ let block = disk.block_bytes as usize;
let entry_blocks = disk.entry_blocks();
let last = disk.blocks - 1;
- let header = |current: u64, backup: u64, entries_lba: u64| {
- let mut h = vec![0u8; block];
- h[0..8].copy_from_slice(SIGNATURE);
- h[8..12].copy_from_slice(&REVISION.to_le_bytes());
- h[12..16].copy_from_slice(&HEADER_BYTES.to_le_bytes());
- h[24..32].copy_from_slice(¤t.to_le_bytes());
- h[32..40].copy_from_slice(&backup.to_le_bytes());
- h[40..48].copy_from_slice(&disk.first_usable().to_le_bytes());
- h[48..56].copy_from_slice(&disk.last_usable().to_le_bytes());
- h[56..72].copy_from_slice(&table.disk_guid.0);
- h[72..80].copy_from_slice(&entries_lba.to_le_bytes());
- h[80..84].copy_from_slice(&ENTRY_COUNT.to_le_bytes());
- h[84..88].copy_from_slice(&ENTRY_BYTES.to_le_bytes());
- h[88..92].copy_from_slice(&entries_crc.to_le_bytes());
- let crc = crc32(&h[..HEADER_BYTES as usize]);
- h[16..20].copy_from_slice(&crc.to_le_bytes());
- h
- };
let mut padded = entries;
padded.resize((entry_blocks * disk.block_bytes) as usize, 0);
let mut mbr = vec![0u8; block];
@@ -677,14 +912,14 @@ pub fn encode(disk: Disk, table: &Table) -> Result, PayloadError> {
mbr[446 + 12..446 + 16].copy_from_slice(&protective_blocks.to_le_bytes());
mbr[510] = 0x55;
mbr[511] = 0xaa;
- Ok(vec![
+ vec![
Write {
lba: last - entry_blocks,
bytes: padded.clone(),
},
Write {
lba: last,
- bytes: header(last, 1, last - entry_blocks),
+ bytes: backup,
},
Write {
lba: 2,
@@ -692,10 +927,10 @@ pub fn encode(disk: Disk, table: &Table) -> Result, PayloadError> {
},
Write {
lba: 1,
- bytes: header(1, last, 2),
+ bytes: primary,
},
Write { lba: 0, bytes: mbr },
- ])
+ ]
}
/// Blocks at each end of a disk that a GPT occupies at 512-byte blocks (the
diff --git a/crates/stela-formats/src/payload/gpt/tests.rs b/crates/stela-formats/src/payload/gpt/tests.rs
index 0c017e8253..7fe9fcba19 100644
--- a/crates/stela-formats/src/payload/gpt/tests.rs
+++ b/crates/stela-formats/src/payload/gpt/tests.rs
@@ -517,6 +517,330 @@ fn entries_the_table_cannot_hold_are_refused_not_moved() {
);
}
+/// `header` with `value` at byte `at` and its checksum made anew, as
+/// another tool writes a field of it.
+fn relabel(header: &mut [u8], at: usize, value: &[u8]) {
+ header[at..at + value.len()].copy_from_slice(value);
+ reseal(header);
+}
+
+/// `header`'s checksum made anew over the bytes its size names.
+fn reseal(header: &mut [u8]) {
+ let size = le32(header, 12) as usize;
+ header[16..20].fill(0);
+ let crc = crc32(&header[..size]);
+ header[16..20].copy_from_slice(&crc.to_le_bytes());
+}
+
+/// The primary and backup headers [`encode`] writes for `table`, each
+/// changed by `edit` as another tool lays the GPT out.
+fn headers(disk: Disk, table: &Table, edit: impl Fn(u64, &mut Vec)) -> (Vec, Vec) {
+ let writes = encode(disk, table).unwrap();
+ let (mut primary, mut backup) = (writes[3].bytes.clone(), writes[1].bytes.clone());
+ edit(1, &mut primary);
+ edit(disk.blocks - 1, &mut backup);
+ (primary, backup)
+}
+
+/// Linux's fdisk (libfdisk): the usable blocks from 1 MiB.
+fn fdisk(disk: Disk) -> impl Fn(u64, &mut Vec) {
+ move |_, header: &mut Vec| {
+ relabel(header, 40, &(ALIGNMENT / disk.block_bytes).to_le_bytes())
+ }
+}
+
+fn data_table(partitions: Vec) -> Table {
+ Table {
+ disk_guid: Guid([7; 16]),
+ partitions,
+ slots: Vec::new(),
+ }
+}
+
+#[test]
+fn a_rewrite_keeps_another_tools_headers_but_for_their_checksums() {
+ for block_bytes in [512, 4096] {
+ let disk = Disk {
+ block_bytes,
+ blocks: DISK.blocks * 512 / block_bytes,
+ };
+ let mib = ALIGNMENT / block_bytes;
+ let was = data_table(vec![data_partition(1, mib)]);
+ let (primary, backup) = headers(disk, &was, fdisk(disk));
+ assert_eq!(
+ kept_layout(disk, &primary, &backup),
+ Ok(Usable {
+ first: mib,
+ last: disk.last_usable(),
+ })
+ );
+ let mut table = was.clone();
+ table.add(data_partition(2, 100 * mib));
+ let writes = encode_keeping(disk, &table, &primary, &backup).unwrap();
+ let lbas: Vec = writes.iter().map(|write| write.lba).collect();
+ let last = disk.blocks - 1;
+ assert_eq!(lbas, [last - disk.entry_blocks(), last, 2, 1, 0]);
+ // The headers differ from the disk's only in their checksums, and
+ // parse back to the table, its usable blocks the disk's own.
+ for (write, was) in [(&writes[3], &primary), (&writes[1], &backup)] {
+ let changed: Vec = (0..block_bytes as usize)
+ .filter(|&at| write.bytes[at] != was[at])
+ .collect();
+ assert!(
+ changed
+ .iter()
+ .all(|at| (16..20).contains(at) || (88..92).contains(at)),
+ "{changed:?}"
+ );
+ let info = parse_header(disk, write.lba, &write.bytes)
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ (info.first_usable, info.last_usable),
+ (mib, disk.last_usable())
+ );
+ }
+ assert_eq!(read_back(disk, &writes), table);
+ let info = keepable(disk, last, &writes[1].bytes).unwrap();
+ assert_eq!(
+ parse_entries(&info, &writes[0].bytes).unwrap(),
+ table,
+ "{block_bytes}"
+ );
+ }
+}
+
+#[test]
+fn on_a_disk_encode_laid_out_a_rewrite_that_keeps_writes_what_encode_writes() {
+ for block_bytes in [512, 1024, 2048, 4096] {
+ let disk = Disk {
+ block_bytes,
+ blocks: DISK.blocks * 512 / block_bytes,
+ };
+ let mib = ALIGNMENT / block_bytes;
+ let was = data_table(vec![data_partition(1, mib), data_partition(3, 50 * mib)]);
+ let (primary, backup) = headers(disk, &was, |_, _| {});
+ let mut table = was.clone();
+ table.add(data_partition(2, 100 * mib));
+ assert_eq!(
+ encode_keeping(disk, &table, &primary, &backup).unwrap(),
+ encode(disk, &table).unwrap(),
+ "{block_bytes}"
+ );
+ }
+}
+
+#[test]
+fn a_rewrite_that_keeps_refuses_a_partition_outside_the_headers_usable_blocks() {
+ let mib = ALIGNMENT / DISK.block_bytes;
+ let was = data_table(vec![data_partition(1, mib)]);
+ let (primary, backup) = headers(DISK, &was, fdisk(DISK));
+ // Before the first usable block fdisk names, though after encode's,
+ // and past a last usable block narrowed by a MiB.
+ let mut early = was.clone();
+ early.add(Partition {
+ first_lba: 34,
+ last_lba: mib - 1,
+ ..data_partition(2, 0)
+ });
+ assert_eq!(
+ encode_keeping(DISK, &early, &primary, &backup),
+ Err(PayloadError::Disk("partition outside the usable range"))
+ );
+ let narrowed = |_: u64, header: &mut Vec| {
+ relabel(header, 48, &(DISK.last_usable() - mib).to_le_bytes())
+ };
+ let (primary, backup) = headers(DISK, &was, narrowed);
+ let mut late = was.clone();
+ late.add(Partition {
+ first_lba: DISK.last_usable() - mib + 1,
+ last_lba: DISK.last_usable(),
+ ..data_partition(2, 0)
+ });
+ assert_eq!(
+ encode_keeping(DISK, &late, &primary, &backup),
+ Err(PayloadError::Disk("partition outside the usable range"))
+ );
+ // Another disk's GUID.
+ let other = Table {
+ disk_guid: Guid([8; 16]),
+ ..was.clone()
+ };
+ assert_eq!(
+ encode_keeping(DISK, &other, &primary, &backup),
+ Err(PayloadError::Disk(
+ "the table's disk GUID is not the one its headers name"
+ ))
+ );
+}
+
+#[test]
+fn headers_a_rewrite_does_not_keep_are_refused_naming_the_field() {
+ let last = DISK.blocks - 1;
+ let was = data_table(vec![data_partition(1, 2048)]);
+ let exactly = |field, found, kept| Unkept::Field {
+ field,
+ found,
+ kept: Kept::Exactly(kept),
+ };
+ type Edit = fn(u64, &mut Vec);
+ let cases: [(Edit, u64, Unkept); 13] = [
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 8, &0x0001_0001u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("revision", 0x0001_0001, 0x0001_0000),
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 80, &64u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("entry count", 64, 128),
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 80, &256u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("entry count", 256, 128),
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 84, &256u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("entry size", 256, 128),
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 72, &3u64.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("entry array LBA", 3, 2),
+ ),
+ (
+ |lba, h| {
+ if lba != 1 {
+ relabel(h, 72, &(lba - 33).to_le_bytes())
+ }
+ },
+ last,
+ exactly("entry array LBA", last - 33, last - 32),
+ ),
+ // Cloned from a smaller disk.
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 32, &1_000_000u64.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("other copy's LBA", 1_000_000, last),
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 12, &96u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("header size", 96, 92),
+ ),
+ // Over the primary entry array, and the backup's.
+ (
+ |_, h| relabel(h, 40, &33u64.to_le_bytes()),
+ 1,
+ Unkept::Field {
+ field: "first usable LBA",
+ found: 33,
+ kept: Kept::AtLeast(34),
+ },
+ ),
+ (
+ |lba, h| relabel(h, 48, &(lba.max(DISK.blocks - 1) - 32).to_le_bytes()),
+ 1,
+ Unkept::Field {
+ field: "last usable LBA",
+ found: last - 32,
+ kept: Kept::AtMost(last - 33),
+ },
+ ),
+ // The copies disagree.
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 40, &2048u64.to_le_bytes())
+ }
+ },
+ last,
+ Unkept::Disagree {
+ field: "first usable LBA",
+ primary: 2048,
+ backup: 34,
+ },
+ ),
+ (
+ |lba, h| {
+ if lba != 1 {
+ relabel(h, 56, &[9; 16])
+ }
+ },
+ last,
+ Unkept::OtherDisk,
+ ),
+ (|_, _| {}, 1, Unkept::Missing),
+ ];
+ for (index, (edit, lba, why)) in cases.into_iter().enumerate() {
+ let (mut primary, backup) = headers(DISK, &was, edit);
+ if why == Unkept::Missing {
+ primary.fill(0);
+ }
+ assert_eq!(
+ kept_layout(DISK, &primary, &backup),
+ Err((lba, why)),
+ "{index}"
+ );
+ assert_eq!(
+ encode_keeping(DISK, &was, &primary, &backup),
+ Err(PayloadError::Disk(
+ "the disk's GPT headers are not ones a rewrite keeps"
+ )),
+ "{index}"
+ );
+ }
+ // A damaged header: its checksum.
+ let (mut primary, backup) = headers(DISK, &was, |_, _| {});
+ primary[20] ^= 1;
+ assert_eq!(
+ kept_layout(DISK, &primary, &backup),
+ Err((1, Unkept::Damaged("GPT header CRC mismatch")))
+ );
+ assert_eq!(
+ alloc::format!(
+ "{}",
+ Unkept::Field {
+ field: "first usable LBA",
+ found: 33,
+ kept: Kept::AtLeast(34),
+ }
+ ),
+ "a GPT header names another layout than the one a rewrite keeps: its first usable LBA \
+ is 33, where a rewrite keeps 34 or more"
+ );
+}
+
#[test]
fn a_protective_mbr_is_its_boot_signature_and_a_type_0xee_entry() {
let plan = plan(DISK, None, request(), counter()).unwrap();
diff --git a/crates/stela-runtime/src/platform/pc/disk_plan.rs b/crates/stela-runtime/src/platform/pc/disk_plan.rs
index 33ab9c4259..5d0407a661 100644
--- a/crates/stela-runtime/src/platform/pc/disk_plan.rs
+++ b/crates/stela-runtime/src/platform/pc/disk_plan.rs
@@ -158,8 +158,9 @@ pub struct Plan {
pub ends: Ends,
pub mode: Mode,
/// The partition table's blocks in the order to write them
- /// ([`shared::encode`]'s, without its protective MBR where the disk
- /// has one); none when the table stays as it is.
+ /// ([`shared::encode_keeping`]'s, the disk's own headers but for their
+ /// checksums, without its protective MBR where the disk has one); none
+ /// when the table stays as it is.
pub table: Vec,
/// The blocks to zero: the partition's first MiB and the machine
/// state's tail, so the restore and the NOR start blank.
@@ -210,6 +211,12 @@ pub enum PlanError {
Overlap,
/// The partition cannot hold a namespace and the machine state.
TooSmall,
+ /// The disk's GPT header at `lba` is not one a rewrite keeps
+ /// ([`shared::kept_layout`]).
+ Layout {
+ lba: u64,
+ why: shared::Unkept,
+ },
/// The new table cannot be encoded.
Table(&'static str),
}
@@ -227,6 +234,12 @@ impl fmt::Display for PlanError {
Self::NotReusable => f.write_str("the partition chosen is not a Stambha partition"),
Self::Overlap => f.write_str("the new partition overlaps one that stays"),
Self::TooSmall => f.write_str("the partition is too small"),
+ Self::Layout { lba, why } => {
+ write!(
+ f,
+ "the disk's partition table at block {lba} is not added to: {why}"
+ )
+ }
Self::Table(why) => write!(f, "the new partition table is invalid: {why}"),
}
}
@@ -310,10 +323,22 @@ pub fn plan(decision: &Decision<'_>, entropy: &mut dyn FnMut() -> Guid) -> Resul
let table = match place {
Place::Reuse(_) => Vec::new(),
Place::Free { .. } => {
- let mut writes = shared::encode(geometry, &new).map_err(|error| match error {
- PayloadError::Disk(why) => PlanError::Table(why),
- _ => PlanError::Table("it cannot be encoded"),
- })?;
+ // The disk's own headers, as the picker read them, but for
+ // their checksums: the layout another tool chose stays, and
+ // every partition lies in the blocks its headers name.
+ let entries = (geometry.entry_blocks() * block) as usize;
+ let (primary, backup) = (
+ &ends.head[block as usize..2 * block as usize],
+ &ends.tail[entries..],
+ );
+ shared::kept_layout(geometry, primary, backup)
+ .map_err(|(lba, why)| PlanError::Layout { lba, why })?;
+ let mut writes = shared::encode_keeping(geometry, &new, primary, backup).map_err(
+ |error| match error {
+ PayloadError::Disk(why) => PlanError::Table(why),
+ _ => PlanError::Table("it cannot be encoded"),
+ },
+ )?;
// The disk's own protective MBR stays: the one `encode` builds
// drops its disk signature and other bytes the systems on the
// disk wrote.
@@ -394,6 +419,9 @@ pub enum Cause {
/// The disk's two copies of the GPT are not whole, alike and in the
/// layout a rewrite keeps: why.
Copies(&'static str),
+ /// A GPT header of the disk names a layout a rewrite does not keep, or
+ /// the two name different ones: the field and its values.
+ Layout(shared::Unkept),
/// The plan writes what no plan writes: why.
Refused(&'static str),
/// The plan changes the entry of a partition that stays, numbered from
@@ -446,6 +474,7 @@ impl fmt::Display for ApplyError {
firmware",
),
Cause::Copies(why) | Cause::Refused(why) => write!(f, ": {why}"),
+ Cause::Layout(why) => write!(f, ": {why}"),
Cause::Entry { entry } => write!(
f,
": the plan changes the entry of partition {entry}, which stays as it is"
@@ -532,15 +561,18 @@ fn first_difference(found: &[u8], expected: &[u8], block: u64) -> Option {
.map(|index| index as u64)
}
-/// The disk's table as both copies of its GPT hold it, from its [`Ends`]:
-/// each header valid at its own block, naming the other copy, the usable
-/// blocks a rewrite keeps and 128 entries of 128 bytes beside it, each
-/// entry array its header's, and both arrays the same bytes.
+/// The disk's table as both copies of its GPT hold it, from its [`Ends`],
+/// and the blocks its headers give partitions: each header valid at its
+/// own block and one a rewrite keeps ([`shared::keepable`]: naming the
+/// other copy and 128 entries of 128 bytes beside it, and usable blocks
+/// that are none of the GPT's own), both headers naming the same usable
+/// blocks, each entry array its header's, both arrays the same bytes, and
+/// no two of the partitions overlapping.
#[expect(
clippy::result_large_err,
reason = "the driver's error is kept whole for the stop's message, and one plan is checked a boot"
)]
-fn copies(geometry: Disk, ends: &Ends) -> Result {
+fn copies(geometry: Disk, ends: &Ends) -> Result<(Table, shared::Usable), ApplyError> {
let block = geometry.block_bytes as usize;
let entry_blocks = geometry.entry_blocks();
let entries = entry_blocks as usize * block;
@@ -560,28 +592,36 @@ fn copies(geometry: Disk, ends: &Ends) -> Result {
&ends.tail[..entries],
);
let mut tables = Vec::new();
- for ((lba, header, entries_lba, array), other) in [(primary, last), (backup, 1)] {
- let info = match shared::parse_header(geometry, lba, header) {
- Ok(Some(info)) => info,
- Ok(None) => return Err(refuse(lba, "a GPT header is missing")),
- Err(_) => return Err(refuse(lba, "a GPT header is damaged")),
- };
- let alternate = u64::from_le_bytes(header[32..40].try_into().expect("8 bytes"));
- if info.entries_lba != entries_lba
- || info.entry_count != 128
- || info.entry_bytes != ENTRY_BYTES as u32
- || info.first_usable != geometry.first_usable()
- || info.last_usable != geometry.last_usable()
- || alternate != other
- {
- return Err(refuse(
- lba,
- "a GPT header names another layout than the one a rewrite keeps",
- ));
- }
+ let mut usable = Vec::new();
+ for (lba, header, entries_lba, array) in [primary, backup] {
+ let info = shared::keepable(geometry, lba, header).map_err(|why| match why {
+ shared::Unkept::Missing => refuse(lba, "a GPT header is missing"),
+ shared::Unkept::Field { .. } => error(Step::Check, Some(lba), Cause::Layout(why)),
+ _ => refuse(lba, "a GPT header is damaged"),
+ })?;
let table = shared::parse_entries(&info, array)
.map_err(|_| refuse(entries_lba, "a GPT entry array is damaged"))?;
tables.push(table);
+ usable.push(shared::Usable {
+ first: info.first_usable,
+ last: info.last_usable,
+ });
+ }
+ for (field, primary, backup) in [
+ ("first usable LBA", usable[0].first, usable[1].first),
+ ("last usable LBA", usable[0].last, usable[1].last),
+ ] {
+ if primary != backup {
+ return Err(error(
+ Step::Check,
+ Some(last),
+ Cause::Layout(shared::Unkept::Disagree {
+ field,
+ primary,
+ backup,
+ }),
+ ));
+ }
}
if primary.3 != backup.3 || tables[0] != tables[1] {
return Err(refuse(
@@ -589,7 +629,19 @@ fn copies(geometry: Disk, ends: &Ends) -> Result {
"the backup GPT is not the primary's copy",
));
}
- Ok(tables.swap_remove(0))
+ let table = tables.swap_remove(0);
+ for (index, one) in table.partitions.iter().enumerate() {
+ let overlapped = table.partitions[index + 1..]
+ .iter()
+ .any(|other| one.first_lba <= other.last_lba && other.first_lba <= one.last_lba);
+ if overlapped {
+ return Err(refuse(
+ 2 + (table.slot(index) as usize * ENTRY_BYTES / block) as u64,
+ "two of the disk's partitions overlap",
+ ));
+ }
+ }
+ Ok((table, usable[0]))
}
/// The table the backup copy in `tail` holds, if it is whole.
@@ -841,12 +893,14 @@ impl Plan {
self.span(span.lba, span.blocks)
));
}
- let existing = copies(geometry, &now)?;
+ let (existing, usable) = copies(geometry, &now)?;
say(&format!(
"PASS both GPT copies are whole and alike: headers at LBA 1 and {}, 128 entries of \
- 128 bytes at LBA 2 and {}, {} partitions",
+ 128 bytes at LBA 2 and {}, usable LBA {}-{}, {} partitions",
geometry.blocks - 1,
tail.lba,
+ usable.first,
+ usable.last,
existing.partitions.len()
));
let partition = self.partition;
@@ -859,7 +913,9 @@ impl Plan {
partition.first_lba,
"the macOS partition has no blocks",
))?;
- if partition.first_lba < geometry.first_usable() || last_lba > geometry.last_usable() {
+ // The blocks the disk's headers give partitions, which another tool
+ // may have made fewer than the geometry's.
+ if partition.first_lba < usable.first || last_lba > usable.last {
return Err(refuse(
partition.first_lba,
"the macOS partition lies outside the blocks the GPT gives partitions",
@@ -1247,7 +1303,8 @@ impl Plan {
let now = read_ends(geometry, Step::Verify, |lba, buffer| {
device.read(lba, buffer)
})?;
- let found = copies(geometry, &now).map_err(|found| verify(found.lba, found.cause))?;
+ let (found, _) =
+ copies(geometry, &now).map_err(|found| verify(found.lba, found.cause))?;
if found != *planned || table != *planned {
return Err(verify(Some(1), Cause::Missing));
}
diff --git a/crates/stela-runtime/src/platform/pc/disk_plan/tests.rs b/crates/stela-runtime/src/platform/pc/disk_plan/tests.rs
index 20df3f8d6e..42d014b7fb 100644
--- a/crates/stela-runtime/src/platform/pc/disk_plan/tests.rs
+++ b/crates/stela-runtime/src/platform/pc/disk_plan/tests.rs
@@ -356,6 +356,216 @@ fn new_in(table: &mut Table) -> &mut Partition {
.unwrap()
}
+/// `plan` as the picker would have made it had it read `disk` as it is
+/// now: its GPT blocks and first blocks `disk`'s, its writes `plan`'s.
+fn as_read(plan: &Plan, disk: &Sparse) -> Plan {
+ Plan {
+ ends: disk.ends(),
+ seen: seen(&disk.bytes(0, SEEN_BLOCKS)),
+ ..plan.clone()
+ }
+}
+
+/// `header` with `value` at byte `at` and its checksum made anew, as
+/// another tool writes a field of it.
+fn relabel(header: &mut [u8], at: usize, value: &[u8]) {
+ header[at..at + value.len()].copy_from_slice(value);
+ let size = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
+ header[16..20].fill(0);
+ let crc = shared::crc32(&header[..size]);
+ header[16..20].copy_from_slice(&crc.to_le_bytes());
+}
+
+impl Sparse {
+ /// A disk of `blocks` blocks of `block` bytes holding `table` as
+ /// another tool lays one out: [`shared::encode`]'s blocks, each header
+ /// then changed by `edit`, given its LBA, and a protective MBR with a
+ /// disk signature.
+ fn laid_out(block: u64, blocks: u64, table: &Table, edit: impl Fn(u64, &mut [u8])) -> Self {
+ let mut disk = Self::new(block);
+ disk.identity.blocks = blocks;
+ for write in shared::encode(gpt::geometry(&disk.identity), table).unwrap() {
+ disk.put(write.lba, &write.bytes);
+ }
+ for lba in [1, blocks - 1] {
+ let mut header = disk.block_at(lba);
+ edit(lba, &mut header);
+ disk.put(lba, &header);
+ }
+ let mut mbr = disk.block_at(0);
+ mbr[440..444].copy_from_slice(&[0x5e, 0x1f, 0x7a, 0x0b]);
+ disk.put(0, &mbr);
+ disk
+ }
+}
+
+/// Linux's fdisk (libfdisk, also behind sfdisk, cfdisk and GNOME Disks):
+/// the usable blocks from 1 MiB, the last and the rest as Windows'.
+fn fdisk(block: u64) -> impl Fn(u64, &mut [u8]) {
+ move |_: u64, header: &mut [u8]| relabel(header, 40, &(MIB / block).to_le_bytes())
+}
+
+/// Windows, gdisk, parted and macOS: the header as [`shared::encode`]'s.
+fn standard(_: u64, _: &mut [u8]) {}
+
+/// The usable blocks `disk`'s primary header names.
+fn usable_of(disk: &Sparse) -> (u64, u64) {
+ let geometry = gpt::geometry(&disk.identity);
+ let info = shared::parse_header(geometry, 1, &disk.block_at(1))
+ .unwrap()
+ .unwrap();
+ (info.first_usable, info.last_usable)
+}
+
+/// The free space after `table`'s last partition as the picker offers
+/// it: from a MiB boundary, to the last MiB boundary of the usable blocks,
+/// all of it.
+fn free_after(disk: &Sparse, table: &Table) -> Place {
+ let block = u64::from(disk.identity.block_size);
+ let mib = MIB / block;
+ let (first, last) = usable_of(disk);
+ let start = table
+ .partitions
+ .iter()
+ .map(|partition| partition.last_lba + 1)
+ .fold(first, u64::max)
+ .div_ceil(mib)
+ * mib;
+ let end = (last + 1) / mib * mib;
+ Place::Free {
+ first_lba: start,
+ bytes: (end - start) * block / MIB * MIB,
+ }
+}
+
+/// Check only, then install, macOS in the free space after the last of
+/// the partitions `disk` holds, as the picker reads them; and prove what
+/// the install leaves: every write in the GPT's own blocks or the new
+/// partition, the MBR, every partition's entry and every header byte but
+/// the two checksums as they were, both copies whole and alike with the
+/// same layout, and the table the disk's with one partition more.
+fn installs_beside(mut disk: Sparse, what: &str) -> Plan {
+ let geometry = gpt::geometry(&disk.identity);
+ let block = geometry.block_bytes as usize;
+ let table = gpt::read(&mut disk).unwrap();
+ let before = disk.ends();
+ let made = planned(&disk, &table, free_after(&disk, &table), Mode::Check);
+ let (result, lines) = checked(&made, &mut disk);
+ assert!(result.is_ok(), "{what}: {result:?}\n{lines:#?}");
+ assert_eq!(disk.done, [], "{what}");
+ let made = Plan {
+ mode: Mode::Install,
+ ..made
+ };
+ made.apply(&mut disk)
+ .unwrap_or_else(|error| panic!("{what}: {error}"));
+ let [head, tail] = Ends::spans(geometry).unwrap();
+ let (first, end) = (
+ made.partition.first_lba,
+ made.partition.first_lba + made.partition.blocks,
+ );
+ for change in disk.changes() {
+ let (Done::Write { lba, blocks } | Done::Zeroes { lba, blocks }) = change else {
+ panic!("{what}: {change:?}");
+ };
+ assert!(
+ lba + blocks <= head.blocks || lba >= tail.lba || (lba >= first && lba + blocks <= end),
+ "{what}: {change:?}"
+ );
+ }
+ let after = disk.ends();
+ assert_eq!(after.head[..block], before.head[..block], "{what}");
+ let entries = geometry.entry_blocks() as usize * block;
+ let array = |ends: &Ends| ends.head[2 * block..2 * block + entries].to_vec();
+ let (was, now) = (array(&before), array(&after));
+ let changed: Vec = (0..128)
+ .filter(|slot| was[slot * 128..][..128] != now[slot * 128..][..128])
+ .collect();
+ assert_eq!(changed.len(), 1, "{what}");
+ assert!(was[changed[0] * 128..][..128].iter().all(|&byte| byte == 0));
+ assert_eq!(after.tail[..entries], now[..], "{what}");
+ let headers = |ends: &Ends| {
+ (
+ ends.head[block..2 * block].to_vec(),
+ ends.tail[entries..].to_vec(),
+ )
+ };
+ let (was_headers, now_headers) = (headers(&before), headers(&after));
+ for (was, now) in [
+ (&was_headers.0, &now_headers.0),
+ (&was_headers.1, &now_headers.1),
+ ] {
+ let changed: Vec = (0..block).filter(|&at| was[at] != now[at]).collect();
+ assert!(
+ changed
+ .iter()
+ .all(|at| CHECKSUMS.iter().any(|c| c.contains(at))),
+ "{what}: {changed:?}"
+ );
+ }
+ assert_eq!(
+ shared::kept_layout(geometry, &now_headers.0, &now_headers.1),
+ shared::kept_layout(geometry, &was_headers.0, &was_headers.1),
+ "{what}"
+ );
+ // As the firmware and the systems on the disk read it: both copies
+ // whole and alike, and a protective MBR.
+ let found = shared::read(geometry, |lba, blocks| Ok(disk.bytes(lba, blocks))).unwrap();
+ let shared::Found::Table {
+ table: read,
+ repair: None,
+ } = found
+ else {
+ panic!("{what}: {found:?}");
+ };
+ assert_eq!(read, written(&made), "{what}");
+ let mut kept = read.clone();
+ let new = kept
+ .partitions
+ .iter()
+ .position(|partition| partition.unique_guid == guid(NEW))
+ .unwrap();
+ assert_eq!(kept.slot(new) as usize, changed[0], "{what}");
+ kept.remove(new);
+ assert_eq!(kept, table, "{what}");
+ made
+}
+
+const LINUX: &str = "0FC63DAF-8483-4772-8E79-3D69D8477DE4";
+const APFS: &str = "7C3457EF-0000-11AA-AA11-00306543ECAC";
+/// The tester's NVMe disk: a Samsung 970 EVO Plus, 500 GB.
+const EVO: u64 = 976_773_168;
+/// The tester's SATA disk: a PNY, 250 GB.
+const PNY: u64 = 488_397_168;
+
+fn blocks_partition(kind: &str, tag: u8, first: u64, last: u64, name: &str) -> Partition {
+ Partition {
+ type_guid: guid(kind),
+ unique_guid: Guid([tag; 16]),
+ first_lba: first,
+ last_lba: last,
+ attributes: 0,
+ name: name.into(),
+ }
+}
+
+fn table_of(partitions: Vec) -> Table {
+ Table {
+ disk_guid: guid(DISK),
+ partitions,
+ slots: Vec::new(),
+ }
+}
+
+/// The tester's SATA disk as the log shows it: a Linux filesystem from
+/// 1 MiB, then a 2 GiB ESP, ending where the plan's free space starts.
+fn pny() -> Table {
+ table_of(vec![
+ blocks_partition(LINUX, 1, 2048, 103_426_047, ""),
+ blocks_partition(ESP, 2, 103_426_048, 107_620_351, ""),
+ ])
+}
+
/// Check `plan` on `disk`; its lines.
fn checked(plan: &Plan, disk: &mut Sparse) -> (Result, Vec) {
let mut lines = Vec::new();
@@ -453,7 +663,7 @@ fn checking_says_every_write_and_writes_nothing() {
"PASS the backup GPT's blocks, LBA 268435423-268435455 (33 blocks, 16896 bytes), read \
through Stela's driver are byte for byte what the picker read through the firmware",
"PASS both GPT copies are whole and alike: headers at LBA 1 and 268435455, 128 entries \
- of 128 bytes at LBA 2 and 268435423, 5 partitions",
+ of 128 bytes at LBA 2 and 268435423, usable LBA 34-268435422, 5 partitions",
"PASS the new partition, LBA 83886080-230686719 (146800640 blocks, 75161927680 bytes), \
lies in free space: it overlaps none of the disk's 5 partitions and holds at least \
60017825792 bytes",
@@ -738,11 +948,16 @@ fn a_disk_whose_gpt_copies_are_not_whole_and_alike_is_not_written() {
let backup = shared::encode(gpt::geometry(&Sparse::new(512).identity), &other).unwrap();
/// Damage done to the disk, given another table's encoded GPT.
type Damage = fn(&mut Sparse, &[Write]);
- let cases: [(Damage, u64, &str); 4] = [
+ type Unplanned = Option<(u64, shared::Unkept)>;
+ // Each with the block at which the picker's plan is refused, when it is:
+ // a plan's headers are the disk's own, so one missing or damaged makes
+ // no plan.
+ let cases: [(Damage, u64, &str, Unplanned); 4] = [
(
|disk, _| disk.put(disk.last(), &[0; 512]),
last,
"a GPT header is missing",
+ Some((last, shared::Unkept::Missing)),
),
(
|disk, _| {
@@ -752,6 +967,7 @@ fn a_disk_whose_gpt_copies_are_not_whole_and_alike_is_not_written() {
},
1,
"a GPT header is damaged",
+ Some((1, shared::Unkept::Damaged("GPT header CRC mismatch"))),
),
(
|disk, _| {
@@ -761,6 +977,7 @@ fn a_disk_whose_gpt_copies_are_not_whole_and_alike_is_not_written() {
},
2,
"a GPT entry array is damaged",
+ None,
),
// A backup that is whole, of another table.
(
@@ -770,13 +987,31 @@ fn a_disk_whose_gpt_copies_are_not_whole_and_alike_is_not_written() {
},
last - 32,
"the backup GPT is not the primary's copy",
+ None,
),
];
- for (damage, lba, why) in cases {
+ let whole = planned(&Sparse::with(512, &table), &table, free(512), Mode::Check);
+ for (damage, lba, why, unplanned) in cases {
let mut disk = Sparse::with(512, &table);
damage(&mut disk, &backup);
- // The picker read the disk as it is now.
- let made = planned(&disk, &table, free(512), Mode::Check);
+ let ends = disk.ends();
+ let picked = plan(
+ &Decision {
+ mode: Mode::Check,
+ ..decision(&disk, &ends, Some(&table), free(512))
+ },
+ &mut || guid(NEW),
+ );
+ assert_eq!(
+ picked.as_ref().err(),
+ unplanned
+ .map(|(lba, why)| PlanError::Layout { lba, why })
+ .as_ref(),
+ "{why}"
+ );
+ // The picker read the disk as it is now; a plan it refused to make
+ // is refused by the check too.
+ let made = picked.unwrap_or_else(|_| as_read(&whole, &disk));
assert_eq!(
checked(&made, &mut disk).0,
Err(ApplyError {
@@ -1345,3 +1580,414 @@ fn the_disk_is_found_by_its_serial_or_by_what_the_picker_read() {
assert_eq!(made.locate(&mut devices), Err(LocateError::NoDisk));
assert_eq!(made.locate(&mut []), Err(LocateError::NoDisk));
}
+
+#[test]
+fn an_empty_libfdisk_gpt_takes_macos() {
+ // The tester's NVMe disk, wiped in Linux: no partitions, the usable
+ // blocks from 1 MiB.
+ let table = table_of(Vec::new());
+ let disk = Sparse::laid_out(512, EVO, &table, fdisk(512));
+ assert_eq!(usable_of(&disk), (2048, EVO - 34));
+ assert_eq!(
+ free_after(&disk, &table),
+ Place::Free {
+ first_lba: 2048,
+ bytes: 976_771_072 * 512
+ }
+ );
+ let made = installs_beside(disk, "fdisk, empty");
+ let lbas: Vec = made.table.iter().map(|write| write.lba).collect();
+ assert_eq!(lbas, [EVO - 33, EVO - 1, 2, 1]);
+ assert_eq!(
+ (made.partition.first_lba, made.partition.blocks),
+ (2048, 976_771_072)
+ );
+}
+
+#[test]
+fn a_libfdisk_disk_with_linux_and_an_esp_takes_macos() {
+ let table = pny();
+ let disk = Sparse::laid_out(512, PNY, &table, fdisk(512));
+ assert_eq!(
+ free_after(&disk, &table),
+ Place::Free {
+ first_lba: 107_620_352,
+ bytes: 380_776_448 * 512
+ }
+ );
+ let made = installs_beside(disk, "fdisk, Linux and an ESP");
+ let new = written(&made);
+ assert_eq!(new.slots, [0, 1, 2]);
+ assert_eq!(
+ (new.partitions[2].first_lba, new.partitions[2].last_lba),
+ (107_620_352, 488_396_799)
+ );
+}
+
+#[test]
+fn a_disk_each_tool_partitioned_takes_macos() {
+ let msr = |last| blocks_partition(RESERVED, 3, 34, last, "Microsoft reserved partition");
+ type Edit = Box;
+ let cases: Vec<(&str, u64, u64, Table, Edit)> = vec![
+ // Windows' Initialize Disk: a 16 MiB reserved partition.
+ (
+ "Windows, initialized",
+ 512,
+ PNY,
+ table_of(vec![msr(32_767)]),
+ Box::new(standard),
+ ),
+ (
+ "Windows, initialized",
+ 512,
+ EVO,
+ table_of(vec![msr(32_767)]),
+ Box::new(standard),
+ ),
+ (
+ "Windows, initialized, 4096-byte blocks",
+ 4096,
+ BYTES / 4096,
+ table_of(vec![blocks_partition(
+ RESERVED,
+ 3,
+ 6,
+ 4095,
+ "Microsoft reserved partition",
+ )]),
+ Box::new(standard),
+ ),
+ (
+ "Windows, installed and shrunk",
+ 512,
+ PNY,
+ layout(512),
+ Box::new(standard),
+ ),
+ (
+ "Windows, installed and shrunk, 4096-byte blocks",
+ 4096,
+ PNY / 8,
+ layout(4096),
+ Box::new(standard),
+ ),
+ (
+ "gdisk, empty",
+ 512,
+ PNY,
+ table_of(Vec::new()),
+ Box::new(standard),
+ ),
+ (
+ "gdisk, a Linux filesystem",
+ 512,
+ PNY,
+ table_of(vec![blocks_partition(
+ LINUX,
+ 4,
+ 2048,
+ 104_859_647,
+ "Linux filesystem",
+ )]),
+ Box::new(standard),
+ ),
+ (
+ "parted, empty",
+ 512,
+ EVO,
+ table_of(Vec::new()),
+ Box::new(standard),
+ ),
+ (
+ "parted, an ESP",
+ 512,
+ EVO,
+ table_of(vec![blocks_partition(ESP, 5, 2048, 1_050_623, "ESP")]),
+ Box::new(standard),
+ ),
+ // diskutil: a 200 MiB ESP from LBA 40, the container after it, on
+ // no MiB boundary.
+ (
+ "macOS, an ESP and an APFS container",
+ 512,
+ EVO,
+ table_of(vec![
+ blocks_partition(ESP, 6, 40, 409_639, "EFI System Partition"),
+ blocks_partition(APFS, 7, 409_640, 409_640 + 200 * GIB / 512 - 1, ""),
+ ]),
+ Box::new(standard),
+ ),
+ (
+ "fdisk, empty",
+ 512,
+ PNY,
+ table_of(Vec::new()),
+ Box::new(fdisk(512)),
+ ),
+ (
+ "fdisk, empty, 4096-byte blocks",
+ 4096,
+ BYTES / 4096,
+ table_of(Vec::new()),
+ Box::new(fdisk(4096)),
+ ),
+ (
+ "fdisk, a Linux filesystem",
+ 512,
+ EVO,
+ table_of(vec![blocks_partition(
+ LINUX,
+ 8,
+ 2048,
+ 2048 + 50 * GIB / 512 - 1,
+ "",
+ )]),
+ Box::new(fdisk(512)),
+ ),
+ // Usable blocks from any block past encode's, and to any before.
+ (
+ "usable from LBA 40",
+ 512,
+ PNY,
+ table_of(Vec::new()),
+ Box::new(|_: u64, header: &mut [u8]| relabel(header, 40, &40u64.to_le_bytes())),
+ ),
+ ];
+ for (what, block, blocks, table, edit) in cases {
+ let disk = Sparse::laid_out(block, blocks, &table, edit);
+ let (first, last) = usable_of(&disk);
+ assert!(first >= 2 + 16384 / block && last == blocks - 2 - 16384 / block);
+ installs_beside(disk, what);
+ }
+}
+
+#[test]
+fn layouts_a_rewrite_does_not_keep_are_refused_naming_the_field() {
+ let table = pny();
+ let last = PNY - 1;
+ let mut clean = Sparse::laid_out(512, PNY, &table, fdisk(512));
+ let read = gpt::read(&mut clean).unwrap();
+ let place = free_after(&clean, &read);
+ let whole = planned(&clean, &read, place, Mode::Install);
+ let exactly = |field, found, kept| shared::Unkept::Field {
+ field,
+ found,
+ kept: shared::Kept::Exactly(kept),
+ };
+ type Edit = fn(u64, &mut [u8]);
+ let cases: [(Edit, u64, shared::Unkept); 10] = [
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 80, &64u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("entry count", 64, 128),
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 80, &256u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("entry count", 256, 128),
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 84, &256u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("entry size", 256, 128),
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 72, &3u64.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("entry array LBA", 3, 2),
+ ),
+ // Cloned from a smaller disk.
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 32, &488_000_000u64.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("other copy's LBA", 488_000_000, PNY - 1),
+ ),
+ (
+ |_, h| relabel(h, 40, &33u64.to_le_bytes()),
+ 1,
+ shared::Unkept::Field {
+ field: "first usable LBA",
+ found: 33,
+ kept: shared::Kept::AtLeast(34),
+ },
+ ),
+ // Over the backup entries.
+ (
+ |_, h| relabel(h, 48, &488_397_135u64.to_le_bytes()),
+ 1,
+ shared::Unkept::Field {
+ field: "last usable LBA",
+ found: 488_397_135,
+ kept: shared::Kept::AtMost(488_397_134),
+ },
+ ),
+ (
+ |lba, h| {
+ if lba == 1 {
+ relabel(h, 12, &96u32.to_le_bytes())
+ }
+ },
+ 1,
+ exactly("header size", 96, 92),
+ ),
+ (
+ |lba, h| {
+ if lba != 1 {
+ relabel(h, 72, &(lba - 33).to_le_bytes())
+ }
+ },
+ last,
+ exactly("entry array LBA", last - 33, last - 32),
+ ),
+ // The copies disagree: the primary from 1 MiB, the backup from 34.
+ (
+ |lba, h| {
+ if lba != 1 {
+ relabel(h, 40, &34u64.to_le_bytes())
+ }
+ },
+ last,
+ shared::Unkept::Disagree {
+ field: "first usable LBA",
+ primary: 2048,
+ backup: 34,
+ },
+ ),
+ ];
+ for (index, (edit, lba, why)) in cases.into_iter().enumerate() {
+ let mut disk = Sparse::laid_out(512, PNY, &table, |lba, header: &mut [u8]| {
+ fdisk(512)(lba, header);
+ edit(lba, header);
+ });
+ let ends = disk.ends();
+ assert_eq!(
+ plan(&decision(&disk, &ends, Some(&read), place), &mut || guid(
+ NEW
+ )),
+ Err(PlanError::Layout { lba, why }),
+ "{index}"
+ );
+ // A plan made anyway is refused before anything is written, a
+ // check and an install alike.
+ let refused = Err(ApplyError {
+ step: Step::Check,
+ lba: Some(lba),
+ cause: Cause::Layout(why),
+ });
+ let made = as_read(&whole, &disk);
+ assert_eq!(made.apply(&mut disk), refused, "{index}");
+ let check = Plan {
+ mode: Mode::Check,
+ ..made
+ };
+ assert_eq!(checked(&check, &mut disk).0.map(drop), refused.map(drop));
+ assert_eq!(disk.done, [], "{index}");
+ }
+ // The stop names the field and both values.
+ let mut disk = Sparse::laid_out(512, PNY, &table, |_, header: &mut [u8]| {
+ relabel(header, 40, &33u64.to_le_bytes())
+ });
+ assert_eq!(
+ as_read(&whole, &disk)
+ .apply(&mut disk)
+ .unwrap_err()
+ .to_string(),
+ "checking the plan against the disk at block 1: a GPT header names another layout than \
+ the one a rewrite keeps: its first usable LBA is 33, where a rewrite keeps 34 or more"
+ );
+ let ends = disk.ends();
+ assert_eq!(
+ plan(&decision(&disk, &ends, Some(&read), place), &mut || guid(
+ NEW
+ ))
+ .unwrap_err()
+ .to_string(),
+ "the disk's partition table at block 1 is not added to: a GPT header names another \
+ layout than the one a rewrite keeps: its first usable LBA is 33, where a rewrite keeps \
+ 34 or more"
+ );
+}
+
+#[test]
+fn a_disk_whose_partitions_overlap_is_not_written() {
+ let table = table_of(vec![
+ blocks_partition(LINUX, 1, 2048, 103_426_047, ""),
+ blocks_partition(ESP, 2, 103_426_000, 107_620_351, ""),
+ ]);
+ let mut disk = Sparse::laid_out(512, PNY, &table, fdisk(512));
+ let read = gpt::read(&mut disk).unwrap();
+ let made = planned(&disk, &read, free_after(&disk, &read), Mode::Install);
+ assert_eq!(
+ made.apply(&mut disk),
+ Err(ApplyError {
+ step: Step::Check,
+ lba: Some(2),
+ cause: Cause::Copies("two of the disk's partitions overlap"),
+ })
+ );
+ assert_eq!(disk.done, []);
+}
+
+#[test]
+fn a_partition_past_a_narrowed_last_usable_is_not_written() {
+ let table = pny();
+ let narrowed = PNY - 34 - 2048;
+ let edit = |lba: u64, header: &mut [u8]| {
+ fdisk(512)(lba, header);
+ relabel(header, 48, &narrowed.to_le_bytes());
+ };
+ let mut disk = Sparse::laid_out(512, PNY, &table, edit);
+ assert_eq!(usable_of(&disk), (2048, narrowed));
+ let read = gpt::read(&mut disk).unwrap();
+ // To the geometry's last MiB, past the header's last usable block.
+ let wide = Place::Free {
+ first_lba: 107_620_352,
+ bytes: 380_776_448 * 512,
+ };
+ let ends = disk.ends();
+ assert_eq!(
+ plan(&decision(&disk, &ends, Some(&read), wide), &mut || guid(
+ NEW
+ )),
+ Err(PlanError::Table("partition outside the usable range"))
+ );
+ // A plan made anyway, from the disk before its usable blocks were
+ // narrowed, is refused by the check.
+ let clean = Sparse::laid_out(512, PNY, &table, fdisk(512));
+ let made = as_read(&planned(&clean, &read, wide, Mode::Install), &disk);
+ assert_eq!(
+ made.apply(&mut disk),
+ Err(error(
+ Step::Check,
+ Some(107_620_352),
+ Cause::Refused("the macOS partition lies outside the blocks the GPT gives partitions"),
+ ))
+ );
+ assert_eq!(disk.done, []);
+ // The free space within them takes macOS.
+ let made = installs_beside(
+ Sparse::laid_out(512, PNY, &table, edit),
+ "a narrowed last usable LBA",
+ );
+ assert!(made.partition.first_lba + made.partition.blocks - 1 <= narrowed);
+}