bootstrap/core/builder/cargo.rs
1use std::env;
2use std::ffi::{OsStr, OsString};
3use std::path::{Path, PathBuf};
4
5use build_helper::ci::CiEnv;
6
7use super::{Builder, Kind};
8use crate::core::build_steps::test;
9use crate::core::build_steps::tool::SourceType;
10use crate::core::config::SplitDebuginfo;
11use crate::core::config::flags::Color;
12use crate::utils::build_stamp;
13use crate::utils::helpers::{self, LldThreads, check_cfg_arg, linker_args, linker_flags};
14use crate::{
15 BootstrapCommand, CLang, Compiler, Config, DryRun, EXTRA_CHECK_CFGS, GitRepo, Mode,
16 RemapScheme, TargetSelection, command, prepare_behaviour_dump_dir, t,
17};
18
19/// Represents flag values in `String` form with whitespace delimiter to pass it to the compiler
20/// later.
21///
22/// `-Z crate-attr` flags will be applied recursively on the target code using the
23/// `rustc_parse::parser::Parser`. See `rustc_builtin_macros::cmdline_attrs::inject` for more
24/// information.
25#[derive(Debug, Clone)]
26struct Rustflags(String, TargetSelection);
27
28impl Rustflags {
29 fn new(target: TargetSelection) -> Rustflags {
30 Rustflags(String::new(), target)
31 }
32
33 /// By default, cargo will pick up on various variables in the environment. However, bootstrap
34 /// reuses those variables to pass additional flags to rustdoc, so by default they get
35 /// overridden. Explicitly add back any previous value in the environment.
36 ///
37 /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.
38 fn propagate_cargo_env(&mut self, prefix: &str) {
39 // Inherit `RUSTFLAGS` by default ...
40 self.env(prefix);
41
42 // ... and also handle target-specific env RUSTFLAGS if they're configured.
43 let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
44 self.env(&target_specific);
45 }
46
47 fn env(&mut self, env: &str) {
48 if let Ok(s) = env::var(env) {
49 for part in s.split(' ') {
50 self.arg(part);
51 }
52 }
53 }
54
55 fn arg(&mut self, arg: &str) -> &mut Self {
56 assert_eq!(arg.split(' ').count(), 1);
57 if !self.0.is_empty() {
58 self.0.push(' ');
59 }
60 self.0.push_str(arg);
61 self
62 }
63
64 fn propagate_rustflag_envs(&mut self, build_compiler_stage: u32) {
65 self.propagate_cargo_env("RUSTFLAGS");
66 if build_compiler_stage != 0 {
67 self.env("RUSTFLAGS_NOT_BOOTSTRAP");
68 } else {
69 self.env("RUSTFLAGS_BOOTSTRAP");
70 self.arg("--cfg=bootstrap");
71 }
72 }
73}
74
75/// Flags that are passed to the `rustc` shim binary. These flags will only be applied when
76/// compiling host code, i.e. when `--target` is unset.
77#[derive(Debug, Default)]
78struct HostFlags {
79 rustc: Vec<String>,
80}
81
82impl HostFlags {
83 const SEPARATOR: &'static str = " ";
84
85 /// Adds a host rustc flag.
86 fn arg<S: Into<String>>(&mut self, flag: S) {
87 let value = flag.into().trim().to_string();
88 assert!(!value.contains(Self::SEPARATOR));
89 self.rustc.push(value);
90 }
91
92 /// Encodes all the flags into a single string.
93 fn encode(self) -> String {
94 self.rustc.join(Self::SEPARATOR)
95 }
96}
97
98#[derive(Debug)]
99pub struct Cargo {
100 command: BootstrapCommand,
101 args: Vec<OsString>,
102 compiler: Compiler,
103 mode: Mode,
104 target: TargetSelection,
105 rustflags: Rustflags,
106 rustdocflags: Rustflags,
107 hostflags: HostFlags,
108 allow_features: String,
109 release_build: bool,
110 build_compiler_stage: u32,
111 extra_rustflags: Vec<String>,
112}
113
114impl Cargo {
115 /// Calls [`Builder::cargo`] and [`Cargo::configure_linker`] to prepare an invocation of `cargo`
116 /// to be run.
117 #[track_caller]
118 pub fn new(
119 builder: &Builder<'_>,
120 compiler: Compiler,
121 mode: Mode,
122 source_type: SourceType,
123 target: TargetSelection,
124 cmd_kind: Kind,
125 ) -> Cargo {
126 let mut cargo = builder.cargo(compiler, mode, source_type, target, cmd_kind);
127
128 match cmd_kind {
129 // No need to configure the target linker for these command types.
130 Kind::Clean | Kind::Check | Kind::Format | Kind::Setup => {}
131 _ => {
132 cargo.configure_linker(builder);
133 }
134 }
135
136 cargo
137 }
138
139 pub fn release_build(&mut self, release_build: bool) {
140 self.release_build = release_build;
141 }
142
143 pub fn compiler(&self) -> Compiler {
144 self.compiler
145 }
146
147 pub fn mode(&self) -> Mode {
148 self.mode
149 }
150
151 pub fn into_cmd(self) -> BootstrapCommand {
152 self.into()
153 }
154
155 /// Same as [`Cargo::new`] except this one doesn't configure the linker with
156 /// [`Cargo::configure_linker`].
157 #[track_caller]
158 pub fn new_for_mir_opt_tests(
159 builder: &Builder<'_>,
160 compiler: Compiler,
161 mode: Mode,
162 source_type: SourceType,
163 target: TargetSelection,
164 cmd_kind: Kind,
165 ) -> Cargo {
166 builder.cargo(compiler, mode, source_type, target, cmd_kind)
167 }
168
169 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
170 self.rustdocflags.arg(arg);
171 self
172 }
173
174 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
175 self.rustflags.arg(arg);
176 self
177 }
178
179 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
180 self.args.push(arg.as_ref().into());
181 self
182 }
183
184 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
185 where
186 I: IntoIterator<Item = S>,
187 S: AsRef<OsStr>,
188 {
189 for arg in args {
190 self.arg(arg.as_ref());
191 }
192 self
193 }
194
195 /// Add an env var to the cargo command instance. Note that `RUSTFLAGS`/`RUSTDOCFLAGS` must go
196 /// through [`Cargo::rustdocflags`] and [`Cargo::rustflags`] because inconsistent `RUSTFLAGS`
197 /// and `RUSTDOCFLAGS` usages will trigger spurious rebuilds.
198 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
199 assert_ne!(key.as_ref(), "RUSTFLAGS");
200 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
201 self.command.env(key.as_ref(), value.as_ref());
202 self
203 }
204
205 /// Append a value to an env var of the cargo command instance.
206 /// If the variable was unset previously, this is equivalent to [`Cargo::env`].
207 /// If the variable was already set, this will append `delimiter` and then `value` to it.
208 ///
209 /// Note that this only considers the existence of the env. var. configured on this `Cargo`
210 /// instance. It does not look at the environment of this process.
211 pub fn append_to_env(
212 &mut self,
213 key: impl AsRef<OsStr>,
214 value: impl AsRef<OsStr>,
215 delimiter: impl AsRef<OsStr>,
216 ) -> &mut Cargo {
217 assert_ne!(key.as_ref(), "RUSTFLAGS");
218 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
219
220 let key = key.as_ref();
221 if let Some((_, Some(previous_value))) = self.command.get_envs().find(|(k, _)| *k == key) {
222 let mut combined: OsString = previous_value.to_os_string();
223 combined.push(delimiter.as_ref());
224 combined.push(value.as_ref());
225 self.env(key, combined)
226 } else {
227 self.env(key, value)
228 }
229 }
230
231 pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>) {
232 builder.add_rustc_lib_path(self.compiler, &mut self.command);
233 }
234
235 pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {
236 self.command.current_dir(dir);
237 self
238 }
239
240 /// Adds nightly-only features that this invocation is allowed to use.
241 ///
242 /// By default, all nightly features are allowed. Once this is called, it will be restricted to
243 /// the given set.
244 pub fn allow_features(&mut self, features: &str) -> &mut Cargo {
245 if !self.allow_features.is_empty() {
246 self.allow_features.push(',');
247 }
248 self.allow_features.push_str(features);
249 self
250 }
251
252 // FIXME(onur-ozkan): Add coverage to make sure modifications to this function
253 // doesn't cause cache invalidations (e.g., #130108).
254 fn configure_linker(&mut self, builder: &Builder<'_>) -> &mut Cargo {
255 let target = self.target;
256 let compiler = self.compiler;
257
258 // Dealing with rpath here is a little special, so let's go into some
259 // detail. First off, `-rpath` is a linker option on Unix platforms
260 // which adds to the runtime dynamic loader path when looking for
261 // dynamic libraries. We use this by default on Unix platforms to ensure
262 // that our nightlies behave the same on Windows, that is they work out
263 // of the box. This can be disabled by setting `rpath = false` in `[rust]`
264 // table of `bootstrap.toml`
265 //
266 // Ok, so the astute might be wondering "why isn't `-C rpath` used
267 // here?" and that is indeed a good question to ask. This codegen
268 // option is the compiler's current interface to generating an rpath.
269 // Unfortunately it doesn't quite suffice for us. The flag currently
270 // takes no value as an argument, so the compiler calculates what it
271 // should pass to the linker as `-rpath`. This unfortunately is based on
272 // the **compile time** directory structure which when building with
273 // Cargo will be very different than the runtime directory structure.
274 //
275 // All that's a really long winded way of saying that if we use
276 // `-Crpath` then the executables generated have the wrong rpath of
277 // something like `$ORIGIN/deps` when in fact the way we distribute
278 // rustc requires the rpath to be `$ORIGIN/../lib`.
279 //
280 // So, all in all, to set up the correct rpath we pass the linker
281 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
282 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
283 // to change a flag in a binary?
284 if builder.config.rpath_enabled(target) && helpers::use_host_linker(target) {
285 let libdir = builder.sysroot_libdir_relative(compiler).to_str().unwrap();
286 let rpath = if target.contains("apple") {
287 // Note that we need to take one extra step on macOS to also pass
288 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
289 // do that we pass a weird flag to the compiler to get it to do
290 // so. Note that this is definitely a hack, and we should likely
291 // flesh out rpath support more fully in the future.
292 self.rustflags.arg("-Zosx-rpath-install-name");
293 Some(format!("-Wl,-rpath,@loader_path/../{libdir}"))
294 } else if !target.is_windows()
295 && !target.contains("cygwin")
296 && !target.contains("aix")
297 && !target.contains("xous")
298 {
299 self.rustflags.arg("-Clink-args=-Wl,-z,origin");
300 Some(format!("-Wl,-rpath,$ORIGIN/../{libdir}"))
301 } else {
302 None
303 };
304 if let Some(rpath) = rpath {
305 self.rustflags.arg(&format!("-Clink-args={rpath}"));
306 }
307 }
308
309 for arg in linker_args(builder, compiler.host, LldThreads::Yes) {
310 self.hostflags.arg(&arg);
311 }
312
313 if let Some(target_linker) = builder.linker(target) {
314 let target = crate::envify(&target.triple);
315 self.command.env(format!("CARGO_TARGET_{target}_LINKER"), target_linker);
316 }
317 // We want to set -Clinker using Cargo, therefore we only call `linker_flags` and not
318 // `linker_args` here.
319 for flag in linker_flags(builder, target, LldThreads::Yes) {
320 self.rustflags.arg(&flag);
321 }
322 for arg in linker_args(builder, target, LldThreads::Yes) {
323 self.rustdocflags.arg(&arg);
324 }
325
326 if !builder.config.dry_run() && builder.cc[&target].args().iter().any(|arg| arg == "-gz") {
327 self.rustflags.arg("-Clink-arg=-gz");
328 }
329
330 // Ignore linker warnings for now. These are complicated to fix and don't affect the build.
331 // FIXME: we should really investigate these...
332 self.rustflags.arg("-Alinker-messages");
333
334 // Throughout the build Cargo can execute a number of build scripts
335 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
336 // obtained previously to those build scripts.
337 // Build scripts use either the `cc` crate or `configure/make` so we pass
338 // the options through environment variables that are fetched and understood by both.
339 //
340 // FIXME: the guard against msvc shouldn't need to be here
341 if target.is_msvc() {
342 if let Some(ref cl) = builder.config.llvm_clang_cl {
343 // FIXME: There is a bug in Clang 18 when building for ARM64:
344 // https://github.com/llvm/llvm-project/pull/81849. This is
345 // fixed in LLVM 19, but can't be backported.
346 if !target.starts_with("aarch64") && !target.starts_with("arm64ec") {
347 self.command.env("CC", cl).env("CXX", cl);
348 }
349 }
350 } else {
351 let ccache = builder.config.ccache.as_ref();
352 let ccacheify = |s: &Path| {
353 let ccache = match ccache {
354 Some(ref s) => s,
355 None => return s.display().to_string(),
356 };
357 // FIXME: the cc-rs crate only recognizes the literal strings
358 // `ccache` and `sccache` when doing caching compilations, so we
359 // mirror that here. It should probably be fixed upstream to
360 // accept a new env var or otherwise work with custom ccache
361 // vars.
362 match &ccache[..] {
363 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
364 _ => s.display().to_string(),
365 }
366 };
367 let triple_underscored = target.triple.replace('-', "_");
368 let cc = ccacheify(&builder.cc(target));
369 self.command.env(format!("CC_{triple_underscored}"), &cc);
370
371 // Extend `CXXFLAGS_$TARGET` with our extra flags.
372 let env = format!("CFLAGS_{triple_underscored}");
373 let mut cflags =
374 builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::C).join(" ");
375 if let Ok(var) = std::env::var(&env) {
376 cflags.push(' ');
377 cflags.push_str(&var);
378 }
379 self.command.env(env, &cflags);
380
381 if let Some(ar) = builder.ar(target) {
382 let ranlib = format!("{} s", ar.display());
383 self.command
384 .env(format!("AR_{triple_underscored}"), ar)
385 .env(format!("RANLIB_{triple_underscored}"), ranlib);
386 }
387
388 if let Ok(cxx) = builder.cxx(target) {
389 let cxx = ccacheify(&cxx);
390 self.command.env(format!("CXX_{triple_underscored}"), &cxx);
391
392 // Extend `CXXFLAGS_$TARGET` with our extra flags.
393 let env = format!("CXXFLAGS_{triple_underscored}");
394 let mut cxxflags =
395 builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");
396 if let Ok(var) = std::env::var(&env) {
397 cxxflags.push(' ');
398 cxxflags.push_str(&var);
399 }
400 self.command.env(&env, cxxflags);
401 }
402 }
403
404 self
405 }
406}
407
408impl From<Cargo> for BootstrapCommand {
409 fn from(mut cargo: Cargo) -> BootstrapCommand {
410 if cargo.release_build {
411 cargo.args.insert(0, "--release".into());
412 }
413
414 for arg in &cargo.extra_rustflags {
415 cargo.rustflags.arg(arg);
416 cargo.rustdocflags.arg(arg);
417 }
418
419 // Propagate the envs here at the very end to make sure they override any previously set flags.
420 cargo.rustflags.propagate_rustflag_envs(cargo.build_compiler_stage);
421 cargo.rustdocflags.propagate_rustflag_envs(cargo.build_compiler_stage);
422
423 cargo.rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");
424
425 if cargo.build_compiler_stage == 0 {
426 cargo.rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");
427 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
428 cargo.args(s.split_whitespace());
429 }
430 } else {
431 cargo.rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");
432 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
433 cargo.args(s.split_whitespace());
434 }
435 }
436
437 if let Ok(s) = env::var("CARGOFLAGS") {
438 cargo.args(s.split_whitespace());
439 }
440
441 cargo.command.args(cargo.args);
442
443 let rustflags = &cargo.rustflags.0;
444 if !rustflags.is_empty() {
445 cargo.command.env("RUSTFLAGS", rustflags);
446 }
447
448 let rustdocflags = &cargo.rustdocflags.0;
449 if !rustdocflags.is_empty() {
450 cargo.command.env("RUSTDOCFLAGS", rustdocflags);
451 }
452
453 let encoded_hostflags = cargo.hostflags.encode();
454 if !encoded_hostflags.is_empty() {
455 cargo.command.env("RUSTC_HOST_FLAGS", encoded_hostflags);
456 }
457
458 if !cargo.allow_features.is_empty() {
459 cargo.command.env("RUSTC_ALLOW_FEATURES", cargo.allow_features);
460 }
461
462 cargo.command
463 }
464}
465
466impl Builder<'_> {
467 /// Like [`Builder::cargo`], but only passes flags that are valid for all commands.
468 #[track_caller]
469 pub fn bare_cargo(
470 &self,
471 compiler: Compiler,
472 mode: Mode,
473 target: TargetSelection,
474 cmd_kind: Kind,
475 ) -> BootstrapCommand {
476 let mut cargo = match cmd_kind {
477 Kind::Clippy => {
478 let mut cargo = self.cargo_clippy_cmd(compiler);
479 cargo.arg(cmd_kind.as_str());
480 cargo
481 }
482 Kind::MiriSetup => {
483 let mut cargo = self.cargo_miri_cmd(compiler);
484 cargo.arg("miri").arg("setup");
485 cargo
486 }
487 Kind::MiriTest => {
488 let mut cargo = self.cargo_miri_cmd(compiler);
489 cargo.arg("miri").arg("test");
490 cargo
491 }
492 _ => {
493 let mut cargo = command(&self.initial_cargo);
494 cargo.arg(cmd_kind.as_str());
495 cargo
496 }
497 };
498
499 // Run cargo from the source root so it can find .cargo/config.
500 // This matters when using vendoring and the working directory is outside the repository.
501 cargo.current_dir(&self.src);
502
503 let out_dir = self.stage_out(compiler, mode);
504 cargo.env("CARGO_TARGET_DIR", &out_dir);
505
506 // Bootstrap makes a lot of assumptions about the artifacts produced in the target
507 // directory. If users override the "build directory" using `build-dir`
508 // (https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-dir), then
509 // bootstrap couldn't find these artifacts. So we forcefully override that option to our
510 // target directory here.
511 // In the future, we could attempt to read the build-dir location from Cargo and actually
512 // respect it.
513 cargo.env("CARGO_BUILD_BUILD_DIR", &out_dir);
514
515 // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`
516 // from out of tree it shouldn't matter, since x.py is only used for
517 // building in-tree.
518 let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];
519 match self.build.config.color {
520 Color::Always => {
521 cargo.arg("--color=always");
522 for log in &color_logs {
523 cargo.env(log, "always");
524 }
525 }
526 Color::Never => {
527 cargo.arg("--color=never");
528 for log in &color_logs {
529 cargo.env(log, "never");
530 }
531 }
532 Color::Auto => {} // nothing to do
533 }
534
535 if cmd_kind != Kind::Install {
536 cargo.arg("--target").arg(target.rustc_target_arg());
537 } else {
538 assert_eq!(target, compiler.host);
539 }
540
541 // Remove make-related flags to ensure Cargo can correctly set things up
542 cargo.env_remove("MAKEFLAGS");
543 cargo.env_remove("MFLAGS");
544
545 cargo
546 }
547
548 /// This will create a [`BootstrapCommand`] that represents a pending execution of cargo. This
549 /// cargo will be configured to use `compiler` as the actual rustc compiler, its output will be
550 /// scoped by `mode`'s output directory, it will pass the `--target` flag for the specified
551 /// `target`, and will be executing the Cargo command `cmd`. `cmd` can be `miri-cmd` for
552 /// commands to be run with Miri.
553 #[track_caller]
554 fn cargo(
555 &self,
556 compiler: Compiler,
557 mode: Mode,
558 source_type: SourceType,
559 target: TargetSelection,
560 cmd_kind: Kind,
561 ) -> Cargo {
562 let mut cargo = self.bare_cargo(compiler, mode, target, cmd_kind);
563 let out_dir = self.stage_out(compiler, mode);
564
565 let mut hostflags = HostFlags::default();
566
567 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
568 // so we need to explicitly clear out if they've been updated.
569 for backend in self.codegen_backends(compiler) {
570 build_stamp::clear_if_dirty(self, &out_dir, &backend);
571 }
572
573 if self.config.cmd.timings() {
574 cargo.arg("--timings");
575 }
576
577 if cmd_kind == Kind::Doc {
578 let my_out = match mode {
579 // This is the intended out directory for compiler documentation.
580 Mode::Rustc | Mode::ToolRustcPrivate | Mode::ToolBootstrap | Mode::ToolTarget => {
581 self.compiler_doc_out(target)
582 }
583 Mode::Std => {
584 if self.config.cmd.json() {
585 out_dir.join(target).join("json-doc")
586 } else {
587 out_dir.join(target).join("doc")
588 }
589 }
590 _ => panic!("doc mode {mode:?} not expected"),
591 };
592 let rustdoc = self.rustdoc_for_compiler(compiler);
593 build_stamp::clear_if_dirty(self, &my_out, &rustdoc);
594 }
595
596 let profile_var = |name: &str| cargo_profile_var(name, &self.config);
597
598 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
599 // needs to not accidentally link to libLLVM in stage0/lib.
600 cargo.env("REAL_LIBRARY_PATH_VAR", helpers::dylib_path_var());
601 if let Some(e) = env::var_os(helpers::dylib_path_var()) {
602 cargo.env("REAL_LIBRARY_PATH", e);
603 }
604
605 // Set a flag for `check`/`clippy`/`fix`, so that certain build
606 // scripts can do less work (i.e. not building/requiring LLVM).
607 if matches!(cmd_kind, Kind::Check | Kind::Clippy | Kind::Fix) {
608 // If we've not yet built LLVM, or it's stale, then bust
609 // the rustc_llvm cache. That will always work, even though it
610 // may mean that on the next non-check build we'll need to rebuild
611 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
612 // of work comparatively, and we'd likely need to rebuild it anyway,
613 // so that's okay.
614 if crate::core::build_steps::llvm::prebuilt_llvm_config(self, target, false)
615 .should_build()
616 {
617 cargo.env("RUST_CHECK", "1");
618 }
619 }
620
621 let build_compiler_stage = if compiler.stage == 0 && self.local_rebuild {
622 // Assume the local-rebuild rustc already has stage1 features.
623 1
624 } else {
625 compiler.stage
626 };
627
628 // We synthetically interpret a stage0 compiler used to build tools as a
629 // "raw" compiler in that it's the exact snapshot we download. For things like
630 // ToolRustcPrivate, we would have to use the artificial stage0-sysroot compiler instead.
631 let use_snapshot =
632 mode == Mode::ToolBootstrap || (mode == Mode::ToolTarget && build_compiler_stage == 0);
633 assert!(!use_snapshot || build_compiler_stage == 0 || self.local_rebuild);
634
635 let sysroot = if use_snapshot {
636 self.rustc_snapshot_sysroot().to_path_buf()
637 } else {
638 self.sysroot(compiler)
639 };
640 let libdir = self.rustc_libdir(compiler);
641
642 let sysroot_str = sysroot.as_os_str().to_str().expect("sysroot should be UTF-8");
643 if self.is_verbose() && !matches!(self.config.get_dry_run(), DryRun::SelfCheck) {
644 println!("using sysroot {sysroot_str}");
645 }
646
647 let mut rustflags = Rustflags::new(target);
648
649 if cmd_kind == Kind::Clippy {
650 // clippy overwrites sysroot if we pass it to cargo.
651 // Pass it directly to clippy instead.
652 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
653 // so it has no way of knowing the sysroot.
654 rustflags.arg("--sysroot");
655 rustflags.arg(sysroot_str);
656 }
657
658 let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling {
659 Some(setting) => {
660 // If an explicit setting is given, use that
661 setting
662 }
663 // Per compiler-team#938, v0 mangling is used on nightly
664 None if self.config.channel == "dev" || self.config.channel == "nightly" => true,
665 None => {
666 if mode == Mode::Std {
667 // The standard library defaults to the legacy scheme
668 false
669 } else {
670 // The compiler and tools default to the new scheme
671 true
672 }
673 }
674 };
675
676 // By default, windows-rs depends on a native library that doesn't get copied into the
677 // sysroot. Passing this cfg enables raw-dylib support instead, which makes the native
678 // library unnecessary. This can be removed when windows-rs enables raw-dylib
679 // unconditionally.
680 if let Mode::Rustc | Mode::ToolRustcPrivate | Mode::ToolBootstrap | Mode::ToolTarget = mode
681 {
682 rustflags.arg("--cfg=windows_raw_dylib");
683 }
684
685 if use_new_symbol_mangling {
686 rustflags.arg("-Csymbol-mangling-version=v0");
687 } else {
688 rustflags.arg("-Csymbol-mangling-version=legacy");
689 }
690
691 // Always enable move/copy annotations for profiler visibility (non-stage0 only).
692 // Note that -Zannotate-moves is only effective with debugging info enabled.
693 if build_compiler_stage >= 1 {
694 if let Some(limit) = self.config.rust_annotate_moves_size_limit {
695 rustflags.arg(&format!("-Zannotate-moves={limit}"));
696 } else {
697 rustflags.arg("-Zannotate-moves");
698 }
699 }
700
701 // FIXME: the following components don't build with `-Zrandomize-layout` yet:
702 // - rust-analyzer, due to the rowan crate
703 // so we exclude an entire category of steps here due to lack of fine-grained control over
704 // rustflags.
705 if self.config.rust_randomize_layout && mode != Mode::ToolRustcPrivate {
706 rustflags.arg("-Zrandomize-layout");
707 }
708
709 // Enable compile-time checking of `cfg` names, values and Cargo `features`.
710 //
711 // Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like
712 // backtrace, core_simd, std_float, ...), those dependencies have their own
713 // features but cargo isn't involved in the #[path] process and so cannot pass the
714 // complete list of features, so for that reason we don't enable checking of
715 // features for std crates.
716 if mode == Mode::Std {
717 rustflags.arg("--check-cfg=cfg(feature,values(any()))");
718 }
719
720 // Add extra cfg not defined in/by rustc
721 //
722 // Note: Although it would seems that "-Zunstable-options" to `rustflags` is useless as
723 // cargo would implicitly add it, it was discover that sometimes bootstrap only use
724 // `rustflags` without `cargo` making it required.
725 rustflags.arg("-Zunstable-options");
726
727 // Add parallel frontend threads configuration
728 if let Some(threads) = self.config.rust_parallel_frontend_threads {
729 rustflags.arg(&format!("-Zthreads={threads}"));
730 }
731
732 for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {
733 if restricted_mode.is_none() || *restricted_mode == Some(mode) {
734 rustflags.arg(&check_cfg_arg(name, *values));
735
736 if *name == "bootstrap" {
737 // Cargo doesn't pass RUSTFLAGS to proc_macros:
738 // https://github.com/rust-lang/cargo/issues/4423
739 // Thus, if we are on stage 0, we explicitly set `--cfg=bootstrap`.
740 // We also declare that the flag is expected, which we need to do to not
741 // get warnings about it being unexpected.
742 hostflags.arg(check_cfg_arg(name, *values));
743 }
744 }
745 }
746
747 // FIXME(rust-lang/cargo#5754) we shouldn't be using special command arguments
748 // to the host invocation here, but rather Cargo should know what flags to pass rustc
749 // itself.
750 if build_compiler_stage == 0 {
751 hostflags.arg("--cfg=bootstrap");
752 }
753
754 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
755 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
756 // #71458.
757 let mut rustdocflags = rustflags.clone();
758
759 match mode {
760 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {}
761 Mode::Rustc | Mode::Codegen | Mode::ToolRustcPrivate => {
762 // Build proc macros both for the host and the target unless proc-macros are not
763 // supported by the target.
764 if target != compiler.host && cmd_kind != Kind::Check {
765 let error = self
766 .rustc_cmd(compiler)
767 .arg("--target")
768 .arg(target.rustc_target_arg())
769 .arg("--print=file-names")
770 .arg("--crate-type=proc-macro")
771 .arg("-")
772 .stdin(std::process::Stdio::null())
773 .run_capture(self)
774 .stderr();
775
776 let not_supported = error
777 .lines()
778 .any(|line| line.contains("unsupported crate type `proc-macro`"));
779 if !not_supported {
780 cargo.arg("-Zdual-proc-macros");
781 rustflags.arg("-Zdual-proc-macros");
782 }
783 }
784 }
785 }
786
787 // This tells Cargo (and in turn, rustc) to output more complete
788 // dependency information. Most importantly for bootstrap, this
789 // includes sysroot artifacts, like libstd, which means that we don't
790 // need to track those in bootstrap (an error prone process!). This
791 // feature is currently unstable as there may be some bugs and such, but
792 // it represents a big improvement in bootstrap's reliability on
793 // rebuilds, so we're using it here.
794 //
795 // For some additional context, see #63470 (the PR originally adding
796 // this), as well as #63012 which is the tracking issue for this
797 // feature on the rustc side.
798 cargo.arg("-Zbinary-dep-depinfo");
799 let allow_features = match mode {
800 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {
801 // Restrict the allowed features so we don't depend on nightly
802 // accidentally.
803 //
804 // binary-dep-depinfo is used by bootstrap itself for all
805 // compilations.
806 //
807 // Lots of tools depend on proc_macro2 and proc-macro-error.
808 // Those have build scripts which assume nightly features are
809 // available if the `rustc` version is "nighty" or "dev". See
810 // bin/rustc.rs for why that is a problem. Instead of labeling
811 // those features for each individual tool that needs them,
812 // just blanket allow them here.
813 //
814 // If this is ever removed, be sure to add something else in
815 // its place to keep the restrictions in place (or make a way
816 // to unset RUSTC_BOOTSTRAP).
817 "binary-dep-depinfo,proc_macro_span,proc_macro_span_shrink,proc_macro_diagnostic"
818 .to_string()
819 }
820 Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustcPrivate => String::new(),
821 };
822
823 cargo.arg("-j").arg(self.jobs().to_string());
824
825 // Make cargo emit diagnostics relative to the rustc src dir.
826 cargo.arg(format!("-Zroot-dir={}", self.src.display()));
827
828 if self.config.compile_time_deps {
829 // Build only build scripts and proc-macros for rust-analyzer when requested.
830 cargo.arg("-Zunstable-options");
831 cargo.arg("--compile-time-deps");
832 }
833
834 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
835 // Force cargo to output binaries with disambiguating hashes in the name
836 let mut metadata = if compiler.stage == 0 {
837 // Treat stage0 like a special channel, whether it's a normal prior-
838 // release rustc or a local rebuild with the same version, so we
839 // never mix these libraries by accident.
840 "bootstrap".to_string()
841 } else {
842 self.config.channel.to_string()
843 };
844 // We want to make sure that none of the dependencies between
845 // std/test/rustc unify with one another. This is done for weird linkage
846 // reasons but the gist of the problem is that if librustc, libtest, and
847 // libstd all depend on libc from crates.io (which they actually do) we
848 // want to make sure they all get distinct versions. Things get really
849 // weird if we try to unify all these dependencies right now, namely
850 // around how many times the library is linked in dynamic libraries and
851 // such. If rustc were a static executable or if we didn't ship dylibs
852 // this wouldn't be a problem, but we do, so it is. This is in general
853 // just here to make sure things build right. If you can remove this and
854 // things still build right, please do!
855 match mode {
856 Mode::Std => metadata.push_str("std"),
857 // When we're building rustc tools, they're built with a search path
858 // that contains things built during the rustc build. For example,
859 // bitflags is built during the rustc build, and is a dependency of
860 // rustdoc as well. We're building rustdoc in a different target
861 // directory, though, which means that Cargo will rebuild the
862 // dependency. When we go on to build rustdoc, we'll look for
863 // bitflags, and find two different copies: one built during the
864 // rustc step and one that we just built. This isn't always a
865 // problem, somehow -- not really clear why -- but we know that this
866 // fixes things.
867 Mode::ToolRustcPrivate => metadata.push_str("tool-rustc"),
868 // Same for codegen backends.
869 Mode::Codegen => metadata.push_str("codegen"),
870 _ => {}
871 }
872 // `rustc_driver`'s version number is always `0.0.0`, which can cause linker search path
873 // problems on side-by-side installs because we don't include the version number of the
874 // `rustc_driver` being built. This can cause builds of different version numbers to produce
875 // `librustc_driver*.so` artifacts that end up with identical filename hashes.
876 metadata.push_str(&self.version);
877
878 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
879
880 if cmd_kind == Kind::Clippy {
881 rustflags.arg("-Zforce-unstable-if-unmarked");
882 }
883
884 rustflags.arg("-Zmacro-backtrace");
885
886 // Clear the output directory if the real rustc we're using has changed;
887 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
888 //
889 // Avoid doing this during dry run as that usually means the relevant
890 // compiler is not yet linked/copied properly.
891 //
892 // Only clear out the directory if we're compiling std; otherwise, we
893 // should let Cargo take care of things for us (via depdep info)
894 if !self.config.dry_run() && mode == Mode::Std && cmd_kind == Kind::Build {
895 build_stamp::clear_if_dirty(self, &out_dir, &self.rustc(compiler));
896 }
897
898 let rustdoc_path = match cmd_kind {
899 Kind::Doc | Kind::Test | Kind::MiriTest => self.rustdoc_for_compiler(compiler),
900 _ => PathBuf::from("/path/to/nowhere/rustdoc/not/required"),
901 };
902
903 // Customize the compiler we're running. Specify the compiler to cargo
904 // as our shim and then pass it some various options used to configure
905 // how the actual compiler itself is called.
906 //
907 // These variables are primarily all read by
908 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
909 cargo
910 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
911 .env("RUSTC_REAL", self.rustc(compiler))
912 .env("RUSTC_STAGE", build_compiler_stage.to_string())
913 .env("RUSTC_SYSROOT", sysroot)
914 .env("RUSTC_LIBDIR", &libdir)
915 .env("RUSTDOC_LIBDIR", libdir)
916 .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))
917 .env("RUSTDOC_REAL", rustdoc_path)
918 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
919
920 if self.config.rust_break_on_ice {
921 cargo.env("RUSTC_BREAK_ON_ICE", "1");
922 }
923
924 // Set RUSTC_WRAPPER to the bootstrap shim, which switches between beta and in-tree
925 // sysroot depending on whether we're building build scripts.
926 // NOTE: we intentionally use RUSTC_WRAPPER so that we can support clippy - RUSTC is not
927 // respected by clippy-driver; RUSTC_WRAPPER happens earlier, before clippy runs.
928 cargo.env("RUSTC_WRAPPER", self.bootstrap_out.join("rustc"));
929 // NOTE: we also need to set RUSTC so cargo can run `rustc -vV`; apparently that ignores RUSTC_WRAPPER >:(
930 cargo.env("RUSTC", self.bootstrap_out.join("rustc"));
931
932 // Someone might have set some previous rustc wrapper (e.g.
933 // sccache) before bootstrap overrode it. Respect that variable.
934 if let Some(existing_wrapper) = env::var_os("RUSTC_WRAPPER") {
935 cargo.env("RUSTC_WRAPPER_REAL", existing_wrapper);
936 }
937
938 // If this is for `miri-test`, prepare the sysroots.
939 if cmd_kind == Kind::MiriTest {
940 self.std(compiler, compiler.host);
941 let host_sysroot = self.sysroot(compiler);
942 let miri_sysroot = test::Miri::build_miri_sysroot(self, compiler, target);
943 cargo.env("MIRI_SYSROOT", &miri_sysroot);
944 cargo.env("MIRI_HOST_SYSROOT", &host_sysroot);
945 }
946
947 cargo.env(profile_var("STRIP"), self.config.rust_strip.to_string());
948
949 if let Some(stack_protector) = &self.config.rust_stack_protector {
950 rustflags.arg(&format!("-Zstack-protector={stack_protector}"));
951 }
952
953 let debuginfo_level = match mode {
954 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
955 Mode::Std => self.config.rust_debuginfo_level_std,
956 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustcPrivate | Mode::ToolTarget => {
957 self.config.rust_debuginfo_level_tools
958 }
959 };
960 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
961 if let Some(opt_level) = &self.config.rust_optimize.get_opt_level() {
962 cargo.env(profile_var("OPT_LEVEL"), opt_level);
963 }
964 cargo.env(
965 profile_var("DEBUG_ASSERTIONS"),
966 match mode {
967 Mode::Std => self.config.std_debug_assertions,
968 Mode::Rustc | Mode::Codegen => self.config.rustc_debug_assertions,
969 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustcPrivate | Mode::ToolTarget => {
970 self.config.tools_debug_assertions
971 }
972 }
973 .to_string(),
974 );
975 cargo.env(
976 profile_var("OVERFLOW_CHECKS"),
977 if mode == Mode::Std {
978 self.config.rust_overflow_checks_std.to_string()
979 } else {
980 self.config.rust_overflow_checks.to_string()
981 },
982 );
983
984 match self.config.split_debuginfo(target) {
985 SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),
986 SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),
987 SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),
988 };
989
990 if self.config.cmd.bless() {
991 // Bless `expect!` tests.
992 cargo.env("UPDATE_EXPECT", "1");
993 }
994
995 if !mode.is_tool() {
996 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
997 }
998
999 if let Some(x) = self.crt_static(target) {
1000 if x {
1001 rustflags.arg("-Ctarget-feature=+crt-static");
1002 } else {
1003 rustflags.arg("-Ctarget-feature=-crt-static");
1004 }
1005 }
1006
1007 if let Some(x) = self.crt_static(compiler.host) {
1008 let sign = if x { "+" } else { "-" };
1009 hostflags.arg(format!("-Ctarget-feature={sign}crt-static"));
1010 }
1011
1012 // `rustc` needs to know the remapping scheme, in order to know how to reverse it (unremap)
1013 // later. Two env vars are set and made available to the compiler
1014 //
1015 // - `CFG_VIRTUAL_RUST_SOURCE_BASE_DIR`: `rust-src` remap scheme (`NonCompiler`)
1016 // - `CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR`: `rustc-dev` remap scheme (`Compiler`)
1017 //
1018 // Keep this scheme in sync with `rustc_metadata::rmeta::decoder`'s
1019 // `try_to_translate_virtual_to_real`.
1020 //
1021 // `RUSTC_DEBUGINFO_MAP` is used to pass through to the underlying rustc
1022 // `--remap-path-prefix`.
1023 match mode {
1024 Mode::Rustc | Mode::Codegen => {
1025 if let Some(ref map_to) =
1026 self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::NonCompiler)
1027 {
1028 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1029 }
1030
1031 if let Some(ref map_to) =
1032 self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::Compiler)
1033 {
1034 // When building compiler sources, we want to apply the compiler remap scheme.
1035 cargo.env(
1036 "RUSTC_DEBUGINFO_MAP",
1037 format!("{}={}", self.build.src.display(), map_to),
1038 );
1039 cargo.env("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR", map_to);
1040 }
1041 }
1042 Mode::Std
1043 | Mode::ToolBootstrap
1044 | Mode::ToolRustcPrivate
1045 | Mode::ToolStd
1046 | Mode::ToolTarget => {
1047 if let Some(ref map_to) =
1048 self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::NonCompiler)
1049 {
1050 cargo.env(
1051 "RUSTC_DEBUGINFO_MAP",
1052 format!("{}={}", self.build.src.display(), map_to),
1053 );
1054 }
1055 }
1056 }
1057
1058 if self.config.rust_remap_debuginfo {
1059 let mut env_var = OsString::new();
1060 if let Some(vendor) = self.build.vendored_crates_path() {
1061 env_var.push(vendor);
1062 env_var.push("=/rust/deps");
1063 } else {
1064 let registry_src = t!(home::cargo_home()).join("registry").join("src");
1065 for entry in t!(std::fs::read_dir(registry_src)) {
1066 if !env_var.is_empty() {
1067 env_var.push("\t");
1068 }
1069 env_var.push(t!(entry).path());
1070 env_var.push("=/rust/deps");
1071 }
1072 }
1073 cargo.env("RUSTC_CARGO_REGISTRY_SRC_TO_REMAP", env_var);
1074 }
1075
1076 // Enable usage of unstable features
1077 cargo.env("RUSTC_BOOTSTRAP", "1");
1078
1079 if self.config.dump_bootstrap_shims {
1080 prepare_behaviour_dump_dir(self.build);
1081
1082 cargo
1083 .env("DUMP_BOOTSTRAP_SHIMS", self.build.out.join("bootstrap-shims-dump"))
1084 .env("BUILD_OUT", &self.build.out)
1085 .env("CARGO_HOME", t!(home::cargo_home()));
1086 };
1087
1088 self.add_rust_test_threads(&mut cargo);
1089
1090 // Almost all of the crates that we compile as part of the bootstrap may
1091 // have a build script, including the standard library. To compile a
1092 // build script, however, it itself needs a standard library! This
1093 // introduces a bit of a pickle when we're compiling the standard
1094 // library itself.
1095 //
1096 // To work around this we actually end up using the snapshot compiler
1097 // (stage0) for compiling build scripts of the standard library itself.
1098 // The stage0 compiler is guaranteed to have a libstd available for use.
1099 //
1100 // For other crates, however, we know that we've already got a standard
1101 // library up and running, so we can use the normal compiler to compile
1102 // build scripts in that situation.
1103 if mode == Mode::Std {
1104 cargo
1105 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1106 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1107 } else {
1108 cargo
1109 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1110 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1111 }
1112
1113 // Tools that use compiler libraries may inherit the `-lLLVM` link
1114 // requirement, but the `-L` library path is not propagated across
1115 // separate Cargo projects. We can add LLVM's library path to the
1116 // rustc args as a workaround.
1117 if (mode == Mode::ToolRustcPrivate || mode == Mode::Codegen)
1118 && let Some(llvm_config) = self.llvm_config(target)
1119 {
1120 let llvm_libdir =
1121 command(llvm_config).cached().arg("--libdir").run_capture_stdout(self).stdout();
1122 if target.is_msvc() {
1123 rustflags.arg(&format!("-Clink-arg=-LIBPATH:{llvm_libdir}"));
1124 } else {
1125 rustflags.arg(&format!("-Clink-arg=-L{llvm_libdir}"));
1126 }
1127 }
1128
1129 // Compile everything except libraries and proc macros with the more
1130 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1131 // so we can't use it by default in general, but we can use it for tools
1132 // and our own internal libraries.
1133 //
1134 // Cygwin only supports emutls.
1135 if !mode.must_support_dlopen()
1136 && !target.triple.starts_with("powerpc-")
1137 && !target.triple.contains("cygwin")
1138 {
1139 cargo.env("RUSTC_TLS_MODEL_INITIAL_EXEC", "1");
1140 }
1141
1142 // Ignore incremental modes except for stage0, since we're
1143 // not guaranteeing correctness across builds if the compiler
1144 // is changing under your feet.
1145 if self.config.incremental && compiler.stage == 0 {
1146 cargo.env("CARGO_INCREMENTAL", "1");
1147 } else {
1148 // Don't rely on any default setting for incr. comp. in Cargo
1149 cargo.env("CARGO_INCREMENTAL", "0");
1150 }
1151
1152 if let Some(ref on_fail) = self.config.on_fail {
1153 cargo.env("RUSTC_ON_FAIL", on_fail);
1154 }
1155
1156 if self.config.print_step_timings {
1157 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1158 }
1159
1160 if self.config.print_step_rusage {
1161 cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");
1162 }
1163
1164 if self.config.backtrace_on_ice {
1165 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1166 }
1167
1168 if self.verbosity >= 2 {
1169 // This provides very useful logs especially when debugging build cache-related stuff.
1170 cargo.env("CARGO_LOG", "cargo::core::compiler::fingerprint=info");
1171 }
1172
1173 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1174
1175 // Downstream forks of the Rust compiler might want to use a custom libc to add support for
1176 // targets that are not yet available upstream. Adding a patch to replace libc with a
1177 // custom one would cause compilation errors though, because Cargo would interpret the
1178 // custom libc as part of the workspace, and apply the check-cfg lints on it.
1179 //
1180 // The libc build script emits check-cfg flags only when this environment variable is set,
1181 // so this line allows the use of custom libcs.
1182 cargo.env("LIBC_CHECK_CFG", "1");
1183
1184 let mut lint_flags = Vec::new();
1185
1186 // Lints for all in-tree code: compiler, rustdoc, cranelift, gcc,
1187 // clippy, rustfmt, rust-analyzer, etc.
1188 if source_type == SourceType::InTree {
1189 // When extending this list, add the new lints to the RUSTFLAGS of the
1190 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1191 // some code doesn't go through this `rustc` wrapper.
1192 lint_flags.push("-Wrust_2018_idioms");
1193 lint_flags.push("-Wunused_lifetimes");
1194
1195 if self.config.deny_warnings {
1196 lint_flags.push("-Dwarnings");
1197 rustdocflags.arg("-Dwarnings");
1198 }
1199
1200 rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");
1201 }
1202
1203 // Lints just for `compiler/` crates.
1204 if mode == Mode::Rustc {
1205 lint_flags.push("-Wrustc::internal");
1206 lint_flags.push("-Drustc::symbol_intern_string_literal");
1207 // FIXME(edition_2024): Change this to `-Wrust_2024_idioms` when all
1208 // of the individual lints are satisfied.
1209 lint_flags.push("-Wkeyword_idents_2024");
1210 lint_flags.push("-Wunreachable_pub");
1211 lint_flags.push("-Wunsafe_op_in_unsafe_fn");
1212 lint_flags.push("-Wunused_crate_dependencies");
1213 }
1214
1215 // This does not use RUSTFLAGS for two reasons.
1216 // - Due to caching issues with Cargo. Clippy is treated as an "in
1217 // tree" tool, but shares the same cache as other "submodule" tools.
1218 // With these options set in RUSTFLAGS, that causes *every* shared
1219 // dependency to be rebuilt. By injecting this into the rustc
1220 // wrapper, this circumvents Cargo's fingerprint detection. This is
1221 // fine because lint flags are always ignored in dependencies.
1222 // Eventually this should be fixed via better support from Cargo.
1223 // - RUSTFLAGS is ignored for proc macro crates that are being built on
1224 // the host (because `--target` is given). But we want the lint flags
1225 // to be applied to proc macro crates.
1226 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1227
1228 if self.config.rust_frame_pointers {
1229 rustflags.arg("-Cforce-frame-pointers=true");
1230 }
1231
1232 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1233 // when compiling the standard library, since this might be linked into the final outputs
1234 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1235 // for the standard library in case the compiler is run on a non-Windows platform.
1236 // This is not needed for stage 0 artifacts because these will only be used for building
1237 // the stage 1 compiler.
1238 if cfg!(windows)
1239 && mode == Mode::Std
1240 && self.config.control_flow_guard
1241 && compiler.stage >= 1
1242 {
1243 rustflags.arg("-Ccontrol-flow-guard");
1244 }
1245
1246 // If EHCont Guard is enabled, pass the `-Zehcont-guard` flag to rustc when compiling the
1247 // standard library, since this might be linked into the final outputs produced by rustc.
1248 // Since this mitigation is only available on Windows, only enable it for the standard
1249 // library in case the compiler is run on a non-Windows platform.
1250 // This is not needed for stage 0 artifacts because these will only be used for building
1251 // the stage 1 compiler.
1252 if cfg!(windows) && mode == Mode::Std && self.config.ehcont_guard && compiler.stage >= 1 {
1253 rustflags.arg("-Zehcont-guard");
1254 }
1255
1256 // Optionally override the rc.exe when compiling rustc on Windows.
1257 if let Some(windows_rc) = &self.config.windows_rc {
1258 cargo.env("RUSTC_WINDOWS_RC", windows_rc);
1259 }
1260
1261 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1262 // This replaces spaces with tabs because RUSTDOCFLAGS does not
1263 // support arguments with regular spaces. Hopefully someday Cargo will
1264 // have space support.
1265 let rust_version = self.rust_version().replace(' ', "\t");
1266 rustdocflags.arg("--crate-version").arg(&rust_version);
1267
1268 // Environment variables *required* throughout the build
1269 //
1270 // FIXME: should update code to not require this env var
1271
1272 // The host this new compiler will *run* on.
1273 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1274 // The host this new compiler is being *built* on.
1275 cargo.env("CFG_COMPILER_BUILD_TRIPLE", compiler.host.triple);
1276
1277 // Set this for all builds to make sure doc builds also get it.
1278 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1279
1280 // This one's a bit tricky. As of the time of this writing the compiler
1281 // links to the `winapi` crate on crates.io. This crate provides raw
1282 // bindings to Windows system functions, sort of like libc does for
1283 // Unix. This crate also, however, provides "import libraries" for the
1284 // MinGW targets. There's an import library per dll in the windows
1285 // distribution which is what's linked to. These custom import libraries
1286 // are used because the winapi crate can reference Windows functions not
1287 // present in the MinGW import libraries.
1288 //
1289 // For example MinGW may ship libdbghelp.a, but it may not have
1290 // references to all the functions in the dbghelp dll. Instead the
1291 // custom import library for dbghelp in the winapi crates has all this
1292 // information.
1293 //
1294 // Unfortunately for us though the import libraries are linked by
1295 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1296 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1297 // conflict with the system MinGW ones). This consequently means that
1298 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1299 // DLL) when linked against *again*, for example with procedural macros
1300 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1301 // `-lwinapi_foo` to the linker again. This isn't actually available in
1302 // our distribution, however, so the link fails.
1303 //
1304 // To solve this problem we tell winapi to not use its bundled import
1305 // libraries. This means that it will link to the system MinGW import
1306 // libraries by default, and the `-ldylib=foo` directives will still get
1307 // passed to the final linker, but they'll look like `-lfoo` which can
1308 // be resolved because MinGW has the import library. The downside is we
1309 // don't get newer functions from Windows, but we don't use any of them
1310 // anyway.
1311 if !mode.is_tool() {
1312 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1313 }
1314
1315 // verbose cargo output is very noisy, so only enable it with -vv
1316 for _ in 0..self.verbosity.saturating_sub(1) {
1317 cargo.arg("--verbose");
1318 }
1319
1320 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1321 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1322 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1323 }
1324 _ => {
1325 // Don't set anything
1326 }
1327 }
1328
1329 if self.config.locked_deps {
1330 cargo.arg("--locked");
1331 }
1332 if self.config.vendor || self.is_sudo {
1333 cargo.arg("--frozen");
1334 }
1335
1336 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1337 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1338
1339 if CiEnv::is_ci() {
1340 // Tell cargo to use colored output for nicer logs in CI, even
1341 // though CI isn't printing to a terminal.
1342 // Also set an explicit `TERM=xterm` so that cargo doesn't warn
1343 // about TERM not being set.
1344 cargo.env("TERM", "xterm").args(["--color=always"]);
1345 };
1346
1347 // When we build Rust dylibs they're all intended for intermediate
1348 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1349 // linking all deps statically into the dylib.
1350 if matches!(mode, Mode::Std) {
1351 rustflags.arg("-Cprefer-dynamic");
1352 }
1353 if matches!(mode, Mode::Rustc) && !self.link_std_into_rustc_driver(target) {
1354 rustflags.arg("-Cprefer-dynamic");
1355 }
1356
1357 cargo.env(
1358 "RUSTC_LINK_STD_INTO_RUSTC_DRIVER",
1359 if self.link_std_into_rustc_driver(target) { "1" } else { "0" },
1360 );
1361
1362 // When building incrementally we default to a lower ThinLTO import limit
1363 // (unless explicitly specified otherwise). This will produce a somewhat
1364 // slower code but give way better compile times.
1365 {
1366 let limit = match self.config.rust_thin_lto_import_instr_limit {
1367 Some(limit) => Some(limit),
1368 None if self.config.incremental => Some(10),
1369 _ => None,
1370 };
1371
1372 if let Some(limit) = limit
1373 && (build_compiler_stage == 0
1374 || self.config.default_codegen_backend(target).is_llvm())
1375 {
1376 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={limit}"));
1377 }
1378 }
1379
1380 if matches!(mode, Mode::Std) {
1381 if let Some(mir_opt_level) = self.config.rust_validate_mir_opts {
1382 rustflags.arg("-Zvalidate-mir");
1383 rustflags.arg(&format!("-Zmir-opt-level={mir_opt_level}"));
1384 }
1385 if self.config.rust_randomize_layout {
1386 rustflags.arg("--cfg=randomized_layouts");
1387 }
1388 // Always enable inlining MIR when building the standard library.
1389 // Without this flag, MIR inlining is disabled when incremental compilation is enabled.
1390 // That causes some mir-opt tests which inline functions from the standard library to
1391 // break when incremental compilation is enabled. So this overrides the "no inlining
1392 // during incremental builds" heuristic for the standard library.
1393 rustflags.arg("-Zinline-mir");
1394
1395 // Similarly, we need to keep debug info for functions inlined into other std functions,
1396 // even if we're not going to output debuginfo for the crate we're currently building,
1397 // so that it'll be available when downstream consumers of std try to use it.
1398 rustflags.arg("-Zinline-mir-preserve-debug");
1399
1400 rustflags.arg("-Zmir_strip_debuginfo=locals-in-tiny-functions");
1401 }
1402
1403 // take target-specific extra rustflags if any otherwise take `rust.rustflags`
1404 let extra_rustflags = self
1405 .config
1406 .target_config
1407 .get(&target)
1408 .map(|t| &t.rustflags)
1409 .unwrap_or(&self.config.rust_rustflags)
1410 .clone();
1411
1412 let release_build = self.config.rust_optimize.is_release() &&
1413 // cargo bench/install do not accept `--release` and miri doesn't want it
1414 !matches!(cmd_kind, Kind::Bench | Kind::Install | Kind::Miri | Kind::MiriSetup | Kind::MiriTest);
1415
1416 Cargo {
1417 command: cargo,
1418 args: vec![],
1419 compiler,
1420 mode,
1421 target,
1422 rustflags,
1423 rustdocflags,
1424 hostflags,
1425 allow_features,
1426 release_build,
1427 build_compiler_stage,
1428 extra_rustflags,
1429 }
1430 }
1431}
1432
1433pub fn cargo_profile_var(name: &str, config: &Config) -> String {
1434 let profile = if config.rust_optimize.is_release() { "RELEASE" } else { "DEV" };
1435 format!("CARGO_PROFILE_{profile}_{name}")
1436}