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.

A failed eject writes to the log what rustyfiles itself holds open on the drive (622)

gelenmedyacd18adf13627
diff --git a/crates/rf-app/src/dock/eject_view.rs b/crates/rf-app/src/dock/eject_view.rs
index 40030d96..012477f7 100644
--- a/crates/rf-app/src/dock/eject_view.rs
+++ b/crates/rf-app/src/dock/eject_view.rs
@@ -206,6 +206,7 @@ impl EjectView {
let failed = !matches!(done, Some(Ok(())));
if failed {
log::warn!("dock: a drive could not be removed safely: {done:?}");
+ crate::log_drive_holders(letter);
}
// Windows takes the drive away a moment after it says yes: looked at at once, a removal that worked looked failed (issue 622)
let now = cx
diff --git a/crates/rf-app/src/lib.rs b/crates/rf-app/src/lib.rs
index f1c7f079..90a5eb59 100644
--- a/crates/rf-app/src/lib.rs
+++ b/crates/rf-app/src/lib.rs
@@ -515,6 +515,21 @@ fn save_and_quit(cx: &mut App) {
cx.quit();
}
+/// After an eject that failed: what rustyfiles' own processes hold open on the drive, into the log (`rf_win::holders`, issue 622:
+/// "the drive is in use" through three versions, with nothing saying by what). On a thread of its own, so that neither the
+/// interface nor the eject waits for it.
+pub(crate) fn log_drive_holders(letter: char) {
+ let _ = std::thread::Builder::new().name("drive-holders".into()).spawn(move || {
+ let held = rf_win::holders::own_handles_on(letter);
+ if held.is_empty() {
+ log::warn!("{letter}: none of rustyfiles' own processes holds a file open on it: another program does");
+ }
+ for line in held {
+ log::warn!("{letter}: held open by {line}");
+ }
+ });
+}
+
/// The variable a restarted rustyfiles is started with: the process id of the one that is ending (see [`restart`]).
const AFTER_EXIT_ENV: &str = "RUSTYFILES_AFTER_EXIT";
diff --git a/crates/rf-app/src/workspace.rs b/crates/rf-app/src/workspace.rs
index 85baa37d..42d7c2f5 100644
--- a/crates/rf-app/src/workspace.rs
+++ b/crates/rf-app/src/workspace.rs
@@ -4618,6 +4618,7 @@ impl Workspace {
let (r, still) = done;
if !matches!(r, Some(Ok(()))) || still {
log::warn!("sidebar: {letter}: could not be removed safely: {r:?} (still there: {still})");
+ crate::log_drive_holders(letter);
crate::prompt::notice(crate::i18n::t("Güvenle çıkar"), crate::i18n::t("Kullanımda: açık dosyaları kapatıp yeniden deneyin").to_string(), window, cx);
}
});
diff --git a/crates/rf-win/src/holders.rs b/crates/rf-win/src/holders.rs
new file mode 100644
index 00000000..73b48df3
--- /dev/null
+++ b/crates/rf-win/src/holders.rs
@@ -0,0 +1,197 @@
+//! 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};
+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;
+}
+
+/// `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(&our_processes(), &prefix)
+}
+
+/// (process id, image name) of every running program of ours.
+fn our_processes() -> 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.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]`.
+fn handles_of(processes: &[(u32, String)], prefix: &str) -> Vec<String> {
+ let mut lines = Vec::new();
+ if processes.is_empty() {
+ return lines;
+ }
+ let Some(table) = handle_table() else { return lines };
+ // 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 { 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)));
+ }
+ }
+ }
+ let _ = CloseHandle(copy);
+ }
+ }
+ // SAFETY: opened above
+ unsafe {
+ let _ = CloseHandle(process);
+ }
+ }
+ lines
+}
+
+/// 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);
+ 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);
+ assert!(!lines.iter().any(|l| l.to_lowercase().contains("held.txt")), "{lines:?}");
+ assert!(handles_of(&me, r"\\?\Q:\no such place").is_empty());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[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"));
+ }
+}
diff --git a/crates/rf-win/src/lib.rs b/crates/rf-win/src/lib.rs
index 489635ad..071a864f 100644
--- a/crates/rf-win/src/lib.rs
+++ b/crates/rf-win/src/lib.rs
@@ -115,6 +115,7 @@ pub mod shellhost;
pub mod sta;
pub mod stayup;
pub mod switcher;
+pub mod holders;
pub mod removal;
pub mod pane_picture;
pub mod rotate;