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