]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/lib.rs
Fixes warnings and errors introduced while moving code around
[rust.git] / src / bootstrap / lib.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 rustbuild, the Rust build system.
12 //!
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:
17 //!
18 //! * To be an easily understandable, easily extensible, and maintainable build
19 //!   system.
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
23 //!
24 //! ## Architecture
25 //!
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.
35 //!
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.
39 //!
40 //! When you execute `x.py build`, the steps which are executed are:
41 //!
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.
46 //!
47 //! * Rustbuild takes over, performs sanity checks, probes the environment,
48 //!   reads configuration, builds up a list of steps, and then starts executing
49 //!   them.
50 //!
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
58 //!
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.
61 //!
62 //! ## Further information
63 //!
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.
66
67 #![deny(warnings)]
68 #![feature(associated_consts)]
69 #![feature(core_intrinsics)]
70
71 #[macro_use]
72 extern crate build_helper;
73 #[macro_use]
74 extern crate serde_derive;
75 extern crate serde;
76 extern crate serde_json;
77 extern crate cmake;
78 extern crate filetime;
79 extern crate gcc;
80 extern crate getopts;
81 extern crate num_cpus;
82 extern crate rustc_serialize;
83 extern crate toml;
84
85 #[cfg(unix)]
86 extern crate libc;
87
88 use std::cell::Cell;
89 use std::cmp;
90 use std::collections::{HashSet, HashMap};
91 use std::env;
92 use std::fs::{self, File};
93 use std::io::Read;
94 use std::path::{PathBuf, Path};
95 use std::process::Command;
96
97 use build_helper::{run_silent, run_suppressed, try_run_silent, try_run_suppressed, output, mtime};
98
99 use util::{exe, libdir, add_lib_path, OutputFolder, CiEnv};
100
101 mod cc;
102 mod channel;
103 mod check;
104 mod clean;
105 mod compile;
106 mod metadata;
107 mod config;
108 mod dist;
109 mod doc;
110 mod flags;
111 mod install;
112 mod native;
113 mod sanity;
114 pub mod util;
115 mod builder;
116 mod cache;
117 mod tool;
118
119 #[cfg(windows)]
120 mod job;
121
122 #[cfg(unix)]
123 mod job {
124     use libc;
125
126     pub unsafe fn setup(build: &mut ::Build) {
127         if build.config.low_priority {
128             libc::setpriority(libc::PRIO_PGRP as _, 0, 10);
129         }
130     }
131 }
132
133 #[cfg(not(any(unix, windows)))]
134 mod job {
135     pub unsafe fn setup(_build: &mut ::Build) {
136     }
137 }
138
139 pub use config::Config;
140 pub use flags::{Flags, Subcommand};
141
142 /// A structure representing a Rust compiler.
143 ///
144 /// Each compiler has a `stage` that it is associated with and a `host` that
145 /// corresponds to the platform the compiler runs on. This structure is used as
146 /// a parameter to many methods below.
147 #[derive(Serialize, Deserialize, Eq, PartialEq, Clone, Copy, Hash, Debug)]
148 pub struct Compiler<'a> {
149     stage: u32,
150     host: &'a str,
151 }
152
153 /// Global configuration for the build system.
154 ///
155 /// This structure transitively contains all configuration for the build system.
156 /// All filesystem-encoded configuration is in `config`, all flags are in
157 /// `flags`, and then parsed or probed information is listed in the keys below.
158 ///
159 /// This structure is a parameter of almost all methods in the build system,
160 /// although most functions are implemented as free functions rather than
161 /// methods specifically on this structure itself (to make it easier to
162 /// organize).
163 pub struct Build {
164     // User-specified configuration via config.toml
165     config: Config,
166
167     // User-specified configuration via CLI flags
168     flags: Flags,
169
170     // Derived properties from the above two configurations
171     src: PathBuf,
172     out: PathBuf,
173     rust_info: channel::GitInfo,
174     cargo_info: channel::GitInfo,
175     rls_info: channel::GitInfo,
176     local_rebuild: bool,
177     fail_fast: bool,
178     verbosity: usize,
179
180     // Targets for which to build.
181     build: String,
182     hosts: Vec<String>,
183     targets: Vec<String>,
184
185     // Stage 0 (downloaded) compiler and cargo or their local rust equivalents.
186     initial_rustc: PathBuf,
187     initial_cargo: PathBuf,
188
189     // Probed tools at runtime
190     lldb_version: Option<String>,
191     lldb_python_dir: Option<String>,
192
193     // Runtime state filled in later on
194     // target -> (cc, ar)
195     cc: HashMap<String, (gcc::Tool, Option<PathBuf>)>,
196     // host -> (cc, ar)
197     cxx: HashMap<String, gcc::Tool>,
198     crates: HashMap<String, Crate>,
199     is_sudo: bool,
200     ci_env: CiEnv,
201     delayed_failures: Cell<usize>,
202 }
203
204 #[derive(Debug)]
205 struct Crate {
206     name: String,
207     version: String,
208     deps: Vec<String>,
209     path: PathBuf,
210     doc_step: String,
211     build_step: String,
212     test_step: String,
213     bench_step: String,
214 }
215
216 /// The various "modes" of invoking Cargo.
217 ///
218 /// These entries currently correspond to the various output directories of the
219 /// build system, with each mod generating output in a different directory.
220 #[derive(Serialize, Clone, Copy, PartialEq, Eq)]
221 pub enum Mode {
222     /// Build the standard library, placing output in the "stageN-std" directory.
223     Libstd,
224
225     /// Build libtest, placing output in the "stageN-test" directory.
226     Libtest,
227
228     /// Build librustc and compiler libraries, placing output in the "stageN-rustc" directory.
229     Librustc,
230
231     /// Build some tool, placing output in the "stageN-tools" directory.
232     Tool,
233 }
234
235 impl Build {
236     /// Creates a new set of build configuration from the `flags` on the command
237     /// line and the filesystem `config`.
238     ///
239     /// By default all build output will be placed in the current directory.
240     pub fn new(flags: Flags, config: Config) -> Build {
241         let cwd = t!(env::current_dir());
242         let src = flags.src.clone();
243         let out = cwd.join("build");
244
245         let is_sudo = match env::var_os("SUDO_USER") {
246             Some(sudo_user) => {
247                 match env::var_os("USER") {
248                     Some(user) => user != sudo_user,
249                     None => false,
250                 }
251             }
252             None => false,
253         };
254         let rust_info = channel::GitInfo::new(&src);
255         let cargo_info = channel::GitInfo::new(&src.join("src/tools/cargo"));
256         let rls_info = channel::GitInfo::new(&src.join("src/tools/rls"));
257
258         let hosts = if !flags.host.is_empty() {
259             for host in flags.host.iter() {
260                 if !config.host.contains(host) {
261                     panic!("specified host `{}` is not in configuration", host);
262                 }
263             }
264             flags.host.clone()
265         } else {
266             config.host.clone()
267         };
268         let targets = if !flags.target.is_empty() {
269             for target in flags.target.iter() {
270                 if !config.target.contains(target) {
271                     panic!("specified target `{}` is not in configuration", target);
272                 }
273             }
274             flags.target.clone()
275         } else {
276             config.target.clone()
277         };
278
279         Build {
280             initial_rustc: config.initial_rustc.clone(),
281             initial_cargo: config.initial_cargo.clone(),
282             local_rebuild: config.local_rebuild,
283             fail_fast: flags.cmd.fail_fast(),
284             verbosity: cmp::max(flags.verbose, config.verbose),
285
286             build: config.host[0].clone(),
287             hosts: hosts,
288             targets: targets,
289
290             flags: flags,
291             config: config,
292             src: src,
293             out: out,
294
295             rust_info: rust_info,
296             cargo_info: cargo_info,
297             rls_info: rls_info,
298             cc: HashMap::new(),
299             cxx: HashMap::new(),
300             crates: HashMap::new(),
301             lldb_version: None,
302             lldb_python_dir: None,
303             is_sudo: is_sudo,
304             ci_env: CiEnv::current(),
305             delayed_failures: Cell::new(0),
306         }
307     }
308
309     /// Executes the entire build, as configured by the flags and configuration.
310     pub fn build(&mut self) {
311         unsafe {
312             job::setup(self);
313         }
314
315         if let Subcommand::Clean = self.flags.cmd {
316             return clean::clean(self);
317         }
318
319         self.verbose("finding compilers");
320         cc::find(self);
321         self.verbose("running sanity check");
322         sanity::check(self);
323         // If local-rust is the same major.minor as the current version, then force a local-rebuild
324         let local_version_verbose = output(
325             Command::new(&self.initial_rustc).arg("--version").arg("--verbose"));
326         let local_release = local_version_verbose
327             .lines().filter(|x| x.starts_with("release:"))
328             .next().unwrap().trim_left_matches("release:").trim();
329         let my_version = channel::CFG_RELEASE_NUM;
330         if local_release.split('.').take(2).eq(my_version.split('.').take(2)) {
331             self.verbose(&format!("auto-detected local-rebuild {}", local_release));
332             self.local_rebuild = true;
333         }
334         self.verbose("learning about cargo");
335         metadata::build(self);
336
337         builder::Builder::run(&self);
338     }
339
340     /// Clear out `dir` if `input` is newer.
341     ///
342     /// After this executes, it will also ensure that `dir` exists.
343     fn clear_if_dirty(&self, dir: &Path, input: &Path) {
344         let stamp = dir.join(".stamp");
345         if mtime(&stamp) < mtime(input) {
346             self.verbose(&format!("Dirty - {}", dir.display()));
347             let _ = fs::remove_dir_all(dir);
348         } else if stamp.exists() {
349             return
350         }
351         t!(fs::create_dir_all(dir));
352         t!(File::create(stamp));
353     }
354
355     /// Prepares an invocation of `cargo` to be run.
356     ///
357     /// This will create a `Command` that represents a pending execution of
358     /// Cargo. This cargo will be configured to use `compiler` as the actual
359     /// rustc compiler, its output will be scoped by `mode`'s output directory,
360     /// it will pass the `--target` flag for the specified `target`, and will be
361     /// executing the Cargo command `cmd`.
362     fn cargo(&self,
363              compiler: Compiler,
364              mode: Mode,
365              target: &str,
366              cmd: &str) -> Command {
367         let mut cargo = Command::new(&self.initial_cargo);
368         let out_dir = self.stage_out(compiler, mode);
369         cargo.env("CARGO_TARGET_DIR", out_dir)
370              .arg(cmd)
371              .arg("-j").arg(self.jobs().to_string())
372              .arg("--target").arg(target);
373
374         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
375         // Force cargo to output binaries with disambiguating hashes in the name
376         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &self.config.channel);
377
378         let stage;
379         if compiler.stage == 0 && self.local_rebuild {
380             // Assume the local-rebuild rustc already has stage1 features.
381             stage = 1;
382         } else {
383             stage = compiler.stage;
384         }
385
386         // Customize the compiler we're running. Specify the compiler to cargo
387         // as our shim and then pass it some various options used to configure
388         // how the actual compiler itself is called.
389         //
390         // These variables are primarily all read by
391         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
392         cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
393              .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
394              .env("RUSTC_REAL", self.compiler_path(compiler))
395              .env("RUSTC_STAGE", stage.to_string())
396              .env("RUSTC_CODEGEN_UNITS",
397                   self.config.rust_codegen_units.to_string())
398              .env("RUSTC_DEBUG_ASSERTIONS",
399                   self.config.rust_debug_assertions.to_string())
400              .env("RUSTC_SYSROOT", self.sysroot(compiler))
401              .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
402              .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
403              .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
404              .env("RUSTDOC_REAL", self.rustdoc(compiler))
405              .env("RUSTC_FLAGS", self.rustc_flags(target).join(" "));
406
407         if mode != Mode::Tool {
408             // Tools don't get debuginfo right now, e.g. cargo and rls don't
409             // get compiled with debuginfo.
410             cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string())
411                  .env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string())
412                  .env("RUSTC_FORCE_UNSTABLE", "1");
413
414             // Currently the compiler depends on crates from crates.io, and
415             // then other crates can depend on the compiler (e.g. proc-macro
416             // crates). Let's say, for example that rustc itself depends on the
417             // bitflags crate. If an external crate then depends on the
418             // bitflags crate as well, we need to make sure they don't
419             // conflict, even if they pick the same verison of bitflags. We'll
420             // want to make sure that e.g. a plugin and rustc each get their
421             // own copy of bitflags.
422
423             // Cargo ensures that this works in general through the -C metadata
424             // flag. This flag will frob the symbols in the binary to make sure
425             // they're different, even though the source code is the exact
426             // same. To solve this problem for the compiler we extend Cargo's
427             // already-passed -C metadata flag with our own. Our rustc.rs
428             // wrapper around the actual rustc will detect -C metadata being
429             // passed and frob it with this extra string we're passing in.
430             cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
431         }
432
433         // Enable usage of unstable features
434         cargo.env("RUSTC_BOOTSTRAP", "1");
435         self.add_rust_test_threads(&mut cargo);
436
437         // Almost all of the crates that we compile as part of the bootstrap may
438         // have a build script, including the standard library. To compile a
439         // build script, however, it itself needs a standard library! This
440         // introduces a bit of a pickle when we're compiling the standard
441         // library itself.
442         //
443         // To work around this we actually end up using the snapshot compiler
444         // (stage0) for compiling build scripts of the standard library itself.
445         // The stage0 compiler is guaranteed to have a libstd available for use.
446         //
447         // For other crates, however, we know that we've already got a standard
448         // library up and running, so we can use the normal compiler to compile
449         // build scripts in that situation.
450         if mode == Mode::Libstd {
451             cargo.env("RUSTC_SNAPSHOT", &self.initial_rustc)
452                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
453         } else {
454             cargo.env("RUSTC_SNAPSHOT", self.compiler_path(compiler))
455                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
456         }
457
458         // Ignore incremental modes except for stage0, since we're
459         // not guaranteeing correctness across builds if the compiler
460         // is changing under your feet.`
461         if self.flags.incremental && compiler.stage == 0 {
462             let incr_dir = self.incremental_dir(compiler);
463             cargo.env("RUSTC_INCREMENTAL", incr_dir);
464         }
465
466         if let Some(ref on_fail) = self.flags.on_fail {
467             cargo.env("RUSTC_ON_FAIL", on_fail);
468         }
469
470         cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
471
472         // Specify some various options for build scripts used throughout
473         // the build.
474         //
475         // FIXME: the guard against msvc shouldn't need to be here
476         if !target.contains("msvc") {
477             cargo.env(format!("CC_{}", target), self.cc(target))
478                  .env(format!("AR_{}", target), self.ar(target).unwrap()) // only msvc is None
479                  .env(format!("CFLAGS_{}", target), self.cflags(target).join(" "));
480
481             if let Ok(cxx) = self.cxx(target) {
482                  cargo.env(format!("CXX_{}", target), cxx);
483             }
484         }
485
486         if mode == Mode::Libstd &&
487            self.config.extended &&
488            compiler.is_final_stage(self) {
489             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
490         }
491
492         // When being built Cargo will at some point call `nmake.exe` on Windows
493         // MSVC. Unfortunately `nmake` will read these two environment variables
494         // below and try to intepret them. We're likely being run, however, from
495         // MSYS `make` which uses the same variables.
496         //
497         // As a result, to prevent confusion and errors, we remove these
498         // variables from our environment to prevent passing MSYS make flags to
499         // nmake, causing it to blow up.
500         if cfg!(target_env = "msvc") {
501             cargo.env_remove("MAKE");
502             cargo.env_remove("MAKEFLAGS");
503         }
504
505         // Environment variables *required* throughout the build
506         //
507         // FIXME: should update code to not require this env var
508         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
509
510         if self.is_verbose() {
511             cargo.arg("-v");
512         }
513         // FIXME: cargo bench does not accept `--release`
514         if self.config.rust_optimize && cmd != "bench" {
515             cargo.arg("--release");
516         }
517         if self.config.locked_deps {
518             cargo.arg("--locked");
519         }
520         if self.config.vendor || self.is_sudo {
521             cargo.arg("--frozen");
522         }
523
524         self.ci_env.force_coloring_in_ci(&mut cargo);
525
526         cargo
527     }
528
529     /// Get a path to the compiler specified.
530     fn compiler_path(&self, compiler: Compiler) -> PathBuf {
531         if compiler.is_snapshot(self) {
532             self.initial_rustc.clone()
533         } else {
534             self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
535         }
536     }
537
538     /// Get the specified tool built by the specified compiler
539     fn tool(&self, compiler: Compiler, tool: &str) -> PathBuf {
540         self.cargo_out(compiler, Mode::Tool, compiler.host)
541             .join(exe(tool, compiler.host))
542     }
543
544     /// Get the `rustdoc` executable next to the specified compiler
545     fn rustdoc(&self, compiler: Compiler) -> PathBuf {
546         let mut rustdoc = self.compiler_path(compiler);
547         rustdoc.pop();
548         rustdoc.push(exe("rustdoc", compiler.host));
549         rustdoc
550     }
551
552     /// Get a `Command` which is ready to run `tool` in `stage` built for
553     /// `host`.
554     fn tool_cmd(&self, compiler: Compiler, tool: &str) -> Command {
555         let mut cmd = Command::new(self.tool(compiler, tool));
556         self.prepare_tool_cmd(compiler, &mut cmd);
557         cmd
558     }
559
560     /// Prepares the `cmd` provided to be able to run the `compiler` provided.
561     ///
562     /// Notably this munges the dynamic library lookup path to point to the
563     /// right location to run `compiler`.
564     fn prepare_tool_cmd(&self, compiler: Compiler, cmd: &mut Command) {
565         let host = compiler.host;
566         let mut paths = vec![
567             self.sysroot_libdir(compiler, compiler.host),
568             self.cargo_out(compiler, Mode::Tool, host).join("deps"),
569         ];
570
571         // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
572         // mode) and that C compiler may need some extra PATH modification. Do
573         // so here.
574         if compiler.host.contains("msvc") {
575             let curpaths = env::var_os("PATH").unwrap_or(OsString::new());
576             let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
577             for &(ref k, ref v) in self.cc[compiler.host].0.env() {
578                 if k != "PATH" {
579                     continue
580                 }
581                 for path in env::split_paths(v) {
582                     if !curpaths.contains(&path) {
583                         paths.push(path);
584                     }
585                 }
586             }
587         }
588         add_lib_path(paths, cmd);
589     }
590
591     /// Get the space-separated set of activated features for the standard
592     /// library.
593     fn std_features(&self) -> String {
594         let mut features = "panic-unwind".to_string();
595
596         if self.config.debug_jemalloc {
597             features.push_str(" debug-jemalloc");
598         }
599         if self.config.use_jemalloc {
600             features.push_str(" jemalloc");
601         }
602         if self.config.backtrace {
603             features.push_str(" backtrace");
604         }
605         if self.config.profiler {
606             features.push_str(" profiler");
607         }
608         features
609     }
610
611     /// Get the space-separated set of activated features for the compiler.
612     fn rustc_features(&self) -> String {
613         let mut features = String::new();
614         if self.config.use_jemalloc {
615             features.push_str(" jemalloc");
616         }
617         features
618     }
619
620     /// Component directory that Cargo will produce output into (e.g.
621     /// release/debug)
622     fn cargo_dir(&self) -> &'static str {
623         if self.config.rust_optimize {"release"} else {"debug"}
624     }
625
626     /// Get the directory for incremental by-products when using the
627     /// given compiler.
628     fn incremental_dir(&self, compiler: Compiler) -> PathBuf {
629         self.out.join(compiler.host).join(format!("stage{}-incremental", compiler.stage))
630     }
631
632     /// Returns the libdir where the standard library and other artifacts are
633     /// found for a compiler's sysroot.
634     fn sysroot_libdir(&self, compiler: &Compiler, target: &str) -> PathBuf {
635         if compiler.stage >= 2 {
636             if let Some(ref libdir_relative) = self.config.libdir_relative {
637                 return self.sysroot(compiler).join(libdir_relative)
638                     .join("rustlib").join(target).join("lib")
639             }
640         }
641        self.sysroot(compiler).join("lib").join("rustlib")
642            .join(target).join("lib")
643     }
644
645     /// Returns the root directory for all output generated in a particular
646     /// stage when running with a particular host compiler.
647     ///
648     /// The mode indicates what the root directory is for.
649     fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
650         let suffix = match mode {
651             Mode::Libstd => "-std",
652             Mode::Libtest => "-test",
653             Mode::Tool => "-tools",
654             Mode::Librustc => "-rustc",
655         };
656         self.out.join(compiler.host)
657                 .join(format!("stage{}{}", compiler.stage, suffix))
658     }
659
660     /// Returns the root output directory for all Cargo output in a given stage,
661     /// running a particular compiler, wehther or not we're building the
662     /// standard library, and targeting the specified architecture.
663     fn cargo_out(&self,
664                  compiler: Compiler,
665                  mode: Mode,
666                  target: &str) -> PathBuf {
667         self.stage_out(compiler, mode).join(target).join(self.cargo_dir())
668     }
669
670     /// Root output directory for LLVM compiled for `target`
671     ///
672     /// Note that if LLVM is configured externally then the directory returned
673     /// will likely be empty.
674     fn llvm_out(&self, target: &str) -> PathBuf {
675         self.out.join(target).join("llvm")
676     }
677
678     /// Output directory for all documentation for a target
679     fn doc_out(&self, target: &str) -> PathBuf {
680         self.out.join(target).join("doc")
681     }
682
683     /// Output directory for some generated md crate documentation for a target (temporary)
684     fn md_doc_out(&self, target: &str) -> PathBuf {
685         self.out.join(target).join("md-doc")
686     }
687
688     /// Output directory for all crate documentation for a target (temporary)
689     ///
690     /// The artifacts here are then copied into `doc_out` above.
691     fn crate_doc_out(&self, target: &str) -> PathBuf {
692         self.out.join(target).join("crate-docs")
693     }
694
695     /// Returns true if no custom `llvm-config` is set for the specified target.
696     ///
697     /// If no custom `llvm-config` was specified then Rust's llvm will be used.
698     fn is_rust_llvm(&self, target: &str) -> bool {
699         match self.config.target_config.get(target) {
700             Some(ref c) => c.llvm_config.is_none(),
701             None => true
702         }
703     }
704
705     /// Returns the path to `llvm-config` for the specified target.
706     ///
707     /// If a custom `llvm-config` was specified for target then that's returned
708     /// instead.
709     fn llvm_config(&self, target: &str) -> PathBuf {
710         let target_config = self.config.target_config.get(target);
711         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
712             s.clone()
713         } else {
714             self.llvm_out(&self.config.build).join("bin")
715                 .join(exe("llvm-config", target))
716         }
717     }
718
719     /// Returns the path to `FileCheck` binary for the specified target
720     fn llvm_filecheck(&self, target: &str) -> PathBuf {
721         let target_config = self.config.target_config.get(target);
722         if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
723             let llvm_bindir = output(Command::new(s).arg("--bindir"));
724             Path::new(llvm_bindir.trim()).join(exe("FileCheck", target))
725         } else {
726             let base = self.llvm_out(&self.config.build).join("build");
727             let exe = exe("FileCheck", target);
728             if !self.config.ninja && self.config.build.contains("msvc") {
729                 base.join("Release/bin").join(exe)
730             } else {
731                 base.join("bin").join(exe)
732             }
733         }
734     }
735
736     /// Directory for libraries built from C/C++ code and shared between stages.
737     fn native_dir(&self, target: &str) -> PathBuf {
738         self.out.join(target).join("native")
739     }
740
741     /// Root output directory for rust_test_helpers library compiled for
742     /// `target`
743     fn test_helpers_out(&self, target: &str) -> PathBuf {
744         self.native_dir(target).join("rust-test-helpers")
745     }
746
747     /// Adds the `RUST_TEST_THREADS` env var if necessary
748     fn add_rust_test_threads(&self, cmd: &mut Command) {
749         if env::var_os("RUST_TEST_THREADS").is_none() {
750             cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
751         }
752     }
753
754     /// Returns the compiler's libdir where it stores the dynamic libraries that
755     /// it itself links against.
756     ///
757     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
758     /// Windows.
759     fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
760         if compiler.is_snapshot(self) {
761             self.rustc_snapshot_libdir()
762         } else {
763             self.sysroot(compiler).join(libdir(compiler.host))
764         }
765     }
766
767     /// Returns the libdir of the snapshot compiler.
768     fn rustc_snapshot_libdir(&self) -> PathBuf {
769         self.initial_rustc.parent().unwrap().parent().unwrap()
770             .join(libdir(&self.config.build))
771     }
772
773     /// Runs a command, printing out nice contextual information if it fails.
774     fn run(&self, cmd: &mut Command) {
775         self.verbose(&format!("running: {:?}", cmd));
776         run_silent(cmd)
777     }
778
779     /// Runs a command, printing out nice contextual information if it fails.
780     fn run_quiet(&self, cmd: &mut Command) {
781         self.verbose(&format!("running: {:?}", cmd));
782         run_suppressed(cmd)
783     }
784
785     /// Runs a command, printing out nice contextual information if it fails.
786     /// Exits if the command failed to execute at all, otherwise returns its
787     /// `status.success()`.
788     fn try_run(&self, cmd: &mut Command) -> bool {
789         self.verbose(&format!("running: {:?}", cmd));
790         try_run_silent(cmd)
791     }
792
793     /// Runs a command, printing out nice contextual information if it fails.
794     /// Exits if the command failed to execute at all, otherwise returns its
795     /// `status.success()`.
796     fn try_run_quiet(&self, cmd: &mut Command) -> bool {
797         self.verbose(&format!("running: {:?}", cmd));
798         try_run_suppressed(cmd)
799     }
800
801     pub fn is_verbose(&self) -> bool {
802         self.verbosity > 0
803     }
804
805     pub fn is_very_verbose(&self) -> bool {
806         self.verbosity > 1
807     }
808
809     /// Prints a message if this build is configured in verbose mode.
810     fn verbose(&self, msg: &str) {
811         if self.is_verbose() {
812             println!("{}", msg);
813         }
814     }
815
816     /// Returns the number of parallel jobs that have been configured for this
817     /// build.
818     fn jobs(&self) -> u32 {
819         self.flags.jobs.unwrap_or_else(|| num_cpus::get() as u32)
820     }
821
822     /// Returns the path to the C compiler for the target specified.
823     fn cc(&self, target: &str) -> &Path {
824         self.cc[target].0.path()
825     }
826
827     /// Returns a list of flags to pass to the C compiler for the target
828     /// specified.
829     fn cflags(&self, target: &str) -> Vec<String> {
830         // Filter out -O and /O (the optimization flags) that we picked up from
831         // gcc-rs because the build scripts will determine that for themselves.
832         let mut base = self.cc[target].0.args().iter()
833                            .map(|s| s.to_string_lossy().into_owned())
834                            .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
835                            .collect::<Vec<_>>();
836
837         // If we're compiling on macOS then we add a few unconditional flags
838         // indicating that we want libc++ (more filled out than libstdc++) and
839         // we want to compile for 10.7. This way we can ensure that
840         // LLVM/jemalloc/etc are all properly compiled.
841         if target.contains("apple-darwin") {
842             base.push("-stdlib=libc++".into());
843         }
844
845         // Work around an apparently bad MinGW / GCC optimization,
846         // See: http://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
847         // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
848         if target == "i686-pc-windows-gnu" {
849             base.push("-fno-omit-frame-pointer".into());
850         }
851         base
852     }
853
854     /// Returns the path to the `ar` archive utility for the target specified.
855     fn ar(&self, target: &str) -> Option<&Path> {
856         self.cc[target].1.as_ref().map(|p| &**p)
857     }
858
859     /// Returns the path to the C++ compiler for the target specified.
860     fn cxx(&self, target: &str) -> Result<&Path, String> {
861         match self.cxx.get(target) {
862             Some(p) => Ok(p.path()),
863             None => Err(format!(
864                     "target `{}` is not configured as a host, only as a target",
865                     target))
866         }
867     }
868
869     /// Returns flags to pass to the compiler to generate code for `target`.
870     fn rustc_flags(&self, target: &str) -> Vec<String> {
871         // New flags should be added here with great caution!
872         //
873         // It's quite unfortunate to **require** flags to generate code for a
874         // target, so it should only be passed here if absolutely necessary!
875         // Most default configuration should be done through target specs rather
876         // than an entry here.
877
878         let mut base = Vec::new();
879         if target != self.config.build && !target.contains("msvc") &&
880             !target.contains("emscripten") {
881             base.push(format!("-Clinker={}", self.cc(target).display()));
882         }
883         base
884     }
885
886     /// Returns the "musl root" for this `target`, if defined
887     fn musl_root(&self, target: &str) -> Option<&Path> {
888         self.config.target_config.get(target)
889             .and_then(|t| t.musl_root.as_ref())
890             .or(self.config.musl_root.as_ref())
891             .map(|p| &**p)
892     }
893
894     /// Returns whether the target will be tested using the `remote-test-client`
895     /// and `remote-test-server` binaries.
896     fn remote_tested(&self, target: &str) -> bool {
897         self.qemu_rootfs(target).is_some() || target.contains("android") ||
898         env::var_os("TEST_DEVICE_ADDR").is_some()
899     }
900
901     /// Returns the root of the "rootfs" image that this target will be using,
902     /// if one was configured.
903     ///
904     /// If `Some` is returned then that means that tests for this target are
905     /// emulated with QEMU and binaries will need to be shipped to the emulator.
906     fn qemu_rootfs(&self, target: &str) -> Option<&Path> {
907         self.config.target_config.get(target)
908             .and_then(|t| t.qemu_rootfs.as_ref())
909             .map(|p| &**p)
910     }
911
912     /// Path to the python interpreter to use
913     fn python(&self) -> &Path {
914         self.config.python.as_ref().unwrap()
915     }
916
917     /// Tests whether the `compiler` compiling for `target` should be forced to
918     /// use a stage1 compiler instead.
919     ///
920     /// Currently, by default, the build system does not perform a "full
921     /// bootstrap" by default where we compile the compiler three times.
922     /// Instead, we compile the compiler two times. The final stage (stage2)
923     /// just copies the libraries from the previous stage, which is what this
924     /// method detects.
925     ///
926     /// Here we return `true` if:
927     ///
928     /// * The build isn't performing a full bootstrap
929     /// * The `compiler` is in the final stage, 2
930     /// * We're not cross-compiling, so the artifacts are already available in
931     ///   stage1
932     ///
933     /// When all of these conditions are met the build will lift artifacts from
934     /// the previous stage forward.
935     fn force_use_stage1(&self, compiler: Compiler, target: &str) -> bool {
936         !self.config.full_bootstrap &&
937             compiler.stage >= 2 &&
938             self.config.host.iter().any(|h| h == target)
939     }
940
941     /// Returns the directory that OpenSSL artifacts are compiled into if
942     /// configured to do so.
943     fn openssl_dir(&self, target: &str) -> Option<PathBuf> {
944         // OpenSSL not used on Windows
945         if target.contains("windows") {
946             None
947         } else if self.config.openssl_static {
948             Some(self.out.join(target).join("openssl"))
949         } else {
950             None
951         }
952     }
953
954     /// Returns the directory that OpenSSL artifacts are installed into if
955     /// configured as such.
956     fn openssl_install_dir(&self, target: &str) -> Option<PathBuf> {
957         self.openssl_dir(target).map(|p| p.join("install"))
958     }
959
960     /// Given `num` in the form "a.b.c" return a "release string" which
961     /// describes the release version number.
962     ///
963     /// For example on nightly this returns "a.b.c-nightly", on beta it returns
964     /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
965     fn release(&self, num: &str) -> String {
966         match &self.config.channel[..] {
967             "stable" => num.to_string(),
968             "beta" => format!("{}-beta{}", num, channel::CFG_PRERELEASE_VERSION),
969             "nightly" => format!("{}-nightly", num),
970             _ => format!("{}-dev", num),
971         }
972     }
973
974     /// Returns the value of `release` above for Rust itself.
975     fn rust_release(&self) -> String {
976         self.release(channel::CFG_RELEASE_NUM)
977     }
978
979     /// Returns the "package version" for a component given the `num` release
980     /// number.
981     ///
982     /// The package version is typically what shows up in the names of tarballs.
983     /// For channels like beta/nightly it's just the channel name, otherwise
984     /// it's the `num` provided.
985     fn package_vers(&self, num: &str) -> String {
986         match &self.config.channel[..] {
987             "stable" => num.to_string(),
988             "beta" => "beta".to_string(),
989             "nightly" => "nightly".to_string(),
990             _ => format!("{}-dev", num),
991         }
992     }
993
994     /// Returns the value of `package_vers` above for Rust itself.
995     fn rust_package_vers(&self) -> String {
996         self.package_vers(channel::CFG_RELEASE_NUM)
997     }
998
999     /// Returns the value of `package_vers` above for Cargo
1000     fn cargo_package_vers(&self) -> String {
1001         self.package_vers(&self.release_num("cargo"))
1002     }
1003
1004     /// Returns the value of `package_vers` above for rls
1005     fn rls_package_vers(&self) -> String {
1006         self.package_vers(&self.release_num("rls"))
1007     }
1008
1009     /// Returns the `version` string associated with this compiler for Rust
1010     /// itself.
1011     ///
1012     /// Note that this is a descriptive string which includes the commit date,
1013     /// sha, version, etc.
1014     fn rust_version(&self) -> String {
1015         self.rust_info.version(self, channel::CFG_RELEASE_NUM)
1016     }
1017
1018     /// Returns the `a.b.c` version that the given package is at.
1019     fn release_num(&self, package: &str) -> String {
1020         let mut toml = String::new();
1021         let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
1022         t!(t!(File::open(toml_file_name)).read_to_string(&mut toml));
1023         for line in toml.lines() {
1024             let prefix = "version = \"";
1025             let suffix = "\"";
1026             if line.starts_with(prefix) && line.ends_with(suffix) {
1027                 return line[prefix.len()..line.len() - suffix.len()].to_string()
1028             }
1029         }
1030
1031         panic!("failed to find version in {}'s Cargo.toml", package)
1032     }
1033
1034     /// Returns whether unstable features should be enabled for the compiler
1035     /// we're building.
1036     fn unstable_features(&self) -> bool {
1037         match &self.config.channel[..] {
1038             "stable" | "beta" => false,
1039             "nightly" | _ => true,
1040         }
1041     }
1042
1043     /// Fold the output of the commands after this method into a group. The fold
1044     /// ends when the returned object is dropped. Folding can only be used in
1045     /// the Travis CI environment.
1046     pub fn fold_output<D, F>(&self, name: F) -> Option<OutputFolder>
1047         where D: Into<String>, F: FnOnce() -> D
1048     {
1049         if self.ci_env == CiEnv::Travis {
1050             Some(OutputFolder::new(name().into()))
1051         } else {
1052             None
1053         }
1054     }
1055
1056     /// Get a list of crates from a root crate.
1057     ///
1058     /// Returns Vec<(crate, path to crate, is_root_crate)>
1059     fn crates(&self, root: &str) -> Vec<(&str, &Path)> {
1060         let mut ret = Vec::new();
1061         let mut list = vec![root];
1062         let mut visited = HashSet::new();
1063         while let Some(krate) = list.pop() {
1064             let krate = &self.crates[krate];
1065             // If we can't strip prefix, then out-of-tree path
1066             let path = krate.path.strip_prefix(&self.src).unwrap_or(&krate.path);
1067             ret.push((&*krate.name, path));
1068             for dep in &krate.deps {
1069                 if visited.insert(dep) && dep != "build_helper" {
1070                     list.push(dep);
1071                 }
1072             }
1073         }
1074         ret
1075     }
1076 }
1077
1078 impl<'a> Compiler<'a> {
1079     pub fn with_stage(mut self, stage: u32) -> Compiler<'a> {
1080         self.stage = stage;
1081         self
1082     }
1083
1084     /// Returns whether this is a snapshot compiler for `build`'s configuration
1085     pub fn is_snapshot(&self, build: &Build) -> bool {
1086         self.stage == 0 && self.host == build.build
1087     }
1088
1089     /// Returns if this compiler should be treated as a final stage one in the
1090     /// current build session.
1091     /// This takes into account whether we're performing a full bootstrap or
1092     /// not; don't directly compare the stage with `2`!
1093     pub fn is_final_stage(&self, build: &Build) -> bool {
1094         let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
1095         self.stage >= final_stage
1096     }
1097 }