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.

13.4 KB
Raw Blame
//! Which files rustyfiles' own processes hold open on a drive: written to the log when an eject fails, so that a report of "the
//! drive is in use" names what held it.
//!
//! WHY (issue 622: a USB disk that could not be ejected, through three versions). Each fix so far closed a handle that was found by
//! thinking (the Dock's watch on the disk's bin, the name index, the working directory); the reporter's disk stayed "in use" and
//! nothing said by what. A drive is in use when any process has a file or folder on it open. Windows does not say which; this does,
//! for our own processes (the window, the Dock, DirectLook, the guard, an add-on), which are the ones we can fix. Tried by hand
//! first (a PowerShell version of the same calls found the handle of a folder watch, of a working directory and of the removal
//! watch on a mounted disc image).
//!
//! HOW. The system's list of every open handle (`NtQuerySystemInformation`, class 64) is filtered to our processes; each handle is
//! duplicated into this process, and one that is a disk file is asked for its path (`GetFinalPathNameByHandleW`). Handles that are
//! not disk files are never asked for a name (a pipe in a blocking read can keep such a question waiting for ever), and a few access
//! masks that only pipes carry are not even duplicated. It runs on the caller's thread and takes a few milliseconds; callers run it
//! off the interface thread and only after an eject has failed.

use std::ffi::c_void;

use windows::Win32::Foundation::{CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE};
use windows::Win32::Storage::FileSystem::{FILE_NAME_NORMALIZED, FILE_TYPE_DISK, GetFileType, GetFinalPathNameByHandleW, QueryDosDeviceW};
use windows::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcess, PROCESS_DUP_HANDLE};

#[link(name = "ntdll")]
unsafe extern "system" {
    fn NtQuerySystemInformation(class: u32, info: *mut c_void, len: u32, returned: *mut u32) -> i32;
    fn NtQueryObject(handle: *mut c_void, class: u32, info: *mut c_void, len: u32, returned: *mut u32) -> i32;
}

/// `ObjectNameInformation`.
const OBJECT_NAME: u32 = 1;

/// `SystemExtendedHandleInformation`.
const HANDLES_CLASS: u32 = 64;
/// `STATUS_INFO_LENGTH_MISMATCH`: the buffer was too small.
const TOO_SMALL: i32 = 0xC000_0004u32 as i32;

/// One entry of the system's handle list (`SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX`).
#[repr(C)]
struct Entry {
    object: *mut c_void,
    process: usize,
    handle: usize,
    access: u32,
    trace: u16,
    kind: u16,
    attributes: u32,
    reserved: u32,
}

/// The programs that are rustyfiles' own (their image names, lower case).
const OURS: [&str; 4] = ["rustyfiles.exe", "directlook.exe", "rustyfiles-shellguard.exe", "hyperdownload.exe"];

/// Access masks seen only on pipes and on handles that give nothing (duplicating some of them can wait on the other end).
fn skipped(access: u32) -> bool {
    matches!(access, 0x0012_019f | 0x001a_019f | 0x0012_0189 | 0x0010_0000)
}

/// The lines for the log: what each of rustyfiles' processes holds open on drive `letter`. Empty when nothing is held by us.
pub fn own_handles_on(letter: char) -> Vec<String> {
    let prefix = format!(r"\\?\{}:", letter.to_ascii_uppercase());
    handles_of(&processes(true), &prefix, volume_device(letter).as_deref()).0
}

/// The same for EVERY process this one may look into, for a measurement by hand (`examples/holders_probe`): the lines, and the
/// names of the processes that could not be looked into (another user's, the system's, an elevated one).
pub fn all_handles_on(letter: char) -> (Vec<String>, Vec<String>) {
    let prefix = format!(r"\\?\{}:", letter.to_ascii_uppercase());
    handles_of(&processes(false), &prefix, volume_device(letter).as_deref())
}

/// The kernel's name of drive `letter`'s volume (`\Device\HarddiskVolume7`).
fn volume_device(letter: char) -> Option<String> {
    let name = crate::wide::wide(format!("{}:", letter.to_ascii_uppercase()));
    let mut buf = [0u16; 512];
    // SAFETY: the name is a NUL-ended string that lives through the call; the buffer's length is its own
    let n = unsafe { QueryDosDeviceW(windows::core::PCWSTR(name.as_ptr()), Some(&mut buf)) } as usize;
    (n > 0).then(|| crate::wide::from_wide(&buf))
}

