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