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 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, &builder.rustc(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 = builder.rustc(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 = builder.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(compiler.stage, &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 = builder.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 =
602 build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
603 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
606 // If we're not building a compiler with debugging information then remove
607 // these two env vars which would be set otherwise.
608 if build.config.rust_debuginfo_only_std {
609 cargo.env_remove("RUSTC_DEBUGINFO");
610 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
613 if let Some(ref ver_date) = build.rust_info.commit_date() {
614 cargo.env("CFG_VER_DATE", ver_date);
616 if let Some(ref ver_hash) = build.rust_info.sha() {
617 cargo.env("CFG_VER_HASH", ver_hash);
619 if !build.unstable_features() {
620 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
622 // Flag that rust llvm is in use
623 if build.is_rust_llvm(target) {
624 cargo.env("LLVM_RUSTLLVM", "1");
626 cargo.env("LLVM_CONFIG", build.llvm_config(target));
627 let target_config = build.config.target_config.get(target);
628 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
629 cargo.env("CFG_LLVM_ROOT", s);
631 // Building with a static libstdc++ is only supported on linux right now,
632 // not for MSVC or macOS
633 if build.config.llvm_static_stdcpp &&
634 !target.contains("windows") &&
635 !target.contains("apple") {
636 cargo.env("LLVM_STATIC_STDCPP",
637 compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
639 if build.config.llvm_link_shared {
640 cargo.env("LLVM_LINK_SHARED", "1");
642 if let Some(ref s) = build.config.rustc_default_linker {
643 cargo.env("CFG_DEFAULT_LINKER", s);
645 if let Some(ref s) = build.config.rustc_default_ar {
646 cargo.env("CFG_DEFAULT_AR", s);
650 &librustc_stamp(build, compiler, target));
652 builder.ensure(RustcLink {
653 compiler: builder.compiler(compiler.stage, &build.build),
654 target_compiler: compiler,
663 // "build-crate-rustc-main",
664 // compile::rustc_link)
665 // .dep(|s| s.name("libtest-link"));
667 struct RustcLink<'a> {
668 pub compiler: Compiler<'a>,
669 pub target_compiler: Compiler<'a>,
673 impl<'a> Step<'a> for RustcLink<'a> {
676 /// Same as `std_link`, only for librustc
677 fn run(self, builder: &Builder) {
678 let build = builder.build;
679 let compiler = self.compiler;
680 let target_compiler = self.target_compiler;
681 let target = self.target;
682 println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
683 target_compiler.stage,
686 target_compiler.host,
688 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
689 &librustc_stamp(build, compiler, target));
693 /// Cargo's output path for the standard library in a given stage, compiled
694 /// by a particular compiler for the specified target.
695 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
696 build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
699 /// Cargo's output path for libtest in a given stage, compiled by a particular
700 /// compiler for the specified target.
701 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
702 build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
705 /// Cargo's output path for librustc in a given stage, compiled by a particular
706 /// compiler for the specified target.
707 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
708 build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
711 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
712 let out = output(Command::new(compiler)
713 .arg(format!("-print-file-name={}", file)));
714 PathBuf::from(out.trim())
717 // rules.build("create-sysroot", "path/to/nowhere")
718 // .run(move |s| compile::create_sysroot(build, &s.compiler()));
721 pub struct Sysroot<'a> {
722 pub compiler: Compiler<'a>,
725 impl<'a> Step<'a> for Sysroot<'a> {
726 type Output = PathBuf;
728 /// Returns the sysroot for the `compiler` specified that *this build system
731 /// That is, the sysroot for the stage0 compiler is not what the compiler
732 /// thinks it is by default, but it's the same as the default for stages
734 fn run(self, builder: &Builder) -> PathBuf {
735 let build = builder.build;
736 let compiler = self.compiler;
737 let sysroot = if compiler.stage == 0 {
738 build.out.join(compiler.host).join("stage0-sysroot")
740 build.out.join(compiler.host).join(format!("stage{}", compiler.stage))
742 let _ = fs::remove_dir_all(&sysroot);
743 t!(fs::create_dir_all(&sysroot));
748 // the compiler with no target libraries ready to go
749 // rules.build("rustc", "src/rustc")
750 // .dep(|s| s.name("create-sysroot").target(s.host))
755 // s.name("librustc")
756 // .host(&build.build)
757 // .stage(s.stage - 1)
760 // .run(move |s| compile::assemble_rustc(build, s.stage, s.target));
763 pub struct Assemble<'a> {
764 /// The compiler which we will produce in this step. Assemble itself will
765 /// take care of ensuring that the necessary prerequisites to do so exist,
766 /// that is, this target can be a stage2 compiler and Assemble will build
767 /// previous stages for you.
768 pub target_compiler: Compiler<'a>,
771 impl<'a> Step<'a> for Assemble<'a> {
772 type Output = Compiler<'a>;
774 /// Prepare a new compiler from the artifacts in `stage`
776 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
777 /// must have been previously produced by the `stage - 1` build.build
779 fn run(self, builder: &Builder) -> Compiler<'a> {
780 let build = builder.build;
781 let target_compiler = self.target_compiler;
783 if target_compiler.stage == 0 {
784 assert_eq!(build.build, target_compiler.host,
785 "Cannot obtain compiler for non-native build triple at stage 0");
786 // The stage 0 compiler for the build triple is always pre-built.
787 return target_compiler;
790 // Get the compiler that we'll use to bootstrap ourselves.
791 let build_compiler = if target_compiler.host != build.build {
792 // Build a compiler for the host platform. We cannot use the stage0
793 // compiler for the host platform for this because it doesn't have
794 // the libraries we need. FIXME: Perhaps we should download those
795 // libraries? It would make builds faster...
796 builder.ensure(Assemble {
797 target_compiler: Compiler {
798 // FIXME: It may be faster if we build just a stage 1
799 // compiler and then use that to bootstrap this compiler
801 stage: target_compiler.stage - 1,
806 // Build the compiler we'll use to build the stage requested. This
807 // may build more than one compiler (going down to stage 0).
808 builder.ensure(Assemble {
809 target_compiler: target_compiler.with_stage(target_compiler.stage - 1),
813 // Build the libraries for this compiler to link to (i.e., the libraries
814 // it uses at runtime). NOTE: Crates the target compiler compiles don't
815 // link to these. (FIXME: Is that correct? It seems to be correct most
816 // of the time but I think we do link to these for stage2/bin compilers
817 // when not performing a full bootstrap).
818 builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
820 let stage = target_compiler.stage;
821 let host = target_compiler.host;
822 println!("Assembling stage{} compiler ({})", stage, host);
824 // Link in all dylibs to the libdir
825 let sysroot = builder.sysroot(target_compiler);
826 let sysroot_libdir = sysroot.join(libdir(host));
827 t!(fs::create_dir_all(&sysroot_libdir));
828 let src_libdir = builder.sysroot_libdir(build_compiler, host);
829 for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
830 let filename = f.file_name().into_string().unwrap();
831 if is_dylib(&filename) {
832 copy(&f.path(), &sysroot_libdir.join(&filename));
836 let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
838 // Link the compiler binary itself into place
839 let rustc = out_dir.join(exe("rustc", host));
840 let bindir = sysroot.join("bin");
841 t!(fs::create_dir_all(&bindir));
842 let compiler = builder.rustc(target_compiler);
843 let _ = fs::remove_file(&compiler);
844 copy(&rustc, &compiler);
846 // See if rustdoc exists to link it into place
847 let rustdoc = exe("rustdoc", host);
848 let rustdoc_src = out_dir.join(&rustdoc);
849 let rustdoc_dst = bindir.join(&rustdoc);
850 if fs::metadata(&rustdoc_src).is_ok() {
851 let _ = fs::remove_file(&rustdoc_dst);
852 copy(&rustdoc_src, &rustdoc_dst);
859 /// Link some files into a rustc sysroot.
861 /// For a particular stage this will link the file listed in `stamp` into the
862 /// `sysroot_dst` provided.
863 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
864 t!(fs::create_dir_all(&sysroot_dst));
865 let mut contents = Vec::new();
866 t!(t!(File::open(stamp)).read_to_end(&mut contents));
867 // This is the method we use for extracting paths from the stamp file passed to us. See
868 // run_cargo for more information (in this file).
869 for part in contents.split(|b| *b == 0) {
873 let path = Path::new(t!(str::from_utf8(part)));
874 copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
878 // Avoiding a dependency on winapi to keep compile times down
880 fn stderr_isatty() -> bool {
882 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
885 fn stderr_isatty() -> bool {
888 type HANDLE = *mut u8;
889 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
891 fn GetStdHandle(which: DWORD) -> HANDLE;
892 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
895 let handle = GetStdHandle(STD_ERROR_HANDLE);
897 GetConsoleMode(handle, &mut out) != 0
901 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
902 // Instruct Cargo to give us json messages on stdout, critically leaving
903 // stderr as piped so we can get those pretty colors.
904 cargo.arg("--message-format").arg("json")
905 .stdout(Stdio::piped());
908 // since we pass message-format=json to cargo, we need to tell the rustc
909 // wrapper to give us colored output if necessary. This is because we
910 // only want Cargo's JSON output, not rustcs.
911 cargo.env("RUSTC_COLOR", "1");
914 build.verbose(&format!("running: {:?}", cargo));
915 let mut child = match cargo.spawn() {
917 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
920 // `target_root_dir` looks like $dir/$target/release
921 let target_root_dir = stamp.parent().unwrap();
922 // `target_deps_dir` looks like $dir/$target/release/deps
923 let target_deps_dir = target_root_dir.join("deps");
924 // `host_root_dir` looks like $dir/release
925 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
926 .parent().unwrap() // chop off `$target`
927 .join(target_root_dir.file_name().unwrap());
929 // Spawn Cargo slurping up its JSON output. We'll start building up the
930 // `deps` array of all files it generated along with a `toplevel` array of
931 // files we need to probe for later.
932 let mut deps = Vec::new();
933 let mut toplevel = Vec::new();
934 let stdout = BufReader::new(child.stdout.take().unwrap());
935 for line in stdout.lines() {
937 let json: serde_json::Value = if line.starts_with("{") {
938 t!(serde_json::from_str(&line))
940 // If this was informational, just print it out and continue
941 println!("{}", line);
944 if json["reason"].as_str() != Some("compiler-artifact") {
947 for filename in json["filenames"].as_array().unwrap() {
948 let filename = filename.as_str().unwrap();
949 // Skip files like executables
950 if !filename.ends_with(".rlib") &&
951 !filename.ends_with(".lib") &&
952 !is_dylib(&filename) {
956 let filename = Path::new(filename);
958 // If this was an output file in the "host dir" we don't actually
959 // worry about it, it's not relevant for us.
960 if filename.starts_with(&host_root_dir) {
964 // If this was output in the `deps` dir then this is a precise file
965 // name (hash included) so we start tracking it.
966 if filename.starts_with(&target_deps_dir) {
967 deps.push(filename.to_path_buf());
971 // Otherwise this was a "top level artifact" which right now doesn't
972 // have a hash in the name, but there's a version of this file in
973 // the `deps` folder which *does* have a hash in the name. That's
974 // the one we'll want to we'll probe for it later.
975 toplevel.push((filename.file_stem().unwrap()
976 .to_str().unwrap().to_string(),
977 filename.extension().unwrap().to_owned()
978 .to_str().unwrap().to_string()));
982 // Make sure Cargo actually succeeded after we read all of its stdout.
983 let status = t!(child.wait());
984 if !status.success() {
985 panic!("command did not execute successfully: {:?}\n\
986 expected success, got: {}",
991 // Ok now we need to actually find all the files listed in `toplevel`. We've
992 // got a list of prefix/extensions and we basically just need to find the
993 // most recent file in the `deps` folder corresponding to each one.
994 let contents = t!(target_deps_dir.read_dir())
996 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
997 .collect::<Vec<_>>();
998 for (prefix, extension) in toplevel {
999 let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
1000 filename.starts_with(&prefix[..]) &&
1001 filename[prefix.len()..].starts_with("-") &&
1002 filename.ends_with(&extension[..])
1004 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1005 FileTime::from_last_modification_time(metadata)
1007 let path_to_add = match max {
1008 Some(triple) => triple.0.to_str().unwrap(),
1009 None => panic!("no output generated for {:?} {:?}", prefix, extension),
1011 if is_dylib(path_to_add) {
1012 let candidate = format!("{}.lib", path_to_add);
1013 let candidate = PathBuf::from(candidate);
1014 if candidate.exists() {
1015 deps.push(candidate);
1018 deps.push(path_to_add.into());
1021 // Now we want to update the contents of the stamp file, if necessary. First
1022 // we read off the previous contents along with its mtime. If our new
1023 // contents (the list of files to copy) is different or if any dep's mtime
1024 // is newer then we rewrite the stamp file.
1026 let mut stamp_contents = Vec::new();
1027 if let Ok(mut f) = File::open(stamp) {
1028 t!(f.read_to_end(&mut stamp_contents));
1030 let stamp_mtime = mtime(&stamp);
1031 let mut new_contents = Vec::new();
1033 let mut max_path = None;
1035 let mtime = mtime(&dep);
1036 if Some(mtime) > max {
1038 max_path = Some(dep.clone());
1040 new_contents.extend(dep.to_str().unwrap().as_bytes());
1041 new_contents.extend(b"\0");
1043 let max = max.unwrap();
1044 let max_path = max_path.unwrap();
1045 if stamp_contents == new_contents && max <= stamp_mtime {
1048 if max > stamp_mtime {
1049 build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1051 build.verbose(&format!("updating {:?} as deps changed", stamp));
1053 t!(t!(File::create(stamp)).write_all(&new_contents));