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 rustbuild, the Rust build system.
13 //! This module, and its descendants, are the implementation of the Rust build
14 //! system. Most of this build system is backed by Cargo but the outer layer
15 //! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
16 //! builds, building artifacts like LLVM, etc. The goals of rustbuild are:
18 //! * To be an easily understandable, easily extensible, and maintainable build
20 //! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
21 //! crates.io and Cargo.
22 //! * A standard interface to build across all platforms, including MSVC
26 //! Although this build system defers most of the complicated logic to Cargo
27 //! itself, it still needs to maintain a list of targets and dependencies which
28 //! it can itself perform. Rustbuild is made up of a list of rules with
29 //! dependencies amongst them (created in the `step` module) and then knows how
30 //! to execute each in sequence. Each time rustbuild is invoked, it will simply
31 //! iterate through this list of steps and execute each serially in turn. For
32 //! each step rustbuild relies on the step internally being incremental and
33 //! parallel. Note, though, that the `-j` parameter to rustbuild gets forwarded
34 //! to appropriate test harnesses and such.
36 //! Most of the "meaty" steps that matter are backed by Cargo, which does indeed
37 //! have its own parallelism and incremental management. Later steps, like
38 //! tests, aren't incremental and simply run the entire suite currently.
40 //! When you execute `x.py build`, the steps which are executed are:
42 //! * First, the python script is run. This will automatically download the
43 //! stage0 rustc and cargo according to `src/stage0.txt`, or using the cached
44 //! versions if they're available. These are then used to compile rustbuild
45 //! itself (using Cargo). Finally, control is then transferred to rustbuild.
47 //! * Rustbuild takes over, performs sanity checks, probes the environment,
48 //! reads configuration, builds up a list of steps, and then starts executing
51 //! * The stage0 libstd is compiled
52 //! * The stage0 libtest is compiled
53 //! * The stage0 librustc is compiled
54 //! * The stage1 compiler is assembled
55 //! * The stage1 libstd, libtest, librustc are compiled
56 //! * The stage2 compiler is assembled
57 //! * The stage2 libstd, libtest, librustc are compiled
59 //! Each step is driven by a separate Cargo project and rustbuild orchestrates
60 //! copying files between steps and otherwise preparing for Cargo to run.
62 //! ## Further information
64 //! More documentation can be found in each respective module below, and you can
65 //! also check out the `src/bootstrap/README.md` file for more information.
70 extern crate build_helper;
72 extern crate filetime;
75 extern crate num_cpus;
76 extern crate rustc_serialize;
80 use std::collections::HashMap;
82 use std::ffi::OsString;
83 use std::fs::{self, File};
85 use std::path::{PathBuf, Path};
86 use std::process::Command;
88 use build_helper::{run_silent, run_suppressed, output, mtime};
90 use util::{exe, libdir, add_lib_path};
113 pub unsafe fn setup() {}
116 pub use config::Config;
117 pub use flags::{Flags, Subcommand};
119 /// A structure representing a Rust compiler.
121 /// Each compiler has a `stage` that it is associated with and a `host` that
122 /// corresponds to the platform the compiler runs on. This structure is used as
123 /// a parameter to many methods below.
124 #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
125 pub struct Compiler<'a> {
130 /// Global configuration for the build system.
132 /// This structure transitively contains all configuration for the build system.
133 /// All filesystem-encoded configuration is in `config`, all flags are in
134 /// `flags`, and then parsed or probed information is listed in the keys below.
136 /// This structure is a parameter of almost all methods in the build system,
137 /// although most functions are implemented as free functions rather than
138 /// methods specifically on this structure itself (to make it easier to
141 // User-specified configuration via config.toml
144 // User-specified configuration via CLI flags
147 // Derived properties from the above two configurations
152 rust_info: channel::GitInfo,
153 cargo_info: channel::GitInfo,
154 rls_info: channel::GitInfo,
157 // Probed tools at runtime
158 lldb_version: Option<String>,
159 lldb_python_dir: Option<String>,
161 // Runtime state filled in later on
162 cc: HashMap<String, (gcc::Tool, Option<PathBuf>)>,
163 cxx: HashMap<String, gcc::Tool>,
164 crates: HashMap<String, Crate>,
181 /// The various "modes" of invoking Cargo.
183 /// These entries currently correspond to the various output directories of the
184 /// build system, with each mod generating output in a different directory.
185 #[derive(Clone, Copy, PartialEq, Eq)]
187 /// This cargo is going to build the standard library, placing output in the
188 /// "stageN-std" directory.
191 /// This cargo is going to build libtest, placing output in the
192 /// "stageN-test" directory.
195 /// This cargo is going to build librustc and compiler libraries, placing
196 /// output in the "stageN-rustc" directory.
199 /// This cargo is going to some build tool, placing output in the
200 /// "stageN-tools" directory.
205 /// Creates a new set of build configuration from the `flags` on the command
206 /// line and the filesystem `config`.
208 /// By default all build output will be placed in the current directory.
209 pub fn new(flags: Flags, config: Config) -> Build {
210 let cwd = t!(env::current_dir());
211 let src = flags.src.clone().or_else(|| {
212 env::var_os("SRC").map(|x| x.into())
213 }).unwrap_or(cwd.clone());
214 let out = cwd.join("build");
216 let stage0_root = out.join(&config.build).join("stage0/bin");
217 let rustc = match config.rustc {
218 Some(ref s) => PathBuf::from(s),
219 None => stage0_root.join(exe("rustc", &config.build)),
221 let cargo = match config.cargo {
222 Some(ref s) => PathBuf::from(s),
223 None => stage0_root.join(exe("cargo", &config.build)),
225 let local_rebuild = config.local_rebuild;
227 let is_sudo = match env::var_os("SUDO_USER") {
229 match env::var_os("USER") {
230 Some(user) => user != sudo_user,
236 let rust_info = channel::GitInfo::new(&src);
237 let cargo_info = channel::GitInfo::new(&src.join("src/tools/cargo"));
238 let rls_info = channel::GitInfo::new(&src.join("src/tools/rls"));
239 let src_is_git = src.join(".git").exists();
249 rust_info: rust_info,
250 cargo_info: cargo_info,
252 local_rebuild: local_rebuild,
255 crates: HashMap::new(),
257 lldb_python_dir: None,
259 src_is_git: src_is_git,
263 /// Executes the entire build, as configured by the flags and configuration.
264 pub fn build(&mut self) {
269 if let Subcommand::Clean = self.flags.cmd {
270 return clean::clean(self);
273 self.verbose("finding compilers");
275 self.verbose("running sanity check");
277 // If local-rust is the same major.minor as the current version, then force a local-rebuild
278 let local_version_verbose = output(
279 Command::new(&self.rustc).arg("--version").arg("--verbose"));
280 let local_release = local_version_verbose
281 .lines().filter(|x| x.starts_with("release:"))
282 .next().unwrap().trim_left_matches("release:").trim();
283 let my_version = channel::CFG_RELEASE_NUM;
284 if local_release.split('.').take(2).eq(my_version.split('.').take(2)) {
285 self.verbose(&format!("auto-detected local-rebuild {}", local_release));
286 self.local_rebuild = true;
288 self.verbose("learning about cargo");
289 metadata::build(self);
294 /// Clear out `dir` if `input` is newer.
296 /// After this executes, it will also ensure that `dir` exists.
297 fn clear_if_dirty(&self, dir: &Path, input: &Path) {
298 let stamp = dir.join(".stamp");
299 if mtime(&stamp) < mtime(input) {
300 self.verbose(&format!("Dirty - {}", dir.display()));
301 let _ = fs::remove_dir_all(dir);
302 } else if stamp.exists() {
305 t!(fs::create_dir_all(dir));
306 t!(File::create(stamp));
309 /// Prepares an invocation of `cargo` to be run.
311 /// This will create a `Command` that represents a pending execution of
312 /// Cargo. This cargo will be configured to use `compiler` as the actual
313 /// rustc compiler, its output will be scoped by `mode`'s output directory,
314 /// it will pass the `--target` flag for the specified `target`, and will be
315 /// executing the Cargo command `cmd`.
320 cmd: &str) -> Command {
321 let mut cargo = Command::new(&self.cargo);
322 let out_dir = self.stage_out(compiler, mode);
323 cargo.env("CARGO_TARGET_DIR", out_dir)
325 .arg("-j").arg(self.jobs().to_string())
326 .arg("--target").arg(target);
328 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
329 // Force cargo to output binaries with disambiguating hashes in the name
330 cargo.env("__CARGO_DEFAULT_LIB_METADATA", "1");
333 if compiler.stage == 0 && self.local_rebuild {
334 // Assume the local-rebuild rustc already has stage1 features.
337 stage = compiler.stage;
340 // Customize the compiler we're running. Specify the compiler to cargo
341 // as our shim and then pass it some various options used to configure
342 // how the actual compiler itself is called.
344 // These variables are primarily all read by
345 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
346 cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
347 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
348 .env("RUSTC_REAL", self.compiler_path(compiler))
349 .env("RUSTC_STAGE", stage.to_string())
350 .env("RUSTC_CODEGEN_UNITS",
351 self.config.rust_codegen_units.to_string())
352 .env("RUSTC_DEBUG_ASSERTIONS",
353 self.config.rust_debug_assertions.to_string())
354 .env("RUSTC_SYSROOT", self.sysroot(compiler))
355 .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
356 .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
357 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
358 .env("RUSTDOC_REAL", self.rustdoc(compiler))
359 .env("RUSTC_FLAGS", self.rustc_flags(target).join(" "));
361 if mode != Mode::Tool {
362 // Tools don't get debuginfo right now, e.g. cargo and rls don't
363 // get compiled with debuginfo.
364 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string())
365 .env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string())
366 .env("RUSTC_FORCE_UNSTABLE", "1");
368 // Currently the compiler depends on crates from crates.io, and
369 // then other crates can depend on the compiler (e.g. proc-macro
370 // crates). Let's say, for example that rustc itself depends on the
371 // bitflags crate. If an external crate then depends on the
372 // bitflags crate as well, we need to make sure they don't
373 // conflict, even if they pick the same verison of bitflags. We'll
374 // want to make sure that e.g. a plugin and rustc each get their
375 // own copy of bitflags.
377 // Cargo ensures that this works in general through the -C metadata
378 // flag. This flag will frob the symbols in the binary to make sure
379 // they're different, even though the source code is the exact
380 // same. To solve this problem for the compiler we extend Cargo's
381 // already-passed -C metadata flag with our own. Our rustc.rs
382 // wrapper around the actual rustc will detect -C metadata being
383 // passed and frob it with this extra string we're passing in.
384 cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
387 // Enable usage of unstable features
388 cargo.env("RUSTC_BOOTSTRAP", "1");
389 self.add_rust_test_threads(&mut cargo);
391 // Almost all of the crates that we compile as part of the bootstrap may
392 // have a build script, including the standard library. To compile a
393 // build script, however, it itself needs a standard library! This
394 // introduces a bit of a pickle when we're compiling the standard
397 // To work around this we actually end up using the snapshot compiler
398 // (stage0) for compiling build scripts of the standard library itself.
399 // The stage0 compiler is guaranteed to have a libstd available for use.
401 // For other crates, however, we know that we've already got a standard
402 // library up and running, so we can use the normal compiler to compile
403 // build scripts in that situation.
404 if mode == Mode::Libstd {
405 cargo.env("RUSTC_SNAPSHOT", &self.rustc)
406 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
408 cargo.env("RUSTC_SNAPSHOT", self.compiler_path(compiler))
409 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
412 // There are two invariants we try must maintain:
413 // * stable crates cannot depend on unstable crates (general Rust rule),
414 // * crates that end up in the sysroot must be unstable (rustbuild rule).
416 // In order to do enforce the latter, we pass the env var
417 // `RUSTBUILD_UNSTABLE` down the line for any crates which will end up
418 // in the sysroot. We read this in bootstrap/bin/rustc.rs and if it is
419 // set, then we pass the `rustbuild` feature to rustc when building the
422 // In turn, crates that can be used here should recognise the `rustbuild`
423 // feature and opt-in to `rustc_private`.
425 // We can't always pass `rustbuild` because crates which are outside of
426 // the comipiler, libs, and tests are stable and we don't want to make
427 // their deps unstable (since this would break the first invariant
430 // FIXME: remove this after next stage0
431 if mode != Mode::Tool && stage == 0 {
432 cargo.env("RUSTBUILD_UNSTABLE", "1");
435 // Ignore incremental modes except for stage0, since we're
436 // not guaranteeing correctness acros builds if the compiler
437 // is changing under your feet.`
438 if self.flags.incremental && compiler.stage == 0 {
439 let incr_dir = self.incremental_dir(compiler);
440 cargo.env("RUSTC_INCREMENTAL", incr_dir);
443 if let Some(ref on_fail) = self.flags.on_fail {
444 cargo.env("RUSTC_ON_FAIL", on_fail);
447 let verbose = cmp::max(self.config.verbose, self.flags.verbose);
448 cargo.env("RUSTC_VERBOSE", format!("{}", verbose));
450 // Specify some various options for build scripts used throughout
453 // FIXME: the guard against msvc shouldn't need to be here
454 if !target.contains("msvc") {
455 cargo.env(format!("CC_{}", target), self.cc(target))
456 .env(format!("AR_{}", target), self.ar(target).unwrap()) // only msvc is None
457 .env(format!("CFLAGS_{}", target), self.cflags(target).join(" "));
460 if self.config.extended && compiler.is_final_stage(self) {
461 cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
464 // When being built Cargo will at some point call `nmake.exe` on Windows
465 // MSVC. Unfortunately `nmake` will read these two environment variables
466 // below and try to intepret them. We're likely being run, however, from
467 // MSYS `make` which uses the same variables.
469 // As a result, to prevent confusion and errors, we remove these
470 // variables from our environment to prevent passing MSYS make flags to
471 // nmake, causing it to blow up.
472 if cfg!(target_env = "msvc") {
473 cargo.env_remove("MAKE");
474 cargo.env_remove("MAKEFLAGS");
477 // Environment variables *required* needed throughout the build
479 // FIXME: should update code to not require this env var
480 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
482 if self.config.verbose() || self.flags.verbose() {
485 // FIXME: cargo bench does not accept `--release`
486 if self.config.rust_optimize && cmd != "bench" {
487 cargo.arg("--release");
489 if self.config.locked_deps {
490 cargo.arg("--locked");
492 if self.config.vendor || self.is_sudo {
493 cargo.arg("--frozen");
498 /// Get a path to the compiler specified.
499 fn compiler_path(&self, compiler: &Compiler) -> PathBuf {
500 if compiler.is_snapshot(self) {
503 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
507 /// Get the specified tool built by the specified compiler
508 fn tool(&self, compiler: &Compiler, tool: &str) -> PathBuf {
509 self.cargo_out(compiler, Mode::Tool, compiler.host)
510 .join(exe(tool, compiler.host))
513 /// Get the `rustdoc` executable next to the specified compiler
514 fn rustdoc(&self, compiler: &Compiler) -> PathBuf {
515 let mut rustdoc = self.compiler_path(compiler);
517 rustdoc.push(exe("rustdoc", compiler.host));
521 /// Get a `Command` which is ready to run `tool` in `stage` built for
523 fn tool_cmd(&self, compiler: &Compiler, tool: &str) -> Command {
524 let mut cmd = Command::new(self.tool(&compiler, tool));
525 self.prepare_tool_cmd(compiler, &mut cmd);
529 /// Prepares the `cmd` provided to be able to run the `compiler` provided.
531 /// Notably this munges the dynamic library lookup path to point to the
532 /// right location to run `compiler`.
533 fn prepare_tool_cmd(&self, compiler: &Compiler, cmd: &mut Command) {
534 let host = compiler.host;
535 let mut paths = vec![
536 self.sysroot_libdir(compiler, compiler.host),
537 self.cargo_out(compiler, Mode::Tool, host).join("deps"),
540 // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
541 // mode) and that C compiler may need some extra PATH modification. Do
543 if compiler.host.contains("msvc") {
544 let curpaths = env::var_os("PATH").unwrap_or(OsString::new());
545 let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
546 for &(ref k, ref v) in self.cc[compiler.host].0.env() {
550 for path in env::split_paths(v) {
551 if !curpaths.contains(&path) {
557 add_lib_path(paths, cmd);
560 /// Get the space-separated set of activated features for the standard
562 fn std_features(&self) -> String {
563 let mut features = "panic-unwind".to_string();
565 if self.config.debug_jemalloc {
566 features.push_str(" debug-jemalloc");
568 if self.config.use_jemalloc {
569 features.push_str(" jemalloc");
571 if self.config.backtrace {
572 features.push_str(" backtrace");
577 /// Get the space-separated set of activated features for the compiler.
578 fn rustc_features(&self) -> String {
579 let mut features = String::new();
580 if self.config.use_jemalloc {
581 features.push_str(" jemalloc");
586 /// Component directory that Cargo will produce output into (e.g.
588 fn cargo_dir(&self) -> &'static str {
589 if self.config.rust_optimize {"release"} else {"debug"}
592 /// Returns the sysroot for the `compiler` specified that *this build system
595 /// That is, the sysroot for the stage0 compiler is not what the compiler
596 /// thinks it is by default, but it's the same as the default for stages
598 fn sysroot(&self, compiler: &Compiler) -> PathBuf {
599 if compiler.stage == 0 {
600 self.out.join(compiler.host).join("stage0-sysroot")
602 self.out.join(compiler.host).join(format!("stage{}", compiler.stage))
606 /// Get the directory for incremental by-products when using the
608 fn incremental_dir(&self, compiler: &Compiler) -> PathBuf {
609 self.out.join(compiler.host).join(format!("stage{}-incremental", compiler.stage))
612 /// Returns the libdir where the standard library and other artifacts are
613 /// found for a compiler's sysroot.
614 fn sysroot_libdir(&self, compiler: &Compiler, target: &str) -> PathBuf {
615 self.sysroot(compiler).join("lib").join("rustlib")
616 .join(target).join("lib")
619 /// Returns the root directory for all output generated in a particular
620 /// stage when running with a particular host compiler.
622 /// The mode indicates what the root directory is for.
623 fn stage_out(&self, compiler: &Compiler, mode: Mode) -> PathBuf {
624 let suffix = match mode {
625 Mode::Libstd => "-std",
626 Mode::Libtest => "-test",
627 Mode::Tool => "-tools",
628 Mode::Librustc => "-rustc",
630 self.out.join(compiler.host)
631 .join(format!("stage{}{}", compiler.stage, suffix))
634 /// Returns the root output directory for all Cargo output in a given stage,
635 /// running a particular comipler, wehther or not we're building the
636 /// standard library, and targeting the specified architecture.
640 target: &str) -> PathBuf {
641 self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
644 /// Root output directory for LLVM compiled for `target`
646 /// Note that if LLVM is configured externally then the directory returned
647 /// will likely be empty.
648 fn llvm_out(&self, target: &str) -> PathBuf {
649 self.out.join(target).join("llvm")
652 /// Output directory for all documentation for a target
653 fn doc_out(&self, target: &str) -> PathBuf {
654 self.out.join(target).join("doc")
657 /// Output directory for all crate documentation for a target (temporary)
659 /// The artifacts here are then copied into `doc_out` above.
660 fn crate_doc_out(&self, target: &str) -> PathBuf {
661 self.out.join(target).join("crate-docs")
664 /// Returns true if no custom `llvm-config` is set for the specified target.
666 /// If no custom `llvm-config` was specified then Rust's llvm will be used.
667 fn is_rust_llvm(&self, target: &str) -> bool {
668 match self.config.target_config.get(target) {
669 Some(ref c) => c.llvm_config.is_none(),
674 /// Returns the path to `llvm-config` for the specified target.
676 /// If a custom `llvm-config` was specified for target then that's returned
678 fn llvm_config(&self, target: &str) -> PathBuf {
679 let target_config = self.config.target_config.get(target);
680 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
683 self.llvm_out(&self.config.build).join("bin")
684 .join(exe("llvm-config", target))
688 /// Returns the path to `FileCheck` binary for the specified target
689 fn llvm_filecheck(&self, target: &str) -> PathBuf {
690 let target_config = self.config.target_config.get(target);
691 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
692 let llvm_bindir = output(Command::new(s).arg("--bindir"));
693 Path::new(llvm_bindir.trim()).join(exe("FileCheck", target))
695 let base = self.llvm_out(&self.config.build).join("build");
696 let exe = exe("FileCheck", target);
697 if !self.config.ninja && self.config.build.contains("msvc") {
698 base.join("Release/bin").join(exe)
700 base.join("bin").join(exe)
705 /// Directory for libraries built from C/C++ code and shared between stages.
706 fn native_dir(&self, target: &str) -> PathBuf {
707 self.out.join(target).join("native")
710 /// Root output directory for rust_test_helpers library compiled for
712 fn test_helpers_out(&self, target: &str) -> PathBuf {
713 self.native_dir(target).join("rust-test-helpers")
716 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
717 /// library lookup path.
718 fn add_rustc_lib_path(&self, compiler: &Compiler, cmd: &mut Command) {
719 // Windows doesn't need dylib path munging because the dlls for the
720 // compiler live next to the compiler and the system will find them
726 add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
729 /// Adds the `RUST_TEST_THREADS` env var if necessary
730 fn add_rust_test_threads(&self, cmd: &mut Command) {
731 if env::var_os("RUST_TEST_THREADS").is_none() {
732 cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
736 /// Returns the compiler's libdir where it stores the dynamic libraries that
737 /// it itself links against.
739 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
741 fn rustc_libdir(&self, compiler: &Compiler) -> PathBuf {
742 if compiler.is_snapshot(self) {
743 self.rustc_snapshot_libdir()
745 self.sysroot(compiler).join(libdir(compiler.host))
749 /// Returns the libdir of the snapshot compiler.
750 fn rustc_snapshot_libdir(&self) -> PathBuf {
751 self.rustc.parent().unwrap().parent().unwrap()
752 .join(libdir(&self.config.build))
755 /// Runs a command, printing out nice contextual information if it fails.
756 fn run(&self, cmd: &mut Command) {
757 self.verbose(&format!("running: {:?}", cmd));
761 /// Runs a command, printing out nice contextual information if it fails.
762 fn run_quiet(&self, cmd: &mut Command) {
763 self.verbose(&format!("running: {:?}", cmd));
767 /// Prints a message if this build is configured in verbose mode.
768 fn verbose(&self, msg: &str) {
769 if self.flags.verbose() || self.config.verbose() {
774 /// Returns the number of parallel jobs that have been configured for this
776 fn jobs(&self) -> u32 {
777 self.flags.jobs.unwrap_or(num_cpus::get() as u32)
780 /// Returns the path to the C compiler for the target specified.
781 fn cc(&self, target: &str) -> &Path {
782 self.cc[target].0.path()
785 /// Returns a list of flags to pass to the C compiler for the target
787 fn cflags(&self, target: &str) -> Vec<String> {
788 // Filter out -O and /O (the optimization flags) that we picked up from
789 // gcc-rs because the build scripts will determine that for themselves.
790 let mut base = self.cc[target].0.args().iter()
791 .map(|s| s.to_string_lossy().into_owned())
792 .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
793 .collect::<Vec<_>>();
795 // If we're compiling on macOS then we add a few unconditional flags
796 // indicating that we want libc++ (more filled out than libstdc++) and
797 // we want to compile for 10.7. This way we can ensure that
798 // LLVM/jemalloc/etc are all properly compiled.
799 if target.contains("apple-darwin") {
800 base.push("-stdlib=libc++".into());
803 // Work around an apparently bad MinGW / GCC optimization,
804 // See: http://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
805 // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
806 if target == "i686-pc-windows-gnu" {
807 base.push("-fno-omit-frame-pointer".into());
812 /// Returns the path to the `ar` archive utility for the target specified.
813 fn ar(&self, target: &str) -> Option<&Path> {
814 self.cc[target].1.as_ref().map(|p| &**p)
817 /// Returns the path to the C++ compiler for the target specified, may panic
818 /// if no C++ compiler was configured for the target.
819 fn cxx(&self, target: &str) -> &Path {
820 match self.cxx.get(target) {
822 None => panic!("\n\ntarget `{}` is not configured as a host,
823 only as a target\n\n", target),
827 /// Returns flags to pass to the compiler to generate code for `target`.
828 fn rustc_flags(&self, target: &str) -> Vec<String> {
829 // New flags should be added here with great caution!
831 // It's quite unfortunate to **require** flags to generate code for a
832 // target, so it should only be passed here if absolutely necessary!
833 // Most default configuration should be done through target specs rather
834 // than an entry here.
836 let mut base = Vec::new();
837 if target != self.config.build && !target.contains("msvc") &&
838 !target.contains("emscripten") {
839 base.push(format!("-Clinker={}", self.cc(target).display()));
844 /// Returns the "musl root" for this `target`, if defined
845 fn musl_root(&self, target: &str) -> Option<&Path> {
846 self.config.target_config.get(target)
847 .and_then(|t| t.musl_root.as_ref())
848 .or(self.config.musl_root.as_ref())
852 /// Returns whether the target will be tested using the `remote-test-client`
853 /// and `remote-test-server` binaries.
854 fn remote_tested(&self, target: &str) -> bool {
855 self.qemu_rootfs(target).is_some() || target.contains("android")
858 /// Returns the root of the "rootfs" image that this target will be using,
859 /// if one was configured.
861 /// If `Some` is returned then that means that tests for this target are
862 /// emulated with QEMU and binaries will need to be shipped to the emulator.
863 fn qemu_rootfs(&self, target: &str) -> Option<&Path> {
864 self.config.target_config.get(target)
865 .and_then(|t| t.qemu_rootfs.as_ref())
869 /// Path to the python interpreter to use
870 fn python(&self) -> &Path {
871 self.config.python.as_ref().unwrap()
874 /// Tests whether the `compiler` compiling for `target` should be forced to
875 /// use a stage1 compiler instead.
877 /// Currently, by default, the build system does not perform a "full
878 /// bootstrap" by default where we compile the compiler three times.
879 /// Instead, we compile the compiler two times. The final stage (stage2)
880 /// just copies the libraries from the previous stage, which is what this
883 /// Here we return `true` if:
885 /// * The build isn't performing a full bootstrap
886 /// * The `compiler` is in the final stage, 2
887 /// * We're not cross-compiling, so the artifacts are already available in
890 /// When all of these conditions are met the build will lift artifacts from
891 /// the previous stage forward.
892 fn force_use_stage1(&self, compiler: &Compiler, target: &str) -> bool {
893 !self.config.full_bootstrap &&
894 compiler.stage >= 2 &&
895 self.config.host.iter().any(|h| h == target)
898 /// Returns the directory that OpenSSL artifacts are compiled into if
899 /// configured to do so.
900 fn openssl_dir(&self, target: &str) -> Option<PathBuf> {
901 // OpenSSL not used on Windows
902 if target.contains("windows") {
904 } else if self.config.openssl_static {
905 Some(self.out.join(target).join("openssl"))
911 /// Returns the directory that OpenSSL artifacts are installed into if
912 /// configured as such.
913 fn openssl_install_dir(&self, target: &str) -> Option<PathBuf> {
914 self.openssl_dir(target).map(|p| p.join("install"))
917 /// Given `num` in the form "a.b.c" return a "release string" which
918 /// describes the release version number.
920 /// For example on nightly this returns "a.b.c-nightly", on beta it returns
921 /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
922 fn release(&self, num: &str) -> String {
923 match &self.config.channel[..] {
924 "stable" => num.to_string(),
925 "beta" => format!("{}-beta{}", num, channel::CFG_PRERELEASE_VERSION),
926 "nightly" => format!("{}-nightly", num),
927 _ => format!("{}-dev", num),
931 /// Returns the value of `release` above for Rust itself.
932 fn rust_release(&self) -> String {
933 self.release(channel::CFG_RELEASE_NUM)
936 /// Returns the "package version" for a component given the `num` release
939 /// The package version is typically what shows up in the names of tarballs.
940 /// For channels like beta/nightly it's just the channel name, otherwise
941 /// it's the `num` provided.
942 fn package_vers(&self, num: &str) -> String {
943 match &self.config.channel[..] {
944 "stable" => num.to_string(),
945 "beta" => "beta".to_string(),
946 "nightly" => "nightly".to_string(),
947 _ => format!("{}-dev", num),
951 /// Returns the value of `package_vers` above for Rust itself.
952 fn rust_package_vers(&self) -> String {
953 self.package_vers(channel::CFG_RELEASE_NUM)
956 /// Returns the value of `package_vers` above for Cargo
957 fn cargo_package_vers(&self) -> String {
958 self.package_vers(&self.release_num("cargo"))
961 /// Returns the value of `package_vers` above for rls
962 fn rls_package_vers(&self) -> String {
963 self.package_vers(&self.release_num("rls"))
966 /// Returns the `version` string associated with this compiler for Rust
969 /// Note that this is a descriptive string which includes the commit date,
970 /// sha, version, etc.
971 fn rust_version(&self) -> String {
972 self.rust_info.version(self, channel::CFG_RELEASE_NUM)
975 /// Returns the `a.b.c` version that the given package is at.
976 fn release_num(&self, package: &str) -> String {
977 let mut toml = String::new();
978 let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
979 t!(t!(File::open(toml_file_name)).read_to_string(&mut toml));
980 for line in toml.lines() {
981 let prefix = "version = \"";
983 if line.starts_with(prefix) && line.ends_with(suffix) {
984 return line[prefix.len()..line.len() - suffix.len()].to_string()
988 panic!("failed to find version in {}'s Cargo.toml", package)
991 /// Returns whether unstable features should be enabled for the compiler
993 fn unstable_features(&self) -> bool {
994 match &self.config.channel[..] {
995 "stable" | "beta" => false,
996 "nightly" | _ => true,
1001 impl<'a> Compiler<'a> {
1002 /// Creates a new complier for the specified stage/host
1003 fn new(stage: u32, host: &'a str) -> Compiler<'a> {
1004 Compiler { stage: stage, host: host }
1007 /// Returns whether this is a snapshot compiler for `build`'s configuration
1008 fn is_snapshot(&self, build: &Build) -> bool {
1009 self.stage == 0 && self.host == build.config.build
1012 /// Returns if this compiler should be treated as a final stage one in the
1013 /// current build session.
1014 /// This takes into account whether we're performing a full bootstrap or
1015 /// not; don't directly compare the stage with `2`!
1016 fn is_final_stage(&self, build: &Build) -> bool {
1017 let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
1018 self.stage >= final_stage