]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[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::{self, File};
21 use std::path::{Path, PathBuf};
22 use std::process::Command;
23
24 use build_helper::{output, mtime};
25 use filetime::FileTime;
26
27 use util::{exe, libdir, is_dylib, copy};
28 use {Build, Compiler, Mode};
29
30 /// Build the standard library.
31 ///
32 /// This will build the standard library for a particular stage of the build
33 /// using the `compiler` targeting the `target` architecture. The artifacts
34 /// created will also be linked into the sysroot directory.
35 pub fn std(build: &Build, target: &str, compiler: &Compiler) {
36     let libdir = build.sysroot_libdir(compiler, target);
37     t!(fs::create_dir_all(&libdir));
38
39     println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
40              compiler.host, target);
41
42     let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
43     build.clear_if_dirty(&out_dir, &build.compiler_path(compiler));
44     let mut cargo = build.cargo(compiler, Mode::Libstd, target, "build");
45     let mut features = build.std_features();
46     // When doing a local rebuild we tell cargo that we're stage1 rather than
47     // stage0. This works fine if the local rust and being-built rust have the
48     // same view of what the default allocator is, but fails otherwise. Since
49     // we don't have a way to express an allocator preference yet, work
50     // around the issue in the case of a local rebuild with jemalloc disabled.
51     if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
52         features.push_str(" force_alloc_system");
53     }
54
55     if compiler.stage != 0 && build.config.sanitizers {
56         // This variable is used by the sanitizer runtime crates, e.g.
57         // rustc_lsan, to build the sanitizer runtime from C code
58         // When this variable is missing, those crates won't compile the C code,
59         // so we don't set this variable during stage0 where llvm-config is
60         // missing
61         // We also only build the runtimes when --enable-sanitizers (or its
62         // config.toml equivalent) is used
63         cargo.env("LLVM_CONFIG", build.llvm_config(target));
64     }
65     cargo.arg("--features").arg(features)
66          .arg("--manifest-path")
67          .arg(build.src.join("src/rustc/std_shim/Cargo.toml"));
68
69     if let Some(target) = build.config.target_config.get(target) {
70         if let Some(ref jemalloc) = target.jemalloc {
71             cargo.env("JEMALLOC_OVERRIDE", jemalloc);
72         }
73     }
74     if target.contains("musl") {
75         if let Some(p) = build.musl_root(target) {
76             cargo.env("MUSL_ROOT", p);
77         }
78     }
79
80     build.run(&mut cargo);
81     update_mtime(build, &libstd_stamp(build, &compiler, target));
82 }
83
84 /// Link all libstd rlibs/dylibs into the sysroot location.
85 ///
86 /// Links those artifacts generated by `compiler` to a the `stage` compiler's
87 /// sysroot for the specified `host` and `target`.
88 ///
89 /// Note that this assumes that `compiler` has already generated the libstd
90 /// libraries for `target`, and this method will find them in the relevant
91 /// output directory.
92 pub fn std_link(build: &Build,
93                 compiler: &Compiler,
94                 target_compiler: &Compiler,
95                 target: &str) {
96     println!("Copying stage{} std from stage{} ({} -> {} / {})",
97              target_compiler.stage,
98              compiler.stage,
99              compiler.host,
100              target_compiler.host,
101              target);
102     let libdir = build.sysroot_libdir(&target_compiler, target);
103     let out_dir = build.cargo_out(&compiler, Mode::Libstd, target);
104
105     t!(fs::create_dir_all(&libdir));
106     add_to_sysroot(&out_dir, &libdir);
107
108     if target.contains("musl") && !target.contains("mips") {
109         copy_musl_third_party_objects(build, target, &libdir);
110     }
111 }
112
113 /// Copies the crt(1,i,n).o startup objects
114 ///
115 /// Only required for musl targets that statically link to libc
116 fn copy_musl_third_party_objects(build: &Build, target: &str, into: &Path) {
117     for &obj in &["crt1.o", "crti.o", "crtn.o"] {
118         copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
119     }
120 }
121
122 /// Build and prepare startup objects like rsbegin.o and rsend.o
123 ///
124 /// These are primarily used on Windows right now for linking executables/dlls.
125 /// They don't require any library support as they're just plain old object
126 /// files, so we just use the nightly snapshot compiler to always build them (as
127 /// no other compilers are guaranteed to be available).
128 pub fn build_startup_objects(build: &Build, for_compiler: &Compiler, target: &str) {
129     if !target.contains("pc-windows-gnu") {
130         return
131     }
132
133     let compiler = Compiler::new(0, &build.config.build);
134     let compiler_path = build.compiler_path(&compiler);
135     let into = build.sysroot_libdir(for_compiler, target);
136     t!(fs::create_dir_all(&into));
137
138     for file in t!(fs::read_dir(build.src.join("src/rtstartup"))) {
139         let file = t!(file);
140         let mut cmd = Command::new(&compiler_path);
141         build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
142                      .arg("--target").arg(target)
143                      .arg("--emit=obj")
144                      .arg("--out-dir").arg(&into)
145                      .arg(file.path()));
146     }
147
148     for obj in ["crt2.o", "dllcrt2.o"].iter() {
149         copy(&compiler_file(build.cc(target), obj), &into.join(obj));
150     }
151 }
152
153 /// Build libtest.
154 ///
155 /// This will build libtest and supporting libraries for a particular stage of
156 /// the build using the `compiler` targeting the `target` architecture. The
157 /// artifacts created will also be linked into the sysroot directory.
158 pub fn test(build: &Build, target: &str, compiler: &Compiler) {
159     println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
160              compiler.host, target);
161     let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
162     build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
163     let mut cargo = build.cargo(compiler, Mode::Libtest, target, "build");
164     cargo.arg("--manifest-path")
165          .arg(build.src.join("src/rustc/test_shim/Cargo.toml"));
166     build.run(&mut cargo);
167     update_mtime(build, &libtest_stamp(build, compiler, target));
168 }
169
170 /// Same as `std_link`, only for libtest
171 pub fn test_link(build: &Build,
172                  compiler: &Compiler,
173                  target_compiler: &Compiler,
174                  target: &str) {
175     println!("Copying stage{} test from stage{} ({} -> {} / {})",
176              target_compiler.stage,
177              compiler.stage,
178              compiler.host,
179              target_compiler.host,
180              target);
181     let libdir = build.sysroot_libdir(&target_compiler, target);
182     let out_dir = build.cargo_out(&compiler, Mode::Libtest, target);
183     add_to_sysroot(&out_dir, &libdir);
184 }
185
186 /// Build the compiler.
187 ///
188 /// This will build the compiler for a particular stage of the build using
189 /// the `compiler` targeting the `target` architecture. The artifacts
190 /// created will also be linked into the sysroot directory.
191 pub fn rustc(build: &Build, target: &str, compiler: &Compiler) {
192     println!("Building stage{} compiler artifacts ({} -> {})",
193              compiler.stage, compiler.host, target);
194
195     let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
196     build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
197
198     let mut cargo = build.cargo(compiler, Mode::Librustc, target, "build");
199     cargo.arg("--features").arg(build.rustc_features())
200          .arg("--manifest-path")
201          .arg(build.src.join("src/rustc/Cargo.toml"));
202
203     // Set some configuration variables picked up by build scripts and
204     // the compiler alike
205     cargo.env("CFG_RELEASE", &build.release)
206          .env("CFG_RELEASE_CHANNEL", &build.config.channel)
207          .env("CFG_VERSION", &build.version)
208          .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or(PathBuf::new()));
209
210     if compiler.stage == 0 {
211         cargo.env("CFG_LIBDIR_RELATIVE", "lib");
212     } else {
213         let libdir_relative = build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
214         cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
215     }
216
217     // If we're not building a compiler with debugging information then remove
218     // these two env vars which would be set otherwise.
219     if build.config.rust_debuginfo_only_std {
220         cargo.env_remove("RUSTC_DEBUGINFO");
221         cargo.env_remove("RUSTC_DEBUGINFO_LINES");
222     }
223
224     if let Some(ref ver_date) = build.ver_date {
225         cargo.env("CFG_VER_DATE", ver_date);
226     }
227     if let Some(ref ver_hash) = build.ver_hash {
228         cargo.env("CFG_VER_HASH", ver_hash);
229     }
230     if !build.unstable_features {
231         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
232     }
233     // Flag that rust llvm is in use
234     if build.is_rust_llvm(target) {
235         cargo.env("LLVM_RUSTLLVM", "1");
236     }
237     cargo.env("LLVM_CONFIG", build.llvm_config(target));
238     let target_config = build.config.target_config.get(target);
239     if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
240         cargo.env("CFG_LLVM_ROOT", s);
241     }
242     // Building with a static libstdc++ is only supported on linux right now,
243     // not for MSVC or OSX
244     if build.config.llvm_static_stdcpp &&
245        !target.contains("windows") &&
246        !target.contains("apple") {
247         cargo.env("LLVM_STATIC_STDCPP",
248                   compiler_file(build.cxx(target), "libstdc++.a"));
249     }
250     if build.config.llvm_link_shared {
251         cargo.env("LLVM_LINK_SHARED", "1");
252     }
253     if let Some(ref s) = build.config.rustc_default_linker {
254         cargo.env("CFG_DEFAULT_LINKER", s);
255     }
256     if let Some(ref s) = build.config.rustc_default_ar {
257         cargo.env("CFG_DEFAULT_AR", s);
258     }
259     build.run(&mut cargo);
260 }
261
262 /// Same as `std_link`, only for librustc
263 pub fn rustc_link(build: &Build,
264                   compiler: &Compiler,
265                   target_compiler: &Compiler,
266                   target: &str) {
267     println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
268              target_compiler.stage,
269              compiler.stage,
270              compiler.host,
271              target_compiler.host,
272              target);
273     let libdir = build.sysroot_libdir(&target_compiler, target);
274     let out_dir = build.cargo_out(&compiler, Mode::Librustc, target);
275     add_to_sysroot(&out_dir, &libdir);
276 }
277
278 /// Cargo's output path for the standard library in a given stage, compiled
279 /// by a particular compiler for the specified target.
280 fn libstd_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
281     build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
282 }
283
284 /// Cargo's output path for libtest in a given stage, compiled by a particular
285 /// compiler for the specified target.
286 fn libtest_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
287     build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
288 }
289
290 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
291     let out = output(Command::new(compiler)
292                             .arg(format!("-print-file-name={}", file)));
293     PathBuf::from(out.trim())
294 }
295
296 pub fn create_sysroot(build: &Build, compiler: &Compiler) {
297     let sysroot = build.sysroot(compiler);
298     let _ = fs::remove_dir_all(&sysroot);
299     t!(fs::create_dir_all(&sysroot));
300 }
301
302 /// Prepare a new compiler from the artifacts in `stage`
303 ///
304 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
305 /// must have been previously produced by the `stage - 1` build.config.build
306 /// compiler.
307 pub fn assemble_rustc(build: &Build, stage: u32, host: &str) {
308     // nothing to do in stage0
309     if stage == 0 {
310         return
311     }
312
313     println!("Copying stage{} compiler ({})", stage, host);
314
315     // The compiler that we're assembling
316     let target_compiler = Compiler::new(stage, host);
317
318     // The compiler that compiled the compiler we're assembling
319     let build_compiler = Compiler::new(stage - 1, &build.config.build);
320
321     // Link in all dylibs to the libdir
322     let sysroot = build.sysroot(&target_compiler);
323     let sysroot_libdir = sysroot.join(libdir(host));
324     t!(fs::create_dir_all(&sysroot_libdir));
325     let src_libdir = build.sysroot_libdir(&build_compiler, host);
326     for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
327         let filename = f.file_name().into_string().unwrap();
328         if is_dylib(&filename) {
329             copy(&f.path(), &sysroot_libdir.join(&filename));
330         }
331     }
332
333     let out_dir = build.cargo_out(&build_compiler, Mode::Librustc, host);
334
335     // Link the compiler binary itself into place
336     let rustc = out_dir.join(exe("rustc", host));
337     let bindir = sysroot.join("bin");
338     t!(fs::create_dir_all(&bindir));
339     let compiler = build.compiler_path(&Compiler::new(stage, host));
340     let _ = fs::remove_file(&compiler);
341     copy(&rustc, &compiler);
342
343     // See if rustdoc exists to link it into place
344     let rustdoc = exe("rustdoc", host);
345     let rustdoc_src = out_dir.join(&rustdoc);
346     let rustdoc_dst = bindir.join(&rustdoc);
347     if fs::metadata(&rustdoc_src).is_ok() {
348         let _ = fs::remove_file(&rustdoc_dst);
349         copy(&rustdoc_src, &rustdoc_dst);
350     }
351 }
352
353 /// Link some files into a rustc sysroot.
354 ///
355 /// For a particular stage this will link all of the contents of `out_dir`
356 /// into the sysroot of the `host` compiler, assuming the artifacts are
357 /// compiled for the specified `target`.
358 fn add_to_sysroot(out_dir: &Path, sysroot_dst: &Path) {
359     // Collect the set of all files in the dependencies directory, keyed
360     // off the name of the library. We assume everything is of the form
361     // `foo-<hash>.{rlib,so,...}`, and there could be multiple different
362     // `<hash>` values for the same name (of old builds).
363     let mut map = HashMap::new();
364     for file in t!(fs::read_dir(out_dir.join("deps"))).map(|f| t!(f)) {
365         let filename = file.file_name().into_string().unwrap();
366
367         // We're only interested in linking rlibs + dylibs, other things like
368         // unit tests don't get linked in
369         if !filename.ends_with(".rlib") &&
370            !filename.ends_with(".lib") &&
371            !is_dylib(&filename) {
372             continue
373         }
374         let file = file.path();
375         let dash = filename.find("-").unwrap();
376         let key = (filename[..dash].to_string(),
377                    file.extension().unwrap().to_owned());
378         map.entry(key).or_insert(Vec::new())
379            .push(file.clone());
380     }
381
382     // For all hash values found, pick the most recent one to move into the
383     // sysroot, that should be the one we just built.
384     for (_, paths) in map {
385         let (_, path) = paths.iter().map(|path| {
386             (mtime(&path).seconds(), path)
387         }).max().unwrap();
388         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
389     }
390 }
391
392 /// Build a tool in `src/tools`
393 ///
394 /// This will build the specified tool with the specified `host` compiler in
395 /// `stage` into the normal cargo output directory.
396 pub fn tool(build: &Build, stage: u32, target: &str, tool: &str) {
397     println!("Building stage{} tool {} ({})", stage, tool, target);
398
399     let compiler = Compiler::new(stage, &build.config.build);
400
401     // FIXME: need to clear out previous tool and ideally deps, may require
402     //        isolating output directories or require a pseudo shim step to
403     //        clear out all the info.
404     //
405     //        Maybe when libstd is compiled it should clear out the rustc of the
406     //        corresponding stage?
407     // let out_dir = build.cargo_out(stage, &host, Mode::Librustc, target);
408     // build.clear_if_dirty(&out_dir, &libstd_stamp(build, stage, &host, target));
409
410     let mut cargo = build.cargo(&compiler, Mode::Tool, target, "build");
411     cargo.arg("--manifest-path")
412          .arg(build.src.join(format!("src/tools/{}/Cargo.toml", tool)));
413
414     // We don't want to build tools dynamically as they'll be running across
415     // stages and such and it's just easier if they're not dynamically linked.
416     cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
417
418     build.run(&mut cargo);
419 }
420
421 /// Updates the mtime of a stamp file if necessary, only changing it if it's
422 /// older than some other library file in the same directory.
423 ///
424 /// We don't know what file Cargo is going to output (because there's a hash in
425 /// the file name) but we know where it's going to put it. We use this helper to
426 /// detect changes to that output file by looking at the modification time for
427 /// all files in a directory and updating the stamp if any are newer.
428 ///
429 /// Note that we only consider Rust libraries as that's what we're interested in
430 /// propagating changes from. Files like executables are tracked elsewhere.
431 fn update_mtime(build: &Build, path: &Path) {
432     let entries = match path.parent().unwrap().join("deps").read_dir() {
433         Ok(entries) => entries,
434         Err(_) => return,
435     };
436     let files = entries.map(|e| t!(e)).filter(|e| t!(e.file_type()).is_file());
437     let files = files.filter(|e| {
438         let filename = e.file_name();
439         let filename = filename.to_str().unwrap();
440         filename.ends_with(".rlib") ||
441             filename.ends_with(".lib") ||
442             is_dylib(&filename)
443     });
444     let max = files.max_by_key(|entry| {
445         let meta = t!(entry.metadata());
446         FileTime::from_last_modification_time(&meta)
447     });
448     let max = match max {
449         Some(max) => max,
450         None => return,
451     };
452
453     if mtime(&max.path()) > mtime(path) {
454         build.verbose(&format!("updating {:?} as {:?} changed", path, max.path()));
455         t!(File::create(path));
456     }
457 }