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