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