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