]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/config.rs
Auto merge of #97433 - GuillaumeGomez:rm-refcell-context, r=notriddle
[rust.git] / src / bootstrap / config.rs
1 //! Serialized configuration of a build.
2 //!
3 //! This module implements parsing `config.toml` configuration files to tweak
4 //! how the build runs.
5
6 use std::cell::Cell;
7 use std::cmp;
8 use std::collections::{HashMap, HashSet};
9 use std::env;
10 use std::fmt;
11 use std::fs;
12 use std::path::{Path, PathBuf};
13 use std::str::FromStr;
14
15 use crate::builder::{Builder, TaskPath};
16 use crate::cache::{Interned, INTERNER};
17 use crate::channel::GitInfo;
18 pub use crate::flags::Subcommand;
19 use crate::flags::{Color, Flags};
20 use crate::util::{exe, t};
21 use serde::{Deserialize, Deserializer};
22
23 macro_rules! check_ci_llvm {
24     ($name:expr) => {
25         assert!(
26             $name.is_none(),
27             "setting {} is incompatible with download-ci-llvm.",
28             stringify!($name)
29         );
30     };
31 }
32
33 /// Global configuration for the entire build and/or bootstrap.
34 ///
35 /// This structure is derived from a combination of both `config.toml` and
36 /// `config.mk`. As of the time of this writing it's unlikely that `config.toml`
37 /// is used all that much, so this is primarily filled out by `config.mk` which
38 /// is generated from `./configure`.
39 ///
40 /// Note that this structure is not decoded directly into, but rather it is
41 /// filled out from the decoded forms of the structs below. For documentation
42 /// each field, see the corresponding fields in
43 /// `config.toml.example`.
44 #[derive(Default)]
45 #[cfg_attr(test, derive(Clone))]
46 pub struct Config {
47     pub changelog_seen: Option<usize>,
48     pub ccache: Option<String>,
49     /// Call Build::ninja() instead of this.
50     pub ninja_in_file: bool,
51     pub verbose: usize,
52     pub submodules: Option<bool>,
53     pub compiler_docs: bool,
54     pub docs_minification: bool,
55     pub docs: bool,
56     pub locked_deps: bool,
57     pub vendor: bool,
58     pub target_config: HashMap<TargetSelection, Target>,
59     pub full_bootstrap: bool,
60     pub extended: bool,
61     pub tools: Option<HashSet<String>>,
62     pub sanitizers: bool,
63     pub profiler: bool,
64     pub ignore_git: bool,
65     pub exclude: Vec<TaskPath>,
66     pub include_default_paths: bool,
67     pub rustc_error_format: Option<String>,
68     pub json_output: bool,
69     pub test_compare_mode: bool,
70     pub color: Color,
71     pub patch_binaries_for_nix: bool,
72
73     pub on_fail: Option<String>,
74     pub stage: u32,
75     pub keep_stage: Vec<u32>,
76     pub keep_stage_std: Vec<u32>,
77     pub src: PathBuf,
78     /// defaults to `config.toml`
79     pub config: PathBuf,
80     pub jobs: Option<u32>,
81     pub cmd: Subcommand,
82     pub incremental: bool,
83     pub dry_run: bool,
84     pub download_rustc: bool,
85
86     pub deny_warnings: bool,
87     pub backtrace_on_ice: bool,
88
89     // llvm codegen options
90     pub llvm_skip_rebuild: bool,
91     pub llvm_assertions: bool,
92     pub llvm_tests: bool,
93     pub llvm_plugins: bool,
94     pub llvm_optimize: bool,
95     pub llvm_thin_lto: bool,
96     pub llvm_release_debuginfo: bool,
97     pub llvm_version_check: bool,
98     pub llvm_static_stdcpp: bool,
99     /// `None` if `llvm_from_ci` is true and we haven't yet downloaded llvm.
100     #[cfg(not(test))]
101     llvm_link_shared: Cell<Option<bool>>,
102     #[cfg(test)]
103     pub llvm_link_shared: Cell<Option<bool>>,
104     pub llvm_clang_cl: Option<String>,
105     pub llvm_targets: Option<String>,
106     pub llvm_experimental_targets: Option<String>,
107     pub llvm_link_jobs: Option<u32>,
108     pub llvm_version_suffix: Option<String>,
109     pub llvm_use_linker: Option<String>,
110     pub llvm_allow_old_toolchain: bool,
111     pub llvm_polly: bool,
112     pub llvm_clang: bool,
113     pub llvm_from_ci: bool,
114     pub llvm_build_config: HashMap<String, String>,
115
116     pub use_lld: bool,
117     pub lld_enabled: bool,
118     pub llvm_tools_enabled: bool,
119
120     pub llvm_cflags: Option<String>,
121     pub llvm_cxxflags: Option<String>,
122     pub llvm_ldflags: Option<String>,
123     pub llvm_use_libcxx: bool,
124
125     // rust codegen options
126     pub rust_optimize: bool,
127     pub rust_codegen_units: Option<u32>,
128     pub rust_codegen_units_std: Option<u32>,
129     pub rust_debug_assertions: bool,
130     pub rust_debug_assertions_std: bool,
131     pub rust_overflow_checks: bool,
132     pub rust_overflow_checks_std: bool,
133     pub rust_debug_logging: bool,
134     pub rust_debuginfo_level_rustc: u32,
135     pub rust_debuginfo_level_std: u32,
136     pub rust_debuginfo_level_tools: u32,
137     pub rust_debuginfo_level_tests: u32,
138     pub rust_split_debuginfo: SplitDebuginfo,
139     pub rust_rpath: bool,
140     pub rustc_parallel: bool,
141     pub rustc_default_linker: Option<String>,
142     pub rust_optimize_tests: bool,
143     pub rust_dist_src: bool,
144     pub rust_codegen_backends: Vec<Interned<String>>,
145     pub rust_verify_llvm_ir: bool,
146     pub rust_thin_lto_import_instr_limit: Option<u32>,
147     pub rust_remap_debuginfo: bool,
148     pub rust_new_symbol_mangling: Option<bool>,
149     pub rust_profile_use: Option<String>,
150     pub rust_profile_generate: Option<String>,
151     pub llvm_profile_use: Option<String>,
152     pub llvm_profile_generate: bool,
153     pub llvm_libunwind_default: Option<LlvmLibunwind>,
154
155     pub build: TargetSelection,
156     pub hosts: Vec<TargetSelection>,
157     pub targets: Vec<TargetSelection>,
158     pub local_rebuild: bool,
159     pub jemalloc: bool,
160     pub control_flow_guard: bool,
161
162     // dist misc
163     pub dist_sign_folder: Option<PathBuf>,
164     pub dist_upload_addr: Option<String>,
165     pub dist_compression_formats: Option<Vec<String>>,
166
167     // libstd features
168     pub backtrace: bool, // support for RUST_BACKTRACE
169
170     // misc
171     pub low_priority: bool,
172     pub channel: String,
173     pub description: Option<String>,
174     pub verbose_tests: bool,
175     pub save_toolstates: Option<PathBuf>,
176     pub print_step_timings: bool,
177     pub print_step_rusage: bool,
178     pub missing_tools: bool,
179
180     // Fallback musl-root for all targets
181     pub musl_root: Option<PathBuf>,
182     pub prefix: Option<PathBuf>,
183     pub sysconfdir: Option<PathBuf>,
184     pub datadir: Option<PathBuf>,
185     pub docdir: Option<PathBuf>,
186     pub bindir: PathBuf,
187     pub libdir: Option<PathBuf>,
188     pub mandir: Option<PathBuf>,
189     pub codegen_tests: bool,
190     pub nodejs: Option<PathBuf>,
191     pub npm: Option<PathBuf>,
192     pub gdb: Option<PathBuf>,
193     pub python: Option<PathBuf>,
194     pub cargo_native_static: bool,
195     pub configure_args: Vec<String>,
196
197     // These are either the stage0 downloaded binaries or the locally installed ones.
198     pub initial_cargo: PathBuf,
199     pub initial_rustc: PathBuf,
200     pub initial_rustfmt: Option<PathBuf>,
201     pub out: PathBuf,
202 }
203
204 #[derive(Debug, Clone, Copy, PartialEq)]
205 pub enum LlvmLibunwind {
206     No,
207     InTree,
208     System,
209 }
210
211 impl Default for LlvmLibunwind {
212     fn default() -> Self {
213         Self::No
214     }
215 }
216
217 impl FromStr for LlvmLibunwind {
218     type Err = String;
219
220     fn from_str(value: &str) -> Result<Self, Self::Err> {
221         match value {
222             "no" => Ok(Self::No),
223             "in-tree" => Ok(Self::InTree),
224             "system" => Ok(Self::System),
225             invalid => Err(format!("Invalid value '{}' for rust.llvm-libunwind config.", invalid)),
226         }
227     }
228 }
229
230 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
231 pub enum SplitDebuginfo {
232     Packed,
233     Unpacked,
234     Off,
235 }
236
237 impl Default for SplitDebuginfo {
238     fn default() -> Self {
239         SplitDebuginfo::Off
240     }
241 }
242
243 impl std::str::FromStr for SplitDebuginfo {
244     type Err = ();
245
246     fn from_str(s: &str) -> Result<Self, Self::Err> {
247         match s {
248             "packed" => Ok(SplitDebuginfo::Packed),
249             "unpacked" => Ok(SplitDebuginfo::Unpacked),
250             "off" => Ok(SplitDebuginfo::Off),
251             _ => Err(()),
252         }
253     }
254 }
255
256 impl SplitDebuginfo {
257     /// Returns the default `-Csplit-debuginfo` value for the current target. See the comment for
258     /// `rust.split-debuginfo` in `config.toml.example`.
259     fn default_for_platform(target: &str) -> Self {
260         if target.contains("apple") {
261             SplitDebuginfo::Unpacked
262         } else if target.contains("windows") {
263             SplitDebuginfo::Packed
264         } else {
265             SplitDebuginfo::Off
266         }
267     }
268 }
269
270 #[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
271 pub struct TargetSelection {
272     pub triple: Interned<String>,
273     file: Option<Interned<String>>,
274 }
275
276 impl TargetSelection {
277     pub fn from_user(selection: &str) -> Self {
278         let path = Path::new(selection);
279
280         let (triple, file) = if path.exists() {
281             let triple = path
282                 .file_stem()
283                 .expect("Target specification file has no file stem")
284                 .to_str()
285                 .expect("Target specification file stem is not UTF-8");
286
287             (triple, Some(selection))
288         } else {
289             (selection, None)
290         };
291
292         let triple = INTERNER.intern_str(triple);
293         let file = file.map(|f| INTERNER.intern_str(f));
294
295         Self { triple, file }
296     }
297
298     pub fn rustc_target_arg(&self) -> &str {
299         self.file.as_ref().unwrap_or(&self.triple)
300     }
301
302     pub fn contains(&self, needle: &str) -> bool {
303         self.triple.contains(needle)
304     }
305
306     pub fn starts_with(&self, needle: &str) -> bool {
307         self.triple.starts_with(needle)
308     }
309
310     pub fn ends_with(&self, needle: &str) -> bool {
311         self.triple.ends_with(needle)
312     }
313 }
314
315 impl fmt::Display for TargetSelection {
316     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317         write!(f, "{}", self.triple)?;
318         if let Some(file) = self.file {
319             write!(f, "({})", file)?;
320         }
321         Ok(())
322     }
323 }
324
325 impl fmt::Debug for TargetSelection {
326     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327         write!(f, "{}", self)
328     }
329 }
330
331 impl PartialEq<&str> for TargetSelection {
332     fn eq(&self, other: &&str) -> bool {
333         self.triple == *other
334     }
335 }
336
337 /// Per-target configuration stored in the global configuration structure.
338 #[derive(Default)]
339 #[cfg_attr(test, derive(Clone))]
340 pub struct Target {
341     /// Some(path to llvm-config) if using an external LLVM.
342     pub llvm_config: Option<PathBuf>,
343     /// Some(path to FileCheck) if one was specified.
344     pub llvm_filecheck: Option<PathBuf>,
345     pub llvm_libunwind: Option<LlvmLibunwind>,
346     pub cc: Option<PathBuf>,
347     pub cxx: Option<PathBuf>,
348     pub ar: Option<PathBuf>,
349     pub ranlib: Option<PathBuf>,
350     pub default_linker: Option<PathBuf>,
351     pub linker: Option<PathBuf>,
352     pub ndk: Option<PathBuf>,
353     pub sanitizers: Option<bool>,
354     pub profiler: Option<bool>,
355     pub crt_static: Option<bool>,
356     pub musl_root: Option<PathBuf>,
357     pub musl_libdir: Option<PathBuf>,
358     pub wasi_root: Option<PathBuf>,
359     pub qemu_rootfs: Option<PathBuf>,
360     pub no_std: bool,
361 }
362
363 impl Target {
364     pub fn from_triple(triple: &str) -> Self {
365         let mut target: Self = Default::default();
366         if triple.contains("-none") || triple.contains("nvptx") {
367             target.no_std = true;
368         }
369         target
370     }
371 }
372 /// Structure of the `config.toml` file that configuration is read from.
373 ///
374 /// This structure uses `Decodable` to automatically decode a TOML configuration
375 /// file into this format, and then this is traversed and written into the above
376 /// `Config` structure.
377 #[derive(Deserialize, Default)]
378 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
379 struct TomlConfig {
380     changelog_seen: Option<usize>,
381     build: Option<Build>,
382     install: Option<Install>,
383     llvm: Option<Llvm>,
384     rust: Option<Rust>,
385     target: Option<HashMap<String, TomlTarget>>,
386     dist: Option<Dist>,
387     profile: Option<String>,
388 }
389
390 trait Merge {
391     fn merge(&mut self, other: Self);
392 }
393
394 impl Merge for TomlConfig {
395     fn merge(
396         &mut self,
397         TomlConfig { build, install, llvm, rust, dist, target, profile: _, changelog_seen: _ }: Self,
398     ) {
399         fn do_merge<T: Merge>(x: &mut Option<T>, y: Option<T>) {
400             if let Some(new) = y {
401                 if let Some(original) = x {
402                     original.merge(new);
403                 } else {
404                     *x = Some(new);
405                 }
406             }
407         }
408         do_merge(&mut self.build, build);
409         do_merge(&mut self.install, install);
410         do_merge(&mut self.llvm, llvm);
411         do_merge(&mut self.rust, rust);
412         do_merge(&mut self.dist, dist);
413         assert!(target.is_none(), "merging target-specific config is not currently supported");
414     }
415 }
416
417 // We are using a decl macro instead of a derive proc macro here to reduce the compile time of
418 // rustbuild.
419 macro_rules! define_config {
420     ($(#[$attr:meta])* struct $name:ident {
421         $($field:ident: Option<$field_ty:ty> = $field_key:literal,)*
422     }) => {
423         $(#[$attr])*
424         struct $name {
425             $($field: Option<$field_ty>,)*
426         }
427
428         impl Merge for $name {
429             fn merge(&mut self, other: Self) {
430                 $(
431                     if !self.$field.is_some() {
432                         self.$field = other.$field;
433                     }
434                 )*
435             }
436         }
437
438         // The following is a trimmed version of what serde_derive generates. All parts not relevant
439         // for toml deserialization have been removed. This reduces the binary size and improves
440         // compile time of rustbuild.
441         impl<'de> Deserialize<'de> for $name {
442             fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
443             where
444                 D: Deserializer<'de>,
445             {
446                 struct Field;
447                 impl<'de> serde::de::Visitor<'de> for Field {
448                     type Value = $name;
449                     fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
450                         f.write_str(concat!("struct ", stringify!($name)))
451                     }
452
453                     #[inline]
454                     fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
455                     where
456                         A: serde::de::MapAccess<'de>,
457                     {
458                         $(let mut $field: Option<$field_ty> = None;)*
459                         while let Some(key) =
460                             match serde::de::MapAccess::next_key::<String>(&mut map) {
461                                 Ok(val) => val,
462                                 Err(err) => {
463                                     return Err(err);
464                                 }
465                             }
466                         {
467                             match &*key {
468                                 $($field_key => {
469                                     if $field.is_some() {
470                                         return Err(<A::Error as serde::de::Error>::duplicate_field(
471                                             $field_key,
472                                         ));
473                                     }
474                                     $field = match serde::de::MapAccess::next_value::<$field_ty>(
475                                         &mut map,
476                                     ) {
477                                         Ok(val) => Some(val),
478                                         Err(err) => {
479                                             return Err(err);
480                                         }
481                                     };
482                                 })*
483                                 key => {
484                                     return Err(serde::de::Error::unknown_field(key, FIELDS));
485                                 }
486                             }
487                         }
488                         Ok($name { $($field),* })
489                     }
490                 }
491                 const FIELDS: &'static [&'static str] = &[
492                     $($field_key,)*
493                 ];
494                 Deserializer::deserialize_struct(
495                     deserializer,
496                     stringify!($name),
497                     FIELDS,
498                     Field,
499                 )
500             }
501         }
502     }
503 }
504
505 define_config! {
506     /// TOML representation of various global build decisions.
507     #[derive(Default)]
508     struct Build {
509         build: Option<String> = "build",
510         host: Option<Vec<String>> = "host",
511         target: Option<Vec<String>> = "target",
512         build_dir: Option<String> = "build-dir",
513         cargo: Option<String> = "cargo",
514         rustc: Option<String> = "rustc",
515         rustfmt: Option<PathBuf> = "rustfmt",
516         docs: Option<bool> = "docs",
517         compiler_docs: Option<bool> = "compiler-docs",
518         docs_minification: Option<bool> = "docs-minification",
519         submodules: Option<bool> = "submodules",
520         gdb: Option<String> = "gdb",
521         nodejs: Option<String> = "nodejs",
522         npm: Option<String> = "npm",
523         python: Option<String> = "python",
524         locked_deps: Option<bool> = "locked-deps",
525         vendor: Option<bool> = "vendor",
526         full_bootstrap: Option<bool> = "full-bootstrap",
527         extended: Option<bool> = "extended",
528         tools: Option<HashSet<String>> = "tools",
529         verbose: Option<usize> = "verbose",
530         sanitizers: Option<bool> = "sanitizers",
531         profiler: Option<bool> = "profiler",
532         cargo_native_static: Option<bool> = "cargo-native-static",
533         low_priority: Option<bool> = "low-priority",
534         configure_args: Option<Vec<String>> = "configure-args",
535         local_rebuild: Option<bool> = "local-rebuild",
536         print_step_timings: Option<bool> = "print-step-timings",
537         print_step_rusage: Option<bool> = "print-step-rusage",
538         check_stage: Option<u32> = "check-stage",
539         doc_stage: Option<u32> = "doc-stage",
540         build_stage: Option<u32> = "build-stage",
541         test_stage: Option<u32> = "test-stage",
542         install_stage: Option<u32> = "install-stage",
543         dist_stage: Option<u32> = "dist-stage",
544         bench_stage: Option<u32> = "bench-stage",
545         patch_binaries_for_nix: Option<bool> = "patch-binaries-for-nix",
546     }
547 }
548
549 define_config! {
550     /// TOML representation of various global install decisions.
551     struct Install {
552         prefix: Option<String> = "prefix",
553         sysconfdir: Option<String> = "sysconfdir",
554         docdir: Option<String> = "docdir",
555         bindir: Option<String> = "bindir",
556         libdir: Option<String> = "libdir",
557         mandir: Option<String> = "mandir",
558         datadir: Option<String> = "datadir",
559     }
560 }
561
562 define_config! {
563     /// TOML representation of how the LLVM build is configured.
564     struct Llvm {
565         skip_rebuild: Option<bool> = "skip-rebuild",
566         optimize: Option<bool> = "optimize",
567         thin_lto: Option<bool> = "thin-lto",
568         release_debuginfo: Option<bool> = "release-debuginfo",
569         assertions: Option<bool> = "assertions",
570         tests: Option<bool> = "tests",
571         plugins: Option<bool> = "plugins",
572         ccache: Option<StringOrBool> = "ccache",
573         version_check: Option<bool> = "version-check",
574         static_libstdcpp: Option<bool> = "static-libstdcpp",
575         ninja: Option<bool> = "ninja",
576         targets: Option<String> = "targets",
577         experimental_targets: Option<String> = "experimental-targets",
578         link_jobs: Option<u32> = "link-jobs",
579         link_shared: Option<bool> = "link-shared",
580         version_suffix: Option<String> = "version-suffix",
581         clang_cl: Option<String> = "clang-cl",
582         cflags: Option<String> = "cflags",
583         cxxflags: Option<String> = "cxxflags",
584         ldflags: Option<String> = "ldflags",
585         use_libcxx: Option<bool> = "use-libcxx",
586         use_linker: Option<String> = "use-linker",
587         allow_old_toolchain: Option<bool> = "allow-old-toolchain",
588         polly: Option<bool> = "polly",
589         clang: Option<bool> = "clang",
590         download_ci_llvm: Option<StringOrBool> = "download-ci-llvm",
591         build_config: Option<HashMap<String, String>> = "build-config",
592     }
593 }
594
595 define_config! {
596     struct Dist {
597         sign_folder: Option<String> = "sign-folder",
598         gpg_password_file: Option<String> = "gpg-password-file",
599         upload_addr: Option<String> = "upload-addr",
600         src_tarball: Option<bool> = "src-tarball",
601         missing_tools: Option<bool> = "missing-tools",
602         compression_formats: Option<Vec<String>> = "compression-formats",
603     }
604 }
605
606 #[derive(Deserialize)]
607 #[serde(untagged)]
608 enum StringOrBool {
609     String(String),
610     Bool(bool),
611 }
612
613 impl Default for StringOrBool {
614     fn default() -> StringOrBool {
615         StringOrBool::Bool(false)
616     }
617 }
618
619 define_config! {
620     /// TOML representation of how the Rust build is configured.
621     struct Rust {
622         optimize: Option<bool> = "optimize",
623         debug: Option<bool> = "debug",
624         codegen_units: Option<u32> = "codegen-units",
625         codegen_units_std: Option<u32> = "codegen-units-std",
626         debug_assertions: Option<bool> = "debug-assertions",
627         debug_assertions_std: Option<bool> = "debug-assertions-std",
628         overflow_checks: Option<bool> = "overflow-checks",
629         overflow_checks_std: Option<bool> = "overflow-checks-std",
630         debug_logging: Option<bool> = "debug-logging",
631         debuginfo_level: Option<u32> = "debuginfo-level",
632         debuginfo_level_rustc: Option<u32> = "debuginfo-level-rustc",
633         debuginfo_level_std: Option<u32> = "debuginfo-level-std",
634         debuginfo_level_tools: Option<u32> = "debuginfo-level-tools",
635         debuginfo_level_tests: Option<u32> = "debuginfo-level-tests",
636         split_debuginfo: Option<String> = "split-debuginfo",
637         run_dsymutil: Option<bool> = "run-dsymutil",
638         backtrace: Option<bool> = "backtrace",
639         incremental: Option<bool> = "incremental",
640         parallel_compiler: Option<bool> = "parallel-compiler",
641         default_linker: Option<String> = "default-linker",
642         channel: Option<String> = "channel",
643         description: Option<String> = "description",
644         musl_root: Option<String> = "musl-root",
645         rpath: Option<bool> = "rpath",
646         verbose_tests: Option<bool> = "verbose-tests",
647         optimize_tests: Option<bool> = "optimize-tests",
648         codegen_tests: Option<bool> = "codegen-tests",
649         ignore_git: Option<bool> = "ignore-git",
650         dist_src: Option<bool> = "dist-src",
651         save_toolstates: Option<String> = "save-toolstates",
652         codegen_backends: Option<Vec<String>> = "codegen-backends",
653         lld: Option<bool> = "lld",
654         use_lld: Option<bool> = "use-lld",
655         llvm_tools: Option<bool> = "llvm-tools",
656         deny_warnings: Option<bool> = "deny-warnings",
657         backtrace_on_ice: Option<bool> = "backtrace-on-ice",
658         verify_llvm_ir: Option<bool> = "verify-llvm-ir",
659         thin_lto_import_instr_limit: Option<u32> = "thin-lto-import-instr-limit",
660         remap_debuginfo: Option<bool> = "remap-debuginfo",
661         jemalloc: Option<bool> = "jemalloc",
662         test_compare_mode: Option<bool> = "test-compare-mode",
663         llvm_libunwind: Option<String> = "llvm-libunwind",
664         control_flow_guard: Option<bool> = "control-flow-guard",
665         new_symbol_mangling: Option<bool> = "new-symbol-mangling",
666         profile_generate: Option<String> = "profile-generate",
667         profile_use: Option<String> = "profile-use",
668         // ignored; this is set from an env var set by bootstrap.py
669         download_rustc: Option<StringOrBool> = "download-rustc",
670     }
671 }
672
673 define_config! {
674     /// TOML representation of how each build target is configured.
675     struct TomlTarget {
676         cc: Option<String> = "cc",
677         cxx: Option<String> = "cxx",
678         ar: Option<String> = "ar",
679         ranlib: Option<String> = "ranlib",
680         default_linker: Option<PathBuf> = "default-linker",
681         linker: Option<String> = "linker",
682         llvm_config: Option<String> = "llvm-config",
683         llvm_filecheck: Option<String> = "llvm-filecheck",
684         llvm_libunwind: Option<String> = "llvm-libunwind",
685         android_ndk: Option<String> = "android-ndk",
686         sanitizers: Option<bool> = "sanitizers",
687         profiler: Option<bool> = "profiler",
688         crt_static: Option<bool> = "crt-static",
689         musl_root: Option<String> = "musl-root",
690         musl_libdir: Option<String> = "musl-libdir",
691         wasi_root: Option<String> = "wasi-root",
692         qemu_rootfs: Option<String> = "qemu-rootfs",
693         no_std: Option<bool> = "no-std",
694     }
695 }
696
697 impl Config {
698     pub fn default_opts() -> Config {
699         let mut config = Config::default();
700         config.llvm_optimize = true;
701         config.ninja_in_file = true;
702         config.llvm_version_check = true;
703         config.llvm_static_stdcpp = true;
704         config.backtrace = true;
705         config.rust_optimize = true;
706         config.rust_optimize_tests = true;
707         config.submodules = None;
708         config.docs = true;
709         config.docs_minification = true;
710         config.rust_rpath = true;
711         config.channel = "dev".to_string();
712         config.codegen_tests = true;
713         config.rust_dist_src = true;
714         config.rust_codegen_backends = vec![INTERNER.intern_str("llvm")];
715         config.deny_warnings = true;
716         config.bindir = "bin".into();
717
718         // set by build.rs
719         config.build = TargetSelection::from_user(&env!("BUILD_TRIPLE"));
720         let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
721         // Undo `src/bootstrap`
722         config.src = manifest_dir.parent().unwrap().parent().unwrap().to_owned();
723         config.out = PathBuf::from("build");
724
725         config.initial_cargo = PathBuf::from(env!("CARGO"));
726         config.initial_rustc = PathBuf::from(env!("RUSTC"));
727
728         config
729     }
730
731     pub fn parse(args: &[String]) -> Config {
732         let flags = Flags::parse(&args);
733
734         let mut config = Config::default_opts();
735         config.exclude = flags.exclude.into_iter().map(|path| TaskPath::parse(path)).collect();
736         config.include_default_paths = flags.include_default_paths;
737         config.rustc_error_format = flags.rustc_error_format;
738         config.json_output = flags.json_output;
739         config.on_fail = flags.on_fail;
740         config.jobs = flags.jobs.map(threads_from_config);
741         config.cmd = flags.cmd;
742         config.incremental = flags.incremental;
743         config.dry_run = flags.dry_run;
744         config.keep_stage = flags.keep_stage;
745         config.keep_stage_std = flags.keep_stage_std;
746         config.color = flags.color;
747         if let Some(value) = flags.deny_warnings {
748             config.deny_warnings = value;
749         }
750         config.llvm_profile_use = flags.llvm_profile_use;
751         config.llvm_profile_generate = flags.llvm_profile_generate;
752
753         #[cfg(test)]
754         let get_toml = |_| TomlConfig::default();
755         #[cfg(not(test))]
756         let get_toml = |file: &Path| {
757             use std::process;
758
759             let contents =
760                 t!(fs::read_to_string(file), format!("config file {} not found", file.display()));
761             // Deserialize to Value and then TomlConfig to prevent the Deserialize impl of
762             // TomlConfig and sub types to be monomorphized 5x by toml.
763             match toml::from_str(&contents)
764                 .and_then(|table: toml::Value| TomlConfig::deserialize(table))
765             {
766                 Ok(table) => table,
767                 Err(err) => {
768                     eprintln!("failed to parse TOML configuration '{}': {}", file.display(), err);
769                     process::exit(2);
770                 }
771             }
772         };
773
774         // Read from `--config`, then `RUST_BOOTSTRAP_CONFIG`, then `./config.toml`, then `config.toml` in the root directory.
775         let toml_path = flags
776             .config
777             .clone()
778             .or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
779         let using_default_path = toml_path.is_none();
780         let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("config.toml"));
781         if using_default_path && !toml_path.exists() {
782             toml_path = config.src.join(toml_path);
783         }
784
785         // Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path,
786         // but not if `config.toml` hasn't been created.
787         let mut toml = if !using_default_path || toml_path.exists() {
788             get_toml(&toml_path)
789         } else {
790             TomlConfig::default()
791         };
792
793         if let Some(include) = &toml.profile {
794             let mut include_path = config.src.clone();
795             include_path.push("src");
796             include_path.push("bootstrap");
797             include_path.push("defaults");
798             include_path.push(format!("config.{}.toml", include));
799             let included_toml = get_toml(&include_path);
800             toml.merge(included_toml);
801         }
802
803         config.changelog_seen = toml.changelog_seen;
804         config.config = toml_path;
805
806         let build = toml.build.unwrap_or_default();
807
808         set(&mut config.initial_rustc, build.rustc.map(PathBuf::from));
809         set(&mut config.out, build.build_dir.map(PathBuf::from));
810         // NOTE: Bootstrap spawns various commands with different working directories.
811         // To avoid writing to random places on the file system, `config.out` needs to be an absolute path.
812         if !config.out.is_absolute() {
813             // `canonicalize` requires the path to already exist. Use our vendored copy of `absolute` instead.
814             config.out = crate::util::absolute(&config.out);
815         }
816
817         if config.dry_run {
818             let dir = config.out.join("tmp-dry-run");
819             t!(fs::create_dir_all(&dir));
820             config.out = dir;
821         }
822
823         config.hosts = if let Some(arg_host) = flags.host {
824             arg_host
825         } else if let Some(file_host) = build.host {
826             file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
827         } else {
828             vec![config.build]
829         };
830         config.targets = if let Some(arg_target) = flags.target {
831             arg_target
832         } else if let Some(file_target) = build.target {
833             file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
834         } else {
835             // If target is *not* configured, then default to the host
836             // toolchains.
837             config.hosts.clone()
838         };
839
840         config.nodejs = build.nodejs.map(PathBuf::from);
841         config.npm = build.npm.map(PathBuf::from);
842         config.gdb = build.gdb.map(PathBuf::from);
843         config.python = build.python.map(PathBuf::from);
844         config.submodules = build.submodules;
845         set(&mut config.low_priority, build.low_priority);
846         set(&mut config.compiler_docs, build.compiler_docs);
847         set(&mut config.docs_minification, build.docs_minification);
848         set(&mut config.docs, build.docs);
849         set(&mut config.locked_deps, build.locked_deps);
850         set(&mut config.vendor, build.vendor);
851         set(&mut config.full_bootstrap, build.full_bootstrap);
852         set(&mut config.extended, build.extended);
853         config.tools = build.tools;
854         if build.rustfmt.is_some() {
855             config.initial_rustfmt = build.rustfmt;
856         }
857         set(&mut config.verbose, build.verbose);
858         set(&mut config.sanitizers, build.sanitizers);
859         set(&mut config.profiler, build.profiler);
860         set(&mut config.cargo_native_static, build.cargo_native_static);
861         set(&mut config.configure_args, build.configure_args);
862         set(&mut config.local_rebuild, build.local_rebuild);
863         set(&mut config.print_step_timings, build.print_step_timings);
864         set(&mut config.print_step_rusage, build.print_step_rusage);
865         set(&mut config.patch_binaries_for_nix, build.patch_binaries_for_nix);
866
867         config.verbose = cmp::max(config.verbose, flags.verbose);
868
869         if let Some(install) = toml.install {
870             config.prefix = install.prefix.map(PathBuf::from);
871             config.sysconfdir = install.sysconfdir.map(PathBuf::from);
872             config.datadir = install.datadir.map(PathBuf::from);
873             config.docdir = install.docdir.map(PathBuf::from);
874             set(&mut config.bindir, install.bindir.map(PathBuf::from));
875             config.libdir = install.libdir.map(PathBuf::from);
876             config.mandir = install.mandir.map(PathBuf::from);
877         }
878
879         // We want the llvm-skip-rebuild flag to take precedence over the
880         // skip-rebuild config.toml option so we store it separately
881         // so that we can infer the right value
882         let mut llvm_skip_rebuild = flags.llvm_skip_rebuild;
883
884         // Store off these values as options because if they're not provided
885         // we'll infer default values for them later
886         let mut llvm_assertions = None;
887         let mut llvm_tests = None;
888         let mut llvm_plugins = None;
889         let mut debug = None;
890         let mut debug_assertions = None;
891         let mut debug_assertions_std = None;
892         let mut overflow_checks = None;
893         let mut overflow_checks_std = None;
894         let mut debug_logging = None;
895         let mut debuginfo_level = None;
896         let mut debuginfo_level_rustc = None;
897         let mut debuginfo_level_std = None;
898         let mut debuginfo_level_tools = None;
899         let mut debuginfo_level_tests = None;
900         let mut optimize = None;
901         let mut ignore_git = None;
902
903         if let Some(llvm) = toml.llvm {
904             match llvm.ccache {
905                 Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
906                 Some(StringOrBool::Bool(true)) => {
907                     config.ccache = Some("ccache".to_string());
908                 }
909                 Some(StringOrBool::Bool(false)) | None => {}
910             }
911             set(&mut config.ninja_in_file, llvm.ninja);
912             llvm_assertions = llvm.assertions;
913             llvm_tests = llvm.tests;
914             llvm_plugins = llvm.plugins;
915             llvm_skip_rebuild = llvm_skip_rebuild.or(llvm.skip_rebuild);
916             set(&mut config.llvm_optimize, llvm.optimize);
917             set(&mut config.llvm_thin_lto, llvm.thin_lto);
918             set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
919             set(&mut config.llvm_version_check, llvm.version_check);
920             set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp);
921             if let Some(v) = llvm.link_shared {
922                 config.llvm_link_shared.set(Some(v));
923             }
924             config.llvm_targets = llvm.targets.clone();
925             config.llvm_experimental_targets = llvm.experimental_targets.clone();
926             config.llvm_link_jobs = llvm.link_jobs;
927             config.llvm_version_suffix = llvm.version_suffix.clone();
928             config.llvm_clang_cl = llvm.clang_cl.clone();
929
930             config.llvm_cflags = llvm.cflags.clone();
931             config.llvm_cxxflags = llvm.cxxflags.clone();
932             config.llvm_ldflags = llvm.ldflags.clone();
933             set(&mut config.llvm_use_libcxx, llvm.use_libcxx);
934             config.llvm_use_linker = llvm.use_linker.clone();
935             config.llvm_allow_old_toolchain = llvm.allow_old_toolchain.unwrap_or(false);
936             config.llvm_polly = llvm.polly.unwrap_or(false);
937             config.llvm_clang = llvm.clang.unwrap_or(false);
938             config.llvm_build_config = llvm.build_config.clone().unwrap_or(Default::default());
939             config.llvm_from_ci = match llvm.download_ci_llvm {
940                 Some(StringOrBool::String(s)) => {
941                     assert!(s == "if-available", "unknown option `{}` for download-ci-llvm", s);
942                     // This is currently all tier 1 targets and tier 2 targets with host tools
943                     // (since others may not have CI artifacts)
944                     // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
945                     // FIXME: this is duplicated in bootstrap.py
946                     let supported_platforms = [
947                         // tier 1
948                         "aarch64-unknown-linux-gnu",
949                         "i686-pc-windows-gnu",
950                         "i686-pc-windows-msvc",
951                         "i686-unknown-linux-gnu",
952                         "x86_64-unknown-linux-gnu",
953                         "x86_64-apple-darwin",
954                         "x86_64-pc-windows-gnu",
955                         "x86_64-pc-windows-msvc",
956                         // tier 2 with host tools
957                         "aarch64-apple-darwin",
958                         "aarch64-pc-windows-msvc",
959                         "aarch64-unknown-linux-musl",
960                         "arm-unknown-linux-gnueabi",
961                         "arm-unknown-linux-gnueabihf",
962                         "armv7-unknown-linux-gnueabihf",
963                         "mips-unknown-linux-gnu",
964                         "mips64-unknown-linux-gnuabi64",
965                         "mips64el-unknown-linux-gnuabi64",
966                         "mipsel-unknown-linux-gnu",
967                         "powerpc-unknown-linux-gnu",
968                         "powerpc64-unknown-linux-gnu",
969                         "powerpc64le-unknown-linux-gnu",
970                         "riscv64gc-unknown-linux-gnu",
971                         "s390x-unknown-linux-gnu",
972                         "x86_64-unknown-freebsd",
973                         "x86_64-unknown-illumos",
974                         "x86_64-unknown-linux-musl",
975                         "x86_64-unknown-netbsd",
976                     ];
977                     supported_platforms.contains(&&*config.build.triple)
978                 }
979                 Some(StringOrBool::Bool(b)) => b,
980                 None => false,
981             };
982
983             if config.llvm_from_ci {
984                 // None of the LLVM options, except assertions, are supported
985                 // when using downloaded LLVM. We could just ignore these but
986                 // that's potentially confusing, so force them to not be
987                 // explicitly set. The defaults and CI defaults don't
988                 // necessarily match but forcing people to match (somewhat
989                 // arbitrary) CI configuration locally seems bad/hard.
990                 check_ci_llvm!(llvm.optimize);
991                 check_ci_llvm!(llvm.thin_lto);
992                 check_ci_llvm!(llvm.release_debuginfo);
993                 // CI-built LLVM can be either dynamic or static. We won't know until we download it.
994                 check_ci_llvm!(llvm.link_shared);
995                 check_ci_llvm!(llvm.static_libstdcpp);
996                 check_ci_llvm!(llvm.targets);
997                 check_ci_llvm!(llvm.experimental_targets);
998                 check_ci_llvm!(llvm.link_jobs);
999                 check_ci_llvm!(llvm.clang_cl);
1000                 check_ci_llvm!(llvm.version_suffix);
1001                 check_ci_llvm!(llvm.cflags);
1002                 check_ci_llvm!(llvm.cxxflags);
1003                 check_ci_llvm!(llvm.ldflags);
1004                 check_ci_llvm!(llvm.use_libcxx);
1005                 check_ci_llvm!(llvm.use_linker);
1006                 check_ci_llvm!(llvm.allow_old_toolchain);
1007                 check_ci_llvm!(llvm.polly);
1008                 check_ci_llvm!(llvm.clang);
1009                 check_ci_llvm!(llvm.build_config);
1010                 check_ci_llvm!(llvm.plugins);
1011             }
1012
1013             // NOTE: can never be hit when downloading from CI, since we call `check_ci_llvm!(thin_lto)` above.
1014             if config.llvm_thin_lto && llvm.link_shared.is_none() {
1015                 // If we're building with ThinLTO on, by default we want to link
1016                 // to LLVM shared, to avoid re-doing ThinLTO (which happens in
1017                 // the link step) with each stage.
1018                 config.llvm_link_shared.set(Some(true));
1019             }
1020         }
1021
1022         if let Some(rust) = toml.rust {
1023             debug = rust.debug;
1024             debug_assertions = rust.debug_assertions;
1025             debug_assertions_std = rust.debug_assertions_std;
1026             overflow_checks = rust.overflow_checks;
1027             overflow_checks_std = rust.overflow_checks_std;
1028             debug_logging = rust.debug_logging;
1029             debuginfo_level = rust.debuginfo_level;
1030             debuginfo_level_rustc = rust.debuginfo_level_rustc;
1031             debuginfo_level_std = rust.debuginfo_level_std;
1032             debuginfo_level_tools = rust.debuginfo_level_tools;
1033             debuginfo_level_tests = rust.debuginfo_level_tests;
1034             config.rust_split_debuginfo = rust
1035                 .split_debuginfo
1036                 .as_deref()
1037                 .map(SplitDebuginfo::from_str)
1038                 .map(|v| v.expect("invalid value for rust.split_debuginfo"))
1039                 .unwrap_or(SplitDebuginfo::default_for_platform(&config.build.triple));
1040             optimize = rust.optimize;
1041             ignore_git = rust.ignore_git;
1042             config.rust_new_symbol_mangling = rust.new_symbol_mangling;
1043             set(&mut config.rust_optimize_tests, rust.optimize_tests);
1044             set(&mut config.codegen_tests, rust.codegen_tests);
1045             set(&mut config.rust_rpath, rust.rpath);
1046             set(&mut config.jemalloc, rust.jemalloc);
1047             set(&mut config.test_compare_mode, rust.test_compare_mode);
1048             set(&mut config.backtrace, rust.backtrace);
1049             set(&mut config.channel, rust.channel);
1050             config.description = rust.description;
1051             set(&mut config.rust_dist_src, rust.dist_src);
1052             set(&mut config.verbose_tests, rust.verbose_tests);
1053             // in the case "false" is set explicitly, do not overwrite the command line args
1054             if let Some(true) = rust.incremental {
1055                 config.incremental = true;
1056             }
1057             set(&mut config.use_lld, rust.use_lld);
1058             set(&mut config.lld_enabled, rust.lld);
1059             set(&mut config.llvm_tools_enabled, rust.llvm_tools);
1060             config.rustc_parallel = rust.parallel_compiler.unwrap_or(false);
1061             config.rustc_default_linker = rust.default_linker;
1062             config.musl_root = rust.musl_root.map(PathBuf::from);
1063             config.save_toolstates = rust.save_toolstates.map(PathBuf::from);
1064             set(&mut config.deny_warnings, flags.deny_warnings.or(rust.deny_warnings));
1065             set(&mut config.backtrace_on_ice, rust.backtrace_on_ice);
1066             set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir);
1067             config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit;
1068             set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo);
1069             set(&mut config.control_flow_guard, rust.control_flow_guard);
1070             config.llvm_libunwind_default = rust
1071                 .llvm_libunwind
1072                 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
1073
1074             if let Some(ref backends) = rust.codegen_backends {
1075                 config.rust_codegen_backends =
1076                     backends.iter().map(|s| INTERNER.intern_str(s)).collect();
1077             }
1078
1079             config.rust_codegen_units = rust.codegen_units.map(threads_from_config);
1080             config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config);
1081             config.rust_profile_use = flags.rust_profile_use.or(rust.profile_use);
1082             config.rust_profile_generate = flags.rust_profile_generate.or(rust.profile_generate);
1083             config.download_rustc = env::var("BOOTSTRAP_DOWNLOAD_RUSTC").as_deref() == Ok("1");
1084         } else {
1085             config.rust_profile_use = flags.rust_profile_use;
1086             config.rust_profile_generate = flags.rust_profile_generate;
1087         }
1088
1089         if let Some(t) = toml.target {
1090             for (triple, cfg) in t {
1091                 let mut target = Target::from_triple(&triple);
1092
1093                 if let Some(ref s) = cfg.llvm_config {
1094                     target.llvm_config = Some(config.src.join(s));
1095                 }
1096                 if let Some(ref s) = cfg.llvm_filecheck {
1097                     target.llvm_filecheck = Some(config.src.join(s));
1098                 }
1099                 target.llvm_libunwind = cfg
1100                     .llvm_libunwind
1101                     .as_ref()
1102                     .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
1103                 if let Some(ref s) = cfg.android_ndk {
1104                     target.ndk = Some(config.src.join(s));
1105                 }
1106                 if let Some(s) = cfg.no_std {
1107                     target.no_std = s;
1108                 }
1109                 target.cc = cfg.cc.map(PathBuf::from);
1110                 target.cxx = cfg.cxx.map(PathBuf::from);
1111                 target.ar = cfg.ar.map(PathBuf::from);
1112                 target.ranlib = cfg.ranlib.map(PathBuf::from);
1113                 target.linker = cfg.linker.map(PathBuf::from);
1114                 target.crt_static = cfg.crt_static;
1115                 target.musl_root = cfg.musl_root.map(PathBuf::from);
1116                 target.musl_libdir = cfg.musl_libdir.map(PathBuf::from);
1117                 target.wasi_root = cfg.wasi_root.map(PathBuf::from);
1118                 target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from);
1119                 target.sanitizers = cfg.sanitizers;
1120                 target.profiler = cfg.profiler;
1121
1122                 config.target_config.insert(TargetSelection::from_user(&triple), target);
1123             }
1124         }
1125
1126         if config.llvm_from_ci {
1127             let triple = &config.build.triple;
1128             let mut build_target = config
1129                 .target_config
1130                 .entry(config.build)
1131                 .or_insert_with(|| Target::from_triple(&triple));
1132
1133             check_ci_llvm!(build_target.llvm_config);
1134             check_ci_llvm!(build_target.llvm_filecheck);
1135             let ci_llvm_bin = config.out.join(&*config.build.triple).join("ci-llvm/bin");
1136             build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", config.build)));
1137             build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", config.build)));
1138         }
1139
1140         if let Some(t) = toml.dist {
1141             config.dist_sign_folder = t.sign_folder.map(PathBuf::from);
1142             config.dist_upload_addr = t.upload_addr;
1143             config.dist_compression_formats = t.compression_formats;
1144             set(&mut config.rust_dist_src, t.src_tarball);
1145             set(&mut config.missing_tools, t.missing_tools);
1146         }
1147
1148         config.initial_rustfmt = config.initial_rustfmt.or_else({
1149             let build = config.build;
1150             let initial_rustc = &config.initial_rustc;
1151
1152             move || {
1153                 // Cargo does not provide a RUSTFMT environment variable, so we
1154                 // synthesize it manually.
1155                 let rustfmt = initial_rustc.with_file_name(exe("rustfmt", build));
1156
1157                 if rustfmt.exists() { Some(rustfmt) } else { None }
1158             }
1159         });
1160
1161         // Now that we've reached the end of our configuration, infer the
1162         // default values for all options that we haven't otherwise stored yet.
1163
1164         config.llvm_skip_rebuild = llvm_skip_rebuild.unwrap_or(false);
1165         config.llvm_assertions = llvm_assertions.unwrap_or(false);
1166         config.llvm_tests = llvm_tests.unwrap_or(false);
1167         config.llvm_plugins = llvm_plugins.unwrap_or(false);
1168         config.rust_optimize = optimize.unwrap_or(true);
1169
1170         let default = debug == Some(true);
1171         config.rust_debug_assertions = debug_assertions.unwrap_or(default);
1172         config.rust_debug_assertions_std =
1173             debug_assertions_std.unwrap_or(config.rust_debug_assertions);
1174         config.rust_overflow_checks = overflow_checks.unwrap_or(default);
1175         config.rust_overflow_checks_std =
1176             overflow_checks_std.unwrap_or(config.rust_overflow_checks);
1177
1178         config.rust_debug_logging = debug_logging.unwrap_or(config.rust_debug_assertions);
1179
1180         let with_defaults = |debuginfo_level_specific: Option<u32>| {
1181             debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
1182                 1
1183             } else {
1184                 0
1185             })
1186         };
1187         config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
1188         config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
1189         config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
1190         config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(0);
1191
1192         let default = config.channel == "dev";
1193         config.ignore_git = ignore_git.unwrap_or(default);
1194
1195         let download_rustc = config.download_rustc;
1196         // See https://github.com/rust-lang/compiler-team/issues/326
1197         config.stage = match config.cmd {
1198             Subcommand::Check { .. } => flags.stage.or(build.check_stage).unwrap_or(0),
1199             // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden.
1200             Subcommand::Doc { .. } => {
1201                 flags.stage.or(build.doc_stage).unwrap_or(if download_rustc { 2 } else { 0 })
1202             }
1203             Subcommand::Build { .. } => {
1204                 flags.stage.or(build.build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1205             }
1206             Subcommand::Test { .. } => {
1207                 flags.stage.or(build.test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1208             }
1209             Subcommand::Bench { .. } => flags.stage.or(build.bench_stage).unwrap_or(2),
1210             Subcommand::Dist { .. } => flags.stage.or(build.dist_stage).unwrap_or(2),
1211             Subcommand::Install { .. } => flags.stage.or(build.install_stage).unwrap_or(2),
1212             // These are all bootstrap tools, which don't depend on the compiler.
1213             // The stage we pass shouldn't matter, but use 0 just in case.
1214             Subcommand::Clean { .. }
1215             | Subcommand::Clippy { .. }
1216             | Subcommand::Fix { .. }
1217             | Subcommand::Run { .. }
1218             | Subcommand::Setup { .. }
1219             | Subcommand::Format { .. } => flags.stage.unwrap_or(0),
1220         };
1221
1222         // CI should always run stage 2 builds, unless it specifically states otherwise
1223         #[cfg(not(test))]
1224         if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None {
1225             match config.cmd {
1226                 Subcommand::Test { .. }
1227                 | Subcommand::Doc { .. }
1228                 | Subcommand::Build { .. }
1229                 | Subcommand::Bench { .. }
1230                 | Subcommand::Dist { .. }
1231                 | Subcommand::Install { .. } => {
1232                     assert_eq!(
1233                         config.stage, 2,
1234                         "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
1235                         config.stage,
1236                     );
1237                 }
1238                 Subcommand::Clean { .. }
1239                 | Subcommand::Check { .. }
1240                 | Subcommand::Clippy { .. }
1241                 | Subcommand::Fix { .. }
1242                 | Subcommand::Run { .. }
1243                 | Subcommand::Setup { .. }
1244                 | Subcommand::Format { .. } => {}
1245             }
1246         }
1247
1248         config
1249     }
1250
1251     /// Try to find the relative path of `bindir`, otherwise return it in full.
1252     pub fn bindir_relative(&self) -> &Path {
1253         let bindir = &self.bindir;
1254         if bindir.is_absolute() {
1255             // Try to make it relative to the prefix.
1256             if let Some(prefix) = &self.prefix {
1257                 if let Ok(stripped) = bindir.strip_prefix(prefix) {
1258                     return stripped;
1259                 }
1260             }
1261         }
1262         bindir
1263     }
1264
1265     /// Try to find the relative path of `libdir`.
1266     pub fn libdir_relative(&self) -> Option<&Path> {
1267         let libdir = self.libdir.as_ref()?;
1268         if libdir.is_relative() {
1269             Some(libdir)
1270         } else {
1271             // Try to make it relative to the prefix.
1272             libdir.strip_prefix(self.prefix.as_ref()?).ok()
1273         }
1274     }
1275
1276     /// The absolute path to the downloaded LLVM artifacts.
1277     pub(crate) fn ci_llvm_root(&self) -> PathBuf {
1278         assert!(self.llvm_from_ci);
1279         self.out.join(&*self.build.triple).join("ci-llvm")
1280     }
1281
1282     /// Determine whether llvm should be linked dynamically.
1283     ///
1284     /// If `false`, llvm should be linked statically.
1285     /// This is computed on demand since LLVM might have to first be downloaded from CI.
1286     pub(crate) fn llvm_link_shared(builder: &Builder<'_>) -> bool {
1287         let mut opt = builder.config.llvm_link_shared.get();
1288         if opt.is_none() && builder.config.dry_run {
1289             // just assume static for now - dynamic linking isn't supported on all platforms
1290             return false;
1291         }
1292
1293         let llvm_link_shared = *opt.get_or_insert_with(|| {
1294             if builder.config.llvm_from_ci {
1295                 crate::native::maybe_download_ci_llvm(builder);
1296                 let ci_llvm = builder.config.ci_llvm_root();
1297                 let link_type = t!(
1298                     std::fs::read_to_string(ci_llvm.join("link-type.txt")),
1299                     format!("CI llvm missing: {}", ci_llvm.display())
1300                 );
1301                 link_type == "dynamic"
1302             } else {
1303                 // unclear how thought-through this default is, but it maintains compatibility with
1304                 // previous behavior
1305                 false
1306             }
1307         });
1308         builder.config.llvm_link_shared.set(opt);
1309         llvm_link_shared
1310     }
1311
1312     pub fn verbose(&self) -> bool {
1313         self.verbose > 0
1314     }
1315
1316     pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1317         self.target_config.get(&target).map(|t| t.sanitizers).flatten().unwrap_or(self.sanitizers)
1318     }
1319
1320     pub fn any_sanitizers_enabled(&self) -> bool {
1321         self.target_config.values().any(|t| t.sanitizers == Some(true)) || self.sanitizers
1322     }
1323
1324     pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1325         self.target_config.get(&target).map(|t| t.profiler).flatten().unwrap_or(self.profiler)
1326     }
1327
1328     pub fn any_profiler_enabled(&self) -> bool {
1329         self.target_config.values().any(|t| t.profiler == Some(true)) || self.profiler
1330     }
1331
1332     pub fn llvm_enabled(&self) -> bool {
1333         self.rust_codegen_backends.contains(&INTERNER.intern_str("llvm"))
1334     }
1335
1336     pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1337         self.target_config
1338             .get(&target)
1339             .and_then(|t| t.llvm_libunwind)
1340             .or(self.llvm_libunwind_default)
1341             .unwrap_or(LlvmLibunwind::No)
1342     }
1343
1344     pub fn submodules(&self, rust_info: &GitInfo) -> bool {
1345         self.submodules.unwrap_or(rust_info.is_git())
1346     }
1347 }
1348
1349 fn set<T>(field: &mut T, val: Option<T>) {
1350     if let Some(v) = val {
1351         *field = v;
1352     }
1353 }
1354
1355 fn threads_from_config(v: u32) -> u32 {
1356     match v {
1357         0 => std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32,
1358         n => n,
1359     }
1360 }