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