1 //! Serialized configuration of a build.
3 //! This module implements parsing `config.toml` configuration files to tweak
4 //! how the build runs.
6 use std::cell::{Cell, RefCell};
8 use std::collections::{HashMap, HashSet};
13 use std::path::{Path, PathBuf};
14 use std::process::Command;
15 use std::str::FromStr;
17 use crate::builder::{Builder, TaskPath};
18 use crate::cache::{Interned, INTERNER};
19 use crate::channel::GitInfo;
20 pub use crate::flags::Subcommand;
21 use crate::flags::{Color, Flags};
22 use crate::util::{exe, output, program_out_of_date, t};
23 use once_cell::sync::OnceCell;
24 use serde::{Deserialize, Deserializer};
26 macro_rules! check_ci_llvm {
30 "setting {} is incompatible with download-ci-llvm.",
36 /// Global configuration for the entire build and/or bootstrap.
38 /// This structure is derived from a combination of both `config.toml` and
39 /// `config.mk`. As of the time of this writing it's unlikely that `config.toml`
40 /// is used all that much, so this is primarily filled out by `config.mk` which
41 /// is generated from `./configure`.
43 /// Note that this structure is not decoded directly into, but rather it is
44 /// filled out from the decoded forms of the structs below. For documentation
45 /// each field, see the corresponding fields in
46 /// `config.toml.example`.
48 #[cfg_attr(test, derive(Clone))]
50 pub changelog_seen: Option<usize>,
51 pub ccache: Option<String>,
52 /// Call Build::ninja() instead of this.
53 pub ninja_in_file: bool,
55 pub submodules: Option<bool>,
56 pub compiler_docs: bool,
57 pub docs_minification: bool,
59 pub locked_deps: bool,
61 pub target_config: HashMap<TargetSelection, Target>,
62 pub full_bootstrap: bool,
64 pub tools: Option<HashSet<String>>,
68 pub exclude: Vec<TaskPath>,
69 pub include_default_paths: bool,
70 pub rustc_error_format: Option<String>,
71 pub json_output: bool,
72 pub test_compare_mode: bool,
74 pub patch_binaries_for_nix: bool,
75 pub stage0_metadata: Stage0Metadata,
76 /// Whether to use the `c` feature of the `compiler_builtins` crate.
77 pub optimized_compiler_builtins: bool,
79 pub on_fail: Option<String>,
81 pub keep_stage: Vec<u32>,
82 pub keep_stage_std: Vec<u32>,
84 /// defaults to `config.toml`
86 pub jobs: Option<u32>,
88 pub incremental: bool,
90 /// `None` if we shouldn't download CI compiler artifacts, or the commit to download if we should.
92 download_rustc_commit: Option<String>,
94 pub download_rustc_commit: Option<String>,
96 pub deny_warnings: bool,
97 pub backtrace_on_ice: bool,
99 // llvm codegen options
100 pub llvm_skip_rebuild: bool,
101 pub llvm_assertions: bool,
102 pub llvm_tests: bool,
103 pub llvm_plugins: bool,
104 pub llvm_optimize: bool,
105 pub llvm_thin_lto: bool,
106 pub llvm_release_debuginfo: bool,
107 pub llvm_version_check: bool,
108 pub llvm_static_stdcpp: bool,
109 /// `None` if `llvm_from_ci` is true and we haven't yet downloaded llvm.
111 llvm_link_shared: Cell<Option<bool>>,
113 pub llvm_link_shared: Cell<Option<bool>>,
114 pub llvm_clang_cl: Option<String>,
115 pub llvm_targets: Option<String>,
116 pub llvm_experimental_targets: Option<String>,
117 pub llvm_link_jobs: Option<u32>,
118 pub llvm_version_suffix: Option<String>,
119 pub llvm_use_linker: Option<String>,
120 pub llvm_allow_old_toolchain: bool,
121 pub llvm_polly: bool,
122 pub llvm_clang: bool,
123 pub llvm_from_ci: bool,
124 pub llvm_build_config: HashMap<String, String>,
127 pub lld_enabled: bool,
128 pub llvm_tools_enabled: bool,
130 pub llvm_cflags: Option<String>,
131 pub llvm_cxxflags: Option<String>,
132 pub llvm_ldflags: Option<String>,
133 pub llvm_use_libcxx: bool,
135 // rust codegen options
136 pub rust_optimize: bool,
137 pub rust_codegen_units: Option<u32>,
138 pub rust_codegen_units_std: Option<u32>,
139 pub rust_debug_assertions: bool,
140 pub rust_debug_assertions_std: bool,
141 pub rust_overflow_checks: bool,
142 pub rust_overflow_checks_std: bool,
143 pub rust_debug_logging: bool,
144 pub rust_debuginfo_level_rustc: u32,
145 pub rust_debuginfo_level_std: u32,
146 pub rust_debuginfo_level_tools: u32,
147 pub rust_debuginfo_level_tests: u32,
148 pub rust_split_debuginfo: SplitDebuginfo,
149 pub rust_rpath: bool,
150 pub rustc_parallel: bool,
151 pub rustc_default_linker: Option<String>,
152 pub rust_optimize_tests: bool,
153 pub rust_dist_src: bool,
154 pub rust_codegen_backends: Vec<Interned<String>>,
155 pub rust_verify_llvm_ir: bool,
156 pub rust_thin_lto_import_instr_limit: Option<u32>,
157 pub rust_remap_debuginfo: bool,
158 pub rust_new_symbol_mangling: Option<bool>,
159 pub rust_profile_use: Option<String>,
160 pub rust_profile_generate: Option<String>,
161 pub llvm_profile_use: Option<String>,
162 pub llvm_profile_generate: bool,
163 pub llvm_libunwind_default: Option<LlvmLibunwind>,
164 pub llvm_bolt_profile_generate: bool,
165 pub llvm_bolt_profile_use: Option<String>,
167 pub build: TargetSelection,
168 pub hosts: Vec<TargetSelection>,
169 pub targets: Vec<TargetSelection>,
170 pub local_rebuild: bool,
172 pub control_flow_guard: bool,
175 pub dist_sign_folder: Option<PathBuf>,
176 pub dist_upload_addr: Option<String>,
177 pub dist_compression_formats: Option<Vec<String>>,
180 pub backtrace: bool, // support for RUST_BACKTRACE
183 pub low_priority: bool,
185 pub description: Option<String>,
186 pub verbose_tests: bool,
187 pub save_toolstates: Option<PathBuf>,
188 pub print_step_timings: bool,
189 pub print_step_rusage: bool,
190 pub missing_tools: bool,
192 // Fallback musl-root for all targets
193 pub musl_root: Option<PathBuf>,
194 pub prefix: Option<PathBuf>,
195 pub sysconfdir: Option<PathBuf>,
196 pub datadir: Option<PathBuf>,
197 pub docdir: Option<PathBuf>,
199 pub libdir: Option<PathBuf>,
200 pub mandir: Option<PathBuf>,
201 pub codegen_tests: bool,
202 pub nodejs: Option<PathBuf>,
203 pub npm: Option<PathBuf>,
204 pub gdb: Option<PathBuf>,
205 pub python: Option<PathBuf>,
206 pub cargo_native_static: bool,
207 pub configure_args: Vec<String>,
209 // These are either the stage0 downloaded binaries or the locally installed ones.
210 pub initial_cargo: PathBuf,
211 pub initial_rustc: PathBuf,
213 initial_rustfmt: RefCell<RustfmtState>,
215 pub initial_rustfmt: RefCell<RustfmtState>,
219 #[derive(Default, Deserialize)]
220 #[cfg_attr(test, derive(Clone))]
221 pub struct Stage0Metadata {
222 pub config: Stage0Config,
223 pub checksums_sha256: HashMap<String, String>,
224 pub rustfmt: Option<RustfmtMetadata>,
226 #[derive(Default, Deserialize)]
227 #[cfg_attr(test, derive(Clone))]
228 pub struct Stage0Config {
229 pub dist_server: String,
230 pub artifacts_server: String,
231 pub artifacts_with_llvm_assertions_server: String,
232 pub git_merge_commit_email: String,
233 pub nightly_branch: String,
235 #[derive(Default, Deserialize)]
236 #[cfg_attr(test, derive(Clone))]
237 pub struct RustfmtMetadata {
242 #[derive(Clone, Debug)]
243 pub enum RustfmtState {
244 SystemToolchain(PathBuf),
250 impl Default for RustfmtState {
251 fn default() -> Self {
252 RustfmtState::LazyEvaluated
256 #[derive(Debug, Clone, Copy, PartialEq)]
257 pub enum LlvmLibunwind {
263 impl Default for LlvmLibunwind {
264 fn default() -> Self {
269 impl FromStr for LlvmLibunwind {
272 fn from_str(value: &str) -> Result<Self, Self::Err> {
274 "no" => Ok(Self::No),
275 "in-tree" => Ok(Self::InTree),
276 "system" => Ok(Self::System),
277 invalid => Err(format!("Invalid value '{}' for rust.llvm-libunwind config.", invalid)),
282 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
283 pub enum SplitDebuginfo {
289 impl Default for SplitDebuginfo {
290 fn default() -> Self {
295 impl std::str::FromStr for SplitDebuginfo {
298 fn from_str(s: &str) -> Result<Self, Self::Err> {
300 "packed" => Ok(SplitDebuginfo::Packed),
301 "unpacked" => Ok(SplitDebuginfo::Unpacked),
302 "off" => Ok(SplitDebuginfo::Off),
308 impl SplitDebuginfo {
309 /// Returns the default `-Csplit-debuginfo` value for the current target. See the comment for
310 /// `rust.split-debuginfo` in `config.toml.example`.
311 fn default_for_platform(target: &str) -> Self {
312 if target.contains("apple") {
313 SplitDebuginfo::Unpacked
314 } else if target.contains("windows") {
315 SplitDebuginfo::Packed
322 #[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
323 pub struct TargetSelection {
324 pub triple: Interned<String>,
325 file: Option<Interned<String>>,
328 impl TargetSelection {
329 pub fn from_user(selection: &str) -> Self {
330 let path = Path::new(selection);
332 let (triple, file) = if path.exists() {
335 .expect("Target specification file has no file stem")
337 .expect("Target specification file stem is not UTF-8");
339 (triple, Some(selection))
344 let triple = INTERNER.intern_str(triple);
345 let file = file.map(|f| INTERNER.intern_str(f));
347 Self { triple, file }
350 pub fn rustc_target_arg(&self) -> &str {
351 self.file.as_ref().unwrap_or(&self.triple)
354 pub fn contains(&self, needle: &str) -> bool {
355 self.triple.contains(needle)
358 pub fn starts_with(&self, needle: &str) -> bool {
359 self.triple.starts_with(needle)
362 pub fn ends_with(&self, needle: &str) -> bool {
363 self.triple.ends_with(needle)
367 impl fmt::Display for TargetSelection {
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 write!(f, "{}", self.triple)?;
370 if let Some(file) = self.file {
371 write!(f, "({})", file)?;
377 impl fmt::Debug for TargetSelection {
378 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
379 write!(f, "{}", self)
383 impl PartialEq<&str> for TargetSelection {
384 fn eq(&self, other: &&str) -> bool {
385 self.triple == *other
389 /// Per-target configuration stored in the global configuration structure.
391 #[cfg_attr(test, derive(Clone))]
393 /// Some(path to llvm-config) if using an external LLVM.
394 pub llvm_config: Option<PathBuf>,
395 pub llvm_has_rust_patches: Option<bool>,
396 /// Some(path to FileCheck) if one was specified.
397 pub llvm_filecheck: Option<PathBuf>,
398 pub llvm_libunwind: Option<LlvmLibunwind>,
399 pub cc: Option<PathBuf>,
400 pub cxx: Option<PathBuf>,
401 pub ar: Option<PathBuf>,
402 pub ranlib: Option<PathBuf>,
403 pub default_linker: Option<PathBuf>,
404 pub linker: Option<PathBuf>,
405 pub ndk: Option<PathBuf>,
406 pub sanitizers: Option<bool>,
407 pub profiler: Option<bool>,
408 pub crt_static: Option<bool>,
409 pub musl_root: Option<PathBuf>,
410 pub musl_libdir: Option<PathBuf>,
411 pub wasi_root: Option<PathBuf>,
412 pub qemu_rootfs: Option<PathBuf>,
417 pub fn from_triple(triple: &str) -> Self {
418 let mut target: Self = Default::default();
419 if triple.contains("-none")
420 || triple.contains("nvptx")
421 || triple.contains("switch")
422 || triple.contains("-uefi")
424 target.no_std = true;
429 /// Structure of the `config.toml` file that configuration is read from.
431 /// This structure uses `Decodable` to automatically decode a TOML configuration
432 /// file into this format, and then this is traversed and written into the above
433 /// `Config` structure.
434 #[derive(Deserialize, Default)]
435 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
437 changelog_seen: Option<usize>,
438 build: Option<Build>,
439 install: Option<Install>,
442 target: Option<HashMap<String, TomlTarget>>,
444 profile: Option<String>,
448 fn merge(&mut self, other: Self);
451 impl Merge for TomlConfig {
454 TomlConfig { build, install, llvm, rust, dist, target, profile: _, changelog_seen: _ }: Self,
456 fn do_merge<T: Merge>(x: &mut Option<T>, y: Option<T>) {
457 if let Some(new) = y {
458 if let Some(original) = x {
465 do_merge(&mut self.build, build);
466 do_merge(&mut self.install, install);
467 do_merge(&mut self.llvm, llvm);
468 do_merge(&mut self.rust, rust);
469 do_merge(&mut self.dist, dist);
470 assert!(target.is_none(), "merging target-specific config is not currently supported");
474 // We are using a decl macro instead of a derive proc macro here to reduce the compile time of
476 macro_rules! define_config {
477 ($(#[$attr:meta])* struct $name:ident {
478 $($field:ident: Option<$field_ty:ty> = $field_key:literal,)*
482 $($field: Option<$field_ty>,)*
485 impl Merge for $name {
486 fn merge(&mut self, other: Self) {
488 if !self.$field.is_some() {
489 self.$field = other.$field;
495 // The following is a trimmed version of what serde_derive generates. All parts not relevant
496 // for toml deserialization have been removed. This reduces the binary size and improves
497 // compile time of rustbuild.
498 impl<'de> Deserialize<'de> for $name {
499 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
501 D: Deserializer<'de>,
504 impl<'de> serde::de::Visitor<'de> for Field {
506 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
507 f.write_str(concat!("struct ", stringify!($name)))
511 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
513 A: serde::de::MapAccess<'de>,
515 $(let mut $field: Option<$field_ty> = None;)*
516 while let Some(key) =
517 match serde::de::MapAccess::next_key::<String>(&mut map) {
526 if $field.is_some() {
527 return Err(<A::Error as serde::de::Error>::duplicate_field(
531 $field = match serde::de::MapAccess::next_value::<$field_ty>(
534 Ok(val) => Some(val),
541 return Err(serde::de::Error::unknown_field(key, FIELDS));
545 Ok($name { $($field),* })
548 const FIELDS: &'static [&'static str] = &[
551 Deserializer::deserialize_struct(
563 /// TOML representation of various global build decisions.
566 build: Option<String> = "build",
567 host: Option<Vec<String>> = "host",
568 target: Option<Vec<String>> = "target",
569 build_dir: Option<String> = "build-dir",
570 cargo: Option<String> = "cargo",
571 rustc: Option<String> = "rustc",
572 rustfmt: Option<PathBuf> = "rustfmt",
573 docs: Option<bool> = "docs",
574 compiler_docs: Option<bool> = "compiler-docs",
575 docs_minification: Option<bool> = "docs-minification",
576 submodules: Option<bool> = "submodules",
577 gdb: Option<String> = "gdb",
578 nodejs: Option<String> = "nodejs",
579 npm: Option<String> = "npm",
580 python: Option<String> = "python",
581 locked_deps: Option<bool> = "locked-deps",
582 vendor: Option<bool> = "vendor",
583 full_bootstrap: Option<bool> = "full-bootstrap",
584 extended: Option<bool> = "extended",
585 tools: Option<HashSet<String>> = "tools",
586 verbose: Option<usize> = "verbose",
587 sanitizers: Option<bool> = "sanitizers",
588 profiler: Option<bool> = "profiler",
589 cargo_native_static: Option<bool> = "cargo-native-static",
590 low_priority: Option<bool> = "low-priority",
591 configure_args: Option<Vec<String>> = "configure-args",
592 local_rebuild: Option<bool> = "local-rebuild",
593 print_step_timings: Option<bool> = "print-step-timings",
594 print_step_rusage: Option<bool> = "print-step-rusage",
595 check_stage: Option<u32> = "check-stage",
596 doc_stage: Option<u32> = "doc-stage",
597 build_stage: Option<u32> = "build-stage",
598 test_stage: Option<u32> = "test-stage",
599 install_stage: Option<u32> = "install-stage",
600 dist_stage: Option<u32> = "dist-stage",
601 bench_stage: Option<u32> = "bench-stage",
602 patch_binaries_for_nix: Option<bool> = "patch-binaries-for-nix",
603 metrics: Option<bool> = "metrics",
604 optimized_compiler_builtins: Option<bool> = "optimized-compiler-builtins",
609 /// TOML representation of various global install decisions.
611 prefix: Option<String> = "prefix",
612 sysconfdir: Option<String> = "sysconfdir",
613 docdir: Option<String> = "docdir",
614 bindir: Option<String> = "bindir",
615 libdir: Option<String> = "libdir",
616 mandir: Option<String> = "mandir",
617 datadir: Option<String> = "datadir",
622 /// TOML representation of how the LLVM build is configured.
624 skip_rebuild: Option<bool> = "skip-rebuild",
625 optimize: Option<bool> = "optimize",
626 thin_lto: Option<bool> = "thin-lto",
627 release_debuginfo: Option<bool> = "release-debuginfo",
628 assertions: Option<bool> = "assertions",
629 tests: Option<bool> = "tests",
630 plugins: Option<bool> = "plugins",
631 ccache: Option<StringOrBool> = "ccache",
632 version_check: Option<bool> = "version-check",
633 static_libstdcpp: Option<bool> = "static-libstdcpp",
634 ninja: Option<bool> = "ninja",
635 targets: Option<String> = "targets",
636 experimental_targets: Option<String> = "experimental-targets",
637 link_jobs: Option<u32> = "link-jobs",
638 link_shared: Option<bool> = "link-shared",
639 version_suffix: Option<String> = "version-suffix",
640 clang_cl: Option<String> = "clang-cl",
641 cflags: Option<String> = "cflags",
642 cxxflags: Option<String> = "cxxflags",
643 ldflags: Option<String> = "ldflags",
644 use_libcxx: Option<bool> = "use-libcxx",
645 use_linker: Option<String> = "use-linker",
646 allow_old_toolchain: Option<bool> = "allow-old-toolchain",
647 polly: Option<bool> = "polly",
648 clang: Option<bool> = "clang",
649 download_ci_llvm: Option<StringOrBool> = "download-ci-llvm",
650 build_config: Option<HashMap<String, String>> = "build-config",
656 sign_folder: Option<String> = "sign-folder",
657 gpg_password_file: Option<String> = "gpg-password-file",
658 upload_addr: Option<String> = "upload-addr",
659 src_tarball: Option<bool> = "src-tarball",
660 missing_tools: Option<bool> = "missing-tools",
661 compression_formats: Option<Vec<String>> = "compression-formats",
665 #[derive(Deserialize)]
672 impl Default for StringOrBool {
673 fn default() -> StringOrBool {
674 StringOrBool::Bool(false)
679 /// TOML representation of how the Rust build is configured.
681 optimize: Option<bool> = "optimize",
682 debug: Option<bool> = "debug",
683 codegen_units: Option<u32> = "codegen-units",
684 codegen_units_std: Option<u32> = "codegen-units-std",
685 debug_assertions: Option<bool> = "debug-assertions",
686 debug_assertions_std: Option<bool> = "debug-assertions-std",
687 overflow_checks: Option<bool> = "overflow-checks",
688 overflow_checks_std: Option<bool> = "overflow-checks-std",
689 debug_logging: Option<bool> = "debug-logging",
690 debuginfo_level: Option<u32> = "debuginfo-level",
691 debuginfo_level_rustc: Option<u32> = "debuginfo-level-rustc",
692 debuginfo_level_std: Option<u32> = "debuginfo-level-std",
693 debuginfo_level_tools: Option<u32> = "debuginfo-level-tools",
694 debuginfo_level_tests: Option<u32> = "debuginfo-level-tests",
695 split_debuginfo: Option<String> = "split-debuginfo",
696 run_dsymutil: Option<bool> = "run-dsymutil",
697 backtrace: Option<bool> = "backtrace",
698 incremental: Option<bool> = "incremental",
699 parallel_compiler: Option<bool> = "parallel-compiler",
700 default_linker: Option<String> = "default-linker",
701 channel: Option<String> = "channel",
702 description: Option<String> = "description",
703 musl_root: Option<String> = "musl-root",
704 rpath: Option<bool> = "rpath",
705 verbose_tests: Option<bool> = "verbose-tests",
706 optimize_tests: Option<bool> = "optimize-tests",
707 codegen_tests: Option<bool> = "codegen-tests",
708 ignore_git: Option<bool> = "ignore-git",
709 dist_src: Option<bool> = "dist-src",
710 save_toolstates: Option<String> = "save-toolstates",
711 codegen_backends: Option<Vec<String>> = "codegen-backends",
712 lld: Option<bool> = "lld",
713 use_lld: Option<bool> = "use-lld",
714 llvm_tools: Option<bool> = "llvm-tools",
715 deny_warnings: Option<bool> = "deny-warnings",
716 backtrace_on_ice: Option<bool> = "backtrace-on-ice",
717 verify_llvm_ir: Option<bool> = "verify-llvm-ir",
718 thin_lto_import_instr_limit: Option<u32> = "thin-lto-import-instr-limit",
719 remap_debuginfo: Option<bool> = "remap-debuginfo",
720 jemalloc: Option<bool> = "jemalloc",
721 test_compare_mode: Option<bool> = "test-compare-mode",
722 llvm_libunwind: Option<String> = "llvm-libunwind",
723 control_flow_guard: Option<bool> = "control-flow-guard",
724 new_symbol_mangling: Option<bool> = "new-symbol-mangling",
725 profile_generate: Option<String> = "profile-generate",
726 profile_use: Option<String> = "profile-use",
727 // ignored; this is set from an env var set by bootstrap.py
728 download_rustc: Option<StringOrBool> = "download-rustc",
733 /// TOML representation of how each build target is configured.
735 cc: Option<String> = "cc",
736 cxx: Option<String> = "cxx",
737 ar: Option<String> = "ar",
738 ranlib: Option<String> = "ranlib",
739 default_linker: Option<PathBuf> = "default-linker",
740 linker: Option<String> = "linker",
741 llvm_config: Option<String> = "llvm-config",
742 llvm_has_rust_patches: Option<bool> = "llvm-has-rust-patches",
743 llvm_filecheck: Option<String> = "llvm-filecheck",
744 llvm_libunwind: Option<String> = "llvm-libunwind",
745 android_ndk: Option<String> = "android-ndk",
746 sanitizers: Option<bool> = "sanitizers",
747 profiler: Option<bool> = "profiler",
748 crt_static: Option<bool> = "crt-static",
749 musl_root: Option<String> = "musl-root",
750 musl_libdir: Option<String> = "musl-libdir",
751 wasi_root: Option<String> = "wasi-root",
752 qemu_rootfs: Option<String> = "qemu-rootfs",
753 no_std: Option<bool> = "no-std",
758 pub fn default_opts() -> Config {
759 let mut config = Config::default();
760 config.llvm_optimize = true;
761 config.ninja_in_file = true;
762 config.llvm_version_check = true;
763 config.llvm_static_stdcpp = true;
764 config.backtrace = true;
765 config.rust_optimize = true;
766 config.rust_optimize_tests = true;
767 config.submodules = None;
769 config.docs_minification = true;
770 config.rust_rpath = true;
771 config.channel = "dev".to_string();
772 config.codegen_tests = true;
773 config.rust_dist_src = true;
774 config.rust_codegen_backends = vec![INTERNER.intern_str("llvm")];
775 config.deny_warnings = true;
776 config.bindir = "bin".into();
779 config.build = TargetSelection::from_user(&env!("BUILD_TRIPLE"));
781 let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
782 // Undo `src/bootstrap`
783 config.src = manifest_dir.parent().unwrap().parent().unwrap().to_owned();
784 config.out = PathBuf::from("build");
789 pub fn parse(args: &[String]) -> Config {
790 let flags = Flags::parse(&args);
791 let mut config = Config::default_opts();
794 config.exclude = flags.exclude.into_iter().map(|path| TaskPath::parse(path)).collect();
795 config.include_default_paths = flags.include_default_paths;
796 config.rustc_error_format = flags.rustc_error_format;
797 config.json_output = flags.json_output;
798 config.on_fail = flags.on_fail;
799 config.jobs = flags.jobs.map(threads_from_config);
800 config.cmd = flags.cmd;
801 config.incremental = flags.incremental;
802 config.dry_run = flags.dry_run;
803 config.keep_stage = flags.keep_stage;
804 config.keep_stage_std = flags.keep_stage_std;
805 config.color = flags.color;
806 if let Some(value) = flags.deny_warnings {
807 config.deny_warnings = value;
809 config.llvm_profile_use = flags.llvm_profile_use;
810 config.llvm_profile_generate = flags.llvm_profile_generate;
811 config.llvm_bolt_profile_generate = flags.llvm_bolt_profile_generate;
812 config.llvm_bolt_profile_use = flags.llvm_bolt_profile_use;
814 if config.llvm_bolt_profile_generate && config.llvm_bolt_profile_use.is_some() {
816 "Cannot use both `llvm_bolt_profile_generate` and `llvm_bolt_profile_use` at the same time"
818 crate::detail_exit(1);
821 // Infer the rest of the configuration.
823 // Infer the source directory. This is non-trivial because we want to support a downloaded bootstrap binary,
824 // running on a completely machine from where it was compiled.
825 let mut cmd = Command::new("git");
826 // NOTE: we cannot support running from outside the repository because the only path we have available
827 // is set at compile time, which can be wrong if bootstrap was downloaded from source.
828 // We still support running outside the repository if we find we aren't in a git directory.
829 cmd.arg("rev-parse").arg("--show-toplevel");
830 // Discard stderr because we expect this to fail when building from a tarball.
832 .stderr(std::process::Stdio::null())
835 .and_then(|output| if output.status.success() { Some(output) } else { None });
836 if let Some(output) = output {
837 let git_root = String::from_utf8(output.stdout).unwrap();
838 // We need to canonicalize this path to make sure it uses backslashes instead of forward slashes.
839 let git_root = PathBuf::from(git_root.trim()).canonicalize().unwrap();
840 let s = git_root.to_str().unwrap();
842 // Bootstrap is quite bad at handling /? in front of paths
843 let src = match s.strip_prefix("\\\\?\\") {
844 Some(p) => PathBuf::from(p),
845 None => PathBuf::from(git_root),
847 // If this doesn't have at least `stage0.json`, we guessed wrong. This can happen when,
848 // for example, the build directory is inside of another unrelated git directory.
849 // In that case keep the original `CARGO_MANIFEST_DIR` handling.
851 // NOTE: this implies that downloadable bootstrap isn't supported when the build directory is outside
852 // the source directory. We could fix that by setting a variable from all three of python, ./x, and x.ps1.
853 if src.join("src").join("stage0.json").exists() {
857 // We're building from a tarball, not git sources.
858 // We don't support pre-downloaded bootstrap in this case.
862 // Use the build directory of the original x.py invocation, so that we can set `initial_rustc` properly.
863 config.out = Path::new(
864 &env::var_os("CARGO_TARGET_DIR").expect("cargo test directly is not supported"),
871 let stage0_json = t!(std::fs::read(&config.src.join("src").join("stage0.json")));
873 config.stage0_metadata = t!(serde_json::from_slice::<Stage0Metadata>(&stage0_json));
876 let get_toml = |_| TomlConfig::default();
878 let get_toml = |file: &Path| {
880 t!(fs::read_to_string(file), format!("config file {} not found", file.display()));
881 // Deserialize to Value and then TomlConfig to prevent the Deserialize impl of
882 // TomlConfig and sub types to be monomorphized 5x by toml.
883 match toml::from_str(&contents)
884 .and_then(|table: toml::Value| TomlConfig::deserialize(table))
888 eprintln!("failed to parse TOML configuration '{}': {}", file.display(), err);
889 crate::detail_exit(2);
894 // Read from `--config`, then `RUST_BOOTSTRAP_CONFIG`, then `./config.toml`, then `config.toml` in the root directory.
895 let toml_path = flags
898 .or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
899 let using_default_path = toml_path.is_none();
900 let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("config.toml"));
901 if using_default_path && !toml_path.exists() {
902 toml_path = config.src.join(toml_path);
905 // Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path,
906 // but not if `config.toml` hasn't been created.
907 let mut toml = if !using_default_path || toml_path.exists() {
910 TomlConfig::default()
913 if let Some(include) = &toml.profile {
914 let mut include_path = config.src.clone();
915 include_path.push("src");
916 include_path.push("bootstrap");
917 include_path.push("defaults");
918 include_path.push(format!("config.{}.toml", include));
919 let included_toml = get_toml(&include_path);
920 toml.merge(included_toml);
923 config.changelog_seen = toml.changelog_seen;
924 config.config = toml_path;
926 let build = toml.build.unwrap_or_default();
928 set(&mut config.out, flags.build_dir.or_else(|| build.build_dir.map(PathBuf::from)));
929 // NOTE: Bootstrap spawns various commands with different working directories.
930 // To avoid writing to random places on the file system, `config.out` needs to be an absolute path.
931 if !config.out.is_absolute() {
932 // `canonicalize` requires the path to already exist. Use our vendored copy of `absolute` instead.
933 config.out = crate::util::absolute(&config.out);
936 config.initial_rustc = build
939 .unwrap_or_else(|| config.out.join(config.build.triple).join("stage0/bin/rustc"));
940 config.initial_cargo = build
943 .unwrap_or_else(|| config.out.join(config.build.triple).join("stage0/bin/cargo"));
945 // NOTE: it's important this comes *after* we set `initial_rustc` just above.
947 let dir = config.out.join("tmp-dry-run");
948 t!(fs::create_dir_all(&dir));
952 config.hosts = if let Some(arg_host) = flags.host {
954 } else if let Some(file_host) = build.host {
955 file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
959 config.targets = if let Some(arg_target) = flags.target {
961 } else if let Some(file_target) = build.target {
962 file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
964 // If target is *not* configured, then default to the host
969 config.nodejs = build.nodejs.map(PathBuf::from);
970 config.npm = build.npm.map(PathBuf::from);
971 config.gdb = build.gdb.map(PathBuf::from);
972 config.python = build.python.map(PathBuf::from);
973 config.submodules = build.submodules;
974 set(&mut config.low_priority, build.low_priority);
975 set(&mut config.compiler_docs, build.compiler_docs);
976 set(&mut config.docs_minification, build.docs_minification);
977 set(&mut config.docs, build.docs);
978 set(&mut config.locked_deps, build.locked_deps);
979 set(&mut config.vendor, build.vendor);
980 set(&mut config.full_bootstrap, build.full_bootstrap);
981 set(&mut config.extended, build.extended);
982 config.tools = build.tools;
983 set(&mut config.verbose, build.verbose);
984 set(&mut config.sanitizers, build.sanitizers);
985 set(&mut config.profiler, build.profiler);
986 set(&mut config.cargo_native_static, build.cargo_native_static);
987 set(&mut config.configure_args, build.configure_args);
988 set(&mut config.local_rebuild, build.local_rebuild);
989 set(&mut config.print_step_timings, build.print_step_timings);
990 set(&mut config.print_step_rusage, build.print_step_rusage);
991 set(&mut config.patch_binaries_for_nix, build.patch_binaries_for_nix);
992 set(&mut config.optimized_compiler_builtins, build.optimized_compiler_builtins);
994 config.verbose = cmp::max(config.verbose, flags.verbose);
996 if let Some(install) = toml.install {
997 config.prefix = install.prefix.map(PathBuf::from);
998 config.sysconfdir = install.sysconfdir.map(PathBuf::from);
999 config.datadir = install.datadir.map(PathBuf::from);
1000 config.docdir = install.docdir.map(PathBuf::from);
1001 set(&mut config.bindir, install.bindir.map(PathBuf::from));
1002 config.libdir = install.libdir.map(PathBuf::from);
1003 config.mandir = install.mandir.map(PathBuf::from);
1006 // We want the llvm-skip-rebuild flag to take precedence over the
1007 // skip-rebuild config.toml option so we store it separately
1008 // so that we can infer the right value
1009 let mut llvm_skip_rebuild = flags.llvm_skip_rebuild;
1011 // Store off these values as options because if they're not provided
1012 // we'll infer default values for them later
1013 let mut llvm_assertions = None;
1014 let mut llvm_tests = None;
1015 let mut llvm_plugins = None;
1016 let mut debug = None;
1017 let mut debug_assertions = None;
1018 let mut debug_assertions_std = None;
1019 let mut overflow_checks = None;
1020 let mut overflow_checks_std = None;
1021 let mut debug_logging = None;
1022 let mut debuginfo_level = None;
1023 let mut debuginfo_level_rustc = None;
1024 let mut debuginfo_level_std = None;
1025 let mut debuginfo_level_tools = None;
1026 let mut debuginfo_level_tests = None;
1027 let mut optimize = None;
1028 let mut ignore_git = None;
1030 if let Some(llvm) = toml.llvm {
1032 Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
1033 Some(StringOrBool::Bool(true)) => {
1034 config.ccache = Some("ccache".to_string());
1036 Some(StringOrBool::Bool(false)) | None => {}
1038 set(&mut config.ninja_in_file, llvm.ninja);
1039 llvm_assertions = llvm.assertions;
1040 llvm_tests = llvm.tests;
1041 llvm_plugins = llvm.plugins;
1042 llvm_skip_rebuild = llvm_skip_rebuild.or(llvm.skip_rebuild);
1043 set(&mut config.llvm_optimize, llvm.optimize);
1044 set(&mut config.llvm_thin_lto, llvm.thin_lto);
1045 set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
1046 set(&mut config.llvm_version_check, llvm.version_check);
1047 set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp);
1048 if let Some(v) = llvm.link_shared {
1049 config.llvm_link_shared.set(Some(v));
1051 config.llvm_targets = llvm.targets.clone();
1052 config.llvm_experimental_targets = llvm.experimental_targets.clone();
1053 config.llvm_link_jobs = llvm.link_jobs;
1054 config.llvm_version_suffix = llvm.version_suffix.clone();
1055 config.llvm_clang_cl = llvm.clang_cl.clone();
1057 config.llvm_cflags = llvm.cflags.clone();
1058 config.llvm_cxxflags = llvm.cxxflags.clone();
1059 config.llvm_ldflags = llvm.ldflags.clone();
1060 set(&mut config.llvm_use_libcxx, llvm.use_libcxx);
1061 config.llvm_use_linker = llvm.use_linker.clone();
1062 config.llvm_allow_old_toolchain = llvm.allow_old_toolchain.unwrap_or(false);
1063 config.llvm_polly = llvm.polly.unwrap_or(false);
1064 config.llvm_clang = llvm.clang.unwrap_or(false);
1065 config.llvm_build_config = llvm.build_config.clone().unwrap_or(Default::default());
1066 config.llvm_from_ci = match llvm.download_ci_llvm {
1067 Some(StringOrBool::String(s)) => {
1068 assert!(s == "if-available", "unknown option `{}` for download-ci-llvm", s);
1069 crate::native::is_ci_llvm_available(&config, llvm_assertions.unwrap_or(false))
1071 Some(StringOrBool::Bool(b)) => b,
1075 if config.llvm_from_ci {
1076 // None of the LLVM options, except assertions, are supported
1077 // when using downloaded LLVM. We could just ignore these but
1078 // that's potentially confusing, so force them to not be
1079 // explicitly set. The defaults and CI defaults don't
1080 // necessarily match but forcing people to match (somewhat
1081 // arbitrary) CI configuration locally seems bad/hard.
1082 check_ci_llvm!(llvm.optimize);
1083 check_ci_llvm!(llvm.thin_lto);
1084 check_ci_llvm!(llvm.release_debuginfo);
1085 // CI-built LLVM can be either dynamic or static. We won't know until we download it.
1086 check_ci_llvm!(llvm.link_shared);
1087 check_ci_llvm!(llvm.static_libstdcpp);
1088 check_ci_llvm!(llvm.targets);
1089 check_ci_llvm!(llvm.experimental_targets);
1090 check_ci_llvm!(llvm.link_jobs);
1091 check_ci_llvm!(llvm.clang_cl);
1092 check_ci_llvm!(llvm.version_suffix);
1093 check_ci_llvm!(llvm.cflags);
1094 check_ci_llvm!(llvm.cxxflags);
1095 check_ci_llvm!(llvm.ldflags);
1096 check_ci_llvm!(llvm.use_libcxx);
1097 check_ci_llvm!(llvm.use_linker);
1098 check_ci_llvm!(llvm.allow_old_toolchain);
1099 check_ci_llvm!(llvm.polly);
1100 check_ci_llvm!(llvm.clang);
1101 check_ci_llvm!(llvm.build_config);
1102 check_ci_llvm!(llvm.plugins);
1105 // NOTE: can never be hit when downloading from CI, since we call `check_ci_llvm!(thin_lto)` above.
1106 if config.llvm_thin_lto && llvm.link_shared.is_none() {
1107 // If we're building with ThinLTO on, by default we want to link
1108 // to LLVM shared, to avoid re-doing ThinLTO (which happens in
1109 // the link step) with each stage.
1110 config.llvm_link_shared.set(Some(true));
1114 if let Some(rust) = toml.rust {
1116 debug_assertions = rust.debug_assertions;
1117 debug_assertions_std = rust.debug_assertions_std;
1118 overflow_checks = rust.overflow_checks;
1119 overflow_checks_std = rust.overflow_checks_std;
1120 debug_logging = rust.debug_logging;
1121 debuginfo_level = rust.debuginfo_level;
1122 debuginfo_level_rustc = rust.debuginfo_level_rustc;
1123 debuginfo_level_std = rust.debuginfo_level_std;
1124 debuginfo_level_tools = rust.debuginfo_level_tools;
1125 debuginfo_level_tests = rust.debuginfo_level_tests;
1126 config.rust_split_debuginfo = rust
1129 .map(SplitDebuginfo::from_str)
1130 .map(|v| v.expect("invalid value for rust.split_debuginfo"))
1131 .unwrap_or(SplitDebuginfo::default_for_platform(&config.build.triple));
1132 optimize = rust.optimize;
1133 ignore_git = rust.ignore_git;
1134 config.rust_new_symbol_mangling = rust.new_symbol_mangling;
1135 set(&mut config.rust_optimize_tests, rust.optimize_tests);
1136 set(&mut config.codegen_tests, rust.codegen_tests);
1137 set(&mut config.rust_rpath, rust.rpath);
1138 set(&mut config.jemalloc, rust.jemalloc);
1139 set(&mut config.test_compare_mode, rust.test_compare_mode);
1140 set(&mut config.backtrace, rust.backtrace);
1141 set(&mut config.channel, rust.channel);
1142 config.description = rust.description;
1143 set(&mut config.rust_dist_src, rust.dist_src);
1144 set(&mut config.verbose_tests, rust.verbose_tests);
1145 // in the case "false" is set explicitly, do not overwrite the command line args
1146 if let Some(true) = rust.incremental {
1147 config.incremental = true;
1149 set(&mut config.use_lld, rust.use_lld);
1150 set(&mut config.lld_enabled, rust.lld);
1151 set(&mut config.llvm_tools_enabled, rust.llvm_tools);
1152 config.rustc_parallel = rust.parallel_compiler.unwrap_or(false);
1153 config.rustc_default_linker = rust.default_linker;
1154 config.musl_root = rust.musl_root.map(PathBuf::from);
1155 config.save_toolstates = rust.save_toolstates.map(PathBuf::from);
1156 set(&mut config.deny_warnings, flags.deny_warnings.or(rust.deny_warnings));
1157 set(&mut config.backtrace_on_ice, rust.backtrace_on_ice);
1158 set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir);
1159 config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit;
1160 set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo);
1161 set(&mut config.control_flow_guard, rust.control_flow_guard);
1162 config.llvm_libunwind_default = rust
1164 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
1166 if let Some(ref backends) = rust.codegen_backends {
1167 config.rust_codegen_backends =
1168 backends.iter().map(|s| INTERNER.intern_str(s)).collect();
1171 config.rust_codegen_units = rust.codegen_units.map(threads_from_config);
1172 config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config);
1173 config.rust_profile_use = flags.rust_profile_use.or(rust.profile_use);
1174 config.rust_profile_generate = flags.rust_profile_generate.or(rust.profile_generate);
1175 config.download_rustc_commit = download_ci_rustc_commit(&config, rust.download_rustc);
1177 config.rust_profile_use = flags.rust_profile_use;
1178 config.rust_profile_generate = flags.rust_profile_generate;
1181 if let Some(t) = toml.target {
1182 for (triple, cfg) in t {
1183 let mut target = Target::from_triple(&triple);
1185 if let Some(ref s) = cfg.llvm_config {
1186 target.llvm_config = Some(config.src.join(s));
1188 target.llvm_has_rust_patches = cfg.llvm_has_rust_patches;
1189 if let Some(ref s) = cfg.llvm_filecheck {
1190 target.llvm_filecheck = Some(config.src.join(s));
1192 target.llvm_libunwind = cfg
1195 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
1196 if let Some(ref s) = cfg.android_ndk {
1197 target.ndk = Some(config.src.join(s));
1199 if let Some(s) = cfg.no_std {
1202 target.cc = cfg.cc.map(PathBuf::from);
1203 target.cxx = cfg.cxx.map(PathBuf::from);
1204 target.ar = cfg.ar.map(PathBuf::from);
1205 target.ranlib = cfg.ranlib.map(PathBuf::from);
1206 target.linker = cfg.linker.map(PathBuf::from);
1207 target.crt_static = cfg.crt_static;
1208 target.musl_root = cfg.musl_root.map(PathBuf::from);
1209 target.musl_libdir = cfg.musl_libdir.map(PathBuf::from);
1210 target.wasi_root = cfg.wasi_root.map(PathBuf::from);
1211 target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from);
1212 target.sanitizers = cfg.sanitizers;
1213 target.profiler = cfg.profiler;
1215 config.target_config.insert(TargetSelection::from_user(&triple), target);
1219 if config.llvm_from_ci {
1220 let triple = &config.build.triple;
1221 let ci_llvm_bin = config.ci_llvm_root().join("bin");
1222 let mut build_target = config
1224 .entry(config.build)
1225 .or_insert_with(|| Target::from_triple(&triple));
1227 check_ci_llvm!(build_target.llvm_config);
1228 check_ci_llvm!(build_target.llvm_filecheck);
1229 build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", config.build)));
1230 build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", config.build)));
1233 if let Some(t) = toml.dist {
1234 config.dist_sign_folder = t.sign_folder.map(PathBuf::from);
1235 config.dist_upload_addr = t.upload_addr;
1236 config.dist_compression_formats = t.compression_formats;
1237 set(&mut config.rust_dist_src, t.src_tarball);
1238 set(&mut config.missing_tools, t.missing_tools);
1241 if let Some(r) = build.rustfmt {
1242 *config.initial_rustfmt.borrow_mut() = if r.exists() {
1243 RustfmtState::SystemToolchain(r)
1245 RustfmtState::Unavailable
1248 // If using a system toolchain for bootstrapping, see if that has rustfmt available.
1249 let host = config.build;
1250 let rustfmt_path = config.initial_rustc.with_file_name(exe("rustfmt", host));
1251 let bin_root = config.out.join(host.triple).join("stage0");
1252 if !rustfmt_path.starts_with(&bin_root) {
1253 // Using a system-provided toolchain; we shouldn't download rustfmt.
1254 *config.initial_rustfmt.borrow_mut() = RustfmtState::SystemToolchain(rustfmt_path);
1258 // Now that we've reached the end of our configuration, infer the
1259 // default values for all options that we haven't otherwise stored yet.
1261 config.llvm_skip_rebuild = llvm_skip_rebuild.unwrap_or(false);
1262 config.llvm_assertions = llvm_assertions.unwrap_or(false);
1263 config.llvm_tests = llvm_tests.unwrap_or(false);
1264 config.llvm_plugins = llvm_plugins.unwrap_or(false);
1265 config.rust_optimize = optimize.unwrap_or(true);
1267 let default = debug == Some(true);
1268 config.rust_debug_assertions = debug_assertions.unwrap_or(default);
1269 config.rust_debug_assertions_std =
1270 debug_assertions_std.unwrap_or(config.rust_debug_assertions);
1271 config.rust_overflow_checks = overflow_checks.unwrap_or(default);
1272 config.rust_overflow_checks_std =
1273 overflow_checks_std.unwrap_or(config.rust_overflow_checks);
1275 config.rust_debug_logging = debug_logging.unwrap_or(config.rust_debug_assertions);
1277 let with_defaults = |debuginfo_level_specific: Option<u32>| {
1278 debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
1284 config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
1285 config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
1286 config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
1287 config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(0);
1289 let default = config.channel == "dev";
1290 config.ignore_git = ignore_git.unwrap_or(default);
1292 let download_rustc = config.download_rustc_commit.is_some();
1293 // See https://github.com/rust-lang/compiler-team/issues/326
1294 config.stage = match config.cmd {
1295 Subcommand::Check { .. } => flags.stage.or(build.check_stage).unwrap_or(0),
1296 // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden.
1297 Subcommand::Doc { .. } => {
1298 flags.stage.or(build.doc_stage).unwrap_or(if download_rustc { 2 } else { 0 })
1300 Subcommand::Build { .. } => {
1301 flags.stage.or(build.build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1303 Subcommand::Test { .. } => {
1304 flags.stage.or(build.test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1306 Subcommand::Bench { .. } => flags.stage.or(build.bench_stage).unwrap_or(2),
1307 Subcommand::Dist { .. } => flags.stage.or(build.dist_stage).unwrap_or(2),
1308 Subcommand::Install { .. } => flags.stage.or(build.install_stage).unwrap_or(2),
1309 // These are all bootstrap tools, which don't depend on the compiler.
1310 // The stage we pass shouldn't matter, but use 0 just in case.
1311 Subcommand::Clean { .. }
1312 | Subcommand::Clippy { .. }
1313 | Subcommand::Fix { .. }
1314 | Subcommand::Run { .. }
1315 | Subcommand::Setup { .. }
1316 | Subcommand::Format { .. } => flags.stage.unwrap_or(0),
1319 // CI should always run stage 2 builds, unless it specifically states otherwise
1321 if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None {
1323 Subcommand::Test { .. }
1324 | Subcommand::Doc { .. }
1325 | Subcommand::Build { .. }
1326 | Subcommand::Bench { .. }
1327 | Subcommand::Dist { .. }
1328 | Subcommand::Install { .. } => {
1331 "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
1335 Subcommand::Clean { .. }
1336 | Subcommand::Check { .. }
1337 | Subcommand::Clippy { .. }
1338 | Subcommand::Fix { .. }
1339 | Subcommand::Run { .. }
1340 | Subcommand::Setup { .. }
1341 | Subcommand::Format { .. } => {}
1348 /// A git invocation which runs inside the source directory.
1350 /// Use this rather than `Command::new("git")` in order to support out-of-tree builds.
1351 pub(crate) fn git(&self) -> Command {
1352 let mut git = Command::new("git");
1353 git.current_dir(&self.src);
1357 pub(crate) fn artifact_channel(&self, builder: &Builder<'_>, commit: &str) -> String {
1358 if builder.rust_info.is_managed_git_subrepository() {
1359 let mut channel = self.git();
1360 channel.arg("show").arg(format!("{}:src/ci/channel", commit));
1361 let channel = output(&mut channel);
1362 channel.trim().to_owned()
1363 } else if let Ok(channel) = fs::read_to_string(builder.src.join("src/ci/channel")) {
1364 channel.trim().to_owned()
1366 let src = builder.src.display();
1367 eprintln!("error: failed to determine artifact channel");
1369 "help: either use git or ensure that {src}/src/ci/channel contains the name of the channel to use"
1375 /// Try to find the relative path of `bindir`, otherwise return it in full.
1376 pub fn bindir_relative(&self) -> &Path {
1377 let bindir = &self.bindir;
1378 if bindir.is_absolute() {
1379 // Try to make it relative to the prefix.
1380 if let Some(prefix) = &self.prefix {
1381 if let Ok(stripped) = bindir.strip_prefix(prefix) {
1389 /// Try to find the relative path of `libdir`.
1390 pub fn libdir_relative(&self) -> Option<&Path> {
1391 let libdir = self.libdir.as_ref()?;
1392 if libdir.is_relative() {
1395 // Try to make it relative to the prefix.
1396 libdir.strip_prefix(self.prefix.as_ref()?).ok()
1400 /// The absolute path to the downloaded LLVM artifacts.
1401 pub(crate) fn ci_llvm_root(&self) -> PathBuf {
1402 assert!(self.llvm_from_ci);
1403 self.out.join(&*self.build.triple).join("ci-llvm")
1406 /// Determine whether llvm should be linked dynamically.
1408 /// If `false`, llvm should be linked statically.
1409 /// This is computed on demand since LLVM might have to first be downloaded from CI.
1410 pub(crate) fn llvm_link_shared(builder: &Builder<'_>) -> bool {
1411 let mut opt = builder.config.llvm_link_shared.get();
1412 if opt.is_none() && builder.config.dry_run {
1413 // just assume static for now - dynamic linking isn't supported on all platforms
1417 let llvm_link_shared = *opt.get_or_insert_with(|| {
1418 if builder.config.llvm_from_ci {
1419 crate::native::maybe_download_ci_llvm(builder);
1420 let ci_llvm = builder.config.ci_llvm_root();
1422 std::fs::read_to_string(ci_llvm.join("link-type.txt")),
1423 format!("CI llvm missing: {}", ci_llvm.display())
1425 link_type == "dynamic"
1427 // unclear how thought-through this default is, but it maintains compatibility with
1428 // previous behavior
1432 builder.config.llvm_link_shared.set(opt);
1436 /// Return whether we will use a downloaded, pre-compiled version of rustc, or just build from source.
1437 pub(crate) fn download_rustc(builder: &Builder<'_>) -> bool {
1438 static DOWNLOAD_RUSTC: OnceCell<bool> = OnceCell::new();
1439 if builder.config.dry_run && DOWNLOAD_RUSTC.get().is_none() {
1440 // avoid trying to actually download the commit
1444 *DOWNLOAD_RUSTC.get_or_init(|| match &builder.config.download_rustc_commit {
1447 download_ci_rustc(builder, commit);
1453 pub(crate) fn initial_rustfmt(builder: &Builder<'_>) -> Option<PathBuf> {
1454 match &mut *builder.config.initial_rustfmt.borrow_mut() {
1455 RustfmtState::SystemToolchain(p) | RustfmtState::Downloaded(p) => Some(p.clone()),
1456 RustfmtState::Unavailable => None,
1457 r @ RustfmtState::LazyEvaluated => {
1458 if builder.config.dry_run {
1459 return Some(PathBuf::new());
1461 let path = maybe_download_rustfmt(builder);
1462 *r = if let Some(p) = &path {
1463 RustfmtState::Downloaded(p.clone())
1465 RustfmtState::Unavailable
1472 pub fn verbose(&self) -> bool {
1476 pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1477 self.target_config.get(&target).map(|t| t.sanitizers).flatten().unwrap_or(self.sanitizers)
1480 pub fn any_sanitizers_enabled(&self) -> bool {
1481 self.target_config.values().any(|t| t.sanitizers == Some(true)) || self.sanitizers
1484 pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1485 self.target_config.get(&target).map(|t| t.profiler).flatten().unwrap_or(self.profiler)
1488 pub fn any_profiler_enabled(&self) -> bool {
1489 self.target_config.values().any(|t| t.profiler == Some(true)) || self.profiler
1492 pub fn llvm_enabled(&self) -> bool {
1493 self.rust_codegen_backends.contains(&INTERNER.intern_str("llvm"))
1496 pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1499 .and_then(|t| t.llvm_libunwind)
1500 .or(self.llvm_libunwind_default)
1501 .unwrap_or(if target.contains("fuchsia") {
1502 LlvmLibunwind::InTree
1508 pub fn submodules(&self, rust_info: &GitInfo) -> bool {
1509 self.submodules.unwrap_or(rust_info.is_managed_git_subrepository())
1513 fn set<T>(field: &mut T, val: Option<T>) {
1514 if let Some(v) = val {
1519 fn threads_from_config(v: u32) -> u32 {
1521 0 => std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32,
1526 /// Returns the commit to download, or `None` if we shouldn't download CI artifacts.
1527 fn download_ci_rustc_commit(
1529 download_rustc: Option<StringOrBool>,
1530 ) -> Option<String> {
1531 // If `download-rustc` is not set, default to rebuilding.
1532 let if_unchanged = match download_rustc {
1533 None | Some(StringOrBool::Bool(false)) => return None,
1534 Some(StringOrBool::Bool(true)) => false,
1535 Some(StringOrBool::String(s)) if s == "if-unchanged" => true,
1536 Some(StringOrBool::String(other)) => {
1537 panic!("unrecognized option for download-rustc: {}", other)
1541 // Handle running from a directory other than the top level
1542 let top_level = output(config.git().args(&["rev-parse", "--show-toplevel"]));
1543 let top_level = top_level.trim_end();
1544 let compiler = format!("{top_level}/compiler/");
1545 let library = format!("{top_level}/library/");
1547 // Look for a version to compare to based on the current commit.
1548 // Only commits merged by bors will have CI artifacts.
1549 let merge_base = output(
1553 .arg(format!("--author={}", config.stage0_metadata.config.git_merge_commit_email))
1554 .args(&["-n1", "--first-parent", "HEAD"]),
1556 let commit = merge_base.trim_end();
1557 if commit.is_empty() {
1558 println!("error: could not find commit hash for downloading rustc");
1559 println!("help: maybe your repository history is too shallow?");
1560 println!("help: consider disabling `download-rustc`");
1561 println!("help: or fetch enough history to include one upstream commit");
1562 crate::detail_exit(1);
1565 // Warn if there were changes to the compiler or standard library since the ancestor commit.
1566 let has_changes = !t!(config
1568 .args(&["diff-index", "--quiet", &commit, "--", &compiler, &library])
1573 if config.verbose > 0 {
1575 "warning: saw changes to compiler/ or library/ since {commit}; \
1576 ignoring `download-rustc`"
1582 "warning: `download-rustc` is enabled, but there are changes to \
1583 compiler/ or library/"
1587 Some(commit.to_string())
1590 fn maybe_download_rustfmt(builder: &Builder<'_>) -> Option<PathBuf> {
1591 let RustfmtMetadata { date, version } = builder.config.stage0_metadata.rustfmt.as_ref()?;
1592 let channel = format!("{version}-{date}");
1594 let host = builder.config.build;
1595 let rustfmt_path = builder.config.initial_rustc.with_file_name(exe("rustfmt", host));
1596 let bin_root = builder.config.out.join(host.triple).join("stage0");
1597 let rustfmt_stamp = bin_root.join(".rustfmt-stamp");
1598 if rustfmt_path.exists() && !program_out_of_date(&rustfmt_stamp, &channel) {
1599 return Some(rustfmt_path);
1602 let filename = format!("rustfmt-{version}-{build}.tar.xz", build = host.triple);
1603 download_component(builder, DownloadSource::Dist, filename, "rustfmt-preview", &date, "stage0");
1605 builder.fix_bin_or_dylib(&bin_root.join("bin").join("rustfmt"));
1606 builder.fix_bin_or_dylib(&bin_root.join("bin").join("cargo-fmt"));
1608 builder.create(&rustfmt_stamp, &channel);
1612 fn download_ci_rustc(builder: &Builder<'_>, commit: &str) {
1613 builder.verbose(&format!("using downloaded stage2 artifacts from CI (commit {commit})"));
1614 let channel = builder.config.artifact_channel(builder, commit);
1615 let host = builder.config.build.triple;
1616 let bin_root = builder.out.join(host).join("ci-rustc");
1617 let rustc_stamp = bin_root.join(".rustc-stamp");
1619 if !bin_root.join("bin").join("rustc").exists() || program_out_of_date(&rustc_stamp, commit) {
1620 if bin_root.exists() {
1621 t!(fs::remove_dir_all(&bin_root));
1623 let filename = format!("rust-std-{channel}-{host}.tar.xz");
1624 let pattern = format!("rust-std-{host}");
1625 download_ci_component(builder, filename, &pattern, commit);
1626 let filename = format!("rustc-{channel}-{host}.tar.xz");
1627 download_ci_component(builder, filename, "rustc", commit);
1628 // download-rustc doesn't need its own cargo, it can just use beta's.
1629 let filename = format!("rustc-dev-{channel}-{host}.tar.xz");
1630 download_ci_component(builder, filename, "rustc-dev", commit);
1632 builder.fix_bin_or_dylib(&bin_root.join("bin").join("rustc"));
1633 builder.fix_bin_or_dylib(&bin_root.join("bin").join("rustdoc"));
1634 let lib_dir = bin_root.join("lib");
1635 for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
1637 if lib.path().extension() == Some(OsStr::new("so")) {
1638 builder.fix_bin_or_dylib(&lib.path());
1641 t!(fs::write(rustc_stamp, commit));
1645 pub(crate) enum DownloadSource {
1650 /// Download a single component of a CI-built toolchain (not necessarily a published nightly).
1651 // NOTE: intentionally takes an owned string to avoid downloading multiple times by accident
1652 fn download_ci_component(builder: &Builder<'_>, filename: String, prefix: &str, commit: &str) {
1653 download_component(builder, DownloadSource::CI, filename, prefix, commit, "ci-rustc")
1656 fn download_component(
1657 builder: &Builder<'_>,
1658 mode: DownloadSource,
1664 let cache_dst = builder.out.join("cache");
1665 let cache_dir = cache_dst.join(key);
1666 if !cache_dir.exists() {
1667 t!(fs::create_dir_all(&cache_dir));
1670 let bin_root = builder.out.join(builder.config.build.triple).join(destination);
1671 let tarball = cache_dir.join(&filename);
1672 let (base_url, url, should_verify) = match mode {
1673 DownloadSource::CI => (
1674 builder.config.stage0_metadata.config.artifacts_server.clone(),
1675 format!("{key}/{filename}"),
1678 DownloadSource::Dist => {
1679 let dist_server = env::var("RUSTUP_DIST_SERVER")
1680 .unwrap_or(builder.config.stage0_metadata.config.dist_server.to_string());
1681 // NOTE: make `dist` part of the URL because that's how it's stored in src/stage0.json
1682 (dist_server, format!("dist/{key}/{filename}"), true)
1686 // For the beta compiler, put special effort into ensuring the checksums are valid.
1687 // FIXME: maybe we should do this for download-rustc as well? but it would be a pain to update
1688 // this on each and every nightly ...
1689 let checksum = if should_verify {
1690 let error = format!(
1691 "src/stage0.json doesn't contain a checksum for {url}. \
1692 Pre-built artifacts might not be available for this \
1693 target at this time, see https://doc.rust-lang.org/nightly\
1694 /rustc/platform-support.html for more information."
1696 let sha256 = builder.config.stage0_metadata.checksums_sha256.get(&url).expect(&error);
1697 if tarball.exists() {
1698 if builder.verify(&tarball, sha256) {
1699 builder.unpack(&tarball, &bin_root, prefix);
1702 builder.verbose(&format!(
1703 "ignoring cached file {} due to failed verification",
1706 builder.remove(&tarball);
1710 } else if tarball.exists() {
1711 builder.unpack(&tarball, &bin_root, prefix);
1717 builder.download_component(&format!("{base_url}/{url}"), &tarball, "");
1718 if let Some(sha256) = checksum {
1719 if !builder.verify(&tarball, sha256) {
1720 panic!("failed to verify {}", tarball.display());
1724 builder.unpack(&tarball, &bin_root, prefix);