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