bootstrap/core/build_steps/
compile.rs

1//! Implementation of compiling various phases of the compiler and standard
2//! library.
3//!
4//! This module contains some of the real meat in the bootstrap build system
5//! which is where Cargo is used to compile the standard library, libtest, and
6//! the compiler. This module is also responsible for assembling the sysroot as it
7//! goes along from the output of the previous stage.
8
9use std::borrow::Cow;
10use std::collections::HashSet;
11use std::ffi::OsStr;
12use std::io::BufReader;
13use std::io::prelude::*;
14use std::path::{Path, PathBuf};
15use std::process::Stdio;
16use std::{env, fs, str};
17
18use serde_derive::Deserialize;
19#[cfg(feature = "tracing")]
20use tracing::{instrument, span};
21
22use crate::core::build_steps::gcc::{Gcc, add_cg_gcc_cargo_flags};
23use crate::core::build_steps::tool::SourceType;
24use crate::core::build_steps::{dist, llvm};
25use crate::core::builder;
26use crate::core::builder::{
27    Builder, Cargo, Kind, PathSet, RunConfig, ShouldRun, Step, TaskPath, crate_description,
28};
29use crate::core::config::{DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection};
30use crate::utils::build_stamp;
31use crate::utils::build_stamp::BuildStamp;
32use crate::utils::exec::command;
33use crate::utils::helpers::{
34    exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date,
35};
36use crate::{CLang, Compiler, DependencyType, FileType, GitRepo, LLVM_TOOLS, Mode, debug, trace};
37
38#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct Std {
40    pub target: TargetSelection,
41    pub compiler: Compiler,
42    /// Whether to build only a subset of crates in the standard library.
43    ///
44    /// This shouldn't be used from other steps; see the comment on [`Rustc`].
45    crates: Vec<String>,
46    /// When using download-rustc, we need to use a new build of `std` for running unit tests of Std itself,
47    /// but we need to use the downloaded copy of std for linking to rustdoc. Allow this to be overridden by `builder.ensure` from other steps.
48    force_recompile: bool,
49    extra_rust_args: &'static [&'static str],
50    is_for_mir_opt_tests: bool,
51}
52
53impl Std {
54    pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
55        Self {
56            target,
57            compiler,
58            crates: Default::default(),
59            force_recompile: false,
60            extra_rust_args: &[],
61            is_for_mir_opt_tests: false,
62        }
63    }
64
65    pub fn force_recompile(mut self, force_recompile: bool) -> Self {
66        self.force_recompile = force_recompile;
67        self
68    }
69
70    #[expect(clippy::wrong_self_convention)]
71    pub fn is_for_mir_opt_tests(mut self, is_for_mir_opt_tests: bool) -> Self {
72        self.is_for_mir_opt_tests = is_for_mir_opt_tests;
73        self
74    }
75
76    pub fn extra_rust_args(mut self, extra_rust_args: &'static [&'static str]) -> Self {
77        self.extra_rust_args = extra_rust_args;
78        self
79    }
80
81    fn copy_extra_objects(
82        &self,
83        builder: &Builder<'_>,
84        compiler: &Compiler,
85        target: TargetSelection,
86    ) -> Vec<(PathBuf, DependencyType)> {
87        let mut deps = Vec::new();
88        if !self.is_for_mir_opt_tests {
89            deps.extend(copy_third_party_objects(builder, compiler, target));
90            deps.extend(copy_self_contained_objects(builder, compiler, target));
91        }
92        deps
93    }
94}
95
96impl Step for Std {
97    type Output = ();
98    const DEFAULT: bool = true;
99
100    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
101        run.crate_or_deps("sysroot").path("library")
102    }
103
104    #[cfg_attr(feature = "tracing", instrument(level = "trace", name = "Std::make_run", skip_all))]
105    fn make_run(run: RunConfig<'_>) {
106        let crates = std_crates_for_run_make(&run);
107        let builder = run.builder;
108
109        // Force compilation of the standard library from source if the `library` is modified. This allows
110        // library team to compile the standard library without needing to compile the compiler with
111        // the `rust.download-rustc=true` option.
112        let force_recompile = builder.rust_info().is_managed_git_subrepository()
113            && builder.download_rustc()
114            && builder.config.has_changes_from_upstream(&["library"]);
115
116        trace!("is managed git repo: {}", builder.rust_info().is_managed_git_subrepository());
117        trace!("download_rustc: {}", builder.download_rustc());
118        trace!(force_recompile);
119
120        run.builder.ensure(Std {
121            compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
122            target: run.target,
123            crates,
124            force_recompile,
125            extra_rust_args: &[],
126            is_for_mir_opt_tests: false,
127        });
128    }
129
130    /// Builds the standard library.
131    ///
132    /// This will build the standard library for a particular stage of the build
133    /// using the `compiler` targeting the `target` architecture. The artifacts
134    /// created will also be linked into the sysroot directory.
135    #[cfg_attr(
136        feature = "tracing",
137        instrument(
138            level = "debug",
139            name = "Std::run",
140            skip_all,
141            fields(
142                target = ?self.target,
143                compiler = ?self.compiler,
144                force_recompile = self.force_recompile
145            ),
146        ),
147    )]
148    fn run(self, builder: &Builder<'_>) {
149        let target = self.target;
150        let compiler = self.compiler;
151
152        // When using `download-rustc`, we already have artifacts for the host available. Don't
153        // recompile them.
154        if builder.download_rustc() && builder.config.is_host_target(target)
155            // NOTE: the beta compiler may generate different artifacts than the downloaded compiler, so
156            // its artifacts can't be reused.
157            && compiler.stage != 0
158            && !self.force_recompile
159        {
160            let sysroot = builder.ensure(Sysroot { compiler, force_recompile: false });
161            cp_rustc_component_to_ci_sysroot(
162                builder,
163                &sysroot,
164                builder.config.ci_rust_std_contents(),
165            );
166            return;
167        }
168
169        if builder.config.keep_stage.contains(&compiler.stage)
170            || builder.config.keep_stage_std.contains(&compiler.stage)
171        {
172            trace!(keep_stage = ?builder.config.keep_stage);
173            trace!(keep_stage_std = ?builder.config.keep_stage_std);
174
175            builder.info("WARNING: Using a potentially old libstd. This may not behave well.");
176
177            builder.ensure(StartupObjects { compiler, target });
178
179            self.copy_extra_objects(builder, &compiler, target);
180
181            builder.ensure(StdLink::from_std(self, compiler));
182            return;
183        }
184
185        builder.require_submodule("library/stdarch", None);
186
187        let mut target_deps = builder.ensure(StartupObjects { compiler, target });
188
189        let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
190        trace!(?compiler_to_use);
191
192        if compiler_to_use != compiler {
193            trace!(?compiler_to_use, ?compiler, "compiler != compiler_to_use, uplifting library");
194
195            builder.ensure(Std::new(compiler_to_use, target));
196            let msg = if compiler_to_use.host == target {
197                format!(
198                    "Uplifting library (stage{} -> stage{})",
199                    compiler_to_use.stage, compiler.stage
200                )
201            } else {
202                format!(
203                    "Uplifting library (stage{}:{} -> stage{}:{})",
204                    compiler_to_use.stage, compiler_to_use.host, compiler.stage, target
205                )
206            };
207            builder.info(&msg);
208
209            // Even if we're not building std this stage, the new sysroot must
210            // still contain the third party objects needed by various targets.
211            self.copy_extra_objects(builder, &compiler, target);
212
213            builder.ensure(StdLink::from_std(self, compiler_to_use));
214            return;
215        }
216
217        trace!(
218            ?compiler_to_use,
219            ?compiler,
220            "compiler == compiler_to_use, handling not-cross-compile scenario"
221        );
222
223        target_deps.extend(self.copy_extra_objects(builder, &compiler, target));
224
225        // The LLD wrappers and `rust-lld` are self-contained linking components that can be
226        // necessary to link the stdlib on some targets. We'll also need to copy these binaries to
227        // the `stage0-sysroot` to ensure the linker is found when bootstrapping on such a target.
228        if compiler.stage == 0 && builder.config.is_host_target(compiler.host) {
229            trace!(
230                "(build == host) copying linking components to `stage0-sysroot` for bootstrapping"
231            );
232            // We want to copy the host `bin` folder within the `rustlib` folder in the sysroot.
233            let src_sysroot_bin = builder
234                .rustc_snapshot_sysroot()
235                .join("lib")
236                .join("rustlib")
237                .join(compiler.host)
238                .join("bin");
239            if src_sysroot_bin.exists() {
240                let target_sysroot_bin = builder.sysroot_target_bindir(compiler, target);
241                t!(fs::create_dir_all(&target_sysroot_bin));
242                builder.cp_link_r(&src_sysroot_bin, &target_sysroot_bin);
243            }
244        }
245
246        // We build a sysroot for mir-opt tests using the same trick that Miri does: A check build
247        // with -Zalways-encode-mir. This frees us from the need to have a target linker, and the
248        // fact that this is a check build integrates nicely with run_cargo.
249        let mut cargo = if self.is_for_mir_opt_tests {
250            trace!("building special sysroot for mir-opt tests");
251            let mut cargo = builder::Cargo::new_for_mir_opt_tests(
252                builder,
253                compiler,
254                Mode::Std,
255                SourceType::InTree,
256                target,
257                Kind::Check,
258            );
259            cargo.rustflag("-Zalways-encode-mir");
260            cargo.arg("--manifest-path").arg(builder.src.join("library/sysroot/Cargo.toml"));
261            cargo
262        } else {
263            trace!("building regular sysroot");
264            let mut cargo = builder::Cargo::new(
265                builder,
266                compiler,
267                Mode::Std,
268                SourceType::InTree,
269                target,
270                Kind::Build,
271            );
272            std_cargo(builder, target, compiler.stage, &mut cargo);
273            for krate in &*self.crates {
274                cargo.arg("-p").arg(krate);
275            }
276            cargo
277        };
278
279        // See src/bootstrap/synthetic_targets.rs
280        if target.is_synthetic() {
281            cargo.env("RUSTC_BOOTSTRAP_SYNTHETIC_TARGET", "1");
282        }
283        for rustflag in self.extra_rust_args.iter() {
284            cargo.rustflag(rustflag);
285        }
286
287        let _guard = builder.msg(
288            Kind::Build,
289            compiler.stage,
290            format_args!("library artifacts{}", crate_description(&self.crates)),
291            compiler.host,
292            target,
293        );
294        run_cargo(
295            builder,
296            cargo,
297            vec![],
298            &build_stamp::libstd_stamp(builder, compiler, target),
299            target_deps,
300            self.is_for_mir_opt_tests, // is_check
301            false,
302        );
303
304        builder.ensure(StdLink::from_std(
305            self,
306            builder.compiler(compiler.stage, builder.config.build),
307        ));
308    }
309}
310
311fn copy_and_stamp(
312    builder: &Builder<'_>,
313    libdir: &Path,
314    sourcedir: &Path,
315    name: &str,
316    target_deps: &mut Vec<(PathBuf, DependencyType)>,
317    dependency_type: DependencyType,
318) {
319    let target = libdir.join(name);
320    builder.copy_link(&sourcedir.join(name), &target, FileType::Regular);
321
322    target_deps.push((target, dependency_type));
323}
324
325fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
326    let libunwind_path = builder.ensure(llvm::Libunwind { target });
327    let libunwind_source = libunwind_path.join("libunwind.a");
328    let libunwind_target = libdir.join("libunwind.a");
329    builder.copy_link(&libunwind_source, &libunwind_target, FileType::NativeLibrary);
330    libunwind_target
331}
332
333/// Copies third party objects needed by various targets.
334fn copy_third_party_objects(
335    builder: &Builder<'_>,
336    compiler: &Compiler,
337    target: TargetSelection,
338) -> Vec<(PathBuf, DependencyType)> {
339    let mut target_deps = vec![];
340
341    if builder.config.needs_sanitizer_runtime_built(target) && compiler.stage != 0 {
342        // The sanitizers are only copied in stage1 or above,
343        // to avoid creating dependency on LLVM.
344        target_deps.extend(
345            copy_sanitizers(builder, compiler, target)
346                .into_iter()
347                .map(|d| (d, DependencyType::Target)),
348        );
349    }
350
351    if target == "x86_64-fortanix-unknown-sgx"
352        || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
353            && (target.contains("linux") || target.contains("fuchsia") || target.contains("aix"))
354    {
355        let libunwind_path =
356            copy_llvm_libunwind(builder, target, &builder.sysroot_target_libdir(*compiler, target));
357        target_deps.push((libunwind_path, DependencyType::Target));
358    }
359
360    target_deps
361}
362
363/// Copies third party objects needed by various targets for self-contained linkage.
364fn copy_self_contained_objects(
365    builder: &Builder<'_>,
366    compiler: &Compiler,
367    target: TargetSelection,
368) -> Vec<(PathBuf, DependencyType)> {
369    let libdir_self_contained =
370        builder.sysroot_target_libdir(*compiler, target).join("self-contained");
371    t!(fs::create_dir_all(&libdir_self_contained));
372    let mut target_deps = vec![];
373
374    // Copies the libc and CRT objects.
375    //
376    // rustc historically provides a more self-contained installation for musl targets
377    // not requiring the presence of a native musl toolchain. For example, it can fall back
378    // to using gcc from a glibc-targeting toolchain for linking.
379    // To do that we have to distribute musl startup objects as a part of Rust toolchain
380    // and link with them manually in the self-contained mode.
381    if target.needs_crt_begin_end() {
382        let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
383            panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
384        });
385        if !target.starts_with("wasm32") {
386            for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
387                copy_and_stamp(
388                    builder,
389                    &libdir_self_contained,
390                    &srcdir,
391                    obj,
392                    &mut target_deps,
393                    DependencyType::TargetSelfContained,
394                );
395            }
396            let crt_path = builder.ensure(llvm::CrtBeginEnd { target });
397            for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
398                let src = crt_path.join(obj);
399                let target = libdir_self_contained.join(obj);
400                builder.copy_link(&src, &target, FileType::NativeLibrary);
401                target_deps.push((target, DependencyType::TargetSelfContained));
402            }
403        } else {
404            // For wasm32 targets, we need to copy the libc.a and crt1-command.o files from the
405            // musl-libdir, but we don't need the other files.
406            for &obj in &["libc.a", "crt1-command.o"] {
407                copy_and_stamp(
408                    builder,
409                    &libdir_self_contained,
410                    &srcdir,
411                    obj,
412                    &mut target_deps,
413                    DependencyType::TargetSelfContained,
414                );
415            }
416        }
417        if !target.starts_with("s390x") {
418            let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
419            target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
420        }
421    } else if target.contains("-wasi") {
422        let srcdir = builder.wasi_libdir(target).unwrap_or_else(|| {
423            panic!(
424                "Target {:?} does not have a \"wasi-root\" key in bootstrap.toml \
425                    or `$WASI_SDK_PATH` set",
426                target.triple
427            )
428        });
429        for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
430            copy_and_stamp(
431                builder,
432                &libdir_self_contained,
433                &srcdir,
434                obj,
435                &mut target_deps,
436                DependencyType::TargetSelfContained,
437            );
438        }
439    } else if target.is_windows_gnu() {
440        for obj in ["crt2.o", "dllcrt2.o"].iter() {
441            let src = compiler_file(builder, &builder.cc(target), target, CLang::C, obj);
442            let dst = libdir_self_contained.join(obj);
443            builder.copy_link(&src, &dst, FileType::NativeLibrary);
444            target_deps.push((dst, DependencyType::TargetSelfContained));
445        }
446    }
447
448    target_deps
449}
450
451/// Resolves standard library crates for `Std::run_make` for any build kind (like check, build, clippy, etc.).
452pub fn std_crates_for_run_make(run: &RunConfig<'_>) -> Vec<String> {
453    // FIXME: Extend builder tests to cover the `crates` field of `Std` instances.
454    if cfg!(test) {
455        return vec![];
456    }
457
458    let has_alias = run.paths.iter().any(|set| set.assert_single_path().path.ends_with("library"));
459    let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
460
461    // For no_std targets, do not add any additional crates to the compilation other than what `compile::std_cargo` already adds for no_std targets.
462    if target_is_no_std {
463        vec![]
464    }
465    // If the paths include "library", build the entire standard library.
466    else if has_alias {
467        run.make_run_crates(builder::Alias::Library)
468    } else {
469        run.cargo_crates_in_set()
470    }
471}
472
473/// Tries to find LLVM's `compiler-rt` source directory, for building `library/profiler_builtins`.
474///
475/// Normally it lives in the `src/llvm-project` submodule, but if we will be using a
476/// downloaded copy of CI LLVM, then we try to use the `compiler-rt` sources from
477/// there instead, which lets us avoid checking out the LLVM submodule.
478fn compiler_rt_for_profiler(builder: &Builder<'_>) -> PathBuf {
479    // Try to use `compiler-rt` sources from downloaded CI LLVM, if possible.
480    if builder.config.llvm_from_ci {
481        // CI LLVM might not have been downloaded yet, so try to download it now.
482        builder.config.maybe_download_ci_llvm();
483        let ci_llvm_compiler_rt = builder.config.ci_llvm_root().join("compiler-rt");
484        if ci_llvm_compiler_rt.exists() {
485            return ci_llvm_compiler_rt;
486        }
487    }
488
489    // Otherwise, fall back to requiring the LLVM submodule.
490    builder.require_submodule("src/llvm-project", {
491        Some("The `build.profiler` config option requires `compiler-rt` sources from LLVM.")
492    });
493    builder.src.join("src/llvm-project/compiler-rt")
494}
495
496/// Configure cargo to compile the standard library, adding appropriate env vars
497/// and such.
498pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, stage: u32, cargo: &mut Cargo) {
499    // rustc already ensures that it builds with the minimum deployment
500    // target, so ideally we shouldn't need to do anything here.
501    //
502    // However, `cc` currently defaults to a higher version for backwards
503    // compatibility, which means that compiler-rt, which is built via
504    // compiler-builtins' build script, gets built with a higher deployment
505    // target. This in turn causes warnings while linking, and is generally
506    // a compatibility hazard.
507    //
508    // So, at least until https://github.com/rust-lang/cc-rs/issues/1171, or
509    // perhaps https://github.com/rust-lang/cargo/issues/13115 is resolved, we
510    // explicitly set the deployment target environment variables to avoid
511    // this issue.
512    //
513    // This place also serves as an extension point if we ever wanted to raise
514    // rustc's default deployment target while keeping the prebuilt `std` at
515    // a lower version, so it's kinda nice to have in any case.
516    if target.contains("apple") && !builder.config.dry_run() {
517        // Query rustc for the deployment target, and the associated env var.
518        // The env var is one of the standard `*_DEPLOYMENT_TARGET` vars, i.e.
519        // `MACOSX_DEPLOYMENT_TARGET`, `IPHONEOS_DEPLOYMENT_TARGET`, etc.
520        let mut cmd = command(builder.rustc(cargo.compiler()));
521        cmd.arg("--target").arg(target.rustc_target_arg());
522        cmd.arg("--print=deployment-target");
523        let output = cmd.run_capture_stdout(builder).stdout();
524
525        let (env_var, value) = output.split_once('=').unwrap();
526        // Unconditionally set the env var (if it was set in the environment
527        // already, rustc should've picked that up).
528        cargo.env(env_var.trim(), value.trim());
529
530        // Allow CI to override the deployment target for `std` on macOS.
531        //
532        // This is useful because we might want the host tooling LLVM, `rustc`
533        // and Cargo to have a different deployment target than `std` itself
534        // (currently, these two versions are the same, but in the past, we
535        // supported macOS 10.7 for user code and macOS 10.8 in host tooling).
536        //
537        // It is not necessary on the other platforms, since only macOS has
538        // support for host tooling.
539        if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
540            cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
541        }
542    }
543
544    // Paths needed by `library/profiler_builtins/build.rs`.
545    if let Some(path) = builder.config.profiler_path(target) {
546        cargo.env("LLVM_PROFILER_RT_LIB", path);
547    } else if builder.config.profiler_enabled(target) {
548        let compiler_rt = compiler_rt_for_profiler(builder);
549        // Currently this is separate from the env var used by `compiler_builtins`
550        // (below) so that adding support for CI LLVM here doesn't risk breaking
551        // the compiler builtins. But they could be unified if desired.
552        cargo.env("RUST_COMPILER_RT_FOR_PROFILER", compiler_rt);
553    }
554
555    // Determine if we're going to compile in optimized C intrinsics to
556    // the `compiler-builtins` crate. These intrinsics live in LLVM's
557    // `compiler-rt` repository.
558    //
559    // Note that this shouldn't affect the correctness of `compiler-builtins`,
560    // but only its speed. Some intrinsics in C haven't been translated to Rust
561    // yet but that's pretty rare. Other intrinsics have optimized
562    // implementations in C which have only had slower versions ported to Rust,
563    // so we favor the C version where we can, but it's not critical.
564    //
565    // If `compiler-rt` is available ensure that the `c` feature of the
566    // `compiler-builtins` crate is enabled and it's configured to learn where
567    // `compiler-rt` is located.
568    let compiler_builtins_c_feature = if builder.config.optimized_compiler_builtins(target) {
569        // NOTE: this interacts strangely with `llvm-has-rust-patches`. In that case, we enforce `submodules = false`, so this is a no-op.
570        // But, the user could still decide to manually use an in-tree submodule.
571        //
572        // NOTE: if we're using system llvm, we'll end up building a version of `compiler-rt` that doesn't match the LLVM we're linking to.
573        // That's probably ok? At least, the difference wasn't enforced before. There's a comment in
574        // the compiler_builtins build script that makes me nervous, though:
575        // https://github.com/rust-lang/compiler-builtins/blob/31ee4544dbe47903ce771270d6e3bea8654e9e50/build.rs#L575-L579
576        builder.require_submodule(
577            "src/llvm-project",
578            Some(
579                "The `build.optimized-compiler-builtins` config option \
580                 requires `compiler-rt` sources from LLVM.",
581            ),
582        );
583        let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
584        assert!(compiler_builtins_root.exists());
585        // The path to `compiler-rt` is also used by `profiler_builtins` (above),
586        // so if you're changing something here please also change that as appropriate.
587        cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
588        " compiler-builtins-c"
589    } else {
590        ""
591    };
592
593    // `libtest` uses this to know whether or not to support
594    // `-Zunstable-options`.
595    if !builder.unstable_features() {
596        cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
597    }
598
599    let mut features = String::new();
600
601    if stage != 0 && builder.config.default_codegen_backend(target).as_deref() == Some("cranelift")
602    {
603        features += "compiler-builtins-no-f16-f128 ";
604    }
605
606    if builder.no_std(target) == Some(true) {
607        features += " compiler-builtins-mem";
608        if !target.starts_with("bpf") {
609            features.push_str(compiler_builtins_c_feature);
610        }
611
612        // for no-std targets we only compile a few no_std crates
613        cargo
614            .args(["-p", "alloc"])
615            .arg("--manifest-path")
616            .arg(builder.src.join("library/alloc/Cargo.toml"))
617            .arg("--features")
618            .arg(features);
619    } else {
620        features += &builder.std_features(target);
621        features.push_str(compiler_builtins_c_feature);
622
623        cargo
624            .arg("--features")
625            .arg(features)
626            .arg("--manifest-path")
627            .arg(builder.src.join("library/sysroot/Cargo.toml"));
628
629        // Help the libc crate compile by assisting it in finding various
630        // sysroot native libraries.
631        if target.contains("musl") {
632            if let Some(p) = builder.musl_libdir(target) {
633                let root = format!("native={}", p.to_str().unwrap());
634                cargo.rustflag("-L").rustflag(&root);
635            }
636        }
637
638        if target.contains("-wasi") {
639            if let Some(dir) = builder.wasi_libdir(target) {
640                let root = format!("native={}", dir.to_str().unwrap());
641                cargo.rustflag("-L").rustflag(&root);
642            }
643        }
644    }
645
646    // By default, rustc uses `-Cembed-bitcode=yes`, and Cargo overrides that
647    // with `-Cembed-bitcode=no` for non-LTO builds. However, libstd must be
648    // built with bitcode so that the produced rlibs can be used for both LTO
649    // builds (which use bitcode) and non-LTO builds (which use object code).
650    // So we override the override here!
651    //
652    // But we don't bother for the stage 0 compiler because it's never used
653    // with LTO.
654    if stage >= 1 {
655        cargo.rustflag("-Cembed-bitcode=yes");
656    }
657    if builder.config.rust_lto == RustcLto::Off {
658        cargo.rustflag("-Clto=off");
659    }
660
661    // By default, rustc does not include unwind tables unless they are required
662    // for a particular target. They are not required by RISC-V targets, but
663    // compiling the standard library with them means that users can get
664    // backtraces without having to recompile the standard library themselves.
665    //
666    // This choice was discussed in https://github.com/rust-lang/rust/pull/69890
667    if target.contains("riscv") {
668        cargo.rustflag("-Cforce-unwind-tables=yes");
669    }
670
671    // Enable frame pointers by default for the library. Note that they are still controlled by a
672    // separate setting for the compiler.
673    cargo.rustflag("-Cforce-frame-pointers=yes");
674
675    let html_root =
676        format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
677    cargo.rustflag(&html_root);
678    cargo.rustdocflag(&html_root);
679
680    cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
681}
682
683#[derive(Debug, Clone, PartialEq, Eq, Hash)]
684struct StdLink {
685    pub compiler: Compiler,
686    pub target_compiler: Compiler,
687    pub target: TargetSelection,
688    /// Not actually used; only present to make sure the cache invalidation is correct.
689    crates: Vec<String>,
690    /// See [`Std::force_recompile`].
691    force_recompile: bool,
692}
693
694impl StdLink {
695    fn from_std(std: Std, host_compiler: Compiler) -> Self {
696        Self {
697            compiler: host_compiler,
698            target_compiler: std.compiler,
699            target: std.target,
700            crates: std.crates,
701            force_recompile: std.force_recompile,
702        }
703    }
704}
705
706impl Step for StdLink {
707    type Output = ();
708
709    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
710        run.never()
711    }
712
713    /// Link all libstd rlibs/dylibs into the sysroot location.
714    ///
715    /// Links those artifacts generated by `compiler` to the `stage` compiler's
716    /// sysroot for the specified `host` and `target`.
717    ///
718    /// Note that this assumes that `compiler` has already generated the libstd
719    /// libraries for `target`, and this method will find them in the relevant
720    /// output directory.
721    #[cfg_attr(
722        feature = "tracing",
723        instrument(
724            level = "trace",
725            name = "StdLink::run",
726            skip_all,
727            fields(
728                compiler = ?self.compiler,
729                target_compiler = ?self.target_compiler,
730                target = ?self.target
731            ),
732        ),
733    )]
734    fn run(self, builder: &Builder<'_>) {
735        let compiler = self.compiler;
736        let target_compiler = self.target_compiler;
737        let target = self.target;
738
739        // NOTE: intentionally does *not* check `target == builder.build` to avoid having to add the same check in `test::Crate`.
740        let (libdir, hostdir) = if self.force_recompile && builder.download_rustc() {
741            // NOTE: copies part of `sysroot_libdir` to avoid having to add a new `force_recompile` argument there too
742            let lib = builder.sysroot_libdir_relative(self.compiler);
743            let sysroot = builder.ensure(crate::core::build_steps::compile::Sysroot {
744                compiler: self.compiler,
745                force_recompile: self.force_recompile,
746            });
747            let libdir = sysroot.join(lib).join("rustlib").join(target).join("lib");
748            let hostdir = sysroot.join(lib).join("rustlib").join(compiler.host).join("lib");
749            (libdir, hostdir)
750        } else {
751            let libdir = builder.sysroot_target_libdir(target_compiler, target);
752            let hostdir = builder.sysroot_target_libdir(target_compiler, compiler.host);
753            (libdir, hostdir)
754        };
755
756        add_to_sysroot(
757            builder,
758            &libdir,
759            &hostdir,
760            &build_stamp::libstd_stamp(builder, compiler, target),
761        );
762
763        // Special case for stage0, to make `rustup toolchain link` and `x dist --stage 0`
764        // work for stage0-sysroot. We only do this if the stage0 compiler comes from beta,
765        // and is not set to a custom path.
766        if compiler.stage == 0
767            && builder
768                .build
769                .config
770                .initial_rustc
771                .starts_with(builder.out.join(compiler.host).join("stage0/bin"))
772        {
773            // Copy bin files from stage0/bin to stage0-sysroot/bin
774            let sysroot = builder.out.join(compiler.host).join("stage0-sysroot");
775
776            let host = compiler.host;
777            let stage0_bin_dir = builder.out.join(host).join("stage0/bin");
778            let sysroot_bin_dir = sysroot.join("bin");
779            t!(fs::create_dir_all(&sysroot_bin_dir));
780            builder.cp_link_r(&stage0_bin_dir, &sysroot_bin_dir);
781
782            // Copy all files from stage0/lib to stage0-sysroot/lib
783            let stage0_lib_dir = builder.out.join(host).join("stage0/lib");
784            if let Ok(files) = fs::read_dir(stage0_lib_dir) {
785                for file in files {
786                    let file = t!(file);
787                    let path = file.path();
788                    if path.is_file() {
789                        builder.copy_link(
790                            &path,
791                            &sysroot.join("lib").join(path.file_name().unwrap()),
792                            FileType::Regular,
793                        );
794                    }
795                }
796            }
797
798            // Copy codegen-backends from stage0
799            let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler);
800            t!(fs::create_dir_all(&sysroot_codegen_backends));
801            let stage0_codegen_backends = builder
802                .out
803                .join(host)
804                .join("stage0/lib/rustlib")
805                .join(host)
806                .join("codegen-backends");
807            if stage0_codegen_backends.exists() {
808                builder.cp_link_r(&stage0_codegen_backends, &sysroot_codegen_backends);
809            }
810        }
811    }
812}
813
814/// Copies sanitizer runtime libraries into target libdir.
815fn copy_sanitizers(
816    builder: &Builder<'_>,
817    compiler: &Compiler,
818    target: TargetSelection,
819) -> Vec<PathBuf> {
820    let runtimes: Vec<llvm::SanitizerRuntime> = builder.ensure(llvm::Sanitizers { target });
821
822    if builder.config.dry_run() {
823        return Vec::new();
824    }
825
826    let mut target_deps = Vec::new();
827    let libdir = builder.sysroot_target_libdir(*compiler, target);
828
829    for runtime in &runtimes {
830        let dst = libdir.join(&runtime.name);
831        builder.copy_link(&runtime.path, &dst, FileType::NativeLibrary);
832
833        // The `aarch64-apple-ios-macabi` and `x86_64-apple-ios-macabi` are also supported for
834        // sanitizers, but they share a sanitizer runtime with `${arch}-apple-darwin`, so we do
835        // not list them here to rename and sign the runtime library.
836        if target == "x86_64-apple-darwin"
837            || target == "aarch64-apple-darwin"
838            || target == "aarch64-apple-ios"
839            || target == "aarch64-apple-ios-sim"
840            || target == "x86_64-apple-ios"
841        {
842            // Update the library’s install name to reflect that it has been renamed.
843            apple_darwin_update_library_name(builder, &dst, &format!("@rpath/{}", runtime.name));
844            // Upon renaming the install name, the code signature of the file will invalidate,
845            // so we will sign it again.
846            apple_darwin_sign_file(builder, &dst);
847        }
848
849        target_deps.push(dst);
850    }
851
852    target_deps
853}
854
855fn apple_darwin_update_library_name(builder: &Builder<'_>, library_path: &Path, new_name: &str) {
856    command("install_name_tool").arg("-id").arg(new_name).arg(library_path).run(builder);
857}
858
859fn apple_darwin_sign_file(builder: &Builder<'_>, file_path: &Path) {
860    command("codesign")
861        .arg("-f") // Force to rewrite the existing signature
862        .arg("-s")
863        .arg("-")
864        .arg(file_path)
865        .run(builder);
866}
867
868#[derive(Debug, Clone, PartialEq, Eq, Hash)]
869pub struct StartupObjects {
870    pub compiler: Compiler,
871    pub target: TargetSelection,
872}
873
874impl Step for StartupObjects {
875    type Output = Vec<(PathBuf, DependencyType)>;
876
877    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
878        run.path("library/rtstartup")
879    }
880
881    fn make_run(run: RunConfig<'_>) {
882        run.builder.ensure(StartupObjects {
883            compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
884            target: run.target,
885        });
886    }
887
888    /// Builds and prepare startup objects like rsbegin.o and rsend.o
889    ///
890    /// These are primarily used on Windows right now for linking executables/dlls.
891    /// They don't require any library support as they're just plain old object
892    /// files, so we just use the nightly snapshot compiler to always build them (as
893    /// no other compilers are guaranteed to be available).
894    #[cfg_attr(
895        feature = "tracing",
896        instrument(
897            level = "trace",
898            name = "StartupObjects::run",
899            skip_all,
900            fields(compiler = ?self.compiler, target = ?self.target),
901        ),
902    )]
903    fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
904        let for_compiler = self.compiler;
905        let target = self.target;
906        if !target.is_windows_gnu() {
907            return vec![];
908        }
909
910        let mut target_deps = vec![];
911
912        let src_dir = &builder.src.join("library").join("rtstartup");
913        let dst_dir = &builder.native_dir(target).join("rtstartup");
914        let sysroot_dir = &builder.sysroot_target_libdir(for_compiler, target);
915        t!(fs::create_dir_all(dst_dir));
916
917        for file in &["rsbegin", "rsend"] {
918            let src_file = &src_dir.join(file.to_string() + ".rs");
919            let dst_file = &dst_dir.join(file.to_string() + ".o");
920            if !up_to_date(src_file, dst_file) {
921                let mut cmd = command(&builder.initial_rustc);
922                cmd.env("RUSTC_BOOTSTRAP", "1");
923                if !builder.local_rebuild {
924                    // a local_rebuild compiler already has stage1 features
925                    cmd.arg("--cfg").arg("bootstrap");
926                }
927                cmd.arg("--target")
928                    .arg(target.rustc_target_arg())
929                    .arg("--emit=obj")
930                    .arg("-o")
931                    .arg(dst_file)
932                    .arg(src_file)
933                    .run(builder);
934            }
935
936            let obj = sysroot_dir.join((*file).to_string() + ".o");
937            builder.copy_link(dst_file, &obj, FileType::NativeLibrary);
938            target_deps.push((obj, DependencyType::Target));
939        }
940
941        target_deps
942    }
943}
944
945fn cp_rustc_component_to_ci_sysroot(builder: &Builder<'_>, sysroot: &Path, contents: Vec<String>) {
946    let ci_rustc_dir = builder.config.ci_rustc_dir();
947
948    for file in contents {
949        let src = ci_rustc_dir.join(&file);
950        let dst = sysroot.join(file);
951        if src.is_dir() {
952            t!(fs::create_dir_all(dst));
953        } else {
954            builder.copy_link(&src, &dst, FileType::Regular);
955        }
956    }
957}
958
959#[derive(Debug, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
960pub struct Rustc {
961    pub target: TargetSelection,
962    /// The **previous** compiler used to compile this compiler.
963    pub compiler: Compiler,
964    /// Whether to build a subset of crates, rather than the whole compiler.
965    ///
966    /// This should only be requested by the user, not used within bootstrap itself.
967    /// Using it within bootstrap can lead to confusing situation where lints are replayed
968    /// in two different steps.
969    crates: Vec<String>,
970}
971
972impl Rustc {
973    pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
974        Self { target, compiler, crates: Default::default() }
975    }
976}
977
978impl Step for Rustc {
979    /// We return the stage of the "actual" compiler (not the uplifted one).
980    ///
981    /// By "actual" we refer to the uplifting logic where we may not compile the requested stage;
982    /// instead, we uplift it from the previous stages. Which can lead to bootstrap failures in
983    /// specific situations where we request stage X from other steps. However we may end up
984    /// uplifting it from stage Y, causing the other stage to fail when attempting to link with
985    /// stage X which was never actually built.
986    type Output = u32;
987    const ONLY_HOSTS: bool = true;
988    const DEFAULT: bool = false;
989
990    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
991        let mut crates = run.builder.in_tree_crates("rustc-main", None);
992        for (i, krate) in crates.iter().enumerate() {
993            // We can't allow `build rustc` as an alias for this Step, because that's reserved by `Assemble`.
994            // Ideally Assemble would use `build compiler` instead, but that seems too confusing to be worth the breaking change.
995            if krate.name == "rustc-main" {
996                crates.swap_remove(i);
997                break;
998            }
999        }
1000        run.crates(crates)
1001    }
1002
1003    fn make_run(run: RunConfig<'_>) {
1004        let crates = run.cargo_crates_in_set();
1005        run.builder.ensure(Rustc {
1006            compiler: run
1007                .builder
1008                .compiler(run.builder.top_stage.saturating_sub(1), run.build_triple()),
1009            target: run.target,
1010            crates,
1011        });
1012    }
1013
1014    /// Builds the compiler.
1015    ///
1016    /// This will build the compiler for a particular stage of the build using
1017    /// the `compiler` targeting the `target` architecture. The artifacts
1018    /// created will also be linked into the sysroot directory.
1019    #[cfg_attr(
1020        feature = "tracing",
1021        instrument(
1022            level = "debug",
1023            name = "Rustc::run",
1024            skip_all,
1025            fields(previous_compiler = ?self.compiler, target = ?self.target),
1026        ),
1027    )]
1028    fn run(self, builder: &Builder<'_>) -> u32 {
1029        let compiler = self.compiler;
1030        let target = self.target;
1031
1032        // NOTE: the ABI of the beta compiler is different from the ABI of the downloaded compiler,
1033        // so its artifacts can't be reused.
1034        if builder.download_rustc() && compiler.stage != 0 {
1035            trace!(stage = compiler.stage, "`download_rustc` requested");
1036
1037            let sysroot = builder.ensure(Sysroot { compiler, force_recompile: false });
1038            cp_rustc_component_to_ci_sysroot(
1039                builder,
1040                &sysroot,
1041                builder.config.ci_rustc_dev_contents(),
1042            );
1043            return compiler.stage;
1044        }
1045
1046        builder.ensure(Std::new(compiler, target));
1047
1048        if builder.config.keep_stage.contains(&compiler.stage) {
1049            trace!(stage = compiler.stage, "`keep-stage` requested");
1050
1051            builder.info("WARNING: Using a potentially old librustc. This may not behave well.");
1052            builder.info("WARNING: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
1053            builder.ensure(RustcLink::from_rustc(self, compiler));
1054
1055            return compiler.stage;
1056        }
1057
1058        let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
1059        if compiler_to_use != compiler {
1060            builder.ensure(Rustc::new(compiler_to_use, target));
1061            let msg = if compiler_to_use.host == target {
1062                format!(
1063                    "Uplifting rustc (stage{} -> stage{})",
1064                    compiler_to_use.stage,
1065                    compiler.stage + 1
1066                )
1067            } else {
1068                format!(
1069                    "Uplifting rustc (stage{}:{} -> stage{}:{})",
1070                    compiler_to_use.stage,
1071                    compiler_to_use.host,
1072                    compiler.stage + 1,
1073                    target
1074                )
1075            };
1076            builder.info(&msg);
1077            builder.ensure(RustcLink::from_rustc(self, compiler_to_use));
1078            return compiler_to_use.stage;
1079        }
1080
1081        // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
1082        builder.ensure(Std::new(
1083            builder.compiler(self.compiler.stage, builder.config.build),
1084            builder.config.build,
1085        ));
1086
1087        let mut cargo = builder::Cargo::new(
1088            builder,
1089            compiler,
1090            Mode::Rustc,
1091            SourceType::InTree,
1092            target,
1093            Kind::Build,
1094        );
1095
1096        rustc_cargo(builder, &mut cargo, target, &compiler, &self.crates);
1097
1098        // NB: all RUSTFLAGS should be added to `rustc_cargo()` so they will be
1099        // consistently applied by check/doc/test modes too.
1100
1101        for krate in &*self.crates {
1102            cargo.arg("-p").arg(krate);
1103        }
1104
1105        if builder.build.config.enable_bolt_settings && compiler.stage == 1 {
1106            // Relocations are required for BOLT to work.
1107            cargo.env("RUSTC_BOLT_LINK_FLAGS", "1");
1108        }
1109
1110        let _guard = builder.msg_sysroot_tool(
1111            Kind::Build,
1112            compiler.stage,
1113            format_args!("compiler artifacts{}", crate_description(&self.crates)),
1114            compiler.host,
1115            target,
1116        );
1117        let stamp = build_stamp::librustc_stamp(builder, compiler, target);
1118        run_cargo(
1119            builder,
1120            cargo,
1121            vec![],
1122            &stamp,
1123            vec![],
1124            false,
1125            true, // Only ship rustc_driver.so and .rmeta files, not all intermediate .rlib files.
1126        );
1127
1128        let target_root_dir = stamp.path().parent().unwrap();
1129        // When building `librustc_driver.so` (like `libLLVM.so`) on linux, it can contain
1130        // unexpected debuginfo from dependencies, for example from the C++ standard library used in
1131        // our LLVM wrapper. Unless we're explicitly requesting `librustc_driver` to be built with
1132        // debuginfo (via the debuginfo level of the executables using it): strip this debuginfo
1133        // away after the fact.
1134        if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None
1135            && builder.config.rust_debuginfo_level_tools == DebuginfoLevel::None
1136        {
1137            let rustc_driver = target_root_dir.join("librustc_driver.so");
1138            strip_debug(builder, target, &rustc_driver);
1139        }
1140
1141        if builder.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
1142            // Due to LTO a lot of debug info from C++ dependencies such as jemalloc can make it into
1143            // our final binaries
1144            strip_debug(builder, target, &target_root_dir.join("rustc-main"));
1145        }
1146
1147        builder.ensure(RustcLink::from_rustc(
1148            self,
1149            builder.compiler(compiler.stage, builder.config.build),
1150        ));
1151
1152        compiler.stage
1153    }
1154}
1155
1156pub fn rustc_cargo(
1157    builder: &Builder<'_>,
1158    cargo: &mut Cargo,
1159    target: TargetSelection,
1160    compiler: &Compiler,
1161    crates: &[String],
1162) {
1163    cargo
1164        .arg("--features")
1165        .arg(builder.rustc_features(builder.kind, target, crates))
1166        .arg("--manifest-path")
1167        .arg(builder.src.join("compiler/rustc/Cargo.toml"));
1168
1169    cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)");
1170
1171    // If the rustc output is piped to e.g. `head -n1` we want the process to be killed, rather than
1172    // having an error bubble up and cause a panic.
1173    //
1174    // FIXME(jieyouxu): this flag is load-bearing for rustc to not ICE on broken pipes, because
1175    // rustc internally sometimes uses std `println!` -- but std `println!` by default will panic on
1176    // broken pipes, and uncaught panics will manifest as an ICE. The compiler *should* handle this
1177    // properly, but this flag is set in the meantime to paper over the I/O errors.
1178    //
1179    // See <https://github.com/rust-lang/rust/issues/131059> for details.
1180    //
1181    // Also see the discussion for properly handling I/O errors related to broken pipes, i.e. safe
1182    // variants of `println!` in
1183    // <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Internal.20lint.20for.20raw.20.60print!.60.20and.20.60println!.60.3F>.
1184    cargo.rustflag("-Zon-broken-pipe=kill");
1185
1186    // We want to link against registerEnzyme and in the future we want to use additional
1187    // functionality from Enzyme core. For that we need to link against Enzyme.
1188    if builder.config.llvm_enzyme {
1189        let arch = builder.build.build;
1190        let enzyme_dir = builder.build.out.join(arch).join("enzyme").join("lib");
1191        cargo.rustflag("-L").rustflag(enzyme_dir.to_str().expect("Invalid path"));
1192
1193        if let Some(llvm_config) = builder.llvm_config(builder.config.build) {
1194            let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
1195            cargo.rustflag("-l").rustflag(&format!("Enzyme-{llvm_version_major}"));
1196        }
1197    }
1198
1199    // Building with protected visibility reduces the number of dynamic relocations needed, giving
1200    // us a faster startup time. However GNU ld < 2.40 will error if we try to link a shared object
1201    // with direct references to protected symbols, so for now we only use protected symbols if
1202    // linking with LLD is enabled.
1203    if builder.build.config.lld_mode.is_used() {
1204        cargo.rustflag("-Zdefault-visibility=protected");
1205    }
1206
1207    if is_lto_stage(compiler) {
1208        match builder.config.rust_lto {
1209            RustcLto::Thin | RustcLto::Fat => {
1210                // Since using LTO for optimizing dylibs is currently experimental,
1211                // we need to pass -Zdylib-lto.
1212                cargo.rustflag("-Zdylib-lto");
1213                // Cargo by default passes `-Cembed-bitcode=no` and doesn't pass `-Clto` when
1214                // compiling dylibs (and their dependencies), even when LTO is enabled for the
1215                // crate. Therefore, we need to override `-Clto` and `-Cembed-bitcode` here.
1216                let lto_type = match builder.config.rust_lto {
1217                    RustcLto::Thin => "thin",
1218                    RustcLto::Fat => "fat",
1219                    _ => unreachable!(),
1220                };
1221                cargo.rustflag(&format!("-Clto={lto_type}"));
1222                cargo.rustflag("-Cembed-bitcode=yes");
1223            }
1224            RustcLto::ThinLocal => { /* Do nothing, this is the default */ }
1225            RustcLto::Off => {
1226                cargo.rustflag("-Clto=off");
1227            }
1228        }
1229    } else if builder.config.rust_lto == RustcLto::Off {
1230        cargo.rustflag("-Clto=off");
1231    }
1232
1233    // With LLD, we can use ICF (identical code folding) to reduce the executable size
1234    // of librustc_driver/rustc and to improve i-cache utilization.
1235    //
1236    // -Wl,[link options] doesn't work on MSVC. However, /OPT:ICF (technically /OPT:REF,ICF)
1237    // is already on by default in MSVC optimized builds, which is interpreted as --icf=all:
1238    // https://github.com/llvm/llvm-project/blob/3329cec2f79185bafd678f310fafadba2a8c76d2/lld/COFF/Driver.cpp#L1746
1239    // https://github.com/rust-lang/rust/blob/f22819bcce4abaff7d1246a56eec493418f9f4ee/compiler/rustc_codegen_ssa/src/back/linker.rs#L827
1240    if builder.config.lld_mode.is_used() && !compiler.host.is_msvc() {
1241        cargo.rustflag("-Clink-args=-Wl,--icf=all");
1242    }
1243
1244    if builder.config.rust_profile_use.is_some() && builder.config.rust_profile_generate.is_some() {
1245        panic!("Cannot use and generate PGO profiles at the same time");
1246    }
1247    let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
1248        if compiler.stage == 1 {
1249            cargo.rustflag(&format!("-Cprofile-generate={path}"));
1250            // Apparently necessary to avoid overflowing the counters during
1251            // a Cargo build profile
1252            cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
1253            true
1254        } else {
1255            false
1256        }
1257    } else if let Some(path) = &builder.config.rust_profile_use {
1258        if compiler.stage == 1 {
1259            cargo.rustflag(&format!("-Cprofile-use={path}"));
1260            if builder.is_verbose() {
1261                cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
1262            }
1263            true
1264        } else {
1265            false
1266        }
1267    } else {
1268        false
1269    };
1270    if is_collecting {
1271        // Ensure paths to Rust sources are relative, not absolute.
1272        cargo.rustflag(&format!(
1273            "-Cllvm-args=-static-func-strip-dirname-prefix={}",
1274            builder.config.src.components().count()
1275        ));
1276    }
1277
1278    rustc_cargo_env(builder, cargo, target, compiler.stage);
1279}
1280
1281pub fn rustc_cargo_env(
1282    builder: &Builder<'_>,
1283    cargo: &mut Cargo,
1284    target: TargetSelection,
1285    stage: u32,
1286) {
1287    // Set some configuration variables picked up by build scripts and
1288    // the compiler alike
1289    cargo
1290        .env("CFG_RELEASE", builder.rust_release())
1291        .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
1292        .env("CFG_VERSION", builder.rust_version());
1293
1294    // Some tools like Cargo detect their own git information in build scripts. When omit-git-hash
1295    // is enabled in bootstrap.toml, we pass this environment variable to tell build scripts to avoid
1296    // detecting git information on their own.
1297    if builder.config.omit_git_hash {
1298        cargo.env("CFG_OMIT_GIT_HASH", "1");
1299    }
1300
1301    if let Some(backend) = builder.config.default_codegen_backend(target) {
1302        cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", backend);
1303    }
1304
1305    let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
1306    let target_config = builder.config.target_config.get(&target);
1307
1308    cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
1309
1310    if let Some(ref ver_date) = builder.rust_info().commit_date() {
1311        cargo.env("CFG_VER_DATE", ver_date);
1312    }
1313    if let Some(ref ver_hash) = builder.rust_info().sha() {
1314        cargo.env("CFG_VER_HASH", ver_hash);
1315    }
1316    if !builder.unstable_features() {
1317        cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
1318    }
1319
1320    // Prefer the current target's own default_linker, else a globally
1321    // specified one.
1322    if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
1323        cargo.env("CFG_DEFAULT_LINKER", s);
1324    } else if let Some(ref s) = builder.config.rustc_default_linker {
1325        cargo.env("CFG_DEFAULT_LINKER", s);
1326    }
1327
1328    // Enable rustc's env var for `rust-lld` when requested.
1329    if builder.config.lld_enabled
1330        && (builder.config.channel == "dev" || builder.config.channel == "nightly")
1331    {
1332        cargo.env("CFG_USE_SELF_CONTAINED_LINKER", "1");
1333    }
1334
1335    if builder.config.rust_verify_llvm_ir {
1336        cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1337    }
1338
1339    if builder.config.llvm_enzyme {
1340        cargo.rustflag("--cfg=llvm_enzyme");
1341    }
1342
1343    // Note that this is disabled if LLVM itself is disabled or we're in a check
1344    // build. If we are in a check build we still go ahead here presuming we've
1345    // detected that LLVM is already built and good to go which helps prevent
1346    // busting caches (e.g. like #71152).
1347    if builder.config.llvm_enabled(target) {
1348        let building_is_expensive =
1349            crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false)
1350                .should_build();
1351        // `top_stage == stage` might be false for `check --stage 1`, if we are building the stage 1 compiler
1352        let can_skip_build = builder.kind == Kind::Check && builder.top_stage == stage;
1353        let should_skip_build = building_is_expensive && can_skip_build;
1354        if !should_skip_build {
1355            rustc_llvm_env(builder, cargo, target)
1356        }
1357    }
1358
1359    // Build jemalloc on AArch64 with support for page sizes up to 64K
1360    // See: https://github.com/rust-lang/rust/pull/135081
1361    if builder.config.jemalloc(target)
1362        && target.starts_with("aarch64")
1363        && env::var_os("JEMALLOC_SYS_WITH_LG_PAGE").is_none()
1364    {
1365        cargo.env("JEMALLOC_SYS_WITH_LG_PAGE", "16");
1366    }
1367}
1368
1369/// Pass down configuration from the LLVM build into the build of
1370/// rustc_llvm and rustc_codegen_llvm.
1371fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
1372    if builder.config.is_rust_llvm(target) {
1373        cargo.env("LLVM_RUSTLLVM", "1");
1374    }
1375    if builder.config.llvm_enzyme {
1376        cargo.env("LLVM_ENZYME", "1");
1377    }
1378    let llvm::LlvmResult { llvm_config, .. } = builder.ensure(llvm::Llvm { target });
1379    cargo.env("LLVM_CONFIG", &llvm_config);
1380
1381    // Some LLVM linker flags (-L and -l) may be needed to link `rustc_llvm`. Its build script
1382    // expects these to be passed via the `LLVM_LINKER_FLAGS` env variable, separated by
1383    // whitespace.
1384    //
1385    // For example:
1386    // - on windows, when `clang-cl` is used with instrumentation, we need to manually add
1387    // clang's runtime library resource directory so that the profiler runtime library can be
1388    // found. This is to avoid the linker errors about undefined references to
1389    // `__llvm_profile_instrument_memop` when linking `rustc_driver`.
1390    let mut llvm_linker_flags = String::new();
1391    if builder.config.llvm_profile_generate && target.is_msvc() {
1392        if let Some(ref clang_cl_path) = builder.config.llvm_clang_cl {
1393            // Add clang's runtime library directory to the search path
1394            let clang_rt_dir = get_clang_cl_resource_dir(builder, clang_cl_path);
1395            llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
1396        }
1397    }
1398
1399    // The config can also specify its own llvm linker flags.
1400    if let Some(ref s) = builder.config.llvm_ldflags {
1401        if !llvm_linker_flags.is_empty() {
1402            llvm_linker_flags.push(' ');
1403        }
1404        llvm_linker_flags.push_str(s);
1405    }
1406
1407    // Set the linker flags via the env var that `rustc_llvm`'s build script will read.
1408    if !llvm_linker_flags.is_empty() {
1409        cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
1410    }
1411
1412    // Building with a static libstdc++ is only supported on linux right now,
1413    // not for MSVC or macOS
1414    if builder.config.llvm_static_stdcpp
1415        && !target.contains("freebsd")
1416        && !target.is_msvc()
1417        && !target.contains("apple")
1418        && !target.contains("solaris")
1419    {
1420        let file = compiler_file(
1421            builder,
1422            &builder.cxx(target).unwrap(),
1423            target,
1424            CLang::Cxx,
1425            "libstdc++.a",
1426        );
1427        cargo.env("LLVM_STATIC_STDCPP", file);
1428    }
1429    if builder.llvm_link_shared() {
1430        cargo.env("LLVM_LINK_SHARED", "1");
1431    }
1432    if builder.config.llvm_use_libcxx {
1433        cargo.env("LLVM_USE_LIBCXX", "1");
1434    }
1435    if builder.config.llvm_assertions {
1436        cargo.env("LLVM_ASSERTIONS", "1");
1437    }
1438}
1439
1440/// `RustcLink` copies all of the rlibs from the rustc build into the previous stage's sysroot.
1441/// This is necessary for tools using `rustc_private`, where the previous compiler will build
1442/// a tool against the next compiler.
1443/// To build a tool against a compiler, the rlibs of that compiler that it links against
1444/// must be in the sysroot of the compiler that's doing the compiling.
1445#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1446struct RustcLink {
1447    /// The compiler whose rlibs we are copying around.
1448    pub compiler: Compiler,
1449    /// This is the compiler into whose sysroot we want to copy the rlibs into.
1450    pub previous_stage_compiler: Compiler,
1451    pub target: TargetSelection,
1452    /// Not actually used; only present to make sure the cache invalidation is correct.
1453    crates: Vec<String>,
1454}
1455
1456impl RustcLink {
1457    fn from_rustc(rustc: Rustc, host_compiler: Compiler) -> Self {
1458        Self {
1459            compiler: host_compiler,
1460            previous_stage_compiler: rustc.compiler,
1461            target: rustc.target,
1462            crates: rustc.crates,
1463        }
1464    }
1465}
1466
1467impl Step for RustcLink {
1468    type Output = ();
1469
1470    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1471        run.never()
1472    }
1473
1474    /// Same as `std_link`, only for librustc
1475    #[cfg_attr(
1476        feature = "tracing",
1477        instrument(
1478            level = "trace",
1479            name = "RustcLink::run",
1480            skip_all,
1481            fields(
1482                compiler = ?self.compiler,
1483                previous_stage_compiler = ?self.previous_stage_compiler,
1484                target = ?self.target,
1485            ),
1486        ),
1487    )]
1488    fn run(self, builder: &Builder<'_>) {
1489        let compiler = self.compiler;
1490        let previous_stage_compiler = self.previous_stage_compiler;
1491        let target = self.target;
1492        add_to_sysroot(
1493            builder,
1494            &builder.sysroot_target_libdir(previous_stage_compiler, target),
1495            &builder.sysroot_target_libdir(previous_stage_compiler, compiler.host),
1496            &build_stamp::librustc_stamp(builder, compiler, target),
1497        );
1498    }
1499}
1500
1501#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1502pub struct CodegenBackend {
1503    pub target: TargetSelection,
1504    pub compiler: Compiler,
1505    pub backend: String,
1506}
1507
1508fn needs_codegen_config(run: &RunConfig<'_>) -> bool {
1509    let mut needs_codegen_cfg = false;
1510    for path_set in &run.paths {
1511        needs_codegen_cfg = match path_set {
1512            PathSet::Set(set) => set.iter().any(|p| is_codegen_cfg_needed(p, run)),
1513            PathSet::Suite(suite) => is_codegen_cfg_needed(suite, run),
1514        }
1515    }
1516    needs_codegen_cfg
1517}
1518
1519pub(crate) const CODEGEN_BACKEND_PREFIX: &str = "rustc_codegen_";
1520
1521fn is_codegen_cfg_needed(path: &TaskPath, run: &RunConfig<'_>) -> bool {
1522    let path = path.path.to_str().unwrap();
1523
1524    let is_explicitly_called = |p| -> bool { run.builder.paths.contains(p) };
1525    let should_enforce = run.builder.kind == Kind::Dist || run.builder.kind == Kind::Install;
1526
1527    if path.contains(CODEGEN_BACKEND_PREFIX) {
1528        let mut needs_codegen_backend_config = true;
1529        for backend in run.builder.config.codegen_backends(run.target) {
1530            if path.ends_with(&(CODEGEN_BACKEND_PREFIX.to_owned() + backend)) {
1531                needs_codegen_backend_config = false;
1532            }
1533        }
1534        if (is_explicitly_called(&PathBuf::from(path)) || should_enforce)
1535            && needs_codegen_backend_config
1536        {
1537            run.builder.info(
1538                "WARNING: no codegen-backends config matched the requested path to build a codegen backend. \
1539                HELP: add backend to codegen-backends in bootstrap.toml.",
1540            );
1541            return true;
1542        }
1543    }
1544
1545    false
1546}
1547
1548impl Step for CodegenBackend {
1549    type Output = ();
1550    const ONLY_HOSTS: bool = true;
1551    /// Only the backends specified in the `codegen-backends` entry of `bootstrap.toml` are built.
1552    const DEFAULT: bool = true;
1553
1554    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1555        run.paths(&["compiler/rustc_codegen_cranelift", "compiler/rustc_codegen_gcc"])
1556    }
1557
1558    fn make_run(run: RunConfig<'_>) {
1559        if needs_codegen_config(&run) {
1560            return;
1561        }
1562
1563        for backend in run.builder.config.codegen_backends(run.target) {
1564            if backend == "llvm" {
1565                continue; // Already built as part of rustc
1566            }
1567
1568            run.builder.ensure(CodegenBackend {
1569                target: run.target,
1570                compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
1571                backend: backend.clone(),
1572            });
1573        }
1574    }
1575
1576    #[cfg_attr(
1577        feature = "tracing",
1578        instrument(
1579            level = "debug",
1580            name = "CodegenBackend::run",
1581            skip_all,
1582            fields(
1583                compiler = ?self.compiler,
1584                target = ?self.target,
1585                backend = ?self.target,
1586            ),
1587        ),
1588    )]
1589    fn run(self, builder: &Builder<'_>) {
1590        let compiler = self.compiler;
1591        let target = self.target;
1592        let backend = self.backend;
1593
1594        builder.ensure(Rustc::new(compiler, target));
1595
1596        if builder.config.keep_stage.contains(&compiler.stage) {
1597            trace!("`keep-stage` requested");
1598            builder.info(
1599                "WARNING: Using a potentially old codegen backend. \
1600                This may not behave well.",
1601            );
1602            // Codegen backends are linked separately from this step today, so we don't do
1603            // anything here.
1604            return;
1605        }
1606
1607        let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
1608        if compiler_to_use != compiler {
1609            builder.ensure(CodegenBackend { compiler: compiler_to_use, target, backend });
1610            return;
1611        }
1612
1613        let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
1614
1615        let mut cargo = builder::Cargo::new(
1616            builder,
1617            compiler,
1618            Mode::Codegen,
1619            SourceType::InTree,
1620            target,
1621            Kind::Build,
1622        );
1623        cargo
1624            .arg("--manifest-path")
1625            .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml")));
1626        rustc_cargo_env(builder, &mut cargo, target, compiler.stage);
1627
1628        // Ideally, we'd have a separate step for the individual codegen backends,
1629        // like we have in tests (test::CodegenGCC) but that would require a lot of restructuring.
1630        // If the logic gets more complicated, it should probably be done.
1631        if backend == "gcc" {
1632            let gcc = builder.ensure(Gcc { target });
1633            add_cg_gcc_cargo_flags(&mut cargo, &gcc);
1634        }
1635
1636        let tmp_stamp = BuildStamp::new(&out_dir).with_prefix("tmp");
1637
1638        let _guard = builder.msg_build(compiler, format_args!("codegen backend {backend}"), target);
1639        let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false, false);
1640        if builder.config.dry_run() {
1641            return;
1642        }
1643        let mut files = files.into_iter().filter(|f| {
1644            let filename = f.file_name().unwrap().to_str().unwrap();
1645            is_dylib(f) && filename.contains("rustc_codegen_")
1646        });
1647        let codegen_backend = match files.next() {
1648            Some(f) => f,
1649            None => panic!("no dylibs built for codegen backend?"),
1650        };
1651        if let Some(f) = files.next() {
1652            panic!(
1653                "codegen backend built two dylibs:\n{}\n{}",
1654                codegen_backend.display(),
1655                f.display()
1656            );
1657        }
1658        let stamp = build_stamp::codegen_backend_stamp(builder, compiler, target, &backend);
1659        let codegen_backend = codegen_backend.to_str().unwrap();
1660        t!(stamp.add_stamp(codegen_backend).write());
1661    }
1662}
1663
1664/// Creates the `codegen-backends` folder for a compiler that's about to be
1665/// assembled as a complete compiler.
1666///
1667/// This will take the codegen artifacts produced by `compiler` and link them
1668/// into an appropriate location for `target_compiler` to be a functional
1669/// compiler.
1670fn copy_codegen_backends_to_sysroot(
1671    builder: &Builder<'_>,
1672    compiler: Compiler,
1673    target_compiler: Compiler,
1674) {
1675    let target = target_compiler.host;
1676
1677    // Note that this step is different than all the other `*Link` steps in
1678    // that it's not assembling a bunch of libraries but rather is primarily
1679    // moving the codegen backend into place. The codegen backend of rustc is
1680    // not linked into the main compiler by default but is rather dynamically
1681    // selected at runtime for inclusion.
1682    //
1683    // Here we're looking for the output dylib of the `CodegenBackend` step and
1684    // we're copying that into the `codegen-backends` folder.
1685    let dst = builder.sysroot_codegen_backends(target_compiler);
1686    t!(fs::create_dir_all(&dst), dst);
1687
1688    if builder.config.dry_run() {
1689        return;
1690    }
1691
1692    for backend in builder.config.codegen_backends(target) {
1693        if backend == "llvm" {
1694            continue; // Already built as part of rustc
1695        }
1696
1697        let stamp = build_stamp::codegen_backend_stamp(builder, compiler, target, backend);
1698        let dylib = t!(fs::read_to_string(stamp.path()));
1699        let file = Path::new(&dylib);
1700        let filename = file.file_name().unwrap().to_str().unwrap();
1701        // change `librustc_codegen_cranelift-xxxxxx.so` to
1702        // `librustc_codegen_cranelift-release.so`
1703        let target_filename = {
1704            let dash = filename.find('-').unwrap();
1705            let dot = filename.find('.').unwrap();
1706            format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1707        };
1708        builder.copy_link(file, &dst.join(target_filename), FileType::NativeLibrary);
1709    }
1710}
1711
1712pub fn compiler_file(
1713    builder: &Builder<'_>,
1714    compiler: &Path,
1715    target: TargetSelection,
1716    c: CLang,
1717    file: &str,
1718) -> PathBuf {
1719    if builder.config.dry_run() {
1720        return PathBuf::new();
1721    }
1722    let mut cmd = command(compiler);
1723    cmd.args(builder.cc_handled_clags(target, c));
1724    cmd.args(builder.cc_unhandled_cflags(target, GitRepo::Rustc, c));
1725    cmd.arg(format!("-print-file-name={file}"));
1726    let out = cmd.run_capture_stdout(builder).stdout();
1727    PathBuf::from(out.trim())
1728}
1729
1730#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1731pub struct Sysroot {
1732    pub compiler: Compiler,
1733    /// See [`Std::force_recompile`].
1734    force_recompile: bool,
1735}
1736
1737impl Sysroot {
1738    pub(crate) fn new(compiler: Compiler) -> Self {
1739        Sysroot { compiler, force_recompile: false }
1740    }
1741}
1742
1743impl Step for Sysroot {
1744    type Output = PathBuf;
1745
1746    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1747        run.never()
1748    }
1749
1750    /// Returns the sysroot that `compiler` is supposed to use.
1751    /// For the stage0 compiler, this is stage0-sysroot (because of the initial std build).
1752    /// For all other stages, it's the same stage directory that the compiler lives in.
1753    #[cfg_attr(
1754        feature = "tracing",
1755        instrument(
1756            level = "debug",
1757            name = "Sysroot::run",
1758            skip_all,
1759            fields(compiler = ?self.compiler),
1760        ),
1761    )]
1762    fn run(self, builder: &Builder<'_>) -> PathBuf {
1763        let compiler = self.compiler;
1764        let host_dir = builder.out.join(compiler.host);
1765
1766        let sysroot_dir = |stage| {
1767            if stage == 0 {
1768                host_dir.join("stage0-sysroot")
1769            } else if self.force_recompile && stage == compiler.stage {
1770                host_dir.join(format!("stage{stage}-test-sysroot"))
1771            } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1772                host_dir.join("ci-rustc-sysroot")
1773            } else {
1774                host_dir.join(format!("stage{}", stage))
1775            }
1776        };
1777        let sysroot = sysroot_dir(compiler.stage);
1778        trace!(stage = ?compiler.stage, ?sysroot);
1779
1780        builder
1781            .verbose(|| println!("Removing sysroot {} to avoid caching bugs", sysroot.display()));
1782        let _ = fs::remove_dir_all(&sysroot);
1783        t!(fs::create_dir_all(&sysroot));
1784
1785        // In some cases(see https://github.com/rust-lang/rust/issues/109314), when the stage0
1786        // compiler relies on more recent version of LLVM than the beta compiler, it may not
1787        // be able to locate the correct LLVM in the sysroot. This situation typically occurs
1788        // when we upgrade LLVM version while the beta compiler continues to use an older version.
1789        //
1790        // Make sure to add the correct version of LLVM into the stage0 sysroot.
1791        if compiler.stage == 0 {
1792            dist::maybe_install_llvm_target(builder, compiler.host, &sysroot);
1793        }
1794
1795        // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0.
1796        if builder.download_rustc() && compiler.stage != 0 {
1797            assert_eq!(
1798                builder.config.build, compiler.host,
1799                "Cross-compiling is not yet supported with `download-rustc`",
1800            );
1801
1802            // #102002, cleanup old toolchain folders when using download-rustc so people don't use them by accident.
1803            for stage in 0..=2 {
1804                if stage != compiler.stage {
1805                    let dir = sysroot_dir(stage);
1806                    if !dir.ends_with("ci-rustc-sysroot") {
1807                        let _ = fs::remove_dir_all(dir);
1808                    }
1809                }
1810            }
1811
1812            // Copy the compiler into the correct sysroot.
1813            // NOTE(#108767): We intentionally don't copy `rustc-dev` artifacts until they're requested with `builder.ensure(Rustc)`.
1814            // This fixes an issue where we'd have multiple copies of libc in the sysroot with no way to tell which to load.
1815            // There are a few quirks of bootstrap that interact to make this reliable:
1816            // 1. The order `Step`s are run is hard-coded in `builder.rs` and not configurable. This
1817            //    avoids e.g. reordering `test::UiFulldeps` before `test::Ui` and causing the latter to
1818            //    fail because of duplicate metadata.
1819            // 2. The sysroot is deleted and recreated between each invocation, so running `x test
1820            //    ui-fulldeps && x test ui` can't cause failures.
1821            let mut filtered_files = Vec::new();
1822            let mut add_filtered_files = |suffix, contents| {
1823                for path in contents {
1824                    let path = Path::new(&path);
1825                    if path.parent().is_some_and(|parent| parent.ends_with(suffix)) {
1826                        filtered_files.push(path.file_name().unwrap().to_owned());
1827                    }
1828                }
1829            };
1830            let suffix = format!("lib/rustlib/{}/lib", compiler.host);
1831            add_filtered_files(suffix.as_str(), builder.config.ci_rustc_dev_contents());
1832            // NOTE: we can't copy std eagerly because `stage2-test-sysroot` needs to have only the
1833            // newly compiled std, not the downloaded std.
1834            add_filtered_files("lib", builder.config.ci_rust_std_contents());
1835
1836            let filtered_extensions = [
1837                OsStr::new("rmeta"),
1838                OsStr::new("rlib"),
1839                // FIXME: this is wrong when compiler.host != build, but we don't support that today
1840                OsStr::new(std::env::consts::DLL_EXTENSION),
1841            ];
1842            let ci_rustc_dir = builder.config.ci_rustc_dir();
1843            builder.cp_link_filtered(&ci_rustc_dir, &sysroot, &|path| {
1844                if path.extension().is_none_or(|ext| !filtered_extensions.contains(&ext)) {
1845                    return true;
1846                }
1847                if !path.parent().is_none_or(|p| p.ends_with(&suffix)) {
1848                    return true;
1849                }
1850                if !filtered_files.iter().all(|f| f != path.file_name().unwrap()) {
1851                    builder.verbose_than(1, || println!("ignoring {}", path.display()));
1852                    false
1853                } else {
1854                    true
1855                }
1856            });
1857        }
1858
1859        // Symlink the source root into the same location inside the sysroot,
1860        // where `rust-src` component would go (`$sysroot/lib/rustlib/src/rust`),
1861        // so that any tools relying on `rust-src` also work for local builds,
1862        // and also for translating the virtual `/rustc/$hash` back to the real
1863        // directory (for running tests with `rust.remap-debuginfo = true`).
1864        let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
1865        t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
1866        let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
1867        if let Err(e) = symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust) {
1868            eprintln!(
1869                "ERROR: creating symbolic link `{}` to `{}` failed with {}",
1870                sysroot_lib_rustlib_src_rust.display(),
1871                builder.src.display(),
1872                e,
1873            );
1874            if builder.config.rust_remap_debuginfo {
1875                eprintln!(
1876                    "ERROR: some `tests/ui` tests will fail when lacking `{}`",
1877                    sysroot_lib_rustlib_src_rust.display(),
1878                );
1879            }
1880            build_helper::exit!(1);
1881        }
1882
1883        // rustc-src component is already part of CI rustc's sysroot
1884        if !builder.download_rustc() {
1885            let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
1886            t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
1887            let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
1888            if let Err(e) =
1889                symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
1890            {
1891                eprintln!(
1892                    "ERROR: creating symbolic link `{}` to `{}` failed with {}",
1893                    sysroot_lib_rustlib_rustcsrc_rust.display(),
1894                    builder.src.display(),
1895                    e,
1896                );
1897                build_helper::exit!(1);
1898            }
1899        }
1900
1901        sysroot
1902    }
1903}
1904
1905#[derive(Debug, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
1906pub struct Assemble {
1907    /// The compiler which we will produce in this step. Assemble itself will
1908    /// take care of ensuring that the necessary prerequisites to do so exist,
1909    /// that is, this target can be a stage2 compiler and Assemble will build
1910    /// previous stages for you.
1911    pub target_compiler: Compiler,
1912}
1913
1914impl Step for Assemble {
1915    type Output = Compiler;
1916    const ONLY_HOSTS: bool = true;
1917
1918    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1919        run.path("compiler/rustc").path("compiler")
1920    }
1921
1922    fn make_run(run: RunConfig<'_>) {
1923        run.builder.ensure(Assemble {
1924            target_compiler: run.builder.compiler(run.builder.top_stage, run.target),
1925        });
1926    }
1927
1928    /// Prepare a new compiler from the artifacts in `stage`
1929    ///
1930    /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
1931    /// must have been previously produced by the `stage - 1` builder.build
1932    /// compiler.
1933    #[cfg_attr(
1934        feature = "tracing",
1935        instrument(
1936            level = "debug",
1937            name = "Assemble::run",
1938            skip_all,
1939            fields(target_compiler = ?self.target_compiler),
1940        ),
1941    )]
1942    fn run(self, builder: &Builder<'_>) -> Compiler {
1943        let target_compiler = self.target_compiler;
1944
1945        if target_compiler.stage == 0 {
1946            trace!("stage 0 build compiler is always available, simply returning");
1947            assert_eq!(
1948                builder.config.build, target_compiler.host,
1949                "Cannot obtain compiler for non-native build triple at stage 0"
1950            );
1951            // The stage 0 compiler for the build triple is always pre-built.
1952            return target_compiler;
1953        }
1954
1955        // We prepend this bin directory to the user PATH when linking Rust binaries. To
1956        // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
1957        let libdir = builder.sysroot_target_libdir(target_compiler, target_compiler.host);
1958        let libdir_bin = libdir.parent().unwrap().join("bin");
1959        t!(fs::create_dir_all(&libdir_bin));
1960
1961        if builder.config.llvm_enabled(target_compiler.host) {
1962            trace!("target_compiler.host" = ?target_compiler.host, "LLVM enabled");
1963
1964            let llvm::LlvmResult { llvm_config, .. } =
1965                builder.ensure(llvm::Llvm { target: target_compiler.host });
1966            if !builder.config.dry_run() && builder.config.llvm_tools_enabled {
1967                trace!("LLVM tools enabled");
1968
1969                let llvm_bin_dir =
1970                    command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout();
1971                let llvm_bin_dir = Path::new(llvm_bin_dir.trim());
1972
1973                // Since we've already built the LLVM tools, install them to the sysroot.
1974                // This is the equivalent of installing the `llvm-tools-preview` component via
1975                // rustup, and lets developers use a locally built toolchain to
1976                // build projects that expect llvm tools to be present in the sysroot
1977                // (e.g. the `bootimage` crate).
1978
1979                #[cfg(feature = "tracing")]
1980                let _llvm_tools_span =
1981                    span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
1982                        .entered();
1983                for tool in LLVM_TOOLS {
1984                    trace!("installing `{tool}`");
1985                    let tool_exe = exe(tool, target_compiler.host);
1986                    let src_path = llvm_bin_dir.join(&tool_exe);
1987                    // When using `download-ci-llvm`, some of the tools
1988                    // may not exist, so skip trying to copy them.
1989                    if src_path.exists() {
1990                        // There is a chance that these tools are being installed from an external LLVM.
1991                        // Use `Builder::resolve_symlink_and_copy` instead of `Builder::copy_link` to ensure
1992                        // we are copying the original file not the symlinked path, which causes issues for
1993                        // tarball distribution.
1994                        //
1995                        // See https://github.com/rust-lang/rust/issues/135554.
1996                        builder.resolve_symlink_and_copy(&src_path, &libdir_bin.join(&tool_exe));
1997                    }
1998                }
1999            }
2000        }
2001
2002        let maybe_install_llvm_bitcode_linker = |compiler| {
2003            if builder.config.llvm_bitcode_linker_enabled {
2004                trace!("llvm-bitcode-linker enabled, installing");
2005                let llvm_bitcode_linker =
2006                    builder.ensure(crate::core::build_steps::tool::LlvmBitcodeLinker {
2007                        compiler,
2008                        target: target_compiler.host,
2009                        extra_features: vec![],
2010                    });
2011                let tool_exe = exe("llvm-bitcode-linker", target_compiler.host);
2012                builder.copy_link(
2013                    &llvm_bitcode_linker.tool_path,
2014                    &libdir_bin.join(tool_exe),
2015                    FileType::Executable,
2016                );
2017            }
2018        };
2019
2020        // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0.
2021        if builder.download_rustc() {
2022            trace!("`download-rustc` requested, reusing CI compiler for stage > 0");
2023
2024            builder.ensure(Std::new(target_compiler, target_compiler.host));
2025            let sysroot =
2026                builder.ensure(Sysroot { compiler: target_compiler, force_recompile: false });
2027            // Ensure that `libLLVM.so` ends up in the newly created target directory,
2028            // so that tools using `rustc_private` can use it.
2029            dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2030            // Lower stages use `ci-rustc-sysroot`, not stageN
2031            if target_compiler.stage == builder.top_stage {
2032                builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage=target_compiler.stage));
2033            }
2034
2035            let mut precompiled_compiler = target_compiler;
2036            precompiled_compiler.forced_compiler(true);
2037            maybe_install_llvm_bitcode_linker(precompiled_compiler);
2038
2039            return target_compiler;
2040        }
2041
2042        // Get the compiler that we'll use to bootstrap ourselves.
2043        //
2044        // Note that this is where the recursive nature of the bootstrap
2045        // happens, as this will request the previous stage's compiler on
2046        // downwards to stage 0.
2047        //
2048        // Also note that we're building a compiler for the host platform. We
2049        // only assume that we can run `build` artifacts, which means that to
2050        // produce some other architecture compiler we need to start from
2051        // `build` to get there.
2052        //
2053        // FIXME: It may be faster if we build just a stage 1 compiler and then
2054        //        use that to bootstrap this compiler forward.
2055        debug!(
2056            "ensuring build compiler is available: compiler(stage = {}, host = {:?})",
2057            target_compiler.stage - 1,
2058            builder.config.build,
2059        );
2060        let mut build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
2061
2062        // Build enzyme
2063        if builder.config.llvm_enzyme && !builder.config.dry_run() {
2064            debug!("`llvm_enzyme` requested");
2065            let enzyme_install = builder.ensure(llvm::Enzyme { target: build_compiler.host });
2066            let llvm_config = builder.llvm_config(builder.config.build).unwrap();
2067            let llvm_version_major = llvm::get_llvm_version_major(builder, &llvm_config);
2068            let lib_ext = std::env::consts::DLL_EXTENSION;
2069            let libenzyme = format!("libEnzyme-{llvm_version_major}");
2070            let src_lib =
2071                enzyme_install.join("build/Enzyme").join(&libenzyme).with_extension(lib_ext);
2072            let libdir = builder.sysroot_target_libdir(build_compiler, build_compiler.host);
2073            let target_libdir =
2074                builder.sysroot_target_libdir(target_compiler, target_compiler.host);
2075            let dst_lib = libdir.join(&libenzyme).with_extension(lib_ext);
2076            let target_dst_lib = target_libdir.join(&libenzyme).with_extension(lib_ext);
2077            builder.copy_link(&src_lib, &dst_lib, FileType::NativeLibrary);
2078            builder.copy_link(&src_lib, &target_dst_lib, FileType::NativeLibrary);
2079        }
2080
2081        // Build the libraries for this compiler to link to (i.e., the libraries
2082        // it uses at runtime). NOTE: Crates the target compiler compiles don't
2083        // link to these. (FIXME: Is that correct? It seems to be correct most
2084        // of the time but I think we do link to these for stage2/bin compilers
2085        // when not performing a full bootstrap).
2086        debug!(
2087            ?build_compiler,
2088            "target_compiler.host" = ?target_compiler.host,
2089            "building compiler libraries to link to"
2090        );
2091        let actual_stage = builder.ensure(Rustc::new(build_compiler, target_compiler.host));
2092        // Current build_compiler.stage might be uplifted instead of being built; so update it
2093        // to not fail while linking the artifacts.
2094        debug!(
2095            "(old) build_compiler.stage" = build_compiler.stage,
2096            "(adjusted) build_compiler.stage" = actual_stage,
2097            "temporarily adjusting `build_compiler.stage` to account for uplifted libraries"
2098        );
2099        build_compiler.stage = actual_stage;
2100
2101        #[cfg(feature = "tracing")]
2102        let _codegen_backend_span =
2103            span!(tracing::Level::DEBUG, "building requested codegen backends").entered();
2104        for backend in builder.config.codegen_backends(target_compiler.host) {
2105            if backend == "llvm" {
2106                debug!("llvm codegen backend is already built as part of rustc");
2107                continue; // Already built as part of rustc
2108            }
2109
2110            builder.ensure(CodegenBackend {
2111                compiler: build_compiler,
2112                target: target_compiler.host,
2113                backend: backend.clone(),
2114            });
2115        }
2116        #[cfg(feature = "tracing")]
2117        drop(_codegen_backend_span);
2118
2119        let stage = target_compiler.stage;
2120        let host = target_compiler.host;
2121        let (host_info, dir_name) = if build_compiler.host == host {
2122            ("".into(), "host".into())
2123        } else {
2124            (format!(" ({host})"), host.to_string())
2125        };
2126        // NOTE: "Creating a sysroot" is somewhat inconsistent with our internal terminology, since
2127        // sysroots can temporarily be empty until we put the compiler inside. However,
2128        // `ensure(Sysroot)` isn't really something that's user facing, so there shouldn't be any
2129        // ambiguity.
2130        let msg = format!(
2131            "Creating a sysroot for stage{stage} compiler{host_info} (use `rustup toolchain link 'name' build/{dir_name}/stage{stage}`)"
2132        );
2133        builder.info(&msg);
2134
2135        // Link in all dylibs to the libdir
2136        let stamp = build_stamp::librustc_stamp(builder, build_compiler, target_compiler.host);
2137        let proc_macros = builder
2138            .read_stamp_file(&stamp)
2139            .into_iter()
2140            .filter_map(|(path, dependency_type)| {
2141                if dependency_type == DependencyType::Host {
2142                    Some(path.file_name().unwrap().to_owned().into_string().unwrap())
2143                } else {
2144                    None
2145                }
2146            })
2147            .collect::<HashSet<_>>();
2148
2149        let sysroot = builder.sysroot(target_compiler);
2150        let rustc_libdir = builder.rustc_libdir(target_compiler);
2151        t!(fs::create_dir_all(&rustc_libdir));
2152        let src_libdir = builder.sysroot_target_libdir(build_compiler, host);
2153        for f in builder.read_dir(&src_libdir) {
2154            let filename = f.file_name().into_string().unwrap();
2155
2156            let is_proc_macro = proc_macros.contains(&filename);
2157            let is_dylib_or_debug = is_dylib(&f.path()) || is_debug_info(&filename);
2158
2159            // If we link statically to stdlib, do not copy the libstd dynamic library file
2160            // FIXME: Also do this for Windows once incremental post-optimization stage0 tests
2161            // work without std.dll (see https://github.com/rust-lang/rust/pull/131188).
2162            let can_be_rustc_dynamic_dep = if builder
2163                .link_std_into_rustc_driver(target_compiler.host)
2164                && !target_compiler.host.is_windows()
2165            {
2166                let is_std = filename.starts_with("std-") || filename.starts_with("libstd-");
2167                !is_std
2168            } else {
2169                true
2170            };
2171
2172            if is_dylib_or_debug && can_be_rustc_dynamic_dep && !is_proc_macro {
2173                builder.copy_link(&f.path(), &rustc_libdir.join(&filename), FileType::Regular);
2174            }
2175        }
2176
2177        debug!("copying codegen backends to sysroot");
2178        copy_codegen_backends_to_sysroot(builder, build_compiler, target_compiler);
2179
2180        if builder.config.lld_enabled && !builder.config.is_system_llvm(target_compiler.host) {
2181            builder.ensure(crate::core::build_steps::tool::LldWrapper {
2182                build_compiler,
2183                target_compiler,
2184            });
2185        }
2186
2187        if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled {
2188            debug!(
2189                "llvm and llvm tools enabled; copying `llvm-objcopy` as `rust-objcopy` to \
2190                workaround faulty homebrew `strip`s"
2191            );
2192
2193            // `llvm-strip` is used by rustc, which is actually just a symlink to `llvm-objcopy`, so
2194            // copy and rename `llvm-objcopy`.
2195            //
2196            // But only do so if llvm-tools are enabled, as bootstrap compiler might not contain any
2197            // LLVM tools, e.g. for cg_clif.
2198            // See <https://github.com/rust-lang/rust/issues/132719>.
2199            let src_exe = exe("llvm-objcopy", target_compiler.host);
2200            let dst_exe = exe("rust-objcopy", target_compiler.host);
2201            builder.copy_link(
2202                &libdir_bin.join(src_exe),
2203                &libdir_bin.join(dst_exe),
2204                FileType::Executable,
2205            );
2206        }
2207
2208        // In addition to `rust-lld` also install `wasm-component-ld` when
2209        // LLD is enabled. This is a relatively small binary that primarily
2210        // delegates to the `rust-lld` binary for linking and then runs
2211        // logic to create the final binary. This is used by the
2212        // `wasm32-wasip2` target of Rust.
2213        if builder.tool_enabled("wasm-component-ld") {
2214            let wasm_component = builder.ensure(crate::core::build_steps::tool::WasmComponentLd {
2215                compiler: build_compiler,
2216                target: target_compiler.host,
2217            });
2218            builder.copy_link(
2219                &wasm_component.tool_path,
2220                &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()),
2221                FileType::Executable,
2222            );
2223        }
2224
2225        maybe_install_llvm_bitcode_linker(target_compiler);
2226
2227        // Ensure that `libLLVM.so` ends up in the newly build compiler directory,
2228        // so that it can be found when the newly built `rustc` is run.
2229        debug!(
2230            "target_compiler.host" = ?target_compiler.host,
2231            ?sysroot,
2232            "ensuring availability of `libLLVM.so` in compiler directory"
2233        );
2234        dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
2235        dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
2236
2237        // Link the compiler binary itself into place
2238        let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
2239        let rustc = out_dir.join(exe("rustc-main", host));
2240        let bindir = sysroot.join("bin");
2241        t!(fs::create_dir_all(bindir));
2242        let compiler = builder.rustc(target_compiler);
2243        debug!(src = ?rustc, dst = ?compiler, "linking compiler binary itself");
2244        builder.copy_link(&rustc, &compiler, FileType::Executable);
2245
2246        target_compiler
2247    }
2248}
2249
2250/// Link some files into a rustc sysroot.
2251///
2252/// For a particular stage this will link the file listed in `stamp` into the
2253/// `sysroot_dst` provided.
2254pub fn add_to_sysroot(
2255    builder: &Builder<'_>,
2256    sysroot_dst: &Path,
2257    sysroot_host_dst: &Path,
2258    stamp: &BuildStamp,
2259) {
2260    let self_contained_dst = &sysroot_dst.join("self-contained");
2261    t!(fs::create_dir_all(sysroot_dst));
2262    t!(fs::create_dir_all(sysroot_host_dst));
2263    t!(fs::create_dir_all(self_contained_dst));
2264    for (path, dependency_type) in builder.read_stamp_file(stamp) {
2265        let dst = match dependency_type {
2266            DependencyType::Host => sysroot_host_dst,
2267            DependencyType::Target => sysroot_dst,
2268            DependencyType::TargetSelfContained => self_contained_dst,
2269        };
2270        builder.copy_link(&path, &dst.join(path.file_name().unwrap()), FileType::Regular);
2271    }
2272}
2273
2274pub fn run_cargo(
2275    builder: &Builder<'_>,
2276    cargo: Cargo,
2277    tail_args: Vec<String>,
2278    stamp: &BuildStamp,
2279    additional_target_deps: Vec<(PathBuf, DependencyType)>,
2280    is_check: bool,
2281    rlib_only_metadata: bool,
2282) -> Vec<PathBuf> {
2283    // `target_root_dir` looks like $dir/$target/release
2284    let target_root_dir = stamp.path().parent().unwrap();
2285    // `target_deps_dir` looks like $dir/$target/release/deps
2286    let target_deps_dir = target_root_dir.join("deps");
2287    // `host_root_dir` looks like $dir/release
2288    let host_root_dir = target_root_dir
2289        .parent()
2290        .unwrap() // chop off `release`
2291        .parent()
2292        .unwrap() // chop off `$target`
2293        .join(target_root_dir.file_name().unwrap());
2294
2295    // Spawn Cargo slurping up its JSON output. We'll start building up the
2296    // `deps` array of all files it generated along with a `toplevel` array of
2297    // files we need to probe for later.
2298    let mut deps = Vec::new();
2299    let mut toplevel = Vec::new();
2300    let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
2301        let (filenames, crate_types) = match msg {
2302            CargoMessage::CompilerArtifact {
2303                filenames,
2304                target: CargoTarget { crate_types },
2305                ..
2306            } => (filenames, crate_types),
2307            _ => return,
2308        };
2309        for filename in filenames {
2310            // Skip files like executables
2311            let mut keep = false;
2312            if filename.ends_with(".lib")
2313                || filename.ends_with(".a")
2314                || is_debug_info(&filename)
2315                || is_dylib(Path::new(&*filename))
2316            {
2317                // Always keep native libraries, rust dylibs and debuginfo
2318                keep = true;
2319            }
2320            if is_check && filename.ends_with(".rmeta") {
2321                // During check builds we need to keep crate metadata
2322                keep = true;
2323            } else if rlib_only_metadata {
2324                if filename.contains("jemalloc_sys")
2325                    || filename.contains("rustc_smir")
2326                    || filename.contains("stable_mir")
2327                {
2328                    // jemalloc_sys and rustc_smir are not linked into librustc_driver.so,
2329                    // so we need to distribute them as rlib to be able to use them.
2330                    keep |= filename.ends_with(".rlib");
2331                } else {
2332                    // Distribute the rest of the rustc crates as rmeta files only to reduce
2333                    // the tarball sizes by about 50%. The object files are linked into
2334                    // librustc_driver.so, so it is still possible to link against them.
2335                    keep |= filename.ends_with(".rmeta");
2336                }
2337            } else {
2338                // In all other cases keep all rlibs
2339                keep |= filename.ends_with(".rlib");
2340            }
2341
2342            if !keep {
2343                continue;
2344            }
2345
2346            let filename = Path::new(&*filename);
2347
2348            // If this was an output file in the "host dir" we don't actually
2349            // worry about it, it's not relevant for us
2350            if filename.starts_with(&host_root_dir) {
2351                // Unless it's a proc macro used in the compiler
2352                if crate_types.iter().any(|t| t == "proc-macro") {
2353                    deps.push((filename.to_path_buf(), DependencyType::Host));
2354                }
2355                continue;
2356            }
2357
2358            // If this was output in the `deps` dir then this is a precise file
2359            // name (hash included) so we start tracking it.
2360            if filename.starts_with(&target_deps_dir) {
2361                deps.push((filename.to_path_buf(), DependencyType::Target));
2362                continue;
2363            }
2364
2365            // Otherwise this was a "top level artifact" which right now doesn't
2366            // have a hash in the name, but there's a version of this file in
2367            // the `deps` folder which *does* have a hash in the name. That's
2368            // the one we'll want to we'll probe for it later.
2369            //
2370            // We do not use `Path::file_stem` or `Path::extension` here,
2371            // because some generated files may have multiple extensions e.g.
2372            // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
2373            // split the file name by the last extension (`.lib`) while we need
2374            // to split by all extensions (`.dll.lib`).
2375            let expected_len = t!(filename.metadata()).len();
2376            let filename = filename.file_name().unwrap().to_str().unwrap();
2377            let mut parts = filename.splitn(2, '.');
2378            let file_stem = parts.next().unwrap().to_owned();
2379            let extension = parts.next().unwrap().to_owned();
2380
2381            toplevel.push((file_stem, extension, expected_len));
2382        }
2383    });
2384
2385    if !ok {
2386        crate::exit!(1);
2387    }
2388
2389    if builder.config.dry_run() {
2390        return Vec::new();
2391    }
2392
2393    // Ok now we need to actually find all the files listed in `toplevel`. We've
2394    // got a list of prefix/extensions and we basically just need to find the
2395    // most recent file in the `deps` folder corresponding to each one.
2396    let contents = target_deps_dir
2397        .read_dir()
2398        .unwrap_or_else(|e| panic!("Couldn't read {}: {}", target_deps_dir.display(), e))
2399        .map(|e| t!(e))
2400        .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
2401        .collect::<Vec<_>>();
2402    for (prefix, extension, expected_len) in toplevel {
2403        let candidates = contents.iter().filter(|&(_, filename, meta)| {
2404            meta.len() == expected_len
2405                && filename
2406                    .strip_prefix(&prefix[..])
2407                    .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
2408                    .unwrap_or(false)
2409        });
2410        let max = candidates.max_by_key(|&(_, _, metadata)| {
2411            metadata.modified().expect("mtime should be available on all relevant OSes")
2412        });
2413        let path_to_add = match max {
2414            Some(triple) => triple.0.to_str().unwrap(),
2415            None => panic!("no output generated for {prefix:?} {extension:?}"),
2416        };
2417        if is_dylib(Path::new(path_to_add)) {
2418            let candidate = format!("{path_to_add}.lib");
2419            let candidate = PathBuf::from(candidate);
2420            if candidate.exists() {
2421                deps.push((candidate, DependencyType::Target));
2422            }
2423        }
2424        deps.push((path_to_add.into(), DependencyType::Target));
2425    }
2426
2427    deps.extend(additional_target_deps);
2428    deps.sort();
2429    let mut new_contents = Vec::new();
2430    for (dep, dependency_type) in deps.iter() {
2431        new_contents.extend(match *dependency_type {
2432            DependencyType::Host => b"h",
2433            DependencyType::Target => b"t",
2434            DependencyType::TargetSelfContained => b"s",
2435        });
2436        new_contents.extend(dep.to_str().unwrap().as_bytes());
2437        new_contents.extend(b"\0");
2438    }
2439    t!(fs::write(stamp.path(), &new_contents));
2440    deps.into_iter().map(|(d, _)| d).collect()
2441}
2442
2443pub fn stream_cargo(
2444    builder: &Builder<'_>,
2445    cargo: Cargo,
2446    tail_args: Vec<String>,
2447    cb: &mut dyn FnMut(CargoMessage<'_>),
2448) -> bool {
2449    let mut cmd = cargo.into_cmd();
2450
2451    #[cfg(feature = "tracing")]
2452    let _run_span = crate::trace_cmd!(cmd);
2453
2454    let cargo = cmd.as_command_mut();
2455    // Instruct Cargo to give us json messages on stdout, critically leaving
2456    // stderr as piped so we can get those pretty colors.
2457    let mut message_format = if builder.config.json_output {
2458        String::from("json")
2459    } else {
2460        String::from("json-render-diagnostics")
2461    };
2462    if let Some(s) = &builder.config.rustc_error_format {
2463        message_format.push_str(",json-diagnostic-");
2464        message_format.push_str(s);
2465    }
2466    cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
2467
2468    for arg in tail_args {
2469        cargo.arg(arg);
2470    }
2471
2472    builder.verbose(|| println!("running: {cargo:?}"));
2473
2474    if builder.config.dry_run() {
2475        return true;
2476    }
2477
2478    let mut child = match cargo.spawn() {
2479        Ok(child) => child,
2480        Err(e) => panic!("failed to execute command: {cargo:?}\nERROR: {e}"),
2481    };
2482
2483    // Spawn Cargo slurping up its JSON output. We'll start building up the
2484    // `deps` array of all files it generated along with a `toplevel` array of
2485    // files we need to probe for later.
2486    let stdout = BufReader::new(child.stdout.take().unwrap());
2487    for line in stdout.lines() {
2488        let line = t!(line);
2489        match serde_json::from_str::<CargoMessage<'_>>(&line) {
2490            Ok(msg) => {
2491                if builder.config.json_output {
2492                    // Forward JSON to stdout.
2493                    println!("{line}");
2494                }
2495                cb(msg)
2496            }
2497            // If this was informational, just print it out and continue
2498            Err(_) => println!("{line}"),
2499        }
2500    }
2501
2502    // Make sure Cargo actually succeeded after we read all of its stdout.
2503    let status = t!(child.wait());
2504    if builder.is_verbose() && !status.success() {
2505        eprintln!(
2506            "command did not execute successfully: {cargo:?}\n\
2507                  expected success, got: {status}"
2508        );
2509    }
2510    status.success()
2511}
2512
2513#[derive(Deserialize)]
2514pub struct CargoTarget<'a> {
2515    crate_types: Vec<Cow<'a, str>>,
2516}
2517
2518#[derive(Deserialize)]
2519#[serde(tag = "reason", rename_all = "kebab-case")]
2520pub enum CargoMessage<'a> {
2521    CompilerArtifact { filenames: Vec<Cow<'a, str>>, target: CargoTarget<'a> },
2522    BuildScriptExecuted,
2523    BuildFinished,
2524}
2525
2526pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) {
2527    // FIXME: to make things simpler for now, limit this to the host and target where we know
2528    // `strip -g` is both available and will fix the issue, i.e. on a x64 linux host that is not
2529    // cross-compiling. Expand this to other appropriate targets in the future.
2530    if target != "x86_64-unknown-linux-gnu"
2531        || !builder.config.is_host_target(target)
2532        || !path.exists()
2533    {
2534        return;
2535    }
2536
2537    let previous_mtime = t!(t!(path.metadata()).modified());
2538    command("strip").arg("--strip-debug").arg(path).run_capture(builder);
2539
2540    let file = t!(fs::File::open(path));
2541
2542    // After running `strip`, we have to set the file modification time to what it was before,
2543    // otherwise we risk Cargo invalidating its fingerprint and rebuilding the world next time
2544    // bootstrap is invoked.
2545    //
2546    // An example of this is if we run this on librustc_driver.so. In the first invocation:
2547    // - Cargo will build librustc_driver.so (mtime of 1)
2548    // - Cargo will build rustc-main (mtime of 2)
2549    // - Bootstrap will strip librustc_driver.so (changing the mtime to 3).
2550    //
2551    // In the second invocation of bootstrap, Cargo will see that the mtime of librustc_driver.so
2552    // is greater than the mtime of rustc-main, and will rebuild rustc-main. That will then cause
2553    // everything else (standard library, future stages...) to be rebuilt.
2554    t!(file.set_modified(previous_mtime));
2555}
2556
2557/// We only use LTO for stage 2+, to speed up build time of intermediate stages.
2558pub fn is_lto_stage(build_compiler: &Compiler) -> bool {
2559    build_compiler.stage != 0
2560}