]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/lib.rs
Auto merge of #107443 - cjgillot:generator-less-query, r=compiler-errors
[rust.git] / src / bootstrap / lib.rs
1 //! Implementation of rustbuild, the Rust build system.
2 //!
3 //! This module, and its descendants, are the implementation of the Rust build
4 //! system. Most of this build system is backed by Cargo but the outer layer
5 //! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
6 //! builds, building artifacts like LLVM, etc. The goals of rustbuild are:
7 //!
8 //! * To be an easily understandable, easily extensible, and maintainable build
9 //!   system.
10 //! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
11 //!   crates.io and Cargo.
12 //! * A standard interface to build across all platforms, including MSVC
13 //!
14 //! ## Architecture
15 //!
16 //! The build system defers most of the complicated logic managing invocations
17 //! of rustc and rustdoc to Cargo itself. However, moving through various stages
18 //! and copying artifacts is still necessary for it to do. Each time rustbuild
19 //! is invoked, it will iterate through the list of predefined steps and execute
20 //! each serially in turn if it matches the paths passed or is a default rule.
21 //! For each step rustbuild relies on the step internally being incremental and
22 //! parallel. Note, though, that the `-j` parameter to rustbuild gets forwarded
23 //! to appropriate test harnesses and such.
24 //!
25 //! Most of the "meaty" steps that matter are backed by Cargo, which does indeed
26 //! have its own parallelism and incremental management. Later steps, like
27 //! tests, aren't incremental and simply run the entire suite currently.
28 //! However, compiletest itself tries to avoid running tests when the artifacts
29 //! that are involved (mainly the compiler) haven't changed.
30 //!
31 //! When you execute `x.py build`, the steps executed are:
32 //!
33 //! * First, the python script is run. This will automatically download the
34 //!   stage0 rustc and cargo according to `src/stage0.json`, or use the cached
35 //!   versions if they're available. These are then used to compile rustbuild
36 //!   itself (using Cargo). Finally, control is then transferred to rustbuild.
37 //!
38 //! * Rustbuild takes over, performs sanity checks, probes the environment,
39 //!   reads configuration, and starts executing steps as it reads the command
40 //!   line arguments (paths) or going through the default rules.
41 //!
42 //!   The build output will be something like the following:
43 //!
44 //!   Building stage0 std artifacts
45 //!   Copying stage0 std
46 //!   Building stage0 test artifacts
47 //!   Copying stage0 test
48 //!   Building stage0 compiler artifacts
49 //!   Copying stage0 rustc
50 //!   Assembling stage1 compiler
51 //!   Building stage1 std artifacts
52 //!   Copying stage1 std
53 //!   Building stage1 test artifacts
54 //!   Copying stage1 test
55 //!   Building stage1 compiler artifacts
56 //!   Copying stage1 rustc
57 //!   Assembling stage2 compiler
58 //!   Uplifting stage1 std
59 //!   Uplifting stage1 test
60 //!   Uplifting stage1 rustc
61 //!
62 //! Let's disect that a little:
63 //!
64 //! ## Building stage0 {std,test,compiler} artifacts
65 //!
66 //! These steps use the provided (downloaded, usually) compiler to compile the
67 //! local Rust source into libraries we can use.
68 //!
69 //! ## Copying stage0 {std,test,rustc}
70 //!
71 //! This copies the build output from Cargo into
72 //! `build/$HOST/stage0-sysroot/lib/rustlib/$ARCH/lib`. FIXME: this step's
73 //! documentation should be expanded -- the information already here may be
74 //! incorrect.
75 //!
76 //! ## Assembling stage1 compiler
77 //!
78 //! This copies the libraries we built in "building stage0 ... artifacts" into
79 //! the stage1 compiler's lib directory. These are the host libraries that the
80 //! compiler itself uses to run. These aren't actually used by artifacts the new
81 //! compiler generates. This step also copies the rustc and rustdoc binaries we
82 //! generated into build/$HOST/stage/bin.
83 //!
84 //! The stage1/bin/rustc is a fully functional compiler, but it doesn't yet have
85 //! any libraries to link built binaries or libraries to. The next 3 steps will
86 //! provide those libraries for it; they are mostly equivalent to constructing
87 //! the stage1/bin compiler so we don't go through them individually.
88 //!
89 //! ## Uplifting stage1 {std,test,rustc}
90 //!
91 //! This step copies the libraries from the stage1 compiler sysroot into the
92 //! stage2 compiler. This is done to avoid rebuilding the compiler; libraries
93 //! we'd build in this step should be identical (in function, if not necessarily
94 //! identical on disk) so there's no need to recompile the compiler again. Note
95 //! that if you want to, you can enable the full-bootstrap option to change this
96 //! behavior.
97 //!
98 //! Each step is driven by a separate Cargo project and rustbuild orchestrates
99 //! copying files between steps and otherwise preparing for Cargo to run.
100 //!
101 //! ## Further information
102 //!
103 //! More documentation can be found in each respective module below, and you can
104 //! also check out the `src/bootstrap/README.md` file for more information.
105
106 use std::cell::{Cell, RefCell};
107 use std::collections::{HashMap, HashSet};
108 use std::env;
109 use std::fs::{self, File};
110 use std::io;
111 use std::io::ErrorKind;
112 use std::path::{Path, PathBuf};
113 use std::process::{Command, Stdio};
114 use std::str;
115
116 use build_helper::ci::CiEnv;
117 use channel::GitInfo;
118 use config::{DryRun, Target};
119 use filetime::FileTime;
120 use once_cell::sync::OnceCell;
121
122 use crate::builder::Kind;
123 use crate::config::{LlvmLibunwind, TargetSelection};
124 use crate::util::{
125     exe, libdir, mtime, output, run, run_suppressed, symlink_dir, try_run_suppressed,
126 };
127
128 mod bolt;
129 mod builder;
130 mod cache;
131 mod cc_detect;
132 mod channel;
133 mod check;
134 mod clean;
135 mod compile;
136 mod config;
137 mod dist;
138 mod doc;
139 mod download;
140 mod flags;
141 mod format;
142 mod install;
143 mod metadata;
144 mod native;
145 mod run;
146 mod sanity;
147 mod setup;
148 mod tarball;
149 mod test;
150 mod tool;
151 mod toolstate;
152 pub mod util;
153
154 #[cfg(feature = "build-metrics")]
155 mod metrics;
156
157 #[cfg(windows)]
158 mod job;
159
160 #[cfg(all(unix, not(target_os = "haiku")))]
161 mod job {
162     pub unsafe fn setup(build: &mut crate::Build) {
163         if build.config.low_priority {
164             libc::setpriority(libc::PRIO_PGRP as _, 0, 10);
165         }
166     }
167 }
168
169 #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))]
170 mod job {
171     pub unsafe fn setup(_build: &mut crate::Build) {}
172 }
173
174 pub use crate::builder::PathSet;
175 use crate::cache::{Interned, INTERNER};
176 pub use crate::config::Config;
177 pub use crate::flags::Subcommand;
178
179 const LLVM_TOOLS: &[&str] = &[
180     "llvm-cov",      // used to generate coverage report
181     "llvm-nm",       // used to inspect binaries; it shows symbol names, their sizes and visibility
182     "llvm-objcopy",  // used to transform ELFs into binary format which flashing tools consume
183     "llvm-objdump",  // used to disassemble programs
184     "llvm-profdata", // used to inspect and merge files generated by profiles
185     "llvm-readobj",  // used to get information from ELFs/objects that the other tools don't provide
186     "llvm-size",     // used to prints the size of the linker sections of a program
187     "llvm-strip",    // used to discard symbols from binary files to reduce their size
188     "llvm-ar",       // used for creating and modifying archive files
189     "llvm-as",       // used to convert LLVM assembly to LLVM bitcode
190     "llvm-dis",      // used to disassemble LLVM bitcode
191     "llc",           // used to compile LLVM bytecode
192     "opt",           // used to optimize LLVM bytecode
193 ];
194
195 /// LLD file names for all flavors.
196 const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
197
198 pub const VERSION: usize = 2;
199
200 /// Extra --check-cfg to add when building
201 /// (Mode restriction, config name, config values (if any))
202 const EXTRA_CHECK_CFGS: &[(Option<Mode>, &'static str, Option<&[&'static str]>)] = &[
203     (None, "bootstrap", None),
204     (Some(Mode::Rustc), "parallel_compiler", None),
205     (Some(Mode::ToolRustc), "parallel_compiler", None),
206     (Some(Mode::Codegen), "parallel_compiler", None),
207     (Some(Mode::Std), "stdarch_intel_sde", None),
208     (Some(Mode::Std), "no_fp_fmt_parse", None),
209     (Some(Mode::Std), "no_global_oom_handling", None),
210     (Some(Mode::Std), "no_rc", None),
211     (Some(Mode::Std), "no_sync", None),
212     (Some(Mode::Std), "freebsd12", None),
213     (Some(Mode::Std), "backtrace_in_libstd", None),
214     /* Extra values not defined in the built-in targets yet, but used in std */
215     (Some(Mode::Std), "target_env", Some(&["libnx"])),
216     // (Some(Mode::Std), "target_os", Some(&[])),
217     (Some(Mode::Std), "target_arch", Some(&["asmjs", "spirv", "nvptx", "xtensa"])),
218     /* Extra names used by dependencies */
219     // FIXME: Used by serde_json, but we should not be triggering on external dependencies.
220     (Some(Mode::Rustc), "no_btreemap_remove_entry", None),
221     (Some(Mode::ToolRustc), "no_btreemap_remove_entry", None),
222     // FIXME: Used by crossbeam-utils, but we should not be triggering on external dependencies.
223     (Some(Mode::Rustc), "crossbeam_loom", None),
224     (Some(Mode::ToolRustc), "crossbeam_loom", None),
225     // FIXME: Used by proc-macro2, but we should not be triggering on external dependencies.
226     (Some(Mode::Rustc), "span_locations", None),
227     (Some(Mode::ToolRustc), "span_locations", None),
228     // FIXME: Used by rustix, but we should not be triggering on external dependencies.
229     (Some(Mode::Rustc), "rustix_use_libc", None),
230     (Some(Mode::ToolRustc), "rustix_use_libc", None),
231     // FIXME: Used by filetime, but we should not be triggering on external dependencies.
232     (Some(Mode::Rustc), "emulate_second_only_system", None),
233     (Some(Mode::ToolRustc), "emulate_second_only_system", None),
234 ];
235
236 /// A structure representing a Rust compiler.
237 ///
238 /// Each compiler has a `stage` that it is associated with and a `host` that
239 /// corresponds to the platform the compiler runs on. This structure is used as
240 /// a parameter to many methods below.
241 #[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
242 pub struct Compiler {
243     stage: u32,
244     host: TargetSelection,
245 }
246
247 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
248 pub enum DocTests {
249     /// Run normal tests and doc tests (default).
250     Yes,
251     /// Do not run any doc tests.
252     No,
253     /// Only run doc tests.
254     Only,
255 }
256
257 pub enum GitRepo {
258     Rustc,
259     Llvm,
260 }
261
262 /// Global configuration for the build system.
263 ///
264 /// This structure transitively contains all configuration for the build system.
265 /// All filesystem-encoded configuration is in `config`, all flags are in
266 /// `flags`, and then parsed or probed information is listed in the keys below.
267 ///
268 /// This structure is a parameter of almost all methods in the build system,
269 /// although most functions are implemented as free functions rather than
270 /// methods specifically on this structure itself (to make it easier to
271 /// organize).
272 pub struct Build {
273     /// User-specified configuration from `config.toml`.
274     config: Config,
275
276     // Version information
277     version: String,
278
279     // Properties derived from the above configuration
280     src: PathBuf,
281     out: PathBuf,
282     bootstrap_out: PathBuf,
283     cargo_info: channel::GitInfo,
284     rust_analyzer_info: channel::GitInfo,
285     clippy_info: channel::GitInfo,
286     miri_info: channel::GitInfo,
287     rustfmt_info: channel::GitInfo,
288     in_tree_llvm_info: channel::GitInfo,
289     local_rebuild: bool,
290     fail_fast: bool,
291     doc_tests: DocTests,
292     verbosity: usize,
293
294     // Targets for which to build
295     build: TargetSelection,
296     hosts: Vec<TargetSelection>,
297     targets: Vec<TargetSelection>,
298
299     initial_rustc: PathBuf,
300     initial_cargo: PathBuf,
301     initial_lld: PathBuf,
302     initial_libdir: PathBuf,
303
304     // Runtime state filled in later on
305     // C/C++ compilers and archiver for all targets
306     cc: HashMap<TargetSelection, cc::Tool>,
307     cxx: HashMap<TargetSelection, cc::Tool>,
308     ar: HashMap<TargetSelection, PathBuf>,
309     ranlib: HashMap<TargetSelection, PathBuf>,
310     // Miscellaneous
311     // allow bidirectional lookups: both name -> path and path -> name
312     crates: HashMap<Interned<String>, Crate>,
313     crate_paths: HashMap<PathBuf, Interned<String>>,
314     is_sudo: bool,
315     ci_env: CiEnv,
316     delayed_failures: RefCell<Vec<String>>,
317     prerelease_version: Cell<Option<u32>>,
318     tool_artifacts:
319         RefCell<HashMap<TargetSelection, HashMap<String, (&'static str, PathBuf, Vec<String>)>>>,
320
321     #[cfg(feature = "build-metrics")]
322     metrics: metrics::BuildMetrics,
323 }
324
325 #[derive(Debug)]
326 struct Crate {
327     name: Interned<String>,
328     deps: HashSet<Interned<String>>,
329     path: PathBuf,
330 }
331
332 impl Crate {
333     fn local_path(&self, build: &Build) -> PathBuf {
334         self.path.strip_prefix(&build.config.src).unwrap().into()
335     }
336 }
337
338 /// When building Rust various objects are handled differently.
339 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
340 pub enum DependencyType {
341     /// Libraries originating from proc-macros.
342     Host,
343     /// Typical Rust libraries.
344     Target,
345     /// Non Rust libraries and objects shipped to ease usage of certain targets.
346     TargetSelfContained,
347 }
348
349 /// The various "modes" of invoking Cargo.
350 ///
351 /// These entries currently correspond to the various output directories of the
352 /// build system, with each mod generating output in a different directory.
353 #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
354 pub enum Mode {
355     /// Build the standard library, placing output in the "stageN-std" directory.
356     Std,
357
358     /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
359     Rustc,
360
361     /// Build a codegen backend for rustc, placing the output in the "stageN-codegen" directory.
362     Codegen,
363
364     /// Build a tool, placing output in the "stage0-bootstrap-tools"
365     /// directory. This is for miscellaneous sets of tools that are built
366     /// using the bootstrap stage0 compiler in its entirety (target libraries
367     /// and all). Typically these tools compile with stable Rust.
368     ToolBootstrap,
369
370     /// Build a tool which uses the locally built std, placing output in the
371     /// "stageN-tools" directory. Its usage is quite rare, mainly used by
372     /// compiletest which needs libtest.
373     ToolStd,
374
375     /// Build a tool which uses the locally built rustc and the target std,
376     /// placing the output in the "stageN-tools" directory. This is used for
377     /// anything that needs a fully functional rustc, such as rustdoc, clippy,
378     /// cargo, rls, rustfmt, miri, etc.
379     ToolRustc,
380 }
381
382 impl Mode {
383     pub fn is_tool(&self) -> bool {
384         matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd)
385     }
386
387     pub fn must_support_dlopen(&self) -> bool {
388         matches!(self, Mode::Std | Mode::Codegen)
389     }
390 }
391
392 pub enum CLang {
393     C,
394     Cxx,
395 }
396
397 macro_rules! forward {
398     ( $( $fn:ident( $($param:ident: $ty:ty),* ) $( -> $ret:ty)? ),+ $(,)? ) => {
399         impl Build {
400             $( fn $fn(&self, $($param: $ty),* ) $( -> $ret)? {
401                 self.config.$fn( $($param),* )
402             } )+
403         }
404     }
405 }
406
407 forward! {
408     verbose(msg: &str),
409     is_verbose() -> bool,
410     create(path: &Path, s: &str),
411     remove(f: &Path),
412     tempdir() -> PathBuf,
413     try_run(cmd: &mut Command) -> bool,
414     llvm_link_shared() -> bool,
415     download_rustc() -> bool,
416     initial_rustfmt() -> Option<PathBuf>,
417 }
418
419 impl Build {
420     /// Creates a new set of build configuration from the `flags` on the command
421     /// line and the filesystem `config`.
422     ///
423     /// By default all build output will be placed in the current directory.
424     pub fn new(mut config: Config) -> Build {
425         let src = config.src.clone();
426         let out = config.out.clone();
427
428         #[cfg(unix)]
429         // keep this consistent with the equivalent check in x.py:
430         // https://github.com/rust-lang/rust/blob/a8a33cf27166d3eabaffc58ed3799e054af3b0c6/src/bootstrap/bootstrap.py#L796-L797
431         let is_sudo = match env::var_os("SUDO_USER") {
432             Some(_sudo_user) => {
433                 let uid = unsafe { libc::getuid() };
434                 uid == 0
435             }
436             None => false,
437         };
438         #[cfg(not(unix))]
439         let is_sudo = false;
440
441         let ignore_git = config.ignore_git;
442         let rust_info = channel::GitInfo::new(ignore_git, &src);
443         let cargo_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/cargo"));
444         let rust_analyzer_info =
445             channel::GitInfo::new(ignore_git, &src.join("src/tools/rust-analyzer"));
446         let clippy_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/clippy"));
447         let miri_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/miri"));
448         let rustfmt_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/rustfmt"));
449
450         // we always try to use git for LLVM builds
451         let in_tree_llvm_info = channel::GitInfo::new(false, &src.join("src/llvm-project"));
452
453         let initial_target_libdir_str = if config.dry_run() {
454             "/dummy/lib/path/to/lib/".to_string()
455         } else {
456             output(
457                 Command::new(&config.initial_rustc)
458                     .arg("--target")
459                     .arg(config.build.rustc_target_arg())
460                     .arg("--print")
461                     .arg("target-libdir"),
462             )
463         };
464         let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
465         let initial_lld = initial_target_dir.join("bin").join("rust-lld");
466
467         let initial_sysroot = if config.dry_run() {
468             "/dummy".to_string()
469         } else {
470             output(Command::new(&config.initial_rustc).arg("--print").arg("sysroot"))
471         };
472         let initial_libdir = initial_target_dir
473             .parent()
474             .unwrap()
475             .parent()
476             .unwrap()
477             .strip_prefix(initial_sysroot.trim())
478             .unwrap()
479             .to_path_buf();
480
481         let version = std::fs::read_to_string(src.join("src").join("version"))
482             .expect("failed to read src/version");
483         let version = version.trim();
484
485         let bootstrap_out = std::env::current_exe()
486             .expect("could not determine path to running process")
487             .parent()
488             .unwrap()
489             .to_path_buf();
490         if !bootstrap_out.join(exe("rustc", config.build)).exists() && !cfg!(test) {
491             // this restriction can be lifted whenever https://github.com/rust-lang/rfcs/pull/3028 is implemented
492             panic!(
493                 "`rustc` not found in {}, run `cargo build --bins` before `cargo run`",
494                 bootstrap_out.display()
495             )
496         }
497
498         if rust_info.is_from_tarball() && config.description.is_none() {
499             config.description = Some("built from a source tarball".to_owned());
500         }
501
502         let mut build = Build {
503             initial_rustc: config.initial_rustc.clone(),
504             initial_cargo: config.initial_cargo.clone(),
505             initial_lld,
506             initial_libdir,
507             local_rebuild: config.local_rebuild,
508             fail_fast: config.cmd.fail_fast(),
509             doc_tests: config.cmd.doc_tests(),
510             verbosity: config.verbose,
511
512             build: config.build,
513             hosts: config.hosts.clone(),
514             targets: config.targets.clone(),
515
516             config,
517             version: version.to_string(),
518             src,
519             out,
520             bootstrap_out,
521
522             cargo_info,
523             rust_analyzer_info,
524             clippy_info,
525             miri_info,
526             rustfmt_info,
527             in_tree_llvm_info,
528             cc: HashMap::new(),
529             cxx: HashMap::new(),
530             ar: HashMap::new(),
531             ranlib: HashMap::new(),
532             crates: HashMap::new(),
533             crate_paths: HashMap::new(),
534             is_sudo,
535             ci_env: CiEnv::current(),
536             delayed_failures: RefCell::new(Vec::new()),
537             prerelease_version: Cell::new(None),
538             tool_artifacts: Default::default(),
539
540             #[cfg(feature = "build-metrics")]
541             metrics: metrics::BuildMetrics::init(),
542         };
543
544         // If local-rust is the same major.minor as the current version, then force a
545         // local-rebuild
546         let local_version_verbose =
547             output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
548         let local_release = local_version_verbose
549             .lines()
550             .filter_map(|x| x.strip_prefix("release:"))
551             .next()
552             .unwrap()
553             .trim();
554         if local_release.split('.').take(2).eq(version.split('.').take(2)) {
555             build.verbose(&format!("auto-detected local-rebuild {}", local_release));
556             build.local_rebuild = true;
557         }
558
559         build.verbose("finding compilers");
560         cc_detect::find(&mut build);
561         // When running `setup`, the profile is about to change, so any requirements we have now may
562         // be different on the next invocation. Don't check for them until the next time x.py is
563         // run. This is ok because `setup` never runs any build commands, so it won't fail if commands are missing.
564         //
565         // Similarly, for `setup` we don't actually need submodules or cargo metadata.
566         if !matches!(build.config.cmd, Subcommand::Setup { .. }) {
567             build.verbose("running sanity check");
568             sanity::check(&mut build);
569
570             // Make sure we update these before gathering metadata so we don't get an error about missing
571             // Cargo.toml files.
572             let rust_submodules = [
573                 "src/tools/rust-installer",
574                 "src/tools/cargo",
575                 "library/backtrace",
576                 "library/stdarch",
577             ];
578             for s in rust_submodules {
579                 build.update_submodule(Path::new(s));
580             }
581             // Now, update all existing submodules.
582             build.update_existing_submodules();
583
584             build.verbose("learning about cargo");
585             metadata::build(&mut build);
586         }
587
588         // Make a symbolic link so we can use a consistent directory in the documentation.
589         let build_triple = build.out.join(&build.build.triple);
590         let host = build.out.join("host");
591         if let Err(e) = symlink_dir(&build.config, &build_triple, &host) {
592             if e.kind() != ErrorKind::AlreadyExists {
593                 panic!(
594                     "symlink_dir({} => {}) failed with {}",
595                     host.display(),
596                     build_triple.display(),
597                     e
598                 );
599             }
600         }
601
602         build
603     }
604
605     // modified from `check_submodule` and `update_submodule` in bootstrap.py
606     /// Given a path to the directory of a submodule, update it.
607     ///
608     /// `relative_path` should be relative to the root of the git repository, not an absolute path.
609     pub(crate) fn update_submodule(&self, relative_path: &Path) {
610         fn dir_is_empty(dir: &Path) -> bool {
611             t!(std::fs::read_dir(dir)).next().is_none()
612         }
613
614         if !self.config.submodules(&self.rust_info()) {
615             return;
616         }
617
618         let absolute_path = self.config.src.join(relative_path);
619
620         // NOTE: The check for the empty directory is here because when running x.py the first time,
621         // the submodule won't be checked out. Check it out now so we can build it.
622         if !channel::GitInfo::new(false, &absolute_path).is_managed_git_subrepository()
623             && !dir_is_empty(&absolute_path)
624         {
625             return;
626         }
627
628         // check_submodule
629         let checked_out_hash =
630             output(Command::new("git").args(&["rev-parse", "HEAD"]).current_dir(&absolute_path));
631         // update_submodules
632         let recorded = output(
633             Command::new("git")
634                 .args(&["ls-tree", "HEAD"])
635                 .arg(relative_path)
636                 .current_dir(&self.config.src),
637         );
638         let actual_hash = recorded
639             .split_whitespace()
640             .nth(2)
641             .unwrap_or_else(|| panic!("unexpected output `{}`", recorded));
642
643         // update_submodule
644         if actual_hash == checked_out_hash.trim_end() {
645             // already checked out
646             return;
647         }
648
649         println!("Updating submodule {}", relative_path.display());
650         self.run(
651             Command::new("git")
652                 .args(&["submodule", "-q", "sync"])
653                 .arg(relative_path)
654                 .current_dir(&self.config.src),
655         );
656
657         // Try passing `--progress` to start, then run git again without if that fails.
658         let update = |progress: bool| {
659             // Git is buggy and will try to fetch submodules from the tracking branch for *this* repository,
660             // even though that has no relation to the upstream for the submodule.
661             let current_branch = {
662                 let output = self
663                     .config
664                     .git()
665                     .args(["symbolic-ref", "--short", "HEAD"])
666                     .stderr(Stdio::inherit())
667                     .output();
668                 let output = t!(output);
669                 if output.status.success() {
670                     Some(String::from_utf8(output.stdout).unwrap().trim().to_owned())
671                 } else {
672                     None
673                 }
674             };
675
676             let mut git = self.config.git();
677             if let Some(branch) = current_branch {
678                 git.arg("-c").arg(format!("branch.{branch}.remote=origin"));
679             }
680             git.args(&["submodule", "update", "--init", "--recursive", "--depth=1"]);
681             if progress {
682                 git.arg("--progress");
683             }
684             git.arg(relative_path);
685             git
686         };
687         // NOTE: doesn't use `try_run` because this shouldn't print an error if it fails.
688         if !update(true).status().map_or(false, |status| status.success()) {
689             self.run(&mut update(false));
690         }
691
692         // Save any local changes, but avoid running `git stash pop` if there are none (since it will exit with an error).
693         let has_local_modifications = !self.try_run(
694             Command::new("git")
695                 .args(&["diff-index", "--quiet", "HEAD"])
696                 .current_dir(&absolute_path),
697         );
698         if has_local_modifications {
699             self.run(Command::new("git").args(&["stash", "push"]).current_dir(&absolute_path));
700         }
701
702         self.run(Command::new("git").args(&["reset", "-q", "--hard"]).current_dir(&absolute_path));
703         self.run(Command::new("git").args(&["clean", "-qdfx"]).current_dir(&absolute_path));
704
705         if has_local_modifications {
706             self.run(Command::new("git").args(&["stash", "pop"]).current_dir(absolute_path));
707         }
708     }
709
710     /// If any submodule has been initialized already, sync it unconditionally.
711     /// This avoids contributors checking in a submodule change by accident.
712     pub fn update_existing_submodules(&self) {
713         // Avoid running git when there isn't a git checkout.
714         if !self.config.submodules(&self.rust_info()) {
715             return;
716         }
717         let output = output(
718             self.config
719                 .git()
720                 .args(&["config", "--file"])
721                 .arg(&self.config.src.join(".gitmodules"))
722                 .args(&["--get-regexp", "path"]),
723         );
724         for line in output.lines() {
725             // Look for `submodule.$name.path = $path`
726             // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer`
727             let submodule = Path::new(line.splitn(2, ' ').nth(1).unwrap());
728             // Don't update the submodule unless it's already been cloned.
729             if channel::GitInfo::new(false, submodule).is_managed_git_subrepository() {
730                 self.update_submodule(submodule);
731             }
732         }
733     }
734
735     /// Executes the entire build, as configured by the flags and configuration.
736     pub fn build(&mut self) {
737         unsafe {
738             job::setup(self);
739         }
740
741         if let Subcommand::Format { check, paths } = &self.config.cmd {
742             return format::format(&builder::Builder::new(&self), *check, &paths);
743         }
744
745         // Download rustfmt early so that it can be used in rust-analyzer configs.
746         let _ = &builder::Builder::new(&self).initial_rustfmt();
747
748         {
749             let builder = builder::Builder::new(&self);
750             if let Some(path) = builder.paths.get(0) {
751                 if path == Path::new("nonexistent/path/to/trigger/cargo/metadata") {
752                     return;
753                 }
754             }
755         }
756
757         if !self.config.dry_run() {
758             {
759                 self.config.dry_run = DryRun::SelfCheck;
760                 let builder = builder::Builder::new(&self);
761                 builder.execute_cli();
762             }
763             self.config.dry_run = DryRun::Disabled;
764             let builder = builder::Builder::new(&self);
765             builder.execute_cli();
766         } else {
767             let builder = builder::Builder::new(&self);
768             builder.execute_cli();
769         }
770
771         // Check for postponed failures from `test --no-fail-fast`.
772         let failures = self.delayed_failures.borrow();
773         if failures.len() > 0 {
774             eprintln!("\n{} command(s) did not execute successfully:\n", failures.len());
775             for failure in failures.iter() {
776                 eprintln!("  - {}\n", failure);
777             }
778             detail_exit(1);
779         }
780
781         #[cfg(feature = "build-metrics")]
782         self.metrics.persist(self);
783     }
784
785     /// Clear out `dir` if `input` is newer.
786     ///
787     /// After this executes, it will also ensure that `dir` exists.
788     fn clear_if_dirty(&self, dir: &Path, input: &Path) -> bool {
789         let stamp = dir.join(".stamp");
790         let mut cleared = false;
791         if mtime(&stamp) < mtime(input) {
792             self.verbose(&format!("Dirty - {}", dir.display()));
793             let _ = fs::remove_dir_all(dir);
794             cleared = true;
795         } else if stamp.exists() {
796             return cleared;
797         }
798         t!(fs::create_dir_all(dir));
799         t!(File::create(stamp));
800         cleared
801     }
802
803     fn rust_info(&self) -> &GitInfo {
804         &self.config.rust_info
805     }
806
807     /// Gets the space-separated set of activated features for the standard
808     /// library.
809     fn std_features(&self, target: TargetSelection) -> String {
810         let mut features = " panic-unwind".to_string();
811
812         match self.config.llvm_libunwind(target) {
813             LlvmLibunwind::InTree => features.push_str(" llvm-libunwind"),
814             LlvmLibunwind::System => features.push_str(" system-llvm-libunwind"),
815             LlvmLibunwind::No => {}
816         }
817         if self.config.backtrace {
818             features.push_str(" backtrace");
819         }
820         if self.config.profiler_enabled(target) {
821             features.push_str(" profiler");
822         }
823         features
824     }
825
826     /// Gets the space-separated set of activated features for the compiler.
827     fn rustc_features(&self, kind: Kind) -> String {
828         let mut features = vec![];
829         if self.config.jemalloc {
830             features.push("jemalloc");
831         }
832         if self.config.llvm_enabled() || kind == Kind::Check {
833             features.push("llvm");
834         }
835         // keep in sync with `bootstrap/compile.rs:rustc_cargo_env`
836         if self.config.rustc_parallel {
837             features.push("rustc_use_parallel_compiler");
838         }
839
840         // If debug logging is on, then we want the default for tracing:
841         // https://github.com/tokio-rs/tracing/blob/3dd5c03d907afdf2c39444a29931833335171554/tracing/src/level_filters.rs#L26
842         // which is everything (including debug/trace/etc.)
843         // if its unset, if debug_assertions is on, then debug_logging will also be on
844         // as well as tracing *ignoring* this feature when debug_assertions is on
845         if !self.config.rust_debug_logging {
846             features.push("max_level_info");
847         }
848
849         features.join(" ")
850     }
851
852     /// Component directory that Cargo will produce output into (e.g.
853     /// release/debug)
854     fn cargo_dir(&self) -> &'static str {
855         if self.config.rust_optimize { "release" } else { "debug" }
856     }
857
858     fn tools_dir(&self, compiler: Compiler) -> PathBuf {
859         let out = self
860             .out
861             .join(&*compiler.host.triple)
862             .join(format!("stage{}-tools-bin", compiler.stage));
863         t!(fs::create_dir_all(&out));
864         out
865     }
866
867     /// Returns the root directory for all output generated in a particular
868     /// stage when running with a particular host compiler.
869     ///
870     /// The mode indicates what the root directory is for.
871     fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
872         let suffix = match mode {
873             Mode::Std => "-std",
874             Mode::Rustc => "-rustc",
875             Mode::Codegen => "-codegen",
876             Mode::ToolBootstrap => "-bootstrap-tools",
877             Mode::ToolStd | Mode::ToolRustc => "-tools",
878         };
879         self.out.join(&*compiler.host.triple).join(format!("stage{}{}", compiler.stage, suffix))
880     }
881
882     /// Returns the root output directory for all Cargo output in a given stage,
883     /// running a particular compiler, whether or not we're building the
884     /// standard library, and targeting the specified architecture.
885     fn cargo_out(&self, compiler: Compiler, mode: Mode, target: TargetSelection) -> PathBuf {
886         self.stage_out(compiler, mode).join(&*target.triple).join(self.cargo_dir())
887     }
888
889     /// Root output directory for LLVM compiled for `target`
890     ///
891     /// Note that if LLVM is configured externally then the directory returned
892     /// will likely be empty.
893     fn llvm_out(&self, target: TargetSelection) -> PathBuf {
894         self.out.join(&*target.triple).join("llvm")
895     }
896
897     fn lld_out(&self, target: TargetSelection) -> PathBuf {
898         self.out.join(&*target.triple).join("lld")
899     }
900
901     /// Output directory for all documentation for a target
902     fn doc_out(&self, target: TargetSelection) -> PathBuf {
903         self.out.join(&*target.triple).join("doc")
904     }
905
906     /// Output directory for all JSON-formatted documentation for a target
907     fn json_doc_out(&self, target: TargetSelection) -> PathBuf {
908         self.out.join(&*target.triple).join("json-doc")
909     }
910
911     fn test_out(&self, target: TargetSelection) -> PathBuf {
912         self.out.join(&*target.triple).join("test")
913     }
914
915     /// Output directory for all documentation for a target
916     fn compiler_doc_out(&self, target: TargetSelection) -> PathBuf {
917         self.out.join(&*target.triple).join("compiler-doc")
918     }
919
920     /// Output directory for some generated md crate documentation for a target (temporary)
921     fn md_doc_out(&self, target: TargetSelection) -> Interned<PathBuf> {
922         INTERNER.intern_path(self.out.join(&*target.triple).join("md-doc"))
923     }
924
925     /// Returns `true` if no custom `llvm-config` is set for the specified target.
926     ///
927     /// If no custom `llvm-config` was specified then Rust's llvm will be used.
928     fn is_rust_llvm(&self, target: TargetSelection) -> bool {
929         match self.config.target_config.get(&target) {
930             Some(Target { llvm_has_rust_patches: Some(patched), .. }) => *patched,
931             Some(Target { llvm_config, .. }) => {
932                 // If the user set llvm-config we assume Rust is not patched,
933                 // but first check to see if it was configured by llvm-from-ci.
934                 (self.config.llvm_from_ci && target == self.config.build) || llvm_config.is_none()
935             }
936             None => true,
937         }
938     }
939
940     /// Returns the path to `FileCheck` binary for the specified target
941     fn llvm_filecheck(&self, target: TargetSelection) -> PathBuf {
942         let target_config = self.config.target_config.get(&target);
943         if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
944             s.to_path_buf()
945         } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
946             let llvm_bindir = output(Command::new(s).arg("--bindir"));
947             let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target));
948             if filecheck.exists() {
949                 filecheck
950             } else {
951                 // On Fedora the system LLVM installs FileCheck in the
952                 // llvm subdirectory of the libdir.
953                 let llvm_libdir = output(Command::new(s).arg("--libdir"));
954                 let lib_filecheck =
955                     Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target));
956                 if lib_filecheck.exists() {
957                     lib_filecheck
958                 } else {
959                     // Return the most normal file name, even though
960                     // it doesn't exist, so that any error message
961                     // refers to that.
962                     filecheck
963                 }
964             }
965         } else {
966             let base = self.llvm_out(target).join("build");
967             let base = if !self.ninja() && target.contains("msvc") {
968                 if self.config.llvm_optimize {
969                     if self.config.llvm_release_debuginfo {
970                         base.join("RelWithDebInfo")
971                     } else {
972                         base.join("Release")
973                     }
974                 } else {
975                     base.join("Debug")
976                 }
977             } else {
978                 base
979             };
980             base.join("bin").join(exe("FileCheck", target))
981         }
982     }
983
984     /// Directory for libraries built from C/C++ code and shared between stages.
985     fn native_dir(&self, target: TargetSelection) -> PathBuf {
986         self.out.join(&*target.triple).join("native")
987     }
988
989     /// Root output directory for rust_test_helpers library compiled for
990     /// `target`
991     fn test_helpers_out(&self, target: TargetSelection) -> PathBuf {
992         self.native_dir(target).join("rust-test-helpers")
993     }
994
995     /// Adds the `RUST_TEST_THREADS` env var if necessary
996     fn add_rust_test_threads(&self, cmd: &mut Command) {
997         if env::var_os("RUST_TEST_THREADS").is_none() {
998             cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
999         }
1000     }
1001
1002     /// Returns the libdir of the snapshot compiler.
1003     fn rustc_snapshot_libdir(&self) -> PathBuf {
1004         self.rustc_snapshot_sysroot().join(libdir(self.config.build))
1005     }
1006
1007     /// Returns the sysroot of the snapshot compiler.
1008     fn rustc_snapshot_sysroot(&self) -> &Path {
1009         static SYSROOT_CACHE: OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
1010         SYSROOT_CACHE.get_or_init(|| {
1011             let mut rustc = Command::new(&self.initial_rustc);
1012             rustc.args(&["--print", "sysroot"]);
1013             output(&mut rustc).trim().into()
1014         })
1015     }
1016
1017     /// Runs a command, printing out nice contextual information if it fails.
1018     fn run(&self, cmd: &mut Command) {
1019         if self.config.dry_run() {
1020             return;
1021         }
1022         self.verbose(&format!("running: {:?}", cmd));
1023         run(cmd, self.is_verbose())
1024     }
1025
1026     /// Runs a command, printing out nice contextual information if it fails.
1027     fn run_quiet(&self, cmd: &mut Command) {
1028         if self.config.dry_run() {
1029             return;
1030         }
1031         self.verbose(&format!("running: {:?}", cmd));
1032         run_suppressed(cmd)
1033     }
1034
1035     /// Runs a command, printing out nice contextual information if it fails.
1036     /// Exits if the command failed to execute at all, otherwise returns its
1037     /// `status.success()`.
1038     fn try_run_quiet(&self, cmd: &mut Command) -> bool {
1039         if self.config.dry_run() {
1040             return true;
1041         }
1042         self.verbose(&format!("running: {:?}", cmd));
1043         try_run_suppressed(cmd)
1044     }
1045
1046     pub fn is_verbose_than(&self, level: usize) -> bool {
1047         self.verbosity > level
1048     }
1049
1050     /// Prints a message if this build is configured in more verbose mode than `level`.
1051     fn verbose_than(&self, level: usize, msg: &str) {
1052         if self.is_verbose_than(level) {
1053             println!("{}", msg);
1054         }
1055     }
1056
1057     fn info(&self, msg: &str) {
1058         match self.config.dry_run {
1059             DryRun::SelfCheck => return,
1060             DryRun::Disabled | DryRun::UserSelected => {
1061                 println!("{}", msg);
1062             }
1063         }
1064     }
1065
1066     /// Returns the number of parallel jobs that have been configured for this
1067     /// build.
1068     fn jobs(&self) -> u32 {
1069         self.config.jobs.unwrap_or_else(|| {
1070             std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32
1071         })
1072     }
1073
1074     fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
1075         if !self.config.rust_remap_debuginfo {
1076             return None;
1077         }
1078
1079         match which {
1080             GitRepo::Rustc => {
1081                 let sha = self.rust_sha().unwrap_or(&self.version);
1082                 Some(format!("/rustc/{}", sha))
1083             }
1084             GitRepo::Llvm => Some(String::from("/rustc/llvm")),
1085         }
1086     }
1087
1088     /// Returns the path to the C compiler for the target specified.
1089     fn cc(&self, target: TargetSelection) -> &Path {
1090         self.cc[&target].path()
1091     }
1092
1093     /// Returns a list of flags to pass to the C compiler for the target
1094     /// specified.
1095     fn cflags(&self, target: TargetSelection, which: GitRepo, c: CLang) -> Vec<String> {
1096         let base = match c {
1097             CLang::C => &self.cc[&target],
1098             CLang::Cxx => &self.cxx[&target],
1099         };
1100
1101         // Filter out -O and /O (the optimization flags) that we picked up from
1102         // cc-rs because the build scripts will determine that for themselves.
1103         let mut base = base
1104             .args()
1105             .iter()
1106             .map(|s| s.to_string_lossy().into_owned())
1107             .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
1108             .collect::<Vec<String>>();
1109
1110         // If we're compiling on macOS then we add a few unconditional flags
1111         // indicating that we want libc++ (more filled out than libstdc++) and
1112         // we want to compile for 10.7. This way we can ensure that
1113         // LLVM/etc are all properly compiled.
1114         if target.contains("apple-darwin") {
1115             base.push("-stdlib=libc++".into());
1116         }
1117
1118         // Work around an apparently bad MinGW / GCC optimization,
1119         // See: https://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
1120         // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
1121         if &*target.triple == "i686-pc-windows-gnu" {
1122             base.push("-fno-omit-frame-pointer".into());
1123         }
1124
1125         if let Some(map_to) = self.debuginfo_map_to(which) {
1126             let map = format!("{}={}", self.src.display(), map_to);
1127             let cc = self.cc(target);
1128             if cc.ends_with("clang") || cc.ends_with("gcc") {
1129                 base.push(format!("-fdebug-prefix-map={}", map));
1130             } else if cc.ends_with("clang-cl.exe") {
1131                 base.push("-Xclang".into());
1132                 base.push(format!("-fdebug-prefix-map={}", map));
1133             }
1134         }
1135         base
1136     }
1137
1138     /// Returns the path to the `ar` archive utility for the target specified.
1139     fn ar(&self, target: TargetSelection) -> Option<&Path> {
1140         self.ar.get(&target).map(|p| &**p)
1141     }
1142
1143     /// Returns the path to the `ranlib` utility for the target specified.
1144     fn ranlib(&self, target: TargetSelection) -> Option<&Path> {
1145         self.ranlib.get(&target).map(|p| &**p)
1146     }
1147
1148     /// Returns the path to the C++ compiler for the target specified.
1149     fn cxx(&self, target: TargetSelection) -> Result<&Path, String> {
1150         match self.cxx.get(&target) {
1151             Some(p) => Ok(p.path()),
1152             None => {
1153                 Err(format!("target `{}` is not configured as a host, only as a target", target))
1154             }
1155         }
1156     }
1157
1158     /// Returns the path to the linker for the given target if it needs to be overridden.
1159     fn linker(&self, target: TargetSelection) -> Option<&Path> {
1160         if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.as_ref())
1161         {
1162             Some(linker)
1163         } else if target.contains("vxworks") {
1164             // need to use CXX compiler as linker to resolve the exception functions
1165             // that are only existed in CXX libraries
1166             Some(self.cxx[&target].path())
1167         } else if target != self.config.build
1168             && util::use_host_linker(target)
1169             && !target.contains("msvc")
1170         {
1171             Some(self.cc(target))
1172         } else if self.config.use_lld && !self.is_fuse_ld_lld(target) && self.build == target {
1173             Some(&self.initial_lld)
1174         } else {
1175             None
1176         }
1177     }
1178
1179     // LLD is used through `-fuse-ld=lld` rather than directly.
1180     // Only MSVC targets use LLD directly at the moment.
1181     fn is_fuse_ld_lld(&self, target: TargetSelection) -> bool {
1182         self.config.use_lld && !target.contains("msvc")
1183     }
1184
1185     fn lld_flags(&self, target: TargetSelection) -> impl Iterator<Item = String> {
1186         let mut options = [None, None];
1187
1188         if self.config.use_lld {
1189             if self.is_fuse_ld_lld(target) {
1190                 options[0] = Some("-Clink-arg=-fuse-ld=lld".to_string());
1191             }
1192
1193             let no_threads = util::lld_flag_no_threads(target.contains("windows"));
1194             options[1] = Some(format!("-Clink-arg=-Wl,{}", no_threads));
1195         }
1196
1197         IntoIterator::into_iter(options).flatten()
1198     }
1199
1200     /// Returns if this target should statically link the C runtime, if specified
1201     fn crt_static(&self, target: TargetSelection) -> Option<bool> {
1202         if target.contains("pc-windows-msvc") {
1203             Some(true)
1204         } else {
1205             self.config.target_config.get(&target).and_then(|t| t.crt_static)
1206         }
1207     }
1208
1209     /// Returns the "musl root" for this `target`, if defined
1210     fn musl_root(&self, target: TargetSelection) -> Option<&Path> {
1211         self.config
1212             .target_config
1213             .get(&target)
1214             .and_then(|t| t.musl_root.as_ref())
1215             .or_else(|| self.config.musl_root.as_ref())
1216             .map(|p| &**p)
1217     }
1218
1219     /// Returns the "musl libdir" for this `target`.
1220     fn musl_libdir(&self, target: TargetSelection) -> Option<PathBuf> {
1221         let t = self.config.target_config.get(&target)?;
1222         if let libdir @ Some(_) = &t.musl_libdir {
1223             return libdir.clone();
1224         }
1225         self.musl_root(target).map(|root| root.join("lib"))
1226     }
1227
1228     /// Returns the sysroot for the wasi target, if defined
1229     fn wasi_root(&self, target: TargetSelection) -> Option<&Path> {
1230         self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p)
1231     }
1232
1233     /// Returns `true` if this is a no-std `target`, if defined
1234     fn no_std(&self, target: TargetSelection) -> Option<bool> {
1235         self.config.target_config.get(&target).map(|t| t.no_std)
1236     }
1237
1238     /// Returns `true` if the target will be tested using the `remote-test-client`
1239     /// and `remote-test-server` binaries.
1240     fn remote_tested(&self, target: TargetSelection) -> bool {
1241         self.qemu_rootfs(target).is_some()
1242             || target.contains("android")
1243             || env::var_os("TEST_DEVICE_ADDR").is_some()
1244     }
1245
1246     /// Returns the root of the "rootfs" image that this target will be using,
1247     /// if one was configured.
1248     ///
1249     /// If `Some` is returned then that means that tests for this target are
1250     /// emulated with QEMU and binaries will need to be shipped to the emulator.
1251     fn qemu_rootfs(&self, target: TargetSelection) -> Option<&Path> {
1252         self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
1253     }
1254
1255     /// Path to the python interpreter to use
1256     fn python(&self) -> &Path {
1257         if self.config.build.ends_with("apple-darwin") {
1258             // Force /usr/bin/python3 on macOS for LLDB tests because we're loading the
1259             // LLDB plugin's compiled module which only works with the system python
1260             // (namely not Homebrew-installed python)
1261             Path::new("/usr/bin/python3")
1262         } else {
1263             self.config
1264                 .python
1265                 .as_ref()
1266                 .expect("python is required for running LLDB or rustdoc tests")
1267         }
1268     }
1269
1270     /// Temporary directory that extended error information is emitted to.
1271     fn extended_error_dir(&self) -> PathBuf {
1272         self.out.join("tmp/extended-error-metadata")
1273     }
1274
1275     /// Tests whether the `compiler` compiling for `target` should be forced to
1276     /// use a stage1 compiler instead.
1277     ///
1278     /// Currently, by default, the build system does not perform a "full
1279     /// bootstrap" by default where we compile the compiler three times.
1280     /// Instead, we compile the compiler two times. The final stage (stage2)
1281     /// just copies the libraries from the previous stage, which is what this
1282     /// method detects.
1283     ///
1284     /// Here we return `true` if:
1285     ///
1286     /// * The build isn't performing a full bootstrap
1287     /// * The `compiler` is in the final stage, 2
1288     /// * We're not cross-compiling, so the artifacts are already available in
1289     ///   stage1
1290     ///
1291     /// When all of these conditions are met the build will lift artifacts from
1292     /// the previous stage forward.
1293     fn force_use_stage1(&self, compiler: Compiler, target: TargetSelection) -> bool {
1294         !self.config.full_bootstrap
1295             && compiler.stage >= 2
1296             && (self.hosts.iter().any(|h| *h == target) || target == self.build)
1297     }
1298
1299     /// Given `num` in the form "a.b.c" return a "release string" which
1300     /// describes the release version number.
1301     ///
1302     /// For example on nightly this returns "a.b.c-nightly", on beta it returns
1303     /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
1304     fn release(&self, num: &str) -> String {
1305         match &self.config.channel[..] {
1306             "stable" => num.to_string(),
1307             "beta" => {
1308                 if self.rust_info().is_managed_git_subrepository() && !self.config.ignore_git {
1309                     format!("{}-beta.{}", num, self.beta_prerelease_version())
1310                 } else {
1311                     format!("{}-beta", num)
1312                 }
1313             }
1314             "nightly" => format!("{}-nightly", num),
1315             _ => format!("{}-dev", num),
1316         }
1317     }
1318
1319     fn beta_prerelease_version(&self) -> u32 {
1320         if let Some(s) = self.prerelease_version.get() {
1321             return s;
1322         }
1323
1324         // Figure out how many merge commits happened since we branched off master.
1325         // That's our beta number!
1326         // (Note that we use a `..` range, not the `...` symmetric difference.)
1327         let count =
1328             output(self.config.git().arg("rev-list").arg("--count").arg("--merges").arg(format!(
1329                 "refs/remotes/origin/{}..HEAD",
1330                 self.config.stage0_metadata.config.nightly_branch
1331             )));
1332         let n = count.trim().parse().unwrap();
1333         self.prerelease_version.set(Some(n));
1334         n
1335     }
1336
1337     /// Returns the value of `release` above for Rust itself.
1338     fn rust_release(&self) -> String {
1339         self.release(&self.version)
1340     }
1341
1342     /// Returns the "package version" for a component given the `num` release
1343     /// number.
1344     ///
1345     /// The package version is typically what shows up in the names of tarballs.
1346     /// For channels like beta/nightly it's just the channel name, otherwise
1347     /// it's the `num` provided.
1348     fn package_vers(&self, num: &str) -> String {
1349         match &self.config.channel[..] {
1350             "stable" => num.to_string(),
1351             "beta" => "beta".to_string(),
1352             "nightly" => "nightly".to_string(),
1353             _ => format!("{}-dev", num),
1354         }
1355     }
1356
1357     /// Returns the value of `package_vers` above for Rust itself.
1358     fn rust_package_vers(&self) -> String {
1359         self.package_vers(&self.version)
1360     }
1361
1362     /// Returns the `version` string associated with this compiler for Rust
1363     /// itself.
1364     ///
1365     /// Note that this is a descriptive string which includes the commit date,
1366     /// sha, version, etc.
1367     fn rust_version(&self) -> String {
1368         let mut version = self.rust_info().version(self, &self.version);
1369         if let Some(ref s) = self.config.description {
1370             version.push_str(" (");
1371             version.push_str(s);
1372             version.push(')');
1373         }
1374         version
1375     }
1376
1377     /// Returns the full commit hash.
1378     fn rust_sha(&self) -> Option<&str> {
1379         self.rust_info().sha()
1380     }
1381
1382     /// Returns the `a.b.c` version that the given package is at.
1383     fn release_num(&self, package: &str) -> String {
1384         let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
1385         let toml = t!(fs::read_to_string(&toml_file_name));
1386         for line in toml.lines() {
1387             if let Some(stripped) =
1388                 line.strip_prefix("version = \"").and_then(|s| s.strip_suffix("\""))
1389             {
1390                 return stripped.to_owned();
1391             }
1392         }
1393
1394         panic!("failed to find version in {}'s Cargo.toml", package)
1395     }
1396
1397     /// Returns `true` if unstable features should be enabled for the compiler
1398     /// we're building.
1399     fn unstable_features(&self) -> bool {
1400         match &self.config.channel[..] {
1401             "stable" | "beta" => false,
1402             "nightly" | _ => true,
1403         }
1404     }
1405
1406     /// Returns a Vec of all the dependencies of the given root crate,
1407     /// including transitive dependencies and the root itself. Only includes
1408     /// "local" crates (those in the local source tree, not from a registry).
1409     fn in_tree_crates(&self, root: &str, target: Option<TargetSelection>) -> Vec<&Crate> {
1410         let mut ret = Vec::new();
1411         let mut list = vec![INTERNER.intern_str(root)];
1412         let mut visited = HashSet::new();
1413         while let Some(krate) = list.pop() {
1414             let krate = self
1415                 .crates
1416                 .get(&krate)
1417                 .unwrap_or_else(|| panic!("metadata missing for {krate}: {:?}", self.crates));
1418             ret.push(krate);
1419             for dep in &krate.deps {
1420                 if !self.crates.contains_key(dep) {
1421                     // Ignore non-workspace members.
1422                     continue;
1423                 }
1424                 // Don't include optional deps if their features are not
1425                 // enabled. Ideally this would be computed from `cargo
1426                 // metadata --features â€¦`, but that is somewhat slow. In
1427                 // the future, we may want to consider just filtering all
1428                 // build and dev dependencies in metadata::build.
1429                 if visited.insert(dep)
1430                     && (dep != "profiler_builtins"
1431                         || target
1432                             .map(|t| self.config.profiler_enabled(t))
1433                             .unwrap_or_else(|| self.config.any_profiler_enabled()))
1434                     && (dep != "rustc_codegen_llvm" || self.config.llvm_enabled())
1435                 {
1436                     list.push(*dep);
1437                 }
1438             }
1439         }
1440         ret
1441     }
1442
1443     fn read_stamp_file(&self, stamp: &Path) -> Vec<(PathBuf, DependencyType)> {
1444         if self.config.dry_run() {
1445             return Vec::new();
1446         }
1447
1448         if !stamp.exists() {
1449             eprintln!(
1450                 "Error: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?",
1451                 stamp.display()
1452             );
1453             crate::detail_exit(1);
1454         }
1455
1456         let mut paths = Vec::new();
1457         let contents = t!(fs::read(stamp), &stamp);
1458         // This is the method we use for extracting paths from the stamp file passed to us. See
1459         // run_cargo for more information (in compile.rs).
1460         for part in contents.split(|b| *b == 0) {
1461             if part.is_empty() {
1462                 continue;
1463             }
1464             let dependency_type = match part[0] as char {
1465                 'h' => DependencyType::Host,
1466                 's' => DependencyType::TargetSelfContained,
1467                 't' => DependencyType::Target,
1468                 _ => unreachable!(),
1469             };
1470             let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1471             paths.push((path, dependency_type));
1472         }
1473         paths
1474     }
1475
1476     /// Copies a file from `src` to `dst`
1477     pub fn copy(&self, src: &Path, dst: &Path) {
1478         self.copy_internal(src, dst, false);
1479     }
1480
1481     fn copy_internal(&self, src: &Path, dst: &Path, dereference_symlinks: bool) {
1482         if self.config.dry_run() {
1483             return;
1484         }
1485         self.verbose_than(1, &format!("Copy {:?} to {:?}", src, dst));
1486         if src == dst {
1487             return;
1488         }
1489         let _ = fs::remove_file(&dst);
1490         let metadata = t!(src.symlink_metadata());
1491         let mut src = src.to_path_buf();
1492         if metadata.file_type().is_symlink() {
1493             if dereference_symlinks {
1494                 src = t!(fs::canonicalize(src));
1495             } else {
1496                 let link = t!(fs::read_link(src));
1497                 t!(self.symlink_file(link, dst));
1498                 return;
1499             }
1500         }
1501         if let Ok(()) = fs::hard_link(&src, dst) {
1502             // Attempt to "easy copy" by creating a hard link
1503             // (symlinks don't work on windows), but if that fails
1504             // just fall back to a slow `copy` operation.
1505         } else {
1506             if let Err(e) = fs::copy(&src, dst) {
1507                 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1508             }
1509             t!(fs::set_permissions(dst, metadata.permissions()));
1510             let atime = FileTime::from_last_access_time(&metadata);
1511             let mtime = FileTime::from_last_modification_time(&metadata);
1512             t!(filetime::set_file_times(dst, atime, mtime));
1513         }
1514     }
1515
1516     /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1517     /// when this function is called.
1518     pub fn cp_r(&self, src: &Path, dst: &Path) {
1519         if self.config.dry_run() {
1520             return;
1521         }
1522         for f in self.read_dir(src) {
1523             let path = f.path();
1524             let name = path.file_name().unwrap();
1525             let dst = dst.join(name);
1526             if t!(f.file_type()).is_dir() {
1527                 t!(fs::create_dir_all(&dst));
1528                 self.cp_r(&path, &dst);
1529             } else {
1530                 let _ = fs::remove_file(&dst);
1531                 self.copy(&path, &dst);
1532             }
1533         }
1534     }
1535
1536     /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1537     /// when this function is called. Unwanted files or directories can be skipped
1538     /// by returning `false` from the filter function.
1539     pub fn cp_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1540         // Immediately recurse with an empty relative path
1541         self.recurse_(src, dst, Path::new(""), filter)
1542     }
1543
1544     // Inner function does the actual work
1545     fn recurse_(&self, src: &Path, dst: &Path, relative: &Path, filter: &dyn Fn(&Path) -> bool) {
1546         for f in self.read_dir(src) {
1547             let path = f.path();
1548             let name = path.file_name().unwrap();
1549             let dst = dst.join(name);
1550             let relative = relative.join(name);
1551             // Only copy file or directory if the filter function returns true
1552             if filter(&relative) {
1553                 if t!(f.file_type()).is_dir() {
1554                     let _ = fs::remove_dir_all(&dst);
1555                     self.create_dir(&dst);
1556                     self.recurse_(&path, &dst, &relative, filter);
1557                 } else {
1558                     let _ = fs::remove_file(&dst);
1559                     self.copy(&path, &dst);
1560                 }
1561             }
1562         }
1563     }
1564
1565     fn copy_to_folder(&self, src: &Path, dest_folder: &Path) {
1566         let file_name = src.file_name().unwrap();
1567         let dest = dest_folder.join(file_name);
1568         self.copy(src, &dest);
1569     }
1570
1571     fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1572         if self.config.dry_run() {
1573             return;
1574         }
1575         let dst = dstdir.join(src.file_name().unwrap());
1576         self.verbose_than(1, &format!("Install {:?} to {:?}", src, dst));
1577         t!(fs::create_dir_all(dstdir));
1578         if !src.exists() {
1579             panic!("Error: File \"{}\" not found!", src.display());
1580         }
1581         self.copy_internal(src, &dst, true);
1582         chmod(&dst, perms);
1583     }
1584
1585     fn read(&self, path: &Path) -> String {
1586         if self.config.dry_run() {
1587             return String::new();
1588         }
1589         t!(fs::read_to_string(path))
1590     }
1591
1592     fn create_dir(&self, dir: &Path) {
1593         if self.config.dry_run() {
1594             return;
1595         }
1596         t!(fs::create_dir_all(dir))
1597     }
1598
1599     fn remove_dir(&self, dir: &Path) {
1600         if self.config.dry_run() {
1601             return;
1602         }
1603         t!(fs::remove_dir_all(dir))
1604     }
1605
1606     fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1607         let iter = match fs::read_dir(dir) {
1608             Ok(v) => v,
1609             Err(_) if self.config.dry_run() => return vec![].into_iter(),
1610             Err(err) => panic!("could not read dir {:?}: {:?}", dir, err),
1611         };
1612         iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1613     }
1614
1615     fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(&self, src: P, link: Q) -> io::Result<()> {
1616         #[cfg(unix)]
1617         use std::os::unix::fs::symlink as symlink_file;
1618         #[cfg(windows)]
1619         use std::os::windows::fs::symlink_file;
1620         if !self.config.dry_run() { symlink_file(src.as_ref(), link.as_ref()) } else { Ok(()) }
1621     }
1622
1623     /// Returns if config.ninja is enabled, and checks for ninja existence,
1624     /// exiting with a nicer error message if not.
1625     fn ninja(&self) -> bool {
1626         let mut cmd_finder = crate::sanity::Finder::new();
1627
1628         if self.config.ninja_in_file {
1629             // Some Linux distros rename `ninja` to `ninja-build`.
1630             // CMake can work with either binary name.
1631             if cmd_finder.maybe_have("ninja-build").is_none()
1632                 && cmd_finder.maybe_have("ninja").is_none()
1633             {
1634                 eprintln!(
1635                     "
1636 Couldn't find required command: ninja (or ninja-build)
1637
1638 You should install ninja as described at
1639 <https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages>,
1640 or set `ninja = false` in the `[llvm]` section of `config.toml`.
1641 Alternatively, set `download-ci-llvm = true` in that `[llvm]` section
1642 to download LLVM rather than building it.
1643 "
1644                 );
1645                 detail_exit(1);
1646             }
1647         }
1648
1649         // If ninja isn't enabled but we're building for MSVC then we try
1650         // doubly hard to enable it. It was realized in #43767 that the msbuild
1651         // CMake generator for MSVC doesn't respect configuration options like
1652         // disabling LLVM assertions, which can often be quite important!
1653         //
1654         // In these cases we automatically enable Ninja if we find it in the
1655         // environment.
1656         if !self.config.ninja_in_file && self.config.build.contains("msvc") {
1657             if cmd_finder.maybe_have("ninja").is_some() {
1658                 return true;
1659             }
1660         }
1661
1662         self.config.ninja_in_file
1663     }
1664 }
1665
1666 #[cfg(unix)]
1667 fn chmod(path: &Path, perms: u32) {
1668     use std::os::unix::fs::*;
1669     t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1670 }
1671 #[cfg(windows)]
1672 fn chmod(_path: &Path, _perms: u32) {}
1673
1674 /// If code is not 0 (successful exit status), exit status is 101 (rust's default error code.)
1675 /// If the test is running and code is an error code, it will cause a panic.
1676 fn detail_exit(code: i32) -> ! {
1677     // if in test and code is an error code, panic with status code provided
1678     if cfg!(test) {
1679         panic!("status code: {}", code);
1680     } else {
1681         // otherwise,exit with provided status code
1682         std::process::exit(code);
1683     }
1684 }
1685
1686 impl Compiler {
1687     pub fn with_stage(mut self, stage: u32) -> Compiler {
1688         self.stage = stage;
1689         self
1690     }
1691
1692     /// Returns `true` if this is a snapshot compiler for `build`'s configuration
1693     pub fn is_snapshot(&self, build: &Build) -> bool {
1694         self.stage == 0 && self.host == build.build
1695     }
1696
1697     /// Returns if this compiler should be treated as a final stage one in the
1698     /// current build session.
1699     /// This takes into account whether we're performing a full bootstrap or
1700     /// not; don't directly compare the stage with `2`!
1701     pub fn is_final_stage(&self, build: &Build) -> bool {
1702         let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
1703         self.stage >= final_stage
1704     }
1705 }
1706
1707 fn envify(s: &str) -> String {
1708     s.chars()
1709         .map(|c| match c {
1710             '-' => '_',
1711             c => c,
1712         })
1713         .flat_map(|c| c.to_uppercase())
1714         .collect()
1715 }