forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
1828 lines (1629 loc) · 73.3 KB
/
Copy pathconfig.rs
File metadata and controls
1828 lines (1629 loc) · 73.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module defines the central `Config` struct, which aggregates all components
//! of the bootstrap configuration into a single unit.
//!
//! It serves as the primary public interface for accessing the bootstrap configuration.
//! The module coordinates the overall configuration parsing process using logic from `parsing.rs`
//! and provides top-level methods such as `Config::parse()` for initialization, as well as
//! utility methods for querying and manipulating the complete configuration state.
//!
//! Additionally, this module contains the core logic for parsing, validating, and inferring
//! the final `Config` from various raw inputs.
//!
//! It manages the process of reading command-line arguments, environment variables,
//! and the `bootstrap.toml` file—merging them, applying defaults, and performing
//! cross-component validation. The main `parse_inner` function and its supporting
//! helpers reside here, transforming raw `Toml` data into the structured `Config` type.
use std::cell::Cell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::io::IsTerminal;
use std::path::{Path, PathBuf, absolute};
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::{cmp, env, fs};
use build_helper::ci::CiEnv;
use build_helper::exit;
use build_helper::git::{GitConfig, PathFreshness, check_path_modifications};
use serde::Deserialize;
#[cfg(feature = "tracing")]
use tracing::{instrument, span};
use crate::core::build_steps::llvm;
use crate::core::build_steps::llvm::LLVM_INVALIDATION_PATHS;
pub use crate::core::config::flags::Subcommand;
use crate::core::config::flags::{Color, Flags};
use crate::core::config::target_selection::TargetSelectionList;
use crate::core::config::toml::TomlConfig;
use crate::core::config::toml::build::{Build, Tool};
use crate::core::config::toml::change_id::ChangeId;
use crate::core::config::toml::rust::{
LldMode, RustOptimize, check_incompatible_options_for_ci_rustc,
};
use crate::core::config::toml::target::Target;
use crate::core::config::{
DebuginfoLevel, DryRun, GccCiMode, LlvmLibunwind, Merge, ReplaceOpt, RustcLto, SplitDebuginfo,
StringOrBool, set, threads_from_config,
};
use crate::core::download::is_download_ci_available;
use crate::utils::channel;
use crate::utils::exec::{ExecutionContext, command};
use crate::utils::helpers::{exe, get_host_target};
use crate::{GitInfo, OnceLock, TargetSelection, check_ci_llvm, helpers, t};
/// Each path in this list is considered "allowed" in the `download-rustc="if-unchanged"` logic.
/// This means they can be modified and changes to these paths should never trigger a compiler build
/// when "if-unchanged" is set.
///
/// NOTE: Paths must have the ":!" prefix to tell git to ignore changes in those paths during
/// the diff check.
///
/// WARNING: Be cautious when adding paths to this list. If a path that influences the compiler build
/// is added here, it will cause bootstrap to skip necessary rebuilds, which may lead to risky results.
/// For example, "src/bootstrap" should never be included in this list as it plays a crucial role in the
/// final output/compiler, which can be significantly affected by changes made to the bootstrap sources.
#[rustfmt::skip] // We don't want rustfmt to oneline this list
pub const RUSTC_IF_UNCHANGED_ALLOWED_PATHS: &[&str] = &[
":!library",
":!src/tools",
":!src/librustdoc",
":!src/rustdoc-json-types",
":!tests",
":!triagebot.toml",
];
/// Global configuration for the entire build and/or bootstrap.
///
/// This structure is parsed from `bootstrap.toml`, and some of the fields are inferred from `git` or build-time parameters.
///
/// Note that this structure is not decoded directly into, but rather it is
/// filled out from the decoded forms of the structs below. For documentation
/// on each field, see the corresponding fields in
/// `bootstrap.example.toml`.
#[derive(Default, Clone)]
pub struct Config {
pub change_id: Option<ChangeId>,
pub bypass_bootstrap_lock: bool,
pub ccache: Option<String>,
/// Call Build::ninja() instead of this.
pub ninja_in_file: bool,
pub verbose: usize,
pub submodules: Option<bool>,
pub compiler_docs: bool,
pub library_docs_private_items: bool,
pub docs_minification: bool,
pub docs: bool,
pub locked_deps: bool,
pub vendor: bool,
pub target_config: HashMap<TargetSelection, Target>,
pub full_bootstrap: bool,
pub bootstrap_cache_path: Option<PathBuf>,
pub extended: bool,
pub tools: Option<HashSet<String>>,
/// Specify build configuration specific for some tool, such as enabled features, see [Tool].
/// The key in the map is the name of the tool, and the value is tool-specific configuration.
pub tool: HashMap<String, Tool>,
pub sanitizers: bool,
pub profiler: bool,
pub omit_git_hash: bool,
pub skip: Vec<PathBuf>,
pub include_default_paths: bool,
pub rustc_error_format: Option<String>,
pub json_output: bool,
pub compile_time_deps: bool,
pub test_compare_mode: bool,
pub color: Color,
pub patch_binaries_for_nix: Option<bool>,
pub stage0_metadata: build_helper::stage0_parser::Stage0,
pub android_ndk: Option<PathBuf>,
/// Whether to use the `c` feature of the `compiler_builtins` crate.
pub optimized_compiler_builtins: bool,
pub stdout_is_tty: bool,
pub stderr_is_tty: bool,
pub on_fail: Option<String>,
pub explicit_stage_from_cli: bool,
pub explicit_stage_from_config: bool,
pub stage: u32,
pub keep_stage: Vec<u32>,
pub keep_stage_std: Vec<u32>,
pub src: PathBuf,
/// defaults to `bootstrap.toml`
pub config: Option<PathBuf>,
pub jobs: Option<u32>,
pub cmd: Subcommand,
pub incremental: bool,
pub dump_bootstrap_shims: bool,
/// Arguments appearing after `--` to be forwarded to tools,
/// e.g. `--fix-broken` or test arguments.
pub free_args: Vec<String>,
/// `None` if we shouldn't download CI compiler artifacts, or the commit to download if we should.
pub download_rustc_commit: Option<String>,
pub deny_warnings: bool,
pub backtrace_on_ice: bool,
// llvm codegen options
pub llvm_assertions: bool,
pub llvm_tests: bool,
pub llvm_enzyme: bool,
pub llvm_offload: bool,
pub llvm_plugins: bool,
pub llvm_optimize: bool,
pub llvm_thin_lto: bool,
pub llvm_release_debuginfo: bool,
pub llvm_static_stdcpp: bool,
pub llvm_libzstd: bool,
pub llvm_link_shared: Cell<Option<bool>>,
pub llvm_clang_cl: Option<String>,
pub llvm_targets: Option<String>,
pub llvm_experimental_targets: Option<String>,
pub llvm_link_jobs: Option<u32>,
pub llvm_version_suffix: Option<String>,
pub llvm_use_linker: Option<String>,
pub llvm_allow_old_toolchain: bool,
pub llvm_polly: bool,
pub llvm_clang: bool,
pub llvm_enable_warnings: bool,
pub llvm_from_ci: bool,
pub llvm_build_config: HashMap<String, String>,
pub lld_mode: LldMode,
pub lld_enabled: bool,
pub llvm_tools_enabled: bool,
pub llvm_bitcode_linker_enabled: bool,
pub llvm_cflags: Option<String>,
pub llvm_cxxflags: Option<String>,
pub llvm_ldflags: Option<String>,
pub llvm_use_libcxx: bool,
// gcc codegen options
pub gcc_ci_mode: GccCiMode,
// rust codegen options
pub rust_optimize: RustOptimize,
pub rust_codegen_units: Option<u32>,
pub rust_codegen_units_std: Option<u32>,
pub rustc_debug_assertions: bool,
pub std_debug_assertions: bool,
pub tools_debug_assertions: bool,
pub rust_overflow_checks: bool,
pub rust_overflow_checks_std: bool,
pub rust_debug_logging: bool,
pub rust_debuginfo_level_rustc: DebuginfoLevel,
pub rust_debuginfo_level_std: DebuginfoLevel,
pub rust_debuginfo_level_tools: DebuginfoLevel,
pub rust_debuginfo_level_tests: DebuginfoLevel,
pub rust_rpath: bool,
pub rust_strip: bool,
pub rust_frame_pointers: bool,
pub rust_stack_protector: Option<String>,
pub rustc_default_linker: Option<String>,
pub rust_optimize_tests: bool,
pub rust_dist_src: bool,
pub rust_codegen_backends: Vec<String>,
pub rust_verify_llvm_ir: bool,
pub rust_thin_lto_import_instr_limit: Option<u32>,
pub rust_randomize_layout: bool,
pub rust_remap_debuginfo: bool,
pub rust_new_symbol_mangling: Option<bool>,
pub rust_profile_use: Option<String>,
pub rust_profile_generate: Option<String>,
pub rust_lto: RustcLto,
pub rust_validate_mir_opts: Option<u32>,
pub rust_std_features: BTreeSet<String>,
pub llvm_profile_use: Option<String>,
pub llvm_profile_generate: bool,
pub llvm_libunwind_default: Option<LlvmLibunwind>,
pub enable_bolt_settings: bool,
pub reproducible_artifacts: Vec<String>,
pub host_target: TargetSelection,
pub hosts: Vec<TargetSelection>,
pub targets: Vec<TargetSelection>,
pub local_rebuild: bool,
pub jemalloc: bool,
pub control_flow_guard: bool,
pub ehcont_guard: bool,
// dist misc
pub dist_sign_folder: Option<PathBuf>,
pub dist_upload_addr: Option<String>,
pub dist_compression_formats: Option<Vec<String>>,
pub dist_compression_profile: String,
pub dist_include_mingw_linker: bool,
pub dist_vendor: bool,
// libstd features
pub backtrace: bool, // support for RUST_BACKTRACE
// misc
pub low_priority: bool,
pub channel: String,
pub description: Option<String>,
pub verbose_tests: bool,
pub save_toolstates: Option<PathBuf>,
pub print_step_timings: bool,
pub print_step_rusage: bool,
// Fallback musl-root for all targets
pub musl_root: Option<PathBuf>,
pub prefix: Option<PathBuf>,
pub sysconfdir: Option<PathBuf>,
pub datadir: Option<PathBuf>,
pub docdir: Option<PathBuf>,
pub bindir: PathBuf,
pub libdir: Option<PathBuf>,
pub mandir: Option<PathBuf>,
pub codegen_tests: bool,
pub nodejs: Option<PathBuf>,
pub npm: Option<PathBuf>,
pub gdb: Option<PathBuf>,
pub lldb: Option<PathBuf>,
pub python: Option<PathBuf>,
pub reuse: Option<PathBuf>,
pub cargo_native_static: bool,
pub configure_args: Vec<String>,
pub out: PathBuf,
pub rust_info: channel::GitInfo,
pub cargo_info: channel::GitInfo,
pub rust_analyzer_info: channel::GitInfo,
pub clippy_info: channel::GitInfo,
pub miri_info: channel::GitInfo,
pub rustfmt_info: channel::GitInfo,
pub enzyme_info: channel::GitInfo,
pub in_tree_llvm_info: channel::GitInfo,
pub in_tree_gcc_info: channel::GitInfo,
// These are either the stage0 downloaded binaries or the locally installed ones.
pub initial_cargo: PathBuf,
pub initial_rustc: PathBuf,
pub initial_cargo_clippy: Option<PathBuf>,
pub initial_sysroot: PathBuf,
pub initial_rustfmt: Option<PathBuf>,
/// The paths to work with. For example: with `./x check foo bar` we get
/// `paths=["foo", "bar"]`.
pub paths: Vec<PathBuf>,
/// Command for visual diff display, e.g. `diff-tool --color=always`.
pub compiletest_diff_tool: Option<String>,
/// Whether to use the precompiled stage0 libtest with compiletest.
pub compiletest_use_stage0_libtest: bool,
/// Default value for `--extra-checks`
pub tidy_extra_checks: String,
pub is_running_on_ci: bool,
/// Cache for determining path modifications
pub path_modification_cache: Arc<Mutex<HashMap<Vec<&'static str>, PathFreshness>>>,
/// Skip checking the standard library if `rust.download-rustc` isn't available.
/// This is mostly for RA as building the stage1 compiler to check the library tree
/// on each code change might be too much for some computers.
pub skip_std_check_if_no_download_rustc: bool,
pub exec_ctx: ExecutionContext,
}
impl Config {
#[cfg_attr(
feature = "tracing",
instrument(target = "CONFIG_HANDLING", level = "trace", name = "Config::default_opts")
)]
pub fn default_opts() -> Config {
#[cfg(feature = "tracing")]
span!(target: "CONFIG_HANDLING", tracing::Level::TRACE, "constructing default config");
Config {
bypass_bootstrap_lock: false,
llvm_optimize: true,
ninja_in_file: true,
llvm_static_stdcpp: false,
llvm_libzstd: false,
backtrace: true,
rust_optimize: RustOptimize::Bool(true),
rust_optimize_tests: true,
rust_randomize_layout: false,
submodules: None,
docs: true,
docs_minification: true,
rust_rpath: true,
rust_strip: false,
channel: "dev".to_string(),
codegen_tests: true,
rust_dist_src: true,
rust_codegen_backends: vec!["llvm".to_owned()],
deny_warnings: true,
bindir: "bin".into(),
dist_include_mingw_linker: true,
dist_compression_profile: "fast".into(),
stdout_is_tty: std::io::stdout().is_terminal(),
stderr_is_tty: std::io::stderr().is_terminal(),
// set by build.rs
host_target: get_host_target(),
src: {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
// Undo `src/bootstrap`
manifest_dir.parent().unwrap().parent().unwrap().to_owned()
},
out: PathBuf::from("build"),
// This is needed by codegen_ssa on macOS to ship `llvm-objcopy` aliased to
// `rust-objcopy` to workaround bad `strip`s on macOS.
llvm_tools_enabled: true,
..Default::default()
}
}
pub fn set_dry_run(&mut self, dry_run: DryRun) {
self.exec_ctx.set_dry_run(dry_run);
}
pub fn get_dry_run(&self) -> &DryRun {
self.exec_ctx.get_dry_run()
}
#[cfg_attr(
feature = "tracing",
instrument(target = "CONFIG_HANDLING", level = "trace", name = "Config::parse", skip_all)
)]
pub fn parse(flags: Flags) -> Config {
Self::parse_inner(flags, Self::get_toml)
}
#[cfg_attr(
feature = "tracing",
instrument(
target = "CONFIG_HANDLING",
level = "trace",
name = "Config::parse_inner",
skip_all
)
)]
pub(crate) fn parse_inner(
flags: Flags,
get_toml: impl Fn(&Path) -> Result<TomlConfig, toml::de::Error>,
) -> Config {
// Destructure flags to ensure that we use all its fields
// The field variables are prefixed with `flags_` to avoid clashes
// with values from TOML config files with same names.
let Flags {
cmd: flags_cmd,
verbose: flags_verbose,
incremental: flags_incremental,
config: flags_config,
build_dir: flags_build_dir,
build: flags_build,
host: flags_host,
target: flags_target,
exclude: flags_exclude,
skip: flags_skip,
include_default_paths: flags_include_default_paths,
rustc_error_format: flags_rustc_error_format,
on_fail: flags_on_fail,
dry_run: flags_dry_run,
dump_bootstrap_shims: flags_dump_bootstrap_shims,
stage: flags_stage,
keep_stage: flags_keep_stage,
keep_stage_std: flags_keep_stage_std,
src: flags_src,
jobs: flags_jobs,
warnings: flags_warnings,
json_output: flags_json_output,
compile_time_deps: flags_compile_time_deps,
color: flags_color,
bypass_bootstrap_lock: flags_bypass_bootstrap_lock,
rust_profile_generate: flags_rust_profile_generate,
rust_profile_use: flags_rust_profile_use,
llvm_profile_use: flags_llvm_profile_use,
llvm_profile_generate: flags_llvm_profile_generate,
enable_bolt_settings: flags_enable_bolt_settings,
skip_stage0_validation: flags_skip_stage0_validation,
reproducible_artifact: flags_reproducible_artifact,
paths: mut flags_paths,
set: flags_set,
free_args: mut flags_free_args,
ci: flags_ci,
skip_std_check_if_no_download_rustc: flags_skip_std_check_if_no_download_rustc,
} = flags;
let mut config = Config::default_opts();
let mut exec_ctx = ExecutionContext::new();
exec_ctx.set_verbose(flags_verbose);
exec_ctx.set_fail_fast(flags_cmd.fail_fast());
config.exec_ctx = exec_ctx;
// Set flags.
config.paths = std::mem::take(&mut flags_paths);
#[cfg(feature = "tracing")]
span!(
target: "CONFIG_HANDLING",
tracing::Level::TRACE,
"collecting paths and path exclusions",
"flags.paths" = ?flags_paths,
"flags.skip" = ?flags_skip,
"flags.exclude" = ?flags_exclude
);
#[cfg(feature = "tracing")]
span!(
target: "CONFIG_HANDLING",
tracing::Level::TRACE,
"normalizing and combining `flag.skip`/`flag.exclude` paths",
"config.skip" = ?config.skip,
);
config.include_default_paths = flags_include_default_paths;
config.rustc_error_format = flags_rustc_error_format;
config.json_output = flags_json_output;
config.compile_time_deps = flags_compile_time_deps;
config.on_fail = flags_on_fail;
config.cmd = flags_cmd;
config.incremental = flags_incremental;
config.set_dry_run(if flags_dry_run { DryRun::UserSelected } else { DryRun::Disabled });
config.dump_bootstrap_shims = flags_dump_bootstrap_shims;
config.keep_stage = flags_keep_stage;
config.keep_stage_std = flags_keep_stage_std;
config.color = flags_color;
config.free_args = std::mem::take(&mut flags_free_args);
config.llvm_profile_use = flags_llvm_profile_use;
config.llvm_profile_generate = flags_llvm_profile_generate;
config.enable_bolt_settings = flags_enable_bolt_settings;
config.bypass_bootstrap_lock = flags_bypass_bootstrap_lock;
config.is_running_on_ci = flags_ci.unwrap_or(CiEnv::is_ci());
config.skip_std_check_if_no_download_rustc = flags_skip_std_check_if_no_download_rustc;
// Infer the rest of the configuration.
if let Some(src) = flags_src {
config.src = src
} else {
// Infer the source directory. This is non-trivial because we want to support a downloaded bootstrap binary,
// running on a completely different machine from where it was compiled.
let mut cmd = helpers::git(None);
// NOTE: we cannot support running from outside the repository because the only other path we have available
// is set at compile time, which can be wrong if bootstrap was downloaded rather than compiled locally.
// We still support running outside the repository if we find we aren't in a git directory.
// NOTE: We get a relative path from git to work around an issue on MSYS/mingw. If we used an absolute path,
// and end up using MSYS's git rather than git-for-windows, we would get a unix-y MSYS path. But as bootstrap
// has already been (kinda-cross-)compiled to Windows land, we require a normal Windows path.
cmd.arg("rev-parse").arg("--show-cdup");
// Discard stderr because we expect this to fail when building from a tarball.
let output = cmd.allow_failure().run_capture_stdout(&config);
if output.is_success() {
let git_root_relative = output.stdout();
// We need to canonicalize this path to make sure it uses backslashes instead of forward slashes,
// and to resolve any relative components.
let git_root = env::current_dir()
.unwrap()
.join(PathBuf::from(git_root_relative.trim()))
.canonicalize()
.unwrap();
let s = git_root.to_str().unwrap();
// Bootstrap is quite bad at handling /? in front of paths
let git_root = match s.strip_prefix("\\\\?\\") {
Some(p) => PathBuf::from(p),
None => git_root,
};
// If this doesn't have at least `stage0`, we guessed wrong. This can happen when,
// for example, the build directory is inside of another unrelated git directory.
// In that case keep the original `CARGO_MANIFEST_DIR` handling.
//
// NOTE: this implies that downloadable bootstrap isn't supported when the build directory is outside
// the source directory. We could fix that by setting a variable from all three of python, ./x, and x.ps1.
if git_root.join("src").join("stage0").exists() {
config.src = git_root;
}
} else {
// We're building from a tarball, not git sources.
// We don't support pre-downloaded bootstrap in this case.
}
}
if cfg!(test) {
// Use the build directory of the original x.py invocation, so that we can set `initial_rustc` properly.
config.out = Path::new(
&env::var_os("CARGO_TARGET_DIR").expect("cargo test directly is not supported"),
)
.parent()
.unwrap()
.to_path_buf();
}
config.stage0_metadata = build_helper::stage0_parser::parse_stage0_file();
// Locate the configuration file using the following priority (first match wins):
// 1. `--config <path>` (explicit flag)
// 2. `RUST_BOOTSTRAP_CONFIG` environment variable
// 3. `./bootstrap.toml` (local file)
// 4. `<root>/bootstrap.toml`
// 5. `./config.toml` (fallback for backward compatibility)
// 6. `<root>/config.toml`
let toml_path = flags_config
.clone()
.or_else(|| env::var_os("RUST_BOOTSTRAP_CONFIG").map(PathBuf::from));
let using_default_path = toml_path.is_none();
let mut toml_path = toml_path.unwrap_or_else(|| PathBuf::from("bootstrap.toml"));
if using_default_path && !toml_path.exists() {
toml_path = config.src.join(PathBuf::from("bootstrap.toml"));
if !toml_path.exists() {
toml_path = PathBuf::from("config.toml");
if !toml_path.exists() {
toml_path = config.src.join(PathBuf::from("config.toml"));
}
}
}
// Give a hard error if `--config` or `RUST_BOOTSTRAP_CONFIG` are set to a missing path,
// but not if `bootstrap.toml` hasn't been created.
let mut toml = if !using_default_path || toml_path.exists() {
config.config = Some(if cfg!(not(test)) {
toml_path = toml_path.canonicalize().unwrap();
toml_path.clone()
} else {
toml_path.clone()
});
get_toml(&toml_path).unwrap_or_else(|e| {
eprintln!("ERROR: Failed to parse '{}': {e}", toml_path.display());
exit!(2);
})
} else {
config.config = None;
TomlConfig::default()
};
if cfg!(test) {
// When configuring bootstrap for tests, make sure to set the rustc and Cargo to the
// same ones used to call the tests (if custom ones are not defined in the toml). If we
// don't do that, bootstrap will use its own detection logic to find a suitable rustc
// and Cargo, which doesn't work when the caller is specìfying a custom local rustc or
// Cargo in their bootstrap.toml.
let build = toml.build.get_or_insert_with(Default::default);
build.rustc = build.rustc.take().or(std::env::var_os("RUSTC").map(|p| p.into()));
build.cargo = build.cargo.take().or(std::env::var_os("CARGO").map(|p| p.into()));
}
if config.git_info(false, &config.src).is_from_tarball() && toml.profile.is_none() {
toml.profile = Some("dist".into());
}
// Reverse the list to ensure the last added config extension remains the most dominant.
// For example, given ["a.toml", "b.toml"], "b.toml" should take precedence over "a.toml".
//
// This must be handled before applying the `profile` since `include`s should always take
// precedence over `profile`s.
for include_path in toml.include.clone().unwrap_or_default().iter().rev() {
let include_path = toml_path.parent().unwrap().join(include_path);
let included_toml = get_toml(&include_path).unwrap_or_else(|e| {
eprintln!("ERROR: Failed to parse '{}': {e}", include_path.display());
exit!(2);
});
toml.merge(
Some(include_path),
&mut Default::default(),
included_toml,
ReplaceOpt::IgnoreDuplicate,
);
}
if let Some(include) = &toml.profile {
// Allows creating alias for profile names, allowing
// profiles to be renamed while maintaining back compatibility
// Keep in sync with `profile_aliases` in bootstrap.py
let profile_aliases = HashMap::from([("user", "dist")]);
let include = match profile_aliases.get(include.as_str()) {
Some(alias) => alias,
None => include.as_str(),
};
let mut include_path = config.src.clone();
include_path.push("src");
include_path.push("bootstrap");
include_path.push("defaults");
include_path.push(format!("bootstrap.{include}.toml"));
let included_toml = get_toml(&include_path).unwrap_or_else(|e| {
eprintln!(
"ERROR: Failed to parse default config profile at '{}': {e}",
include_path.display()
);
exit!(2);
});
toml.merge(
Some(include_path),
&mut Default::default(),
included_toml,
ReplaceOpt::IgnoreDuplicate,
);
}
let mut override_toml = TomlConfig::default();
for option in flags_set.iter() {
fn get_table(option: &str) -> Result<TomlConfig, toml::de::Error> {
toml::from_str(option).and_then(|table: toml::Value| TomlConfig::deserialize(table))
}
let mut err = match get_table(option) {
Ok(v) => {
override_toml.merge(
None,
&mut Default::default(),
v,
ReplaceOpt::ErrorOnDuplicate,
);
continue;
}
Err(e) => e,
};
// We want to be able to set string values without quotes,
// like in `configure.py`. Try adding quotes around the right hand side
if let Some((key, value)) = option.split_once('=')
&& !value.contains('"')
{
match get_table(&format!(r#"{key}="{value}""#)) {
Ok(v) => {
override_toml.merge(
None,
&mut Default::default(),
v,
ReplaceOpt::ErrorOnDuplicate,
);
continue;
}
Err(e) => err = e,
}
}
eprintln!("failed to parse override `{option}`: `{err}");
exit!(2)
}
toml.merge(None, &mut Default::default(), override_toml, ReplaceOpt::Override);
config.change_id = toml.change_id.inner;
let Build {
description,
build,
host,
target,
build_dir,
cargo,
rustc,
rustfmt,
cargo_clippy,
docs,
compiler_docs,
library_docs_private_items,
docs_minification,
submodules,
gdb,
lldb,
nodejs,
npm,
python,
reuse,
locked_deps,
vendor,
full_bootstrap,
bootstrap_cache_path,
extended,
tools,
tool,
verbose,
sanitizers,
profiler,
cargo_native_static,
low_priority,
configure_args,
local_rebuild,
print_step_timings,
print_step_rusage,
check_stage,
doc_stage,
build_stage,
test_stage,
install_stage,
dist_stage,
bench_stage,
patch_binaries_for_nix,
// This field is only used by bootstrap.py
metrics: _,
android_ndk,
optimized_compiler_builtins,
jobs,
compiletest_diff_tool,
compiletest_use_stage0_libtest,
tidy_extra_checks,
ccache,
exclude,
} = toml.build.unwrap_or_default();
let mut paths: Vec<PathBuf> = flags_skip.into_iter().chain(flags_exclude).collect();
if let Some(exclude) = exclude {
paths.extend(exclude);
}
config.skip = paths
.into_iter()
.map(|p| {
// Never return top-level path here as it would break `--skip`
// logic on rustc's internal test framework which is utilized
// by compiletest.
if cfg!(windows) {
PathBuf::from(p.to_str().unwrap().replace('/', "\\"))
} else {
p
}
})
.collect();
config.jobs = Some(threads_from_config(flags_jobs.unwrap_or(jobs.unwrap_or(0))));
if let Some(flags_build) = flags_build {
config.host_target = TargetSelection::from_user(&flags_build);
} else if let Some(file_build) = build {
config.host_target = TargetSelection::from_user(&file_build);
};
set(&mut config.out, flags_build_dir.or_else(|| build_dir.map(PathBuf::from)));
// NOTE: Bootstrap spawns various commands with different working directories.
// To avoid writing to random places on the file system, `config.out` needs to be an absolute path.
if !config.out.is_absolute() {
// `canonicalize` requires the path to already exist. Use our vendored copy of `absolute` instead.
config.out = absolute(&config.out).expect("can't make empty path absolute");
}
if cargo_clippy.is_some() && rustc.is_none() {
println!(
"WARNING: Using `build.cargo-clippy` without `build.rustc` usually fails due to toolchain conflict."
);
}
config.initial_rustc = if let Some(rustc) = rustc {
if !flags_skip_stage0_validation {
config.check_stage0_version(&rustc, "rustc");
}
rustc
} else {
config.download_beta_toolchain();
config
.out
.join(config.host_target)
.join("stage0")
.join("bin")
.join(exe("rustc", config.host_target))
};
config.initial_sysroot = t!(PathBuf::from_str(
command(&config.initial_rustc)
.args(["--print", "sysroot"])
.run_in_dry_run()
.run_capture_stdout(&config)
.stdout()
.trim()
));
config.initial_cargo_clippy = cargo_clippy;
config.initial_cargo = if let Some(cargo) = cargo {
if !flags_skip_stage0_validation {
config.check_stage0_version(&cargo, "cargo");
}
cargo
} else {
config.download_beta_toolchain();
config.initial_sysroot.join("bin").join(exe("cargo", config.host_target))
};
// NOTE: it's important this comes *after* we set `initial_rustc` just above.
if config.dry_run() {
let dir = config.out.join("tmp-dry-run");
t!(fs::create_dir_all(&dir));
config.out = dir;
}
config.hosts = if let Some(TargetSelectionList(arg_host)) = flags_host {
arg_host
} else if let Some(file_host) = host {
file_host.iter().map(|h| TargetSelection::from_user(h)).collect()
} else {
vec![config.host_target]
};
config.targets = if let Some(TargetSelectionList(arg_target)) = flags_target {
arg_target
} else if let Some(file_target) = target {
file_target.iter().map(|h| TargetSelection::from_user(h)).collect()
} else {
// If target is *not* configured, then default to the host
// toolchains.
config.hosts.clone()
};
config.nodejs = nodejs.map(PathBuf::from);
config.npm = npm.map(PathBuf::from);
config.gdb = gdb.map(PathBuf::from);
config.lldb = lldb.map(PathBuf::from);
config.python = python.map(PathBuf::from);
config.reuse = reuse.map(PathBuf::from);
config.submodules = submodules;
config.android_ndk = android_ndk;
config.bootstrap_cache_path = bootstrap_cache_path;
set(&mut config.low_priority, low_priority);
set(&mut config.compiler_docs, compiler_docs);
set(&mut config.library_docs_private_items, library_docs_private_items);
set(&mut config.docs_minification, docs_minification);
set(&mut config.docs, docs);
set(&mut config.locked_deps, locked_deps);
set(&mut config.full_bootstrap, full_bootstrap);
set(&mut config.extended, extended);
config.tools = tools;
set(&mut config.tool, tool);
set(&mut config.verbose, verbose);
set(&mut config.sanitizers, sanitizers);
set(&mut config.profiler, profiler);
set(&mut config.cargo_native_static, cargo_native_static);
set(&mut config.configure_args, configure_args);
set(&mut config.local_rebuild, local_rebuild);
set(&mut config.print_step_timings, print_step_timings);
set(&mut config.print_step_rusage, print_step_rusage);
config.patch_binaries_for_nix = patch_binaries_for_nix;
config.verbose = cmp::max(config.verbose, flags_verbose as usize);
// Verbose flag is a good default for `rust.verbose-tests`.
config.verbose_tests = config.is_verbose();
config.apply_install_config(toml.install);
config.llvm_assertions =
toml.llvm.as_ref().is_some_and(|llvm| llvm.assertions.unwrap_or(false));
let file_content = t!(fs::read_to_string(config.src.join("src/ci/channel")));
let ci_channel = file_content.trim_end();
let toml_channel = toml.rust.as_ref().and_then(|r| r.channel.clone());
let is_user_configured_rust_channel = match toml_channel {
Some(channel) if channel == "auto-detect" => {
config.channel = ci_channel.into();
true
}
Some(channel) => {
config.channel = channel;
true
}
None => false,
};
let default = config.channel == "dev";
config.omit_git_hash = toml.rust.as_ref().and_then(|r| r.omit_git_hash).unwrap_or(default);
config.rust_info = config.git_info(config.omit_git_hash, &config.src);
config.cargo_info =
config.git_info(config.omit_git_hash, &config.src.join("src/tools/cargo"));
config.rust_analyzer_info =
config.git_info(config.omit_git_hash, &config.src.join("src/tools/rust-analyzer"));
config.clippy_info =
config.git_info(config.omit_git_hash, &config.src.join("src/tools/clippy"));
config.miri_info =
config.git_info(config.omit_git_hash, &config.src.join("src/tools/miri"));
config.rustfmt_info =
config.git_info(config.omit_git_hash, &config.src.join("src/tools/rustfmt"));
config.enzyme_info =
config.git_info(config.omit_git_hash, &config.src.join("src/tools/enzyme"));
config.in_tree_llvm_info = config.git_info(false, &config.src.join("src/llvm-project"));
config.in_tree_gcc_info = config.git_info(false, &config.src.join("src/gcc"));
config.vendor = vendor.unwrap_or(
config.rust_info.is_from_tarball()
&& config.src.join("vendor").exists()
&& config.src.join(".cargo/config.toml").exists(),
);
if !is_user_configured_rust_channel && config.rust_info.is_from_tarball() {
config.channel = ci_channel.into();
}
config.rust_profile_use = flags_rust_profile_use;
config.rust_profile_generate = flags_rust_profile_generate;
config.apply_target_config(toml.target);
config.apply_rust_config(toml.rust, flags_warnings);
config.reproducible_artifacts = flags_reproducible_artifact;
config.description = description;
// We need to override `rust.channel` if it's manually specified when using the CI rustc.
// This is because if the compiler uses a different channel than the one specified in bootstrap.toml,
// tests may fail due to using a different channel than the one used by the compiler during tests.
if let Some(commit) = &config.download_rustc_commit
&& is_user_configured_rust_channel
{
println!(
"WARNING: `rust.download-rustc` is enabled. The `rust.channel` option will be overridden by the CI rustc's channel."
);
let channel =
config.read_file_by_commit(Path::new("src/ci/channel"), commit).trim().to_owned();
config.channel = channel;
}
config.apply_llvm_config(toml.llvm);
config.apply_gcc_config(toml.gcc);
match ccache {
Some(StringOrBool::String(ref s)) => config.ccache = Some(s.to_string()),
Some(StringOrBool::Bool(true)) => {
config.ccache = Some("ccache".to_string());
}
Some(StringOrBool::Bool(false)) | None => {}
}
if config.llvm_from_ci {
let triple = &config.host_target.triple;
let ci_llvm_bin = config.ci_llvm_root().join("bin");
let build_target = config
.target_config
.entry(config.host_target)
.or_insert_with(|| Target::from_triple(triple));
check_ci_llvm!(build_target.llvm_config);
check_ci_llvm!(build_target.llvm_filecheck);
build_target.llvm_config =
Some(ci_llvm_bin.join(exe("llvm-config", config.host_target)));
build_target.llvm_filecheck =
Some(ci_llvm_bin.join(exe("FileCheck", config.host_target)));
}
config.apply_dist_config(toml.dist);
config.initial_rustfmt =
if let Some(r) = rustfmt { Some(r) } else { config.maybe_download_rustfmt() };
if matches!(config.lld_mode, LldMode::SelfContained)