]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Utilize interning to allow Copy/Clone steps
[rust.git] / src / bootstrap / compile.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Implementation of compiling various phases of the compiler and standard
12 //! library.
13 //!
14 //! This module contains some of the real meat in the rustbuild build system
15 //! which is where Cargo is used to compiler the standard library, libtest, and
16 //! compiler. This module is also responsible for assembling the sysroot as it
17 //! goes along from the output of the previous stage.
18
19 use std::env;
20 use std::fs::{self, File};
21 use std::io::BufReader;
22 use std::io::prelude::*;
23 use std::path::{Path, PathBuf};
24 use std::process::{Command, Stdio};
25 use std::str;
26
27 use build_helper::{output, mtime, up_to_date};
28 use filetime::FileTime;
29 use serde_json;
30
31 use util::{exe, libdir, is_dylib, copy};
32 use {Build, Compiler, Mode};
33 use native;
34
35 use cache::{INTERNER, Interned};
36 use builder::{Step, Builder};
37
38 //
39 //    // Crates which have build scripts need to rely on this rule to ensure that
40 //    // the necessary prerequisites for a build script are linked and located in
41 //    // place.
42 //    rules.build("may-run-build-script", "path/to/nowhere")
43 //         .dep(move |s| {
44 //             s.name("libstd-link")
45 //              .host(&build.build)
46 //              .target(&build.build)
47 //         });
48
49 //    // ========================================================================
50 //    // Crate compilations
51 //    //
52 //    // Tools used during the build system but not shipped
53 //    // These rules are "pseudo rules" that don't actually do any work
54 //    // themselves, but represent a complete sysroot with the relevant compiler
55 //    // linked into place.
56 //    //
57 //    // That is, depending on "libstd" means that when the rule is completed then
58 //    // the `stage` sysroot for the compiler `host` will be available with a
59 //    // standard library built for `target` linked in place. Not all rules need
60 //    // the compiler itself to be available, just the standard library, so
61 //    // there's a distinction between the two.
62 //    rules.build("libstd", "src/libstd")
63 //         .dep(|s| s.name("rustc").target(s.host))
64 //         .dep(|s| s.name("libstd-link"));
65 //    rules.build("libtest", "src/libtest")
66 //         .dep(|s| s.name("libstd"))
67 //         .dep(|s| s.name("libtest-link"))
68 //         .default(true);
69 //    rules.build("librustc", "src/librustc")
70 //         .dep(|s| s.name("libtest"))
71 //         .dep(|s| s.name("librustc-link"))
72 //         .host(true)
73 //         .default(true);
74
75 // Helper method to define the rules to link a crate into its place in the
76 // sysroot.
77 //
78 // The logic here is a little subtle as there's a few cases to consider.
79 // Not all combinations of (stage, host, target) actually require something
80 // to be compiled, but rather libraries could get propagated from a
81 // different location. For example:
82 //
83 // * Any crate with a `host` that's not the build triple will not actually
84 //   compile something. A different `host` means that the build triple will
85 //   actually compile the libraries, and then we'll copy them over from the
86 //   build triple to the `host` directory.
87 //
88 // * Some crates aren't even compiled by the build triple, but may be copied
89 //   from previous stages. For example if we're not doing a full bootstrap
90 //   then we may just depend on the stage1 versions of libraries to be
91 //   available to get linked forward.
92 //
93 // * Finally, there are some cases, however, which do indeed comiple crates
94 //   and link them into place afterwards.
95 //
96 // The rule definition below mirrors these three cases. The `dep` method
97 // calculates the correct dependency which either comes from stage1, a
98 // different compiler, or from actually building the crate itself (the `dep`
99 // rule). The `run` rule then mirrors these three cases and links the cases
100 // forward into the compiler sysroot specified from the correct location.
101 // fn crate_rule<'a, 'b>(build: &'a Build,
102 //                         rules: &'b mut Rules<'a>,
103 //                         krate: &'a str,
104 //                         dep: &'a str,
105 //                         link: fn(&Build, compiler, compiler, &str))
106 //                         -> RuleBuilder<'a, 'b> {
107 //     let mut rule = rules.build(&krate, "path/to/nowhere");
108 //     rule.dep(move |s| {
109 //             if build.force_use_stage1(&s.compiler(), s.target) {
110 //                 s.host(&build.build).stage(1)
111 //             } else if s.host == build.build {
112 //                 s.name(dep)
113 //             } else {
114 //                 s.host(&build.build)
115 //             }
116 //         })
117 //         .run(move |s| {
118 //             if build.force_use_stage1(&s.compiler(), s.target) {
119 //                 link(build,
120 //                         &s.stage(1).host(&build.build).compiler(),
121 //                         &s.compiler(),
122 //                         s.target)
123 //             } else if s.host == build.build {
124 //                 link(build, &s.compiler(), &s.compiler(), s.target)
125 //             } else {
126 //                 link(build,
127 //                         &s.host(&build.build).compiler(),
128 //                         &s.compiler(),
129 //                         s.target)
130 //             }
131 //         });
132 //         rule
133 // }
134
135 //        rules.build("libstd", "src/libstd")
136 //             .dep(|s| s.name("rustc").target(s.host))
137 //             .dep(|s| s.name("libstd-link"));
138 //    for (krate, path, _default) in krates("std") {
139 //        rules.build(&krate.build_step, path)
140 //             .dep(|s| s.name("startup-objects"))
141 //             .dep(move |s| s.name("rustc").host(&build.build).target(s.host))
142 //             .run(move |s| compile::std(build, s.target, &s.compiler()));
143 //    }
144 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
145 pub struct Std {
146     pub target: Interned<String>,
147     pub compiler: Compiler,
148 }
149
150 impl Step for Std {
151     type Output = ();
152     const DEFAULT: bool = true;
153
154     fn should_run(builder: &Builder, path: &Path) -> bool {
155         path.ends_with("src/libstd") ||
156         builder.crates("std").into_iter().any(|(_, krate_path)| {
157             path.ends_with(krate_path)
158         })
159     }
160
161     fn make_run(
162         builder: &Builder,
163         _path: Option<&Path>,
164         host: Interned<String>,
165         target: Interned<String>,
166     ) {
167         builder.ensure(Std {
168             compiler: builder.compiler(builder.top_stage, host),
169             target,
170         });
171     }
172
173     /// Build the standard library.
174     ///
175     /// This will build the standard library for a particular stage of the build
176     /// using the `compiler` targeting the `target` architecture. The artifacts
177     /// created will also be linked into the sysroot directory.
178     fn run(self, builder: &Builder) {
179         let build = builder.build;
180         let target = self.target;
181         let compiler = self.compiler;
182
183         builder.ensure(StartupObjects { compiler, target });
184
185         if build.force_use_stage1(compiler, target) {
186             let from = builder.compiler(1, build.build);
187             builder.ensure(Std {
188                 compiler: from,
189                 target: target,
190             });
191             println!("Uplifting stage1 std ({} -> {})", from.host, target);
192             builder.ensure(StdLink {
193                 compiler: from,
194                 target_compiler: compiler,
195                 target: target,
196             });
197             return;
198         }
199
200         let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
201         println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
202                 &compiler.host, target);
203
204         let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
205         build.clear_if_dirty(&out_dir, &builder.rustc(compiler));
206         let mut cargo = builder.cargo(compiler, Mode::Libstd, target, "build");
207         let mut features = build.std_features();
208
209         if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
210             cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
211         }
212
213         // When doing a local rebuild we tell cargo that we're stage1 rather than
214         // stage0. This works fine if the local rust and being-built rust have the
215         // same view of what the default allocator is, but fails otherwise. Since
216         // we don't have a way to express an allocator preference yet, work
217         // around the issue in the case of a local rebuild with jemalloc disabled.
218         if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
219             features.push_str(" force_alloc_system");
220         }
221
222         if compiler.stage != 0 && build.config.sanitizers {
223             // This variable is used by the sanitizer runtime crates, e.g.
224             // rustc_lsan, to build the sanitizer runtime from C code
225             // When this variable is missing, those crates won't compile the C code,
226             // so we don't set this variable during stage0 where llvm-config is
227             // missing
228             // We also only build the runtimes when --enable-sanitizers (or its
229             // config.toml equivalent) is used
230             cargo.env("LLVM_CONFIG", build.llvm_config(target));
231         }
232
233         cargo.arg("--features").arg(features)
234             .arg("--manifest-path")
235             .arg(build.src.join("src/libstd/Cargo.toml"));
236
237         if let Some(target) = build.config.target_config.get(&target) {
238             if let Some(ref jemalloc) = target.jemalloc {
239                 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
240             }
241         }
242         if target.contains("musl") {
243             if let Some(p) = build.musl_root(target) {
244                 cargo.env("MUSL_ROOT", p);
245             }
246         }
247
248         run_cargo(build,
249                 &mut cargo,
250                 &libstd_stamp(build, compiler, target));
251
252         builder.ensure(StdLink {
253             compiler: builder.compiler(compiler.stage, build.build),
254             target_compiler: compiler,
255             target: target,
256         });
257     }
258 }
259
260
261 // crate_rule(build,
262 //            &mut rules,
263 //            "libstd-link",
264 //            "build-crate-std",
265 //            compile::std_link)
266 //     .dep(|s| s.name("startup-objects"))
267 //     .dep(|s| s.name("create-sysroot").target(s.host));
268
269 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
270 struct StdLink {
271     pub compiler: Compiler,
272     pub target_compiler: Compiler,
273     pub target: Interned<String>,
274 }
275
276 impl Step for StdLink {
277     type Output = ();
278
279     /// Link all libstd rlibs/dylibs into the sysroot location.
280     ///
281     /// Links those artifacts generated by `compiler` to a the `stage` compiler's
282     /// sysroot for the specified `host` and `target`.
283     ///
284     /// Note that this assumes that `compiler` has already generated the libstd
285     /// libraries for `target`, and this method will find them in the relevant
286     /// output directory.
287     fn run(self, builder: &Builder) {
288         let build = builder.build;
289         let compiler = self.compiler;
290         let target_compiler = self.target_compiler;
291         let target = self.target;
292         println!("Copying stage{} std from stage{} ({} -> {} / {})",
293                 target_compiler.stage,
294                 compiler.stage,
295                 &compiler.host,
296                 target_compiler.host,
297                 target);
298         let libdir = builder.sysroot_libdir(target_compiler, target);
299         add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
300
301         if target.contains("musl") && !target.contains("mips") {
302             copy_musl_third_party_objects(build, target, &libdir);
303         }
304
305         if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
306             // The sanitizers are only built in stage1 or above, so the dylibs will
307             // be missing in stage0 and causes panic. See the `std()` function above
308             // for reason why the sanitizers are not built in stage0.
309             copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
310         }
311     }
312 }
313
314 /// Copies the crt(1,i,n).o startup objects
315 ///
316 /// Only required for musl targets that statically link to libc
317 fn copy_musl_third_party_objects(build: &Build, target: Interned<String>, into: &Path) {
318     for &obj in &["crt1.o", "crti.o", "crtn.o"] {
319         copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
320     }
321 }
322
323 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
324     for &sanitizer in &["asan", "tsan"] {
325         let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
326         let mut src_path = native_dir.join(sanitizer);
327         src_path.push("build");
328         src_path.push("lib");
329         src_path.push("darwin");
330         src_path.push(&filename);
331         copy(&src_path, &into.join(filename));
332     }
333 }
334
335 // rules.build("startup-objects", "src/rtstartup")
336 //      .dep(|s| s.name("create-sysroot").target(s.host))
337 //      .run(move |s| compile::build_startup_objects(build, &s.compiler(), s.target));
338
339 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
340 pub struct StartupObjects {
341     pub compiler: Compiler,
342     pub target: Interned<String>,
343 }
344
345 impl Step for StartupObjects {
346     type Output = ();
347
348     fn should_run(_builder: &Builder, path: &Path) -> bool {
349         path.ends_with("src/rtstartup")
350     }
351
352     fn make_run(
353         builder: &Builder,
354         _path: Option<&Path>,
355         host: Interned<String>,
356         target: Interned<String>,
357     ) {
358         builder.ensure(StartupObjects {
359             compiler: builder.compiler(builder.top_stage, host),
360             target,
361         });
362     }
363
364     /// Build and prepare startup objects like rsbegin.o and rsend.o
365     ///
366     /// These are primarily used on Windows right now for linking executables/dlls.
367     /// They don't require any library support as they're just plain old object
368     /// files, so we just use the nightly snapshot compiler to always build them (as
369     /// no other compilers are guaranteed to be available).
370     fn run(self, builder: &Builder) {
371         let build = builder.build;
372         let for_compiler = self.compiler;
373         let target = self.target;
374         if !target.contains("pc-windows-gnu") {
375             return
376         }
377
378         let src_dir = &build.src.join("src/rtstartup");
379         let dst_dir = &build.native_dir(target).join("rtstartup");
380         let sysroot_dir = &builder.sysroot_libdir(for_compiler, target);
381         t!(fs::create_dir_all(dst_dir));
382
383         for file in &["rsbegin", "rsend"] {
384             let src_file = &src_dir.join(file.to_string() + ".rs");
385             let dst_file = &dst_dir.join(file.to_string() + ".o");
386             if !up_to_date(src_file, dst_file) {
387                 let mut cmd = Command::new(&build.initial_rustc);
388                 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
389                             .arg("--cfg").arg("stage0")
390                             .arg("--target").arg(target)
391                             .arg("--emit=obj")
392                             .arg("--o").arg(dst_file)
393                             .arg(src_file));
394             }
395
396             copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
397         }
398
399         for obj in ["crt2.o", "dllcrt2.o"].iter() {
400             copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
401         }
402     }
403 }
404
405 //    for (krate, path, _default) in krates("test") {
406 //        rules.build(&krate.build_step, path)
407 //             .dep(|s| s.name("libstd-link"))
408 //             .run(move |s| compile::test(build, s.target, &s.compiler()));
409 //    }
410 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
411 pub struct Test {
412     pub compiler: Compiler,
413     pub target: Interned<String>,
414 }
415
416 impl Step for Test {
417     type Output = ();
418     const DEFAULT: bool = true;
419
420     fn should_run(builder: &Builder, path: &Path) -> bool {
421         path.ends_with("src/libtest") ||
422         builder.crates("test").into_iter().any(|(_, krate_path)| {
423             path.ends_with(krate_path)
424         })
425     }
426
427     fn make_run(
428         builder: &Builder,
429         _path: Option<&Path>,
430         host: Interned<String>,
431         target: Interned<String>,
432     ) {
433         builder.ensure(Test {
434             compiler: builder.compiler(builder.top_stage, host),
435             target,
436         });
437     }
438
439     /// Build libtest.
440     ///
441     /// This will build libtest and supporting libraries for a particular stage of
442     /// the build using the `compiler` targeting the `target` architecture. The
443     /// artifacts created will also be linked into the sysroot directory.
444     fn run(self, builder: &Builder) {
445         let build = builder.build;
446         let target = self.target;
447         let compiler = self.compiler;
448
449         builder.ensure(Std { compiler, target });
450
451         if build.force_use_stage1(compiler, target) {
452             builder.ensure(Test {
453                 compiler: builder.compiler(1, build.build),
454                 target: target,
455             });
456             println!("Uplifting stage1 test ({} -> {})", &build.build, target);
457             builder.ensure(TestLink {
458                 compiler: builder.compiler(1, build.build),
459                 target_compiler: compiler,
460                 target: target,
461             });
462             return;
463         }
464
465         let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
466         println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
467                 &compiler.host, target);
468         let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
469         build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
470         let mut cargo = builder.cargo(compiler, Mode::Libtest, target, "build");
471         if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
472             cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
473         }
474         cargo.arg("--manifest-path")
475             .arg(build.src.join("src/libtest/Cargo.toml"));
476         run_cargo(build,
477                 &mut cargo,
478                 &libtest_stamp(build, compiler, target));
479
480         builder.ensure(TestLink {
481             compiler: builder.compiler(compiler.stage, build.build),
482             target_compiler: compiler,
483             target: target,
484         });
485     }
486 }
487
488
489 // crate_rule(build,
490 //            &mut rules,
491 //            "libtest-link",
492 //            "build-crate-test",
493 //            compile::test_link)
494 //     .dep(|s| s.name("libstd-link"));
495
496 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
497 pub struct TestLink {
498     pub compiler: Compiler,
499     pub target_compiler: Compiler,
500     pub target: Interned<String>,
501 }
502
503 impl Step for TestLink {
504     type Output = ();
505
506     /// Same as `std_link`, only for libtest
507     fn run(self, builder: &Builder) {
508         let build = builder.build;
509         let compiler = self.compiler;
510         let target_compiler = self.target_compiler;
511         let target = self.target;
512         println!("Copying stage{} test from stage{} ({} -> {} / {})",
513                 target_compiler.stage,
514                 compiler.stage,
515                 &compiler.host,
516                 target_compiler.host,
517                 target);
518         add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
519                     &libtest_stamp(build, compiler, target));
520     }
521 }
522
523 //    for (krate, path, _default) in krates("rustc-main") {
524 //        rules.build(&krate.build_step, path)
525 //             .dep(|s| s.name("libtest-link"))
526 //             .dep(move |s| s.name("llvm").host(&build.build).stage(0))
527 //             .dep(|s| s.name("may-run-build-script"))
528 //             .run(move |s| compile::rustc(build, s.target, &s.compiler()));
529 //    }
530
531 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
532 pub struct Rustc {
533     pub compiler: Compiler,
534     pub target: Interned<String>,
535 }
536
537 impl Step for Rustc {
538     type Output = ();
539     const ONLY_HOSTS: bool = true;
540     const DEFAULT: bool = true;
541
542     fn should_run(builder: &Builder, path: &Path) -> bool {
543         path.ends_with("src/librustc") ||
544         builder.crates("rustc-main").into_iter().any(|(_, krate_path)| {
545             path.ends_with(krate_path)
546         })
547     }
548
549     fn make_run(
550         builder: &Builder,
551         _path: Option<&Path>,
552         host: Interned<String>,
553         target: Interned<String>,
554     ) {
555         builder.ensure(Rustc {
556             compiler: builder.compiler(builder.top_stage, host),
557             target,
558         });
559     }
560
561     /// Build the compiler.
562     ///
563     /// This will build the compiler for a particular stage of the build using
564     /// the `compiler` targeting the `target` architecture. The artifacts
565     /// created will also be linked into the sysroot directory.
566     fn run(self, builder: &Builder) {
567         let build = builder.build;
568         let compiler = self.compiler;
569         let target = self.target;
570
571         builder.ensure(Test { compiler, target });
572
573         // Build LLVM for our target. This will implicitly build the host LLVM
574         // if necessary.
575         builder.ensure(native::Llvm { target });
576
577         if build.force_use_stage1(compiler, target) {
578             builder.ensure(Rustc {
579                 compiler: builder.compiler(1, build.build),
580                 target: target,
581             });
582             println!("Uplifting stage1 rustc ({} -> {})", &build.build, target);
583             builder.ensure(RustcLink {
584                 compiler: builder.compiler(1, build.build),
585                 target_compiler: compiler,
586                 target,
587             });
588             return;
589         }
590
591         // Ensure that build scripts have a std to link against.
592         builder.ensure(Std {
593             compiler: builder.compiler(self.compiler.stage, build.build),
594             target: build.build,
595         });
596
597         let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
598         println!("Building stage{} compiler artifacts ({} -> {})",
599                  compiler.stage, &compiler.host, target);
600
601         let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
602         build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
603
604         let mut cargo = builder.cargo(compiler, Mode::Librustc, target, "build");
605         cargo.arg("--features").arg(build.rustc_features())
606              .arg("--manifest-path")
607              .arg(build.src.join("src/rustc/Cargo.toml"));
608
609         // Set some configuration variables picked up by build scripts and
610         // the compiler alike
611         cargo.env("CFG_RELEASE", build.rust_release())
612              .env("CFG_RELEASE_CHANNEL", &build.config.channel)
613              .env("CFG_VERSION", build.rust_version())
614              .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default());
615
616         if compiler.stage == 0 {
617             cargo.env("CFG_LIBDIR_RELATIVE", "lib");
618         } else {
619             let libdir_relative =
620                 build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
621             cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
622         }
623
624         // If we're not building a compiler with debugging information then remove
625         // these two env vars which would be set otherwise.
626         if build.config.rust_debuginfo_only_std {
627             cargo.env_remove("RUSTC_DEBUGINFO");
628             cargo.env_remove("RUSTC_DEBUGINFO_LINES");
629         }
630
631         if let Some(ref ver_date) = build.rust_info.commit_date() {
632             cargo.env("CFG_VER_DATE", ver_date);
633         }
634         if let Some(ref ver_hash) = build.rust_info.sha() {
635             cargo.env("CFG_VER_HASH", ver_hash);
636         }
637         if !build.unstable_features() {
638             cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
639         }
640         // Flag that rust llvm is in use
641         if build.is_rust_llvm(target) {
642             cargo.env("LLVM_RUSTLLVM", "1");
643         }
644         cargo.env("LLVM_CONFIG", build.llvm_config(target));
645         let target_config = build.config.target_config.get(&target);
646         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
647             cargo.env("CFG_LLVM_ROOT", s);
648         }
649         // Building with a static libstdc++ is only supported on linux right now,
650         // not for MSVC or macOS
651         if build.config.llvm_static_stdcpp &&
652            !target.contains("windows") &&
653            !target.contains("apple") {
654             cargo.env("LLVM_STATIC_STDCPP",
655                       compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
656         }
657         if build.config.llvm_link_shared {
658             cargo.env("LLVM_LINK_SHARED", "1");
659         }
660         if let Some(ref s) = build.config.rustc_default_linker {
661             cargo.env("CFG_DEFAULT_LINKER", s);
662         }
663         if let Some(ref s) = build.config.rustc_default_ar {
664             cargo.env("CFG_DEFAULT_AR", s);
665         }
666         run_cargo(build,
667                   &mut cargo,
668                   &librustc_stamp(build, compiler, target));
669
670         builder.ensure(RustcLink {
671             compiler: builder.compiler(compiler.stage, build.build),
672             target_compiler: compiler,
673             target,
674         });
675     }
676 }
677
678 // crate_rule(build,
679 //            &mut rules,
680 //            "librustc-link",
681 //            "build-crate-rustc-main",
682 //            compile::rustc_link)
683 //     .dep(|s| s.name("libtest-link"));
684 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
685 struct RustcLink {
686     pub compiler: Compiler,
687     pub target_compiler: Compiler,
688     pub target: Interned<String>,
689 }
690
691 impl Step for RustcLink {
692     type Output = ();
693
694     /// Same as `std_link`, only for librustc
695     fn run(self, builder: &Builder) {
696         let build = builder.build;
697         let compiler = self.compiler;
698         let target_compiler = self.target_compiler;
699         let target = self.target;
700         println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
701                  target_compiler.stage,
702                  compiler.stage,
703                  &compiler.host,
704                  target_compiler.host,
705                  target);
706         add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
707                        &librustc_stamp(build, compiler, target));
708     }
709 }
710
711 /// Cargo's output path for the standard library in a given stage, compiled
712 /// by a particular compiler for the specified target.
713 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
714     build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
715 }
716
717 /// Cargo's output path for libtest in a given stage, compiled by a particular
718 /// compiler for the specified target.
719 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
720     build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
721 }
722
723 /// Cargo's output path for librustc in a given stage, compiled by a particular
724 /// compiler for the specified target.
725 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: Interned<String>) -> PathBuf {
726     build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
727 }
728
729 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
730     let out = output(Command::new(compiler)
731                             .arg(format!("-print-file-name={}", file)));
732     PathBuf::from(out.trim())
733 }
734
735 // rules.build("create-sysroot", "path/to/nowhere")
736 //      .run(move |s| compile::create_sysroot(build, &s.compiler()));
737
738 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
739 pub struct Sysroot {
740     pub compiler: Compiler,
741 }
742
743 impl Step for Sysroot {
744     type Output = Interned<PathBuf>;
745
746     /// Returns the sysroot for the `compiler` specified that *this build system
747     /// generates*.
748     ///
749     /// That is, the sysroot for the stage0 compiler is not what the compiler
750     /// thinks it is by default, but it's the same as the default for stages
751     /// 1-3.
752     fn run(self, builder: &Builder) -> Interned<PathBuf> {
753         let build = builder.build;
754         let compiler = self.compiler;
755         let sysroot = if compiler.stage == 0 {
756             build.out.join(&compiler.host).join("stage0-sysroot")
757         } else {
758             build.out.join(&compiler.host).join(format!("stage{}", compiler.stage))
759         };
760         let _ = fs::remove_dir_all(&sysroot);
761         t!(fs::create_dir_all(&sysroot));
762         INTERNER.intern_path(sysroot)
763     }
764 }
765
766 // the compiler with no target libraries ready to go
767 // rules.build("rustc", "src/rustc")
768 //      .dep(|s| s.name("create-sysroot").target(s.host))
769 //      .dep(move |s| {
770 //          if s.stage == 0 {
771 //              Step::noop()
772 //          } else {
773 //              s.name("librustc")
774 //               .host(&build.build)
775 //               .stage(s.stage - 1)
776 //          }
777 //      })
778 //      .run(move |s| compile::assemble_rustc(build, s.stage, s.target));
779
780 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
781 pub struct Assemble {
782     /// The compiler which we will produce in this step. Assemble itself will
783     /// take care of ensuring that the necessary prerequisites to do so exist,
784     /// that is, this target can be a stage2 compiler and Assemble will build
785     /// previous stages for you.
786     pub target_compiler: Compiler,
787 }
788
789 impl Step for Assemble {
790     type Output = Compiler;
791
792     /// Prepare a new compiler from the artifacts in `stage`
793     ///
794     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
795     /// must have been previously produced by the `stage - 1` build.build
796     /// compiler.
797     fn run(self, builder: &Builder) -> Compiler {
798         let build = builder.build;
799         let target_compiler = self.target_compiler;
800
801         if target_compiler.stage == 0 {
802             assert_eq!(build.build, target_compiler.host,
803                 "Cannot obtain compiler for non-native build triple at stage 0");
804             // The stage 0 compiler for the build triple is always pre-built.
805             return target_compiler;
806         }
807
808         // Get the compiler that we'll use to bootstrap ourselves.
809         let build_compiler = if target_compiler.host != build.build {
810             // Build a compiler for the host platform. We cannot use the stage0
811             // compiler for the host platform for this because it doesn't have
812             // the libraries we need.  FIXME: Perhaps we should download those
813             // libraries? It would make builds faster...
814             // FIXME: It may be faster if we build just a stage 1
815             // compiler and then use that to bootstrap this compiler
816             // forward.
817             builder.compiler(target_compiler.stage - 1, build.build)
818         } else {
819             // Build the compiler we'll use to build the stage requested. This
820             // may build more than one compiler (going down to stage 0).
821             builder.compiler(target_compiler.stage - 1, target_compiler.host)
822         };
823
824         // Build the libraries for this compiler to link to (i.e., the libraries
825         // it uses at runtime). NOTE: Crates the target compiler compiles don't
826         // link to these. (FIXME: Is that correct? It seems to be correct most
827         // of the time but I think we do link to these for stage2/bin compilers
828         // when not performing a full bootstrap).
829         builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
830
831         let stage = target_compiler.stage;
832         let host = target_compiler.host;
833         println!("Assembling stage{} compiler ({})", stage, host);
834
835         // Link in all dylibs to the libdir
836         let sysroot = builder.sysroot(target_compiler);
837         let sysroot_libdir = sysroot.join(libdir(&*host));
838         t!(fs::create_dir_all(&sysroot_libdir));
839         let src_libdir = builder.sysroot_libdir(build_compiler, host);
840         for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
841             let filename = f.file_name().into_string().unwrap();
842             if is_dylib(&filename) {
843                 copy(&f.path(), &sysroot_libdir.join(&filename));
844             }
845         }
846
847         let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
848
849         // Link the compiler binary itself into place
850         let rustc = out_dir.join(exe("rustc", &*host));
851         let bindir = sysroot.join("bin");
852         t!(fs::create_dir_all(&bindir));
853         let compiler = builder.rustc(target_compiler);
854         let _ = fs::remove_file(&compiler);
855         copy(&rustc, &compiler);
856
857         // See if rustdoc exists to link it into place
858         let rustdoc = exe("rustdoc", &*host);
859         let rustdoc_src = out_dir.join(&rustdoc);
860         let rustdoc_dst = bindir.join(&rustdoc);
861         if fs::metadata(&rustdoc_src).is_ok() {
862             let _ = fs::remove_file(&rustdoc_dst);
863             copy(&rustdoc_src, &rustdoc_dst);
864         }
865
866         target_compiler
867     }
868 }
869
870 /// Link some files into a rustc sysroot.
871 ///
872 /// For a particular stage this will link the file listed in `stamp` into the
873 /// `sysroot_dst` provided.
874 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
875     t!(fs::create_dir_all(&sysroot_dst));
876     let mut contents = Vec::new();
877     t!(t!(File::open(stamp)).read_to_end(&mut contents));
878     // This is the method we use for extracting paths from the stamp file passed to us. See
879     // run_cargo for more information (in this file).
880     for part in contents.split(|b| *b == 0) {
881         if part.is_empty() {
882             continue
883         }
884         let path = Path::new(t!(str::from_utf8(part)));
885         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
886     }
887 }
888
889 // Avoiding a dependency on winapi to keep compile times down
890 #[cfg(unix)]
891 fn stderr_isatty() -> bool {
892     use libc;
893     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
894 }
895 #[cfg(windows)]
896 fn stderr_isatty() -> bool {
897     type DWORD = u32;
898     type BOOL = i32;
899     type HANDLE = *mut u8;
900     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
901     extern "system" {
902         fn GetStdHandle(which: DWORD) -> HANDLE;
903         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
904     }
905     unsafe {
906         let handle = GetStdHandle(STD_ERROR_HANDLE);
907         let mut out = 0;
908         GetConsoleMode(handle, &mut out) != 0
909     }
910 }
911
912 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
913     // Instruct Cargo to give us json messages on stdout, critically leaving
914     // stderr as piped so we can get those pretty colors.
915     cargo.arg("--message-format").arg("json")
916          .stdout(Stdio::piped());
917
918     if stderr_isatty() {
919         // since we pass message-format=json to cargo, we need to tell the rustc
920         // wrapper to give us colored output if necessary. This is because we
921         // only want Cargo's JSON output, not rustcs.
922         cargo.env("RUSTC_COLOR", "1");
923     }
924
925     build.verbose(&format!("running: {:?}", cargo));
926     let mut child = match cargo.spawn() {
927         Ok(child) => child,
928         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
929     };
930
931     // `target_root_dir` looks like $dir/$target/release
932     let target_root_dir = stamp.parent().unwrap();
933     // `target_deps_dir` looks like $dir/$target/release/deps
934     let target_deps_dir = target_root_dir.join("deps");
935     // `host_root_dir` looks like $dir/release
936     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
937                                        .parent().unwrap() // chop off `$target`
938                                        .join(target_root_dir.file_name().unwrap());
939
940     // Spawn Cargo slurping up its JSON output. We'll start building up the
941     // `deps` array of all files it generated along with a `toplevel` array of
942     // files we need to probe for later.
943     let mut deps = Vec::new();
944     let mut toplevel = Vec::new();
945     let stdout = BufReader::new(child.stdout.take().unwrap());
946     for line in stdout.lines() {
947         let line = t!(line);
948         let json: serde_json::Value = if line.starts_with("{") {
949             t!(serde_json::from_str(&line))
950         } else {
951             // If this was informational, just print it out and continue
952             println!("{}", line);
953             continue
954         };
955         if json["reason"].as_str() != Some("compiler-artifact") {
956             continue
957         }
958         for filename in json["filenames"].as_array().unwrap() {
959             let filename = filename.as_str().unwrap();
960             // Skip files like executables
961             if !filename.ends_with(".rlib") &&
962                !filename.ends_with(".lib") &&
963                !is_dylib(&filename) {
964                 continue
965             }
966
967             let filename = Path::new(filename);
968
969             // If this was an output file in the "host dir" we don't actually
970             // worry about it, it's not relevant for us.
971             if filename.starts_with(&host_root_dir) {
972                 continue;
973             }
974
975             // If this was output in the `deps` dir then this is a precise file
976             // name (hash included) so we start tracking it.
977             if filename.starts_with(&target_deps_dir) {
978                 deps.push(filename.to_path_buf());
979                 continue;
980             }
981
982             // Otherwise this was a "top level artifact" which right now doesn't
983             // have a hash in the name, but there's a version of this file in
984             // the `deps` folder which *does* have a hash in the name. That's
985             // the one we'll want to we'll probe for it later.
986             toplevel.push((filename.file_stem().unwrap()
987                                     .to_str().unwrap().to_string(),
988                             filename.extension().unwrap().to_owned()
989                                     .to_str().unwrap().to_string()));
990         }
991     }
992
993     // Make sure Cargo actually succeeded after we read all of its stdout.
994     let status = t!(child.wait());
995     if !status.success() {
996         panic!("command did not execute successfully: {:?}\n\
997                 expected success, got: {}",
998                cargo,
999                status);
1000     }
1001
1002     // Ok now we need to actually find all the files listed in `toplevel`. We've
1003     // got a list of prefix/extensions and we basically just need to find the
1004     // most recent file in the `deps` folder corresponding to each one.
1005     let contents = t!(target_deps_dir.read_dir())
1006         .map(|e| t!(e))
1007         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
1008         .collect::<Vec<_>>();
1009     for (prefix, extension) in toplevel {
1010         let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
1011             filename.starts_with(&prefix[..]) &&
1012                 filename[prefix.len()..].starts_with("-") &&
1013                 filename.ends_with(&extension[..])
1014         });
1015         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1016             FileTime::from_last_modification_time(metadata)
1017         });
1018         let path_to_add = match max {
1019             Some(triple) => triple.0.to_str().unwrap(),
1020             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1021         };
1022         if is_dylib(path_to_add) {
1023             let candidate = format!("{}.lib", path_to_add);
1024             let candidate = PathBuf::from(candidate);
1025             if candidate.exists() {
1026                 deps.push(candidate);
1027             }
1028         }
1029         deps.push(path_to_add.into());
1030     }
1031
1032     // Now we want to update the contents of the stamp file, if necessary. First
1033     // we read off the previous contents along with its mtime. If our new
1034     // contents (the list of files to copy) is different or if any dep's mtime
1035     // is newer then we rewrite the stamp file.
1036     deps.sort();
1037     let mut stamp_contents = Vec::new();
1038     if let Ok(mut f) = File::open(stamp) {
1039         t!(f.read_to_end(&mut stamp_contents));
1040     }
1041     let stamp_mtime = mtime(&stamp);
1042     let mut new_contents = Vec::new();
1043     let mut max = None;
1044     let mut max_path = None;
1045     for dep in deps {
1046         let mtime = mtime(&dep);
1047         if Some(mtime) > max {
1048             max = Some(mtime);
1049             max_path = Some(dep.clone());
1050         }
1051         new_contents.extend(dep.to_str().unwrap().as_bytes());
1052         new_contents.extend(b"\0");
1053     }
1054     let max = max.unwrap();
1055     let max_path = max_path.unwrap();
1056     if stamp_contents == new_contents && max <= stamp_mtime {
1057         return
1058     }
1059     if max > stamp_mtime {
1060         build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1061     } else {
1062         build.verbose(&format!("updating {:?} as deps changed", stamp));
1063     }
1064     t!(t!(File::create(stamp)).write_all(&new_contents));
1065 }