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