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