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