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