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