src/bootstrap/src/core/builder/cargo.rs RUST 1,470 lines View on github.com → Search inside
1use std::env;2use std::ffi::{OsStr, OsString};3use std::path::{Path, PathBuf};45use 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};1617/// Represents flag values in `String` form with whitespace delimiter to pass it to the compiler18/// later.19///20/// `-Z crate-attr` flags will be applied recursively on the target code using the21/// `rustc_parse::parser::Parser`. See `rustc_builtin_macros::cmdline_attrs::inject` for more22/// information.23#[derive(Debug, Clone)]24struct Rustflags(String, TargetSelection);2526impl Rustflags {27    fn new(target: TargetSelection) -> Rustflags {28        Rustflags(String::new(), target)29    }3031    /// By default, cargo will pick up on various variables in the environment. However, bootstrap32    /// reuses those variables to pass additional flags to rustdoc, so by default they get33    /// overridden. Explicitly add back any previous value in the environment.34    ///35    /// `prefix` is usually `RUSTFLAGS` or `RUSTDOCFLAGS`.36    fn propagate_cargo_env(&mut self, prefix: &str) {37        // Inherit `RUSTFLAGS` by default ...38        self.env(prefix);3940        // ... and also handle target-specific env RUSTFLAGS if they're configured.41        let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);42        self.env(&target_specific);43    }4445    fn env(&mut self, env: &str) {46        if let Ok(s) = env::var(env) {47            for part in s.split(' ') {48                self.arg(part);49            }50        }51    }5253    fn arg(&mut self, arg: &str) -> &mut Self {54        assert_eq!(arg.split(' ').count(), 1);55        if !self.0.is_empty() {56            self.0.push(' ');57        }58        self.0.push_str(arg);59        self60    }6162    fn propagate_rustflag_envs(&mut self, build_compiler_stage: u32) {63        self.propagate_cargo_env("RUSTFLAGS");64        if build_compiler_stage != 0 {65            self.env("RUSTFLAGS_NOT_BOOTSTRAP");66        } else {67            self.env("RUSTFLAGS_BOOTSTRAP");68            self.arg("--cfg=bootstrap");69        }70    }71}7273/// Flags that are passed to the `rustc` shim binary. These flags will only be applied when74/// compiling host code, i.e. when `--target` is unset.75#[derive(Debug, Default)]76struct HostFlags {77    rustc: Vec<String>,78}7980impl HostFlags {81    const SEPARATOR: &'static str = " ";8283    /// Adds a host rustc flag.84    fn arg<S: Into<String>>(&mut self, flag: S) {85        let value = flag.into().trim().to_string();86        assert!(!value.contains(Self::SEPARATOR));87        self.rustc.push(value);88    }8990    /// Encodes all the flags into a single string.91    fn encode(self) -> String {92        self.rustc.join(Self::SEPARATOR)93    }94}9596#[derive(Debug)]97pub struct Cargo {98    command: BootstrapCommand,99    args: Vec<OsString>,100    compiler: Compiler,101    mode: Mode,102    target: TargetSelection,103    rustflags: Rustflags,104    rustdocflags: Rustflags,105    hostflags: HostFlags,106    allow_features: String,107    build_compiler_stage: u32,108    extra_rustflags: Vec<String>,109    profile: Option<&'static str>,110}111112impl Cargo {113    /// Calls [`Builder::cargo`] and [`Cargo::configure_linker`] to prepare an invocation of `cargo`114    /// to be run.115    #[track_caller]116    pub fn new(117        builder: &Builder<'_>,118        compiler: Compiler,119        mode: Mode,120        source_type: SourceType,121        target: TargetSelection,122        cmd_kind: Kind,123    ) -> Cargo {124        let mut cargo = builder.cargo(compiler, mode, source_type, target, cmd_kind);125        if target.synthetic {126            cargo.arg("-Zjson-target-spec");127        }128129        match cmd_kind {130            // No need to configure the target linker for these command types.131            Kind::Clean | Kind::Check | Kind::Format | Kind::Setup => {}132            _ => {133                cargo.configure_linker(builder);134            }135        }136137        cargo138    }139140    pub fn release_build(&mut self, release_build: bool) {141        self.profile = if release_build { Some("release") } else { None };142    }143144    pub fn profile(&mut self, profile: &'static str) {145        self.profile = Some(profile);146    }147148    pub fn compiler(&self) -> Compiler {149        self.compiler150    }151152    pub fn mode(&self) -> Mode {153        self.mode154    }155156    pub fn into_cmd(self) -> BootstrapCommand {157        self.into()158    }159160    /// Same as [`Cargo::new`] except this one doesn't configure the linker with161    /// [`Cargo::configure_linker`].162    #[track_caller]163    pub fn new_for_mir_opt_tests(164        builder: &Builder<'_>,165        compiler: Compiler,166        mode: Mode,167        source_type: SourceType,168        target: TargetSelection,169        cmd_kind: Kind,170    ) -> Cargo {171        let mut cargo = builder.cargo(compiler, mode, source_type, target, cmd_kind);172        if target.synthetic {173            cargo.arg("-Zjson-target-spec");174        }175        cargo176    }177178    pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {179        self.rustdocflags.arg(arg);180        self181    }182183    pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {184        self.rustflags.arg(arg);185        self186    }187188    pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {189        self.args.push(arg.as_ref().into());190        self191    }192193    pub fn args<I, S>(&mut self, args: I) -> &mut Cargo194    where195        I: IntoIterator<Item = S>,196        S: AsRef<OsStr>,197    {198        for arg in args {199            self.arg(arg.as_ref());200        }201        self202    }203204    /// Add an env var to the cargo command instance. Note that `RUSTFLAGS`/`RUSTDOCFLAGS` must go205    /// through [`Cargo::rustdocflags`] and [`Cargo::rustflags`] because inconsistent `RUSTFLAGS`206    /// and `RUSTDOCFLAGS` usages will trigger spurious rebuilds.207    pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {208        assert_ne!(key.as_ref(), "RUSTFLAGS");209        assert_ne!(key.as_ref(), "RUSTDOCFLAGS");210        self.command.env(key.as_ref(), value.as_ref());211        self212    }213214    /// Append a value to an env var of the cargo command instance.215    /// If the variable was unset previously, this is equivalent to [`Cargo::env`].216    /// If the variable was already set, this will append `delimiter` and then `value` to it.217    ///218    /// Note that this only considers the existence of the env. var. configured on this `Cargo`219    /// instance. It does not look at the environment of this process.220    pub fn append_to_env(221        &mut self,222        key: impl AsRef<OsStr>,223        value: impl AsRef<OsStr>,224        delimiter: impl AsRef<OsStr>,225    ) -> &mut Cargo {226        assert_ne!(key.as_ref(), "RUSTFLAGS");227        assert_ne!(key.as_ref(), "RUSTDOCFLAGS");228229        let key = key.as_ref();230        if let Some((_, Some(previous_value))) = self.command.get_envs().find(|(k, _)| *k == key) {231            let mut combined: OsString = previous_value.to_os_string();232            combined.push(delimiter.as_ref());233            combined.push(value.as_ref());234            self.env(key, combined)235        } else {236            self.env(key, value)237        }238    }239240    pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>) {241        builder.add_rustc_lib_path(self.compiler, &mut self.command);242    }243244    pub fn current_dir(&mut self, dir: &Path) -> &mut Cargo {245        self.command.current_dir(dir);246        self247    }248249    /// Adds nightly-only features that this invocation is allowed to use.250    ///251    /// By default, all nightly features are allowed. Once this is called, it will be restricted to252    /// the given set.253    pub fn allow_features(&mut self, features: &str) -> &mut Cargo {254        if !self.allow_features.is_empty() {255            self.allow_features.push(',');256        }257        self.allow_features.push_str(features);258        self259    }260261    // FIXME(onur-ozkan): Add coverage to make sure modifications to this function262    // doesn't cause cache invalidations (e.g., #130108).263    fn configure_linker(&mut self, builder: &Builder<'_>) -> &mut Cargo {264        let target = self.target;265        let compiler = self.compiler;266267        // Dealing with rpath here is a little special, so let's go into some268        // detail. First off, `-rpath` is a linker option on Unix platforms269        // which adds to the runtime dynamic loader path when looking for270        // dynamic libraries. We use this by default on Unix platforms to ensure271        // that our nightlies behave the same on Windows, that is they work out272        // of the box. This can be disabled by setting `rpath = false` in `[rust]`273        // table of `bootstrap.toml`274        //275        // Ok, so the astute might be wondering "why isn't `-C rpath` used276        // here?" and that is indeed a good question to ask. This codegen277        // option is the compiler's current interface to generating an rpath.278        // Unfortunately it doesn't quite suffice for us. The flag currently279        // takes no value as an argument, so the compiler calculates what it280        // should pass to the linker as `-rpath`. This unfortunately is based on281        // the **compile time** directory structure which when building with282        // Cargo will be very different than the runtime directory structure.283        //284        // All that's a really long winded way of saying that if we use285        // `-Crpath` then the executables generated have the wrong rpath of286        // something like `$ORIGIN/deps` when in fact the way we distribute287        // rustc requires the rpath to be `$ORIGIN/../lib`.288        //289        // So, all in all, to set up the correct rpath we pass the linker290        // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it291        // fun to pass a flag to a tool to pass a flag to pass a flag to a tool292        // to change a flag in a binary?293        if builder.config.rpath_enabled(target) && helpers::use_host_linker(target) {294            let libdir = builder.sysroot_libdir_relative(compiler).to_str().unwrap();295            let rpath = if target.contains("apple") {296                // Note that we need to take one extra step on macOS to also pass297                // `-Wl,-instal_name,@rpath/...` to get things to work right. To298                // do that we pass a weird flag to the compiler to get it to do299                // so. Note that this is definitely a hack, and we should likely300                // flesh out rpath support more fully in the future.301                self.rustflags.arg("-Zosx-rpath-install-name");302                Some(format!("-Wl,-rpath,@loader_path/../{libdir}"))303            } else if !target.is_windows()304                && !target.contains("cygwin")305                && !target.contains("aix")306                && !target.contains("xous")307            {308                self.rustflags.arg("-Clink-args=-Wl,-z,origin");309                Some(format!("-Wl,-rpath,$ORIGIN/../{libdir}"))310            } else {311                None312            };313            if let Some(rpath) = rpath {314                self.rustflags.arg(&format!("-Clink-args={rpath}"));315            }316        }317318        // We need to set host linker flags for compiling build scripts and proc-macros.319        // This is done the same way as the target linker flags below, so cargo won't see320        // any fingerprint difference between host==target versus cross-compiled targets321        // when it comes to those host build artifacts.322        if let Some(host_linker) = builder.linker(compiler.host) {323            let host = crate::envify(&compiler.host.triple);324            self.command.env(format!("CARGO_TARGET_{host}_LINKER"), host_linker);325        }326        for arg in linker_flags(builder, compiler.host, LldThreads::Yes) {327            self.hostflags.arg(&arg);328        }329330        if let Some(target_linker) = builder.linker(target) {331            let target = crate::envify(&target.triple);332            self.command.env(format!("CARGO_TARGET_{target}_LINKER"), target_linker);333        }334        // We want to set -Clinker using Cargo, therefore we only call `linker_flags` and not335        // `linker_args` here. Cargo will pass that to both rustc and rustdoc invocations.336        for flag in linker_flags(builder, target, LldThreads::Yes) {337            self.rustflags.arg(&flag);338        }339        for arg in linker_flags(builder, target, LldThreads::Yes) {340            self.rustdocflags.arg(&arg);341        }342343        if !builder.config.dry_run() && builder.cc[&target].args().iter().any(|arg| arg == "-gz") {344            self.rustflags.arg("-Clink-arg=-gz");345        }346347        // Ignore linker warnings for now. These are complicated to fix and don't affect the build.348        // FIXME: we should really investigate these...349        self.rustflags.arg("-Alinker-messages");350351        // Throughout the build Cargo can execute a number of build scripts352        // compiling C/C++ code and we need to pass compilers, archivers, flags, etc353        // obtained previously to those build scripts.354        // Build scripts use either the `cc` crate or `configure/make` so we pass355        // the options through environment variables that are fetched and understood by both.356        //357        // FIXME: the guard against msvc shouldn't need to be here358        if target.is_msvc() {359            if let Some(ref cl) = builder.config.llvm_clang_cl {360                // FIXME: There is a bug in Clang 18 when building for ARM64:361                // https://github.com/llvm/llvm-project/pull/81849. This is362                // fixed in LLVM 19, but can't be backported.363                if !target.starts_with("aarch64") && !target.starts_with("arm64ec") {364                    self.command.env("CC", cl).env("CXX", cl);365                }366            }367        } else {368            let ccache = builder.config.ccache.as_ref();369            let ccacheify = |s: &Path| {370                let ccache = match ccache {371                    Some(ref s) => s,372                    None => return s.display().to_string(),373                };374                // FIXME: the cc-rs crate only recognizes the literal strings375                // `ccache` and `sccache` when doing caching compilations, so we376                // mirror that here. It should probably be fixed upstream to377                // accept a new env var or otherwise work with custom ccache378                // vars.379                match &ccache[..] {380                    "ccache" | "sccache" => format!("{} {}", ccache, s.display()),381                    _ => s.display().to_string(),382                }383            };384            let triple_underscored = target.triple.replace('-', "_");385            let cc = ccacheify(&builder.cc(target));386            self.command.env(format!("CC_{triple_underscored}"), &cc);387388            // Extend `CXXFLAGS_$TARGET` with our extra flags.389            let env = format!("CFLAGS_{triple_underscored}");390            let mut cflags =391                builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::C).join(" ");392            if let Ok(var) = std::env::var(&env) {393                cflags.push(' ');394                cflags.push_str(&var);395            }396            self.command.env(env, &cflags);397398            if let Some(ar) = builder.ar(target) {399                let ranlib = format!("{} s", ar.display());400                self.command401                    .env(format!("AR_{triple_underscored}"), ar)402                    .env(format!("RANLIB_{triple_underscored}"), ranlib);403            }404405            if let Ok(cxx) = builder.cxx(target) {406                let cxx = ccacheify(&cxx);407                self.command.env(format!("CXX_{triple_underscored}"), &cxx);408409                // Extend `CXXFLAGS_$TARGET` with our extra flags.410                let env = format!("CXXFLAGS_{triple_underscored}");411                let mut cxxflags =412                    builder.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx).join(" ");413                if let Ok(var) = std::env::var(&env) {414                    cxxflags.push(' ');415                    cxxflags.push_str(&var);416                }417                self.command.env(&env, cxxflags);418            }419        }420421        self422    }423}424425impl From<Cargo> for BootstrapCommand {426    fn from(mut cargo: Cargo) -> BootstrapCommand {427        if let Some(profile) = cargo.profile {428            cargo.args.insert(0, format!("--profile={profile}").into());429        }430431        for arg in &cargo.extra_rustflags {432            cargo.rustflags.arg(arg);433            cargo.rustdocflags.arg(arg);434        }435436        // Propagate the envs here at the very end to make sure they override any previously set flags.437        cargo.rustflags.propagate_rustflag_envs(cargo.build_compiler_stage);438        cargo.rustdocflags.propagate_rustflag_envs(cargo.build_compiler_stage);439440        cargo.rustdocflags.propagate_cargo_env("RUSTDOCFLAGS");441442        if cargo.build_compiler_stage == 0 {443            cargo.rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP");444            if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {445                cargo.args(s.split_whitespace());446            }447        } else {448            cargo.rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP");449            if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {450                cargo.args(s.split_whitespace());451            }452        }453454        if let Ok(s) = env::var("CARGOFLAGS") {455            cargo.args(s.split_whitespace());456        }457458        cargo.command.args(cargo.args);459460        let rustflags = &cargo.rustflags.0;461        if !rustflags.is_empty() {462            cargo.command.env("RUSTFLAGS", rustflags);463        }464465        let rustdocflags = &cargo.rustdocflags.0;466        if !rustdocflags.is_empty() {467            cargo.command.env("RUSTDOCFLAGS", rustdocflags);468        }469470        let encoded_hostflags = cargo.hostflags.encode();471        if !encoded_hostflags.is_empty() {472            cargo.command.env("RUSTC_HOST_FLAGS", encoded_hostflags);473        }474475        if !cargo.allow_features.is_empty() {476            cargo.command.env("RUSTC_ALLOW_FEATURES", cargo.allow_features);477        }478479        cargo.command480    }481}482483impl Builder<'_> {484    /// Like [`Builder::cargo`], but only passes flags that are valid for all commands.485    #[track_caller]486    pub fn bare_cargo(487        &self,488        compiler: Compiler,489        mode: Mode,490        target: TargetSelection,491        cmd_kind: Kind,492    ) -> BootstrapCommand {493        let mut cargo = match cmd_kind {494            Kind::Clippy => {495                let mut cargo = self.cargo_clippy_cmd(compiler);496                cargo.arg(cmd_kind.as_str());497                cargo498            }499            Kind::MiriSetup => {500                let mut cargo = self.cargo_miri_cmd(compiler);501                cargo.arg("miri").arg("setup");502                cargo503            }504            Kind::MiriTest => {505                let mut cargo = self.cargo_miri_cmd(compiler);506                cargo.arg("miri").arg("test");507                cargo508            }509            _ => {510                let mut cargo = command(&self.initial_cargo);511                cargo.arg(cmd_kind.as_str());512                cargo513            }514        };515516        // Optionally suppress cargo output.517        if self.config.quiet {518            cargo.arg("--quiet");519        }520521        // Run cargo from the source root so it can find .cargo/config.522        // This matters when using vendoring and the working directory is outside the repository.523        cargo.current_dir(&self.src);524525        let out_dir = self.stage_out(compiler, mode);526        cargo.env("CARGO_TARGET_DIR", &out_dir);527528        // Bootstrap makes a lot of assumptions about the artifacts produced in the target529        // directory. If users override the "build directory" using `build-dir`530        // (https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-dir), then531        // bootstrap couldn't find these artifacts. So we forcefully override that option to our532        // target directory here.533        // In the future, we could attempt to read the build-dir location from Cargo and actually534        // respect it.535        cargo.env("CARGO_BUILD_BUILD_DIR", &out_dir);536537        // Found with `rg "init_env_logger\("`. If anyone uses `init_env_logger`538        // from out of tree it shouldn't matter, since x.py is only used for539        // building in-tree.540        let color_logs = ["RUSTDOC_LOG_COLOR", "RUSTC_LOG_COLOR", "RUST_LOG_COLOR"];541        match self.build.config.color {542            Color::Always => {543                cargo.arg("--color=always");544                for log in &color_logs {545                    cargo.env(log, "always");546                }547            }548            Color::Never => {549                cargo.arg("--color=never");550                for log in &color_logs {551                    cargo.env(log, "never");552                }553            }554            Color::Auto => {} // nothing to do555        }556557        if cmd_kind != Kind::Install {558            cargo.arg("--target").arg(target.rustc_target_arg());559        } else {560            assert_eq!(target, compiler.host);561        }562563        // Bootstrap only supports modern FIFO jobservers. Older pipe-based jobservers can run into564        // "invalid file descriptor" errors, as the jobserver file descriptors are not inherited by565        // scripts like bootstrap.py, while the environment variable is propagated. So, we pass566        // MAKEFLAGS only if we detect a FIFO jobserver, otherwise we clear it.567        let has_modern_jobserver = env::var("MAKEFLAGS")568            .map(|flags| flags.contains("--jobserver-auth=fifo:"))569            .unwrap_or(false);570571        if !has_modern_jobserver {572            cargo.env_remove("MAKEFLAGS");573            cargo.env_remove("MFLAGS");574        }575576        cargo577    }578579    /// This will create a [`BootstrapCommand`] that represents a pending execution of cargo. This580    /// cargo will be configured to use `compiler` as the actual rustc compiler, its output will be581    /// scoped by `mode`'s output directory, it will pass the `--target` flag for the specified582    /// `target`, and will be executing the Cargo command `cmd`. `cmd` can be `miri-cmd` for583    /// commands to be run with Miri.584    #[track_caller]585    fn cargo(586        &self,587        compiler: Compiler,588        mode: Mode,589        source_type: SourceType,590        target: TargetSelection,591        cmd_kind: Kind,592    ) -> Cargo {593        let mut cargo = self.bare_cargo(compiler, mode, target, cmd_kind);594        let out_dir = self.stage_out(compiler, mode);595596        let mut hostflags = HostFlags::default();597598        // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,599        // so we need to explicitly clear out if they've been updated.600        for backend in self.codegen_backends(compiler) {601            build_stamp::clear_if_dirty(self, &out_dir, &backend);602        }603604        if self.config.cmd.timings() {605            cargo.arg("--timings");606        }607608        if cmd_kind == Kind::Doc {609            let my_out = match mode {610                // This is the intended out directory for compiler documentation.611                Mode::Rustc | Mode::ToolRustcPrivate | Mode::ToolBootstrap | Mode::ToolTarget => {612                    self.compiler_doc_out(target)613                }614                Mode::Std => {615                    if self.config.cmd.json() {616                        out_dir.join(target).join("json-doc")617                    } else {618                        out_dir.join(target).join("doc")619                    }620                }621                _ => panic!("doc mode {mode:?} not expected"),622            };623            let rustdoc = self.rustdoc_for_compiler(compiler);624            build_stamp::clear_if_dirty(self, &my_out, &rustdoc);625        }626627        let profile_var = |name: &str| cargo_profile_var(name, &self.config, mode);628629        // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config630        // needs to not accidentally link to libLLVM in stage0/lib.631        cargo.env("REAL_LIBRARY_PATH_VAR", helpers::dylib_path_var());632        if let Some(e) = env::var_os(helpers::dylib_path_var()) {633            cargo.env("REAL_LIBRARY_PATH", e);634        }635636        // Set a flag for `check`/`clippy`/`fix`, so that certain build637        // scripts can do less work (i.e. not building/requiring LLVM).638        if matches!(cmd_kind, Kind::Check | Kind::Clippy | Kind::Fix) {639            // If we've not yet built LLVM, or it's stale, then bust640            // the rustc_llvm cache. That will always work, even though it641            // may mean that on the next non-check build we'll need to rebuild642            // rustc_llvm. But if LLVM is stale, that'll be a tiny amount643            // of work comparatively, and we'd likely need to rebuild it anyway,644            // so that's okay.645            if crate::core::build_steps::llvm::prebuilt_llvm_config(self, target, false)646                .should_build()647            {648                cargo.env("RUST_CHECK", "1");649            }650        }651652        let build_compiler_stage = if compiler.stage == 0 && self.local_rebuild {653            // Assume the local-rebuild rustc already has stage1 features.654            1655        } else {656            compiler.stage657        };658659        // We synthetically interpret a stage0 compiler used to build tools as a660        // "raw" compiler in that it's the exact snapshot we download. For things like661        // ToolRustcPrivate, we would have to use the artificial stage0-sysroot compiler instead.662        let use_snapshot =663            mode == Mode::ToolBootstrap || (mode == Mode::ToolTarget && build_compiler_stage == 0);664        assert!(!use_snapshot || build_compiler_stage == 0 || self.local_rebuild);665666        let sysroot = if use_snapshot {667            self.rustc_snapshot_sysroot().to_path_buf()668        } else {669            self.sysroot(compiler)670        };671        let libdir = self.rustc_libdir(compiler);672673        let sysroot_str = sysroot.as_os_str().to_str().expect("sysroot should be UTF-8");674        if self.is_verbose() && !matches!(self.config.get_dry_run(), DryRun::SelfCheck) {675            println!("using sysroot {sysroot_str}");676        }677678        let mut rustflags = Rustflags::new(target);679680        if cmd_kind == Kind::Clippy {681            // clippy overwrites sysroot if we pass it to cargo.682            // Pass it directly to clippy instead.683            // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,684            // so it has no way of knowing the sysroot.685            rustflags.arg("--sysroot");686            rustflags.arg(sysroot_str);687        }688689        // By default, windows-rs depends on a native library that doesn't get copied into the690        // sysroot. Passing this cfg enables raw-dylib support instead, which makes the native691        // library unnecessary. This can be removed when windows-rs enables raw-dylib692        // unconditionally.693        if let Mode::Rustc | Mode::ToolRustcPrivate | Mode::ToolBootstrap | Mode::ToolTarget = mode694        {695            rustflags.arg("--cfg=windows_raw_dylib");696        }697698        // When unset, follow the default of the compiler flag - the compiler, tools and std use v0699        if let Some(usm) = self.config.rust_new_symbol_mangling {700            rustflags.arg(if usm {701                "-Csymbol-mangling-version=v0"702            } else {703                "-Csymbol-mangling-version=legacy"704            });705        }706707        // Always enable move/copy annotations for profiler visibility (non-stage0 only).708        // Note that -Zannotate-moves is only effective with debugging info enabled.709        if build_compiler_stage >= 1 {710            if let Some(limit) = self.config.rust_annotate_moves_size_limit {711                rustflags.arg(&format!("-Zannotate-moves={limit}"));712            } else {713                rustflags.arg("-Zannotate-moves");714            }715        }716717        // FIXME: the following components don't build with `-Zrandomize-layout` yet:718        // - rust-analyzer, due to the rowan crate719        // so we exclude an entire category of steps here due to lack of fine-grained control over720        // rustflags.721        if self.config.rust_randomize_layout && mode != Mode::ToolRustcPrivate {722            rustflags.arg("-Zrandomize-layout");723        }724725        // Enable compile-time checking of `cfg` names, values and Cargo `features`.726        //727        // Note: `std`, `alloc` and `core` imports some dependencies by #[path] (like728        // backtrace, core_simd, std_float, ...), those dependencies have their own729        // features but cargo isn't involved in the #[path] process and so cannot pass the730        // complete list of features, so for that reason we don't enable checking of731        // features for std crates.732        if mode == Mode::Std {733            rustflags.arg("--check-cfg=cfg(feature,values(any()))");734        }735736        // Add extra cfg not defined in/by rustc737        //738        // Note: Although it would seems that "-Zunstable-options" to `rustflags` is useless as739        // cargo would implicitly add it, it was discover that sometimes bootstrap only use740        // `rustflags` without `cargo` making it required.741        rustflags.arg("-Zunstable-options");742743        // Add parallel frontend threads configuration744        if let Some(threads) = self.config.rust_parallel_frontend_threads {745            rustflags.arg(&format!("-Zthreads={threads}"));746        }747748        for (restricted_mode, name, values) in EXTRA_CHECK_CFGS {749            if restricted_mode.is_none() || *restricted_mode == Some(mode) {750                rustflags.arg(&check_cfg_arg(name, *values));751752                if *name == "bootstrap" {753                    // Cargo doesn't pass RUSTFLAGS to proc_macros:754                    // https://github.com/rust-lang/cargo/issues/4423755                    // Thus, if we are on stage 0, we explicitly set `--cfg=bootstrap`.756                    // We also declare that the flag is expected, which we need to do to not757                    // get warnings about it being unexpected.758                    hostflags.arg(check_cfg_arg(name, *values));759                }760            }761        }762763        // FIXME(rust-lang/cargo#5754) we shouldn't be using special command arguments764        // to the host invocation here, but rather Cargo should know what flags to pass rustc765        // itself.766        if build_compiler_stage == 0 {767            hostflags.arg("--cfg=bootstrap");768        }769770        // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,771        // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See772        // #71458.773        let mut rustdocflags = rustflags.clone();774775        match mode {776            Mode::Std | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {}777            Mode::Rustc | Mode::Codegen | Mode::ToolRustcPrivate => {778                // Build proc macros both for the host and the target unless proc-macros are not779                // supported by the target.780                if target != compiler.host && cmd_kind != Kind::Check {781                    let error = self782                        .rustc_cmd(compiler)783                        .arg("--target")784                        .arg(target.rustc_target_arg())785                        // FIXME(#152709): -Zunstable-options is to handle JSON targets.786                        // Remove when JSON targets are stabilized.787                        .arg("-Zunstable-options")788                        .env("RUSTC_BOOTSTRAP", "1")789                        .arg("--print=file-names")790                        .arg("--crate-type=proc-macro")791                        .arg("-")792                        .stdin(std::process::Stdio::null())793                        .run_capture(self)794                        .stderr();795796                    let not_supported = error797                        .lines()798                        .any(|line| line.contains("unsupported crate type `proc-macro`"));799                    if !not_supported {800                        cargo.arg("-Zdual-proc-macros");801                        rustflags.arg("-Zdual-proc-macros");802                    }803                }804            }805        }806807        // This tells Cargo (and in turn, rustc) to output more complete808        // dependency information.  Most importantly for bootstrap, this809        // includes sysroot artifacts, like libstd, which means that we don't810        // need to track those in bootstrap (an error prone process!). This811        // feature is currently unstable as there may be some bugs and such, but812        // it represents a big improvement in bootstrap's reliability on813        // rebuilds, so we're using it here.814        //815        // For some additional context, see #63470 (the PR originally adding816        // this), as well as #63012 which is the tracking issue for this817        // feature on the rustc side.818        cargo.arg("-Zbinary-dep-depinfo");819        let allow_features = match mode {820            Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {821                // Restrict the allowed features so we don't depend on nightly822                // accidentally.823                //824                // binary-dep-depinfo is used by bootstrap itself for all825                // compilations.826                //827                // Lots of tools depend on proc_macro2 and proc-macro-error.828                // Those have build scripts which assume nightly features are829                // available if the `rustc` version is "nighty" or "dev". See830                // bin/rustc.rs for why that is a problem. Instead of labeling831                // those features for each individual tool that needs them,832                // just blanket allow them here.833                //834                // If this is ever removed, be sure to add something else in835                // its place to keep the restrictions in place (or make a way836                // to unset RUSTC_BOOTSTRAP).837                "binary-dep-depinfo,proc_macro_span,proc_macro_span_shrink,proc_macro_diagnostic"838                    .to_string()839            }840            Mode::Std | Mode::Rustc | Mode::Codegen | Mode::ToolRustcPrivate => String::new(),841        };842843        cargo.arg("-j").arg(self.jobs().to_string());844845        // Make cargo emit diagnostics relative to the rustc src dir.846        cargo.arg(format!("-Zroot-dir={}", self.src.display()));847848        if self.config.compile_time_deps {849            // Build only build scripts and proc-macros for rust-analyzer when requested.850            cargo.arg("-Zunstable-options");851            cargo.arg("--compile-time-deps");852        }853854        // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005855        // Force cargo to output binaries with disambiguating hashes in the name856        let mut metadata = if compiler.stage == 0 {857            // Treat stage0 like a special channel, whether it's a normal prior-858            // release rustc or a local rebuild with the same version, so we859            // never mix these libraries by accident.860            "bootstrap".to_string()861        } else {862            self.config.channel.to_string()863        };864        // We want to make sure that none of the dependencies between865        // std/test/rustc unify with one another. This is done for weird linkage866        // reasons but the gist of the problem is that if librustc, libtest, and867        // libstd all depend on libc from crates.io (which they actually do) we868        // want to make sure they all get distinct versions. Things get really869        // weird if we try to unify all these dependencies right now, namely870        // around how many times the library is linked in dynamic libraries and871        // such. If rustc were a static executable or if we didn't ship dylibs872        // this wouldn't be a problem, but we do, so it is. This is in general873        // just here to make sure things build right. If you can remove this and874        // things still build right, please do!875        match mode {876            Mode::Std => metadata.push_str("std"),877            // When we're building rustc tools, they're built with a search path878            // that contains things built during the rustc build. For example,879            // bitflags is built during the rustc build, and is a dependency of880            // rustdoc as well. We're building rustdoc in a different target881            // directory, though, which means that Cargo will rebuild the882            // dependency. When we go on to build rustdoc, we'll look for883            // bitflags, and find two different copies: one built during the884            // rustc step and one that we just built. This isn't always a885            // problem, somehow -- not really clear why -- but we know that this886            // fixes things.887            Mode::ToolRustcPrivate => metadata.push_str("tool-rustc"),888            // Same for codegen backends.889            Mode::Codegen => metadata.push_str("codegen"),890            _ => {}891        }892        // `rustc_driver`'s version number is always `0.0.0`, which can cause linker search path893        // problems on side-by-side installs because we don't include the version number of the894        // `rustc_driver` being built. This can cause builds of different version numbers to produce895        // `librustc_driver*.so` artifacts that end up with identical filename hashes.896        metadata.push_str(&self.version);897898        cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);899900        if cmd_kind == Kind::Clippy {901            rustflags.arg("-Zforce-unstable-if-unmarked");902        }903904        rustflags.arg("-Zmacro-backtrace");905906        // Clear the output directory if the real rustc we're using has changed;907        // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.908        //909        // Avoid doing this during dry run as that usually means the relevant910        // compiler is not yet linked/copied properly.911        //912        // Only clear out the directory if we're compiling std; otherwise, we913        // should let Cargo take care of things for us (via depdep info)914        if !self.config.dry_run() && mode == Mode::Std && cmd_kind == Kind::Build {915            build_stamp::clear_if_dirty(self, &out_dir, &self.rustc(compiler));916        }917918        let rustdoc_path = match cmd_kind {919            Kind::Doc | Kind::Test | Kind::MiriTest => self.rustdoc_for_compiler(compiler),920            _ => PathBuf::from("/path/to/nowhere/rustdoc/not/required"),921        };922923        // Customize the compiler we're running. Specify the compiler to cargo924        // as our shim and then pass it some various options used to configure925        // how the actual compiler itself is called.926        //927        // These variables are primarily all read by928        // src/bootstrap/bin/{rustc.rs,rustdoc.rs}929        cargo930            .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))931            .env("RUSTC_REAL", self.rustc(compiler))932            .env("RUSTC_STAGE", build_compiler_stage.to_string())933            .env("RUSTC_SYSROOT", sysroot)934            .env("RUSTC_LIBDIR", &libdir)935            .env("RUSTDOC_LIBDIR", libdir)936            .env("RUSTDOC", self.bootstrap_out.join("rustdoc"))937            .env("RUSTDOC_REAL", rustdoc_path)938            .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());939940        if self.config.rust_break_on_ice {941            cargo.env("RUSTC_BREAK_ON_ICE", "1");942        }943944        // Set RUSTC_WRAPPER to the bootstrap shim, which switches between beta and in-tree945        // sysroot depending on whether we're building build scripts.946        // NOTE: we intentionally use RUSTC_WRAPPER so that we can support clippy - RUSTC is not947        // respected by clippy-driver; RUSTC_WRAPPER happens earlier, before clippy runs.948        cargo.env("RUSTC_WRAPPER", self.bootstrap_out.join("rustc"));949        // NOTE: we also need to set RUSTC so cargo can run `rustc -vV`; apparently that ignores RUSTC_WRAPPER >:(950        cargo.env("RUSTC", self.bootstrap_out.join("rustc"));951952        // Someone might have set some previous rustc wrapper (e.g.953        // sccache) before bootstrap overrode it. Respect that variable.954        if let Some(existing_wrapper) = env::var_os("RUSTC_WRAPPER") {955            cargo.env("RUSTC_WRAPPER_REAL", existing_wrapper);956        }957958        // If this is for `miri-test`, prepare the sysroots.959        if cmd_kind == Kind::MiriTest {960            self.std(compiler, compiler.host);961            let host_sysroot = self.sysroot(compiler);962            let miri_sysroot = test::Miri::build_miri_sysroot(self, compiler, target);963            cargo.env("MIRI_SYSROOT", &miri_sysroot);964            cargo.env("MIRI_HOST_SYSROOT", &host_sysroot);965        }966967        cargo.env(profile_var("STRIP"), self.config.rust_strip.to_string());968969        if let Some(stack_protector) = &self.config.rust_stack_protector {970            rustflags.arg(&format!("-Zstack-protector={stack_protector}"));971        }972973        let debuginfo_level = match mode {974            Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,975            Mode::Std => self.config.rust_debuginfo_level_std,976            Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustcPrivate | Mode::ToolTarget => {977                self.config.rust_debuginfo_level_tools978            }979        };980        cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());981        if let Some(opt_level) = &self.config.rust_optimize.get_opt_level() {982            cargo.env(profile_var("OPT_LEVEL"), opt_level);983        }984        cargo.env(985            profile_var("DEBUG_ASSERTIONS"),986            match mode {987                Mode::Std => self.config.std_debug_assertions,988                Mode::Rustc | Mode::Codegen => self.config.rustc_debug_assertions,989                Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustcPrivate | Mode::ToolTarget => {990                    self.config.tools_debug_assertions991                }992            }993            .to_string(),994        );995        cargo.env(996            profile_var("OVERFLOW_CHECKS"),997            if mode == Mode::Std {998                self.config.rust_overflow_checks_std.to_string()999            } else {1000                self.config.rust_overflow_checks.to_string()1001            },1002        );10031004        match self.config.split_debuginfo(target) {1005            SplitDebuginfo::Packed => rustflags.arg("-Csplit-debuginfo=packed"),1006            SplitDebuginfo::Unpacked => rustflags.arg("-Csplit-debuginfo=unpacked"),1007            SplitDebuginfo::Off => rustflags.arg("-Csplit-debuginfo=off"),1008        };10091010        if self.config.cmd.bless() {1011            // Bless `expect!` tests.1012            cargo.env("UPDATE_EXPECT", "1");1013        }10141015        // Set an environment variable that tells the rustc/rustdoc wrapper1016        // binary to pass `-Zforce-unstable-if-unmarked` to the real compiler.1017        match mode {1018            // Any library crate that's part of the sysroot should be marked unstable1019            // (including third-party dependencies), unless it uses a staged_api1020            // `#![stable(..)]` attribute to explicitly mark itself stable.1021            Mode::Std | Mode::Codegen | Mode::Rustc => {1022                cargo.env("RUSTC_FORCE_UNSTABLE", "1");1023            }10241025            // For everything else, crate stability shouldn't matter, so don't set a flag.1026            Mode::ToolBootstrap | Mode::ToolRustcPrivate | Mode::ToolStd | Mode::ToolTarget => {}1027        }10281029        if let Some(x) = self.crt_static(target) {1030            if x {1031                rustflags.arg("-Ctarget-feature=+crt-static");1032            } else {1033                rustflags.arg("-Ctarget-feature=-crt-static");1034            }1035        }10361037        if let Some(x) = self.crt_static(compiler.host) {1038            let sign = if x { "+" } else { "-" };1039            hostflags.arg(format!("-Ctarget-feature={sign}crt-static"));1040        }10411042        // `rustc` needs to know the remapping scheme, in order to know how to reverse it (unremap)1043        // later. Two env vars are set and made available to the compiler1044        //1045        // - `CFG_VIRTUAL_RUST_SOURCE_BASE_DIR`: `rust-src` remap scheme (`NonCompiler`)1046        // - `CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR`: `rustc-dev` remap scheme (`Compiler`)1047        //1048        // Keep this scheme in sync with `rustc_metadata::rmeta::decoder`'s1049        // `try_to_translate_virtual_to_real`.1050        //1051        // `RUSTC_DEBUGINFO_MAP` is used to pass through to the underlying rustc1052        // `--remap-path-prefix`.1053        match mode {1054            Mode::Rustc | Mode::Codegen => {1055                if let Some(ref map_to) =1056                    self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::NonCompiler)1057                {1058                    // Tell the compiler which prefix was used for remapping the standard library1059                    cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);1060                }10611062                if let Some(ref map_to) =1063                    self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::Compiler)1064                {1065                    // Tell the compiler which prefix was used for remapping the compiler it-self1066                    cargo.env("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR", map_to);10671068                    // When building compiler sources, we want to apply the compiler remap scheme.1069                    let map = [1070                        // Cargo use relative paths for workspace members, so let's remap those.1071                        format!("compiler/={map_to}/compiler"),1072                        // rustc creates absolute paths (in part bc of the `rust-src` unremap1073                        // and for working directory) so let's remap the build directory as well.1074                        format!("{}={map_to}", self.build.src.display()),1075                        // remap OUT_DIR so they don't leak into artifacts.1076                        format!("{}={map_to}/out", self.build.out.display()),1077                        // on windows, rustc may use forward slashes internally1078                        #[cfg(windows)]1079                        format!(1080                            "{}={map_to}\\out",1081                            self.build.out.display().to_string().replace('/', "\\")1082                        ),1083                    ]1084                    .join("\t");1085                    cargo.env("RUSTC_DEBUGINFO_MAP", map);1086                }1087            }1088            Mode::Std1089            | Mode::ToolBootstrap1090            | Mode::ToolRustcPrivate1091            | Mode::ToolStd1092            | Mode::ToolTarget => {1093                if let Some(ref map_to) =1094                    self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::NonCompiler)1095                {1096                    // When building the standard library sources, we want to apply the std remap scheme.1097                    let map = [1098                        // Cargo use relative paths for workspace members, so let's remap those.1099                        format!("library/={map_to}/library"),1100                        // rustc creates absolute paths (in part bc of the `rust-src` unremap1101                        // and for working directory) so let's remap the build directory as well.1102                        format!("{}={map_to}", self.build.src.display()),1103                        // remap OUT_DIR so they don't leak into artifacts.1104                        format!("{}={map_to}/out", self.build.out.display()),1105                        // on windows, rustc may use forward slashes internally1106                        #[cfg(windows)]1107                        format!(1108                            "{}={map_to}\\out",1109                            self.build.out.display().to_string().replace('/', "\\")1110                        ),1111                    ]1112                    .join("\t");1113                    cargo.env("RUSTC_DEBUGINFO_MAP", map);1114                }1115            }1116        }11171118        if self.config.rust_remap_debuginfo {1119            let mut env_var = OsString::new();1120            if let Some(vendor) = self.build.vendored_crates_path() {1121                env_var.push(vendor);1122                env_var.push("=/rust/deps");1123            } else {1124                let registry_src = t!(home::cargo_home()).join("registry").join("src");1125                for entry in t!(std::fs::read_dir(registry_src)) {1126                    if !env_var.is_empty() {1127                        env_var.push("\t");1128                    }1129                    env_var.push(t!(entry).path());1130                    env_var.push("=/rust/deps");1131                }1132            }1133            cargo.env("RUSTC_CARGO_REGISTRY_SRC_TO_REMAP", env_var);1134        }11351136        // Enable usage of unstable features1137        cargo.env("RUSTC_BOOTSTRAP", "1");11381139        if matches!(mode, Mode::Std) {1140            cargo.arg("-Zno-embed-metadata");1141        }11421143        if self.config.dump_bootstrap_shims {1144            prepare_behaviour_dump_dir(self.build);11451146            cargo1147                .env("DUMP_BOOTSTRAP_SHIMS", self.build.out.join("bootstrap-shims-dump"))1148                .env("BUILD_OUT", &self.build.out)1149                .env("CARGO_HOME", t!(home::cargo_home()));1150        };11511152        self.add_rust_test_threads(&mut cargo);11531154        // Almost all of the crates that we compile as part of the bootstrap may1155        // have a build script, including the standard library. To compile a1156        // build script, however, it itself needs a standard library! This1157        // introduces a bit of a pickle when we're compiling the standard1158        // library itself.1159        //1160        // To work around this we actually end up using the snapshot compiler1161        // (stage0) for compiling build scripts of the standard library itself.1162        // The stage0 compiler is guaranteed to have a libstd available for use.1163        //1164        // For other crates, however, we know that we've already got a standard1165        // library up and running, so we can use the normal compiler to compile1166        // build scripts in that situation.1167        if mode == Mode::Std {1168            cargo1169                .env("RUSTC_SNAPSHOT", &self.initial_rustc)1170                .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());1171        } else {1172            cargo1173                .env("RUSTC_SNAPSHOT", self.rustc(compiler))1174                .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));1175        }11761177        // Tools that use compiler libraries may inherit the `-lLLVM` link1178        // requirement, but the `-L` library path is not propagated across1179        // separate Cargo projects. We can add LLVM's library path to the1180        // rustc args as a workaround.1181        if (mode == Mode::ToolRustcPrivate || mode == Mode::Codegen)1182            && let Some(llvm_config) = self.llvm_config(target)1183        {1184            let llvm_libdir =1185                command(llvm_config).cached().arg("--libdir").run_capture_stdout(self).stdout();1186            if target.is_msvc() {1187                rustflags.arg(&format!("-Clink-arg=-LIBPATH:{llvm_libdir}"));1188            } else {1189                rustflags.arg(&format!("-Clink-arg=-L{llvm_libdir}"));1190            }1191        }11921193        // Compile everything except libraries and proc macros with the more1194        // efficient initial-exec TLS model. This doesn't work with `dlopen`,1195        // so we can't use it by default in general, but we can use it for tools1196        // and our own internal libraries.1197        //1198        // Cygwin only supports emutls.1199        if !mode.must_support_dlopen()1200            && !target.triple.starts_with("powerpc-")1201            && !target.triple.contains("cygwin")1202        {1203            cargo.env("RUSTC_TLS_MODEL_INITIAL_EXEC", "1");1204        }12051206        // Ignore incremental modes except for stage0, since we're1207        // not guaranteeing correctness across builds if the compiler1208        // is changing under your feet.1209        if self.config.incremental && compiler.stage == 0 {1210            cargo.env("CARGO_INCREMENTAL", "1");1211        } else {1212            // Don't rely on any default setting for incr. comp. in Cargo1213            cargo.env("CARGO_INCREMENTAL", "0");1214        }12151216        if let Some(ref on_fail) = self.config.on_fail {1217            cargo.env("RUSTC_ON_FAIL", on_fail);1218        }12191220        if self.config.print_step_timings {1221            cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");1222        }12231224        if self.config.print_step_rusage {1225            cargo.env("RUSTC_PRINT_STEP_RUSAGE", "1");1226        }12271228        if self.config.backtrace_on_ice {1229            cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");1230        }12311232        if self.verbosity >= 2 {1233            // This provides very useful logs especially when debugging build cache-related stuff.1234            cargo.env("CARGO_LOG", "cargo::core::compiler::fingerprint=info");1235        }12361237        cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());12381239        // Downstream forks of the Rust compiler might want to use a custom libc to add support for1240        // targets that are not yet available upstream. Adding a patch to replace libc with a1241        // custom one would cause compilation errors though, because Cargo would interpret the1242        // custom libc as part of the workspace, and apply the check-cfg lints on it.1243        //1244        // The libc build script emits check-cfg flags only when this environment variable is set,1245        // so this line allows the use of custom libcs.1246        cargo.env("LIBC_CHECK_CFG", "1");12471248        let mut lint_flags = Vec::new();12491250        // Lints for all in-tree code: compiler, rustdoc, cranelift, gcc,1251        // clippy, rustfmt, rust-analyzer, etc.1252        if source_type == SourceType::InTree {1253            // When extending this list, add the new lints to the RUSTFLAGS of the1254            // build_bootstrap function of src/bootstrap/bootstrap.py as well as1255            // some code doesn't go through this `rustc` wrapper.1256            lint_flags.push("-Wrust_2018_idioms");1257            lint_flags.push("-Wunused_lifetimes");12581259            if self.config.deny_warnings {1260                // We use this instead of `lint_flags` so that we don't have to rebuild all1261                // workspace dependencies when `deny-warnings` changes, but we still get an error1262                // immediately instead of having to wait until the next rebuild.1263                cargo.env("CARGO_BUILD_WARNINGS", "deny");1264            }12651266            rustdocflags.arg("-Wrustdoc::invalid_codeblock_attributes");1267        }12681269        // Lints just for `compiler/` crates.1270        if mode == Mode::Rustc {1271            lint_flags.push("-Wrustc::internal");1272            lint_flags.push("-Drustc::symbol_intern_string_literal");1273            // FIXME(edition_2024): Change this to `-Wrust_2024_idioms` when all1274            // of the individual lints are satisfied.1275            lint_flags.push("-Wkeyword_idents_2024");1276            lint_flags.push("-Wunreachable_pub");1277            lint_flags.push("-Wunsafe_op_in_unsafe_fn");1278            lint_flags.push("-Wunused_crate_dependencies");1279        }12801281        // This does not use RUSTFLAGS for two reasons.1282        // - Due to caching issues with Cargo. Clippy is treated as an "in1283        //   tree" tool, but shares the same cache as other "submodule" tools.1284        //   With these options set in RUSTFLAGS, that causes *every* shared1285        //   dependency to be rebuilt. By injecting this into the rustc1286        //   wrapper, this circumvents Cargo's fingerprint detection. This is1287        //   fine because lint flags are always ignored in dependencies.1288        //   Eventually this should be fixed via better support from Cargo.1289        // - RUSTFLAGS is ignored for proc macro crates that are being built on1290        //   the host (because `--target` is given). But we want the lint flags1291        //   to be applied to proc macro crates.1292        cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));12931294        if self.config.rust_frame_pointers {1295            rustflags.arg("-Cforce-frame-pointers=true");1296        }12971298        // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc1299        // when compiling the standard library, since this might be linked into the final outputs1300        // produced by rustc. Since this mitigation is only available on Windows, only enable it1301        // for the standard library in case the compiler is run on a non-Windows platform.1302        if cfg!(windows) && mode == Mode::Std && self.config.control_flow_guard {1303            rustflags.arg("-Ccontrol-flow-guard");1304        }13051306        // If EHCont Guard is enabled, pass the `-Zehcont-guard` flag to rustc when compiling the1307        // standard library, since this might be linked into the final outputs produced by rustc.1308        // Since this mitigation is only available on Windows, only enable it for the standard1309        // library in case the compiler is run on a non-Windows platform.1310        if cfg!(windows) && mode == Mode::Std && self.config.ehcont_guard {1311            rustflags.arg("-Zehcont-guard");1312        }13131314        // Optionally override the rc.exe when compiling rustc on Windows.1315        if let Some(windows_rc) = &self.config.windows_rc {1316            cargo.env("RUSTC_WINDOWS_RC", windows_rc);1317        }13181319        // For `cargo doc` invocations, make rustdoc print the Rust version into the docs1320        // This replaces spaces with tabs because RUSTDOCFLAGS does not1321        // support arguments with regular spaces. Hopefully someday Cargo will1322        // have space support.1323        let rust_version = self.rust_version().replace(' ', "\t");1324        rustdocflags.arg("--crate-version").arg(&rust_version);13251326        // Environment variables *required* throughout the build13271328        // The host this new compiler is being *built* on.1329        cargo.env("CFG_COMPILER_BUILD_TRIPLE", compiler.host.triple);13301331        // Set this for all builds to make sure doc builds also get it.1332        cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);13331334        // verbose cargo output is very noisy, so only enable it with -vv1335        for _ in 0..self.verbosity.saturating_sub(1) {1336            cargo.arg("--verbose");1337        }13381339        match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {1340            (Mode::Std, Some(n), _) | (_, _, Some(n)) => {1341                cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());1342            }1343            _ => {1344                // Don't set anything1345            }1346        }13471348        if self.config.locked_deps {1349            cargo.arg("--locked");1350        }1351        if self.config.vendor || self.is_sudo {1352            cargo.arg("--frozen");1353        }13541355        // Try to use a sysroot-relative bindir, in case it was configured absolutely.1356        cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());13571358        if self.config.is_running_on_ci() {1359            // Tell cargo to use colored output for nicer logs in CI, even1360            // though CI isn't printing to a terminal.1361            // Also set an explicit `TERM=xterm` so that cargo doesn't warn1362            // about TERM not being set.1363            cargo.env("TERM", "xterm").args(["--color=always"]);1364        };13651366        // When we build Rust dylibs they're all intended for intermediate1367        // usage, so make sure we pass the -Cprefer-dynamic flag instead of1368        // linking all deps statically into the dylib.1369        if matches!(mode, Mode::Std) {1370            rustflags.arg("-Cprefer-dynamic");1371        }1372        if matches!(mode, Mode::Rustc) && !self.link_std_into_rustc_driver(target) {1373            rustflags.arg("-Cprefer-dynamic");1374        }13751376        cargo.env(1377            "RUSTC_LINK_STD_INTO_RUSTC_DRIVER",1378            if self.link_std_into_rustc_driver(target) { "1" } else { "0" },1379        );13801381        // When building incrementally we default to a lower ThinLTO import limit1382        // (unless explicitly specified otherwise). This will produce a somewhat1383        // slower code but give way better compile times.1384        {1385            let limit = match self.config.rust_thin_lto_import_instr_limit {1386                Some(limit) => Some(limit),1387                None if self.config.incremental => Some(10),1388                _ => None,1389            };13901391            if let Some(limit) = limit1392                && (build_compiler_stage == 01393                    || self.config.default_codegen_backend(target).is_llvm())1394            {1395                rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={limit}"));1396            }1397        }13981399        if matches!(mode, Mode::Std) {1400            if let Some(mir_opt_level) = self.config.rust_validate_mir_opts {1401                rustflags.arg("-Zvalidate-mir");1402                rustflags.arg(&format!("-Zmir-opt-level={mir_opt_level}"));1403            }1404            if self.config.rust_randomize_layout {1405                rustflags.arg("--cfg=randomized_layouts");1406            }1407            // Always enable inlining MIR when building the standard library.1408            // Without this flag, MIR inlining is disabled when incremental compilation is enabled.1409            // That causes some mir-opt tests which inline functions from the standard library to1410            // break when incremental compilation is enabled. So this overrides the "no inlining1411            // during incremental builds" heuristic for the standard library.1412            rustflags.arg("-Zinline-mir");14131414            // Similarly, we need to keep debug info for functions inlined into other std functions,1415            // even if we're not going to output debuginfo for the crate we're currently building,1416            // so that it'll be available when downstream consumers of std try to use it.1417            rustflags.arg("-Zinline-mir-preserve-debug");14181419            rustflags.arg("-Zmir_strip_debuginfo=locals-in-tiny-functions");1420        }14211422        // take target-specific extra rustflags if any otherwise take `rust.rustflags`1423        let extra_rustflags = self1424            .config1425            .target_config1426            .get(&target)1427            .map(|t| &t.rustflags)1428            .unwrap_or(&self.config.rust_rustflags)1429            .clone();14301431        let profile =1432            if matches!(cmd_kind, Kind::Bench | Kind::Miri | Kind::MiriSetup | Kind::MiriTest) {1433                // Use the default profile for bench/miri1434                None1435            } else {1436                match (mode, self.config.rust_optimize.is_release()) {1437                    // Some std configuration exists in its own profile1438                    (Mode::Std, _) => Some("dist"),1439                    (_, true) => Some("release"),1440                    (_, false) => Some("dev"),1441                }1442            };14431444        Cargo {1445            command: cargo,1446            args: vec![],1447            compiler,1448            mode,1449            target,1450            rustflags,1451            rustdocflags,1452            hostflags,1453            allow_features,1454            build_compiler_stage,1455            extra_rustflags,1456            profile,1457        }1458    }1459}14601461pub fn cargo_profile_var(name: &str, config: &Config, mode: Mode) -> String {1462    let profile = match (mode, config.rust_optimize.is_release()) {1463        // Some std configuration exists in its own profile1464        (Mode::Std, _) => "DIST",1465        (_, true) => "RELEASE",1466        (_, false) => "DEV",1467    };1468    format!("CARGO_PROFILE_{profile}_{name}")1469}

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.