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