Skip to main content

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