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