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