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