1 //! Serialized configuration of a build.
3 //! This module implements parsing `config.toml` configuration files to tweak
4 //! how the build runs.
9 use std::cell::{Cell, RefCell};
11 use std::collections::{HashMap, HashSet};
15 use std::path::{Path, PathBuf};
16 use std::process::Command;
17 use std::str::FromStr;
19 use crate::builder::TaskPath;
20 use crate::cache::{Interned, INTERNER};
21 use crate::channel::{self, GitInfo};
22 pub use crate::flags::Subcommand;
23 use crate::flags::{Color, Flags};
24 use crate::util::{exe, output, t};
25 use once_cell::sync::OnceCell;
26 use serde::{Deserialize, Deserializer};
28 macro_rules! check_ci_llvm {
32 "setting {} is incompatible with download-ci-llvm.",
38 #[derive(Clone, Default)]
40 /// This isn't a dry run.
43 /// This is a dry run enabled by bootstrap itself, so it can verify that no work is done.
45 /// This is a dry run enabled by the `--dry-run` flag.
49 /// Global configuration for the entire build and/or bootstrap.
51 /// This structure is derived from a combination of both `config.toml` and
52 /// `config.mk`. As of the time of this writing it's unlikely that `config.toml`
53 /// is used all that much, so this is primarily filled out by `config.mk` which
54 /// is generated from `./configure`.
56 /// Note that this structure is not decoded directly into, but rather it is
57 /// filled out from the decoded forms of the structs below. For documentation
58 /// each field, see the corresponding fields in
59 /// `config.toml.example`.
61 #[cfg_attr(test, derive(Clone))]
63 pub changelog_seen: Option<usize>,
64 pub ccache: Option<String>,
65 /// Call Build::ninja() instead of this.
66 pub ninja_in_file: bool,
68 pub submodules: Option<bool>,
69 pub compiler_docs: bool,
70 pub docs_minification: bool,
72 pub locked_deps: bool,
74 pub target_config: HashMap<TargetSelection, Target>,
75 pub full_bootstrap: bool,
77 pub tools: Option<HashSet<String>>,
81 pub exclude: Vec<TaskPath>,
82 pub include_default_paths: bool,
83 pub rustc_error_format: Option<String>,
84 pub json_output: bool,
85 pub test_compare_mode: bool,
87 pub patch_binaries_for_nix: bool,
88 pub stage0_metadata: Stage0Metadata,
90 pub on_fail: Option<String>,
92 pub keep_stage: Vec<u32>,
93 pub keep_stage_std: Vec<u32>,
95 /// defaults to `config.toml`
96 pub config: Option<PathBuf>,
97 pub jobs: Option<u32>,
99 pub incremental: bool,
101 /// `None` if we shouldn't download CI compiler artifacts, or the commit to download if we should.
103 download_rustc_commit: Option<String>,
105 pub download_rustc_commit: Option<String>,
107 pub deny_warnings: bool,
108 pub backtrace_on_ice: bool,
110 // llvm codegen options
111 pub llvm_skip_rebuild: bool,
112 pub llvm_assertions: bool,
113 pub llvm_tests: bool,
114 pub llvm_plugins: bool,
115 pub llvm_optimize: bool,
116 pub llvm_thin_lto: bool,
117 pub llvm_release_debuginfo: bool,
118 pub llvm_version_check: bool,
119 pub llvm_static_stdcpp: bool,
120 /// `None` if `llvm_from_ci` is true and we haven't yet downloaded llvm.
122 llvm_link_shared: Cell<Option<bool>>,
124 pub llvm_link_shared: Cell<Option<bool>>,
125 pub llvm_clang_cl: Option<String>,
126 pub llvm_targets: Option<String>,
127 pub llvm_experimental_targets: Option<String>,
128 pub llvm_link_jobs: Option<u32>,
129 pub llvm_version_suffix: Option<String>,
130 pub llvm_use_linker: Option<String>,
131 pub llvm_allow_old_toolchain: bool,
132 pub llvm_polly: bool,
133 pub llvm_clang: bool,
134 pub llvm_from_ci: bool,
135 pub llvm_build_config: HashMap<String, String>,
138 pub lld_enabled: bool,
139 pub llvm_tools_enabled: bool,
141 pub llvm_cflags: Option<String>,
142 pub llvm_cxxflags: Option<String>,
143 pub llvm_ldflags: Option<String>,
144 pub llvm_use_libcxx: bool,
146 // rust codegen options
147 pub rust_optimize: bool,
148 pub rust_codegen_units: Option<u32>,
149 pub rust_codegen_units_std: Option<u32>,
150 pub rust_debug_assertions: bool,
151 pub rust_debug_assertions_std: bool,
152 pub rust_overflow_checks: bool,
153 pub rust_overflow_checks_std: bool,
154 pub rust_debug_logging: bool,
155 pub rust_debuginfo_level_rustc: u32,
156 pub rust_debuginfo_level_std: u32,
157 pub rust_debuginfo_level_tools: u32,
158 pub rust_debuginfo_level_tests: u32,
159 pub rust_split_debuginfo: SplitDebuginfo,
160 pub rust_rpath: bool,
161 pub rustc_parallel: bool,
162 pub rustc_default_linker: Option<String>,
163 pub rust_optimize_tests: bool,
164 pub rust_dist_src: bool,
165 pub rust_codegen_backends: Vec<Interned<String>>,
166 pub rust_verify_llvm_ir: bool,
167 pub rust_thin_lto_import_instr_limit: Option<u32>,
168 pub rust_remap_debuginfo: bool,
169 pub rust_new_symbol_mangling: Option<bool>,
170 pub rust_profile_use: Option<String>,
171 pub rust_profile_generate: Option<String>,
172 pub rust_lto: RustcLto,
173 pub llvm_profile_use: Option<String>,
174 pub llvm_profile_generate: bool,
175 pub llvm_libunwind_default: Option<LlvmLibunwind>,
176 pub llvm_bolt_profile_generate: bool,
177 pub llvm_bolt_profile_use: Option<String>,
179 pub build: TargetSelection,
180 pub hosts: Vec<TargetSelection>,
181 pub targets: Vec<TargetSelection>,
182 pub local_rebuild: bool,
184 pub control_flow_guard: bool,
187 pub dist_sign_folder: Option<PathBuf>,
188 pub dist_upload_addr: Option<String>,
189 pub dist_compression_formats: Option<Vec<String>>,
192 pub backtrace: bool, // support for RUST_BACKTRACE
195 pub low_priority: bool,
197 pub description: Option<String>,
198 pub verbose_tests: bool,
199 pub save_toolstates: Option<PathBuf>,
200 pub print_step_timings: bool,
201 pub print_step_rusage: bool,
202 pub missing_tools: bool,
204 // Fallback musl-root for all targets
205 pub musl_root: Option<PathBuf>,
206 pub prefix: Option<PathBuf>,
207 pub sysconfdir: Option<PathBuf>,
208 pub datadir: Option<PathBuf>,
209 pub docdir: Option<PathBuf>,
211 pub libdir: Option<PathBuf>,
212 pub mandir: Option<PathBuf>,
213 pub codegen_tests: bool,
214 pub nodejs: Option<PathBuf>,
215 pub npm: Option<PathBuf>,
216 pub gdb: Option<PathBuf>,
217 pub python: Option<PathBuf>,
218 pub cargo_native_static: bool,
219 pub configure_args: Vec<String>,
221 // These are either the stage0 downloaded binaries or the locally installed ones.
222 pub initial_cargo: PathBuf,
223 pub initial_rustc: PathBuf,
225 initial_rustfmt: RefCell<RustfmtState>,
227 pub initial_rustfmt: RefCell<RustfmtState>,
229 pub rust_info: channel::GitInfo,
232 #[derive(Default, Deserialize)]
233 #[cfg_attr(test, derive(Clone))]
234 pub struct Stage0Metadata {
235 pub config: Stage0Config,
236 pub checksums_sha256: HashMap<String, String>,
237 pub rustfmt: Option<RustfmtMetadata>,
239 #[derive(Default, Deserialize)]
240 #[cfg_attr(test, derive(Clone))]
241 pub struct Stage0Config {
242 pub dist_server: String,
243 pub artifacts_server: String,
244 pub artifacts_with_llvm_assertions_server: String,
245 pub git_merge_commit_email: String,
246 pub nightly_branch: String,
248 #[derive(Default, Deserialize)]
249 #[cfg_attr(test, derive(Clone))]
250 pub struct RustfmtMetadata {
255 #[derive(Clone, Debug)]
256 pub enum RustfmtState {
257 SystemToolchain(PathBuf),
263 impl Default for RustfmtState {
264 fn default() -> Self {
265 RustfmtState::LazyEvaluated
269 #[derive(Debug, Clone, Copy, PartialEq)]
270 pub enum LlvmLibunwind {
276 impl Default for LlvmLibunwind {
277 fn default() -> Self {
282 impl FromStr for LlvmLibunwind {
285 fn from_str(value: &str) -> Result<Self, Self::Err> {
287 "no" => Ok(Self::No),
288 "in-tree" => Ok(Self::InTree),
289 "system" => Ok(Self::System),
290 invalid => Err(format!("Invalid value '{}' for rust.llvm-libunwind config.", invalid)),
295 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
296 pub enum SplitDebuginfo {
302 impl Default for SplitDebuginfo {
303 fn default() -> Self {
308 impl std::str::FromStr for SplitDebuginfo {
311 fn from_str(s: &str) -> Result<Self, Self::Err> {
313 "packed" => Ok(SplitDebuginfo::Packed),
314 "unpacked" => Ok(SplitDebuginfo::Unpacked),
315 "off" => Ok(SplitDebuginfo::Off),
321 impl SplitDebuginfo {
322 /// Returns the default `-Csplit-debuginfo` value for the current target. See the comment for
323 /// `rust.split-debuginfo` in `config.toml.example`.
324 fn default_for_platform(target: &str) -> Self {
325 if target.contains("apple") {
326 SplitDebuginfo::Unpacked
327 } else if target.contains("windows") {
328 SplitDebuginfo::Packed
335 /// LTO mode used for compiling rustc itself.
336 #[derive(Default, Clone)]
344 impl std::str::FromStr for RustcLto {
347 fn from_str(s: &str) -> Result<Self, Self::Err> {
349 "thin-local" => Ok(RustcLto::ThinLocal),
350 "thin" => Ok(RustcLto::Thin),
351 "fat" => Ok(RustcLto::Fat),
352 _ => Err(format!("Invalid value for rustc LTO: {}", s)),
357 #[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
358 pub struct TargetSelection {
359 pub triple: Interned<String>,
360 file: Option<Interned<String>>,
363 impl TargetSelection {
364 pub fn from_user(selection: &str) -> Self {
365 let path = Path::new(selection);
367 let (triple, file) = if path.exists() {
370 .expect("Target specification file has no file stem")
372 .expect("Target specification file stem is not UTF-8");
374 (triple, Some(selection))
379 let triple = INTERNER.intern_str(triple);
380 let file = file.map(|f| INTERNER.intern_str(f));
382 Self { triple, file }
385 pub fn rustc_target_arg(&self) -> &str {
386 self.file.as_ref().unwrap_or(&self.triple)
389 pub fn contains(&self, needle: &str) -> bool {
390 self.triple.contains(needle)
393 pub fn starts_with(&self, needle: &str) -> bool {
394 self.triple.starts_with(needle)
397 pub fn ends_with(&self, needle: &str) -> bool {
398 self.triple.ends_with(needle)
402 impl fmt::Display for TargetSelection {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 write!(f, "{}", self.triple)?;
405 if let Some(file) = self.file {
406 write!(f, "({})", file)?;
412 impl fmt::Debug for TargetSelection {
413 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414 write!(f, "{}", self)
418 impl PartialEq<&str> for TargetSelection {
419 fn eq(&self, other: &&str) -> bool {
420 self.triple == *other
424 /// Per-target configuration stored in the global configuration structure.
426 #[cfg_attr(test, derive(Clone))]
428 /// Some(path to llvm-config) if using an external LLVM.
429 pub llvm_config: Option<PathBuf>,
430 pub llvm_has_rust_patches: Option<bool>,
431 /// Some(path to FileCheck) if one was specified.
432 pub llvm_filecheck: Option<PathBuf>,
433 pub llvm_libunwind: Option<LlvmLibunwind>,
434 pub cc: Option<PathBuf>,
435 pub cxx: Option<PathBuf>,
436 pub ar: Option<PathBuf>,
437 pub ranlib: Option<PathBuf>,
438 pub default_linker: Option<PathBuf>,
439 pub linker: Option<PathBuf>,
440 pub ndk: Option<PathBuf>,
441 pub sanitizers: Option<bool>,
442 pub profiler: Option<bool>,
443 pub crt_static: Option<bool>,
444 pub musl_root: Option<PathBuf>,
445 pub musl_libdir: Option<PathBuf>,
446 pub wasi_root: Option<PathBuf>,
447 pub qemu_rootfs: Option<PathBuf>,
452 pub fn from_triple(triple: &str) -> Self {
453 let mut target: Self = Default::default();
454 if triple.contains("-none")
455 || triple.contains("nvptx")
456 || triple.contains("switch")
457 || triple.contains("-uefi")
459 target.no_std = true;
464 /// Structure of the `config.toml` file that configuration is read from.
466 /// This structure uses `Decodable` to automatically decode a TOML configuration
467 /// file into this format, and then this is traversed and written into the above
468 /// `Config` structure.
469 #[derive(Deserialize, Default)]
470 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
472 changelog_seen: Option<usize>,
473 build: Option<Build>,
474 install: Option<Install>,
477 target: Option<HashMap<String, TomlTarget>>,
479 profile: Option<String>,
483 fn merge(&mut self, other: Self);
486 impl Merge for TomlConfig {
489 TomlConfig { build, install, llvm, rust, dist, target, profile: _, changelog_seen: _ }: Self,
491 fn do_merge<T: Merge>(x: &mut Option<T>, y: Option<T>) {
492 if let Some(new) = y {
493 if let Some(original) = x {
500 do_merge(&mut self.build, build);
501 do_merge(&mut self.install, install);
502 do_merge(&mut self.llvm, llvm);
503 do_merge(&mut self.rust, rust);
504 do_merge(&mut self.dist, dist);
505 assert!(target.is_none(), "merging target-specific config is not currently supported");
509 // We are using a decl macro instead of a derive proc macro here to reduce the compile time of
511 macro_rules! define_config {
512 ($(#[$attr:meta])* struct $name:ident {
513 $($field:ident: Option<$field_ty:ty> = $field_key:literal,)*
517 $($field: Option<$field_ty>,)*
520 impl Merge for $name {
521 fn merge(&mut self, other: Self) {
523 if !self.$field.is_some() {
524 self.$field = other.$field;
530 // The following is a trimmed version of what serde_derive generates. All parts not relevant
531 // for toml deserialization have been removed. This reduces the binary size and improves
532 // compile time of rustbuild.
533 impl<'de> Deserialize<'de> for $name {
534 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
536 D: Deserializer<'de>,
539 impl<'de> serde::de::Visitor<'de> for Field {
541 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
542 f.write_str(concat!("struct ", stringify!($name)))
546 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
548 A: serde::de::MapAccess<'de>,
550 $(let mut $field: Option<$field_ty> = None;)*
551 while let Some(key) =
552 match serde::de::MapAccess::next_key::<String>(&mut map) {
561 if $field.is_some() {
562 return Err(<A::Error as serde::de::Error>::duplicate_field(
566 $field = match serde::de::MapAccess::next_value::<$field_ty>(
569 Ok(val) => Some(val),
576 return Err(serde::de::Error::unknown_field(key, FIELDS));
580 Ok($name { $($field),* })
583 const FIELDS: &'static [&'static str] = &[
586 Deserializer::deserialize_struct(
598 /// TOML representation of various global build decisions.
601 build: Option<String> = "build",
602 host: Option<Vec<String>> = "host",
603 target: Option<Vec<String>> = "target",
604 build_dir: Option<String> = "build-dir",
605 cargo: Option<String> = "cargo",
606 rustc: Option<String> = "rustc",
607 rustfmt: Option<PathBuf> = "rustfmt",
608 docs: Option<bool> = "docs",
609 compiler_docs: Option<bool> = "compiler-docs",
610 docs_minification: Option<bool> = "docs-minification",
611 submodules: Option<bool> = "submodules",
612 gdb: Option<String> = "gdb",
613 nodejs: Option<String> = "nodejs",
614 npm: Option<String> = "npm",
615 python: Option<String> = "python",
616 locked_deps: Option<bool> = "locked-deps",
617 vendor: Option<bool> = "vendor",
618 full_bootstrap: Option<bool> = "full-bootstrap",
619 extended: Option<bool> = "extended",
620 tools: Option<HashSet<String>> = "tools",
621 verbose: Option<usize> = "verbose",
622 sanitizers: Option<bool> = "sanitizers",
623 profiler: Option<bool> = "profiler",
624 cargo_native_static: Option<bool> = "cargo-native-static",
625 low_priority: Option<bool> = "low-priority",
626 configure_args: Option<Vec<String>> = "configure-args",
627 local_rebuild: Option<bool> = "local-rebuild",
628 print_step_timings: Option<bool> = "print-step-timings",
629 print_step_rusage: Option<bool> = "print-step-rusage",
630 check_stage: Option<u32> = "check-stage",
631 doc_stage: Option<u32> = "doc-stage",
632 build_stage: Option<u32> = "build-stage",
633 test_stage: Option<u32> = "test-stage",
634 install_stage: Option<u32> = "install-stage",
635 dist_stage: Option<u32> = "dist-stage",
636 bench_stage: Option<u32> = "bench-stage",
637 patch_binaries_for_nix: Option<bool> = "patch-binaries-for-nix",
638 metrics: Option<bool> = "metrics",
643 /// TOML representation of various global install decisions.
645 prefix: Option<String> = "prefix",
646 sysconfdir: Option<String> = "sysconfdir",
647 docdir: Option<String> = "docdir",
648 bindir: Option<String> = "bindir",
649 libdir: Option<String> = "libdir",
650 mandir: Option<String> = "mandir",
651 datadir: Option<String> = "datadir",
656 /// TOML representation of how the LLVM build is configured.
658 skip_rebuild: Option<bool> = "skip-rebuild",
659 optimize: Option<bool> = "optimize",
660 thin_lto: Option<bool> = "thin-lto",
661 release_debuginfo: Option<bool> = "release-debuginfo",
662 assertions: Option<bool> = "assertions",
663 tests: Option<bool> = "tests",
664 plugins: Option<bool> = "plugins",
665 ccache: Option<StringOrBool> = "ccache",
666 version_check: Option<bool> = "version-check",
667 static_libstdcpp: Option<bool> = "static-libstdcpp",
668 ninja: Option<bool> = "ninja",
669 targets: Option<String> = "targets",
670 experimental_targets: Option<String> = "experimental-targets",
671 link_jobs: Option<u32> = "link-jobs",
672 link_shared: Option<bool> = "link-shared",
673 version_suffix: Option<String> = "version-suffix",
674 clang_cl: Option<String> = "clang-cl",
675 cflags: Option<String> = "cflags",
676 cxxflags: Option<String> = "cxxflags",
677 ldflags: Option<String> = "ldflags",
678 use_libcxx: Option<bool> = "use-libcxx",
679 use_linker: Option<String> = "use-linker",
680 allow_old_toolchain: Option<bool> = "allow-old-toolchain",
681 polly: Option<bool> = "polly",
682 clang: Option<bool> = "clang",
683 download_ci_llvm: Option<StringOrBool> = "download-ci-llvm",
684 build_config: Option<HashMap<String, String>> = "build-config",
690 sign_folder: Option<String> = "sign-folder",
691 gpg_password_file: Option<String> = "gpg-password-file",
692 upload_addr: Option<String> = "upload-addr",
693 src_tarball: Option<bool> = "src-tarball",
694 missing_tools: Option<bool> = "missing-tools",
695 compression_formats: Option<Vec<String>> = "compression-formats",
699 #[derive(Debug, Deserialize)]
706 impl Default for StringOrBool {
707 fn default() -> StringOrBool {
708 StringOrBool::Bool(false)
713 /// TOML representation of how the Rust build is configured.
715 optimize: Option<bool> = "optimize",
716 debug: Option<bool> = "debug",
717 codegen_units: Option<u32> = "codegen-units",
718 codegen_units_std: Option<u32> = "codegen-units-std",
719 debug_assertions: Option<bool> = "debug-assertions",
720 debug_assertions_std: Option<bool> = "debug-assertions-std",
721 overflow_checks: Option<bool> = "overflow-checks",
722 overflow_checks_std: Option<bool> = "overflow-checks-std",
723 debug_logging: Option<bool> = "debug-logging",
724 debuginfo_level: Option<u32> = "debuginfo-level",
725 debuginfo_level_rustc: Option<u32> = "debuginfo-level-rustc",
726 debuginfo_level_std: Option<u32> = "debuginfo-level-std",
727 debuginfo_level_tools: Option<u32> = "debuginfo-level-tools",
728 debuginfo_level_tests: Option<u32> = "debuginfo-level-tests",
729 split_debuginfo: Option<String> = "split-debuginfo",
730 run_dsymutil: Option<bool> = "run-dsymutil",
731 backtrace: Option<bool> = "backtrace",
732 incremental: Option<bool> = "incremental",
733 parallel_compiler: Option<bool> = "parallel-compiler",
734 default_linker: Option<String> = "default-linker",
735 channel: Option<String> = "channel",
736 description: Option<String> = "description",
737 musl_root: Option<String> = "musl-root",
738 rpath: Option<bool> = "rpath",
739 verbose_tests: Option<bool> = "verbose-tests",
740 optimize_tests: Option<bool> = "optimize-tests",
741 codegen_tests: Option<bool> = "codegen-tests",
742 ignore_git: Option<bool> = "ignore-git",
743 dist_src: Option<bool> = "dist-src",
744 save_toolstates: Option<String> = "save-toolstates",
745 codegen_backends: Option<Vec<String>> = "codegen-backends",
746 lld: Option<bool> = "lld",
747 use_lld: Option<bool> = "use-lld",
748 llvm_tools: Option<bool> = "llvm-tools",
749 deny_warnings: Option<bool> = "deny-warnings",
750 backtrace_on_ice: Option<bool> = "backtrace-on-ice",
751 verify_llvm_ir: Option<bool> = "verify-llvm-ir",
752 thin_lto_import_instr_limit: Option<u32> = "thin-lto-import-instr-limit",
753 remap_debuginfo: Option<bool> = "remap-debuginfo",
754 jemalloc: Option<bool> = "jemalloc",
755 test_compare_mode: Option<bool> = "test-compare-mode",
756 llvm_libunwind: Option<String> = "llvm-libunwind",
757 control_flow_guard: Option<bool> = "control-flow-guard",
758 new_symbol_mangling: Option<bool> = "new-symbol-mangling",
759 profile_generate: Option<String> = "profile-generate",
760 profile_use: Option<String> = "profile-use",
761 // ignored; this is set from an env var set by bootstrap.py
762 download_rustc: Option<StringOrBool> = "download-rustc",
763 lto: Option<String> = "lto",
768 /// TOML representation of how each build target is configured.
770 cc: Option<String> = "cc",
771 cxx: Option<String> = "cxx",
772 ar: Option<String> = "ar",
773 ranlib: Option<String> = "ranlib",
774 default_linker: Option<PathBuf> = "default-linker",
775 linker: Option<String> = "linker",
776 llvm_config: Option<String> = "llvm-config",
777 llvm_has_rust_patches: Option<bool> = "llvm-has-rust-patches",
778 llvm_filecheck: Option<String> = "llvm-filecheck",
779 llvm_libunwind: Option<String> = "llvm-libunwind",
780 android_ndk: Option<String> = "android-ndk",
781 sanitizers: Option<bool> = "sanitizers",
782 profiler: Option<bool> = "profiler",
783 crt_static: Option<bool> = "crt-static",
784 musl_root: Option<String> = "musl-root",
785 musl_libdir: Option<String> = "musl-libdir",
786 wasi_root: Option<String> = "wasi-root",
787 qemu_rootfs: Option<String> = "qemu-rootfs",
788 no_std: Option<bool> = "no-std",
793 pub fn default_opts() -> Config {
794 let mut config = Config::default();
795 config.llvm_optimize = true;
796 config.ninja_in_file = true;
797 config.llvm_version_check = true;
798 config.llvm_static_stdcpp = false;
799 config.backtrace = true;
800 config.rust_optimize = true;
801 config.rust_optimize_tests = true;
802 config.submodules = None;
804 config.docs_minification = true;
805 config.rust_rpath = true;
806 config.channel = "dev".to_string();
807 config.codegen_tests = true;
808 config.rust_dist_src = true;
809 config.rust_codegen_backends = vec![INTERNER.intern_str("llvm")];
810 config.deny_warnings = true;
811 config.bindir = "bin".into();
814 config.build = TargetSelection::from_user(&env!("BUILD_TRIPLE"));
816 let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
817 // Undo `src/bootstrap`
818 config.src = manifest_dir.parent().unwrap().parent().unwrap().to_owned();
819 config.out = PathBuf::from("build");
824 pub fn parse(args: &[String]) -> Config {
826 let get_toml = |_: &_| TomlConfig::default();
828 let get_toml = |file: &Path| {
830 t!(fs::read_to_string(file), format!("config file {} not found", file.display()));
831 // Deserialize to Value and then TomlConfig to prevent the Deserialize impl of
832 // TomlConfig and sub types to be monomorphized 5x by toml.
833 match toml::from_str(&contents)
834 .and_then(|table: toml::Value| TomlConfig::deserialize(table))
838 eprintln!("failed to parse TOML configuration '{}': {}", file.display(), err);
839 crate::detail_exit(2);
844 Self::parse_inner(args, get_toml)
847 fn parse_inner<'a>(args: &[String], get_toml: impl 'a + Fn(&Path) -> TomlConfig) -> Config {
848 let flags = Flags::parse(&args);
849 let mut config = Config::default_opts();
852 config.exclude = flags.exclude.into_iter().map(|path| TaskPath::parse(path)).collect();
853 config.include_default_paths = flags.include_default_paths;
854 config.rustc_error_format = flags.rustc_error_format;
855 config.json_output = flags.json_output;
856 config.on_fail = flags.on_fail;
857 config.jobs = flags.jobs.map(threads_from_config);
858 config.cmd = flags.cmd;
859 config.incremental = flags.incremental;
860 config.dry_run = if flags.dry_run { DryRun::UserSelected } else { DryRun::Disabled };
861 config.keep_stage = flags.keep_stage;
862 config.keep_stage_std = flags.keep_stage_std;
863 config.color = flags.color;
864 if let Some(value) = flags.deny_warnings {
865 config.deny_warnings = value;
867 config.llvm_profile_use = flags.llvm_profile_use;
868 config.llvm_profile_generate = flags.llvm_profile_generate;
869 config.llvm_bolt_profile_generate = flags.llvm_bolt_profile_generate;
870 config.llvm_bolt_profile_use = flags.llvm_bolt_profile_use;
872 if config.llvm_bolt_profile_generate && config.llvm_bolt_profile_use.is_some() {
874 "Cannot use both `llvm_bolt_profile_generate` and `llvm_bolt_profile_use` at the same time"
876 crate::detail_exit(1);
879 // Infer the rest of the configuration.
881 // Infer the source directory. This is non-trivial because we want to support a downloaded bootstrap binary,
882 // running on a completely machine from where it was compiled.
883 let mut cmd = Command::new("git");
884 // NOTE: we cannot support running from outside the repository because the only path we have available
885 // is set at compile time, which can be wrong if bootstrap was downloaded from source.
886 // We still support running outside the repository if we find we aren't in a git directory.
887 cmd.arg("rev-parse").arg("--show-toplevel");
888 // Discard stderr because we expect this to fail when building from a tarball.
890 .stderr(std::process::Stdio::null())
893 .and_then(|output| if output.status.success() { Some(output) } else { None });
894 if let Some(output) = output {
895 let git_root = String::from_utf8(output.stdout).unwrap();
896 // We need to canonicalize this path to make sure it uses backslashes instead of forward slashes.
897 let git_root = PathBuf::from(git_root.trim()).canonicalize().unwrap();
898 let s = git_root.to_str().unwrap();
900 // Bootstrap is quite bad at handling /? in front of paths
901 let src = match s.strip_prefix("\\\\?\\") {
902 Some(p) => PathBuf::from(p),
903 None => PathBuf::from(git_root),
905 // If this doesn't have at least `stage0.json`, we guessed wrong. This can happen when,
906 // for example, the build directory is inside of another unrelated git directory.
907 // In that case keep the original `CARGO_MANIFEST_DIR` handling.
909 // NOTE: this implies that downloadable bootstrap isn't supported when the build directory is outside
910 // the source directory. We could fix that by setting a variable from all three of python, ./x, and x.ps1.
911 if src.join("src").join("stage0.json").exists() {
915 // We're building from a tarball, not git sources.
916 // We don't support pre-downloaded bootstrap in this case.
920 // Use the build directory of the original x.py invocation, so that we can set `initial_rustc` properly.
921 config.out = Path::new(
922 &env::var_os("CARGO_TARGET_DIR").expect("cargo test directly is not supported"),
929 let stage0_json = t!(std::fs::read(&config.src.join("src").join("stage0.json")));
931 config.stage0_metadata = t!(serde_json::from_slice::<Stage0Metadata>(&stage0_json));
933 // Read from `--config`, then `RUST_BOOTSTRAP_CONFIG`, then `./config.toml`, then `config.toml` in the root directory.
934 let toml_path = flags
937 .or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
938 let using_default_path = toml_path.is_none();
939 let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("config.toml"));
940 if using_default_path && !toml_path.exists() {
941 toml_path = config.src.join(toml_path);
944 // Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path,
945 // but not if `config.toml` hasn't been created.
946 let mut toml = if !using_default_path || toml_path.exists() {
947 config.config = Some(toml_path.clone());
950 config.config = None;
951 TomlConfig::default()
954 if let Some(include) = &toml.profile {
955 let mut include_path = config.src.clone();
956 include_path.push("src");
957 include_path.push("bootstrap");
958 include_path.push("defaults");
959 include_path.push(format!("config.{}.toml", include));
960 let included_toml = get_toml(&include_path);
961 toml.merge(included_toml);
964 config.changelog_seen = toml.changelog_seen;
966 let build = toml.build.unwrap_or_default();
968 set(&mut config.out, flags.build_dir.or_else(|| build.build_dir.map(PathBuf::from)));
969 // NOTE: Bootstrap spawns various commands with different working directories.
970 // To avoid writing to random places on the file system, `config.out` needs to be an absolute path.
971 if !config.out.is_absolute() {
972 // `canonicalize` requires the path to already exist. Use our vendored copy of `absolute` instead.
973 config.out = crate::util::absolute(&config.out);
976 config.initial_rustc = build
979 .unwrap_or_else(|| config.out.join(config.build.triple).join("stage0/bin/rustc"));
980 config.initial_cargo = build
983 .unwrap_or_else(|| config.out.join(config.build.triple).join("stage0/bin/cargo"));
985 // NOTE: it's important this comes *after* we set `initial_rustc` just above.
986 if config.dry_run() {
987 let dir = config.out.join("tmp-dry-run");
988 t!(fs::create_dir_all(&dir));
992 config.hosts = if let Some(arg_host) = flags.host {
994 } else if let Some(file_host) = build.host {
995 file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
999 config.targets = if let Some(arg_target) = flags.target {
1001 } else if let Some(file_target) = build.target {
1002 file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
1004 // If target is *not* configured, then default to the host
1006 config.hosts.clone()
1009 config.nodejs = build.nodejs.map(PathBuf::from);
1010 config.npm = build.npm.map(PathBuf::from);
1011 config.gdb = build.gdb.map(PathBuf::from);
1012 config.python = build.python.map(PathBuf::from);
1013 config.submodules = build.submodules;
1014 set(&mut config.low_priority, build.low_priority);
1015 set(&mut config.compiler_docs, build.compiler_docs);
1016 set(&mut config.docs_minification, build.docs_minification);
1017 set(&mut config.docs, build.docs);
1018 set(&mut config.locked_deps, build.locked_deps);
1019 set(&mut config.vendor, build.vendor);
1020 set(&mut config.full_bootstrap, build.full_bootstrap);
1021 set(&mut config.extended, build.extended);
1022 config.tools = build.tools;
1023 set(&mut config.verbose, build.verbose);
1024 set(&mut config.sanitizers, build.sanitizers);
1025 set(&mut config.profiler, build.profiler);
1026 set(&mut config.cargo_native_static, build.cargo_native_static);
1027 set(&mut config.configure_args, build.configure_args);
1028 set(&mut config.local_rebuild, build.local_rebuild);
1029 set(&mut config.print_step_timings, build.print_step_timings);
1030 set(&mut config.print_step_rusage, build.print_step_rusage);
1031 set(&mut config.patch_binaries_for_nix, build.patch_binaries_for_nix);
1033 config.verbose = cmp::max(config.verbose, flags.verbose);
1035 if let Some(install) = toml.install {
1036 config.prefix = install.prefix.map(PathBuf::from);
1037 config.sysconfdir = install.sysconfdir.map(PathBuf::from);
1038 config.datadir = install.datadir.map(PathBuf::from);
1039 config.docdir = install.docdir.map(PathBuf::from);
1040 set(&mut config.bindir, install.bindir.map(PathBuf::from));
1041 config.libdir = install.libdir.map(PathBuf::from);
1042 config.mandir = install.mandir.map(PathBuf::from);
1045 // We want the llvm-skip-rebuild flag to take precedence over the
1046 // skip-rebuild config.toml option so we store it separately
1047 // so that we can infer the right value
1048 let mut llvm_skip_rebuild = flags.llvm_skip_rebuild;
1050 // Store off these values as options because if they're not provided
1051 // we'll infer default values for them later
1052 let mut llvm_assertions = None;
1053 let mut llvm_tests = None;
1054 let mut llvm_plugins = None;
1055 let mut debug = None;
1056 let mut debug_assertions = None;
1057 let mut debug_assertions_std = None;
1058 let mut overflow_checks = None;
1059 let mut overflow_checks_std = None;
1060 let mut debug_logging = None;
1061 let mut debuginfo_level = None;
1062 let mut debuginfo_level_rustc = None;
1063 let mut debuginfo_level_std = None;
1064 let mut debuginfo_level_tools = None;
1065 let mut debuginfo_level_tests = None;
1066 let mut optimize = None;
1067 let mut ignore_git = None;
1069 if let Some(rust) = toml.rust {
1071 debug_assertions = rust.debug_assertions;
1072 debug_assertions_std = rust.debug_assertions_std;
1073 overflow_checks = rust.overflow_checks;
1074 overflow_checks_std = rust.overflow_checks_std;
1075 debug_logging = rust.debug_logging;
1076 debuginfo_level = rust.debuginfo_level;
1077 debuginfo_level_rustc = rust.debuginfo_level_rustc;
1078 debuginfo_level_std = rust.debuginfo_level_std;
1079 debuginfo_level_tools = rust.debuginfo_level_tools;
1080 debuginfo_level_tests = rust.debuginfo_level_tests;
1081 config.rust_split_debuginfo = rust
1084 .map(SplitDebuginfo::from_str)
1085 .map(|v| v.expect("invalid value for rust.split_debuginfo"))
1086 .unwrap_or(SplitDebuginfo::default_for_platform(&config.build.triple));
1087 optimize = rust.optimize;
1088 ignore_git = rust.ignore_git;
1089 config.rust_new_symbol_mangling = rust.new_symbol_mangling;
1090 set(&mut config.rust_optimize_tests, rust.optimize_tests);
1091 set(&mut config.codegen_tests, rust.codegen_tests);
1092 set(&mut config.rust_rpath, rust.rpath);
1093 set(&mut config.jemalloc, rust.jemalloc);
1094 set(&mut config.test_compare_mode, rust.test_compare_mode);
1095 set(&mut config.backtrace, rust.backtrace);
1096 set(&mut config.channel, rust.channel);
1097 config.description = rust.description;
1098 set(&mut config.rust_dist_src, rust.dist_src);
1099 set(&mut config.verbose_tests, rust.verbose_tests);
1100 // in the case "false" is set explicitly, do not overwrite the command line args
1101 if let Some(true) = rust.incremental {
1102 config.incremental = true;
1104 set(&mut config.use_lld, rust.use_lld);
1105 set(&mut config.lld_enabled, rust.lld);
1106 set(&mut config.llvm_tools_enabled, rust.llvm_tools);
1107 config.rustc_parallel = rust.parallel_compiler.unwrap_or(false);
1108 config.rustc_default_linker = rust.default_linker;
1109 config.musl_root = rust.musl_root.map(PathBuf::from);
1110 config.save_toolstates = rust.save_toolstates.map(PathBuf::from);
1111 set(&mut config.deny_warnings, flags.deny_warnings.or(rust.deny_warnings));
1112 set(&mut config.backtrace_on_ice, rust.backtrace_on_ice);
1113 set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir);
1114 config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit;
1115 set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo);
1116 set(&mut config.control_flow_guard, rust.control_flow_guard);
1117 config.llvm_libunwind_default = rust
1119 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
1121 if let Some(ref backends) = rust.codegen_backends {
1122 config.rust_codegen_backends =
1123 backends.iter().map(|s| INTERNER.intern_str(s)).collect();
1126 config.rust_codegen_units = rust.codegen_units.map(threads_from_config);
1127 config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config);
1128 config.rust_profile_use = flags.rust_profile_use.or(rust.profile_use);
1129 config.rust_profile_generate = flags.rust_profile_generate.or(rust.profile_generate);
1130 config.download_rustc_commit = config.download_ci_rustc_commit(rust.download_rustc);
1132 config.rust_lto = rust
1135 .map(|value| RustcLto::from_str(value).unwrap())
1136 .unwrap_or_default();
1138 config.rust_profile_use = flags.rust_profile_use;
1139 config.rust_profile_generate = flags.rust_profile_generate;
1142 if let Some(llvm) = toml.llvm {
1144 Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
1145 Some(StringOrBool::Bool(true)) => {
1146 config.ccache = Some("ccache".to_string());
1148 Some(StringOrBool::Bool(false)) | None => {}
1150 set(&mut config.ninja_in_file, llvm.ninja);
1151 llvm_assertions = llvm.assertions;
1152 llvm_tests = llvm.tests;
1153 llvm_plugins = llvm.plugins;
1154 llvm_skip_rebuild = llvm_skip_rebuild.or(llvm.skip_rebuild);
1155 set(&mut config.llvm_optimize, llvm.optimize);
1156 set(&mut config.llvm_thin_lto, llvm.thin_lto);
1157 set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
1158 set(&mut config.llvm_version_check, llvm.version_check);
1159 set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp);
1160 if let Some(v) = llvm.link_shared {
1161 config.llvm_link_shared.set(Some(v));
1163 config.llvm_targets = llvm.targets.clone();
1164 config.llvm_experimental_targets = llvm.experimental_targets.clone();
1165 config.llvm_link_jobs = llvm.link_jobs;
1166 config.llvm_version_suffix = llvm.version_suffix.clone();
1167 config.llvm_clang_cl = llvm.clang_cl.clone();
1169 config.llvm_cflags = llvm.cflags.clone();
1170 config.llvm_cxxflags = llvm.cxxflags.clone();
1171 config.llvm_ldflags = llvm.ldflags.clone();
1172 set(&mut config.llvm_use_libcxx, llvm.use_libcxx);
1173 config.llvm_use_linker = llvm.use_linker.clone();
1174 config.llvm_allow_old_toolchain = llvm.allow_old_toolchain.unwrap_or(false);
1175 config.llvm_polly = llvm.polly.unwrap_or(false);
1176 config.llvm_clang = llvm.clang.unwrap_or(false);
1177 config.llvm_build_config = llvm.build_config.clone().unwrap_or(Default::default());
1179 let asserts = llvm_assertions.unwrap_or(false);
1180 config.llvm_from_ci = match llvm.download_ci_llvm {
1181 Some(StringOrBool::String(s)) => {
1182 assert!(s == "if-available", "unknown option `{}` for download-ci-llvm", s);
1183 crate::native::is_ci_llvm_available(&config, asserts)
1185 Some(StringOrBool::Bool(b)) => b,
1187 config.channel == "dev" && crate::native::is_ci_llvm_available(&config, asserts)
1191 if config.llvm_from_ci {
1192 // None of the LLVM options, except assertions, are supported
1193 // when using downloaded LLVM. We could just ignore these but
1194 // that's potentially confusing, so force them to not be
1195 // explicitly set. The defaults and CI defaults don't
1196 // necessarily match but forcing people to match (somewhat
1197 // arbitrary) CI configuration locally seems bad/hard.
1198 check_ci_llvm!(llvm.optimize);
1199 check_ci_llvm!(llvm.thin_lto);
1200 check_ci_llvm!(llvm.release_debuginfo);
1201 // CI-built LLVM can be either dynamic or static. We won't know until we download it.
1202 check_ci_llvm!(llvm.link_shared);
1203 check_ci_llvm!(llvm.static_libstdcpp);
1204 check_ci_llvm!(llvm.targets);
1205 check_ci_llvm!(llvm.experimental_targets);
1206 check_ci_llvm!(llvm.link_jobs);
1207 check_ci_llvm!(llvm.clang_cl);
1208 check_ci_llvm!(llvm.version_suffix);
1209 check_ci_llvm!(llvm.cflags);
1210 check_ci_llvm!(llvm.cxxflags);
1211 check_ci_llvm!(llvm.ldflags);
1212 check_ci_llvm!(llvm.use_libcxx);
1213 check_ci_llvm!(llvm.use_linker);
1214 check_ci_llvm!(llvm.allow_old_toolchain);
1215 check_ci_llvm!(llvm.polly);
1216 check_ci_llvm!(llvm.clang);
1217 check_ci_llvm!(llvm.build_config);
1218 check_ci_llvm!(llvm.plugins);
1221 // NOTE: can never be hit when downloading from CI, since we call `check_ci_llvm!(thin_lto)` above.
1222 if config.llvm_thin_lto && llvm.link_shared.is_none() {
1223 // If we're building with ThinLTO on, by default we want to link
1224 // to LLVM shared, to avoid re-doing ThinLTO (which happens in
1225 // the link step) with each stage.
1226 config.llvm_link_shared.set(Some(true));
1229 config.llvm_from_ci =
1230 config.channel == "dev" && crate::native::is_ci_llvm_available(&config, false);
1233 if let Some(t) = toml.target {
1234 for (triple, cfg) in t {
1235 let mut target = Target::from_triple(&triple);
1237 if let Some(ref s) = cfg.llvm_config {
1238 target.llvm_config = Some(config.src.join(s));
1240 target.llvm_has_rust_patches = cfg.llvm_has_rust_patches;
1241 if let Some(ref s) = cfg.llvm_filecheck {
1242 target.llvm_filecheck = Some(config.src.join(s));
1244 target.llvm_libunwind = cfg
1247 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
1248 if let Some(ref s) = cfg.android_ndk {
1249 target.ndk = Some(config.src.join(s));
1251 if let Some(s) = cfg.no_std {
1254 target.cc = cfg.cc.map(PathBuf::from);
1255 target.cxx = cfg.cxx.map(PathBuf::from);
1256 target.ar = cfg.ar.map(PathBuf::from);
1257 target.ranlib = cfg.ranlib.map(PathBuf::from);
1258 target.linker = cfg.linker.map(PathBuf::from);
1259 target.crt_static = cfg.crt_static;
1260 target.musl_root = cfg.musl_root.map(PathBuf::from);
1261 target.musl_libdir = cfg.musl_libdir.map(PathBuf::from);
1262 target.wasi_root = cfg.wasi_root.map(PathBuf::from);
1263 target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from);
1264 target.sanitizers = cfg.sanitizers;
1265 target.profiler = cfg.profiler;
1267 config.target_config.insert(TargetSelection::from_user(&triple), target);
1271 if config.llvm_from_ci {
1272 let triple = &config.build.triple;
1273 let ci_llvm_bin = config.ci_llvm_root().join("bin");
1274 let mut build_target = config
1276 .entry(config.build)
1277 .or_insert_with(|| Target::from_triple(&triple));
1279 check_ci_llvm!(build_target.llvm_config);
1280 check_ci_llvm!(build_target.llvm_filecheck);
1281 build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", config.build)));
1282 build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", config.build)));
1285 if let Some(t) = toml.dist {
1286 config.dist_sign_folder = t.sign_folder.map(PathBuf::from);
1287 config.dist_upload_addr = t.upload_addr;
1288 config.dist_compression_formats = t.compression_formats;
1289 set(&mut config.rust_dist_src, t.src_tarball);
1290 set(&mut config.missing_tools, t.missing_tools);
1293 if let Some(r) = build.rustfmt {
1294 *config.initial_rustfmt.borrow_mut() = if r.exists() {
1295 RustfmtState::SystemToolchain(r)
1297 RustfmtState::Unavailable
1300 // If using a system toolchain for bootstrapping, see if that has rustfmt available.
1301 let host = config.build;
1302 let rustfmt_path = config.initial_rustc.with_file_name(exe("rustfmt", host));
1303 let bin_root = config.out.join(host.triple).join("stage0");
1304 if !rustfmt_path.starts_with(&bin_root) {
1305 // Using a system-provided toolchain; we shouldn't download rustfmt.
1306 *config.initial_rustfmt.borrow_mut() = RustfmtState::SystemToolchain(rustfmt_path);
1310 // Now that we've reached the end of our configuration, infer the
1311 // default values for all options that we haven't otherwise stored yet.
1313 config.llvm_skip_rebuild = llvm_skip_rebuild.unwrap_or(false);
1314 config.llvm_assertions = llvm_assertions.unwrap_or(false);
1315 config.llvm_tests = llvm_tests.unwrap_or(false);
1316 config.llvm_plugins = llvm_plugins.unwrap_or(false);
1317 config.rust_optimize = optimize.unwrap_or(true);
1319 let default = debug == Some(true);
1320 config.rust_debug_assertions = debug_assertions.unwrap_or(default);
1321 config.rust_debug_assertions_std =
1322 debug_assertions_std.unwrap_or(config.rust_debug_assertions);
1323 config.rust_overflow_checks = overflow_checks.unwrap_or(default);
1324 config.rust_overflow_checks_std =
1325 overflow_checks_std.unwrap_or(config.rust_overflow_checks);
1327 config.rust_debug_logging = debug_logging.unwrap_or(config.rust_debug_assertions);
1329 let with_defaults = |debuginfo_level_specific: Option<u32>| {
1330 debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
1336 config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
1337 config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
1338 config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
1339 config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(0);
1341 let default = config.channel == "dev";
1342 config.ignore_git = ignore_git.unwrap_or(default);
1343 config.rust_info = GitInfo::new(config.ignore_git, &config.src);
1345 let download_rustc = config.download_rustc_commit.is_some();
1346 // See https://github.com/rust-lang/compiler-team/issues/326
1347 config.stage = match config.cmd {
1348 Subcommand::Check { .. } => flags.stage.or(build.check_stage).unwrap_or(0),
1349 // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden.
1350 Subcommand::Doc { .. } => {
1351 flags.stage.or(build.doc_stage).unwrap_or(if download_rustc { 2 } else { 0 })
1353 Subcommand::Build { .. } => {
1354 flags.stage.or(build.build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1356 Subcommand::Test { .. } => {
1357 flags.stage.or(build.test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1359 Subcommand::Bench { .. } => flags.stage.or(build.bench_stage).unwrap_or(2),
1360 Subcommand::Dist { .. } => flags.stage.or(build.dist_stage).unwrap_or(2),
1361 Subcommand::Install { .. } => flags.stage.or(build.install_stage).unwrap_or(2),
1362 // These are all bootstrap tools, which don't depend on the compiler.
1363 // The stage we pass shouldn't matter, but use 0 just in case.
1364 Subcommand::Clean { .. }
1365 | Subcommand::Clippy { .. }
1366 | Subcommand::Fix { .. }
1367 | Subcommand::Run { .. }
1368 | Subcommand::Setup { .. }
1369 | Subcommand::Format { .. } => flags.stage.unwrap_or(0),
1372 // CI should always run stage 2 builds, unless it specifically states otherwise
1374 if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None {
1376 Subcommand::Test { .. }
1377 | Subcommand::Doc { .. }
1378 | Subcommand::Build { .. }
1379 | Subcommand::Bench { .. }
1380 | Subcommand::Dist { .. }
1381 | Subcommand::Install { .. } => {
1384 "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
1388 Subcommand::Clean { .. }
1389 | Subcommand::Check { .. }
1390 | Subcommand::Clippy { .. }
1391 | Subcommand::Fix { .. }
1392 | Subcommand::Run { .. }
1393 | Subcommand::Setup { .. }
1394 | Subcommand::Format { .. } => {}
1401 pub(crate) fn dry_run(&self) -> bool {
1402 match self.dry_run {
1403 DryRun::Disabled => false,
1404 DryRun::SelfCheck | DryRun::UserSelected => true,
1408 /// A git invocation which runs inside the source directory.
1410 /// Use this rather than `Command::new("git")` in order to support out-of-tree builds.
1411 pub(crate) fn git(&self) -> Command {
1412 let mut git = Command::new("git");
1413 git.current_dir(&self.src);
1417 /// Bootstrap embeds a version number into the name of shared libraries it uploads in CI.
1418 /// Return the version it would have used for the given commit.
1419 pub(crate) fn artifact_version_part(&self, commit: &str) -> String {
1420 let (channel, version) = if self.rust_info.is_managed_git_subrepository() {
1421 let mut channel = self.git();
1422 channel.arg("show").arg(format!("{}:src/ci/channel", commit));
1423 let channel = output(&mut channel);
1424 let mut version = self.git();
1425 version.arg("show").arg(format!("{}:src/version", commit));
1426 let version = output(&mut version);
1427 (channel.trim().to_owned(), version.trim().to_owned())
1429 let channel = fs::read_to_string(self.src.join("src/ci/channel"));
1430 let version = fs::read_to_string(self.src.join("src/version"));
1431 match (channel, version) {
1432 (Ok(channel), Ok(version)) => {
1433 (channel.trim().to_owned(), version.trim().to_owned())
1435 (channel, version) => {
1436 let src = self.src.display();
1437 eprintln!("error: failed to determine artifact channel and/or version");
1439 "help: consider using a git checkout or ensure these files are readable"
1441 if let Err(channel) = channel {
1442 eprintln!("reading {}/src/ci/channel failed: {:?}", src, channel);
1444 if let Err(version) = version {
1445 eprintln!("reading {}/src/version failed: {:?}", src, version);
1452 match channel.as_str() {
1453 "stable" => version,
1455 "nightly" => channel,
1456 other => unreachable!("{:?} is not recognized as a valid channel", other),
1460 /// Try to find the relative path of `bindir`, otherwise return it in full.
1461 pub fn bindir_relative(&self) -> &Path {
1462 let bindir = &self.bindir;
1463 if bindir.is_absolute() {
1464 // Try to make it relative to the prefix.
1465 if let Some(prefix) = &self.prefix {
1466 if let Ok(stripped) = bindir.strip_prefix(prefix) {
1474 /// Try to find the relative path of `libdir`.
1475 pub fn libdir_relative(&self) -> Option<&Path> {
1476 let libdir = self.libdir.as_ref()?;
1477 if libdir.is_relative() {
1480 // Try to make it relative to the prefix.
1481 libdir.strip_prefix(self.prefix.as_ref()?).ok()
1485 /// The absolute path to the downloaded LLVM artifacts.
1486 pub(crate) fn ci_llvm_root(&self) -> PathBuf {
1487 assert!(self.llvm_from_ci);
1488 self.out.join(&*self.build.triple).join("ci-llvm")
1491 /// Determine whether llvm should be linked dynamically.
1493 /// If `false`, llvm should be linked statically.
1494 /// This is computed on demand since LLVM might have to first be downloaded from CI.
1495 pub(crate) fn llvm_link_shared(&self) -> bool {
1496 let mut opt = self.llvm_link_shared.get();
1497 if opt.is_none() && self.dry_run() {
1498 // just assume static for now - dynamic linking isn't supported on all platforms
1502 let llvm_link_shared = *opt.get_or_insert_with(|| {
1503 if self.llvm_from_ci {
1504 self.maybe_download_ci_llvm();
1505 let ci_llvm = self.ci_llvm_root();
1507 std::fs::read_to_string(ci_llvm.join("link-type.txt")),
1508 format!("CI llvm missing: {}", ci_llvm.display())
1510 link_type == "dynamic"
1512 // unclear how thought-through this default is, but it maintains compatibility with
1513 // previous behavior
1517 self.llvm_link_shared.set(opt);
1521 /// Return whether we will use a downloaded, pre-compiled version of rustc, or just build from source.
1522 pub(crate) fn download_rustc(&self) -> bool {
1523 static DOWNLOAD_RUSTC: OnceCell<bool> = OnceCell::new();
1524 if self.dry_run() && DOWNLOAD_RUSTC.get().is_none() {
1525 // avoid trying to actually download the commit
1529 *DOWNLOAD_RUSTC.get_or_init(|| match &self.download_rustc_commit {
1532 self.download_ci_rustc(commit);
1538 pub(crate) fn initial_rustfmt(&self) -> Option<PathBuf> {
1539 match &mut *self.initial_rustfmt.borrow_mut() {
1540 RustfmtState::SystemToolchain(p) | RustfmtState::Downloaded(p) => Some(p.clone()),
1541 RustfmtState::Unavailable => None,
1542 r @ RustfmtState::LazyEvaluated => {
1544 return Some(PathBuf::new());
1546 let path = self.maybe_download_rustfmt();
1547 *r = if let Some(p) = &path {
1548 RustfmtState::Downloaded(p.clone())
1550 RustfmtState::Unavailable
1557 pub fn verbose(&self, msg: &str) {
1558 if self.verbose > 0 {
1559 println!("{}", msg);
1563 pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1564 self.target_config.get(&target).map(|t| t.sanitizers).flatten().unwrap_or(self.sanitizers)
1567 pub fn any_sanitizers_enabled(&self) -> bool {
1568 self.target_config.values().any(|t| t.sanitizers == Some(true)) || self.sanitizers
1571 pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1572 self.target_config.get(&target).map(|t| t.profiler).flatten().unwrap_or(self.profiler)
1575 pub fn any_profiler_enabled(&self) -> bool {
1576 self.target_config.values().any(|t| t.profiler == Some(true)) || self.profiler
1579 pub fn llvm_enabled(&self) -> bool {
1580 self.rust_codegen_backends.contains(&INTERNER.intern_str("llvm"))
1583 pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1586 .and_then(|t| t.llvm_libunwind)
1587 .or(self.llvm_libunwind_default)
1588 .unwrap_or(if target.contains("fuchsia") {
1589 LlvmLibunwind::InTree
1595 pub fn submodules(&self, rust_info: &GitInfo) -> bool {
1596 self.submodules.unwrap_or(rust_info.is_managed_git_subrepository())
1599 /// Returns the commit to download, or `None` if we shouldn't download CI artifacts.
1600 fn download_ci_rustc_commit(&self, download_rustc: Option<StringOrBool>) -> Option<String> {
1601 // If `download-rustc` is not set, default to rebuilding.
1602 let if_unchanged = match download_rustc {
1603 None | Some(StringOrBool::Bool(false)) => return None,
1604 Some(StringOrBool::Bool(true)) => false,
1605 Some(StringOrBool::String(s)) if s == "if-unchanged" => true,
1606 Some(StringOrBool::String(other)) => {
1607 panic!("unrecognized option for download-rustc: {}", other)
1611 // Handle running from a directory other than the top level
1612 let top_level = output(self.git().args(&["rev-parse", "--show-toplevel"]));
1613 let top_level = top_level.trim_end();
1614 let compiler = format!("{top_level}/compiler/");
1615 let library = format!("{top_level}/library/");
1617 // Look for a version to compare to based on the current commit.
1618 // Only commits merged by bors will have CI artifacts.
1619 let merge_base = output(
1622 .arg(format!("--author={}", self.stage0_metadata.config.git_merge_commit_email))
1623 .args(&["-n1", "--first-parent", "HEAD"]),
1625 let commit = merge_base.trim_end();
1626 if commit.is_empty() {
1627 println!("error: could not find commit hash for downloading rustc");
1628 println!("help: maybe your repository history is too shallow?");
1629 println!("help: consider disabling `download-rustc`");
1630 println!("help: or fetch enough history to include one upstream commit");
1631 crate::detail_exit(1);
1634 // Warn if there were changes to the compiler or standard library since the ancestor commit.
1635 let has_changes = !t!(self
1637 .args(&["diff-index", "--quiet", &commit, "--", &compiler, &library])
1642 if self.verbose > 0 {
1644 "warning: saw changes to compiler/ or library/ since {commit}; \
1645 ignoring `download-rustc`"
1651 "warning: `download-rustc` is enabled, but there are changes to \
1652 compiler/ or library/"
1656 Some(commit.to_string())
1660 fn set<T>(field: &mut T, val: Option<T>) {
1661 if let Some(v) = val {
1666 fn threads_from_config(v: u32) -> u32 {
1668 0 => std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32,