Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

3.5 KB
Raw Blame
//! Can a normal (not elevated) process enumerate a volume's MFT records with FSCTL_ENUM_USN_DATA, and how fast?
//! Tries a handle on the volume's root folder and one on the volume itself, each with attribute access only. Reads, changes nothing.
//! `cargo run --release -p rf-win --example mft_enum_probe -- C:`

use std::time::Instant;

use windows::Win32::Storage::FileSystem::{
    CreateFileW, FILE_FLAG_BACKUP_SEMANTICS, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE,
    FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
};
use windows::Win32::System::IO::DeviceIoControl;
use windows::Win32::System::Ioctl::{FSCTL_ENUM_USN_DATA, MFT_ENUM_DATA_V0, USN_RECORD_V2};
use windows::core::PCWSTR;

fn try_enum(label: &str, path: &str, access: u32) {
    let w: Vec<u16> = path.encode_utf16().chain(Some(0)).collect();
    let h = unsafe {
        CreateFileW(
            PCWSTR(w.as_ptr()),
            access,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            None,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS,
            None,
        )
    };
    let h = match h {
        Ok(h) => h,
        Err(e) => {
            println!("{label}: open failed: {e}");
            return;
        }
    };
    let mut med = MFT_ENUM_DATA_V0 {
        StartFileReferenceNumber: 0,
        LowUsn: 0,
        HighUsn: i64::MAX,
    };
    let mut buf = vec![0u8; 1 << 20];
    let (mut records, mut dirs, mut calls) = (0u64, 0u64, 0u32);
    let t = Instant::now();
    loop {
        let mut got = 0u32;
        let r = unsafe {
            DeviceIoControl(
                h,
                FSCTL_ENUM_USN_DATA,
                Some(&med as *const _ as *const _),
                std::mem::size_of_val(&med) as u32,
                Some(buf.as_mut_ptr() as *mut _),
                buf.len() as u32,
                Some(&mut got),
                None,
            )
        };
        if let Err(e) = r {
            if calls == 0 {
                println!("{label}: FSCTL_ENUM_USN_DATA failed: {e}");
            }
            break;
        }
        calls += 1;
        if got <= 8 {
            break;
        }
        // the first 8 bytes are the next start reference; records follow
        med.StartFileReferenceNumber = u64::from_le_bytes(buf[0..8].try_into().unwrap());
        let mut off = 8usize;
        while off + std::mem::size_of::<USN_RECORD_V2>() <= got as usize {
            let rec = unsafe { &*(buf.as_ptr().add(off) as *const USN_RECORD_V2) };
            if rec.RecordLength == 0 {
                break;
            }
            records += 1;
            if rec.FileAttributes & 0x10 != 0 {
                dirs += 1;
            }
            off += rec.RecordLength as usize;
        }
    }
    if calls > 0 {
        let s = t.elapsed().as_secs_f64();
        println!(
            "{label}: {records} records ({dirs} folders) in {s:.2} s, {:.0} records/s, {calls} calls",
            records as f64 / s.max(0.001)
        );
    }
}

fn main() {
    let vol = std::env::args().nth(1).unwrap_or_else(|| "C:".into());
    try_enum(
        "root folder handle",
        &format!("{vol}\\"),
        FILE_READ_ATTRIBUTES.0,
    );
    try_enum(
        "volume handle (attributes)",
        &format!("\\\\.\\{vol}"),
        FILE_READ_ATTRIBUTES.0,
    );
    // (GENERIC_READ on the volume: what the enumeration needs; only an administrator gets it)
    try_enum(
        "volume handle (read)",
        &format!("\\\\.\\{vol}"),
        0x8000_0000,
    );
}