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