Skip to main content

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