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