1 //! Implementation of compiling various phases of the compiler and standard
4 //! This module contains some of the real meat in the rustbuild build system
5 //! which is where Cargo is used to compiler the standard library, libtest, and
6 //! compiler. This module is also responsible for assembling the sysroot as it
7 //! goes along from the output of the previous stage.
12 use std::io::BufReader;
13 use std::io::prelude::*;
14 use std::path::{Path, PathBuf};
15 use std::process::{Command, Stdio, exit};
18 use build_helper::{output, mtime, up_to_date};
19 use filetime::FileTime;
23 use crate::util::{exe, libdir, is_dylib};
24 use crate::{Compiler, Mode, GitRepo};
27 use crate::cache::{INTERNER, Interned};
28 use crate::builder::{Step, RunConfig, ShouldRun, Builder};
30 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
32 pub target: Interned<String>,
33 pub compiler: Compiler,
38 const DEFAULT: bool = true;
40 fn should_run(run: ShouldRun) -> ShouldRun {
44 fn make_run(run: RunConfig) {
45 run.builder.ensure(Std {
46 compiler: run.builder.compiler(run.builder.top_stage, run.host),
51 /// Build the standard library.
53 /// This will build the standard library for a particular stage of the build
54 /// using the `compiler` targeting the `target` architecture. The artifacts
55 /// created will also be linked into the sysroot directory.
56 fn run(self, builder: &Builder) {
57 let target = self.target;
58 let compiler = self.compiler;
60 if builder.config.keep_stage.contains(&compiler.stage) {
61 builder.info("Warning: Using a potentially old libstd. This may not behave well.");
62 builder.ensure(StdLink {
64 target_compiler: compiler,
70 builder.ensure(StartupObjects { compiler, target });
72 if builder.force_use_stage1(compiler, target) {
73 let from = builder.compiler(1, builder.config.build);
78 builder.info(&format!("Uplifting stage1 std ({} -> {})", from.host, target));
80 // Even if we're not building std this stage, the new sysroot must
81 // still contain the musl startup objects.
82 if target.contains("musl") {
83 let libdir = builder.sysroot_libdir(compiler, target);
84 copy_musl_third_party_objects(builder, target, &libdir);
87 builder.ensure(StdLink {
89 target_compiler: compiler,
95 if target.contains("musl") {
96 let libdir = builder.sysroot_libdir(compiler, target);
97 copy_musl_third_party_objects(builder, target, &libdir);
100 let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
101 std_cargo(builder, &compiler, target, &mut cargo);
103 let _folder = builder.fold_output(|| format!("stage{}-std", compiler.stage));
104 builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
105 &compiler.host, target));
108 &libstd_stamp(builder, compiler, target),
111 builder.ensure(StdLink {
112 compiler: builder.compiler(compiler.stage, builder.config.build),
113 target_compiler: compiler,
119 /// Copies the crt(1,i,n).o startup objects
121 /// Since musl supports fully static linking, we can cross link for it even
122 /// with a glibc-targeting toolchain, given we have the appropriate startup
123 /// files. As those shipped with glibc won't work, copy the ones provided by
124 /// musl so we have them on linux-gnu hosts.
125 fn copy_musl_third_party_objects(builder: &Builder,
126 target: Interned<String>,
128 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
129 builder.copy(&builder.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
133 /// Configure cargo to compile the standard library, adding appropriate env vars
135 pub fn std_cargo(builder: &Builder,
137 target: Interned<String>,
138 cargo: &mut Command) {
139 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
140 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
143 if builder.no_std(target) == Some(true) {
144 // for no-std targets we only compile a few no_std crates
146 .args(&["-p", "alloc"])
147 .arg("--manifest-path")
148 .arg(builder.src.join("src/liballoc/Cargo.toml"))
150 .arg("compiler-builtins-mem");
152 let features = builder.std_features();
154 if compiler.stage != 0 && builder.config.sanitizers {
155 // This variable is used by the sanitizer runtime crates, e.g.
156 // rustc_lsan, to build the sanitizer runtime from C code
157 // When this variable is missing, those crates won't compile the C code,
158 // so we don't set this variable during stage0 where llvm-config is
160 // We also only build the runtimes when --enable-sanitizers (or its
161 // config.toml equivalent) is used
162 let llvm_config = builder.ensure(native::Llvm {
163 target: builder.config.build,
166 cargo.env("LLVM_CONFIG", llvm_config);
169 cargo.arg("--features").arg(features)
170 .arg("--manifest-path")
171 .arg(builder.src.join("src/libstd/Cargo.toml"));
173 if target.contains("musl") {
174 if let Some(p) = builder.musl_root(target) {
175 cargo.env("MUSL_ROOT", p);
181 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
183 pub compiler: Compiler,
184 pub target_compiler: Compiler,
185 pub target: Interned<String>,
188 impl Step for StdLink {
191 fn should_run(run: ShouldRun) -> ShouldRun {
195 /// Link all libstd rlibs/dylibs into the sysroot location.
197 /// Links those artifacts generated by `compiler` to the `stage` compiler's
198 /// sysroot for the specified `host` and `target`.
200 /// Note that this assumes that `compiler` has already generated the libstd
201 /// libraries for `target`, and this method will find them in the relevant
202 /// output directory.
203 fn run(self, builder: &Builder) {
204 let compiler = self.compiler;
205 let target_compiler = self.target_compiler;
206 let target = self.target;
207 builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
208 target_compiler.stage,
211 target_compiler.host,
213 let libdir = builder.sysroot_libdir(target_compiler, target);
214 add_to_sysroot(builder, &libdir, &libstd_stamp(builder, compiler, target));
216 if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
217 // The sanitizers are only built in stage1 or above, so the dylibs will
218 // be missing in stage0 and causes panic. See the `std()` function above
219 // for reason why the sanitizers are not built in stage0.
220 copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
223 builder.cargo(target_compiler, Mode::ToolStd, target, "clean");
227 fn copy_apple_sanitizer_dylibs(builder: &Builder, native_dir: &Path, platform: &str, into: &Path) {
228 for &sanitizer in &["asan", "tsan"] {
229 let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
230 let mut src_path = native_dir.join(sanitizer);
231 src_path.push("build");
232 src_path.push("lib");
233 src_path.push("darwin");
234 src_path.push(&filename);
235 builder.copy(&src_path, &into.join(filename));
239 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
240 pub struct StartupObjects {
241 pub compiler: Compiler,
242 pub target: Interned<String>,
245 impl Step for StartupObjects {
248 fn should_run(run: ShouldRun) -> ShouldRun {
249 run.path("src/rtstartup")
252 fn make_run(run: RunConfig) {
253 run.builder.ensure(StartupObjects {
254 compiler: run.builder.compiler(run.builder.top_stage, run.host),
259 /// Build and prepare startup objects like rsbegin.o and rsend.o
261 /// These are primarily used on Windows right now for linking executables/dlls.
262 /// They don't require any library support as they're just plain old object
263 /// files, so we just use the nightly snapshot compiler to always build them (as
264 /// no other compilers are guaranteed to be available).
265 fn run(self, builder: &Builder) {
266 let for_compiler = self.compiler;
267 let target = self.target;
268 if !target.contains("pc-windows-gnu") {
272 let src_dir = &builder.src.join("src/rtstartup");
273 let dst_dir = &builder.native_dir(target).join("rtstartup");
274 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
275 t!(fs::create_dir_all(dst_dir));
277 for file in &["rsbegin", "rsend"] {
278 let src_file = &src_dir.join(file.to_string() + ".rs");
279 let dst_file = &dst_dir.join(file.to_string() + ".o");
280 if !up_to_date(src_file, dst_file) {
281 let mut cmd = Command::new(&builder.initial_rustc);
282 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
283 .arg("--cfg").arg("stage0")
284 .arg("--target").arg(target)
286 .arg("-o").arg(dst_file)
290 builder.copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
293 for obj in ["crt2.o", "dllcrt2.o"].iter() {
294 let src = compiler_file(builder,
298 builder.copy(&src, &sysroot_dir.join(obj));
303 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
305 pub target: Interned<String>,
306 pub compiler: Compiler,
311 const DEFAULT: bool = true;
313 fn should_run(run: ShouldRun) -> ShouldRun {
314 run.all_krates("test")
317 fn make_run(run: RunConfig) {
318 run.builder.ensure(Test {
319 compiler: run.builder.compiler(run.builder.top_stage, run.host),
326 /// This will build libtest and supporting libraries for a particular stage of
327 /// the build using the `compiler` targeting the `target` architecture. The
328 /// artifacts created will also be linked into the sysroot directory.
329 fn run(self, builder: &Builder) {
330 let target = self.target;
331 let compiler = self.compiler;
333 builder.ensure(Std { compiler, target });
335 if builder.config.keep_stage.contains(&compiler.stage) {
336 builder.info("Warning: Using a potentially old libtest. This may not behave well.");
337 builder.ensure(TestLink {
339 target_compiler: compiler,
345 if builder.force_use_stage1(compiler, target) {
346 builder.ensure(Test {
347 compiler: builder.compiler(1, builder.config.build),
351 &format!("Uplifting stage1 test ({} -> {})", builder.config.build, target));
352 builder.ensure(TestLink {
353 compiler: builder.compiler(1, builder.config.build),
354 target_compiler: compiler,
360 let mut cargo = builder.cargo(compiler, Mode::Test, target, "build");
361 test_cargo(builder, &compiler, target, &mut cargo);
363 let _folder = builder.fold_output(|| format!("stage{}-test", compiler.stage));
364 builder.info(&format!("Building stage{} test artifacts ({} -> {})", compiler.stage,
365 &compiler.host, target));
368 &libtest_stamp(builder, compiler, target),
371 builder.ensure(TestLink {
372 compiler: builder.compiler(compiler.stage, builder.config.build),
373 target_compiler: compiler,
379 /// Same as `std_cargo`, but for libtest
380 pub fn test_cargo(builder: &Builder,
381 _compiler: &Compiler,
382 _target: Interned<String>,
383 cargo: &mut Command) {
384 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
385 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
387 cargo.arg("--manifest-path")
388 .arg(builder.src.join("src/libtest/Cargo.toml"));
391 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
392 pub struct TestLink {
393 pub compiler: Compiler,
394 pub target_compiler: Compiler,
395 pub target: Interned<String>,
398 impl Step for TestLink {
401 fn should_run(run: ShouldRun) -> ShouldRun {
405 /// Same as `std_link`, only for libtest
406 fn run(self, builder: &Builder) {
407 let compiler = self.compiler;
408 let target_compiler = self.target_compiler;
409 let target = self.target;
410 builder.info(&format!("Copying stage{} test from stage{} ({} -> {} / {})",
411 target_compiler.stage,
414 target_compiler.host,
416 add_to_sysroot(builder, &builder.sysroot_libdir(target_compiler, target),
417 &libtest_stamp(builder, compiler, target));
419 builder.cargo(target_compiler, Mode::ToolTest, target, "clean");
423 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
425 pub target: Interned<String>,
426 pub compiler: Compiler,
429 impl Step for Rustc {
431 const ONLY_HOSTS: bool = true;
432 const DEFAULT: bool = true;
434 fn should_run(run: ShouldRun) -> ShouldRun {
435 run.all_krates("rustc-main")
438 fn make_run(run: RunConfig) {
439 run.builder.ensure(Rustc {
440 compiler: run.builder.compiler(run.builder.top_stage, run.host),
445 /// Build the compiler.
447 /// This will build the compiler for a particular stage of the build using
448 /// the `compiler` targeting the `target` architecture. The artifacts
449 /// created will also be linked into the sysroot directory.
450 fn run(self, builder: &Builder) {
451 let compiler = self.compiler;
452 let target = self.target;
454 builder.ensure(Test { compiler, target });
456 if builder.config.keep_stage.contains(&compiler.stage) {
457 builder.info("Warning: Using a potentially old librustc. This may not behave well.");
458 builder.ensure(RustcLink {
460 target_compiler: compiler,
466 if builder.force_use_stage1(compiler, target) {
467 builder.ensure(Rustc {
468 compiler: builder.compiler(1, builder.config.build),
471 builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
472 builder.config.build, target));
473 builder.ensure(RustcLink {
474 compiler: builder.compiler(1, builder.config.build),
475 target_compiler: compiler,
481 // Ensure that build scripts have a std to link against.
483 compiler: builder.compiler(self.compiler.stage, builder.config.build),
484 target: builder.config.build,
487 let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
488 rustc_cargo(builder, &mut cargo);
490 let _folder = builder.fold_output(|| format!("stage{}-rustc", compiler.stage));
491 builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
492 compiler.stage, &compiler.host, target));
495 &librustc_stamp(builder, compiler, target),
498 builder.ensure(RustcLink {
499 compiler: builder.compiler(compiler.stage, builder.config.build),
500 target_compiler: compiler,
506 pub fn rustc_cargo(builder: &Builder, cargo: &mut Command) {
507 cargo.arg("--features").arg(builder.rustc_features())
508 .arg("--manifest-path")
509 .arg(builder.src.join("src/rustc/Cargo.toml"));
510 rustc_cargo_env(builder, cargo);
513 pub fn rustc_cargo_env(builder: &Builder, cargo: &mut Command) {
514 // Set some configuration variables picked up by build scripts and
515 // the compiler alike
516 cargo.env("CFG_RELEASE", builder.rust_release())
517 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
518 .env("CFG_VERSION", builder.rust_version())
519 .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default())
520 .env("CFG_CODEGEN_BACKENDS_DIR", &builder.config.rust_codegen_backends_dir);
522 let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
523 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
525 // If we're not building a compiler with debugging information then remove
526 // these two env vars which would be set otherwise.
527 if builder.config.rust_debuginfo_only_std {
528 cargo.env_remove("RUSTC_DEBUGINFO");
529 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
532 if let Some(ref ver_date) = builder.rust_info.commit_date() {
533 cargo.env("CFG_VER_DATE", ver_date);
535 if let Some(ref ver_hash) = builder.rust_info.sha() {
536 cargo.env("CFG_VER_HASH", ver_hash);
538 if !builder.unstable_features() {
539 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
541 if let Some(ref s) = builder.config.rustc_default_linker {
542 cargo.env("CFG_DEFAULT_LINKER", s);
544 if builder.config.rustc_parallel_queries {
545 cargo.env("RUSTC_PARALLEL_QUERIES", "1");
547 if builder.config.rust_verify_llvm_ir {
548 cargo.env("RUSTC_VERIFY_LLVM_IR", "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 compiler = self.compiler;
569 let target_compiler = self.target_compiler;
570 let target = self.target;
571 builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
572 target_compiler.stage,
575 target_compiler.host,
577 add_to_sysroot(builder, &builder.sysroot_libdir(target_compiler, target),
578 &librustc_stamp(builder, compiler, target));
579 builder.cargo(target_compiler, Mode::ToolRustc, target, "clean");
583 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
584 pub struct CodegenBackend {
585 pub compiler: Compiler,
586 pub target: Interned<String>,
587 pub backend: Interned<String>,
590 impl Step for CodegenBackend {
592 const ONLY_HOSTS: bool = true;
593 const DEFAULT: bool = true;
595 fn should_run(run: ShouldRun) -> ShouldRun {
596 run.all_krates("rustc_codegen_llvm")
599 fn make_run(run: RunConfig) {
600 let backend = run.builder.config.rust_codegen_backends.get(0);
601 let backend = backend.cloned().unwrap_or_else(|| {
602 INTERNER.intern_str("llvm")
604 run.builder.ensure(CodegenBackend {
605 compiler: run.builder.compiler(run.builder.top_stage, run.host),
611 fn run(self, builder: &Builder) {
612 let compiler = self.compiler;
613 let target = self.target;
614 let backend = self.backend;
616 builder.ensure(Rustc { compiler, target });
618 if builder.config.keep_stage.contains(&compiler.stage) {
619 builder.info("Warning: Using a potentially old codegen backend. \
620 This may not behave well.");
621 // Codegen backends are linked separately from this step today, so we don't do
626 if builder.force_use_stage1(compiler, target) {
627 builder.ensure(CodegenBackend {
628 compiler: builder.compiler(1, builder.config.build),
635 let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
637 let mut cargo = builder.cargo(compiler, Mode::Codegen, target, "build");
638 cargo.arg("--manifest-path")
639 .arg(builder.src.join("src/librustc_codegen_llvm/Cargo.toml"));
640 rustc_cargo_env(builder, &mut cargo);
642 let features = build_codegen_backend(&builder, &mut cargo, &compiler, target, backend);
644 let tmp_stamp = out_dir.join(".tmp.stamp");
646 let _folder = builder.fold_output(|| format!("stage{}-rustc_codegen_llvm", compiler.stage));
647 let files = run_cargo(builder,
648 cargo.arg("--features").arg(features),
651 if builder.config.dry_run {
654 let mut files = files.into_iter()
656 let filename = f.file_name().unwrap().to_str().unwrap();
657 is_dylib(filename) && filename.contains("rustc_codegen_llvm-")
659 let codegen_backend = match files.next() {
661 None => panic!("no dylibs built for codegen backend?"),
663 if let Some(f) = files.next() {
664 panic!("codegen backend built two dylibs:\n{}\n{}",
665 codegen_backend.display(),
668 let stamp = codegen_backend_stamp(builder, compiler, target, backend);
669 let codegen_backend = codegen_backend.to_str().unwrap();
670 t!(fs::write(&stamp, &codegen_backend));
674 pub fn build_codegen_backend(builder: &Builder,
677 target: Interned<String>,
678 backend: Interned<String>) -> String {
679 let mut features = String::new();
682 "llvm" | "emscripten" => {
683 // Build LLVM for our target. This will implicitly build the
684 // host LLVM if necessary.
685 let llvm_config = builder.ensure(native::Llvm {
687 emscripten: backend == "emscripten",
690 if backend == "emscripten" {
691 features.push_str(" emscripten");
694 builder.info(&format!("Building stage{} codegen artifacts ({} -> {}, {})",
695 compiler.stage, &compiler.host, target, backend));
697 // Pass down configuration from the LLVM build into the build of
698 // librustc_llvm and librustc_codegen_llvm.
699 if builder.is_rust_llvm(target) && backend != "emscripten" {
700 cargo.env("LLVM_RUSTLLVM", "1");
702 cargo.env("LLVM_CONFIG", &llvm_config);
703 if backend != "emscripten" {
704 let target_config = builder.config.target_config.get(&target);
705 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
706 cargo.env("CFG_LLVM_ROOT", s);
709 // Building with a static libstdc++ is only supported on linux right now,
710 // not for MSVC or macOS
711 if builder.config.llvm_static_stdcpp &&
712 !target.contains("freebsd") &&
713 !target.contains("windows") &&
714 !target.contains("apple") {
715 let file = compiler_file(builder,
716 builder.cxx(target).unwrap(),
719 cargo.env("LLVM_STATIC_STDCPP", file);
721 if builder.config.llvm_link_shared ||
722 (builder.config.llvm_thin_lto && backend != "emscripten")
724 cargo.env("LLVM_LINK_SHARED", "1");
726 if builder.config.llvm_use_libcxx {
727 cargo.env("LLVM_USE_LIBCXX", "1");
730 _ => panic!("unknown backend: {}", backend),
736 /// Creates the `codegen-backends` folder for a compiler that's about to be
737 /// assembled as a complete compiler.
739 /// This will take the codegen artifacts produced by `compiler` and link them
740 /// into an appropriate location for `target_compiler` to be a functional
742 fn copy_codegen_backends_to_sysroot(builder: &Builder,
744 target_compiler: Compiler) {
745 let target = target_compiler.host;
747 // Note that this step is different than all the other `*Link` steps in
748 // that it's not assembling a bunch of libraries but rather is primarily
749 // moving the codegen backend into place. The codegen backend of rustc is
750 // not linked into the main compiler by default but is rather dynamically
751 // selected at runtime for inclusion.
753 // Here we're looking for the output dylib of the `CodegenBackend` step and
754 // we're copying that into the `codegen-backends` folder.
755 let dst = builder.sysroot_codegen_backends(target_compiler);
756 t!(fs::create_dir_all(&dst));
758 if builder.config.dry_run {
762 for backend in builder.config.rust_codegen_backends.iter() {
763 let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
764 let dylib = t!(fs::read_to_string(&stamp));
765 let file = Path::new(&dylib);
766 let filename = file.file_name().unwrap().to_str().unwrap();
767 // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
768 let target_filename = {
769 let dash = filename.find('-').unwrap();
770 let dot = filename.find('.').unwrap();
776 builder.copy(&file, &dst.join(target_filename));
780 fn copy_lld_to_sysroot(builder: &Builder,
781 target_compiler: Compiler,
782 lld_install_root: &Path) {
783 let target = target_compiler.host;
785 let dst = builder.sysroot_libdir(target_compiler, target)
789 t!(fs::create_dir_all(&dst));
791 let src_exe = exe("lld", &target);
792 let dst_exe = exe("rust-lld", &target);
793 // we prepend this bin directory to the user PATH when linking Rust binaries. To
794 // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
795 builder.copy(&lld_install_root.join("bin").join(&src_exe), &dst.join(&dst_exe));
798 /// Cargo's output path for the standard library in a given stage, compiled
799 /// by a particular compiler for the specified target.
800 pub fn libstd_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
801 builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
804 /// Cargo's output path for libtest in a given stage, compiled by a particular
805 /// compiler for the specified target.
806 pub fn libtest_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
807 builder.cargo_out(compiler, Mode::Test, target).join(".libtest.stamp")
810 /// Cargo's output path for librustc in a given stage, compiled by a particular
811 /// compiler for the specified target.
812 pub fn librustc_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
813 builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
816 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
817 /// compiler for the specified target and backend.
818 fn codegen_backend_stamp(builder: &Builder,
820 target: Interned<String>,
821 backend: Interned<String>) -> PathBuf {
822 builder.cargo_out(compiler, Mode::Codegen, target)
823 .join(format!(".librustc_codegen_llvm-{}.stamp", backend))
826 pub fn compiler_file(builder: &Builder,
828 target: Interned<String>,
829 file: &str) -> PathBuf {
830 let mut cmd = Command::new(compiler);
831 cmd.args(builder.cflags(target, GitRepo::Rustc));
832 cmd.arg(format!("-print-file-name={}", file));
833 let out = output(&mut cmd);
834 PathBuf::from(out.trim())
837 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
839 pub compiler: Compiler,
842 impl Step for Sysroot {
843 type Output = Interned<PathBuf>;
845 fn should_run(run: ShouldRun) -> ShouldRun {
849 /// Returns the sysroot for the `compiler` specified that *this build system
852 /// That is, the sysroot for the stage0 compiler is not what the compiler
853 /// thinks it is by default, but it's the same as the default for stages
855 fn run(self, builder: &Builder) -> Interned<PathBuf> {
856 let compiler = self.compiler;
857 let sysroot = if compiler.stage == 0 {
858 builder.out.join(&compiler.host).join("stage0-sysroot")
860 builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
862 let _ = fs::remove_dir_all(&sysroot);
863 t!(fs::create_dir_all(&sysroot));
864 INTERNER.intern_path(sysroot)
868 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
869 pub struct Assemble {
870 /// The compiler which we will produce in this step. Assemble itself will
871 /// take care of ensuring that the necessary prerequisites to do so exist,
872 /// that is, this target can be a stage2 compiler and Assemble will build
873 /// previous stages for you.
874 pub target_compiler: Compiler,
877 impl Step for Assemble {
878 type Output = Compiler;
880 fn should_run(run: ShouldRun) -> ShouldRun {
884 /// Prepare a new compiler from the artifacts in `stage`
886 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
887 /// must have been previously produced by the `stage - 1` builder.build
889 fn run(self, builder: &Builder) -> Compiler {
890 let target_compiler = self.target_compiler;
892 if target_compiler.stage == 0 {
893 assert_eq!(builder.config.build, target_compiler.host,
894 "Cannot obtain compiler for non-native build triple at stage 0");
895 // The stage 0 compiler for the build triple is always pre-built.
896 return target_compiler;
899 // Get the compiler that we'll use to bootstrap ourselves.
901 // Note that this is where the recursive nature of the bootstrap
902 // happens, as this will request the previous stage's compiler on
903 // downwards to stage 0.
905 // Also note that we're building a compiler for the host platform. We
906 // only assume that we can run `build` artifacts, which means that to
907 // produce some other architecture compiler we need to start from
908 // `build` to get there.
910 // FIXME: Perhaps we should download those libraries?
911 // It would make builds faster...
913 // FIXME: It may be faster if we build just a stage 1 compiler and then
914 // use that to bootstrap this compiler forward.
916 builder.compiler(target_compiler.stage - 1, builder.config.build);
918 // Build the libraries for this compiler to link to (i.e., the libraries
919 // it uses at runtime). NOTE: Crates the target compiler compiles don't
920 // link to these. (FIXME: Is that correct? It seems to be correct most
921 // of the time but I think we do link to these for stage2/bin compilers
922 // when not performing a full bootstrap).
923 builder.ensure(Rustc {
924 compiler: build_compiler,
925 target: target_compiler.host,
927 for &backend in builder.config.rust_codegen_backends.iter() {
928 builder.ensure(CodegenBackend {
929 compiler: build_compiler,
930 target: target_compiler.host,
935 let lld_install = if builder.config.lld_enabled {
936 Some(builder.ensure(native::Lld {
937 target: target_compiler.host,
943 let stage = target_compiler.stage;
944 let host = target_compiler.host;
945 builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
947 // Link in all dylibs to the libdir
948 let sysroot = builder.sysroot(target_compiler);
949 let sysroot_libdir = sysroot.join(libdir(&*host));
950 t!(fs::create_dir_all(&sysroot_libdir));
951 let src_libdir = builder.sysroot_libdir(build_compiler, host);
952 for f in builder.read_dir(&src_libdir) {
953 let filename = f.file_name().into_string().unwrap();
954 if is_dylib(&filename) {
955 builder.copy(&f.path(), &sysroot_libdir.join(&filename));
959 copy_codegen_backends_to_sysroot(builder,
962 if let Some(lld_install) = lld_install {
963 copy_lld_to_sysroot(builder, target_compiler, &lld_install);
966 dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
968 // Link the compiler binary itself into place
969 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
970 let rustc = out_dir.join(exe("rustc_binary", &*host));
971 let bindir = sysroot.join("bin");
972 t!(fs::create_dir_all(&bindir));
973 let compiler = builder.rustc(target_compiler);
974 let _ = fs::remove_file(&compiler);
975 builder.copy(&rustc, &compiler);
981 /// Link some files into a rustc sysroot.
983 /// For a particular stage this will link the file listed in `stamp` into the
984 /// `sysroot_dst` provided.
985 pub fn add_to_sysroot(builder: &Builder, sysroot_dst: &Path, stamp: &Path) {
986 t!(fs::create_dir_all(&sysroot_dst));
987 for path in builder.read_stamp_file(stamp) {
988 builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
992 pub fn run_cargo(builder: &Builder,
998 if builder.config.dry_run {
1002 // `target_root_dir` looks like $dir/$target/release
1003 let target_root_dir = stamp.parent().unwrap();
1004 // `target_deps_dir` looks like $dir/$target/release/deps
1005 let target_deps_dir = target_root_dir.join("deps");
1006 // `host_root_dir` looks like $dir/release
1007 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
1008 .parent().unwrap() // chop off `$target`
1009 .join(target_root_dir.file_name().unwrap());
1011 // Spawn Cargo slurping up its JSON output. We'll start building up the
1012 // `deps` array of all files it generated along with a `toplevel` array of
1013 // files we need to probe for later.
1014 let mut deps = Vec::new();
1015 let mut toplevel = Vec::new();
1016 let ok = stream_cargo(builder, cargo, &mut |msg| {
1017 let filenames = match msg {
1018 CargoMessage::CompilerArtifact { filenames, .. } => filenames,
1021 for filename in filenames {
1022 // Skip files like executables
1023 if !filename.ends_with(".rlib") &&
1024 !filename.ends_with(".lib") &&
1025 !is_dylib(&filename) &&
1026 !(is_check && filename.ends_with(".rmeta")) {
1030 let filename = Path::new(&*filename);
1032 // If this was an output file in the "host dir" we don't actually
1033 // worry about it, it's not relevant for us.
1034 if filename.starts_with(&host_root_dir) {
1038 // If this was output in the `deps` dir then this is a precise file
1039 // name (hash included) so we start tracking it.
1040 if filename.starts_with(&target_deps_dir) {
1041 deps.push(filename.to_path_buf());
1045 // Otherwise this was a "top level artifact" which right now doesn't
1046 // have a hash in the name, but there's a version of this file in
1047 // the `deps` folder which *does* have a hash in the name. That's
1048 // the one we'll want to we'll probe for it later.
1050 // We do not use `Path::file_stem` or `Path::extension` here,
1051 // because some generated files may have multiple extensions e.g.
1052 // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1053 // split the file name by the last extension (`.lib`) while we need
1054 // to split by all extensions (`.dll.lib`).
1055 let expected_len = t!(filename.metadata()).len();
1056 let filename = filename.file_name().unwrap().to_str().unwrap();
1057 let mut parts = filename.splitn(2, '.');
1058 let file_stem = parts.next().unwrap().to_owned();
1059 let extension = parts.next().unwrap().to_owned();
1061 toplevel.push((file_stem, extension, expected_len));
1069 // Ok now we need to actually find all the files listed in `toplevel`. We've
1070 // got a list of prefix/extensions and we basically just need to find the
1071 // most recent file in the `deps` folder corresponding to each one.
1072 let contents = t!(target_deps_dir.read_dir())
1074 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1075 .collect::<Vec<_>>();
1076 for (prefix, extension, expected_len) in toplevel {
1077 let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1078 filename.starts_with(&prefix[..]) &&
1079 filename[prefix.len()..].starts_with("-") &&
1080 filename.ends_with(&extension[..]) &&
1081 meta.len() == expected_len
1083 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1084 FileTime::from_last_modification_time(metadata)
1086 let path_to_add = match max {
1087 Some(triple) => triple.0.to_str().unwrap(),
1088 None => panic!("no output generated for {:?} {:?}", prefix, extension),
1090 if is_dylib(path_to_add) {
1091 let candidate = format!("{}.lib", path_to_add);
1092 let candidate = PathBuf::from(candidate);
1093 if candidate.exists() {
1094 deps.push(candidate);
1097 deps.push(path_to_add.into());
1100 // Now we want to update the contents of the stamp file, if necessary. First
1101 // we read off the previous contents along with its mtime. If our new
1102 // contents (the list of files to copy) is different or if any dep's mtime
1103 // is newer then we rewrite the stamp file.
1105 let stamp_contents = fs::read(stamp);
1106 let stamp_mtime = mtime(&stamp);
1107 let mut new_contents = Vec::new();
1109 let mut max_path = None;
1110 for dep in deps.iter() {
1111 let mtime = mtime(dep);
1112 if Some(mtime) > max {
1114 max_path = Some(dep.clone());
1116 new_contents.extend(dep.to_str().unwrap().as_bytes());
1117 new_contents.extend(b"\0");
1119 let max = max.unwrap();
1120 let max_path = max_path.unwrap();
1121 let contents_equal = stamp_contents
1122 .map(|contents| contents == new_contents)
1123 .unwrap_or_default();
1124 if contents_equal && max <= stamp_mtime {
1125 builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}",
1126 stamp, max, stamp_mtime));
1129 if max > stamp_mtime {
1130 builder.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1132 builder.verbose(&format!("updating {:?} as deps changed", stamp));
1134 t!(fs::write(&stamp, &new_contents));
1138 pub fn stream_cargo(
1140 cargo: &mut Command,
1141 cb: &mut dyn FnMut(CargoMessage),
1143 if builder.config.dry_run {
1146 // Instruct Cargo to give us json messages on stdout, critically leaving
1147 // stderr as piped so we can get those pretty colors.
1148 cargo.arg("--message-format").arg("json")
1149 .stdout(Stdio::piped());
1151 builder.verbose(&format!("running: {:?}", cargo));
1152 let mut child = match cargo.spawn() {
1154 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1157 // Spawn Cargo slurping up its JSON output. We'll start building up the
1158 // `deps` array of all files it generated along with a `toplevel` array of
1159 // files we need to probe for later.
1160 let stdout = BufReader::new(child.stdout.take().unwrap());
1161 for line in stdout.lines() {
1162 let line = t!(line);
1163 match serde_json::from_str::<CargoMessage>(&line) {
1165 // If this was informational, just print it out and continue
1166 Err(_) => println!("{}", line)
1170 // Make sure Cargo actually succeeded after we read all of its stdout.
1171 let status = t!(child.wait());
1172 if !status.success() {
1173 eprintln!("command did not execute successfully: {:?}\n\
1174 expected success, got: {}",
1181 #[derive(Deserialize)]
1182 #[serde(tag = "reason", rename_all = "kebab-case")]
1183 pub enum CargoMessage<'a> {
1185 package_id: Cow<'a, str>,
1186 features: Vec<Cow<'a, str>>,
1187 filenames: Vec<Cow<'a, str>>,
1189 BuildScriptExecuted {
1190 package_id: Cow<'a, str>,