]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Clean tools after building libstd/libtest/librustc.
[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 use tool;
36
37 use cache::{INTERNER, Interned};
38 use builder::{Step, RunConfig, ShouldRun, Builder};
39
40 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
41 pub struct Std {
42     pub target: Interned<String>,
43     pub compiler: Compiler,
44 }
45
46 impl Step for Std {
47     type Output = ();
48     const DEFAULT: bool = true;
49
50     fn should_run(run: ShouldRun) -> ShouldRun {
51         run.path("src/libstd").krate("std")
52     }
53
54     fn make_run(run: RunConfig) {
55         run.builder.ensure(Std {
56             compiler: run.builder.compiler(run.builder.top_stage, run.host),
57             target: run.target,
58         });
59     }
60
61     /// Build the standard library.
62     ///
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;
70
71         builder.ensure(StartupObjects { compiler, target });
72
73         if build.force_use_stage1(compiler, target) {
74             let from = builder.compiler(1, build.build);
75             builder.ensure(Std {
76                 compiler: from,
77                 target: target,
78             });
79             println!("Uplifting stage1 std ({} -> {})", from.host, target);
80             builder.ensure(StdLink {
81                 compiler: from,
82                 target_compiler: compiler,
83                 target: target,
84             });
85             return;
86         }
87
88         let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
89         println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
90                 &compiler.host, target);
91
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);
96         run_cargo(build,
97                 &mut cargo,
98                 &libstd_stamp(build, compiler, target));
99
100         builder.ensure(StdLink {
101             compiler: builder.compiler(compiler.stage, build.build),
102             target_compiler: compiler,
103             target: target,
104         });
105     }
106 }
107
108 /// Configure cargo to compile the standard library, adding appropriate env vars
109 /// and such.
110 pub fn std_cargo(build: &Build,
111                  compiler: &Compiler,
112                  target: Interned<String>,
113                  cargo: &mut Command) {
114     let mut features = build.std_features();
115
116     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
117         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
118     }
119
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");
127     }
128
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
134         // missing
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));
138     }
139
140     cargo.arg("--features").arg(features)
141         .arg("--manifest-path")
142         .arg(build.src.join("src/libstd/Cargo.toml"));
143
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);
147         }
148     }
149     if target.contains("musl") {
150         if let Some(p) = build.musl_root(target) {
151             cargo.env("MUSL_ROOT", p);
152         }
153     }
154 }
155
156 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
157 struct StdLink {
158     pub compiler: Compiler,
159     pub target_compiler: Compiler,
160     pub target: Interned<String>,
161 }
162
163 impl Step for StdLink {
164     type Output = ();
165
166     fn should_run(run: ShouldRun) -> ShouldRun {
167         run.never()
168     }
169
170     /// Link all libstd rlibs/dylibs into the sysroot location.
171     ///
172     /// Links those artifacts generated by `compiler` to a the `stage` compiler's
173     /// sysroot for the specified `host` and `target`.
174     ///
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,
185                 compiler.stage,
186                 &compiler.host,
187                 target_compiler.host,
188                 target);
189         let libdir = builder.sysroot_libdir(target_compiler, target);
190         add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
191
192         if target.contains("musl") && !target.contains("mips") {
193             copy_musl_third_party_objects(build, target, &libdir);
194         }
195
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);
201         }
202
203         builder.ensure(tool::CleanTools {
204             compiler: target_compiler,
205             target: target,
206             mode: Mode::Libstd,
207         });
208     }
209 }
210
211 /// Copies the crt(1,i,n).o startup objects
212 ///
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));
217     }
218 }
219
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));
229     }
230 }
231
232 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
233 pub struct StartupObjects {
234     pub compiler: Compiler,
235     pub target: Interned<String>,
236 }
237
238 impl Step for StartupObjects {
239     type Output = ();
240
241     fn should_run(run: ShouldRun) -> ShouldRun {
242         run.path("src/rtstartup")
243     }
244
245     fn make_run(run: RunConfig) {
246         run.builder.ensure(StartupObjects {
247             compiler: run.builder.compiler(run.builder.top_stage, run.host),
248             target: run.target,
249         });
250     }
251
252     /// Build and prepare startup objects like rsbegin.o and rsend.o
253     ///
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") {
263             return
264         }
265
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));
270
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)
279                             .arg("--emit=obj")
280                             .arg("-o").arg(dst_file)
281                             .arg(src_file));
282             }
283
284             copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
285         }
286
287         for obj in ["crt2.o", "dllcrt2.o"].iter() {
288             copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
289         }
290     }
291 }
292
293 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
294 pub struct Test {
295     pub compiler: Compiler,
296     pub target: Interned<String>,
297 }
298
299 impl Step for Test {
300     type Output = ();
301     const DEFAULT: bool = true;
302
303     fn should_run(run: ShouldRun) -> ShouldRun {
304         run.path("src/libtest").krate("test")
305     }
306
307     fn make_run(run: RunConfig) {
308         run.builder.ensure(Test {
309             compiler: run.builder.compiler(run.builder.top_stage, run.host),
310             target: run.target,
311         });
312     }
313
314     /// Build libtest.
315     ///
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;
323
324         builder.ensure(Std { compiler, target });
325
326         if build.force_use_stage1(compiler, target) {
327             builder.ensure(Test {
328                 compiler: builder.compiler(1, build.build),
329                 target: target,
330             });
331             println!("Uplifting stage1 test ({} -> {})", &build.build, target);
332             builder.ensure(TestLink {
333                 compiler: builder.compiler(1, build.build),
334                 target_compiler: compiler,
335                 target: target,
336             });
337             return;
338         }
339
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);
347         run_cargo(build,
348                 &mut cargo,
349                 &libtest_stamp(build, compiler, target));
350
351         builder.ensure(TestLink {
352             compiler: builder.compiler(compiler.stage, build.build),
353             target_compiler: compiler,
354             target: target,
355         });
356     }
357 }
358
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);
366     }
367     cargo.arg("--manifest-path")
368         .arg(build.src.join("src/libtest/Cargo.toml"));
369 }
370
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>,
376 }
377
378 impl Step for TestLink {
379     type Output = ();
380
381     fn should_run(run: ShouldRun) -> ShouldRun {
382         run.never()
383     }
384
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,
393                 compiler.stage,
394                 &compiler.host,
395                 target_compiler.host,
396                 target);
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,
401             target: target,
402             mode: Mode::Libtest,
403         });
404     }
405 }
406
407 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
408 pub struct Rustc {
409     pub compiler: Compiler,
410     pub target: Interned<String>,
411 }
412
413 impl Step for Rustc {
414     type Output = ();
415     const ONLY_HOSTS: bool = true;
416     const DEFAULT: bool = true;
417
418     fn should_run(run: ShouldRun) -> ShouldRun {
419         run.path("src/librustc").krate("rustc-main")
420     }
421
422     fn make_run(run: RunConfig) {
423         run.builder.ensure(Rustc {
424             compiler: run.builder.compiler(run.builder.top_stage, run.host),
425             target: run.target,
426         });
427     }
428
429     /// Build the compiler.
430     ///
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;
438
439         builder.ensure(Test { compiler, target });
440
441         // Build LLVM for our target. This will implicitly build the host LLVM
442         // if necessary.
443         builder.ensure(native::Llvm { target });
444
445         if build.force_use_stage1(compiler, target) {
446             builder.ensure(Rustc {
447                 compiler: builder.compiler(1, build.build),
448                 target: target,
449             });
450             println!("Uplifting stage1 rustc ({} -> {})", &build.build, target);
451             builder.ensure(RustcLink {
452                 compiler: builder.compiler(1, build.build),
453                 target_compiler: compiler,
454                 target,
455             });
456             return;
457         }
458
459         // Ensure that build scripts have a std to link against.
460         builder.ensure(Std {
461             compiler: builder.compiler(self.compiler.stage, build.build),
462             target: build.build,
463         });
464
465         let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
466         println!("Building stage{} compiler artifacts ({} -> {})",
467                  compiler.stage, &compiler.host, target);
468
469         let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
470         build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
471
472         let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
473         rustc_cargo(build, &compiler, target, &mut cargo);
474         run_cargo(build,
475                   &mut cargo,
476                   &librustc_stamp(build, compiler, target));
477
478         builder.ensure(RustcLink {
479             compiler: builder.compiler(compiler.stage, build.build),
480             target_compiler: compiler,
481             target,
482         });
483     }
484 }
485
486 /// Same as `std_cargo`, but for libtest
487 pub fn rustc_cargo(build: &Build,
488                    compiler: &Compiler,
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"));
494
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());
501
502     if compiler.stage == 0 {
503         cargo.env("CFG_LIBDIR_RELATIVE", "lib");
504     } else {
505         let libdir_relative =
506             build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
507         cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
508     }
509
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");
515     }
516
517     if let Some(ref ver_date) = build.rust_info.commit_date() {
518         cargo.env("CFG_VER_DATE", ver_date);
519     }
520     if let Some(ref ver_hash) = build.rust_info.sha() {
521         cargo.env("CFG_VER_HASH", ver_hash);
522     }
523     if !build.unstable_features() {
524         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
525     }
526     // Flag that rust llvm is in use
527     if build.is_rust_llvm(target) {
528         cargo.env("LLVM_RUSTLLVM", "1");
529     }
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);
534     }
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"));
542     }
543     if build.config.llvm_link_shared {
544         cargo.env("LLVM_LINK_SHARED", "1");
545     }
546     if let Some(ref s) = build.config.rustc_default_linker {
547         cargo.env("CFG_DEFAULT_LINKER", s);
548     }
549     if let Some(ref s) = build.config.rustc_default_ar {
550         cargo.env("CFG_DEFAULT_AR", s);
551     }
552 }
553
554 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
555 struct RustcLink {
556     pub compiler: Compiler,
557     pub target_compiler: Compiler,
558     pub target: Interned<String>,
559 }
560
561 impl Step for RustcLink {
562     type Output = ();
563
564     fn should_run(run: ShouldRun) -> ShouldRun {
565         run.never()
566     }
567
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,
576                  compiler.stage,
577                  &compiler.host,
578                  target_compiler.host,
579                  target);
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,
584             target: target,
585             mode: Mode::Librustc,
586         });
587     }
588 }
589
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")
594 }
595
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")
600 }
601
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")
606 }
607
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())
612 }
613
614 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
615 pub struct Sysroot {
616     pub compiler: Compiler,
617 }
618
619 impl Step for Sysroot {
620     type Output = Interned<PathBuf>;
621
622     fn should_run(run: ShouldRun) -> ShouldRun {
623         run.never()
624     }
625
626     /// Returns the sysroot for the `compiler` specified that *this build system
627     /// generates*.
628     ///
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
631     /// 1-3.
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")
637         } else {
638             build.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
639         };
640         let _ = fs::remove_dir_all(&sysroot);
641         t!(fs::create_dir_all(&sysroot));
642         INTERNER.intern_path(sysroot)
643     }
644 }
645
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,
653 }
654
655 impl Step for Assemble {
656     type Output = Compiler;
657
658     fn should_run(run: ShouldRun) -> ShouldRun {
659         run.path("src/rustc")
660     }
661
662     /// Prepare a new compiler from the artifacts in `stage`
663     ///
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
666     /// compiler.
667     fn run(self, builder: &Builder) -> Compiler {
668         let build = builder.build;
669         let target_compiler = self.target_compiler;
670
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;
676         }
677
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
686             // forward.
687             builder.compiler(target_compiler.stage - 1, build.build)
688         } else {
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)
692         };
693
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 });
708             }
709         } else {
710             builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
711         }
712
713         let stage = target_compiler.stage;
714         let host = target_compiler.host;
715         println!("Assembling stage{} compiler ({})", stage, host);
716
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));
726             }
727         }
728
729         let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
730
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);
738
739         target_compiler
740     }
741 }
742
743 /// Link some files into a rustc sysroot.
744 ///
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) {
754         if part.is_empty() {
755             continue
756         }
757         let path = Path::new(t!(str::from_utf8(part)));
758         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
759     }
760 }
761
762 // Avoiding a dependency on winapi to keep compile times down
763 #[cfg(unix)]
764 fn stderr_isatty() -> bool {
765     use libc;
766     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
767 }
768 #[cfg(windows)]
769 fn stderr_isatty() -> bool {
770     type DWORD = u32;
771     type BOOL = i32;
772     type HANDLE = *mut u8;
773     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
774     extern "system" {
775         fn GetStdHandle(which: DWORD) -> HANDLE;
776         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
777     }
778     unsafe {
779         let handle = GetStdHandle(STD_ERROR_HANDLE);
780         let mut out = 0;
781         GetConsoleMode(handle, &mut out) != 0
782     }
783 }
784
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());
790
791     if stderr_isatty() {
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");
796     }
797
798     build.verbose(&format!("running: {:?}", cargo));
799     let mut child = match cargo.spawn() {
800         Ok(child) => child,
801         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
802     };
803
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());
812
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() {
820         let line = t!(line);
821         let json: serde_json::Value = if line.starts_with("{") {
822             t!(serde_json::from_str(&line))
823         } else {
824             // If this was informational, just print it out and continue
825             println!("{}", line);
826             continue
827         };
828         if json["reason"].as_str() != Some("compiler-artifact") {
829             continue
830         }
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) {
837                 continue
838             }
839
840             let filename = Path::new(filename);
841
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) {
845                 continue;
846             }
847
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());
852                 continue;
853             }
854
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()));
863         }
864     }
865
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: {}",
871                cargo,
872                status);
873     }
874
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())
879         .map(|e| t!(e))
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[..])
887         });
888         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
889             FileTime::from_last_modification_time(metadata)
890         });
891         let path_to_add = match max {
892             Some(triple) => triple.0.to_str().unwrap(),
893             None => panic!("no output generated for {:?} {:?}", prefix, extension),
894         };
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);
900             }
901         }
902         deps.push(path_to_add.into());
903     }
904
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.
909     deps.sort();
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));
913     }
914     let stamp_mtime = mtime(&stamp);
915     let mut new_contents = Vec::new();
916     let mut max = None;
917     let mut max_path = None;
918     for dep in deps {
919         let mtime = mtime(&dep);
920         if Some(mtime) > max {
921             max = Some(mtime);
922             max_path = Some(dep.clone());
923         }
924         new_contents.extend(dep.to_str().unwrap().as_bytes());
925         new_contents.extend(b"\0");
926     }
927     let max = max.unwrap();
928     let max_path = max_path.unwrap();
929     if stamp_contents == new_contents && max <= stamp_mtime {
930         return
931     }
932     if max > stamp_mtime {
933         build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
934     } else {
935         build.verbose(&format!("updating {:?} as deps changed", stamp));
936     }
937     t!(t!(File::create(stamp)).write_all(&new_contents));
938 }