1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Implementation of compiling various phases of the compiler and standard
14 //! This module contains some of the real meat in the rustbuild build system
15 //! which is where Cargo is used to compiler the standard library, libtest, and
16 //! compiler. This module is also responsible for assembling the sysroot as it
17 //! goes along from the output of the previous stage.
20 use std::fs::{self, File};
21 use std::io::BufReader;
22 use std::io::prelude::*;
23 use std::path::{Path, PathBuf};
24 use std::process::{Command, Stdio};
28 use build_helper::{output, mtime, up_to_date};
29 use filetime::FileTime;
32 use util::{exe, libdir, is_dylib, copy};
33 use {Build, Compiler, Mode};
37 use cache::{INTERNER, Interned};
38 use builder::{Step, RunConfig, ShouldRun, Builder};
40 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
42 pub target: Interned<String>,
43 pub compiler: Compiler,
48 const DEFAULT: bool = true;
50 fn should_run(run: ShouldRun) -> ShouldRun {
51 run.path("src/libstd").krate("std")
54 fn make_run(run: RunConfig) {
55 run.builder.ensure(Std {
56 compiler: run.builder.compiler(run.builder.top_stage, run.host),
61 /// Build the standard library.
63 /// This will build the standard library for a particular stage of the build
64 /// using the `compiler` targeting the `target` architecture. The artifacts
65 /// created will also be linked into the sysroot directory.
66 fn run(self, builder: &Builder) {
67 let build = builder.build;
68 let target = self.target;
69 let compiler = self.compiler;
71 builder.ensure(StartupObjects { compiler, target });
73 if build.force_use_stage1(compiler, target) {
74 let from = builder.compiler(1, build.build);
79 println!("Uplifting stage1 std ({} -> {})", from.host, target);
80 builder.ensure(StdLink {
82 target_compiler: compiler,
88 let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
89 println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
90 &compiler.host, target);
92 let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
93 build.clear_if_dirty(&out_dir, &builder.rustc(compiler));
94 let mut cargo = builder.cargo(compiler, Mode::Libstd, target, "build");
95 std_cargo(build, &compiler, target, &mut cargo);
98 &libstd_stamp(build, compiler, target));
100 builder.ensure(StdLink {
101 compiler: builder.compiler(compiler.stage, build.build),
102 target_compiler: compiler,
108 /// Configure cargo to compile the standard library, adding appropriate env vars
110 pub fn std_cargo(build: &Build,
112 target: Interned<String>,
113 cargo: &mut Command) {
114 let mut features = build.std_features();
116 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
117 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
120 // When doing a local rebuild we tell cargo that we're stage1 rather than
121 // stage0. This works fine if the local rust and being-built rust have the
122 // same view of what the default allocator is, but fails otherwise. Since
123 // we don't have a way to express an allocator preference yet, work
124 // around the issue in the case of a local rebuild with jemalloc disabled.
125 if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
126 features.push_str(" force_alloc_system");
129 if compiler.stage != 0 && build.config.sanitizers {
130 // This variable is used by the sanitizer runtime crates, e.g.
131 // rustc_lsan, to build the sanitizer runtime from C code
132 // When this variable is missing, those crates won't compile the C code,
133 // so we don't set this variable during stage0 where llvm-config is
135 // We also only build the runtimes when --enable-sanitizers (or its
136 // config.toml equivalent) is used
137 cargo.env("LLVM_CONFIG", build.llvm_config(target));
140 cargo.arg("--features").arg(features)
141 .arg("--manifest-path")
142 .arg(build.src.join("src/libstd/Cargo.toml"));
144 if let Some(target) = build.config.target_config.get(&target) {
145 if let Some(ref jemalloc) = target.jemalloc {
146 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
149 if target.contains("musl") {
150 if let Some(p) = build.musl_root(target) {
151 cargo.env("MUSL_ROOT", p);
156 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
158 pub compiler: Compiler,
159 pub target_compiler: Compiler,
160 pub target: Interned<String>,
163 impl Step for StdLink {
166 fn should_run(run: ShouldRun) -> ShouldRun {
170 /// Link all libstd rlibs/dylibs into the sysroot location.
172 /// Links those artifacts generated by `compiler` to a the `stage` compiler's
173 /// sysroot for the specified `host` and `target`.
175 /// Note that this assumes that `compiler` has already generated the libstd
176 /// libraries for `target`, and this method will find them in the relevant
177 /// output directory.
178 fn run(self, builder: &Builder) {
179 let build = builder.build;
180 let compiler = self.compiler;
181 let target_compiler = self.target_compiler;
182 let target = self.target;
183 println!("Copying stage{} std from stage{} ({} -> {} / {})",
184 target_compiler.stage,
187 target_compiler.host,
189 let libdir = builder.sysroot_libdir(target_compiler, target);
190 add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
192 if target.contains("musl") && !target.contains("mips") {
193 copy_musl_third_party_objects(build, target, &libdir);
196 if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
197 // The sanitizers are only built in stage1 or above, so the dylibs will
198 // be missing in stage0 and causes panic. See the `std()` function above
199 // for reason why the sanitizers are not built in stage0.
200 copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
203 builder.ensure(tool::CleanTools {
204 compiler: target_compiler,
211 /// Copies the crt(1,i,n).o startup objects
213 /// Only required for musl targets that statically link to libc
214 fn copy_musl_third_party_objects(build: &Build, target: Interned<String>, into: &Path) {
215 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
216 copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
220 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
221 for &sanitizer in &["asan", "tsan"] {
222 let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
223 let mut src_path = native_dir.join(sanitizer);
224 src_path.push("build");
225 src_path.push("lib");
226 src_path.push("darwin");
227 src_path.push(&filename);
228 copy(&src_path, &into.join(filename));
232 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
233 pub struct StartupObjects {
234 pub compiler: Compiler,
235 pub target: Interned<String>,
238 impl Step for StartupObjects {
241 fn should_run(run: ShouldRun) -> ShouldRun {
242 run.path("src/rtstartup")
245 fn make_run(run: RunConfig) {
246 run.builder.ensure(StartupObjects {
247 compiler: run.builder.compiler(run.builder.top_stage, run.host),
252 /// Build and prepare startup objects like rsbegin.o and rsend.o
254 /// These are primarily used on Windows right now for linking executables/dlls.
255 /// They don't require any library support as they're just plain old object
256 /// files, so we just use the nightly snapshot compiler to always build them (as
257 /// no other compilers are guaranteed to be available).
258 fn run(self, builder: &Builder) {
259 let build = builder.build;
260 let for_compiler = self.compiler;
261 let target = self.target;
262 if !target.contains("pc-windows-gnu") {
266 let src_dir = &build.src.join("src/rtstartup");
267 let dst_dir = &build.native_dir(target).join("rtstartup");
268 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
269 t!(fs::create_dir_all(dst_dir));
271 for file in &["rsbegin", "rsend"] {
272 let src_file = &src_dir.join(file.to_string() + ".rs");
273 let dst_file = &dst_dir.join(file.to_string() + ".o");
274 if !up_to_date(src_file, dst_file) {
275 let mut cmd = Command::new(&build.initial_rustc);
276 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
277 .arg("--cfg").arg("stage0")
278 .arg("--target").arg(target)
280 .arg("-o").arg(dst_file)
284 copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
287 for obj in ["crt2.o", "dllcrt2.o"].iter() {
288 copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
293 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
295 pub compiler: Compiler,
296 pub target: Interned<String>,
301 const DEFAULT: bool = true;
303 fn should_run(run: ShouldRun) -> ShouldRun {
304 run.path("src/libtest").krate("test")
307 fn make_run(run: RunConfig) {
308 run.builder.ensure(Test {
309 compiler: run.builder.compiler(run.builder.top_stage, run.host),
316 /// This will build libtest and supporting libraries for a particular stage of
317 /// the build using the `compiler` targeting the `target` architecture. The
318 /// artifacts created will also be linked into the sysroot directory.
319 fn run(self, builder: &Builder) {
320 let build = builder.build;
321 let target = self.target;
322 let compiler = self.compiler;
324 builder.ensure(Std { compiler, target });
326 if build.force_use_stage1(compiler, target) {
327 builder.ensure(Test {
328 compiler: builder.compiler(1, build.build),
331 println!("Uplifting stage1 test ({} -> {})", &build.build, target);
332 builder.ensure(TestLink {
333 compiler: builder.compiler(1, build.build),
334 target_compiler: compiler,
340 let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
341 println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
342 &compiler.host, target);
343 let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
344 build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
345 let mut cargo = builder.cargo(compiler, Mode::Libtest, target, "build");
346 test_cargo(build, &compiler, target, &mut cargo);
349 &libtest_stamp(build, compiler, target));
351 builder.ensure(TestLink {
352 compiler: builder.compiler(compiler.stage, build.build),
353 target_compiler: compiler,
359 /// Same as `std_cargo`, but for libtest
360 pub fn test_cargo(build: &Build,
361 _compiler: &Compiler,
362 _target: Interned<String>,
363 cargo: &mut Command) {
364 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
365 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
367 cargo.arg("--manifest-path")
368 .arg(build.src.join("src/libtest/Cargo.toml"));
371 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
372 pub struct TestLink {
373 pub compiler: Compiler,
374 pub target_compiler: Compiler,
375 pub target: Interned<String>,
378 impl Step for TestLink {
381 fn should_run(run: ShouldRun) -> ShouldRun {
385 /// Same as `std_link`, only for libtest
386 fn run(self, builder: &Builder) {
387 let build = builder.build;
388 let compiler = self.compiler;
389 let target_compiler = self.target_compiler;
390 let target = self.target;
391 println!("Copying stage{} test from stage{} ({} -> {} / {})",
392 target_compiler.stage,
395 target_compiler.host,
397 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
398 &libtest_stamp(build, compiler, target));
399 builder.ensure(tool::CleanTools {
400 compiler: target_compiler,
407 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
409 pub compiler: Compiler,
410 pub target: Interned<String>,
413 impl Step for Rustc {
415 const ONLY_HOSTS: bool = true;
416 const DEFAULT: bool = true;
418 fn should_run(run: ShouldRun) -> ShouldRun {
419 run.path("src/librustc").krate("rustc-main")
422 fn make_run(run: RunConfig) {
423 run.builder.ensure(Rustc {
424 compiler: run.builder.compiler(run.builder.top_stage, run.host),
429 /// Build the compiler.
431 /// This will build the compiler for a particular stage of the build using
432 /// the `compiler` targeting the `target` architecture. The artifacts
433 /// created will also be linked into the sysroot directory.
434 fn run(self, builder: &Builder) {
435 let build = builder.build;
436 let compiler = self.compiler;
437 let target = self.target;
439 builder.ensure(Test { compiler, target });
441 // Build LLVM for our target. This will implicitly build the host LLVM
443 builder.ensure(native::Llvm { target });
445 if build.force_use_stage1(compiler, target) {
446 builder.ensure(Rustc {
447 compiler: builder.compiler(1, build.build),
450 println!("Uplifting stage1 rustc ({} -> {})", &build.build, target);
451 builder.ensure(RustcLink {
452 compiler: builder.compiler(1, build.build),
453 target_compiler: compiler,
459 // Ensure that build scripts have a std to link against.
461 compiler: builder.compiler(self.compiler.stage, build.build),
465 let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
466 println!("Building stage{} compiler artifacts ({} -> {})",
467 compiler.stage, &compiler.host, target);
469 let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
470 build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
472 let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
473 rustc_cargo(build, &compiler, target, &mut cargo);
476 &librustc_stamp(build, compiler, target));
478 builder.ensure(RustcLink {
479 compiler: builder.compiler(compiler.stage, build.build),
480 target_compiler: compiler,
486 /// Same as `std_cargo`, but for libtest
487 pub fn rustc_cargo(build: &Build,
489 target: Interned<String>,
490 cargo: &mut Command) {
491 cargo.arg("--features").arg(build.rustc_features())
492 .arg("--manifest-path")
493 .arg(build.src.join("src/rustc/Cargo.toml"));
495 // Set some configuration variables picked up by build scripts and
496 // the compiler alike
497 cargo.env("CFG_RELEASE", build.rust_release())
498 .env("CFG_RELEASE_CHANNEL", &build.config.channel)
499 .env("CFG_VERSION", build.rust_version())
500 .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default());
502 if compiler.stage == 0 {
503 cargo.env("CFG_LIBDIR_RELATIVE", "lib");
505 let libdir_relative =
506 build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
507 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
510 // If we're not building a compiler with debugging information then remove
511 // these two env vars which would be set otherwise.
512 if build.config.rust_debuginfo_only_std {
513 cargo.env_remove("RUSTC_DEBUGINFO");
514 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
517 if let Some(ref ver_date) = build.rust_info.commit_date() {
518 cargo.env("CFG_VER_DATE", ver_date);
520 if let Some(ref ver_hash) = build.rust_info.sha() {
521 cargo.env("CFG_VER_HASH", ver_hash);
523 if !build.unstable_features() {
524 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
526 // Flag that rust llvm is in use
527 if build.is_rust_llvm(target) {
528 cargo.env("LLVM_RUSTLLVM", "1");
530 cargo.env("LLVM_CONFIG", build.llvm_config(target));
531 let target_config = build.config.target_config.get(&target);
532 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
533 cargo.env("CFG_LLVM_ROOT", s);
535 // Building with a static libstdc++ is only supported on linux right now,
536 // not for MSVC or macOS
537 if build.config.llvm_static_stdcpp &&
538 !target.contains("windows") &&
539 !target.contains("apple") {
540 cargo.env("LLVM_STATIC_STDCPP",
541 compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
543 if build.config.llvm_link_shared {
544 cargo.env("LLVM_LINK_SHARED", "1");
546 if let Some(ref s) = build.config.rustc_default_linker {
547 cargo.env("CFG_DEFAULT_LINKER", s);
549 if let Some(ref s) = build.config.rustc_default_ar {
550 cargo.env("CFG_DEFAULT_AR", s);
554 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
556 pub compiler: Compiler,
557 pub target_compiler: Compiler,
558 pub target: Interned<String>,
561 impl Step for RustcLink {
564 fn should_run(run: ShouldRun) -> ShouldRun {
568 /// Same as `std_link`, only for librustc
569 fn run(self, builder: &Builder) {
570 let build = builder.build;
571 let compiler = self.compiler;
572 let target_compiler = self.target_compiler;
573 let target = self.target;
574 println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
575 target_compiler.stage,
578 target_compiler.host,
580 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
581 &librustc_stamp(build, compiler, target));
582 builder.ensure(tool::CleanTools {
583 compiler: target_compiler,
585 mode: Mode::Librustc,
590 /// Cargo's output path for the standard library in a given stage, compiled
591 /// by a particular compiler for the specified target.
592 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
593 build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
596 /// Cargo's output path for libtest in a given stage, compiled by a particular
597 /// compiler for the specified target.
598 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
599 build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
602 /// Cargo's output path for librustc in a given stage, compiled by a particular
603 /// compiler for the specified target.
604 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
605 build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
608 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
609 let out = output(Command::new(compiler)
610 .arg(format!("-print-file-name={}", file)));
611 PathBuf::from(out.trim())
614 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
616 pub compiler: Compiler,
619 impl Step for Sysroot {
620 type Output = Interned<PathBuf>;
622 fn should_run(run: ShouldRun) -> ShouldRun {
626 /// Returns the sysroot for the `compiler` specified that *this build system
629 /// That is, the sysroot for the stage0 compiler is not what the compiler
630 /// thinks it is by default, but it's the same as the default for stages
632 fn run(self, builder: &Builder) -> Interned<PathBuf> {
633 let build = builder.build;
634 let compiler = self.compiler;
635 let sysroot = if compiler.stage == 0 {
636 build.out.join(&compiler.host).join("stage0-sysroot")
638 build.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, 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 {
659 run.path("src/rustc")
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` build.build
667 fn run(self, builder: &Builder) -> Compiler {
668 let build = builder.build;
669 let target_compiler = self.target_compiler;
671 if target_compiler.stage == 0 {
672 assert_eq!(build.build, target_compiler.host,
673 "Cannot obtain compiler for non-native build triple at stage 0");
674 // The stage 0 compiler for the build triple is always pre-built.
675 return target_compiler;
678 // Get the compiler that we'll use to bootstrap ourselves.
679 let build_compiler = if target_compiler.host != build.build {
680 // Build a compiler for the host platform. We cannot use the stage0
681 // compiler for the host platform for this because it doesn't have
682 // the libraries we need. FIXME: Perhaps we should download those
683 // libraries? It would make builds faster...
684 // FIXME: It may be faster if we build just a stage 1
685 // compiler and then use that to bootstrap this compiler
687 builder.compiler(target_compiler.stage - 1, build.build)
689 // Build the compiler we'll use to build the stage requested. This
690 // may build more than one compiler (going down to stage 0).
691 builder.compiler(target_compiler.stage - 1, target_compiler.host)
694 // Build the libraries for this compiler to link to (i.e., the libraries
695 // it uses at runtime). NOTE: Crates the target compiler compiles don't
696 // link to these. (FIXME: Is that correct? It seems to be correct most
697 // of the time but I think we do link to these for stage2/bin compilers
698 // when not performing a full bootstrap).
699 if builder.build.config.keep_stage.map_or(false, |s| target_compiler.stage <= s) {
700 builder.verbose("skipping compilation of compiler due to --keep-stage");
701 let compiler = build_compiler;
702 for stage in 0..min(target_compiler.stage, builder.config.keep_stage.unwrap()) {
703 let target_compiler = builder.compiler(stage, target_compiler.host);
704 let target = target_compiler.host;
705 builder.ensure(StdLink { compiler, target_compiler, target });
706 builder.ensure(TestLink { compiler, target_compiler, target });
707 builder.ensure(RustcLink { compiler, target_compiler, target });
710 builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
713 let stage = target_compiler.stage;
714 let host = target_compiler.host;
715 println!("Assembling stage{} compiler ({})", stage, host);
717 // Link in all dylibs to the libdir
718 let sysroot = builder.sysroot(target_compiler);
719 let sysroot_libdir = sysroot.join(libdir(&*host));
720 t!(fs::create_dir_all(&sysroot_libdir));
721 let src_libdir = builder.sysroot_libdir(build_compiler, host);
722 for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
723 let filename = f.file_name().into_string().unwrap();
724 if is_dylib(&filename) {
725 copy(&f.path(), &sysroot_libdir.join(&filename));
729 let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
731 // Link the compiler binary itself into place
732 let rustc = out_dir.join(exe("rustc", &*host));
733 let bindir = sysroot.join("bin");
734 t!(fs::create_dir_all(&bindir));
735 let compiler = builder.rustc(target_compiler);
736 let _ = fs::remove_file(&compiler);
737 copy(&rustc, &compiler);
743 /// Link some files into a rustc sysroot.
745 /// For a particular stage this will link the file listed in `stamp` into the
746 /// `sysroot_dst` provided.
747 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
748 t!(fs::create_dir_all(&sysroot_dst));
749 let mut contents = Vec::new();
750 t!(t!(File::open(stamp)).read_to_end(&mut contents));
751 // This is the method we use for extracting paths from the stamp file passed to us. See
752 // run_cargo for more information (in this file).
753 for part in contents.split(|b| *b == 0) {
757 let path = Path::new(t!(str::from_utf8(part)));
758 copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
762 // Avoiding a dependency on winapi to keep compile times down
764 fn stderr_isatty() -> bool {
766 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
769 fn stderr_isatty() -> bool {
772 type HANDLE = *mut u8;
773 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
775 fn GetStdHandle(which: DWORD) -> HANDLE;
776 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
779 let handle = GetStdHandle(STD_ERROR_HANDLE);
781 GetConsoleMode(handle, &mut out) != 0
785 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
786 // Instruct Cargo to give us json messages on stdout, critically leaving
787 // stderr as piped so we can get those pretty colors.
788 cargo.arg("--message-format").arg("json")
789 .stdout(Stdio::piped());
792 // since we pass message-format=json to cargo, we need to tell the rustc
793 // wrapper to give us colored output if necessary. This is because we
794 // only want Cargo's JSON output, not rustcs.
795 cargo.env("RUSTC_COLOR", "1");
798 build.verbose(&format!("running: {:?}", cargo));
799 let mut child = match cargo.spawn() {
801 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
804 // `target_root_dir` looks like $dir/$target/release
805 let target_root_dir = stamp.parent().unwrap();
806 // `target_deps_dir` looks like $dir/$target/release/deps
807 let target_deps_dir = target_root_dir.join("deps");
808 // `host_root_dir` looks like $dir/release
809 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
810 .parent().unwrap() // chop off `$target`
811 .join(target_root_dir.file_name().unwrap());
813 // Spawn Cargo slurping up its JSON output. We'll start building up the
814 // `deps` array of all files it generated along with a `toplevel` array of
815 // files we need to probe for later.
816 let mut deps = Vec::new();
817 let mut toplevel = Vec::new();
818 let stdout = BufReader::new(child.stdout.take().unwrap());
819 for line in stdout.lines() {
821 let json: serde_json::Value = if line.starts_with("{") {
822 t!(serde_json::from_str(&line))
824 // If this was informational, just print it out and continue
825 println!("{}", line);
828 if json["reason"].as_str() != Some("compiler-artifact") {
831 for filename in json["filenames"].as_array().unwrap() {
832 let filename = filename.as_str().unwrap();
833 // Skip files like executables
834 if !filename.ends_with(".rlib") &&
835 !filename.ends_with(".lib") &&
836 !is_dylib(&filename) {
840 let filename = Path::new(filename);
842 // If this was an output file in the "host dir" we don't actually
843 // worry about it, it's not relevant for us.
844 if filename.starts_with(&host_root_dir) {
848 // If this was output in the `deps` dir then this is a precise file
849 // name (hash included) so we start tracking it.
850 if filename.starts_with(&target_deps_dir) {
851 deps.push(filename.to_path_buf());
855 // Otherwise this was a "top level artifact" which right now doesn't
856 // have a hash in the name, but there's a version of this file in
857 // the `deps` folder which *does* have a hash in the name. That's
858 // the one we'll want to we'll probe for it later.
859 toplevel.push((filename.file_stem().unwrap()
860 .to_str().unwrap().to_string(),
861 filename.extension().unwrap().to_owned()
862 .to_str().unwrap().to_string()));
866 // Make sure Cargo actually succeeded after we read all of its stdout.
867 let status = t!(child.wait());
868 if !status.success() {
869 panic!("command did not execute successfully: {:?}\n\
870 expected success, got: {}",
875 // Ok now we need to actually find all the files listed in `toplevel`. We've
876 // got a list of prefix/extensions and we basically just need to find the
877 // most recent file in the `deps` folder corresponding to each one.
878 let contents = t!(target_deps_dir.read_dir())
880 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
881 .collect::<Vec<_>>();
882 for (prefix, extension) in toplevel {
883 let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
884 filename.starts_with(&prefix[..]) &&
885 filename[prefix.len()..].starts_with("-") &&
886 filename.ends_with(&extension[..])
888 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
889 FileTime::from_last_modification_time(metadata)
891 let path_to_add = match max {
892 Some(triple) => triple.0.to_str().unwrap(),
893 None => panic!("no output generated for {:?} {:?}", prefix, extension),
895 if is_dylib(path_to_add) {
896 let candidate = format!("{}.lib", path_to_add);
897 let candidate = PathBuf::from(candidate);
898 if candidate.exists() {
899 deps.push(candidate);
902 deps.push(path_to_add.into());
905 // Now we want to update the contents of the stamp file, if necessary. First
906 // we read off the previous contents along with its mtime. If our new
907 // contents (the list of files to copy) is different or if any dep's mtime
908 // is newer then we rewrite the stamp file.
910 let mut stamp_contents = Vec::new();
911 if let Ok(mut f) = File::open(stamp) {
912 t!(f.read_to_end(&mut stamp_contents));
914 let stamp_mtime = mtime(&stamp);
915 let mut new_contents = Vec::new();
917 let mut max_path = None;
919 let mtime = mtime(&dep);
920 if Some(mtime) > max {
922 max_path = Some(dep.clone());
924 new_contents.extend(dep.to_str().unwrap().as_bytes());
925 new_contents.extend(b"\0");
927 let max = max.unwrap();
928 let max_path = max_path.unwrap();
929 if stamp_contents == new_contents && max <= stamp_mtime {
932 if max > stamp_mtime {
933 build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
935 build.verbose(&format!("updating {:?} as deps changed", stamp));
937 t!(t!(File::create(stamp)).write_all(&new_contents));