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