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.

Open/Save: no pending pipe I/O on a return, relays unadvised, no borrow across Shell calls (1126); real items for a pick (1107)

gelenmedyaeda2f19735cd
diff --git a/crates/rf-dialog/src/ipc.rs b/crates/rf-dialog/src/ipc.rs
index da15b351..f58f4394 100644
--- a/crates/rf-dialog/src/ipc.rs
+++ b/crates/rf-dialog/src/ipc.rs
@@ -8,7 +8,7 @@ use std::time::{Duration, Instant};
use windows::Win32::Foundation::{CloseHandle, ERROR_IO_PENDING, ERROR_PIPE_CONNECTED, HANDLE, HMODULE, HWND, WAIT_OBJECT_0};
use windows::Win32::Storage::FileSystem::{FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OVERLAPPED, PIPE_ACCESS_DUPLEX, ReadFile, WriteFile};
-use windows::Win32::System::IO::{GetOverlappedResult, OVERLAPPED};
+use windows::Win32::System::IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED};
use windows::Win32::System::LibraryLoader::{GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, GetModuleHandleExW};
use windows::Win32::System::Pipes::{ConnectNamedPipe, CreateNamedPipeW, GetNamedPipeClientProcessId, PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_WAIT};
use windows::Win32::System::Threading::{CreateEventW, GetCurrentProcessId};
@@ -83,6 +83,23 @@ fn pump_until(event: HANDLE, timeout: Option<Duration>) -> bool {
}
}
+/// Takes back an overlapped operation on `pipe` that is still running, and waits until the system is done with `ov` (and with the
+/// buffer it was given). Call it before `ov` or its buffer goes out of scope with the operation unfinished.
+///
+/// WHY (issue 1126, a private review: "on ConnectNamedPipe timeout or WM_QUIT, pick()/io() return without calling CancelIoEx +
+/// GetOverlappedResult(..., true)"). A pending read, write or connect keeps the addresses it was given; returning from the
+/// function that owns them on a timeout or on the app's WM_QUIT left the kernel free to write into a stack that was already reused,
+/// inside the app that asked for the dialog. Cancelled and waited for, nothing is written after the return.
+fn abandon(pipe: HANDLE, ov: &OVERLAPPED) {
+ let mut n = 0u32;
+ // SAFETY: `ov` is the OVERLAPPED of the operation started on `pipe`; both outlive these two calls, and the wait returns only once
+ // the system no longer uses them
+ unsafe {
+ let _ = CancelIoEx(pipe, Some(ov));
+ let _ = GetOverlappedResult(pipe, ov, &mut n, true);
+ }
+}
+
/// Overlapped read/write of exactly `buf.len()` bytes, pumping messages meanwhile.
fn io(pipe: HANDLE, event: HANDLE, buf: &mut [u8], write: bool) -> bool {
let mut done = 0usize;
@@ -100,6 +117,8 @@ fn io(pipe: HANDLE, event: HANDLE, buf: &mut [u8], write: bool) -> bool {
Ok(()) => {}
Err(e) if e.code() == ERROR_IO_PENDING.to_hresult() => {
if !pump_until(event, None) {
+ // (the app is quitting, or the wait failed: the read or write still holds `ov` and `buf`, see `abandon`)
+ abandon(pipe, &ov);
return false;
}
if unsafe { GetOverlappedResult(pipe, &ov, &mut n, false) }.is_err() {
@@ -192,6 +211,8 @@ pub fn pick(req: &Request, owner: HWND) -> Option<Response> {
Err(e) if e.code() == ERROR_IO_PENDING.to_hresult() => {
if !pump_until(event.0, Some(CONNECT_TIMEOUT)) {
crate::log("pick: rustyfiles didn't connect");
+ // (the connect still holds `ov` on this stack, see `abandon`)
+ abandon(pipe.0, &ov);
return None;
}
}
diff --git a/crates/rf-dialog/src/lib.rs b/crates/rf-dialog/src/lib.rs
index f8a76060..95323d10 100644
--- a/crates/rf-dialog/src/lib.rs
+++ b/crates/rf-dialog/src/lib.rs
@@ -139,11 +139,20 @@ mod com {
}
}
+ /// The picked paths as an item array, each item made as [`item_for`] makes one: a real item of the file system.
+ ///
+ /// WHY (issue 1107: Free Download Manager, a Qt 6 app, took no folder from rustyfiles' picker: "dialog.log: GetResults -> ok",
+ /// and the path box kept the old folder). The array was made of bare ID lists (`SHSimpleIDListFromPath`), which carry no
+ /// attributes: Qt's dialog code asks each item whether it is a file system item (SFGAO_FILESYSTEM) before it reads its path, got
+ /// no, and read nothing. Windows' own dialog gives real items, as `GetResult` here already did (print drivers check the same).
fn items_for(paths: &[String]) -> Result<IShellItemArray> {
let mut pidls: Vec<*mut ITEMIDLIST> = Vec::new();
for p in paths {
- let wide: Vec<u16> = p.encode_utf16().chain(std::iter::once(0)).collect();
- let pidl = unsafe { SHSimpleIDListFromPath(PCWSTR(wide.as_ptr())) };
+ // (the item's own ID list; a bare one only where the item cannot be made)
+ let pidl = item_for(p).ok().and_then(|i| unsafe { SHGetIDListFromObject(&i) }.ok()).unwrap_or_else(|| {
+ let wide: Vec<u16> = p.encode_utf16().chain(std::iter::once(0)).collect();
+ unsafe { SHSimpleIDListFromPath(PCWSTR(wide.as_ptr())) }
+ });
if !pidl.is_null() {
pidls.push(pidl);
}
@@ -200,6 +209,35 @@ mod com {
st: RefCell<State>,
}
+ impl Dialog {
+ /// The paths picked, copied out: the state's borrow is over before a Shell call made with them.
+ ///
+ /// WHY (issue 1126, a private review: "GetResult, GetResults, GetSelectedItems, GetFolder, and GetCurrentSelection hold
+ /// self.st.borrow() across Shell/COM item_for/items_for calls"). A borrow taken in an `if let` lives through its whole
+ /// block. A Shell call made there can come back into this dialog (a Shell extension, the app's own event sink), and a
+ /// `borrow_mut` then panics, inside the app that asked for the dialog.
+ fn picked(&self) -> Option<Vec<String>> {
+ self.st.borrow().result.clone()
+ }
+
+ fn first_picked(&self) -> Option<String> {
+ self.st.borrow().result.as_ref().and_then(|r| r.first().cloned())
+ }
+ }
+
+ /// Windows' dialog is told to forget the relays this wrapper gave it before the wrapper goes (issue 1126: a relay holds the
+ /// wrapper's address without a count, see `Relay`; Windows' dialog could outlive the wrapper while a caller still holds it and
+ /// call a relay that points at freed memory). Each app sink still advised is unadvised here.
+ impl Drop for Dialog {
+ fn drop(&mut self) {
+ let cookies: Vec<u32> = self.st.get_mut().sinks.drain(..).map(|(c, _)| c).collect();
+ for c in cookies {
+ // SAFETY: `real` is alive until this struct is gone, and the cookie came from its own Advise
+ let _ = unsafe { self.real.Unadvise(c) };
+ }
+ }
+ }
+
/// The interfaces a [`Dialog`] has a table for, with the number of entries in each.
const TABLES: [(GUID, usize); 7] = [
(IUnknown::IID, size_of::<windows_core::IInspectable_Vtbl>() / size_of::<usize>()),
@@ -574,7 +612,7 @@ mod com {
}
fn GetFolder(&self) -> Result<IShellItem> {
trace("GetFolder");
- if let Some(first) = self.st.borrow().result.as_ref().and_then(|r| r.first().cloned()) {
+ if let Some(first) = self.first_picked() {
crate::log("GetFolder");
if let Some(dir) = std::path::Path::new(&first).parent() {
return item_for(&dir.to_string_lossy());
@@ -585,10 +623,11 @@ mod com {
fn GetCurrentSelection(&self) -> Result<IShellItem> {
trace("GetCurrentSelection");
// (while the app is asked what it does with a selection: that selection)
- if let Some(p) = self.st.borrow().probe.clone() {
+ let probe = self.st.borrow().probe.clone();
+ if let Some(p) = probe {
return item_for(&p);
}
- if let Some(first) = self.st.borrow().result.as_ref().and_then(|r| r.first().cloned()) {
+ if let Some(first) = self.first_picked() {
return item_for(&first);
}
unsafe { self.real.GetCurrentSelection() }
@@ -625,7 +664,7 @@ mod com {
}
fn GetResult(&self) -> Result<IShellItem> {
trace("GetResult");
- if let Some(first) = self.st.borrow().result.as_ref().and_then(|r| r.first().cloned()) {
+ if let Some(first) = self.first_picked() {
let r = item_for(&first);
// whether the app gets a file system item (what print drivers check)
let fs = r.as_ref().ok().and_then(|i| unsafe { i.GetAttributes(windows::Win32::System::SystemServices::SFGAO_FILESYSTEM) }.ok()).is_some_and(|a| a.0 & windows::Win32::System::SystemServices::SFGAO_FILESYSTEM.0 != 0);
@@ -667,8 +706,8 @@ mod com {
impl IFileOpenDialog_Impl for Dialog_Impl {
fn GetResults(&self) -> Result<IShellItemArray> {
trace("GetResults");
- if let Some(r) = self.st.borrow().result.as_ref() {
- let a = items_for(r);
+ if let Some(r) = self.picked() {
+ let a = items_for(&r);
crate::log(&format!("GetResults -> {}", if a.is_ok() { "ok" } else { "FAILED" }));
return a;
}
@@ -676,8 +715,8 @@ mod com {
}
fn GetSelectedItems(&self) -> Result<IShellItemArray> {
trace("GetSelectedItems");
- if let Some(r) = self.st.borrow().result.as_ref() {
- return items_for(r);
+ if let Some(r) = self.picked() {
+ return items_for(&r);
}
unsafe { self.real.cast::<IFileOpenDialog>()?.GetSelectedItems() }
}
@@ -935,6 +974,30 @@ mod com {
}
}
+ /// Issue 1107: the items of a pick are real file system items, a folder as a folder and a file being saved too, as Qt's
+ /// dialog code asks before it reads their paths.
+ #[test]
+ fn picked_items_are_file_system_items() {
+ use windows::Win32::System::SystemServices::{SFGAO_FILESYSTEM, SFGAO_FOLDER};
+ let dir = std::env::temp_dir().join(format!("rf-dialog-items-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let not_yet = dir.join("new file.txt");
+ unsafe {
+ let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+ let paths = vec![dir.to_string_lossy().into_owned(), not_yet.to_string_lossy().into_owned()];
+ let arr = items_for(&paths).unwrap();
+ assert_eq!(arr.GetCount().unwrap(), 2);
+ let folder = arr.GetItemAt(0).unwrap();
+ let attrs = folder.GetAttributes(SFGAO_FILESYSTEM | SFGAO_FOLDER).unwrap();
+ assert!(attrs.contains(SFGAO_FILESYSTEM) && attrs.contains(SFGAO_FOLDER), "{attrs:?}");
+ assert_eq!(item_path(&folder).map(std::path::PathBuf::from), Some(dir.clone()));
+ let file = arr.GetItemAt(1).unwrap();
+ assert!(file.GetAttributes(SFGAO_FILESYSTEM).unwrap().contains(SFGAO_FILESYSTEM));
+ assert_eq!(item_path(&file).map(std::path::PathBuf::from), Some(not_yet));
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
/// Issue 977: the shell's own processes are left to Windows' dialog, whatever the case of the name; other apps are not.
#[test]
fn the_shell_gets_windows_own_class() {