]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Fix test
[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.all_krates("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") {
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") {
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(builder, &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: &Builder,
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         let llvm_config = build.ensure(native::Llvm {
166             target: build.config.build,
167             emscripten: false,
168         });
169         cargo.env("LLVM_CONFIG", llvm_config);
170     }
171
172     cargo.arg("--features").arg(features)
173         .arg("--manifest-path")
174         .arg(build.src.join("src/libstd/Cargo.toml"));
175
176     if let Some(target) = build.config.target_config.get(&target) {
177         if let Some(ref jemalloc) = target.jemalloc {
178             cargo.env("JEMALLOC_OVERRIDE", jemalloc);
179         }
180     }
181     if target.contains("musl") {
182         if let Some(p) = build.musl_root(target) {
183             cargo.env("MUSL_ROOT", p);
184         }
185     }
186 }
187
188 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
189 struct StdLink {
190     pub compiler: Compiler,
191     pub target_compiler: Compiler,
192     pub target: Interned<String>,
193 }
194
195 impl Step for StdLink {
196     type Output = ();
197
198     fn should_run(run: ShouldRun) -> ShouldRun {
199         run.never()
200     }
201
202     /// Link all libstd rlibs/dylibs into the sysroot location.
203     ///
204     /// Links those artifacts generated by `compiler` to a the `stage` compiler's
205     /// sysroot for the specified `host` and `target`.
206     ///
207     /// Note that this assumes that `compiler` has already generated the libstd
208     /// libraries for `target`, and this method will find them in the relevant
209     /// output directory.
210     fn run(self, builder: &Builder) {
211         let build = builder.build;
212         let compiler = self.compiler;
213         let target_compiler = self.target_compiler;
214         let target = self.target;
215         println!("Copying stage{} std from stage{} ({} -> {} / {})",
216                 target_compiler.stage,
217                 compiler.stage,
218                 &compiler.host,
219                 target_compiler.host,
220                 target);
221         let libdir = builder.sysroot_libdir(target_compiler, target);
222         add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
223
224         if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
225             // The sanitizers are only built in stage1 or above, so the dylibs will
226             // be missing in stage0 and causes panic. See the `std()` function above
227             // for reason why the sanitizers are not built in stage0.
228             copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
229         }
230
231         builder.ensure(tool::CleanTools {
232             compiler: target_compiler,
233             target,
234             mode: Mode::Libstd,
235         });
236     }
237 }
238
239 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
240     for &sanitizer in &["asan", "tsan"] {
241         let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
242         let mut src_path = native_dir.join(sanitizer);
243         src_path.push("build");
244         src_path.push("lib");
245         src_path.push("darwin");
246         src_path.push(&filename);
247         copy(&src_path, &into.join(filename));
248     }
249 }
250
251 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
252 pub struct StartupObjects {
253     pub compiler: Compiler,
254     pub target: Interned<String>,
255 }
256
257 impl Step for StartupObjects {
258     type Output = ();
259
260     fn should_run(run: ShouldRun) -> ShouldRun {
261         run.path("src/rtstartup")
262     }
263
264     fn make_run(run: RunConfig) {
265         run.builder.ensure(StartupObjects {
266             compiler: run.builder.compiler(run.builder.top_stage, run.host),
267             target: run.target,
268         });
269     }
270
271     /// Build and prepare startup objects like rsbegin.o and rsend.o
272     ///
273     /// These are primarily used on Windows right now for linking executables/dlls.
274     /// They don't require any library support as they're just plain old object
275     /// files, so we just use the nightly snapshot compiler to always build them (as
276     /// no other compilers are guaranteed to be available).
277     fn run(self, builder: &Builder) {
278         let build = builder.build;
279         let for_compiler = self.compiler;
280         let target = self.target;
281         if !target.contains("pc-windows-gnu") {
282             return
283         }
284
285         let src_dir = &build.src.join("src/rtstartup");
286         let dst_dir = &build.native_dir(target).join("rtstartup");
287         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
288         t!(fs::create_dir_all(dst_dir));
289
290         for file in &["rsbegin", "rsend"] {
291             let src_file = &src_dir.join(file.to_string() + ".rs");
292             let dst_file = &dst_dir.join(file.to_string() + ".o");
293             if !up_to_date(src_file, dst_file) {
294                 let mut cmd = Command::new(&build.initial_rustc);
295                 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
296                             .arg("--cfg").arg("stage0")
297                             .arg("--target").arg(target)
298                             .arg("--emit=obj")
299                             .arg("-o").arg(dst_file)
300                             .arg(src_file));
301             }
302
303             copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
304         }
305
306         for obj in ["crt2.o", "dllcrt2.o"].iter() {
307             let src = compiler_file(build,
308                                     build.cc(target),
309                                     target,
310                                     obj);
311             copy(&src, &sysroot_dir.join(obj));
312         }
313     }
314 }
315
316 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
317 pub struct Test {
318     pub compiler: Compiler,
319     pub target: Interned<String>,
320 }
321
322 impl Step for Test {
323     type Output = ();
324     const DEFAULT: bool = true;
325
326     fn should_run(run: ShouldRun) -> ShouldRun {
327         run.all_krates("test")
328     }
329
330     fn make_run(run: RunConfig) {
331         run.builder.ensure(Test {
332             compiler: run.builder.compiler(run.builder.top_stage, run.host),
333             target: run.target,
334         });
335     }
336
337     /// Build libtest.
338     ///
339     /// This will build libtest and supporting libraries for a particular stage of
340     /// the build using the `compiler` targeting the `target` architecture. The
341     /// artifacts created will also be linked into the sysroot directory.
342     fn run(self, builder: &Builder) {
343         let build = builder.build;
344         let target = self.target;
345         let compiler = self.compiler;
346
347         builder.ensure(Std { compiler, target });
348
349         if build.force_use_stage1(compiler, target) {
350             builder.ensure(Test {
351                 compiler: builder.compiler(1, build.build),
352                 target,
353             });
354             println!("Uplifting stage1 test ({} -> {})", &build.build, target);
355             builder.ensure(TestLink {
356                 compiler: builder.compiler(1, build.build),
357                 target_compiler: compiler,
358                 target,
359             });
360             return;
361         }
362
363         let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
364         println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
365                 &compiler.host, target);
366         let out_dir = build.stage_out(compiler, Mode::Libtest);
367         build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
368         let mut cargo = builder.cargo(compiler, Mode::Libtest, target, "build");
369         test_cargo(build, &compiler, target, &mut cargo);
370         run_cargo(build,
371                   &mut cargo,
372                   &libtest_stamp(build, compiler, target),
373                   false);
374
375         builder.ensure(TestLink {
376             compiler: builder.compiler(compiler.stage, build.build),
377             target_compiler: compiler,
378             target,
379         });
380     }
381 }
382
383 /// Same as `std_cargo`, but for libtest
384 pub fn test_cargo(build: &Build,
385                   _compiler: &Compiler,
386                   _target: Interned<String>,
387                   cargo: &mut Command) {
388     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
389         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
390     }
391     cargo.arg("--manifest-path")
392         .arg(build.src.join("src/libtest/Cargo.toml"));
393 }
394
395 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
396 pub struct TestLink {
397     pub compiler: Compiler,
398     pub target_compiler: Compiler,
399     pub target: Interned<String>,
400 }
401
402 impl Step for TestLink {
403     type Output = ();
404
405     fn should_run(run: ShouldRun) -> ShouldRun {
406         run.never()
407     }
408
409     /// Same as `std_link`, only for libtest
410     fn run(self, builder: &Builder) {
411         let build = builder.build;
412         let compiler = self.compiler;
413         let target_compiler = self.target_compiler;
414         let target = self.target;
415         println!("Copying stage{} test from stage{} ({} -> {} / {})",
416                 target_compiler.stage,
417                 compiler.stage,
418                 &compiler.host,
419                 target_compiler.host,
420                 target);
421         add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
422                     &libtest_stamp(build, compiler, target));
423         builder.ensure(tool::CleanTools {
424             compiler: target_compiler,
425             target,
426             mode: Mode::Libtest,
427         });
428     }
429 }
430
431 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
432 pub struct Rustc {
433     pub compiler: Compiler,
434     pub target: Interned<String>,
435 }
436
437 impl Step for Rustc {
438     type Output = ();
439     const ONLY_HOSTS: bool = true;
440     const DEFAULT: bool = true;
441
442     fn should_run(run: ShouldRun) -> ShouldRun {
443         run.all_krates("rustc-main")
444     }
445
446     fn make_run(run: RunConfig) {
447         run.builder.ensure(Rustc {
448             compiler: run.builder.compiler(run.builder.top_stage, run.host),
449             target: run.target,
450         });
451     }
452
453     /// Build the compiler.
454     ///
455     /// This will build the compiler for a particular stage of the build using
456     /// the `compiler` targeting the `target` architecture. The artifacts
457     /// created will also be linked into the sysroot directory.
458     fn run(self, builder: &Builder) {
459         let build = builder.build;
460         let compiler = self.compiler;
461         let target = self.target;
462
463         builder.ensure(Test { compiler, target });
464
465         if build.force_use_stage1(compiler, target) {
466             builder.ensure(Rustc {
467                 compiler: builder.compiler(1, build.build),
468                 target,
469             });
470             println!("Uplifting stage1 rustc ({} -> {})", &build.build, target);
471             builder.ensure(RustcLink {
472                 compiler: builder.compiler(1, build.build),
473                 target_compiler: compiler,
474                 target,
475             });
476             return;
477         }
478
479         // Ensure that build scripts have a std to link against.
480         builder.ensure(Std {
481             compiler: builder.compiler(self.compiler.stage, build.build),
482             target: build.build,
483         });
484
485         let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
486         println!("Building stage{} compiler artifacts ({} -> {})",
487                  compiler.stage, &compiler.host, target);
488
489         let stage_out = builder.stage_out(compiler, Mode::Librustc);
490         build.clear_if_dirty(&stage_out, &libstd_stamp(build, compiler, target));
491         build.clear_if_dirty(&stage_out, &libtest_stamp(build, compiler, target));
492
493         let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
494         rustc_cargo(build, &mut cargo);
495         run_cargo(build,
496                   &mut cargo,
497                   &librustc_stamp(build, compiler, target),
498                   false);
499
500         builder.ensure(RustcLink {
501             compiler: builder.compiler(compiler.stage, build.build),
502             target_compiler: compiler,
503             target,
504         });
505     }
506 }
507
508 pub fn rustc_cargo(build: &Build, cargo: &mut Command) {
509     cargo.arg("--features").arg(build.rustc_features())
510          .arg("--manifest-path")
511          .arg(build.src.join("src/rustc/Cargo.toml"));
512     rustc_cargo_env(build, cargo);
513 }
514
515 fn rustc_cargo_env(build: &Build, cargo: &mut Command) {
516     // Set some configuration variables picked up by build scripts and
517     // the compiler alike
518     cargo.env("CFG_RELEASE", build.rust_release())
519          .env("CFG_RELEASE_CHANNEL", &build.config.channel)
520          .env("CFG_VERSION", build.rust_version())
521          .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default())
522          .env("CFG_CODEGEN_BACKENDS_DIR", &build.config.rust_codegen_backends_dir);
523
524     let libdir_relative = build.config.libdir_relative().unwrap_or(Path::new("lib"));
525     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
526
527     // If we're not building a compiler with debugging information then remove
528     // these two env vars which would be set otherwise.
529     if build.config.rust_debuginfo_only_std {
530         cargo.env_remove("RUSTC_DEBUGINFO");
531         cargo.env_remove("RUSTC_DEBUGINFO_LINES");
532     }
533
534     if let Some(ref ver_date) = build.rust_info.commit_date() {
535         cargo.env("CFG_VER_DATE", ver_date);
536     }
537     if let Some(ref ver_hash) = build.rust_info.sha() {
538         cargo.env("CFG_VER_HASH", ver_hash);
539     }
540     if !build.unstable_features() {
541         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
542     }
543     if let Some(ref s) = build.config.rustc_default_linker {
544         cargo.env("CFG_DEFAULT_LINKER", s);
545     }
546     if build.config.rustc_parallel_queries {
547         cargo.env("RUSTC_PARALLEL_QUERIES", "1");
548     }
549 }
550
551 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
552 struct RustcLink {
553     pub compiler: Compiler,
554     pub target_compiler: Compiler,
555     pub target: Interned<String>,
556 }
557
558 impl Step for RustcLink {
559     type Output = ();
560
561     fn should_run(run: ShouldRun) -> ShouldRun {
562         run.never()
563     }
564
565     /// Same as `std_link`, only for librustc
566     fn run(self, builder: &Builder) {
567         let build = builder.build;
568         let compiler = self.compiler;
569         let target_compiler = self.target_compiler;
570         let target = self.target;
571         println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
572                  target_compiler.stage,
573                  compiler.stage,
574                  &compiler.host,
575                  target_compiler.host,
576                  target);
577         add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
578                        &librustc_stamp(build, compiler, target));
579         builder.ensure(tool::CleanTools {
580             compiler: target_compiler,
581             target,
582             mode: Mode::Librustc,
583         });
584     }
585 }
586
587 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
588 pub struct CodegenBackend {
589     pub compiler: Compiler,
590     pub target: Interned<String>,
591     pub backend: Interned<String>,
592 }
593
594 impl Step for CodegenBackend {
595     type Output = ();
596     const ONLY_HOSTS: bool = true;
597     const DEFAULT: bool = true;
598
599     fn should_run(run: ShouldRun) -> ShouldRun {
600         run.all_krates("rustc_trans")
601     }
602
603     fn make_run(run: RunConfig) {
604         let backend = run.builder.config.rust_codegen_backends.get(0);
605         let backend = backend.cloned().unwrap_or_else(|| {
606             INTERNER.intern_str("llvm")
607         });
608         run.builder.ensure(CodegenBackend {
609             compiler: run.builder.compiler(run.builder.top_stage, run.host),
610             target: run.target,
611             backend
612         });
613     }
614
615     fn run(self, builder: &Builder) {
616         let build = builder.build;
617         let compiler = self.compiler;
618         let target = self.target;
619
620         builder.ensure(Rustc { compiler, target });
621
622         if build.force_use_stage1(compiler, target) {
623             builder.ensure(CodegenBackend {
624                 compiler: builder.compiler(1, build.build),
625                 target,
626                 backend: self.backend,
627             });
628             return;
629         }
630
631         let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
632         let mut features = build.rustc_features().to_string();
633         cargo.arg("--manifest-path")
634             .arg(build.src.join("src/librustc_trans/Cargo.toml"));
635         rustc_cargo_env(build, &mut cargo);
636
637         let _folder = build.fold_output(|| format!("stage{}-rustc_trans", compiler.stage));
638
639         match &*self.backend {
640             "llvm" | "emscripten" => {
641                 // Build LLVM for our target. This will implicitly build the
642                 // host LLVM if necessary.
643                 let llvm_config = builder.ensure(native::Llvm {
644                     target,
645                     emscripten: self.backend == "emscripten",
646                 });
647
648                 if self.backend == "emscripten" {
649                     features.push_str(" emscripten");
650                 }
651
652                 println!("Building stage{} codegen artifacts ({} -> {}, {})",
653                          compiler.stage, &compiler.host, target, self.backend);
654
655                 // Pass down configuration from the LLVM build into the build of
656                 // librustc_llvm and librustc_trans.
657                 if build.is_rust_llvm(target) {
658                     cargo.env("LLVM_RUSTLLVM", "1");
659                 }
660                 cargo.env("LLVM_CONFIG", &llvm_config);
661                 if self.backend != "emscripten" {
662                     let target_config = build.config.target_config.get(&target);
663                     if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
664                         cargo.env("CFG_LLVM_ROOT", s);
665                     }
666                 }
667                 // Building with a static libstdc++ is only supported on linux right now,
668                 // not for MSVC or macOS
669                 if build.config.llvm_static_stdcpp &&
670                    !target.contains("freebsd") &&
671                    !target.contains("windows") &&
672                    !target.contains("apple") {
673                     let file = compiler_file(build,
674                                              build.cxx(target).unwrap(),
675                                              target,
676                                              "libstdc++.a");
677                     cargo.env("LLVM_STATIC_STDCPP", file);
678                 }
679                 if build.config.llvm_link_shared {
680                     cargo.env("LLVM_LINK_SHARED", "1");
681                 }
682             }
683             _ => panic!("unknown backend: {}", self.backend),
684         }
685
686         let tmp_stamp = build.cargo_out(compiler, Mode::Librustc, target)
687             .join(".tmp.stamp");
688         let files = run_cargo(build,
689                               cargo.arg("--features").arg(features),
690                               &tmp_stamp,
691                               false);
692         let mut files = files.into_iter()
693             .filter(|f| {
694                 let filename = f.file_name().unwrap().to_str().unwrap();
695                 is_dylib(filename) && filename.contains("rustc_trans-")
696             });
697         let codegen_backend = match files.next() {
698             Some(f) => f,
699             None => panic!("no dylibs built for codegen backend?"),
700         };
701         if let Some(f) = files.next() {
702             panic!("codegen backend built two dylibs:\n{}\n{}",
703                    codegen_backend.display(),
704                    f.display());
705         }
706         let stamp = codegen_backend_stamp(build, compiler, target, self.backend);
707         let codegen_backend = codegen_backend.to_str().unwrap();
708         t!(t!(File::create(&stamp)).write_all(codegen_backend.as_bytes()));
709     }
710 }
711
712 /// Creates the `codegen-backends` folder for a compiler that's about to be
713 /// assembled as a complete compiler.
714 ///
715 /// This will take the codegen artifacts produced by `compiler` and link them
716 /// into an appropriate location for `target_compiler` to be a functional
717 /// compiler.
718 fn copy_codegen_backends_to_sysroot(builder: &Builder,
719                                     compiler: Compiler,
720                                     target_compiler: Compiler) {
721     let build = builder.build;
722     let target = target_compiler.host;
723
724     // Note that this step is different than all the other `*Link` steps in
725     // that it's not assembling a bunch of libraries but rather is primarily
726     // moving the codegen backend into place. The codegen backend of rustc is
727     // not linked into the main compiler by default but is rather dynamically
728     // selected at runtime for inclusion.
729     //
730     // Here we're looking for the output dylib of the `CodegenBackend` step and
731     // we're copying that into the `codegen-backends` folder.
732     let dst = builder.sysroot_codegen_backends(target_compiler);
733     t!(fs::create_dir_all(&dst));
734
735     for backend in builder.config.rust_codegen_backends.iter() {
736         let stamp = codegen_backend_stamp(build, compiler, target, *backend);
737         let mut dylib = String::new();
738         t!(t!(File::open(&stamp)).read_to_string(&mut dylib));
739         let file = Path::new(&dylib);
740         let filename = file.file_name().unwrap().to_str().unwrap();
741         // change `librustc_trans-xxxxxx.so` to `librustc_trans-llvm.so`
742         let target_filename = {
743             let dash = filename.find("-").unwrap();
744             let dot = filename.find(".").unwrap();
745             format!("{}-{}{}",
746                     &filename[..dash],
747                     backend,
748                     &filename[dot..])
749         };
750         copy(&file, &dst.join(target_filename));
751     }
752 }
753
754 fn copy_lld_to_sysroot(builder: &Builder,
755                        target_compiler: Compiler,
756                        lld_install_root: &Path) {
757     let target = target_compiler.host;
758
759     let dst = builder.sysroot_libdir(target_compiler, target)
760         .parent()
761         .unwrap()
762         .join("bin");
763     t!(fs::create_dir_all(&dst));
764
765     let exe = exe("lld", &target);
766     copy(&lld_install_root.join("bin").join(&exe), &dst.join(&exe));
767 }
768
769 /// Cargo's output path for the standard library in a given stage, compiled
770 /// by a particular compiler for the specified target.
771 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
772     build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
773 }
774
775 /// Cargo's output path for libtest in a given stage, compiled by a particular
776 /// compiler for the specified target.
777 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
778     build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
779 }
780
781 /// Cargo's output path for librustc in a given stage, compiled by a particular
782 /// compiler for the specified target.
783 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
784     build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
785 }
786
787 fn codegen_backend_stamp(build: &Build,
788                          compiler: Compiler,
789                          target: Interned<String>,
790                          backend: Interned<String>) -> PathBuf {
791     build.cargo_out(compiler, Mode::Librustc, target)
792         .join(format!(".librustc_trans-{}.stamp", backend))
793 }
794
795 fn compiler_file(build: &Build,
796                  compiler: &Path,
797                  target: Interned<String>,
798                  file: &str) -> PathBuf {
799     let mut cmd = Command::new(compiler);
800     cmd.args(build.cflags(target));
801     cmd.arg(format!("-print-file-name={}", file));
802     let out = output(&mut cmd);
803     PathBuf::from(out.trim())
804 }
805
806 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
807 pub struct Sysroot {
808     pub compiler: Compiler,
809 }
810
811 impl Step for Sysroot {
812     type Output = Interned<PathBuf>;
813
814     fn should_run(run: ShouldRun) -> ShouldRun {
815         run.never()
816     }
817
818     /// Returns the sysroot for the `compiler` specified that *this build system
819     /// generates*.
820     ///
821     /// That is, the sysroot for the stage0 compiler is not what the compiler
822     /// thinks it is by default, but it's the same as the default for stages
823     /// 1-3.
824     fn run(self, builder: &Builder) -> Interned<PathBuf> {
825         let build = builder.build;
826         let compiler = self.compiler;
827         let sysroot = if compiler.stage == 0 {
828             build.out.join(&compiler.host).join("stage0-sysroot")
829         } else {
830             build.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
831         };
832         let _ = fs::remove_dir_all(&sysroot);
833         t!(fs::create_dir_all(&sysroot));
834         INTERNER.intern_path(sysroot)
835     }
836 }
837
838 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
839 pub struct Assemble {
840     /// The compiler which we will produce in this step. Assemble itself will
841     /// take care of ensuring that the necessary prerequisites to do so exist,
842     /// that is, this target can be a stage2 compiler and Assemble will build
843     /// previous stages for you.
844     pub target_compiler: Compiler,
845 }
846
847 impl Step for Assemble {
848     type Output = Compiler;
849
850     fn should_run(run: ShouldRun) -> ShouldRun {
851         run.all_krates("rustc-main")
852     }
853
854     /// Prepare a new compiler from the artifacts in `stage`
855     ///
856     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
857     /// must have been previously produced by the `stage - 1` build.build
858     /// compiler.
859     fn run(self, builder: &Builder) -> Compiler {
860         let build = builder.build;
861         let target_compiler = self.target_compiler;
862
863         if target_compiler.stage == 0 {
864             assert_eq!(build.build, target_compiler.host,
865                 "Cannot obtain compiler for non-native build triple at stage 0");
866             // The stage 0 compiler for the build triple is always pre-built.
867             return target_compiler;
868         }
869
870         // Get the compiler that we'll use to bootstrap ourselves.
871         //
872         // Note that this is where the recursive nature of the bootstrap
873         // happens, as this will request the previous stage's compiler on
874         // downwards to stage 0.
875         //
876         // Also note that we're building a compiler for the host platform. We
877         // only assume that we can run `build` artifacts, which means that to
878         // produce some other architecture compiler we need to start from
879         // `build` to get there.
880         //
881         // FIXME: Perhaps we should download those libraries?
882         //        It would make builds faster...
883         //
884         // FIXME: It may be faster if we build just a stage 1 compiler and then
885         //        use that to bootstrap this compiler forward.
886         let build_compiler =
887             builder.compiler(target_compiler.stage - 1, build.build);
888
889         // Build the libraries for this compiler to link to (i.e., the libraries
890         // it uses at runtime). NOTE: Crates the target compiler compiles don't
891         // link to these. (FIXME: Is that correct? It seems to be correct most
892         // of the time but I think we do link to these for stage2/bin compilers
893         // when not performing a full bootstrap).
894         if builder.build.config.keep_stage.map_or(false, |s| target_compiler.stage <= s) {
895             builder.verbose("skipping compilation of compiler due to --keep-stage");
896             let compiler = build_compiler;
897             for stage in 0..min(target_compiler.stage, builder.config.keep_stage.unwrap()) {
898                 let target_compiler = builder.compiler(stage, target_compiler.host);
899                 let target = target_compiler.host;
900                 builder.ensure(StdLink { compiler, target_compiler, target });
901                 builder.ensure(TestLink { compiler, target_compiler, target });
902                 builder.ensure(RustcLink { compiler, target_compiler, target });
903             }
904         } else {
905             builder.ensure(Rustc {
906                 compiler: build_compiler,
907                 target: target_compiler.host,
908             });
909             for &backend in build.config.rust_codegen_backends.iter() {
910                 builder.ensure(CodegenBackend {
911                     compiler: build_compiler,
912                     target: target_compiler.host,
913                     backend,
914                 });
915             }
916         }
917
918         let lld_install = if build.config.lld_enabled {
919             Some(builder.ensure(native::Lld {
920                 target: target_compiler.host,
921             }))
922         } else {
923             None
924         };
925
926         let stage = target_compiler.stage;
927         let host = target_compiler.host;
928         println!("Assembling stage{} compiler ({})", stage, host);
929
930         // Link in all dylibs to the libdir
931         let sysroot = builder.sysroot(target_compiler);
932         let sysroot_libdir = sysroot.join(libdir(&*host));
933         t!(fs::create_dir_all(&sysroot_libdir));
934         let src_libdir = builder.sysroot_libdir(build_compiler, host);
935         for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
936             let filename = f.file_name().into_string().unwrap();
937             if is_dylib(&filename) {
938                 copy(&f.path(), &sysroot_libdir.join(&filename));
939             }
940         }
941
942         copy_codegen_backends_to_sysroot(builder,
943                                          build_compiler,
944                                          target_compiler);
945         if let Some(lld_install) = lld_install {
946             copy_lld_to_sysroot(builder, target_compiler, &lld_install);
947         }
948
949         // Link the compiler binary itself into place
950         let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
951         let rustc = out_dir.join(exe("rustc", &*host));
952         let bindir = sysroot.join("bin");
953         t!(fs::create_dir_all(&bindir));
954         let compiler = builder.rustc(target_compiler);
955         let _ = fs::remove_file(&compiler);
956         copy(&rustc, &compiler);
957
958         target_compiler
959     }
960 }
961
962 /// Link some files into a rustc sysroot.
963 ///
964 /// For a particular stage this will link the file listed in `stamp` into the
965 /// `sysroot_dst` provided.
966 pub fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
967     t!(fs::create_dir_all(&sysroot_dst));
968     for path in read_stamp_file(stamp) {
969         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
970     }
971 }
972
973 // Avoiding a dependency on winapi to keep compile times down
974 #[cfg(unix)]
975 fn stderr_isatty() -> bool {
976     use libc;
977     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
978 }
979 #[cfg(windows)]
980 fn stderr_isatty() -> bool {
981     type DWORD = u32;
982     type BOOL = i32;
983     type HANDLE = *mut u8;
984     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
985     extern "system" {
986         fn GetStdHandle(which: DWORD) -> HANDLE;
987         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
988     }
989     unsafe {
990         let handle = GetStdHandle(STD_ERROR_HANDLE);
991         let mut out = 0;
992         GetConsoleMode(handle, &mut out) != 0
993     }
994 }
995
996 pub fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path, is_check: bool)
997     -> Vec<PathBuf>
998 {
999     // Instruct Cargo to give us json messages on stdout, critically leaving
1000     // stderr as piped so we can get those pretty colors.
1001     cargo.arg("--message-format").arg("json")
1002          .stdout(Stdio::piped());
1003
1004     if stderr_isatty() && build.ci_env == CiEnv::None {
1005         // since we pass message-format=json to cargo, we need to tell the rustc
1006         // wrapper to give us colored output if necessary. This is because we
1007         // only want Cargo's JSON output, not rustcs.
1008         cargo.env("RUSTC_COLOR", "1");
1009     }
1010
1011     build.verbose(&format!("running: {:?}", cargo));
1012     let mut child = match cargo.spawn() {
1013         Ok(child) => child,
1014         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1015     };
1016
1017     // `target_root_dir` looks like $dir/$target/release
1018     let target_root_dir = stamp.parent().unwrap();
1019     // `target_deps_dir` looks like $dir/$target/release/deps
1020     let target_deps_dir = target_root_dir.join("deps");
1021     // `host_root_dir` looks like $dir/release
1022     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
1023                                        .parent().unwrap() // chop off `$target`
1024                                        .join(target_root_dir.file_name().unwrap());
1025
1026     // Spawn Cargo slurping up its JSON output. We'll start building up the
1027     // `deps` array of all files it generated along with a `toplevel` array of
1028     // files we need to probe for later.
1029     let mut deps = Vec::new();
1030     let mut toplevel = Vec::new();
1031     let stdout = BufReader::new(child.stdout.take().unwrap());
1032     for line in stdout.lines() {
1033         let line = t!(line);
1034         let json: serde_json::Value = if line.starts_with("{") {
1035             t!(serde_json::from_str(&line))
1036         } else {
1037             // If this was informational, just print it out and continue
1038             println!("{}", line);
1039             continue
1040         };
1041         if json["reason"].as_str() != Some("compiler-artifact") {
1042             if build.config.rustc_error_format.as_ref().map_or(false, |e| e == "json") {
1043                 // most likely not a cargo message, so let's send it out as well
1044                 println!("{}", line);
1045             }
1046             continue
1047         }
1048         for filename in json["filenames"].as_array().unwrap() {
1049             let filename = filename.as_str().unwrap();
1050             // Skip files like executables
1051             if !filename.ends_with(".rlib") &&
1052                !filename.ends_with(".lib") &&
1053                !is_dylib(&filename) &&
1054                !(is_check && filename.ends_with(".rmeta")) {
1055                 continue
1056             }
1057
1058             let filename = Path::new(filename);
1059
1060             // If this was an output file in the "host dir" we don't actually
1061             // worry about it, it's not relevant for us.
1062             if filename.starts_with(&host_root_dir) {
1063                 continue;
1064             }
1065
1066             // If this was output in the `deps` dir then this is a precise file
1067             // name (hash included) so we start tracking it.
1068             if filename.starts_with(&target_deps_dir) {
1069                 deps.push(filename.to_path_buf());
1070                 continue;
1071             }
1072
1073             // Otherwise this was a "top level artifact" which right now doesn't
1074             // have a hash in the name, but there's a version of this file in
1075             // the `deps` folder which *does* have a hash in the name. That's
1076             // the one we'll want to we'll probe for it later.
1077             //
1078             // We do not use `Path::file_stem` or `Path::extension` here,
1079             // because some generated files may have multiple extensions e.g.
1080             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1081             // split the file name by the last extension (`.lib`) while we need
1082             // to split by all extensions (`.dll.lib`).
1083             let expected_len = t!(filename.metadata()).len();
1084             let filename = filename.file_name().unwrap().to_str().unwrap();
1085             let mut parts = filename.splitn(2, '.');
1086             let file_stem = parts.next().unwrap().to_owned();
1087             let extension = parts.next().unwrap().to_owned();
1088
1089             toplevel.push((file_stem, extension, expected_len));
1090         }
1091     }
1092
1093     // Make sure Cargo actually succeeded after we read all of its stdout.
1094     let status = t!(child.wait());
1095     if !status.success() {
1096         panic!("command did not execute successfully: {:?}\n\
1097                 expected success, got: {}",
1098                cargo,
1099                status);
1100     }
1101
1102     // Ok now we need to actually find all the files listed in `toplevel`. We've
1103     // got a list of prefix/extensions and we basically just need to find the
1104     // most recent file in the `deps` folder corresponding to each one.
1105     let contents = t!(target_deps_dir.read_dir())
1106         .map(|e| t!(e))
1107         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1108         .collect::<Vec<_>>();
1109     for (prefix, extension, expected_len) in toplevel {
1110         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1111             filename.starts_with(&prefix[..]) &&
1112                 filename[prefix.len()..].starts_with("-") &&
1113                 filename.ends_with(&extension[..]) &&
1114                 meta.len() == expected_len
1115         });
1116         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1117             FileTime::from_last_modification_time(metadata)
1118         });
1119         let path_to_add = match max {
1120             Some(triple) => triple.0.to_str().unwrap(),
1121             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1122         };
1123         if is_dylib(path_to_add) {
1124             let candidate = format!("{}.lib", path_to_add);
1125             let candidate = PathBuf::from(candidate);
1126             if candidate.exists() {
1127                 deps.push(candidate);
1128             }
1129         }
1130         deps.push(path_to_add.into());
1131     }
1132
1133     // Now we want to update the contents of the stamp file, if necessary. First
1134     // we read off the previous contents along with its mtime. If our new
1135     // contents (the list of files to copy) is different or if any dep's mtime
1136     // is newer then we rewrite the stamp file.
1137     deps.sort();
1138     let mut stamp_contents = Vec::new();
1139     if let Ok(mut f) = File::open(stamp) {
1140         t!(f.read_to_end(&mut stamp_contents));
1141     }
1142     let stamp_mtime = mtime(&stamp);
1143     let mut new_contents = Vec::new();
1144     let mut max = None;
1145     let mut max_path = None;
1146     for dep in deps.iter() {
1147         let mtime = mtime(dep);
1148         if Some(mtime) > max {
1149             max = Some(mtime);
1150             max_path = Some(dep.clone());
1151         }
1152         new_contents.extend(dep.to_str().unwrap().as_bytes());
1153         new_contents.extend(b"\0");
1154     }
1155     let max = max.unwrap();
1156     let max_path = max_path.unwrap();
1157     if stamp_contents == new_contents && max <= stamp_mtime {
1158         build.verbose(&format!("not updating {:?}; contents equal and {} <= {}",
1159                 stamp, max, stamp_mtime));
1160         return deps
1161     }
1162     if max > stamp_mtime {
1163         build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1164     } else {
1165         build.verbose(&format!("updating {:?} as deps changed", stamp));
1166     }
1167     t!(t!(File::create(stamp)).write_all(&new_contents));
1168     deps
1169 }