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