]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/compile.rs
Auto merge of #42899 - alexcrichton:compiler-builtins, r=nikomatsakis
[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 Some(target) = env::var_os("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.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 Some(target) = env::var_os("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_default());
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.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.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(&target_compiler);
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     // This is the method we use for extracting paths from the stamp file passed to us. See
411     // run_cargo for more information (in this file).
412     for part in contents.split(|b| *b == 0) {
413         if part.is_empty() {
414             continue
415         }
416         let path = Path::new(t!(str::from_utf8(part)));
417         copy(&path, &sysroot_dst.join(path.file_name().unwrap()));
418     }
419 }
420
421 /// Build a tool in `src/tools`
422 ///
423 /// This will build the specified tool with the specified `host` compiler in
424 /// `stage` into the normal cargo output directory.
425 pub fn maybe_clean_tools(build: &Build, stage: u32, target: &str, mode: Mode) {
426     let compiler = Compiler::new(stage, &build.build);
427
428     let stamp = match mode {
429         Mode::Libstd => libstd_stamp(build, &compiler, target),
430         Mode::Libtest => libtest_stamp(build, &compiler, target),
431         Mode::Librustc => librustc_stamp(build, &compiler, target),
432         _ => panic!(),
433     };
434     let out_dir = build.cargo_out(&compiler, Mode::Tool, target);
435     build.clear_if_dirty(&out_dir, &stamp);
436 }
437
438 /// Build a tool in `src/tools`
439 ///
440 /// This will build the specified tool with the specified `host` compiler in
441 /// `stage` into the normal cargo output directory.
442 pub fn tool(build: &Build, stage: u32, target: &str, tool: &str) {
443     let _folder = build.fold_output(|| format!("stage{}-{}", stage, tool));
444     println!("Building stage{} tool {} ({})", stage, tool, target);
445
446     let compiler = Compiler::new(stage, &build.build);
447
448     let mut cargo = build.cargo(&compiler, Mode::Tool, target, "build");
449     let dir = build.src.join("src/tools").join(tool);
450     cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));
451
452     // We don't want to build tools dynamically as they'll be running across
453     // stages and such and it's just easier if they're not dynamically linked.
454     cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
455
456     if let Some(dir) = build.openssl_install_dir(target) {
457         cargo.env("OPENSSL_STATIC", "1");
458         cargo.env("OPENSSL_DIR", dir);
459         cargo.env("LIBZ_SYS_STATIC", "1");
460     }
461
462     cargo.env("CFG_RELEASE_CHANNEL", &build.config.channel);
463
464     let info = GitInfo::new(&dir);
465     if let Some(sha) = info.sha() {
466         cargo.env("CFG_COMMIT_HASH", sha);
467     }
468     if let Some(sha_short) = info.sha_short() {
469         cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
470     }
471     if let Some(date) = info.commit_date() {
472         cargo.env("CFG_COMMIT_DATE", date);
473     }
474
475     build.run(&mut cargo);
476 }
477
478
479 // Avoiding a dependency on winapi to keep compile times down
480 #[cfg(unix)]
481 fn stderr_isatty() -> bool {
482     use libc;
483     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
484 }
485 #[cfg(windows)]
486 fn stderr_isatty() -> bool {
487     type DWORD = u32;
488     type BOOL = i32;
489     type HANDLE = *mut u8;
490     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
491     extern "system" {
492         fn GetStdHandle(which: DWORD) -> HANDLE;
493         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
494     }
495     unsafe {
496         let handle = GetStdHandle(STD_ERROR_HANDLE);
497         let mut out = 0;
498         GetConsoleMode(handle, &mut out) != 0
499     }
500 }
501
502 fn run_cargo(build: &Build, cargo: &mut Command, stamp: &Path) {
503     // Instruct Cargo to give us json messages on stdout, critically leaving
504     // stderr as piped so we can get those pretty colors.
505     cargo.arg("--message-format").arg("json")
506          .stdout(Stdio::piped());
507
508     if stderr_isatty() {
509         // since we pass message-format=json to cargo, we need to tell the rustc
510         // wrapper to give us colored output if necessary. This is because we
511         // only want Cargo's JSON output, not rustcs.
512         cargo.env("RUSTC_COLOR", "1");
513     }
514
515     build.verbose(&format!("running: {:?}", cargo));
516     let mut child = match cargo.spawn() {
517         Ok(child) => child,
518         Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e),
519     };
520
521     // `target_root_dir` looks like $dir/$target/release
522     let target_root_dir = stamp.parent().unwrap();
523     // `target_deps_dir` looks like $dir/$target/release/deps
524     let target_deps_dir = target_root_dir.join("deps");
525     // `host_root_dir` looks like $dir/release
526     let host_root_dir = target_root_dir.parent().unwrap() // chop off `release`
527                                        .parent().unwrap() // chop off `$target`
528                                        .join(target_root_dir.file_name().unwrap());
529
530     // Spawn Cargo slurping up its JSON output. We'll start building up the
531     // `deps` array of all files it generated along with a `toplevel` array of
532     // files we need to probe for later.
533     let mut deps = Vec::new();
534     let mut toplevel = Vec::new();
535     let stdout = BufReader::new(child.stdout.take().unwrap());
536     for line in stdout.lines() {
537         let line = t!(line);
538         let json = if line.starts_with("{") {
539             t!(line.parse::<json::Json>())
540         } else {
541             // If this was informational, just print it out and continue
542             println!("{}", line);
543             continue
544         };
545         if json.find("reason").and_then(|j| j.as_string()) != Some("compiler-artifact") {
546             continue
547         }
548         for filename in json["filenames"].as_array().unwrap() {
549             let filename = filename.as_string().unwrap();
550             // Skip files like executables
551             if !filename.ends_with(".rlib") &&
552                !filename.ends_with(".lib") &&
553                !is_dylib(&filename) {
554                 continue
555             }
556
557             let filename = Path::new(filename);
558
559             // If this was an output file in the "host dir" we don't actually
560             // worry about it, it's not relevant for us.
561             if filename.starts_with(&host_root_dir) {
562                 continue;
563             }
564
565             // If this was output in the `deps` dir then this is a precise file
566             // name (hash included) so we start tracking it.
567             if filename.starts_with(&target_deps_dir) {
568                 deps.push(filename.to_path_buf());
569                 continue;
570             }
571
572             // Otherwise this was a "top level artifact" which right now doesn't
573             // have a hash in the name, but there's a version of this file in
574             // the `deps` folder which *does* have a hash in the name. That's
575             // the one we'll want to we'll probe for it later.
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     // Make sure Cargo actually succeeded after we read all of its stdout.
584     let status = t!(child.wait());
585     if !status.success() {
586         panic!("command did not execute successfully: {:?}\n\
587                 expected success, got: {}",
588                cargo,
589                status);
590     }
591
592     // Ok now we need to actually find all the files listed in `toplevel`. We've
593     // got a list of prefix/extensions and we basically just need to find the
594     // most recent file in the `deps` folder corresponding to each one.
595     let contents = t!(target_deps_dir.read_dir())
596         .map(|e| t!(e))
597         .map(|e| (e.path(), e.file_name().into_string().unwrap(), t!(e.metadata())))
598         .collect::<Vec<_>>();
599     for (prefix, extension) in toplevel {
600         let candidates = contents.iter().filter(|&&(_, ref filename, _)| {
601             filename.starts_with(&prefix[..]) &&
602                 filename[prefix.len()..].starts_with("-") &&
603                 filename.ends_with(&extension[..])
604         });
605         let max = candidates.max_by_key(|&&(_, _, ref metadata)| {
606             FileTime::from_last_modification_time(metadata)
607         });
608         let path_to_add = match max {
609             Some(triple) => triple.0.to_str().unwrap(),
610             None => panic!("no output generated for {:?} {:?}", prefix, extension),
611         };
612         if is_dylib(path_to_add) {
613             let candidate = format!("{}.lib", path_to_add);
614             let candidate = PathBuf::from(candidate);
615             if candidate.exists() {
616                 deps.push(candidate);
617             }
618         }
619         deps.push(path_to_add.into());
620     }
621
622     // Now we want to update the contents of the stamp file, if necessary. First
623     // we read off the previous contents along with its mtime. If our new
624     // contents (the list of files to copy) is different or if any dep's mtime
625     // is newer then we rewrite the stamp file.
626     deps.sort();
627     let mut stamp_contents = Vec::new();
628     if let Ok(mut f) = File::open(stamp) {
629         t!(f.read_to_end(&mut stamp_contents));
630     }
631     let stamp_mtime = mtime(&stamp);
632     let mut new_contents = Vec::new();
633     let mut max = None;
634     let mut max_path = None;
635     for dep in deps {
636         let mtime = mtime(&dep);
637         if Some(mtime) > max {
638             max = Some(mtime);
639             max_path = Some(dep.clone());
640         }
641         new_contents.extend(dep.to_str().unwrap().as_bytes());
642         new_contents.extend(b"\0");
643     }
644     let max = max.unwrap();
645     let max_path = max_path.unwrap();
646     if stamp_contents == new_contents && max <= stamp_mtime {
647         return
648     }
649     if max > stamp_mtime {
650         build.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
651     } else {
652         build.verbose(&format!("updating {:?} as deps changed", stamp));
653     }
654     t!(t!(File::create(stamp)).write_all(&new_contents));
655 }