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.
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.
11 //! Implementation of compiling various phases of the compiler and standard
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.
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};
27 use build_helper::{output, mtime, up_to_date};
28 use filetime::FileTime;
29 use rustc_serialize::json;
32 use util::{exe, libdir, is_dylib, copy};
33 use {Build, Compiler, Mode};
35 // for (krate, path, _default) in krates("std") {
36 // rules.build(&krate.build_step, path)
37 // .dep(|s| s.name("startup-objects"))
38 // .dep(move |s| s.name("rustc").host(&build.build).target(s.host))
39 // .run(move |s| compile::std(build, s.target, &s.compiler()));
41 // for (krate, path, _default) in krates("test") {
42 // rules.build(&krate.build_step, path)
43 // .dep(|s| s.name("libstd-link"))
44 // .run(move |s| compile::test(build, s.target, &s.compiler()));
46 // for (krate, path, _default) in krates("rustc-main") {
47 // rules.build(&krate.build_step, path)
48 // .dep(|s| s.name("libtest-link"))
49 // .dep(move |s| s.name("llvm").host(&build.build).stage(0))
50 // .dep(|s| s.name("may-run-build-script"))
51 // .run(move |s| compile::rustc(build, s.target, &s.compiler()));
54 // // Crates which have build scripts need to rely on this rule to ensure that
55 // // the necessary prerequisites for a build script are linked and located in
57 // rules.build("may-run-build-script", "path/to/nowhere")
59 // s.name("libstd-link")
60 // .host(&build.build)
61 // .target(&build.build)
64 // // ========================================================================
65 // // Crate compilations
67 // // Tools used during the build system but not shipped
68 // // These rules are "pseudo rules" that don't actually do any work
69 // // themselves, but represent a complete sysroot with the relevant compiler
70 // // linked into place.
72 // // That is, depending on "libstd" means that when the rule is completed then
73 // // the `stage` sysroot for the compiler `host` will be available with a
74 // // standard library built for `target` linked in place. Not all rules need
75 // // the compiler itself to be available, just the standard library, so
76 // // there's a distinction between the two.
77 // rules.build("libstd", "src/libstd")
78 // .dep(|s| s.name("rustc").target(s.host))
79 // .dep(|s| s.name("libstd-link"));
80 // rules.build("libtest", "src/libtest")
81 // .dep(|s| s.name("libstd"))
82 // .dep(|s| s.name("libtest-link"))
84 // rules.build("librustc", "src/librustc")
85 // .dep(|s| s.name("libtest"))
86 // .dep(|s| s.name("librustc-link"))
90 // Helper method to define the rules to link a crate into its place in the
93 // The logic here is a little subtle as there's a few cases to consider.
94 // Not all combinations of (stage, host, target) actually require something
95 // to be compiled, but rather libraries could get propagated from a
96 // different location. For example:
98 // * Any crate with a `host` that's not the build triple will not actually
99 // compile something. A different `host` means that the build triple will
100 // actually compile the libraries, and then we'll copy them over from the
101 // build triple to the `host` directory.
103 // * Some crates aren't even compiled by the build triple, but may be copied
104 // from previous stages. For example if we're not doing a full bootstrap
105 // then we may just depend on the stage1 versions of libraries to be
106 // available to get linked forward.
108 // * Finally, there are some cases, however, which do indeed comiple crates
109 // and link them into place afterwards.
111 // The rule definition below mirrors these three cases. The `dep` method
112 // calculates the correct dependency which either comes from stage1, a
113 // different compiler, or from actually building the crate itself (the `dep`
114 // rule). The `run` rule then mirrors these three cases and links the cases
115 // forward into the compiler sysroot specified from the correct location.
116 fn crate_rule<'a, 'b>(build: &'a Build,
117 rules: &'b mut Rules<'a>,
120 link: fn(&Build, &Compiler, &Compiler, &str))
121 -> RuleBuilder<'a, 'b> {
122 let mut rule = rules.build(&krate, "path/to/nowhere");
124 if build.force_use_stage1(&s.compiler(), s.target) {
125 s.host(&build.build).stage(1)
126 } else if s.host == build.build {
133 if build.force_use_stage1(&s.compiler(), s.target) {
135 &s.stage(1).host(&build.build).compiler(),
138 } else if s.host == build.build {
139 link(build, &s.compiler(), &s.compiler(), s.target)
142 &s.host(&build.build).compiler(),
150 /// Build the standard library.
152 /// This will build the standard library for a particular stage of the build
153 /// using the `compiler` targeting the `target` architecture. The artifacts
154 /// created will also be linked into the sysroot directory.
155 pub fn std(build: &Build, target: &str, compiler: &Compiler) {
156 let libdir = build.sysroot_libdir(compiler, target);
157 t!(fs::create_dir_all(&libdir));
159 let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
160 println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
161 compiler.host, target);
163 let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
164 build.clear_if_dirty(&out_dir, &build.compiler_path(compiler));
165 let mut cargo = build.cargo(compiler, Mode::Libstd, target, "build");
166 let mut features = build.std_features();
168 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
169 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
172 // When doing a local rebuild we tell cargo that we're stage1 rather than
173 // stage0. This works fine if the local rust and being-built rust have the
174 // same view of what the default allocator is, but fails otherwise. Since
175 // we don't have a way to express an allocator preference yet, work
176 // around the issue in the case of a local rebuild with jemalloc disabled.
177 if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
178 features.push_str(" force_alloc_system");
181 if compiler.stage != 0 && build.config.sanitizers {
182 // This variable is used by the sanitizer runtime crates, e.g.
183 // rustc_lsan, to build the sanitizer runtime from C code
184 // When this variable is missing, those crates won't compile the C code,
185 // so we don't set this variable during stage0 where llvm-config is
187 // We also only build the runtimes when --enable-sanitizers (or its
188 // config.toml equivalent) is used
189 cargo.env("LLVM_CONFIG", build.llvm_config(target));
191 cargo.arg("--features").arg(features)
192 .arg("--manifest-path")
193 .arg(build.src.join("src/libstd/Cargo.toml"));
195 if let Some(target) = build.config.target_config.get(target) {
196 if let Some(ref jemalloc) = target.jemalloc {
197 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
200 if target.contains("musl") {
201 if let Some(p) = build.musl_root(target) {
202 cargo.env("MUSL_ROOT", p);
208 &libstd_stamp(build, &compiler, target));
215 // "build-crate-std",
216 // compile::std_link)
217 // .dep(|s| s.name("startup-objects"))
218 // .dep(|s| s.name("create-sysroot").target(s.host));
219 /// Link all libstd rlibs/dylibs into the sysroot location.
221 /// Links those artifacts generated by `compiler` to a the `stage` compiler's
222 /// sysroot for the specified `host` and `target`.
224 /// Note that this assumes that `compiler` has already generated the libstd
225 /// libraries for `target`, and this method will find them in the relevant
226 /// output directory.
227 pub fn std_link(build: &Build,
229 target_compiler: &Compiler,
231 println!("Copying stage{} std from stage{} ({} -> {} / {})",
232 target_compiler.stage,
235 target_compiler.host,
237 let libdir = build.sysroot_libdir(target_compiler, target);
238 add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
240 if target.contains("musl") && !target.contains("mips") {
241 copy_musl_third_party_objects(build, target, &libdir);
244 if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
245 // The sanitizers are only built in stage1 or above, so the dylibs will
246 // be missing in stage0 and causes panic. See the `std()` function above
247 // for reason why the sanitizers are not built in stage0.
248 copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
252 /// Copies the crt(1,i,n).o startup objects
254 /// Only required for musl targets that statically link to libc
255 fn copy_musl_third_party_objects(build: &Build, target: &str, into: &Path) {
256 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
257 copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
261 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
262 for &sanitizer in &["asan", "tsan"] {
263 let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
264 let mut src_path = native_dir.join(sanitizer);
265 src_path.push("build");
266 src_path.push("lib");
267 src_path.push("darwin");
268 src_path.push(&filename);
269 copy(&src_path, &into.join(filename));
273 // rules.build("startup-objects", "src/rtstartup")
274 // .dep(|s| s.name("create-sysroot").target(s.host))
275 // .run(move |s| compile::build_startup_objects(build, &s.compiler(), s.target));
277 /// Build and prepare startup objects like rsbegin.o and rsend.o
279 /// These are primarily used on Windows right now for linking executables/dlls.
280 /// They don't require any library support as they're just plain old object
281 /// files, so we just use the nightly snapshot compiler to always build them (as
282 /// no other compilers are guaranteed to be available).
283 pub fn build_startup_objects(build: &Build, for_compiler: &Compiler, target: &str) {
284 if !target.contains("pc-windows-gnu") {
288 let compiler = Compiler::new(0, &build.build);
289 let compiler_path = build.compiler_path(&compiler);
290 let src_dir = &build.src.join("src/rtstartup");
291 let dst_dir = &build.native_dir(target).join("rtstartup");
292 let sysroot_dir = &build.sysroot_libdir(for_compiler, target);
293 t!(fs::create_dir_all(dst_dir));
294 t!(fs::create_dir_all(sysroot_dir));
296 for file in &["rsbegin", "rsend"] {
297 let src_file = &src_dir.join(file.to_string() + ".rs");
298 let dst_file = &dst_dir.join(file.to_string() + ".o");
299 if !up_to_date(src_file, dst_file) {
300 let mut cmd = Command::new(&compiler_path);
301 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
302 .arg("--cfg").arg(format!("stage{}", compiler.stage))
303 .arg("--target").arg(target)
305 .arg("--out-dir").arg(dst_dir)
309 copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
312 for obj in ["crt2.o", "dllcrt2.o"].iter() {
313 copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
319 /// This will build libtest and supporting libraries for a particular stage of
320 /// the build using the `compiler` targeting the `target` architecture. The
321 /// artifacts created will also be linked into the sysroot directory.
322 pub fn test(build: &Build, target: &str, compiler: &Compiler) {
323 let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
324 println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
325 compiler.host, target);
326 let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
327 build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
328 let mut cargo = build.cargo(compiler, Mode::Libtest, target, "build");
329 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
330 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
332 cargo.arg("--manifest-path")
333 .arg(build.src.join("src/libtest/Cargo.toml"));
336 &libtest_stamp(build, compiler, target));
343 // "build-crate-test",
344 // compile::test_link)
345 // .dep(|s| s.name("libstd-link"));
347 /// Same as `std_link`, only for libtest
348 pub fn test_link(build: &Build,
350 target_compiler: &Compiler,
352 println!("Copying stage{} test from stage{} ({} -> {} / {})",
353 target_compiler.stage,
356 target_compiler.host,
358 add_to_sysroot(&build.sysroot_libdir(target_compiler, target),
359 &libtest_stamp(build, compiler, target));
362 /// Build the compiler.
364 /// This will build the compiler for a particular stage of the build using
365 /// the `compiler` targeting the `target` architecture. The artifacts
366 /// created will also be linked into the sysroot directory.
367 pub fn rustc(build: &Build, target: &str, compiler: &Compiler) {
368 let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
369 println!("Building stage{} compiler artifacts ({} -> {})",
370 compiler.stage, compiler.host, target);
372 let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
373 build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
375 let mut cargo = build.cargo(compiler, Mode::Librustc, target, "build");
376 cargo.arg("--features").arg(build.rustc_features())
377 .arg("--manifest-path")
378 .arg(build.src.join("src/rustc/Cargo.toml"));
380 // Set some configuration variables picked up by build scripts and
381 // the compiler alike
382 cargo.env("CFG_RELEASE", build.rust_release())
383 .env("CFG_RELEASE_CHANNEL", &build.config.channel)
384 .env("CFG_VERSION", build.rust_version())
385 .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default());
387 if compiler.stage == 0 {
388 cargo.env("CFG_LIBDIR_RELATIVE", "lib");
390 let libdir_relative = build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
391 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
394 // If we're not building a compiler with debugging information then remove
395 // these two env vars which would be set otherwise.
396 if build.config.rust_debuginfo_only_std {
397 cargo.env_remove("RUSTC_DEBUGINFO");
398 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
401 if let Some(ref ver_date) = build.rust_info.commit_date() {
402 cargo.env("CFG_VER_DATE", ver_date);
404 if let Some(ref ver_hash) = build.rust_info.sha() {
405 cargo.env("CFG_VER_HASH", ver_hash);
407 if !build.unstable_features() {
408 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
410 // Flag that rust llvm is in use
411 if build.is_rust_llvm(target) {
412 cargo.env("LLVM_RUSTLLVM", "1");
414 cargo.env("LLVM_CONFIG", build.llvm_config(target));
415 let target_config = build.config.target_config.get(target);
416 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
417 cargo.env("CFG_LLVM_ROOT", s);
419 // Building with a static libstdc++ is only supported on linux right now,
420 // not for MSVC or macOS
421 if build.config.llvm_static_stdcpp &&
422 !target.contains("windows") &&
423 !target.contains("apple") {
424 cargo.env("LLVM_STATIC_STDCPP",
425 compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
427 if build.config.llvm_link_shared {
428 cargo.env("LLVM_LINK_SHARED", "1");
430 if let Some(ref s) = build.config.rustc_default_linker {
431 cargo.env("CFG_DEFAULT_LINKER", s);
433 if let Some(ref s) = build.config.rustc_default_ar {
434 cargo.env("CFG_DEFAULT_AR", s);
438 &librustc_stamp(build, compiler, target));
444 // "build-crate-rustc-main",
445 // compile::rustc_link)
446 // .dep(|s| s.name("libtest-link"));
447 /// Same as `std_link`, only for librustc
448 pub fn rustc_link(build: &Build,
450 target_compiler: &Compiler,
452 println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
453 target_compiler.stage,
456 target_compiler.host,
458 add_to_sysroot(&build.sysroot_libdir(target_compiler, target),
459 &librustc_stamp(build, compiler, target));
462 /// Cargo's output path for the standard library in a given stage, compiled
463 /// by a particular compiler for the specified target.
464 fn libstd_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
465 build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
468 /// Cargo's output path for libtest in a given stage, compiled by a particular
469 /// compiler for the specified target.
470 fn libtest_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
471 build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
474 /// Cargo's output path for librustc in a given stage, compiled by a particular
475 /// compiler for the specified target.
476 fn librustc_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
477 build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
480 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
481 let out = output(Command::new(compiler)
482 .arg(format!("-print-file-name={}", file)));
483 PathBuf::from(out.trim())
486 // rules.build("create-sysroot", "path/to/nowhere")
487 // .run(move |s| compile::create_sysroot(build, &s.compiler()));
488 pub fn create_sysroot(build: &Build, compiler: &Compiler) {
489 let sysroot = build.sysroot(compiler);
490 let _ = fs::remove_dir_all(&sysroot);
491 t!(fs::create_dir_all(&sysroot));
494 // the compiler with no target libraries ready to go
495 // rules.build("rustc", "src/rustc")
496 // .dep(|s| s.name("create-sysroot").target(s.host))
501 // s.name("librustc")
502 // .host(&build.build)
503 // .stage(s.stage - 1)
506 // .run(move |s| compile::assemble_rustc(build, s.stage, s.target));
507 /// Prepare a new compiler from the artifacts in `stage`
509 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
510 /// must have been previously produced by the `stage - 1` build.build
512 pub fn assemble_rustc(build: &Build, stage: u32, host: &str) {
513 // nothing to do in stage0
518 println!("Copying stage{} compiler ({})", stage, host);
520 // The compiler that we're assembling
521 let target_compiler = Compiler::new(stage, host);
523 // The compiler that compiled the compiler we're assembling
524 let build_compiler = Compiler::new(stage - 1, &build.build);
526 // Link in all dylibs to the libdir
527 let sysroot = build.sysroot(&target_compiler);
528 let sysroot_libdir = sysroot.join(libdir(host));
529 t!(fs::create_dir_all(&sysroot_libdir));
530 let src_libdir = build.sysroot_libdir(&build_compiler, host);
531 for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
532 let filename = f.file_name().into_string().unwrap();
533 if is_dylib(&filename) {
534 copy(&f.path(), &sysroot_libdir.join(&filename));
538 let out_dir = build.cargo_out(&build_compiler, Mode::Librustc, host);
540 // Link the compiler binary itself into place
541 let rustc = out_dir.join(exe("rustc", host));
542 let bindir = sysroot.join("bin");
543 t!(fs::create_dir_all(&bindir));
544 let compiler = build.compiler_path(&target_compiler);
545 let _ = fs::remove_file(&compiler);
546 copy(&rustc, &compiler);
548 // See if rustdoc exists to link it into place
549 let rustdoc = exe("rustdoc", host);
550 let rustdoc_src = out_dir.join(&rustdoc);
551 let rustdoc_dst = bindir.join(&rustdoc);
552 if fs::metadata(&rustdoc_src).is_ok() {
553 let _ = fs::remove_file(&rustdoc_dst);
554 copy(&rustdoc_src, &rustdoc_dst);
558 /// Link some files into a rustc sysroot.
560 /// For a particular stage this will link the file listed in `stamp` into the
561 /// `sysroot_dst` provided.
562 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
563 t!(fs::create_dir_all(&sysroot_dst));
564 let mut contents = Vec::new();
565 t!(t!(File::open(stamp)).read_to_end(&mut contents));
566 // This is the method we use for extracting paths from the stamp file passed to us. See
567 // run_cargo for more information (in this file).
568 for part in contents.split(|b| *b == 0) {
572 let path = Path::new(t!(str::from_utf8(part)));
573 copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
577 //// ========================================================================
580 //// Tools used during the build system but not shipped
581 //// "pseudo rule" which represents completely cleaning out the tools dir in
582 //// one stage. This needs to happen whenever a dependency changes (e.g.
583 //// libstd, libtest, librustc) and all of the tool compilations above will
584 //// be sequenced after this rule.
585 //rules.build("maybe-clean-tools", "path/to/nowhere")
586 // .after("librustc-tool")
587 // .after("libtest-tool")
588 // .after("libstd-tool");
590 //rules.build("librustc-tool", "path/to/nowhere")
591 // .dep(|s| s.name("librustc"))
592 // .run(move |s| compile::maybe_clean_tools(build, s.stage, s.target, Mode::Librustc));
593 //rules.build("libtest-tool", "path/to/nowhere")
594 // .dep(|s| s.name("libtest"))
595 // .run(move |s| compile::maybe_clean_tools(build, s.stage, s.target, Mode::Libtest));
596 //rules.build("libstd-tool", "path/to/nowhere")
597 // .dep(|s| s.name("libstd"))
598 // .run(move |s| compile::maybe_clean_tools(build, s.stage, s.target, Mode::Libstd));
600 /// Build a tool in `src/tools`
602 /// This will build the specified tool with the specified `host` compiler in
603 /// `stage` into the normal cargo output directory.
604 pub fn maybe_clean_tools(build: &Build, stage: u32, target: &str, mode: Mode) {
605 let compiler = Compiler::new(stage, &build.build);
607 let stamp = match mode {
608 Mode::Libstd => libstd_stamp(build, &compiler, target),
609 Mode::Libtest => libtest_stamp(build, &compiler, target),
610 Mode::Librustc => librustc_stamp(build, &compiler, target),
613 let out_dir = build.cargo_out(&compiler, Mode::Tool, target);
614 build.clear_if_dirty(&out_dir, &stamp);
618 // rules.build("tool-rustbook", "src/tools/rustbook")
619 // .dep(|s| s.name("maybe-clean-tools"))
620 // .dep(|s| s.name("librustc-tool"))
621 // .run(move |s| compile::tool(build, s.stage, s.target, "rustbook"));
622 // rules.build("tool-error-index", "src/tools/error_index_generator")
623 // .dep(|s| s.name("maybe-clean-tools"))
624 // .dep(|s| s.name("librustc-tool"))
625 // .run(move |s| compile::tool(build, s.stage, s.target, "error_index_generator"));
626 // rules.build("tool-unstable-book-gen", "src/tools/unstable-book-gen")
627 // .dep(|s| s.name("maybe-clean-tools"))
628 // .dep(|s| s.name("libstd-tool"))
629 // .run(move |s| compile::tool(build, s.stage, s.target, "unstable-book-gen"));
630 // rules.build("tool-tidy", "src/tools/tidy")
631 // .dep(|s| s.name("maybe-clean-tools"))
632 // .dep(|s| s.name("libstd-tool"))
633 // .run(move |s| compile::tool(build, s.stage, s.target, "tidy"));
634 // rules.build("tool-linkchecker", "src/tools/linkchecker")
635 // .dep(|s| s.name("maybe-clean-tools"))
636 // .dep(|s| s.name("libstd-tool"))
637 // .run(move |s| compile::tool(build, s.stage, s.target, "linkchecker"));
638 // rules.build("tool-cargotest", "src/tools/cargotest")
639 // .dep(|s| s.name("maybe-clean-tools"))
640 // .dep(|s| s.name("libstd-tool"))
641 // .run(move |s| compile::tool(build, s.stage, s.target, "cargotest"));
642 // rules.build("tool-compiletest", "src/tools/compiletest")
643 // .dep(|s| s.name("maybe-clean-tools"))
644 // .dep(|s| s.name("libtest-tool"))
645 // .run(move |s| compile::tool(build, s.stage, s.target, "compiletest"));
646 // rules.build("tool-build-manifest", "src/tools/build-manifest")
647 // .dep(|s| s.name("maybe-clean-tools"))
648 // .dep(|s| s.name("libstd-tool"))
649 // .run(move |s| compile::tool(build, s.stage, s.target, "build-manifest"));
650 // rules.build("tool-remote-test-server", "src/tools/remote-test-server")
651 // .dep(|s| s.name("maybe-clean-tools"))
652 // .dep(|s| s.name("libstd-tool"))
653 // .run(move |s| compile::tool(build, s.stage, s.target, "remote-test-server"));
654 // rules.build("tool-remote-test-client", "src/tools/remote-test-client")
655 // .dep(|s| s.name("maybe-clean-tools"))
656 // .dep(|s| s.name("libstd-tool"))
657 // .run(move |s| compile::tool(build, s.stage, s.target, "remote-test-client"));
658 // rules.build("tool-rust-installer", "src/tools/rust-installer")
659 // .dep(|s| s.name("maybe-clean-tools"))
660 // .dep(|s| s.name("libstd-tool"))
661 // .run(move |s| compile::tool(build, s.stage, s.target, "rust-installer"));
662 // rules.build("tool-cargo", "src/tools/cargo")
664 // .default(build.config.extended)
665 // .dep(|s| s.name("maybe-clean-tools"))
666 // .dep(|s| s.name("libstd-tool"))
667 // .dep(|s| s.stage(0).host(s.target).name("openssl"))
669 // // Cargo depends on procedural macros, which requires a full host
670 // // compiler to be available, so we need to depend on that.
671 // s.name("librustc-link")
672 // .target(&build.build)
673 // .host(&build.build)
675 // .run(move |s| compile::tool(build, s.stage, s.target, "cargo"));
676 // rules.build("tool-rls", "src/tools/rls")
678 // .default(build.config.extended)
679 // .dep(|s| s.name("librustc-tool"))
680 // .dep(|s| s.stage(0).host(s.target).name("openssl"))
682 // // rls, like cargo, uses procedural macros
683 // s.name("librustc-link")
684 // .target(&build.build)
685 // .host(&build.build)
687 // .run(move |s| compile::tool(build, s.stage, s.target, "rls"));
690 /// Build a tool in `src/tools`
692 /// This will build the specified tool with the specified `host` compiler in
693 /// `stage` into the normal cargo output directory.
694 pub fn tool(build: &Build, stage: u32, target: &str, tool: &str) {
695 let _folder = build.fold_output(|| format!("stage{}-{}", stage, tool));
696 println!("Building stage{} tool {} ({})", stage, tool, target);
698 let compiler = Compiler::new(stage, &build.build);
700 let mut cargo = build.cargo(&compiler, Mode::Tool, target, "build");
701 let dir = build.src.join("src/tools").join(tool);
702 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
704 // We don't want to build tools dynamically as they'll be running across
705 // stages and such and it's just easier if they're not dynamically linked.
706 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
708 if let Some(dir) = build.openssl_install_dir(target) {
709 cargo.env("OPENSSL_STATIC", "1");
710 cargo.env("OPENSSL_DIR", dir);
711 cargo.env("LIBZ_SYS_STATIC", "1");
714 cargo.env("CFG_RELEASE_CHANNEL", &build.config.channel);
716 let info = GitInfo::new(&dir);
717 if let Some(sha) = info.sha() {
718 cargo.env("CFG_COMMIT_HASH", sha);
720 if let Some(sha_short) = info.sha_short() {
721 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
723 if let Some(date) = info.commit_date() {
724 cargo.env("CFG_COMMIT_DATE", date);
727 build.run(&mut cargo);
731 // Avoiding a dependency on winapi to keep compile times down
733 fn stderr_isatty() -> bool {
735 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
738 fn stderr_isatty() -> bool {
741 type HANDLE = *mut u8;
742 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
744 fn GetStdHandle(which: DWORD) -> HANDLE;
745 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
748 let handle = GetStdHandle(STD_ERROR_HANDLE);
750 GetConsoleMode(handle, &mut out) != 0
754 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
755 // Instruct Cargo to give us json messages on stdout, critically leaving
756 // stderr as piped so we can get those pretty colors.
757 cargo.arg("--message-format").arg("json")
758 .stdout(Stdio::piped());
761 // since we pass message-format=json to cargo, we need to tell the rustc
762 // wrapper to give us colored output if necessary. This is because we
763 // only want Cargo's JSON output, not rustcs.
764 cargo.env("RUSTC_COLOR", "1");
767 build.verbose(&format!("running: {:?}", cargo));
768 let mut child = match cargo.spawn() {
770 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
773 // `target_root_dir` looks like $dir/$target/release
774 let target_root_dir = stamp.parent().unwrap();
775 // `target_deps_dir` looks like $dir/$target/release/deps
776 let target_deps_dir = target_root_dir.join("deps");
777 // `host_root_dir` looks like $dir/release
778 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
779 .parent().unwrap() // chop off `$target`
780 .join(target_root_dir.file_name().unwrap());
782 // Spawn Cargo slurping up its JSON output. We'll start building up the
783 // `deps` array of all files it generated along with a `toplevel` array of
784 // files we need to probe for later.
785 let mut deps = Vec::new();
786 let mut toplevel = Vec::new();
787 let stdout = BufReader::new(child.stdout.take().unwrap());
788 for line in stdout.lines() {
790 let json = if line.starts_with("{") {
791 t!(line.parse::<json::Json>())
793 // If this was informational, just print it out and continue
794 println!("{}", line);
797 if json.find("reason").and_then(|j| j.as_string()) != Some("compiler-artifact") {
800 for filename in json["filenames"].as_array().unwrap() {
801 let filename = filename.as_string().unwrap();
802 // Skip files like executables
803 if !filename.ends_with(".rlib") &&
804 !filename.ends_with(".lib") &&
805 !is_dylib(&filename) {
809 let filename = Path::new(filename);
811 // If this was an output file in the "host dir" we don't actually
812 // worry about it, it's not relevant for us.
813 if filename.starts_with(&host_root_dir) {
817 // If this was output in the `deps` dir then this is a precise file
818 // name (hash included) so we start tracking it.
819 if filename.starts_with(&target_deps_dir) {
820 deps.push(filename.to_path_buf());
824 // Otherwise this was a "top level artifact" which right now doesn't
825 // have a hash in the name, but there's a version of this file in
826 // the `deps` folder which *does* have a hash in the name. That's
827 // the one we'll want to we'll probe for it later.
828 toplevel.push((filename.file_stem().unwrap()
829 .to_str().unwrap().to_string(),
830 filename.extension().unwrap().to_owned()
831 .to_str().unwrap().to_string()));
835 // Make sure Cargo actually succeeded after we read all of its stdout.
836 let status = t!(child.wait());
837 if !status.success() {
838 panic!("command did not execute successfully: {:?}\n\
839 expected success, got: {}",
844 // Ok now we need to actually find all the files listed in `toplevel`. We've
845 // got a list of prefix/extensions and we basically just need to find the
846 // most recent file in the `deps` folder corresponding to each one.
847 let contents = t!(target_deps_dir.read_dir())
849 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
850 .collect::<Vec<_>>();
851 for (prefix, extension) in toplevel {
852 let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
853 filename.starts_with(&prefix[..]) &&
854 filename[prefix.len()..].starts_with("-") &&
855 filename.ends_with(&extension[..])
857 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
858 FileTime::from_last_modification_time(metadata)
860 let path_to_add = match max {
861 Some(triple) => triple.0.to_str().unwrap(),
862 None => panic!("no output generated for {:?} {:?}", prefix, extension),
864 if is_dylib(path_to_add) {
865 let candidate = format!("{}.lib", path_to_add);
866 let candidate = PathBuf::from(candidate);
867 if candidate.exists() {
868 deps.push(candidate);
871 deps.push(path_to_add.into());
874 // Now we want to update the contents of the stamp file, if necessary. First
875 // we read off the previous contents along with its mtime. If our new
876 // contents (the list of files to copy) is different or if any dep's mtime
877 // is newer then we rewrite the stamp file.
879 let mut stamp_contents = Vec::new();
880 if let Ok(mut f) = File::open(stamp) {
881 t!(f.read_to_end(&mut stamp_contents));
883 let stamp_mtime = mtime(&stamp);
884 let mut new_contents = Vec::new();
886 let mut max_path = None;
888 let mtime = mtime(&dep);
889 if Some(mtime) > max {
891 max_path = Some(dep.clone());
893 new_contents.extend(dep.to_str().unwrap().as_bytes());
894 new_contents.extend(b"\0");
896 let max = max.unwrap();
897 let max_path = max_path.unwrap();
898 if stamp_contents == new_contents && max <= stamp_mtime {
901 if max > stamp_mtime {
902 build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
904 build.verbose(&format!("updating {:?} as deps changed", stamp));
906 t!(t!(File::create(stamp)).write_all(&new_contents));