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