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