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;
31 use util::{exe, libdir, is_dylib, copy};
32 use {Build, Compiler, Mode};
35 use cache::{INTERNER, Interned};
36 use builder::{Step, Builder};
39 // // Crates which have build scripts need to rely on this rule to ensure that
40 // // the necessary prerequisites for a build script are linked and located in
42 // rules.build("may-run-build-script", "path/to/nowhere")
44 // s.name("libstd-link")
45 // .host(&build.build)
46 // .target(&build.build)
49 // // ========================================================================
50 // // Crate compilations
52 // // Tools used during the build system but not shipped
53 // // These rules are "pseudo rules" that don't actually do any work
54 // // themselves, but represent a complete sysroot with the relevant compiler
55 // // linked into place.
57 // // That is, depending on "libstd" means that when the rule is completed then
58 // // the `stage` sysroot for the compiler `host` will be available with a
59 // // standard library built for `target` linked in place. Not all rules need
60 // // the compiler itself to be available, just the standard library, so
61 // // there's a distinction between the two.
62 // rules.build("libstd", "src/libstd")
63 // .dep(|s| s.name("rustc").target(s.host))
64 // .dep(|s| s.name("libstd-link"));
65 // rules.build("libtest", "src/libtest")
66 // .dep(|s| s.name("libstd"))
67 // .dep(|s| s.name("libtest-link"))
69 // rules.build("librustc", "src/librustc")
70 // .dep(|s| s.name("libtest"))
71 // .dep(|s| s.name("librustc-link"))
75 // Helper method to define the rules to link a crate into its place in the
78 // The logic here is a little subtle as there's a few cases to consider.
79 // Not all combinations of (stage, host, target) actually require something
80 // to be compiled, but rather libraries could get propagated from a
81 // different location. For example:
83 // * Any crate with a `host` that's not the build triple will not actually
84 // compile something. A different `host` means that the build triple will
85 // actually compile the libraries, and then we'll copy them over from the
86 // build triple to the `host` directory.
88 // * Some crates aren't even compiled by the build triple, but may be copied
89 // from previous stages. For example if we're not doing a full bootstrap
90 // then we may just depend on the stage1 versions of libraries to be
91 // available to get linked forward.
93 // * Finally, there are some cases, however, which do indeed comiple crates
94 // and link them into place afterwards.
96 // The rule definition below mirrors these three cases. The `dep` method
97 // calculates the correct dependency which either comes from stage1, a
98 // different compiler, or from actually building the crate itself (the `dep`
99 // rule). The `run` rule then mirrors these three cases and links the cases
100 // forward into the compiler sysroot specified from the correct location.
101 // fn crate_rule<'a, 'b>(build: &'a Build,
102 // rules: &'b mut Rules<'a>,
105 // link: fn(&Build, compiler, compiler, &str))
106 // -> RuleBuilder<'a, 'b> {
107 // let mut rule = rules.build(&krate, "path/to/nowhere");
108 // rule.dep(move |s| {
109 // if build.force_use_stage1(&s.compiler(), s.target) {
110 // s.host(&build.build).stage(1)
111 // } else if s.host == build.build {
114 // s.host(&build.build)
118 // if build.force_use_stage1(&s.compiler(), s.target) {
120 // &s.stage(1).host(&build.build).compiler(),
123 // } else if s.host == build.build {
124 // link(build, &s.compiler(), &s.compiler(), s.target)
127 // &s.host(&build.build).compiler(),
135 // rules.build("libstd", "src/libstd")
136 // .dep(|s| s.name("rustc").target(s.host))
137 // .dep(|s| s.name("libstd-link"));
138 // for (krate, path, _default) in krates("std") {
139 // rules.build(&krate.build_step, path)
140 // .dep(|s| s.name("startup-objects"))
141 // .dep(move |s| s.name("rustc").host(&build.build).target(s.host))
142 // .run(move |s| compile::std(build, s.target, &s.compiler()));
144 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
146 pub target: Interned<String>,
147 pub compiler: Compiler,
152 const DEFAULT: bool = true;
154 fn should_run(builder: &Builder, path: &Path) -> bool {
155 path.ends_with("src/libstd") ||
156 builder.crates("std").into_iter().any(|(_, krate_path)| {
157 path.ends_with(krate_path)
163 _path: Option<&Path>,
164 host: Interned<String>,
165 target: Interned<String>,
168 compiler: builder.compiler(builder.top_stage, host),
173 /// Build the standard library.
175 /// This will build the standard library for a particular stage of the build
176 /// using the `compiler` targeting the `target` architecture. The artifacts
177 /// created will also be linked into the sysroot directory.
178 fn run(self, builder: &Builder) {
179 let build = builder.build;
180 let target = self.target;
181 let compiler = self.compiler;
183 builder.ensure(StartupObjects { compiler, target });
185 if build.force_use_stage1(compiler, target) {
186 let from = builder.compiler(1, build.build);
191 println!("Uplifting stage1 std ({} -> {})", from.host, target);
192 builder.ensure(StdLink {
194 target_compiler: compiler,
200 let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
201 println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
202 &compiler.host, target);
204 let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
205 build.clear_if_dirty(&out_dir, &builder.rustc(compiler));
206 let mut cargo = builder.cargo(compiler, Mode::Libstd, target, "build");
207 let mut features = build.std_features();
209 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
210 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
213 // When doing a local rebuild we tell cargo that we're stage1 rather than
214 // stage0. This works fine if the local rust and being-built rust have the
215 // same view of what the default allocator is, but fails otherwise. Since
216 // we don't have a way to express an allocator preference yet, work
217 // around the issue in the case of a local rebuild with jemalloc disabled.
218 if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
219 features.push_str(" force_alloc_system");
222 if compiler.stage != 0 && build.config.sanitizers {
223 // This variable is used by the sanitizer runtime crates, e.g.
224 // rustc_lsan, to build the sanitizer runtime from C code
225 // When this variable is missing, those crates won't compile the C code,
226 // so we don't set this variable during stage0 where llvm-config is
228 // We also only build the runtimes when --enable-sanitizers (or its
229 // config.toml equivalent) is used
230 cargo.env("LLVM_CONFIG", build.llvm_config(target));
233 cargo.arg("--features").arg(features)
234 .arg("--manifest-path")
235 .arg(build.src.join("src/libstd/Cargo.toml"));
237 if let Some(target) = build.config.target_config.get(&target) {
238 if let Some(ref jemalloc) = target.jemalloc {
239 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
242 if target.contains("musl") {
243 if let Some(p) = build.musl_root(target) {
244 cargo.env("MUSL_ROOT", p);
250 &libstd_stamp(build, compiler, target));
252 builder.ensure(StdLink {
253 compiler: builder.compiler(compiler.stage, build.build),
254 target_compiler: compiler,
264 // "build-crate-std",
265 // compile::std_link)
266 // .dep(|s| s.name("startup-objects"))
267 // .dep(|s| s.name("create-sysroot").target(s.host));
269 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
271 pub compiler: Compiler,
272 pub target_compiler: Compiler,
273 pub target: Interned<String>,
276 impl Step for StdLink {
279 /// Link all libstd rlibs/dylibs into the sysroot location.
281 /// Links those artifacts generated by `compiler` to a the `stage` compiler's
282 /// sysroot for the specified `host` and `target`.
284 /// Note that this assumes that `compiler` has already generated the libstd
285 /// libraries for `target`, and this method will find them in the relevant
286 /// output directory.
287 fn run(self, builder: &Builder) {
288 let build = builder.build;
289 let compiler = self.compiler;
290 let target_compiler = self.target_compiler;
291 let target = self.target;
292 println!("Copying stage{} std from stage{} ({} -> {} / {})",
293 target_compiler.stage,
296 target_compiler.host,
298 let libdir = builder.sysroot_libdir(target_compiler, target);
299 add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
301 if target.contains("musl") && !target.contains("mips") {
302 copy_musl_third_party_objects(build, target, &libdir);
305 if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
306 // The sanitizers are only built in stage1 or above, so the dylibs will
307 // be missing in stage0 and causes panic. See the `std()` function above
308 // for reason why the sanitizers are not built in stage0.
309 copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
314 /// Copies the crt(1,i,n).o startup objects
316 /// Only required for musl targets that statically link to libc
317 fn copy_musl_third_party_objects(build: &Build, target: Interned<String>, into: &Path) {
318 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
319 copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
323 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
324 for &sanitizer in &["asan", "tsan"] {
325 let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
326 let mut src_path = native_dir.join(sanitizer);
327 src_path.push("build");
328 src_path.push("lib");
329 src_path.push("darwin");
330 src_path.push(&filename);
331 copy(&src_path, &into.join(filename));
335 // rules.build("startup-objects", "src/rtstartup")
336 // .dep(|s| s.name("create-sysroot").target(s.host))
337 // .run(move |s| compile::build_startup_objects(build, &s.compiler(), s.target));
339 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
340 pub struct StartupObjects {
341 pub compiler: Compiler,
342 pub target: Interned<String>,
345 impl Step for StartupObjects {
348 fn should_run(_builder: &Builder, path: &Path) -> bool {
349 path.ends_with("src/rtstartup")
354 _path: Option<&Path>,
355 host: Interned<String>,
356 target: Interned<String>,
358 builder.ensure(StartupObjects {
359 compiler: builder.compiler(builder.top_stage, host),
364 /// Build and prepare startup objects like rsbegin.o and rsend.o
366 /// These are primarily used on Windows right now for linking executables/dlls.
367 /// They don't require any library support as they're just plain old object
368 /// files, so we just use the nightly snapshot compiler to always build them (as
369 /// no other compilers are guaranteed to be available).
370 fn run(self, builder: &Builder) {
371 let build = builder.build;
372 let for_compiler = self.compiler;
373 let target = self.target;
374 if !target.contains("pc-windows-gnu") {
378 let src_dir = &build.src.join("src/rtstartup");
379 let dst_dir = &build.native_dir(target).join("rtstartup");
380 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
381 t!(fs::create_dir_all(dst_dir));
383 for file in &["rsbegin", "rsend"] {
384 let src_file = &src_dir.join(file.to_string() + ".rs");
385 let dst_file = &dst_dir.join(file.to_string() + ".o");
386 if !up_to_date(src_file, dst_file) {
387 let mut cmd = Command::new(&build.initial_rustc);
388 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
389 .arg("--cfg").arg("stage0")
390 .arg("--target").arg(target)
392 .arg("--o").arg(dst_file)
396 copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
399 for obj in ["crt2.o", "dllcrt2.o"].iter() {
400 copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
405 // for (krate, path, _default) in krates("test") {
406 // rules.build(&krate.build_step, path)
407 // .dep(|s| s.name("libstd-link"))
408 // .run(move |s| compile::test(build, s.target, &s.compiler()));
410 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
412 pub compiler: Compiler,
413 pub target: Interned<String>,
418 const DEFAULT: bool = true;
420 fn should_run(builder: &Builder, path: &Path) -> bool {
421 path.ends_with("src/libtest") ||
422 builder.crates("test").into_iter().any(|(_, krate_path)| {
423 path.ends_with(krate_path)
429 _path: Option<&Path>,
430 host: Interned<String>,
431 target: Interned<String>,
433 builder.ensure(Test {
434 compiler: builder.compiler(builder.top_stage, host),
441 /// This will build libtest and supporting libraries for a particular stage of
442 /// the build using the `compiler` targeting the `target` architecture. The
443 /// artifacts created will also be linked into the sysroot directory.
444 fn run(self, builder: &Builder) {
445 let build = builder.build;
446 let target = self.target;
447 let compiler = self.compiler;
449 builder.ensure(Std { compiler, target });
451 if build.force_use_stage1(compiler, target) {
452 builder.ensure(Test {
453 compiler: builder.compiler(1, build.build),
456 println!("Uplifting stage1 test ({} -> {})", &build.build, target);
457 builder.ensure(TestLink {
458 compiler: builder.compiler(1, build.build),
459 target_compiler: compiler,
465 let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
466 println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
467 &compiler.host, target);
468 let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
469 build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
470 let mut cargo = builder.cargo(compiler, Mode::Libtest, target, "build");
471 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
472 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
474 cargo.arg("--manifest-path")
475 .arg(build.src.join("src/libtest/Cargo.toml"));
478 &libtest_stamp(build, compiler, target));
480 builder.ensure(TestLink {
481 compiler: builder.compiler(compiler.stage, build.build),
482 target_compiler: compiler,
492 // "build-crate-test",
493 // compile::test_link)
494 // .dep(|s| s.name("libstd-link"));
496 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
497 pub struct TestLink {
498 pub compiler: Compiler,
499 pub target_compiler: Compiler,
500 pub target: Interned<String>,
503 impl Step for TestLink {
506 /// Same as `std_link`, only for libtest
507 fn run(self, builder: &Builder) {
508 let build = builder.build;
509 let compiler = self.compiler;
510 let target_compiler = self.target_compiler;
511 let target = self.target;
512 println!("Copying stage{} test from stage{} ({} -> {} / {})",
513 target_compiler.stage,
516 target_compiler.host,
518 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
519 &libtest_stamp(build, compiler, target));
523 // for (krate, path, _default) in krates("rustc-main") {
524 // rules.build(&krate.build_step, path)
525 // .dep(|s| s.name("libtest-link"))
526 // .dep(move |s| s.name("llvm").host(&build.build).stage(0))
527 // .dep(|s| s.name("may-run-build-script"))
528 // .run(move |s| compile::rustc(build, s.target, &s.compiler()));
531 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
533 pub compiler: Compiler,
534 pub target: Interned<String>,
537 impl Step for Rustc {
539 const ONLY_HOSTS: bool = true;
540 const DEFAULT: bool = true;
542 fn should_run(builder: &Builder, path: &Path) -> bool {
543 path.ends_with("src/librustc") ||
544 builder.crates("rustc-main").into_iter().any(|(_, krate_path)| {
545 path.ends_with(krate_path)
551 _path: Option<&Path>,
552 host: Interned<String>,
553 target: Interned<String>,
555 builder.ensure(Rustc {
556 compiler: builder.compiler(builder.top_stage, host),
561 /// Build the compiler.
563 /// This will build the compiler for a particular stage of the build using
564 /// the `compiler` targeting the `target` architecture. The artifacts
565 /// created will also be linked into the sysroot directory.
566 fn run(self, builder: &Builder) {
567 let build = builder.build;
568 let compiler = self.compiler;
569 let target = self.target;
571 builder.ensure(Test { compiler, target });
573 // Build LLVM for our target. This will implicitly build the host LLVM
575 builder.ensure(native::Llvm { target });
577 if build.force_use_stage1(compiler, target) {
578 builder.ensure(Rustc {
579 compiler: builder.compiler(1, build.build),
582 println!("Uplifting stage1 rustc ({} -> {})", &build.build, target);
583 builder.ensure(RustcLink {
584 compiler: builder.compiler(1, build.build),
585 target_compiler: compiler,
591 // Ensure that build scripts have a std to link against.
593 compiler: builder.compiler(self.compiler.stage, build.build),
597 let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
598 println!("Building stage{} compiler artifacts ({} -> {})",
599 compiler.stage, &compiler.host, target);
601 let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
602 build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
604 let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
605 cargo.arg("--features").arg(build.rustc_features())
606 .arg("--manifest-path")
607 .arg(build.src.join("src/rustc/Cargo.toml"));
609 // Set some configuration variables picked up by build scripts and
610 // the compiler alike
611 cargo.env("CFG_RELEASE", build.rust_release())
612 .env("CFG_RELEASE_CHANNEL", &build.config.channel)
613 .env("CFG_VERSION", build.rust_version())
614 .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default());
616 if compiler.stage == 0 {
617 cargo.env("CFG_LIBDIR_RELATIVE", "lib");
619 let libdir_relative =
620 build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
621 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
624 // If we're not building a compiler with debugging information then remove
625 // these two env vars which would be set otherwise.
626 if build.config.rust_debuginfo_only_std {
627 cargo.env_remove("RUSTC_DEBUGINFO");
628 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
631 if let Some(ref ver_date) = build.rust_info.commit_date() {
632 cargo.env("CFG_VER_DATE", ver_date);
634 if let Some(ref ver_hash) = build.rust_info.sha() {
635 cargo.env("CFG_VER_HASH", ver_hash);
637 if !build.unstable_features() {
638 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
640 // Flag that rust llvm is in use
641 if build.is_rust_llvm(target) {
642 cargo.env("LLVM_RUSTLLVM", "1");
644 cargo.env("LLVM_CONFIG", build.llvm_config(target));
645 let target_config = build.config.target_config.get(&target);
646 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
647 cargo.env("CFG_LLVM_ROOT", s);
649 // Building with a static libstdc++ is only supported on linux right now,
650 // not for MSVC or macOS
651 if build.config.llvm_static_stdcpp &&
652 !target.contains("windows") &&
653 !target.contains("apple") {
654 cargo.env("LLVM_STATIC_STDCPP",
655 compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
657 if build.config.llvm_link_shared {
658 cargo.env("LLVM_LINK_SHARED", "1");
660 if let Some(ref s) = build.config.rustc_default_linker {
661 cargo.env("CFG_DEFAULT_LINKER", s);
663 if let Some(ref s) = build.config.rustc_default_ar {
664 cargo.env("CFG_DEFAULT_AR", s);
668 &librustc_stamp(build, compiler, target));
670 builder.ensure(RustcLink {
671 compiler: builder.compiler(compiler.stage, build.build),
672 target_compiler: compiler,
681 // "build-crate-rustc-main",
682 // compile::rustc_link)
683 // .dep(|s| s.name("libtest-link"));
684 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
686 pub compiler: Compiler,
687 pub target_compiler: Compiler,
688 pub target: Interned<String>,
691 impl Step for RustcLink {
694 /// Same as `std_link`, only for librustc
695 fn run(self, builder: &Builder) {
696 let build = builder.build;
697 let compiler = self.compiler;
698 let target_compiler = self.target_compiler;
699 let target = self.target;
700 println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
701 target_compiler.stage,
704 target_compiler.host,
706 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
707 &librustc_stamp(build, compiler, target));
711 /// Cargo's output path for the standard library in a given stage, compiled
712 /// by a particular compiler for the specified target.
713 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
714 build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
717 /// Cargo's output path for libtest in a given stage, compiled by a particular
718 /// compiler for the specified target.
719 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
720 build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
723 /// Cargo's output path for librustc in a given stage, compiled by a particular
724 /// compiler for the specified target.
725 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
726 build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
729 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
730 let out = output(Command::new(compiler)
731 .arg(format!("-print-file-name={}", file)));
732 PathBuf::from(out.trim())
735 // rules.build("create-sysroot", "path/to/nowhere")
736 // .run(move |s| compile::create_sysroot(build, &s.compiler()));
738 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
740 pub compiler: Compiler,
743 impl Step for Sysroot {
744 type Output = Interned<PathBuf>;
746 /// Returns the sysroot for the `compiler` specified that *this build system
749 /// That is, the sysroot for the stage0 compiler is not what the compiler
750 /// thinks it is by default, but it's the same as the default for stages
752 fn run(self, builder: &Builder) -> Interned<PathBuf> {
753 let build = builder.build;
754 let compiler = self.compiler;
755 let sysroot = if compiler.stage == 0 {
756 build.out.join(&compiler.host).join("stage0-sysroot")
758 build.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
760 let _ = fs::remove_dir_all(&sysroot);
761 t!(fs::create_dir_all(&sysroot));
762 INTERNER.intern_path(sysroot)
766 // the compiler with no target libraries ready to go
767 // rules.build("rustc", "src/rustc")
768 // .dep(|s| s.name("create-sysroot").target(s.host))
773 // s.name("librustc")
774 // .host(&build.build)
775 // .stage(s.stage - 1)
778 // .run(move |s| compile::assemble_rustc(build, s.stage, s.target));
780 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
781 pub struct Assemble {
782 /// The compiler which we will produce in this step. Assemble itself will
783 /// take care of ensuring that the necessary prerequisites to do so exist,
784 /// that is, this target can be a stage2 compiler and Assemble will build
785 /// previous stages for you.
786 pub target_compiler: Compiler,
789 impl Step for Assemble {
790 type Output = Compiler;
792 /// Prepare a new compiler from the artifacts in `stage`
794 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
795 /// must have been previously produced by the `stage - 1` build.build
797 fn run(self, builder: &Builder) -> Compiler {
798 let build = builder.build;
799 let target_compiler = self.target_compiler;
801 if target_compiler.stage == 0 {
802 assert_eq!(build.build, target_compiler.host,
803 "Cannot obtain compiler for non-native build triple at stage 0");
804 // The stage 0 compiler for the build triple is always pre-built.
805 return target_compiler;
808 // Get the compiler that we'll use to bootstrap ourselves.
809 let build_compiler = if target_compiler.host != build.build {
810 // Build a compiler for the host platform. We cannot use the stage0
811 // compiler for the host platform for this because it doesn't have
812 // the libraries we need. FIXME: Perhaps we should download those
813 // libraries? It would make builds faster...
814 // FIXME: It may be faster if we build just a stage 1
815 // compiler and then use that to bootstrap this compiler
817 builder.compiler(target_compiler.stage - 1, build.build)
819 // Build the compiler we'll use to build the stage requested. This
820 // may build more than one compiler (going down to stage 0).
821 builder.compiler(target_compiler.stage - 1, target_compiler.host)
824 // Build the libraries for this compiler to link to (i.e., the libraries
825 // it uses at runtime). NOTE: Crates the target compiler compiles don't
826 // link to these. (FIXME: Is that correct? It seems to be correct most
827 // of the time but I think we do link to these for stage2/bin compilers
828 // when not performing a full bootstrap).
829 builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
831 let stage = target_compiler.stage;
832 let host = target_compiler.host;
833 println!("Assembling stage{} compiler ({})", stage, host);
835 // Link in all dylibs to the libdir
836 let sysroot = builder.sysroot(target_compiler);
837 let sysroot_libdir = sysroot.join(libdir(&*host));
838 t!(fs::create_dir_all(&sysroot_libdir));
839 let src_libdir = builder.sysroot_libdir(build_compiler, host);
840 for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
841 let filename = f.file_name().into_string().unwrap();
842 if is_dylib(&filename) {
843 copy(&f.path(), &sysroot_libdir.join(&filename));
847 let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
849 // Link the compiler binary itself into place
850 let rustc = out_dir.join(exe("rustc", &*host));
851 let bindir = sysroot.join("bin");
852 t!(fs::create_dir_all(&bindir));
853 let compiler = builder.rustc(target_compiler);
854 let _ = fs::remove_file(&compiler);
855 copy(&rustc, &compiler);
857 // See if rustdoc exists to link it into place
858 let rustdoc = exe("rustdoc", &*host);
859 let rustdoc_src = out_dir.join(&rustdoc);
860 let rustdoc_dst = bindir.join(&rustdoc);
861 if fs::metadata(&rustdoc_src).is_ok() {
862 let _ = fs::remove_file(&rustdoc_dst);
863 copy(&rustdoc_src, &rustdoc_dst);
870 /// Link some files into a rustc sysroot.
872 /// For a particular stage this will link the file listed in `stamp` into the
873 /// `sysroot_dst` provided.
874 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
875 t!(fs::create_dir_all(&sysroot_dst));
876 let mut contents = Vec::new();
877 t!(t!(File::open(stamp)).read_to_end(&mut contents));
878 // This is the method we use for extracting paths from the stamp file passed to us. See
879 // run_cargo for more information (in this file).
880 for part in contents.split(|b| *b == 0) {
884 let path = Path::new(t!(str::from_utf8(part)));
885 copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
889 // Avoiding a dependency on winapi to keep compile times down
891 fn stderr_isatty() -> bool {
893 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
896 fn stderr_isatty() -> bool {
899 type HANDLE = *mut u8;
900 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
902 fn GetStdHandle(which: DWORD) -> HANDLE;
903 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
906 let handle = GetStdHandle(STD_ERROR_HANDLE);
908 GetConsoleMode(handle, &mut out) != 0
912 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
913 // Instruct Cargo to give us json messages on stdout, critically leaving
914 // stderr as piped so we can get those pretty colors.
915 cargo.arg("--message-format").arg("json")
916 .stdout(Stdio::piped());
919 // since we pass message-format=json to cargo, we need to tell the rustc
920 // wrapper to give us colored output if necessary. This is because we
921 // only want Cargo's JSON output, not rustcs.
922 cargo.env("RUSTC_COLOR", "1");
925 build.verbose(&format!("running: {:?}", cargo));
926 let mut child = match cargo.spawn() {
928 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
931 // `target_root_dir` looks like $dir/$target/release
932 let target_root_dir = stamp.parent().unwrap();
933 // `target_deps_dir` looks like $dir/$target/release/deps
934 let target_deps_dir = target_root_dir.join("deps");
935 // `host_root_dir` looks like $dir/release
936 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
937 .parent().unwrap() // chop off `$target`
938 .join(target_root_dir.file_name().unwrap());
940 // Spawn Cargo slurping up its JSON output. We'll start building up the
941 // `deps` array of all files it generated along with a `toplevel` array of
942 // files we need to probe for later.
943 let mut deps = Vec::new();
944 let mut toplevel = Vec::new();
945 let stdout = BufReader::new(child.stdout.take().unwrap());
946 for line in stdout.lines() {
948 let json: serde_json::Value = if line.starts_with("{") {
949 t!(serde_json::from_str(&line))
951 // If this was informational, just print it out and continue
952 println!("{}", line);
955 if json["reason"].as_str() != Some("compiler-artifact") {
958 for filename in json["filenames"].as_array().unwrap() {
959 let filename = filename.as_str().unwrap();
960 // Skip files like executables
961 if !filename.ends_with(".rlib") &&
962 !filename.ends_with(".lib") &&
963 !is_dylib(&filename) {
967 let filename = Path::new(filename);
969 // If this was an output file in the "host dir" we don't actually
970 // worry about it, it's not relevant for us.
971 if filename.starts_with(&host_root_dir) {
975 // If this was output in the `deps` dir then this is a precise file
976 // name (hash included) so we start tracking it.
977 if filename.starts_with(&target_deps_dir) {
978 deps.push(filename.to_path_buf());
982 // Otherwise this was a "top level artifact" which right now doesn't
983 // have a hash in the name, but there's a version of this file in
984 // the `deps` folder which *does* have a hash in the name. That's
985 // the one we'll want to we'll probe for it later.
986 toplevel.push((filename.file_stem().unwrap()
987 .to_str().unwrap().to_string(),
988 filename.extension().unwrap().to_owned()
989 .to_str().unwrap().to_string()));
993 // Make sure Cargo actually succeeded after we read all of its stdout.
994 let status = t!(child.wait());
995 if !status.success() {
996 panic!("command did not execute successfully: {:?}\n\
997 expected success, got: {}",
1002 // Ok now we need to actually find all the files listed in `toplevel`. We've
1003 // got a list of prefix/extensions and we basically just need to find the
1004 // most recent file in the `deps` folder corresponding to each one.
1005 let contents = t!(target_deps_dir.read_dir())
1007 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1008 .collect::<Vec<_>>();
1009 for (prefix, extension) in toplevel {
1010 let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
1011 filename.starts_with(&prefix[..]) &&
1012 filename[prefix.len()..].starts_with("-") &&
1013 filename.ends_with(&extension[..])
1015 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1016 FileTime::from_last_modification_time(metadata)
1018 let path_to_add = match max {
1019 Some(triple) => triple.0.to_str().unwrap(),
1020 None => panic!("no output generated for {:?} {:?}", prefix, extension),
1022 if is_dylib(path_to_add) {
1023 let candidate = format!("{}.lib", path_to_add);
1024 let candidate = PathBuf::from(candidate);
1025 if candidate.exists() {
1026 deps.push(candidate);
1029 deps.push(path_to_add.into());
1032 // Now we want to update the contents of the stamp file, if necessary. First
1033 // we read off the previous contents along with its mtime. If our new
1034 // contents (the list of files to copy) is different or if any dep's mtime
1035 // is newer then we rewrite the stamp file.
1037 let mut stamp_contents = Vec::new();
1038 if let Ok(mut f) = File::open(stamp) {
1039 t!(f.read_to_end(&mut stamp_contents));
1041 let stamp_mtime = mtime(&stamp);
1042 let mut new_contents = Vec::new();
1044 let mut max_path = None;
1046 let mtime = mtime(&dep);
1047 if Some(mtime) > max {
1049 max_path = Some(dep.clone());
1051 new_contents.extend(dep.to_str().unwrap().as_bytes());
1052 new_contents.extend(b"\0");
1054 let max = max.unwrap();
1055 let max_path = max_path.unwrap();
1056 if stamp_contents == new_contents && max <= stamp_mtime {
1059 if max > stamp_mtime {
1060 build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1062 build.verbose(&format!("updating {:?} as deps changed", stamp));
1064 t!(t!(File::create(stamp)).write_all(&new_contents));