]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Auto merge of #65637 - ssomers:master, r=scottmcm
[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};
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 pary 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);
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) {
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);
472 }
473
474 pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo) {
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          .env("CFG_CODEGEN_BACKENDS_DIR", &builder.config.rust_codegen_backends_dir);
482
483     let libdir_relative = builder.config.libdir_relative().unwrap_or(Path::new("lib"));
484     cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
485
486     if let Some(ref ver_date) = builder.rust_info.commit_date() {
487         cargo.env("CFG_VER_DATE", ver_date);
488     }
489     if let Some(ref ver_hash) = builder.rust_info.sha() {
490         cargo.env("CFG_VER_HASH", ver_hash);
491     }
492     if !builder.unstable_features() {
493         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
494     }
495     if let Some(ref s) = builder.config.rustc_default_linker {
496         cargo.env("CFG_DEFAULT_LINKER", s);
497     }
498     if builder.config.rustc_parallel {
499         cargo.rustflag("--cfg=parallel_compiler");
500     }
501     if builder.config.rust_verify_llvm_ir {
502         cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
503     }
504 }
505
506 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
507 struct RustcLink {
508     pub compiler: Compiler,
509     pub target_compiler: Compiler,
510     pub target: Interned<String>,
511 }
512
513 impl Step for RustcLink {
514     type Output = ();
515
516     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
517         run.never()
518     }
519
520     /// Same as `std_link`, only for librustc
521     fn run(self, builder: &Builder<'_>) {
522         let compiler = self.compiler;
523         let target_compiler = self.target_compiler;
524         let target = self.target;
525         builder.info(&format!("Copying stage{} rustc from stage{} ({} -> {} / {})",
526                  target_compiler.stage,
527                  compiler.stage,
528                  &compiler.host,
529                  target_compiler.host,
530                  target));
531         add_to_sysroot(
532             builder,
533             &builder.sysroot_libdir(target_compiler, target),
534             &builder.sysroot_libdir(target_compiler, compiler.host),
535             &librustc_stamp(builder, compiler, target)
536         );
537     }
538 }
539
540 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
541 pub struct CodegenBackend {
542     pub compiler: Compiler,
543     pub target: Interned<String>,
544     pub backend: Interned<String>,
545 }
546
547 impl Step for CodegenBackend {
548     type Output = ();
549     const ONLY_HOSTS: bool = true;
550     const DEFAULT: bool = true;
551
552     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
553         run.all_krates("rustc_codegen_llvm")
554     }
555
556     fn make_run(run: RunConfig<'_>) {
557         let backend = run.builder.config.rust_codegen_backends.get(0);
558         let backend = backend.cloned().unwrap_or_else(|| {
559             INTERNER.intern_str("llvm")
560         });
561         run.builder.ensure(CodegenBackend {
562             compiler: run.builder.compiler(run.builder.top_stage, run.host),
563             target: run.target,
564             backend,
565         });
566     }
567
568     fn run(self, builder: &Builder<'_>) {
569         let compiler = self.compiler;
570         let target = self.target;
571         let backend = self.backend;
572
573         builder.ensure(Rustc { compiler, target });
574
575         if builder.config.keep_stage.contains(&compiler.stage) {
576             builder.info("Warning: Using a potentially old codegen backend. \
577                 This may not behave well.");
578             // Codegen backends are linked separately from this step today, so we don't do
579             // anything here.
580             return;
581         }
582
583         let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);
584         if compiler_to_use != compiler {
585             builder.ensure(CodegenBackend {
586                 compiler: compiler_to_use,
587                 target,
588                 backend,
589             });
590             return;
591         }
592
593         let out_dir = builder.cargo_out(compiler, Mode::Codegen, target);
594
595         let mut cargo = builder.cargo(compiler, Mode::Codegen, target, "build");
596         cargo.arg("--manifest-path")
597             .arg(builder.src.join("src/librustc_codegen_llvm/Cargo.toml"));
598         rustc_cargo_env(builder, &mut cargo);
599
600         let features = build_codegen_backend(&builder, &mut cargo, &compiler, target, backend);
601         cargo.arg("--features").arg(features);
602
603         let tmp_stamp = out_dir.join(".tmp.stamp");
604
605         let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false);
606         if builder.config.dry_run {
607             return;
608         }
609         let mut files = files.into_iter()
610             .filter(|f| {
611                 let filename = f.file_name().unwrap().to_str().unwrap();
612                 is_dylib(filename) && filename.contains("rustc_codegen_llvm-")
613             });
614         let codegen_backend = match files.next() {
615             Some(f) => f,
616             None => panic!("no dylibs built for codegen backend?"),
617         };
618         if let Some(f) = files.next() {
619             panic!("codegen backend built two dylibs:\n{}\n{}",
620                    codegen_backend.display(),
621                    f.display());
622         }
623         let stamp = codegen_backend_stamp(builder, compiler, target, backend);
624         let codegen_backend = codegen_backend.to_str().unwrap();
625         t!(fs::write(&stamp, &codegen_backend));
626     }
627 }
628
629 pub fn build_codegen_backend(builder: &Builder<'_>,
630                              cargo: &mut Cargo,
631                              compiler: &Compiler,
632                              target: Interned<String>,
633                              backend: Interned<String>) -> String {
634     match &*backend {
635         "llvm" => {
636             // Build LLVM for our target. This will implicitly build the
637             // host LLVM if necessary.
638             let llvm_config = builder.ensure(native::Llvm {
639                 target,
640             });
641
642             builder.info(&format!("Building stage{} codegen artifacts ({} -> {}, {})",
643                      compiler.stage, &compiler.host, target, backend));
644
645             // Pass down configuration from the LLVM build into the build of
646             // librustc_llvm and librustc_codegen_llvm.
647             if builder.is_rust_llvm(target) {
648                 cargo.env("LLVM_RUSTLLVM", "1");
649             }
650
651             cargo.env("LLVM_CONFIG", &llvm_config);
652             let target_config = builder.config.target_config.get(&target);
653             if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
654                 cargo.env("CFG_LLVM_ROOT", s);
655             }
656             // Some LLVM linker flags (-L and -l) may be needed to link librustc_llvm.
657             if let Some(ref s) = builder.config.llvm_ldflags {
658                 cargo.env("LLVM_LINKER_FLAGS", s);
659             }
660             // Building with a static libstdc++ is only supported on linux and mingw right now,
661             // not for MSVC or macOS
662             if builder.config.llvm_static_stdcpp &&
663                !target.contains("freebsd") &&
664                !target.contains("msvc") &&
665                !target.contains("apple") {
666                 let file = compiler_file(builder,
667                                          builder.cxx(target).unwrap(),
668                                          target,
669                                          "libstdc++.a");
670                 cargo.env("LLVM_STATIC_STDCPP", file);
671             }
672             if builder.config.llvm_link_shared || builder.config.llvm_thin_lto {
673                 cargo.env("LLVM_LINK_SHARED", "1");
674             }
675             if builder.config.llvm_use_libcxx {
676                 cargo.env("LLVM_USE_LIBCXX", "1");
677             }
678             if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
679                 cargo.env("LLVM_NDEBUG", "1");
680             }
681         }
682         _ => panic!("unknown backend: {}", backend),
683     }
684     String::new()
685 }
686
687 /// Creates the `codegen-backends` folder for a compiler that's about to be
688 /// assembled as a complete compiler.
689 ///
690 /// This will take the codegen artifacts produced by `compiler` and link them
691 /// into an appropriate location for `target_compiler` to be a functional
692 /// compiler.
693 fn copy_codegen_backends_to_sysroot(builder: &Builder<'_>,
694                                     compiler: Compiler,
695                                     target_compiler: Compiler) {
696     let target = target_compiler.host;
697
698     // Note that this step is different than all the other `*Link` steps in
699     // that it's not assembling a bunch of libraries but rather is primarily
700     // moving the codegen backend into place. The codegen backend of rustc is
701     // not linked into the main compiler by default but is rather dynamically
702     // selected at runtime for inclusion.
703     //
704     // Here we're looking for the output dylib of the `CodegenBackend` step and
705     // we're copying that into the `codegen-backends` folder.
706     let dst = builder.sysroot_codegen_backends(target_compiler);
707     t!(fs::create_dir_all(&dst));
708
709     if builder.config.dry_run {
710         return;
711     }
712
713     for backend in builder.config.rust_codegen_backends.iter() {
714         let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
715         let dylib = t!(fs::read_to_string(&stamp));
716         let file = Path::new(&dylib);
717         let filename = file.file_name().unwrap().to_str().unwrap();
718         // change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
719         let target_filename = {
720             let dash = filename.find('-').unwrap();
721             let dot = filename.find('.').unwrap();
722             format!("{}-{}{}",
723                     &filename[..dash],
724                     backend,
725                     &filename[dot..])
726         };
727         builder.copy(&file, &dst.join(target_filename));
728     }
729 }
730
731 fn copy_lld_to_sysroot(builder: &Builder<'_>,
732                        target_compiler: Compiler,
733                        lld_install_root: &Path) {
734     let target = target_compiler.host;
735
736     let dst = builder.sysroot_libdir(target_compiler, target)
737         .parent()
738         .unwrap()
739         .join("bin");
740     t!(fs::create_dir_all(&dst));
741
742     let src_exe = exe("lld", &target);
743     let dst_exe = exe("rust-lld", &target);
744     // we prepend this bin directory to the user PATH when linking Rust binaries. To
745     // avoid shadowing the system LLD we rename the LLD we provide to `rust-lld`.
746     builder.copy(&lld_install_root.join("bin").join(&src_exe), &dst.join(&dst_exe));
747 }
748
749 /// Cargo's output path for the standard library in a given stage, compiled
750 /// by a particular compiler for the specified target.
751 pub fn libstd_stamp(
752     builder: &Builder<'_>,
753     compiler: Compiler,
754     target: Interned<String>,
755 ) -> PathBuf {
756     builder.cargo_out(compiler, Mode::Std, target).join(".libstd.stamp")
757 }
758
759 /// Cargo's output path for librustc in a given stage, compiled by a particular
760 /// compiler for the specified target.
761 pub fn librustc_stamp(
762     builder: &Builder<'_>,
763     compiler: Compiler,
764     target: Interned<String>,
765 ) -> PathBuf {
766     builder.cargo_out(compiler, Mode::Rustc, target).join(".librustc.stamp")
767 }
768
769 /// Cargo's output path for librustc_codegen_llvm in a given stage, compiled by a particular
770 /// compiler for the specified target and backend.
771 fn codegen_backend_stamp(builder: &Builder<'_>,
772                          compiler: Compiler,
773                          target: Interned<String>,
774                          backend: Interned<String>) -> PathBuf {
775     builder.cargo_out(compiler, Mode::Codegen, target)
776         .join(format!(".librustc_codegen_llvm-{}.stamp", backend))
777 }
778
779 pub fn compiler_file(
780     builder: &Builder<'_>,
781     compiler: &Path,
782     target: Interned<String>,
783     file: &str,
784 ) -> PathBuf {
785     let mut cmd = Command::new(compiler);
786     cmd.args(builder.cflags(target, GitRepo::Rustc));
787     cmd.arg(format!("-print-file-name={}", file));
788     let out = output(&mut cmd);
789     PathBuf::from(out.trim())
790 }
791
792 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
793 pub struct Sysroot {
794     pub compiler: Compiler,
795 }
796
797 impl Step for Sysroot {
798     type Output = Interned<PathBuf>;
799
800     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
801         run.never()
802     }
803
804     /// Returns the sysroot for the `compiler` specified that *this build system
805     /// generates*.
806     ///
807     /// That is, the sysroot for the stage0 compiler is not what the compiler
808     /// thinks it is by default, but it's the same as the default for stages
809     /// 1-3.
810     fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
811         let compiler = self.compiler;
812         let sysroot = if compiler.stage == 0 {
813             builder.out.join(&compiler.host).join("stage0-sysroot")
814         } else {
815             builder.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
816         };
817         let _ = fs::remove_dir_all(&sysroot);
818         t!(fs::create_dir_all(&sysroot));
819         INTERNER.intern_path(sysroot)
820     }
821 }
822
823 #[derive(Debug, Copy, PartialOrd, Ord, Clone, PartialEq, Eq, Hash)]
824 pub struct Assemble {
825     /// The compiler which we will produce in this step. Assemble itself will
826     /// take care of ensuring that the necessary prerequisites to do so exist,
827     /// that is, this target can be a stage2 compiler and Assemble will build
828     /// previous stages for you.
829     pub target_compiler: Compiler,
830 }
831
832 impl Step for Assemble {
833     type Output = Compiler;
834
835     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
836         run.never()
837     }
838
839     /// Prepare a new compiler from the artifacts in `stage`
840     ///
841     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
842     /// must have been previously produced by the `stage - 1` builder.build
843     /// compiler.
844     fn run(self, builder: &Builder<'_>) -> Compiler {
845         let target_compiler = self.target_compiler;
846
847         if target_compiler.stage == 0 {
848             assert_eq!(builder.config.build, target_compiler.host,
849                 "Cannot obtain compiler for non-native build triple at stage 0");
850             // The stage 0 compiler for the build triple is always pre-built.
851             return target_compiler;
852         }
853
854         // Get the compiler that we'll use to bootstrap ourselves.
855         //
856         // Note that this is where the recursive nature of the bootstrap
857         // happens, as this will request the previous stage's compiler on
858         // downwards to stage 0.
859         //
860         // Also note that we're building a compiler for the host platform. We
861         // only assume that we can run `build` artifacts, which means that to
862         // produce some other architecture compiler we need to start from
863         // `build` to get there.
864         //
865         // FIXME: Perhaps we should download those libraries?
866         //        It would make builds faster...
867         //
868         // FIXME: It may be faster if we build just a stage 1 compiler and then
869         //        use that to bootstrap this compiler forward.
870         let build_compiler =
871             builder.compiler(target_compiler.stage - 1, builder.config.build);
872
873         // Build the libraries for this compiler to link to (i.e., the libraries
874         // it uses at runtime). NOTE: Crates the target compiler compiles don't
875         // link to these. (FIXME: Is that correct? It seems to be correct most
876         // of the time but I think we do link to these for stage2/bin compilers
877         // when not performing a full bootstrap).
878         builder.ensure(Rustc {
879             compiler: build_compiler,
880             target: target_compiler.host,
881         });
882         for &backend in builder.config.rust_codegen_backends.iter() {
883             builder.ensure(CodegenBackend {
884                 compiler: build_compiler,
885                 target: target_compiler.host,
886                 backend,
887             });
888         }
889
890         let lld_install = if builder.config.lld_enabled {
891             Some(builder.ensure(native::Lld {
892                 target: target_compiler.host,
893             }))
894         } else {
895             None
896         };
897
898         let stage = target_compiler.stage;
899         let host = target_compiler.host;
900         builder.info(&format!("Assembling stage{} compiler ({})", stage, host));
901
902         // Link in all dylibs to the libdir
903         let sysroot = builder.sysroot(target_compiler);
904         let rustc_libdir = builder.rustc_libdir(target_compiler);
905         t!(fs::create_dir_all(&rustc_libdir));
906         let src_libdir = builder.sysroot_libdir(build_compiler, host);
907         for f in builder.read_dir(&src_libdir) {
908             let filename = f.file_name().into_string().unwrap();
909             if is_dylib(&filename) {
910                 builder.copy(&f.path(), &rustc_libdir.join(&filename));
911             }
912         }
913
914         copy_codegen_backends_to_sysroot(builder,
915                                          build_compiler,
916                                          target_compiler);
917         if let Some(lld_install) = lld_install {
918             copy_lld_to_sysroot(builder, target_compiler, &lld_install);
919         }
920
921         dist::maybe_install_llvm_dylib(builder, target_compiler.host, &sysroot);
922
923         // Link the compiler binary itself into place
924         let out_dir = builder.cargo_out(build_compiler, Mode::Rustc, host);
925         let rustc = out_dir.join(exe("rustc_binary", &*host));
926         let bindir = sysroot.join("bin");
927         t!(fs::create_dir_all(&bindir));
928         let compiler = builder.rustc(target_compiler);
929         let _ = fs::remove_file(&compiler);
930         builder.copy(&rustc, &compiler);
931
932         target_compiler
933     }
934 }
935
936 /// Link some files into a rustc sysroot.
937 ///
938 /// For a particular stage this will link the file listed in `stamp` into the
939 /// `sysroot_dst` provided.
940 pub fn add_to_sysroot(
941     builder: &Builder<'_>,
942     sysroot_dst: &Path,
943     sysroot_host_dst: &Path,
944     stamp: &Path
945 ) {
946     t!(fs::create_dir_all(&sysroot_dst));
947     t!(fs::create_dir_all(&sysroot_host_dst));
948     for (path, host) in builder.read_stamp_file(stamp) {
949         if host {
950             builder.copy(&path, &sysroot_host_dst.join(path.file_name().unwrap()));
951         } else {
952             builder.copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
953         }
954     }
955 }
956
957 pub fn run_cargo(builder: &Builder<'_>,
958                  cargo: Cargo,
959                  tail_args: Vec<String>,
960                  stamp: &Path,
961                  additional_target_deps: Vec<PathBuf>,
962                  is_check: bool)
963     -> Vec<PathBuf>
964 {
965     if builder.config.dry_run {
966         return Vec::new();
967     }
968
969     // `target_root_dir` looks like $dir/$target/release
970     let target_root_dir = stamp.parent().unwrap();
971     // `target_deps_dir` looks like $dir/$target/release/deps
972     let target_deps_dir = target_root_dir.join("deps");
973     // `host_root_dir` looks like $dir/release
974     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
975                                        .parent().unwrap() // chop off `$target`
976                                        .join(target_root_dir.file_name().unwrap());
977
978     // Spawn Cargo slurping up its JSON output. We'll start building up the
979     // `deps` array of all files it generated along with a `toplevel` array of
980     // files we need to probe for later.
981     let mut deps = Vec::new();
982     let mut toplevel = Vec::new();
983     let ok = stream_cargo(builder, cargo, tail_args, &mut |msg| {
984         let (filenames, crate_types) = match msg {
985             CargoMessage::CompilerArtifact {
986                 filenames,
987                 target: CargoTarget {
988                     crate_types,
989                 },
990                 ..
991             } => (filenames, crate_types),
992             _ => return,
993         };
994         for filename in filenames {
995             // Skip files like executables
996             if !filename.ends_with(".rlib") &&
997                !filename.ends_with(".lib") &&
998                !filename.ends_with(".a") &&
999                !is_dylib(&filename) &&
1000                !(is_check && filename.ends_with(".rmeta")) {
1001                 continue;
1002             }
1003
1004             let filename = Path::new(&*filename);
1005
1006             // If this was an output file in the "host dir" we don't actually
1007             // worry about it, it's not relevant for us
1008             if filename.starts_with(&host_root_dir) {
1009                 // Unless it's a proc macro used in the compiler
1010                 if crate_types.iter().any(|t| t == "proc-macro") {
1011                     deps.push((filename.to_path_buf(), true));
1012                 }
1013                 continue;
1014             }
1015
1016             // If this was output in the `deps` dir then this is a precise file
1017             // name (hash included) so we start tracking it.
1018             if filename.starts_with(&target_deps_dir) {
1019                 deps.push((filename.to_path_buf(), false));
1020                 continue;
1021             }
1022
1023             // Otherwise this was a "top level artifact" which right now doesn't
1024             // have a hash in the name, but there's a version of this file in
1025             // the `deps` folder which *does* have a hash in the name. That's
1026             // the one we'll want to we'll probe for it later.
1027             //
1028             // We do not use `Path::file_stem` or `Path::extension` here,
1029             // because some generated files may have multiple extensions e.g.
1030             // `std-<hash>.dll.lib` on Windows. The aforementioned methods only
1031             // split the file name by the last extension (`.lib`) while we need
1032             // to split by all extensions (`.dll.lib`).
1033             let expected_len = t!(filename.metadata()).len();
1034             let filename = filename.file_name().unwrap().to_str().unwrap();
1035             let mut parts = filename.splitn(2, '.');
1036             let file_stem = parts.next().unwrap().to_owned();
1037             let extension = parts.next().unwrap().to_owned();
1038
1039             toplevel.push((file_stem, extension, expected_len));
1040         }
1041     });
1042
1043     if !ok {
1044         exit(1);
1045     }
1046
1047     // Ok now we need to actually find all the files listed in `toplevel`. We've
1048     // got a list of prefix/extensions and we basically just need to find the
1049     // most recent file in the `deps` folder corresponding to each one.
1050     let contents = t!(target_deps_dir.read_dir())
1051         .map(|e| t!(e))
1052         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1053         .collect::<Vec<_>>();
1054     for (prefix, extension, expected_len) in toplevel {
1055         let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
1056             filename.starts_with(&prefix[..]) &&
1057                 filename[prefix.len()..].starts_with("-") &&
1058                 filename.ends_with(&extension[..]) &&
1059                 meta.len() == expected_len
1060         });
1061         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1062             FileTime::from_last_modification_time(metadata)
1063         });
1064         let path_to_add = match max {
1065             Some(triple) => triple.0.to_str().unwrap(),
1066             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1067         };
1068         if is_dylib(path_to_add) {
1069             let candidate = format!("{}.lib", path_to_add);
1070             let candidate = PathBuf::from(candidate);
1071             if candidate.exists() {
1072                 deps.push((candidate, false));
1073             }
1074         }
1075         deps.push((path_to_add.into(), false));
1076     }
1077
1078     deps.extend(additional_target_deps.into_iter().map(|d| (d, false)));
1079     deps.sort();
1080     let mut new_contents = Vec::new();
1081     for (dep, proc_macro) in deps.iter() {
1082         new_contents.extend(if *proc_macro { b"h" } else { b"t" });
1083         new_contents.extend(dep.to_str().unwrap().as_bytes());
1084         new_contents.extend(b"\0");
1085     }
1086     t!(fs::write(&stamp, &new_contents));
1087     deps.into_iter().map(|(d, _)| d).collect()
1088 }
1089
1090 pub fn stream_cargo(
1091     builder: &Builder<'_>,
1092     cargo: Cargo,
1093     tail_args: Vec<String>,
1094     cb: &mut dyn FnMut(CargoMessage<'_>),
1095 ) -> bool {
1096     let mut cargo = Command::from(cargo);
1097     if builder.config.dry_run {
1098         return true;
1099     }
1100     // Instruct Cargo to give us json messages on stdout, critically leaving
1101     // stderr as piped so we can get those pretty colors.
1102     let mut message_format = String::from("json-render-diagnostics");
1103     if let Some(s) = &builder.config.rustc_error_format  {
1104         message_format.push_str(",json-diagnostic-");
1105         message_format.push_str(s);
1106     }
1107     cargo.arg("--message-format").arg(message_format).stdout(Stdio::piped());
1108
1109     for arg in tail_args {
1110         cargo.arg(arg);
1111     }
1112
1113     builder.verbose(&format!("running: {:?}", cargo));
1114     let mut child = match cargo.spawn() {
1115         Ok(child) => child,
1116         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
1117     };
1118
1119     // Spawn Cargo slurping up its JSON output. We'll start building up the
1120     // `deps` array of all files it generated along with a `toplevel` array of
1121     // files we need to probe for later.
1122     let stdout = BufReader::new(child.stdout.take().unwrap());
1123     for line in stdout.lines() {
1124         let line = t!(line);
1125         match serde_json::from_str::<CargoMessage<'_>>(&line) {
1126             Ok(msg) => cb(msg),
1127             // If this was informational, just print it out and continue
1128             Err(_) => println!("{}", line)
1129         }
1130     }
1131
1132     // Make sure Cargo actually succeeded after we read all of its stdout.
1133     let status = t!(child.wait());
1134     if !status.success() {
1135         eprintln!("command did not execute successfully: {:?}\n\
1136                   expected success, got: {}",
1137                  cargo,
1138                  status);
1139     }
1140     status.success()
1141 }
1142
1143 #[derive(Deserialize)]
1144 pub struct CargoTarget<'a> {
1145     crate_types: Vec<Cow<'a, str>>,
1146 }
1147
1148 #[derive(Deserialize)]
1149 #[serde(tag = "reason", rename_all = "kebab-case")]
1150 pub enum CargoMessage<'a> {
1151     CompilerArtifact {
1152         package_id: Cow<'a, str>,
1153         features: Vec<Cow<'a, str>>,
1154         filenames: Vec<Cow<'a, str>>,
1155         target: CargoTarget<'a>,
1156     },
1157     BuildScriptExecuted {
1158         package_id: Cow<'a, str>,
1159     },
1160 }