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