]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/config.rs
Avoid the merge derive macro in rustbuild
[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::cmp;
7 use std::collections::{HashMap, HashSet};
8 use std::env;
9 use std::ffi::OsString;
10 use std::fmt;
11 use std::fs;
12 use std::path::{Path, PathBuf};
13 use std::str::FromStr;
14
15 use crate::cache::{Interned, INTERNER};
16 use crate::channel::GitInfo;
17 pub use crate::flags::Subcommand;
18 use crate::flags::{Color, Flags};
19 use crate::util::exe;
20 use build_helper::t;
21 use merge::Merge;
22 use serde::Deserialize;
23
24 macro_rules! check_ci_llvm {
25     ($name:expr) => {
26         assert!(
27             $name.is_none(),
28             "setting {} is incompatible with download-ci-llvm.",
29             stringify!($name)
30         );
31     };
32 }
33
34 /// Global configuration for the entire build and/or bootstrap.
35 ///
36 /// This structure is derived from a combination of both `config.toml` and
37 /// `config.mk`. As of the time of this writing it's unlikely that `config.toml`
38 /// is used all that much, so this is primarily filled out by `config.mk` which
39 /// is generated from `./configure`.
40 ///
41 /// Note that this structure is not decoded directly into, but rather it is
42 /// filled out from the decoded forms of the structs below. For documentation
43 /// each field, see the corresponding fields in
44 /// `config.toml.example`.
45 #[derive(Default)]
46 pub struct Config {
47     pub changelog_seen: Option<usize>,
48     pub ccache: Option<String>,
49     /// Call Build::ninja() instead of this.
50     pub ninja_in_file: bool,
51     pub verbose: usize,
52     pub submodules: Option<bool>,
53     pub fast_submodules: bool,
54     pub compiler_docs: bool,
55     pub docs_minification: bool,
56     pub docs: bool,
57     pub locked_deps: bool,
58     pub vendor: bool,
59     pub target_config: HashMap<TargetSelection, Target>,
60     pub full_bootstrap: bool,
61     pub extended: bool,
62     pub tools: Option<HashSet<String>>,
63     pub sanitizers: bool,
64     pub profiler: bool,
65     pub ignore_git: bool,
66     pub exclude: Vec<PathBuf>,
67     pub include_default_paths: bool,
68     pub rustc_error_format: Option<String>,
69     pub json_output: bool,
70     pub test_compare_mode: bool,
71     pub llvm_libunwind: LlvmLibunwind,
72     pub color: Color,
73
74     pub on_fail: Option<String>,
75     pub stage: u32,
76     pub keep_stage: Vec<u32>,
77     pub keep_stage_std: Vec<u32>,
78     pub src: PathBuf,
79     // defaults to `config.toml`
80     pub config: PathBuf,
81     pub jobs: Option<u32>,
82     pub cmd: Subcommand,
83     pub incremental: bool,
84     pub dry_run: bool,
85     pub download_rustc: bool,
86
87     pub deny_warnings: bool,
88     pub backtrace_on_ice: bool,
89
90     // llvm codegen options
91     pub llvm_skip_rebuild: bool,
92     pub llvm_assertions: bool,
93     pub llvm_tests: bool,
94     pub llvm_plugins: bool,
95     pub llvm_optimize: bool,
96     pub llvm_thin_lto: bool,
97     pub llvm_release_debuginfo: bool,
98     pub llvm_version_check: bool,
99     pub llvm_static_stdcpp: bool,
100     pub llvm_link_shared: bool,
101     pub llvm_clang_cl: Option<String>,
102     pub llvm_targets: Option<String>,
103     pub llvm_experimental_targets: Option<String>,
104     pub llvm_link_jobs: Option<u32>,
105     pub llvm_version_suffix: Option<String>,
106     pub llvm_use_linker: Option<String>,
107     pub llvm_allow_old_toolchain: bool,
108     pub llvm_polly: bool,
109     pub llvm_clang: bool,
110     pub llvm_from_ci: bool,
111
112     pub use_lld: bool,
113     pub lld_enabled: bool,
114     pub llvm_tools_enabled: bool,
115
116     pub llvm_cflags: Option<String>,
117     pub llvm_cxxflags: Option<String>,
118     pub llvm_ldflags: Option<String>,
119     pub llvm_use_libcxx: bool,
120
121     // rust codegen options
122     pub rust_optimize: bool,
123     pub rust_codegen_units: Option<u32>,
124     pub rust_codegen_units_std: Option<u32>,
125     pub rust_debug_assertions: bool,
126     pub rust_debug_assertions_std: bool,
127     pub rust_overflow_checks: bool,
128     pub rust_overflow_checks_std: bool,
129     pub rust_debug_logging: bool,
130     pub rust_debuginfo_level_rustc: u32,
131     pub rust_debuginfo_level_std: u32,
132     pub rust_debuginfo_level_tools: u32,
133     pub rust_debuginfo_level_tests: u32,
134     pub rust_run_dsymutil: bool,
135     pub rust_rpath: bool,
136     pub rustc_parallel: bool,
137     pub rustc_default_linker: Option<String>,
138     pub rust_optimize_tests: bool,
139     pub rust_dist_src: bool,
140     pub rust_codegen_backends: Vec<Interned<String>>,
141     pub rust_verify_llvm_ir: bool,
142     pub rust_thin_lto_import_instr_limit: Option<u32>,
143     pub rust_remap_debuginfo: bool,
144     pub rust_new_symbol_mangling: Option<bool>,
145     pub rust_profile_use: Option<String>,
146     pub rust_profile_generate: Option<String>,
147     pub llvm_profile_use: Option<String>,
148     pub llvm_profile_generate: bool,
149
150     pub build: TargetSelection,
151     pub hosts: Vec<TargetSelection>,
152     pub targets: Vec<TargetSelection>,
153     pub local_rebuild: bool,
154     pub jemalloc: bool,
155     pub control_flow_guard: bool,
156
157     // dist misc
158     pub dist_sign_folder: Option<PathBuf>,
159     pub dist_upload_addr: Option<String>,
160     pub dist_compression_formats: Option<Vec<String>>,
161
162     // libstd features
163     pub backtrace: bool, // support for RUST_BACKTRACE
164
165     // misc
166     pub low_priority: bool,
167     pub channel: String,
168     pub description: Option<String>,
169     pub verbose_tests: bool,
170     pub save_toolstates: Option<PathBuf>,
171     pub print_step_timings: bool,
172     pub print_step_rusage: bool,
173     pub missing_tools: bool,
174
175     // Fallback musl-root for all targets
176     pub musl_root: Option<PathBuf>,
177     pub prefix: Option<PathBuf>,
178     pub sysconfdir: Option<PathBuf>,
179     pub datadir: Option<PathBuf>,
180     pub docdir: Option<PathBuf>,
181     pub bindir: PathBuf,
182     pub libdir: Option<PathBuf>,
183     pub mandir: Option<PathBuf>,
184     pub codegen_tests: bool,
185     pub nodejs: Option<PathBuf>,
186     pub npm: Option<PathBuf>,
187     pub gdb: Option<PathBuf>,
188     pub python: Option<PathBuf>,
189     pub cargo_native_static: bool,
190     pub configure_args: Vec<String>,
191
192     // These are either the stage0 downloaded binaries or the locally installed ones.
193     pub initial_cargo: PathBuf,
194     pub initial_rustc: PathBuf,
195     pub initial_rustfmt: Option<PathBuf>,
196     pub out: PathBuf,
197 }
198
199 #[derive(Debug, Clone, Copy, PartialEq)]
200 pub enum LlvmLibunwind {
201     No,
202     InTree,
203     System,
204 }
205
206 impl Default for LlvmLibunwind {
207     fn default() -> Self {
208         Self::No
209     }
210 }
211
212 impl FromStr for LlvmLibunwind {
213     type Err = String;
214
215     fn from_str(value: &str) -> Result<Self, Self::Err> {
216         match value {
217             "no" => Ok(Self::No),
218             "in-tree" => Ok(Self::InTree),
219             "system" => Ok(Self::System),
220             invalid => Err(format!("Invalid value '{}' for rust.llvm-libunwind config.", invalid)),
221         }
222     }
223 }
224
225 #[derive(Debug, Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
226 pub struct TargetSelection {
227     pub triple: Interned<String>,
228     file: Option<Interned<String>>,
229 }
230
231 impl TargetSelection {
232     pub fn from_user(selection: &str) -> Self {
233         let path = Path::new(selection);
234
235         let (triple, file) = if path.exists() {
236             let triple = path
237                 .file_stem()
238                 .expect("Target specification file has no file stem")
239                 .to_str()
240                 .expect("Target specification file stem is not UTF-8");
241
242             (triple, Some(selection))
243         } else {
244             (selection, None)
245         };
246
247         let triple = INTERNER.intern_str(triple);
248         let file = file.map(|f| INTERNER.intern_str(f));
249
250         Self { triple, file }
251     }
252
253     pub fn rustc_target_arg(&self) -> &str {
254         self.file.as_ref().unwrap_or(&self.triple)
255     }
256
257     pub fn contains(&self, needle: &str) -> bool {
258         self.triple.contains(needle)
259     }
260
261     pub fn starts_with(&self, needle: &str) -> bool {
262         self.triple.starts_with(needle)
263     }
264
265     pub fn ends_with(&self, needle: &str) -> bool {
266         self.triple.ends_with(needle)
267     }
268 }
269
270 impl fmt::Display for TargetSelection {
271     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272         write!(f, "{}", self.triple)?;
273         if let Some(file) = self.file {
274             write!(f, "({})", file)?;
275         }
276         Ok(())
277     }
278 }
279
280 impl PartialEq<&str> for TargetSelection {
281     fn eq(&self, other: &&str) -> bool {
282         self.triple == *other
283     }
284 }
285
286 /// Per-target configuration stored in the global configuration structure.
287 #[derive(Default)]
288 pub struct Target {
289     /// Some(path to llvm-config) if using an external LLVM.
290     pub llvm_config: Option<PathBuf>,
291     /// Some(path to FileCheck) if one was specified.
292     pub llvm_filecheck: Option<PathBuf>,
293     pub cc: Option<PathBuf>,
294     pub cxx: Option<PathBuf>,
295     pub ar: Option<PathBuf>,
296     pub ranlib: Option<PathBuf>,
297     pub default_linker: Option<PathBuf>,
298     pub linker: Option<PathBuf>,
299     pub ndk: Option<PathBuf>,
300     pub sanitizers: Option<bool>,
301     pub profiler: Option<bool>,
302     pub crt_static: Option<bool>,
303     pub musl_root: Option<PathBuf>,
304     pub musl_libdir: Option<PathBuf>,
305     pub wasi_root: Option<PathBuf>,
306     pub qemu_rootfs: Option<PathBuf>,
307     pub no_std: bool,
308 }
309
310 impl Target {
311     pub fn from_triple(triple: &str) -> Self {
312         let mut target: Self = Default::default();
313         if triple.contains("-none") || triple.contains("nvptx") {
314             target.no_std = true;
315         }
316         target
317     }
318 }
319 /// Structure of the `config.toml` file that configuration is read from.
320 ///
321 /// This structure uses `Decodable` to automatically decode a TOML configuration
322 /// file into this format, and then this is traversed and written into the above
323 /// `Config` structure.
324 #[derive(Deserialize, Default)]
325 #[serde(deny_unknown_fields, rename_all = "kebab-case")]
326 struct TomlConfig {
327     changelog_seen: Option<usize>,
328     build: Option<Build>,
329     install: Option<Install>,
330     llvm: Option<Llvm>,
331     rust: Option<Rust>,
332     target: Option<HashMap<String, TomlTarget>>,
333     dist: Option<Dist>,
334     profile: Option<String>,
335 }
336
337 impl Merge for TomlConfig {
338     fn merge(
339         &mut self,
340         TomlConfig { build, install, llvm, rust, dist, target, profile: _, changelog_seen: _ }: Self,
341     ) {
342         fn do_merge<T: Merge>(x: &mut Option<T>, y: Option<T>) {
343             if let Some(new) = y {
344                 if let Some(original) = x {
345                     original.merge(new);
346                 } else {
347                     *x = Some(new);
348                 }
349             }
350         }
351         do_merge(&mut self.build, build);
352         do_merge(&mut self.install, install);
353         do_merge(&mut self.llvm, llvm);
354         do_merge(&mut self.rust, rust);
355         do_merge(&mut self.dist, dist);
356         assert!(target.is_none(), "merging target-specific config is not currently supported");
357     }
358 }
359
360 macro_rules! derive_merge {
361     ($(#[$attr:meta])* struct $name:ident {
362         $($field:ident: $field_ty:ty,)*
363     }) => {
364         $(#[$attr])*
365         struct $name {
366             $($field: $field_ty,)*
367         }
368
369         impl Merge for $name {
370             fn merge(&mut self, other: Self) {
371                 $(
372                     Merge::merge(&mut self.$field, other.$field);
373                 )*
374             }
375         }
376     }
377 }
378
379 derive_merge! {
380     /// TOML representation of various global build decisions.
381     #[derive(Deserialize, Default, Clone)]
382     #[serde(deny_unknown_fields, rename_all = "kebab-case")]
383     struct Build {
384         build: Option<String>,
385         host: Option<Vec<String>>,
386         target: Option<Vec<String>>,
387         // This is ignored, the rust code always gets the build directory from the `BUILD_DIR` env variable
388         build_dir: Option<String>,
389         cargo: Option<String>,
390         rustc: Option<String>,
391         rustfmt: Option<PathBuf>,
392         docs: Option<bool>,
393         compiler_docs: Option<bool>,
394         docs_minification: Option<bool>,
395         submodules: Option<bool>,
396         fast_submodules: Option<bool>,
397         gdb: Option<String>,
398         nodejs: Option<String>,
399         npm: Option<String>,
400         python: Option<String>,
401         locked_deps: Option<bool>,
402         vendor: Option<bool>,
403         full_bootstrap: Option<bool>,
404         extended: Option<bool>,
405         tools: Option<HashSet<String>>,
406         verbose: Option<usize>,
407         sanitizers: Option<bool>,
408         profiler: Option<bool>,
409         cargo_native_static: Option<bool>,
410         low_priority: Option<bool>,
411         configure_args: Option<Vec<String>>,
412         local_rebuild: Option<bool>,
413         print_step_timings: Option<bool>,
414         print_step_rusage: Option<bool>,
415         check_stage: Option<u32>,
416         doc_stage: Option<u32>,
417         build_stage: Option<u32>,
418         test_stage: Option<u32>,
419         install_stage: Option<u32>,
420         dist_stage: Option<u32>,
421         bench_stage: Option<u32>,
422         patch_binaries_for_nix: Option<bool>,
423     }
424 }
425
426 derive_merge! {
427     /// TOML representation of various global install decisions.
428     #[derive(Deserialize, Default, Clone)]
429     #[serde(deny_unknown_fields, rename_all = "kebab-case")]
430     struct Install {
431         prefix: Option<String>,
432         sysconfdir: Option<String>,
433         docdir: Option<String>,
434         bindir: Option<String>,
435         libdir: Option<String>,
436         mandir: Option<String>,
437         datadir: Option<String>,
438     }
439 }
440
441 derive_merge! {
442     /// TOML representation of how the LLVM build is configured.
443     #[derive(Deserialize, Default)]
444     #[serde(deny_unknown_fields, rename_all = "kebab-case")]
445     struct Llvm {
446         skip_rebuild: Option<bool>,
447         optimize: Option<bool>,
448         thin_lto: Option<bool>,
449         release_debuginfo: Option<bool>,
450         assertions: Option<bool>,
451         tests: Option<bool>,
452         plugins: Option<bool>,
453         ccache: Option<StringOrBool>,
454         version_check: Option<bool>,
455         static_libstdcpp: Option<bool>,
456         ninja: Option<bool>,
457         targets: Option<String>,
458         experimental_targets: Option<String>,
459         link_jobs: Option<u32>,
460         link_shared: Option<bool>,
461         version_suffix: Option<String>,
462         clang_cl: Option<String>,
463         cflags: Option<String>,
464         cxxflags: Option<String>,
465         ldflags: Option<String>,
466         use_libcxx: Option<bool>,
467         use_linker: Option<String>,
468         allow_old_toolchain: Option<bool>,
469         polly: Option<bool>,
470         clang: Option<bool>,
471         download_ci_llvm: Option<StringOrBool>,
472     }
473 }
474
475 derive_merge! {
476     #[derive(Deserialize, Default, Clone)]
477     #[serde(deny_unknown_fields, rename_all = "kebab-case")]
478     struct Dist {
479         sign_folder: Option<String>,
480         gpg_password_file: Option<String>,
481         upload_addr: Option<String>,
482         src_tarball: Option<bool>,
483         missing_tools: Option<bool>,
484         compression_formats: Option<Vec<String>>,
485     }
486 }
487
488 #[derive(Deserialize)]
489 #[serde(untagged)]
490 enum StringOrBool {
491     String(String),
492     Bool(bool),
493 }
494
495 impl Default for StringOrBool {
496     fn default() -> StringOrBool {
497         StringOrBool::Bool(false)
498     }
499 }
500
501 derive_merge! {
502     /// TOML representation of how the Rust build is configured.
503     #[derive(Deserialize, Default)]
504     #[serde(deny_unknown_fields, rename_all = "kebab-case")]
505     struct Rust {
506         optimize: Option<bool>,
507         debug: Option<bool>,
508         codegen_units: Option<u32>,
509         codegen_units_std: Option<u32>,
510         debug_assertions: Option<bool>,
511         debug_assertions_std: Option<bool>,
512         overflow_checks: Option<bool>,
513         overflow_checks_std: Option<bool>,
514         debug_logging: Option<bool>,
515         debuginfo_level: Option<u32>,
516         debuginfo_level_rustc: Option<u32>,
517         debuginfo_level_std: Option<u32>,
518         debuginfo_level_tools: Option<u32>,
519         debuginfo_level_tests: Option<u32>,
520         run_dsymutil: Option<bool>,
521         backtrace: Option<bool>,
522         incremental: Option<bool>,
523         parallel_compiler: Option<bool>,
524         default_linker: Option<String>,
525         channel: Option<String>,
526         description: Option<String>,
527         musl_root: Option<String>,
528         rpath: Option<bool>,
529         verbose_tests: Option<bool>,
530         optimize_tests: Option<bool>,
531         codegen_tests: Option<bool>,
532         ignore_git: Option<bool>,
533         dist_src: Option<bool>,
534         save_toolstates: Option<String>,
535         codegen_backends: Option<Vec<String>>,
536         lld: Option<bool>,
537         use_lld: Option<bool>,
538         llvm_tools: Option<bool>,
539         deny_warnings: Option<bool>,
540         backtrace_on_ice: Option<bool>,
541         verify_llvm_ir: Option<bool>,
542         thin_lto_import_instr_limit: Option<u32>,
543         remap_debuginfo: Option<bool>,
544         jemalloc: Option<bool>,
545         test_compare_mode: Option<bool>,
546         llvm_libunwind: Option<String>,
547         control_flow_guard: Option<bool>,
548         new_symbol_mangling: Option<bool>,
549         profile_generate: Option<String>,
550         profile_use: Option<String>,
551         // ignored; this is set from an env var set by bootstrap.py
552         download_rustc: Option<StringOrBool>,
553     }
554 }
555
556 derive_merge! {
557     /// TOML representation of how each build target is configured.
558     #[derive(Deserialize, Default)]
559     #[serde(deny_unknown_fields, rename_all = "kebab-case")]
560     struct TomlTarget {
561         cc: Option<String>,
562         cxx: Option<String>,
563         ar: Option<String>,
564         ranlib: Option<String>,
565         default_linker: Option<PathBuf>,
566         linker: Option<String>,
567         llvm_config: Option<String>,
568         llvm_filecheck: Option<String>,
569         android_ndk: Option<String>,
570         sanitizers: Option<bool>,
571         profiler: Option<bool>,
572         crt_static: Option<bool>,
573         musl_root: Option<String>,
574         musl_libdir: Option<String>,
575         wasi_root: Option<String>,
576         qemu_rootfs: Option<String>,
577         no_std: Option<bool>,
578     }
579 }
580
581 impl Config {
582     fn path_from_python(var_key: &str) -> PathBuf {
583         match env::var_os(var_key) {
584             Some(var_val) => Self::normalize_python_path(var_val),
585             _ => panic!("expected '{}' to be set", var_key),
586         }
587     }
588
589     /// Normalizes paths from Python slightly. We don't trust paths from Python (#49785).
590     fn normalize_python_path(path: OsString) -> PathBuf {
591         Path::new(&path).components().collect()
592     }
593
594     pub fn default_opts() -> Config {
595         let mut config = Config::default();
596         config.llvm_optimize = true;
597         config.ninja_in_file = true;
598         config.llvm_version_check = true;
599         config.backtrace = true;
600         config.rust_optimize = true;
601         config.rust_optimize_tests = true;
602         config.submodules = None;
603         config.fast_submodules = true;
604         config.docs = true;
605         config.docs_minification = true;
606         config.rust_rpath = true;
607         config.channel = "dev".to_string();
608         config.codegen_tests = true;
609         config.rust_dist_src = true;
610         config.rust_codegen_backends = vec![INTERNER.intern_str("llvm")];
611         config.deny_warnings = true;
612         config.bindir = "bin".into();
613
614         // set by build.rs
615         config.build = TargetSelection::from_user(&env!("BUILD_TRIPLE"));
616         let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
617         // Undo `src/bootstrap`
618         config.src = manifest_dir.parent().unwrap().parent().unwrap().to_owned();
619         config.out = Config::path_from_python("BUILD_DIR");
620
621         config.initial_cargo = PathBuf::from(env!("CARGO"));
622         config.initial_rustc = PathBuf::from(env!("RUSTC"));
623
624         config
625     }
626
627     pub fn parse(args: &[String]) -> Config {
628         let flags = Flags::parse(&args);
629
630         let mut config = Config::default_opts();
631         config.exclude = flags.exclude;
632         config.include_default_paths = flags.include_default_paths;
633         config.rustc_error_format = flags.rustc_error_format;
634         config.json_output = flags.json_output;
635         config.on_fail = flags.on_fail;
636         config.jobs = flags.jobs.map(threads_from_config);
637         config.cmd = flags.cmd;
638         config.incremental = flags.incremental;
639         config.dry_run = flags.dry_run;
640         config.keep_stage = flags.keep_stage;
641         config.keep_stage_std = flags.keep_stage_std;
642         config.color = flags.color;
643         if let Some(value) = flags.deny_warnings {
644             config.deny_warnings = value;
645         }
646         config.llvm_profile_use = flags.llvm_profile_use;
647         config.llvm_profile_generate = flags.llvm_profile_generate;
648
649         if config.dry_run {
650             let dir = config.out.join("tmp-dry-run");
651             t!(fs::create_dir_all(&dir));
652             config.out = dir;
653         }
654
655         #[cfg(test)]
656         let get_toml = |_| TomlConfig::default();
657         #[cfg(not(test))]
658         let get_toml = |file: &Path| {
659             use std::process;
660
661             let contents = t!(fs::read_to_string(file), "`include` config not found");
662             match toml::from_str(&contents) {
663                 Ok(table) => table,
664                 Err(err) => {
665                     println!("failed to parse TOML configuration '{}': {}", file.display(), err);
666                     process::exit(2);
667                 }
668             }
669         };
670
671         let mut toml = flags.config.as_deref().map(get_toml).unwrap_or_else(TomlConfig::default);
672         if let Some(include) = &toml.profile {
673             let mut include_path = config.src.clone();
674             include_path.push("src");
675             include_path.push("bootstrap");
676             include_path.push("defaults");
677             include_path.push(format!("config.{}.toml", include));
678             let included_toml = get_toml(&include_path);
679             toml.merge(included_toml);
680         }
681
682         config.changelog_seen = toml.changelog_seen;
683         if let Some(cfg) = flags.config {
684             config.config = cfg;
685         }
686
687         let build = toml.build.unwrap_or_default();
688
689         config.hosts = if let Some(arg_host) = flags.host {
690             arg_host
691         } else if let Some(file_host) = build.host {
692             file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
693         } else {
694             vec![config.build]
695         };
696         config.targets = if let Some(arg_target) = flags.target {
697             arg_target
698         } else if let Some(file_target) = build.target {
699             file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
700         } else {
701             // If target is *not* configured, then default to the host
702             // toolchains.
703             config.hosts.clone()
704         };
705
706         config.nodejs = build.nodejs.map(PathBuf::from);
707         config.npm = build.npm.map(PathBuf::from);
708         config.gdb = build.gdb.map(PathBuf::from);
709         config.python = build.python.map(PathBuf::from);
710         config.submodules = build.submodules;
711         set(&mut config.low_priority, build.low_priority);
712         set(&mut config.compiler_docs, build.compiler_docs);
713         set(&mut config.docs_minification, build.docs_minification);
714         set(&mut config.docs, build.docs);
715         set(&mut config.fast_submodules, build.fast_submodules);
716         set(&mut config.locked_deps, build.locked_deps);
717         set(&mut config.vendor, build.vendor);
718         set(&mut config.full_bootstrap, build.full_bootstrap);
719         set(&mut config.extended, build.extended);
720         config.tools = build.tools;
721         if build.rustfmt.is_some() {
722             config.initial_rustfmt = build.rustfmt;
723         }
724         set(&mut config.verbose, build.verbose);
725         set(&mut config.sanitizers, build.sanitizers);
726         set(&mut config.profiler, build.profiler);
727         set(&mut config.cargo_native_static, build.cargo_native_static);
728         set(&mut config.configure_args, build.configure_args);
729         set(&mut config.local_rebuild, build.local_rebuild);
730         set(&mut config.print_step_timings, build.print_step_timings);
731         set(&mut config.print_step_rusage, build.print_step_rusage);
732
733         config.verbose = cmp::max(config.verbose, flags.verbose);
734
735         if let Some(install) = toml.install {
736             config.prefix = install.prefix.map(PathBuf::from);
737             config.sysconfdir = install.sysconfdir.map(PathBuf::from);
738             config.datadir = install.datadir.map(PathBuf::from);
739             config.docdir = install.docdir.map(PathBuf::from);
740             set(&mut config.bindir, install.bindir.map(PathBuf::from));
741             config.libdir = install.libdir.map(PathBuf::from);
742             config.mandir = install.mandir.map(PathBuf::from);
743         }
744
745         // We want the llvm-skip-rebuild flag to take precedence over the
746         // skip-rebuild config.toml option so we store it separately
747         // so that we can infer the right value
748         let mut llvm_skip_rebuild = flags.llvm_skip_rebuild;
749
750         // Store off these values as options because if they're not provided
751         // we'll infer default values for them later
752         let mut llvm_assertions = None;
753         let mut llvm_tests = None;
754         let mut llvm_plugins = None;
755         let mut debug = None;
756         let mut debug_assertions = None;
757         let mut debug_assertions_std = None;
758         let mut overflow_checks = None;
759         let mut overflow_checks_std = None;
760         let mut debug_logging = None;
761         let mut debuginfo_level = None;
762         let mut debuginfo_level_rustc = None;
763         let mut debuginfo_level_std = None;
764         let mut debuginfo_level_tools = None;
765         let mut debuginfo_level_tests = None;
766         let mut optimize = None;
767         let mut ignore_git = None;
768
769         if let Some(llvm) = toml.llvm {
770             match llvm.ccache {
771                 Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
772                 Some(StringOrBool::Bool(true)) => {
773                     config.ccache = Some("ccache".to_string());
774                 }
775                 Some(StringOrBool::Bool(false)) | None => {}
776             }
777             set(&mut config.ninja_in_file, llvm.ninja);
778             llvm_assertions = llvm.assertions;
779             llvm_tests = llvm.tests;
780             llvm_plugins = llvm.plugins;
781             llvm_skip_rebuild = llvm_skip_rebuild.or(llvm.skip_rebuild);
782             set(&mut config.llvm_optimize, llvm.optimize);
783             set(&mut config.llvm_thin_lto, llvm.thin_lto);
784             set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
785             set(&mut config.llvm_version_check, llvm.version_check);
786             set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp);
787             set(&mut config.llvm_link_shared, llvm.link_shared);
788             config.llvm_targets = llvm.targets.clone();
789             config.llvm_experimental_targets = llvm.experimental_targets.clone();
790             config.llvm_link_jobs = llvm.link_jobs;
791             config.llvm_version_suffix = llvm.version_suffix.clone();
792             config.llvm_clang_cl = llvm.clang_cl.clone();
793
794             config.llvm_cflags = llvm.cflags.clone();
795             config.llvm_cxxflags = llvm.cxxflags.clone();
796             config.llvm_ldflags = llvm.ldflags.clone();
797             set(&mut config.llvm_use_libcxx, llvm.use_libcxx);
798             config.llvm_use_linker = llvm.use_linker.clone();
799             config.llvm_allow_old_toolchain = llvm.allow_old_toolchain.unwrap_or(false);
800             config.llvm_polly = llvm.polly.unwrap_or(false);
801             config.llvm_clang = llvm.clang.unwrap_or(false);
802             config.llvm_from_ci = match llvm.download_ci_llvm {
803                 Some(StringOrBool::String(s)) => {
804                     assert!(s == "if-available", "unknown option `{}` for download-ci-llvm", s);
805                     // This is currently all tier 1 targets and tier 2 targets with host tools
806                     // (since others may not have CI artifacts)
807                     // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
808                     // FIXME: this is duplicated in bootstrap.py
809                     let supported_platforms = [
810                         // tier 1
811                         "aarch64-unknown-linux-gnu",
812                         "i686-pc-windows-gnu",
813                         "i686-pc-windows-msvc",
814                         "i686-unknown-linux-gnu",
815                         "x86_64-unknown-linux-gnu",
816                         "x86_64-apple-darwin",
817                         "x86_64-pc-windows-gnu",
818                         "x86_64-pc-windows-msvc",
819                         // tier 2 with host tools
820                         "aarch64-apple-darwin",
821                         "aarch64-pc-windows-msvc",
822                         "aarch64-unknown-linux-musl",
823                         "arm-unknown-linux-gnueabi",
824                         "arm-unknown-linux-gnueabihf",
825                         "armv7-unknown-linux-gnueabihf",
826                         "mips-unknown-linux-gnu",
827                         "mips64-unknown-linux-gnuabi64",
828                         "mips64el-unknown-linux-gnuabi64",
829                         "mipsel-unknown-linux-gnu",
830                         "powerpc-unknown-linux-gnu",
831                         "powerpc64-unknown-linux-gnu",
832                         "powerpc64le-unknown-linux-gnu",
833                         "riscv64gc-unknown-linux-gnu",
834                         "s390x-unknown-linux-gnu",
835                         "x86_64-unknown-freebsd",
836                         "x86_64-unknown-illumos",
837                         "x86_64-unknown-linux-musl",
838                         "x86_64-unknown-netbsd",
839                     ];
840                     supported_platforms.contains(&&*config.build.triple)
841                 }
842                 Some(StringOrBool::Bool(b)) => b,
843                 None => false,
844             };
845
846             if config.llvm_from_ci {
847                 // None of the LLVM options, except assertions, are supported
848                 // when using downloaded LLVM. We could just ignore these but
849                 // that's potentially confusing, so force them to not be
850                 // explicitly set. The defaults and CI defaults don't
851                 // necessarily match but forcing people to match (somewhat
852                 // arbitrary) CI configuration locally seems bad/hard.
853                 check_ci_llvm!(llvm.optimize);
854                 check_ci_llvm!(llvm.thin_lto);
855                 check_ci_llvm!(llvm.release_debuginfo);
856                 check_ci_llvm!(llvm.link_shared);
857                 check_ci_llvm!(llvm.static_libstdcpp);
858                 check_ci_llvm!(llvm.targets);
859                 check_ci_llvm!(llvm.experimental_targets);
860                 check_ci_llvm!(llvm.link_jobs);
861                 check_ci_llvm!(llvm.clang_cl);
862                 check_ci_llvm!(llvm.version_suffix);
863                 check_ci_llvm!(llvm.cflags);
864                 check_ci_llvm!(llvm.cxxflags);
865                 check_ci_llvm!(llvm.ldflags);
866                 check_ci_llvm!(llvm.use_libcxx);
867                 check_ci_llvm!(llvm.use_linker);
868                 check_ci_llvm!(llvm.allow_old_toolchain);
869                 check_ci_llvm!(llvm.polly);
870                 check_ci_llvm!(llvm.clang);
871                 check_ci_llvm!(llvm.plugins);
872
873                 // CI-built LLVM can be either dynamic or static.
874                 let ci_llvm = config.out.join(&*config.build.triple).join("ci-llvm");
875                 config.llvm_link_shared = if config.dry_run {
876                     // just assume dynamic for now
877                     true
878                 } else {
879                     let link_type = t!(
880                         std::fs::read_to_string(ci_llvm.join("link-type.txt")),
881                         format!("CI llvm missing: {}", ci_llvm.display())
882                     );
883                     link_type == "dynamic"
884                 };
885             }
886
887             if config.llvm_thin_lto && llvm.link_shared.is_none() {
888                 // If we're building with ThinLTO on, by default we want to link
889                 // to LLVM shared, to avoid re-doing ThinLTO (which happens in
890                 // the link step) with each stage.
891                 config.llvm_link_shared = true;
892             }
893         }
894
895         if let Some(rust) = toml.rust {
896             debug = rust.debug;
897             debug_assertions = rust.debug_assertions;
898             debug_assertions_std = rust.debug_assertions_std;
899             overflow_checks = rust.overflow_checks;
900             overflow_checks_std = rust.overflow_checks_std;
901             debug_logging = rust.debug_logging;
902             debuginfo_level = rust.debuginfo_level;
903             debuginfo_level_rustc = rust.debuginfo_level_rustc;
904             debuginfo_level_std = rust.debuginfo_level_std;
905             debuginfo_level_tools = rust.debuginfo_level_tools;
906             debuginfo_level_tests = rust.debuginfo_level_tests;
907             config.rust_run_dsymutil = rust.run_dsymutil.unwrap_or(false);
908             optimize = rust.optimize;
909             ignore_git = rust.ignore_git;
910             config.rust_new_symbol_mangling = rust.new_symbol_mangling;
911             set(&mut config.rust_optimize_tests, rust.optimize_tests);
912             set(&mut config.codegen_tests, rust.codegen_tests);
913             set(&mut config.rust_rpath, rust.rpath);
914             set(&mut config.jemalloc, rust.jemalloc);
915             set(&mut config.test_compare_mode, rust.test_compare_mode);
916             config.llvm_libunwind = rust
917                 .llvm_libunwind
918                 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"))
919                 .unwrap_or_default();
920             set(&mut config.backtrace, rust.backtrace);
921             set(&mut config.channel, rust.channel);
922             config.description = rust.description;
923             set(&mut config.rust_dist_src, rust.dist_src);
924             set(&mut config.verbose_tests, rust.verbose_tests);
925             // in the case "false" is set explicitly, do not overwrite the command line args
926             if let Some(true) = rust.incremental {
927                 config.incremental = true;
928             }
929             set(&mut config.use_lld, rust.use_lld);
930             set(&mut config.lld_enabled, rust.lld);
931             set(&mut config.llvm_tools_enabled, rust.llvm_tools);
932             config.rustc_parallel = rust.parallel_compiler.unwrap_or(false);
933             config.rustc_default_linker = rust.default_linker;
934             config.musl_root = rust.musl_root.map(PathBuf::from);
935             config.save_toolstates = rust.save_toolstates.map(PathBuf::from);
936             set(&mut config.deny_warnings, flags.deny_warnings.or(rust.deny_warnings));
937             set(&mut config.backtrace_on_ice, rust.backtrace_on_ice);
938             set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir);
939             config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit;
940             set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo);
941             set(&mut config.control_flow_guard, rust.control_flow_guard);
942
943             if let Some(ref backends) = rust.codegen_backends {
944                 config.rust_codegen_backends =
945                     backends.iter().map(|s| INTERNER.intern_str(s)).collect();
946             }
947
948             config.rust_codegen_units = rust.codegen_units.map(threads_from_config);
949             config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config);
950             config.rust_profile_use = flags.rust_profile_use.or(rust.profile_use);
951             config.rust_profile_generate = flags.rust_profile_generate.or(rust.profile_generate);
952             config.download_rustc = env::var("BOOTSTRAP_DOWNLOAD_RUSTC").as_deref() == Ok("1");
953         } else {
954             config.rust_profile_use = flags.rust_profile_use;
955             config.rust_profile_generate = flags.rust_profile_generate;
956         }
957
958         if let Some(t) = toml.target {
959             for (triple, cfg) in t {
960                 let mut target = Target::from_triple(&triple);
961
962                 if let Some(ref s) = cfg.llvm_config {
963                     target.llvm_config = Some(config.src.join(s));
964                 }
965                 if let Some(ref s) = cfg.llvm_filecheck {
966                     target.llvm_filecheck = Some(config.src.join(s));
967                 }
968                 if let Some(ref s) = cfg.android_ndk {
969                     target.ndk = Some(config.src.join(s));
970                 }
971                 if let Some(s) = cfg.no_std {
972                     target.no_std = s;
973                 }
974                 target.cc = cfg.cc.map(PathBuf::from);
975                 target.cxx = cfg.cxx.map(PathBuf::from);
976                 target.ar = cfg.ar.map(PathBuf::from);
977                 target.ranlib = cfg.ranlib.map(PathBuf::from);
978                 target.linker = cfg.linker.map(PathBuf::from);
979                 target.crt_static = cfg.crt_static;
980                 target.musl_root = cfg.musl_root.map(PathBuf::from);
981                 target.musl_libdir = cfg.musl_libdir.map(PathBuf::from);
982                 target.wasi_root = cfg.wasi_root.map(PathBuf::from);
983                 target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from);
984                 target.sanitizers = cfg.sanitizers;
985                 target.profiler = cfg.profiler;
986
987                 config.target_config.insert(TargetSelection::from_user(&triple), target);
988             }
989         }
990
991         if config.llvm_from_ci {
992             let triple = &config.build.triple;
993             let mut build_target = config
994                 .target_config
995                 .entry(config.build)
996                 .or_insert_with(|| Target::from_triple(&triple));
997
998             check_ci_llvm!(build_target.llvm_config);
999             check_ci_llvm!(build_target.llvm_filecheck);
1000             let ci_llvm_bin = config.out.join(&*config.build.triple).join("ci-llvm/bin");
1001             build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", config.build)));
1002             build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", config.build)));
1003         }
1004
1005         if let Some(t) = toml.dist {
1006             config.dist_sign_folder = t.sign_folder.map(PathBuf::from);
1007             config.dist_upload_addr = t.upload_addr;
1008             config.dist_compression_formats = t.compression_formats;
1009             set(&mut config.rust_dist_src, t.src_tarball);
1010             set(&mut config.missing_tools, t.missing_tools);
1011         }
1012
1013         config.initial_rustfmt = config.initial_rustfmt.or_else({
1014             let build = config.build;
1015             let initial_rustc = &config.initial_rustc;
1016
1017             move || {
1018                 // Cargo does not provide a RUSTFMT environment variable, so we
1019                 // synthesize it manually.
1020                 let rustfmt = initial_rustc.with_file_name(exe("rustfmt", build));
1021
1022                 if rustfmt.exists() { Some(rustfmt) } else { None }
1023             }
1024         });
1025
1026         // Now that we've reached the end of our configuration, infer the
1027         // default values for all options that we haven't otherwise stored yet.
1028
1029         config.llvm_skip_rebuild = llvm_skip_rebuild.unwrap_or(false);
1030         config.llvm_assertions = llvm_assertions.unwrap_or(false);
1031         config.llvm_tests = llvm_tests.unwrap_or(false);
1032         config.llvm_plugins = llvm_plugins.unwrap_or(false);
1033         config.rust_optimize = optimize.unwrap_or(true);
1034
1035         let default = debug == Some(true);
1036         config.rust_debug_assertions = debug_assertions.unwrap_or(default);
1037         config.rust_debug_assertions_std =
1038             debug_assertions_std.unwrap_or(config.rust_debug_assertions);
1039         config.rust_overflow_checks = overflow_checks.unwrap_or(default);
1040         config.rust_overflow_checks_std =
1041             overflow_checks_std.unwrap_or(config.rust_overflow_checks);
1042
1043         config.rust_debug_logging = debug_logging.unwrap_or(config.rust_debug_assertions);
1044
1045         let with_defaults = |debuginfo_level_specific: Option<u32>| {
1046             debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
1047                 1
1048             } else {
1049                 0
1050             })
1051         };
1052         config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
1053         config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
1054         config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
1055         config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(0);
1056
1057         let default = config.channel == "dev";
1058         config.ignore_git = ignore_git.unwrap_or(default);
1059
1060         let download_rustc = config.download_rustc;
1061         // See https://github.com/rust-lang/compiler-team/issues/326
1062         config.stage = match config.cmd {
1063             Subcommand::Check { .. } => flags.stage.or(build.check_stage).unwrap_or(0),
1064             // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden.
1065             Subcommand::Doc { .. } => {
1066                 flags.stage.or(build.doc_stage).unwrap_or(if download_rustc { 2 } else { 0 })
1067             }
1068             Subcommand::Build { .. } => {
1069                 flags.stage.or(build.build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1070             }
1071             Subcommand::Test { .. } => {
1072                 flags.stage.or(build.test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
1073             }
1074             Subcommand::Bench { .. } => flags.stage.or(build.bench_stage).unwrap_or(2),
1075             Subcommand::Dist { .. } => flags.stage.or(build.dist_stage).unwrap_or(2),
1076             Subcommand::Install { .. } => flags.stage.or(build.install_stage).unwrap_or(2),
1077             // These are all bootstrap tools, which don't depend on the compiler.
1078             // The stage we pass shouldn't matter, but use 0 just in case.
1079             Subcommand::Clean { .. }
1080             | Subcommand::Clippy { .. }
1081             | Subcommand::Fix { .. }
1082             | Subcommand::Run { .. }
1083             | Subcommand::Setup { .. }
1084             | Subcommand::Format { .. } => flags.stage.unwrap_or(0),
1085         };
1086
1087         // CI should always run stage 2 builds, unless it specifically states otherwise
1088         #[cfg(not(test))]
1089         if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None {
1090             match config.cmd {
1091                 Subcommand::Test { .. }
1092                 | Subcommand::Doc { .. }
1093                 | Subcommand::Build { .. }
1094                 | Subcommand::Bench { .. }
1095                 | Subcommand::Dist { .. }
1096                 | Subcommand::Install { .. } => {
1097                     assert_eq!(
1098                         config.stage, 2,
1099                         "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
1100                         config.stage,
1101                     );
1102                 }
1103                 Subcommand::Clean { .. }
1104                 | Subcommand::Check { .. }
1105                 | Subcommand::Clippy { .. }
1106                 | Subcommand::Fix { .. }
1107                 | Subcommand::Run { .. }
1108                 | Subcommand::Setup { .. }
1109                 | Subcommand::Format { .. } => {}
1110             }
1111         }
1112
1113         config
1114     }
1115
1116     /// Try to find the relative path of `bindir`, otherwise return it in full.
1117     pub fn bindir_relative(&self) -> &Path {
1118         let bindir = &self.bindir;
1119         if bindir.is_absolute() {
1120             // Try to make it relative to the prefix.
1121             if let Some(prefix) = &self.prefix {
1122                 if let Ok(stripped) = bindir.strip_prefix(prefix) {
1123                     return stripped;
1124                 }
1125             }
1126         }
1127         bindir
1128     }
1129
1130     /// Try to find the relative path of `libdir`.
1131     pub fn libdir_relative(&self) -> Option<&Path> {
1132         let libdir = self.libdir.as_ref()?;
1133         if libdir.is_relative() {
1134             Some(libdir)
1135         } else {
1136             // Try to make it relative to the prefix.
1137             libdir.strip_prefix(self.prefix.as_ref()?).ok()
1138         }
1139     }
1140
1141     pub fn verbose(&self) -> bool {
1142         self.verbose > 0
1143     }
1144
1145     pub fn very_verbose(&self) -> bool {
1146         self.verbose > 1
1147     }
1148
1149     pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1150         self.target_config.get(&target).map(|t| t.sanitizers).flatten().unwrap_or(self.sanitizers)
1151     }
1152
1153     pub fn any_sanitizers_enabled(&self) -> bool {
1154         self.target_config.values().any(|t| t.sanitizers == Some(true)) || self.sanitizers
1155     }
1156
1157     pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1158         self.target_config.get(&target).map(|t| t.profiler).flatten().unwrap_or(self.profiler)
1159     }
1160
1161     pub fn any_profiler_enabled(&self) -> bool {
1162         self.target_config.values().any(|t| t.profiler == Some(true)) || self.profiler
1163     }
1164
1165     pub fn llvm_enabled(&self) -> bool {
1166         self.rust_codegen_backends.contains(&INTERNER.intern_str("llvm"))
1167     }
1168
1169     pub fn submodules(&self, rust_info: &GitInfo) -> bool {
1170         self.submodules.unwrap_or(rust_info.is_git())
1171     }
1172 }
1173
1174 fn set<T>(field: &mut T, val: Option<T>) {
1175     if let Some(v) = val {
1176         *field = v;
1177     }
1178 }
1179
1180 fn threads_from_config(v: u32) -> u32 {
1181     match v {
1182         0 => num_cpus::get() as u32,
1183         n => n,
1184     }
1185 }