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