]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Fix StartupObject build
[rust.git] / src / bootstrap / compile.rs
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.
4 //
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.
10
11 //! Implementation of compiling various phases of the compiler and standard
12 //! library.
13 //!
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.
18
19 use std::env;
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};
25 use std::str;
26 use std::cmp::min;
27
28 use build_helper::{output, mtime, up_to_date};
29 use filetime::FileTime;
30 use serde_json;
31
32 use util::{exe, libdir, is_dylib, copy};
33 use {Build, Compiler, Mode};
34 use native;
35
36 use cache::{INTERNER, Interned};
37 use builder::{Step, RunConfig, ShouldRun, Builder};
38
39 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
40 pub struct Std {
41     pub target: Interned<String>,
42     pub compiler: Compiler,
43 }
44
45 impl Step for Std {
46     type Output = ();
47     const DEFAULT: bool = true;
48
49     fn should_run(run: ShouldRun) -> ShouldRun {
50         run.path("src/libstd").krate("std")
51     }
52
53     fn make_run(run: RunConfig) {
54         run.builder.ensure(Std {
55             compiler: run.builder.compiler(run.builder.top_stage, run.host),
56             target: run.target,
57         });
58     }
59
60     /// Build the standard library.
61     ///
62     /// This will build the standard library for a particular stage of the build
63     /// using the `compiler` targeting the `target` architecture. The artifacts
64     /// created will also be linked into the sysroot directory.
65     fn run(self, builder: &Builder) {
66         let build = builder.build;
67         let target = self.target;
68         let compiler = self.compiler;
69
70         builder.ensure(StartupObjects { compiler, target });
71
72         if build.force_use_stage1(compiler, target) {
73             let from = builder.compiler(1, build.build);
74             builder.ensure(Std {
75                 compiler: from,
76                 target: target,
77             });
78             println!("Uplifting stage1 std ({} -> {})", from.host, target);
79             builder.ensure(StdLink {
80                 compiler: from,
81                 target_compiler: compiler,
82                 target: target,
83             });
84             return;
85         }
86
87         let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
88         println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
89                 &compiler.host, target);
90
91         let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
92         build.clear_if_dirty(&out_dir, &builder.rustc(compiler));
93         let mut cargo = builder.cargo(compiler, Mode::Libstd, target, "build");
94         let mut features = build.std_features();
95
96         if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
97             cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
98         }
99
100         // When doing a local rebuild we tell cargo that we're stage1 rather than
101         // stage0. This works fine if the local rust and being-built rust have the
102         // same view of what the default allocator is, but fails otherwise. Since
103         // we don't have a way to express an allocator preference yet, work
104         // around the issue in the case of a local rebuild with jemalloc disabled.
105         if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
106             features.push_str(" force_alloc_system");
107         }
108
109         if compiler.stage != 0 && build.config.sanitizers {
110             // This variable is used by the sanitizer runtime crates, e.g.
111             // rustc_lsan, to build the sanitizer runtime from C code
112             // When this variable is missing, those crates won't compile the C code,
113             // so we don't set this variable during stage0 where llvm-config is
114             // missing
115             // We also only build the runtimes when --enable-sanitizers (or its
116             // config.toml equivalent) is used
117             cargo.env("LLVM_CONFIG", build.llvm_config(target));
118         }
119
120         cargo.arg("--features").arg(features)
121             .arg("--manifest-path")
122             .arg(build.src.join("src/libstd/Cargo.toml"));
123
124         if let Some(target) = build.config.target_config.get(&target) {
125             if let Some(ref jemalloc) = target.jemalloc {
126                 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
127             }
128         }
129         if target.contains("musl") {
130             if let Some(p) = build.musl_root(target) {
131                 cargo.env("MUSL_ROOT", p);
132             }
133         }
134
135         run_cargo(build,
136                 &mut cargo,
137                 &libstd_stamp(build, compiler, target));
138
139         builder.ensure(StdLink {
140             compiler: builder.compiler(compiler.stage, build.build),
141             target_compiler: compiler,
142             target: target,
143         });
144     }
145 }
146
147
148 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
149 struct StdLink {
150     pub compiler: Compiler,
151     pub target_compiler: Compiler,
152     pub target: Interned<String>,
153 }
154
155 impl Step for StdLink {
156     type Output = ();
157
158     fn should_run(run: ShouldRun) -> ShouldRun {
159         run.never()
160     }
161
162     /// Link all libstd rlibs/dylibs into the sysroot location.
163     ///
164     /// Links those artifacts generated by `compiler` to a the `stage` compiler's
165     /// sysroot for the specified `host` and `target`.
166     ///
167     /// Note that this assumes that `compiler` has already generated the libstd
168     /// libraries for `target`, and this method will find them in the relevant
169     /// output directory.
170     fn run(self, builder: &Builder) {
171         let build = builder.build;
172         let compiler = self.compiler;
173         let target_compiler = self.target_compiler;
174         let target = self.target;
175         println!("Copying stage{} std from stage{} ({} -> {} / {})",
176                 target_compiler.stage,
177                 compiler.stage,
178                 &compiler.host,
179                 target_compiler.host,
180                 target);
181         let libdir = builder.sysroot_libdir(target_compiler, target);
182         add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
183
184         if target.contains("musl") && !target.contains("mips") {
185             copy_musl_third_party_objects(build, target, &libdir);
186         }
187
188         if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
189             // The sanitizers are only built in stage1 or above, so the dylibs will
190             // be missing in stage0 and causes panic. See the `std()` function above
191             // for reason why the sanitizers are not built in stage0.
192             copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
193         }
194     }
195 }
196
197 /// Copies the crt(1,i,n).o startup objects
198 ///
199 /// Only required for musl targets that statically link to libc
200 fn copy_musl_third_party_objects(build: &Build, target: Interned<String>, into: &Path) {
201     for &obj in &["crt1.o", "crti.o", "crtn.o"] {
202         copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
203     }
204 }
205
206 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
207     for &sanitizer in &["asan", "tsan"] {
208         let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
209         let mut src_path = native_dir.join(sanitizer);
210         src_path.push("build");
211         src_path.push("lib");
212         src_path.push("darwin");
213         src_path.push(&filename);
214         copy(&src_path, &into.join(filename));
215     }
216 }
217
218 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
219 pub struct StartupObjects {
220     pub compiler: Compiler,
221     pub target: Interned<String>,
222 }
223
224 impl Step for StartupObjects {
225     type Output = ();
226
227     fn should_run(run: ShouldRun) -> ShouldRun {
228         run.path("src/rtstartup")
229     }
230
231     fn make_run(run: RunConfig) {
232         run.builder.ensure(StartupObjects {
233             compiler: run.builder.compiler(run.builder.top_stage, run.host),
234             target: run.target,
235         });
236     }
237
238     /// Build and prepare startup objects like rsbegin.o and rsend.o
239     ///
240     /// These are primarily used on Windows right now for linking executables/dlls.
241     /// They don't require any library support as they're just plain old object
242     /// files, so we just use the nightly snapshot compiler to always build them (as
243     /// no other compilers are guaranteed to be available).
244     fn run(self, builder: &Builder) {
245         let build = builder.build;
246         let for_compiler = self.compiler;
247         let target = self.target;
248         if !target.contains("pc-windows-gnu") {
249             return
250         }
251
252         let src_dir = &build.src.join("src/rtstartup");
253         let dst_dir = &build.native_dir(target).join("rtstartup");
254         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
255         t!(fs::create_dir_all(dst_dir));
256
257         for file in &["rsbegin", "rsend"] {
258             let src_file = &src_dir.join(file.to_string() + ".rs");
259             let dst_file = &dst_dir.join(file.to_string() + ".o");
260             if !up_to_date(src_file, dst_file) {
261                 let mut cmd = Command::new(&build.initial_rustc);
262                 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
263                             .arg("--cfg").arg("stage0")
264                             .arg("--target").arg(target)
265                             .arg("--emit=obj")
266                             .arg("-o").arg(dst_file)
267                             .arg(src_file));
268             }
269
270             copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
271         }
272
273         for obj in ["crt2.o", "dllcrt2.o"].iter() {
274             copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
275         }
276     }
277 }
278
279 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
280 pub struct Test {
281     pub compiler: Compiler,
282     pub target: Interned<String>,
283 }
284
285 impl Step for Test {
286     type Output = ();
287     const DEFAULT: bool = true;
288
289     fn should_run(run: ShouldRun) -> ShouldRun {
290         run.path("src/libtest").krate("test")
291     }
292
293     fn make_run(run: RunConfig) {
294         run.builder.ensure(Test {
295             compiler: run.builder.compiler(run.builder.top_stage, run.host),
296             target: run.target,
297         });
298     }
299
300     /// Build libtest.
301     ///
302     /// This will build libtest and supporting libraries for a particular stage of
303     /// the build using the `compiler` targeting the `target` architecture. The
304     /// artifacts created will also be linked into the sysroot directory.
305     fn run(self, builder: &Builder) {
306         let build = builder.build;
307         let target = self.target;
308         let compiler = self.compiler;
309
310         builder.ensure(Std { compiler, target });
311
312         if build.force_use_stage1(compiler, target) {
313             builder.ensure(Test {
314                 compiler: builder.compiler(1, build.build),
315                 target: target,
316             });
317             println!("Uplifting stage1 test ({} -> {})", &build.build, target);
318             builder.ensure(TestLink {
319                 compiler: builder.compiler(1, build.build),
320                 target_compiler: compiler,
321                 target: target,
322             });
323             return;
324         }
325
326         let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
327         println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
328                 &compiler.host, target);
329         let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
330         build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
331         let mut cargo = builder.cargo(compiler, Mode::Libtest, target, "build");
332         if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
333             cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
334         }
335         cargo.arg("--manifest-path")
336             .arg(build.src.join("src/libtest/Cargo.toml"));
337         run_cargo(build,
338                 &mut cargo,
339                 &libtest_stamp(build, compiler, target));
340
341         builder.ensure(TestLink {
342             compiler: builder.compiler(compiler.stage, build.build),
343             target_compiler: compiler,
344             target: target,
345         });
346     }
347 }
348
349 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
350 pub struct TestLink {
351     pub compiler: Compiler,
352     pub target_compiler: Compiler,
353     pub target: Interned<String>,
354 }
355
356 impl Step for TestLink {
357     type Output = ();
358
359     fn should_run(run: ShouldRun) -> ShouldRun {
360         run.never()
361     }
362
363     /// Same as `std_link`, only for libtest
364     fn run(self, builder: &Builder) {
365         let build = builder.build;
366         let compiler = self.compiler;
367         let target_compiler = self.target_compiler;
368         let target = self.target;
369         println!("Copying stage{} test from stage{} ({} -> {} / {})",
370                 target_compiler.stage,
371                 compiler.stage,
372                 &compiler.host,
373                 target_compiler.host,
374                 target);
375         add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
376                     &libtest_stamp(build, compiler, target));
377     }
378 }
379
380 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
381 pub struct Rustc {
382     pub compiler: Compiler,
383     pub target: Interned<String>,
384 }
385
386 impl Step for Rustc {
387     type Output = ();
388     const ONLY_HOSTS: bool = true;
389     const DEFAULT: bool = true;
390
391     fn should_run(run: ShouldRun) -> ShouldRun {
392         run.path("src/librustc").krate("rustc-main")
393     }
394
395     fn make_run(run: RunConfig) {
396         run.builder.ensure(Rustc {
397             compiler: run.builder.compiler(run.builder.top_stage, run.host),
398             target: run.target,
399         });
400     }
401
402     /// Build the compiler.
403     ///
404     /// This will build the compiler for a particular stage of the build using
405     /// the `compiler` targeting the `target` architecture. The artifacts
406     /// created will also be linked into the sysroot directory.
407     fn run(self, builder: &Builder) {
408         let build = builder.build;
409         let compiler = self.compiler;
410         let target = self.target;
411
412         builder.ensure(Test { compiler, target });
413
414         // Build LLVM for our target. This will implicitly build the host LLVM
415         // if necessary.
416         builder.ensure(native::Llvm { target });
417
418         if build.force_use_stage1(compiler, target) {
419             builder.ensure(Rustc {
420                 compiler: builder.compiler(1, build.build),
421                 target: target,
422             });
423             println!("Uplifting stage1 rustc ({} -> {})", &build.build, target);
424             builder.ensure(RustcLink {
425                 compiler: builder.compiler(1, build.build),
426                 target_compiler: compiler,
427                 target,
428             });
429             return;
430         }
431
432         // Ensure that build scripts have a std to link against.
433         builder.ensure(Std {
434             compiler: builder.compiler(self.compiler.stage, build.build),
435             target: build.build,
436         });
437
438         let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
439         println!("Building stage{} compiler artifacts ({} -> {})",
440                  compiler.stage, &compiler.host, target);
441
442         let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
443         build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
444
445         let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
446         cargo.arg("--features").arg(build.rustc_features())
447              .arg("--manifest-path")
448              .arg(build.src.join("src/rustc/Cargo.toml"));
449
450         // Set some configuration variables picked up by build scripts and
451         // the compiler alike
452         cargo.env("CFG_RELEASE", build.rust_release())
453              .env("CFG_RELEASE_CHANNEL", &build.config.channel)
454              .env("CFG_VERSION", build.rust_version())
455              .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default());
456
457         if compiler.stage == 0 {
458             cargo.env("CFG_LIBDIR_RELATIVE", "lib");
459         } else {
460             let libdir_relative =
461                 build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
462             cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
463         }
464
465         // If we're not building a compiler with debugging information then remove
466         // these two env vars which would be set otherwise.
467         if build.config.rust_debuginfo_only_std {
468             cargo.env_remove("RUSTC_DEBUGINFO");
469             cargo.env_remove("RUSTC_DEBUGINFO_LINES");
470         }
471
472         if let Some(ref ver_date) = build.rust_info.commit_date() {
473             cargo.env("CFG_VER_DATE", ver_date);
474         }
475         if let Some(ref ver_hash) = build.rust_info.sha() {
476             cargo.env("CFG_VER_HASH", ver_hash);
477         }
478         if !build.unstable_features() {
479             cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
480         }
481         // Flag that rust llvm is in use
482         if build.is_rust_llvm(target) {
483             cargo.env("LLVM_RUSTLLVM", "1");
484         }
485         cargo.env("LLVM_CONFIG", build.llvm_config(target));
486         let target_config = build.config.target_config.get(&target);
487         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
488             cargo.env("CFG_LLVM_ROOT", s);
489         }
490         // Building with a static libstdc++ is only supported on linux right now,
491         // not for MSVC or macOS
492         if build.config.llvm_static_stdcpp &&
493            !target.contains("windows") &&
494            !target.contains("apple") {
495             cargo.env("LLVM_STATIC_STDCPP",
496                       compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
497         }
498         if build.config.llvm_link_shared {
499             cargo.env("LLVM_LINK_SHARED", "1");
500         }
501         if let Some(ref s) = build.config.rustc_default_linker {
502             cargo.env("CFG_DEFAULT_LINKER", s);
503         }
504         if let Some(ref s) = build.config.rustc_default_ar {
505             cargo.env("CFG_DEFAULT_AR", s);
506         }
507         run_cargo(build,
508                   &mut cargo,
509                   &librustc_stamp(build, compiler, target));
510
511         builder.ensure(RustcLink {
512             compiler: builder.compiler(compiler.stage, build.build),
513             target_compiler: compiler,
514             target,
515         });
516     }
517 }
518
519 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
520 struct RustcLink {
521     pub compiler: Compiler,
522     pub target_compiler: Compiler,
523     pub target: Interned<String>,
524 }
525
526 impl Step for RustcLink {
527     type Output = ();
528
529     fn should_run(run: ShouldRun) -> ShouldRun {
530         run.never()
531     }
532
533     /// Same as `std_link`, only for librustc
534     fn run(self, builder: &Builder) {
535         let build = builder.build;
536         let compiler = self.compiler;
537         let target_compiler = self.target_compiler;
538         let target = self.target;
539         println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
540                  target_compiler.stage,
541                  compiler.stage,
542                  &compiler.host,
543                  target_compiler.host,
544                  target);
545         add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
546                        &librustc_stamp(build, compiler, target));
547     }
548 }
549
550 /// Cargo's output path for the standard library in a given stage, compiled
551 /// by a particular compiler for the specified target.
552 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
553     build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
554 }
555
556 /// Cargo's output path for libtest in a given stage, compiled by a particular
557 /// compiler for the specified target.
558 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
559     build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
560 }
561
562 /// Cargo's output path for librustc in a given stage, compiled by a particular
563 /// compiler for the specified target.
564 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
565     build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
566 }
567
568 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
569     let out = output(Command::new(compiler)
570                             .arg(format!("-print-file-name={}", file)));
571     PathBuf::from(out.trim())
572 }
573
574 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
575 pub struct Sysroot {
576     pub compiler: Compiler,
577 }
578
579 impl Step for Sysroot {
580     type Output = Interned<PathBuf>;
581
582     fn should_run(run: ShouldRun) -> ShouldRun {
583         run.never()
584     }
585
586     /// Returns the sysroot for the `compiler` specified that *this build system
587     /// generates*.
588     ///
589     /// That is, the sysroot for the stage0 compiler is not what the compiler
590     /// thinks it is by default, but it's the same as the default for stages
591     /// 1-3.
592     fn run(self, builder: &Builder) -> Interned<PathBuf> {
593         let build = builder.build;
594         let compiler = self.compiler;
595         let sysroot = if compiler.stage == 0 {
596             build.out.join(&compiler.host).join("stage0-sysroot")
597         } else {
598             build.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
599         };
600         let _ = fs::remove_dir_all(&sysroot);
601         t!(fs::create_dir_all(&sysroot));
602         INTERNER.intern_path(sysroot)
603     }
604 }
605
606 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
607 pub struct Assemble {
608     /// The compiler which we will produce in this step. Assemble itself will
609     /// take care of ensuring that the necessary prerequisites to do so exist,
610     /// that is, this target can be a stage2 compiler and Assemble will build
611     /// previous stages for you.
612     pub target_compiler: Compiler,
613 }
614
615 impl Step for Assemble {
616     type Output = Compiler;
617
618     fn should_run(run: ShouldRun) -> ShouldRun {
619         run.path("src/rustc")
620     }
621
622     /// Prepare a new compiler from the artifacts in `stage`
623     ///
624     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
625     /// must have been previously produced by the `stage - 1` build.build
626     /// compiler.
627     fn run(self, builder: &Builder) -> Compiler {
628         let build = builder.build;
629         let target_compiler = self.target_compiler;
630
631         if target_compiler.stage == 0 {
632             assert_eq!(build.build, target_compiler.host,
633                 "Cannot obtain compiler for non-native build triple at stage 0");
634             // The stage 0 compiler for the build triple is always pre-built.
635             return target_compiler;
636         }
637
638         // Get the compiler that we'll use to bootstrap ourselves.
639         let build_compiler = if target_compiler.host != build.build {
640             // Build a compiler for the host platform. We cannot use the stage0
641             // compiler for the host platform for this because it doesn't have
642             // the libraries we need.  FIXME: Perhaps we should download those
643             // libraries? It would make builds faster...
644             // FIXME: It may be faster if we build just a stage 1
645             // compiler and then use that to bootstrap this compiler
646             // forward.
647             builder.compiler(target_compiler.stage - 1, build.build)
648         } else {
649             // Build the compiler we'll use to build the stage requested. This
650             // may build more than one compiler (going down to stage 0).
651             builder.compiler(target_compiler.stage - 1, target_compiler.host)
652         };
653
654         // Build the libraries for this compiler to link to (i.e., the libraries
655         // it uses at runtime). NOTE: Crates the target compiler compiles don't
656         // link to these. (FIXME: Is that correct? It seems to be correct most
657         // of the time but I think we do link to these for stage2/bin compilers
658         // when not performing a full bootstrap).
659         if builder.build.flags.keep_stage.map_or(false, |s| target_compiler.stage <= s) {
660             builder.verbose("skipping compilation of compiler due to --keep-stage");
661             let compiler = build_compiler;
662             for stage in 0..min(target_compiler.stage, builder.flags.keep_stage.unwrap()) {
663                 let target_compiler = builder.compiler(stage, target_compiler.host);
664                 let target = target_compiler.host;
665                 builder.ensure(StdLink { compiler, target_compiler, target });
666                 builder.ensure(TestLink { compiler, target_compiler, target });
667                 builder.ensure(RustcLink { compiler, target_compiler, target });
668             }
669         } else {
670             builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
671         }
672
673         let stage = target_compiler.stage;
674         let host = target_compiler.host;
675         println!("Assembling stage{} compiler ({})", stage, host);
676
677         // Link in all dylibs to the libdir
678         let sysroot = builder.sysroot(target_compiler);
679         let sysroot_libdir = sysroot.join(libdir(&*host));
680         t!(fs::create_dir_all(&sysroot_libdir));
681         let src_libdir = builder.sysroot_libdir(build_compiler, host);
682         for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
683             let filename = f.file_name().into_string().unwrap();
684             if is_dylib(&filename) {
685                 copy(&f.path(), &sysroot_libdir.join(&filename));
686             }
687         }
688
689         let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
690
691         // Link the compiler binary itself into place
692         let rustc = out_dir.join(exe("rustc", &*host));
693         let bindir = sysroot.join("bin");
694         t!(fs::create_dir_all(&bindir));
695         let compiler = builder.rustc(target_compiler);
696         let _ = fs::remove_file(&compiler);
697         copy(&rustc, &compiler);
698
699         // See if rustdoc exists to link it into place
700         let rustdoc = exe("rustdoc", &*host);
701         let rustdoc_src = out_dir.join(&rustdoc);
702         let rustdoc_dst = bindir.join(&rustdoc);
703         if fs::metadata(&rustdoc_src).is_ok() {
704             let _ = fs::remove_file(&rustdoc_dst);
705             copy(&rustdoc_src, &rustdoc_dst);
706         }
707
708         target_compiler
709     }
710 }
711
712 /// Link some files into a rustc sysroot.
713 ///
714 /// For a particular stage this will link the file listed in `stamp` into the
715 /// `sysroot_dst` provided.
716 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
717     t!(fs::create_dir_all(&sysroot_dst));
718     let mut contents = Vec::new();
719     t!(t!(File::open(stamp)).read_to_end(&mut contents));
720     // This is the method we use for extracting paths from the stamp file passed to us. See
721     // run_cargo for more information (in this file).
722     for part in contents.split(|b| *b == 0) {
723         if part.is_empty() {
724             continue
725         }
726         let path = Path::new(t!(str::from_utf8(part)));
727         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
728     }
729 }
730
731 // Avoiding a dependency on winapi to keep compile times down
732 #[cfg(unix)]
733 fn stderr_isatty() -> bool {
734     use libc;
735     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
736 }
737 #[cfg(windows)]
738 fn stderr_isatty() -> bool {
739     type DWORD = u32;
740     type BOOL = i32;
741     type HANDLE = *mut u8;
742     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
743     extern "system" {
744         fn GetStdHandle(which: DWORD) -> HANDLE;
745         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
746     }
747     unsafe {
748         let handle = GetStdHandle(STD_ERROR_HANDLE);
749         let mut out = 0;
750         GetConsoleMode(handle, &mut out) != 0
751     }
752 }
753
754 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
755     // Instruct Cargo to give us json messages on stdout, critically leaving
756     // stderr as piped so we can get those pretty colors.
757     cargo.arg("--message-format").arg("json")
758          .stdout(Stdio::piped());
759
760     if stderr_isatty() {
761         // since we pass message-format=json to cargo, we need to tell the rustc
762         // wrapper to give us colored output if necessary. This is because we
763         // only want Cargo's JSON output, not rustcs.
764         cargo.env("RUSTC_COLOR", "1");
765     }
766
767     build.verbose(&format!("running: {:?}", cargo));
768     let mut child = match cargo.spawn() {
769         Ok(child) => child,
770         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
771     };
772
773     // `target_root_dir` looks like $dir/$target/release
774     let target_root_dir = stamp.parent().unwrap();
775     // `target_deps_dir` looks like $dir/$target/release/deps
776     let target_deps_dir = target_root_dir.join("deps");
777     // `host_root_dir` looks like $dir/release
778     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
779                                        .parent().unwrap() // chop off `$target`
780                                        .join(target_root_dir.file_name().unwrap());
781
782     // Spawn Cargo slurping up its JSON output. We'll start building up the
783     // `deps` array of all files it generated along with a `toplevel` array of
784     // files we need to probe for later.
785     let mut deps = Vec::new();
786     let mut toplevel = Vec::new();
787     let stdout = BufReader::new(child.stdout.take().unwrap());
788     for line in stdout.lines() {
789         let line = t!(line);
790         let json: serde_json::Value = if line.starts_with("{") {
791             t!(serde_json::from_str(&line))
792         } else {
793             // If this was informational, just print it out and continue
794             println!("{}", line);
795             continue
796         };
797         if json["reason"].as_str() != Some("compiler-artifact") {
798             continue
799         }
800         for filename in json["filenames"].as_array().unwrap() {
801             let filename = filename.as_str().unwrap();
802             // Skip files like executables
803             if !filename.ends_with(".rlib") &&
804                !filename.ends_with(".lib") &&
805                !is_dylib(&filename) {
806                 continue
807             }
808
809             let filename = Path::new(filename);
810
811             // If this was an output file in the "host dir" we don't actually
812             // worry about it, it's not relevant for us.
813             if filename.starts_with(&host_root_dir) {
814                 continue;
815             }
816
817             // If this was output in the `deps` dir then this is a precise file
818             // name (hash included) so we start tracking it.
819             if filename.starts_with(&target_deps_dir) {
820                 deps.push(filename.to_path_buf());
821                 continue;
822             }
823
824             // Otherwise this was a "top level artifact" which right now doesn't
825             // have a hash in the name, but there's a version of this file in
826             // the `deps` folder which *does* have a hash in the name. That's
827             // the one we'll want to we'll probe for it later.
828             toplevel.push((filename.file_stem().unwrap()
829                                     .to_str().unwrap().to_string(),
830                             filename.extension().unwrap().to_owned()
831                                     .to_str().unwrap().to_string()));
832         }
833     }
834
835     // Make sure Cargo actually succeeded after we read all of its stdout.
836     let status = t!(child.wait());
837     if !status.success() {
838         panic!("command did not execute successfully: {:?}\n\
839                 expected success, got: {}",
840                cargo,
841                status);
842     }
843
844     // Ok now we need to actually find all the files listed in `toplevel`. We've
845     // got a list of prefix/extensions and we basically just need to find the
846     // most recent file in the `deps` folder corresponding to each one.
847     let contents = t!(target_deps_dir.read_dir())
848         .map(|e| t!(e))
849         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
850         .collect::<Vec<_>>();
851     for (prefix, extension) in toplevel {
852         let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
853             filename.starts_with(&prefix[..]) &&
854                 filename[prefix.len()..].starts_with("-") &&
855                 filename.ends_with(&extension[..])
856         });
857         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
858             FileTime::from_last_modification_time(metadata)
859         });
860         let path_to_add = match max {
861             Some(triple) => triple.0.to_str().unwrap(),
862             None => panic!("no output generated for {:?} {:?}", prefix, extension),
863         };
864         if is_dylib(path_to_add) {
865             let candidate = format!("{}.lib", path_to_add);
866             let candidate = PathBuf::from(candidate);
867             if candidate.exists() {
868                 deps.push(candidate);
869             }
870         }
871         deps.push(path_to_add.into());
872     }
873
874     // Now we want to update the contents of the stamp file, if necessary. First
875     // we read off the previous contents along with its mtime. If our new
876     // contents (the list of files to copy) is different or if any dep's mtime
877     // is newer then we rewrite the stamp file.
878     deps.sort();
879     let mut stamp_contents = Vec::new();
880     if let Ok(mut f) = File::open(stamp) {
881         t!(f.read_to_end(&mut stamp_contents));
882     }
883     let stamp_mtime = mtime(&stamp);
884     let mut new_contents = Vec::new();
885     let mut max = None;
886     let mut max_path = None;
887     for dep in deps {
888         let mtime = mtime(&dep);
889         if Some(mtime) > max {
890             max = Some(mtime);
891             max_path = Some(dep.clone());
892         }
893         new_contents.extend(dep.to_str().unwrap().as_bytes());
894         new_contents.extend(b"\0");
895     }
896     let max = max.unwrap();
897     let max_path = max_path.unwrap();
898     if stamp_contents == new_contents && max <= stamp_mtime {
899         return
900     }
901     if max > stamp_mtime {
902         build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
903     } else {
904         build.verbose(&format!("updating {:?} as deps changed", stamp));
905     }
906     t!(t!(File::create(stamp)).write_all(&new_contents));
907 }