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