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 third party objects needed by various targets.
82 copy_third_party_objects(builder, &compiler, target);
84 builder.ensure(StdLink {
86 target_compiler: compiler,
92 copy_third_party_objects(builder, &compiler, target);
94 let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
95 std_cargo(builder, &compiler, target, &mut cargo);
97 let _folder = builder.fold_output(|| format!("stage{}-std", compiler.stage));
98 builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
99 &compiler.host, target));
102 &libstd_stamp(builder, compiler, target),
105 builder.ensure(StdLink {
106 compiler: builder.compiler(compiler.stage, builder.config.build),
107 target_compiler: compiler,
113 /// Copies third pary objects needed by various targets.
114 fn copy_third_party_objects(builder: &Builder, compiler: &Compiler, target: Interned<String>) {
115 let libdir = builder.sysroot_libdir(*compiler, target);
117 // Copies the crt(1,i,n).o startup objects
119 // Since musl supports fully static linking, we can cross link for it even
120 // with a glibc-targeting toolchain, given we have the appropriate startup
121 // files. As those shipped with glibc won't work, copy the ones provided by
122 // musl so we have them on linux-gnu hosts.
123 if target.contains("musl") {
124 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
126 &builder.musl_root(target).unwrap().join("lib").join(obj),
132 // Copies libunwind.a compiled to be linked wit x86_64-fortanix-unknown-sgx.
134 // This target needs to be linked to Fortanix's port of llvm's libunwind.
135 // libunwind requires support for rwlock and printing to stderr,
136 // which is provided by std for this target.
137 if target == "x86_64-fortanix-unknown-sgx" {
138 let src_path_env = "X86_FORTANIX_SGX_LIBS";
139 let obj = "libunwind.a";
140 let src = env::var(src_path_env).expect(&format!("{} not found in env", src_path_env));
141 let src = Path::new(&src).join(obj);
142 builder.copy(&src, &libdir.join(obj));
146 /// Configure cargo to compile the standard library, adding appropriate env vars
148 pub fn std_cargo(builder: &Builder,
150 target: Interned<String>,
151 cargo: &mut Command) {
152 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
153 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
156 if builder.no_std(target) == Some(true) {
157 // for no-std targets we only compile a few no_std crates
159 .args(&["-p", "alloc"])
160 .arg("--manifest-path")
161 .arg(builder.src.join("src/liballoc/Cargo.toml"))
163 .arg("compiler-builtins-mem");
165 let features = builder.std_features();
167 if compiler.stage != 0 && builder.config.sanitizers {
168 // This variable is used by the sanitizer runtime crates, e.g.
169 // rustc_lsan, to build the sanitizer runtime from C code
170 // When this variable is missing, those crates won't compile the C code,
171 // so we don't set this variable during stage0 where llvm-config is
173 // We also only build the runtimes when --enable-sanitizers (or its
174 // config.toml equivalent) is used
175 let llvm_config = builder.ensure(native::Llvm {
176 target: builder.config.build,
179 cargo.env("LLVM_CONFIG", llvm_config);
182 cargo.arg("--features").arg(features)
183 .arg("--manifest-path")
184 .arg(builder.src.join("src/libstd/Cargo.toml"));
186 if target.contains("musl") {
187 if let Some(p) = builder.musl_root(target) {
188 cargo.env("MUSL_ROOT", p);
194 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
196 pub compiler: Compiler,
197 pub target_compiler: Compiler,
198 pub target: Interned<String>,
201 impl Step for StdLink {
204 fn should_run(run: ShouldRun) -> ShouldRun {
208 /// Link all libstd rlibs/dylibs into the sysroot location.
210 /// Links those artifacts generated by `compiler` to the `stage` compiler's
211 /// sysroot for the specified `host` and `target`.
213 /// Note that this assumes that `compiler` has already generated the libstd
214 /// libraries for `target`, and this method will find them in the relevant
215 /// output directory.
216 fn run(self, builder: &Builder) {
217 let compiler = self.compiler;
218 let target_compiler = self.target_compiler;
219 let target = self.target;
220 builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
221 target_compiler.stage,
224 target_compiler.host,
226 let libdir = builder.sysroot_libdir(target_compiler, target);
227 add_to_sysroot(builder, &libdir, &libstd_stamp(builder, compiler, target));
229 if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
230 // The sanitizers are only built in stage1 or above, so the dylibs will
231 // be missing in stage0 and causes panic. See the `std()` function above
232 // for reason why the sanitizers are not built in stage0.
233 copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
236 builder.cargo(target_compiler, Mode::ToolStd, target, "clean");
240 fn copy_apple_sanitizer_dylibs(builder: &Builder, native_dir: &Path, platform: &str, into: &Path) {
241 for &sanitizer in &["asan", "tsan"] {
242 let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
243 let mut src_path = native_dir.join(sanitizer);
244 src_path.push("build");
245 src_path.push("lib");
246 src_path.push("darwin");
247 src_path.push(&filename);
248 builder.copy(&src_path, &into.join(filename));
252 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
253 pub struct StartupObjects {
254 pub compiler: Compiler,
255 pub target: Interned<String>,
258 impl Step for StartupObjects {
261 fn should_run(run: ShouldRun) -> ShouldRun {
262 run.path("src/rtstartup")
265 fn make_run(run: RunConfig) {
266 run.builder.ensure(StartupObjects {
267 compiler: run.builder.compiler(run.builder.top_stage, run.host),
272 /// Build and prepare startup objects like rsbegin.o and rsend.o
274 /// These are primarily used on Windows right now for linking executables/dlls.
275 /// They don't require any library support as they're just plain old object
276 /// files, so we just use the nightly snapshot compiler to always build them (as
277 /// no other compilers are guaranteed to be available).
278 fn run(self, builder: &Builder) {
279 let for_compiler = self.compiler;
280 let target = self.target;
281 if !target.contains("pc-windows-gnu") {
285 let src_dir = &builder.src.join("src/rtstartup");
286 let dst_dir = &builder.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(&builder.initial_rustc);
295 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
296 .arg("--cfg").arg("stage0")
297 .arg("--target").arg(target)
299 .arg("-o").arg(dst_file)
303 builder.copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
306 for obj in ["crt2.o", "dllcrt2.o"].iter() {
307 let src = compiler_file(builder,
311 builder.copy(&src, &sysroot_dir.join(obj));
316 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
318 pub target: Interned<String>,
319 pub compiler: Compiler,
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 target = self.target;
344 let compiler = self.compiler;
346 builder.ensure(Std { compiler, target });
348 if builder.config.keep_stage.contains(&compiler.stage) {
349 builder.info("Warning: Using a potentially old libtest. This may not behave well.");
350 builder.ensure(TestLink {
352 target_compiler: compiler,
358 if builder.force_use_stage1(compiler, target) {
359 builder.ensure(Test {
360 compiler: builder.compiler(1, builder.config.build),
364 &format!("Uplifting stage1 test ({} -> {})", builder.config.build, target));
365 builder.ensure(TestLink {
366 compiler: builder.compiler(1, builder.config.build),
367 target_compiler: compiler,
373 let mut cargo = builder.cargo(compiler, Mode::Test, target, "build");
374 test_cargo(builder, &compiler, target, &mut cargo);
376 let _folder = builder.fold_output(|| format!("stage{}-test", compiler.stage));
377 builder.info(&format!("Building stage{} test artifacts ({} -> {})", compiler.stage,
378 &compiler.host, target));
381 &libtest_stamp(builder, compiler, target),
384 builder.ensure(TestLink {
385 compiler: builder.compiler(compiler.stage, builder.config.build),
386 target_compiler: compiler,
392 /// Same as `std_cargo`, but for libtest
393 pub fn test_cargo(builder: &Builder,
394 _compiler: &Compiler,
395 _target: Interned<String>,
396 cargo: &mut Command) {
397 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
398 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
400 cargo.arg("--manifest-path")
401 .arg(builder.src.join("src/libtest/Cargo.toml"));
404 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
405 pub struct TestLink {
406 pub compiler: Compiler,
407 pub target_compiler: Compiler,
408 pub target: Interned<String>,
411 impl Step for TestLink {
414 fn should_run(run: ShouldRun) -> ShouldRun {
418 /// Same as `std_link`, only for libtest
419 fn run(self, builder: &Builder) {
420 let compiler = self.compiler;
421 let target_compiler = self.target_compiler;
422 let target = self.target;
423 builder.info(&format!("Copying stage{} test from stage{} ({} -> {} / {})",
424 target_compiler.stage,
427 target_compiler.host,
429 add_to_sysroot(builder, &builder.sysroot_libdir(target_compiler, target),
430 &libtest_stamp(builder, compiler, target));
432 builder.cargo(target_compiler, Mode::ToolTest, target, "clean");
436 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
438 pub target: Interned<String>,
439 pub compiler: Compiler,
442 impl Step for Rustc {
444 const ONLY_HOSTS: bool = true;
445 const DEFAULT: bool = true;
447 fn should_run(run: ShouldRun) -> ShouldRun {
448 run.all_krates("rustc-main")
451 fn make_run(run: RunConfig) {
452 run.builder.ensure(Rustc {
453 compiler: run.builder.compiler(run.builder.top_stage, run.host),
458 /// Build the compiler.
460 /// This will build the compiler for a particular stage of the build using
461 /// the `compiler` targeting the `target` architecture. The artifacts
462 /// created will also be linked into the sysroot directory.
463 fn run(self, builder: &Builder) {
464 let compiler = self.compiler;
465 let target = self.target;
467 builder.ensure(Test { compiler, target });
469 if builder.config.keep_stage.contains(&compiler.stage) {
470 builder.info("Warning: Using a potentially old librustc. This may not behave well.");
471 builder.ensure(RustcLink {
473 target_compiler: compiler,
479 if builder.force_use_stage1(compiler, target) {
480 builder.ensure(Rustc {
481 compiler: builder.compiler(1, builder.config.build),
484 builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
485 builder.config.build, target));
486 builder.ensure(RustcLink {
487 compiler: builder.compiler(1, builder.config.build),
488 target_compiler: compiler,
494 // Ensure that build scripts have a std to link against.
496 compiler: builder.compiler(self.compiler.stage, builder.config.build),
497 target: builder.config.build,
500 let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
501 rustc_cargo(builder, &mut cargo);
503 let _folder = builder.fold_output(|| format!("stage{}-rustc", compiler.stage));
504 builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
505 compiler.stage, &compiler.host, target));
508 &librustc_stamp(builder, compiler, target),
511 builder.ensure(RustcLink {
512 compiler: builder.compiler(compiler.stage, builder.config.build),
513 target_compiler: compiler,
519 pub fn rustc_cargo(builder: &Builder, cargo: &mut Command) {
520 cargo.arg("--features").arg(builder.rustc_features())
521 .arg("--manifest-path")
522 .arg(builder.src.join("src/rustc/Cargo.toml"));
523 rustc_cargo_env(builder, cargo);
526 pub fn rustc_cargo_env(builder: &Builder, cargo: &mut Command) {
527 // Set some configuration variables picked up by build scripts and
528 // the compiler alike
529 cargo.env("CFG_RELEASE", builder.rust_release())
530 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
531 .env("CFG_VERSION", builder.rust_version())
532 .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default())
533 .env("CFG_CODEGEN_BACKENDS_DIR", &builder.config.rust_codegen_backends_dir);
535 let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
536 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
538 // If we're not building a compiler with debugging information then remove
539 // these two env vars which would be set otherwise.
540 if builder.config.rust_debuginfo_only_std {
541 cargo.env_remove("RUSTC_DEBUGINFO");
542 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
545 if let Some(ref ver_date) = builder.rust_info.commit_date() {
546 cargo.env("CFG_VER_DATE", ver_date);
548 if let Some(ref ver_hash) = builder.rust_info.sha() {
549 cargo.env("CFG_VER_HASH", ver_hash);
551 if !builder.unstable_features() {
552 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
554 if let Some(ref s) = builder.config.rustc_default_linker {
555 cargo.env("CFG_DEFAULT_LINKER", s);
557 if builder.config.rustc_parallel {
558 cargo.env("RUSTC_PARALLEL_COMPILER", "1");
560 if builder.config.rust_verify_llvm_ir {
561 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
565 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
567 pub compiler: Compiler,
568 pub target_compiler: Compiler,
569 pub target: Interned<String>,
572 impl Step for RustcLink {
575 fn should_run(run: ShouldRun) -> ShouldRun {
579 /// Same as `std_link`, only for librustc
580 fn run(self, builder: &Builder) {
581 let compiler = self.compiler;
582 let target_compiler = self.target_compiler;
583 let target = self.target;
584 builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
585 target_compiler.stage,
588 target_compiler.host,
590 add_to_sysroot(builder, &builder.sysroot_libdir(target_compiler, target),
591 &librustc_stamp(builder, compiler, target));
592 builder.cargo(target_compiler, Mode::ToolRustc, target, "clean");
596 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
597 pub struct CodegenBackend {
598 pub compiler: Compiler,
599 pub target: Interned<String>,
600 pub backend: Interned<String>,
603 impl Step for CodegenBackend {
605 const ONLY_HOSTS: bool = true;
606 const DEFAULT: bool = true;
608 fn should_run(run: ShouldRun) -> ShouldRun {
609 run.all_krates("rustc_codegen_llvm")
612 fn make_run(run: RunConfig) {
613 let backend = run.builder.config.rust_codegen_backends.get(0);
614 let backend = backend.cloned().unwrap_or_else(|| {
615 INTERNER.intern_str("llvm")
617 run.builder.ensure(CodegenBackend {
618 compiler: run.builder.compiler(run.builder.top_stage, run.host),
624 fn run(self, builder: &Builder) {
625 let compiler = self.compiler;
626 let target = self.target;
627 let backend = self.backend;
629 builder.ensure(Rustc { compiler, target });
631 if builder.config.keep_stage.contains(&compiler.stage) {
632 builder.info("Warning: Using a potentially old codegen backend. \
633 This may not behave well.");
634 // Codegen backends are linked separately from this step today, so we don't do
639 if builder.force_use_stage1(compiler, target) {
640 builder.ensure(CodegenBackend {
641 compiler: builder.compiler(1, builder.config.build),
648 let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
650 let mut cargo = builder.cargo(compiler, Mode::Codegen, target, "build");
651 cargo.arg("--manifest-path")
652 .arg(builder.src.join("src/librustc_codegen_llvm/Cargo.toml"));
653 rustc_cargo_env(builder, &mut cargo);
655 let features = build_codegen_backend(&builder, &mut cargo, &compiler, target, backend);
657 let tmp_stamp = out_dir.join(".tmp.stamp");
659 let _folder = builder.fold_output(|| format!("stage{}-rustc_codegen_llvm", compiler.stage));
660 let files = run_cargo(builder,
661 cargo.arg("--features").arg(features),
664 if builder.config.dry_run {
667 let mut files = files.into_iter()
669 let filename = f.file_name().unwrap().to_str().unwrap();
670 is_dylib(filename) && filename.contains("rustc_codegen_llvm-")
672 let codegen_backend = match files.next() {
674 None => panic!("no dylibs built for codegen backend?"),
676 if let Some(f) = files.next() {
677 panic!("codegen backend built two dylibs:\n{}\n{}",
678 codegen_backend.display(),
681 let stamp = codegen_backend_stamp(builder, compiler, target, backend);
682 let codegen_backend = codegen_backend.to_str().unwrap();
683 t!(fs::write(&stamp, &codegen_backend));
687 pub fn build_codegen_backend(builder: &Builder,
690 target: Interned<String>,
691 backend: Interned<String>) -> String {
692 let mut features = String::new();
695 "llvm" | "emscripten" => {
696 // Build LLVM for our target. This will implicitly build the
697 // host LLVM if necessary.
698 let llvm_config = builder.ensure(native::Llvm {
700 emscripten: backend == "emscripten",
703 if backend == "emscripten" {
704 features.push_str(" emscripten");
707 builder.info(&format!("Building stage{} codegen artifacts ({} -> {}, {})",
708 compiler.stage, &compiler.host, target, backend));
710 // Pass down configuration from the LLVM build into the build of
711 // librustc_llvm and librustc_codegen_llvm.
712 if builder.is_rust_llvm(target) && backend != "emscripten" {
713 cargo.env("LLVM_RUSTLLVM", "1");
716 cargo.env("LLVM_CONFIG", &llvm_config);
717 if backend != "emscripten" {
718 let target_config = builder.config.target_config.get(&target);
719 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
720 cargo.env("CFG_LLVM_ROOT", s);
723 // Building with a static libstdc++ is only supported on linux right now,
724 // not for MSVC or macOS
725 if builder.config.llvm_static_stdcpp &&
726 !target.contains("freebsd") &&
727 !target.contains("windows") &&
728 !target.contains("apple") {
729 let file = compiler_file(builder,
730 builder.cxx(target).unwrap(),
733 cargo.env("LLVM_STATIC_STDCPP", file);
735 if builder.config.llvm_link_shared ||
736 (builder.config.llvm_thin_lto && backend != "emscripten")
738 cargo.env("LLVM_LINK_SHARED", "1");
740 if builder.config.llvm_use_libcxx {
741 cargo.env("LLVM_USE_LIBCXX", "1");
744 _ => panic!("unknown backend: {}", backend),
750 /// Creates the `codegen-backends` folder for a compiler that's about to be
751 /// assembled as a complete compiler.
753 /// This will take the codegen artifacts produced by `compiler` and link them
754 /// into an appropriate location for `target_compiler` to be a functional
756 fn copy_codegen_backends_to_sysroot(builder: &Builder,
758 target_compiler: Compiler) {
759 let target = target_compiler.host;
761 // Note that this step is different than all the other `*Link` steps in
762 // that it's not assembling a bunch of libraries but rather is primarily
763 // moving the codegen backend into place. The codegen backend of rustc is
764 // not linked into the main compiler by default but is rather dynamically
765 // selected at runtime for inclusion.
767 // Here we're looking for the output dylib of the `CodegenBackend` step and
768 // we're copying that into the `codegen-backends` folder.
769 let dst = builder.sysroot_codegen_backends(target_compiler);
770 t!(fs::create_dir_all(&dst));
772 if builder.config.dry_run {
776 for backend in builder.config.rust_codegen_backends.iter() {
777 let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
778 let dylib = t!(fs::read_to_string(&stamp));
779 let file = Path::new(&dylib);
780 let filename = file.file_name().unwrap().to_str().unwrap();
781 // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
782 let target_filename = {
783 let dash = filename.find('-').unwrap();
784 let dot = filename.find('.').unwrap();
790 builder.copy(&file, &dst.join(target_filename));
794 fn copy_lld_to_sysroot(builder: &Builder,
795 target_compiler: Compiler,
796 lld_install_root: &Path) {
797 let target = target_compiler.host;
799 let dst = builder.sysroot_libdir(target_compiler, target)
803 t!(fs::create_dir_all(&dst));
805 let src_exe = exe("lld", &target);
806 let dst_exe = exe("rust-lld", &target);
807 // we prepend this bin directory to the user PATH when linking Rust binaries. To
808 // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
809 builder.copy(&lld_install_root.join("bin").join(&src_exe), &dst.join(&dst_exe));
812 /// Cargo's output path for the standard library in a given stage, compiled
813 /// by a particular compiler for the specified target.
814 pub fn libstd_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
815 builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
818 /// Cargo's output path for libtest in a given stage, compiled by a particular
819 /// compiler for the specified target.
820 pub fn libtest_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
821 builder.cargo_out(compiler, Mode::Test, target).join(".libtest.stamp")
824 /// Cargo's output path for librustc in a given stage, compiled by a particular
825 /// compiler for the specified target.
826 pub fn librustc_stamp(builder: &Builder, compiler: Compiler, target: Interned<String>) -> PathBuf {
827 builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
830 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
831 /// compiler for the specified target and backend.
832 fn codegen_backend_stamp(builder: &Builder,
834 target: Interned<String>,
835 backend: Interned<String>) -> PathBuf {
836 builder.cargo_out(compiler, Mode::Codegen, target)
837 .join(format!(".librustc_codegen_llvm-{}.stamp", backend))
840 pub fn compiler_file(builder: &Builder,
842 target: Interned<String>,
843 file: &str) -> PathBuf {
844 let mut cmd = Command::new(compiler);
845 cmd.args(builder.cflags(target, GitRepo::Rustc));
846 cmd.arg(format!("-print-file-name={}", file));
847 let out = output(&mut cmd);
848 PathBuf::from(out.trim())
851 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
853 pub compiler: Compiler,
856 impl Step for Sysroot {
857 type Output = Interned<PathBuf>;
859 fn should_run(run: ShouldRun) -> ShouldRun {
863 /// Returns the sysroot for the `compiler` specified that *this build system
866 /// That is, the sysroot for the stage0 compiler is not what the compiler
867 /// thinks it is by default, but it's the same as the default for stages
869 fn run(self, builder: &Builder) -> Interned<PathBuf> {
870 let compiler = self.compiler;
871 let sysroot = if compiler.stage == 0 {
872 builder.out.join(&compiler.host).join("stage0-sysroot")
874 builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
876 let _ = fs::remove_dir_all(&sysroot);
877 t!(fs::create_dir_all(&sysroot));
878 INTERNER.intern_path(sysroot)
882 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
883 pub struct Assemble {
884 /// The compiler which we will produce in this step. Assemble itself will
885 /// take care of ensuring that the necessary prerequisites to do so exist,
886 /// that is, this target can be a stage2 compiler and Assemble will build
887 /// previous stages for you.
888 pub target_compiler: Compiler,
891 impl Step for Assemble {
892 type Output = Compiler;
894 fn should_run(run: ShouldRun) -> ShouldRun {
898 /// Prepare a new compiler from the artifacts in `stage`
900 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
901 /// must have been previously produced by the `stage - 1` builder.build
903 fn run(self, builder: &Builder) -> Compiler {
904 let target_compiler = self.target_compiler;
906 if target_compiler.stage == 0 {
907 assert_eq!(builder.config.build, target_compiler.host,
908 "Cannot obtain compiler for non-native build triple at stage 0");
909 // The stage 0 compiler for the build triple is always pre-built.
910 return target_compiler;
913 // Get the compiler that we'll use to bootstrap ourselves.
915 // Note that this is where the recursive nature of the bootstrap
916 // happens, as this will request the previous stage's compiler on
917 // downwards to stage 0.
919 // Also note that we're building a compiler for the host platform. We
920 // only assume that we can run `build` artifacts, which means that to
921 // produce some other architecture compiler we need to start from
922 // `build` to get there.
924 // FIXME: Perhaps we should download those libraries?
925 // It would make builds faster...
927 // FIXME: It may be faster if we build just a stage 1 compiler and then
928 // use that to bootstrap this compiler forward.
930 builder.compiler(target_compiler.stage - 1, builder.config.build);
932 // Build the libraries for this compiler to link to (i.e., the libraries
933 // it uses at runtime). NOTE: Crates the target compiler compiles don't
934 // link to these. (FIXME: Is that correct? It seems to be correct most
935 // of the time but I think we do link to these for stage2/bin compilers
936 // when not performing a full bootstrap).
937 builder.ensure(Rustc {
938 compiler: build_compiler,
939 target: target_compiler.host,
941 for &backend in builder.config.rust_codegen_backends.iter() {
942 builder.ensure(CodegenBackend {
943 compiler: build_compiler,
944 target: target_compiler.host,
949 let lld_install = if builder.config.lld_enabled {
950 Some(builder.ensure(native::Lld {
951 target: target_compiler.host,
957 let stage = target_compiler.stage;
958 let host = target_compiler.host;
959 builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
961 // Link in all dylibs to the libdir
962 let sysroot = builder.sysroot(target_compiler);
963 let sysroot_libdir = sysroot.join(libdir(&*host));
964 t!(fs::create_dir_all(&sysroot_libdir));
965 let src_libdir = builder.sysroot_libdir(build_compiler, host);
966 for f in builder.read_dir(&src_libdir) {
967 let filename = f.file_name().into_string().unwrap();
968 if is_dylib(&filename) {
969 builder.copy(&f.path(), &sysroot_libdir.join(&filename));
973 copy_codegen_backends_to_sysroot(builder,
976 if let Some(lld_install) = lld_install {
977 copy_lld_to_sysroot(builder, target_compiler, &lld_install);
980 dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
982 // Link the compiler binary itself into place
983 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
984 let rustc = out_dir.join(exe("rustc_binary", &*host));
985 let bindir = sysroot.join("bin");
986 t!(fs::create_dir_all(&bindir));
987 let compiler = builder.rustc(target_compiler);
988 let _ = fs::remove_file(&compiler);
989 builder.copy(&rustc, &compiler);
995 /// Link some files into a rustc sysroot.
997 /// For a particular stage this will link the file listed in `stamp` into the
998 /// `sysroot_dst` provided.
999 pub fn add_to_sysroot(builder: &Builder, sysroot_dst: &Path, stamp: &Path) {
1000 t!(fs::create_dir_all(&sysroot_dst));
1001 for path in builder.read_stamp_file(stamp) {
1002 builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
1006 pub fn run_cargo(builder: &Builder,
1007 cargo: &mut Command,
1012 if builder.config.dry_run {
1016 // `target_root_dir` looks like $dir/$target/release
1017 let target_root_dir = stamp.parent().unwrap();
1018 // `target_deps_dir` looks like $dir/$target/release/deps
1019 let target_deps_dir = target_root_dir.join("deps");
1020 // `host_root_dir` looks like $dir/release
1021 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
1022 .parent().unwrap() // chop off `$target`
1023 .join(target_root_dir.file_name().unwrap());
1025 // Spawn Cargo slurping up its JSON output. We'll start building up the
1026 // `deps` array of all files it generated along with a `toplevel` array of
1027 // files we need to probe for later.
1028 let mut deps = Vec::new();
1029 let mut toplevel = Vec::new();
1030 let ok = stream_cargo(builder, cargo, &mut |msg| {
1031 let filenames = match msg {
1032 CargoMessage::CompilerArtifact { filenames, .. } => filenames,
1035 for filename in filenames {
1036 // Skip files like executables
1037 if !filename.ends_with(".rlib") &&
1038 !filename.ends_with(".lib") &&
1039 !is_dylib(&filename) &&
1040 !(is_check && filename.ends_with(".rmeta")) {
1044 let filename = Path::new(&*filename);
1046 // If this was an output file in the "host dir" we don't actually
1047 // worry about it, it's not relevant for us.
1048 if filename.starts_with(&host_root_dir) {
1052 // If this was output in the `deps` dir then this is a precise file
1053 // name (hash included) so we start tracking it.
1054 if filename.starts_with(&target_deps_dir) {
1055 deps.push(filename.to_path_buf());
1059 // Otherwise this was a "top level artifact" which right now doesn't
1060 // have a hash in the name, but there's a version of this file in
1061 // the `deps` folder which *does* have a hash in the name. That's
1062 // the one we'll want to we'll probe for it later.
1064 // We do not use `Path::file_stem` or `Path::extension` here,
1065 // because some generated files may have multiple extensions e.g.
1066 // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1067 // split the file name by the last extension (`.lib`) while we need
1068 // to split by all extensions (`.dll.lib`).
1069 let expected_len = t!(filename.metadata()).len();
1070 let filename = filename.file_name().unwrap().to_str().unwrap();
1071 let mut parts = filename.splitn(2, '.');
1072 let file_stem = parts.next().unwrap().to_owned();
1073 let extension = parts.next().unwrap().to_owned();
1075 toplevel.push((file_stem, extension, expected_len));
1083 // Ok now we need to actually find all the files listed in `toplevel`. We've
1084 // got a list of prefix/extensions and we basically just need to find the
1085 // most recent file in the `deps` folder corresponding to each one.
1086 let contents = t!(target_deps_dir.read_dir())
1088 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1089 .collect::<Vec<_>>();
1090 for (prefix, extension, expected_len) in toplevel {
1091 let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1092 filename.starts_with(&prefix[..]) &&
1093 filename[prefix.len()..].starts_with("-") &&
1094 filename.ends_with(&extension[..]) &&
1095 meta.len() == expected_len
1097 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1098 FileTime::from_last_modification_time(metadata)
1100 let path_to_add = match max {
1101 Some(triple) => triple.0.to_str().unwrap(),
1102 None => panic!("no output generated for {:?} {:?}", prefix, extension),
1104 if is_dylib(path_to_add) {
1105 let candidate = format!("{}.lib", path_to_add);
1106 let candidate = PathBuf::from(candidate);
1107 if candidate.exists() {
1108 deps.push(candidate);
1111 deps.push(path_to_add.into());
1114 // Now we want to update the contents of the stamp file, if necessary. First
1115 // we read off the previous contents along with its mtime. If our new
1116 // contents (the list of files to copy) is different or if any dep's mtime
1117 // is newer then we rewrite the stamp file.
1119 let stamp_contents = fs::read(stamp);
1120 let stamp_mtime = mtime(&stamp);
1121 let mut new_contents = Vec::new();
1123 let mut max_path = None;
1124 for dep in deps.iter() {
1125 let mtime = mtime(dep);
1126 if Some(mtime) > max {
1128 max_path = Some(dep.clone());
1130 new_contents.extend(dep.to_str().unwrap().as_bytes());
1131 new_contents.extend(b"\0");
1133 let max = max.unwrap();
1134 let max_path = max_path.unwrap();
1135 let contents_equal = stamp_contents
1136 .map(|contents| contents == new_contents)
1137 .unwrap_or_default();
1138 if contents_equal && max <= stamp_mtime {
1139 builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}",
1140 stamp, max, stamp_mtime));
1143 if max > stamp_mtime {
1144 builder.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1146 builder.verbose(&format!("updating {:?} as deps changed", stamp));
1148 t!(fs::write(&stamp, &new_contents));
1152 pub fn stream_cargo(
1154 cargo: &mut Command,
1155 cb: &mut dyn FnMut(CargoMessage),
1157 if builder.config.dry_run {
1160 // Instruct Cargo to give us json messages on stdout, critically leaving
1161 // stderr as piped so we can get those pretty colors.
1162 cargo.arg("--message-format").arg("json")
1163 .stdout(Stdio::piped());
1165 builder.verbose(&format!("running: {:?}", cargo));
1166 let mut child = match cargo.spawn() {
1168 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1171 // Spawn Cargo slurping up its JSON output. We'll start building up the
1172 // `deps` array of all files it generated along with a `toplevel` array of
1173 // files we need to probe for later.
1174 let stdout = BufReader::new(child.stdout.take().unwrap());
1175 for line in stdout.lines() {
1176 let line = t!(line);
1177 match serde_json::from_str::<CargoMessage>(&line) {
1179 // If this was informational, just print it out and continue
1180 Err(_) => println!("{}", line)
1184 // Make sure Cargo actually succeeded after we read all of its stdout.
1185 let status = t!(child.wait());
1186 if !status.success() {
1187 eprintln!("command did not execute successfully: {:?}\n\
1188 expected success, got: {}",
1195 #[derive(Deserialize)]
1196 #[serde(tag = "reason", rename_all = "kebab-case")]
1197 pub enum CargoMessage<'a> {
1199 package_id: Cow<'a, str>,
1200 features: Vec<Cow<'a, str>>,
1201 filenames: Vec<Cow<'a, str>>,
1203 BuildScriptExecuted {
1204 package_id: Cow<'a, str>,