crates

file_allocation_table

check proofs license minimum Rust version

File Allocation Table (FAT) volumes as pure computation, in all three widths: FAT12, FAT16 and FAT32. The crate reads, writes and formats volumes through a sector interface you implement. It does no I/O, needs no allocator (no_std), and names no device. It reads and writes the long file names that the Virtual File Allocation Table (VFAT) extension adds. Kani, a model checker that proves properties for all inputs up to a stated size, checks every function that parses bytes read from a disk.

What it does

EXAMPLES

use file_allocation_table::{
    Attributes, DirectoryCluster, FormatOptions, FormatPlan, NoClock, SectorDevice, SectorSize,
    WritableSectorDevice, WritableVolume,
};

/// A volume held in memory. A real caller wraps a block device the same way.
struct Memory(Vec<u8>);

impl SectorDevice for Memory {
    type Error = ();

    fn sector_size(&self) -> SectorSize {
        SectorSize::Bytes512
    }

    fn read_sector(&mut self, index: u64, buffer: &mut [u8]) -> Result<(), ()> {
        let start = usize::try_from(index).map_err(|_| ())? * 512;
        buffer.copy_from_slice(self.0.get(start..start + 512).ok_or(())?);
        Ok(())
    }
}

impl WritableSectorDevice for Memory {
    fn write_sector(&mut self, index: u64, buffer: &[u8]) -> Result<(), ()> {
        let start = usize::try_from(index).map_err(|_| ())? * 512;
        self.0
            .get_mut(start..start + 512)
            .ok_or(())?
            .copy_from_slice(buffer);
        Ok(())
    }
}

fn main() {
    // Format 8 MiB. The size makes it FAT16 with 1 KiB clusters; about 4 MiB or less makes FAT12,
    // and 512 MiB or more makes FAT32.
    let sectors = 16 * 1024;
    let options = FormatOptions::new(SectorSize::Bytes512, sectors)
        .with_label("EXAMPLE")
        .unwrap();
    let format = FormatPlan::new(options, &mut NoClock).expect("a legal size");
    let mut device = Memory(vec![0; sectors as usize * 512]);
    format.write_to(&mut device).unwrap();

    // Open it, make a directory and a file with a long name, and write some bytes.
    let mut volume = WritableVolume::open(device, NoClock).unwrap();
    let docs = volume
        .create_directory(DirectoryCluster::ROOT, "Documents")
        .unwrap();
    let file = volume
        .create_file(docs.directory_cluster().unwrap(), "A long file name.txt")
        .unwrap();
    volume
        .open_file_writer(&file)
        .unwrap()
        .write(b"hello, volume")
        .unwrap();
    let stored = volume.lookup("Documents/A long file name.txt").unwrap();
    let hidden = Attributes::ARCHIVE.union(Attributes::HIDDEN);
    volume.set_attributes(&stored, hidden).unwrap();
    volume.mark_clean().unwrap();

    // Read it back by path, as another program would.
    let entry = volume.lookup("documents/A LONG FILE NAME.TXT").unwrap();
    let mut bytes = [0u8; 32];
    let read = volume
        .open_file_reader(&entry)
        .unwrap()
        .read(&mut bytes)
        .unwrap();
    assert_eq!(&bytes[..read], b"hello, volume");
    assert_eq!(
        volume.volume_label().unwrap().unwrap().trim_ascii_end(),
        b"EXAMPLE"
    );
}

A documentation test compiles and runs this example. lookup splits a path at / or \ and skips an empty component, as from a leading, trailing or doubled separator. A name may not end in a dot or a space: Windows and Linux strip those, and this crate refuses with NameRefused instead. Every write goes through a WritableVolume, which needs a Clock. NoClock is the explicit "no time", and the entries it stamps carry the zero timestamp. FormatPlan formats any FAT volume onto a device, and a WritableVolume then writes its files. VolumeLayout is for one shape, an EFI system partition, written without a device in one pass. VolumeLayout::new takes a VolumeLayoutOptions and a clock. The options hold the total sector count, and optionally the hidden sectors, the volume identifier, a label you choose, such as "EFI SYSTEM", and the one boot file's name and size. The layout then tells you what every metadata sector holds. Write sectors 0..metadata_sectors() from fill_sector, then the file's bytes from file_first_sector() on, file_sectors() long. Without a label the volume has none, and without a file it is an empty FAT32 volume.

