shared_target_core/lock.rs
1//! Taking part in Cargo's build lock, so that a tree is not read while it is
2//! being written.
3//!
4//! Cargo holds a lock for the length of a build. Reading a target directory
5//! without it can capture an artifact and then, moments later, the fingerprint
6//! written after it — a destination tree that is torn in exactly the way the
7//! staging rename exists to prevent, and torn silently, because what Cargo
8//! reads afterwards says fresh.
9//!
10//! What this locks is not a stable contract. The path and the mechanism are
11//! Cargo's internals, so [`BuildLocks::held`] is reported rather than assumed:
12//! holding nothing is a fact about this run, not a guarantee about it.
13
14use std::fs::File;
15use std::path::{Path, PathBuf};
16
17use crate::error::{Error, Result};
18
19/// Cargo's lock file, one per profile directory.
20const LOCK_FILE: &str = ".cargo-lock";
21
22/// Locks held for as long as this value lives. Dropping it closes the
23/// descriptors, which is what releases them.
24pub struct BuildLocks {
25 held: Vec<(PathBuf, File)>,
26}
27
28impl BuildLocks {
29 /// The lock files being held. Empty means none were found — a target
30 /// directory nothing has built in yet, a Cargo that has moved them, or a
31 /// platform without the call. It does not mean the tree is quiet.
32 pub fn held(&self) -> impl ExactSizeIterator<Item = &Path> {
33 self.held.iter().map(|(path, _)| path.as_path())
34 }
35}
36
37/// Takes a shared lock on every profile lock under `src`.
38///
39/// Shared rather than exclusive: several of these may run at once, and what
40/// must not overlap is this and a build. Refused rather than waited on — a
41/// caller told that a build is running can decide, where one left blocking on
42/// a `cargo build` that has forty crates to go cannot.
43pub fn acquire(src: &Path) -> Result<BuildLocks> {
44 let mut held = Vec::new();
45
46 for path in lock_files(src)? {
47 if let Some(file) = lock_shared(&path)? {
48 held.push((path, file));
49 }
50 }
51
52 Ok(BuildLocks { held })
53}
54
55/// Cargo puts its lock in the profile directory — `<target>/debug` — and one
56/// level deeper when the build was given a target triple:
57/// `<target>/x86_64-unknown-linux-gnu/debug`.
58///
59/// Looked for in those two places rather than by walking. A profile directory
60/// holds the artifacts, so descending into one to search for a lock file would
61/// mean listing tens of thousands of entries to find something that is not
62/// there.
63fn lock_files(src: &Path) -> Result<Vec<PathBuf>> {
64 let mut found = Vec::new();
65
66 for candidate in directories_in(src)? {
67 let direct = candidate.join(LOCK_FILE);
68 if direct.is_file() {
69 found.push(direct);
70 // A profile directory holds no further profile directories, and it
71 // is the expensive one to list.
72 continue;
73 }
74
75 for nested in directories_in(&candidate)? {
76 let deeper = nested.join(LOCK_FILE);
77 if deeper.is_file() {
78 found.push(deeper);
79 }
80 }
81 }
82
83 Ok(found)
84}
85
86fn directories_in(path: &Path) -> Result<Vec<PathBuf>> {
87 let entries = std::fs::read_dir(path).map_err(Error::io("reading", path))?;
88 let mut directories = Vec::new();
89
90 for entry in entries {
91 let entry = entry.map_err(Error::io("reading", path))?;
92 if entry.path().is_dir() {
93 directories.push(entry.path());
94 }
95 }
96
97 Ok(directories)
98}
99
100#[cfg(unix)]
101fn lock_shared(path: &Path) -> Result<Option<File>> {
102 use rustix::fs::{FlockOperation, flock};
103
104 let file = File::open(path).map_err(Error::io("opening the build lock", path))?;
105
106 match flock(&file, FlockOperation::NonBlockingLockShared) {
107 Ok(()) => Ok(Some(file)),
108 Err(rustix::io::Errno::WOULDBLOCK) => Err(Error::SourceBusy {
109 path: path.to_path_buf(),
110 }),
111 Err(errno) => Err(Error::Io {
112 op: "locking",
113 path: path.to_path_buf(),
114 source: errno.into(),
115 }),
116 }
117}
118
119#[cfg(not(unix))]
120fn lock_shared(_path: &Path) -> Result<Option<File>> {
121 // Nothing is claimed here rather than something being claimed falsely. The
122 // count of locks held stays at zero, and the caller reports that.
123 Ok(None)
124}