]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Auto merge of #42976 - ids1024:redoxfix, r=sfackler
[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::env;
20 use std::fs::{self, File};
21 use std::io::BufReader;
22 use std::io::prelude::*;
23 use std::path::{Path, PathBuf};
24 use std::process::{Command, Stdio};
25 use std::str;
26
27 use build_helper::{output, mtime, up_to_date};
28 use filetime::FileTime;
29 use rustc_serialize::json;
30
31 use channel::GitInfo;
32 use util::{exe, libdir, is_dylib, copy};
33 use {Build, Compiler, Mode};
34
35 /// Build the standard library.
36 ///
37 /// This will build the standard library for a particular stage of the build
38 /// using the `compiler` targeting the `target` architecture. The artifacts
39 /// created will also be linked into the sysroot directory.
40 pub fn std(build: &Build, target: &str, compiler: &Compiler) {
41     let libdir = build.sysroot_libdir(compiler, target);
42     t!(fs::create_dir_all(&libdir));
43
44     let _folder = build.fold_output(|| format!("stage{}-std", compiler.stage));
45     println!("Building stage{} std artifacts ({} -> {})", compiler.stage,
46              compiler.host, target);
47
48     let out_dir = build.cargo_out(compiler, Mode::Libstd, target);
49     build.clear_if_dirty(&out_dir, &build.compiler_path(compiler));
50     let mut cargo = build.cargo(compiler, Mode::Libstd, target, "build");
51     let mut features = build.std_features();
52
53     if let Ok(target) = env::var("MACOSX_STD_DEPLOYMENT_TARGET") {
54         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
55     }
56
57     // When doing a local rebuild we tell cargo that we're stage1 rather than
58     // stage0. This works fine if the local rust and being-built rust have the
59     // same view of what the default allocator is, but fails otherwise. Since
60     // we don't have a way to express an allocator preference yet, work
61     // around the issue in the case of a local rebuild with jemalloc disabled.
62     if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
63         features.push_str(" force_alloc_system");
64     }
65
66     if compiler.stage != 0 && build.config.sanitizers {
67         // This variable is used by the sanitizer runtime crates, e.g.
68         // rustc_lsan, to build the sanitizer runtime from C code
69         // When this variable is missing, those crates won't compile the C code,
70         // so we don't set this variable during stage0 where llvm-config is
71         // missing
72         // We also only build the runtimes when --enable-sanitizers (or its
73         // config.toml equivalent) is used
74         cargo.env("LLVM_CONFIG", build.llvm_config(target));
75     }
76     cargo.arg("--features").arg(features)
77          .arg("--manifest-path")
78          .arg(build.src.join("src/libstd/Cargo.toml"));
79
80     if let Some(target) = build.config.target_config.get(target) {
81         if let Some(ref jemalloc) = target.jemalloc {
82             cargo.env("JEMALLOC_OVERRIDE", jemalloc);
83         }
84     }
85     if target.contains("musl") {
86         if let Some(p) = build.musl_root(target) {
87             cargo.env("MUSL_ROOT", p);
88         }
89     }
90
91     run_cargo(build,
92               &mut cargo,
93               &libstd_stamp(build, &compiler, target));
94 }
95
96 /// Link all libstd rlibs/dylibs into the sysroot location.
97 ///
98 /// Links those artifacts generated by `compiler` to a the `stage` compiler's
99 /// sysroot for the specified `host` and `target`.
100 ///
101 /// Note that this assumes that `compiler` has already generated the libstd
102 /// libraries for `target`, and this method will find them in the relevant
103 /// output directory.
104 pub fn std_link(build: &Build,
105                 compiler: &Compiler,
106                 target_compiler: &Compiler,
107                 target: &str) {
108     println!("Copying stage{} std from stage{} ({} -> {} / {})",
109              target_compiler.stage,
110              compiler.stage,
111              compiler.host,
112              target_compiler.host,
113              target);
114     let libdir = build.sysroot_libdir(target_compiler, target);
115     add_to_sysroot(&libdir, &libstd_stamp(build, compiler, target));
116
117     if target.contains("musl") && !target.contains("mips") {
118         copy_musl_third_party_objects(build, target, &libdir);
119     }
120
121     if build.config.sanitizers && compiler.stage != 0 && target == "x86_64-apple-darwin" {
122         // The sanitizers are only built in stage1 or above, so the dylibs will
123         // be missing in stage0 and causes panic. See the `std()` function above
124         // for reason why the sanitizers are not built in stage0.
125         copy_apple_sanitizer_dylibs(&build.native_dir(target), "osx", &libdir);
126     }
127 }
128
129 /// Copies the crt(1,i,n).o startup objects
130 ///
131 /// Only required for musl targets that statically link to libc
132 fn copy_musl_third_party_objects(build: &Build, target: &str, into: &Path) {
133     for &obj in &["crt1.o", "crti.o", "crtn.o"] {
134         copy(&build.musl_root(target).unwrap().join("lib").join(obj), &into.join(obj));
135     }
136 }
137
138 fn copy_apple_sanitizer_dylibs(native_dir: &Path, platform: &str, into: &Path) {
139     for &sanitizer in &["asan", "tsan"] {
140         let filename = format!("libclang_rt.{}_{}_dynamic.dylib", sanitizer, platform);
141         let mut src_path = native_dir.join(sanitizer);
142         src_path.push("build");
143         src_path.push("lib");
144         src_path.push("darwin");
145         src_path.push(&filename);
146         copy(&src_path, &into.join(filename));
147     }
148 }
149
150 /// Build and prepare startup objects like rsbegin.o and rsend.o
151 ///
152 /// These are primarily used on Windows right now for linking executables/dlls.
153 /// They don't require any library support as they're just plain old object
154 /// files, so we just use the nightly snapshot compiler to always build them (as
155 /// no other compilers are guaranteed to be available).
156 pub fn build_startup_objects(build: &Build, for_compiler: &Compiler, target: &str) {
157     if !target.contains("pc-windows-gnu") {
158         return
159     }
160
161     let compiler = Compiler::new(0, &build.config.build);
162     let compiler_path = build.compiler_path(&compiler);
163     let src_dir = &build.src.join("src/rtstartup");
164     let dst_dir = &build.native_dir(target).join("rtstartup");
165     let sysroot_dir = &build.sysroot_libdir(for_compiler, target);
166     t!(fs::create_dir_all(dst_dir));
167     t!(fs::create_dir_all(sysroot_dir));
168
169     for file in &["rsbegin", "rsend"] {
170         let src_file = &src_dir.join(file.to_string() + ".rs");
171         let dst_file = &dst_dir.join(file.to_string() + ".o");
172         if !up_to_date(src_file, dst_file) {
173             let mut cmd = Command::new(&compiler_path);
174             build.run(cmd.env("RUSTC_BOOTSTRAP", "1")
175                         .arg("--cfg").arg(format!("stage{}", compiler.stage))
176                         .arg("--target").arg(target)
177                         .arg("--emit=obj")
178                         .arg("--out-dir").arg(dst_dir)
179                         .arg(src_file));
180         }
181
182         copy(dst_file, &sysroot_dir.join(file.to_string() + ".o"));
183     }
184
185     for obj in ["crt2.o", "dllcrt2.o"].iter() {
186         copy(&compiler_file(build.cc(target), obj), &sysroot_dir.join(obj));
187     }
188 }
189
190 /// Build libtest.
191 ///
192 /// This will build libtest and supporting libraries for a particular stage of
193 /// the build using the `compiler` targeting the `target` architecture. The
194 /// artifacts created will also be linked into the sysroot directory.
195 pub fn test(build: &Build, target: &str, compiler: &Compiler) {
196     let _folder = build.fold_output(|| format!("stage{}-test", compiler.stage));
197     println!("Building stage{} test artifacts ({} -> {})", compiler.stage,
198              compiler.host, target);
199     let out_dir = build.cargo_out(compiler, Mode::Libtest, target);
200     build.clear_if_dirty(&out_dir, &libstd_stamp(build, compiler, target));
201     let mut cargo = build.cargo(compiler, Mode::Libtest, target, "build");
202     if let Ok(target) = env::var("MACOSX_STD_DEPLOYMENT_TARGET") {
203         cargo.env("MACOSX_DEPLOYMENT_TARGET", target);
204     }
205     cargo.arg("--manifest-path")
206          .arg(build.src.join("src/libtest/Cargo.toml"));
207     run_cargo(build,
208               &mut cargo,
209               &libtest_stamp(build, compiler, target));
210 }
211
212 /// Same as `std_link`, only for libtest
213 pub fn test_link(build: &Build,
214                  compiler: &Compiler,
215                  target_compiler: &Compiler,
216                  target: &str) {
217     println!("Copying stage{} test from stage{} ({} -> {} / {})",
218              target_compiler.stage,
219              compiler.stage,
220              compiler.host,
221              target_compiler.host,
222              target);
223     add_to_sysroot(&build.sysroot_libdir(target_compiler, target),
224                    &libtest_stamp(build, compiler, target));
225 }
226
227 /// Build the compiler.
228 ///
229 /// This will build the compiler for a particular stage of the build using
230 /// the `compiler` targeting the `target` architecture. The artifacts
231 /// created will also be linked into the sysroot directory.
232 pub fn rustc(build: &Build, target: &str, compiler: &Compiler) {
233     let _folder = build.fold_output(|| format!("stage{}-rustc", compiler.stage));
234     println!("Building stage{} compiler artifacts ({} -> {})",
235              compiler.stage, compiler.host, target);
236
237     let out_dir = build.cargo_out(compiler, Mode::Librustc, target);
238     build.clear_if_dirty(&out_dir, &libtest_stamp(build, compiler, target));
239
240     let mut cargo = build.cargo(compiler, Mode::Librustc, target, "build");
241     cargo.arg("--features").arg(build.rustc_features())
242          .arg("--manifest-path")
243          .arg(build.src.join("src/rustc/Cargo.toml"));
244
245     // Set some configuration variables picked up by build scripts and
246     // the compiler alike
247     cargo.env("CFG_RELEASE", build.rust_release())
248          .env("CFG_RELEASE_CHANNEL", &build.config.channel)
249          .env("CFG_VERSION", build.rust_version())
250          .env("CFG_PREFIX", build.config.prefix.clone().unwrap_or(PathBuf::new()));
251
252     if compiler.stage == 0 {
253         cargo.env("CFG_LIBDIR_RELATIVE", "lib");
254     } else {
255         let libdir_relative = build.config.libdir_relative.clone().unwrap_or(PathBuf::from("lib"));
256         cargo.env("CFG_LIBDIR_RELATIVE", libdir_relative);
257     }
258
259     // If we're not building a compiler with debugging information then remove
260     // these two env vars which would be set otherwise.
261     if build.config.rust_debuginfo_only_std {
262         cargo.env_remove("RUSTC_DEBUGINFO");
263         cargo.env_remove("RUSTC_DEBUGINFO_LINES");
264     }
265
266     if let Some(ref ver_date) = build.rust_info.commit_date() {
267         cargo.env("CFG_VER_DATE", ver_date);
268     }
269     if let Some(ref ver_hash) = build.rust_info.sha() {
270         cargo.env("CFG_VER_HASH", ver_hash);
271     }
272     if !build.unstable_features() {
273         cargo.env("CFG_DISABLE_UNSTABLE_FEATURES", "1");
274     }
275     // Flag that rust llvm is in use
276     if build.is_rust_llvm(target) {
277         cargo.env("LLVM_RUSTLLVM", "1");
278     }
279     cargo.env("LLVM_CONFIG", build.llvm_config(target));
280     let target_config = build.config.target_config.get(target);
281     if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
282         cargo.env("CFG_LLVM_ROOT", s);
283     }
284     // Building with a static libstdc++ is only supported on linux right now,
285     // not for MSVC or macOS
286     if build.config.llvm_static_stdcpp &&
287        !target.contains("windows") &&
288        !target.contains("apple") {
289         cargo.env("LLVM_STATIC_STDCPP",
290                   compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
291     }
292     if build.config.llvm_link_shared {
293         cargo.env("LLVM_LINK_SHARED", "1");
294     }
295     if let Some(ref s) = build.config.rustc_default_linker {
296         cargo.env("CFG_DEFAULT_LINKER", s);
297     }
298     if let Some(ref s) = build.config.rustc_default_ar {
299         cargo.env("CFG_DEFAULT_AR", s);
300     }
301     run_cargo(build,
302               &mut cargo,
303               &librustc_stamp(build, compiler, target));
304 }
305
306 /// Same as `std_link`, only for librustc
307 pub fn rustc_link(build: &Build,
308                   compiler: &Compiler,
309                   target_compiler: &Compiler,
310                   target: &str) {
311     println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
312              target_compiler.stage,
313              compiler.stage,
314              compiler.host,
315              target_compiler.host,
316              target);
317     add_to_sysroot(&build.sysroot_libdir(target_compiler, target),
318                    &librustc_stamp(build, compiler, target));
319 }
320
321 /// Cargo's output path for the standard library in a given stage, compiled
322 /// by a particular compiler for the specified target.
323 fn libstd_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
324     build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
325 }
326
327 /// Cargo's output path for libtest in a given stage, compiled by a particular
328 /// compiler for the specified target.
329 fn libtest_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
330     build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
331 }
332
333 /// Cargo's output path for librustc in a given stage, compiled by a particular
334 /// compiler for the specified target.
335 fn librustc_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
336     build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
337 }
338
339 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
340     let out = output(Command::new(compiler)
341                             .arg(format!("-print-file-name={}", file)));
342     PathBuf::from(out.trim())
343 }
344
345 pub fn create_sysroot(build: &Build, compiler: &Compiler) {
346     let sysroot = build.sysroot(compiler);
347     let _ = fs::remove_dir_all(&sysroot);
348     t!(fs::create_dir_all(&sysroot));
349 }
350
351 /// Prepare a new compiler from the artifacts in `stage`
352 ///
353 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
354 /// must have been previously produced by the `stage - 1` build.config.build
355 /// compiler.
356 pub fn assemble_rustc(build: &Build, stage: u32, host: &str) {
357     // nothing to do in stage0
358     if stage == 0 {
359         return
360     }
361
362     println!("Copying stage{} compiler ({})", stage, host);
363
364     // The compiler that we're assembling
365     let target_compiler = Compiler::new(stage, host);
366
367     // The compiler that compiled the compiler we're assembling
368     let build_compiler = Compiler::new(stage - 1, &build.config.build);
369
370     // Link in all dylibs to the libdir
371     let sysroot = build.sysroot(&target_compiler);
372     let sysroot_libdir = sysroot.join(libdir(host));
373     t!(fs::create_dir_all(&sysroot_libdir));
374     let src_libdir = build.sysroot_libdir(&build_compiler, host);
375     for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
376         let filename = f.file_name().into_string().unwrap();
377         if is_dylib(&filename) {
378             copy(&f.path(), &sysroot_libdir.join(&filename));
379         }
380     }
381
382     let out_dir = build.cargo_out(&build_compiler, Mode::Librustc, host);
383
384     // Link the compiler binary itself into place
385     let rustc = out_dir.join(exe("rustc", host));
386     let bindir = sysroot.join("bin");
387     t!(fs::create_dir_all(&bindir));
388     let compiler = build.compiler_path(&Compiler::new(stage, host));
389     let _ = fs::remove_file(&compiler);
390     copy(&rustc, &compiler);
391
392     // See if rustdoc exists to link it into place
393     let rustdoc = exe("rustdoc", host);
394     let rustdoc_src = out_dir.join(&rustdoc);
395     let rustdoc_dst = bindir.join(&rustdoc);
396     if fs::metadata(&rustdoc_src).is_ok() {
397         let _ = fs::remove_file(&rustdoc_dst);
398         copy(&rustdoc_src, &rustdoc_dst);
399     }
400 }
401
402 /// Link some files into a rustc sysroot.
403 ///
404 /// For a particular stage this will link the file listed in `stamp` into the
405 /// `sysroot_dst` provided.
406 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
407     t!(fs::create_dir_all(&sysroot_dst));
408     let mut contents = Vec::new();
409     t!(t!(File::open(stamp)).read_to_end(&mut contents));
410     for part in contents.split(|b| *b == 0) {
411         if part.is_empty() {
412             continue
413         }
414         let path = Path::new(t!(str::from_utf8(part)));
415         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
416     }
417 }
418
419 /// Build a tool in `src/tools`
420 ///
421 /// This will build the specified tool with the specified `host` compiler in
422 /// `stage` into the normal cargo output directory.
423 pub fn maybe_clean_tools(build: &Build, stage: u32, target: &str, mode: Mode) {
424     let compiler = Compiler::new(stage, &build.config.build);
425
426     let stamp = match mode {
427         Mode::Libstd => libstd_stamp(build, &compiler, target),
428         Mode::Libtest => libtest_stamp(build, &compiler, target),
429         Mode::Librustc => librustc_stamp(build, &compiler, target),
430         _ => panic!(),
431     };
432     let out_dir = build.cargo_out(&compiler, Mode::Tool, target);
433     build.clear_if_dirty(&out_dir, &stamp);
434 }
435
436 /// Build a tool in `src/tools`
437 ///
438 /// This will build the specified tool with the specified `host` compiler in
439 /// `stage` into the normal cargo output directory.
440 pub fn tool(build: &Build, stage: u32, target: &str, tool: &str) {
441     let _folder = build.fold_output(|| format!("stage{}-{}", stage, tool));
442     println!("Building stage{} tool {} ({})", stage, tool, target);
443
444     let compiler = Compiler::new(stage, &build.config.build);
445
446     let mut cargo = build.cargo(&compiler, Mode::Tool, target, "build");
447     let dir = build.src.join("src/tools").join(tool);
448     cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
449
450     // We don't want to build tools dynamically as they'll be running across
451     // stages and such and it's just easier if they're not dynamically linked.
452     cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
453
454     if let Some(dir) = build.openssl_install_dir(target) {
455         cargo.env("OPENSSL_STATIC", "1");
456         cargo.env("OPENSSL_DIR", dir);
457         cargo.env("LIBZ_SYS_STATIC", "1");
458     }
459
460     cargo.env("CFG_RELEASE_CHANNEL", &build.config.channel);
461
462     let info = GitInfo::new(&dir);
463     if let Some(sha) = info.sha() {
464         cargo.env("CFG_COMMIT_HASH", sha);
465     }
466     if let Some(sha_short) = info.sha_short() {
467         cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
468     }
469     if let Some(date) = info.commit_date() {
470         cargo.env("CFG_COMMIT_DATE", date);
471     }
472
473     build.run(&mut cargo);
474 }
475
476
477 // Avoiding a dependency on winapi to keep compile times down
478 #[cfg(unix)]
479 fn stderr_isatty() -> bool {
480     use libc;
481     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
482 }
483 #[cfg(windows)]
484 fn stderr_isatty() -> bool {
485     type DWORD = u32;
486     type BOOL = i32;
487     type HANDLE = *mut u8;
488     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
489     extern "system" {
490         fn GetStdHandle(which: DWORD) -> HANDLE;
491         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
492     }
493     unsafe {
494         let handle = GetStdHandle(STD_ERROR_HANDLE);
495         let mut out = 0;
496         GetConsoleMode(handle, &mut out) != 0
497     }
498 }
499
500 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
501     // Instruct Cargo to give us json messages on stdout, critically leaving
502     // stderr as piped so we can get those pretty colors.
503     cargo.arg("--message-format").arg("json")
504          .stdout(Stdio::piped());
505
506     if stderr_isatty() {
507         // since we pass message-format=json to cargo, we need to tell the rustc
508         // wrapper to give us colored output if necessary. This is because we
509         // only want Cargo's JSON output, not rustcs.
510         cargo.env("RUSTC_COLOR", "1");
511     }
512
513     build.verbose(&format!("running: {:?}", cargo));
514     let mut child = match cargo.spawn() {
515         Ok(child) => child,
516         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
517     };
518
519     // `target_root_dir` looks like $dir/$target/release
520     let target_root_dir = stamp.parent().unwrap();
521     // `target_deps_dir` looks like $dir/$target/release/deps
522     let target_deps_dir = target_root_dir.join("deps");
523     // `host_root_dir` looks like $dir/release
524     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
525                                        .parent().unwrap() // chop off `$target`
526                                        .join(target_root_dir.file_name().unwrap());
527
528     // Spawn Cargo slurping up its JSON output. We'll start building up the
529     // `deps` array of all files it generated along with a `toplevel` array of
530     // files we need to probe for later.
531     let mut deps = Vec::new();
532     let mut toplevel = Vec::new();
533     let stdout = BufReader::new(child.stdout.take().unwrap());
534     for line in stdout.lines() {
535         let line = t!(line);
536         let json = if line.starts_with("{") {
537             t!(line.parse::<json::Json>())
538         } else {
539             // If this was informational, just print it out and continue
540             println!("{}", line);
541             continue
542         };
543         if json.find("reason").and_then(|j| j.as_string()) != Some("compiler-artifact") {
544             continue
545         }
546         for filename in json["filenames"].as_array().unwrap() {
547             let filename = filename.as_string().unwrap();
548             // Skip files like executables
549             if !filename.ends_with(".rlib") &&
550                !filename.ends_with(".lib") &&
551                !is_dylib(&filename) {
552                 continue
553             }
554
555             let filename = Path::new(filename);
556
557             // If this was an output file in the "host dir" we don't actually
558             // worry about it, it's not relevant for us.
559             if filename.starts_with(&host_root_dir) {
560                 continue
561
562             // If this was output in the `deps` dir then this is a precise file
563             // name (hash included) so we start tracking it.
564             } else if filename.starts_with(&target_deps_dir) {
565                 deps.push(filename.to_path_buf());
566
567             // Otherwise this was a "top level artifact" which right now doesn't
568             // have a hash in the name, but there's a version of this file in
569             // the `deps` folder which *does* have a hash in the name. That's
570             // the one we'll want to we'll probe for it later.
571             } else {
572                 toplevel.push((filename.file_stem().unwrap()
573                                        .to_str().unwrap().to_string(),
574                                filename.extension().unwrap().to_owned()
575                                        .to_str().unwrap().to_string()));
576             }
577         }
578     }
579
580     // Make sure Cargo actually succeeded after we read all of its stdout.
581     let status = t!(child.wait());
582     if !status.success() {
583         panic!("command did not execute successfully: {:?}\n\
584                 expected success, got: {}",
585                cargo,
586                status);
587     }
588
589     // Ok now we need to actually find all the files listed in `toplevel`. We've
590     // got a list of prefix/extensions and we basically just need to find the
591     // most recent file in the `deps` folder corresponding to each one.
592     let contents = t!(target_deps_dir.read_dir())
593         .map(|e| t!(e))
594         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
595         .collect::<Vec<_>>();
596     for (prefix, extension) in toplevel {
597         let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
598             filename.starts_with(&prefix[..]) &&
599                 filename[prefix.len()..].starts_with("-") &&
600                 filename.ends_with(&extension[..])
601         });
602         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
603             FileTime::from_last_modification_time(metadata)
604         });
605         let path_to_add = match max {
606             Some(triple) => triple.0.to_str().unwrap(),
607             None => panic!("no output generated for {:?} {:?}", prefix, extension),
608         };
609         if is_dylib(path_to_add) {
610             let candidate = format!("{}.lib", path_to_add);
611             let candidate = PathBuf::from(candidate);
612             if candidate.exists() {
613                 deps.push(candidate);
614             }
615         }
616         deps.push(path_to_add.into());
617     }
618
619     // Now we want to update the contents of the stamp file, if necessary. First
620     // we read off the previous contents along with its mtime. If our new
621     // contents (the list of files to copy) is different or if any dep's mtime
622     // is newer then we rewrite the stamp file.
623     deps.sort();
624     let mut stamp_contents = Vec::new();
625     if let Ok(mut f) = File::open(stamp) {
626         t!(f.read_to_end(&mut stamp_contents));
627     }
628     let stamp_mtime = mtime(&stamp);
629     let mut new_contents = Vec::new();
630     let mut max = None;
631     let mut max_path = None;
632     for dep in deps {
633         let mtime = mtime(&dep);
634         if Some(mtime) > max {
635             max = Some(mtime);
636             max_path = Some(dep.clone());
637         }
638         new_contents.extend(dep.to_str().unwrap().as_bytes());
639         new_contents.extend(b"\0");
640     }
641     let max = max.unwrap();
642     let max_path = max_path.unwrap();
643     if stamp_contents == new_contents && max <= stamp_mtime {
644         return
645     }
646     if max > stamp_mtime {
647         build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
648     } else {
649         build.verbose(&format!("updating {:?} as deps changed", stamp));
650     }
651     t!(t!(File::create(stamp)).write_all(&new_contents));
652 }