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