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