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