]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
618fa3805b37fc0af6e2a3a576791f1c12d667b4
[rust.git] / src / bootstrap / compile.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 compiling various phases of the compiler and standard
12 //! library.
13 //!
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.
18
19 use std::collections::HashMap;
20 use std::fs;
21 use std::path::{Path, PathBuf};
22 use std::process::Command;
23
24 use build_helper::output;
25
26 use util::{exe, staticlib, libdir, mtime, is_dylib, copy};
27 use {Build, Compiler, Mode};
28
29 /// Build the standard library.
30 ///
31 /// This will build the standard library for a particular stage of the build
32 /// using the `compiler` targeting the `target` architecture. The artifacts
33 /// created will also be linked into the sysroot directory.
34 pub fn std<'a>(build: &'a Build, target: &str, compiler: &Compiler<'a>) {
35     println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
36              compiler.host, target);
37
38     // Move compiler-rt into place as it'll be required by the compiler when
39     // building the standard library to link the dylib of libstd
40     let libdir = build.sysroot_libdir(compiler, target);
41     let _ = fs::remove_dir_all(&libdir);
42     t!(fs::create_dir_all(&libdir));
43     copy(&build.compiler_rt_built.borrow()[target],
44          &libdir.join(staticlib("compiler-rt", target)));
45
46     // Some platforms have startup objects that may be required to produce the
47     // libstd dynamic library, for example.
48     build_startup_objects(build, target, &libdir);
49
50     let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
51     build.clear_if_dirty(&out_dir, &build.compiler_path(compiler));
52     let mut cargo = build.cargo(compiler, Mode::Libstd, target, "build");
53     cargo.arg("--features").arg(build.std_features())
54          .arg("--manifest-path")
55          .arg(build.src.join("src/rustc/std_shim/Cargo.toml"));
56
57     if let Some(target) = build.config.target_config.get(target) {
58         if let Some(ref jemalloc) = target.jemalloc {
59             cargo.env("JEMALLOC_OVERRIDE", jemalloc);
60         }
61     }
62     if target.contains("musl") {
63         if let Some(p) = build.musl_root(target) {
64             cargo.env("MUSL_ROOT", p);
65         }
66     }
67
68     build.run(&mut cargo);
69     std_link(build, target, compiler, compiler.host);
70 }
71
72 /// Link all libstd rlibs/dylibs into the sysroot location.
73 ///
74 /// Links those artifacts generated in the given `stage` for `target` produced
75 /// by `compiler` into `host`'s sysroot.
76 pub fn std_link(build: &Build,
77                 target: &str,
78                 compiler: &Compiler,
79                 host: &str) {
80     let target_compiler = Compiler::new(compiler.stage, host);
81     let libdir = build.sysroot_libdir(&target_compiler, target);
82     let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
83
84     // If we're linking one compiler host's output into another, then we weren't
85     // called from the `std` method above. In that case we clean out what's
86     // already there and then also link compiler-rt into place.
87     if host != compiler.host {
88         let _ = fs::remove_dir_all(&libdir);
89         t!(fs::create_dir_all(&libdir));
90         copy(&build.compiler_rt_built.borrow()[target],
91              &libdir.join(staticlib("compiler-rt", target)));
92     }
93     add_to_sysroot(&out_dir, &libdir);
94
95     if target.contains("musl") && !target.contains("mips") {
96         copy_musl_third_party_objects(build, &libdir);
97     }
98 }
99
100 /// Copies the crt(1,i,n).o startup objects
101 ///
102 /// Only required for musl targets that statically link to libc
103 fn copy_musl_third_party_objects(build: &Build, into: &Path) {
104     for &obj in &["crt1.o", "crti.o", "crtn.o"] {
105         copy(&build.config.musl_root.as_ref().unwrap().join("lib").join(obj), &into.join(obj));
106     }
107 }
108
109 /// Build and prepare startup objects like rsbegin.o and rsend.o
110 ///
111 /// These are primarily used on Windows right now for linking executables/dlls.
112 /// They don't require any library support as they're just plain old object
113 /// files, so we just use the nightly snapshot compiler to always build them (as
114 /// no other compilers are guaranteed to be available).
115 fn build_startup_objects(build: &Build, target: &str, into: &Path) {
116     if !target.contains("pc-windows-gnu") {
117         return
118     }
119     let compiler = Compiler::new(0, &build.config.build);
120     let compiler_path = build.compiler_path(&compiler);
121
122     for file in t!(fs::read_dir(build.src.join("src/rtstartup"))) {
123         let file = t!(file);
124         let mut cmd = Command::new(&compiler_path);
125         build.add_bootstrap_key(&compiler, &mut cmd);
126         build.run(cmd.arg("--target").arg(target)
127                      .arg("--emit=obj")
128                      .arg("--out-dir").arg(into)
129                      .arg(file.path()));
130     }
131
132     for obj in ["crt2.o", "dllcrt2.o"].iter() {
133         copy(&compiler_file(build.cc(target), obj), &into.join(obj));
134     }
135 }
136
137 /// Build libtest.
138 ///
139 /// This will build libtest and supporting libraries for a particular stage of
140 /// the build using the `compiler` targeting the `target` architecture. The
141 /// artifacts created will also be linked into the sysroot directory.
142 pub fn test<'a>(build: &'a Build, target: &str, compiler: &Compiler<'a>) {
143     println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
144              compiler.host, target);
145     let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
146     build.clear_if_dirty(&out_dir, &libstd_shim(build, compiler, target));
147     let mut cargo = build.cargo(compiler, Mode::Libtest, target, "build");
148     cargo.arg("--manifest-path")
149          .arg(build.src.join("src/rustc/test_shim/Cargo.toml"));
150     build.run(&mut cargo);
151     test_link(build, target, compiler, compiler.host);
152 }
153
154 /// Link all libtest rlibs/dylibs into the sysroot location.
155 ///
156 /// Links those artifacts generated in the given `stage` for `target` produced
157 /// by `compiler` into `host`'s sysroot.
158 pub fn test_link(build: &Build,
159                  target: &str,
160                  compiler: &Compiler,
161                  host: &str) {
162     let target_compiler = Compiler::new(compiler.stage, host);
163     let libdir = build.sysroot_libdir(&target_compiler, target);
164     let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
165     add_to_sysroot(&out_dir, &libdir);
166 }
167
168 /// Build the compiler.
169 ///
170 /// This will build the compiler for a particular stage of the build using
171 /// the `compiler` targeting the `target` architecture. The artifacts
172 /// created will also be linked into the sysroot directory.
173 pub fn rustc<'a>(build: &'a Build, target: &str, compiler: &Compiler<'a>) {
174     println!("Building stage{} compiler artifacts ({} -> {})",
175              compiler.stage, compiler.host, target);
176
177     let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
178     build.clear_if_dirty(&out_dir, &libtest_shim(build, compiler, target));
179
180     let mut cargo = build.cargo(compiler, Mode::Librustc, target, "build");
181     cargo.arg("--features").arg(build.rustc_features())
182          .arg("--manifest-path")
183          .arg(build.src.join("src/rustc/Cargo.toml"));
184
185     // Set some configuration variables picked up by build scripts and
186     // the compiler alike
187     cargo.env("CFG_RELEASE", &build.release)
188          .env("CFG_RELEASE_CHANNEL", &build.config.channel)
189          .env("CFG_VERSION", &build.version)
190          .env("CFG_BOOTSTRAP_KEY", &build.bootstrap_key)
191          .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or(String::new()))
192          .env("CFG_LIBDIR_RELATIVE", "lib");
193
194     if let Some(ref ver_date) = build.ver_date {
195         cargo.env("CFG_VER_DATE", ver_date);
196     }
197     if let Some(ref ver_hash) = build.ver_hash {
198         cargo.env("CFG_VER_HASH", ver_hash);
199     }
200     if !build.unstable_features {
201         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
202     }
203     // Flag that rust llvm is in use
204     if build.is_rust_llvm(target) {
205         cargo.env("LLVM_RUSTLLVM", "1");
206     }
207     cargo.env("LLVM_CONFIG", build.llvm_config(target));
208     let target_config = build.config.target_config.get(target);
209     if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
210         cargo.env("CFG_LLVM_ROOT", s);
211     }
212     if build.config.llvm_static_stdcpp {
213         cargo.env("LLVM_STATIC_STDCPP",
214                   compiler_file(build.cxx(target), "libstdc++.a"));
215     }
216     if let Some(ref s) = build.config.rustc_default_linker {
217         cargo.env("CFG_DEFAULT_LINKER", s);
218     }
219     if let Some(ref s) = build.config.rustc_default_ar {
220         cargo.env("CFG_DEFAULT_AR", s);
221     }
222     build.run(&mut cargo);
223
224     rustc_link(build, target, compiler, compiler.host);
225 }
226
227 /// Link all librustc rlibs/dylibs into the sysroot location.
228 ///
229 /// Links those artifacts generated in the given `stage` for `target` produced
230 /// by `compiler` into `host`'s sysroot.
231 pub fn rustc_link(build: &Build,
232                   target: &str,
233                   compiler: &Compiler,
234                   host: &str) {
235     let target_compiler = Compiler::new(compiler.stage, host);
236     let libdir = build.sysroot_libdir(&target_compiler, target);
237     let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
238     add_to_sysroot(&out_dir, &libdir);
239 }
240
241 /// Cargo's output path for the standard library in a given stage, compiled
242 /// by a particular compiler for the specified target.
243 fn libstd_shim(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
244     build.cargo_out(compiler, Mode::Libstd, target).join("libstd_shim.rlib")
245 }
246
247 /// Cargo's output path for libtest in a given stage, compiled by a particular
248 /// compiler for the specified target.
249 fn libtest_shim(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
250     build.cargo_out(compiler, Mode::Libtest, target).join("libtest_shim.rlib")
251 }
252
253 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
254     let out = output(Command::new(compiler)
255                             .arg(format!("-print-file-name={}", file)));
256     PathBuf::from(out.trim())
257 }
258
259 /// Prepare a new compiler from the artifacts in `stage`
260 ///
261 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
262 /// must have been previously produced by the `stage - 1` build.config.build
263 /// compiler.
264 pub fn assemble_rustc(build: &Build, stage: u32, host: &str) {
265     assert!(stage > 0, "the stage0 compiler isn't assembled, it's downloaded");
266     // The compiler that we're assembling
267     let target_compiler = Compiler::new(stage, host);
268
269     // The compiler that compiled the compiler we're assembling
270     let build_compiler = Compiler::new(stage - 1, &build.config.build);
271
272     // Clear out old files
273     let sysroot = build.sysroot(&target_compiler);
274     let _ = fs::remove_dir_all(&sysroot);
275     t!(fs::create_dir_all(&sysroot));
276
277     // Link in all dylibs to the libdir
278     let sysroot_libdir = sysroot.join(libdir(host));
279     t!(fs::create_dir_all(&sysroot_libdir));
280     let src_libdir = build.sysroot_libdir(&build_compiler, host);
281     for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
282         let filename = f.file_name().into_string().unwrap();
283         if is_dylib(&filename) {
284             copy(&f.path(), &sysroot_libdir.join(&filename));
285         }
286     }
287
288     let out_dir = build.cargo_out(&build_compiler, Mode::Librustc, host);
289
290     // Link the compiler binary itself into place
291     let rustc = out_dir.join(exe("rustc", host));
292     let bindir = sysroot.join("bin");
293     t!(fs::create_dir_all(&bindir));
294     let compiler = build.compiler_path(&Compiler::new(stage, host));
295     let _ = fs::remove_file(&compiler);
296     copy(&rustc, &compiler);
297
298     // See if rustdoc exists to link it into place
299     let rustdoc = exe("rustdoc", host);
300     let rustdoc_src = out_dir.join(&rustdoc);
301     let rustdoc_dst = bindir.join(&rustdoc);
302     if fs::metadata(&rustdoc_src).is_ok() {
303         let _ = fs::remove_file(&rustdoc_dst);
304         copy(&rustdoc_src, &rustdoc_dst);
305     }
306 }
307
308 /// Link some files into a rustc sysroot.
309 ///
310 /// For a particular stage this will link all of the contents of `out_dir`
311 /// into the sysroot of the `host` compiler, assuming the artifacts are
312 /// compiled for the specified `target`.
313 fn add_to_sysroot(out_dir: &Path, sysroot_dst: &Path) {
314     // Collect the set of all files in the dependencies directory, keyed
315     // off the name of the library. We assume everything is of the form
316     // `foo-<hash>.{rlib,so,...}`, and there could be multiple different
317     // `<hash>` values for the same name (of old builds).
318     let mut map = HashMap::new();
319     for file in t!(fs::read_dir(out_dir.join("deps"))).map(|f| t!(f)) {
320         let filename = file.file_name().into_string().unwrap();
321
322         // We're only interested in linking rlibs + dylibs, other things like
323         // unit tests don't get linked in
324         if !filename.ends_with(".rlib") &&
325            !filename.ends_with(".lib") &&
326            !is_dylib(&filename) {
327             continue
328         }
329         let file = file.path();
330         let dash = filename.find("-").unwrap();
331         let key = (filename[..dash].to_string(),
332                    file.extension().unwrap().to_owned());
333         map.entry(key).or_insert(Vec::new())
334            .push(file.clone());
335     }
336
337     // For all hash values found, pick the most recent one to move into the
338     // sysroot, that should be the one we just built.
339     for (_, paths) in map {
340         let (_, path) = paths.iter().map(|path| {
341             (mtime(&path).seconds(), path)
342         }).max().unwrap();
343         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
344     }
345 }
346
347 /// Build a tool in `src/tools`
348 ///
349 /// This will build the specified tool with the specified `host` compiler in
350 /// `stage` into the normal cargo output directory.
351 pub fn tool(build: &Build, stage: u32, host: &str, tool: &str) {
352     println!("Building stage{} tool {} ({})", stage, tool, host);
353
354     let compiler = Compiler::new(stage, host);
355
356     // FIXME: need to clear out previous tool and ideally deps, may require
357     //        isolating output directories or require a pseudo shim step to
358     //        clear out all the info.
359     //
360     //        Maybe when libstd is compiled it should clear out the rustc of the
361     //        corresponding stage?
362     // let out_dir = build.cargo_out(stage, &host, Mode::Librustc, target);
363     // build.clear_if_dirty(&out_dir, &libstd_shim(build, stage, &host, target));
364
365     let mut cargo = build.cargo(&compiler, Mode::Tool, host, "build");
366     cargo.arg("--manifest-path")
367          .arg(build.src.join(format!("src/tools/{}/Cargo.toml", tool)));
368     build.run(&mut cargo);
369 }