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