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.
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.
11 //! Implementation of compiling various phases of the compiler and standard
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.
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};
27 use build_helper::{output, mtime, up_to_date};
28 use filetime::FileTime;
29 use rustc_serialize::json;
31 use util::{exe, libdir, is_dylib, copy};
32 use {Build, Compiler, Mode};
35 use builder::{Step, Builder};
38 // // Crates which have build scripts need to rely on this rule to ensure that
39 // // the necessary prerequisites for a build script are linked and located in
41 // rules.build("may-run-build-script", "path/to/nowhere")
43 // s.name("libstd-link")
44 // .host(&build.build)
45 // .target(&build.build)
48 // // ========================================================================
49 // // Crate compilations
51 // // Tools used during the build system but not shipped
52 // // These rules are "pseudo rules" that don't actually do any work
53 // // themselves, but represent a complete sysroot with the relevant compiler
54 // // linked into place.
56 // // That is, depending on "libstd" means that when the rule is completed then
57 // // the `stage` sysroot for the compiler `host` will be available with a
58 // // standard library built for `target` linked in place. Not all rules need
59 // // the compiler itself to be available, just the standard library, so
60 // // there's a distinction between the two.
61 // rules.build("libstd", "src/libstd")
62 // .dep(|s| s.name("rustc").target(s.host))
63 // .dep(|s| s.name("libstd-link"));
64 // rules.build("libtest", "src/libtest")
65 // .dep(|s| s.name("libstd"))
66 // .dep(|s| s.name("libtest-link"))
68 // rules.build("librustc", "src/librustc")
69 // .dep(|s| s.name("libtest"))
70 // .dep(|s| s.name("librustc-link"))
74 // Helper method to define the rules to link a crate into its place in the
77 // The logic here is a little subtle as there's a few cases to consider.
78 // Not all combinations of (stage, host, target) actually require something
79 // to be compiled, but rather libraries could get propagated from a
80 // different location. For example:
82 // * Any crate with a `host` that's not the build triple will not actually
83 // compile something. A different `host` means that the build triple will
84 // actually compile the libraries, and then we'll copy them over from the
85 // build triple to the `host` directory.
87 // * Some crates aren't even compiled by the build triple, but may be copied
88 // from previous stages. For example if we're not doing a full bootstrap
89 // then we may just depend on the stage1 versions of libraries to be
90 // available to get linked forward.
92 // * Finally, there are some cases, however, which do indeed comiple crates
93 // and link them into place afterwards.
95 // The rule definition below mirrors these three cases. The `dep` method
96 // calculates the correct dependency which either comes from stage1, a
97 // different compiler, or from actually building the crate itself (the `dep`
98 // rule). The `run` rule then mirrors these three cases and links the cases
99 // forward into the compiler sysroot specified from the correct location.
100 // fn crate_rule<'a, 'b>(build: &'a Build,
101 // rules: &'b mut Rules<'a>,
104 // link: fn(&Build, compiler, compiler, &str))
105 // -> RuleBuilder<'a, 'b> {
106 // let mut rule = rules.build(&krate, "path/to/nowhere");
107 // rule.dep(move |s| {
108 // if build.force_use_stage1(&s.compiler(), s.target) {
109 // s.host(&build.build).stage(1)
110 // } else if s.host == build.build {
113 // s.host(&build.build)
117 // if build.force_use_stage1(&s.compiler(), s.target) {
119 // &s.stage(1).host(&build.build).compiler(),
122 // } else if s.host == build.build {
123 // link(build, &s.compiler(), &s.compiler(), s.target)
126 // &s.host(&build.build).compiler(),
134 // rules.build("libstd", "src/libstd")
135 // .dep(|s| s.name("rustc").target(s.host))
136 // .dep(|s| s.name("libstd-link"));
137 // for (krate, path, _default) in krates("std") {
138 // rules.build(&krate.build_step, path)
139 // .dep(|s| s.name("startup-objects"))
140 // .dep(move |s| s.name("rustc").host(&build.build).target(s.host))
141 // .run(move |s| compile::std(build, s.target, &s.compiler()));
146 pub compiler: Compiler<'a>,
149 impl<'a> Step<'a> for Std<'a> {
151 const DEFAULT: bool = true;
153 fn should_run(builder: &Builder, path: &Path) -> bool {
154 path.ends_with("src/libstd") ||
155 builder.crates("std").into_iter().any(|(_, krate_path)| {
156 path.ends_with(krate_path)
160 fn make_run(builder: &Builder, _path: Option<&Path>, host: &str, target: &str) {
162 compiler: builder.compiler(builder.top_stage, host),
167 /// Build the standard library.
169 /// This will build the standard library for a particular stage of the build
170 /// using the `compiler` targeting the `target` architecture. The artifacts
171 /// created will also be linked into the sysroot directory.
172 fn run(self, builder: &Builder) {
173 let build = builder.build;
174 let target = self.target;
175 let compiler = self.compiler;
177 builder.ensure(StartupObjects { compiler, target });
179 if build.force_use_stage1(compiler, target) {
180 let from = builder.compiler(1, &build.build);
185 println!("Uplifting stage1 std ({} -> {})", from.host, target);
186 builder.ensure(StdLink {
188 target_compiler: compiler,
194 let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
195 println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
196 compiler.host, target);
198 let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
199 build.clear_if_dirty(&out_dir, &build.compiler_path(compiler));
200 let mut cargo = builder.cargo(compiler, Mode::Libstd, target, "build");
201 let mut features = build.std_features();
203 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
204 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
207 // When doing a local rebuild we tell cargo that we're stage1 rather than
208 // stage0. This works fine if the local rust and being-built rust have the
209 // same view of what the default allocator is, but fails otherwise. Since
210 // we don't have a way to express an allocator preference yet, work
211 // around the issue in the case of a local rebuild with jemalloc disabled.
212 if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
213 features.push_str(" force_alloc_system");
216 if compiler.stage != 0 && build.config.sanitizers {
217 // This variable is used by the sanitizer runtime crates, e.g.
218 // rustc_lsan, to build the sanitizer runtime from C code
219 // When this variable is missing, those crates won't compile the C code,
220 // so we don't set this variable during stage0 where llvm-config is
222 // We also only build the runtimes when --enable-sanitizers (or its
223 // config.toml equivalent) is used
224 cargo.env("LLVM_CONFIG", build.llvm_config(target));
227 cargo.arg("--features").arg(features)
228 .arg("--manifest-path")
229 .arg(build.src.join("src/libstd/Cargo.toml"));
231 if let Some(target) = build.config.target_config.get(target) {
232 if let Some(ref jemalloc) = target.jemalloc {
233 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
236 if target.contains("musl") {
237 if let Some(p) = build.musl_root(target) {
238 cargo.env("MUSL_ROOT", p);
244 &libstd_stamp(build, compiler, target));
246 builder.ensure(StdLink {
247 compiler: builder.compiler(compiler.stage, &build.build),
248 target_compiler: compiler,
258 // "build-crate-std",
259 // compile::std_link)
260 // .dep(|s| s.name("startup-objects"))
261 // .dep(|s| s.name("create-sysroot").target(s.host));
265 pub compiler: Compiler<'a>,
266 pub target_compiler: Compiler<'a>,
270 impl<'a> Step<'a> for StdLink<'a> {
273 /// Link all libstd rlibs/dylibs into the sysroot location.
275 /// Links those artifacts generated by `compiler` to a the `stage` compiler's
276 /// sysroot for the specified `host` and `target`.
278 /// Note that this assumes that `compiler` has already generated the libstd
279 /// libraries for `target`, and this method will find them in the relevant
280 /// output directory.
281 fn run(self, builder: &Builder) {
282 let build = builder.build;
283 let compiler = self.compiler;
284 let target_compiler = self.target_compiler;
285 let target = self.target;
286 println!("Copying stage{} std from stage{} ({} -> {} / {})",
287 target_compiler.stage,
290 target_compiler.host,
292 let libdir = builder.sysroot_libdir(target_compiler, target);
293 add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
295 if target.contains("musl") && !target.contains("mips") {
296 copy_musl_third_party_objects(build, target, &libdir);
299 if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
300 // The sanitizers are only built in stage1 or above, so the dylibs will
301 // be missing in stage0 and causes panic. See the `std()` function above
302 // for reason why the sanitizers are not built in stage0.
303 copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
308 /// Copies the crt(1,i,n).o startup objects
310 /// Only required for musl targets that statically link to libc
311 fn copy_musl_third_party_objects(build: &Build, target: &str, into: &Path) {
312 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
313 copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
317 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
318 for &sanitizer in &["asan", "tsan"] {
319 let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
320 let mut src_path = native_dir.join(sanitizer);
321 src_path.push("build");
322 src_path.push("lib");
323 src_path.push("darwin");
324 src_path.push(&filename);
325 copy(&src_path, &into.join(filename));
329 // rules.build("startup-objects", "src/rtstartup")
330 // .dep(|s| s.name("create-sysroot").target(s.host))
331 // .run(move |s| compile::build_startup_objects(build, &s.compiler(), s.target));
334 pub struct StartupObjects<'a> {
335 pub compiler: Compiler<'a>,
339 impl<'a> Step<'a> for StartupObjects<'a> {
342 fn should_run(_builder: &Builder, path: &Path) -> bool {
343 path.ends_with("src/rtstartup")
346 fn make_run(builder: &Builder, _path: Option<&Path>, host: &str, target: &str) {
347 builder.ensure(StartupObjects {
348 compiler: builder.compiler(builder.top_stage, host),
353 /// Build and prepare startup objects like rsbegin.o and rsend.o
355 /// These are primarily used on Windows right now for linking executables/dlls.
356 /// They don't require any library support as they're just plain old object
357 /// files, so we just use the nightly snapshot compiler to always build them (as
358 /// no other compilers are guaranteed to be available).
359 fn run(self, builder: &Builder) {
360 let build = builder.build;
361 let for_compiler = self.compiler;
362 let target = self.target;
363 if !target.contains("pc-windows-gnu") {
367 let compiler = builder.compiler(0, &build.build);
368 let compiler_path = build.compiler_path(compiler);
369 let src_dir = &build.src.join("src/rtstartup");
370 let dst_dir = &build.native_dir(target).join("rtstartup");
371 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
372 t!(fs::create_dir_all(dst_dir));
373 t!(fs::create_dir_all(sysroot_dir));
375 for file in &["rsbegin", "rsend"] {
376 let src_file = &src_dir.join(file.to_string() + ".rs");
377 let dst_file = &dst_dir.join(file.to_string() + ".o");
378 if !up_to_date(src_file, dst_file) {
379 let mut cmd = Command::new(&compiler_path);
380 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
381 .arg("--cfg").arg(format!("stage{}", compiler.stage))
382 .arg("--target").arg(target)
384 .arg("--out-dir").arg(dst_dir)
388 copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
391 for obj in ["crt2.o", "dllcrt2.o"].iter() {
392 copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
397 // for (krate, path, _default) in krates("test") {
398 // rules.build(&krate.build_step, path)
399 // .dep(|s| s.name("libstd-link"))
400 // .run(move |s| compile::test(build, s.target, &s.compiler()));
403 pub struct Test<'a> {
404 pub compiler: Compiler<'a>,
408 impl<'a> Step<'a> for Test<'a> {
410 const DEFAULT: bool = true;
412 fn should_run(builder: &Builder, path: &Path) -> bool {
413 path.ends_with("src/libtest") ||
414 builder.crates("test").into_iter().any(|(_, krate_path)| {
415 path.ends_with(krate_path)
419 fn make_run(builder: &Builder, _path: Option<&Path>, host: &str, target: &str) {
420 builder.ensure(Test {
421 compiler: builder.compiler(builder.top_stage, host),
428 /// This will build libtest and supporting libraries for a particular stage of
429 /// the build using the `compiler` targeting the `target` architecture. The
430 /// artifacts created will also be linked into the sysroot directory.
431 fn run(self, builder: &Builder) {
432 let build = builder.build;
433 let target = self.target;
434 let compiler = self.compiler;
436 builder.ensure(Std { compiler, target });
438 if build.force_use_stage1(compiler, target) {
439 builder.ensure(Test {
440 compiler: builder.compiler(1, &build.build),
443 println!("Uplifting stage1 test ({} -> {})", &build.build, target);
444 builder.ensure(TestLink {
445 compiler: builder.compiler(1, &build.build),
446 target_compiler: compiler,
452 let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
453 println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
454 compiler.host, target);
455 let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
456 build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
457 let mut cargo = build.cargo(compiler, Mode::Libtest, target, "build");
458 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
459 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
461 cargo.arg("--manifest-path")
462 .arg(build.src.join("src/libtest/Cargo.toml"));
465 &libtest_stamp(build, compiler, target));
467 builder.ensure(TestLink {
468 compiler: builder.compiler(1, &build.build),
469 target_compiler: compiler,
479 // "build-crate-test",
480 // compile::test_link)
481 // .dep(|s| s.name("libstd-link"));
484 pub struct TestLink<'a> {
485 pub compiler: Compiler<'a>,
486 pub target_compiler: Compiler<'a>,
490 impl<'a> Step<'a> for TestLink<'a> {
493 /// Same as `std_link`, only for libtest
494 fn run(self, builder: &Builder) {
495 let build = builder.build;
496 let compiler = self.compiler;
497 let target_compiler = self.target_compiler;
498 let target = self.target;
499 println!("Copying stage{} test from stage{} ({} -> {} / {})",
500 target_compiler.stage,
503 target_compiler.host,
505 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
506 &libtest_stamp(build, compiler, target));
510 // for (krate, path, _default) in krates("rustc-main") {
511 // rules.build(&krate.build_step, path)
512 // .dep(|s| s.name("libtest-link"))
513 // .dep(move |s| s.name("llvm").host(&build.build).stage(0))
514 // .dep(|s| s.name("may-run-build-script"))
515 // .run(move |s| compile::rustc(build, s.target, &s.compiler()));
519 pub struct Rustc<'a> {
520 pub compiler: Compiler<'a>,
524 impl<'a> Step<'a> for Rustc<'a> {
526 const ONLY_HOSTS: bool = true;
527 const DEFAULT: bool = true;
529 fn should_run(builder: &Builder, path: &Path) -> bool {
530 path.ends_with("src/librustc") ||
531 builder.crates("rustc-main").into_iter().any(|(_, krate_path)| {
532 path.ends_with(krate_path)
536 fn make_run(builder: &Builder, _path: Option<&Path>, host: &str, target: &str) {
537 builder.ensure(Rustc {
538 compiler: builder.compiler(builder.top_stage, host),
543 /// Build the compiler.
545 /// This will build the compiler for a particular stage of the build using
546 /// the `compiler` targeting the `target` architecture. The artifacts
547 /// created will also be linked into the sysroot directory.
548 fn run(self, builder: &Builder) {
549 let build = builder.build;
550 let compiler = self.compiler;
551 let target = self.target;
553 builder.ensure(Test { compiler, target });
555 // Build LLVM for our target. This will implicitly build the host LLVM
557 builder.ensure(native::Llvm { target });
559 if build.force_use_stage1(compiler, target) {
560 builder.ensure(Rustc {
561 compiler: builder.compiler(1, &build.build),
564 println!("Uplifting stage1 rustc ({} -> {})", &build.build, target);
565 builder.ensure(RustcLink {
566 compiler: builder.compiler(1, &build.build),
567 target_compiler: compiler,
573 // Ensure that build scripts have a std to link against.
575 compiler: builder.compiler(self.compiler.stage, &build.build),
576 target: &build.build,
579 let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
580 println!("Building stage{} compiler artifacts ({} -> {})",
581 compiler.stage, compiler.host, target);
583 let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
584 build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
586 let mut cargo = build.cargo(compiler, Mode::Librustc, target, "build");
587 cargo.arg("--features").arg(build.rustc_features())
588 .arg("--manifest-path")
589 .arg(build.src.join("src/rustc/Cargo.toml"));
591 // Set some configuration variables picked up by build scripts and
592 // the compiler alike
593 cargo.env("CFG_RELEASE", build.rust_release())
594 .env("CFG_RELEASE_CHANNEL", &build.config.channel)
595 .env("CFG_VERSION", build.rust_version())
596 .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default());
598 if compiler.stage == 0 {
599 cargo.env("CFG_LIBDIR_RELATIVE", "lib");
601 let libdir_relative = build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
602 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
605 // If we're not building a compiler with debugging information then remove
606 // these two env vars which would be set otherwise.
607 if build.config.rust_debuginfo_only_std {
608 cargo.env_remove("RUSTC_DEBUGINFO");
609 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
612 if let Some(ref ver_date) = build.rust_info.commit_date() {
613 cargo.env("CFG_VER_DATE", ver_date);
615 if let Some(ref ver_hash) = build.rust_info.sha() {
616 cargo.env("CFG_VER_HASH", ver_hash);
618 if !build.unstable_features() {
619 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
621 // Flag that rust llvm is in use
622 if build.is_rust_llvm(target) {
623 cargo.env("LLVM_RUSTLLVM", "1");
625 cargo.env("LLVM_CONFIG", build.llvm_config(target));
626 let target_config = build.config.target_config.get(target);
627 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
628 cargo.env("CFG_LLVM_ROOT", s);
630 // Building with a static libstdc++ is only supported on linux right now,
631 // not for MSVC or macOS
632 if build.config.llvm_static_stdcpp &&
633 !target.contains("windows") &&
634 !target.contains("apple") {
635 cargo.env("LLVM_STATIC_STDCPP",
636 compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
638 if build.config.llvm_link_shared {
639 cargo.env("LLVM_LINK_SHARED", "1");
641 if let Some(ref s) = build.config.rustc_default_linker {
642 cargo.env("CFG_DEFAULT_LINKER", s);
644 if let Some(ref s) = build.config.rustc_default_ar {
645 cargo.env("CFG_DEFAULT_AR", s);
649 &librustc_stamp(build, compiler, target));
651 builder.ensure(RustcLink {
652 compiler: builder.compiler(compiler.stage, &build.build),
653 target_compiler: compiler,
662 // "build-crate-rustc-main",
663 // compile::rustc_link)
664 // .dep(|s| s.name("libtest-link"));
666 struct RustcLink<'a> {
667 pub compiler: Compiler<'a>,
668 pub target_compiler: Compiler<'a>,
672 impl<'a> Step<'a> for RustcLink<'a> {
675 /// Same as `std_link`, only for librustc
676 fn run(self, builder: &Builder) {
677 let build = builder.build;
678 let compiler = self.compiler;
679 let target_compiler = self.target_compiler;
680 let target = self.target;
681 println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
682 target_compiler.stage,
685 target_compiler.host,
687 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
688 &librustc_stamp(build, compiler, target));
692 /// Cargo's output path for the standard library in a given stage, compiled
693 /// by a particular compiler for the specified target.
694 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
695 build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
698 /// Cargo's output path for libtest in a given stage, compiled by a particular
699 /// compiler for the specified target.
700 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
701 build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
704 /// Cargo's output path for librustc in a given stage, compiled by a particular
705 /// compiler for the specified target.
706 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
707 build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
710 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
711 let out = output(Command::new(compiler)
712 .arg(format!("-print-file-name={}", file)));
713 PathBuf::from(out.trim())
716 // rules.build("create-sysroot", "path/to/nowhere")
717 // .run(move |s| compile::create_sysroot(build, &s.compiler()));
720 pub struct Sysroot<'a> {
721 pub compiler: Compiler<'a>,
724 impl<'a> Step<'a> for Sysroot<'a> {
725 type Output = PathBuf;
727 /// Returns the sysroot for the `compiler` specified that *this build system
730 /// That is, the sysroot for the stage0 compiler is not what the compiler
731 /// thinks it is by default, but it's the same as the default for stages
733 fn run(self, builder: &Builder) -> PathBuf {
734 let build = builder.build;
735 let compiler = self.compiler;
736 let sysroot = if compiler.stage == 0 {
737 build.out.join(compiler.host).join("stage0-sysroot")
739 build.out.join(compiler.host).join(format!("stage{}", compiler.stage))
741 let _ = fs::remove_dir_all(&sysroot);
742 t!(fs::create_dir_all(&sysroot));
747 // the compiler with no target libraries ready to go
748 // rules.build("rustc", "src/rustc")
749 // .dep(|s| s.name("create-sysroot").target(s.host))
754 // s.name("librustc")
755 // .host(&build.build)
756 // .stage(s.stage - 1)
759 // .run(move |s| compile::assemble_rustc(build, s.stage, s.target));
762 pub struct Assemble<'a> {
763 /// The compiler which we will produce in this step. Assemble itself will
764 /// take care of ensuring that the necessary prerequisites to do so exist,
765 /// that is, this target can be a stage2 compiler and Assemble will build
766 /// previous stages for you.
767 pub target_compiler: Compiler<'a>,
770 impl<'a> Step<'a> for Assemble<'a> {
771 type Output = Compiler<'a>;
773 /// Prepare a new compiler from the artifacts in `stage`
775 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
776 /// must have been previously produced by the `stage - 1` build.build
778 fn run(self, builder: &Builder) -> Compiler<'a> {
779 let build = builder.build;
780 let target_compiler = self.target_compiler;
782 if target_compiler.stage == 0 {
783 assert_eq!(build.build, target_compiler.host,
784 "Cannot obtain compiler for non-native build triple at stage 0");
785 // The stage 0 compiler for the build triple is always pre-built.
786 return target_compiler;
789 // Get the compiler that we'll use to bootstrap ourselves.
790 let build_compiler = if target_compiler.host != build.build {
791 // Build a compiler for the host platform. We cannot use the stage0
792 // compiler for the host platform for this because it doesn't have
793 // the libraries we need. FIXME: Perhaps we should download those
794 // libraries? It would make builds faster...
795 builder.ensure(Assemble {
796 target_compiler: Compiler {
797 // FIXME: It may be faster if we build just a stage 1
798 // compiler and then use that to bootstrap this compiler
800 stage: target_compiler.stage - 1,
805 // Build the compiler we'll use to build the stage requested. This
806 // may build more than one compiler (going down to stage 0).
807 builder.ensure(Assemble {
808 target_compiler: target_compiler.with_stage(target_compiler.stage - 1),
812 // Build the libraries for this compiler to link to (i.e., the libraries
813 // it uses at runtime). NOTE: Crates the target compiler compiles don't
814 // link to these. (FIXME: Is that correct? It seems to be correct most
815 // of the time but I think we do link to these for stage2/bin compilers
816 // when not performing a full bootstrap).
817 builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
819 let stage = target_compiler.stage;
820 let host = target_compiler.host;
821 println!("Assembling stage{} compiler ({})", stage, host);
823 // Link in all dylibs to the libdir
824 let sysroot = builder.sysroot(target_compiler);
825 let sysroot_libdir = sysroot.join(libdir(host));
826 t!(fs::create_dir_all(&sysroot_libdir));
827 let src_libdir = builder.sysroot_libdir(build_compiler, host);
828 for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
829 let filename = f.file_name().into_string().unwrap();
830 if is_dylib(&filename) {
831 copy(&f.path(), &sysroot_libdir.join(&filename));
835 let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
837 // Link the compiler binary itself into place
838 let rustc = out_dir.join(exe("rustc", host));
839 let bindir = sysroot.join("bin");
840 t!(fs::create_dir_all(&bindir));
841 let compiler = build.compiler_path(target_compiler);
842 let _ = fs::remove_file(&compiler);
843 copy(&rustc, &compiler);
845 // See if rustdoc exists to link it into place
846 let rustdoc = exe("rustdoc", host);
847 let rustdoc_src = out_dir.join(&rustdoc);
848 let rustdoc_dst = bindir.join(&rustdoc);
849 if fs::metadata(&rustdoc_src).is_ok() {
850 let _ = fs::remove_file(&rustdoc_dst);
851 copy(&rustdoc_src, &rustdoc_dst);
858 /// Link some files into a rustc sysroot.
860 /// For a particular stage this will link the file listed in `stamp` into the
861 /// `sysroot_dst` provided.
862 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
863 t!(fs::create_dir_all(&sysroot_dst));
864 let mut contents = Vec::new();
865 t!(t!(File::open(stamp)).read_to_end(&mut contents));
866 // This is the method we use for extracting paths from the stamp file passed to us. See
867 // run_cargo for more information (in this file).
868 for part in contents.split(|b| *b == 0) {
872 let path = Path::new(t!(str::from_utf8(part)));
873 copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
877 // Avoiding a dependency on winapi to keep compile times down
879 fn stderr_isatty() -> bool {
881 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
884 fn stderr_isatty() -> bool {
887 type HANDLE = *mut u8;
888 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
890 fn GetStdHandle(which: DWORD) -> HANDLE;
891 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
894 let handle = GetStdHandle(STD_ERROR_HANDLE);
896 GetConsoleMode(handle, &mut out) != 0
900 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
901 // Instruct Cargo to give us json messages on stdout, critically leaving
902 // stderr as piped so we can get those pretty colors.
903 cargo.arg("--message-format").arg("json")
904 .stdout(Stdio::piped());
907 // since we pass message-format=json to cargo, we need to tell the rustc
908 // wrapper to give us colored output if necessary. This is because we
909 // only want Cargo's JSON output, not rustcs.
910 cargo.env("RUSTC_COLOR", "1");
913 build.verbose(&format!("running: {:?}", cargo));
914 let mut child = match cargo.spawn() {
916 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
919 // `target_root_dir` looks like $dir/$target/release
920 let target_root_dir = stamp.parent().unwrap();
921 // `target_deps_dir` looks like $dir/$target/release/deps
922 let target_deps_dir = target_root_dir.join("deps");
923 // `host_root_dir` looks like $dir/release
924 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
925 .parent().unwrap() // chop off `$target`
926 .join(target_root_dir.file_name().unwrap());
928 // Spawn Cargo slurping up its JSON output. We'll start building up the
929 // `deps` array of all files it generated along with a `toplevel` array of
930 // files we need to probe for later.
931 let mut deps = Vec::new();
932 let mut toplevel = Vec::new();
933 let stdout = BufReader::new(child.stdout.take().unwrap());
934 for line in stdout.lines() {
936 let json = if line.starts_with("{") {
937 t!(line.parse::<json::Json>())
939 // If this was informational, just print it out and continue
940 println!("{}", line);
943 if json.find("reason").and_then(|j| j.as_string()) != Some("compiler-artifact") {
946 for filename in json["filenames"].as_array().unwrap() {
947 let filename = filename.as_string().unwrap();
948 // Skip files like executables
949 if !filename.ends_with(".rlib") &&
950 !filename.ends_with(".lib") &&
951 !is_dylib(&filename) {
955 let filename = Path::new(filename);
957 // If this was an output file in the "host dir" we don't actually
958 // worry about it, it's not relevant for us.
959 if filename.starts_with(&host_root_dir) {
963 // If this was output in the `deps` dir then this is a precise file
964 // name (hash included) so we start tracking it.
965 if filename.starts_with(&target_deps_dir) {
966 deps.push(filename.to_path_buf());
970 // Otherwise this was a "top level artifact" which right now doesn't
971 // have a hash in the name, but there's a version of this file in
972 // the `deps` folder which *does* have a hash in the name. That's
973 // the one we'll want to we'll probe for it later.
974 toplevel.push((filename.file_stem().unwrap()
975 .to_str().unwrap().to_string(),
976 filename.extension().unwrap().to_owned()
977 .to_str().unwrap().to_string()));
981 // Make sure Cargo actually succeeded after we read all of its stdout.
982 let status = t!(child.wait());
983 if !status.success() {
984 panic!("command did not execute successfully: {:?}\n\
985 expected success, got: {}",
990 // Ok now we need to actually find all the files listed in `toplevel`. We've
991 // got a list of prefix/extensions and we basically just need to find the
992 // most recent file in the `deps` folder corresponding to each one.
993 let contents = t!(target_deps_dir.read_dir())
995 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
996 .collect::<Vec<_>>();
997 for (prefix, extension) in toplevel {
998 let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
999 filename.starts_with(&prefix[..]) &&
1000 filename[prefix.len()..].starts_with("-") &&
1001 filename.ends_with(&extension[..])
1003 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1004 FileTime::from_last_modification_time(metadata)
1006 let path_to_add = match max {
1007 Some(triple) => triple.0.to_str().unwrap(),
1008 None => panic!("no output generated for {:?} {:?}", prefix, extension),
1010 if is_dylib(path_to_add) {
1011 let candidate = format!("{}.lib", path_to_add);
1012 let candidate = PathBuf::from(candidate);
1013 if candidate.exists() {
1014 deps.push(candidate);
1017 deps.push(path_to_add.into());
1020 // Now we want to update the contents of the stamp file, if necessary. First
1021 // we read off the previous contents along with its mtime. If our new
1022 // contents (the list of files to copy) is different or if any dep's mtime
1023 // is newer then we rewrite the stamp file.
1025 let mut stamp_contents = Vec::new();
1026 if let Ok(mut f) = File::open(stamp) {
1027 t!(f.read_to_end(&mut stamp_contents));
1029 let stamp_mtime = mtime(&stamp);
1030 let mut new_contents = Vec::new();
1032 let mut max_path = None;
1034 let mtime = mtime(&dep);
1035 if Some(mtime) > max {
1037 max_path = Some(dep.clone());
1039 new_contents.extend(dep.to_str().unwrap().as_bytes());
1040 new_contents.extend(b"\0");
1042 let max = max.unwrap();
1043 let max_path = max_path.unwrap();
1044 if stamp_contents == new_contents && max <= stamp_mtime {
1047 if max > stamp_mtime {
1048 build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1050 build.verbose(&format!("updating {:?} as deps changed", stamp));
1052 t!(t!(File::create(stamp)).write_all(&new_contents));