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