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