]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Fix some linking of LLVM's dynamic library
[rust.git] / src / bootstrap / compile.rs
1 //! Implementation of compiling various phases of the compiler and standard
2 //! library.
3 //!
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.
8
9 use std::borrow::Cow;
10 use std::env;
11 use std::fs;
12 use std::io::BufReader;
13 use std::io::prelude::*;
14 use std::path::{Path, PathBuf};
15 use std::process::{Command, Stdio, exit};
16 use std::str;
17
18 use build_helper::{output, t, up_to_date};
19 use filetime::FileTime;
20 use serde::Deserialize;
21 use serde_json;
22
23 use crate::dist;
24 use crate::builder::Cargo;
25 use crate::util::{exe, is_dylib};
26 use crate::{Compiler, Mode, GitRepo};
27 use crate::native;
28
29 use crate::cache::{INTERNER, Interned};
30 use crate::builder::{Step, RunConfig, ShouldRun, Builder, Kind};
31
32 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
33 pub struct Std {
34     pub target: Interned<String>,
35     pub compiler: Compiler,
36 }
37
38 impl Step for Std {
39     type Output = ();
40     const DEFAULT: bool = true;
41
42     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
43         run.all_krates("test")
44     }
45
46     fn make_run(run: RunConfig<'_>) {
47         run.builder.ensure(Std {
48             compiler: run.builder.compiler(run.builder.top_stage, run.host),
49             target: run.target,
50         });
51     }
52
53     /// Builds the standard library.
54     ///
55     /// This will build the standard library for a particular stage of the build
56     /// using the `compiler` targeting the `target` architecture. The artifacts
57     /// created will also be linked into the sysroot directory.
58     fn run(self, builder: &Builder<'_>) {
59         let target = self.target;
60         let compiler = self.compiler;
61
62         if builder.config.keep_stage.contains(&compiler.stage) {
63             builder.info("Warning: Using a potentially old libstd. This may not behave well.");
64             builder.ensure(StdLink {
65                 compiler,
66                 target_compiler: compiler,
67                 target,
68             });
69             return;
70         }
71
72         let mut target_deps = builder.ensure(StartupObjects { compiler, target });
73
74         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
75         if compiler_to_use != compiler {
76             builder.ensure(Std {
77                 compiler: compiler_to_use,
78                 target,
79             });
80             builder.info(&format!("Uplifting stage1 std ({} -> {})", compiler_to_use.host, target));
81
82             // Even if we're not building std this stage, the new sysroot must
83             // still contain the third party objects needed by various targets.
84             copy_third_party_objects(builder, &compiler, target);
85
86             builder.ensure(StdLink {
87                 compiler: compiler_to_use,
88                 target_compiler: compiler,
89                 target,
90             });
91             return;
92         }
93
94         target_deps.extend(copy_third_party_objects(builder, &compiler, target).into_iter());
95
96         let mut cargo = builder.cargo(compiler, Mode::Std, target, "build");
97         std_cargo(builder, &compiler, target, &mut cargo);
98
99         builder.info(&format!("Building stage{} std artifacts ({} -> {})", compiler.stage,
100                 &compiler.host, target));
101         run_cargo(builder,
102                   cargo,
103                   vec![],
104                   &libstd_stamp(builder, compiler, target),
105                   target_deps,
106                   false);
107
108         builder.ensure(StdLink {
109             compiler: builder.compiler(compiler.stage, builder.config.build),
110             target_compiler: compiler,
111             target,
112         });
113     }
114 }
115
116 /// Copies third party objects needed by various targets.
117 fn copy_third_party_objects(builder: &Builder<'_>, compiler: &Compiler, target: Interned<String>)
118     -> Vec<PathBuf>
119 {
120     let libdir = builder.sysroot_libdir(*compiler, target);
121
122     let mut target_deps = vec![];
123
124     let mut copy_and_stamp = |sourcedir: &Path, name: &str| {
125         let target = libdir.join(name);
126         builder.copy(
127             &sourcedir.join(name),
128             &target,
129         );
130         target_deps.push(target);
131     };
132
133     // Copies the crt(1,i,n).o startup objects
134     //
135     // Since musl supports fully static linking, we can cross link for it even
136     // with a glibc-targeting toolchain, given we have the appropriate startup
137     // files. As those shipped with glibc won't work, copy the ones provided by
138     // musl so we have them on linux-gnu hosts.
139     if target.contains("musl") {
140         let srcdir = builder.musl_root(target).unwrap().join("lib");
141         for &obj in &["crt1.o", "crti.o", "crtn.o"] {
142             copy_and_stamp(&srcdir, obj);
143         }
144     } else if target.ends_with("-wasi") {
145         let srcdir = builder.wasi_root(target).unwrap().join("lib/wasm32-wasi");
146         copy_and_stamp(&srcdir, "crt1.o");
147     }
148
149     // Copies libunwind.a compiled to be linked wit x86_64-fortanix-unknown-sgx.
150     //
151     // This target needs to be linked to Fortanix's port of llvm's libunwind.
152     // libunwind requires support for rwlock and printing to stderr,
153     // which is provided by std for this target.
154     if target == "x86_64-fortanix-unknown-sgx" {
155         let src_path_env = "X86_FORTANIX_SGX_LIBS";
156         let src = env::var(src_path_env).expect(&format!("{} not found in env", src_path_env));
157         copy_and_stamp(Path::new(&src), "libunwind.a");
158     }
159
160     target_deps
161 }
162
163 /// Configure cargo to compile the standard library, adding appropriate env vars
164 /// and such.
165 pub fn std_cargo(builder: &Builder<'_>,
166                  compiler: &Compiler,
167                  target: Interned<String>,
168                  cargo: &mut Cargo) {
169     if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
170         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
171     }
172
173     // Determine if we're going to compile in optimized C intrinsics to
174     // the `compiler-builtins` crate. These intrinsics live in LLVM's
175     // `compiler-rt` repository, but our `src/llvm-project` submodule isn't
176     // always checked out, so we need to conditionally look for this. (e.g. if
177     // an external LLVM is used we skip the LLVM submodule checkout).
178     //
179     // Note that this shouldn't affect the correctness of `compiler-builtins`,
180     // but only its speed. Some intrinsics in C haven't been translated to Rust
181     // yet but that's pretty rare. Other intrinsics have optimized
182     // implementations in C which have only had slower versions ported to Rust,
183     // so we favor the C version where we can, but it's not critical.
184     //
185     // If `compiler-rt` is available ensure that the `c` feature of the
186     // `compiler-builtins` crate is enabled and it's configured to learn where
187     // `compiler-rt` is located.
188     let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt");
189     let compiler_builtins_c_feature = if compiler_builtins_root.exists() {
190         cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root);
191         " compiler-builtins-c".to_string()
192     } else {
193         String::new()
194     };
195
196     if builder.no_std(target) == Some(true) {
197         let mut features = "compiler-builtins-mem".to_string();
198         features.push_str(&compiler_builtins_c_feature);
199
200         // for no-std targets we only compile a few no_std crates
201         cargo
202             .args(&["-p", "alloc"])
203             .arg("--manifest-path")
204             .arg(builder.src.join("src/liballoc/Cargo.toml"))
205             .arg("--features")
206             .arg("compiler-builtins-mem compiler-builtins-c");
207     } else {
208         let mut features = builder.std_features();
209         features.push_str(&compiler_builtins_c_feature);
210
211         if compiler.stage != 0 && builder.config.sanitizers {
212             // This variable is used by the sanitizer runtime crates, e.g.
213             // rustc_lsan, to build the sanitizer runtime from C code
214             // When this variable is missing, those crates won't compile the C code,
215             // so we don't set this variable during stage0 where llvm-config is
216             // missing
217             // We also only build the runtimes when --enable-sanitizers (or its
218             // config.toml equivalent) is used
219             let llvm_config = builder.ensure(native::Llvm {
220                 target: builder.config.build,
221             });
222             cargo.env("LLVM_CONFIG", llvm_config);
223             cargo.env("RUSTC_BUILD_SANITIZERS", "1");
224         }
225
226         cargo.arg("--features").arg(features)
227             .arg("--manifest-path")
228             .arg(builder.src.join("src/libtest/Cargo.toml"));
229
230         // Help the libc crate compile by assisting it in finding various
231         // sysroot native libraries.
232         if target.contains("musl") {
233             if let Some(p) = builder.musl_root(target) {
234                 let root = format!("native={}/lib", p.to_str().unwrap());
235                 cargo.rustflag("-L").rustflag(&root);
236             }
237         }
238
239         if target.ends_with("-wasi") {
240             if let Some(p) = builder.wasi_root(target) {
241                 let root = format!("native={}/lib/wasm32-wasi", p.to_str().unwrap());
242                 cargo.rustflag("-L").rustflag(&root);
243             }
244         }
245     }
246 }
247
248 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
249 struct StdLink {
250     pub compiler: Compiler,
251     pub target_compiler: Compiler,
252     pub target: Interned<String>,
253 }
254
255 impl Step for StdLink {
256     type Output = ();
257
258     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
259         run.never()
260     }
261
262     /// Link all libstd rlibs/dylibs into the sysroot location.
263     ///
264     /// Links those artifacts generated by `compiler` to the `stage` compiler's
265     /// sysroot for the specified `host` and `target`.
266     ///
267     /// Note that this assumes that `compiler` has already generated the libstd
268     /// libraries for `target`, and this method will find them in the relevant
269     /// output directory.
270     fn run(self, builder: &Builder<'_>) {
271         let compiler = self.compiler;
272         let target_compiler = self.target_compiler;
273         let target = self.target;
274         builder.info(&format!("Copying stage{} std from stage{} ({} -> {} / {})",
275                 target_compiler.stage,
276                 compiler.stage,
277                 &compiler.host,
278                 target_compiler.host,
279                 target));
280         let libdir = builder.sysroot_libdir(target_compiler, target);
281         let hostdir = builder.sysroot_libdir(target_compiler, compiler.host);
282         add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target));
283
284         if builder.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
285             // The sanitizers are only built in stage1 or above, so the dylibs will
286             // be missing in stage0 and causes panic. See the `std()` function above
287             // for reason why the sanitizers are not built in stage0.
288             copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
289         }
290     }
291 }
292
293 fn copy_apple_sanitizer_dylibs(
294     builder: &Builder<'_>,
295     native_dir: &Path,
296     platform: &str,
297     into: &Path,
298 ) {
299     for &sanitizer in &["asan", "tsan"] {
300         let filename = format!("lib__rustc__clang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
301         let mut src_path = native_dir.join(sanitizer);
302         src_path.push("build");
303         src_path.push("lib");
304         src_path.push("darwin");
305         src_path.push(&filename);
306         builder.copy(&src_path, &into.join(filename));
307     }
308 }
309
310 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
311 pub struct StartupObjects {
312     pub compiler: Compiler,
313     pub target: Interned<String>,
314 }
315
316 impl Step for StartupObjects {
317     type Output = Vec<PathBuf>;
318
319     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
320         run.path("src/rtstartup")
321     }
322
323     fn make_run(run: RunConfig<'_>) {
324         run.builder.ensure(StartupObjects {
325             compiler: run.builder.compiler(run.builder.top_stage, run.host),
326             target: run.target,
327         });
328     }
329
330     /// Builds and prepare startup objects like rsbegin.o and rsend.o
331     ///
332     /// These are primarily used on Windows right now for linking executables/dlls.
333     /// They don't require any library support as they're just plain old object
334     /// files, so we just use the nightly snapshot compiler to always build them (as
335     /// no other compilers are guaranteed to be available).
336     fn run(self, builder: &Builder<'_>) -> Vec<PathBuf> {
337         let for_compiler = self.compiler;
338         let target = self.target;
339         if !target.contains("windows-gnu") {
340             return vec![]
341         }
342
343         let mut target_deps = vec![];
344
345         let src_dir = &builder.src.join("src/rtstartup");
346         let dst_dir = &builder.native_dir(target).join("rtstartup");
347         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
348         t!(fs::create_dir_all(dst_dir));
349
350         for file in &["rsbegin", "rsend"] {
351             let src_file = &src_dir.join(file.to_string() + ".rs");
352             let dst_file = &dst_dir.join(file.to_string() + ".o");
353             if !up_to_date(src_file, dst_file) {
354                 let mut cmd = Command::new(&builder.initial_rustc);
355                 builder.run(cmd.env("RUSTC_BOOTSTRAP", "1")
356                             .arg("--cfg").arg("bootstrap")
357                             .arg("--target").arg(target)
358                             .arg("--emit=obj")
359                             .arg("-o").arg(dst_file)
360                             .arg(src_file));
361             }
362
363             let target = sysroot_dir.join(file.to_string() + ".o");
364             builder.copy(dst_file, &target);
365             target_deps.push(target);
366         }
367
368         for obj in ["crt2.o", "dllcrt2.o"].iter() {
369             let src = compiler_file(builder,
370                                     builder.cc(target),
371                                     target,
372                                     obj);
373             let target = sysroot_dir.join(obj);
374             builder.copy(&src, &target);
375             target_deps.push(target);
376         }
377
378         target_deps
379     }
380 }
381
382 #[derive(Debug, PartialOrd, Ord, Copy, Clone, PartialEq, Eq, Hash)]
383 pub struct Rustc {
384     pub target: Interned<String>,
385     pub compiler: Compiler,
386 }
387
388 impl Step for Rustc {
389     type Output = ();
390     const ONLY_HOSTS: bool = true;
391     const DEFAULT: bool = true;
392
393     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
394         run.all_krates("rustc-main")
395     }
396
397     fn make_run(run: RunConfig<'_>) {
398         run.builder.ensure(Rustc {
399             compiler: run.builder.compiler(run.builder.top_stage, run.host),
400             target: run.target,
401         });
402     }
403
404     /// Builds the compiler.
405     ///
406     /// This will build the compiler for a particular stage of the build using
407     /// the `compiler` targeting the `target` architecture. The artifacts
408     /// created will also be linked into the sysroot directory.
409     fn run(self, builder: &Builder<'_>) {
410         let compiler = self.compiler;
411         let target = self.target;
412
413         builder.ensure(Std { compiler, target });
414
415         if builder.config.keep_stage.contains(&compiler.stage) {
416             builder.info("Warning: Using a potentially old librustc. This may not behave well.");
417             builder.ensure(RustcLink {
418                 compiler,
419                 target_compiler: compiler,
420                 target,
421             });
422             return;
423         }
424
425         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
426         if compiler_to_use != compiler {
427             builder.ensure(Rustc {
428                 compiler: compiler_to_use,
429                 target,
430             });
431             builder.info(&format!("Uplifting stage1 rustc ({} -> {})",
432                 builder.config.build, target));
433             builder.ensure(RustcLink {
434                 compiler: compiler_to_use,
435                 target_compiler: compiler,
436                 target,
437             });
438             return;
439         }
440
441         // Ensure that build scripts and proc macros have a std / libproc_macro to link against.
442         builder.ensure(Std {
443             compiler: builder.compiler(self.compiler.stage, builder.config.build),
444             target: builder.config.build,
445         });
446
447         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "build");
448         rustc_cargo(builder, &mut cargo, target);
449
450         builder.info(&format!("Building stage{} compiler artifacts ({} -> {})",
451                  compiler.stage, &compiler.host, target));
452         run_cargo(builder,
453                   cargo,
454                   vec![],
455                   &librustc_stamp(builder, compiler, target),
456                   vec![],
457                   false);
458
459         builder.ensure(RustcLink {
460             compiler: builder.compiler(compiler.stage, builder.config.build),
461             target_compiler: compiler,
462             target,
463         });
464     }
465 }
466
467 pub fn rustc_cargo(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
468     cargo.arg("--features").arg(builder.rustc_features())
469          .arg("--manifest-path")
470          .arg(builder.src.join("src/rustc/Cargo.toml"));
471     rustc_cargo_env(builder, cargo, target);
472 }
473
474 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: Interned<String>) {
475     // Set some configuration variables picked up by build scripts and
476     // the compiler alike
477     cargo.env("CFG_RELEASE", builder.rust_release())
478          .env("CFG_RELEASE_CHANNEL", &builder.config.channel)
479          .env("CFG_VERSION", builder.rust_version())
480          .env("CFG_PREFIX", builder.config.prefix.clone().unwrap_or_default());
481
482     let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
483     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
484
485     if let Some(ref ver_date) = builder.rust_info.commit_date() {
486         cargo.env("CFG_VER_DATE", ver_date);
487     }
488     if let Some(ref ver_hash) = builder.rust_info.sha() {
489         cargo.env("CFG_VER_HASH", ver_hash);
490     }
491     if !builder.unstable_features() {
492         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
493     }
494     if let Some(ref s) = builder.config.rustc_default_linker {
495         cargo.env("CFG_DEFAULT_LINKER", s);
496     }
497     if builder.config.rustc_parallel {
498         cargo.rustflag("--cfg=parallel_compiler");
499     }
500     if builder.config.rust_verify_llvm_ir {
501         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
502     }
503
504     // Pass down configuration from the LLVM build into the build of
505     // librustc_llvm and librustc_codegen_llvm.
506     //
507     // Note that this is disabled if LLVM itself is disabled or we're in a check
508     // build, where if we're in a check build there's no need to build all of
509     // LLVM and such.
510     if builder.config.llvm_enabled() && builder.kind != Kind::Check {
511         if builder.is_rust_llvm(target) {
512             cargo.env("LLVM_RUSTLLVM", "1");
513         }
514         let llvm_config = builder.ensure(native::Llvm { target });
515         cargo.env("LLVM_CONFIG", &llvm_config);
516         let target_config = builder.config.target_config.get(&target);
517         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
518             cargo.env("CFG_LLVM_ROOT", s);
519         }
520         // Some LLVM linker flags (-L and -l) may be needed to link librustc_llvm.
521         if let Some(ref s) = builder.config.llvm_ldflags {
522             cargo.env("LLVM_LINKER_FLAGS", s);
523         }
524         // Building with a static libstdc++ is only supported on linux right now,
525         // not for MSVC or macOS
526         if builder.config.llvm_static_stdcpp &&
527            !target.contains("freebsd") &&
528            !target.contains("windows") &&
529            !target.contains("apple") {
530             let file = compiler_file(builder,
531                                      builder.cxx(target).unwrap(),
532                                      target,
533                                      "libstdc++.a");
534             cargo.env("LLVM_STATIC_STDCPP", file);
535         }
536         if builder.config.llvm_link_shared || builder.config.llvm_thin_lto {
537             cargo.env("LLVM_LINK_SHARED", "1");
538         }
539         if builder.config.llvm_use_libcxx {
540             cargo.env("LLVM_USE_LIBCXX", "1");
541         }
542         if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
543             cargo.env("LLVM_NDEBUG", "1");
544         }
545     }
546 }
547
548 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
549 struct RustcLink {
550     pub compiler: Compiler,
551     pub target_compiler: Compiler,
552     pub target: Interned<String>,
553 }
554
555 impl Step for RustcLink {
556     type Output = ();
557
558     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
559         run.never()
560     }
561
562     /// Same as `std_link`, only for librustc
563     fn run(self, builder: &Builder<'_>) {
564         let compiler = self.compiler;
565         let target_compiler = self.target_compiler;
566         let target = self.target;
567         builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
568                  target_compiler.stage,
569                  compiler.stage,
570                  &compiler.host,
571                  target_compiler.host,
572                  target));
573         add_to_sysroot(
574             builder,
575             &builder.sysroot_libdir(target_compiler, target),
576             &builder.sysroot_libdir(target_compiler, compiler.host),
577             &librustc_stamp(builder, compiler, target)
578         );
579     }
580 }
581
582 /// Cargo's output path for the standard library in a given stage, compiled
583 /// by a particular compiler for the specified target.
584 pub fn libstd_stamp(
585     builder: &Builder<'_>,
586     compiler: Compiler,
587     target: Interned<String>,
588 ) -> PathBuf {
589     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
590 }
591
592 /// Cargo's output path for librustc in a given stage, compiled by a particular
593 /// compiler for the specified target.
594 pub fn librustc_stamp(
595     builder: &Builder<'_>,
596     compiler: Compiler,
597     target: Interned<String>,
598 ) -> PathBuf {
599     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
600 }
601
602 pub fn compiler_file(
603     builder: &Builder<'_>,
604     compiler: &Path,
605     target: Interned<String>,
606     file: &str,
607 ) -> PathBuf {
608     let mut cmd = Command::new(compiler);
609     cmd.args(builder.cflags(target, GitRepo::Rustc));
610     cmd.arg(format!("-print-file-name={}", file));
611     let out = output(&mut cmd);
612     PathBuf::from(out.trim())
613 }
614
615 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
616 pub struct Sysroot {
617     pub compiler: Compiler,
618 }
619
620 impl Step for Sysroot {
621     type Output = Interned<PathBuf>;
622
623     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
624         run.never()
625     }
626
627     /// Returns the sysroot for the `compiler` specified that *this build system
628     /// generates*.
629     ///
630     /// That is, the sysroot for the stage0 compiler is not what the compiler
631     /// thinks it is by default, but it's the same as the default for stages
632     /// 1-3.
633     fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
634         let compiler = self.compiler;
635         let sysroot = if compiler.stage == 0 {
636             builder.out.join(&compiler.host).join("stage0-sysroot")
637         } else {
638             builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
639         };
640         let _ = fs::remove_dir_all(&sysroot);
641         t!(fs::create_dir_all(&sysroot));
642         INTERNER.intern_path(sysroot)
643     }
644 }
645
646 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
647 pub struct Assemble {
648     /// The compiler which we will produce in this step. Assemble itself will
649     /// take care of ensuring that the necessary prerequisites to do so exist,
650     /// that is, this target can be a stage2 compiler and Assemble will build
651     /// previous stages for you.
652     pub target_compiler: Compiler,
653 }
654
655 impl Step for Assemble {
656     type Output = Compiler;
657
658     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
659         run.never()
660     }
661
662     /// Prepare a new compiler from the artifacts in `stage`
663     ///
664     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
665     /// must have been previously produced by the `stage - 1` builder.build
666     /// compiler.
667     fn run(self, builder: &Builder<'_>) -> Compiler {
668         let target_compiler = self.target_compiler;
669
670         if target_compiler.stage == 0 {
671             assert_eq!(builder.config.build, target_compiler.host,
672                 "Cannot obtain compiler for non-native build triple at stage 0");
673             // The stage 0 compiler for the build triple is always pre-built.
674             return target_compiler;
675         }
676
677         // Get the compiler that we'll use to bootstrap ourselves.
678         //
679         // Note that this is where the recursive nature of the bootstrap
680         // happens, as this will request the previous stage's compiler on
681         // downwards to stage 0.
682         //
683         // Also note that we're building a compiler for the host platform. We
684         // only assume that we can run `build` artifacts, which means that to
685         // produce some other architecture compiler we need to start from
686         // `build` to get there.
687         //
688         // FIXME: Perhaps we should download those libraries?
689         //        It would make builds faster...
690         //
691         // FIXME: It may be faster if we build just a stage 1 compiler and then
692         //        use that to bootstrap this compiler forward.
693         let build_compiler =
694             builder.compiler(target_compiler.stage - 1, builder.config.build);
695
696         // Build the libraries for this compiler to link to (i.e., the libraries
697         // it uses at runtime). NOTE: Crates the target compiler compiles don't
698         // link to these. (FIXME: Is that correct? It seems to be correct most
699         // of the time but I think we do link to these for stage2/bin compilers
700         // when not performing a full bootstrap).
701         builder.ensure(Rustc {
702             compiler: build_compiler,
703             target: target_compiler.host,
704         });
705
706         let lld_install = if builder.config.lld_enabled {
707             Some(builder.ensure(native::Lld {
708                 target: target_compiler.host,
709             }))
710         } else {
711             None
712         };
713
714         let stage = target_compiler.stage;
715         let host = target_compiler.host;
716         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
717
718         // Link in all dylibs to the libdir
719         let sysroot = builder.sysroot(target_compiler);
720         let rustc_libdir = builder.rustc_libdir(target_compiler);
721         t!(fs::create_dir_all(&rustc_libdir));
722         let src_libdir = builder.sysroot_libdir(build_compiler, host);
723         for f in builder.read_dir(&src_libdir) {
724             let filename = f.file_name().into_string().unwrap();
725             if is_dylib(&filename) {
726                 builder.copy(&f.path(), &rustc_libdir.join(&filename));
727             }
728         }
729
730         let libdir = builder.sysroot_libdir(target_compiler, target_compiler.host);
731         if let Some(lld_install) = lld_install {
732             let src_exe = exe("lld", &target_compiler.host);
733             let dst_exe = exe("rust-lld", &target_compiler.host);
734             // we prepend this bin directory to the user PATH when linking Rust binaries. To
735             // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
736             let dst = libdir.parent().unwrap().join("bin");
737             t!(fs::create_dir_all(&dst));
738             builder.copy(&lld_install.join("bin").join(&src_exe), &dst.join(&dst_exe));
739         }
740         dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
741
742         // Link the compiler binary itself into place
743         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
744         let rustc = out_dir.join(exe("rustc_binary", &*host));
745         let bindir = sysroot.join("bin");
746         t!(fs::create_dir_all(&bindir));
747         let compiler = builder.rustc(target_compiler);
748         let _ = fs::remove_file(&compiler);
749         builder.copy(&rustc, &compiler);
750
751         target_compiler
752     }
753 }
754
755 /// Link some files into a rustc sysroot.
756 ///
757 /// For a particular stage this will link the file listed in `stamp` into the
758 /// `sysroot_dst` provided.
759 pub fn add_to_sysroot(
760     builder: &Builder<'_>,
761     sysroot_dst: &Path,
762     sysroot_host_dst: &Path,
763     stamp: &Path
764 ) {
765     t!(fs::create_dir_all(&sysroot_dst));
766     t!(fs::create_dir_all(&sysroot_host_dst));
767     for (path, host) in builder.read_stamp_file(stamp) {
768         if host {
769             builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
770         } else {
771             builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
772         }
773     }
774 }
775
776 pub fn run_cargo(builder: &Builder<'_>,
777                  cargo: Cargo,
778                  tail_args: Vec<String>,
779                  stamp: &Path,
780                  additional_target_deps: Vec<PathBuf>,
781                  is_check: bool)
782     -> Vec<PathBuf>
783 {
784     if builder.config.dry_run {
785         return Vec::new();
786     }
787
788     // `target_root_dir` looks like $dir/$target/release
789     let target_root_dir = stamp.parent().unwrap();
790     // `target_deps_dir` looks like $dir/$target/release/deps
791     let target_deps_dir = target_root_dir.join("deps");
792     // `host_root_dir` looks like $dir/release
793     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
794                                        .parent().unwrap() // chop off `$target`
795                                        .join(target_root_dir.file_name().unwrap());
796
797     // Spawn Cargo slurping up its JSON output. We'll start building up the
798     // `deps` array of all files it generated along with a `toplevel` array of
799     // files we need to probe for later.
800     let mut deps = Vec::new();
801     let mut toplevel = Vec::new();
802     let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
803         let (filenames, crate_types) = match msg {
804             CargoMessage::CompilerArtifact {
805                 filenames,
806                 target: CargoTarget {
807                     crate_types,
808                 },
809                 ..
810             } => (filenames, crate_types),
811             _ => return,
812         };
813         for filename in filenames {
814             // Skip files like executables
815             if !filename.ends_with(".rlib") &&
816                !filename.ends_with(".lib") &&
817                !filename.ends_with(".a") &&
818                !is_dylib(&filename) &&
819                !(is_check && filename.ends_with(".rmeta")) {
820                 continue;
821             }
822
823             let filename = Path::new(&*filename);
824
825             // If this was an output file in the "host dir" we don't actually
826             // worry about it, it's not relevant for us
827             if filename.starts_with(&host_root_dir) {
828                 // Unless it's a proc macro used in the compiler
829                 if crate_types.iter().any(|t| t == "proc-macro") {
830                     deps.push((filename.to_path_buf(), true));
831                 }
832                 continue;
833             }
834
835             // If this was output in the `deps` dir then this is a precise file
836             // name (hash included) so we start tracking it.
837             if filename.starts_with(&target_deps_dir) {
838                 deps.push((filename.to_path_buf(), false));
839                 continue;
840             }
841
842             // Otherwise this was a "top level artifact" which right now doesn't
843             // have a hash in the name, but there's a version of this file in
844             // the `deps` folder which *does* have a hash in the name. That's
845             // the one we'll want to we'll probe for it later.
846             //
847             // We do not use `Path::file_stem` or `Path::extension` here,
848             // because some generated files may have multiple extensions e.g.
849             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
850             // split the file name by the last extension (`.lib`) while we need
851             // to split by all extensions (`.dll.lib`).
852             let expected_len = t!(filename.metadata()).len();
853             let filename = filename.file_name().unwrap().to_str().unwrap();
854             let mut parts = filename.splitn(2, '.');
855             let file_stem = parts.next().unwrap().to_owned();
856             let extension = parts.next().unwrap().to_owned();
857
858             toplevel.push((file_stem, extension, expected_len));
859         }
860     });
861
862     if !ok {
863         exit(1);
864     }
865
866     // Ok now we need to actually find all the files listed in `toplevel`. We've
867     // got a list of prefix/extensions and we basically just need to find the
868     // most recent file in the `deps` folder corresponding to each one.
869     let contents = t!(target_deps_dir.read_dir())
870         .map(|e| t!(e))
871         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
872         .collect::<Vec<_>>();
873     for (prefix, extension, expected_len) in toplevel {
874         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
875             filename.starts_with(&prefix[..]) &&
876                 filename[prefix.len()..].starts_with("-") &&
877                 filename.ends_with(&extension[..]) &&
878                 meta.len() == expected_len
879         });
880         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
881             FileTime::from_last_modification_time(metadata)
882         });
883         let path_to_add = match max {
884             Some(triple) => triple.0.to_str().unwrap(),
885             None => panic!("no output generated for {:?} {:?}", prefix, extension),
886         };
887         if is_dylib(path_to_add) {
888             let candidate = format!("{}.lib", path_to_add);
889             let candidate = PathBuf::from(candidate);
890             if candidate.exists() {
891                 deps.push((candidate, false));
892             }
893         }
894         deps.push((path_to_add.into(), false));
895     }
896
897     deps.extend(additional_target_deps.into_iter().map(|d| (d, false)));
898     deps.sort();
899     let mut new_contents = Vec::new();
900     for (dep, proc_macro) in deps.iter() {
901         new_contents.extend(if *proc_macro { b"h" } else { b"t" });
902         new_contents.extend(dep.to_str().unwrap().as_bytes());
903         new_contents.extend(b"\0");
904     }
905     t!(fs::write(&stamp, &new_contents));
906     deps.into_iter().map(|(d, _)| d).collect()
907 }
908
909 pub fn stream_cargo(
910     builder: &Builder<'_>,
911     cargo: Cargo,
912     tail_args: Vec<String>,
913     cb: &mut dyn FnMut(CargoMessage<'_>),
914 ) -> bool {
915     let mut cargo = Command::from(cargo);
916     if builder.config.dry_run {
917         return true;
918     }
919     // Instruct Cargo to give us json messages on stdout, critically leaving
920     // stderr as piped so we can get those pretty colors.
921     let mut message_format = String::from("json-render-diagnostics");
922     if let Some(s) = &builder.config.rustc_error_format  {
923         message_format.push_str(",json-diagnostic-");
924         message_format.push_str(s);
925     }
926     cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
927
928     for arg in tail_args {
929         cargo.arg(arg);
930     }
931
932     builder.verbose(&format!("running: {:?}", cargo));
933     let mut child = match cargo.spawn() {
934         Ok(child) => child,
935         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
936     };
937
938     // Spawn Cargo slurping up its JSON output. We'll start building up the
939     // `deps` array of all files it generated along with a `toplevel` array of
940     // files we need to probe for later.
941     let stdout = BufReader::new(child.stdout.take().unwrap());
942     for line in stdout.lines() {
943         let line = t!(line);
944         match serde_json::from_str::<CargoMessage<'_>>(&line) {
945             Ok(msg) => cb(msg),
946             // If this was informational, just print it out and continue
947             Err(_) => println!("{}", line)
948         }
949     }
950
951     // Make sure Cargo actually succeeded after we read all of its stdout.
952     let status = t!(child.wait());
953     if !status.success() {
954         eprintln!("command did not execute successfully: {:?}\n\
955                   expected success, got: {}",
956                  cargo,
957                  status);
958     }
959     status.success()
960 }
961
962 #[derive(Deserialize)]
963 pub struct CargoTarget<'a> {
964     crate_types: Vec<Cow<'a, str>>,
965 }
966
967 #[derive(Deserialize)]
968 #[serde(tag = "reason", rename_all = "kebab-case")]
969 pub enum CargoMessage<'a> {
970     CompilerArtifact {
971         package_id: Cow<'a, str>,
972         features: Vec<Cow<'a, str>>,
973         filenames: Vec<Cow<'a, str>>,
974         target: CargoTarget<'a>,
975     },
976     BuildScriptExecuted {
977         package_id: Cow<'a, str>,
978     },
979 }