git clone https://garage44.eu/jeroen/pinnacle.git.. /disk/src/fat.rs
//! FAT32 (Microsoft's FAT specification, 1.03), as far as a boot partition
//! needs it: [`format`] makes one holding the files given, laid out one
//! after another; [`read_file`] reads a file back from one, any FAT32 a
//! firmware or another system made. Names are 8.3, upper case, as UEFI's
//! own paths (`EFI/BOOT/BOOTX64.EFI`) are; long names are skipped when
//! read and never written.
use crate::{Medium, u16_at, u32_at};
use alloc::vec;
use alloc::vec::Vec;
const SECTOR: u64 = 512;
const SECTORS_PER_CLUSTER: u64 = 8;
const CLUSTER: u64 = SECTOR * SECTORS_PER_CLUSTER;
const RESERVED: u64 = 32;
const FATS: u64 = 2;
/// Fewer clusters than this make a FAT16 by the specification's rule.
const MIN_CLUSTERS: u64 = 65_525;
const END_OF_CHAIN: u32 = 0x0fff_ffff;
const ATTR_DIRECTORY: u8 = 0x10;
const ATTR_ARCHIVE: u8 = 0x20;
const ATTR_VOLUME: u8 = 0x08;
const ATTR_LONG_NAME: u8 = 0x0f;
/// 2026-01-01, the date every entry is written with: a boot partition's
/// files need no history.
const DATE: u16 = (2026 - 1980) << 9 | 1 << 5 | 1;
/// The smallest partition [`format`] makes a FAT32 of, in bytes.
pub fn min_size() -> u64 {
// Each FAT of that many clusters takes 513 sectors; 1024 leaves room.
(RESERVED + MIN_CLUSTERS * SECTORS_PER_CLUSTER + FATS * 1024) * SECTOR
}
/// An 8.3 name as a directory entry holds it, or None when `name` is not
/// one (too long, a character FAT does not allow, lower case).
fn short_name(name: &str) -> Option<[u8; 11]> {
let (base, ext) = name.split_once('.').unwrap_or((name, ""));
let allowed = |c: u8| c.is_ascii_uppercase() || c.is_ascii_digit() || b"_-~$!#%&".contains(&c);
if base.is_empty() || base.len() > 8 || ext.len() > 3 || !base.bytes().chain(ext.bytes()).all(allowed) {
return None;
}
let mut out = [b' '; 11];
out[..base.len()].copy_from_slice(base.as_bytes());
out[8..8 + ext.len()].copy_from_slice(ext.as_bytes());
Some(out)
}
/// A directory being laid out: its entries' names and what each is.
struct Dir {
name: [u8; 11],
parent: usize,
/// Subdirectories by index into the list of directories, and files by
/// index into those given.
dirs: Vec<usize>,
files: Vec<usize>,
cluster: u64,
clusters: u64,
}
fn entry(name: &[u8; 11], attr: u8, cluster: u64, size: u32) -> [u8; 32] {
let mut e = [0u8; 32];
e[..11].copy_from_slice(name);
e[11] = attr;
for at in [16, 18, 24] {
e[at..at + 2].copy_from_slice(&DATE.to_le_bytes());
}
e[20..22].copy_from_slice(&((cluster >> 16) as u16).to_le_bytes());
e[26..28].copy_from_slice(&(cluster as u16).to_le_bytes());
e[28..32].copy_from_slice(&size.to_le_bytes());
e
}
/// Makes the `size` bytes at `offset` a FAT32 named `label` (up to 11
/// characters) holding `files`, each a path of 8.3 names (`EFI/BOOT/BOOTX64.EFI`)
/// and its contents; the folders on their paths are made. What was there
/// before is gone.
pub fn format(
disk: &mut impl Medium,
offset: u64,
size: u64,
label: &str,
volume_id: u32,
files: &[(&str, &[u8])],
) -> Result<(), &'static str> {
let sizes: Vec<(&str, u64)> = files.iter().map(|(p, d)| (*p, d.len() as u64)).collect();
let mut at = vec![0usize; files.len()];
format_from(disk, offset, size, label, volume_id, &sizes, &mut |f, into| {
let data = files[f].1;
let Some(part) = data.get(at[f]..at[f] + into.len()) else {
return false;
};
into.copy_from_slice(part);
at[f] += into.len();
true
})
}
/// As [`format`], each file given as its path and size, its contents read
/// in order as they are written: `read(i, into)` fills `into` with the next
/// bytes of file `i`, false when it cannot. A file need not be in memory
/// whole (a kernel larger than the largest allocation a kernel makes).
pub fn format_from(
disk: &mut impl Medium,
offset: u64,
size: u64,
label: &str,
volume_id: u32,
files: &[(&str, u64)],
read: &mut dyn FnMut(usize, &mut [u8]) -> bool,
) -> Result<(), &'static str> {
if size < min_size() {
return Err("the partition is too small for FAT32");
}
let total = (size / SECTOR).min(u64::from(u32::MAX));
// The FAT's size, from an upper bound on the clusters it maps.
let fat_sectors = (((total - RESERVED) / SECTORS_PER_CLUSTER + 2) * 4).div_ceil(SECTOR);
let clusters = (total - RESERVED - FATS * fat_sectors) / SECTORS_PER_CLUSTER;
if clusters < MIN_CLUSTERS {
return Err("the partition is too small for FAT32");
}
// The folders, the root first, and which holds what.
let mut dirs = vec![Dir {
name: [b' '; 11],
parent: 0,
dirs: Vec::new(),
files: Vec::new(),
cluster: 0,
clusters: 0,
}];
for (i, (path, _)) in files.iter().enumerate() {
let mut parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();
let file = parts.pop().ok_or("an empty path")?;
short_name(file).ok_or("a name that is not 8.3 upper case")?;
let mut at = 0;
for part in parts {
let name = short_name(part).ok_or("a folder name that is not 8.3 upper case")?;
at = match dirs[at].dirs.iter().find(|&&d| dirs[d].name == name) {
Some(&d) => d,
None => {
dirs.push(Dir {
name,
parent: at,
dirs: Vec::new(),
files: Vec::new(),
cluster: 0,
clusters: 0,
});
let d = dirs.len() - 1;
dirs[at].dirs.push(d);
d
}
};
}
dirs[at].files.push(i);
}
// Clusters: the folders from 2 on, then each file's, one after another.
let mut next = 2u64;
for (i, d) in dirs.iter_mut().enumerate() {
// The volume label in the root, "." and ".." elsewhere.
let entries = d.dirs.len() + d.files.len() + if i == 0 { 1 } else { 2 };
d.cluster = next;
d.clusters = (entries as u64 * 32).div_ceil(CLUSTER).max(1);
next += d.clusters;
}
let mut file_clusters = Vec::with_capacity(files.len());
for &(_, len) in files {
if len > u64::from(u32::MAX) {
return Err("a file larger than FAT32 holds");
}
let n = len.div_ceil(CLUSTER);
file_clusters.push(if n == 0 { 0 } else { next });
next += n;
}
if next - 2 > clusters {
return Err("the files do not fit");
}
let fail = "a write to the disk failed";
// The reserved sectors: the boot sector, FSInfo, and their copies.
let mut reserved = vec![0u8; (RESERVED * SECTOR) as usize];
let boot = &mut reserved[..512];
boot[..3].copy_from_slice(&[0xeb, 0x58, 0x90]);
boot[3..11].copy_from_slice(b"PINNACLE");
boot[11..13].copy_from_slice(&(SECTOR as u16).to_le_bytes());
boot[13] = SECTORS_PER_CLUSTER as u8;
boot[14..16].copy_from_slice(&(RESERVED as u16).to_le_bytes());
boot[16] = FATS as u8;
boot[21] = 0xf8;
boot[24..26].copy_from_slice(&63u16.to_le_bytes());
boot[26..28].copy_from_slice(&255u16.to_le_bytes());
boot[28..32].copy_from_slice(&((offset / SECTOR) as u32).to_le_bytes());
boot[32..36].copy_from_slice(&(total as u32).to_le_bytes());
boot[36..40].copy_from_slice(&(fat_sectors as u32).to_le_bytes());
boot[44..48].copy_from_slice(&2u32.to_le_bytes());
boot[48..50].copy_from_slice(&1u16.to_le_bytes());
boot[50..52].copy_from_slice(&6u16.to_le_bytes());
boot[64] = 0x80;
boot[66] = 0x29;
boot[67..71].copy_from_slice(&volume_id.to_le_bytes());
let mut name = [b' '; 11];
for (n, c) in name.iter_mut().zip(label.bytes()) {
*n = c.to_ascii_uppercase();
}
boot[71..82].copy_from_slice(&name);
boot[82..90].copy_from_slice(b"FAT32 ");
boot[510] = 0x55;
boot[511] = 0xaa;
let info = &mut reserved[512..1024];
info[..4].copy_from_slice(&0x4161_5252u32.to_le_bytes());
info[484..488].copy_from_slice(&0x6141_7272u32.to_le_bytes());
info[488..492].copy_from_slice(&((clusters - (next - 2)) as u32).to_le_bytes());
info[492..496].copy_from_slice(&(next as u32).to_le_bytes());
info[508..512].copy_from_slice(&0xaa55_0000u32.to_le_bytes());
let (first, second) = reserved.split_at_mut(6 * 512);
second[..1024].copy_from_slice(&first[..1024]);
if !disk.write_at(offset, &reserved) {
return Err(fail);
}
// The FATs: each chain's clusters point to the next, the last ends it.
let mut chains: Vec<(u64, u64)> = dirs.iter().map(|d| (d.cluster, d.clusters)).collect();
for (&start, &(_, len)) in file_clusters.iter().zip(files) {
if start != 0 {
chains.push((start, len.div_ceil(CLUSTER)));
}
}
let fat_bytes = fat_sectors * SECTOR;
let chunk = 64 * 1024;
for copy in 0..FATS {
let base = offset + (RESERVED + copy * fat_sectors) * SECTOR;
let mut at = 0;
while at < fat_bytes {
let len = chunk.min(fat_bytes - at);
let mut part = vec![0u8; len as usize];
let first_entry = at / 4;
let mut set = |cluster: u64, value: u32| {
if (first_entry..first_entry + len / 4).contains(&cluster) {
let i = ((cluster - first_entry) * 4) as usize;
part[i..i + 4].copy_from_slice(&value.to_le_bytes());
}
};
set(0, 0x0fff_fff8);
set(1, END_OF_CHAIN);
for &(start, n) in &chains {
// Only the entries this part holds.
let lo = start.max(first_entry);
let hi = (start + n).min(first_entry + len / 4);
for c in lo..hi {
set(
c,
if c + 1 == start + n {
END_OF_CHAIN
} else {
c as u32 + 1
},
);
}
}
if !disk.write_at(base + at, &part) {
return Err(fail);
}
at += len;
}
}
let data_start = offset + (RESERVED + FATS * fat_sectors) * SECTOR;
let cluster_at = |c: u64| data_start + (c - 2) * CLUSTER;
// The folders' entries.
for (i, d) in dirs.iter().enumerate() {
let mut bytes = vec![0u8; (d.clusters * CLUSTER) as usize];
let mut at = 0;
let mut put = |e: [u8; 32]| {
bytes[at..at + 32].copy_from_slice(&e);
at += 32;
};
if i == 0 {
put(entry(&name, ATTR_VOLUME, 0, 0));
} else {
let parent = if d.parent == 0 { 0 } else { dirs[d.parent].cluster };
put(entry(b". ", ATTR_DIRECTORY, d.cluster, 0));
put(entry(b".. ", ATTR_DIRECTORY, parent, 0));
}
for &s in &d.dirs {
put(entry(&dirs[s].name, ATTR_DIRECTORY, dirs[s].cluster, 0));
}
for &f in &d.files {
let (path, len) = files[f];
let name = short_name(path.rsplit('/').next().unwrap()).unwrap();
put(entry(&name, ATTR_ARCHIVE, file_clusters[f], len as u32));
}
if !disk.write_at(cluster_at(d.cluster), &bytes) {
return Err(fail);
}
}
// The files' contents, a piece at a time, their last cluster's rest
// zeroed.
let mut piece = vec![0u8; chunk as usize];
for (f, (&start, &(_, len))) in file_clusters.iter().zip(files).enumerate() {
if start == 0 {
continue;
}
let at = cluster_at(start);
let mut done = 0;
while done < len {
let n = chunk.min(len - done) as usize;
if !read(f, &mut piece[..n]) {
return Err("a file to write could not be read");
}
// The last piece out to its cluster's end.
let whole = n.next_multiple_of(CLUSTER as usize);
piece[n..whole].fill(0);
if !disk.write_at(at + done, &piece[..whole]) {
return Err(fail);
}
done += n as u64;
}
}
Ok(())
}
/// A FAT32's layout, from its boot sector.
struct Volume {
cluster: u64,
fat: u64,
data: u64,
root: u32,
clusters: u32,
}
impl Volume {
fn open(disk: &mut impl Medium, offset: u64) -> Option<Volume> {
let mut b = [0u8; 512];
if !disk.read_at(offset, &mut b) || b[510..512] != [0x55, 0xaa] {
return None;
}
let sector = u64::from(u16_at(&b, 11));
let per_cluster = u64::from(b[13]);
let reserved = u64::from(u16_at(&b, 14));
let fats = u64::from(b[16]);
let fat_sectors = u64::from(u32_at(&b, 36));
// A FAT12 or FAT16 says its FAT's size in the 16-bit field.
if !matches!(sector, 512 | 1024 | 2048 | 4096)
|| per_cluster == 0
|| u16_at(&b, 22) != 0
|| fat_sectors == 0
|| fats == 0
{
return None;
}
let total = u64::from(u32_at(&b, 32));
let data = reserved + fats * fat_sectors;
Some(Volume {
cluster: sector * per_cluster,
fat: offset + reserved * sector,
data: offset + data * sector,
root: u32_at(&b, 44),
clusters: (total.saturating_sub(data) / per_cluster) as u32,
})
}
fn next(&self, disk: &mut impl Medium, cluster: u32) -> Option<u32> {
let mut e = [0u8; 4];
disk.read_at(self.fat + u64::from(cluster) * 4, &mut e)
.then_some(())?;
let next = u32::from_le_bytes(e) & 0x0fff_ffff;
(2..self.clusters + 2).contains(&next).then_some(next)
}
/// The chain from `first`, read whole, at most `limit` bytes of it.
fn chain(&self, disk: &mut impl Medium, first: u32, limit: u64) -> Option<Vec<u8>> {
let mut out = Vec::new();
let mut at = Some(first).filter(|&c| c >= 2);
let mut steps = 0;
while let Some(c) = at {
if out.len() as u64 >= limit || steps > self.clusters {
break;
}
let start = out.len();
out.resize(start + self.cluster as usize, 0);
let place = self.data + u64::from(c - 2) * self.cluster;
disk.read_at(place, &mut out[start..]).then_some(())?;
at = self.next(disk, c);
steps += 1;
}
out.truncate(limit.min(out.len() as u64) as usize);
Some(out)
}
}
/// The file at `path` (8.3 names, `/` between; case does not matter) in
/// the FAT32 at `offset`, or None when there is none, or no FAT32.
pub fn read_file(disk: &mut impl Medium, offset: u64, path: &str) -> Option<Vec<u8>> {
let mut reader = Reader::open(disk, offset, path)?;
let mut out = vec![0u8; reader.size as usize];
reader.read(disk, &mut out).then_some(out)
}
/// A file of a FAT32 read from its start on, a piece at a time: for one
/// too large to hold whole.
pub struct Reader {
volume: Volume,
/// The cluster the next bytes are in, and how far into it.
cluster: Option<u32>,
within: u64,
/// Its size, and the bytes not yet read.
pub size: u64,
left: u64,
}
impl Reader {
/// The file at `path`, as [`read_file`] finds it.
pub fn open(disk: &mut impl Medium, offset: u64, path: &str) -> Option<Reader> {
let volume = Volume::open(disk, offset)?;
let mut dir = volume.root;
let mut parts = path.split('/').filter(|p| !p.is_empty()).peekable();
while let Some(part) = parts.next() {
let wanted = short_name(&part.to_ascii_uppercase())?;
let entries = volume.chain(disk, dir, 1 << 20)?;
let found = entries
.as_chunks::<32>()
.0
.iter()
.take_while(|e| e[0] != 0)
.filter(|e| e[0] != 0xe5 && e[11] != ATTR_LONG_NAME && e[11] & ATTR_VOLUME == 0)
.find(|e| e[..11] == wanted)?;
let cluster = u32::from(u16_at(found, 20)) << 16 | u32::from(u16_at(found, 26));
let is_dir = found[11] & ATTR_DIRECTORY != 0;
if parts.peek().is_none() {
let size = u64::from(u32_at(found, 28));
return (!is_dir).then_some(Reader {
volume,
cluster: Some(cluster).filter(|&c| c >= 2),
within: 0,
size,
left: size,
});
}
if !is_dir {
return None;
}
dir = cluster;
}
None
}
/// Fills `into` with the file's next bytes. False when the file has
/// fewer left, or a read failed.
pub fn read(&mut self, disk: &mut impl Medium, into: &mut [u8]) -> bool {
if into.len() as u64 > self.left {
return false;
}
let mut done = 0;
while done < into.len() {
let Some(c) = self.cluster else { return false };
let place = self.volume.data + u64::from(c - 2) * self.volume.cluster + self.within;
let n = ((self.volume.cluster - self.within) as usize).min(into.len() - done);
if !disk.read_at(place, &mut into[done..done + n]) {
return false;
}
done += n;
self.within += n as u64;
if self.within == self.volume.cluster {
self.within = 0;
self.cluster = self.volume.next(disk, c);
}
}
self.left -= into.len() as u64;
true
}
}