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