A PartitionDevice only reads, and Partition::restrict_device makes one. To write inside a partition, wrap the whole-disk device in a small device of your own. It adds the partition's first sector to every index, and the volume opens through it. The example below does this.

use file_allocation_table::{
    DirectoryCluster, NoClock, Partition, SectorDevice, SectorSize, WritableSectorDevice,
    WritableVolume,
};

/// Shows a disk from sector `first` on, as a device whose sector 0 is that sector.
struct Offset<D> {
    device: D,
    first: u64,
}

impl<D: SectorDevice> SectorDevice for Offset<D> {
    type Error = D::Error;

    fn sector_size(&self) -> SectorSize {
        self.device.sector_size()
    }

    fn read_sector(&mut self, index: u64, buffer: &mut [u8]) -> Result<(), D::Error> {
        self.device.read_sector(self.first + index, buffer)
    }
}

impl<D: WritableSectorDevice> WritableSectorDevice for Offset<D> {
    fn write_sector(&mut self, index: u64, buffer: &[u8]) -> Result<(), D::Error> {
        self.device.write_sector(self.first + index, buffer)
    }
}

/// Make a file in the volume inside `partition`, which `MasterBootRecord::partitions` yielded.
fn create_in_partition<D: WritableSectorDevice>(disk: D, partition: Partition) {
    let first = u64::from(partition.first_sector());
    let Ok(mut volume) = WritableVolume::open(Offset { device: disk, first }, NoClock) else {
        return;
    };
    let _ = volume.create_file(DirectoryCluster::ROOT, "NOTE.TXT");
}

This Offset does not stop a write past the partition's last sector, which would land in the next partition. A caller that cannot trust the volume's boot sector checks each index against Partition::sector_count before it writes.

Every error enum is #[non_exhaustive], so a match on one needs a wildcard arm, and a later release can add a variant without breaking your code. Every error type implements Display and core::error::Error, with no allocator. A message names its own level only, and source() returns the error it wraps. A type generic over your device's error displays for any error, and is an Error, so ? takes it into a boxed error, when your device's error is one.

examples/image.rs is a host program over an image file. It makes a std::fs::File a sector device, stamps writes with the host's clock as UTC, and prints a volume's tree.

The commands read and write paths relative to the current directory, so run them from a scratch directory. format disk.img 64 makes a 64 MiB image.

cargo run --example image -- format disk.img 64
cargo run --example image -- put disk.img notes.txt
cargo run --example image -- list disk.img

The embedded-io traits

The embedded-io-07 feature, off by default, implements the embedded-io 0.7 traits: a FileReader is Read and Seek, and a FileWriter is Write and Seek, so a file plugs into any crate written against those traits. Turn it on with file_allocation_table = { version = "0.1", features = ["embedded-io-07"] }, and add embedded-io = "0.7" beside it to name the traits; the crate does not re-export them. Without the feature the crate has no dependency at all. docs.rs builds with the feature on. A later embedded-io major version will get a feature of its own beside this one, so a caller on either version is served.

use embedded_io::{Read, Seek, SeekFrom};
use file_allocation_table::{
    DirectoryCluster, FormatOptions, FormatPlan, NoClock, SectorSize, WritableVolume,
};

// `Memory` is the device of the first example, with an error type that implements
// `core::error::Error`, which `embedded_io::Error` requires.
/// Any `embedded-io` writer, such as a file on this crate's volume.
fn greet(out: &mut impl embedded_io::Write) -> Result<(), impl embedded_io::Error> {
    out.write_all(b"hello, ")?;
    out.write_all(b"embedded-io")
}

fn main() {
    let sectors = 16 * 1024;
    let options = FormatOptions::new(SectorSize::Bytes512, sectors);
    let mut device = Memory(vec![0; sectors as usize * 512]);
    let format = FormatPlan::new(options, &mut NoClock).unwrap();
    format.write_to(&mut device).unwrap();
    let mut volume = WritableVolume::open(device, NoClock).unwrap();
    let file = volume
        .create_file(DirectoryCluster::ROOT, "GREETING.TXT")
        .unwrap();

    greet(&mut volume.open_file_writer(&file).unwrap()).unwrap();

    let entry = volume.lookup("GREETING.TXT").unwrap();
    let mut reader = volume.open_file_reader(&entry).unwrap();
    reader.seek(SeekFrom::End(-11)).unwrap();
    let mut bytes = [0u8; 11];
    reader.read_exact(&mut bytes).unwrap();
    assert_eq!(&bytes, b"embedded-io");
}

