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, t, up_to_date};
19 use filetime::FileTime;
20 use serde::Deserialize;
24 use crate::util::{exe, is_dylib};
25 use crate::{Compiler, Mode, GitRepo};
28 use crate::cache::{INTERNER, Interned};
29 use crate::builder::{Step, RunConfig, ShouldRun, Builder};
31 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
33 pub target: Interned<String>,
34 pub compiler: Compiler,
39 const DEFAULT: bool = true;
41 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
45 fn make_run(run: RunConfig<'_>) {
46 run.builder.ensure(Std {
47 compiler: run.builder.compiler(run.builder.top_stage, run.host),
52 /// Builds the standard library.
54 /// This will build the standard library for a particular stage of the build
55 /// using the `compiler` targeting the `target` architecture. The artifacts
56 /// created will also be linked into the sysroot directory.
57 fn run(self, builder: &Builder<'_>) {
58 let target = self.target;
59 let compiler = self.compiler;
61 if builder.config.keep_stage.contains(&compiler.stage) {
62 builder.info("Warning: Using a potentially old libstd. This may not behave well.");
63 builder.ensure(StdLink {
65 target_compiler: compiler,
71 builder.ensure(StartupObjects { compiler, target });
73 if builder.force_use_stage1(compiler, target) {
74 let from = builder.compiler(1, builder.config.build);
79 builder.info(&format!("Uplifting stage1 std ({} -> {})", from.host, target));
81 // Even if we're not building std this stage, the new sysroot must
82 // still contain the third party objects needed by various targets.
83 copy_third_party_objects(builder, &compiler, target);
85 builder.ensure(StdLink {
87 target_compiler: compiler,
93 copy_third_party_objects(builder, &compiler, target);
95 let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
96 std_cargo(builder, &compiler, target, &mut cargo);
98 let _folder = builder.fold_output(|| format!("stage{}-std", compiler.stage));
99 builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
100 &compiler.host, target));
103 &libstd_stamp(builder, compiler, target),
106 builder.ensure(StdLink {
107 compiler: builder.compiler(compiler.stage, builder.config.build),
108 target_compiler: compiler,
114 /// Copies third pary objects needed by various targets.
115 fn copy_third_party_objects(builder: &Builder<'_>, compiler: &Compiler, target: Interned<String>) {
116 let libdir = builder.sysroot_libdir(*compiler, target);
118 // Copies the crt(1,i,n).o startup objects
120 // Since musl supports fully static linking, we can cross link for it even
121 // with a glibc-targeting toolchain, given we have the appropriate startup
122 // files. As those shipped with glibc won't work, copy the ones provided by
123 // musl so we have them on linux-gnu hosts.
124 if target.contains("musl") {
125 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
127 &builder.musl_root(target).unwrap().join("lib").join(obj),
131 } else if target.ends_with("-wasi") {
132 for &obj in &["crt1.o"] {
134 &builder.wasi_root(target).unwrap().join("lib/wasm32-wasi").join(obj),
140 // Copies libunwind.a compiled to be linked wit x86_64-fortanix-unknown-sgx.
142 // This target needs to be linked to Fortanix's port of llvm's libunwind.
143 // libunwind requires support for rwlock and printing to stderr,
144 // which is provided by std for this target.
145 if target == "x86_64-fortanix-unknown-sgx" {
146 let src_path_env = "X86_FORTANIX_SGX_LIBS";
147 let obj = "libunwind.a";
148 let src = env::var(src_path_env).expect(&format!("{} not found in env", src_path_env));
149 let src = Path::new(&src).join(obj);
150 builder.copy(&src, &libdir.join(obj));
154 /// Configure cargo to compile the standard library, adding appropriate env vars
156 pub fn std_cargo(builder: &Builder<'_>,
158 target: Interned<String>,
159 cargo: &mut Command) {
160 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
161 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
164 if builder.no_std(target) == Some(true) {
165 // for no-std targets we only compile a few no_std crates
167 .args(&["-p", "alloc"])
168 .arg("--manifest-path")
169 .arg(builder.src.join("src/liballoc/Cargo.toml"))
171 .arg("compiler-builtins-mem compiler-builtins-c");
173 let features = builder.std_features();
175 if compiler.stage != 0 && builder.config.sanitizers {
176 // This variable is used by the sanitizer runtime crates, e.g.
177 // rustc_lsan, to build the sanitizer runtime from C code
178 // When this variable is missing, those crates won't compile the C code,
179 // so we don't set this variable during stage0 where llvm-config is
181 // We also only build the runtimes when --enable-sanitizers (or its
182 // config.toml equivalent) is used
183 let llvm_config = builder.ensure(native::Llvm {
184 target: builder.config.build,
187 cargo.env("LLVM_CONFIG", llvm_config);
190 cargo.arg("--features").arg(features)
191 .arg("--manifest-path")
192 .arg(builder.src.join("src/libstd/Cargo.toml"));
194 if target.contains("musl") {
195 if let Some(p) = builder.musl_root(target) {
196 cargo.env("MUSL_ROOT", p);
200 if target.ends_with("-wasi") {
201 if let Some(p) = builder.wasi_root(target) {
202 cargo.env("WASI_ROOT", p);
208 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
210 pub compiler: Compiler,
211 pub target_compiler: Compiler,
212 pub target: Interned<String>,
215 impl Step for StdLink {
218 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
222 /// Link all libstd rlibs/dylibs into the sysroot location.
224 /// Links those artifacts generated by `compiler` to the `stage` compiler's
225 /// sysroot for the specified `host` and `target`.
227 /// Note that this assumes that `compiler` has already generated the libstd
228 /// libraries for `target`, and this method will find them in the relevant
229 /// output directory.
230 fn run(self, builder: &Builder<'_>) {
231 let compiler = self.compiler;
232 let target_compiler = self.target_compiler;
233 let target = self.target;
234 builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
235 target_compiler.stage,
238 target_compiler.host,
240 let libdir = builder.sysroot_libdir(target_compiler, target);
241 let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
242 add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
244 if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
245 // The sanitizers are only built in stage1 or above, so the dylibs will
246 // be missing in stage0 and causes panic. See the `std()` function above
247 // for reason why the sanitizers are not built in stage0.
248 copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
251 builder.cargo(target_compiler, Mode::ToolStd, target, "clean");
255 fn copy_apple_sanitizer_dylibs(
256 builder: &Builder<'_>,
261 for &sanitizer in &["asan", "tsan"] {
262 let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
263 let mut src_path = native_dir.join(sanitizer);
264 src_path.push("build");
265 src_path.push("lib");
266 src_path.push("darwin");
267 src_path.push(&filename);
268 builder.copy(&src_path, &into.join(filename));
272 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
273 pub struct StartupObjects {
274 pub compiler: Compiler,
275 pub target: Interned<String>,
278 impl Step for StartupObjects {
281 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
282 run.path("src/rtstartup")
285 fn make_run(run: RunConfig<'_>) {
286 run.builder.ensure(StartupObjects {
287 compiler: run.builder.compiler(run.builder.top_stage, run.host),
292 /// Builds and prepare startup objects like rsbegin.o and rsend.o
294 /// These are primarily used on Windows right now for linking executables/dlls.
295 /// They don't require any library support as they're just plain old object
296 /// files, so we just use the nightly snapshot compiler to always build them (as
297 /// no other compilers are guaranteed to be available).
298 fn run(self, builder: &Builder<'_>) {
299 let for_compiler = self.compiler;
300 let target = self.target;
301 if !target.contains("pc-windows-gnu") {
305 let src_dir = &builder.src.join("src/rtstartup");
306 let dst_dir = &builder.native_dir(target).join("rtstartup");
307 let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
308 t!(fs::create_dir_all(dst_dir));
310 for file in &["rsbegin", "rsend"] {
311 let src_file = &src_dir.join(file.to_string() + ".rs");
312 let dst_file = &dst_dir.join(file.to_string() + ".o");
313 if !up_to_date(src_file, dst_file) {
314 let mut cmd = Command::new(&builder.initial_rustc);
315 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
316 .arg("--cfg").arg("stage0")
317 .arg("--target").arg(target)
319 .arg("-o").arg(dst_file)
323 builder.copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
326 for obj in ["crt2.o", "dllcrt2.o"].iter() {
327 let src = compiler_file(builder,
331 builder.copy(&src, &sysroot_dir.join(obj));
336 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
338 pub target: Interned<String>,
339 pub compiler: Compiler,
344 const DEFAULT: bool = true;
346 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
347 run.all_krates("test")
350 fn make_run(run: RunConfig<'_>) {
351 run.builder.ensure(Test {
352 compiler: run.builder.compiler(run.builder.top_stage, run.host),
359 /// This will build libtest and supporting libraries for a particular stage of
360 /// the build using the `compiler` targeting the `target` architecture. The
361 /// artifacts created will also be linked into the sysroot directory.
362 fn run(self, builder: &Builder<'_>) {
363 let target = self.target;
364 let compiler = self.compiler;
366 builder.ensure(Std { compiler, target });
368 if builder.config.keep_stage.contains(&compiler.stage) {
369 builder.info("Warning: Using a potentially old libtest. This may not behave well.");
370 builder.ensure(TestLink {
372 target_compiler: compiler,
378 if builder.force_use_stage1(compiler, target) {
379 builder.ensure(Test {
380 compiler: builder.compiler(1, builder.config.build),
384 &format!("Uplifting stage1 test ({} -> {})", builder.config.build, target));
385 builder.ensure(TestLink {
386 compiler: builder.compiler(1, builder.config.build),
387 target_compiler: compiler,
393 let mut cargo = builder.cargo(compiler, Mode::Test, target, "build");
394 test_cargo(builder, &compiler, target, &mut cargo);
396 let _folder = builder.fold_output(|| format!("stage{}-test", compiler.stage));
397 builder.info(&format!("Building stage{} test artifacts ({} -> {})", compiler.stage,
398 &compiler.host, target));
401 &libtest_stamp(builder, compiler, target),
404 builder.ensure(TestLink {
405 compiler: builder.compiler(compiler.stage, builder.config.build),
406 target_compiler: compiler,
412 /// Same as `std_cargo`, but for libtest
413 pub fn test_cargo(builder: &Builder<'_>,
414 _compiler: &Compiler,
415 _target: Interned<String>,
416 cargo: &mut Command) {
417 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
418 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
420 cargo.arg("--manifest-path")
421 .arg(builder.src.join("src/libtest/Cargo.toml"));
424 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
425 pub struct TestLink {
426 pub compiler: Compiler,
427 pub target_compiler: Compiler,
428 pub target: Interned<String>,
431 impl Step for TestLink {
434 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
438 /// Same as `std_link`, only for libtest
439 fn run(self, builder: &Builder<'_>) {
440 let compiler = self.compiler;
441 let target_compiler = self.target_compiler;
442 let target = self.target;
443 builder.info(&format!("Copying stage{} test from stage{} ({} -> {} / {})",
444 target_compiler.stage,
447 target_compiler.host,
451 &builder.sysroot_libdir(target_compiler, target),
452 &builder.sysroot_libdir(target_compiler, compiler.host),
453 &libtest_stamp(builder, compiler, target)
456 builder.cargo(target_compiler, Mode::ToolTest, target, "clean");
460 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
462 pub target: Interned<String>,
463 pub compiler: Compiler,
466 impl Step for Rustc {
468 const ONLY_HOSTS: bool = true;
469 const DEFAULT: bool = true;
471 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
472 run.all_krates("rustc-main")
475 fn make_run(run: RunConfig<'_>) {
476 run.builder.ensure(Rustc {
477 compiler: run.builder.compiler(run.builder.top_stage, run.host),
482 /// Builds the compiler.
484 /// This will build the compiler for a particular stage of the build using
485 /// the `compiler` targeting the `target` architecture. The artifacts
486 /// created will also be linked into the sysroot directory.
487 fn run(self, builder: &Builder<'_>) {
488 let compiler = self.compiler;
489 let target = self.target;
491 builder.ensure(Test { compiler, target });
493 if builder.config.keep_stage.contains(&compiler.stage) {
494 builder.info("Warning: Using a potentially old librustc. This may not behave well.");
495 builder.ensure(RustcLink {
497 target_compiler: compiler,
503 if builder.force_use_stage1(compiler, target) {
504 builder.ensure(Rustc {
505 compiler: builder.compiler(1, builder.config.build),
508 builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
509 builder.config.build, target));
510 builder.ensure(RustcLink {
511 compiler: builder.compiler(1, builder.config.build),
512 target_compiler: compiler,
518 // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
519 builder.ensure(Test {
520 compiler: builder.compiler(self.compiler.stage, builder.config.build),
521 target: builder.config.build,
524 let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
525 rustc_cargo(builder, &mut cargo);
527 let _folder = builder.fold_output(|| format!("stage{}-rustc", compiler.stage));
528 builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
529 compiler.stage, &compiler.host, target));
532 &librustc_stamp(builder, compiler, target),
535 builder.ensure(RustcLink {
536 compiler: builder.compiler(compiler.stage, builder.config.build),
537 target_compiler: compiler,
543 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Command) {
544 cargo.arg("--features").arg(builder.rustc_features())
545 .arg("--manifest-path")
546 .arg(builder.src.join("src/rustc/Cargo.toml"));
547 rustc_cargo_env(builder, cargo);
550 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Command) {
551 // Set some configuration variables picked up by build scripts and
552 // the compiler alike
553 cargo.env("CFG_RELEASE", builder.rust_release())
554 .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
555 .env("CFG_VERSION", builder.rust_version())
556 .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default())
557 .env("CFG_CODEGEN_BACKENDS_DIR", &builder.config.rust_codegen_backends_dir);
559 let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
560 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
562 // If we're not building a compiler with debugging information then remove
563 // these two env vars which would be set otherwise.
564 if builder.config.rust_debuginfo_only_std {
565 cargo.env_remove("RUSTC_DEBUGINFO");
566 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
569 if let Some(ref ver_date) = builder.rust_info.commit_date() {
570 cargo.env("CFG_VER_DATE", ver_date);
572 if let Some(ref ver_hash) = builder.rust_info.sha() {
573 cargo.env("CFG_VER_HASH", ver_hash);
575 if !builder.unstable_features() {
576 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
578 if let Some(ref s) = builder.config.rustc_default_linker {
579 cargo.env("CFG_DEFAULT_LINKER", s);
581 if builder.config.rustc_parallel {
582 cargo.env("RUSTC_PARALLEL_COMPILER", "1");
584 if builder.config.rust_verify_llvm_ir {
585 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
589 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
591 pub compiler: Compiler,
592 pub target_compiler: Compiler,
593 pub target: Interned<String>,
596 impl Step for RustcLink {
599 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
603 /// Same as `std_link`, only for librustc
604 fn run(self, builder: &Builder<'_>) {
605 let compiler = self.compiler;
606 let target_compiler = self.target_compiler;
607 let target = self.target;
608 builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
609 target_compiler.stage,
612 target_compiler.host,
616 &builder.sysroot_libdir(target_compiler, target),
617 &builder.sysroot_libdir(target_compiler, compiler.host),
618 &librustc_stamp(builder, compiler, target)
620 builder.cargo(target_compiler, Mode::ToolRustc, target, "clean");
624 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
625 pub struct CodegenBackend {
626 pub compiler: Compiler,
627 pub target: Interned<String>,
628 pub backend: Interned<String>,
631 impl Step for CodegenBackend {
633 const ONLY_HOSTS: bool = true;
634 const DEFAULT: bool = true;
636 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
637 run.all_krates("rustc_codegen_llvm")
640 fn make_run(run: RunConfig<'_>) {
641 let backend = run.builder.config.rust_codegen_backends.get(0);
642 let backend = backend.cloned().unwrap_or_else(|| {
643 INTERNER.intern_str("llvm")
645 run.builder.ensure(CodegenBackend {
646 compiler: run.builder.compiler(run.builder.top_stage, run.host),
652 fn run(self, builder: &Builder<'_>) {
653 let compiler = self.compiler;
654 let target = self.target;
655 let backend = self.backend;
657 builder.ensure(Rustc { compiler, target });
659 if builder.config.keep_stage.contains(&compiler.stage) {
660 builder.info("Warning: Using a potentially old codegen backend. \
661 This may not behave well.");
662 // Codegen backends are linked separately from this step today, so we don't do
667 if builder.force_use_stage1(compiler, target) {
668 builder.ensure(CodegenBackend {
669 compiler: builder.compiler(1, builder.config.build),
676 let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
678 let mut cargo = builder.cargo(compiler, Mode::Codegen, target, "build");
679 cargo.arg("--manifest-path")
680 .arg(builder.src.join("src/librustc_codegen_llvm/Cargo.toml"));
681 rustc_cargo_env(builder, &mut cargo);
683 let features = build_codegen_backend(&builder, &mut cargo, &compiler, target, backend);
685 let tmp_stamp = out_dir.join(".tmp.stamp");
687 let _folder = builder.fold_output(|| format!("stage{}-rustc_codegen_llvm", compiler.stage));
688 let files = run_cargo(builder,
689 cargo.arg("--features").arg(features),
692 if builder.config.dry_run {
695 let mut files = files.into_iter()
697 let filename = f.file_name().unwrap().to_str().unwrap();
698 is_dylib(filename) && filename.contains("rustc_codegen_llvm-")
700 let codegen_backend = match files.next() {
702 None => panic!("no dylibs built for codegen backend?"),
704 if let Some(f) = files.next() {
705 panic!("codegen backend built two dylibs:\n{}\n{}",
706 codegen_backend.display(),
709 let stamp = codegen_backend_stamp(builder, compiler, target, backend);
710 let codegen_backend = codegen_backend.to_str().unwrap();
711 t!(fs::write(&stamp, &codegen_backend));
715 pub fn build_codegen_backend(builder: &Builder<'_>,
718 target: Interned<String>,
719 backend: Interned<String>) -> String {
720 let mut features = String::new();
723 "llvm" | "emscripten" => {
724 // Build LLVM for our target. This will implicitly build the
725 // host LLVM if necessary.
726 let llvm_config = builder.ensure(native::Llvm {
728 emscripten: backend == "emscripten",
731 if backend == "emscripten" {
732 features.push_str(" emscripten");
735 builder.info(&format!("Building stage{} codegen artifacts ({} -> {}, {})",
736 compiler.stage, &compiler.host, target, backend));
738 // Pass down configuration from the LLVM build into the build of
739 // librustc_llvm and librustc_codegen_llvm.
740 if builder.is_rust_llvm(target) && backend != "emscripten" {
741 cargo.env("LLVM_RUSTLLVM", "1");
744 cargo.env("LLVM_CONFIG", &llvm_config);
745 if backend != "emscripten" {
746 let target_config = builder.config.target_config.get(&target);
747 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
748 cargo.env("CFG_LLVM_ROOT", s);
751 // Building with a static libstdc++ is only supported on linux right now,
752 // not for MSVC or macOS
753 if builder.config.llvm_static_stdcpp &&
754 !target.contains("freebsd") &&
755 !target.contains("windows") &&
756 !target.contains("apple") {
757 let file = compiler_file(builder,
758 builder.cxx(target).unwrap(),
761 cargo.env("LLVM_STATIC_STDCPP", file);
763 if builder.config.llvm_link_shared ||
764 (builder.config.llvm_thin_lto && backend != "emscripten")
766 cargo.env("LLVM_LINK_SHARED", "1");
768 if builder.config.llvm_use_libcxx {
769 cargo.env("LLVM_USE_LIBCXX", "1");
772 _ => panic!("unknown backend: {}", backend),
778 /// Creates the `codegen-backends` folder for a compiler that's about to be
779 /// assembled as a complete compiler.
781 /// This will take the codegen artifacts produced by `compiler` and link them
782 /// into an appropriate location for `target_compiler` to be a functional
784 fn copy_codegen_backends_to_sysroot(builder: &Builder<'_>,
786 target_compiler: Compiler) {
787 let target = target_compiler.host;
789 // Note that this step is different than all the other `*Link` steps in
790 // that it's not assembling a bunch of libraries but rather is primarily
791 // moving the codegen backend into place. The codegen backend of rustc is
792 // not linked into the main compiler by default but is rather dynamically
793 // selected at runtime for inclusion.
795 // Here we're looking for the output dylib of the `CodegenBackend` step and
796 // we're copying that into the `codegen-backends` folder.
797 let dst = builder.sysroot_codegen_backends(target_compiler);
798 t!(fs::create_dir_all(&dst));
800 if builder.config.dry_run {
804 for backend in builder.config.rust_codegen_backends.iter() {
805 let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
806 let dylib = t!(fs::read_to_string(&stamp));
807 let file = Path::new(&dylib);
808 let filename = file.file_name().unwrap().to_str().unwrap();
809 // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
810 let target_filename = {
811 let dash = filename.find('-').unwrap();
812 let dot = filename.find('.').unwrap();
818 builder.copy(&file, &dst.join(target_filename));
822 fn copy_lld_to_sysroot(builder: &Builder<'_>,
823 target_compiler: Compiler,
824 lld_install_root: &Path) {
825 let target = target_compiler.host;
827 let dst = builder.sysroot_libdir(target_compiler, target)
831 t!(fs::create_dir_all(&dst));
833 let src_exe = exe("lld", &target);
834 let dst_exe = exe("rust-lld", &target);
835 // we prepend this bin directory to the user PATH when linking Rust binaries. To
836 // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
837 builder.copy(&lld_install_root.join("bin").join(&src_exe), &dst.join(&dst_exe));
840 /// Cargo's output path for the standard library in a given stage, compiled
841 /// by a particular compiler for the specified target.
843 builder: &Builder<'_>,
845 target: Interned<String>,
847 builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
850 /// Cargo's output path for libtest in a given stage, compiled by a particular
851 /// compiler for the specified target.
852 pub fn libtest_stamp(
853 builder: &Builder<'_>,
855 target: Interned<String>,
857 builder.cargo_out(compiler, Mode::Test, target).join(".libtest.stamp")
860 /// Cargo's output path for librustc in a given stage, compiled by a particular
861 /// compiler for the specified target.
862 pub fn librustc_stamp(
863 builder: &Builder<'_>,
865 target: Interned<String>,
867 builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
870 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
871 /// compiler for the specified target and backend.
872 fn codegen_backend_stamp(builder: &Builder<'_>,
874 target: Interned<String>,
875 backend: Interned<String>) -> PathBuf {
876 builder.cargo_out(compiler, Mode::Codegen, target)
877 .join(format!(".librustc_codegen_llvm-{}.stamp", backend))
880 pub fn compiler_file(
881 builder: &Builder<'_>,
883 target: Interned<String>,
886 let mut cmd = Command::new(compiler);
887 cmd.args(builder.cflags(target, GitRepo::Rustc));
888 cmd.arg(format!("-print-file-name={}", file));
889 let out = output(&mut cmd);
890 PathBuf::from(out.trim())
893 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
895 pub compiler: Compiler,
898 impl Step for Sysroot {
899 type Output = Interned<PathBuf>;
901 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
905 /// Returns the sysroot for the `compiler` specified that *this build system
908 /// That is, the sysroot for the stage0 compiler is not what the compiler
909 /// thinks it is by default, but it's the same as the default for stages
911 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
912 let compiler = self.compiler;
913 let sysroot = if compiler.stage == 0 {
914 builder.out.join(&compiler.host).join("stage0-sysroot")
916 builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
918 let _ = fs::remove_dir_all(&sysroot);
919 t!(fs::create_dir_all(&sysroot));
920 INTERNER.intern_path(sysroot)
924 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
925 pub struct Assemble {
926 /// The compiler which we will produce in this step. Assemble itself will
927 /// take care of ensuring that the necessary prerequisites to do so exist,
928 /// that is, this target can be a stage2 compiler and Assemble will build
929 /// previous stages for you.
930 pub target_compiler: Compiler,
933 impl Step for Assemble {
934 type Output = Compiler;
936 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
940 /// Prepare a new compiler from the artifacts in `stage`
942 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
943 /// must have been previously produced by the `stage - 1` builder.build
945 fn run(self, builder: &Builder<'_>) -> Compiler {
946 let target_compiler = self.target_compiler;
948 if target_compiler.stage == 0 {
949 assert_eq!(builder.config.build, target_compiler.host,
950 "Cannot obtain compiler for non-native build triple at stage 0");
951 // The stage 0 compiler for the build triple is always pre-built.
952 return target_compiler;
955 // Get the compiler that we'll use to bootstrap ourselves.
957 // Note that this is where the recursive nature of the bootstrap
958 // happens, as this will request the previous stage's compiler on
959 // downwards to stage 0.
961 // Also note that we're building a compiler for the host platform. We
962 // only assume that we can run `build` artifacts, which means that to
963 // produce some other architecture compiler we need to start from
964 // `build` to get there.
966 // FIXME: Perhaps we should download those libraries?
967 // It would make builds faster...
969 // FIXME: It may be faster if we build just a stage 1 compiler and then
970 // use that to bootstrap this compiler forward.
972 builder.compiler(target_compiler.stage - 1, builder.config.build);
974 // Build the libraries for this compiler to link to (i.e., the libraries
975 // it uses at runtime). NOTE: Crates the target compiler compiles don't
976 // link to these. (FIXME: Is that correct? It seems to be correct most
977 // of the time but I think we do link to these for stage2/bin compilers
978 // when not performing a full bootstrap).
979 builder.ensure(Rustc {
980 compiler: build_compiler,
981 target: target_compiler.host,
983 for &backend in builder.config.rust_codegen_backends.iter() {
984 builder.ensure(CodegenBackend {
985 compiler: build_compiler,
986 target: target_compiler.host,
991 let lld_install = if builder.config.lld_enabled {
992 Some(builder.ensure(native::Lld {
993 target: target_compiler.host,
999 let stage = target_compiler.stage;
1000 let host = target_compiler.host;
1001 builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
1003 // Link in all dylibs to the libdir
1004 let sysroot = builder.sysroot(target_compiler);
1005 let rustc_libdir = builder.rustc_libdir(target_compiler);
1006 t!(fs::create_dir_all(&rustc_libdir));
1007 let src_libdir = builder.sysroot_libdir(build_compiler, host);
1008 for f in builder.read_dir(&src_libdir) {
1009 let filename = f.file_name().into_string().unwrap();
1010 if is_dylib(&filename) {
1011 builder.copy(&f.path(), &rustc_libdir.join(&filename));
1015 copy_codegen_backends_to_sysroot(builder,
1018 if let Some(lld_install) = lld_install {
1019 copy_lld_to_sysroot(builder, target_compiler, &lld_install);
1022 dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
1024 // Link the compiler binary itself into place
1025 let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
1026 let rustc = out_dir.join(exe("rustc_binary", &*host));
1027 let bindir = sysroot.join("bin");
1028 t!(fs::create_dir_all(&bindir));
1029 let compiler = builder.rustc(target_compiler);
1030 let _ = fs::remove_file(&compiler);
1031 builder.copy(&rustc, &compiler);
1037 /// Link some files into a rustc sysroot.
1039 /// For a particular stage this will link the file listed in `stamp` into the
1040 /// `sysroot_dst` provided.
1041 pub fn add_to_sysroot(
1042 builder: &Builder<'_>,
1044 sysroot_host_dst: &Path,
1047 t!(fs::create_dir_all(&sysroot_dst));
1048 t!(fs::create_dir_all(&sysroot_host_dst));
1049 for (path, host) in builder.read_stamp_file(stamp) {
1051 builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
1053 builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
1058 pub fn run_cargo(builder: &Builder<'_>,
1059 cargo: &mut Command,
1064 if builder.config.dry_run {
1068 // `target_root_dir` looks like $dir/$target/release
1069 let target_root_dir = stamp.parent().unwrap();
1070 // `target_deps_dir` looks like $dir/$target/release/deps
1071 let target_deps_dir = target_root_dir.join("deps");
1072 // `host_root_dir` looks like $dir/release
1073 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
1074 .parent().unwrap() // chop off `$target`
1075 .join(target_root_dir.file_name().unwrap());
1077 // Spawn Cargo slurping up its JSON output. We'll start building up the
1078 // `deps` array of all files it generated along with a `toplevel` array of
1079 // files we need to probe for later.
1080 let mut deps = Vec::new();
1081 let mut toplevel = Vec::new();
1082 let ok = stream_cargo(builder, cargo, &mut |msg| {
1083 let (filenames, crate_types) = match msg {
1084 CargoMessage::CompilerArtifact {
1086 target: CargoTarget {
1090 } => (filenames, crate_types),
1093 for filename in filenames {
1094 // Skip files like executables
1095 if !filename.ends_with(".rlib") &&
1096 !filename.ends_with(".lib") &&
1097 !is_dylib(&filename) &&
1098 !(is_check && filename.ends_with(".rmeta")) {
1102 let filename = Path::new(&*filename);
1104 // If this was an output file in the "host dir" we don't actually
1105 // worry about it, it's not relevant for us
1106 if filename.starts_with(&host_root_dir) {
1107 // Unless it's a proc macro used in the compiler
1108 if crate_types.iter().any(|t| t == "proc-macro") {
1109 deps.push((filename.to_path_buf(), true));
1114 // If this was output in the `deps` dir then this is a precise file
1115 // name (hash included) so we start tracking it.
1116 if filename.starts_with(&target_deps_dir) {
1117 deps.push((filename.to_path_buf(), false));
1121 // Otherwise this was a "top level artifact" which right now doesn't
1122 // have a hash in the name, but there's a version of this file in
1123 // the `deps` folder which *does* have a hash in the name. That's
1124 // the one we'll want to we'll probe for it later.
1126 // We do not use `Path::file_stem` or `Path::extension` here,
1127 // because some generated files may have multiple extensions e.g.
1128 // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1129 // split the file name by the last extension (`.lib`) while we need
1130 // to split by all extensions (`.dll.lib`).
1131 let expected_len = t!(filename.metadata()).len();
1132 let filename = filename.file_name().unwrap().to_str().unwrap();
1133 let mut parts = filename.splitn(2, '.');
1134 let file_stem = parts.next().unwrap().to_owned();
1135 let extension = parts.next().unwrap().to_owned();
1137 toplevel.push((file_stem, extension, expected_len));
1145 // Ok now we need to actually find all the files listed in `toplevel`. We've
1146 // got a list of prefix/extensions and we basically just need to find the
1147 // most recent file in the `deps` folder corresponding to each one.
1148 let contents = t!(target_deps_dir.read_dir())
1150 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1151 .collect::<Vec<_>>();
1152 for (prefix, extension, expected_len) in toplevel {
1153 let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1154 filename.starts_with(&prefix[..]) &&
1155 filename[prefix.len()..].starts_with("-") &&
1156 filename.ends_with(&extension[..]) &&
1157 meta.len() == expected_len
1159 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1160 FileTime::from_last_modification_time(metadata)
1162 let path_to_add = match max {
1163 Some(triple) => triple.0.to_str().unwrap(),
1164 None => panic!("no output generated for {:?} {:?}", prefix, extension),
1166 if is_dylib(path_to_add) {
1167 let candidate = format!("{}.lib", path_to_add);
1168 let candidate = PathBuf::from(candidate);
1169 if candidate.exists() {
1170 deps.push((candidate, false));
1173 deps.push((path_to_add.into(), false));
1176 // Now we want to update the contents of the stamp file, if necessary. First
1177 // we read off the previous contents along with its mtime. If our new
1178 // contents (the list of files to copy) is different or if any dep's mtime
1179 // is newer then we rewrite the stamp file.
1181 let stamp_contents = fs::read(stamp);
1182 let stamp_mtime = mtime(&stamp);
1183 let mut new_contents = Vec::new();
1185 let mut max_path = None;
1186 for (dep, proc_macro) in deps.iter() {
1187 let mtime = mtime(dep);
1188 if Some(mtime) > max {
1190 max_path = Some(dep.clone());
1192 new_contents.extend(if *proc_macro { b"h" } else { b"t" });
1193 new_contents.extend(dep.to_str().unwrap().as_bytes());
1194 new_contents.extend(b"\0");
1196 let max = max.unwrap();
1197 let max_path = max_path.unwrap();
1198 let contents_equal = stamp_contents
1199 .map(|contents| contents == new_contents)
1200 .unwrap_or_default();
1201 if contents_equal && max <= stamp_mtime {
1202 builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}",
1203 stamp, max, stamp_mtime));
1204 return deps.into_iter().map(|(d, _)| d).collect()
1206 if max > stamp_mtime {
1207 builder.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1209 builder.verbose(&format!("updating {:?} as deps changed", stamp));
1211 t!(fs::write(&stamp, &new_contents));
1212 deps.into_iter().map(|(d, _)| d).collect()
1215 pub fn stream_cargo(
1216 builder: &Builder<'_>,
1217 cargo: &mut Command,
1218 cb: &mut dyn FnMut(CargoMessage<'_>),
1220 if builder.config.dry_run {
1223 // Instruct Cargo to give us json messages on stdout, critically leaving
1224 // stderr as piped so we can get those pretty colors.
1225 cargo.arg("--message-format").arg("json")
1226 .stdout(Stdio::piped());
1228 builder.verbose(&format!("running: {:?}", cargo));
1229 let mut child = match cargo.spawn() {
1231 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1234 // Spawn Cargo slurping up its JSON output. We'll start building up the
1235 // `deps` array of all files it generated along with a `toplevel` array of
1236 // files we need to probe for later.
1237 let stdout = BufReader::new(child.stdout.take().unwrap());
1238 for line in stdout.lines() {
1239 let line = t!(line);
1240 match serde_json::from_str::<CargoMessage<'_>>(&line) {
1242 // If this was informational, just print it out and continue
1243 Err(_) => println!("{}", line)
1247 // Make sure Cargo actually succeeded after we read all of its stdout.
1248 let status = t!(child.wait());
1249 if !status.success() {
1250 eprintln!("command did not execute successfully: {:?}\n\
1251 expected success, got: {}",
1258 #[derive(Deserialize)]
1259 pub struct CargoTarget<'a> {
1260 crate_types: Vec<Cow<'a, str>>,
1263 #[derive(Deserialize)]
1264 #[serde(tag = "reason", rename_all = "kebab-case")]
1265 pub enum CargoMessage<'a> {
1267 package_id: Cow<'a, str>,
1268 features: Vec<Cow<'a, str>>,
1269 filenames: Vec<Cow<'a, str>>,
1270 target: CargoTarget<'a>,
1272 BuildScriptExecuted {
1273 package_id: Cow<'a, str>,