]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/lib.rs
Rollup merge of #73471 - raoulstrackx:raoul/fpu_tag_word, r=jethrogb
[rust.git] / src / bootstrap / lib.rs
1 //! Implementation of rustbuild, the Rust build system.
2 //!
3 //! This module, and its descendants, are the implementation of the Rust build
4 //! system. Most of this build system is backed by Cargo but the outer layer
5 //! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
6 //! builds, building artifacts like LLVM, etc. The goals of rustbuild are:
7 //!
8 //! * To be an easily understandable, easily extensible, and maintainable build
9 //!   system.
10 //! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
11 //!   crates.io and Cargo.
12 //! * A standard interface to build across all platforms, including MSVC
13 //!
14 //! ## Architecture
15 //!
16 //! The build system defers most of the complicated logic managing invocations
17 //! of rustc and rustdoc to Cargo itself. However, moving through various stages
18 //! and copying artifacts is still necessary for it to do. Each time rustbuild
19 //! is invoked, it will iterate through the list of predefined steps and execute
20 //! each serially in turn if it matches the paths passed or is a default rule.
21 //! For each step rustbuild relies on the step internally being incremental and
22 //! parallel. Note, though, that the `-j` parameter to rustbuild gets forwarded
23 //! to appropriate test harnesses and such.
24 //!
25 //! Most of the "meaty" steps that matter are backed by Cargo, which does indeed
26 //! have its own parallelism and incremental management. Later steps, like
27 //! tests, aren't incremental and simply run the entire suite currently.
28 //! However, compiletest itself tries to avoid running tests when the artifacts
29 //! that are involved (mainly the compiler) haven't changed.
30 //!
31 //! When you execute `x.py build`, the steps executed are:
32 //!
33 //! * First, the python script is run. This will automatically download the
34 //!   stage0 rustc and cargo according to `src/stage0.txt`, or use the cached
35 //!   versions if they're available. These are then used to compile rustbuild
36 //!   itself (using Cargo). Finally, control is then transferred to rustbuild.
37 //!
38 //! * Rustbuild takes over, performs sanity checks, probes the environment,
39 //!   reads configuration, and starts executing steps as it reads the command
40 //!   line arguments (paths) or going through the default rules.
41 //!
42 //!   The build output will be something like the following:
43 //!
44 //!   Building stage0 std artifacts
45 //!   Copying stage0 std
46 //!   Building stage0 test artifacts
47 //!   Copying stage0 test
48 //!   Building stage0 compiler artifacts
49 //!   Copying stage0 rustc
50 //!   Assembling stage1 compiler
51 //!   Building stage1 std artifacts
52 //!   Copying stage1 std
53 //!   Building stage1 test artifacts
54 //!   Copying stage1 test
55 //!   Building stage1 compiler artifacts
56 //!   Copying stage1 rustc
57 //!   Assembling stage2 compiler
58 //!   Uplifting stage1 std
59 //!   Uplifting stage1 test
60 //!   Uplifting stage1 rustc
61 //!
62 //! Let's disect that a little:
63 //!
64 //! ## Building stage0 {std,test,compiler} artifacts
65 //!
66 //! These steps use the provided (downloaded, usually) compiler to compile the
67 //! local Rust source into libraries we can use.
68 //!
69 //! ## Copying stage0 {std,test,rustc}
70 //!
71 //! This copies the build output from Cargo into
72 //! `build/$HOST/stage0-sysroot/lib/rustlib/$ARCH/lib`. FIXME: this step's
73 //! documentation should be expanded -- the information already here may be
74 //! incorrect.
75 //!
76 //! ## Assembling stage1 compiler
77 //!
78 //! This copies the libraries we built in "building stage0 ... artifacts" into
79 //! the stage1 compiler's lib directory. These are the host libraries that the
80 //! compiler itself uses to run. These aren't actually used by artifacts the new
81 //! compiler generates. This step also copies the rustc and rustdoc binaries we
82 //! generated into build/$HOST/stage/bin.
83 //!
84 //! The stage1/bin/rustc is a fully functional compiler, but it doesn't yet have
85 //! any libraries to link built binaries or libraries to. The next 3 steps will
86 //! provide those libraries for it; they are mostly equivalent to constructing
87 //! the stage1/bin compiler so we don't go through them individually.
88 //!
89 //! ## Uplifting stage1 {std,test,rustc}
90 //!
91 //! This step copies the libraries from the stage1 compiler sysroot into the
92 //! stage2 compiler. This is done to avoid rebuilding the compiler; libraries
93 //! we'd build in this step should be identical (in function, if not necessarily
94 //! identical on disk) so there's no need to recompile the compiler again. Note
95 //! that if you want to, you can enable the full-bootstrap option to change this
96 //! behavior.
97 //!
98 //! Each step is driven by a separate Cargo project and rustbuild orchestrates
99 //! copying files between steps and otherwise preparing for Cargo to run.
100 //!
101 //! ## Further information
102 //!
103 //! More documentation can be found in each respective module below, and you can
104 //! also check out the `src/bootstrap/README.md` file for more information.
105
106 #![feature(drain_filter)]
107
108 use std::cell::{Cell, RefCell};
109 use std::collections::{HashMap, HashSet};
110 use std::env;
111 use std::fs::{self, File, OpenOptions};
112 use std::io::{Read, Seek, SeekFrom, Write};
113 use std::path::{Path, PathBuf};
114 use std::process::{self, Command};
115 use std::slice;
116 use std::str;
117
118 #[cfg(unix)]
119 use std::os::unix::fs::symlink as symlink_file;
120 #[cfg(windows)]
121 use std::os::windows::fs::symlink_file;
122
123 use build_helper::{mtime, output, run, run_suppressed, t, try_run, try_run_suppressed};
124 use filetime::FileTime;
125
126 use crate::util::{exe, libdir, CiEnv};
127
128 mod builder;
129 mod cache;
130 mod cc_detect;
131 mod channel;
132 mod check;
133 mod clean;
134 mod compile;
135 mod config;
136 mod dist;
137 mod doc;
138 mod flags;
139 mod format;
140 mod install;
141 mod metadata;
142 mod native;
143 mod run;
144 mod sanity;
145 mod test;
146 mod tool;
147 mod toolstate;
148 pub mod util;
149
150 #[cfg(windows)]
151 mod job;
152
153 #[cfg(all(unix, not(target_os = "haiku")))]
154 mod job {
155     pub unsafe fn setup(build: &mut crate::Build) {
156         if build.config.low_priority {
157             libc::setpriority(libc::PRIO_PGRP as _, 0, 10);
158         }
159     }
160 }
161
162 #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))]
163 mod job {
164     pub unsafe fn setup(_build: &mut crate::Build) {}
165 }
166
167 use crate::cache::{Interned, INTERNER};
168 pub use crate::config::Config;
169 use crate::flags::Subcommand;
170
171 const LLVM_TOOLS: &[&str] = &[
172     "llvm-nm", // used to inspect binaries; it shows symbol names, their sizes and visibility
173     "llvm-objcopy", // used to transform ELFs into binary format which flashing tools consume
174     "llvm-objdump", // used to disassemble programs
175     "llvm-profdata", // used to inspect and merge files generated by profiles
176     "llvm-readobj", // used to get information from ELFs/objects that the other tools don't provide
177     "llvm-size", // used to prints the size of the linker sections of a program
178     "llvm-strip", // used to discard symbols from binary files to reduce their size
179     "llvm-ar", // used for creating and modifying archive files
180 ];
181
182 /// A structure representing a Rust compiler.
183 ///
184 /// Each compiler has a `stage` that it is associated with and a `host` that
185 /// corresponds to the platform the compiler runs on. This structure is used as
186 /// a parameter to many methods below.
187 #[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
188 pub struct Compiler {
189     stage: u32,
190     host: Interned<String>,
191 }
192
193 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
194 pub enum DocTests {
195     /// Run normal tests and doc tests (default).
196     Yes,
197     /// Do not run any doc tests.
198     No,
199     /// Only run doc tests.
200     Only,
201 }
202
203 pub enum GitRepo {
204     Rustc,
205     Llvm,
206 }
207
208 /// Global configuration for the build system.
209 ///
210 /// This structure transitively contains all configuration for the build system.
211 /// All filesystem-encoded configuration is in `config`, all flags are in
212 /// `flags`, and then parsed or probed information is listed in the keys below.
213 ///
214 /// This structure is a parameter of almost all methods in the build system,
215 /// although most functions are implemented as free functions rather than
216 /// methods specifically on this structure itself (to make it easier to
217 /// organize).
218 pub struct Build {
219     /// User-specified configuration from `config.toml`.
220     config: Config,
221
222     // Properties derived from the above configuration
223     src: PathBuf,
224     out: PathBuf,
225     rust_info: channel::GitInfo,
226     cargo_info: channel::GitInfo,
227     rls_info: channel::GitInfo,
228     clippy_info: channel::GitInfo,
229     miri_info: channel::GitInfo,
230     rustfmt_info: channel::GitInfo,
231     in_tree_llvm_info: channel::GitInfo,
232     local_rebuild: bool,
233     fail_fast: bool,
234     doc_tests: DocTests,
235     verbosity: usize,
236
237     // Targets for which to build
238     build: Interned<String>,
239     hosts: Vec<Interned<String>>,
240     targets: Vec<Interned<String>>,
241
242     // Stage 0 (downloaded) compiler, lld and cargo or their local rust equivalents
243     initial_rustc: PathBuf,
244     initial_cargo: PathBuf,
245     initial_lld: PathBuf,
246     initial_libdir: PathBuf,
247
248     // Runtime state filled in later on
249     // C/C++ compilers and archiver for all targets
250     cc: HashMap<Interned<String>, cc::Tool>,
251     cxx: HashMap<Interned<String>, cc::Tool>,
252     ar: HashMap<Interned<String>, PathBuf>,
253     ranlib: HashMap<Interned<String>, PathBuf>,
254     // Miscellaneous
255     crates: HashMap<Interned<String>, Crate>,
256     is_sudo: bool,
257     ci_env: CiEnv,
258     delayed_failures: RefCell<Vec<String>>,
259     prerelease_version: Cell<Option<u32>>,
260     tool_artifacts:
261         RefCell<HashMap<Interned<String>, HashMap<String, (&'static str, PathBuf, Vec<String>)>>>,
262 }
263
264 #[derive(Debug)]
265 struct Crate {
266     name: Interned<String>,
267     deps: HashSet<Interned<String>>,
268     id: String,
269     path: PathBuf,
270 }
271
272 impl Crate {
273     fn local_path(&self, build: &Build) -> PathBuf {
274         self.path.strip_prefix(&build.config.src).unwrap().into()
275     }
276 }
277
278 /// When building Rust various objects are handled differently.
279 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
280 pub enum DependencyType {
281     /// Libraries originating from proc-macros.
282     Host,
283     /// Typical Rust libraries.
284     Target,
285     /// Non Rust libraries and objects shipped to ease usage of certain targets.
286     TargetSelfContained,
287 }
288
289 /// The various "modes" of invoking Cargo.
290 ///
291 /// These entries currently correspond to the various output directories of the
292 /// build system, with each mod generating output in a different directory.
293 #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
294 pub enum Mode {
295     /// Build the standard library, placing output in the "stageN-std" directory.
296     Std,
297
298     /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
299     Rustc,
300
301     /// Build codegen libraries, placing output in the "stageN-codegen" directory
302     Codegen,
303
304     /// Build some tools, placing output in the "stageN-tools" directory. The
305     /// "other" here is for miscellaneous sets of tools that are built using the
306     /// bootstrap compiler in its entirety (target libraries and all).
307     /// Typically these tools compile with stable Rust.
308     ToolBootstrap,
309
310     /// Compile a tool which uses all libraries we compile (up to rustc).
311     /// Doesn't use the stage0 compiler libraries like "other", and includes
312     /// tools like rustdoc, cargo, rls, etc.
313     ToolStd,
314     ToolRustc,
315 }
316
317 impl Mode {
318     pub fn is_tool(&self) -> bool {
319         match self {
320             Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd => true,
321             _ => false,
322         }
323     }
324 }
325
326 impl Build {
327     /// Creates a new set of build configuration from the `flags` on the command
328     /// line and the filesystem `config`.
329     ///
330     /// By default all build output will be placed in the current directory.
331     pub fn new(config: Config) -> Build {
332         let src = config.src.clone();
333         let out = config.out.clone();
334
335         let is_sudo = match env::var_os("SUDO_USER") {
336             Some(sudo_user) => match env::var_os("USER") {
337                 Some(user) => user != sudo_user,
338                 None => false,
339             },
340             None => false,
341         };
342
343         let ignore_git = config.ignore_git;
344         let rust_info = channel::GitInfo::new(ignore_git, &src);
345         let cargo_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/cargo"));
346         let rls_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/rls"));
347         let clippy_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/clippy"));
348         let miri_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/miri"));
349         let rustfmt_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/rustfmt"));
350
351         // we always try to use git for LLVM builds
352         let in_tree_llvm_info = channel::GitInfo::new(false, &src.join("src/llvm-project"));
353
354         let initial_target_libdir_str = if config.dry_run {
355             "/dummy/lib/path/to/lib/".to_string()
356         } else {
357             output(
358                 Command::new(&config.initial_rustc)
359                     .arg("--target")
360                     .arg(config.build)
361                     .arg("--print")
362                     .arg("target-libdir"),
363             )
364         };
365         let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
366         let initial_lld = initial_target_dir.join("bin").join("rust-lld");
367
368         let initial_sysroot = if config.dry_run {
369             "/dummy".to_string()
370         } else {
371             output(Command::new(&config.initial_rustc).arg("--print").arg("sysroot"))
372         };
373         let initial_libdir = initial_target_dir
374             .parent()
375             .unwrap()
376             .parent()
377             .unwrap()
378             .strip_prefix(initial_sysroot.trim())
379             .unwrap()
380             .to_path_buf();
381
382         let mut build = Build {
383             initial_rustc: config.initial_rustc.clone(),
384             initial_cargo: config.initial_cargo.clone(),
385             initial_lld,
386             initial_libdir,
387             local_rebuild: config.local_rebuild,
388             fail_fast: config.cmd.fail_fast(),
389             doc_tests: config.cmd.doc_tests(),
390             verbosity: config.verbose,
391
392             build: config.build,
393             hosts: config.hosts.clone(),
394             targets: config.targets.clone(),
395
396             config,
397             src,
398             out,
399
400             rust_info,
401             cargo_info,
402             rls_info,
403             clippy_info,
404             miri_info,
405             rustfmt_info,
406             in_tree_llvm_info,
407             cc: HashMap::new(),
408             cxx: HashMap::new(),
409             ar: HashMap::new(),
410             ranlib: HashMap::new(),
411             crates: HashMap::new(),
412             is_sudo,
413             ci_env: CiEnv::current(),
414             delayed_failures: RefCell::new(Vec::new()),
415             prerelease_version: Cell::new(None),
416             tool_artifacts: Default::default(),
417         };
418
419         build.verbose("finding compilers");
420         cc_detect::find(&mut build);
421         build.verbose("running sanity check");
422         sanity::check(&mut build);
423
424         // If local-rust is the same major.minor as the current version, then force a
425         // local-rebuild
426         let local_version_verbose =
427             output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
428         let local_release = local_version_verbose
429             .lines()
430             .filter(|x| x.starts_with("release:"))
431             .next()
432             .unwrap()
433             .trim_start_matches("release:")
434             .trim();
435         let my_version = channel::CFG_RELEASE_NUM;
436         if local_release.split('.').take(2).eq(my_version.split('.').take(2)) {
437             build.verbose(&format!("auto-detected local-rebuild {}", local_release));
438             build.local_rebuild = true;
439         }
440
441         build.verbose("learning about cargo");
442         metadata::build(&mut build);
443
444         build
445     }
446
447     pub fn build_triple(&self) -> &[Interned<String>] {
448         unsafe { slice::from_raw_parts(&self.build, 1) }
449     }
450
451     /// Executes the entire build, as configured by the flags and configuration.
452     pub fn build(&mut self) {
453         unsafe {
454             job::setup(self);
455         }
456
457         if let Subcommand::Format { check } = self.config.cmd {
458             return format::format(self, check);
459         }
460
461         if let Subcommand::Clean { all } = self.config.cmd {
462             return clean::clean(self, all);
463         }
464
465         {
466             let builder = builder::Builder::new(&self);
467             if let Some(path) = builder.paths.get(0) {
468                 if path == Path::new("nonexistent/path/to/trigger/cargo/metadata") {
469                     return;
470                 }
471             }
472         }
473
474         if !self.config.dry_run {
475             {
476                 self.config.dry_run = true;
477                 let builder = builder::Builder::new(&self);
478                 builder.execute_cli();
479             }
480             self.config.dry_run = false;
481             let builder = builder::Builder::new(&self);
482             builder.execute_cli();
483         } else {
484             let builder = builder::Builder::new(&self);
485             builder.execute_cli();
486         }
487
488         // Check for postponed failures from `test --no-fail-fast`.
489         let failures = self.delayed_failures.borrow();
490         if failures.len() > 0 {
491             println!("\n{} command(s) did not execute successfully:\n", failures.len());
492             for failure in failures.iter() {
493                 println!("  - {}\n", failure);
494             }
495             process::exit(1);
496         }
497     }
498
499     /// Clear out `dir` if `input` is newer.
500     ///
501     /// After this executes, it will also ensure that `dir` exists.
502     fn clear_if_dirty(&self, dir: &Path, input: &Path) -> bool {
503         let stamp = dir.join(".stamp");
504         let mut cleared = false;
505         if mtime(&stamp) < mtime(input) {
506             self.verbose(&format!("Dirty - {}", dir.display()));
507             let _ = fs::remove_dir_all(dir);
508             cleared = true;
509         } else if stamp.exists() {
510             return cleared;
511         }
512         t!(fs::create_dir_all(dir));
513         t!(File::create(stamp));
514         cleared
515     }
516
517     /// Gets the space-separated set of activated features for the standard
518     /// library.
519     fn std_features(&self) -> String {
520         let mut features = "panic-unwind".to_string();
521
522         if self.config.llvm_libunwind {
523             features.push_str(" llvm-libunwind");
524         }
525         if self.config.backtrace {
526             features.push_str(" backtrace");
527         }
528         if self.config.profiler {
529             features.push_str(" profiler");
530         }
531         features
532     }
533
534     /// Gets the space-separated set of activated features for the compiler.
535     fn rustc_features(&self) -> String {
536         let mut features = String::new();
537         if self.config.jemalloc {
538             features.push_str("jemalloc");
539         }
540         if self.config.llvm_enabled() {
541             features.push_str(" llvm");
542         }
543         features
544     }
545
546     /// Component directory that Cargo will produce output into (e.g.
547     /// release/debug)
548     fn cargo_dir(&self) -> &'static str {
549         if self.config.rust_optimize { "release" } else { "debug" }
550     }
551
552     fn tools_dir(&self, compiler: Compiler) -> PathBuf {
553         let out = self.out.join(&*compiler.host).join(format!("stage{}-tools-bin", compiler.stage));
554         t!(fs::create_dir_all(&out));
555         out
556     }
557
558     /// Returns the root directory for all output generated in a particular
559     /// stage when running with a particular host compiler.
560     ///
561     /// The mode indicates what the root directory is for.
562     fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
563         let suffix = match mode {
564             Mode::Std => "-std",
565             Mode::Rustc => "-rustc",
566             Mode::Codegen => "-codegen",
567             Mode::ToolBootstrap => "-bootstrap-tools",
568             Mode::ToolStd | Mode::ToolRustc => "-tools",
569         };
570         self.out.join(&*compiler.host).join(format!("stage{}{}", compiler.stage, suffix))
571     }
572
573     /// Returns the root output directory for all Cargo output in a given stage,
574     /// running a particular compiler, whether or not we're building the
575     /// standard library, and targeting the specified architecture.
576     fn cargo_out(&self, compiler: Compiler, mode: Mode, target: Interned<String>) -> PathBuf {
577         self.stage_out(compiler, mode).join(&*target).join(self.cargo_dir())
578     }
579
580     /// Root output directory for LLVM compiled for `target`
581     ///
582     /// Note that if LLVM is configured externally then the directory returned
583     /// will likely be empty.
584     fn llvm_out(&self, target: Interned<String>) -> PathBuf {
585         self.out.join(&*target).join("llvm")
586     }
587
588     fn lld_out(&self, target: Interned<String>) -> PathBuf {
589         self.out.join(&*target).join("lld")
590     }
591
592     /// Output directory for all documentation for a target
593     fn doc_out(&self, target: Interned<String>) -> PathBuf {
594         self.out.join(&*target).join("doc")
595     }
596
597     /// Output directory for all documentation for a target
598     fn compiler_doc_out(&self, target: Interned<String>) -> PathBuf {
599         self.out.join(&*target).join("compiler-doc")
600     }
601
602     /// Output directory for some generated md crate documentation for a target (temporary)
603     fn md_doc_out(&self, target: Interned<String>) -> Interned<PathBuf> {
604         INTERNER.intern_path(self.out.join(&*target).join("md-doc"))
605     }
606
607     /// Output directory for all crate documentation for a target (temporary)
608     ///
609     /// The artifacts here are then copied into `doc_out` above.
610     fn crate_doc_out(&self, target: Interned<String>) -> PathBuf {
611         self.out.join(&*target).join("crate-docs")
612     }
613
614     /// Returns `true` if no custom `llvm-config` is set for the specified target.
615     ///
616     /// If no custom `llvm-config` was specified then Rust's llvm will be used.
617     fn is_rust_llvm(&self, target: Interned<String>) -> bool {
618         match self.config.target_config.get(&target) {
619             Some(ref c) => c.llvm_config.is_none(),
620             None => true,
621         }
622     }
623
624     /// Returns the path to `FileCheck` binary for the specified target
625     fn llvm_filecheck(&self, target: Interned<String>) -> PathBuf {
626         let target_config = self.config.target_config.get(&target);
627         if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
628             s.to_path_buf()
629         } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
630             let llvm_bindir = output(Command::new(s).arg("--bindir"));
631             let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", &*target));
632             if filecheck.exists() {
633                 filecheck
634             } else {
635                 // On Fedora the system LLVM installs FileCheck in the
636                 // llvm subdirectory of the libdir.
637                 let llvm_libdir = output(Command::new(s).arg("--libdir"));
638                 let lib_filecheck =
639                     Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", &*target));
640                 if lib_filecheck.exists() {
641                     lib_filecheck
642                 } else {
643                     // Return the most normal file name, even though
644                     // it doesn't exist, so that any error message
645                     // refers to that.
646                     filecheck
647                 }
648             }
649         } else {
650             let base = self.llvm_out(self.config.build).join("build");
651             let base = if !self.config.ninja && self.config.build.contains("msvc") {
652                 if self.config.llvm_optimize {
653                     if self.config.llvm_release_debuginfo {
654                         base.join("RelWithDebInfo")
655                     } else {
656                         base.join("Release")
657                     }
658                 } else {
659                     base.join("Debug")
660                 }
661             } else {
662                 base
663             };
664             base.join("bin").join(exe("FileCheck", &*target))
665         }
666     }
667
668     /// Directory for libraries built from C/C++ code and shared between stages.
669     fn native_dir(&self, target: Interned<String>) -> PathBuf {
670         self.out.join(&*target).join("native")
671     }
672
673     /// Root output directory for rust_test_helpers library compiled for
674     /// `target`
675     fn test_helpers_out(&self, target: Interned<String>) -> PathBuf {
676         self.native_dir(target).join("rust-test-helpers")
677     }
678
679     /// Adds the `RUST_TEST_THREADS` env var if necessary
680     fn add_rust_test_threads(&self, cmd: &mut Command) {
681         if env::var_os("RUST_TEST_THREADS").is_none() {
682             cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
683         }
684     }
685
686     /// Returns the libdir of the snapshot compiler.
687     fn rustc_snapshot_libdir(&self) -> PathBuf {
688         self.rustc_snapshot_sysroot().join(libdir(&self.config.build))
689     }
690
691     /// Returns the sysroot of the snapshot compiler.
692     fn rustc_snapshot_sysroot(&self) -> &Path {
693         self.initial_rustc.parent().unwrap().parent().unwrap()
694     }
695
696     /// Runs a command, printing out nice contextual information if it fails.
697     fn run(&self, cmd: &mut Command) {
698         if self.config.dry_run {
699             return;
700         }
701         self.verbose(&format!("running: {:?}", cmd));
702         run(cmd)
703     }
704
705     /// Runs a command, printing out nice contextual information if it fails.
706     fn run_quiet(&self, cmd: &mut Command) {
707         if self.config.dry_run {
708             return;
709         }
710         self.verbose(&format!("running: {:?}", cmd));
711         run_suppressed(cmd)
712     }
713
714     /// Runs a command, printing out nice contextual information if it fails.
715     /// Exits if the command failed to execute at all, otherwise returns its
716     /// `status.success()`.
717     fn try_run(&self, cmd: &mut Command) -> bool {
718         if self.config.dry_run {
719             return true;
720         }
721         self.verbose(&format!("running: {:?}", cmd));
722         try_run(cmd)
723     }
724
725     /// Runs a command, printing out nice contextual information if it fails.
726     /// Exits if the command failed to execute at all, otherwise returns its
727     /// `status.success()`.
728     fn try_run_quiet(&self, cmd: &mut Command) -> bool {
729         if self.config.dry_run {
730             return true;
731         }
732         self.verbose(&format!("running: {:?}", cmd));
733         try_run_suppressed(cmd)
734     }
735
736     pub fn is_verbose(&self) -> bool {
737         self.verbosity > 0
738     }
739
740     /// Prints a message if this build is configured in verbose mode.
741     fn verbose(&self, msg: &str) {
742         if self.is_verbose() {
743             println!("{}", msg);
744         }
745     }
746
747     pub fn is_verbose_than(&self, level: usize) -> bool {
748         self.verbosity > level
749     }
750
751     /// Prints a message if this build is configured in more verbose mode than `level`.
752     fn verbose_than(&self, level: usize, msg: &str) {
753         if self.is_verbose_than(level) {
754             println!("{}", msg);
755         }
756     }
757
758     fn info(&self, msg: &str) {
759         if self.config.dry_run {
760             return;
761         }
762         println!("{}", msg);
763     }
764
765     /// Returns the number of parallel jobs that have been configured for this
766     /// build.
767     fn jobs(&self) -> u32 {
768         self.config.jobs.unwrap_or_else(|| num_cpus::get() as u32)
769     }
770
771     fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
772         if !self.config.rust_remap_debuginfo {
773             return None;
774         }
775
776         match which {
777             GitRepo::Rustc => {
778                 let sha = self.rust_sha().unwrap_or(channel::CFG_RELEASE_NUM);
779                 Some(format!("/rustc/{}", sha))
780             }
781             GitRepo::Llvm => Some(String::from("/rustc/llvm")),
782         }
783     }
784
785     /// Returns the path to the C compiler for the target specified.
786     fn cc(&self, target: Interned<String>) -> &Path {
787         self.cc[&target].path()
788     }
789
790     /// Returns a list of flags to pass to the C compiler for the target
791     /// specified.
792     fn cflags(&self, target: Interned<String>, which: GitRepo) -> Vec<String> {
793         // Filter out -O and /O (the optimization flags) that we picked up from
794         // cc-rs because the build scripts will determine that for themselves.
795         let mut base = self.cc[&target]
796             .args()
797             .iter()
798             .map(|s| s.to_string_lossy().into_owned())
799             .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
800             .collect::<Vec<String>>();
801
802         // If we're compiling on macOS then we add a few unconditional flags
803         // indicating that we want libc++ (more filled out than libstdc++) and
804         // we want to compile for 10.7. This way we can ensure that
805         // LLVM/etc are all properly compiled.
806         if target.contains("apple-darwin") {
807             base.push("-stdlib=libc++".into());
808         }
809
810         // Work around an apparently bad MinGW / GCC optimization,
811         // See: http://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
812         // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
813         if &*target == "i686-pc-windows-gnu" {
814             base.push("-fno-omit-frame-pointer".into());
815         }
816
817         if let Some(map_to) = self.debuginfo_map_to(which) {
818             let map = format!("{}={}", self.src.display(), map_to);
819             let cc = self.cc(target);
820             if cc.ends_with("clang") || cc.ends_with("gcc") {
821                 base.push(format!("-fdebug-prefix-map={}", map));
822             } else if cc.ends_with("clang-cl.exe") {
823                 base.push("-Xclang".into());
824                 base.push(format!("-fdebug-prefix-map={}", map));
825             }
826         }
827         base
828     }
829
830     /// Returns the path to the `ar` archive utility for the target specified.
831     fn ar(&self, target: Interned<String>) -> Option<&Path> {
832         self.ar.get(&target).map(|p| &**p)
833     }
834
835     /// Returns the path to the `ranlib` utility for the target specified.
836     fn ranlib(&self, target: Interned<String>) -> Option<&Path> {
837         self.ranlib.get(&target).map(|p| &**p)
838     }
839
840     /// Returns the path to the C++ compiler for the target specified.
841     fn cxx(&self, target: Interned<String>) -> Result<&Path, String> {
842         match self.cxx.get(&target) {
843             Some(p) => Ok(p.path()),
844             None => {
845                 Err(format!("target `{}` is not configured as a host, only as a target", target))
846             }
847         }
848     }
849
850     /// Returns the path to the linker for the given target if it needs to be overridden.
851     fn linker(&self, target: Interned<String>, can_use_lld: bool) -> Option<&Path> {
852         if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.as_ref())
853         {
854             Some(linker)
855         } else if target != self.config.build
856             && util::use_host_linker(&target)
857             && !target.contains("msvc")
858         {
859             Some(self.cc(target))
860         } else if can_use_lld && self.config.use_lld && self.build == target {
861             Some(&self.initial_lld)
862         } else {
863             None
864         }
865     }
866
867     /// Returns if this target should statically link the C runtime, if specified
868     fn crt_static(&self, target: Interned<String>) -> Option<bool> {
869         if target.contains("pc-windows-msvc") {
870             Some(true)
871         } else {
872             self.config.target_config.get(&target).and_then(|t| t.crt_static)
873         }
874     }
875
876     /// Returns the "musl root" for this `target`, if defined
877     fn musl_root(&self, target: Interned<String>) -> Option<&Path> {
878         self.config
879             .target_config
880             .get(&target)
881             .and_then(|t| t.musl_root.as_ref())
882             .or_else(|| self.config.musl_root.as_ref())
883             .map(|p| &**p)
884     }
885
886     /// Returns the sysroot for the wasi target, if defined
887     fn wasi_root(&self, target: Interned<String>) -> Option<&Path> {
888         self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p)
889     }
890
891     /// Returns `true` if this is a no-std `target`, if defined
892     fn no_std(&self, target: Interned<String>) -> Option<bool> {
893         self.config.target_config.get(&target).map(|t| t.no_std)
894     }
895
896     /// Returns `true` if the target will be tested using the `remote-test-client`
897     /// and `remote-test-server` binaries.
898     fn remote_tested(&self, target: Interned<String>) -> bool {
899         self.qemu_rootfs(target).is_some()
900             || target.contains("android")
901             || env::var_os("TEST_DEVICE_ADDR").is_some()
902     }
903
904     /// Returns the root of the "rootfs" image that this target will be using,
905     /// if one was configured.
906     ///
907     /// If `Some` is returned then that means that tests for this target are
908     /// emulated with QEMU and binaries will need to be shipped to the emulator.
909     fn qemu_rootfs(&self, target: Interned<String>) -> Option<&Path> {
910         self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
911     }
912
913     /// Path to the python interpreter to use
914     fn python(&self) -> &Path {
915         self.config.python.as_ref().unwrap()
916     }
917
918     /// Temporary directory that extended error information is emitted to.
919     fn extended_error_dir(&self) -> PathBuf {
920         self.out.join("tmp/extended-error-metadata")
921     }
922
923     /// Tests whether the `compiler` compiling for `target` should be forced to
924     /// use a stage1 compiler instead.
925     ///
926     /// Currently, by default, the build system does not perform a "full
927     /// bootstrap" by default where we compile the compiler three times.
928     /// Instead, we compile the compiler two times. The final stage (stage2)
929     /// just copies the libraries from the previous stage, which is what this
930     /// method detects.
931     ///
932     /// Here we return `true` if:
933     ///
934     /// * The build isn't performing a full bootstrap
935     /// * The `compiler` is in the final stage, 2
936     /// * We're not cross-compiling, so the artifacts are already available in
937     ///   stage1
938     ///
939     /// When all of these conditions are met the build will lift artifacts from
940     /// the previous stage forward.
941     fn force_use_stage1(&self, compiler: Compiler, target: Interned<String>) -> bool {
942         !self.config.full_bootstrap
943             && compiler.stage >= 2
944             && (self.hosts.iter().any(|h| *h == target) || target == self.build)
945     }
946
947     /// Given `num` in the form "a.b.c" return a "release string" which
948     /// describes the release version number.
949     ///
950     /// For example on nightly this returns "a.b.c-nightly", on beta it returns
951     /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
952     fn release(&self, num: &str) -> String {
953         match &self.config.channel[..] {
954             "stable" => num.to_string(),
955             "beta" => {
956                 if self.rust_info.is_git() {
957                     format!("{}-beta.{}", num, self.beta_prerelease_version())
958                 } else {
959                     format!("{}-beta", num)
960                 }
961             }
962             "nightly" => format!("{}-nightly", num),
963             _ => format!("{}-dev", num),
964         }
965     }
966
967     fn beta_prerelease_version(&self) -> u32 {
968         if let Some(s) = self.prerelease_version.get() {
969             return s;
970         }
971
972         // Figure out how many merge commits happened since we branched off master.
973         // That's our beta number!
974         // (Note that we use a `..` range, not the `...` symmetric difference.)
975         let count = output(
976             Command::new("git")
977                 .arg("rev-list")
978                 .arg("--count")
979                 .arg("--merges")
980                 .arg("refs/remotes/origin/master..HEAD")
981                 .current_dir(&self.src),
982         );
983         let n = count.trim().parse().unwrap();
984         self.prerelease_version.set(Some(n));
985         n
986     }
987
988     /// Returns the value of `release` above for Rust itself.
989     fn rust_release(&self) -> String {
990         self.release(channel::CFG_RELEASE_NUM)
991     }
992
993     /// Returns the "package version" for a component given the `num` release
994     /// number.
995     ///
996     /// The package version is typically what shows up in the names of tarballs.
997     /// For channels like beta/nightly it's just the channel name, otherwise
998     /// it's the `num` provided.
999     fn package_vers(&self, num: &str) -> String {
1000         match &self.config.channel[..] {
1001             "stable" => num.to_string(),
1002             "beta" => "beta".to_string(),
1003             "nightly" => "nightly".to_string(),
1004             _ => format!("{}-dev", num),
1005         }
1006     }
1007
1008     /// Returns the value of `package_vers` above for Rust itself.
1009     fn rust_package_vers(&self) -> String {
1010         self.package_vers(channel::CFG_RELEASE_NUM)
1011     }
1012
1013     /// Returns the value of `package_vers` above for Cargo
1014     fn cargo_package_vers(&self) -> String {
1015         self.package_vers(&self.release_num("cargo"))
1016     }
1017
1018     /// Returns the value of `package_vers` above for rls
1019     fn rls_package_vers(&self) -> String {
1020         self.package_vers(&self.release_num("rls"))
1021     }
1022
1023     /// Returns the value of `package_vers` above for clippy
1024     fn clippy_package_vers(&self) -> String {
1025         self.package_vers(&self.release_num("clippy"))
1026     }
1027
1028     /// Returns the value of `package_vers` above for miri
1029     fn miri_package_vers(&self) -> String {
1030         self.package_vers(&self.release_num("miri"))
1031     }
1032
1033     /// Returns the value of `package_vers` above for rustfmt
1034     fn rustfmt_package_vers(&self) -> String {
1035         self.package_vers(&self.release_num("rustfmt"))
1036     }
1037
1038     fn llvm_tools_package_vers(&self) -> String {
1039         self.package_vers(channel::CFG_RELEASE_NUM)
1040     }
1041
1042     fn llvm_tools_vers(&self) -> String {
1043         self.rust_version()
1044     }
1045
1046     fn llvm_link_tools_dynamically(&self, target: Interned<String>) -> bool {
1047         target.contains("linux-gnu") || target.contains("apple-darwin")
1048     }
1049
1050     /// Returns the `version` string associated with this compiler for Rust
1051     /// itself.
1052     ///
1053     /// Note that this is a descriptive string which includes the commit date,
1054     /// sha, version, etc.
1055     fn rust_version(&self) -> String {
1056         self.rust_info.version(self, channel::CFG_RELEASE_NUM)
1057     }
1058
1059     /// Returns the full commit hash.
1060     fn rust_sha(&self) -> Option<&str> {
1061         self.rust_info.sha()
1062     }
1063
1064     /// Returns the `a.b.c` version that the given package is at.
1065     fn release_num(&self, package: &str) -> String {
1066         let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
1067         let toml = t!(fs::read_to_string(&toml_file_name));
1068         for line in toml.lines() {
1069             let prefix = "version = \"";
1070             let suffix = "\"";
1071             if line.starts_with(prefix) && line.ends_with(suffix) {
1072                 return line[prefix.len()..line.len() - suffix.len()].to_string();
1073             }
1074         }
1075
1076         panic!("failed to find version in {}'s Cargo.toml", package)
1077     }
1078
1079     /// Returns `true` if unstable features should be enabled for the compiler
1080     /// we're building.
1081     fn unstable_features(&self) -> bool {
1082         match &self.config.channel[..] {
1083             "stable" | "beta" => false,
1084             "nightly" | _ => true,
1085         }
1086     }
1087
1088     /// Returns a Vec of all the dependencies of the given root crate,
1089     /// including transitive dependencies and the root itself. Only includes
1090     /// "local" crates (those in the local source tree, not from a registry).
1091     fn in_tree_crates(&self, root: &str) -> Vec<&Crate> {
1092         let mut ret = Vec::new();
1093         let mut list = vec![INTERNER.intern_str(root)];
1094         let mut visited = HashSet::new();
1095         while let Some(krate) = list.pop() {
1096             let krate = &self.crates[&krate];
1097             ret.push(krate);
1098             for dep in &krate.deps {
1099                 // Don't include optional deps if their features are not
1100                 // enabled. Ideally this would be computed from `cargo
1101                 // metadata --features …`, but that is somewhat slow. Just
1102                 // skip `build_helper` since there aren't any operations we
1103                 // want to perform on it. In the future, we may want to
1104                 // consider just filtering all build and dev dependencies in
1105                 // metadata::build.
1106                 if visited.insert(dep)
1107                     && dep != "build_helper"
1108                     && (dep != "profiler_builtins" || self.config.profiler)
1109                     && (dep != "rustc_codegen_llvm" || self.config.llvm_enabled())
1110                 {
1111                     list.push(*dep);
1112                 }
1113             }
1114         }
1115         ret
1116     }
1117
1118     fn read_stamp_file(&self, stamp: &Path) -> Vec<(PathBuf, DependencyType)> {
1119         if self.config.dry_run {
1120             return Vec::new();
1121         }
1122
1123         let mut paths = Vec::new();
1124         let contents = t!(fs::read(stamp), &stamp);
1125         // This is the method we use for extracting paths from the stamp file passed to us. See
1126         // run_cargo for more information (in compile.rs).
1127         for part in contents.split(|b| *b == 0) {
1128             if part.is_empty() {
1129                 continue;
1130             }
1131             let dependency_type = match part[0] as char {
1132                 'h' => DependencyType::Host,
1133                 's' => DependencyType::TargetSelfContained,
1134                 't' => DependencyType::Target,
1135                 _ => unreachable!(),
1136             };
1137             let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1138             paths.push((path, dependency_type));
1139         }
1140         paths
1141     }
1142
1143     /// Copies a file from `src` to `dst`
1144     pub fn copy(&self, src: &Path, dst: &Path) {
1145         if self.config.dry_run {
1146             return;
1147         }
1148         self.verbose_than(1, &format!("Copy {:?} to {:?}", src, dst));
1149         if src == dst {
1150             return;
1151         }
1152         let _ = fs::remove_file(&dst);
1153         let metadata = t!(src.symlink_metadata());
1154         if metadata.file_type().is_symlink() {
1155             let link = t!(fs::read_link(src));
1156             t!(symlink_file(link, dst));
1157         } else if let Ok(()) = fs::hard_link(src, dst) {
1158             // Attempt to "easy copy" by creating a hard link
1159             // (symlinks don't work on windows), but if that fails
1160             // just fall back to a slow `copy` operation.
1161         } else {
1162             if let Err(e) = fs::copy(src, dst) {
1163                 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1164             }
1165             t!(fs::set_permissions(dst, metadata.permissions()));
1166             let atime = FileTime::from_last_access_time(&metadata);
1167             let mtime = FileTime::from_last_modification_time(&metadata);
1168             t!(filetime::set_file_times(dst, atime, mtime));
1169         }
1170     }
1171
1172     /// Search-and-replaces within a file. (Not maximally efficiently: allocates a
1173     /// new string for each replacement.)
1174     pub fn replace_in_file(&self, path: &Path, replacements: &[(&str, &str)]) {
1175         if self.config.dry_run {
1176             return;
1177         }
1178         let mut contents = String::new();
1179         let mut file = t!(OpenOptions::new().read(true).write(true).open(path));
1180         t!(file.read_to_string(&mut contents));
1181         for &(target, replacement) in replacements {
1182             contents = contents.replace(target, replacement);
1183         }
1184         t!(file.seek(SeekFrom::Start(0)));
1185         t!(file.set_len(0));
1186         t!(file.write_all(contents.as_bytes()));
1187     }
1188
1189     /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1190     /// when this function is called.
1191     pub fn cp_r(&self, src: &Path, dst: &Path) {
1192         if self.config.dry_run {
1193             return;
1194         }
1195         for f in self.read_dir(src) {
1196             let path = f.path();
1197             let name = path.file_name().unwrap();
1198             let dst = dst.join(name);
1199             if t!(f.file_type()).is_dir() {
1200                 t!(fs::create_dir_all(&dst));
1201                 self.cp_r(&path, &dst);
1202             } else {
1203                 let _ = fs::remove_file(&dst);
1204                 self.copy(&path, &dst);
1205             }
1206         }
1207     }
1208
1209     /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1210     /// when this function is called. Unwanted files or directories can be skipped
1211     /// by returning `false` from the filter function.
1212     pub fn cp_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1213         // Immediately recurse with an empty relative path
1214         self.recurse_(src, dst, Path::new(""), filter)
1215     }
1216
1217     // Inner function does the actual work
1218     fn recurse_(&self, src: &Path, dst: &Path, relative: &Path, filter: &dyn Fn(&Path) -> bool) {
1219         for f in self.read_dir(src) {
1220             let path = f.path();
1221             let name = path.file_name().unwrap();
1222             let dst = dst.join(name);
1223             let relative = relative.join(name);
1224             // Only copy file or directory if the filter function returns true
1225             if filter(&relative) {
1226                 if t!(f.file_type()).is_dir() {
1227                     let _ = fs::remove_dir_all(&dst);
1228                     self.create_dir(&dst);
1229                     self.recurse_(&path, &dst, &relative, filter);
1230                 } else {
1231                     let _ = fs::remove_file(&dst);
1232                     self.copy(&path, &dst);
1233                 }
1234             }
1235         }
1236     }
1237
1238     fn copy_to_folder(&self, src: &Path, dest_folder: &Path) {
1239         let file_name = src.file_name().unwrap();
1240         let dest = dest_folder.join(file_name);
1241         self.copy(src, &dest);
1242     }
1243
1244     fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1245         if self.config.dry_run {
1246             return;
1247         }
1248         let dst = dstdir.join(src.file_name().unwrap());
1249         self.verbose_than(1, &format!("Install {:?} to {:?}", src, dst));
1250         t!(fs::create_dir_all(dstdir));
1251         drop(fs::remove_file(&dst));
1252         {
1253             if !src.exists() {
1254                 panic!("Error: File \"{}\" not found!", src.display());
1255             }
1256             let metadata = t!(src.symlink_metadata());
1257             if let Err(e) = fs::copy(&src, &dst) {
1258                 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1259             }
1260             t!(fs::set_permissions(&dst, metadata.permissions()));
1261             let atime = FileTime::from_last_access_time(&metadata);
1262             let mtime = FileTime::from_last_modification_time(&metadata);
1263             t!(filetime::set_file_times(&dst, atime, mtime));
1264         }
1265         chmod(&dst, perms);
1266     }
1267
1268     fn create(&self, path: &Path, s: &str) {
1269         if self.config.dry_run {
1270             return;
1271         }
1272         t!(fs::write(path, s));
1273     }
1274
1275     fn read(&self, path: &Path) -> String {
1276         if self.config.dry_run {
1277             return String::new();
1278         }
1279         t!(fs::read_to_string(path))
1280     }
1281
1282     fn create_dir(&self, dir: &Path) {
1283         if self.config.dry_run {
1284             return;
1285         }
1286         t!(fs::create_dir_all(dir))
1287     }
1288
1289     fn remove_dir(&self, dir: &Path) {
1290         if self.config.dry_run {
1291             return;
1292         }
1293         t!(fs::remove_dir_all(dir))
1294     }
1295
1296     fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1297         let iter = match fs::read_dir(dir) {
1298             Ok(v) => v,
1299             Err(_) if self.config.dry_run => return vec![].into_iter(),
1300             Err(err) => panic!("could not read dir {:?}: {:?}", dir, err),
1301         };
1302         iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1303     }
1304
1305     fn remove(&self, f: &Path) {
1306         if self.config.dry_run {
1307             return;
1308         }
1309         fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {:?}", f));
1310     }
1311 }
1312
1313 #[cfg(unix)]
1314 fn chmod(path: &Path, perms: u32) {
1315     use std::os::unix::fs::*;
1316     t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1317 }
1318 #[cfg(windows)]
1319 fn chmod(_path: &Path, _perms: u32) {}
1320
1321 impl Compiler {
1322     pub fn with_stage(mut self, stage: u32) -> Compiler {
1323         self.stage = stage;
1324         self
1325     }
1326
1327     /// Returns `true` if this is a snapshot compiler for `build`'s configuration
1328     pub fn is_snapshot(&self, build: &Build) -> bool {
1329         self.stage == 0 && self.host == build.build
1330     }
1331
1332     /// Returns if this compiler should be treated as a final stage one in the
1333     /// current build session.
1334     /// This takes into account whether we're performing a full bootstrap or
1335     /// not; don't directly compare the stage with `2`!
1336     pub fn is_final_stage(&self, build: &Build) -> bool {
1337         let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
1338         self.stage >= final_stage
1339     }
1340 }
1341
1342 fn envify(s: &str) -> String {
1343     s.chars()
1344         .map(|c| match c {
1345             '-' => '_',
1346             c => c,
1347         })
1348         .flat_map(|c| c.to_uppercase())
1349         .collect()
1350 }