/// The kernel's name of what a handle is open on. Asked only of a disk file's handle (see the top of this file about pipes).
fn object_name(h: HANDLE) -> Option<String> {
    let mut buf = vec![0u16; 2048];
    let mut got = 0u32;
    // SAFETY: the buffer is 4096 bytes and the call is told so; it writes a UNICODE_STRING (length in bytes, a pointer into the
    // same buffer) followed by the letters
    let status = unsafe { NtQueryObject(h.0, OBJECT_NAME, buf.as_mut_ptr() as *mut c_void, (buf.len() * 2) as u32, &mut got) };
    if status < 0 {
        return None;
    }
    let bytes = buf[0] as usize;
    // (the header is 16 bytes on a 64-bit system: two lengths, padding, the pointer)
    let first = 16 / 2;
    (bytes > 0 && first + bytes / 2 <= buf.len()).then(|| String::from_utf16_lossy(&buf[first..first + bytes / 2]))
}

/// (process id, image name) of every running program: of ours only, or of all.
fn processes(ours: bool) -> Vec<(u32, String)> {
    let mut out = Vec::new();
    // SAFETY: the snapshot handle is used and closed here; `dwSize` is set as the API asks.
    unsafe {
        let Ok(snap) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { return out };
        let mut e = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
        let mut more = Process32FirstW(snap, &mut e).is_ok();
        while more {
            let name = crate::wide::from_wide(&e.szExeFile);
            if !ours || OURS.iter().any(|o| name.eq_ignore_ascii_case(o)) {
                out.push((e.th32ProcessID, name));
            }
            more = Process32NextW(snap, &mut e).is_ok();
        }
        let _ = CloseHandle(snap);
    }
    out
}

/// The disk files the given processes hold open whose path begins with `prefix` (compared without regard to case), one line each:
/// `name (pid): path [access]`. A handle on the volume itself (`device`: opened as `\\.\D:`, as a program does to read the change
/// journal or the disk's layout) has no path and is named as that: it keeps a drive from being removed just the same, and was
/// invisible here until 2026-12-05. The second list: the processes that could not be opened.
pub(crate) fn handles_of(processes: &[(u32, String)], prefix: &str, device: Option<&str>) -> (Vec<String>, Vec<String>) {
    let mut lines = Vec::new();
    let mut closed = Vec::new();
    if processes.is_empty() {
        return (lines, closed);
    }
    let Some(table) = handle_table() else { return (lines, closed) };
    // SAFETY: `table` holds what the system wrote: a count, a reserved word, then that many entries; the count is checked against
    // the buffer's length before an entry is read.
    let count = unsafe { *(table.as_ptr() as *const usize) };
    let first = 2 * std::mem::size_of::<usize>();
    let size = std::mem::size_of::<Entry>();
    let count = count.min((table.len().saturating_sub(first)) / size);
    let prefix = prefix.to_lowercase();
    let me = unsafe { GetCurrentProcess() };
    for (pid, name) in processes {
        // SAFETY: a handle to one of our own processes, closed below
        let Ok(process) = (unsafe { OpenProcess(PROCESS_DUP_HANDLE, false, *pid) }) else {
            closed.push(format!("{name} ({pid})"));
            continue;
        };
        for i in 0..count {
            // SAFETY: `i < count`, and `count` entries lie inside the buffer (checked above); read unaligned, as a byte buffer gives
            let e = unsafe { std::ptr::read_unaligned(table.as_ptr().add(first + i * size) as *const Entry) };
            if e.process != *pid as usize || skipped(e.access) {
                continue;
            }
            let mut copy = HANDLE::default();
            // SAFETY: duplicates a handle of the other process into this one; the copy is closed below
            if unsafe { DuplicateHandle(process, HANDLE(e.handle as *mut c_void), me, &mut copy, 0, false, DUPLICATE_SAME_ACCESS) }.is_err() {
                continue;
            }
            // SAFETY: `copy` is a valid handle of this process until it is closed here
            unsafe {
                if GetFileType(copy) == FILE_TYPE_DISK {
                    let mut buf = [0u16; 1024];
                    let n = GetFinalPathNameByHandleW(copy, &mut buf, FILE_NAME_NORMALIZED) as usize;
                    if n > 0 && n < buf.len() {
                        let path = String::from_utf16_lossy(&buf[..n]);
                        if path.to_lowercase().starts_with(&prefix) {
                            lines.push(format!("{name} ({pid}): {path} [{}]", what(e.access)));
                        }
                    } else if n == 0
                        && let Some(device) = device
                        && object_name(copy).is_some_and(|o| o.eq_ignore_ascii_case(device))
                    {
                        lines.push(format!("{name} ({pid}): the volume itself, opened as a device [access {:#010x}]", e.access));
                    }
                }
                let _ = CloseHandle(copy);
            }
        }
        // SAFETY: opened above
        unsafe {
            let _ = CloseHandle(process);
        }
    }
    (lines, closed)
}

