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