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