use crate::bytes::{get_arr, get_u8, get_u16, get_u32, put_arr, put_u8, put_u16, put_u32};
use super::ParseError;
pub const BOOT_SIGNATURE: u16 = 0xAA55;
pub const EXTENDED_BOOT_SIGNATURE: u8 = 0x29;
pub const FSINFO_LEAD_SIGNATURE: u32 = 0x4161_5252;
pub const FSINFO_STRUCT_SIGNATURE: u32 = 0x6141_7272;
pub const FSINFO_TRAIL_SIGNATURE: u32 = 0xAA55_0000;
const FSINFO_UNKNOWN: u32 = 0xFFFF_FFFF;
pub const VOLUME_DIRTY: u8 = 0x01;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct VolumeInfo {
pub drive_number: u8,
pub reserved: u8,
pub ext_boot_signature: u8,
pub volume_id: u32,
pub label: [u8; 11],
pub fs_type: [u8; 8],
}
impl VolumeInfo {
pub const SIZE: usize = 26;
pub const NO_NAME: [u8; 11] = *b"NO NAME ";
fn read_at(buf: &[u8], off: usize) -> Self {
Self {
drive_number: get_u8(buf, off),
reserved: get_u8(buf, off + 1),
ext_boot_signature: get_u8(buf, off + 2),
volume_id: get_u32(buf, off + 3),
label: get_arr::<11>(buf, off + 7),
fs_type: get_arr::<8>(buf, off + 18),
}
}
fn write_at(&self, buf: &mut [u8], off: usize) {
put_u8(buf, off, self.drive_number);
put_u8(buf, off + 1, self.reserved);
put_u8(buf, off + 2, self.ext_boot_signature);
put_u32(buf, off + 3, self.volume_id);
put_arr(buf, off + 7, &self.label);
put_arr(buf, off + 18, &self.fs_type);
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Fat32Params {
pub fat_sectors: u32,
pub ext_flags: u16,
pub version: u16,
pub root_cluster: u32,
pub fs_info_sector: u16,
pub backup_boot_sector: u16,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BootSectorTail {
Fat1216 {
volume: VolumeInfo,
},
Fat32 {
params: Fat32Params,
volume: VolumeInfo,
},
}
impl BootSectorTail {
#[must_use]
pub const fn volume(&self) -> &VolumeInfo {
match self {
BootSectorTail::Fat1216 { volume } | BootSectorTail::Fat32 { volume, .. } => volume,
}
}
#[must_use]
pub const fn volume_offset(&self) -> usize {
match self {
BootSectorTail::Fat1216 { .. } => 36,
BootSectorTail::Fat32 { .. } => 64,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct BootSector {
pub jump: [u8; 3],
pub oem_name: [u8; 8],
pub bytes_per_sector: u16,
pub sectors_per_cluster: u8,
pub reserved_sectors: u16,
pub fats: u8,
pub root_entries: u16,
pub total_sectors_16: u16,
pub media: u8,
pub fat_sectors_16: u16,
pub sectors_per_track: u16,
pub heads: u16,
pub hidden_sectors: u32,
pub total_sectors_32: u32,
pub tail: BootSectorTail,
}
impl BootSector {
pub const SIZE: usize = 512;
pub const SIGNATURE_OFFSET: usize = 510;
#[must_use]
pub fn total_sectors(&self) -> u32 {
if self.total_sectors_16 != 0 {
u32::from(self.total_sectors_16)
} else {
self.total_sectors_32
}
}
#[must_use]
pub fn fat_sectors(&self) -> u32 {
if self.fat_sectors_16 != 0 {
u32::from(self.fat_sectors_16)
} else {
match self.tail {
BootSectorTail::Fat1216 { .. } => 0,
BootSectorTail::Fat32 { params, .. } => params.fat_sectors,
}
}
}
pub fn read_from(buf: &[u8]) -> Result<Self, ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "boot sector",
need: Self::SIZE,
got: buf.len(),
});
}
let fat_sectors_16 = get_u16(buf, 22);
let tail = if fat_sectors_16 == 0 {
BootSectorTail::Fat32 {
params: Fat32Params {
fat_sectors: get_u32(buf, 36),
ext_flags: get_u16(buf, 40),
version: get_u16(buf, 42),
root_cluster: get_u32(buf, 44),
fs_info_sector: get_u16(buf, 48),
backup_boot_sector: get_u16(buf, 50),
},
volume: VolumeInfo::read_at(buf, 64),
}
} else {
BootSectorTail::Fat1216 {
volume: VolumeInfo::read_at(buf, 36),
}
};
Ok(Self {
jump: get_arr::<3>(buf, 0),
oem_name: get_arr::<8>(buf, 3),
bytes_per_sector: get_u16(buf, 11),
sectors_per_cluster: get_u8(buf, 13),
reserved_sectors: get_u16(buf, 14),
fats: get_u8(buf, 16),
root_entries: get_u16(buf, 17),
total_sectors_16: get_u16(buf, 19),
media: get_u8(buf, 21),
fat_sectors_16,
sectors_per_track: get_u16(buf, 24),
heads: get_u16(buf, 26),
hidden_sectors: get_u32(buf, 28),
total_sectors_32: get_u32(buf, 32),
tail,
})
}
pub fn write_to(&self, buf: &mut [u8]) -> Result<(), ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "boot sector",
need: Self::SIZE,
got: buf.len(),
});
}
put_arr(buf, 0, &self.jump);
put_arr(buf, 3, &self.oem_name);
put_u16(buf, 11, self.bytes_per_sector);
put_u8(buf, 13, self.sectors_per_cluster);
put_u16(buf, 14, self.reserved_sectors);
put_u8(buf, 16, self.fats);
put_u16(buf, 17, self.root_entries);
put_u16(buf, 19, self.total_sectors_16);
put_u8(buf, 21, self.media);
put_u16(buf, 22, self.fat_sectors_16);
put_u16(buf, 24, self.sectors_per_track);
put_u16(buf, 26, self.heads);
put_u32(buf, 28, self.hidden_sectors);
put_u32(buf, 32, self.total_sectors_32);
match self.tail {
BootSectorTail::Fat1216 { volume } => volume.write_at(buf, 36),
BootSectorTail::Fat32 { params, volume } => {
put_u32(buf, 36, params.fat_sectors);
put_u16(buf, 40, params.ext_flags);
put_u16(buf, 42, params.version);
put_u32(buf, 44, params.root_cluster);
put_u16(buf, 48, params.fs_info_sector);
put_u16(buf, 50, params.backup_boot_sector);
put_arr(buf, 52, &[0u8; 12]);
volume.write_at(buf, 64);
}
}
put_u16(buf, Self::SIGNATURE_OFFSET, BOOT_SIGNATURE);
Ok(())
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct FsInfo {
pub free_clusters: Option<u32>,
pub next_free_cluster: Option<u32>,
}
impl FsInfo {
pub const SIZE: usize = 512;
pub const TRAIL_OFFSET: usize = 508;
pub fn read_from(buf: &[u8]) -> Result<Self, ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "fsinfo sector",
need: Self::SIZE,
got: buf.len(),
});
}
for (off, expected) in [
(0usize, FSINFO_LEAD_SIGNATURE),
(484, FSINFO_STRUCT_SIGNATURE),
] {
let found = get_u32(buf, off);
if found != expected {
return Err(ParseError::BadMagic {
structure: "fsinfo sector",
found,
expected,
});
}
}
let known = |v: u32| (v != FSINFO_UNKNOWN).then_some(v);
Ok(Self {
free_clusters: known(get_u32(buf, 488)),
next_free_cluster: known(get_u32(buf, 492)),
})
}
pub fn write_to(&self, buf: &mut [u8]) -> Result<(), ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "fsinfo sector",
need: Self::SIZE,
got: buf.len(),
});
}
buf[..Self::SIZE].fill(0);
put_u32(buf, 0, FSINFO_LEAD_SIGNATURE);
put_u32(buf, 484, FSINFO_STRUCT_SIGNATURE);
put_u32(buf, 488, self.free_clusters.unwrap_or(FSINFO_UNKNOWN));
put_u32(buf, 492, self.next_free_cluster.unwrap_or(FSINFO_UNKNOWN));
put_u32(buf, Self::TRAIL_OFFSET, FSINFO_TRAIL_SIGNATURE);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn volume(fs_type: &[u8; 8]) -> VolumeInfo {
VolumeInfo {
drive_number: 0x80,
reserved: 0,
ext_boot_signature: EXTENDED_BOOT_SIGNATURE,
volume_id: 0x1234_abcd,
label: VolumeInfo::NO_NAME,
fs_type: *fs_type,
}
}
fn fat16() -> BootSector {
BootSector {
jump: [0xEB, 0x3C, 0x90],
oem_name: *b"ferrosys",
bytes_per_sector: 512,
sectors_per_cluster: 1,
reserved_sectors: 8,
fats: 2,
root_entries: 512,
total_sectors_16: 4160,
media: 0xF8,
fat_sectors_16: 17,
sectors_per_track: 32,
heads: 2,
hidden_sectors: 0,
total_sectors_32: 0,
tail: BootSectorTail::Fat1216 {
volume: volume(b"FAT16 "),
},
}
}
fn fat32() -> BootSector {
BootSector {
jump: [0xEB, 0x58, 0x90],
oem_name: *b"ferrosys",
bytes_per_sector: 512,
sectors_per_cluster: 1,
reserved_sectors: 32,
fats: 2,
root_entries: 0,
total_sectors_16: 0,
media: 0xF8,
fat_sectors_16: 0,
sectors_per_track: 32,
heads: 16,
hidden_sectors: 0,
total_sectors_32: 524_288,
tail: BootSectorTail::Fat32 {
params: Fat32Params {
fat_sectors: 4033,
ext_flags: 0,
version: 0,
root_cluster: 2,
fs_info_sector: 1,
backup_boot_sector: 6,
},
volume: volume(b"FAT32 "),
},
}
}
#[test]
fn a_boot_sector_round_trips_on_both_tails() {
for original in [fat16(), fat32()] {
let mut buf = [0u8; BootSector::SIZE];
original.write_to(&mut buf).expect("write");
assert_eq!(BootSector::read_from(&buf).expect("read"), original);
}
}
#[test]
fn the_tail_written_is_the_tail_read_back() {
let mut buf = [0u8; BootSector::SIZE];
fat32().write_to(&mut buf).expect("write");
assert_eq!(&buf[64 + 7..64 + 18], &VolumeInfo::NO_NAME);
assert_eq!(
u32::from_le_bytes([buf[67], buf[68], buf[69], buf[70]]),
0x1234_abcd
);
buf.fill(0);
fat16().write_to(&mut buf).expect("write");
assert_eq!(&buf[36 + 7..36 + 18], &VolumeInfo::NO_NAME);
}
#[test]
fn the_field_offsets_are_where_the_format_puts_them() {
let mut buf = [0u8; BootSector::SIZE];
fat32().write_to(&mut buf).expect("write");
assert_eq!(&buf[0..3], &[0xEB, 0x58, 0x90]);
assert_eq!(&buf[3..11], b"ferrosys");
assert_eq!(u16::from_le_bytes([buf[11], buf[12]]), 512);
assert_eq!(buf[13], 1);
assert_eq!(u16::from_le_bytes([buf[14], buf[15]]), 32);
assert_eq!(buf[16], 2);
assert_eq!(u16::from_le_bytes([buf[17], buf[18]]), 0);
assert_eq!(buf[21], 0xF8);
assert_eq!(u16::from_le_bytes([buf[22], buf[23]]), 0);
assert_eq!(
u32::from_le_bytes([buf[32], buf[33], buf[34], buf[35]]),
524_288
);
assert_eq!(
u32::from_le_bytes([buf[36], buf[37], buf[38], buf[39]]),
4033
);
assert_eq!(u32::from_le_bytes([buf[44], buf[45], buf[46], buf[47]]), 2);
assert_eq!(u16::from_le_bytes([buf[48], buf[49]]), 1);
assert_eq!(u16::from_le_bytes([buf[50], buf[51]]), 6);
assert_eq!(&buf[52..64], &[0u8; 12]);
assert_eq!(u16::from_le_bytes([buf[510], buf[511]]), BOOT_SIGNATURE);
}
#[test]
fn writing_leaves_the_boot_code_alone() {
let mut buf = [0x5Au8; BootSector::SIZE];
fat32().write_to(&mut buf).expect("write");
assert!(buf[90..510].iter().all(|&b| b == 0x5A));
let mut buf = [0x5Au8; BootSector::SIZE];
fat16().write_to(&mut buf).expect("write");
assert!(buf[62..510].iter().all(|&b| b == 0x5A));
}
#[test]
fn a_short_buffer_is_refused_rather_than_indexed() {
let mut buf = [0u8; BootSector::SIZE - 1];
assert!(matches!(
BootSector::read_from(&buf),
Err(ParseError::TooShort { .. })
));
assert!(matches!(
fat16().write_to(&mut buf),
Err(ParseError::TooShort { .. })
));
assert!(matches!(
FsInfo::read_from(&buf),
Err(ParseError::TooShort { .. })
));
}
#[test]
fn either_total_sector_field_answers_the_same_question() {
let mut small = fat32();
small.total_sectors_16 = 4160;
small.total_sectors_32 = 0;
assert_eq!(small.total_sectors(), 4160);
assert_eq!(fat32().total_sectors(), 524_288);
assert_eq!(fat32().fat_sectors(), 4033);
assert_eq!(fat16().fat_sectors(), 17);
}
#[test]
fn an_information_sector_round_trips_including_its_sentinels() {
for original in [
FsInfo {
free_clusters: Some(516_189),
next_free_cluster: Some(3),
},
FsInfo {
free_clusters: None,
next_free_cluster: None,
},
] {
let mut buf = [0xA5u8; FsInfo::SIZE];
original.write_to(&mut buf).expect("write");
assert_eq!(FsInfo::read_from(&buf).expect("read"), original);
}
}
#[test]
fn an_information_sector_writes_its_three_signatures() {
let mut buf = [0xA5u8; FsInfo::SIZE];
FsInfo {
free_clusters: None,
next_free_cluster: None,
}
.write_to(&mut buf)
.expect("write");
assert_eq!(
u32::from_le_bytes(buf[0..4].try_into().unwrap()),
FSINFO_LEAD_SIGNATURE
);
assert_eq!(
u32::from_le_bytes(buf[484..488].try_into().unwrap()),
FSINFO_STRUCT_SIGNATURE
);
assert_eq!(
u32::from_le_bytes(buf[508..512].try_into().unwrap()),
FSINFO_TRAIL_SIGNATURE
);
assert!(buf[4..484].iter().all(|&b| b == 0));
assert!(buf[496..508].iter().all(|&b| b == 0));
}
#[test]
fn an_information_sector_without_its_signatures_is_refused() {
let mut buf = [0u8; FsInfo::SIZE];
FsInfo {
free_clusters: Some(1),
next_free_cluster: Some(2),
}
.write_to(&mut buf)
.expect("write");
for off in [0usize, 484] {
let mut damaged = buf;
damaged[off] ^= 0xFF;
assert!(matches!(
FsInfo::read_from(&damaged),
Err(ParseError::BadMagic { .. })
));
}
}
}