-
-
Notifications
You must be signed in to change notification settings - Fork 14.8k
Expand file tree
/
Copy pathcargo.rs
More file actions
1380 lines (1225 loc) · 58.3 KB
/
cargo.rs
File metadata and controls
1380 lines (1225 loc) · 58.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
use std::env;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use super::{Builder, Kind};
use crate::core::build_steps::test;
use crate::core::build_steps::tool::SourceType;
use crate::core::config::SplitDebuginfo;
use crate::core::config::flags::Color;
use crate::utils::build_stamp;
use crate::utils::helpers::{self, LldThreads, check_cfg_arg, linker_args, linker_flags};
use crate::{
BootstrapCommand, CLang, Compiler, Config, DocTests, DryRun, EXTRA_CHECK_CFGS, GitRepo, Mode,
RemapScheme, TargetSelection, command, prepare_behaviour_dump_dir, t,
};
/// Represents flag values in `String` form with whitespace delimiter to pass it to the compiler
/// later.
///
/// `-Z crate-attr` flags will be applied recursively on the target code using the
/// `rustc_parse::parser::Parser`. See `rustc_builtin_macros::cmdline_attrs::inject` for more
/// information.
#[derive(Debug, Clone)]
struct Rustflags(String, TargetSelection);
impl Rustflags {
fn new(target: TargetSelection) -> Rustflags {
let mut ret = Rustflags(String::new(), target);
ret.propagate_cargo_env("RUSTFLAGS");
ret
}
/// By default, cargo will pick up on various variables in the environment. However, bootstrap
/// reuses those variables to pass additional flags to rustdoc, so by default they get
/// overridden. Explicitly add back any previous value in the environment.
///
/// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
fn propagate_cargo_env(&mut self, prefix: &str) {
// Inherit `RUSTFLAGS` by default ...
self.env(prefix);
// ... and also handle target-specific env RUSTFLAGS if they're configured.
let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
self.env(&target_specific);
}
fn env(&mut self, env: &str) {
if let Ok(s) = env::var(env) {
for part in s.split(' ') {
self.arg(part);
}
}
}
fn arg(&mut self, arg: &str) -> &mut Self {
assert_eq!(arg.split(' ').count(), 1);
if !self.0.is_empty() {
self.0.push(' ');
}
self.0.push_str(arg);
self
}
}
/// Flags that are passed to the `rustc` shim binary. These flags will only be applied when
/// compiling host code, i.e. when `--target` is unset.
#[derive(Debug, Default)]
struct HostFlags {
rustc: Vec<String>,
}
impl HostFlags {
const SEPARATOR: &'static str = " ";
/// Adds a host rustc flag.
fn arg<S: Into<String>>(&mut self, flag: S) {
let value = flag.into().trim().to_string();
assert!(!value.contains(Self::SEPARATOR));
self.rustc.push(value);
}
/// Encodes all the flags into a single string.
fn encode(self) -> String {
self.rustc.join(Self::SEPARATOR)
}
}
#[derive(Debug)]
pub struct Cargo {
command: BootstrapCommand,
args: Vec<OsString>,
compiler: Compiler,
target: TargetSelection,
rustflags: Rustflags,
rustdocflags: Rustflags,
hostflags: HostFlags,
allow_features: String,
release_build: bool,
}
impl Cargo {
/// Calls [`Builder::cargo`] and [`Cargo::configure_linker`] to prepare an invocation of `cargo`
/// to be run.
#[track_caller]
pub fn new(
builder: &Builder<'_>,
compiler: Compiler,
mode: Mode,
source_type: SourceType,
target: TargetSelection,
cmd_kind: Kind,
) -> Cargo {
let mut cargo = builder.cargo(compiler, mode, source_type, target, cmd_kind);
match cmd_kind {
// No need to configure the target linker for these command types.
Kind::Clean | Kind::Check | Kind::Format | Kind::Setup => {}
_ => {
cargo.configure_linker(builder);
}
}
cargo
}
pub fn release_build(&mut self, release_build: bool) {
self.release_build = release_build;
}
pub fn compiler(&self) -> Compiler {
self.compiler
}
pub fn into_cmd(self) -> BootstrapCommand {
self.into()
}
/// Same as [`Cargo::new`] except this one doesn't configure the linker with
/// [`Cargo::configure_linker`].
#[track_caller]
pub fn new_for_mir_opt_tests(
builder: &Builder<'_>,
compiler: Compiler,
mode: Mode,
source_type: SourceType,
target: TargetSelection,
cmd_kind: Kind,
) -> Cargo {
builder.cargo(compiler, mode, source_type, target, cmd_kind)
}
pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
self.rustdocflags.arg(arg);
self
}
pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
self.rustflags.arg(arg);
self
}
pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
self.args.push(arg.as_ref().into());
self
}
pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
for arg in args {
self.arg(arg.as_ref());
}
self
}
/// Add an env var to the cargo command instance. Note that `RUSTFLAGS`/`RUSTDOCFLAGS` must go
/// through [`Cargo::rustdocflags`] and [`Cargo::rustflags`] because inconsistent `RUSTFLAGS`
/// and `RUSTDOCFLAGS` usages will trigger spurious rebuilds.
pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
assert_ne!(key.as_ref(), "RUSTFLAGS");
assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
self.command.env(key.as_ref(), value.as_ref());
self
}
/// Append a value to an env var of the cargo command instance.
/// If the variable was unset previously, this is equivalent to [`Cargo::env`].
/// If the variable was already set, this will append `delimiter` and then `value` to it.
///
/// Note that this only considers the existence of the env. var. configured on this `Cargo`
/// instance. It does not look at the environment of this process.
pub fn append_to_env(
&mut self,
key: impl AsRef<OsStr>,
value: impl AsRef<OsStr>,
delimiter: impl AsRef<OsStr>,
) -> &mut Cargo {
assert_ne!(key.as_ref(), "RUSTFLAGS");
assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
let key = key.as_ref();
if let Some((_, Some(previous_value))) = self.command.get_envs().find(|(k, _)| *k == key) {
let mut combined: OsString = previous_value.to_os_string();
combined.push(delimiter.as_ref());
combined.push(value.as_ref());
self.env(key, combined)
} else {
self.env(key, value)
}
}
pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>) {
builder.add_rustc_lib_path(self.compiler, &mut self.command);
}
pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
self.command.current_dir(dir);
self
}
/// Adds nightly-only features that this invocation is allowed to use.
///
/// By default, all nightly features are allowed. Once this is called, it will be restricted to
/// the given set.
pub fn allow_features(&mut self, features: &str) -> &mut Cargo {
if !self.allow_features.is_empty() {
self.allow_features.push(',');
}
self.allow_features.push_str(features);
self
}
// FIXME(onur-ozkan): Add coverage to make sure modifications to this function
// doesn't cause cache invalidations (e.g., #130108).
fn configure_linker(&mut self, builder: &Builder<'_>) -> &mut Cargo {
let target = self.target;
let compiler = self.compiler;
// Dealing with rpath here is a little special, so let's go into some
// detail. First off, `-rpath` is a linker option on Unix platforms
// which adds to the runtime dynamic loader path when looking for
// dynamic libraries. We use this by default on Unix platforms to ensure
// that our nightlies behave the same on Windows, that is they work out
// of the box. This can be disabled by setting `rpath = false` in `[rust]`
// table of `bootstrap.toml`
//
// Ok, so the astute might be wondering "why isn't `-C rpath` used
// here?" and that is indeed a good question to ask. This codegen
// option is the compiler's current interface to generating an rpath.
// Unfortunately it doesn't quite suffice for us. The flag currently
// takes no value as an argument, so the compiler calculates what it
// should pass to the linker as `-rpath`. This unfortunately is based on
// the **compile time** directory structure which when building with
// Cargo will be very different than the runtime directory structure.
//
// All that's a really long winded way of saying that if we use
// `-Crpath` then the executables generated have the wrong rpath of
// something like `$ORIGIN/deps` when in fact the way we distribute
// rustc requires the rpath to be `$ORIGIN/../lib`.
//
// So, all in all, to set up the correct rpath we pass the linker
// argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
// fun to pass a flag to a tool to pass a flag to pass a flag to a tool
// to change a flag in a binary?
if builder.config.rpath_enabled(target) && helpers::use_host_linker(target) {
let libdir = builder.sysroot_libdir_relative(compiler).to_str().unwrap();
let rpath = if target.contains("apple") {
// Note that we need to take one extra step on macOS to also pass
// `-Wl,-instal_name,@rpath/...` to get things to work right. To
// do that we pass a weird flag to the compiler to get it to do
// so. Note that this is definitely a hack, and we should likely
// flesh out rpath support more fully in the future.
self.rustflags.arg("-Zosx-rpath-install-name");
Some(format!("-Wl,-rpath,@loader_path/../{libdir}"))
} else if !target.is_windows()
&& !target.contains("cygwin")
&& !target.contains("aix")
&& !target.contains("xous")
{
self.rustflags.arg("-Clink-args=-Wl,-z,origin");
Some(format!("-Wl,-rpath,$ORIGIN/../{libdir}"))
} else {
None
};
if let Some(rpath) = rpath {
self.rustflags.arg(&format!("-Clink-args={rpath}"));
}
}
for arg in linker_args(builder, compiler.host, LldThreads::Yes) {
self.hostflags.arg(&arg);
}
if let Some(target_linker) = builder.linker(target) {
let target = crate::envify(&target.triple);
self.command.env(format!("CARGO_TARGET_{target}_LINKER"), target_linker);
}
// We want to set -Clinker using Cargo, therefore we only call `linker_flags` and not
// `linker_args` here.
for flag in linker_flags(builder, target, LldThreads::Yes) {
self.rustflags.arg(&flag);
}
for arg in linker_args(builder, target, LldThreads::Yes) {
self.rustdocflags.arg(&arg);
}
if !builder.config.dry_run() && builder.cc[&target].args().iter().any(|arg| arg == "-gz") {
self.rustflags.arg("-Clink-arg=-gz");
}
// Ignore linker warnings for now. These are complicated to fix and don't affect the build.
// FIXME: we should really investigate these...
self.rustflags.arg("-Alinker-messages");
// Throughout the build Cargo can execute a number of build scripts
// compiling C/C++ code and we need to pass compilers, archivers, flags, etc
// obtained previously to those build scripts.
// Build scripts use either the `cc` crate or `configure/make` so we pass
// the options through environment variables that are fetched and understood by both.
//
// FIXME: the guard against msvc shouldn't need to be here
if target.is_msvc() {
if let Some(ref cl) = builder.config.llvm_clang_cl {
// FIXME: There is a bug in Clang 18 when building for ARM64:
// https://github.com/llvm/llvm-project/pull/81849. This is
// fixed in LLVM 19, but can't be backported.
if !target.starts_with("aarch64") && !target.starts_with("arm64ec") {
self.command.env("CC", cl).env("CXX", cl);
}
}
} else {
let ccache = builder.config.ccache.as_ref();
let ccacheify = |s: &Path| {
let ccache = match ccache {
Some(ref s) => s,
None => return s.display().to_string(),
};
// FIXME: the cc-rs crate only recognizes the literal strings
// `ccache` and `sccache` when doing caching compilations, so we
// mirror that here. It should probably be fixed upstream to
// accept a new env var or otherwise work with custom ccache
// vars.
match &ccache[..] {
"ccache" | "sccache" => format!("{} {}", ccache, s.display()),
_ => s.display().to_string(),
}
};
let triple_underscored = target.triple.replace('-', "_");
let cc = ccacheify(&builder.cc(target));
self.command.env(format!("CC_{triple_underscored}"), &cc);
// Extend `CXXFLAGS_$TARGET` with our extra flags.
let env = format!("CFLAGS_{triple_underscored}");
let mut cflags =
builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::C).join(" ");
if let Ok(var) = std::env::var(&env) {
cflags.push(' ');
cflags.push_str(&var);
}
self.command.env(env, &cflags);
if let Some(ar) = builder.ar(target) {
let ranlib = format!("{} s", ar.display());
self.command
.env(format!("AR_{triple_underscored}"), ar)
.env(format!("RANLIB_{triple_underscored}"), ranlib);
}
if let Ok(cxx) = builder.cxx(target) {
let cxx = ccacheify(&cxx);
self.command.env(format!("CXX_{triple_underscored}"), &cxx);
// Extend `CXXFLAGS_$TARGET` with our extra flags.
let env = format!("CXXFLAGS_{triple_underscored}");
let mut cxxflags =
builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");
if let Ok(var) = std::env::var(&env) {
cxxflags.push(' ');
cxxflags.push_str(&var);
}
self.command.env(&env, cxxflags);
}
}
self
}
}
impl From<Cargo> for BootstrapCommand {
fn from(mut cargo: Cargo) -> BootstrapCommand {
if cargo.release_build {
cargo.args.insert(0, "--release".into());
}
cargo.command.args(cargo.args);
let rustflags = &cargo.rustflags.0;
if !rustflags.is_empty() {
cargo.command.env("RUSTFLAGS", rustflags);
}
let rustdocflags = &cargo.rustdocflags.0;
if !rustdocflags.is_empty() {
cargo.command.env("RUSTDOCFLAGS", rustdocflags);
}
let encoded_hostflags = cargo.hostflags.encode();
if !encoded_hostflags.is_empty() {
cargo.command.env("RUSTC_HOST_FLAGS", encoded_hostflags);
}
if !cargo.allow_features.is_empty() {
cargo.command.env("RUSTC_ALLOW_FEATURES", cargo.allow_features);
}
cargo.command
}
}
impl Builder<'_> {
/// Like [`Builder::cargo`], but only passes flags that are valid for all commands.
#[track_caller]
pub fn bare_cargo(
&self,
compiler: Compiler,
mode: Mode,
target: TargetSelection,
cmd_kind: Kind,
) -> BootstrapCommand {
let mut cargo = match cmd_kind {
Kind::Clippy => {
let mut cargo = self.cargo_clippy_cmd(compiler);
cargo.arg(cmd_kind.as_str());
cargo
}
Kind::MiriSetup => {
let mut cargo = self.cargo_miri_cmd(compiler);
cargo.arg("miri").arg("setup");
cargo
}
Kind::MiriTest => {
let mut cargo = self.cargo_miri_cmd(compiler);
cargo.arg("miri").arg("test");
cargo
}
_ => {
let mut cargo = command(&self.initial_cargo);
cargo.arg(cmd_kind.as_str());
cargo
}
};
// Run cargo from the source root so it can find .cargo/config.
// This matters when using vendoring and the working directory is outside the repository.
cargo.current_dir(&self.src);
let out_dir = self.stage_out(compiler, mode);
cargo.env("CARGO_TARGET_DIR", &out_dir);
// Bootstrap makes a lot of assumptions about the artifacts produced in the target
// directory. If users override the "build directory" using `build-dir`
// (https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-dir), then
// bootstrap couldn't find these artifacts. So we forcefully override that option to our
// target directory here.
// In the future, we could attempt to read the build-dir location from Cargo and actually
// respect it.
cargo.env("CARGO_BUILD_BUILD_DIR", &out_dir);
// Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
// from out of tree it shouldn't matter, since x.py is only used for
// building in-tree.
let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
match self.build.config.color {
Color::Always => {
cargo.arg("--color=always");
for log in &color_logs {
cargo.env(log, "always");
}
}
Color::Never => {
cargo.arg("--color=never");
for log in &color_logs {
cargo.env(log, "never");
}
}
Color::Auto => {} // nothing to do
}
if cmd_kind != Kind::Install {
cargo.arg("--target").arg(target.rustc_target_arg());
} else {
assert_eq!(target, compiler.host);
}
// Remove make-related flags to ensure Cargo can correctly set things up
cargo.env_remove("MAKEFLAGS");
cargo.env_remove("MFLAGS");
cargo
}
/// This will create a [`BootstrapCommand`] that represents a pending execution of cargo. This
/// cargo will be configured to use `compiler` as the actual rustc compiler, its output will be
/// scoped by `mode`'s output directory, it will pass the `--target` flag for the specified
/// `target`, and will be executing the Cargo command `cmd`. `cmd` can be `miri-cmd` for
/// commands to be run with Miri.
#[track_caller]
fn cargo(
&self,
compiler: Compiler,
mode: Mode,
source_type: SourceType,
target: TargetSelection,
cmd_kind: Kind,
) -> Cargo {
let mut cargo = self.bare_cargo(compiler, mode, target, cmd_kind);
let out_dir = self.stage_out(compiler, mode);
let mut hostflags = HostFlags::default();
// Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
// so we need to explicitly clear out if they've been updated.
for backend in self.codegen_backends(compiler) {
build_stamp::clear_if_dirty(self, &out_dir, &backend);
}
if self.config.cmd.timings() {
cargo.arg("--timings");
}
if cmd_kind == Kind::Doc {
let my_out = match mode {
// This is the intended out directory for compiler documentation.
Mode::Rustc | Mode::ToolRustcPrivate | Mode::ToolBootstrap | Mode::ToolTarget => {
self.compiler_doc_out(target)
}
Mode::Std => {
if self.config.cmd.json() {
out_dir.join(target).join("json-doc")
} else {
out_dir.join(target).join("doc")
}
}
_ => panic!("doc mode {mode:?} not expected"),
};
let rustdoc = self.rustdoc_for_compiler(compiler);
build_stamp::clear_if_dirty(self, &my_out, &rustdoc);
}
let profile_var = |name: &str| cargo_profile_var(name, &self.config);
// See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
// needs to not accidentally link to libLLVM in stage0/lib.
cargo.env("REAL_LIBRARY_PATH_VAR", helpers::dylib_path_var());
if let Some(e) = env::var_os(helpers::dylib_path_var()) {
cargo.env("REAL_LIBRARY_PATH", e);
}
// Set a flag for `check`/`clippy`/`fix`, so that certain build
// scripts can do less work (i.e. not building/requiring LLVM).
if matches!(cmd_kind, Kind::Check | Kind::Clippy | Kind::Fix) {
// If we've not yet built LLVM, or it's stale, then bust
// the rustc_llvm cache. That will always work, even though it
// may mean that on the next non-check build we'll need to rebuild
// rustc_llvm. But if LLVM is stale, that'll be a tiny amount
// of work comparatively, and we'd likely need to rebuild it anyway,
// so that's okay.
if crate::core::build_steps::llvm::prebuilt_llvm_config(self, target, false)
.should_build()
{
cargo.env("RUST_CHECK", "1");
}
}
let build_compiler_stage = if compiler.stage == 0 && self.local_rebuild {
// Assume the local-rebuild rustc already has stage1 features.
1
} else {
compiler.stage
};
// We synthetically interpret a stage0 compiler used to build tools as a
// "raw" compiler in that it's the exact snapshot we download. For things like
// ToolRustcPrivate, we would have to use the artificial stage0-sysroot compiler instead.
let use_snapshot =
mode == Mode::ToolBootstrap || (mode == Mode::ToolTarget && build_compiler_stage == 0);
assert!(!use_snapshot || build_compiler_stage == 0 || self.local_rebuild);
let sysroot = if use_snapshot {
self.rustc_snapshot_sysroot().to_path_buf()
} else {
self.sysroot(compiler)
};
let libdir = self.rustc_libdir(compiler);
let sysroot_str = sysroot.as_os_str().to_str().expect("sysroot should be UTF-8");
if self.is_verbose() && !matches!(self.config.get_dry_run(), DryRun::SelfCheck) {
println!("using sysroot {sysroot_str}");
}
let mut rustflags = Rustflags::new(target);
if build_compiler_stage != 0 {
if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
cargo.args(s.split_whitespace());
}
rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
} else {
if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
cargo.args(s.split_whitespace());
}
rustflags.env("RUSTFLAGS_BOOTSTRAP");
rustflags.arg("--cfg=bootstrap");
}
if cmd_kind == Kind::Clippy {
// clippy overwrites sysroot if we pass it to cargo.
// Pass it directly to clippy instead.
// NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
// so it has no way of knowing the sysroot.
rustflags.arg("--sysroot");
rustflags.arg(sysroot_str);
}
let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
Some(setting) => {
// If an explicit setting is given, use that
setting
}
None => {
if mode == Mode::Std {
// The standard library defaults to the legacy scheme
false
} else {
// The compiler and tools default to the new scheme
true
}
}
};
// By default, windows-rs depends on a native library that doesn't get copied into the
// sysroot. Passing this cfg enables raw-dylib support instead, which makes the native
// library unnecessary. This can be removed when windows-rs enables raw-dylib
// unconditionally.
if let Mode::Rustc | Mode::ToolRustcPrivate | Mode::ToolBootstrap | Mode::ToolTarget = mode
{
rustflags.arg("--cfg=windows_raw_dylib");
}
if use_new_symbol_mangling {
rustflags.arg("-Csymbol-mangling-version=v0");
} else {
rustflags.arg("-Csymbol-mangling-version=legacy");
}
// FIXME: the following components don't build with `-Zrandomize-layout` yet:
// - rust-analyzer, due to the rowan crate
// so we exclude an entire category of steps here due to lack of fine-grained control over
// rustflags.
if self.config.rust_randomize_layout && mode != Mode::ToolRustcPrivate {
rustflags.arg("-Zrandomize-layout");
}
// Enable compile-time checking of `cfg` names, values and Cargo `features`.
//
// Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like
// backtrace, core_simd, std_float, ...), those dependencies have their own
// features but cargo isn't involved in the #[path] process and so cannot pass the
// complete list of features, so for that reason we don't enable checking of
// features for std crates.
if mode == Mode::Std {
rustflags.arg("--check-cfg=cfg(feature,values(any()))");
}
// Add extra cfg not defined in/by rustc
//
// Note: Although it would seems that "-Zunstable-options" to `rustflags` is useless as
// cargo would implicitly add it, it was discover that sometimes bootstrap only use
// `rustflags` without `cargo` making it required.
rustflags.arg("-Zunstable-options");
for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
if restricted_mode.is_none() || *restricted_mode == Some(mode) {
rustflags.arg(&check_cfg_arg(name, *values));
if *name == "bootstrap" {
// Cargo doesn't pass RUSTFLAGS to proc_macros:
// https://github.com/rust-lang/cargo/issues/4423
// Thus, if we are on stage 0, we explicitly set `--cfg=bootstrap`.
// We also declare that the flag is expected, which we need to do to not
// get warnings about it being unexpected.
hostflags.arg(check_cfg_arg(name, *values));
}
}
}
// FIXME(rust-lang/cargo#5754) we shouldn't be using special command arguments
// to the host invocation here, but rather Cargo should know what flags to pass rustc
// itself.
if build_compiler_stage == 0 {
hostflags.arg("--cfg=bootstrap");
}
// FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
// but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
// #71458.
let mut rustdocflags = rustflags.clone();
rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
if build_compiler_stage == 0 {
rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
} else {
rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
}
if let Ok(s) = env::var("CARGOFLAGS") {
cargo.args(s.split_whitespace());
}
match mode {
Mode::Std | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {}
Mode::Rustc | Mode::Codegen | Mode::ToolRustcPrivate => {
// Build proc macros both for the host and the target unless proc-macros are not
// supported by the target.
if target != compiler.host && cmd_kind != Kind::Check {
let mut rustc_cmd = command(self.rustc(compiler));
self.add_rustc_lib_path(compiler, &mut rustc_cmd);
let error = rustc_cmd
.arg("--target")
.arg(target.rustc_target_arg())
.arg("--print=file-names")
.arg("--crate-type=proc-macro")
.arg("-")
.stdin(std::process::Stdio::null())
.run_capture(self)
.stderr();
let not_supported = error
.lines()
.any(|line| line.contains("unsupported crate type `proc-macro`"));
if !not_supported {
cargo.arg("-Zdual-proc-macros");
rustflags.arg("-Zdual-proc-macros");
}
}
}
}
// This tells Cargo (and in turn, rustc) to output more complete
// dependency information. Most importantly for bootstrap, this
// includes sysroot artifacts, like libstd, which means that we don't
// need to track those in bootstrap (an error prone process!). This
// feature is currently unstable as there may be some bugs and such, but
// it represents a big improvement in bootstrap's reliability on
// rebuilds, so we're using it here.
//
// For some additional context, see #63470 (the PR originally adding
// this), as well as #63012 which is the tracking issue for this
// feature on the rustc side.
cargo.arg("-Zbinary-dep-depinfo");
let allow_features = match mode {
Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {
// Restrict the allowed features so we don't depend on nightly
// accidentally.
//
// binary-dep-depinfo is used by bootstrap itself for all
// compilations.
//
// Lots of tools depend on proc_macro2 and proc-macro-error.
// Those have build scripts which assume nightly features are
// available if the `rustc` version is "nighty" or "dev". See
// bin/rustc.rs for why that is a problem. Instead of labeling
// those features for each individual tool that needs them,
// just blanket allow them here.
//
// If this is ever removed, be sure to add something else in
// its place to keep the restrictions in place (or make a way
// to unset RUSTC_BOOTSTRAP).
"binary-dep-depinfo,proc_macro_span,proc_macro_span_shrink,proc_macro_diagnostic"
.to_string()
}
Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustcPrivate => String::new(),
};
cargo.arg("-j").arg(self.jobs().to_string());
// Make cargo emit diagnostics relative to the rustc src dir.
cargo.arg(format!("-Zroot-dir={}", self.src.display()));
if self.config.compile_time_deps {
// Build only build scripts and proc-macros for rust-analyzer when requested.
cargo.arg("-Zunstable-options");
cargo.arg("--compile-time-deps");
}
// FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
// Force cargo to output binaries with disambiguating hashes in the name
let mut metadata = if compiler.stage == 0 {
// Treat stage0 like a special channel, whether it's a normal prior-
// release rustc or a local rebuild with the same version, so we
// never mix these libraries by accident.
"bootstrap".to_string()
} else {
self.config.channel.to_string()
};
// We want to make sure that none of the dependencies between
// std/test/rustc unify with one another. This is done for weird linkage
// reasons but the gist of the problem is that if librustc, libtest, and
// libstd all depend on libc from crates.io (which they actually do) we
// want to make sure they all get distinct versions. Things get really
// weird if we try to unify all these dependencies right now, namely
// around how many times the library is linked in dynamic libraries and
// such. If rustc were a static executable or if we didn't ship dylibs
// this wouldn't be a problem, but we do, so it is. This is in general
// just here to make sure things build right. If you can remove this and
// things still build right, please do!
match mode {
Mode::Std => metadata.push_str("std"),
// When we're building rustc tools, they're built with a search path
// that contains things built during the rustc build. For example,
// bitflags is built during the rustc build, and is a dependency of
// rustdoc as well. We're building rustdoc in a different target
// directory, though, which means that Cargo will rebuild the
// dependency. When we go on to build rustdoc, we'll look for
// bitflags, and find two different copies: one built during the
// rustc step and one that we just built. This isn't always a
// problem, somehow -- not really clear why -- but we know that this
// fixes things.
Mode::ToolRustcPrivate => metadata.push_str("tool-rustc"),
// Same for codegen backends.
Mode::Codegen => metadata.push_str("codegen"),
_ => {}
}
// `rustc_driver`'s version number is always `0.0.0`, which can cause linker search path
// problems on side-by-side installs because we don't include the version number of the
// `rustc_driver` being built. This can cause builds of different version numbers to produce
// `librustc_driver*.so` artifacts that end up with identical filename hashes.
metadata.push_str(&self.version);
cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
if cmd_kind == Kind::Clippy {
rustflags.arg("-Zforce-unstable-if-unmarked");
}
rustflags.arg("-Zmacro-backtrace");
let want_rustdoc = self.doc_tests != DocTests::No;
// Clear the output directory if the real rustc we're using has changed;
// Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
//
// Avoid doing this during dry run as that usually means the relevant
// compiler is not yet linked/copied properly.
//
// Only clear out the directory if we're compiling std; otherwise, we
// should let Cargo take care of things for us (via depdep info)
if !self.config.dry_run() && mode == Mode::Std && cmd_kind == Kind::Build {
build_stamp::clear_if_dirty(self, &out_dir, &self.rustc(compiler));
}
let rustdoc_path = match cmd_kind {
Kind::Doc | Kind::Test | Kind::MiriTest => self.rustdoc_for_compiler(compiler),
_ => PathBuf::from("/path/to/nowhere/rustdoc/not/required"),
};
// Customize the compiler we're running. Specify the compiler to cargo
// as our shim and then pass it some various options used to configure
// how the actual compiler itself is called.
//
// These variables are primarily all read by
// src/bootstrap/bin/{rustc.rs,rustdoc.rs}
cargo
.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
.env("RUSTC_REAL", self.rustc(compiler))
.env("RUSTC_STAGE", build_compiler_stage.to_string())
.env("RUSTC_SYSROOT", sysroot)
.env("RUSTC_LIBDIR", libdir)
.env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
.env("RUSTDOC_REAL", rustdoc_path)
.env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
if self.config.rust_break_on_ice {
cargo.env("RUSTC_BREAK_ON_ICE", "1");
}
// Set RUSTC_WRAPPER to the bootstrap shim, which switches between beta and in-tree
// sysroot depending on whether we're building build scripts.
// NOTE: we intentionally use RUSTC_WRAPPER so that we can support clippy - RUSTC is not
// respected by clippy-driver; RUSTC_WRAPPER happens earlier, before clippy runs.
cargo.env("RUSTC_WRAPPER", self.bootstrap_out.join("rustc"));
// NOTE: we also need to set RUSTC so cargo can run `rustc -vV`; apparently that ignores RUSTC_WRAPPER >:(
cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
// Someone might have set some previous rustc wrapper (e.g.
// sccache) before bootstrap overrode it. Respect that variable.
if let Some(existing_wrapper) = env::var_os("RUSTC_WRAPPER") {
cargo.env("RUSTC_WRAPPER_REAL", existing_wrapper);
}
// If this is for `miri-test`, prepare the sysroots.
if cmd_kind == Kind::MiriTest {
self.std(compiler, compiler.host);
let host_sysroot = self.sysroot(compiler);
let miri_sysroot = test::Miri::build_miri_sysroot(self, compiler, target);
cargo.env("MIRI_SYSROOT", &miri_sysroot);
cargo.env("MIRI_HOST_SYSROOT", &host_sysroot);
}
cargo.env(profile_var("STRIP"), self.config.rust_strip.to_string());
if let Some(stack_protector) = &self.config.rust_stack_protector {
rustflags.arg(&format!("-Zstack-protector={stack_protector}"));
}
if !matches!(cmd_kind, Kind::Build | Kind::Check | Kind::Clippy | Kind::Fix) && want_rustdoc
{
cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
}
let debuginfo_level = match mode {
Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
Mode::Std => self.config.rust_debuginfo_level_std,
Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustcPrivate | Mode::ToolTarget => {
self.config.rust_debuginfo_level_tools
}
};
cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
if let Some(opt_level) = &self.config.rust_optimize.get_opt_level() {
cargo.env(profile_var("OPT_LEVEL"), opt_level);
}
cargo.env(
profile_var("DEBUG_ASSERTIONS"),
match mode {
Mode::Std => self.config.std_debug_assertions,
Mode::Rustc | Mode::Codegen => self.config.rustc_debug_assertions,
Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustcPrivate | Mode::ToolTarget => {
self.config.tools_debug_assertions
}
}
.to_string(),
);
cargo.env(
profile_var("OVERFLOW_CHECKS"),
if mode == Mode::Std {
self.config.rust_overflow_checks_std.to_string()
} else {
self.config.rust_overflow_checks.to_string()
},
);
match self.config.split_debuginfo(target) {
SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
};
if self.config.cmd.bless() {
// Bless `expect!` tests.
cargo.env("UPDATE_EXPECT", "1");
}
if !mode.is_tool() {
cargo.env("RUSTC_FORCE_UNSTABLE", "1");
}
if let Some(x) = self.crt_static(target) {
if x {
rustflags.arg("-Ctarget-feature=+crt-static");
} else {
rustflags.arg("-Ctarget-feature=-crt-static");
}
}
if let Some(x) = self.crt_static(compiler.host) {
let sign = if x { "+" } else { "-" };
hostflags.arg(format!("-Ctarget-feature={sign}crt-static"));
}
// `rustc` needs to know the remapping scheme, in order to know how to reverse it (unremap)
// later. Two env vars are set and made available to the compiler
//
// - `CFG_VIRTUAL_RUST_SOURCE_BASE_DIR`: `rust-src` remap scheme (`NonCompiler`)
// - `CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR`: `rustc-dev` remap scheme (`Compiler`)
//
// Keep this scheme in sync with `rustc_metadata::rmeta::decoder`'s
// `try_to_translate_virtual_to_real`.
//
// `RUSTC_DEBUGINFO_MAP` is used to pass through to the underlying rustc
// `--remap-path-prefix`.
match mode {
Mode::Rustc | Mode::Codegen => {
if let Some(ref map_to) =
self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::NonCompiler)
{
cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
}
if let Some(ref map_to) =
self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::Compiler)