cargo test --features embedded-io-07 runs this example and the trait tests; plain cargo test leaves them out. Each trait method calls the inherent method of the same purpose. A seek past the end of a file stops at its end and returns that position, and a seek before the start fails with SeekBeforeStart and moves nothing. flush has nothing to do, since every write rewrites the directory entry before it returns. Each error reports the ErrorKind nearest its meaning: a full volume is WriteZero, as embedded_io::Write asks, a damaged chain is InvalidData, a read-only file is PermissionDenied, and the device's own error is Other.

Footprint

The crate allocates nothing; every byte below lives where the caller puts the value or on the stack of the call. A Volume or a WritableVolume is 4,192 bytes plus the device, most of it one sector buffer of 4,096 bytes, the largest sector size. A Directory or a FileReader borrows the volume and holds its own buffer, 4,152 bytes each. A FileWriter is 88 bytes, a NamedEntry 576 (it holds the long name), a FormatPlan 64 and a VolumeLayout 624. These are the sizes on a 64-bit host. The write paths put sector-sized arrays on the stack for each call. Measured on x86-64 in a release build, a thread that formats a volume and then creates a directory and a file, writes 10,000 bytes, renames, looks up and reads needed about 40 KiB of stack, the volume itself included.

A FAT32 directory holds at most 65,536 entries. In a release build on x86-64, creating 8.3-named files one after another in the root of a 1 GiB FAT32 volume held in memory filled it in 255 seconds, and the next create failed with DirectoryFull. The time grows with the square of the count: 5,000 entries took 1.7 seconds and 30,000 took 55. A real device adds its own time.

How it compares

What is proven

Kani harnesses prove, over every input they can unroll, the properties below.

cargo build builds the crate and cargo test runs its unit tests, integration tests and documentation tests in well under a minute. The proofs need Kani, which rustup does not install. Run cargo install --locked kani-verifier --version 0.68.0, then cargo kani setup. The setup step downloads a model checker, so it needs network access. CI uses version 0.68.0, and another version may verify differently. cargo kani setup also installs the nightly toolchain that Kani pins. After that, cargo kani from the crate's directory runs all 35 harnesses, one at a time; the whole run takes 10 to 20 minutes and needs about 5 gigabytes of memory. cargo kani --harness <name> runs one. A test fails when that count and the source differ.

Each harness has a falsification record at falsifications/<module.path>.<harness>.patch. Applying it with patch -p1 --no-backup-if-mismatch from the crate root (the flag stops an offset from leaving a .orig file beside the source) makes that harness fail at its own assertion, which shows the proof checks something. Kani bounds what it unrolls: the model volumes are a few clusters, and the format proof covers clusters of 1 to 8 sectors. The tests against rust-fatfs cover whole images.

The tests compare against rust-fatfs (the lamfat dev-dependency), an independent FAT library. Each library writes trees on FAT12, FAT16 and FAT32 volumes, and the other must read them, name for name and byte for byte. If the host has fsck.fat or fsck_msdos, every image must pass fsck -n. If the host has mkfs.fat, its FAT12 and FAT16 volumes take this crate's writer, and so does a FAT32 volume under 65525 clusters opened with with_small_fat32. If the host has mtools, it lists and reads what this crate writes, and this crate reads and writes beside what mmd and mcopy write. On a host without one of these tools, its tests pass without comparing; cargo test -- --nocapture prints which ones it skipped. The crate reads two FAT32 images that a macOS host formatted and wrote, to their recorded hashes. An ignored test has the host's own driver read an image (cargo test -- --ignored, on macOS).

Two cargo-fuzz targets in the repository's fuzz/ directory, which the crates.io package leaves out, reach what the proofs bound. file_allocation_table_boot_sector reads an arbitrary volume at each sector size and walks its directories, chains and files. file_allocation_table_writer runs arbitrary writes, renames and removals on a hostile image or on a volume the crate formatted. Run one with cargo +nightly fuzz run <target>; the weekly fuzz job runs both for a bounded time.

BUGS

Minimum Rust version

Rust 1.88.

License

Licensed under either of the MIT license (LICENSE-MIT) or the Apache License, Version 2.0 (LICENSE-APACHE), at your option.