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