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