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 builder.ensure(RustcLink {
460 compiler: builder.compiler(compiler.stage, builder.config.build),
461 target_compiler: compiler,
467 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
468 cargo.arg("--features").arg(builder.rustc_features())
469 .arg("--manifest-path")
470 .arg(builder.src.join("src/rustc/Cargo.toml"));
471 rustc_cargo_env(builder, cargo, target);
474 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
475 // Set some configuration variables picked up by build scripts and
476 // the compiler alike
477 cargo.env("CFG_RELEASE", builder.rust_release())
478 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
479 .env("CFG_VERSION", builder.rust_version())
480 .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default());
482 let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
483 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
485 if let Some(ref ver_date) = builder.rust_info.commit_date() {
486 cargo.env("CFG_VER_DATE", ver_date);
488 if let Some(ref ver_hash) = builder.rust_info.sha() {
489 cargo.env("CFG_VER_HASH", ver_hash);
491 if !builder.unstable_features() {
492 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
494 if let Some(ref s) = builder.config.rustc_default_linker {
495 cargo.env("CFG_DEFAULT_LINKER", s);
497 if builder.config.rustc_parallel {
498 cargo.rustflag("--cfg=parallel_compiler");
500 if builder.config.rust_verify_llvm_ir {
501 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
504 // Pass down configuration from the LLVM build into the build of
505 // librustc_llvm and librustc_codegen_llvm.
507 // Note that this is disabled if LLVM itself is disabled or we're in a check
508 // build, where if we're in a check build there's no need to build all of
510 if builder.config.llvm_enabled() && builder.kind != Kind::Check {
511 if builder.is_rust_llvm(target) {
512 cargo.env("LLVM_RUSTLLVM", "1");
514 let llvm_config = builder.ensure(native::Llvm { target });
515 cargo.env("LLVM_CONFIG", &llvm_config);
516 let target_config = builder.config.target_config.get(&target);
517 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
518 cargo.env("CFG_LLVM_ROOT", s);
520 // Some LLVM linker flags (-L and -l) may be needed to link librustc_llvm.
521 if let Some(ref s) = builder.config.llvm_ldflags {
522 cargo.env("LLVM_LINKER_FLAGS", s);
524 // Building with a static libstdc++ is only supported on linux right now,
525 // not for MSVC or macOS
526 if builder.config.llvm_static_stdcpp &&
527 !target.contains("freebsd") &&
528 !target.contains("windows") &&
529 !target.contains("apple") {
530 let file = compiler_file(builder,
531 builder.cxx(target).unwrap(),
534 cargo.env("LLVM_STATIC_STDCPP", file);
536 if builder.config.llvm_link_shared || builder.config.llvm_thin_lto {
537 cargo.env("LLVM_LINK_SHARED", "1");
539 if builder.config.llvm_use_libcxx {
540 cargo.env("LLVM_USE_LIBCXX", "1");
542 if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
543 cargo.env("LLVM_NDEBUG", "1");
548 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
550 pub compiler: Compiler,
551 pub target_compiler: Compiler,
552 pub target: Interned<String>,
555 impl Step for RustcLink {
558 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
562 /// Same as `std_link`, only for librustc
563 fn run(self, builder: &Builder<'_>) {
564 let compiler = self.compiler;
565 let target_compiler = self.target_compiler;
566 let target = self.target;
567 builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
568 target_compiler.stage,
571 target_compiler.host,
575 &builder.sysroot_libdir(target_compiler, target),
576 &builder.sysroot_libdir(target_compiler, compiler.host),
577 &librustc_stamp(builder, compiler, target)
582 /// Cargo's output path for the standard library in a given stage, compiled
583 /// by a particular compiler for the specified target.
585 builder: &Builder<'_>,
587 target: Interned<String>,
589 builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
592 /// Cargo's output path for librustc in a given stage, compiled by a particular
593 /// compiler for the specified target.
594 pub fn librustc_stamp(
595 builder: &Builder<'_>,
597 target: Interned<String>,
599 builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
602 pub fn compiler_file(
603 builder: &Builder<'_>,
605 target: Interned<String>,
608 let mut cmd = Command::new(compiler);
609 cmd.args(builder.cflags(target, GitRepo::Rustc));
610 cmd.arg(format!("-print-file-name={}", file));
611 let out = output(&mut cmd);
612 PathBuf::from(out.trim())
615 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
617 pub compiler: Compiler,
620 impl Step for Sysroot {
621 type Output = Interned<PathBuf>;
623 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
627 /// Returns the sysroot for the `compiler` specified that *this build system
630 /// That is, the sysroot for the stage0 compiler is not what the compiler
631 /// thinks it is by default, but it's the same as the default for stages
633 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
634 let compiler = self.compiler;
635 let sysroot = if compiler.stage == 0 {
636 builder.out.join(&compiler.host).join("stage0-sysroot")
638 builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
640 let _ = fs::remove_dir_all(&sysroot);
641 t!(fs::create_dir_all(&sysroot));
642 INTERNER.intern_path(sysroot)
646 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
647 pub struct Assemble {
648 /// The compiler which we will produce in this step. Assemble itself will
649 /// take care of ensuring that the necessary prerequisites to do so exist,
650 /// that is, this target can be a stage2 compiler and Assemble will build
651 /// previous stages for you.
652 pub target_compiler: Compiler,
655 impl Step for Assemble {
656 type Output = Compiler;
658 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
662 /// Prepare a new compiler from the artifacts in `stage`
664 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
665 /// must have been previously produced by the `stage - 1` builder.build
667 fn run(self, builder: &Builder<'_>) -> Compiler {
668 let target_compiler = self.target_compiler;
670 if target_compiler.stage == 0 {
671 assert_eq!(builder.config.build, target_compiler.host,
672 "Cannot obtain compiler for non-native build triple at stage 0");
673 // The stage 0 compiler for the build triple is always pre-built.
674 return target_compiler;
677 // Get the compiler that we'll use to bootstrap ourselves.
679 // Note that this is where the recursive nature of the bootstrap
680 // happens, as this will request the previous stage's compiler on
681 // downwards to stage 0.
683 // Also note that we're building a compiler for the host platform. We
684 // only assume that we can run `build` artifacts, which means that to
685 // produce some other architecture compiler we need to start from
686 // `build` to get there.
688 // FIXME: Perhaps we should download those libraries?
689 // It would make builds faster...
691 // FIXME: It may be faster if we build just a stage 1 compiler and then
692 // use that to bootstrap this compiler forward.
694 builder.compiler(target_compiler.stage - 1, builder.config.build);
696 // Build the libraries for this compiler to link to (i.e., the libraries
697 // it uses at runtime). NOTE: Crates the target compiler compiles don't
698 // link to these. (FIXME: Is that correct? It seems to be correct most
699 // of the time but I think we do link to these for stage2/bin compilers
700 // when not performing a full bootstrap).
701 builder.ensure(Rustc {
702 compiler: build_compiler,
703 target: target_compiler.host,
706 let lld_install = if builder.config.lld_enabled {
707 Some(builder.ensure(native::Lld {
708 target: target_compiler.host,
714 let stage = target_compiler.stage;
715 let host = target_compiler.host;
716 builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
718 // Link in all dylibs to the libdir
719 let sysroot = builder.sysroot(target_compiler);
720 let rustc_libdir = builder.rustc_libdir(target_compiler);
721 t!(fs::create_dir_all(&rustc_libdir));
722 let src_libdir = builder.sysroot_libdir(build_compiler, host);
723 for f in builder.read_dir(&src_libdir) {
724 let filename = f.file_name().into_string().unwrap();
725 if is_dylib(&filename) {
726 builder.copy(&f.path(), &rustc_libdir.join(&filename));
730 let libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
731 if let Some(lld_install) = lld_install {
732 let src_exe = exe("lld", &target_compiler.host);
733 let dst_exe = exe("rust-lld", &target_compiler.host);
734 // we prepend this bin directory to the user PATH when linking Rust binaries. To
735 // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
736 let dst = libdir.parent().unwrap().join("bin");
737 t!(fs::create_dir_all(&dst));
738 builder.copy(&lld_install.join("bin").join(&src_exe), &dst.join(&dst_exe));
740 dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
742 // Link the compiler binary itself into place
743 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
744 let rustc = out_dir.join(exe("rustc_binary", &*host));
745 let bindir = sysroot.join("bin");
746 t!(fs::create_dir_all(&bindir));
747 let compiler = builder.rustc(target_compiler);
748 let _ = fs::remove_file(&compiler);
749 builder.copy(&rustc, &compiler);
755 /// Link some files into a rustc sysroot.
757 /// For a particular stage this will link the file listed in `stamp` into the
758 /// `sysroot_dst` provided.
759 pub fn add_to_sysroot(
760 builder: &Builder<'_>,
762 sysroot_host_dst: &Path,
765 t!(fs::create_dir_all(&sysroot_dst));
766 t!(fs::create_dir_all(&sysroot_host_dst));
767 for (path, host) in builder.read_stamp_file(stamp) {
769 builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
771 builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
776 pub fn run_cargo(builder: &Builder<'_>,
778 tail_args: Vec<String>,
780 additional_target_deps: Vec<PathBuf>,
784 if builder.config.dry_run {
788 // `target_root_dir` looks like $dir/$target/release
789 let target_root_dir = stamp.parent().unwrap();
790 // `target_deps_dir` looks like $dir/$target/release/deps
791 let target_deps_dir = target_root_dir.join("deps");
792 // `host_root_dir` looks like $dir/release
793 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
794 .parent().unwrap() // chop off `$target`
795 .join(target_root_dir.file_name().unwrap());
797 // Spawn Cargo slurping up its JSON output. We'll start building up the
798 // `deps` array of all files it generated along with a `toplevel` array of
799 // files we need to probe for later.
800 let mut deps = Vec::new();
801 let mut toplevel = Vec::new();
802 let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
803 let (filenames, crate_types) = match msg {
804 CargoMessage::CompilerArtifact {
806 target: CargoTarget {
810 } => (filenames, crate_types),
813 for filename in filenames {
814 // Skip files like executables
815 if !filename.ends_with(".rlib") &&
816 !filename.ends_with(".lib") &&
817 !filename.ends_with(".a") &&
818 !is_dylib(&filename) &&
819 !(is_check && filename.ends_with(".rmeta")) {
823 let filename = Path::new(&*filename);
825 // If this was an output file in the "host dir" we don't actually
826 // worry about it, it's not relevant for us
827 if filename.starts_with(&host_root_dir) {
828 // Unless it's a proc macro used in the compiler
829 if crate_types.iter().any(|t| t == "proc-macro") {
830 deps.push((filename.to_path_buf(), true));
835 // If this was output in the `deps` dir then this is a precise file
836 // name (hash included) so we start tracking it.
837 if filename.starts_with(&target_deps_dir) {
838 deps.push((filename.to_path_buf(), false));
842 // Otherwise this was a "top level artifact" which right now doesn't
843 // have a hash in the name, but there's a version of this file in
844 // the `deps` folder which *does* have a hash in the name. That's
845 // the one we'll want to we'll probe for it later.
847 // We do not use `Path::file_stem` or `Path::extension` here,
848 // because some generated files may have multiple extensions e.g.
849 // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
850 // split the file name by the last extension (`.lib`) while we need
851 // to split by all extensions (`.dll.lib`).
852 let expected_len = t!(filename.metadata()).len();
853 let filename = filename.file_name().unwrap().to_str().unwrap();
854 let mut parts = filename.splitn(2, '.');
855 let file_stem = parts.next().unwrap().to_owned();
856 let extension = parts.next().unwrap().to_owned();
858 toplevel.push((file_stem, extension, expected_len));
866 // Ok now we need to actually find all the files listed in `toplevel`. We've
867 // got a list of prefix/extensions and we basically just need to find the
868 // most recent file in the `deps` folder corresponding to each one.
869 let contents = t!(target_deps_dir.read_dir())
871 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
872 .collect::<Vec<_>>();
873 for (prefix, extension, expected_len) in toplevel {
874 let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
875 filename.starts_with(&prefix[..]) &&
876 filename[prefix.len()..].starts_with("-") &&
877 filename.ends_with(&extension[..]) &&
878 meta.len() == expected_len
880 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
881 FileTime::from_last_modification_time(metadata)
883 let path_to_add = match max {
884 Some(triple) => triple.0.to_str().unwrap(),
885 None => panic!("no output generated for {:?} {:?}", prefix, extension),
887 if is_dylib(path_to_add) {
888 let candidate = format!("{}.lib", path_to_add);
889 let candidate = PathBuf::from(candidate);
890 if candidate.exists() {
891 deps.push((candidate, false));
894 deps.push((path_to_add.into(), false));
897 deps.extend(additional_target_deps.into_iter().map(|d| (d, false)));
899 let mut new_contents = Vec::new();
900 for (dep, proc_macro) in deps.iter() {
901 new_contents.extend(if *proc_macro { b"h" } else { b"t" });
902 new_contents.extend(dep.to_str().unwrap().as_bytes());
903 new_contents.extend(b"\0");
905 t!(fs::write(&stamp, &new_contents));
906 deps.into_iter().map(|(d, _)| d).collect()
910 builder: &Builder<'_>,
912 tail_args: Vec<String>,
913 cb: &mut dyn FnMut(CargoMessage<'_>),
915 let mut cargo = Command::from(cargo);
916 if builder.config.dry_run {
919 // Instruct Cargo to give us json messages on stdout, critically leaving
920 // stderr as piped so we can get those pretty colors.
921 let mut message_format = String::from("json-render-diagnostics");
922 if let Some(s) = &builder.config.rustc_error_format {
923 message_format.push_str(",json-diagnostic-");
924 message_format.push_str(s);
926 cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
928 for arg in tail_args {
932 builder.verbose(&format!("running: {:?}", cargo));
933 let mut child = match cargo.spawn() {
935 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
938 // Spawn Cargo slurping up its JSON output. We'll start building up the
939 // `deps` array of all files it generated along with a `toplevel` array of
940 // files we need to probe for later.
941 let stdout = BufReader::new(child.stdout.take().unwrap());
942 for line in stdout.lines() {
944 match serde_json::from_str::<CargoMessage<'_>>(&line) {
946 // If this was informational, just print it out and continue
947 Err(_) => println!("{}", line)
951 // Make sure Cargo actually succeeded after we read all of its stdout.
952 let status = t!(child.wait());
953 if !status.success() {
954 eprintln!("command did not execute successfully: {:?}\n\
955 expected success, got: {}",
962 #[derive(Deserialize)]
963 pub struct CargoTarget<'a> {
964 crate_types: Vec<Cow<'a, str>>,
967 #[derive(Deserialize)]
968 #[serde(tag = "reason", rename_all = "kebab-case")]
969 pub enum CargoMessage<'a> {
971 package_id: Cow<'a, str>,
972 features: Vec<Cow<'a, str>>,
973 filenames: Vec<Cow<'a, str>>,
974 target: CargoTarget<'a>,
976 BuildScriptExecuted {
977 package_id: Cow<'a, str>,