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