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