mirror of
https://github.com/allankoechke/rust.git
synced 2026-11-30 11:05:36 +00:00
Rollup merge of #162602 - bjorn3:safer_fcntl_fallback, r=oli-obk
Ensure concurrent rustc instances in the same process correctly lock the session dir This introduces a global lock registry for the `fcntl` lock fallback to allow 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. Based on https://github.com/rust-lang/rust/pull/162584
This commit is contained in:
@@ -5056,6 +5056,7 @@ dependencies = [
|
||||
"expect-test",
|
||||
"indexmap",
|
||||
"itertools",
|
||||
"libc",
|
||||
"minifier",
|
||||
"proc-macro2",
|
||||
"pulldown-cmark-escape",
|
||||
|
||||
@@ -21,7 +21,7 @@ pub enum Lock {
|
||||
}
|
||||
|
||||
impl Lock {
|
||||
pub fn new(p: &Path, wait: bool, create: bool, exclusive: bool) -> io::Result<Lock> {
|
||||
pub fn try_lock(p: &Path, create: bool, exclusive: bool) -> io::Result<Lock> {
|
||||
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),
|
||||
}
|
||||
|
||||
@@ -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<Mutex<FxHashMap<PathBuf, LockState>>> =
|
||||
LazyLock::new(|| Mutex::new(FxHashMap::default()));
|
||||
|
||||
enum LockState {
|
||||
/// Lock exclusively held. `Lock.file` contains an `Arc<UnlockGuard>` 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<File> },
|
||||
/// Lock can be shared. When there are N lock holders, the `Arc<UnlockGuard>` 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<UnlockGuard>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Lock {
|
||||
file: File,
|
||||
path: PathBuf,
|
||||
file: Option<Arc<UnlockGuard>>,
|
||||
}
|
||||
|
||||
impl Lock {
|
||||
pub fn new(p: &Path, wait: bool, create: bool, exclusive: bool) -> io::Result<Lock> {
|
||||
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<Lock> {
|
||||
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<Self> {
|
||||
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")))]
|
||||
|
||||
@@ -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<Lock> {
|
||||
pub fn try_lock(_p: &Path, _f: File, _exclusive: bool) -> io::Result<Lock> {
|
||||
let msg = "file locks not supported on this platform";
|
||||
Err(io::Error::new(io::ErrorKind::Unsupported, msg))
|
||||
}
|
||||
|
||||
@@ -392,9 +392,8 @@ fn copy_files(sess: &Session, target_dir: &Path, source_dir: &Path) -> Result<bo
|
||||
let lock_file_path = lock_file_path(source_dir);
|
||||
|
||||
// not exclusive
|
||||
let Ok(_lock) = flock::Lock::new(
|
||||
let Ok(_lock) = flock::Lock::try_lock(
|
||||
&lock_file_path,
|
||||
false, // don't wait,
|
||||
false, // don't create
|
||||
false,
|
||||
) else {
|
||||
@@ -477,10 +476,9 @@ fn lock_directory(sess: &Session, session_dir: &Path) -> (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,
|
||||
) {
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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,
|
||||
|
||||
92
src/librustdoc/html/render/write_shared/flock.rs
Normal file
92
src/librustdoc/html/render/write_shared/flock.rs
Normal file
@@ -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<Lock> {
|
||||
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<FcntlLock> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user