cargo/compiler/layout.rs
1//! Management of the directory layout of a build
2//!
3//! The directory layout is a little tricky at times, hence a separate file to
4//! house this logic. Cargo stores build artifacts in two directories: `artifact-dir` and
5//! `build-dir`
6//!
7//! ## `artifact-dir` layout
8//!
9//! `artifact-dir` is where final artifacts like binaries are stored.
10//! The `artifact-dir` layout is consider part of the public API and
11//! cannot be easily changed.
12//!
13//! ```text
14//! <artifact-dir>/
15//!
16//! # Compilation files are grouped by build target and profile.
17//! # The target is omitted if not explicitly specified.
18//! [<target>]/<profile>/ # e.g. `debug` / `release`
19//!
20//! # File used to lock the directory to prevent multiple cargo processes
21//! # from using it at the same time.
22//! .cargo-lock
23//!
24//! # Root directory for all compiled examples.
25//! examples/
26//!
27//! # Output from rustdoc
28//! doc/
29//!
30//! # Output from `cargo package` to build a `.crate` file.
31//! package/
32//! ```
33//!
34//! ## `build-dir` layout
35//!
36//! `build-dir` is where intermediate build artifacts are stored.
37//! The `build-dir` layout is considered an internal implementation detail of Cargo
38//! meaning that we can change this if needed. However, in reality many tools rely on
39//! implementation details of Cargo so breaking changes need to be done carefully.
40//!
41//! ```text
42//! <build-dir>/
43//!
44//! # Cache of `rustc -Vv` output for performance.
45//! .rustc-info.json
46//!
47//! # Compilation files are grouped by build target and profile.
48//! # The target is omitted if not explicitly specified.
49//! [<target>]/<profile>/ # e.g. `debug` / `release`
50//!
51//! # File used to lock the directory to prevent multiple cargo processes
52//! # from using it at the same time.
53//! .cargo-lock
54//!
55//! # Hidden directory that holds all of the fingerprint files for all
56//! # packages
57//! .fingerprint/
58//! # Each package is in a separate directory.
59//! # Note that different target kinds have different filename prefixes.
60//! $pkgname-$META/
61//! # Set of source filenames for this package.
62//! dep-lib-$targetname
63//! # Timestamp when this unit was last built or execution for build scripts.
64//! lib-$targetname.timestamp
65//! # The fingerprint hash.
66//! lib-$targetname
67//! # Detailed information used for logging the reason why
68//! # something is being recompiled.
69//! lib-$targetname.json
70//! # The console output from the compiler. This is cached
71//! # so that warnings can be redisplayed for "fresh" units.
72//! output-lib-$targetname
73//!
74//! # This is the root directory for all rustc artifacts except build
75//! # scripts, examples, and test and bench executables. Almost every
76//! # artifact should have a metadata hash added to its filename to
77//! # prevent collisions. One notable exception is dynamic libraries.
78//! deps/
79//!
80//! # Each artifact dependency gets in its own directory.
81//! /artifact/$pkgname-$META/$kind
82//!
83//! # Root directory for all compiled examples.
84//! examples/
85//!
86//! # Directory used to store incremental data for the compiler (when
87//! # incremental is enabled.
88//! incremental/
89//!
90//! # This is the location at which the output of all custom build
91//! # commands are rooted.
92//! build/
93//!
94//! # Each package gets its own directory where its build script and
95//! # script output are placed
96//! $pkgname-$META/ # For the build script itself.
97//! # The build script executable (name may be changed by user).
98//! build-script-build-$META
99//! # Hard link to build-script-build-$META.
100//! build-script-build
101//! # Dependency information generated by rustc.
102//! build-script-build-$META.d
103//! # Debug information, depending on platform and profile
104//! # settings.
105//! <debug symbols>
106//!
107//! # The package shows up twice with two different metadata hashes.
108//! $pkgname-$META/ # For the output of the build script.
109//! # Directory where script can output files ($OUT_DIR).
110//! out/
111//! # Output from the build script.
112//! output
113//! # Path to `out`, used to help when the target directory is
114//! # moved.
115//! root-output
116//! # Stderr output from the build script.
117//! stderr
118//!
119//! # Used by `cargo package` and `cargo publish` to build a `.crate` file.
120//! package/
121//!
122//! # Experimental feature for generated build scripts.
123//! .metabuild/
124//! ```
125//!
126//! ### New `build-dir` layout
127//!
128//! `build-dir` supports a new "build unit" based layout that is unstable.
129//! It can be enabled via `-Zbuild-dir-new-layout`.
130//! For more info about the layout transition see: [#15010](https://github.com/rust-lang/cargo/issues/15010)
131//!
132//! ```text
133//! <build-dir>/
134//!
135//! # Cache of `rustc -Vv` output for performance.
136//! .rustc-info.json
137//!
138//! # Compilation files are grouped by build target and profile.
139//! # The target is omitted if not explicitly specified.
140//! [<target>]/<profile>/ # e.g. `debug` / `release`
141//!
142//! # File used to lock the directory to prevent multiple cargo processes
143//! # from using it at the same time.
144//! .cargo-lock
145//!
146//! # Directory used to store incremental data for the compiler (when
147//! # incremental is enabled.
148//! incremental/
149//!
150//! # Main directory for storing build unit related files.
151//! # Files are organized by Cargo build unit (`$pkgname/$META`) so that
152//! # related files are stored in a single directory.
153//! build/
154//!
155//! # This is the location at which the output of all files related to
156//! # a given build unit. These files are organized together so that we can
157//! # treat this directly like a single unit for locking and caching.
158//! $pkgname/
159//! $META/
160//! # The general purpose output directory for build units.
161//! # For compilation units, the rustc artifact will be located here.
162//! # For build script run units, this is the $OUT_DIR
163//! out/
164//!
165//! # For artifact dependency units, the output is nested by the kind
166//! artifact/$kind
167//!
168//! # Directory that holds all of the fingerprint files for the build unit.
169//! fingerprint/
170//! # Set of source filenames for this package.
171//! dep-lib-$targetname
172//! # Timestamp when this unit was last built or execution for build scripts.
173//! lib-$targetname.timestamp
174//! # The fingerprint hash.
175//! lib-$targetname
176//! # Detailed information used for logging the reason why
177//! # something is being recompiled.
178//! lib-$targetname.json
179//! # The console output from the compiler. This is cached
180//! # so that warnings can be redisplayed for "fresh" units.
181//! output-lib-$targetname
182//!
183//! # Directory for "execution" units that spawn a process (excluding compilation with
184//! # rustc). Contains the process execution details.
185//! # Currently the only execution unit Cargo supports is running build script
186//! # binaries.
187//! run/
188//! # Stdout output from the process.
189//! stdout
190//! # Stderr output from the process.
191//! stderr
192//! # Path to `out`, used to help when the target directory is
193//! # moved. (build scripts)
194//! root-output
195//!
196//! # Used by `cargo package` and `cargo publish` to build a `.crate` file.
197//! package/
198//!
199//! # Experimental feature for generated build scripts.
200//! .metabuild/
201//! ```
202//!
203//! When cross-compiling, the layout is the same, except it appears in
204//! `target/$TUPLE`.
205
206use crate::compiler::CompileTarget;
207use crate::util::flock::is_on_nfs_mount;
208use crate::util::{CargoResult, FileLock};
209use crate::workspace::Workspace;
210use cargo_util::paths;
211use std::path::{Path, PathBuf};
212
213/// Contains the paths of all target output locations.
214///
215/// See module docs for more information.
216pub struct Layout {
217 artifact_dir: Option<ArtifactDirLayout>,
218 build_dir: BuildDirLayout,
219 _lock: Option<FileLock>,
220}
221
222impl Layout {
223 /// Calculate the paths for build output, lock the build directory, and return as a Layout.
224 ///
225 /// This function will block if the directory is already locked.
226 ///
227 /// `dest` should be the final artifact directory name. Currently either
228 /// "debug" or "release".
229 pub fn new(
230 ws: &Workspace<'_>,
231 target: Option<CompileTarget>,
232 dest: &str,
233 must_take_artifact_dir_lock: bool,
234 must_take_build_dir_lock_exclusively: bool,
235 ) -> CargoResult<Layout> {
236 let is_new_layout = ws.gctx().cli_unstable().build_dir_new_layout;
237 let mut root = ws.target_dir();
238 let mut build_root = ws.build_dir();
239 if let Some(target) = target {
240 root.push(target.short_name());
241 build_root.push(target.short_name());
242 }
243 let build_dest = build_root.join(dest);
244 let dest = root.join(dest);
245 // If the root directory doesn't already exist go ahead and create it
246 // here. Use this opportunity to exclude it from backups as well if the
247 // system supports it since this is a freshly created folder.
248 //
249 // Only the created directory is excluded, not the parents created
250 // along the way, so when one root contains the other, as with a
251 // `--target-dir` inside `build.build-dir`, the outer one is created
252 // first.
253 for dir in outer_first(root.as_path_unlocked(), build_root.as_path_unlocked()) {
254 paths::create_dir_all_excluded_from_backups_atomic(dir)?;
255 }
256
257 // Now that the excluded from backups target root is created we can create the
258 // actual destination (sub)subdirectory.
259 paths::create_dir_all(dest.as_path_unlocked())?;
260
261 let build_dir_lock = if is_on_nfs_mount(build_root.as_path_unlocked()) {
262 None
263 } else {
264 if ws.gctx().cli_unstable().fine_grain_locking && !must_take_build_dir_lock_exclusively
265 {
266 Some(build_dest.open_ro_shared_create(
267 ".cargo-build-lock",
268 ws.gctx(),
269 "build directory",
270 )?)
271 } else {
272 Some(build_dest.open_rw_exclusive_create(
273 ".cargo-build-lock",
274 ws.gctx(),
275 "build directory",
276 )?)
277 }
278 };
279 let build_root = build_root.into_path_unlocked();
280 let build_dest = build_dest.as_path_unlocked();
281 let deps = build_dest.join("deps");
282 let artifact = deps.join("artifact");
283
284 // We take a shared lock on `.cargo-lock` to make sure we don't run currently with
285 // older versions of Cargo (including tools that use Cargo as a library) that don't support
286 // `.cargo-build-lock`.
287 let lock = if is_on_nfs_mount(root.as_path_unlocked()) {
288 None
289 } else {
290 Some(dest.open_ro_shared_create(".cargo-lock", ws.gctx(), "artifact directory")?)
291 };
292
293 let artifact_dir = if must_take_artifact_dir_lock {
294 // For now we don't do any more finer-grained locking on the artifact
295 // directory, so just lock the entire thing for the duration of this
296 // compile.
297 let artifact_dir_lock = if is_on_nfs_mount(root.as_path_unlocked()) {
298 None
299 } else {
300 Some(dest.open_rw_exclusive_create(
301 ".cargo-artifact-lock",
302 ws.gctx(),
303 "artifact directory",
304 )?)
305 };
306 let root = root.into_path_unlocked();
307 let dest = dest.into_path_unlocked();
308 Some(ArtifactDirLayout {
309 dest: dest.clone(),
310 examples: dest.join("examples"),
311 doc: root.join("doc"),
312 timings: root.join("cargo-timings"),
313 _lock: artifact_dir_lock,
314 })
315 } else {
316 None
317 };
318 Ok(Layout {
319 artifact_dir,
320 build_dir: BuildDirLayout {
321 root: build_root.clone(),
322 deps,
323 build: build_dest.join("build"),
324 artifact,
325 incremental: build_dest.join("incremental"),
326 fingerprint: build_dest.join(".fingerprint"),
327 examples: build_dest.join("examples"),
328 tmp: build_root.join("tmp"),
329 _lock: build_dir_lock,
330 is_new_layout,
331 },
332 _lock: lock,
333 })
334 }
335
336 /// Makes sure all directories stored in the Layout exist on the filesystem.
337 pub fn prepare(&mut self) -> CargoResult<()> {
338 if let Some(ref mut artifact_dir) = self.artifact_dir {
339 artifact_dir.prepare()?;
340 }
341 self.build_dir.prepare()?;
342
343 Ok(())
344 }
345
346 pub fn artifact_dir(&self) -> Option<&ArtifactDirLayout> {
347 self.artifact_dir.as_ref()
348 }
349
350 pub fn build_dir(&self) -> &BuildDirLayout {
351 &self.build_dir
352 }
353}
354
355/// Orders two directories so that one that contains the other comes first.
356pub fn outer_first<'a>(a: &'a Path, b: &'a Path) -> [&'a Path; 2] {
357 if a.starts_with(b) { [b, a] } else { [a, b] }
358}
359
360pub struct ArtifactDirLayout {
361 /// The final artifact destination: `<artifact-dir>/debug` (or `release`).
362 dest: PathBuf,
363 /// The directory for examples
364 examples: PathBuf,
365 /// The directory for rustdoc output
366 doc: PathBuf,
367 /// The directory for --timings output
368 timings: PathBuf,
369 /// The lockfile for a build (`.cargo-lock`). Will be unlocked when this
370 /// struct is `drop`ped.
371 _lock: Option<FileLock>,
372}
373
374impl ArtifactDirLayout {
375 /// Makes sure all directories stored in the Layout exist on the filesystem.
376 pub fn prepare(&mut self) -> CargoResult<()> {
377 paths::create_dir_all(&self.examples)?;
378
379 Ok(())
380 }
381 /// Fetch the destination path for final artifacts (`/…/target/debug`).
382 pub fn dest(&self) -> &Path {
383 &self.dest
384 }
385 /// Fetch the examples path.
386 pub fn examples(&self) -> &Path {
387 &self.examples
388 }
389 /// Fetch the doc path.
390 pub fn doc(&self) -> &Path {
391 &self.doc
392 }
393 /// Fetch the cargo-timings path.
394 pub fn timings(&self) -> &Path {
395 &self.timings
396 }
397}
398
399pub struct BuildDirLayout {
400 /// The root directory: `/path/to/build-dir`.
401 /// If cross compiling: `/path/to/build-dir/$TUPLE`.
402 root: PathBuf,
403 /// The directory with rustc artifacts
404 deps: PathBuf,
405 /// The primary directory for build files
406 build: PathBuf,
407 /// The directory for artifacts, i.e. binaries, cdylibs, staticlibs
408 artifact: PathBuf,
409 /// The directory for incremental files
410 incremental: PathBuf,
411 /// The directory for fingerprints
412 fingerprint: PathBuf,
413 /// The directory for pre-uplifted examples: `build-dir/debug/examples`
414 examples: PathBuf,
415 /// The directory for temporary data of integration tests and benches
416 tmp: PathBuf,
417 /// The lockfile for a build (`.cargo-lock`). Will be unlocked when this
418 /// struct is `drop`ped.
419 ///
420 /// Will be `None` when the build-dir and target-dir are the same path as we cannot
421 /// lock the same path twice.
422 _lock: Option<FileLock>,
423 is_new_layout: bool,
424}
425
426impl BuildDirLayout {
427 /// Makes sure all directories stored in the Layout exist on the filesystem.
428 pub fn prepare(&mut self) -> CargoResult<()> {
429 if !self.is_new_layout {
430 paths::create_dir_all(&self.deps)?;
431 paths::create_dir_all(&self.fingerprint)?;
432 paths::create_dir_all(&self.examples)?;
433 }
434 paths::create_dir_all(&self.incremental)?;
435 paths::create_dir_all(&self.build)?;
436
437 Ok(())
438 }
439 /// Fetch the deps path.
440 pub fn deps(&self, pkg_dir: &str) -> PathBuf {
441 if self.is_new_layout {
442 self.out_force_new_layout(pkg_dir)
443 } else {
444 self.legacy_deps().to_path_buf()
445 }
446 }
447 /// Fetch the output path for build units. (new layout only)
448 ///
449 /// New features should consider using this so we can avoid their migrations.
450 pub fn out_force_new_layout(&self, pkg_dir: &str) -> PathBuf {
451 let mut build_dir = self.build_unit(pkg_dir);
452 // This function can be somewhat hot for packages with many dependencies, so reuse the
453 // PathBuf allocation here.
454 build_dir.push("out");
455 build_dir
456 }
457 /// Fetch the deps path. (old layout)
458 pub fn legacy_deps(&self) -> &Path {
459 &self.deps
460 }
461 pub fn root(&self) -> &Path {
462 &self.root
463 }
464 /// Fetch the build examples path.
465 pub fn examples(&self) -> &Path {
466 &self.examples
467 }
468 /// Fetch the incremental path.
469 pub fn incremental(&self) -> &Path {
470 &self.incremental
471 }
472 /// Fetch the fingerprint path.
473 pub fn fingerprint(&self, pkg_dir: &str) -> PathBuf {
474 if self.is_new_layout {
475 self.build_unit(pkg_dir).join("fingerprint")
476 } else {
477 self.legacy_fingerprint().join(pkg_dir)
478 }
479 }
480 /// Fetch the fingerprint path. (old layout)
481 pub fn legacy_fingerprint(&self) -> &Path {
482 &self.fingerprint
483 }
484 /// Fetch the build path.
485 pub fn build(&self) -> &Path {
486 &self.build
487 }
488 /// Fetch the build script path.
489 pub fn build_script(&self, pkg_dir: &str) -> PathBuf {
490 if self.is_new_layout {
491 self.deps(pkg_dir)
492 } else {
493 self.build().join(pkg_dir)
494 }
495 }
496 /// Fetch the build script execution path.
497 pub fn build_script_execution(&self, pkg_dir: &str) -> PathBuf {
498 if self.is_new_layout {
499 self.build_unit(pkg_dir).join("run")
500 } else {
501 self.build().join(pkg_dir)
502 }
503 }
504 /// Fetch the artifact path.
505 pub fn artifact(&self, pkg_dir: &str, kind: &str) -> PathBuf {
506 if self.is_new_layout {
507 self.build_unit(pkg_dir).join("artifact").join(kind)
508 } else {
509 self.artifact.join(pkg_dir).join(kind)
510 }
511 }
512 /// Fetch the build unit path
513 pub fn build_unit(&self, pkg_dir: &str) -> PathBuf {
514 self.build().join(pkg_dir)
515 }
516 /// Create and return the tmp path.
517 pub fn prepare_tmp(&self) -> CargoResult<&Path> {
518 paths::create_dir_all(&self.tmp)?;
519 Ok(&self.tmp)
520 }
521}