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