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};
28 use build_helper::{output, mtime, up_to_date};
29 use filetime::FileTime;
32 use util::{exe, libdir, is_dylib, copy, read_stamp_file, CiEnv};
33 use {Build, Compiler, Mode};
37 use cache::{INTERNER, Interned};
38 use builder::{Step, RunConfig, ShouldRun, Builder};
40 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
42 pub target: Interned<String>,
43 pub compiler: Compiler,
48 const DEFAULT: bool = true;
50 fn should_run(run: ShouldRun) -> ShouldRun {
54 fn make_run(run: RunConfig) {
55 run.builder.ensure(Std {
56 compiler: run.builder.compiler(run.builder.top_stage, run.host),
61 /// Build the standard library.
63 /// This will build the standard library for a particular stage of the build
64 /// using the `compiler` targeting the `target` architecture. The artifacts
65 /// created will also be linked into the sysroot directory.
66 fn run(self, builder: &Builder) {
67 let build = builder.build;
68 let target = self.target;
69 let compiler = self.compiler;
71 builder.ensure(StartupObjects { compiler, target });
73 if build.force_use_stage1(compiler, target) {
74 let from = builder.compiler(1, build.build);
79 println!("Uplifting stage1 std ({} -> {})", from.host, target);
81 // Even if we're not building std this stage, the new sysroot must
82 // still contain the musl startup objects.
83 if target.contains("musl") {
84 let libdir = builder.sysroot_libdir(compiler, target);
85 copy_musl_third_party_objects(build, target, &libdir);
88 builder.ensure(StdLink {
90 target_compiler: compiler,
96 if target.contains("musl") {
97 let libdir = builder.sysroot_libdir(compiler, target);
98 copy_musl_third_party_objects(build, target, &libdir);
101 let out_dir = build.stage_out(compiler, Mode::Libstd);
102 build.clear_if_dirty(&out_dir, &builder.rustc(compiler));
103 let mut cargo = builder.cargo(compiler, Mode::Libstd, target, "build");
104 std_cargo(builder, &compiler, target, &mut cargo);
106 let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
107 println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
108 &compiler.host, target);
111 &libstd_stamp(build, compiler, target),
114 builder.ensure(StdLink {
115 compiler: builder.compiler(compiler.stage, build.build),
116 target_compiler: compiler,
122 /// Copies the crt(1,i,n).o startup objects
124 /// Since musl supports fully static linking, we can cross link for it even
125 /// with a glibc-targeting toolchain, given we have the appropriate startup
126 /// files. As those shipped with glibc won't work, copy the ones provided by
127 /// musl so we have them on linux-gnu hosts.
128 fn copy_musl_third_party_objects(build: &Build,
129 target: Interned<String>,
131 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
132 copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
136 /// Configure cargo to compile the standard library, adding appropriate env vars
138 pub fn std_cargo(build: &Builder,
140 target: Interned<String>,
141 cargo: &mut Command) {
142 let mut features = build.std_features();
144 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
145 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
148 // When doing a local rebuild we tell cargo that we're stage1 rather than
149 // stage0. This works fine if the local rust and being-built rust have the
150 // same view of what the default allocator is, but fails otherwise. Since
151 // we don't have a way to express an allocator preference yet, work
152 // around the issue in the case of a local rebuild with jemalloc disabled.
153 if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
154 features.push_str(" force_alloc_system");
157 if compiler.stage != 0 && build.config.sanitizers {
158 // This variable is used by the sanitizer runtime crates, e.g.
159 // rustc_lsan, to build the sanitizer runtime from C code
160 // When this variable is missing, those crates won't compile the C code,
161 // so we don't set this variable during stage0 where llvm-config is
163 // We also only build the runtimes when --enable-sanitizers (or its
164 // config.toml equivalent) is used
165 let llvm_config = build.ensure(native::Llvm {
166 target: build.config.build,
169 cargo.env("LLVM_CONFIG", llvm_config);
172 cargo.arg("--features").arg(features)
173 .arg("--manifest-path")
174 .arg(build.src.join("src/libstd/Cargo.toml"));
176 if let Some(target) = build.config.target_config.get(&target) {
177 if let Some(ref jemalloc) = target.jemalloc {
178 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
181 if target.contains("musl") {
182 if let Some(p) = build.musl_root(target) {
183 cargo.env("MUSL_ROOT", p);
188 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
190 pub compiler: Compiler,
191 pub target_compiler: Compiler,
192 pub target: Interned<String>,
195 impl Step for StdLink {
198 fn should_run(run: ShouldRun) -> ShouldRun {
202 /// Link all libstd rlibs/dylibs into the sysroot location.
204 /// Links those artifacts generated by `compiler` to a the `stage` compiler's
205 /// sysroot for the specified `host` and `target`.
207 /// Note that this assumes that `compiler` has already generated the libstd
208 /// libraries for `target`, and this method will find them in the relevant
209 /// output directory.
210 fn run(self, builder: &Builder) {
211 let build = builder.build;
212 let compiler = self.compiler;
213 let target_compiler = self.target_compiler;
214 let target = self.target;
215 println!("Copying stage{} std from stage{} ({} -> {} / {})",
216 target_compiler.stage,
219 target_compiler.host,
221 let libdir = builder.sysroot_libdir(target_compiler, target);
222 add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
224 if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
225 // The sanitizers are only built in stage1 or above, so the dylibs will
226 // be missing in stage0 and causes panic. See the `std()` function above
227 // for reason why the sanitizers are not built in stage0.
228 copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
231 builder.ensure(tool::CleanTools {
232 compiler: target_compiler,
239 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
240 for &sanitizer in &["asan", "tsan"] {
241 let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
242 let mut src_path = native_dir.join(sanitizer);
243 src_path.push("build");
244 src_path.push("lib");
245 src_path.push("darwin");
246 src_path.push(&filename);
247 copy(&src_path, &into.join(filename));
251 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
252 pub struct StartupObjects {
253 pub compiler: Compiler,
254 pub target: Interned<String>,
257 impl Step for StartupObjects {
260 fn should_run(run: ShouldRun) -> ShouldRun {
261 run.path("src/rtstartup")
264 fn make_run(run: RunConfig) {
265 run.builder.ensure(StartupObjects {
266 compiler: run.builder.compiler(run.builder.top_stage, run.host),
271 /// Build and prepare startup objects like rsbegin.o and rsend.o
273 /// These are primarily used on Windows right now for linking executables/dlls.
274 /// They don't require any library support as they're just plain old object
275 /// files, so we just use the nightly snapshot compiler to always build them (as
276 /// no other compilers are guaranteed to be available).
277 fn run(self, builder: &Builder) {
278 let build = builder.build;
279 let for_compiler = self.compiler;
280 let target = self.target;
281 if !target.contains("pc-windows-gnu") {
285 let src_dir = &build.src.join("src/rtstartup");
286 let dst_dir = &build.native_dir(target).join("rtstartup");
287 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
288 t!(fs::create_dir_all(dst_dir));
290 for file in &["rsbegin", "rsend"] {
291 let src_file = &src_dir.join(file.to_string() + ".rs");
292 let dst_file = &dst_dir.join(file.to_string() + ".o");
293 if !up_to_date(src_file, dst_file) {
294 let mut cmd = Command::new(&build.initial_rustc);
295 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
296 .arg("--cfg").arg("stage0")
297 .arg("--target").arg(target)
299 .arg("-o").arg(dst_file)
303 copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
306 for obj in ["crt2.o", "dllcrt2.o"].iter() {
307 let src = compiler_file(build,
311 copy(&src, &sysroot_dir.join(obj));
316 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
318 pub compiler: Compiler,
319 pub target: Interned<String>,
324 const DEFAULT: bool = true;
326 fn should_run(run: ShouldRun) -> ShouldRun {
327 run.all_krates("test")
330 fn make_run(run: RunConfig) {
331 run.builder.ensure(Test {
332 compiler: run.builder.compiler(run.builder.top_stage, run.host),
339 /// This will build libtest and supporting libraries for a particular stage of
340 /// the build using the `compiler` targeting the `target` architecture. The
341 /// artifacts created will also be linked into the sysroot directory.
342 fn run(self, builder: &Builder) {
343 let build = builder.build;
344 let target = self.target;
345 let compiler = self.compiler;
347 builder.ensure(Std { compiler, target });
349 if build.force_use_stage1(compiler, target) {
350 builder.ensure(Test {
351 compiler: builder.compiler(1, build.build),
354 println!("Uplifting stage1 test ({} -> {})", &build.build, target);
355 builder.ensure(TestLink {
356 compiler: builder.compiler(1, build.build),
357 target_compiler: compiler,
363 let out_dir = build.stage_out(compiler, Mode::Libtest);
364 build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
365 let mut cargo = builder.cargo(compiler, Mode::Libtest, target, "build");
366 test_cargo(build, &compiler, target, &mut cargo);
368 let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
369 println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
370 &compiler.host, target);
373 &libtest_stamp(build, compiler, target),
376 builder.ensure(TestLink {
377 compiler: builder.compiler(compiler.stage, build.build),
378 target_compiler: compiler,
384 /// Same as `std_cargo`, but for libtest
385 pub fn test_cargo(build: &Build,
386 _compiler: &Compiler,
387 _target: Interned<String>,
388 cargo: &mut Command) {
389 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
390 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
392 cargo.arg("--manifest-path")
393 .arg(build.src.join("src/libtest/Cargo.toml"));
396 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
397 pub struct TestLink {
398 pub compiler: Compiler,
399 pub target_compiler: Compiler,
400 pub target: Interned<String>,
403 impl Step for TestLink {
406 fn should_run(run: ShouldRun) -> ShouldRun {
410 /// Same as `std_link`, only for libtest
411 fn run(self, builder: &Builder) {
412 let build = builder.build;
413 let compiler = self.compiler;
414 let target_compiler = self.target_compiler;
415 let target = self.target;
416 println!("Copying stage{} test from stage{} ({} -> {} / {})",
417 target_compiler.stage,
420 target_compiler.host,
422 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
423 &libtest_stamp(build, compiler, target));
424 builder.ensure(tool::CleanTools {
425 compiler: target_compiler,
432 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
434 pub compiler: Compiler,
435 pub target: Interned<String>,
438 impl Step for Rustc {
440 const ONLY_HOSTS: bool = true;
441 const DEFAULT: bool = true;
443 fn should_run(run: ShouldRun) -> ShouldRun {
444 run.all_krates("rustc-main")
447 fn make_run(run: RunConfig) {
448 run.builder.ensure(Rustc {
449 compiler: run.builder.compiler(run.builder.top_stage, run.host),
454 /// Build the compiler.
456 /// This will build the compiler for a particular stage of the build using
457 /// the `compiler` targeting the `target` architecture. The artifacts
458 /// created will also be linked into the sysroot directory.
459 fn run(self, builder: &Builder) {
460 let build = builder.build;
461 let compiler = self.compiler;
462 let target = self.target;
464 builder.ensure(Test { compiler, target });
466 if build.force_use_stage1(compiler, target) {
467 builder.ensure(Rustc {
468 compiler: builder.compiler(1, build.build),
471 println!("Uplifting stage1 rustc ({} -> {})", &build.build, target);
472 builder.ensure(RustcLink {
473 compiler: builder.compiler(1, build.build),
474 target_compiler: compiler,
480 // Ensure that build scripts have a std to link against.
482 compiler: builder.compiler(self.compiler.stage, build.build),
486 let stage_out = builder.stage_out(compiler, Mode::Librustc);
487 build.clear_if_dirty(&stage_out, &libstd_stamp(build, compiler, target));
488 build.clear_if_dirty(&stage_out, &libtest_stamp(build, compiler, target));
490 let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
491 rustc_cargo(build, &mut cargo);
493 let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
494 println!("Building stage{} compiler artifacts ({} -> {})",
495 compiler.stage, &compiler.host, target);
498 &librustc_stamp(build, compiler, target),
501 builder.ensure(RustcLink {
502 compiler: builder.compiler(compiler.stage, build.build),
503 target_compiler: compiler,
509 pub fn rustc_cargo(build: &Build, cargo: &mut Command) {
510 cargo.arg("--features").arg(build.rustc_features())
511 .arg("--manifest-path")
512 .arg(build.src.join("src/rustc/Cargo.toml"));
513 rustc_cargo_env(build, cargo);
516 fn rustc_cargo_env(build: &Build, cargo: &mut Command) {
517 // Set some configuration variables picked up by build scripts and
518 // the compiler alike
519 cargo.env("CFG_RELEASE", build.rust_release())
520 .env("CFG_RELEASE_CHANNEL", &build.config.channel)
521 .env("CFG_VERSION", build.rust_version())
522 .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default())
523 .env("CFG_CODEGEN_BACKENDS_DIR", &build.config.rust_codegen_backends_dir);
525 let libdir_relative = build.config.libdir_relative().unwrap_or(Path::new("lib"));
526 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
528 // If we're not building a compiler with debugging information then remove
529 // these two env vars which would be set otherwise.
530 if build.config.rust_debuginfo_only_std {
531 cargo.env_remove("RUSTC_DEBUGINFO");
532 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
535 if let Some(ref ver_date) = build.rust_info.commit_date() {
536 cargo.env("CFG_VER_DATE", ver_date);
538 if let Some(ref ver_hash) = build.rust_info.sha() {
539 cargo.env("CFG_VER_HASH", ver_hash);
541 if !build.unstable_features() {
542 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
544 if let Some(ref s) = build.config.rustc_default_linker {
545 cargo.env("CFG_DEFAULT_LINKER", s);
547 if build.config.rustc_parallel_queries {
548 cargo.env("RUSTC_PARALLEL_QUERIES", "1");
552 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
554 pub compiler: Compiler,
555 pub target_compiler: Compiler,
556 pub target: Interned<String>,
559 impl Step for RustcLink {
562 fn should_run(run: ShouldRun) -> ShouldRun {
566 /// Same as `std_link`, only for librustc
567 fn run(self, builder: &Builder) {
568 let build = builder.build;
569 let compiler = self.compiler;
570 let target_compiler = self.target_compiler;
571 let target = self.target;
572 println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
573 target_compiler.stage,
576 target_compiler.host,
578 add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
579 &librustc_stamp(build, compiler, target));
580 builder.ensure(tool::CleanTools {
581 compiler: target_compiler,
583 mode: Mode::Librustc,
588 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
589 pub struct CodegenBackend {
590 pub compiler: Compiler,
591 pub target: Interned<String>,
592 pub backend: Interned<String>,
595 impl Step for CodegenBackend {
597 const ONLY_HOSTS: bool = true;
598 const DEFAULT: bool = true;
600 fn should_run(run: ShouldRun) -> ShouldRun {
601 run.all_krates("rustc_trans")
604 fn make_run(run: RunConfig) {
605 let backend = run.builder.config.rust_codegen_backends.get(0);
606 let backend = backend.cloned().unwrap_or_else(|| {
607 INTERNER.intern_str("llvm")
609 run.builder.ensure(CodegenBackend {
610 compiler: run.builder.compiler(run.builder.top_stage, run.host),
616 fn run(self, builder: &Builder) {
617 let build = builder.build;
618 let compiler = self.compiler;
619 let target = self.target;
621 builder.ensure(Rustc { compiler, target });
623 if build.force_use_stage1(compiler, target) {
624 builder.ensure(CodegenBackend {
625 compiler: builder.compiler(1, build.build),
627 backend: self.backend,
632 let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
633 let mut features = build.rustc_features().to_string();
634 cargo.arg("--manifest-path")
635 .arg(build.src.join("src/librustc_trans/Cargo.toml"));
636 rustc_cargo_env(build, &mut cargo);
638 match &*self.backend {
639 "llvm" | "emscripten" => {
640 // Build LLVM for our target. This will implicitly build the
641 // host LLVM if necessary.
642 let llvm_config = builder.ensure(native::Llvm {
644 emscripten: self.backend == "emscripten",
647 if self.backend == "emscripten" {
648 features.push_str(" emscripten");
651 println!("Building stage{} codegen artifacts ({} -> {}, {})",
652 compiler.stage, &compiler.host, target, self.backend);
654 // Pass down configuration from the LLVM build into the build of
655 // librustc_llvm and librustc_trans.
656 if build.is_rust_llvm(target) {
657 cargo.env("LLVM_RUSTLLVM", "1");
659 cargo.env("LLVM_CONFIG", &llvm_config);
660 if self.backend != "emscripten" {
661 let target_config = build.config.target_config.get(&target);
662 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
663 cargo.env("CFG_LLVM_ROOT", s);
666 // Building with a static libstdc++ is only supported on linux right now,
667 // not for MSVC or macOS
668 if build.config.llvm_static_stdcpp &&
669 !target.contains("freebsd") &&
670 !target.contains("windows") &&
671 !target.contains("apple") {
672 let file = compiler_file(build,
673 build.cxx(target).unwrap(),
676 cargo.env("LLVM_STATIC_STDCPP", file);
678 if build.config.llvm_link_shared {
679 cargo.env("LLVM_LINK_SHARED", "1");
682 _ => panic!("unknown backend: {}", self.backend),
685 let tmp_stamp = build.cargo_out(compiler, Mode::Librustc, target)
688 let _folder = build.fold_output(|| format!("stage{}-rustc_trans", compiler.stage));
689 let files = run_cargo(build,
690 cargo.arg("--features").arg(features),
693 let mut files = files.into_iter()
695 let filename = f.file_name().unwrap().to_str().unwrap();
696 is_dylib(filename) && filename.contains("rustc_trans-")
698 let codegen_backend = match files.next() {
700 None => panic!("no dylibs built for codegen backend?"),
702 if let Some(f) = files.next() {
703 panic!("codegen backend built two dylibs:\n{}\n{}",
704 codegen_backend.display(),
707 let stamp = codegen_backend_stamp(build, compiler, target, self.backend);
708 let codegen_backend = codegen_backend.to_str().unwrap();
709 t!(t!(File::create(&stamp)).write_all(codegen_backend.as_bytes()));
713 /// Creates the `codegen-backends` folder for a compiler that's about to be
714 /// assembled as a complete compiler.
716 /// This will take the codegen artifacts produced by `compiler` and link them
717 /// into an appropriate location for `target_compiler` to be a functional
719 fn copy_codegen_backends_to_sysroot(builder: &Builder,
721 target_compiler: Compiler) {
722 let build = builder.build;
723 let target = target_compiler.host;
725 // Note that this step is different than all the other `*Link` steps in
726 // that it's not assembling a bunch of libraries but rather is primarily
727 // moving the codegen backend into place. The codegen backend of rustc is
728 // not linked into the main compiler by default but is rather dynamically
729 // selected at runtime for inclusion.
731 // Here we're looking for the output dylib of the `CodegenBackend` step and
732 // we're copying that into the `codegen-backends` folder.
733 let dst = builder.sysroot_codegen_backends(target_compiler);
734 t!(fs::create_dir_all(&dst));
736 for backend in builder.config.rust_codegen_backends.iter() {
737 let stamp = codegen_backend_stamp(build, compiler, target, *backend);
738 let mut dylib = String::new();
739 t!(t!(File::open(&stamp)).read_to_string(&mut dylib));
740 let file = Path::new(&dylib);
741 let filename = file.file_name().unwrap().to_str().unwrap();
742 // change `librustc_trans-xxxxxx.so` to `librustc_trans-llvm.so`
743 let target_filename = {
744 let dash = filename.find("-").unwrap();
745 let dot = filename.find(".").unwrap();
751 copy(&file, &dst.join(target_filename));
755 fn copy_lld_to_sysroot(builder: &Builder,
756 target_compiler: Compiler,
757 lld_install_root: &Path) {
758 let target = target_compiler.host;
760 let dst = builder.sysroot_libdir(target_compiler, target)
764 t!(fs::create_dir_all(&dst));
766 let exe = exe("lld", &target);
767 copy(&lld_install_root.join("bin").join(&exe), &dst.join(&exe));
770 /// Cargo's output path for the standard library in a given stage, compiled
771 /// by a particular compiler for the specified target.
772 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
773 build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
776 /// Cargo's output path for libtest in a given stage, compiled by a particular
777 /// compiler for the specified target.
778 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
779 build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
782 /// Cargo's output path for librustc in a given stage, compiled by a particular
783 /// compiler for the specified target.
784 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
785 build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
788 fn codegen_backend_stamp(build: &Build,
790 target: Interned<String>,
791 backend: Interned<String>) -> PathBuf {
792 build.cargo_out(compiler, Mode::Librustc, target)
793 .join(format!(".librustc_trans-{}.stamp", backend))
796 fn compiler_file(build: &Build,
798 target: Interned<String>,
799 file: &str) -> PathBuf {
800 let mut cmd = Command::new(compiler);
801 cmd.args(build.cflags(target));
802 cmd.arg(format!("-print-file-name={}", file));
803 let out = output(&mut cmd);
804 PathBuf::from(out.trim())
807 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
809 pub compiler: Compiler,
812 impl Step for Sysroot {
813 type Output = Interned<PathBuf>;
815 fn should_run(run: ShouldRun) -> ShouldRun {
819 /// Returns the sysroot for the `compiler` specified that *this build system
822 /// That is, the sysroot for the stage0 compiler is not what the compiler
823 /// thinks it is by default, but it's the same as the default for stages
825 fn run(self, builder: &Builder) -> Interned<PathBuf> {
826 let build = builder.build;
827 let compiler = self.compiler;
828 let sysroot = if compiler.stage == 0 {
829 build.out.join(&compiler.host).join("stage0-sysroot")
831 build.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
833 let _ = fs::remove_dir_all(&sysroot);
834 t!(fs::create_dir_all(&sysroot));
835 INTERNER.intern_path(sysroot)
839 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
840 pub struct Assemble {
841 /// The compiler which we will produce in this step. Assemble itself will
842 /// take care of ensuring that the necessary prerequisites to do so exist,
843 /// that is, this target can be a stage2 compiler and Assemble will build
844 /// previous stages for you.
845 pub target_compiler: Compiler,
848 impl Step for Assemble {
849 type Output = Compiler;
851 fn should_run(run: ShouldRun) -> ShouldRun {
852 run.all_krates("rustc-main")
855 /// Prepare a new compiler from the artifacts in `stage`
857 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
858 /// must have been previously produced by the `stage - 1` build.build
860 fn run(self, builder: &Builder) -> Compiler {
861 let build = builder.build;
862 let target_compiler = self.target_compiler;
864 if target_compiler.stage == 0 {
865 assert_eq!(build.build, target_compiler.host,
866 "Cannot obtain compiler for non-native build triple at stage 0");
867 // The stage 0 compiler for the build triple is always pre-built.
868 return target_compiler;
871 // Get the compiler that we'll use to bootstrap ourselves.
873 // Note that this is where the recursive nature of the bootstrap
874 // happens, as this will request the previous stage's compiler on
875 // downwards to stage 0.
877 // Also note that we're building a compiler for the host platform. We
878 // only assume that we can run `build` artifacts, which means that to
879 // produce some other architecture compiler we need to start from
880 // `build` to get there.
882 // FIXME: Perhaps we should download those libraries?
883 // It would make builds faster...
885 // FIXME: It may be faster if we build just a stage 1 compiler and then
886 // use that to bootstrap this compiler forward.
888 builder.compiler(target_compiler.stage - 1, build.build);
890 // Build the libraries for this compiler to link to (i.e., the libraries
891 // it uses at runtime). NOTE: Crates the target compiler compiles don't
892 // link to these. (FIXME: Is that correct? It seems to be correct most
893 // of the time but I think we do link to these for stage2/bin compilers
894 // when not performing a full bootstrap).
895 if builder.build.config.keep_stage.map_or(false, |s| target_compiler.stage <= s) {
896 builder.verbose("skipping compilation of compiler due to --keep-stage");
897 let compiler = build_compiler;
898 for stage in 0..min(target_compiler.stage, builder.config.keep_stage.unwrap()) {
899 let target_compiler = builder.compiler(stage, target_compiler.host);
900 let target = target_compiler.host;
901 builder.ensure(StdLink { compiler, target_compiler, target });
902 builder.ensure(TestLink { compiler, target_compiler, target });
903 builder.ensure(RustcLink { compiler, target_compiler, target });
906 builder.ensure(Rustc {
907 compiler: build_compiler,
908 target: target_compiler.host,
910 for &backend in build.config.rust_codegen_backends.iter() {
911 builder.ensure(CodegenBackend {
912 compiler: build_compiler,
913 target: target_compiler.host,
919 let lld_install = if build.config.lld_enabled {
920 Some(builder.ensure(native::Lld {
921 target: target_compiler.host,
927 let stage = target_compiler.stage;
928 let host = target_compiler.host;
929 println!("Assembling stage{} compiler ({})", stage, host);
931 // Link in all dylibs to the libdir
932 let sysroot = builder.sysroot(target_compiler);
933 let sysroot_libdir = sysroot.join(libdir(&*host));
934 t!(fs::create_dir_all(&sysroot_libdir));
935 let src_libdir = builder.sysroot_libdir(build_compiler, host);
936 for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
937 let filename = f.file_name().into_string().unwrap();
938 if is_dylib(&filename) {
939 copy(&f.path(), &sysroot_libdir.join(&filename));
943 copy_codegen_backends_to_sysroot(builder,
946 if let Some(lld_install) = lld_install {
947 copy_lld_to_sysroot(builder, target_compiler, &lld_install);
950 // Link the compiler binary itself into place
951 let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
952 let rustc = out_dir.join(exe("rustc", &*host));
953 let bindir = sysroot.join("bin");
954 t!(fs::create_dir_all(&bindir));
955 let compiler = builder.rustc(target_compiler);
956 let _ = fs::remove_file(&compiler);
957 copy(&rustc, &compiler);
963 /// Link some files into a rustc sysroot.
965 /// For a particular stage this will link the file listed in `stamp` into the
966 /// `sysroot_dst` provided.
967 pub fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
968 t!(fs::create_dir_all(&sysroot_dst));
969 for path in read_stamp_file(stamp) {
970 copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
974 // Avoiding a dependency on winapi to keep compile times down
976 fn stderr_isatty() -> bool {
978 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
981 fn stderr_isatty() -> bool {
984 type HANDLE = *mut u8;
985 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
987 fn GetStdHandle(which: DWORD) -> HANDLE;
988 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
991 let handle = GetStdHandle(STD_ERROR_HANDLE);
993 GetConsoleMode(handle, &mut out) != 0
997 pub fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path, is_check: bool)
1000 // Instruct Cargo to give us json messages on stdout, critically leaving
1001 // stderr as piped so we can get those pretty colors.
1002 cargo.arg("--message-format").arg("json")
1003 .stdout(Stdio::piped());
1005 if stderr_isatty() && build.ci_env == CiEnv::None {
1006 // since we pass message-format=json to cargo, we need to tell the rustc
1007 // wrapper to give us colored output if necessary. This is because we
1008 // only want Cargo's JSON output, not rustcs.
1009 cargo.env("RUSTC_COLOR", "1");
1012 build.verbose(&format!("running: {:?}", cargo));
1013 let mut child = match cargo.spawn() {
1015 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1018 // `target_root_dir` looks like $dir/$target/release
1019 let target_root_dir = stamp.parent().unwrap();
1020 // `target_deps_dir` looks like $dir/$target/release/deps
1021 let target_deps_dir = target_root_dir.join("deps");
1022 // `host_root_dir` looks like $dir/release
1023 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
1024 .parent().unwrap() // chop off `$target`
1025 .join(target_root_dir.file_name().unwrap());
1027 // Spawn Cargo slurping up its JSON output. We'll start building up the
1028 // `deps` array of all files it generated along with a `toplevel` array of
1029 // files we need to probe for later.
1030 let mut deps = Vec::new();
1031 let mut toplevel = Vec::new();
1032 let stdout = BufReader::new(child.stdout.take().unwrap());
1033 for line in stdout.lines() {
1034 let line = t!(line);
1035 let json: serde_json::Value = if line.starts_with("{") {
1036 t!(serde_json::from_str(&line))
1038 // If this was informational, just print it out and continue
1039 println!("{}", line);
1042 if json["reason"].as_str() != Some("compiler-artifact") {
1043 if build.config.rustc_error_format.as_ref().map_or(false, |e| e == "json") {
1044 // most likely not a cargo message, so let's send it out as well
1045 println!("{}", line);
1049 for filename in json["filenames"].as_array().unwrap() {
1050 let filename = filename.as_str().unwrap();
1051 // Skip files like executables
1052 if !filename.ends_with(".rlib") &&
1053 !filename.ends_with(".lib") &&
1054 !is_dylib(&filename) &&
1055 !(is_check && filename.ends_with(".rmeta")) {
1059 let filename = Path::new(filename);
1061 // If this was an output file in the "host dir" we don't actually
1062 // worry about it, it's not relevant for us.
1063 if filename.starts_with(&host_root_dir) {
1067 // If this was output in the `deps` dir then this is a precise file
1068 // name (hash included) so we start tracking it.
1069 if filename.starts_with(&target_deps_dir) {
1070 deps.push(filename.to_path_buf());
1074 // Otherwise this was a "top level artifact" which right now doesn't
1075 // have a hash in the name, but there's a version of this file in
1076 // the `deps` folder which *does* have a hash in the name. That's
1077 // the one we'll want to we'll probe for it later.
1079 // We do not use `Path::file_stem` or `Path::extension` here,
1080 // because some generated files may have multiple extensions e.g.
1081 // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1082 // split the file name by the last extension (`.lib`) while we need
1083 // to split by all extensions (`.dll.lib`).
1084 let expected_len = t!(filename.metadata()).len();
1085 let filename = filename.file_name().unwrap().to_str().unwrap();
1086 let mut parts = filename.splitn(2, '.');
1087 let file_stem = parts.next().unwrap().to_owned();
1088 let extension = parts.next().unwrap().to_owned();
1090 toplevel.push((file_stem, extension, expected_len));
1094 // Make sure Cargo actually succeeded after we read all of its stdout.
1095 let status = t!(child.wait());
1096 if !status.success() {
1097 panic!("command did not execute successfully: {:?}\n\
1098 expected success, got: {}",
1103 // Ok now we need to actually find all the files listed in `toplevel`. We've
1104 // got a list of prefix/extensions and we basically just need to find the
1105 // most recent file in the `deps` folder corresponding to each one.
1106 let contents = t!(target_deps_dir.read_dir())
1108 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1109 .collect::<Vec<_>>();
1110 for (prefix, extension, expected_len) in toplevel {
1111 let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1112 filename.starts_with(&prefix[..]) &&
1113 filename[prefix.len()..].starts_with("-") &&
1114 filename.ends_with(&extension[..]) &&
1115 meta.len() == expected_len
1117 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1118 FileTime::from_last_modification_time(metadata)
1120 let path_to_add = match max {
1121 Some(triple) => triple.0.to_str().unwrap(),
1122 None => panic!("no output generated for {:?} {:?}", prefix, extension),
1124 if is_dylib(path_to_add) {
1125 let candidate = format!("{}.lib", path_to_add);
1126 let candidate = PathBuf::from(candidate);
1127 if candidate.exists() {
1128 deps.push(candidate);
1131 deps.push(path_to_add.into());
1134 // Now we want to update the contents of the stamp file, if necessary. First
1135 // we read off the previous contents along with its mtime. If our new
1136 // contents (the list of files to copy) is different or if any dep's mtime
1137 // is newer then we rewrite the stamp file.
1139 let mut stamp_contents = Vec::new();
1140 if let Ok(mut f) = File::open(stamp) {
1141 t!(f.read_to_end(&mut stamp_contents));
1143 let stamp_mtime = mtime(&stamp);
1144 let mut new_contents = Vec::new();
1146 let mut max_path = None;
1147 for dep in deps.iter() {
1148 let mtime = mtime(dep);
1149 if Some(mtime) > max {
1151 max_path = Some(dep.clone());
1153 new_contents.extend(dep.to_str().unwrap().as_bytes());
1154 new_contents.extend(b"\0");
1156 let max = max.unwrap();
1157 let max_path = max_path.unwrap();
1158 if stamp_contents == new_contents && max <= stamp_mtime {
1159 build.verbose(&format!("not updating {:?}; contents equal and {} <= {}",
1160 stamp, max, stamp_mtime));
1163 if max > stamp_mtime {
1164 build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1166 build.verbose(&format!("updating {:?} as deps changed", stamp));
1168 t!(t!(File::create(stamp)).write_all(&new_contents));