]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/config.rs
Auto merge of #85903 - bjorn3:rustc_serialize_cleanup, r=varkor
[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     // ignored; this is set from an env var set by bootstrap.py
509     download_rustc: Option<StringOrBool>,
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.docs_minification = true;
559         config.rust_rpath = true;
560         config.channel = "dev".to_string();
561         config.codegen_tests = true;
562         config.rust_dist_src = true;
563         config.rust_codegen_backends = vec![INTERNER.intern_str("llvm")];
564         config.deny_warnings = true;
565         config.bindir = "bin".into();
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.color = flags.color;
596         if let Some(value) = flags.deny_warnings {
597             config.deny_warnings = value;
598         }
599
600         if config.dry_run {
601             let dir = config.out.join("tmp-dry-run");
602             t!(fs::create_dir_all(&dir));
603             config.out = dir;
604         }
605
606         #[cfg(test)]
607         let get_toml = |_| TomlConfig::default();
608         #[cfg(not(test))]
609         let get_toml = |file: &Path| {
610             use std::process;
611
612             let contents = t!(fs::read_to_string(file), "`include` config not found");
613             match toml::from_str(&contents) {
614                 Ok(table) => table,
615                 Err(err) => {
616                     println!("failed to parse TOML configuration '{}': {}", file.display(), err);
617                     process::exit(2);
618                 }
619             }
620         };
621
622         let mut toml = flags.config.as_deref().map(get_toml).unwrap_or_else(TomlConfig::default);
623         if let Some(include) = &toml.profile {
624             let mut include_path = config.src.clone();
625             include_path.push("src");
626             include_path.push("bootstrap");
627             include_path.push("defaults");
628             include_path.push(format!("config.{}.toml", include));
629             let included_toml = get_toml(&include_path);
630             toml.merge(included_toml);
631         }
632
633         config.changelog_seen = toml.changelog_seen;
634         if let Some(cfg) = flags.config {
635             config.config = cfg;
636         }
637
638         let build = toml.build.unwrap_or_default();
639
640         config.hosts = if let Some(arg_host) = flags.host {
641             arg_host
642         } else if let Some(file_host) = build.host {
643             file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
644         } else {
645             vec![config.build]
646         };
647         config.targets = if let Some(arg_target) = flags.target {
648             arg_target
649         } else if let Some(file_target) = build.target {
650             file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
651         } else {
652             // If target is *not* configured, then default to the host
653             // toolchains.
654             config.hosts.clone()
655         };
656
657         config.nodejs = build.nodejs.map(PathBuf::from);
658         config.npm = build.npm.map(PathBuf::from);
659         config.gdb = build.gdb.map(PathBuf::from);
660         config.python = build.python.map(PathBuf::from);
661         set(&mut config.low_priority, build.low_priority);
662         set(&mut config.compiler_docs, build.compiler_docs);
663         set(&mut config.docs_minification, build.docs_minification);
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         set(&mut config.print_step_rusage, build.print_step_rusage);
683
684         config.verbose = cmp::max(config.verbose, flags.verbose);
685
686         if let Some(install) = toml.install {
687             config.prefix = install.prefix.map(PathBuf::from);
688             config.sysconfdir = install.sysconfdir.map(PathBuf::from);
689             config.datadir = install.datadir.map(PathBuf::from);
690             config.docdir = install.docdir.map(PathBuf::from);
691             set(&mut config.bindir, install.bindir.map(PathBuf::from));
692             config.libdir = install.libdir.map(PathBuf::from);
693             config.mandir = install.mandir.map(PathBuf::from);
694         }
695
696         // We want the llvm-skip-rebuild flag to take precedence over the
697         // skip-rebuild config.toml option so we store it separately
698         // so that we can infer the right value
699         let mut llvm_skip_rebuild = flags.llvm_skip_rebuild;
700
701         // Store off these values as options because if they're not provided
702         // we'll infer default values for them later
703         let mut llvm_assertions = None;
704         let mut debug = None;
705         let mut debug_assertions = None;
706         let mut debug_assertions_std = None;
707         let mut debug_logging = None;
708         let mut debuginfo_level = None;
709         let mut debuginfo_level_rustc = None;
710         let mut debuginfo_level_std = None;
711         let mut debuginfo_level_tools = None;
712         let mut debuginfo_level_tests = None;
713         let mut optimize = None;
714         let mut ignore_git = None;
715
716         if let Some(llvm) = toml.llvm {
717             match llvm.ccache {
718                 Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
719                 Some(StringOrBool::Bool(true)) => {
720                     config.ccache = Some("ccache".to_string());
721                 }
722                 Some(StringOrBool::Bool(false)) | None => {}
723             }
724             set(&mut config.ninja_in_file, llvm.ninja);
725             llvm_assertions = llvm.assertions;
726             llvm_skip_rebuild = llvm_skip_rebuild.or(llvm.skip_rebuild);
727             set(&mut config.llvm_optimize, llvm.optimize);
728             set(&mut config.llvm_thin_lto, llvm.thin_lto);
729             set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
730             set(&mut config.llvm_version_check, llvm.version_check);
731             set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp);
732             set(&mut config.llvm_link_shared, llvm.link_shared);
733             config.llvm_targets = llvm.targets.clone();
734             config.llvm_experimental_targets = llvm.experimental_targets.clone();
735             config.llvm_link_jobs = llvm.link_jobs;
736             config.llvm_version_suffix = llvm.version_suffix.clone();
737             config.llvm_clang_cl = llvm.clang_cl.clone();
738
739             config.llvm_cflags = llvm.cflags.clone();
740             config.llvm_cxxflags = llvm.cxxflags.clone();
741             config.llvm_ldflags = llvm.ldflags.clone();
742             set(&mut config.llvm_use_libcxx, llvm.use_libcxx);
743             config.llvm_use_linker = llvm.use_linker.clone();
744             config.llvm_allow_old_toolchain = llvm.allow_old_toolchain.unwrap_or(false);
745             config.llvm_polly = llvm.polly.unwrap_or(false);
746             config.llvm_from_ci = match llvm.download_ci_llvm {
747                 Some(StringOrBool::String(s)) => {
748                     assert!(s == "if-available", "unknown option `{}` for download-ci-llvm", s);
749                     // This is currently all tier 1 targets (since others may not have CI artifacts)
750                     // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
751                     // FIXME: this is duplicated in bootstrap.py
752                     let supported_platforms = [
753                         "aarch64-unknown-linux-gnu",
754                         "i686-pc-windows-gnu",
755                         "i686-pc-windows-msvc",
756                         "i686-unknown-linux-gnu",
757                         "x86_64-unknown-linux-gnu",
758                         "x86_64-apple-darwin",
759                         "x86_64-pc-windows-gnu",
760                         "x86_64-pc-windows-msvc",
761                     ];
762                     supported_platforms.contains(&&*config.build.triple)
763                 }
764                 Some(StringOrBool::Bool(b)) => b,
765                 None => false,
766             };
767
768             if config.llvm_from_ci {
769                 // None of the LLVM options, except assertions, are supported
770                 // when using downloaded LLVM. We could just ignore these but
771                 // that's potentially confusing, so force them to not be
772                 // explicitly set. The defaults and CI defaults don't
773                 // necessarily match but forcing people to match (somewhat
774                 // arbitrary) CI configuration locally seems bad/hard.
775                 check_ci_llvm!(llvm.optimize);
776                 check_ci_llvm!(llvm.thin_lto);
777                 check_ci_llvm!(llvm.release_debuginfo);
778                 check_ci_llvm!(llvm.link_shared);
779                 check_ci_llvm!(llvm.static_libstdcpp);
780                 check_ci_llvm!(llvm.targets);
781                 check_ci_llvm!(llvm.experimental_targets);
782                 check_ci_llvm!(llvm.link_jobs);
783                 check_ci_llvm!(llvm.clang_cl);
784                 check_ci_llvm!(llvm.version_suffix);
785                 check_ci_llvm!(llvm.cflags);
786                 check_ci_llvm!(llvm.cxxflags);
787                 check_ci_llvm!(llvm.ldflags);
788                 check_ci_llvm!(llvm.use_libcxx);
789                 check_ci_llvm!(llvm.use_linker);
790                 check_ci_llvm!(llvm.allow_old_toolchain);
791                 check_ci_llvm!(llvm.polly);
792
793                 // CI-built LLVM can be either dynamic or static.
794                 let ci_llvm = config.out.join(&*config.build.triple).join("ci-llvm");
795                 let link_type = t!(std::fs::read_to_string(ci_llvm.join("link-type.txt")));
796                 config.llvm_link_shared = link_type == "dynamic";
797             }
798
799             if config.llvm_thin_lto {
800                 // If we're building with ThinLTO on, we want to link to LLVM
801                 // shared, to avoid re-doing ThinLTO (which happens in the link
802                 // step) with each stage.
803                 assert_ne!(
804                     llvm.link_shared,
805                     Some(false),
806                     "setting link-shared=false is incompatible with thin-lto=true"
807                 );
808                 config.llvm_link_shared = true;
809             }
810         }
811
812         if let Some(rust) = toml.rust {
813             debug = rust.debug;
814             debug_assertions = rust.debug_assertions;
815             debug_assertions_std = rust.debug_assertions_std;
816             debug_logging = rust.debug_logging;
817             debuginfo_level = rust.debuginfo_level;
818             debuginfo_level_rustc = rust.debuginfo_level_rustc;
819             debuginfo_level_std = rust.debuginfo_level_std;
820             debuginfo_level_tools = rust.debuginfo_level_tools;
821             debuginfo_level_tests = rust.debuginfo_level_tests;
822             config.rust_run_dsymutil = rust.run_dsymutil.unwrap_or(false);
823             optimize = rust.optimize;
824             ignore_git = rust.ignore_git;
825             set(&mut config.rust_new_symbol_mangling, rust.new_symbol_mangling);
826             set(&mut config.rust_optimize_tests, rust.optimize_tests);
827             set(&mut config.codegen_tests, rust.codegen_tests);
828             set(&mut config.rust_rpath, rust.rpath);
829             set(&mut config.jemalloc, rust.jemalloc);
830             set(&mut config.test_compare_mode, rust.test_compare_mode);
831             config.llvm_libunwind = rust
832                 .llvm_libunwind
833                 .map(|v| v.parse().expect("failed to parse rust.llvm-libunwind"))
834                 .unwrap_or_default();
835             set(&mut config.backtrace, rust.backtrace);
836             set(&mut config.channel, rust.channel);
837             config.description = rust.description;
838             set(&mut config.rust_dist_src, rust.dist_src);
839             set(&mut config.verbose_tests, rust.verbose_tests);
840             // in the case "false" is set explicitly, do not overwrite the command line args
841             if let Some(true) = rust.incremental {
842                 config.incremental = true;
843             }
844             set(&mut config.use_lld, rust.use_lld);
845             set(&mut config.lld_enabled, rust.lld);
846             set(&mut config.llvm_tools_enabled, rust.llvm_tools);
847             config.rustc_parallel = rust.parallel_compiler.unwrap_or(false);
848             config.rustc_default_linker = rust.default_linker;
849             config.musl_root = rust.musl_root.map(PathBuf::from);
850             config.save_toolstates = rust.save_toolstates.map(PathBuf::from);
851             set(&mut config.deny_warnings, flags.deny_warnings.or(rust.deny_warnings));
852             set(&mut config.backtrace_on_ice, rust.backtrace_on_ice);
853             set(&mut config.rust_verify_llvm_ir, rust.verify_llvm_ir);
854             config.rust_thin_lto_import_instr_limit = rust.thin_lto_import_instr_limit;
855             set(&mut config.rust_remap_debuginfo, rust.remap_debuginfo);
856             set(&mut config.control_flow_guard, rust.control_flow_guard);
857
858             if let Some(ref backends) = rust.codegen_backends {
859                 config.rust_codegen_backends =
860                     backends.iter().map(|s| INTERNER.intern_str(s)).collect();
861             }
862
863             config.rust_codegen_units = rust.codegen_units.map(threads_from_config);
864             config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config);
865             config.rust_profile_use = flags.rust_profile_use.or(rust.profile_use);
866             config.rust_profile_generate = flags.rust_profile_generate.or(rust.profile_generate);
867             config.download_rustc = env::var("BOOTSTRAP_DOWNLOAD_RUSTC").as_deref() == Ok("1");
868         } else {
869             config.rust_profile_use = flags.rust_profile_use;
870             config.rust_profile_generate = flags.rust_profile_generate;
871         }
872
873         if let Some(t) = toml.target {
874             for (triple, cfg) in t {
875                 let mut target = Target::from_triple(&triple);
876
877                 if let Some(ref s) = cfg.llvm_config {
878                     target.llvm_config = Some(config.src.join(s));
879                 }
880                 if let Some(ref s) = cfg.llvm_filecheck {
881                     target.llvm_filecheck = Some(config.src.join(s));
882                 }
883                 if let Some(ref s) = cfg.android_ndk {
884                     target.ndk = Some(config.src.join(s));
885                 }
886                 if let Some(s) = cfg.no_std {
887                     target.no_std = s;
888                 }
889                 target.cc = cfg.cc.map(PathBuf::from);
890                 target.cxx = cfg.cxx.map(PathBuf::from);
891                 target.ar = cfg.ar.map(PathBuf::from);
892                 target.ranlib = cfg.ranlib.map(PathBuf::from);
893                 target.linker = cfg.linker.map(PathBuf::from);
894                 target.crt_static = cfg.crt_static;
895                 target.musl_root = cfg.musl_root.map(PathBuf::from);
896                 target.musl_libdir = cfg.musl_libdir.map(PathBuf::from);
897                 target.wasi_root = cfg.wasi_root.map(PathBuf::from);
898                 target.qemu_rootfs = cfg.qemu_rootfs.map(PathBuf::from);
899                 target.sanitizers = cfg.sanitizers;
900                 target.profiler = cfg.profiler;
901
902                 config.target_config.insert(TargetSelection::from_user(&triple), target);
903             }
904         }
905
906         if config.llvm_from_ci {
907             let triple = &config.build.triple;
908             let mut build_target = config
909                 .target_config
910                 .entry(config.build)
911                 .or_insert_with(|| Target::from_triple(&triple));
912
913             check_ci_llvm!(build_target.llvm_config);
914             check_ci_llvm!(build_target.llvm_filecheck);
915             let ci_llvm_bin = config.out.join(&*config.build.triple).join("ci-llvm/bin");
916             build_target.llvm_config = Some(ci_llvm_bin.join(exe("llvm-config", config.build)));
917             build_target.llvm_filecheck = Some(ci_llvm_bin.join(exe("FileCheck", config.build)));
918         }
919
920         if let Some(t) = toml.dist {
921             config.dist_sign_folder = t.sign_folder.map(PathBuf::from);
922             config.dist_upload_addr = t.upload_addr;
923             config.dist_compression_formats = t.compression_formats;
924             set(&mut config.rust_dist_src, t.src_tarball);
925             set(&mut config.missing_tools, t.missing_tools);
926         }
927
928         config.initial_rustfmt = config.initial_rustfmt.or_else({
929             let build = config.build;
930             let initial_rustc = &config.initial_rustc;
931
932             move || {
933                 // Cargo does not provide a RUSTFMT environment variable, so we
934                 // synthesize it manually.
935                 let rustfmt = initial_rustc.with_file_name(exe("rustfmt", build));
936
937                 if rustfmt.exists() { Some(rustfmt) } else { None }
938             }
939         });
940
941         // Now that we've reached the end of our configuration, infer the
942         // default values for all options that we haven't otherwise stored yet.
943
944         config.llvm_skip_rebuild = llvm_skip_rebuild.unwrap_or(false);
945         config.llvm_assertions = llvm_assertions.unwrap_or(false);
946         config.rust_optimize = optimize.unwrap_or(true);
947
948         let default = debug == Some(true);
949         config.rust_debug_assertions = debug_assertions.unwrap_or(default);
950         config.rust_debug_assertions_std =
951             debug_assertions_std.unwrap_or(config.rust_debug_assertions);
952
953         config.rust_debug_logging = debug_logging.unwrap_or(config.rust_debug_assertions);
954
955         let with_defaults = |debuginfo_level_specific: Option<u32>| {
956             debuginfo_level_specific.or(debuginfo_level).unwrap_or(if debug == Some(true) {
957                 1
958             } else {
959                 0
960             })
961         };
962         config.rust_debuginfo_level_rustc = with_defaults(debuginfo_level_rustc);
963         config.rust_debuginfo_level_std = with_defaults(debuginfo_level_std);
964         config.rust_debuginfo_level_tools = with_defaults(debuginfo_level_tools);
965         config.rust_debuginfo_level_tests = debuginfo_level_tests.unwrap_or(0);
966
967         let default = config.channel == "dev";
968         config.ignore_git = ignore_git.unwrap_or(default);
969
970         let download_rustc = config.download_rustc;
971         // See https://github.com/rust-lang/compiler-team/issues/326
972         config.stage = match config.cmd {
973             Subcommand::Check { .. } => flags.stage.or(build.check_stage).unwrap_or(0),
974             // `download-rustc` only has a speed-up for stage2 builds. Default to stage2 unless explicitly overridden.
975             Subcommand::Doc { .. } => {
976                 flags.stage.or(build.doc_stage).unwrap_or(if download_rustc { 2 } else { 0 })
977             }
978             Subcommand::Build { .. } => {
979                 flags.stage.or(build.build_stage).unwrap_or(if download_rustc { 2 } else { 1 })
980             }
981             Subcommand::Test { .. } => {
982                 flags.stage.or(build.test_stage).unwrap_or(if download_rustc { 2 } else { 1 })
983             }
984             Subcommand::Bench { .. } => flags.stage.or(build.bench_stage).unwrap_or(2),
985             Subcommand::Dist { .. } => flags.stage.or(build.dist_stage).unwrap_or(2),
986             Subcommand::Install { .. } => flags.stage.or(build.install_stage).unwrap_or(2),
987             // These are all bootstrap tools, which don't depend on the compiler.
988             // The stage we pass shouldn't matter, but use 0 just in case.
989             Subcommand::Clean { .. }
990             | Subcommand::Clippy { .. }
991             | Subcommand::Fix { .. }
992             | Subcommand::Run { .. }
993             | Subcommand::Setup { .. }
994             | Subcommand::Format { .. } => flags.stage.unwrap_or(0),
995         };
996
997         // CI should always run stage 2 builds, unless it specifically states otherwise
998         #[cfg(not(test))]
999         if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None {
1000             match config.cmd {
1001                 Subcommand::Test { .. }
1002                 | Subcommand::Doc { .. }
1003                 | Subcommand::Build { .. }
1004                 | Subcommand::Bench { .. }
1005                 | Subcommand::Dist { .. }
1006                 | Subcommand::Install { .. } => {
1007                     assert_eq!(
1008                         config.stage, 2,
1009                         "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
1010                         config.stage,
1011                     );
1012                 }
1013                 Subcommand::Clean { .. }
1014                 | Subcommand::Check { .. }
1015                 | Subcommand::Clippy { .. }
1016                 | Subcommand::Fix { .. }
1017                 | Subcommand::Run { .. }
1018                 | Subcommand::Setup { .. }
1019                 | Subcommand::Format { .. } => {}
1020             }
1021         }
1022
1023         config
1024     }
1025
1026     /// Try to find the relative path of `bindir`, otherwise return it in full.
1027     pub fn bindir_relative(&self) -> &Path {
1028         let bindir = &self.bindir;
1029         if bindir.is_absolute() {
1030             // Try to make it relative to the prefix.
1031             if let Some(prefix) = &self.prefix {
1032                 if let Ok(stripped) = bindir.strip_prefix(prefix) {
1033                     return stripped;
1034                 }
1035             }
1036         }
1037         bindir
1038     }
1039
1040     /// Try to find the relative path of `libdir`.
1041     pub fn libdir_relative(&self) -> Option<&Path> {
1042         let libdir = self.libdir.as_ref()?;
1043         if libdir.is_relative() {
1044             Some(libdir)
1045         } else {
1046             // Try to make it relative to the prefix.
1047             libdir.strip_prefix(self.prefix.as_ref()?).ok()
1048         }
1049     }
1050
1051     pub fn verbose(&self) -> bool {
1052         self.verbose > 0
1053     }
1054
1055     pub fn very_verbose(&self) -> bool {
1056         self.verbose > 1
1057     }
1058
1059     pub fn sanitizers_enabled(&self, target: TargetSelection) -> bool {
1060         self.target_config.get(&target).map(|t| t.sanitizers).flatten().unwrap_or(self.sanitizers)
1061     }
1062
1063     pub fn any_sanitizers_enabled(&self) -> bool {
1064         self.target_config.values().any(|t| t.sanitizers == Some(true)) || self.sanitizers
1065     }
1066
1067     pub fn profiler_enabled(&self, target: TargetSelection) -> bool {
1068         self.target_config.get(&target).map(|t| t.profiler).flatten().unwrap_or(self.profiler)
1069     }
1070
1071     pub fn any_profiler_enabled(&self) -> bool {
1072         self.target_config.values().any(|t| t.profiler == Some(true)) || self.profiler
1073     }
1074
1075     pub fn llvm_enabled(&self) -> bool {
1076         self.rust_codegen_backends.contains(&INTERNER.intern_str("llvm"))
1077     }
1078 }
1079
1080 fn set<T>(field: &mut T, val: Option<T>) {
1081     if let Some(v) = val {
1082         *field = v;
1083     }
1084 }
1085
1086 fn threads_from_config(v: u32) -> u32 {
1087     match v {
1088         0 => num_cpus::get() as u32,
1089         n => n,
1090     }
1091 }