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