use crate::bytes::{
get_arr, get_u8, get_u16, get_u32, get_u64, put_arr, put_u8, put_u16, put_u32, put_u64,
};
use super::ParseError;
pub const FILE_SYSTEM_NAME: [u8; 8] = *b"EXFAT ";
pub const MUST_BE_ZERO_RANGE: core::ops::Range<usize> = 11..64;
pub const BOOT_SIGNATURE: u16 = 0xAA55;
pub const EXTENDED_BOOT_SIGNATURE: u32 = 0xAA55_0000;
pub const FILE_SYSTEM_REVISION: u16 = 0x0100;
pub const FILE_SYSTEM_MAJOR_REVISION: u8 = (FILE_SYSTEM_REVISION >> 8) as u8;
pub const FILE_SYSTEM_MINOR_REVISION: u8 = FILE_SYSTEM_REVISION as u8;
pub const BOOT_REGION_SECTORS: u64 = 12;
pub const EXTENDED_BOOT_FIRST_SECTOR: u64 = 1;
pub const EXTENDED_BOOT_SECTORS: u64 = 8;
pub const OEM_PARAMETERS_SECTOR: u64 = 9;
pub const RESERVED_SECTOR: u64 = 10;
pub const CHECKSUM_SECTOR: u64 = 11;
pub const MAIN_BOOT_REGION_SECTOR: u64 = 0;
pub const BACKUP_BOOT_REGION_SECTOR: u64 = BOOT_REGION_SECTORS;
pub const VOLUME_FLAG_ACTIVE_FAT: u16 = 0x0001;
pub const VOLUME_FLAG_VOLUME_DIRTY: u16 = 0x0002;
pub const VOLUME_FLAG_MEDIA_FAILURE: u16 = 0x0004;
pub const VOLUME_FLAG_CLEAR_TO_ZERO: u16 = 0x0008;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct MainBootSector {
pub jump_boot: [u8; 3],
pub file_system_name: [u8; 8],
pub partition_offset: u64,
pub volume_length: u64,
pub fat_offset: u32,
pub fat_length: u32,
pub cluster_heap_offset: u32,
pub cluster_count: u32,
pub first_cluster_of_root: u32,
pub volume_serial: u32,
pub file_system_revision: u16,
pub volume_flags: u16,
pub bytes_per_sector_shift: u8,
pub sectors_per_cluster_shift: u8,
pub number_of_fats: u8,
pub drive_select: u8,
pub percent_in_use: u8,
pub boot_code: [u8; BOOT_CODE_LEN],
}
pub const BOOT_CODE_LEN: usize = 390;
impl MainBootSector {
pub const SIZE: usize = 512;
pub const JUMP_BOOT: [u8; 3] = [0xEB, 0x76, 0x90];
pub fn read_from(buf: &[u8]) -> Result<Self, ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "exFAT main boot sector",
need: Self::SIZE,
got: buf.len(),
});
}
let name = get_arr::<8>(buf, 3);
if name != FILE_SYSTEM_NAME {
return Err(ParseError::BadMagic {
structure: "exFAT main boot sector: FileSystemName",
found: get_u32(buf, 3),
expected: u32::from_le_bytes([
FILE_SYSTEM_NAME[0],
FILE_SYSTEM_NAME[1],
FILE_SYSTEM_NAME[2],
FILE_SYSTEM_NAME[3],
]),
});
}
if let Some(at) = buf[MUST_BE_ZERO_RANGE].iter().position(|b| *b != 0) {
return Err(ParseError::BadMagic {
structure: "exFAT main boot sector: MustBeZero",
found: u32::from(buf[MUST_BE_ZERO_RANGE.start + at]),
expected: 0,
});
}
let signature = get_u16(buf, 510);
if signature != BOOT_SIGNATURE {
return Err(ParseError::BadMagic {
structure: "exFAT main boot sector: BootSignature",
found: u32::from(signature),
expected: u32::from(BOOT_SIGNATURE),
});
}
Ok(Self {
jump_boot: get_arr::<3>(buf, 0),
file_system_name: name,
partition_offset: get_u64(buf, 64),
volume_length: get_u64(buf, 72),
fat_offset: get_u32(buf, 80),
fat_length: get_u32(buf, 84),
cluster_heap_offset: get_u32(buf, 88),
cluster_count: get_u32(buf, 92),
first_cluster_of_root: get_u32(buf, 96),
volume_serial: get_u32(buf, 100),
file_system_revision: get_u16(buf, 104),
volume_flags: get_u16(buf, 106),
bytes_per_sector_shift: get_u8(buf, 108),
sectors_per_cluster_shift: get_u8(buf, 109),
number_of_fats: get_u8(buf, 110),
drive_select: get_u8(buf, 111),
percent_in_use: get_u8(buf, 112),
boot_code: get_arr::<BOOT_CODE_LEN>(buf, 120),
})
}
pub fn write_to(&self, buf: &mut [u8]) -> Result<(), ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "exFAT main boot sector",
need: Self::SIZE,
got: buf.len(),
});
}
put_arr(buf, 0, &self.jump_boot);
put_arr(buf, 3, &self.file_system_name);
buf[MUST_BE_ZERO_RANGE].fill(0);
put_u64(buf, 64, self.partition_offset);
put_u64(buf, 72, self.volume_length);
put_u32(buf, 80, self.fat_offset);
put_u32(buf, 84, self.fat_length);
put_u32(buf, 88, self.cluster_heap_offset);
put_u32(buf, 92, self.cluster_count);
put_u32(buf, 96, self.first_cluster_of_root);
put_u32(buf, 100, self.volume_serial);
put_u16(buf, 104, self.file_system_revision);
put_u16(buf, 106, self.volume_flags);
put_u8(buf, 108, self.bytes_per_sector_shift);
put_u8(buf, 109, self.sectors_per_cluster_shift);
put_u8(buf, 110, self.number_of_fats);
put_u8(buf, 111, self.drive_select);
put_u8(buf, 112, self.percent_in_use);
buf[113..120].fill(0);
put_arr(buf, 120, &self.boot_code);
put_u16(buf, 510, BOOT_SIGNATURE);
Ok(())
}
#[must_use]
pub const fn major_revision(&self) -> u8 {
(self.file_system_revision >> 8) as u8
}
#[must_use]
pub const fn minor_revision(&self) -> u8 {
self.file_system_revision as u8
}
#[must_use]
pub const fn bytes_per_sector(&self) -> Option<u32> {
match self.bytes_per_sector_shift {
9..=12 => Some(1 << self.bytes_per_sector_shift),
_ => None,
}
}
#[must_use]
pub const fn bytes_per_cluster(&self) -> Option<u32> {
let Some(sector) = self.bytes_per_sector() else {
return None;
};
let Some(shift) = self
.bytes_per_sector_shift
.checked_add(self.sectors_per_cluster_shift)
else {
return None;
};
if shift > MAX_CLUSTER_SHIFT {
return None;
}
Some(sector << self.sectors_per_cluster_shift)
}
}
pub const MAX_CLUSTER_SHIFT: u8 = 25;
pub const PERCENT_IN_USE_UNKNOWN: u8 = 0xFF;
pub const PERCENT_IN_USE_MAX: u8 = 100;
#[must_use]
pub const fn percent_in_use(used: u32, total: u32) -> u8 {
if total == 0 {
return 0;
}
let percent = used as u64 * 100 / total as u64;
if percent > 100 {
100
} else {
percent as u8
}
}
pub fn write_extended_boot_sector(sector: &mut [u8]) {
sector.fill(0);
let at = sector.len() - 4;
put_u32(sector, at, EXTENDED_BOOT_SIGNATURE);
}
#[must_use]
pub fn extended_boot_signature(sector: &[u8]) -> Option<u32> {
let at = sector.len().checked_sub(4)?;
Some(get_u32(sector, at))
}
pub fn write_checksum_sector(sector: &mut [u8], checksum: u32) {
let (words, rest) = sector.as_chunks_mut::<4>();
assert!(
rest.is_empty(),
"a sector is a whole number of four-byte words"
);
let word = checksum.to_le_bytes();
for at in words {
*at = word;
}
}
#[must_use]
pub fn checksum_sector_value(sector: &[u8]) -> Option<u32> {
let (words, rest) = sector.as_chunks::<4>();
let (first, others) = words.split_first()?;
if !rest.is_empty() || others.iter().any(|w| w != first) {
return None;
}
Some(get_u32(first, 0))
}
#[cfg(test)]
mod tests {
use super::*;
fn filled() -> MainBootSector {
MainBootSector {
jump_boot: MainBootSector::JUMP_BOOT,
file_system_name: FILE_SYSTEM_NAME,
partition_offset: 0x0011_2233_4455_6677,
volume_length: 0x0000_0001_0000_0002,
fat_offset: 2048,
fat_length: 62,
cluster_heap_offset: 4096,
cluster_count: 7680,
first_cluster_of_root: 5,
volume_serial: 0x1234_5678,
file_system_revision: FILE_SYSTEM_REVISION,
volume_flags: VOLUME_FLAG_VOLUME_DIRTY,
bytes_per_sector_shift: 9,
sectors_per_cluster_shift: 3,
number_of_fats: 1,
drive_select: 0x80,
percent_in_use: 42,
boot_code: [0x5A; 390],
}
}
#[test]
fn a_boot_sector_round_trips() {
let mut buf = [0u8; MainBootSector::SIZE];
let boot = filled();
boot.write_to(&mut buf).expect("write");
assert_eq!(MainBootSector::read_from(&buf).expect("read"), boot);
}
#[test]
fn every_field_lands_at_the_offset_the_format_defines() {
let mut buf = [0u8; MainBootSector::SIZE];
filled().write_to(&mut buf).expect("write");
assert_eq!(&buf[0..3], &[0xEB, 0x76, 0x90]);
assert_eq!(&buf[3..11], b"EXFAT ");
assert_eq!(&buf[64..72], &0x0011_2233_4455_6677u64.to_le_bytes());
assert_eq!(&buf[72..80], &0x0000_0001_0000_0002u64.to_le_bytes());
assert_eq!(&buf[80..84], &2048u32.to_le_bytes());
assert_eq!(&buf[84..88], &62u32.to_le_bytes());
assert_eq!(&buf[88..92], &4096u32.to_le_bytes());
assert_eq!(&buf[92..96], &7680u32.to_le_bytes());
assert_eq!(&buf[96..100], &5u32.to_le_bytes());
assert_eq!(&buf[100..104], &0x1234_5678u32.to_le_bytes());
assert_eq!(&buf[104..106], &[0x00, 0x01]);
assert_eq!(&buf[106..108], &2u16.to_le_bytes());
assert_eq!(buf[108], 9);
assert_eq!(buf[109], 3);
assert_eq!(buf[110], 1);
assert_eq!(buf[111], 0x80);
assert_eq!(buf[112], 42);
assert_eq!(&buf[120..510], &[0x5A; 390]);
assert_eq!(&buf[510..512], &BOOT_SIGNATURE.to_le_bytes());
}
#[test]
fn the_runs_the_format_requires_to_be_zero_are_written_zero() {
let mut buf = [0xFFu8; MainBootSector::SIZE];
filled().write_to(&mut buf).expect("write");
assert!(buf[MUST_BE_ZERO_RANGE].iter().all(|b| *b == 0));
assert!(buf[113..120].iter().all(|b| *b == 0));
}
#[test]
fn a_sector_missing_any_of_the_three_fixed_values_is_refused() {
let mut buf = [0u8; MainBootSector::SIZE];
filled().write_to(&mut buf).expect("write");
let mut no_name = buf;
no_name[3] = b'F';
assert!(matches!(
MainBootSector::read_from(&no_name),
Err(ParseError::BadMagic { .. })
));
let mut no_signature = buf;
no_signature[510] = 0;
assert!(matches!(
MainBootSector::read_from(&no_signature),
Err(ParseError::BadMagic { .. })
));
assert!(matches!(
MainBootSector::read_from(&buf[..511]),
Err(ParseError::TooShort { .. })
));
}
#[test]
fn a_sector_whose_must_be_zero_run_is_not_zero_is_refused_at_the_byte_that_is_not() {
let mut buf = [0u8; MainBootSector::SIZE];
filled().write_to(&mut buf).expect("write");
assert!(MainBootSector::read_from(&buf).is_ok());
for at in [MUST_BE_ZERO_RANGE.start, 30, MUST_BE_ZERO_RANGE.end - 1] {
let mut spoiled = buf;
spoiled[at] = 0x02;
let err = MainBootSector::read_from(&spoiled)
.expect_err("a non-zero byte in the run is refused");
let ParseError::BadMagic {
found, expected, ..
} = err
else {
panic!("expected a bad-signature refusal at {at}, got {err:?}");
};
assert_eq!((found, expected), (2, 0), "at {at}");
}
}
#[test]
fn a_fat_boot_sector_whose_oem_name_spells_this_format_is_refused() {
let mut fat = [0u8; MainBootSector::SIZE];
fat[0..3].copy_from_slice(&[0xEB, 0x3C, 0x90]);
fat[3..11].copy_from_slice(b"EXFAT ");
fat[11..13].copy_from_slice(&512u16.to_le_bytes()); fat[13] = 8; fat[14..16].copy_from_slice(&1u16.to_le_bytes()); fat[16] = 2; fat[21] = 0xF8; fat[510..512].copy_from_slice(&BOOT_SIGNATURE.to_le_bytes());
assert!(
matches!(
MainBootSector::read_from(&fat),
Err(ParseError::BadMagic { .. })
),
"a FAT boot sector spelling this magic must not parse as one of these"
);
}
#[test]
fn the_two_shifts_answer_only_within_the_ranges_the_format_defines() {
let mut boot = filled();
for (shift, want) in [(9u8, Some(512u32)), (12, Some(4096)), (8, None), (13, None)] {
boot.bytes_per_sector_shift = shift;
assert_eq!(boot.bytes_per_sector(), want, "shift {shift}");
}
boot.bytes_per_sector_shift = 9;
boot.sectors_per_cluster_shift = 16;
assert_eq!(boot.bytes_per_cluster(), Some(32 << 20));
boot.sectors_per_cluster_shift = 17;
assert_eq!(boot.bytes_per_cluster(), None);
boot.bytes_per_sector_shift = 12;
boot.sectors_per_cluster_shift = 13;
assert_eq!(boot.bytes_per_cluster(), Some(32 << 20));
boot.sectors_per_cluster_shift = 14;
assert_eq!(boot.bytes_per_cluster(), None);
for shift in [u8::MAX, u8::MAX - 12, 244, 200] {
boot.sectors_per_cluster_shift = shift;
assert_eq!(boot.bytes_per_cluster(), None, "cluster shift {shift}");
}
}
#[test]
fn an_extended_boot_sector_carries_its_signature_at_its_own_end() {
for size in [512usize, 4096] {
let mut sector = vec![0xFFu8; size];
write_extended_boot_sector(&mut sector);
assert_eq!(
extended_boot_signature(§or),
Some(EXTENDED_BOOT_SIGNATURE)
);
assert_eq!(§or[size - 4..], &[0x00, 0x00, 0x55, 0xAA]);
assert!(sector[..size - 4].iter().all(|b| *b == 0));
}
assert_eq!(extended_boot_signature(&[0u8; 3]), None);
}
#[test]
fn a_checksum_sector_repeats_its_value_and_is_read_back_only_when_it_does() {
for size in [512usize, 4096] {
let mut sector = vec![0u8; size];
write_checksum_sector(&mut sector, 0xDEAD_BEEF);
assert!(
sector
.as_chunks::<4>()
.0
.iter()
.all(|w| *w == 0xDEAD_BEEFu32.to_le_bytes())
);
assert_eq!(checksum_sector_value(§or), Some(0xDEAD_BEEF));
sector[size - 1] ^= 0x01;
assert_eq!(checksum_sector_value(§or), None);
}
assert_eq!(checksum_sector_value(&[]), None);
}
#[test]
#[should_panic(expected = "a sector is a whole number of four-byte words")]
fn a_checksum_sector_that_is_not_whole_words_is_refused_by_the_writer() {
write_checksum_sector(&mut [0u8; 510], 0xDEAD_BEEF);
}
#[test]
fn a_checksum_sector_with_a_partial_word_has_no_value() {
let mut sector = [0u8; 18];
write_checksum_sector(&mut sector[..16], 0xDEAD_BEEF);
assert_eq!(checksum_sector_value(§or[..16]), Some(0xDEAD_BEEF));
assert_eq!(checksum_sector_value(§or), None);
}
}