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