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