1 //! Implementation of compiling various phases of the compiler and standard
4 //! This module contains some of the real meat in the rustbuild 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.
10 use std::collections::HashSet;
13 use std::io::prelude::*;
14 use std::io::BufReader;
15 use std::path::{Path, PathBuf};
16 use std::process::{Command, Stdio};
19 use serde::Deserialize;
21 use crate::builder::Cargo;
22 use crate::builder::{Builder, Kind, RunConfig, ShouldRun, Step};
23 use crate::cache::{Interned, INTERNER};
24 use crate::config::{LlvmLibunwind, RustcLto, TargetSelection};
27 use crate::tool::SourceType;
28 use crate::util::get_clang_cl_resource_dir;
29 use crate::util::{exe, is_debug_info, is_dylib, output, symlink_dir, t, up_to_date};
30 use crate::LLVM_TOOLS;
31 use crate::{CLang, Compiler, DependencyType, GitRepo, Mode};
33 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
35 pub target: TargetSelection,
36 pub compiler: Compiler,
37 /// Whether to build only a subset of crates in the standard library.
39 /// This shouldn't be used from other steps; see the comment on [`Rustc`].
40 crates: Interned<Vec<String>>,
44 pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
45 Self { target, compiler, crates: Default::default() }
51 const DEFAULT: bool = true;
53 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
54 // When downloading stage1, the standard library has already been copied to the sysroot, so
55 // there's no need to rebuild it.
56 let builder = run.builder;
57 run.crate_or_deps("test")
59 .lazy_default_condition(Box::new(|| !builder.download_rustc()))
62 fn make_run(run: RunConfig<'_>) {
63 // Normally, people will pass *just* library if they pass it.
64 // But it's possible (although strange) to pass something like `library std core`.
65 // Build all crates anyway, as if they hadn't passed the other args.
67 run.paths.iter().any(|set| set.assert_single_path().path.ends_with("library"));
68 let crates = if has_library { Default::default() } else { run.cargo_crates_in_set() };
69 run.builder.ensure(Std {
70 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
76 /// Builds the standard library.
78 /// This will build the standard library for a particular stage of the build
79 /// using the `compiler` targeting the `target` architecture. The artifacts
80 /// created will also be linked into the sysroot directory.
81 fn run(self, builder: &Builder<'_>) {
82 let target = self.target;
83 let compiler = self.compiler;
85 // These artifacts were already copied (in `impl Step for Sysroot`).
86 // Don't recompile them.
87 // NOTE: the ABI of the beta compiler is different from the ABI of the downloaded compiler,
88 // so its artifacts can't be reused.
89 if builder.download_rustc() && compiler.stage != 0 {
93 if builder.config.keep_stage.contains(&compiler.stage)
94 || builder.config.keep_stage_std.contains(&compiler.stage)
96 builder.info("Warning: Using a potentially old libstd. This may not behave well.");
97 builder.ensure(StdLink::from_std(self, compiler));
101 builder.update_submodule(&Path::new("library").join("stdarch"));
103 // Profiler information requires LLVM's compiler-rt
104 if builder.config.profiler {
105 builder.update_submodule(&Path::new("src/llvm-project"));
108 let mut target_deps = builder.ensure(StartupObjects { compiler, target });
110 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
111 if compiler_to_use != compiler {
112 builder.ensure(Std::new(compiler_to_use, target));
113 builder.info(&format!("Uplifting stage1 std ({} -> {})", compiler_to_use.host, target));
115 // Even if we're not building std this stage, the new sysroot must
116 // still contain the third party objects needed by various targets.
117 copy_third_party_objects(builder, &compiler, target);
118 copy_self_contained_objects(builder, &compiler, target);
120 builder.ensure(StdLink::from_std(self, compiler_to_use));
124 target_deps.extend(copy_third_party_objects(builder, &compiler, target));
125 target_deps.extend(copy_self_contained_objects(builder, &compiler, target));
127 let mut cargo = builder.cargo(compiler, Mode::Std, SourceType::InTree, target, "build");
128 std_cargo(builder, target, compiler.stage, &mut cargo);
130 builder.info(&format!(
131 "Building stage{} std artifacts ({} -> {})",
132 compiler.stage, &compiler.host, target
137 self.crates.to_vec(),
138 &libstd_stamp(builder, compiler, target),
143 builder.ensure(StdLink::from_std(
145 builder.compiler(compiler.stage, builder.config.build),
151 builder: &Builder<'_>,
155 target_deps: &mut Vec<(PathBuf, DependencyType)>,
156 dependency_type: DependencyType,
158 let target = libdir.join(name);
159 builder.copy(&sourcedir.join(name), &target);
161 target_deps.push((target, dependency_type));
164 fn copy_llvm_libunwind(builder: &Builder<'_>, target: TargetSelection, libdir: &Path) -> PathBuf {
165 let libunwind_path = builder.ensure(native::Libunwind { target });
166 let libunwind_source = libunwind_path.join("libunwind.a");
167 let libunwind_target = libdir.join("libunwind.a");
168 builder.copy(&libunwind_source, &libunwind_target);
172 /// Copies third party objects needed by various targets.
173 fn copy_third_party_objects(
174 builder: &Builder<'_>,
176 target: TargetSelection,
177 ) -> Vec<(PathBuf, DependencyType)> {
178 let mut target_deps = vec![];
180 // FIXME: remove this in 2021
181 if target == "x86_64-fortanix-unknown-sgx" {
182 if env::var_os("X86_FORTANIX_SGX_LIBS").is_some() {
183 builder.info("Warning: X86_FORTANIX_SGX_LIBS environment variable is ignored, libunwind is now compiled as part of rustbuild");
187 if builder.config.sanitizers_enabled(target) && compiler.stage != 0 {
188 // The sanitizers are only copied in stage1 or above,
189 // to avoid creating dependency on LLVM.
191 copy_sanitizers(builder, &compiler, target)
193 .map(|d| (d, DependencyType::Target)),
197 if target == "x86_64-fortanix-unknown-sgx"
198 || builder.config.llvm_libunwind(target) == LlvmLibunwind::InTree
199 && (target.contains("linux") || target.contains("fuchsia"))
202 copy_llvm_libunwind(builder, target, &builder.sysroot_libdir(*compiler, target));
203 target_deps.push((libunwind_path, DependencyType::Target));
209 /// Copies third party objects needed by various targets for self-contained linkage.
210 fn copy_self_contained_objects(
211 builder: &Builder<'_>,
213 target: TargetSelection,
214 ) -> Vec<(PathBuf, DependencyType)> {
215 let libdir_self_contained = builder.sysroot_libdir(*compiler, target).join("self-contained");
216 t!(fs::create_dir_all(&libdir_self_contained));
217 let mut target_deps = vec![];
219 // Copies the libc and CRT objects.
221 // rustc historically provides a more self-contained installation for musl targets
222 // not requiring the presence of a native musl toolchain. For example, it can fall back
223 // to using gcc from a glibc-targeting toolchain for linking.
224 // To do that we have to distribute musl startup objects as a part of Rust toolchain
225 // and link with them manually in the self-contained mode.
226 if target.contains("musl") {
227 let srcdir = builder.musl_libdir(target).unwrap_or_else(|| {
228 panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple)
230 for &obj in &["libc.a", "crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
233 &libdir_self_contained,
237 DependencyType::TargetSelfContained,
240 let crt_path = builder.ensure(native::CrtBeginEnd { target });
241 for &obj in &["crtbegin.o", "crtbeginS.o", "crtend.o", "crtendS.o"] {
242 let src = crt_path.join(obj);
243 let target = libdir_self_contained.join(obj);
244 builder.copy(&src, &target);
245 target_deps.push((target, DependencyType::TargetSelfContained));
248 if !target.starts_with("s390x") {
249 let libunwind_path = copy_llvm_libunwind(builder, target, &libdir_self_contained);
250 target_deps.push((libunwind_path, DependencyType::TargetSelfContained));
252 } else if target.ends_with("-wasi") {
256 panic!("Target {:?} does not have a \"wasi-root\" key", target.triple)
258 .join("lib/wasm32-wasi");
259 for &obj in &["libc.a", "crt1-command.o", "crt1-reactor.o"] {
262 &libdir_self_contained,
266 DependencyType::TargetSelfContained,
269 } else if target.ends_with("windows-gnu") {
270 for obj in ["crt2.o", "dllcrt2.o"].iter() {
271 let src = compiler_file(builder, builder.cc(target), target, CLang::C, obj);
272 let target = libdir_self_contained.join(obj);
273 builder.copy(&src, &target);
274 target_deps.push((target, DependencyType::TargetSelfContained));
281 /// Configure cargo to compile the standard library, adding appropriate env vars
283 pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, stage: u32, cargo: &mut Cargo) {
284 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
285 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
288 // Determine if we're going to compile in optimized C intrinsics to
289 // the `compiler-builtins` crate. These intrinsics live in LLVM's
290 // `compiler-rt` repository, but our `src/llvm-project` submodule isn't
291 // always checked out, so we need to conditionally look for this. (e.g. if
292 // an external LLVM is used we skip the LLVM submodule checkout).
294 // Note that this shouldn't affect the correctness of `compiler-builtins`,
295 // but only its speed. Some intrinsics in C haven't been translated to Rust
296 // yet but that's pretty rare. Other intrinsics have optimized
297 // implementations in C which have only had slower versions ported to Rust,
298 // so we favor the C version where we can, but it's not critical.
300 // If `compiler-rt` is available ensure that the `c` feature of the
301 // `compiler-builtins` crate is enabled and it's configured to learn where
302 // `compiler-rt` is located.
303 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
304 let compiler_builtins_c_feature = if compiler_builtins_root.exists() {
305 // Note that `libprofiler_builtins/build.rs` also computes this so if
306 // you're changing something here please also change that.
307 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
308 " compiler-builtins-c"
313 let mut features = String::new();
315 // Cranelift doesn't support `asm`.
316 if stage != 0 && builder.config.default_codegen_backend().unwrap_or_default() == "cranelift" {
317 features += " compiler-builtins-no-asm";
320 if builder.no_std(target) == Some(true) {
321 features += " compiler-builtins-mem";
322 if !target.starts_with("bpf") {
323 features.push_str(compiler_builtins_c_feature);
326 // for no-std targets we only compile a few no_std crates
328 .args(&["-p", "alloc"])
329 .arg("--manifest-path")
330 .arg(builder.src.join("library/alloc/Cargo.toml"))
334 features += &builder.std_features(target);
335 features.push_str(compiler_builtins_c_feature);
340 .arg("--manifest-path")
341 .arg(builder.src.join("library/test/Cargo.toml"));
343 // Help the libc crate compile by assisting it in finding various
344 // sysroot native libraries.
345 if target.contains("musl") {
346 if let Some(p) = builder.musl_libdir(target) {
347 let root = format!("native={}", p.to_str().unwrap());
348 cargo.rustflag("-L").rustflag(&root);
352 if target.ends_with("-wasi") {
353 if let Some(p) = builder.wasi_root(target) {
354 let root = format!("native={}/lib/wasm32-wasi", p.to_str().unwrap());
355 cargo.rustflag("-L").rustflag(&root);
360 // By default, rustc uses `-Cembed-bitcode=yes`, and Cargo overrides that
361 // with `-Cembed-bitcode=no` for non-LTO builds. However, libstd must be
362 // built with bitcode so that the produced rlibs can be used for both LTO
363 // builds (which use bitcode) and non-LTO builds (which use object code).
364 // So we override the override here!
366 // But we don't bother for the stage 0 compiler because it's never used
369 cargo.rustflag("-Cembed-bitcode=yes");
372 // By default, rustc does not include unwind tables unless they are required
373 // for a particular target. They are not required by RISC-V targets, but
374 // compiling the standard library with them means that users can get
375 // backtraces without having to recompile the standard library themselves.
377 // This choice was discussed in https://github.com/rust-lang/rust/pull/69890
378 if target.contains("riscv") {
379 cargo.rustflag("-Cforce-unwind-tables=yes");
383 format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
384 cargo.rustflag(&html_root);
385 cargo.rustdocflag(&html_root);
388 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
390 pub compiler: Compiler,
391 pub target_compiler: Compiler,
392 pub target: TargetSelection,
393 /// Not actually used; only present to make sure the cache invalidation is correct.
394 crates: Interned<Vec<String>>,
398 fn from_std(std: Std, host_compiler: Compiler) -> Self {
400 compiler: host_compiler,
401 target_compiler: std.compiler,
408 impl Step for StdLink {
411 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
415 /// Link all libstd rlibs/dylibs into the sysroot location.
417 /// Links those artifacts generated by `compiler` to the `stage` compiler's
418 /// sysroot for the specified `host` and `target`.
420 /// Note that this assumes that `compiler` has already generated the libstd
421 /// libraries for `target`, and this method will find them in the relevant
422 /// output directory.
423 fn run(self, builder: &Builder<'_>) {
424 let compiler = self.compiler;
425 let target_compiler = self.target_compiler;
426 let target = self.target;
427 builder.info(&format!(
428 "Copying stage{} std from stage{} ({} -> {} / {})",
429 target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
431 let libdir = builder.sysroot_libdir(target_compiler, target);
432 let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
433 add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
437 /// Copies sanitizer runtime libraries into target libdir.
439 builder: &Builder<'_>,
441 target: TargetSelection,
443 let runtimes: Vec<native::SanitizerRuntime> = builder.ensure(native::Sanitizers { target });
445 if builder.config.dry_run() {
449 let mut target_deps = Vec::new();
450 let libdir = builder.sysroot_libdir(*compiler, target);
452 for runtime in &runtimes {
453 let dst = libdir.join(&runtime.name);
454 builder.copy(&runtime.path, &dst);
456 if target == "x86_64-apple-darwin" || target == "aarch64-apple-darwin" {
457 // Update the library’s install name to reflect that it has been renamed.
458 apple_darwin_update_library_name(&dst, &format!("@rpath/{}", &runtime.name));
459 // Upon renaming the install name, the code signature of the file will invalidate,
460 // so we will sign it again.
461 apple_darwin_sign_file(&dst);
464 target_deps.push(dst);
470 fn apple_darwin_update_library_name(library_path: &Path, new_name: &str) {
471 let status = Command::new("install_name_tool")
476 .expect("failed to execute `install_name_tool`");
477 assert!(status.success());
480 fn apple_darwin_sign_file(file_path: &Path) {
481 let status = Command::new("codesign")
482 .arg("-f") // Force to rewrite the existing signature
487 .expect("failed to execute `codesign`");
488 assert!(status.success());
491 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
492 pub struct StartupObjects {
493 pub compiler: Compiler,
494 pub target: TargetSelection,
497 impl Step for StartupObjects {
498 type Output = Vec<(PathBuf, DependencyType)>;
500 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
501 run.path("library/rtstartup")
504 fn make_run(run: RunConfig<'_>) {
505 run.builder.ensure(StartupObjects {
506 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
511 /// Builds and prepare startup objects like rsbegin.o and rsend.o
513 /// These are primarily used on Windows right now for linking executables/dlls.
514 /// They don't require any library support as they're just plain old object
515 /// files, so we just use the nightly snapshot compiler to always build them (as
516 /// no other compilers are guaranteed to be available).
517 fn run(self, builder: &Builder<'_>) -> Vec<(PathBuf, DependencyType)> {
518 let for_compiler = self.compiler;
519 let target = self.target;
520 if !target.ends_with("windows-gnu") {
524 let mut target_deps = vec![];
526 let src_dir = &builder.src.join("library").join("rtstartup");
527 let dst_dir = &builder.native_dir(target).join("rtstartup");
528 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
529 t!(fs::create_dir_all(dst_dir));
531 for file in &["rsbegin", "rsend"] {
532 let src_file = &src_dir.join(file.to_string() + ".rs");
533 let dst_file = &dst_dir.join(file.to_string() + ".o");
534 if !up_to_date(src_file, dst_file) {
535 let mut cmd = Command::new(&builder.initial_rustc);
536 cmd.env("RUSTC_BOOTSTRAP", "1");
537 if !builder.local_rebuild {
538 // a local_rebuild compiler already has stage1 features
539 cmd.arg("--cfg").arg("bootstrap");
543 .arg(target.rustc_target_arg())
551 let target = sysroot_dir.join((*file).to_string() + ".o");
552 builder.copy(dst_file, &target);
553 target_deps.push((target, DependencyType::Target));
560 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
562 pub target: TargetSelection,
563 pub compiler: Compiler,
564 /// Whether to build a subset of crates, rather than the whole compiler.
566 /// This should only be requested by the user, not used within rustbuild itself.
567 /// Using it within rustbuild can lead to confusing situation where lints are replayed
568 /// in two different steps.
569 crates: Interned<Vec<String>>,
573 pub fn new(compiler: Compiler, target: TargetSelection) -> Self {
574 Self { target, compiler, crates: Default::default() }
578 impl Step for Rustc {
580 const ONLY_HOSTS: bool = true;
581 const DEFAULT: bool = false;
583 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
584 let mut crates = run.builder.in_tree_crates("rustc-main", None);
585 for (i, krate) in crates.iter().enumerate() {
586 if krate.name == "rustc-main" {
587 crates.swap_remove(i);
594 fn make_run(run: RunConfig<'_>) {
595 let crates = run.cargo_crates_in_set();
596 run.builder.ensure(Rustc {
597 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
603 /// Builds the compiler.
605 /// This will build the compiler for a particular stage of the build using
606 /// the `compiler` targeting the `target` architecture. The artifacts
607 /// created will also be linked into the sysroot directory.
608 fn run(self, builder: &Builder<'_>) {
609 let compiler = self.compiler;
610 let target = self.target;
612 // NOTE: the ABI of the beta compiler is different from the ABI of the downloaded compiler,
613 // so its artifacts can't be reused.
614 if builder.download_rustc() && compiler.stage != 0 {
615 // Copy the existing artifacts instead of rebuilding them.
616 // NOTE: this path is only taken for tools linking to rustc-dev.
617 builder.ensure(Sysroot { compiler });
621 builder.ensure(Std::new(compiler, target));
623 if builder.config.keep_stage.contains(&compiler.stage) {
624 builder.info("Warning: Using a potentially old librustc. This may not behave well.");
625 builder.info("Warning: Use `--keep-stage-std` if you want to rebuild the compiler when it changes");
626 builder.ensure(RustcLink::from_rustc(self, compiler));
630 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
631 if compiler_to_use != compiler {
632 builder.ensure(Rustc::new(compiler_to_use, target));
634 .info(&format!("Uplifting stage1 rustc ({} -> {})", builder.config.build, target));
635 builder.ensure(RustcLink::from_rustc(self, compiler_to_use));
639 // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
640 builder.ensure(Std::new(
641 builder.compiler(self.compiler.stage, builder.config.build),
642 builder.config.build,
645 let mut cargo = builder.cargo(compiler, Mode::Rustc, SourceType::InTree, target, "build");
646 rustc_cargo(builder, &mut cargo, target);
648 if builder.config.rust_profile_use.is_some()
649 && builder.config.rust_profile_generate.is_some()
651 panic!("Cannot use and generate PGO profiles at the same time");
654 // With LLD, we can use ICF (identical code folding) to reduce the executable size
655 // of librustc_driver/rustc and to improve i-cache utilization.
657 // -Wl,[link options] doesn't work on MSVC. However, /OPT:ICF (technically /OPT:REF,ICF)
658 // is already on by default in MSVC optimized builds, which is interpreted as --icf=all:
659 // https://github.com/llvm/llvm-project/blob/3329cec2f79185bafd678f310fafadba2a8c76d2/lld/COFF/Driver.cpp#L1746
660 // https://github.com/rust-lang/rust/blob/f22819bcce4abaff7d1246a56eec493418f9f4ee/compiler/rustc_codegen_ssa/src/back/linker.rs#L827
661 if builder.config.use_lld && !compiler.host.contains("msvc") {
662 cargo.rustflag("-Clink-args=-Wl,--icf=all");
665 let is_collecting = if let Some(path) = &builder.config.rust_profile_generate {
666 if compiler.stage == 1 {
667 cargo.rustflag(&format!("-Cprofile-generate={}", path));
668 // Apparently necessary to avoid overflowing the counters during
669 // a Cargo build profile
670 cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4");
675 } else if let Some(path) = &builder.config.rust_profile_use {
676 if compiler.stage == 1 {
677 cargo.rustflag(&format!("-Cprofile-use={}", path));
678 cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function");
687 // Ensure paths to Rust sources are relative, not absolute.
688 cargo.rustflag(&format!(
689 "-Cllvm-args=-static-func-strip-dirname-prefix={}",
690 builder.config.src.components().count()
694 // cfg(bootstrap): remove if condition once the bootstrap compiler supports dylib LTO
695 if compiler.stage != 0 {
696 match builder.config.rust_lto {
697 RustcLto::Thin | RustcLto::Fat => {
698 // Since using LTO for optimizing dylibs is currently experimental,
699 // we need to pass -Zdylib-lto.
700 cargo.rustflag("-Zdylib-lto");
701 // Cargo by default passes `-Cembed-bitcode=no` and doesn't pass `-Clto` when
702 // compiling dylibs (and their dependencies), even when LTO is enabled for the
703 // crate. Therefore, we need to override `-Clto` and `-Cembed-bitcode` here.
704 let lto_type = match builder.config.rust_lto {
705 RustcLto::Thin => "thin",
706 RustcLto::Fat => "fat",
709 cargo.rustflag(&format!("-Clto={}", lto_type));
710 cargo.rustflag("-Cembed-bitcode=yes");
712 RustcLto::ThinLocal => { /* Do nothing, this is the default */ }
716 builder.info(&format!(
717 "Building stage{} compiler artifacts ({} -> {})",
718 compiler.stage, &compiler.host, target
723 self.crates.to_vec(),
724 &librustc_stamp(builder, compiler, target),
729 builder.ensure(RustcLink::from_rustc(
731 builder.compiler(compiler.stage, builder.config.build),
736 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
739 .arg(builder.rustc_features(builder.kind))
740 .arg("--manifest-path")
741 .arg(builder.src.join("compiler/rustc/Cargo.toml"));
742 rustc_cargo_env(builder, cargo, target);
745 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) {
746 // Set some configuration variables picked up by build scripts and
747 // the compiler alike
749 .env("CFG_RELEASE", builder.rust_release())
750 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
751 .env("CFG_VERSION", builder.rust_version());
753 if let Some(backend) = builder.config.default_codegen_backend() {
754 cargo.env("CFG_DEFAULT_CODEGEN_BACKEND", backend);
757 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
758 let target_config = builder.config.target_config.get(&target);
760 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
762 if let Some(ref ver_date) = builder.rust_info().commit_date() {
763 cargo.env("CFG_VER_DATE", ver_date);
765 if let Some(ref ver_hash) = builder.rust_info().sha() {
766 cargo.env("CFG_VER_HASH", ver_hash);
768 if !builder.unstable_features() {
769 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
772 // Prefer the current target's own default_linker, else a globally
774 if let Some(s) = target_config.and_then(|c| c.default_linker.as_ref()) {
775 cargo.env("CFG_DEFAULT_LINKER", s);
776 } else if let Some(ref s) = builder.config.rustc_default_linker {
777 cargo.env("CFG_DEFAULT_LINKER", s);
780 if builder.config.rustc_parallel {
781 // keep in sync with `bootstrap/lib.rs:Build::rustc_features`
782 // `cfg` option for rustc, `features` option for cargo, for conditional compilation
783 cargo.rustflag("--cfg=parallel_compiler");
784 cargo.rustdocflag("--cfg=parallel_compiler");
786 if builder.config.rust_verify_llvm_ir {
787 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
790 // Pass down configuration from the LLVM build into the build of
791 // rustc_llvm and rustc_codegen_llvm.
793 // Note that this is disabled if LLVM itself is disabled or we're in a check
794 // build. If we are in a check build we still go ahead here presuming we've
795 // detected that LLVM is already built and good to go which helps prevent
796 // busting caches (e.g. like #71152).
797 if builder.config.llvm_enabled()
798 && (builder.kind != Kind::Check
799 || crate::native::prebuilt_llvm_config(builder, target).is_ok())
801 if builder.is_rust_llvm(target) {
802 cargo.env("LLVM_RUSTLLVM", "1");
804 let native::LlvmResult { llvm_config, .. } = builder.ensure(native::Llvm { target });
805 cargo.env("LLVM_CONFIG", &llvm_config);
806 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
807 cargo.env("CFG_LLVM_ROOT", s);
810 // Some LLVM linker flags (-L and -l) may be needed to link `rustc_llvm`. Its build script
811 // expects these to be passed via the `LLVM_LINKER_FLAGS` env variable, separated by
815 // - on windows, when `clang-cl` is used with instrumentation, we need to manually add
816 // clang's runtime library resource directory so that the profiler runtime library can be
817 // found. This is to avoid the linker errors about undefined references to
818 // `__llvm_profile_instrument_memop` when linking `rustc_driver`.
819 let mut llvm_linker_flags = String::new();
820 if builder.config.llvm_profile_generate && target.contains("msvc") {
821 if let Some(ref clang_cl_path) = builder.config.llvm_clang_cl {
822 // Add clang's runtime library directory to the search path
823 let clang_rt_dir = get_clang_cl_resource_dir(clang_cl_path);
824 llvm_linker_flags.push_str(&format!("-L{}", clang_rt_dir.display()));
828 // The config can also specify its own llvm linker flags.
829 if let Some(ref s) = builder.config.llvm_ldflags {
830 if !llvm_linker_flags.is_empty() {
831 llvm_linker_flags.push_str(" ");
833 llvm_linker_flags.push_str(s);
836 // Set the linker flags via the env var that `rustc_llvm`'s build script will read.
837 if !llvm_linker_flags.is_empty() {
838 cargo.env("LLVM_LINKER_FLAGS", llvm_linker_flags);
841 // Building with a static libstdc++ is only supported on linux right now,
842 // not for MSVC or macOS
843 if builder.config.llvm_static_stdcpp
844 && !target.contains("freebsd")
845 && !target.contains("msvc")
846 && !target.contains("apple")
847 && !target.contains("solaris")
849 let file = compiler_file(
851 builder.cxx(target).unwrap(),
856 cargo.env("LLVM_STATIC_STDCPP", file);
858 if builder.llvm_link_shared() {
859 cargo.env("LLVM_LINK_SHARED", "1");
861 if builder.config.llvm_use_libcxx {
862 cargo.env("LLVM_USE_LIBCXX", "1");
864 if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
865 cargo.env("LLVM_NDEBUG", "1");
870 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
872 pub compiler: Compiler,
873 pub target_compiler: Compiler,
874 pub target: TargetSelection,
875 /// Not actually used; only present to make sure the cache invalidation is correct.
876 crates: Interned<Vec<String>>,
880 fn from_rustc(rustc: Rustc, host_compiler: Compiler) -> Self {
882 compiler: host_compiler,
883 target_compiler: rustc.compiler,
884 target: rustc.target,
885 crates: rustc.crates,
890 impl Step for RustcLink {
893 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
897 /// Same as `std_link`, only for librustc
898 fn run(self, builder: &Builder<'_>) {
899 let compiler = self.compiler;
900 let target_compiler = self.target_compiler;
901 let target = self.target;
902 builder.info(&format!(
903 "Copying stage{} rustc from stage{} ({} -> {} / {})",
904 target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
908 &builder.sysroot_libdir(target_compiler, target),
909 &builder.sysroot_libdir(target_compiler, compiler.host),
910 &librustc_stamp(builder, compiler, target),
915 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
916 pub struct CodegenBackend {
917 pub target: TargetSelection,
918 pub compiler: Compiler,
919 pub backend: Interned<String>,
922 impl Step for CodegenBackend {
924 const ONLY_HOSTS: bool = true;
925 // Only the backends specified in the `codegen-backends` entry of `config.toml` are built.
926 const DEFAULT: bool = true;
928 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
929 run.paths(&["compiler/rustc_codegen_cranelift", "compiler/rustc_codegen_gcc"])
932 fn make_run(run: RunConfig<'_>) {
933 for &backend in &run.builder.config.rust_codegen_backends {
934 if backend == "llvm" {
935 continue; // Already built as part of rustc
938 run.builder.ensure(CodegenBackend {
940 compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()),
946 fn run(self, builder: &Builder<'_>) {
947 let compiler = self.compiler;
948 let target = self.target;
949 let backend = self.backend;
951 builder.ensure(Rustc::new(compiler, target));
953 if builder.config.keep_stage.contains(&compiler.stage) {
955 "Warning: Using a potentially old codegen backend. \
956 This may not behave well.",
958 // Codegen backends are linked separately from this step today, so we don't do
963 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
964 if compiler_to_use != compiler {
965 builder.ensure(CodegenBackend { compiler: compiler_to_use, target, backend });
969 let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
971 let mut cargo = builder.cargo(compiler, Mode::Codegen, SourceType::InTree, target, "build");
973 .arg("--manifest-path")
974 .arg(builder.src.join(format!("compiler/rustc_codegen_{}/Cargo.toml", backend)));
975 rustc_cargo_env(builder, &mut cargo, target);
977 let tmp_stamp = out_dir.join(".tmp.stamp");
979 builder.info(&format!(
980 "Building stage{} codegen backend {} ({} -> {})",
981 compiler.stage, backend, &compiler.host, target
983 let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false);
984 if builder.config.dry_run() {
987 let mut files = files.into_iter().filter(|f| {
988 let filename = f.file_name().unwrap().to_str().unwrap();
989 is_dylib(filename) && filename.contains("rustc_codegen_")
991 let codegen_backend = match files.next() {
993 None => panic!("no dylibs built for codegen backend?"),
995 if let Some(f) = files.next() {
997 "codegen backend built two dylibs:\n{}\n{}",
998 codegen_backend.display(),
1002 let stamp = codegen_backend_stamp(builder, compiler, target, backend);
1003 let codegen_backend = codegen_backend.to_str().unwrap();
1004 t!(fs::write(&stamp, &codegen_backend));
1008 /// Creates the `codegen-backends` folder for a compiler that's about to be
1009 /// assembled as a complete compiler.
1011 /// This will take the codegen artifacts produced by `compiler` and link them
1012 /// into an appropriate location for `target_compiler` to be a functional
1014 fn copy_codegen_backends_to_sysroot(
1015 builder: &Builder<'_>,
1017 target_compiler: Compiler,
1019 let target = target_compiler.host;
1021 // Note that this step is different than all the other `*Link` steps in
1022 // that it's not assembling a bunch of libraries but rather is primarily
1023 // moving the codegen backend into place. The codegen backend of rustc is
1024 // not linked into the main compiler by default but is rather dynamically
1025 // selected at runtime for inclusion.
1027 // Here we're looking for the output dylib of the `CodegenBackend` step and
1028 // we're copying that into the `codegen-backends` folder.
1029 let dst = builder.sysroot_codegen_backends(target_compiler);
1030 t!(fs::create_dir_all(&dst), dst);
1032 if builder.config.dry_run() {
1036 for backend in builder.config.rust_codegen_backends.iter() {
1037 if backend == "llvm" {
1038 continue; // Already built as part of rustc
1041 let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
1042 let dylib = t!(fs::read_to_string(&stamp));
1043 let file = Path::new(&dylib);
1044 let filename = file.file_name().unwrap().to_str().unwrap();
1045 // change `librustc_codegen_cranelift-xxxxxx.so` to
1046 // `librustc_codegen_cranelift-release.so`
1047 let target_filename = {
1048 let dash = filename.find('-').unwrap();
1049 let dot = filename.find('.').unwrap();
1050 format!("{}-{}{}", &filename[..dash], builder.rust_release(), &filename[dot..])
1052 builder.copy(&file, &dst.join(target_filename));
1056 /// Cargo's output path for the standard library in a given stage, compiled
1057 /// by a particular compiler for the specified target.
1058 pub fn libstd_stamp(builder: &Builder<'_>, compiler: Compiler, target: TargetSelection) -> PathBuf {
1059 builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
1062 /// Cargo's output path for librustc in a given stage, compiled by a particular
1063 /// compiler for the specified target.
1064 pub fn librustc_stamp(
1065 builder: &Builder<'_>,
1067 target: TargetSelection,
1069 builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
1072 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
1073 /// compiler for the specified target and backend.
1074 fn codegen_backend_stamp(
1075 builder: &Builder<'_>,
1077 target: TargetSelection,
1078 backend: Interned<String>,
1081 .cargo_out(compiler, Mode::Codegen, target)
1082 .join(format!(".librustc_codegen_{}.stamp", backend))
1085 pub fn compiler_file(
1086 builder: &Builder<'_>,
1088 target: TargetSelection,
1092 let mut cmd = Command::new(compiler);
1093 cmd.args(builder.cflags(target, GitRepo::Rustc, c));
1094 cmd.arg(format!("-print-file-name={}", file));
1095 let out = output(&mut cmd);
1096 PathBuf::from(out.trim())
1099 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1100 pub struct Sysroot {
1101 pub compiler: Compiler,
1104 impl Step for Sysroot {
1105 type Output = Interned<PathBuf>;
1107 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1111 /// Returns the sysroot for the `compiler` specified that *this build system
1114 /// That is, the sysroot for the stage0 compiler is not what the compiler
1115 /// thinks it is by default, but it's the same as the default for stages
1117 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
1118 let compiler = self.compiler;
1119 let host_dir = builder.out.join(&compiler.host.triple);
1121 let sysroot_dir = |stage| {
1123 host_dir.join("stage0-sysroot")
1124 } else if builder.download_rustc() && compiler.stage != builder.top_stage {
1125 host_dir.join("ci-rustc-sysroot")
1127 host_dir.join(format!("stage{}", stage))
1130 let sysroot = sysroot_dir(compiler.stage);
1132 let _ = fs::remove_dir_all(&sysroot);
1133 t!(fs::create_dir_all(&sysroot));
1135 // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0.
1136 if builder.download_rustc() && compiler.stage != 0 {
1138 builder.config.build, compiler.host,
1139 "Cross-compiling is not yet supported with `download-rustc`",
1142 // #102002, cleanup old toolchain folders when using download-rustc so people don't use them by accident.
1143 for stage in 0..=2 {
1144 if stage != compiler.stage {
1145 let dir = sysroot_dir(stage);
1146 if !dir.ends_with("ci-rustc-sysroot") {
1147 let _ = fs::remove_dir_all(dir);
1152 // Copy the compiler into the correct sysroot.
1154 builder.config.out.join(&*builder.config.build.triple).join("ci-rustc");
1155 builder.cp_r(&ci_rustc_dir, &sysroot);
1156 return INTERNER.intern_path(sysroot);
1159 // Symlink the source root into the same location inside the sysroot,
1160 // where `rust-src` component would go (`$sysroot/lib/rustlib/src/rust`),
1161 // so that any tools relying on `rust-src` also work for local builds,
1162 // and also for translating the virtual `/rustc/$hash` back to the real
1163 // directory (for running tests with `rust.remap-debuginfo = true`).
1164 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
1165 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
1166 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
1167 if let Err(e) = symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust) {
1169 "warning: creating symbolic link `{}` to `{}` failed with {}",
1170 sysroot_lib_rustlib_src_rust.display(),
1171 builder.src.display(),
1174 if builder.config.rust_remap_debuginfo {
1176 "warning: some `src/test/ui` tests will fail when lacking `{}`",
1177 sysroot_lib_rustlib_src_rust.display(),
1181 // Same for the rustc-src component.
1182 let sysroot_lib_rustlib_rustcsrc = sysroot.join("lib/rustlib/rustc-src");
1183 t!(fs::create_dir_all(&sysroot_lib_rustlib_rustcsrc));
1184 let sysroot_lib_rustlib_rustcsrc_rust = sysroot_lib_rustlib_rustcsrc.join("rust");
1186 symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_rustcsrc_rust)
1189 "warning: creating symbolic link `{}` to `{}` failed with {}",
1190 sysroot_lib_rustlib_rustcsrc_rust.display(),
1191 builder.src.display(),
1196 INTERNER.intern_path(sysroot)
1200 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
1201 pub struct Assemble {
1202 /// The compiler which we will produce in this step. Assemble itself will
1203 /// take care of ensuring that the necessary prerequisites to do so exist,
1204 /// that is, this target can be a stage2 compiler and Assemble will build
1205 /// previous stages for you.
1206 pub target_compiler: Compiler,
1209 impl Step for Assemble {
1210 type Output = Compiler;
1211 const ONLY_HOSTS: bool = true;
1213 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1214 run.path("compiler/rustc").path("compiler")
1217 fn make_run(run: RunConfig<'_>) {
1218 run.builder.ensure(Assemble {
1219 target_compiler: run.builder.compiler(run.builder.top_stage + 1, run.target),
1223 /// Prepare a new compiler from the artifacts in `stage`
1225 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
1226 /// must have been previously produced by the `stage - 1` builder.build
1228 fn run(self, builder: &Builder<'_>) -> Compiler {
1229 let target_compiler = self.target_compiler;
1231 if target_compiler.stage == 0 {
1233 builder.config.build, target_compiler.host,
1234 "Cannot obtain compiler for non-native build triple at stage 0"
1236 // The stage 0 compiler for the build triple is always pre-built.
1237 return target_compiler;
1240 // Get the compiler that we'll use to bootstrap ourselves.
1242 // Note that this is where the recursive nature of the bootstrap
1243 // happens, as this will request the previous stage's compiler on
1244 // downwards to stage 0.
1246 // Also note that we're building a compiler for the host platform. We
1247 // only assume that we can run `build` artifacts, which means that to
1248 // produce some other architecture compiler we need to start from
1249 // `build` to get there.
1251 // FIXME: It may be faster if we build just a stage 1 compiler and then
1252 // use that to bootstrap this compiler forward.
1253 let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
1255 // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0.
1256 if builder.download_rustc() {
1257 builder.ensure(Sysroot { compiler: target_compiler });
1258 return target_compiler;
1261 // Build the libraries for this compiler to link to (i.e., the libraries
1262 // it uses at runtime). NOTE: Crates the target compiler compiles don't
1263 // link to these. (FIXME: Is that correct? It seems to be correct most
1264 // of the time but I think we do link to these for stage2/bin compilers
1265 // when not performing a full bootstrap).
1266 builder.ensure(Rustc::new(build_compiler, target_compiler.host));
1268 for &backend in builder.config.rust_codegen_backends.iter() {
1269 if backend == "llvm" {
1270 continue; // Already built as part of rustc
1273 builder.ensure(CodegenBackend {
1274 compiler: build_compiler,
1275 target: target_compiler.host,
1280 let lld_install = if builder.config.lld_enabled {
1281 Some(builder.ensure(native::Lld { target: target_compiler.host }))
1286 let stage = target_compiler.stage;
1287 let host = target_compiler.host;
1288 builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
1290 // Link in all dylibs to the libdir
1291 let stamp = librustc_stamp(builder, build_compiler, target_compiler.host);
1292 let proc_macros = builder
1293 .read_stamp_file(&stamp)
1295 .filter_map(|(path, dependency_type)| {
1296 if dependency_type == DependencyType::Host {
1297 Some(path.file_name().unwrap().to_owned().into_string().unwrap())
1302 .collect::<HashSet<_>>();
1304 let sysroot = builder.sysroot(target_compiler);
1305 let rustc_libdir = builder.rustc_libdir(target_compiler);
1306 t!(fs::create_dir_all(&rustc_libdir));
1307 let src_libdir = builder.sysroot_libdir(build_compiler, host);
1308 for f in builder.read_dir(&src_libdir) {
1309 let filename = f.file_name().into_string().unwrap();
1310 if (is_dylib(&filename) || is_debug_info(&filename)) && !proc_macros.contains(&filename)
1312 builder.copy(&f.path(), &rustc_libdir.join(&filename));
1316 copy_codegen_backends_to_sysroot(builder, build_compiler, target_compiler);
1318 // We prepend this bin directory to the user PATH when linking Rust binaries. To
1319 // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
1320 let libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
1321 let libdir_bin = libdir.parent().unwrap().join("bin");
1322 t!(fs::create_dir_all(&libdir_bin));
1323 if let Some(lld_install) = lld_install {
1324 let src_exe = exe("lld", target_compiler.host);
1325 let dst_exe = exe("rust-lld", target_compiler.host);
1326 builder.copy(&lld_install.join("bin").join(&src_exe), &libdir_bin.join(&dst_exe));
1327 // for `-Z gcc-ld=lld`
1328 let gcc_ld_dir = libdir_bin.join("gcc-ld");
1329 t!(fs::create_dir(&gcc_ld_dir));
1330 let lld_wrapper_exe = builder.ensure(crate::tool::LldWrapper {
1331 compiler: build_compiler,
1332 target: target_compiler.host,
1334 for name in crate::LLD_FILE_NAMES {
1335 builder.copy(&lld_wrapper_exe, &gcc_ld_dir.join(exe(name, target_compiler.host)));
1339 if builder.config.rust_codegen_backends.contains(&INTERNER.intern_str("llvm")) {
1340 let native::LlvmResult { llvm_config, .. } =
1341 builder.ensure(native::Llvm { target: target_compiler.host });
1342 if !builder.config.dry_run() {
1343 let llvm_bin_dir = output(Command::new(llvm_config).arg("--bindir"));
1344 let llvm_bin_dir = Path::new(llvm_bin_dir.trim());
1346 // Since we've already built the LLVM tools, install them to the sysroot.
1347 // This is the equivalent of installing the `llvm-tools-preview` component via
1348 // rustup, and lets developers use a locally built toolchain to
1349 // build projects that expect llvm tools to be present in the sysroot
1350 // (e.g. the `bootimage` crate).
1351 for tool in LLVM_TOOLS {
1352 let tool_exe = exe(tool, target_compiler.host);
1353 let src_path = llvm_bin_dir.join(&tool_exe);
1354 // When using `download-ci-llvm`, some of the tools
1355 // may not exist, so skip trying to copy them.
1356 if src_path.exists() {
1357 builder.copy(&src_path, &libdir_bin.join(&tool_exe));
1363 // Ensure that `libLLVM.so` ends up in the newly build compiler directory,
1364 // so that it can be found when the newly built `rustc` is run.
1365 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
1366 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
1368 // Link the compiler binary itself into place
1369 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
1370 let rustc = out_dir.join(exe("rustc-main", host));
1371 let bindir = sysroot.join("bin");
1372 t!(fs::create_dir_all(&bindir));
1373 let compiler = builder.rustc(target_compiler);
1374 builder.copy(&rustc, &compiler);
1380 /// Link some files into a rustc sysroot.
1382 /// For a particular stage this will link the file listed in `stamp` into the
1383 /// `sysroot_dst` provided.
1384 pub fn add_to_sysroot(
1385 builder: &Builder<'_>,
1387 sysroot_host_dst: &Path,
1390 let self_contained_dst = &sysroot_dst.join("self-contained");
1391 t!(fs::create_dir_all(&sysroot_dst));
1392 t!(fs::create_dir_all(&sysroot_host_dst));
1393 t!(fs::create_dir_all(&self_contained_dst));
1394 for (path, dependency_type) in builder.read_stamp_file(stamp) {
1395 let dst = match dependency_type {
1396 DependencyType::Host => sysroot_host_dst,
1397 DependencyType::Target => sysroot_dst,
1398 DependencyType::TargetSelfContained => self_contained_dst,
1400 builder.copy(&path, &dst.join(path.file_name().unwrap()));
1405 builder: &Builder<'_>,
1407 tail_args: Vec<String>,
1409 additional_target_deps: Vec<(PathBuf, DependencyType)>,
1412 if builder.config.dry_run() {
1416 // `target_root_dir` looks like $dir/$target/release
1417 let target_root_dir = stamp.parent().unwrap();
1418 // `target_deps_dir` looks like $dir/$target/release/deps
1419 let target_deps_dir = target_root_dir.join("deps");
1420 // `host_root_dir` looks like $dir/release
1421 let host_root_dir = target_root_dir
1423 .unwrap() // chop off `release`
1425 .unwrap() // chop off `$target`
1426 .join(target_root_dir.file_name().unwrap());
1428 // Spawn Cargo slurping up its JSON output. We'll start building up the
1429 // `deps` array of all files it generated along with a `toplevel` array of
1430 // files we need to probe for later.
1431 let mut deps = Vec::new();
1432 let mut toplevel = Vec::new();
1433 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
1434 let (filenames, crate_types) = match msg {
1435 CargoMessage::CompilerArtifact {
1437 target: CargoTarget { crate_types },
1439 } => (filenames, crate_types),
1442 for filename in filenames {
1443 // Skip files like executables
1444 if !(filename.ends_with(".rlib")
1445 || filename.ends_with(".lib")
1446 || filename.ends_with(".a")
1447 || is_debug_info(&filename)
1448 || is_dylib(&filename)
1449 || (is_check && filename.ends_with(".rmeta")))
1454 let filename = Path::new(&*filename);
1456 // If this was an output file in the "host dir" we don't actually
1457 // worry about it, it's not relevant for us
1458 if filename.starts_with(&host_root_dir) {
1459 // Unless it's a proc macro used in the compiler
1460 if crate_types.iter().any(|t| t == "proc-macro") {
1461 deps.push((filename.to_path_buf(), DependencyType::Host));
1466 // If this was output in the `deps` dir then this is a precise file
1467 // name (hash included) so we start tracking it.
1468 if filename.starts_with(&target_deps_dir) {
1469 deps.push((filename.to_path_buf(), DependencyType::Target));
1473 // Otherwise this was a "top level artifact" which right now doesn't
1474 // have a hash in the name, but there's a version of this file in
1475 // the `deps` folder which *does* have a hash in the name. That's
1476 // the one we'll want to we'll probe for it later.
1478 // We do not use `Path::file_stem` or `Path::extension` here,
1479 // because some generated files may have multiple extensions e.g.
1480 // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1481 // split the file name by the last extension (`.lib`) while we need
1482 // to split by all extensions (`.dll.lib`).
1483 let expected_len = t!(filename.metadata()).len();
1484 let filename = filename.file_name().unwrap().to_str().unwrap();
1485 let mut parts = filename.splitn(2, '.');
1486 let file_stem = parts.next().unwrap().to_owned();
1487 let extension = parts.next().unwrap().to_owned();
1489 toplevel.push((file_stem, extension, expected_len));
1494 crate::detail_exit(1);
1497 // Ok now we need to actually find all the files listed in `toplevel`. We've
1498 // got a list of prefix/extensions and we basically just need to find the
1499 // most recent file in the `deps` folder corresponding to each one.
1500 let contents = t!(target_deps_dir.read_dir())
1502 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1503 .collect::<Vec<_>>();
1504 for (prefix, extension, expected_len) in toplevel {
1505 let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1506 meta.len() == expected_len
1508 .strip_prefix(&prefix[..])
1509 .map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
1512 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1513 metadata.modified().expect("mtime should be available on all relevant OSes")
1515 let path_to_add = match max {
1516 Some(triple) => triple.0.to_str().unwrap(),
1517 None => panic!("no output generated for {:?} {:?}", prefix, extension),
1519 if is_dylib(path_to_add) {
1520 let candidate = format!("{}.lib", path_to_add);
1521 let candidate = PathBuf::from(candidate);
1522 if candidate.exists() {
1523 deps.push((candidate, DependencyType::Target));
1526 deps.push((path_to_add.into(), DependencyType::Target));
1529 deps.extend(additional_target_deps);
1531 let mut new_contents = Vec::new();
1532 for (dep, dependency_type) in deps.iter() {
1533 new_contents.extend(match *dependency_type {
1534 DependencyType::Host => b"h",
1535 DependencyType::Target => b"t",
1536 DependencyType::TargetSelfContained => b"s",
1538 new_contents.extend(dep.to_str().unwrap().as_bytes());
1539 new_contents.extend(b"\0");
1541 t!(fs::write(&stamp, &new_contents));
1542 deps.into_iter().map(|(d, _)| d).collect()
1545 pub fn stream_cargo(
1546 builder: &Builder<'_>,
1548 tail_args: Vec<String>,
1549 cb: &mut dyn FnMut(CargoMessage<'_>),
1551 let mut cargo = Command::from(cargo);
1552 if builder.config.dry_run() {
1555 // Instruct Cargo to give us json messages on stdout, critically leaving
1556 // stderr as piped so we can get those pretty colors.
1557 let mut message_format = if builder.config.json_output {
1558 String::from("json")
1560 String::from("json-render-diagnostics")
1562 if let Some(s) = &builder.config.rustc_error_format {
1563 message_format.push_str(",json-diagnostic-");
1564 message_format.push_str(s);
1566 cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
1568 for arg in tail_args {
1572 builder.verbose(&format!("running: {:?}", cargo));
1573 let mut child = match cargo.spawn() {
1575 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1578 // Spawn Cargo slurping up its JSON output. We'll start building up the
1579 // `deps` array of all files it generated along with a `toplevel` array of
1580 // files we need to probe for later.
1581 let stdout = BufReader::new(child.stdout.take().unwrap());
1582 for line in stdout.lines() {
1583 let line = t!(line);
1584 match serde_json::from_str::<CargoMessage<'_>>(&line) {
1586 if builder.config.json_output {
1587 // Forward JSON to stdout.
1588 println!("{}", line);
1592 // If this was informational, just print it out and continue
1593 Err(_) => println!("{}", line),
1597 // Make sure Cargo actually succeeded after we read all of its stdout.
1598 let status = t!(child.wait());
1599 if builder.is_verbose() && !status.success() {
1601 "command did not execute successfully: {:?}\n\
1602 expected success, got: {}",
1609 #[derive(Deserialize)]
1610 pub struct CargoTarget<'a> {
1611 crate_types: Vec<Cow<'a, str>>,
1614 #[derive(Deserialize)]
1615 #[serde(tag = "reason", rename_all = "kebab-case")]
1616 pub enum CargoMessage<'a> {
1618 package_id: Cow<'a, str>,
1619 features: Vec<Cow<'a, str>>,
1620 filenames: Vec<Cow<'a, str>>,
1621 target: CargoTarget<'a>,
1623 BuildScriptExecuted {
1624 package_id: Cow<'a, str>,