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