]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/build/compile.rs
c22648b47109836a23def709144c46421b6c8e13
[rust.git] / src / bootstrap / build / 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 use std::collections::HashMap;
12 use std::fs;
13 use std::path::{Path, PathBuf};
14 use std::process::Command;
15
16 use build_helper::output;
17
18 use build::util::{exe, staticlib, libdir, mtime, is_dylib};
19 use build::{Build, Compiler};
20
21 /// Build the standard library.
22 ///
23 /// This will build the standard library for a particular stage of the build
24 /// using the `compiler` targeting the `target` architecture. The artifacts
25 /// created will also be linked into the sysroot directory.
26 pub fn std<'a>(build: &'a Build, stage: u32, target: &str,
27                compiler: &Compiler<'a>) {
28     let host = compiler.host;
29     println!("Building stage{} std artifacts ({} -> {})", stage,
30              host, target);
31
32     // Move compiler-rt into place as it'll be required by the compiler when
33     // building the standard library to link the dylib of libstd
34     let libdir = build.sysroot_libdir(stage, &host, target);
35     let _ = fs::remove_dir_all(&libdir);
36     t!(fs::create_dir_all(&libdir));
37     t!(fs::hard_link(&build.compiler_rt_built.borrow()[target],
38                      libdir.join(staticlib("compiler-rt", target))));
39
40     build_startup_objects(build, target, &libdir);
41
42     let out_dir = build.cargo_out(stage, &host, true, target);
43     build.clear_if_dirty(&out_dir, &build.compiler_path(compiler));
44     let mut cargo = build.cargo(stage, compiler, true, target, "build");
45     cargo.arg("--features").arg(build.std_features())
46          .arg("--manifest-path")
47          .arg(build.src.join("src/rustc/std_shim/Cargo.toml"));
48
49     if let Some(target) = build.config.target_config.get(target) {
50         if let Some(ref jemalloc) = target.jemalloc {
51             cargo.env("JEMALLOC_OVERRIDE", jemalloc);
52         }
53     }
54     if let Some(ref p) = build.config.musl_root {
55         if target.contains("musl") {
56             cargo.env("MUSL_ROOT", p);
57         }
58     }
59
60     build.run(&mut cargo);
61     add_to_sysroot(&out_dir, &libdir);
62 }
63
64 /// Build and prepare startup objects like rsbegin.o and rsend.o
65 ///
66 /// These are primarily used on Windows right now for linking executables/dlls.
67 /// They don't require any library support as they're just plain old object
68 /// files, so we just use the nightly snapshot compiler to always build them (as
69 /// no other compilers are guaranteed to be available).
70 fn build_startup_objects(build: &Build, target: &str, into: &Path) {
71     if !target.contains("pc-windows-gnu") {
72         return
73     }
74     let compiler = Compiler::new(0, &build.config.build);
75     let compiler = build.compiler_path(&compiler);
76
77     for file in t!(fs::read_dir(build.src.join("src/rtstartup"))) {
78         let file = t!(file);
79         build.run(Command::new(&compiler)
80                           .arg("--emit=obj")
81                           .arg("--out-dir").arg(into)
82                           .arg(file.path()));
83     }
84
85     for obj in ["crt2.o", "dllcrt2.o"].iter() {
86         t!(fs::copy(compiler_file(build.cc(target), obj), into.join(obj)));
87     }
88 }
89
90 /// Build the compiler.
91 ///
92 /// This will build the compiler for a particular stage of the build using
93 /// the `compiler` targeting the `target` architecture. The artifacts
94 /// created will also be linked into the sysroot directory.
95 pub fn rustc<'a>(build: &'a Build, stage: u32, target: &str,
96                  compiler: &Compiler<'a>) {
97     let host = compiler.host;
98     println!("Building stage{} compiler artifacts ({} -> {})", stage,
99              host, target);
100
101     let out_dir = build.cargo_out(stage, &host, false, target);
102     let rustc = out_dir.join(exe("rustc", target));
103     build.clear_if_dirty(&out_dir, &libstd_shim(build, stage, &host, target));
104
105     let mut cargo = build.cargo(stage, compiler, false, target, "build");
106     cargo.arg("--features").arg(build.rustc_features(stage))
107          .arg("--manifest-path")
108          .arg(build.src.join("src/rustc/Cargo.toml"));
109
110     // In stage0 we may not need to build as many executables
111     if stage == 0 {
112         cargo.arg("--bin").arg("rustc");
113     }
114
115     // Set some configuration variables picked up by build scripts and
116     // the compiler alike
117     cargo.env("CFG_RELEASE", &build.release)
118          .env("CFG_RELEASE_CHANNEL", &build.config.channel)
119          .env("CFG_VERSION", &build.version)
120          .env("CFG_BOOTSTRAP_KEY", &build.bootstrap_key)
121          .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or(String::new()))
122          .env("RUSTC_BOOTSTRAP_KEY", &build.bootstrap_key)
123          .env("CFG_LIBDIR_RELATIVE", "lib");
124
125     if let Some(ref ver_date) = build.ver_date {
126         cargo.env("CFG_VER_DATE", ver_date);
127     }
128     if let Some(ref ver_hash) = build.ver_hash {
129         cargo.env("CFG_VER_HASH", ver_hash);
130     }
131     if !build.unstable_features {
132         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
133     }
134     if let Some(config) = build.config.target_config.get(target) {
135         if let Some(ref s) = config.llvm_config {
136             cargo.env("LLVM_CONFIG", s);
137         }
138     }
139     if build.config.llvm_static_stdcpp {
140         cargo.env("LLVM_STATIC_STDCPP",
141                   compiler_file(build.cxx(target), "libstdc++.a"));
142     }
143     if let Some(ref s) = build.config.rustc_default_linker {
144         cargo.env("CFG_DEFAULT_LINKER", s);
145     }
146     if let Some(ref s) = build.config.rustc_default_ar {
147         cargo.env("CFG_DEFAULT_AR", s);
148     }
149     build.run(&mut cargo);
150
151     let sysroot_libdir = build.sysroot_libdir(stage, host, target);
152     add_to_sysroot(&out_dir, &sysroot_libdir);
153
154     if host == target {
155         assemble_compiler(build, stage, target, &rustc);
156     }
157 }
158
159 /// Cargo's output path for the standard library in a given stage, compiled
160 /// by a particular compiler for the specified target.
161 fn libstd_shim(build: &Build, stage: u32, host: &str, target: &str) -> PathBuf {
162     build.cargo_out(stage, host, true, target).join("libstd_shim.rlib")
163 }
164
165 fn compiler_file(compiler: &Path, file: &str) -> String {
166     output(Command::new(compiler)
167                    .arg(format!("-print-file-name={}", file))).trim().to_string()
168 }
169
170 /// Prepare a new compiler from the artifacts in `stage`
171 ///
172 /// This will link the compiler built by `host` during the stage
173 /// specified to the sysroot location for `host` to be the official
174 /// `stage + 1` compiler for that host. This means that the `rustc` binary
175 /// itself will be linked into place along with all supporting dynamic
176 /// libraries.
177 fn assemble_compiler(build: &Build, stage: u32, host: &str, rustc: &Path) {
178     // Clear out old files
179     let sysroot = build.sysroot(stage + 1, host);
180     let _ = fs::remove_dir_all(&sysroot);
181     t!(fs::create_dir_all(&sysroot));
182
183     // Link in all dylibs to the libdir
184     let sysroot_libdir = sysroot.join(libdir(host));
185     t!(fs::create_dir_all(&sysroot_libdir));
186     let src_libdir = build.sysroot_libdir(stage, host, host);
187     for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
188         let filename = f.file_name().into_string().unwrap();
189         if is_dylib(&filename) {
190             t!(fs::hard_link(&f.path(), sysroot_libdir.join(&filename)));
191         }
192     }
193
194     // Link the compiler binary itself into place
195     let bindir = sysroot.join("bin");
196     t!(fs::create_dir_all(&bindir));
197     let compiler = build.compiler_path(&Compiler::new(stage + 1, host));
198     let _ = fs::remove_file(&compiler);
199     t!(fs::hard_link(rustc, compiler));
200
201     // See if rustdoc exists to link it into place
202     let exe = exe("rustdoc", host);
203     let rustdoc_src = rustc.parent().unwrap().join(&exe);
204     let rustdoc_dst = bindir.join(exe);
205     if fs::metadata(&rustdoc_src).is_ok() {
206         let _ = fs::remove_file(&rustdoc_dst);
207         t!(fs::hard_link(&rustdoc_src, &rustdoc_dst));
208     }
209 }
210
211 /// Link some files into a rustc sysroot.
212 ///
213 /// For a particular stage this will link all of the contents of `out_dir`
214 /// into the sysroot of the `host` compiler, assuming the artifacts are
215 /// compiled for the specified `target`.
216 fn add_to_sysroot(out_dir: &Path, sysroot_dst: &Path) {
217     // Collect the set of all files in the dependencies directory, keyed
218     // off the name of the library. We assume everything is of the form
219     // `foo-<hash>.{rlib,so,...}`, and there could be multiple different
220     // `<hash>` values for the same name (of old builds).
221     let mut map = HashMap::new();
222     for file in t!(fs::read_dir(out_dir.join("deps"))).map(|f| t!(f)) {
223         let filename = file.file_name().into_string().unwrap();
224
225         // We're only interested in linking rlibs + dylibs, other things like
226         // unit tests don't get linked in
227         if !filename.ends_with(".rlib") &&
228            !filename.ends_with(".lib") &&
229            !is_dylib(&filename) {
230             continue
231         }
232         let file = file.path();
233         let dash = filename.find("-").unwrap();
234         let key = (filename[..dash].to_string(),
235                    file.extension().unwrap().to_owned());
236         map.entry(key).or_insert(Vec::new())
237            .push(file.clone());
238     }
239
240     // For all hash values found, pick the most recent one to move into the
241     // sysroot, that should be the one we just built.
242     for (_, paths) in map {
243         let (_, path) = paths.iter().map(|path| {
244             (mtime(&path).seconds(), path)
245         }).max().unwrap();
246         t!(fs::hard_link(&path,
247                          sysroot_dst.join(path.file_name().unwrap())));
248     }
249 }