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