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 compiler the standard library, libtest, and
6 //! compiler. This module is also responsible for assembling the sysroot as it
7 //! goes along from the output of the previous stage.
12 use std::io::prelude::*;
13 use std::io::BufReader;
14 use std::path::{Path, PathBuf};
15 use std::process::{exit, Command, Stdio};
18 use build_helper::{output, t, up_to_date};
19 use filetime::FileTime;
20 use serde::Deserialize;
22 use crate::builder::Cargo;
25 use crate::util::{exe, is_dylib, symlink_dir};
26 use crate::{Compiler, GitRepo, Mode};
28 use crate::builder::{Builder, Kind, RunConfig, ShouldRun, Step};
29 use crate::cache::{Interned, INTERNER};
31 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
33 pub target: Interned<String>,
34 pub compiler: Compiler,
39 const DEFAULT: bool = true;
41 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
42 run.all_krates("test")
45 fn make_run(run: RunConfig<'_>) {
46 run.builder.ensure(Std {
47 compiler: run.builder.compiler(run.builder.top_stage, run.host),
52 /// Builds the standard library.
54 /// This will build the standard library for a particular stage of the build
55 /// using the `compiler` targeting the `target` architecture. The artifacts
56 /// created will also be linked into the sysroot directory.
57 fn run(self, builder: &Builder<'_>) {
58 let target = self.target;
59 let compiler = self.compiler;
61 if builder.config.keep_stage.contains(&compiler.stage) {
62 builder.info("Warning: Using a potentially old libstd. This may not behave well.");
63 builder.ensure(StdLink { compiler, target_compiler: compiler, target });
67 let mut target_deps = builder.ensure(StartupObjects { compiler, target });
69 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
70 if compiler_to_use != compiler {
71 builder.ensure(Std { compiler: compiler_to_use, target });
72 builder.info(&format!("Uplifting stage1 std ({} -> {})", compiler_to_use.host, target));
74 // Even if we're not building std this stage, the new sysroot must
75 // still contain the third party objects needed by various targets.
76 copy_third_party_objects(builder, &compiler, target);
78 builder.ensure(StdLink {
79 compiler: compiler_to_use,
80 target_compiler: compiler,
86 target_deps.extend(copy_third_party_objects(builder, &compiler, target).into_iter());
88 let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
89 std_cargo(builder, target, compiler.stage, &mut cargo);
91 builder.info(&format!(
92 "Building stage{} std artifacts ({} -> {})",
93 compiler.stage, &compiler.host, target
99 &libstd_stamp(builder, compiler, target),
104 builder.ensure(StdLink {
105 compiler: builder.compiler(compiler.stage, builder.config.build),
106 target_compiler: compiler,
112 /// Copies third party objects needed by various targets.
113 fn copy_third_party_objects(
114 builder: &Builder<'_>,
116 target: Interned<String>,
118 let libdir = builder.sysroot_libdir(*compiler, target);
120 let mut target_deps = vec![];
122 let mut copy_and_stamp = |sourcedir: &Path, name: &str| {
123 let target = libdir.join(name);
124 builder.copy(&sourcedir.join(name), &target);
125 target_deps.push(target);
128 // Copies the CRT objects.
130 // rustc historically provides a more self-contained installation for musl targets
131 // not requiring the presence of a native musl toolchain. For example, it can fall back
132 // to using gcc from a glibc-targeting toolchain for linking.
133 // To do that we have to distribute musl startup objects as a part of Rust toolchain
134 // and link with them manually in the self-contained mode.
135 if target.contains("musl") {
136 let srcdir = builder.musl_root(target).unwrap().join("lib");
137 for &obj in &["crt1.o", "Scrt1.o", "rcrt1.o", "crti.o", "crtn.o"] {
138 copy_and_stamp(&srcdir, obj);
140 } else if target.ends_with("-wasi") {
141 let srcdir = builder.wasi_root(target).unwrap().join("lib/wasm32-wasi");
142 copy_and_stamp(&srcdir, "crt1.o");
145 // Copies libunwind.a compiled to be linked with x86_64-fortanix-unknown-sgx.
147 // This target needs to be linked to Fortanix's port of llvm's libunwind.
148 // libunwind requires support for rwlock and printing to stderr,
149 // which is provided by std for this target.
150 if target == "x86_64-fortanix-unknown-sgx" {
151 let src_path_env = "X86_FORTANIX_SGX_LIBS";
153 env::var(src_path_env).unwrap_or_else(|_| panic!("{} not found in env", src_path_env));
154 copy_and_stamp(Path::new(&src), "libunwind.a");
157 if builder.config.sanitizers && compiler.stage != 0 {
158 // The sanitizers are only copied in stage1 or above,
159 // to avoid creating dependency on LLVM.
160 target_deps.extend(copy_sanitizers(builder, &compiler, target));
166 /// Configure cargo to compile the standard library, adding appropriate env vars
168 pub fn std_cargo(builder: &Builder<'_>, target: Interned<String>, stage: u32, cargo: &mut Cargo) {
169 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
170 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
173 // Determine if we're going to compile in optimized C intrinsics to
174 // the `compiler-builtins` crate. These intrinsics live in LLVM's
175 // `compiler-rt` repository, but our `src/llvm-project` submodule isn't
176 // always checked out, so we need to conditionally look for this. (e.g. if
177 // an external LLVM is used we skip the LLVM submodule checkout).
179 // Note that this shouldn't affect the correctness of `compiler-builtins`,
180 // but only its speed. Some intrinsics in C haven't been translated to Rust
181 // yet but that's pretty rare. Other intrinsics have optimized
182 // implementations in C which have only had slower versions ported to Rust,
183 // so we favor the C version where we can, but it's not critical.
185 // If `compiler-rt` is available ensure that the `c` feature of the
186 // `compiler-builtins` crate is enabled and it's configured to learn where
187 // `compiler-rt` is located.
188 let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
189 let compiler_builtins_c_feature = if compiler_builtins_root.exists() {
190 // Note that `libprofiler_builtins/build.rs` also computes this so if
191 // you're changing something here please also change that.
192 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
193 " compiler-builtins-c".to_string()
198 if builder.no_std(target) == Some(true) {
199 let mut features = "compiler-builtins-mem".to_string();
200 features.push_str(&compiler_builtins_c_feature);
202 // for no-std targets we only compile a few no_std crates
204 .args(&["-p", "alloc"])
205 .arg("--manifest-path")
206 .arg(builder.src.join("src/liballoc/Cargo.toml"))
208 .arg("compiler-builtins-mem compiler-builtins-c");
210 let mut features = builder.std_features();
211 features.push_str(&compiler_builtins_c_feature);
216 .arg("--manifest-path")
217 .arg(builder.src.join("src/libtest/Cargo.toml"));
219 // Help the libc crate compile by assisting it in finding various
220 // sysroot native libraries.
221 if target.contains("musl") {
222 if let Some(p) = builder.musl_root(target) {
223 let root = format!("native={}/lib", p.to_str().unwrap());
224 cargo.rustflag("-L").rustflag(&root);
228 if target.ends_with("-wasi") {
229 if let Some(p) = builder.wasi_root(target) {
230 let root = format!("native={}/lib/wasm32-wasi", p.to_str().unwrap());
231 cargo.rustflag("-L").rustflag(&root);
236 // By default, rustc uses `-Cembed-bitcode=yes`, and Cargo overrides that
237 // with `-Cembed-bitcode=no` for non-LTO builds. However, libstd must be
238 // built with bitcode so that the produced rlibs can be used for both LTO
239 // builds (which use bitcode) and non-LTO builds (which use object code).
240 // So we override the override here!
242 // But we don't bother for the stage 0 compiler because it's never used
245 cargo.rustflag("-Cembed-bitcode=yes");
248 // By default, rustc does not include unwind tables unless they are required
249 // for a particular target. They are not required by RISC-V targets, but
250 // compiling the standard library with them means that users can get
251 // backtraces without having to recompile the standard library themselves.
253 // This choice was discussed in https://github.com/rust-lang/rust/pull/69890
254 if target.contains("riscv") {
255 cargo.rustflag("-Cforce-unwind-tables=yes");
259 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
261 pub compiler: Compiler,
262 pub target_compiler: Compiler,
263 pub target: Interned<String>,
266 impl Step for StdLink {
269 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
273 /// Link all libstd rlibs/dylibs into the sysroot location.
275 /// Links those artifacts generated by `compiler` to the `stage` compiler's
276 /// sysroot for the specified `host` and `target`.
278 /// Note that this assumes that `compiler` has already generated the libstd
279 /// libraries for `target`, and this method will find them in the relevant
280 /// output directory.
281 fn run(self, builder: &Builder<'_>) {
282 let compiler = self.compiler;
283 let target_compiler = self.target_compiler;
284 let target = self.target;
285 builder.info(&format!(
286 "Copying stage{} std from stage{} ({} -> {} / {})",
287 target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
289 let libdir = builder.sysroot_libdir(target_compiler, target);
290 let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
291 add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
295 /// Copies sanitizer runtime libraries into target libdir.
297 builder: &Builder<'_>,
299 target: Interned<String>,
301 let runtimes: Vec<native::SanitizerRuntime> = builder.ensure(native::Sanitizers { target });
303 if builder.config.dry_run {
307 let mut target_deps = Vec::new();
308 let libdir = builder.sysroot_libdir(*compiler, target);
310 for runtime in &runtimes {
311 let dst = libdir.join(&runtime.name);
312 builder.copy(&runtime.path, &dst);
314 if target == "x86_64-apple-darwin" {
315 // Update the library install name reflect the fact it has been renamed.
316 let status = Command::new("install_name_tool")
318 .arg(format!("@rpath/{}", runtime.name))
321 .expect("failed to execute `install_name_tool`");
322 assert!(status.success());
325 target_deps.push(dst);
331 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
332 pub struct StartupObjects {
333 pub compiler: Compiler,
334 pub target: Interned<String>,
337 impl Step for StartupObjects {
338 type Output = Vec<PathBuf>;
340 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
341 run.path("src/rtstartup")
344 fn make_run(run: RunConfig<'_>) {
345 run.builder.ensure(StartupObjects {
346 compiler: run.builder.compiler(run.builder.top_stage, run.host),
351 /// Builds and prepare startup objects like rsbegin.o and rsend.o
353 /// These are primarily used on Windows right now for linking executables/dlls.
354 /// They don't require any library support as they're just plain old object
355 /// files, so we just use the nightly snapshot compiler to always build them (as
356 /// no other compilers are guaranteed to be available).
357 fn run(self, builder: &Builder<'_>) -> Vec<PathBuf> {
358 let for_compiler = self.compiler;
359 let target = self.target;
360 if !target.contains("windows-gnu") {
364 let mut target_deps = vec![];
366 let src_dir = &builder.src.join("src/rtstartup");
367 let dst_dir = &builder.native_dir(target).join("rtstartup");
368 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
369 t!(fs::create_dir_all(dst_dir));
371 for file in &["rsbegin", "rsend"] {
372 let src_file = &src_dir.join(file.to_string() + ".rs");
373 let dst_file = &dst_dir.join(file.to_string() + ".o");
374 if !up_to_date(src_file, dst_file) {
375 let mut cmd = Command::new(&builder.initial_rustc);
377 cmd.env("RUSTC_BOOTSTRAP", "1")
389 let target = sysroot_dir.join((*file).to_string() + ".o");
390 builder.copy(dst_file, &target);
391 target_deps.push(target);
394 for obj in ["crt2.o", "dllcrt2.o"].iter() {
395 let src = compiler_file(builder, builder.cc(target), target, obj);
396 let target = sysroot_dir.join(obj);
397 builder.copy(&src, &target);
398 target_deps.push(target);
405 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
407 pub target: Interned<String>,
408 pub compiler: Compiler,
411 impl Step for Rustc {
413 const ONLY_HOSTS: bool = true;
414 const DEFAULT: bool = true;
416 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
417 run.all_krates("rustc-main")
420 fn make_run(run: RunConfig<'_>) {
421 run.builder.ensure(Rustc {
422 compiler: run.builder.compiler(run.builder.top_stage, run.host),
427 /// Builds the compiler.
429 /// This will build the compiler for a particular stage of the build using
430 /// the `compiler` targeting the `target` architecture. The artifacts
431 /// created will also be linked into the sysroot directory.
432 fn run(self, builder: &Builder<'_>) {
433 let compiler = self.compiler;
434 let target = self.target;
436 builder.ensure(Std { compiler, target });
438 if builder.config.keep_stage.contains(&compiler.stage) {
439 builder.info("Warning: Using a potentially old librustc. This may not behave well.");
440 builder.ensure(RustcLink { compiler, target_compiler: compiler, target });
444 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
445 if compiler_to_use != compiler {
446 builder.ensure(Rustc { compiler: compiler_to_use, target });
448 .info(&format!("Uplifting stage1 rustc ({} -> {})", builder.config.build, target));
449 builder.ensure(RustcLink {
450 compiler: compiler_to_use,
451 target_compiler: compiler,
457 // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
459 compiler: builder.compiler(self.compiler.stage, builder.config.build),
460 target: builder.config.build,
463 let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
464 rustc_cargo(builder, &mut cargo, target);
466 builder.info(&format!(
467 "Building stage{} compiler artifacts ({} -> {})",
468 compiler.stage, &compiler.host, target
474 &librustc_stamp(builder, compiler, target),
479 builder.ensure(RustcLink {
480 compiler: builder.compiler(compiler.stage, builder.config.build),
481 target_compiler: compiler,
487 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
490 .arg(builder.rustc_features())
491 .arg("--manifest-path")
492 .arg(builder.src.join("src/rustc/Cargo.toml"));
493 rustc_cargo_env(builder, cargo, target);
496 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
497 // Set some configuration variables picked up by build scripts and
498 // the compiler alike
500 .env("CFG_RELEASE", builder.rust_release())
501 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
502 .env("CFG_VERSION", builder.rust_version())
503 .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default());
505 let libdir_relative = builder.config.libdir_relative().unwrap_or_else(|| Path::new("lib"));
506 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
508 if let Some(ref ver_date) = builder.rust_info.commit_date() {
509 cargo.env("CFG_VER_DATE", ver_date);
511 if let Some(ref ver_hash) = builder.rust_info.sha() {
512 cargo.env("CFG_VER_HASH", ver_hash);
514 if !builder.unstable_features() {
515 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
517 if let Some(ref s) = builder.config.rustc_default_linker {
518 cargo.env("CFG_DEFAULT_LINKER", s);
520 if builder.config.rustc_parallel {
521 cargo.rustflag("--cfg=parallel_compiler");
523 if builder.config.rust_verify_llvm_ir {
524 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
527 // Pass down configuration from the LLVM build into the build of
528 // librustc_llvm and librustc_codegen_llvm.
530 // Note that this is disabled if LLVM itself is disabled or we're in a check
531 // build. If we are in a check build we still go ahead here presuming we've
532 // detected that LLVM is alreay built and good to go which helps prevent
533 // busting caches (e.g. like #71152).
534 if builder.config.llvm_enabled()
535 && (builder.kind != Kind::Check
536 || crate::native::prebuilt_llvm_config(builder, target).is_ok())
538 if builder.is_rust_llvm(target) {
539 cargo.env("LLVM_RUSTLLVM", "1");
541 let llvm_config = builder.ensure(native::Llvm { target });
542 cargo.env("LLVM_CONFIG", &llvm_config);
543 let target_config = builder.config.target_config.get(&target);
544 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
545 cargo.env("CFG_LLVM_ROOT", s);
547 // Some LLVM linker flags (-L and -l) may be needed to link librustc_llvm.
548 if let Some(ref s) = builder.config.llvm_ldflags {
549 cargo.env("LLVM_LINKER_FLAGS", s);
551 // Building with a static libstdc++ is only supported on linux right now,
552 // not for MSVC or macOS
553 if builder.config.llvm_static_stdcpp
554 && !target.contains("freebsd")
555 && !target.contains("msvc")
556 && !target.contains("apple")
558 let file = compiler_file(builder, builder.cxx(target).unwrap(), target, "libstdc++.a");
559 cargo.env("LLVM_STATIC_STDCPP", file);
561 if builder.config.llvm_link_shared || builder.config.llvm_thin_lto {
562 cargo.env("LLVM_LINK_SHARED", "1");
564 if builder.config.llvm_use_libcxx {
565 cargo.env("LLVM_USE_LIBCXX", "1");
567 if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
568 cargo.env("LLVM_NDEBUG", "1");
573 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
575 pub compiler: Compiler,
576 pub target_compiler: Compiler,
577 pub target: Interned<String>,
580 impl Step for RustcLink {
583 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
587 /// Same as `std_link`, only for librustc
588 fn run(self, builder: &Builder<'_>) {
589 let compiler = self.compiler;
590 let target_compiler = self.target_compiler;
591 let target = self.target;
592 builder.info(&format!(
593 "Copying stage{} rustc from stage{} ({} -> {} / {})",
594 target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target
598 &builder.sysroot_libdir(target_compiler, target),
599 &builder.sysroot_libdir(target_compiler, compiler.host),
600 &librustc_stamp(builder, compiler, target),
605 /// Cargo's output path for the standard library in a given stage, compiled
606 /// by a particular compiler for the specified target.
608 builder: &Builder<'_>,
610 target: Interned<String>,
612 builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
615 /// Cargo's output path for librustc in a given stage, compiled by a particular
616 /// compiler for the specified target.
617 pub fn librustc_stamp(
618 builder: &Builder<'_>,
620 target: Interned<String>,
622 builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
625 pub fn compiler_file(
626 builder: &Builder<'_>,
628 target: Interned<String>,
631 let mut cmd = Command::new(compiler);
632 cmd.args(builder.cflags(target, GitRepo::Rustc));
633 cmd.arg(format!("-print-file-name={}", file));
634 let out = output(&mut cmd);
635 PathBuf::from(out.trim())
638 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
640 pub compiler: Compiler,
643 impl Step for Sysroot {
644 type Output = Interned<PathBuf>;
646 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
650 /// Returns the sysroot for the `compiler` specified that *this build system
653 /// That is, the sysroot for the stage0 compiler is not what the compiler
654 /// thinks it is by default, but it's the same as the default for stages
656 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
657 let compiler = self.compiler;
658 let sysroot = if compiler.stage == 0 {
659 builder.out.join(&compiler.host).join("stage0-sysroot")
661 builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
663 let _ = fs::remove_dir_all(&sysroot);
664 t!(fs::create_dir_all(&sysroot));
666 // Symlink the source root into the same location inside the sysroot,
667 // where `rust-src` component would go (`$sysroot/lib/rustlib/src/rust`),
668 // so that any tools relying on `rust-src` also work for local builds,
669 // and also for translating the virtual `/rustc/$hash` back to the real
670 // directory (for running tests with `rust.remap-debuginfo = true`).
671 let sysroot_lib_rustlib_src = sysroot.join("lib/rustlib/src");
672 t!(fs::create_dir_all(&sysroot_lib_rustlib_src));
673 let sysroot_lib_rustlib_src_rust = sysroot_lib_rustlib_src.join("rust");
674 if let Err(e) = symlink_dir(&builder.config, &builder.src, &sysroot_lib_rustlib_src_rust) {
676 "warning: creating symbolic link `{}` to `{}` failed with {}",
677 sysroot_lib_rustlib_src_rust.display(),
678 builder.src.display(),
681 if builder.config.rust_remap_debuginfo {
683 "warning: some `src/test/ui` tests will fail when lacking `{}`",
684 sysroot_lib_rustlib_src_rust.display(),
689 INTERNER.intern_path(sysroot)
693 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
694 pub struct Assemble {
695 /// The compiler which we will produce in this step. Assemble itself will
696 /// take care of ensuring that the necessary prerequisites to do so exist,
697 /// that is, this target can be a stage2 compiler and Assemble will build
698 /// previous stages for you.
699 pub target_compiler: Compiler,
702 impl Step for Assemble {
703 type Output = Compiler;
705 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
709 /// Prepare a new compiler from the artifacts in `stage`
711 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
712 /// must have been previously produced by the `stage - 1` builder.build
714 fn run(self, builder: &Builder<'_>) -> Compiler {
715 let target_compiler = self.target_compiler;
717 if target_compiler.stage == 0 {
719 builder.config.build, target_compiler.host,
720 "Cannot obtain compiler for non-native build triple at stage 0"
722 // The stage 0 compiler for the build triple is always pre-built.
723 return target_compiler;
726 // Get the compiler that we'll use to bootstrap ourselves.
728 // Note that this is where the recursive nature of the bootstrap
729 // happens, as this will request the previous stage's compiler on
730 // downwards to stage 0.
732 // Also note that we're building a compiler for the host platform. We
733 // only assume that we can run `build` artifacts, which means that to
734 // produce some other architecture compiler we need to start from
735 // `build` to get there.
737 // FIXME: Perhaps we should download those libraries?
738 // It would make builds faster...
740 // FIXME: It may be faster if we build just a stage 1 compiler and then
741 // use that to bootstrap this compiler forward.
742 let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build);
744 // Build the libraries for this compiler to link to (i.e., the libraries
745 // it uses at runtime). NOTE: Crates the target compiler compiles don't
746 // link to these. (FIXME: Is that correct? It seems to be correct most
747 // of the time but I think we do link to these for stage2/bin compilers
748 // when not performing a full bootstrap).
749 builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
751 let lld_install = if builder.config.lld_enabled {
752 Some(builder.ensure(native::Lld { target: target_compiler.host }))
757 let stage = target_compiler.stage;
758 let host = target_compiler.host;
759 builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
761 // Link in all dylibs to the libdir
762 let sysroot = builder.sysroot(target_compiler);
763 let rustc_libdir = builder.rustc_libdir(target_compiler);
764 t!(fs::create_dir_all(&rustc_libdir));
765 let src_libdir = builder.sysroot_libdir(build_compiler, host);
766 for f in builder.read_dir(&src_libdir) {
767 let filename = f.file_name().into_string().unwrap();
768 if is_dylib(&filename) {
769 builder.copy(&f.path(), &rustc_libdir.join(&filename));
773 let libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
774 if let Some(lld_install) = lld_install {
775 let src_exe = exe("lld", &target_compiler.host);
776 let dst_exe = exe("rust-lld", &target_compiler.host);
777 // we prepend this bin directory to the user PATH when linking Rust binaries. To
778 // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
779 let dst = libdir.parent().unwrap().join("bin");
780 t!(fs::create_dir_all(&dst));
781 builder.copy(&lld_install.join("bin").join(&src_exe), &dst.join(&dst_exe));
784 // Ensure that `libLLVM.so` ends up in the newly build compiler directory,
785 // so that it can be found when the newly built `rustc` is run.
786 dist::maybe_install_llvm_runtime(builder, target_compiler.host, &sysroot);
787 dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot);
789 // Link the compiler binary itself into place
790 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
791 let rustc = out_dir.join(exe("rustc_binary", &*host));
792 let bindir = sysroot.join("bin");
793 t!(fs::create_dir_all(&bindir));
794 let compiler = builder.rustc(target_compiler);
795 builder.copy(&rustc, &compiler);
801 /// Link some files into a rustc sysroot.
803 /// For a particular stage this will link the file listed in `stamp` into the
804 /// `sysroot_dst` provided.
805 pub fn add_to_sysroot(
806 builder: &Builder<'_>,
808 sysroot_host_dst: &Path,
811 t!(fs::create_dir_all(&sysroot_dst));
812 t!(fs::create_dir_all(&sysroot_host_dst));
813 for (path, host) in builder.read_stamp_file(stamp) {
815 builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
817 builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
823 builder: &Builder<'_>,
825 tail_args: Vec<String>,
827 additional_target_deps: Vec<PathBuf>,
830 if builder.config.dry_run {
834 // `target_root_dir` looks like $dir/$target/release
835 let target_root_dir = stamp.parent().unwrap();
836 // `target_deps_dir` looks like $dir/$target/release/deps
837 let target_deps_dir = target_root_dir.join("deps");
838 // `host_root_dir` looks like $dir/release
839 let host_root_dir = target_root_dir
841 .unwrap() // chop off `release`
843 .unwrap() // chop off `$target`
844 .join(target_root_dir.file_name().unwrap());
846 // Spawn Cargo slurping up its JSON output. We'll start building up the
847 // `deps` array of all files it generated along with a `toplevel` array of
848 // files we need to probe for later.
849 let mut deps = Vec::new();
850 let mut toplevel = Vec::new();
851 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
852 let (filenames, crate_types) = match msg {
853 CargoMessage::CompilerArtifact {
855 target: CargoTarget { crate_types },
857 } => (filenames, crate_types),
860 for filename in filenames {
861 // Skip files like executables
862 if !(filename.ends_with(".rlib")
863 || filename.ends_with(".lib")
864 || filename.ends_with(".a")
865 || is_dylib(&filename)
866 || (is_check && filename.ends_with(".rmeta")))
871 let filename = Path::new(&*filename);
873 // If this was an output file in the "host dir" we don't actually
874 // worry about it, it's not relevant for us
875 if filename.starts_with(&host_root_dir) {
876 // Unless it's a proc macro used in the compiler
877 if crate_types.iter().any(|t| t == "proc-macro") {
878 deps.push((filename.to_path_buf(), true));
883 // If this was output in the `deps` dir then this is a precise file
884 // name (hash included) so we start tracking it.
885 if filename.starts_with(&target_deps_dir) {
886 deps.push((filename.to_path_buf(), false));
890 // Otherwise this was a "top level artifact" which right now doesn't
891 // have a hash in the name, but there's a version of this file in
892 // the `deps` folder which *does* have a hash in the name. That's
893 // the one we'll want to we'll probe for it later.
895 // We do not use `Path::file_stem` or `Path::extension` here,
896 // because some generated files may have multiple extensions e.g.
897 // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
898 // split the file name by the last extension (`.lib`) while we need
899 // to split by all extensions (`.dll.lib`).
900 let expected_len = t!(filename.metadata()).len();
901 let filename = filename.file_name().unwrap().to_str().unwrap();
902 let mut parts = filename.splitn(2, '.');
903 let file_stem = parts.next().unwrap().to_owned();
904 let extension = parts.next().unwrap().to_owned();
906 toplevel.push((file_stem, extension, expected_len));
914 // Ok now we need to actually find all the files listed in `toplevel`. We've
915 // got a list of prefix/extensions and we basically just need to find the
916 // most recent file in the `deps` folder corresponding to each one.
917 let contents = t!(target_deps_dir.read_dir())
919 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
920 .collect::<Vec<_>>();
921 for (prefix, extension, expected_len) in toplevel {
922 let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
923 filename.starts_with(&prefix[..])
924 && filename[prefix.len()..].starts_with('-')
925 && filename.ends_with(&extension[..])
926 && meta.len() == expected_len
929 .max_by_key(|&&(_, _, ref metadata)| FileTime::from_last_modification_time(metadata));
930 let path_to_add = match max {
931 Some(triple) => triple.0.to_str().unwrap(),
932 None => panic!("no output generated for {:?} {:?}", prefix, extension),
934 if is_dylib(path_to_add) {
935 let candidate = format!("{}.lib", path_to_add);
936 let candidate = PathBuf::from(candidate);
937 if candidate.exists() {
938 deps.push((candidate, false));
941 deps.push((path_to_add.into(), false));
944 deps.extend(additional_target_deps.into_iter().map(|d| (d, false)));
946 let mut new_contents = Vec::new();
947 for (dep, proc_macro) in deps.iter() {
948 new_contents.extend(if *proc_macro { b"h" } else { b"t" });
949 new_contents.extend(dep.to_str().unwrap().as_bytes());
950 new_contents.extend(b"\0");
952 t!(fs::write(&stamp, &new_contents));
953 deps.into_iter().map(|(d, _)| d).collect()
957 builder: &Builder<'_>,
959 tail_args: Vec<String>,
960 cb: &mut dyn FnMut(CargoMessage<'_>),
962 let mut cargo = Command::from(cargo);
963 if builder.config.dry_run {
966 // Instruct Cargo to give us json messages on stdout, critically leaving
967 // stderr as piped so we can get those pretty colors.
968 let mut message_format = if builder.config.json_output {
971 String::from("json-render-diagnostics")
973 if let Some(s) = &builder.config.rustc_error_format {
974 message_format.push_str(",json-diagnostic-");
975 message_format.push_str(s);
977 cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
979 for arg in tail_args {
983 builder.verbose(&format!("running: {:?}", cargo));
984 let mut child = match cargo.spawn() {
986 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
989 // Spawn Cargo slurping up its JSON output. We'll start building up the
990 // `deps` array of all files it generated along with a `toplevel` array of
991 // files we need to probe for later.
992 let stdout = BufReader::new(child.stdout.take().unwrap());
993 for line in stdout.lines() {
995 match serde_json::from_str::<CargoMessage<'_>>(&line) {
997 if builder.config.json_output {
998 // Forward JSON to stdout.
999 println!("{}", line);
1003 // If this was informational, just print it out and continue
1004 Err(_) => println!("{}", line),
1008 // Make sure Cargo actually succeeded after we read all of its stdout.
1009 let status = t!(child.wait());
1010 if !status.success() {
1012 "command did not execute successfully: {:?}\n\
1013 expected success, got: {}",
1020 #[derive(Deserialize)]
1021 pub struct CargoTarget<'a> {
1022 crate_types: Vec<Cow<'a, str>>,
1025 #[derive(Deserialize)]
1026 #[serde(tag = "reason", rename_all = "kebab-case")]
1027 pub enum CargoMessage<'a> {
1029 package_id: Cow<'a, str>,
1030 features: Vec<Cow<'a, str>>,
1031 filenames: Vec<Cow<'a, str>>,
1032 target: CargoTarget<'a>,
1034 BuildScriptExecuted {
1035 package_id: Cow<'a, str>,