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