]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Rollup merge of #42831 - rthomas:master, r=QuietMisdreavus
[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     if let Some(ref cfg_file) = build.flags.config {
280         let cfg_path = t!(PathBuf::from(cfg_file).canonicalize());
281         cargo.env("CFG_LLVM_TOML", cfg_path.into_os_string());
282     }
283     cargo.env("LLVM_CONFIG", build.llvm_config(target));
284     let target_config = build.config.target_config.get(target);
285     if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
286         cargo.env("CFG_LLVM_ROOT", s);
287     }
288     // Building with a static libstdc++ is only supported on linux right now,
289     // not for MSVC or macOS
290     if build.config.llvm_static_stdcpp &&
291        !target.contains("windows") &&
292        !target.contains("apple") {
293         cargo.env("LLVM_STATIC_STDCPP",
294                   compiler_file(build.cxx(target).unwrap(), "libstdc++.a"));
295     }
296     if build.config.llvm_link_shared {
297         cargo.env("LLVM_LINK_SHARED", "1");
298     }
299     if let Some(ref s) = build.config.rustc_default_linker {
300         cargo.env("CFG_DEFAULT_LINKER", s);
301     }
302     if let Some(ref s) = build.config.rustc_default_ar {
303         cargo.env("CFG_DEFAULT_AR", s);
304     }
305     run_cargo(build,
306               &mut cargo,
307               &librustc_stamp(build, compiler, target));
308 }
309
310 /// Same as `std_link`, only for librustc
311 pub fn rustc_link(build: &Build,
312                   compiler: &Compiler,
313                   target_compiler: &Compiler,
314                   target: &str) {
315     println!("Copying stage{} rustc from stage{} ({} -> {} / {})",
316              target_compiler.stage,
317              compiler.stage,
318              compiler.host,
319              target_compiler.host,
320              target);
321     add_to_sysroot(&build.sysroot_libdir(target_compiler, target),
322                    &librustc_stamp(build, compiler, target));
323 }
324
325 /// Cargo's output path for the standard library in a given stage, compiled
326 /// by a particular compiler for the specified target.
327 fn libstd_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
328     build.cargo_out(compiler, Mode::Libstd, target).join(".libstd.stamp")
329 }
330
331 /// Cargo's output path for libtest in a given stage, compiled by a particular
332 /// compiler for the specified target.
333 fn libtest_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
334     build.cargo_out(compiler, Mode::Libtest, target).join(".libtest.stamp")
335 }
336
337 /// Cargo's output path for librustc in a given stage, compiled by a particular
338 /// compiler for the specified target.
339 fn librustc_stamp(build: &Build, compiler: &Compiler, target: &str) -> PathBuf {
340     build.cargo_out(compiler, Mode::Librustc, target).join(".librustc.stamp")
341 }
342
343 fn compiler_file(compiler: &Path, file: &str) -> PathBuf {
344     let out = output(Command::new(compiler)
345                             .arg(format!("-print-file-name={}", file)));
346     PathBuf::from(out.trim())
347 }
348
349 pub fn create_sysroot(build: &Build, compiler: &Compiler) {
350     let sysroot = build.sysroot(compiler);
351     let _ = fs::remove_dir_all(&sysroot);
352     t!(fs::create_dir_all(&sysroot));
353 }
354
355 /// Prepare a new compiler from the artifacts in `stage`
356 ///
357 /// This will assemble a compiler in `build/$host/stage$stage`. The compiler
358 /// must have been previously produced by the `stage - 1` build.config.build
359 /// compiler.
360 pub fn assemble_rustc(build: &Build, stage: u32, host: &str) {
361     // nothing to do in stage0
362     if stage == 0 {
363         return
364     }
365
366     println!("Copying stage{} compiler ({})", stage, host);
367
368     // The compiler that we're assembling
369     let target_compiler = Compiler::new(stage, host);
370
371     // The compiler that compiled the compiler we're assembling
372     let build_compiler = Compiler::new(stage - 1, &build.config.build);
373
374     // Link in all dylibs to the libdir
375     let sysroot = build.sysroot(&target_compiler);
376     let sysroot_libdir = sysroot.join(libdir(host));
377     t!(fs::create_dir_all(&sysroot_libdir));
378     let src_libdir = build.sysroot_libdir(&build_compiler, host);
379     for f in t!(fs::read_dir(&src_libdir)).map(|f| t!(f)) {
380         let filename = f.file_name().into_string().unwrap();
381         if is_dylib(&filename) {
382             copy(&f.path(), &sysroot_libdir.join(&filename));
383         }
384     }
385
386     let out_dir = build.cargo_out(&build_compiler, Mode::Librustc, host);
387
388     // Link the compiler binary itself into place
389     let rustc = out_dir.join(exe("rustc", host));
390     let bindir = sysroot.join("bin");
391     t!(fs::create_dir_all(&bindir));
392     let compiler = build.compiler_path(&Compiler::new(stage, host));
393     let _ = fs::remove_file(&compiler);
394     copy(&rustc, &compiler);
395
396     // See if rustdoc exists to link it into place
397     let rustdoc = exe("rustdoc", host);
398     let rustdoc_src = out_dir.join(&rustdoc);
399     let rustdoc_dst = bindir.join(&rustdoc);
400     if fs::metadata(&rustdoc_src).is_ok() {
401         let _ = fs::remove_file(&rustdoc_dst);
402         copy(&rustdoc_src, &rustdoc_dst);
403     }
404 }
405
406 /// Link some files into a rustc sysroot.
407 ///
408 /// For a particular stage this will link the file listed in `stamp` into the
409 /// `sysroot_dst` provided.
410 fn add_to_sysroot(sysroot_dst: &Path, stamp: &Path) {
411     t!(fs::create_dir_all(&sysroot_dst));
412     let mut contents = Vec::new();
413     t!(t!(File::open(stamp)).read_to_end(&mut contents));
414     for part in contents.split(|b| *b == 0) {
415         if part.is_empty() {
416             continue
417         }
418         let path = Path::new(t!(str::from_utf8(part)));
419         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
420     }
421 }
422
423 /// Build a tool in `src/tools`
424 ///
425 /// This will build the specified tool with the specified `host` compiler in
426 /// `stage` into the normal cargo output directory.
427 pub fn maybe_clean_tools(build: &Build, stage: u32, target: &str, mode: Mode) {
428     let compiler = Compiler::new(stage, &build.config.build);
429
430     let stamp = match mode {
431         Mode::Libstd => libstd_stamp(build, &compiler, target),
432         Mode::Libtest => libtest_stamp(build, &compiler, target),
433         Mode::Librustc => librustc_stamp(build, &compiler, target),
434         _ => panic!(),
435     };
436     let out_dir = build.cargo_out(&compiler, Mode::Tool, target);
437     build.clear_if_dirty(&out_dir, &stamp);
438 }
439
440 /// Build a tool in `src/tools`
441 ///
442 /// This will build the specified tool with the specified `host` compiler in
443 /// `stage` into the normal cargo output directory.
444 pub fn tool(build: &Build, stage: u32, target: &str, tool: &str) {
445     let _folder = build.fold_output(|| format!("stage{}-{}", stage, tool));
446     println!("Building stage{} tool {} ({})", stage, tool, target);
447
448     let compiler = Compiler::new(stage, &build.config.build);
449
450     let mut cargo = build.cargo(&compiler, Mode::Tool, target, "build");
451     let dir = build.src.join("src/tools").join(tool);
452     cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
453
454     // We don't want to build tools dynamically as they'll be running across
455     // stages and such and it's just easier if they're not dynamically linked.
456     cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
457
458     if let Some(dir) = build.openssl_install_dir(target) {
459         cargo.env("OPENSSL_STATIC", "1");
460         cargo.env("OPENSSL_DIR", dir);
461         cargo.env("LIBZ_SYS_STATIC", "1");
462     }
463
464     cargo.env("CFG_RELEASE_CHANNEL", &build.config.channel);
465
466     let info = GitInfo::new(&dir);
467     if let Some(sha) = info.sha() {
468         cargo.env("CFG_COMMIT_HASH", sha);
469     }
470     if let Some(sha_short) = info.sha_short() {
471         cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
472     }
473     if let Some(date) = info.commit_date() {
474         cargo.env("CFG_COMMIT_DATE", date);
475     }
476
477     build.run(&mut cargo);
478 }
479
480
481 // Avoiding a dependency on winapi to keep compile times down
482 #[cfg(unix)]
483 fn stderr_isatty() -> bool {
484     use libc;
485     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
486 }
487 #[cfg(windows)]
488 fn stderr_isatty() -> bool {
489     type DWORD = u32;
490     type BOOL = i32;
491     type HANDLE = *mut u8;
492     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
493     extern "system" {
494         fn GetStdHandle(which: DWORD) -> HANDLE;
495         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
496     }
497     unsafe {
498         let handle = GetStdHandle(STD_ERROR_HANDLE);
499         let mut out = 0;
500         GetConsoleMode(handle, &mut out) != 0
501     }
502 }
503
504 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
505     // Instruct Cargo to give us json messages on stdout, critically leaving
506     // stderr as piped so we can get those pretty colors.
507     cargo.arg("--message-format").arg("json")
508          .stdout(Stdio::piped());
509
510     if stderr_isatty() {
511         // since we pass message-format=json to cargo, we need to tell the rustc
512         // wrapper to give us colored output if necessary. This is because we
513         // only want Cargo's JSON output, not rustcs.
514         cargo.env("RUSTC_COLOR", "1");
515     }
516
517     build.verbose(&format!("running: {:?}", cargo));
518     let mut child = match cargo.spawn() {
519         Ok(child) => child,
520         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
521     };
522
523     // `target_root_dir` looks like $dir/$target/release
524     let target_root_dir = stamp.parent().unwrap();
525     // `target_deps_dir` looks like $dir/$target/release/deps
526     let target_deps_dir = target_root_dir.join("deps");
527     // `host_root_dir` looks like $dir/release
528     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
529                                        .parent().unwrap() // chop off `$target`
530                                        .join(target_root_dir.file_name().unwrap());
531
532     // Spawn Cargo slurping up its JSON output. We'll start building up the
533     // `deps` array of all files it generated along with a `toplevel` array of
534     // files we need to probe for later.
535     let mut deps = Vec::new();
536     let mut toplevel = Vec::new();
537     let stdout = BufReader::new(child.stdout.take().unwrap());
538     for line in stdout.lines() {
539         let line = t!(line);
540         let json = if line.starts_with("{") {
541             t!(line.parse::<json::Json>())
542         } else {
543             // If this was informational, just print it out and continue
544             println!("{}", line);
545             continue
546         };
547         if json.find("reason").and_then(|j| j.as_string()) != Some("compiler-artifact") {
548             continue
549         }
550         for filename in json["filenames"].as_array().unwrap() {
551             let filename = filename.as_string().unwrap();
552             // Skip files like executables
553             if !filename.ends_with(".rlib") &&
554                !filename.ends_with(".lib") &&
555                !is_dylib(&filename) {
556                 continue
557             }
558
559             let filename = Path::new(filename);
560
561             // If this was an output file in the "host dir" we don't actually
562             // worry about it, it's not relevant for us.
563             if filename.starts_with(&host_root_dir) {
564                 continue
565
566             // If this was output in the `deps` dir then this is a precise file
567             // name (hash included) so we start tracking it.
568             } else if filename.starts_with(&target_deps_dir) {
569                 deps.push(filename.to_path_buf());
570
571             // Otherwise this was a "top level artifact" which right now doesn't
572             // have a hash in the name, but there's a version of this file in
573             // the `deps` folder which *does* have a hash in the name. That's
574             // the one we'll want to we'll probe for it later.
575             } else {
576                 toplevel.push((filename.file_stem().unwrap()
577                                        .to_str().unwrap().to_string(),
578                                filename.extension().unwrap().to_owned()
579                                        .to_str().unwrap().to_string()));
580             }
581         }
582     }
583
584     // Make sure Cargo actually succeeded after we read all of its stdout.
585     let status = t!(child.wait());
586     if !status.success() {
587         panic!("command did not execute successfully: {:?}\n\
588                 expected success, got: {}",
589                cargo,
590                status);
591     }
592
593     // Ok now we need to actually find all the files listed in `toplevel`. We've
594     // got a list of prefix/extensions and we basically just need to find the
595     // most recent file in the `deps` folder corresponding to each one.
596     let contents = t!(target_deps_dir.read_dir())
597         .map(|e| t!(e))
598         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
599         .collect::<Vec<_>>();
600     for (prefix, extension) in toplevel {
601         let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
602             filename.starts_with(&prefix[..]) &&
603                 filename[prefix.len()..].starts_with("-") &&
604                 filename.ends_with(&extension[..])
605         });
606         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
607             FileTime::from_last_modification_time(metadata)
608         });
609         let path_to_add = match max {
610             Some(triple) => triple.0.to_str().unwrap(),
611             None => panic!("no output generated for {:?} {:?}", prefix, extension),
612         };
613         if is_dylib(path_to_add) {
614             let candidate = format!("{}.lib", path_to_add);
615             let candidate = PathBuf::from(candidate);
616             if candidate.exists() {
617                 deps.push(candidate);
618             }
619         }
620         deps.push(path_to_add.into());
621     }
622
623     // Now we want to update the contents of the stamp file, if necessary. First
624     // we read off the previous contents along with its mtime. If our new
625     // contents (the list of files to copy) is different or if any dep's mtime
626     // is newer then we rewrite the stamp file.
627     deps.sort();
628     let mut stamp_contents = Vec::new();
629     if let Ok(mut f) = File::open(stamp) {
630         t!(f.read_to_end(&mut stamp_contents));
631     }
632     let stamp_mtime = mtime(&stamp);
633     let mut new_contents = Vec::new();
634     let mut max = None;
635     let mut max_path = None;
636     for dep in deps {
637         let mtime = mtime(&dep);
638         if Some(mtime) > max {
639             max = Some(mtime);
640             max_path = Some(dep.clone());
641         }
642         new_contents.extend(dep.to_str().unwrap().as_bytes());
643         new_contents.extend(b"\0");
644     }
645     let max = max.unwrap();
646     let max_path = max_path.unwrap();
647     if stamp_contents == new_contents && max <= stamp_mtime {
648         return
649     }
650     if max > stamp_mtime {
651         build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
652     } else {
653         build.verbose(&format!("updating {:?} as deps changed", stamp));
654     }
655     t!(t!(File::create(stamp)).write_all(&new_contents));
656 }