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