/// What a handle's access rights say it is for, in words (with the number).
fn what(access: u32) -> String {
    let kind = match access {
        0x0010_0020 => "a working directory or a folder passed through",
        0x0010_0081 => "a folder being watched or listed",
        0x0010_0080 => "attributes only (the removal watch, or the index's hold on a drive)",
        a if a & 0x0000_0002 != 0 || a & 0x4000_0000 != 0 => "a file open for writing",
        a if a & 0x0000_0001 != 0 || a & 0x8000_0000 != 0 => "a file or folder open for reading",
        _ => "open",
    };
    format!("{kind}, access {access:#010x}")
}

/// The system's list of open handles, as it wrote it. `None` when it cannot be read.
fn handle_table() -> Option<Vec<u8>> {
    let mut len = 4usize << 20;
    for _ in 0..8 {
        let mut buf = vec![0u8; len];
        let mut needed = 0u32;
        // SAFETY: the buffer is `len` bytes, and the call writes at most that many
        let status = unsafe { NtQuerySystemInformation(HANDLES_CLASS, buf.as_mut_ptr() as *mut c_void, len as u32, &mut needed) };
        if status == TOO_SMALL {
            len = (needed as usize + (1 << 20)).max(len * 2);
            continue;
        }
        return (status >= 0).then_some(buf);
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A folder this very process holds open is found, with the process's name and the folder's path, and a place nothing is open
    /// in gives nothing.
    #[test]
    fn a_folder_this_process_holds_open_is_listed() {
        let dir = std::env::temp_dir().join(format!("rf-holders-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("held.txt");
        std::fs::write(&file, b"x").unwrap();
        let held = std::fs::File::open(&file).unwrap();
        let me = [(std::process::id(), "this test".to_string())];
        let prefix = format!(r"\\?\{}", std::fs::canonicalize(&dir).unwrap().to_string_lossy().trim_start_matches(r"\\?\"));
        let (lines, _) = handles_of(&me, &prefix, None);
        assert!(lines.iter().any(|l| l.starts_with("this test (") && l.to_lowercase().contains("held.txt")), "{lines:?}");
        drop(held);
        let (lines, _) = handles_of(&me, &prefix, None);
        assert!(!lines.iter().any(|l| l.to_lowercase().contains("held.txt")), "{lines:?}");
        assert!(handles_of(&me, r"\\?\Q:\no such place", None).0.is_empty());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A program that opens the volume itself (the change journal's readers do) holds the drive as much as an open file does.
    #[test]
    fn a_volume_opened_as_a_device_is_listed_too() {
        let letter = std::env::temp_dir().to_string_lossy().chars().next().unwrap();
        let device = volume_device(letter).expect("the temp folder's drive has a device name");
        assert!(device.starts_with(r"\Device\"), "{device}");
        // (opened with no access rights asked: allowed to any user, and it is the object that counts here)
        use std::os::windows::fs::OpenOptionsExt;
        let Ok(volume) = std::fs::OpenOptions::new().access_mode(0).share_mode(7).open(format!(r"\\.\{letter}:")) else { return };
        let me = [(std::process::id(), "this test".to_string())];
        let (lines, _) = handles_of(&me, &format!(r"\\?\{letter}:"), Some(&device));
        assert!(lines.iter().any(|l| l.contains("the volume itself")), "{lines:?}");
        drop(volume);
        let (lines, _) = handles_of(&me, &format!(r"\\?\{letter}:"), Some(&device));
        assert!(!lines.iter().any(|l| l.contains("the volume itself")), "{lines:?}");
    }

    #[test]
    fn pipes_access_masks_are_left_alone_and_file_ones_are_named() {
        assert!(skipped(0x0012_019f));
        assert!(!skipped(0x0010_0081));
        assert!(what(0x0010_0020).starts_with("a working directory"));
        assert!(what(0x0010_0081).starts_with("a folder being watched"));
        assert!(what(0x0012_0089).contains("reading"));
        assert!(what(0x0012_0116).contains("writing"));
    }
}