Merge pull request #9857 from dotCooCoo/fix/file-locks-unlock-on-drop

Locks: dropping a lock holder unlocks its file
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-27 21:37:36 -08:00
commit a628629f7d
8 files changed
+137 -28

No files matched your search

+22 -12
View File
@@ -220,11 +220,20 @@ fn report_path(dir: &Path) -> PathBuf {
dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id()))
}
/// A report file this process wrote and holds locked until the interface answers again.
/// A report file this process holds locked: the one it wrote, until the interface answers again,
/// or a left one while it is read. Dropping it unlocks the file. A child process that any thread
/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed
/// by closing every copy or by unlocking.
#[derive(Debug)]
pub struct Held {
path: PathBuf,
_file: File,
file: File,
}
impl Drop for Held {
fn drop(&mut self) {
let _ = self.file.unlock();
}
}
/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no
@@ -237,7 +246,7 @@ fn write_report(dir: &Path, text: &str) -> std::io::Result<Held> {
log::warn!("the hang report file is written without a lock: {e}");
}
file.write_all(text.as_bytes())?;
Ok(Held { path, _file: file })
Ok(Held { path, file })
}
/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file
@@ -253,13 +262,14 @@ fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool {
/// The report file at `path`, opened and locked, with its length, when it was abandoned
/// ([`abandoned`]) and is not empty (an empty one may be being written).
fn open_abandoned(path: &Path) -> Option<(File, u64)> {
fn open_abandoned(path: &Path) -> Option<(Held, u64)> {
let file = File::options().read(true).write(true).open(path).ok()?;
if !abandoned(file.try_lock()) {
return None;
}
let len = file.metadata().map_or(0, |m| m.len());
(len > 0).then_some((file, len))
let held = Held { path: path.to_path_buf(), file };
let len = held.file.metadata().map_or(0, |m| m.len());
(len > 0).then_some((held, len))
}
/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None`
@@ -286,20 +296,20 @@ pub fn take_previous(dir: &Path) -> Option<String> {
// Newest first: only abandoned reports count toward the limit.
let mut texts = Vec::new();
for (_, path) in found.into_iter().rev() {
let Some((file, len)) = open_abandoned(&path) else { continue };
let Some((held, len)) = open_abandoned(&path) else { continue };
if texts.len() == MAX_REPORT_FILES {
drop(file);
drop(held);
remove_quietly(&path);
continue;
}
let mut bytes = Vec::new();
let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
let text = if len <= MAX_REPORT_BYTES && (&held.file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
String::from_utf8_lossy(&bytes).into_owned()
} else {
format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n")
};
// Closed (and unlocked) before it is moved: Windows moves no open file.
drop(file);
drop(held);
if !texts.is_empty() {
remove_quietly(&path);
} else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) {
@@ -324,8 +334,8 @@ pub static CLOSING: AtomicBool = AtomicBool::new(false);
/// Remove `held`'s file, closing it first. → the error message; a file already gone is none.
fn remove(held: Held) -> Option<String> {
let Held { path, _file: file } = held;
drop(file);
let path = held.path.clone();
drop(held);
match std::fs::remove_file(&path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()),
_ => None,
+11
View File
@@ -136,6 +136,17 @@ fn a_stall_writes_the_report_file_and_its_end_removes_it() {
assert!(shared.last.lock().unwrap().is_some());
}
#[test]
fn a_dropped_report_frees_its_lock_while_a_copy_of_its_handle_is_open() {
let dir = tempfile::tempdir().unwrap();
let held = write_report(dir.path(), "left\n").unwrap();
// A child process that is starting holds such a copy.
let copy = held.file.try_clone().unwrap();
drop(held);
assert_eq!(take_previous(dir.path()).as_deref(), Some("left\n"), "a dropped report is no longer locked");
drop(copy);
}
#[test]
fn closing_normally_removes_the_report_and_writes_no_more() {
let dir = tempfile::tempdir().unwrap();
+4 -2
View File
@@ -409,7 +409,7 @@ impl FolderStore {
/// names that file.
pub(crate) fn take(file: std::fs::File, path: &std::path::Path) -> std::result::Result<Lock, String> {
match file.try_lock() {
Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(file))),
Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(crate::store::LockedFile::new(file)))),
Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy),
// The lock file was removed meanwhile, and locking it failed instead.
Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy),
@@ -498,7 +498,9 @@ impl RecoveryStore for FolderStore {
Self::lock_area(&dir)
}
fn still_held(&self, area: &str, hold: &(dyn std::any::Any + Send + Sync)) -> bool {
let (Some(file), Ok(dir)) = (hold.downcast_ref::<std::fs::File>(), self.area(area)) else { return true };
let (Some(file), Ok(dir)) = (hold.downcast_ref::<crate::store::LockedFile>().map(crate::store::LockedFile::file), self.area(area)) else {
return true;
};
let path = dir.join(LOCK_FILE);
// Only a lock file or folder that is gone, or another one in its place, ends the hold. One
// that can't be read now (a network folder that doesn't answer) still counts as held.
+4 -4
View File
@@ -1026,7 +1026,7 @@ const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50);
/// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the
/// lock cannot be taken.
#[cfg(not(target_arch = "wasm32"))]
fn lock_store(store: &Path) -> std::io::Result<std::fs::File> {
pub(crate) fn lock_store(store: &Path) -> std::io::Result<crate::store::LockedFile> {
let lock = store.with_extension("lock");
let opened = store
.parent()
@@ -1041,11 +1041,11 @@ fn lock_store(store: &Path) -> std::io::Result<std::fs::File> {
/// `file`, locked within [`lock_store`]'s tries.
#[cfg(not(target_arch = "wasm32"))]
fn take_lock(file: std::fs::File) -> std::io::Result<std::fs::File> {
fn take_lock(file: std::fs::File) -> std::io::Result<crate::store::LockedFile> {
let mut tries = 1;
loop {
match file.try_lock() {
Ok(()) => return Ok(file),
Ok(()) => return Ok(crate::store::LockedFile::new(file)),
Err(std::fs::TryLockError::Error(e)) => return Err(e),
Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => {
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock"));
@@ -1068,7 +1068,7 @@ thread_local! {
/// The browser has no folders to keep anything in.
#[cfg(target_arch = "wasm32")]
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
fn lock_store(_: &Path) -> std::io::Result<crate::store::LockedFile> {
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
}
+41 -10
View File
@@ -491,15 +491,40 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> {
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
}
/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until the file is dropped, waiting while
/// A lock file this process locked, unlocked when it is dropped. A child process that any thread
/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed
/// by closing every copy or by unlocking.
pub(crate) struct LockedFile(std::fs::File);
impl LockedFile {
/// `file`, which the caller has locked.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn new(file: std::fs::File) -> Self {
LockedFile(file)
}
/// The locked file.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn file(&self) -> &std::fs::File {
&self.0
}
}
impl Drop for LockedFile {
fn drop(&mut self) {
let _ = self.0.unlock();
}
}
/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until it is dropped, waiting while
/// another window or process holds it, or another handle in this process. The file is opened for
/// reading and writing (a handle that only appends can't be locked on Windows) and is never
/// replaced or removed, so that every window locks the same file.
#[cfg(not(target_arch = "wasm32"))]
fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
fn lock_store(dir: &Path) -> std::io::Result<LockedFile> {
let file = open_store_lock(dir)?;
match file.try_lock() {
Ok(()) => return Ok(file),
Ok(()) => return Ok(LockedFile::new(file)),
Err(std::fs::TryLockError::WouldBlock) => {}
Err(std::fs::TryLockError::Error(e)) => return Err(e),
}
@@ -508,7 +533,7 @@ fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
waiting();
}
file.lock()?;
Ok(file)
Ok(LockedFile::new(file))
}
/// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked.
@@ -520,10 +545,10 @@ fn open_store_lock(dir: &Path) -> std::io::Result<std::fs::File> {
/// [`lock_store`] without waiting: `None` while another window or process holds the lock.
#[cfg(not(target_arch = "wasm32"))]
fn try_lock_store(dir: &Path) -> std::io::Result<Option<std::fs::File>> {
fn try_lock_store(dir: &Path) -> std::io::Result<Option<LockedFile>> {
let file = open_store_lock(dir)?;
match file.try_lock() {
Ok(()) => Ok(Some(file)),
Ok(()) => Ok(Some(LockedFile::new(file))),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(e)) => Err(e),
}
@@ -531,13 +556,13 @@ fn try_lock_store(dir: &Path) -> std::io::Result<Option<std::fs::File>> {
/// The browser has no folders to keep anything in.
#[cfg(target_arch = "wasm32")]
fn try_lock_store(_: &Path) -> std::io::Result<Option<std::fs::File>> {
fn try_lock_store(_: &Path) -> std::io::Result<Option<LockedFile>> {
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
}
/// The browser has no folders to keep anything in.
#[cfg(target_arch = "wasm32")]
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
fn lock_store(_: &Path) -> std::io::Result<LockedFile> {
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
}
@@ -548,7 +573,7 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
pub(crate) struct StoreTurn {
/// [`DISABLED_LOCK`], locked; `None` without a store, and for a load that goes ahead without
/// a turn ([`Session::plugin_store_turn_for_load`]), which then writes nothing to the store.
lock: Option<std::fs::File>,
lock: Option<LockedFile>,
}
impl StoreTurn {
@@ -557,6 +582,12 @@ impl StoreTurn {
StoreTurn { lock: None }
}
/// Tests: the locked [`DISABLED_LOCK`], when the turn is held.
#[cfg(test)]
pub(crate) fn lock_file(&self) -> Option<&std::fs::File> {
self.lock.as_ref().map(LockedFile::file)
}
/// Whether the store may be written in this turn.
fn held(&self) -> bool {
self.lock.is_some()
@@ -1838,7 +1869,7 @@ impl PluginStorage {
/// A turn on the plug-in store ([`lock_store`]), taken before [`PLUGIN_DATA_LOCK`], so that a
/// window or process changing the same settings or cache waits for this change.
fn turn(&self) -> Result<std::fs::File, StorageError> {
fn turn(&self) -> Result<LockedFile, StorageError> {
lock_store(&self.root).map_err(|e| StorageError::Io(format!("{STORE_NOT_LOCKED}: {e}")))
}
+15
View File
@@ -4256,6 +4256,21 @@ fn installs_from_two_processes_into_one_store_keep_each_module_with_its_grant()
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A turn on a plug-in store that ends frees the store while a copy of the lock file's handle is
/// open, as a child process that is starting holds one: another process can take a turn.
#[test]
fn an_ended_store_turn_frees_the_store_while_a_copy_of_its_handle_is_open() {
let folder = crate::tests_links::Folder::new("plugin-store-turn-copied");
let s = other_process(folder.0.clone());
let turn = s.plugin_store_turn().unwrap();
let copy = turn.lock_file().map(|file| file.try_clone().unwrap());
assert!(copy.is_some(), "the turn is held");
drop(turn);
let other = std::fs::File::options().read(true).write(true).open(folder.0.join(crate::store::DISABLED_LOCK)).unwrap();
assert!(other.try_lock().is_ok(), "an ended turn frees the store");
drop(copy);
}
/// Grants written for two plug-ins into one `Plug-ins` folder by two processes are both kept: the
/// second write reads `grants.json` only once the first has written it.
#[test]
+17
View File
@@ -789,6 +789,23 @@ fn an_area_tidied_away_before_it_is_locked_is_busy() {
let _ = std::fs::remove_dir_all(&base);
}
/// A dropped hold frees its area while a copy of the lock file's handle is open, as a child
/// process that is starting holds one: the area can be locked again.
#[test]
fn a_dropped_hold_frees_the_area_while_a_copy_of_its_handle_is_open() {
use cmd::recovery::Lock;
let base = std::env::temp_dir().join(format!("vc-recovery-copied-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let store = FolderStore::new(&base);
let Ok(Lock::Held(hold)) = store.lock("6-1") else { panic!("the area is locked") };
let copy = hold.downcast_ref::<crate::store::LockedFile>().map(|locked| locked.file().try_clone().unwrap());
assert!(copy.is_some(), "the hold is the locked file");
drop(hold);
assert!(matches!(store.lock("6-1"), Ok(Lock::Held(_))), "a dropped hold frees the area");
drop(copy);
let _ = std::fs::remove_dir_all(&base);
}
/// Opening an area's lock file failed. When the folder went after it was checked, or the lock file
/// is there but can't be opened (a removed lock file that another app still has open, on file
/// systems that keep it until it is closed), the area is busy. A lock file that can't be made is an
+23
View File
@@ -746,6 +746,29 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() {
let _ = std::fs::remove_dir_all(base);
}
/// A grants lock that is dropped frees the grants file while a copy of its handle is open, as a
/// child process that is starting holds one: the next change takes the lock without waiting.
#[test]
fn a_dropped_grants_lock_frees_the_file_while_a_copy_of_its_handle_is_open() {
use crate::script::files::{GRANTS_FILE, WHILE_GRANTS_LOCKED, lock_store, revoke_grants};
let base = folder("grants-lock-copied");
let data = base.join("settings/Script Data");
let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false});
write(&base.join("settings").join(GRANTS_FILE), json!({"version": 1, "grants": [grant]}).to_string().as_bytes());
let lock = lock_store(&base.join("settings").join(GRANTS_FILE)).unwrap();
let copy = lock.file().try_clone().unwrap();
drop(lock);
let waits = std::rc::Rc::new(std::cell::Cell::new(0));
let counted = waits.clone();
WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1))));
let revoked = revoke_grants(&data, None, None);
WHILE_GRANTS_LOCKED.set(None);
assert_eq!(revoked.map_err(|e| e.kind()), Ok(1), "a dropped lock is free");
assert_eq!(waits.get(), 0, "it is taken without waiting");
drop(copy);
let _ = std::fs::remove_dir_all(base);
}
/// `rename` of a file an earlier run wrote names both its old and its new path in `written`.
#[test]
fn a_renamed_file_names_its_old_and_new_paths_in_written() {