diff --git a/Cargo.lock b/Cargo.lock index d0016796d16..28d77841521 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5056,6 +5056,7 @@ dependencies = [ "expect-test", "indexmap", "itertools", + "libc", "minifier", "proc-macro2", "pulldown-cmark-escape", diff --git a/compiler/rustc_data_structures/src/flock.rs b/compiler/rustc_data_structures/src/flock.rs index 3e3aa32f52e..9bd7d06c27f 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(p, wait, create, 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 af1a6b14795..35f865b68a7 100644 --- a/compiler/rustc_data_structures/src/flock/unix.rs +++ b/compiler/rustc_data_structures/src/flock/unix.rs @@ -1,22 +1,100 @@ -use std::fs::{File, OpenOptions}; +use std::collections::hash_map::Entry; +use std::fs::File; use std::os::unix::prelude::*; -use std::path::Path; +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 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 try_lock(p: &Path, file: File, exclusive: bool) -> io::Result { + let mut locks = LOCK_REGISTRY.lock().unwrap(); + 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) + } + } + } + } + Entry::Vacant(vacant) => { + let file = Arc::new(UnlockGuard::try_lock(file, exclusive)?); + + if exclusive { + vacant.insert(LockState::Exclusive { extra_files: vec![] }); + } else { + vacant.insert(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() }; @@ -33,13 +111,12 @@ 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) }; - if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(Lock { file }) } + let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLK, &flock) }; + 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 67757847497..17b83e252d2 100644 --- a/compiler/rustc_data_structures/src/flock/unsupported.rs +++ b/compiler/rustc_data_structures/src/flock/unsupported.rs @@ -1,3 +1,4 @@ +use std::fs::File; use std::io; use std::path::Path; @@ -5,7 +6,7 @@ use std::path::Path; pub struct Lock(()); impl Lock { - pub fn new(_p: &Path, _wait: bool, _create: bool, _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)) } diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index a6394e90586..504e93cf2aa 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -392,9 +392,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 @@ -738,9 +736,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, ) { @@ -807,9 +804,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, ) { 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); + } + } +}