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