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