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