From b4beb1eeeabc82c0e4a73dc3472c64e7871e1613 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 16 Sep 2026 11:32:17 +0200 Subject: [PATCH 1/5] Pass File to Fallback::lock --- compiler/rustc_data_structures/src/flock.rs | 2 +- compiler/rustc_data_structures/src/flock/unix.rs | 12 ++---------- .../rustc_data_structures/src/flock/unsupported.rs | 4 ++-- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/compiler/rustc_data_structures/src/flock.rs b/compiler/rustc_data_structures/src/flock.rs index 3e3aa32f52e..123e7cff3ac 100644 --- a/compiler/rustc_data_structures/src/flock.rs +++ b/compiler/rustc_data_structures/src/flock.rs @@ -42,7 +42,7 @@ impl Lock { match res { Ok(()) => Ok(Lock::FdLocked { _file: file }), Err(err) if matches!(err.kind(), io::ErrorKind::Unsupported) => { - Ok(Lock::Fallback(fallback::Lock::new(p, wait, create, exclusive)?)) + Ok(Lock::Fallback(fallback::Lock::new(file, wait, exclusive)?)) } Err(err) => Err(err), } diff --git a/compiler/rustc_data_structures/src/flock/unix.rs b/compiler/rustc_data_structures/src/flock/unix.rs index af1a6b14795..b4107085565 100644 --- a/compiler/rustc_data_structures/src/flock/unix.rs +++ b/compiler/rustc_data_structures/src/flock/unix.rs @@ -1,6 +1,5 @@ -use std::fs::{File, OpenOptions}; +use std::fs::File; use std::os::unix::prelude::*; -use std::path::Path; use std::{io, mem}; #[derive(Debug)] @@ -9,14 +8,7 @@ pub struct Lock { } impl Lock { - pub fn new(p: &Path, wait: bool, create: bool, exclusive: bool) -> io::Result { - let file = OpenOptions::new() - .read(true) - .write(true) - .create(create) - .mode(libc::S_IRWXU as u32) - .open(p)?; - + pub fn new(file: File, wait: bool, exclusive: bool) -> io::Result { let lock_type = if exclusive { libc::F_WRLCK } else { libc::F_RDLCK }; let mut flock: libc::flock = unsafe { mem::zeroed() }; diff --git a/compiler/rustc_data_structures/src/flock/unsupported.rs b/compiler/rustc_data_structures/src/flock/unsupported.rs index 67757847497..e2f1d8ce22f 100644 --- a/compiler/rustc_data_structures/src/flock/unsupported.rs +++ b/compiler/rustc_data_structures/src/flock/unsupported.rs @@ -1,11 +1,11 @@ +use std::fs::File; use std::io; -use std::path::Path; #[derive(Debug)] pub struct Lock(()); impl Lock { - pub fn new(_p: &Path, _wait: bool, _create: bool, _exclusive: bool) -> io::Result { + pub fn new(_f: File, _wait: bool, _exclusive: bool) -> io::Result { let msg = "file locks not supported on this platform"; Err(io::Error::new(io::ErrorKind::Unsupported, msg)) } From 0143ce1a521e90002ef00d2d189a01a21367b627 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 16 Sep 2026 11:35:09 +0200 Subject: [PATCH 2/5] Have a separate copy of the flock code for rustdoc This copy will retain and is specialized for blocking operations. --- Cargo.lock | 1 + src/librustdoc/Cargo.toml | 1 + src/librustdoc/html/render/write_shared.rs | 5 +- .../html/render/write_shared/flock.rs | 92 +++++++++++++++++++ 4 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 src/librustdoc/html/render/write_shared/flock.rs diff --git a/Cargo.lock b/Cargo.lock index 36213a1e4e4..2b56dc6ab16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5055,6 +5055,7 @@ dependencies = [ "expect-test", "indexmap", "itertools", + "libc", "minifier", "proc-macro2", "pulldown-cmark-escape", diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml index 19600ff2bb6..4d7895264c1 100644 --- a/src/librustdoc/Cargo.toml +++ b/src/librustdoc/Cargo.toml @@ -14,6 +14,7 @@ askama = { version = "0.16.1", default-features = false, features = ["alloc", "c base64 = "0.21.7" indexmap = { version = "2", features = ["serde"] } itertools = "0.15" +libc = "0.2" minifier = { version = "0.4.0", default-features = false } proc-macro2 = "1.0.103" pulldown-cmark-escape = { version = "0.11.0", features = ["simd"] } diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index ab72edacae2..5c963afd3a2 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -26,7 +26,6 @@ use std::{fmt, fs}; use indexmap::IndexMap; use rustc_ast::join_path_syms; -use rustc_data_structures::flock; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_middle::ty::TyCtxt; use rustc_middle::ty::fast_reject::DeepRejectCtxt; @@ -57,6 +56,8 @@ use crate::html::static_files::{self, suffix_path}; use crate::visit::DocVisitor; use crate::{DOC_RUST_LANG_ORG_VERSION, try_err, try_none}; +mod flock; + pub(crate) fn write_shared( cx: &mut Context<'_>, krate: &Crate, @@ -67,7 +68,7 @@ pub(crate) fn write_shared( cx.shared.fs.set_sync_only(true); let lock_file = cx.dst.join(".lock"); // Write shared runs within a flock; disable thread dispatching of IO temporarily. - let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file); + let _lock = try_err!(flock::Lock::new(&lock_file), &lock_file); let search_index = build_index( krate, diff --git a/src/librustdoc/html/render/write_shared/flock.rs b/src/librustdoc/html/render/write_shared/flock.rs new file mode 100644 index 00000000000..385c0bcc84c --- /dev/null +++ b/src/librustdoc/html/render/write_shared/flock.rs @@ -0,0 +1,92 @@ +use std::fs::{File, OpenOptions}; +use std::io; +#[cfg(unix)] +use std::os::unix::prelude::*; +use std::path::Path; + +#[derive(Debug)] +pub(super) enum Lock { + /// A well behaved lock scoped to a single fd/handle and unlocked when closing it. + #[doc(hidden)] + FdLocked { _file: File }, + /// A fallback implementation using the legacy `fcntl(F_SETLK)` which is scoped to + /// an entire process. This should only be used when `flock()` or equivalent sane + /// locking mechanism is unsupported by the OS. + #[doc(hidden)] + #[cfg(unix)] + FcntlFallback { _lock: FcntlLock }, +} + +impl Lock { + pub(super) fn new(p: &Path) -> io::Result { + let mut open_options = OpenOptions::new(); + open_options.read(true).write(true).create(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + open_options.mode(0o600); + } + + let file = open_options.open(p)?; + + match file.lock() { + Ok(()) => Ok(Lock::FdLocked { _file: file }), + #[cfg(unix)] + Err(err) if matches!(err.kind(), io::ErrorKind::Unsupported) => { + Ok(Lock::FcntlFallback { _lock: FcntlLock::new(file)? }) + } + Err(err) => Err(err), + } + } +} + +#[derive(Debug)] +#[cfg(unix)] +pub(super) struct FcntlLock { + file: File, +} + +#[cfg(unix)] +impl FcntlLock { + fn new(file: File) -> io::Result { + let mut flock: libc::flock = unsafe { std::mem::zeroed() }; + #[cfg(not(all(target_os = "hurd", target_arch = "x86")))] + { + flock.l_type = libc::F_WRLCK as libc::c_short; + flock.l_whence = libc::SEEK_SET as libc::c_short; + } + #[cfg(all(target_os = "hurd", target_arch = "x86"))] + { + flock.l_type = libc::F_WRLCK as libc::c_int; + flock.l_whence = libc::SEEK_SET as libc::c_int; + } + flock.l_start = 0; + flock.l_len = 0; + + let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLKW, &flock) }; + if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(FcntlLock { file }) } + } +} + +#[cfg(unix)] +impl Drop for FcntlLock { + fn drop(&mut self) { + let mut flock: libc::flock = unsafe { std::mem::zeroed() }; + #[cfg(not(all(target_os = "hurd", target_arch = "x86")))] + { + flock.l_type = libc::F_UNLCK as libc::c_short; + flock.l_whence = libc::SEEK_SET as libc::c_short; + } + #[cfg(all(target_os = "hurd", target_arch = "x86"))] + { + flock.l_type = libc::F_UNLCK as libc::c_int; + flock.l_whence = libc::SEEK_SET as libc::c_int; + } + flock.l_start = 0; + flock.l_len = 0; + + unsafe { + libc::fcntl(self.file.as_raw_fd(), libc::F_SETLK, &flock); + } + } +} From 435b07d29f2ff479bc26d635d9ae54947f773f0c Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:43:10 +0200 Subject: [PATCH 3/5] Remove wait argument from Lock::new Incr comp only uses the non-blocking variant. --- compiler/rustc_data_structures/src/flock.rs | 13 ++++++------- compiler/rustc_data_structures/src/flock/unix.rs | 5 ++--- .../rustc_data_structures/src/flock/unsupported.rs | 2 +- compiler/rustc_incremental/src/persist/fs.rs | 14 +++++--------- 4 files changed, 14 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_data_structures/src/flock.rs b/compiler/rustc_data_structures/src/flock.rs index 123e7cff3ac..0eb05e5229d 100644 --- a/compiler/rustc_data_structures/src/flock.rs +++ b/compiler/rustc_data_structures/src/flock.rs @@ -21,7 +21,7 @@ pub enum Lock { } impl Lock { - pub fn new(p: &Path, wait: bool, create: bool, exclusive: bool) -> io::Result { + pub fn try_lock(p: &Path, create: bool, exclusive: bool) -> io::Result { let mut open_options = OpenOptions::new(); open_options.read(true).write(true).create(create); #[cfg(unix)] @@ -32,17 +32,16 @@ impl Lock { let file = open_options.open(p)?; - let res = match (wait, exclusive) { - (true, true) => file.lock(), - (true, false) => file.lock_shared(), - (false, true) => file.try_lock().map_err(io::Error::from), - (false, false) => file.try_lock_shared().map_err(io::Error::from), + let res = if exclusive { + file.try_lock().map_err(io::Error::from) + } else { + file.try_lock_shared().map_err(io::Error::from) }; match res { Ok(()) => Ok(Lock::FdLocked { _file: file }), Err(err) if matches!(err.kind(), io::ErrorKind::Unsupported) => { - Ok(Lock::Fallback(fallback::Lock::new(file, wait, exclusive)?)) + Ok(Lock::Fallback(fallback::Lock::try_lock(file, exclusive)?)) } Err(err) => Err(err), } diff --git a/compiler/rustc_data_structures/src/flock/unix.rs b/compiler/rustc_data_structures/src/flock/unix.rs index b4107085565..e9ff4a60b57 100644 --- a/compiler/rustc_data_structures/src/flock/unix.rs +++ b/compiler/rustc_data_structures/src/flock/unix.rs @@ -8,7 +8,7 @@ pub struct Lock { } impl Lock { - pub fn new(file: File, wait: bool, exclusive: bool) -> io::Result { + pub fn try_lock(file: File, exclusive: bool) -> io::Result { let lock_type = if exclusive { libc::F_WRLCK } else { libc::F_RDLCK }; let mut flock: libc::flock = unsafe { mem::zeroed() }; @@ -25,8 +25,7 @@ impl Lock { flock.l_start = 0; flock.l_len = 0; - let cmd = if wait { libc::F_SETLKW } else { libc::F_SETLK }; - let ret = unsafe { libc::fcntl(file.as_raw_fd(), cmd, &flock) }; + let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLK, &flock) }; if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(Lock { file }) } } } diff --git a/compiler/rustc_data_structures/src/flock/unsupported.rs b/compiler/rustc_data_structures/src/flock/unsupported.rs index e2f1d8ce22f..12d2a993858 100644 --- a/compiler/rustc_data_structures/src/flock/unsupported.rs +++ b/compiler/rustc_data_structures/src/flock/unsupported.rs @@ -5,7 +5,7 @@ use std::io; pub struct Lock(()); impl Lock { - pub fn new(_f: File, _wait: bool, _exclusive: bool) -> io::Result { + pub fn try_lock(_f: File, _exclusive: bool) -> io::Result { let msg = "file locks not supported on this platform"; Err(io::Error::new(io::ErrorKind::Unsupported, msg)) } diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index 7493653987a..ba80975c331 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -366,9 +366,8 @@ fn copy_files(sess: &Session, target_dir: &Path, source_dir: &Path) -> Result (flock::Lock, PathBuf) let lock_file_path = lock_file_path(session_dir); debug!("lock_directory() - lock_file: {}", lock_file_path.display()); - match flock::Lock::new( + match flock::Lock::try_lock( &lock_file_path, - false, // don't wait - true, // create the lock file + true, // create the lock file true, ) { // the lock should be exclusive @@ -712,9 +710,8 @@ pub(crate) fn garbage_collect_session_directories( if is_finalized(directory_name) { let lock_file_path = crate_directory.join(lock_file_name); - match flock::Lock::new( + match flock::Lock::try_lock( &lock_file_path, - false, // don't wait false, // don't create the lock-file true, ) { @@ -781,9 +778,8 @@ pub(crate) fn garbage_collect_session_directories( // means that the owning process is still alive and we // leave this directory alone. let lock_file_path = crate_directory.join(lock_file_name); - match flock::Lock::new( + match flock::Lock::try_lock( &lock_file_path, - false, // don't wait false, // don't create the lock-file true, ) { From de50895c4c8c723f8bc9ed633330cb968f84ea57 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 10 Sep 2026 17:58:30 +0200 Subject: [PATCH 4/5] Introduce a global lock registry for the fcntl lock fallback This lock registry allows emulating fd based locks (like flock()) on top of the fcntl(F_SETLK) process based locks, thereby ensuring that concurrent rustc instances inside the same process don't break the incr comp locking scheme. --- compiler/rustc_data_structures/src/flock.rs | 2 +- .../rustc_data_structures/src/flock/unix.rs | 90 ++++++++++++++++++- .../src/flock/unsupported.rs | 3 +- 3 files changed, 89 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_data_structures/src/flock.rs b/compiler/rustc_data_structures/src/flock.rs index 0eb05e5229d..9bd7d06c27f 100644 --- a/compiler/rustc_data_structures/src/flock.rs +++ b/compiler/rustc_data_structures/src/flock.rs @@ -41,7 +41,7 @@ impl Lock { match res { Ok(()) => Ok(Lock::FdLocked { _file: file }), Err(err) if matches!(err.kind(), io::ErrorKind::Unsupported) => { - Ok(Lock::Fallback(fallback::Lock::try_lock(file, exclusive)?)) + Ok(Lock::Fallback(fallback::Lock::try_lock(p, file, exclusive)?)) } Err(err) => Err(err), } diff --git a/compiler/rustc_data_structures/src/flock/unix.rs b/compiler/rustc_data_structures/src/flock/unix.rs index e9ff4a60b57..bceeb84ff52 100644 --- a/compiler/rustc_data_structures/src/flock/unix.rs +++ b/compiler/rustc_data_structures/src/flock/unix.rs @@ -1,14 +1,96 @@ use std::fs::File; use std::os::unix::prelude::*; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock, Mutex}; use std::{io, mem}; +use rustc_hash::FxHashMap; + +static LOCK_REGISTRY: LazyLock>> = + LazyLock::new(|| Mutex::new(FxHashMap::default())); + +enum LockState { + /// Lock exclusively held. `Lock.file` contains an `Arc` with a single reference. + /// + /// The `extra_files` fields contains files we opened while the lock was held. We have to + /// persist them until we actually want to unlock the file to prevent unlocking on close. + Exclusive { extra_files: Vec }, + /// Lock can be shared. When there are N lock holders, the `Arc` has N+1 references + /// with the last one being held by `LockState` and getting removed in the drop impl of `Lock` + /// if it is the remaining reference. + Shared(Arc), +} + #[derive(Debug)] pub struct Lock { - file: File, + path: PathBuf, + file: Option>, } impl Lock { - pub fn try_lock(file: File, exclusive: bool) -> io::Result { + pub fn try_lock(p: &Path, file: File, exclusive: bool) -> io::Result { + let mut locks = LOCK_REGISTRY.lock().unwrap(); + + let file = if let Some(state) = locks.get_mut(p) { + // We must not open the file again if there is an existing lock to prevent the close + // from unlocking the file even when another `Lock` already had the lock held before + // this `Lock::try_lock` call. + match state { + LockState::Exclusive { extra_files } => { + // Retain file to prevent unlock on close + extra_files.push(file); + + return Err(io::ErrorKind::WouldBlock.into()); + } + LockState::Shared(file) => { + if exclusive { + return Err(io::ErrorKind::WouldBlock.into()); + } else { + Arc::clone(file) + } + } + } + } else { + let file = Arc::new(UnlockGuard::try_lock(file, exclusive)?); + + if exclusive { + locks.insert(p.to_owned(), LockState::Exclusive { extra_files: vec![] }); + } else { + locks.insert(p.to_owned(), LockState::Shared(Arc::clone(&file))); + } + + file + }; + + Ok(Lock { path: p.to_owned(), file: Some(file) }) + } +} + +impl Drop for Lock { + fn drop(&mut self) { + let mut locks = LOCK_REGISTRY.lock().unwrap(); + self.file.take().unwrap(); + match locks.get_mut(&self.path).unwrap() { + LockState::Exclusive { extra_files: _ } => { + locks.remove(&self.path); + } + LockState::Shared(file) => { + if Arc::strong_count(file) == 1 { + locks.remove(&self.path); + } + } + } + } +} + +/// A file guard which will unlock the file when dropped. +#[derive(Debug)] +struct UnlockGuard { + file: File, +} + +impl UnlockGuard { + fn try_lock(file: File, exclusive: bool) -> io::Result { let lock_type = if exclusive { libc::F_WRLCK } else { libc::F_RDLCK }; let mut flock: libc::flock = unsafe { mem::zeroed() }; @@ -26,11 +108,11 @@ impl Lock { flock.l_len = 0; let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLK, &flock) }; - if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(Lock { file }) } + if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(Self { file }) } } } -impl Drop for Lock { +impl Drop for UnlockGuard { fn drop(&mut self) { let mut flock: libc::flock = unsafe { mem::zeroed() }; #[cfg(not(all(target_os = "hurd", target_arch = "x86")))] diff --git a/compiler/rustc_data_structures/src/flock/unsupported.rs b/compiler/rustc_data_structures/src/flock/unsupported.rs index 12d2a993858..17b83e252d2 100644 --- a/compiler/rustc_data_structures/src/flock/unsupported.rs +++ b/compiler/rustc_data_structures/src/flock/unsupported.rs @@ -1,11 +1,12 @@ use std::fs::File; use std::io; +use std::path::Path; #[derive(Debug)] pub struct Lock(()); impl Lock { - pub fn try_lock(_f: File, _exclusive: bool) -> io::Result { + pub fn try_lock(_p: &Path, _f: File, _exclusive: bool) -> io::Result { let msg = "file locks not supported on this platform"; Err(io::Error::new(io::ErrorKind::Unsupported, msg)) } From 2be177e4a2b01471d86b31bc9d0c35fc65f42e79 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 17 Sep 2026 11:33:58 +0200 Subject: [PATCH 5/5] Use HashMap::entry --- .../rustc_data_structures/src/flock/unix.rs | 48 ++++++++++--------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_data_structures/src/flock/unix.rs b/compiler/rustc_data_structures/src/flock/unix.rs index bceeb84ff52..35f865b68a7 100644 --- a/compiler/rustc_data_structures/src/flock/unix.rs +++ b/compiler/rustc_data_structures/src/flock/unix.rs @@ -1,3 +1,4 @@ +use std::collections::hash_map::Entry; use std::fs::File; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; @@ -31,35 +32,38 @@ impl Lock { pub fn try_lock(p: &Path, file: File, exclusive: bool) -> io::Result { let mut locks = LOCK_REGISTRY.lock().unwrap(); - let file = if let Some(state) = locks.get_mut(p) { - // We must not open the file again if there is an existing lock to prevent the close - // from unlocking the file even when another `Lock` already had the lock held before - // this `Lock::try_lock` call. - match state { - LockState::Exclusive { extra_files } => { - // Retain file to prevent unlock on close - extra_files.push(file); + let file = match locks.entry(p.to_owned()) { + Entry::Occupied(mut state) => { + // We must not open the file again if there is an existing lock to prevent the close + // from unlocking the file even when another `Lock` already had the lock held before + // this `Lock::try_lock` call. + match state.get_mut() { + LockState::Exclusive { extra_files } => { + // Retain file to prevent unlock on close + extra_files.push(file); - return Err(io::ErrorKind::WouldBlock.into()); - } - LockState::Shared(file) => { - if exclusive { return Err(io::ErrorKind::WouldBlock.into()); - } else { - Arc::clone(file) + } + LockState::Shared(file) => { + if exclusive { + return Err(io::ErrorKind::WouldBlock.into()); + } else { + Arc::clone(file) + } } } } - } else { - let file = Arc::new(UnlockGuard::try_lock(file, exclusive)?); + Entry::Vacant(vacant) => { + let file = Arc::new(UnlockGuard::try_lock(file, exclusive)?); - if exclusive { - locks.insert(p.to_owned(), LockState::Exclusive { extra_files: vec![] }); - } else { - locks.insert(p.to_owned(), LockState::Shared(Arc::clone(&file))); + if exclusive { + vacant.insert(LockState::Exclusive { extra_files: vec![] }); + } else { + vacant.insert(LockState::Shared(Arc::clone(&file))); + } + + file } - - file }; Ok(Lock { path: p.to_owned(), file: Some(file) })