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