]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Migrate to serde_json entirely
[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 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, &builder.rustc(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 = builder.rustc(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 = builder.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(compiler.stage, &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 = builder.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 =
602                 build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
603             cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
604         }
605
606         // If we're not building a compiler with debugging information then remove
607         // these two env vars which would be set otherwise.
608         if build.config.rust_debuginfo_only_std {
609             cargo.env_remove("RUSTC_DEBUGINFO");
610             cargo.env_remove("RUSTC_DEBUGINFO_LINES");
611         }
612
613         if let Some(ref ver_date) = build.rust_info.commit_date() {
614             cargo.env("CFG_VER_DATE", ver_date);
615         }
616         if let Some(ref ver_hash) = build.rust_info.sha() {
617             cargo.env("CFG_VER_HASH", ver_hash);
618         }
619         if !build.unstable_features() {
620             cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
621         }
622         // Flag that rust llvm is in use
623         if build.is_rust_llvm(target) {
624             cargo.env("LLVM_RUSTLLVM", "1");
625         }
626         cargo.env("LLVM_CONFIG", build.llvm_config(target));
627         let target_config = build.config.target_config.get(target);
628         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
629             cargo.env("CFG_LLVM_ROOT", s);
630         }
631         // Building with a static libstdc++ is only supported on linux right now,
632         // not for MSVC or macOS
633         if build.config.llvm_static_stdcpp &&
634            !target.contains("windows") &&
635            !target.contains("apple") {
636             cargo.env("LLVM_STATIC_STDCPP",
637                       compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
638         }
639         if build.config.llvm_link_shared {
640             cargo.env("LLVM_LINK_SHARED", "1");
641         }
642         if let Some(ref s) = build.config.rustc_default_linker {
643             cargo.env("CFG_DEFAULT_LINKER", s);
644         }
645         if let Some(ref s) = build.config.rustc_default_ar {
646             cargo.env("CFG_DEFAULT_AR", s);
647         }
648         run_cargo(build,
649                   &mut cargo,
650                   &librustc_stamp(build, compiler, target));
651
652         builder.ensure(RustcLink {
653             compiler: builder.compiler(compiler.stage, &build.build),
654             target_compiler: compiler,
655             target,
656         });
657     }
658 }
659
660 // crate_rule(build,
661 //            &mut rules,
662 //            "librustc-link",
663 //            "build-crate-rustc-main",
664 //            compile::rustc_link)
665 //     .dep(|s| s.name("libtest-link"));
666 #[derive(Serialize)]
667 struct RustcLink<'a> {
668     pub compiler: Compiler<'a>,
669     pub target_compiler: Compiler<'a>,
670     pub target: &'a str,
671 }
672
673 impl<'a> Step<'a> for RustcLink<'a> {
674     type Output = ();
675
676     /// Same as `std_link`, only for librustc
677     fn run(self, builder: &Builder) {
678         let build = builder.build;
679         let compiler = self.compiler;
680         let target_compiler = self.target_compiler;
681         let target = self.target;
682         println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
683                  target_compiler.stage,
684                  compiler.stage,
685                  compiler.host,
686                  target_compiler.host,
687                  target);
688         add_to_sysroot(&builder.sysroot_libdir(target_compiler, target),
689                        &librustc_stamp(build, compiler, target));
690     }
691 }
692
693 /// Cargo's output path for the standard library in a given stage, compiled
694 /// by a particular compiler for the specified target.
695 pub fn libstd_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
696     build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
697 }
698
699 /// Cargo's output path for libtest in a given stage, compiled by a particular
700 /// compiler for the specified target.
701 pub fn libtest_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
702     build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
703 }
704
705 /// Cargo's output path for librustc in a given stage, compiled by a particular
706 /// compiler for the specified target.
707 pub fn librustc_stamp(build: &Build, compiler: Compiler, target: &str) -> PathBuf {
708     build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
709 }
710
711 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
712     let out = output(Command::new(compiler)
713                             .arg(format!("-print-file-name={}", file)));
714     PathBuf::from(out.trim())
715 }
716
717 // rules.build("create-sysroot", "path/to/nowhere")
718 //      .run(move |s| compile::create_sysroot(build, &s.compiler()));
719
720 #[derive(Serialize)]
721 pub struct Sysroot<'a> {
722     pub compiler: Compiler<'a>,
723 }
724
725 impl<'a> Step<'a> for Sysroot<'a> {
726     type Output = PathBuf;
727
728     /// Returns the sysroot for the `compiler` specified that *this build system
729     /// generates*.
730     ///
731     /// That is, the sysroot for the stage0 compiler is not what the compiler
732     /// thinks it is by default, but it's the same as the default for stages
733     /// 1-3.
734     fn run(self, builder: &Builder) -> PathBuf {
735         let build = builder.build;
736         let compiler = self.compiler;
737         let sysroot = if compiler.stage == 0 {
738             build.out.join(compiler.host).join("stage0-sysroot")
739         } else {
740             build.out.join(compiler.host).join(format!("stage{}", compiler.stage))
741         };
742         let _ = fs::remove_dir_all(&sysroot);
743         t!(fs::create_dir_all(&sysroot));
744         sysroot
745     }
746 }
747
748 // the compiler with no target libraries ready to go
749 // rules.build("rustc", "src/rustc")
750 //      .dep(|s| s.name("create-sysroot").target(s.host))
751 //      .dep(move |s| {
752 //          if s.stage == 0 {
753 //              Step::noop()
754 //          } else {
755 //              s.name("librustc")
756 //               .host(&build.build)
757 //               .stage(s.stage - 1)
758 //          }
759 //      })
760 //      .run(move |s| compile::assemble_rustc(build, s.stage, s.target));
761
762 #[derive(Serialize)]
763 pub struct Assemble<'a> {
764     /// The compiler which we will produce in this step. Assemble itself will
765     /// take care of ensuring that the necessary prerequisites to do so exist,
766     /// that is, this target can be a stage2 compiler and Assemble will build
767     /// previous stages for you.
768     pub target_compiler: Compiler<'a>,
769 }
770
771 impl<'a> Step<'a> for Assemble<'a> {
772     type Output = Compiler<'a>;
773
774     /// Prepare a new compiler from the artifacts in `stage`
775     ///
776     /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
777     /// must have been previously produced by the `stage - 1` build.build
778     /// compiler.
779     fn run(self, builder: &Builder) -> Compiler<'a> {
780         let build = builder.build;
781         let target_compiler = self.target_compiler;
782
783         if target_compiler.stage == 0 {
784             assert_eq!(build.build, target_compiler.host,
785                 "Cannot obtain compiler for non-native build triple at stage 0");
786             // The stage 0 compiler for the build triple is always pre-built.
787             return target_compiler;
788         }
789
790         // Get the compiler that we'll use to bootstrap ourselves.
791         let build_compiler = if target_compiler.host != build.build {
792             // Build a compiler for the host platform. We cannot use the stage0
793             // compiler for the host platform for this because it doesn't have
794             // the libraries we need.  FIXME: Perhaps we should download those
795             // libraries? It would make builds faster...
796             builder.ensure(Assemble {
797                 target_compiler: Compiler {
798                     // FIXME: It may be faster if we build just a stage 1
799                     // compiler and then use that to bootstrap this compiler
800                     // forward.
801                     stage: target_compiler.stage - 1,
802                     host: &build.build
803                 },
804             })
805         } else {
806             // Build the compiler we'll use to build the stage requested. This
807             // may build more than one compiler (going down to stage 0).
808             builder.ensure(Assemble {
809                 target_compiler: target_compiler.with_stage(target_compiler.stage - 1),
810             })
811         };
812
813         // Build the libraries for this compiler to link to (i.e., the libraries
814         // it uses at runtime). NOTE: Crates the target compiler compiles don't
815         // link to these. (FIXME: Is that correct? It seems to be correct most
816         // of the time but I think we do link to these for stage2/bin compilers
817         // when not performing a full bootstrap).
818         builder.ensure(Rustc { compiler: build_compiler, target: target_compiler.host });
819
820         let stage = target_compiler.stage;
821         let host = target_compiler.host;
822         println!("Assembling stage{} compiler ({})", stage, host);
823
824         // Link in all dylibs to the libdir
825         let sysroot = builder.sysroot(target_compiler);
826         let sysroot_libdir = sysroot.join(libdir(host));
827         t!(fs::create_dir_all(&sysroot_libdir));
828         let src_libdir = builder.sysroot_libdir(build_compiler, host);
829         for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
830             let filename = f.file_name().into_string().unwrap();
831             if is_dylib(&filename) {
832                 copy(&f.path(), &sysroot_libdir.join(&filename));
833             }
834         }
835
836         let out_dir = build.cargo_out(build_compiler, Mode::Librustc, host);
837
838         // Link the compiler binary itself into place
839         let rustc = out_dir.join(exe("rustc", host));
840         let bindir = sysroot.join("bin");
841         t!(fs::create_dir_all(&bindir));
842         let compiler = builder.rustc(target_compiler);
843         let _ = fs::remove_file(&compiler);
844         copy(&rustc, &compiler);
845
846         // See if rustdoc exists to link it into place
847         let rustdoc = exe("rustdoc", host);
848         let rustdoc_src = out_dir.join(&rustdoc);
849         let rustdoc_dst = bindir.join(&rustdoc);
850         if fs::metadata(&rustdoc_src).is_ok() {
851             let _ = fs::remove_file(&rustdoc_dst);
852             copy(&rustdoc_src, &rustdoc_dst);
853         }
854
855         target_compiler
856     }
857 }
858
859 /// Link some files into a rustc sysroot.
860 ///
861 /// For a particular stage this will link the file listed in `stamp` into the
862 /// `sysroot_dst` provided.
863 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
864     t!(fs::create_dir_all(&sysroot_dst));
865     let mut contents = Vec::new();
866     t!(t!(File::open(stamp)).read_to_end(&mut contents));
867     // This is the method we use for extracting paths from the stamp file passed to us. See
868     // run_cargo for more information (in this file).
869     for part in contents.split(|b| *b == 0) {
870         if part.is_empty() {
871             continue
872         }
873         let path = Path::new(t!(str::from_utf8(part)));
874         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
875     }
876 }
877
878 // Avoiding a dependency on winapi to keep compile times down
879 #[cfg(unix)]
880 fn stderr_isatty() -> bool {
881     use libc;
882     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
883 }
884 #[cfg(windows)]
885 fn stderr_isatty() -> bool {
886     type DWORD = u32;
887     type BOOL = i32;
888     type HANDLE = *mut u8;
889     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
890     extern "system" {
891         fn GetStdHandle(which: DWORD) -> HANDLE;
892         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
893     }
894     unsafe {
895         let handle = GetStdHandle(STD_ERROR_HANDLE);
896         let mut out = 0;
897         GetConsoleMode(handle, &mut out) != 0
898     }
899 }
900
901 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
902     // Instruct Cargo to give us json messages on stdout, critically leaving
903     // stderr as piped so we can get those pretty colors.
904     cargo.arg("--message-format").arg("json")
905          .stdout(Stdio::piped());
906
907     if stderr_isatty() {
908         // since we pass message-format=json to cargo, we need to tell the rustc
909         // wrapper to give us colored output if necessary. This is because we
910         // only want Cargo's JSON output, not rustcs.
911         cargo.env("RUSTC_COLOR", "1");
912     }
913
914     build.verbose(&format!("running: {:?}", cargo));
915     let mut child = match cargo.spawn() {
916         Ok(child) => child,
917         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
918     };
919
920     // `target_root_dir` looks like $dir/$target/release
921     let target_root_dir = stamp.parent().unwrap();
922     // `target_deps_dir` looks like $dir/$target/release/deps
923     let target_deps_dir = target_root_dir.join("deps");
924     // `host_root_dir` looks like $dir/release
925     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
926                                        .parent().unwrap() // chop off `$target`
927                                        .join(target_root_dir.file_name().unwrap());
928
929     // Spawn Cargo slurping up its JSON output. We'll start building up the
930     // `deps` array of all files it generated along with a `toplevel` array of
931     // files we need to probe for later.
932     let mut deps = Vec::new();
933     let mut toplevel = Vec::new();
934     let stdout = BufReader::new(child.stdout.take().unwrap());
935     for line in stdout.lines() {
936         let line = t!(line);
937         let json: serde_json::Value = if line.starts_with("{") {
938             t!(serde_json::from_str(&line))
939         } else {
940             // If this was informational, just print it out and continue
941             println!("{}", line);
942             continue
943         };
944         if json["reason"].as_str() != Some("compiler-artifact") {
945             continue
946         }
947         for filename in json["filenames"].as_array().unwrap() {
948             let filename = filename.as_str().unwrap();
949             // Skip files like executables
950             if !filename.ends_with(".rlib") &&
951                !filename.ends_with(".lib") &&
952                !is_dylib(&filename) {
953                 continue
954             }
955
956             let filename = Path::new(filename);
957
958             // If this was an output file in the "host dir" we don't actually
959             // worry about it, it's not relevant for us.
960             if filename.starts_with(&host_root_dir) {
961                 continue;
962             }
963
964             // If this was output in the `deps` dir then this is a precise file
965             // name (hash included) so we start tracking it.
966             if filename.starts_with(&target_deps_dir) {
967                 deps.push(filename.to_path_buf());
968                 continue;
969             }
970
971             // Otherwise this was a "top level artifact" which right now doesn't
972             // have a hash in the name, but there's a version of this file in
973             // the `deps` folder which *does* have a hash in the name. That's
974             // the one we'll want to we'll probe for it later.
975             toplevel.push((filename.file_stem().unwrap()
976                                     .to_str().unwrap().to_string(),
977                             filename.extension().unwrap().to_owned()
978                                     .to_str().unwrap().to_string()));
979         }
980     }
981
982     // Make sure Cargo actually succeeded after we read all of its stdout.
983     let status = t!(child.wait());
984     if !status.success() {
985         panic!("command did not execute successfully: {:?}\n\
986                 expected success, got: {}",
987                cargo,
988                status);
989     }
990
991     // Ok now we need to actually find all the files listed in `toplevel`. We've
992     // got a list of prefix/extensions and we basically just need to find the
993     // most recent file in the `deps` folder corresponding to each one.
994     let contents = t!(target_deps_dir.read_dir())
995         .map(|e| t!(e))
996         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
997         .collect::<Vec<_>>();
998     for (prefix, extension) in toplevel {
999         let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
1000             filename.starts_with(&prefix[..]) &&
1001                 filename[prefix.len()..].starts_with("-") &&
1002                 filename.ends_with(&extension[..])
1003         });
1004         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
1005             FileTime::from_last_modification_time(metadata)
1006         });
1007         let path_to_add = match max {
1008             Some(triple) => triple.0.to_str().unwrap(),
1009             None => panic!("no output generated for {:?} {:?}", prefix, extension),
1010         };
1011         if is_dylib(path_to_add) {
1012             let candidate = format!("{}.lib", path_to_add);
1013             let candidate = PathBuf::from(candidate);
1014             if candidate.exists() {
1015                 deps.push(candidate);
1016             }
1017         }
1018         deps.push(path_to_add.into());
1019     }
1020
1021     // Now we want to update the contents of the stamp file, if necessary. First
1022     // we read off the previous contents along with its mtime. If our new
1023     // contents (the list of files to copy) is different or if any dep's mtime
1024     // is newer then we rewrite the stamp file.
1025     deps.sort();
1026     let mut stamp_contents = Vec::new();
1027     if let Ok(mut f) = File::open(stamp) {
1028         t!(f.read_to_end(&mut stamp_contents));
1029     }
1030     let stamp_mtime = mtime(&stamp);
1031     let mut new_contents = Vec::new();
1032     let mut max = None;
1033     let mut max_path = None;
1034     for dep in deps {
1035         let mtime = mtime(&dep);
1036         if Some(mtime) > max {
1037             max = Some(mtime);
1038             max_path = Some(dep.clone());
1039         }
1040         new_contents.extend(dep.to_str().unwrap().as_bytes());
1041         new_contents.extend(b"\0");
1042     }
1043     let max = max.unwrap();
1044     let max_path = max_path.unwrap();
1045     if stamp_contents == new_contents && max <= stamp_mtime {
1046         return
1047     }
1048     if max > stamp_mtime {
1049         build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
1050     } else {
1051         build.verbose(&format!("updating {:?} as deps changed", stamp));
1052     }
1053     t!(t!(File::create(stamp)).write_all(&new_contents));
1054 }