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::BufReader;
13 use std::io::prelude::*;
14 use std::path::{Path, PathBuf};
15 use std::process::{Command, Stdio, exit};
18 use build_helper::{output, t, up_to_date};
19 use filetime::FileTime;
20 use serde::Deserialize;
24 use crate::builder::Cargo;
25 use crate::util::{exe, is_dylib};
26 use crate::{Compiler, Mode, GitRepo};
29 use crate::cache::{INTERNER, Interned};
30 use crate::builder::{Step, RunConfig, ShouldRun, Builder, Kind};
32 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
34 pub target: Interned<String>,
35 pub compiler: Compiler,
40 const DEFAULT: bool = true;
42 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
43 run.all_krates("test")
46 fn make_run(run: RunConfig<'_>) {
47 run.builder.ensure(Std {
48 compiler: run.builder.compiler(run.builder.top_stage, run.host),
53 /// Builds the standard library.
55 /// This will build the standard library for a particular stage of the build
56 /// using the `compiler` targeting the `target` architecture. The artifacts
57 /// created will also be linked into the sysroot directory.
58 fn run(self, builder: &Builder<'_>) {
59 let target = self.target;
60 let compiler = self.compiler;
62 if builder.config.keep_stage.contains(&compiler.stage) {
63 builder.info("Warning: Using a potentially old libstd. This may not behave well.");
64 builder.ensure(StdLink {
66 target_compiler: compiler,
72 let mut target_deps = builder.ensure(StartupObjects { compiler, target });
74 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
75 if compiler_to_use != compiler {
77 compiler: compiler_to_use,
80 builder.info(&format!("Uplifting stage1 std ({} -> {})", compiler_to_use.host, target));
82 // Even if we're not building std this stage, the new sysroot must
83 // still contain the third party objects needed by various targets.
84 copy_third_party_objects(builder, &compiler, target);
86 builder.ensure(StdLink {
87 compiler: compiler_to_use,
88 target_compiler: compiler,
94 target_deps.extend(copy_third_party_objects(builder, &compiler, target).into_iter());
96 let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
97 std_cargo(builder, &compiler, target, &mut cargo);
99 builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
100 &compiler.host, target));
104 &libstd_stamp(builder, compiler, target),
108 builder.ensure(StdLink {
109 compiler: builder.compiler(compiler.stage, builder.config.build),
110 target_compiler: compiler,
116 /// Copies third party objects needed by various targets.
117 fn copy_third_party_objects(builder: &Builder<'_>, compiler: &Compiler, target: Interned<String>)
120 let libdir = builder.sysroot_libdir(*compiler, target);
122 let mut target_deps = vec![];
124 let mut copy_and_stamp = |sourcedir: &Path, name: &str| {
125 let target = libdir.join(name);
127 &sourcedir.join(name),
130 target_deps.push(target);
133 // Copies the crt(1,i,n).o startup objects
135 // Since musl supports fully static linking, we can cross link for it even
136 // with a glibc-targeting toolchain, given we have the appropriate startup
137 // files. As those shipped with glibc won't work, copy the ones provided by
138 // musl so we have them on linux-gnu hosts.
139 if target.contains("musl") {
140 let srcdir = builder.musl_root(target).unwrap().join("lib");
141 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
142 copy_and_stamp(&srcdir, obj);
144 } else if target.ends_with("-wasi") {
145 let srcdir = builder.wasi_root(target).unwrap().join("lib/wasm32-wasi");
146 copy_and_stamp(&srcdir, "crt1.o");
149 // Copies libunwind.a compiled to be linked wit x86_64-fortanix-unknown-sgx.
151 // This target needs to be linked to Fortanix's port of llvm's libunwind.
152 // libunwind requires support for rwlock and printing to stderr,
153 // which is provided by std for this target.
154 if target == "x86_64-fortanix-unknown-sgx" {
155 let src_path_env = "X86_FORTANIX_SGX_LIBS";
156 let src = env::var(src_path_env).expect(&format!("{} not found in env", src_path_env));
157 copy_and_stamp(Path::new(&src), "libunwind.a");
163 /// Configure cargo to compile the standard library, adding appropriate env vars
165 pub fn std_cargo(builder: &Builder<'_>,
167 target: Interned<String>,
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 cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
191 " compiler-builtins-c".to_string()
196 if builder.no_std(target) == Some(true) {
197 let mut features = "compiler-builtins-mem".to_string();
198 features.push_str(&compiler_builtins_c_feature);
200 // for no-std targets we only compile a few no_std crates
202 .args(&["-p", "alloc"])
203 .arg("--manifest-path")
204 .arg(builder.src.join("src/liballoc/Cargo.toml"))
206 .arg("compiler-builtins-mem compiler-builtins-c");
208 let mut features = builder.std_features();
209 features.push_str(&compiler_builtins_c_feature);
211 if compiler.stage != 0 && builder.config.sanitizers {
212 // This variable is used by the sanitizer runtime crates, e.g.
213 // rustc_lsan, to build the sanitizer runtime from C code
214 // When this variable is missing, those crates won't compile the C code,
215 // so we don't set this variable during stage0 where llvm-config is
217 // We also only build the runtimes when --enable-sanitizers (or its
218 // config.toml equivalent) is used
219 let llvm_config = builder.ensure(native::Llvm {
220 target: builder.config.build,
222 cargo.env("LLVM_CONFIG", llvm_config);
223 cargo.env("RUSTC_BUILD_SANITIZERS", "1");
226 cargo.arg("--features").arg(features)
227 .arg("--manifest-path")
228 .arg(builder.src.join("src/libtest/Cargo.toml"));
230 // Help the libc crate compile by assisting it in finding various
231 // sysroot native libraries.
232 if target.contains("musl") {
233 if let Some(p) = builder.musl_root(target) {
234 let root = format!("native={}/lib", p.to_str().unwrap());
235 cargo.rustflag("-L").rustflag(&root);
239 if target.ends_with("-wasi") {
240 if let Some(p) = builder.wasi_root(target) {
241 let root = format!("native={}/lib/wasm32-wasi", p.to_str().unwrap());
242 cargo.rustflag("-L").rustflag(&root);
248 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
250 pub compiler: Compiler,
251 pub target_compiler: Compiler,
252 pub target: Interned<String>,
255 impl Step for StdLink {
258 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
262 /// Link all libstd rlibs/dylibs into the sysroot location.
264 /// Links those artifacts generated by `compiler` to the `stage` compiler's
265 /// sysroot for the specified `host` and `target`.
267 /// Note that this assumes that `compiler` has already generated the libstd
268 /// libraries for `target`, and this method will find them in the relevant
269 /// output directory.
270 fn run(self, builder: &Builder<'_>) {
271 let compiler = self.compiler;
272 let target_compiler = self.target_compiler;
273 let target = self.target;
274 builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
275 target_compiler.stage,
278 target_compiler.host,
280 let libdir = builder.sysroot_libdir(target_compiler, target);
281 let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
282 add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
284 if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
285 // The sanitizers are only built in stage1 or above, so the dylibs will
286 // be missing in stage0 and causes panic. See the `std()` function above
287 // for reason why the sanitizers are not built in stage0.
288 copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
293 fn copy_apple_sanitizer_dylibs(
294 builder: &Builder<'_>,
299 for &sanitizer in &["asan", "tsan"] {
300 let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
301 let mut src_path = native_dir.join(sanitizer);
302 src_path.push("build");
303 src_path.push("lib");
304 src_path.push("darwin");
305 src_path.push(&filename);
306 builder.copy(&src_path, &into.join(filename));
310 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
311 pub struct StartupObjects {
312 pub compiler: Compiler,
313 pub target: Interned<String>,
316 impl Step for StartupObjects {
317 type Output = Vec<PathBuf>;
319 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
320 run.path("src/rtstartup")
323 fn make_run(run: RunConfig<'_>) {
324 run.builder.ensure(StartupObjects {
325 compiler: run.builder.compiler(run.builder.top_stage, run.host),
330 /// Builds and prepare startup objects like rsbegin.o and rsend.o
332 /// These are primarily used on Windows right now for linking executables/dlls.
333 /// They don't require any library support as they're just plain old object
334 /// files, so we just use the nightly snapshot compiler to always build them (as
335 /// no other compilers are guaranteed to be available).
336 fn run(self, builder: &Builder<'_>) -> Vec<PathBuf> {
337 let for_compiler = self.compiler;
338 let target = self.target;
339 if !target.contains("windows-gnu") {
343 let mut target_deps = vec![];
345 let src_dir = &builder.src.join("src/rtstartup");
346 let dst_dir = &builder.native_dir(target).join("rtstartup");
347 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
348 t!(fs::create_dir_all(dst_dir));
350 for file in &["rsbegin", "rsend"] {
351 let src_file = &src_dir.join(file.to_string() + ".rs");
352 let dst_file = &dst_dir.join(file.to_string() + ".o");
353 if !up_to_date(src_file, dst_file) {
354 let mut cmd = Command::new(&builder.initial_rustc);
355 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
356 .arg("--cfg").arg("bootstrap")
357 .arg("--target").arg(target)
359 .arg("-o").arg(dst_file)
363 let target = sysroot_dir.join(file.to_string() + ".o");
364 builder.copy(dst_file, &target);
365 target_deps.push(target);
368 for obj in ["crt2.o", "dllcrt2.o"].iter() {
369 let src = compiler_file(builder,
373 let target = sysroot_dir.join(obj);
374 builder.copy(&src, &target);
375 target_deps.push(target);
382 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
384 pub target: Interned<String>,
385 pub compiler: Compiler,
388 impl Step for Rustc {
390 const ONLY_HOSTS: bool = true;
391 const DEFAULT: bool = true;
393 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
394 run.all_krates("rustc-main")
397 fn make_run(run: RunConfig<'_>) {
398 run.builder.ensure(Rustc {
399 compiler: run.builder.compiler(run.builder.top_stage, run.host),
404 /// Builds the compiler.
406 /// This will build the compiler for a particular stage of the build using
407 /// the `compiler` targeting the `target` architecture. The artifacts
408 /// created will also be linked into the sysroot directory.
409 fn run(self, builder: &Builder<'_>) {
410 let compiler = self.compiler;
411 let target = self.target;
413 builder.ensure(Std { compiler, target });
415 if builder.config.keep_stage.contains(&compiler.stage) {
416 builder.info("Warning: Using a potentially old librustc. This may not behave well.");
417 builder.ensure(RustcLink {
419 target_compiler: compiler,
425 let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
426 if compiler_to_use != compiler {
427 builder.ensure(Rustc {
428 compiler: compiler_to_use,
431 builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
432 builder.config.build, target));
433 builder.ensure(RustcLink {
434 compiler: compiler_to_use,
435 target_compiler: compiler,
441 // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
443 compiler: builder.compiler(self.compiler.stage, builder.config.build),
444 target: builder.config.build,
447 let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
448 rustc_cargo(builder, &mut cargo, target);
450 builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
451 compiler.stage, &compiler.host, target));
455 &librustc_stamp(builder, compiler, target),
459 // We used to build librustc_codegen_llvm as a separate step,
460 // which produced a dylib that the compiler would dlopen() at runtime.
461 // This meant that we only needed to make sure that libLLVM.so was
462 // installed by the time we went to run a tool using it - since
463 // librustc_codegen_llvm was effectively a standalone artifact,
464 // other crates were completely oblivious to its dependency
465 // on `libLLVM.so` during build time.
467 // However, librustc_codegen_llvm is now built as an ordinary
468 // crate during the same step as the rest of the compiler crates.
469 // This means that any crates depending on it will see the fact
470 // that it uses `libLLVM.so` as a native library, and will
471 // cause us to pass `-llibLLVM.so` to the linker when we link
474 // For `rustc` itself, this works out fine.
475 // During the `Assemble` step, we call `dist::maybe_install_llvm_dylib`
476 // to copy libLLVM.so into the `stage` directory. We then link
477 // the compiler binary, which will find `libLLVM.so` in the correct place.
479 // However, this is insufficient for tools that are build against stage0
480 // (e.g. stage1 rustdoc). Since `Assemble` for stage0 doesn't actually do anything,
481 // we won't have `libLLVM.so` in the stage0 sysroot. In the past, this wasn't
482 // a problem - we would copy the tool binary into its correct stage directory
483 // (e.g. stage1 for a stage1 rustdoc built against a stage0 compiler).
484 // Since libLLVM.so wasn't resolved until runtime, it was fine for it to
485 // not exist while we were building it.
487 // To ensure that we can still build stage1 tools against a stage0 compiler,
488 // we explicitly copy libLLVM.so into the stage0 sysroot when building
489 // the stage0 compiler. This ensures that tools built against stage0
490 // will see libLLVM.so at build time, making the linker happy.
491 if compiler.stage == 0 {
492 builder.info(&format!("Installing libLLVM.so to stage 0 ({})", compiler.host));
493 let sysroot = builder.sysroot(compiler);
494 dist::maybe_install_llvm_dylib(builder, compiler.host, &sysroot);
497 builder.ensure(RustcLink {
498 compiler: builder.compiler(compiler.stage, builder.config.build),
499 target_compiler: compiler,
505 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
506 cargo.arg("--features").arg(builder.rustc_features())
507 .arg("--manifest-path")
508 .arg(builder.src.join("src/rustc/Cargo.toml"));
509 rustc_cargo_env(builder, cargo, target);
512 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
513 // Set some configuration variables picked up by build scripts and
514 // the compiler alike
515 cargo.env("CFG_RELEASE", builder.rust_release())
516 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
517 .env("CFG_VERSION", builder.rust_version())
518 .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default());
520 let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
521 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
523 if let Some(ref ver_date) = builder.rust_info.commit_date() {
524 cargo.env("CFG_VER_DATE", ver_date);
526 if let Some(ref ver_hash) = builder.rust_info.sha() {
527 cargo.env("CFG_VER_HASH", ver_hash);
529 if !builder.unstable_features() {
530 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
532 if let Some(ref s) = builder.config.rustc_default_linker {
533 cargo.env("CFG_DEFAULT_LINKER", s);
535 if builder.config.rustc_parallel {
536 cargo.rustflag("--cfg=parallel_compiler");
538 if builder.config.rust_verify_llvm_ir {
539 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
542 // Pass down configuration from the LLVM build into the build of
543 // librustc_llvm and librustc_codegen_llvm.
545 // Note that this is disabled if LLVM itself is disabled or we're in a check
546 // build, where if we're in a check build there's no need to build all of
548 if builder.config.llvm_enabled() && builder.kind != Kind::Check {
549 if builder.is_rust_llvm(target) {
550 cargo.env("LLVM_RUSTLLVM", "1");
552 let llvm_config = builder.ensure(native::Llvm { target });
553 cargo.env("LLVM_CONFIG", &llvm_config);
554 let target_config = builder.config.target_config.get(&target);
555 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
556 cargo.env("CFG_LLVM_ROOT", s);
558 // Some LLVM linker flags (-L and -l) may be needed to link librustc_llvm.
559 if let Some(ref s) = builder.config.llvm_ldflags {
560 cargo.env("LLVM_LINKER_FLAGS", s);
562 // Building with a static libstdc++ is only supported on linux right now,
563 // not for MSVC or macOS
564 if builder.config.llvm_static_stdcpp &&
565 !target.contains("freebsd") &&
566 !target.contains("windows") &&
567 !target.contains("apple") {
568 let file = compiler_file(builder,
569 builder.cxx(target).unwrap(),
572 cargo.env("LLVM_STATIC_STDCPP", file);
574 if builder.config.llvm_link_shared || builder.config.llvm_thin_lto {
575 cargo.env("LLVM_LINK_SHARED", "1");
577 if builder.config.llvm_use_libcxx {
578 cargo.env("LLVM_USE_LIBCXX", "1");
580 if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
581 cargo.env("LLVM_NDEBUG", "1");
586 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
588 pub compiler: Compiler,
589 pub target_compiler: Compiler,
590 pub target: Interned<String>,
593 impl Step for RustcLink {
596 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
600 /// Same as `std_link`, only for librustc
601 fn run(self, builder: &Builder<'_>) {
602 let compiler = self.compiler;
603 let target_compiler = self.target_compiler;
604 let target = self.target;
605 builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
606 target_compiler.stage,
609 target_compiler.host,
613 &builder.sysroot_libdir(target_compiler, target),
614 &builder.sysroot_libdir(target_compiler, compiler.host),
615 &librustc_stamp(builder, compiler, target)
620 /// Cargo's output path for the standard library in a given stage, compiled
621 /// by a particular compiler for the specified target.
623 builder: &Builder<'_>,
625 target: Interned<String>,
627 builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
630 /// Cargo's output path for librustc in a given stage, compiled by a particular
631 /// compiler for the specified target.
632 pub fn librustc_stamp(
633 builder: &Builder<'_>,
635 target: Interned<String>,
637 builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
640 pub fn compiler_file(
641 builder: &Builder<'_>,
643 target: Interned<String>,
646 let mut cmd = Command::new(compiler);
647 cmd.args(builder.cflags(target, GitRepo::Rustc));
648 cmd.arg(format!("-print-file-name={}", file));
649 let out = output(&mut cmd);
650 PathBuf::from(out.trim())
653 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
655 pub compiler: Compiler,
658 impl Step for Sysroot {
659 type Output = Interned<PathBuf>;
661 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
665 /// Returns the sysroot for the `compiler` specified that *this build system
668 /// That is, the sysroot for the stage0 compiler is not what the compiler
669 /// thinks it is by default, but it's the same as the default for stages
671 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
672 let compiler = self.compiler;
673 let sysroot = if compiler.stage == 0 {
674 builder.out.join(&compiler.host).join("stage0-sysroot")
676 builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
678 let _ = fs::remove_dir_all(&sysroot);
679 t!(fs::create_dir_all(&sysroot));
680 INTERNER.intern_path(sysroot)
684 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
685 pub struct Assemble {
686 /// The compiler which we will produce in this step. Assemble itself will
687 /// take care of ensuring that the necessary prerequisites to do so exist,
688 /// that is, this target can be a stage2 compiler and Assemble will build
689 /// previous stages for you.
690 pub target_compiler: Compiler,
693 impl Step for Assemble {
694 type Output = Compiler;
696 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
700 /// Prepare a new compiler from the artifacts in `stage`
702 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
703 /// must have been previously produced by the `stage - 1` builder.build
705 fn run(self, builder: &Builder<'_>) -> Compiler {
706 let target_compiler = self.target_compiler;
708 if target_compiler.stage == 0 {
709 assert_eq!(builder.config.build, target_compiler.host,
710 "Cannot obtain compiler for non-native build triple at stage 0");
711 // The stage 0 compiler for the build triple is always pre-built.
712 return target_compiler;
715 // Get the compiler that we'll use to bootstrap ourselves.
717 // Note that this is where the recursive nature of the bootstrap
718 // happens, as this will request the previous stage's compiler on
719 // downwards to stage 0.
721 // Also note that we're building a compiler for the host platform. We
722 // only assume that we can run `build` artifacts, which means that to
723 // produce some other architecture compiler we need to start from
724 // `build` to get there.
726 // FIXME: Perhaps we should download those libraries?
727 // It would make builds faster...
729 // FIXME: It may be faster if we build just a stage 1 compiler and then
730 // use that to bootstrap this compiler forward.
732 builder.compiler(target_compiler.stage - 1, builder.config.build);
734 // Build the libraries for this compiler to link to (i.e., the libraries
735 // it uses at runtime). NOTE: Crates the target compiler compiles don't
736 // link to these. (FIXME: Is that correct? It seems to be correct most
737 // of the time but I think we do link to these for stage2/bin compilers
738 // when not performing a full bootstrap).
739 builder.ensure(Rustc {
740 compiler: build_compiler,
741 target: target_compiler.host,
744 let lld_install = if builder.config.lld_enabled {
745 Some(builder.ensure(native::Lld {
746 target: target_compiler.host,
752 let stage = target_compiler.stage;
753 let host = target_compiler.host;
754 builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
756 // Link in all dylibs to the libdir
757 let sysroot = builder.sysroot(target_compiler);
758 let rustc_libdir = builder.rustc_libdir(target_compiler);
759 t!(fs::create_dir_all(&rustc_libdir));
760 let src_libdir = builder.sysroot_libdir(build_compiler, host);
761 for f in builder.read_dir(&src_libdir) {
762 let filename = f.file_name().into_string().unwrap();
763 if is_dylib(&filename) {
764 builder.copy(&f.path(), &rustc_libdir.join(&filename));
768 let libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
769 if let Some(lld_install) = lld_install {
770 let src_exe = exe("lld", &target_compiler.host);
771 let dst_exe = exe("rust-lld", &target_compiler.host);
772 // we prepend this bin directory to the user PATH when linking Rust binaries. To
773 // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
774 let dst = libdir.parent().unwrap().join("bin");
775 t!(fs::create_dir_all(&dst));
776 builder.copy(&lld_install.join("bin").join(&src_exe), &dst.join(&dst_exe));
779 // Ensure that `libLLVM.so` ends up in the newly build compiler directory,
780 // so that it can be found when the newly built `rustc` is run.
781 dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
783 // Link the compiler binary itself into place
784 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
785 let rustc = out_dir.join(exe("rustc_binary", &*host));
786 let bindir = sysroot.join("bin");
787 t!(fs::create_dir_all(&bindir));
788 let compiler = builder.rustc(target_compiler);
789 let _ = fs::remove_file(&compiler);
790 builder.copy(&rustc, &compiler);
796 /// Link some files into a rustc sysroot.
798 /// For a particular stage this will link the file listed in `stamp` into the
799 /// `sysroot_dst` provided.
800 pub fn add_to_sysroot(
801 builder: &Builder<'_>,
803 sysroot_host_dst: &Path,
806 t!(fs::create_dir_all(&sysroot_dst));
807 t!(fs::create_dir_all(&sysroot_host_dst));
808 for (path, host) in builder.read_stamp_file(stamp) {
810 builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
812 builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
817 pub fn run_cargo(builder: &Builder<'_>,
819 tail_args: Vec<String>,
821 additional_target_deps: Vec<PathBuf>,
825 if builder.config.dry_run {
829 // `target_root_dir` looks like $dir/$target/release
830 let target_root_dir = stamp.parent().unwrap();
831 // `target_deps_dir` looks like $dir/$target/release/deps
832 let target_deps_dir = target_root_dir.join("deps");
833 // `host_root_dir` looks like $dir/release
834 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
835 .parent().unwrap() // chop off `$target`
836 .join(target_root_dir.file_name().unwrap());
838 // Spawn Cargo slurping up its JSON output. We'll start building up the
839 // `deps` array of all files it generated along with a `toplevel` array of
840 // files we need to probe for later.
841 let mut deps = Vec::new();
842 let mut toplevel = Vec::new();
843 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
844 let (filenames, crate_types) = match msg {
845 CargoMessage::CompilerArtifact {
847 target: CargoTarget {
851 } => (filenames, crate_types),
854 for filename in filenames {
855 // Skip files like executables
856 if !filename.ends_with(".rlib") &&
857 !filename.ends_with(".lib") &&
858 !filename.ends_with(".a") &&
859 !is_dylib(&filename) &&
860 !(is_check && filename.ends_with(".rmeta")) {
864 let filename = Path::new(&*filename);
866 // If this was an output file in the "host dir" we don't actually
867 // worry about it, it's not relevant for us
868 if filename.starts_with(&host_root_dir) {
869 // Unless it's a proc macro used in the compiler
870 if crate_types.iter().any(|t| t == "proc-macro") {
871 deps.push((filename.to_path_buf(), true));
876 // If this was output in the `deps` dir then this is a precise file
877 // name (hash included) so we start tracking it.
878 if filename.starts_with(&target_deps_dir) {
879 deps.push((filename.to_path_buf(), false));
883 // Otherwise this was a "top level artifact" which right now doesn't
884 // have a hash in the name, but there's a version of this file in
885 // the `deps` folder which *does* have a hash in the name. That's
886 // the one we'll want to we'll probe for it later.
888 // We do not use `Path::file_stem` or `Path::extension` here,
889 // because some generated files may have multiple extensions e.g.
890 // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
891 // split the file name by the last extension (`.lib`) while we need
892 // to split by all extensions (`.dll.lib`).
893 let expected_len = t!(filename.metadata()).len();
894 let filename = filename.file_name().unwrap().to_str().unwrap();
895 let mut parts = filename.splitn(2, '.');
896 let file_stem = parts.next().unwrap().to_owned();
897 let extension = parts.next().unwrap().to_owned();
899 toplevel.push((file_stem, extension, expected_len));
907 // Ok now we need to actually find all the files listed in `toplevel`. We've
908 // got a list of prefix/extensions and we basically just need to find the
909 // most recent file in the `deps` folder corresponding to each one.
910 let contents = t!(target_deps_dir.read_dir())
912 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
913 .collect::<Vec<_>>();
914 for (prefix, extension, expected_len) in toplevel {
915 let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
916 filename.starts_with(&prefix[..]) &&
917 filename[prefix.len()..].starts_with("-") &&
918 filename.ends_with(&extension[..]) &&
919 meta.len() == expected_len
921 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
922 FileTime::from_last_modification_time(metadata)
924 let path_to_add = match max {
925 Some(triple) => triple.0.to_str().unwrap(),
926 None => panic!("no output generated for {:?} {:?}", prefix, extension),
928 if is_dylib(path_to_add) {
929 let candidate = format!("{}.lib", path_to_add);
930 let candidate = PathBuf::from(candidate);
931 if candidate.exists() {
932 deps.push((candidate, false));
935 deps.push((path_to_add.into(), false));
938 deps.extend(additional_target_deps.into_iter().map(|d| (d, false)));
940 let mut new_contents = Vec::new();
941 for (dep, proc_macro) in deps.iter() {
942 new_contents.extend(if *proc_macro { b"h" } else { b"t" });
943 new_contents.extend(dep.to_str().unwrap().as_bytes());
944 new_contents.extend(b"\0");
946 t!(fs::write(&stamp, &new_contents));
947 deps.into_iter().map(|(d, _)| d).collect()
951 builder: &Builder<'_>,
953 tail_args: Vec<String>,
954 cb: &mut dyn FnMut(CargoMessage<'_>),
956 let mut cargo = Command::from(cargo);
957 if builder.config.dry_run {
960 // Instruct Cargo to give us json messages on stdout, critically leaving
961 // stderr as piped so we can get those pretty colors.
962 let mut message_format = String::from("json-render-diagnostics");
963 if let Some(s) = &builder.config.rustc_error_format {
964 message_format.push_str(",json-diagnostic-");
965 message_format.push_str(s);
967 cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
969 for arg in tail_args {
973 builder.verbose(&format!("running: {:?}", cargo));
974 let mut child = match cargo.spawn() {
976 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
979 // Spawn Cargo slurping up its JSON output. We'll start building up the
980 // `deps` array of all files it generated along with a `toplevel` array of
981 // files we need to probe for later.
982 let stdout = BufReader::new(child.stdout.take().unwrap());
983 for line in stdout.lines() {
985 match serde_json::from_str::<CargoMessage<'_>>(&line) {
987 // If this was informational, just print it out and continue
988 Err(_) => println!("{}", line)
992 // Make sure Cargo actually succeeded after we read all of its stdout.
993 let status = t!(child.wait());
994 if !status.success() {
995 eprintln!("command did not execute successfully: {:?}\n\
996 expected success, got: {}",
1003 #[derive(Deserialize)]
1004 pub struct CargoTarget<'a> {
1005 crate_types: Vec<Cow<'a, str>>,
1008 #[derive(Deserialize)]
1009 #[serde(tag = "reason", rename_all = "kebab-case")]
1010 pub enum CargoMessage<'a> {
1012 package_id: Cow<'a, str>,
1013 features: Vec<Cow<'a, str>>,
1014 filenames: Vec<Cow<'a, str>>,
1015 target: CargoTarget<'a>,
1017 BuildScriptExecuted {
1018 package_id: Cow<'a, str>,