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