]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/config.rs
Auto merge of #93668 - SUPERCILEX:path_alloc, r=joshtriplett
[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             let src = match s.strip_prefix("\\\\?\\") {
833                 Some(p) => PathBuf::from(p),
834                 None => PathBuf::from(git_root),
835             };
836             // If this doesn't have at least `stage0.json`, we guessed wrong. This can happen when,
837             // for example, the build directory is inside of another unrelated git directory.
838             // In that case keep the original `CARGO_MANIFEST_DIR` handling.
839             //
840             // NOTE: this implies that downloadable bootstrap isn't supported when the build directory is outside
841             // the source directory. We could fix that by setting a variable from all three of python, ./x, and x.ps1.
842             if src.join("src").join("stage0.json").exists() {
843                 config.src = src;
844             }
845         } else {
846             // We're building from a tarball, not git sources.
847             // We don't support pre-downloaded bootstrap in this case.
848         }
849
850         if cfg!(test) {
851             // Use the build directory of the original x.py invocation, so that we can set `initial_rustc` properly.
852             config.out = Path::new(
853                 &env::var_os("CARGO_TARGET_DIR").expect("cargo test directly is not supported"),
854             )
855             .parent()
856             .unwrap()
857             .to_path_buf();
858         }
859
860         let stage0_json = t!(std::fs::read(&config.src.join("src").join("stage0.json")));
861
862         config.stage0_metadata = t!(serde_json::from_slice::<Stage0Metadata>(&stage0_json));
863
864         #[cfg(test)]
865         let get_toml = |_| TomlConfig::default();
866         #[cfg(not(test))]
867         let get_toml = |file: &Path| {
868             let contents =
869                 t!(fs::read_to_string(file), format!("config file {} not found", file.display()));
870             // Deserialize to Value and then TomlConfig to prevent the Deserialize impl of
871             // TomlConfig and sub types to be monomorphized 5x by toml.
872             match toml::from_str(&contents)
873                 .and_then(|table: toml::Value| TomlConfig::deserialize(table))
874             {
875                 Ok(table) => table,
876                 Err(err) => {
877                     eprintln!("failed to parse TOML configuration '{}': {}", file.display(), err);
878                     crate::detail_exit(2);
879                 }
880             }
881         };
882
883         // Read from `--config`, then `RUST_BOOTSTRAP_CONFIG`, then `./config.toml`, then `config.toml` in the root directory.
884         let toml_path = flags
885             .config
886             .clone()
887             .or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
888         let using_default_path = toml_path.is_none();
889         let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("config.toml"));
890         if using_default_path && !toml_path.exists() {
891             toml_path = config.src.join(toml_path);
892         }
893
894         // Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path,
895         // but not if `config.toml` hasn't been created.
896         let mut toml = if !using_default_path || toml_path.exists() {
897             get_toml(&toml_path)
898         } else {
899             TomlConfig::default()
900         };
901
902         if let Some(include) = &toml.profile {
903             let mut include_path = config.src.clone();
904             include_path.push("src");
905             include_path.push("bootstrap");
906             include_path.push("defaults");
907             include_path.push(format!("config.{}.toml", include));
908             let included_toml = get_toml(&include_path);
909             toml.merge(included_toml);
910         }
911
912         config.changelog_seen = toml.changelog_seen;
913         config.config = toml_path;
914
915         let build = toml.build.unwrap_or_default();
916
917         set(&mut config.out, flags.build_dir.or_else(|| build.build_dir.map(PathBuf::from)));
918         // NOTE: Bootstrap spawns various commands with different working directories.
919         // To avoid writing to random places on the file system, `config.out` needs to be an absolute path.
920         if !config.out.is_absolute() {
921             // `canonicalize` requires the path to already exist. Use our vendored copy of `absolute` instead.
922             config.out = crate::util::absolute(&config.out);
923         }
924
925         config.initial_rustc = build
926             .rustc
927             .map(PathBuf::from)
928             .unwrap_or_else(|| config.out.join(config.build.triple).join("stage0/bin/rustc"));
929         config.initial_cargo = build
930             .cargo
931             .map(PathBuf::from)
932             .unwrap_or_else(|| config.out.join(config.build.triple).join("stage0/bin/cargo"));
933
934         // NOTE: it's important this comes *after* we set `initial_rustc` just above.
935         if config.dry_run {
936             let dir = config.out.join("tmp-dry-run");
937             t!(fs::create_dir_all(&dir));
938             config.out = dir;
939         }
940
941         config.hosts = if let Some(arg_host) = flags.host {
942             arg_host
943         } else if let Some(file_host) = build.host {
944             file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
945         } else {
946             vec![config.build]
947         };
948         config.targets = if let Some(arg_target) = flags.target {
949             arg_target
950         } else if let Some(file_target) = build.target {
951             file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
952         } else {
953             // If target is *not* configured, then default to the host
954             // toolchains.
955             config.hosts.clone()
956         };
957
958         config.nodejs = build.nodejs.map(PathBuf::from);
959         config.npm = build.npm.map(PathBuf::from);
960         config.gdb = build.gdb.map(PathBuf::from);
961         config.python = build.python.map(PathBuf::from);
962         config.submodules = build.submodules;
963         set(&mut config.low_priority, build.low_priority);
964         set(&mut config.compiler_docs, build.compiler_docs);
965         set(&mut config.docs_minification, build.docs_minification);
966         set(&mut config.docs, build.docs);
967         set(&mut config.locked_deps, build.locked_deps);
968         set(&mut config.vendor, build.vendor);
969         set(&mut config.full_bootstrap, build.full_bootstrap);
970         set(&mut config.extended, build.extended);
971         config.tools = build.tools;
972         set(&mut config.verbose, build.verbose);
973         set(&mut config.sanitizers, build.sanitizers);
974         set(&mut config.profiler, build.profiler);
975         set(&mut config.cargo_native_static, build.cargo_native_static);
976         set(&mut config.configure_args, build.configure_args);
977         set(&mut config.local_rebuild, build.local_rebuild);
978         set(&mut config.print_step_timings, build.print_step_timings);
979         set(&mut config.print_step_rusage, build.print_step_rusage);
980         set(&mut config.patch_binaries_for_nix, build.patch_binaries_for_nix);
981         set(&mut config.optimized_compiler_builtins, build.optimized_compiler_builtins);
982
983         config.verbose = cmp::max(config.verbose, flags.verbose);
984
985         if let Some(install) = toml.install {
986             config.prefix = install.prefix.map(PathBuf::from);
987             config.sysconfdir = install.sysconfdir.map(PathBuf::from);
988             config.datadir = install.datadir.map(PathBuf::from);
989             config.docdir = install.docdir.map(PathBuf::from);
990             set(&mut config.bindir, install.bindir.map(PathBuf::from));
991             config.libdir = install.libdir.map(PathBuf::from);
992             config.mandir = install.mandir.map(PathBuf::from);
993         }
994
995         // We want the llvm-skip-rebuild flag to take precedence over the
996         // skip-rebuild config.toml option so we store it separately
997         // so that we can infer the right value
998         let mut llvm_skip_rebuild = flags.llvm_skip_rebuild;
999
1000         // Store off these values as options because if they're not provided
1001         // we'll infer default values for them later
1002         let mut llvm_assertions = None;
1003         let mut llvm_tests = None;
1004         let mut llvm_plugins = None;
1005         let mut debug = None;
1006         let mut debug_assertions = None;
1007         let mut debug_assertions_std = None;
1008         let mut overflow_checks = None;
1009         let mut overflow_checks_std = None;
1010         let mut debug_logging = None;
1011         let mut debuginfo_level = None;
1012         let mut debuginfo_level_rustc = None;
1013         let mut debuginfo_level_std = None;
1014         let mut debuginfo_level_tools = None;
1015         let mut debuginfo_level_tests = None;
1016         let mut optimize = None;
1017         let mut ignore_git = None;
1018
1019         if let Some(llvm) = toml.llvm {
1020             match llvm.ccache {
1021                 Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
1022                 Some(StringOrBool::Bool(true)) => {
1023                     config.ccache = Some("ccache".to_string());
1024                 }
1025                 Some(StringOrBool::Bool(false)) | None => {}
1026             }
1027             set(&mut config.ninja_in_file, llvm.ninja);
1028             llvm_assertions = llvm.assertions;
1029             llvm_tests = llvm.tests;
1030             llvm_plugins = llvm.plugins;
1031             llvm_skip_rebuild = llvm_skip_rebuild.or(llvm.skip_rebuild);
1032             set(&mut config.llvm_optimize, llvm.optimize);
1033             set(&mut config.llvm_thin_lto, llvm.thin_lto);
1034             set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
1035             set(&mut config.llvm_version_check, llvm.version_check);
1036             set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp);
1037             if let Some(v) = llvm.link_shared {
1038                 config.llvm_link_shared.set(Some(v));
1039             }
1040             config.llvm_targets = llvm.targets.clone();
1041             config.llvm_experimental_targets = llvm.experimental_targets.clone();
1042             config.llvm_link_jobs = llvm.link_jobs;
1043             config.llvm_version_suffix = llvm.version_suffix.clone();
1044             config.llvm_clang_cl = llvm.clang_cl.clone();
1045
1046             config.llvm_cflags = llvm.cflags.clone();
1047             config.llvm_cxxflags = llvm.cxxflags.clone();
1048             config.llvm_ldflags = llvm.ldflags.clone();
1049             set(&mut config.llvm_use_libcxx, llvm.use_libcxx);
1050             config.llvm_use_linker = llvm.use_linker.clone();
1051             config.llvm_allow_old_toolchain = llvm.allow_old_toolchain.unwrap_or(false);
1052             config.llvm_polly = llvm.polly.unwrap_or(false);
1053             config.llvm_clang = llvm.clang.unwrap_or(false);
1054             config.llvm_build_config = llvm.build_config.clone().unwrap_or(Default::default());
1055             config.llvm_from_ci = match llvm.download_ci_llvm {
1056                 Some(StringOrBool::String(s)) => {
1057                     assert!(s == "if-available", "unknown option `{}` for download-ci-llvm", s);
1058                     crate::native::is_ci_llvm_available(&config, llvm_assertions.unwrap_or(false))
1059                 }
1060                 Some(StringOrBool::Bool(b)) => b,
1061                 None => false,
1062             };
1063
1064             if config.llvm_from_ci {
1065                 // None of the LLVM options, except assertions, are supported
1066                 // when using downloaded LLVM. We could just ignore these but
1067                 // that's potentially confusing, so force them to not be
1068                 // explicitly set. The defaults and CI defaults don't
1069                 // necessarily match but forcing people to match (somewhat
1070                 // arbitrary) CI configuration locally seems bad/hard.
1071                 check_ci_llvm!(llvm.optimize);
1072                 check_ci_llvm!(llvm.thin_lto);
1073                 check_ci_llvm!(llvm.release_debuginfo);
1074                 // CI-built LLVM can be either dynamic or static. We won't know until we download it.
1075                 check_ci_llvm!(llvm.link_shared);
1076                 check_ci_llvm!(llvm.static_libstdcpp);
1077                 check_ci_llvm!(llvm.targets);
1078                 check_ci_llvm!(llvm.experimental_targets);
1079                 check_ci_llvm!(llvm.link_jobs);
1080                 check_ci_llvm!(llvm.clang_cl);
1081                 check_ci_llvm!(llvm.version_suffix);
1082                 check_ci_llvm!(llvm.cflags);
1083                 check_ci_llvm!(llvm.cxxflags);
1084                 check_ci_llvm!(llvm.ldflags);
1085                 check_ci_llvm!(llvm.use_libcxx);
1086                 check_ci_llvm!(llvm.use_linker);
1087                 check_ci_llvm!(llvm.allow_old_toolchain);
1088                 check_ci_llvm!(llvm.polly);
1089                 check_ci_llvm!(llvm.clang);
1090                 check_ci_llvm!(llvm.build_config);
1091                 check_ci_llvm!(llvm.plugins);
1092             }
1093
1094             // NOTE: can never be hit when downloading from CI, since we call `check_ci_llvm!(thin_lto)` above.
1095             if config.llvm_thin_lto && llvm.link_shared.is_none() {
1096                 // If we're building with ThinLTO on, by default we want to link
1097                 // to LLVM shared, to avoid re-doing ThinLTO (which happens in
1098                 // the link step) with each stage.
1099                 config.llvm_link_shared.set(Some(true));
1100             }
1101         }
1102
1103         if let Some(rust) = toml.rust {
1104             debug = rust.debug;
1105             debug_assertions = rust.debug_assertions;
1106             debug_assertions_std = rust.debug_assertions_std;
1107             overflow_checks = rust.overflow_checks;
1108             overflow_checks_std = rust.overflow_checks_std;
1109             debug_logging = rust.debug_logging;
1110             debuginfo_level = rust.debuginfo_level;
1111             debuginfo_level_rustc = rust.debuginfo_level_rustc;
1112             debuginfo_level_std = rust.debuginfo_level_std;
1113             debuginfo_level_tools = rust.debuginfo_level_tools;
1114             debuginfo_level_tests = rust.debuginfo_level_tests;
1115             config.rust_split_debuginfo = rust
1116                 .split_debuginfo
1117                 .as_deref()
1118                 .map(SplitDebuginfo::from_str)
1119                 .map(|v| v.expect("invalid value for rust.split_debuginfo"))
1120                 .unwrap_or(SplitDebuginfo::default_for_platform(&config.build.triple));
1121             optimize = rust.optimize;
1122             ignore_git = rust.ignore_git;
1123             config.rust_new_symbol_mangling = rust.new_symbol_mangling;
1124             set(&mut config.rust_optimize_tests, rust.optimize_tests);
1125             set(&mut config.codegen_tests, rust.codegen_tests);
1126             set(&mut config.rust_rpath, rust.rpath);
1127             set(&mut config.jemalloc, rust.jemalloc);
1128             set(&mut config.test_compare_mode, rust.test_compare_mode);
1129             set(&mut config.backtrace, rust.backtrace);
1130             set(&mut config.channel, rust.channel);
1131             config.description = rust.description;
1132             set(&mut config.rust_dist_src, rust.dist_src);
1133             set(&mut config.verbose_tests, rust.verbose_tests);
1134             // in the case "false" is set explicitly, do not overwrite the command line args
1135             if let Some(true) = rust.incremental {
1136                 config.incremental = true;
1137             }
1138             set(&mut config.use_lld, rust.use_lld);
1139             set(&mut config.lld_enabled, rust.lld);
1140             set(&mut config.llvm_tools_enabled, rust.llvm_tools);
1141             config.rustc_parallel = rust.parallel_compiler.unwrap_or(false);
1142             config.rustc_default_linker = rust.default_linker;
1143             config.musl_root = rust.musl_root.map(PathBuf::from);
1144             config.save_toolstates = rust.save_toolstates.map(PathBuf::from);
1145             set(&mut config.deny_warnings, flags.deny_warnings.or(rust.deny_warnings));
1146             set(&mut config.backtrace_on_ice, rust.backtrace_on_ice);
1147             set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir);
1148             config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit;
1149             set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo);
1150             set(&mut config.control_flow_guard, rust.control_flow_guard);
1151             config.llvm_libunwind_default = rust
1152                 .llvm_libunwind
1153                 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
1154
1155             if let Some(ref backends) = rust.codegen_backends {
1156                 config.rust_codegen_backends =
1157                     backends.iter().map(|s| INTERNER.intern_str(s)).collect();
1158             }
1159
1160             config.rust_codegen_units = rust.codegen_units.map(threads_from_config);
1161             config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config);
1162             config.rust_profile_use = flags.rust_profile_use.or(rust.profile_use);
1163             config.rust_profile_generate = flags.rust_profile_generate.or(rust.profile_generate);
1164             config.download_rustc_commit = download_ci_rustc_commit(&config, rust.download_rustc);
1165         } else {
1166             config.rust_profile_use = flags.rust_profile_use;
1167             config.rust_profile_generate = flags.rust_profile_generate;
1168         }
1169
1170         if let Some(t) = toml.target {
1171             for (triple, cfg) in t {
1172                 let mut target = Target::from_triple(&triple);
1173
1174                 if let Some(ref s) = cfg.llvm_config {
1175                     target.llvm_config = Some(config.src.join(s));
1176                 }
1177                 target.llvm_has_rust_patches = cfg.llvm_has_rust_patches;
1178                 if let Some(ref s) = cfg.llvm_filecheck {
1179                     target.llvm_filecheck = Some(config.src.join(s));
1180                 }
1181                 target.llvm_libunwind = cfg
1182                     .llvm_libunwind
1183                     .as_ref()
1184                     .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"));
1185                 if let Some(ref s) = cfg.android_ndk {
1186                     target.ndk = Some(config.src.join(s));
1187                 }
1188                 if let Some(s) = cfg.no_std {
1189                     target.no_std = s;
1190                 }
1191                 target.cc = cfg.cc.map(PathBuf::from);
1192                 target.cxx = cfg.cxx.map(PathBuf::from);
1193                 target.ar = cfg.ar.map(PathBuf::from);
1194                 target.ranlib = cfg.ranlib.map(PathBuf::from);
1195                 target.linker = cfg.linker.map(PathBuf::from);
1196                 target.crt_static = cfg.crt_static;
1197                 target.musl_root = cfg.musl_root.map(PathBuf::from);
1198                 target.musl_libdir = cfg.musl_libdir.map(PathBuf::from);
1199                 target.wasi_root = cfg.wasi_root.map(PathBuf::from);
1200                 target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from);
1201                 target.sanitizers = cfg.sanitizers;
1202                 target.profiler = cfg.profiler;
1203
1204                 config.target_config.insert(TargetSelection::from_user(&triple), target);
1205             }
1206         }
1207
1208         if config.llvm_from_ci {
1209             let triple = &config.build.triple;
1210             let ci_llvm_bin = config.ci_llvm_root().join("bin");
1211             let mut build_target = config
1212                 .target_config
1213                 .entry(config.build)
1214                 .or_insert_with(|| Target::from_triple(&triple));
1215
1216             check_ci_llvm!(build_target.llvm_config);
1217             check_ci_llvm!(build_target.llvm_filecheck);
1218             build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", config.build)));
1219             build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", config.build)));
1220         }
1221
1222         if let Some(t) = toml.dist {
1223             config.dist_sign_folder = t.sign_folder.map(PathBuf::from);
1224             config.dist_upload_addr = t.upload_addr;
1225             config.dist_compression_formats = t.compression_formats;
1226             set(&mut config.rust_dist_src, t.src_tarball);
1227             set(&mut config.missing_tools, t.missing_tools);
1228         }
1229
1230         if let Some(r) = build.rustfmt {
1231             *config.initial_rustfmt.borrow_mut() = if r.exists() {
1232                 RustfmtState::SystemToolchain(r)
1233             } else {
1234                 RustfmtState::Unavailable
1235             };
1236         } else {
1237             // If using a system toolchain for bootstrapping, see if that has rustfmt available.
1238             let host = config.build;
1239             let rustfmt_path = config.initial_rustc.with_file_name(exe("rustfmt", host));
1240             let bin_root = config.out.join(host.triple).join("stage0");
1241             if !rustfmt_path.starts_with(&bin_root) {
1242                 // Using a system-provided toolchain; we shouldn't download rustfmt.
1243                 *config.initial_rustfmt.borrow_mut() = RustfmtState::SystemToolchain(rustfmt_path);
1244             }
1245         }
1246
1247         // Now that we've reached the end of our configuration, infer the
1248         // default values for all options that we haven't otherwise stored yet.
1249
1250         config.llvm_skip_rebuild = llvm_skip_rebuild.unwrap_or(false);
1251         config.llvm_assertions = llvm_assertions.unwrap_or(false);
1252         config.llvm_tests = llvm_tests.unwrap_or(false);
1253         config.llvm_plugins = llvm_plugins.unwrap_or(false);
1254         config.rust_optimize = optimize.unwrap_or(true);
1255
1256         let default = debug == Some(true);
1257         config.rust_debug_assertions = debug_assertions.unwrap_or(default);
1258         config.rust_debug_assertions_std =
1259             debug_assertions_std.unwrap_or(config.rust_debug_assertions);
1260         config.rust_overflow_checks = overflow_checks.unwrap_or(default);
1261         config.rust_overflow_checks_std =
1262             overflow_checks_std.unwrap_or(config.rust_overflow_checks);
1263
1264         config.rust_debug_logging = debug_logging.unwrap_or(config.rust_debug_assertions);
1265
1266         let with_defaults = |debuginfo_level_specific: Option<u32>| {
1267             debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
1268                 1
1269             } else {
1270                 0
1271             })
1272         };
1273         config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
1274         config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
1275         config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
1276         config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(0);
1277
1278         let default = config.channel == "dev";
1279         config.ignore_git = ignore_git.unwrap_or(default);
1280
1281         let download_rustc = config.download_rustc_commit.is_some();
1282         // See https://github.com/rust-lang/compiler-team/issues/326
1283         config.stage = match config.cmd {
1284             Subcommand::Check { .. } => flags.stage.or(build.check_stage).unwrap_or(0),
1285             // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden.
1286             Subcommand::Doc { .. } => {
1287                 flags.stage.or(build.doc_stage).unwrap_or(if download_rustc { 2 } else { 0 })
1288             }
1289             Subcommand::Build { .. } => {
1290                 flags.stage.or(build.build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1291             }
1292             Subcommand::Test { .. } => {
1293                 flags.stage.or(build.test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1294             }
1295             Subcommand::Bench { .. } => flags.stage.or(build.bench_stage).unwrap_or(2),
1296             Subcommand::Dist { .. } => flags.stage.or(build.dist_stage).unwrap_or(2),
1297             Subcommand::Install { .. } => flags.stage.or(build.install_stage).unwrap_or(2),
1298             // These are all bootstrap tools, which don't depend on the compiler.
1299             // The stage we pass shouldn't matter, but use 0 just in case.
1300             Subcommand::Clean { .. }
1301             | Subcommand::Clippy { .. }
1302             | Subcommand::Fix { .. }
1303             | Subcommand::Run { .. }
1304             | Subcommand::Setup { .. }
1305             | Subcommand::Format { .. } => flags.stage.unwrap_or(0),
1306         };
1307
1308         // CI should always run stage 2 builds, unless it specifically states otherwise
1309         #[cfg(not(test))]
1310         if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None {
1311             match config.cmd {
1312                 Subcommand::Test { .. }
1313                 | Subcommand::Doc { .. }
1314                 | Subcommand::Build { .. }
1315                 | Subcommand::Bench { .. }
1316                 | Subcommand::Dist { .. }
1317                 | Subcommand::Install { .. } => {
1318                     assert_eq!(
1319                         config.stage, 2,
1320                         "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
1321                         config.stage,
1322                     );
1323                 }
1324                 Subcommand::Clean { .. }
1325                 | Subcommand::Check { .. }
1326                 | Subcommand::Clippy { .. }
1327                 | Subcommand::Fix { .. }
1328                 | Subcommand::Run { .. }
1329                 | Subcommand::Setup { .. }
1330                 | Subcommand::Format { .. } => {}
1331             }
1332         }
1333
1334         config
1335     }
1336
1337     /// A git invocation which runs inside the source directory.
1338     ///
1339     /// Use this rather than `Command::new("git")` in order to support out-of-tree builds.
1340     pub(crate) fn git(&self) -> Command {
1341         let mut git = Command::new("git");
1342         git.current_dir(&self.src);
1343         git
1344     }
1345
1346     pub(crate) fn artifact_channel(&self, builder: &Builder<'_>, commit: &str) -> String {
1347         if builder.rust_info.is_managed_git_subrepository() {
1348             let mut channel = self.git();
1349             channel.arg("show").arg(format!("{}:src/ci/channel", commit));
1350             let channel = output(&mut channel);
1351             channel.trim().to_owned()
1352         } else if let Ok(channel) = fs::read_to_string(builder.src.join("src/ci/channel")) {
1353             channel.trim().to_owned()
1354         } else {
1355             let src = builder.src.display();
1356             eprintln!("error: failed to determine artifact channel");
1357             eprintln!(
1358                 "help: either use git or ensure that {src}/src/ci/channel contains the name of the channel to use"
1359             );
1360             panic!();
1361         }
1362     }
1363
1364     /// Try to find the relative path of `bindir`, otherwise return it in full.
1365     pub fn bindir_relative(&self) -> &Path {
1366         let bindir = &self.bindir;
1367         if bindir.is_absolute() {
1368             // Try to make it relative to the prefix.
1369             if let Some(prefix) = &self.prefix {
1370                 if let Ok(stripped) = bindir.strip_prefix(prefix) {
1371                     return stripped;
1372                 }
1373             }
1374         }
1375         bindir
1376     }
1377
1378     /// Try to find the relative path of `libdir`.
1379     pub fn libdir_relative(&self) -> Option<&Path> {
1380         let libdir = self.libdir.as_ref()?;
1381         if libdir.is_relative() {
1382             Some(libdir)
1383         } else {
1384             // Try to make it relative to the prefix.
1385             libdir.strip_prefix(self.prefix.as_ref()?).ok()
1386         }
1387     }
1388
1389     /// The absolute path to the downloaded LLVM artifacts.
1390     pub(crate) fn ci_llvm_root(&self) -> PathBuf {
1391         assert!(self.llvm_from_ci);
1392         self.out.join(&*self.build.triple).join("ci-llvm")
1393     }
1394
1395     /// Determine whether llvm should be linked dynamically.
1396     ///
1397     /// If `false`, llvm should be linked statically.
1398     /// This is computed on demand since LLVM might have to first be downloaded from CI.
1399     pub(crate) fn llvm_link_shared(builder: &Builder<'_>) -> bool {
1400         let mut opt = builder.config.llvm_link_shared.get();
1401         if opt.is_none() && builder.config.dry_run {
1402             // just assume static for now - dynamic linking isn't supported on all platforms
1403             return false;
1404         }
1405
1406         let llvm_link_shared = *opt.get_or_insert_with(|| {
1407             if builder.config.llvm_from_ci {
1408                 crate::native::maybe_download_ci_llvm(builder);
1409                 let ci_llvm = builder.config.ci_llvm_root();
1410                 let link_type = t!(
1411                     std::fs::read_to_string(ci_llvm.join("link-type.txt")),
1412                     format!("CI llvm missing: {}", ci_llvm.display())
1413                 );
1414                 link_type == "dynamic"
1415             } else {
1416                 // unclear how thought-through this default is, but it maintains compatibility with
1417                 // previous behavior
1418                 false
1419             }
1420         });
1421         builder.config.llvm_link_shared.set(opt);
1422         llvm_link_shared
1423     }
1424
1425     /// Return whether we will use a downloaded, pre-compiled version of rustc, or just build from source.
1426     pub(crate) fn download_rustc(builder: &Builder<'_>) -> bool {
1427         static DOWNLOAD_RUSTC: OnceCell<bool> = OnceCell::new();
1428         if builder.config.dry_run && DOWNLOAD_RUSTC.get().is_none() {
1429             // avoid trying to actually download the commit
1430             return false;
1431         }
1432
1433         *DOWNLOAD_RUSTC.get_or_init(|| match &builder.config.download_rustc_commit {
1434             None => false,
1435             Some(commit) => {
1436                 download_ci_rustc(builder, commit);
1437                 true
1438             }
1439         })
1440     }
1441
1442     pub(crate) fn initial_rustfmt(builder: &Builder<'_>) -> Option<PathBuf> {
1443         match &mut *builder.config.initial_rustfmt.borrow_mut() {
1444             RustfmtState::SystemToolchain(p) | RustfmtState::Downloaded(p) => Some(p.clone()),
1445             RustfmtState::Unavailable => None,
1446             r @ RustfmtState::LazyEvaluated => {
1447                 if builder.config.dry_run {
1448                     return Some(PathBuf::new());
1449                 }
1450                 let path = maybe_download_rustfmt(builder);
1451                 *r = if let Some(p) = &path {
1452                     RustfmtState::Downloaded(p.clone())
1453                 } else {
1454                     RustfmtState::Unavailable
1455                 };
1456                 path
1457             }
1458         }
1459     }
1460
1461     pub fn verbose(&self) -> bool {
1462         self.verbose > 0
1463     }
1464
1465     pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1466         self.target_config.get(&target).map(|t| t.sanitizers).flatten().unwrap_or(self.sanitizers)
1467     }
1468
1469     pub fn any_sanitizers_enabled(&self) -> bool {
1470         self.target_config.values().any(|t| t.sanitizers == Some(true)) || self.sanitizers
1471     }
1472
1473     pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1474         self.target_config.get(&target).map(|t| t.profiler).flatten().unwrap_or(self.profiler)
1475     }
1476
1477     pub fn any_profiler_enabled(&self) -> bool {
1478         self.target_config.values().any(|t| t.profiler == Some(true)) || self.profiler
1479     }
1480
1481     pub fn llvm_enabled(&self) -> bool {
1482         self.rust_codegen_backends.contains(&INTERNER.intern_str("llvm"))
1483     }
1484
1485     pub fn llvm_libunwind(&self, target: TargetSelection) -> LlvmLibunwind {
1486         self.target_config
1487             .get(&target)
1488             .and_then(|t| t.llvm_libunwind)
1489             .or(self.llvm_libunwind_default)
1490             .unwrap_or(if target.contains("fuchsia") {
1491                 LlvmLibunwind::InTree
1492             } else {
1493                 LlvmLibunwind::No
1494             })
1495     }
1496
1497     pub fn submodules(&self, rust_info: &GitInfo) -> bool {
1498         self.submodules.unwrap_or(rust_info.is_managed_git_subrepository())
1499     }
1500 }
1501
1502 fn set<T>(field: &mut T, val: Option<T>) {
1503     if let Some(v) = val {
1504         *field = v;
1505     }
1506 }
1507
1508 fn threads_from_config(v: u32) -> u32 {
1509     match v {
1510         0 => std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) as u32,
1511         n => n,
1512     }
1513 }
1514
1515 /// Returns the commit to download, or `None` if we shouldn't download CI artifacts.
1516 fn download_ci_rustc_commit(
1517     config: &Config,
1518     download_rustc: Option<StringOrBool>,
1519 ) -> Option<String> {
1520     // If `download-rustc` is not set, default to rebuilding.
1521     let if_unchanged = match download_rustc {
1522         None | Some(StringOrBool::Bool(false)) => return None,
1523         Some(StringOrBool::Bool(true)) => false,
1524         Some(StringOrBool::String(s)) if s == "if-unchanged" => true,
1525         Some(StringOrBool::String(other)) => {
1526             panic!("unrecognized option for download-rustc: {}", other)
1527         }
1528     };
1529
1530     // Handle running from a directory other than the top level
1531     let top_level = output(config.git().args(&["rev-parse", "--show-toplevel"]));
1532     let top_level = top_level.trim_end();
1533     let compiler = format!("{top_level}/compiler/");
1534     let library = format!("{top_level}/library/");
1535
1536     // Look for a version to compare to based on the current commit.
1537     // Only commits merged by bors will have CI artifacts.
1538     let merge_base = output(
1539         config
1540             .git()
1541             .arg("rev-list")
1542             .arg(format!("--author={}", config.stage0_metadata.config.git_merge_commit_email))
1543             .args(&["-n1", "--first-parent", "HEAD"]),
1544     );
1545     let commit = merge_base.trim_end();
1546     if commit.is_empty() {
1547         println!("error: could not find commit hash for downloading rustc");
1548         println!("help: maybe your repository history is too shallow?");
1549         println!("help: consider disabling `download-rustc`");
1550         println!("help: or fetch enough history to include one upstream commit");
1551         crate::detail_exit(1);
1552     }
1553
1554     // Warn if there were changes to the compiler or standard library since the ancestor commit.
1555     let has_changes = !t!(config
1556         .git()
1557         .args(&["diff-index", "--quiet", &commit, "--", &compiler, &library])
1558         .status())
1559     .success();
1560     if has_changes {
1561         if if_unchanged {
1562             if config.verbose > 0 {
1563                 println!(
1564                     "warning: saw changes to compiler/ or library/ since {commit}; \
1565                           ignoring `download-rustc`"
1566                 );
1567             }
1568             return None;
1569         }
1570         println!(
1571             "warning: `download-rustc` is enabled, but there are changes to \
1572                   compiler/ or library/"
1573         );
1574     }
1575
1576     Some(commit.to_string())
1577 }
1578
1579 fn maybe_download_rustfmt(builder: &Builder<'_>) -> Option<PathBuf> {
1580     let RustfmtMetadata { date, version } = builder.config.stage0_metadata.rustfmt.as_ref()?;
1581     let channel = format!("{version}-{date}");
1582
1583     let host = builder.config.build;
1584     let rustfmt_path = builder.config.initial_rustc.with_file_name(exe("rustfmt", host));
1585     let bin_root = builder.config.out.join(host.triple).join("stage0");
1586     let rustfmt_stamp = bin_root.join(".rustfmt-stamp");
1587     if rustfmt_path.exists() && !program_out_of_date(&rustfmt_stamp, &channel) {
1588         return Some(rustfmt_path);
1589     }
1590
1591     let filename = format!("rustfmt-{version}-{build}.tar.xz", build = host.triple);
1592     download_component(builder, DownloadSource::Dist, filename, "rustfmt-preview", &date, "stage0");
1593
1594     builder.fix_bin_or_dylib(&bin_root.join("bin").join("rustfmt"));
1595     builder.fix_bin_or_dylib(&bin_root.join("bin").join("cargo-fmt"));
1596
1597     builder.create(&rustfmt_stamp, &channel);
1598     Some(rustfmt_path)
1599 }
1600
1601 fn download_ci_rustc(builder: &Builder<'_>, commit: &str) {
1602     builder.verbose(&format!("using downloaded stage2 artifacts from CI (commit {commit})"));
1603     let channel = builder.config.artifact_channel(builder, commit);
1604     let host = builder.config.build.triple;
1605     let bin_root = builder.out.join(host).join("ci-rustc");
1606     let rustc_stamp = bin_root.join(".rustc-stamp");
1607
1608     if !bin_root.join("bin").join("rustc").exists() || program_out_of_date(&rustc_stamp, commit) {
1609         if bin_root.exists() {
1610             t!(fs::remove_dir_all(&bin_root));
1611         }
1612         let filename = format!("rust-std-{channel}-{host}.tar.xz");
1613         let pattern = format!("rust-std-{host}");
1614         download_ci_component(builder, filename, &pattern, commit);
1615         let filename = format!("rustc-{channel}-{host}.tar.xz");
1616         download_ci_component(builder, filename, "rustc", commit);
1617         // download-rustc doesn't need its own cargo, it can just use beta's.
1618         let filename = format!("rustc-dev-{channel}-{host}.tar.xz");
1619         download_ci_component(builder, filename, "rustc-dev", commit);
1620
1621         builder.fix_bin_or_dylib(&bin_root.join("bin").join("rustc"));
1622         builder.fix_bin_or_dylib(&bin_root.join("bin").join("rustdoc"));
1623         let lib_dir = bin_root.join("lib");
1624         for lib in t!(fs::read_dir(&lib_dir), lib_dir.display().to_string()) {
1625             let lib = t!(lib);
1626             if lib.path().extension() == Some(OsStr::new("so")) {
1627                 builder.fix_bin_or_dylib(&lib.path());
1628             }
1629         }
1630         t!(fs::write(rustc_stamp, commit));
1631     }
1632 }
1633
1634 pub(crate) enum DownloadSource {
1635     CI,
1636     Dist,
1637 }
1638
1639 /// Download a single component of a CI-built toolchain (not necessarily a published nightly).
1640 // NOTE: intentionally takes an owned string to avoid downloading multiple times by accident
1641 fn download_ci_component(builder: &Builder<'_>, filename: String, prefix: &str, commit: &str) {
1642     download_component(builder, DownloadSource::CI, filename, prefix, commit, "ci-rustc")
1643 }
1644
1645 fn download_component(
1646     builder: &Builder<'_>,
1647     mode: DownloadSource,
1648     filename: String,
1649     prefix: &str,
1650     key: &str,
1651     destination: &str,
1652 ) {
1653     let cache_dst = builder.out.join("cache");
1654     let cache_dir = cache_dst.join(key);
1655     if !cache_dir.exists() {
1656         t!(fs::create_dir_all(&cache_dir));
1657     }
1658
1659     let bin_root = builder.out.join(builder.config.build.triple).join(destination);
1660     let tarball = cache_dir.join(&filename);
1661     let (base_url, url, should_verify) = match mode {
1662         DownloadSource::CI => (
1663             builder.config.stage0_metadata.config.artifacts_server.clone(),
1664             format!("{key}/{filename}"),
1665             false,
1666         ),
1667         DownloadSource::Dist => {
1668             let dist_server = env::var("RUSTUP_DIST_SERVER")
1669                 .unwrap_or(builder.config.stage0_metadata.config.dist_server.to_string());
1670             // NOTE: make `dist` part of the URL because that's how it's stored in src/stage0.json
1671             (dist_server, format!("dist/{key}/{filename}"), true)
1672         }
1673     };
1674
1675     // For the beta compiler, put special effort into ensuring the checksums are valid.
1676     // FIXME: maybe we should do this for download-rustc as well? but it would be a pain to update
1677     // this on each and every nightly ...
1678     let checksum = if should_verify {
1679         let error = format!(
1680             "src/stage0.json doesn't contain a checksum for {url}. \
1681             Pre-built artifacts might not be available for this \
1682             target at this time, see https://doc.rust-lang.org/nightly\
1683             /rustc/platform-support.html for more information."
1684         );
1685         let sha256 = builder.config.stage0_metadata.checksums_sha256.get(&url).expect(&error);
1686         if tarball.exists() {
1687             if builder.verify(&tarball, sha256) {
1688                 builder.unpack(&tarball, &bin_root, prefix);
1689                 return;
1690             } else {
1691                 builder.verbose(&format!(
1692                     "ignoring cached file {} due to failed verification",
1693                     tarball.display()
1694                 ));
1695                 builder.remove(&tarball);
1696             }
1697         }
1698         Some(sha256)
1699     } else if tarball.exists() {
1700         builder.unpack(&tarball, &bin_root, prefix);
1701         return;
1702     } else {
1703         None
1704     };
1705
1706     builder.download_component(&format!("{base_url}/{url}"), &tarball, "");
1707     if let Some(sha256) = checksum {
1708         if !builder.verify(&tarball, sha256) {
1709             panic!("failed to verify {}", tarball.display());
1710         }
1711     }
1712
1713     builder.unpack(&tarball, &bin_root, prefix);
1714 }