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