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