1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Implementation of compiling various phases of the compiler and standard
14 //! This module contains some of the real meat in the rustbuild build system
15 //! which is where Cargo is used to compiler the standard library, libtest, and
16 //! compiler. This module is also responsible for assembling the sysroot as it
17 //! goes along from the output of the previous stage.
20 use std::fs::{self, File};
21 use std::io::BufReader;
22 use std::io::prelude::*;
23 use std::path::{Path, PathBuf};
24 use std::process::{Command, Stdio};
27 use build_helper::{output, mtime, up_to_date};
28 use filetime::FileTime;
29 use rustc_serialize::json;
32 use util::{exe, libdir, is_dylib, copy};
33 use {Build, Compiler, Mode};
35 /// Build the standard library.
37 /// This will build the standard library for a particular stage of the build
38 /// using the `compiler` targeting the `target` architecture. The artifacts
39 /// created will also be linked into the sysroot directory.
40 pub fn std(build: &Build, target: &str, compiler: &Compiler) {
41 let libdir = build.sysroot_libdir(compiler, target);
42 t!(fs::create_dir_all(&libdir));
44 let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
45 println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
46 compiler.host, target);
48 let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
49 build.clear_if_dirty(&out_dir, &build.compiler_path(compiler));
50 let mut cargo = build.cargo(compiler, Mode::Libstd, target, "build");
51 let mut features = build.std_features();
53 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
54 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
57 // When doing a local rebuild we tell cargo that we're stage1 rather than
58 // stage0. This works fine if the local rust and being-built rust have the
59 // same view of what the default allocator is, but fails otherwise. Since
60 // we don't have a way to express an allocator preference yet, work
61 // around the issue in the case of a local rebuild with jemalloc disabled.
62 if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
63 features.push_str(" force_alloc_system");
66 if compiler.stage != 0 && build.config.sanitizers {
67 // This variable is used by the sanitizer runtime crates, e.g.
68 // rustc_lsan, to build the sanitizer runtime from C code
69 // When this variable is missing, those crates won't compile the C code,
70 // so we don't set this variable during stage0 where llvm-config is
72 // We also only build the runtimes when --enable-sanitizers (or its
73 // config.toml equivalent) is used
74 cargo.env("LLVM_CONFIG", build.llvm_config(target));
76 cargo.arg("--features").arg(features)
77 .arg("--manifest-path")
78 .arg(build.src.join("src/libstd/Cargo.toml"));
80 if let Some(target) = build.config.target_config.get(target) {
81 if let Some(ref jemalloc) = target.jemalloc {
82 cargo.env("JEMALLOC_OVERRIDE", jemalloc);
85 if target.contains("musl") {
86 if let Some(p) = build.musl_root(target) {
87 cargo.env("MUSL_ROOT", p);
93 &libstd_stamp(build, &compiler, target));
96 /// Link all libstd rlibs/dylibs into the sysroot location.
98 /// Links those artifacts generated by `compiler` to a the `stage` compiler's
99 /// sysroot for the specified `host` and `target`.
101 /// Note that this assumes that `compiler` has already generated the libstd
102 /// libraries for `target`, and this method will find them in the relevant
103 /// output directory.
104 pub fn std_link(build: &Build,
106 target_compiler: &Compiler,
108 println!("Copying stage{} std from stage{} ({} -> {} / {})",
109 target_compiler.stage,
112 target_compiler.host,
114 let libdir = build.sysroot_libdir(target_compiler, target);
115 add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
117 if target.contains("musl") && !target.contains("mips") {
118 copy_musl_third_party_objects(build, target, &libdir);
121 if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
122 // The sanitizers are only built in stage1 or above, so the dylibs will
123 // be missing in stage0 and causes panic. See the `std()` function above
124 // for reason why the sanitizers are not built in stage0.
125 copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
129 /// Copies the crt(1,i,n).o startup objects
131 /// Only required for musl targets that statically link to libc
132 fn copy_musl_third_party_objects(build: &Build, target: &str, into: &Path) {
133 for &obj in &["crt1.o", "crti.o", "crtn.o"] {
134 copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
138 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
139 for &sanitizer in &["asan", "tsan"] {
140 let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
141 let mut src_path = native_dir.join(sanitizer);
142 src_path.push("build");
143 src_path.push("lib");
144 src_path.push("darwin");
145 src_path.push(&filename);
146 copy(&src_path, &into.join(filename));
150 /// Build and prepare startup objects like rsbegin.o and rsend.o
152 /// These are primarily used on Windows right now for linking executables/dlls.
153 /// They don't require any library support as they're just plain old object
154 /// files, so we just use the nightly snapshot compiler to always build them (as
155 /// no other compilers are guaranteed to be available).
156 pub fn build_startup_objects(build: &Build, for_compiler: &Compiler, target: &str) {
157 if !target.contains("pc-windows-gnu") {
161 let compiler = Compiler::new(0, &build.build);
162 let compiler_path = build.compiler_path(&compiler);
163 let src_dir = &build.src.join("src/rtstartup");
164 let dst_dir = &build.native_dir(target).join("rtstartup");
165 let sysroot_dir = &build.sysroot_libdir(for_compiler, target);
166 t!(fs::create_dir_all(dst_dir));
167 t!(fs::create_dir_all(sysroot_dir));
169 for file in &["rsbegin", "rsend"] {
170 let src_file = &src_dir.join(file.to_string() + ".rs");
171 let dst_file = &dst_dir.join(file.to_string() + ".o");
172 if !up_to_date(src_file, dst_file) {
173 let mut cmd = Command::new(&compiler_path);
174 build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
175 .arg("--cfg").arg(format!("stage{}", compiler.stage))
176 .arg("--target").arg(target)
178 .arg("--out-dir").arg(dst_dir)
182 copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
185 for obj in ["crt2.o", "dllcrt2.o"].iter() {
186 copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
192 /// This will build libtest and supporting libraries for a particular stage of
193 /// the build using the `compiler` targeting the `target` architecture. The
194 /// artifacts created will also be linked into the sysroot directory.
195 pub fn test(build: &Build, target: &str, compiler: &Compiler) {
196 let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
197 println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
198 compiler.host, target);
199 let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
200 build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
201 let mut cargo = build.cargo(compiler, Mode::Libtest, target, "build");
202 if let Some(target) = env::var_os("MACOSX_STD_DEPLOYMENT_TARGET") {
203 cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
205 cargo.arg("--manifest-path")
206 .arg(build.src.join("src/libtest/Cargo.toml"));
209 &libtest_stamp(build, compiler, target));
212 /// Same as `std_link`, only for libtest
213 pub fn test_link(build: &Build,
215 target_compiler: &Compiler,
217 println!("Copying stage{} test from stage{} ({} -> {} / {})",
218 target_compiler.stage,
221 target_compiler.host,
223 add_to_sysroot(&build.sysroot_libdir(target_compiler, target),
224 &libtest_stamp(build, compiler, target));
227 /// Build the compiler.
229 /// This will build the compiler for a particular stage of the build using
230 /// the `compiler` targeting the `target` architecture. The artifacts
231 /// created will also be linked into the sysroot directory.
232 pub fn rustc(build: &Build, target: &str, compiler: &Compiler) {
233 let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
234 println!("Building stage{} compiler artifacts ({} -> {})",
235 compiler.stage, compiler.host, target);
237 let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
238 build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
240 let mut cargo = build.cargo(compiler, Mode::Librustc, target, "build");
241 cargo.arg("--features").arg(build.rustc_features())
242 .arg("--manifest-path")
243 .arg(build.src.join("src/rustc/Cargo.toml"));
245 // Set some configuration variables picked up by build scripts and
246 // the compiler alike
247 cargo.env("CFG_RELEASE", build.rust_release())
248 .env("CFG_RELEASE_CHANNEL", &build.config.channel)
249 .env("CFG_VERSION", build.rust_version())
250 .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or_default());
252 if compiler.stage == 0 {
253 cargo.env("CFG_LIBDIR_RELATIVE", "lib");
255 let libdir_relative = build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
256 cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
259 // If we're not building a compiler with debugging information then remove
260 // these two env vars which would be set otherwise.
261 if build.config.rust_debuginfo_only_std {
262 cargo.env_remove("RUSTC_DEBUGINFO");
263 cargo.env_remove("RUSTC_DEBUGINFO_LINES");
266 if let Some(ref ver_date) = build.rust_info.commit_date() {
267 cargo.env("CFG_VER_DATE", ver_date);
269 if let Some(ref ver_hash) = build.rust_info.sha() {
270 cargo.env("CFG_VER_HASH", ver_hash);
272 if !build.unstable_features() {
273 cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
275 // Flag that rust llvm is in use
276 if build.is_rust_llvm(target) {
277 cargo.env("LLVM_RUSTLLVM", "1");
279 cargo.env("LLVM_CONFIG", build.llvm_config(target));
280 let target_config = build.config.target_config.get(target);
281 if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
282 cargo.env("CFG_LLVM_ROOT", s);
284 // Building with a static libstdc++ is only supported on linux right now,
285 // not for MSVC or macOS
286 if build.config.llvm_static_stdcpp &&
287 !target.contains("windows") &&
288 !target.contains("apple") {
289 cargo.env("LLVM_STATIC_STDCPP",
290 compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
292 if build.config.llvm_link_shared {
293 cargo.env("LLVM_LINK_SHARED", "1");
295 if let Some(ref s) = build.config.rustc_default_linker {
296 cargo.env("CFG_DEFAULT_LINKER", s);
298 if let Some(ref s) = build.config.rustc_default_ar {
299 cargo.env("CFG_DEFAULT_AR", s);
303 &librustc_stamp(build, compiler, target));
306 /// Same as `std_link`, only for librustc
307 pub fn rustc_link(build: &Build,
309 target_compiler: &Compiler,
311 println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
312 target_compiler.stage,
315 target_compiler.host,
317 add_to_sysroot(&build.sysroot_libdir(target_compiler, target),
318 &librustc_stamp(build, compiler, target));
321 /// Cargo's output path for the standard library in a given stage, compiled
322 /// by a particular compiler for the specified target.
323 fn libstd_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
324 build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
327 /// Cargo's output path for libtest in a given stage, compiled by a particular
328 /// compiler for the specified target.
329 fn libtest_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
330 build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
333 /// Cargo's output path for librustc in a given stage, compiled by a particular
334 /// compiler for the specified target.
335 fn librustc_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
336 build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
339 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
340 let out = output(Command::new(compiler)
341 .arg(format!("-print-file-name={}", file)));
342 PathBuf::from(out.trim())
345 pub fn create_sysroot(build: &Build, compiler: &Compiler) {
346 let sysroot = build.sysroot(compiler);
347 let _ = fs::remove_dir_all(&sysroot);
348 t!(fs::create_dir_all(&sysroot));
351 /// Prepare a new compiler from the artifacts in `stage`
353 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
354 /// must have been previously produced by the `stage - 1` build.build
356 pub fn assemble_rustc(build: &Build, stage: u32, host: &str) {
357 // nothing to do in stage0
362 println!("Copying stage{} compiler ({})", stage, host);
364 // The compiler that we're assembling
365 let target_compiler = Compiler::new(stage, host);
367 // The compiler that compiled the compiler we're assembling
368 let build_compiler = Compiler::new(stage - 1, &build.build);
370 // Link in all dylibs to the libdir
371 let sysroot = build.sysroot(&target_compiler);
372 let sysroot_libdir = sysroot.join(libdir(host));
373 t!(fs::create_dir_all(&sysroot_libdir));
374 let src_libdir = build.sysroot_libdir(&build_compiler, host);
375 for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
376 let filename = f.file_name().into_string().unwrap();
377 if is_dylib(&filename) {
378 copy(&f.path(), &sysroot_libdir.join(&filename));
382 let out_dir = build.cargo_out(&build_compiler, Mode::Librustc, host);
384 // Link the compiler binary itself into place
385 let rustc = out_dir.join(exe("rustc", host));
386 let bindir = sysroot.join("bin");
387 t!(fs::create_dir_all(&bindir));
388 let compiler = build.compiler_path(&target_compiler);
389 let _ = fs::remove_file(&compiler);
390 copy(&rustc, &compiler);
392 // See if rustdoc exists to link it into place
393 let rustdoc = exe("rustdoc", host);
394 let rustdoc_src = out_dir.join(&rustdoc);
395 let rustdoc_dst = bindir.join(&rustdoc);
396 if fs::metadata(&rustdoc_src).is_ok() {
397 let _ = fs::remove_file(&rustdoc_dst);
398 copy(&rustdoc_src, &rustdoc_dst);
402 /// Link some files into a rustc sysroot.
404 /// For a particular stage this will link the file listed in `stamp` into the
405 /// `sysroot_dst` provided.
406 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
407 t!(fs::create_dir_all(&sysroot_dst));
408 let mut contents = Vec::new();
409 t!(t!(File::open(stamp)).read_to_end(&mut contents));
410 // This is the method we use for extracting paths from the stamp file passed to us. See
411 // run_cargo for more information (in this file).
412 for part in contents.split(|b| *b == 0) {
416 let path = Path::new(t!(str::from_utf8(part)));
417 copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
421 /// Build a tool in `src/tools`
423 /// This will build the specified tool with the specified `host` compiler in
424 /// `stage` into the normal cargo output directory.
425 pub fn maybe_clean_tools(build: &Build, stage: u32, target: &str, mode: Mode) {
426 let compiler = Compiler::new(stage, &build.build);
428 let stamp = match mode {
429 Mode::Libstd => libstd_stamp(build, &compiler, target),
430 Mode::Libtest => libtest_stamp(build, &compiler, target),
431 Mode::Librustc => librustc_stamp(build, &compiler, target),
434 let out_dir = build.cargo_out(&compiler, Mode::Tool, target);
435 build.clear_if_dirty(&out_dir, &stamp);
438 /// Build a tool in `src/tools`
440 /// This will build the specified tool with the specified `host` compiler in
441 /// `stage` into the normal cargo output directory.
442 pub fn tool(build: &Build, stage: u32, target: &str, tool: &str) {
443 let _folder = build.fold_output(|| format!("stage{}-{}", stage, tool));
444 println!("Building stage{} tool {} ({})", stage, tool, target);
446 let compiler = Compiler::new(stage, &build.build);
448 let mut cargo = build.cargo(&compiler, Mode::Tool, target, "build");
449 let dir = build.src.join("src/tools").join(tool);
450 cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
452 // We don't want to build tools dynamically as they'll be running across
453 // stages and such and it's just easier if they're not dynamically linked.
454 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
456 if let Some(dir) = build.openssl_install_dir(target) {
457 cargo.env("OPENSSL_STATIC", "1");
458 cargo.env("OPENSSL_DIR", dir);
459 cargo.env("LIBZ_SYS_STATIC", "1");
462 cargo.env("CFG_RELEASE_CHANNEL", &build.config.channel);
464 let info = GitInfo::new(&dir);
465 if let Some(sha) = info.sha() {
466 cargo.env("CFG_COMMIT_HASH", sha);
468 if let Some(sha_short) = info.sha_short() {
469 cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
471 if let Some(date) = info.commit_date() {
472 cargo.env("CFG_COMMIT_DATE", date);
475 build.run(&mut cargo);
479 // Avoiding a dependency on winapi to keep compile times down
481 fn stderr_isatty() -> bool {
483 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
486 fn stderr_isatty() -> bool {
489 type HANDLE = *mut u8;
490 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
492 fn GetStdHandle(which: DWORD) -> HANDLE;
493 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
496 let handle = GetStdHandle(STD_ERROR_HANDLE);
498 GetConsoleMode(handle, &mut out) != 0
502 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
503 // Instruct Cargo to give us json messages on stdout, critically leaving
504 // stderr as piped so we can get those pretty colors.
505 cargo.arg("--message-format").arg("json")
506 .stdout(Stdio::piped());
509 // since we pass message-format=json to cargo, we need to tell the rustc
510 // wrapper to give us colored output if necessary. This is because we
511 // only want Cargo's JSON output, not rustcs.
512 cargo.env("RUSTC_COLOR", "1");
515 build.verbose(&format!("running: {:?}", cargo));
516 let mut child = match cargo.spawn() {
518 Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
521 // `target_root_dir` looks like $dir/$target/release
522 let target_root_dir = stamp.parent().unwrap();
523 // `target_deps_dir` looks like $dir/$target/release/deps
524 let target_deps_dir = target_root_dir.join("deps");
525 // `host_root_dir` looks like $dir/release
526 let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
527 .parent().unwrap() // chop off `$target`
528 .join(target_root_dir.file_name().unwrap());
530 // Spawn Cargo slurping up its JSON output. We'll start building up the
531 // `deps` array of all files it generated along with a `toplevel` array of
532 // files we need to probe for later.
533 let mut deps = Vec::new();
534 let mut toplevel = Vec::new();
535 let stdout = BufReader::new(child.stdout.take().unwrap());
536 for line in stdout.lines() {
538 let json = if line.starts_with("{") {
539 t!(line.parse::<json::Json>())
541 // If this was informational, just print it out and continue
542 println!("{}", line);
545 if json.find("reason").and_then(|j| j.as_string()) != Some("compiler-artifact") {
548 for filename in json["filenames"].as_array().unwrap() {
549 let filename = filename.as_string().unwrap();
550 // Skip files like executables
551 if !filename.ends_with(".rlib") &&
552 !filename.ends_with(".lib") &&
553 !is_dylib(&filename) {
557 let filename = Path::new(filename);
559 // If this was an output file in the "host dir" we don't actually
560 // worry about it, it's not relevant for us.
561 if filename.starts_with(&host_root_dir) {
565 // If this was output in the `deps` dir then this is a precise file
566 // name (hash included) so we start tracking it.
567 if filename.starts_with(&target_deps_dir) {
568 deps.push(filename.to_path_buf());
572 // Otherwise this was a "top level artifact" which right now doesn't
573 // have a hash in the name, but there's a version of this file in
574 // the `deps` folder which *does* have a hash in the name. That's
575 // the one we'll want to we'll probe for it later.
576 toplevel.push((filename.file_stem().unwrap()
577 .to_str().unwrap().to_string(),
578 filename.extension().unwrap().to_owned()
579 .to_str().unwrap().to_string()));
583 // Make sure Cargo actually succeeded after we read all of its stdout.
584 let status = t!(child.wait());
585 if !status.success() {
586 panic!("command did not execute successfully: {:?}\n\
587 expected success, got: {}",
592 // Ok now we need to actually find all the files listed in `toplevel`. We've
593 // got a list of prefix/extensions and we basically just need to find the
594 // most recent file in the `deps` folder corresponding to each one.
595 let contents = t!(target_deps_dir.read_dir())
597 .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
598 .collect::<Vec<_>>();
599 for (prefix, extension) in toplevel {
600 let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
601 filename.starts_with(&prefix[..]) &&
602 filename[prefix.len()..].starts_with("-") &&
603 filename.ends_with(&extension[..])
605 let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
606 FileTime::from_last_modification_time(metadata)
608 let path_to_add = match max {
609 Some(triple) => triple.0.to_str().unwrap(),
610 None => panic!("no output generated for {:?} {:?}", prefix, extension),
612 if is_dylib(path_to_add) {
613 let candidate = format!("{}.lib", path_to_add);
614 let candidate = PathBuf::from(candidate);
615 if candidate.exists() {
616 deps.push(candidate);
619 deps.push(path_to_add.into());
622 // Now we want to update the contents of the stamp file, if necessary. First
623 // we read off the previous contents along with its mtime. If our new
624 // contents (the list of files to copy) is different or if any dep's mtime
625 // is newer then we rewrite the stamp file.
627 let mut stamp_contents = Vec::new();
628 if let Ok(mut f) = File::open(stamp) {
629 t!(f.read_to_end(&mut stamp_contents));
631 let stamp_mtime = mtime(&stamp);
632 let mut new_contents = Vec::new();
634 let mut max_path = None;
636 let mtime = mtime(&dep);
637 if Some(mtime) > max {
639 max_path = Some(dep.clone());
641 new_contents.extend(dep.to_str().unwrap().as_bytes());
642 new_contents.extend(b"\0");
644 let max = max.unwrap();
645 let max_path = max_path.unwrap();
646 if stamp_contents == new_contents && max <= stamp_mtime {
649 if max > stamp_mtime {
650 build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
652 build.verbose(&format!("updating {:?} as deps changed", stamp));
654 t!(t!(File::create(stamp)).write_all(&new_contents));