]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/link.rs
remove implementation detail from doc
[rust.git] / src / librustc_trans / back / link.rs
1 // Copyright 2012-2014 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 use super::archive::{ArchiveBuilder, ArchiveConfig};
12 use super::bytecode::RLIB_BYTECODE_EXTENSION;
13 use super::linker::Linker;
14 use super::command::Command;
15 use super::rpath::RPathConfig;
16 use super::rpath;
17 use metadata::METADATA_FILENAME;
18 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType, PrintRequest};
19 use rustc::session::config::RUST_CGU_EXT;
20 use rustc::session::filesearch;
21 use rustc::session::search_paths::PathKind;
22 use rustc::session::Session;
23 use rustc::middle::cstore::{NativeLibrary, LibSource, NativeLibraryKind};
24 use rustc::middle::dependency_format::Linkage;
25 use {CrateTranslation, CrateInfo};
26 use rustc::util::common::time;
27 use rustc::util::fs::fix_windows_verbatim_for_gcc;
28 use rustc::hir::def_id::CrateNum;
29 use tempdir::TempDir;
30 use rustc_back::{PanicStrategy, RelroLevel, LinkerFlavor};
31 use context::get_reloc_model;
32 use llvm;
33
34 use std::ascii;
35 use std::char;
36 use std::env;
37 use std::ffi::OsString;
38 use std::fmt;
39 use std::fs::{self, File};
40 use std::io::{self, Write, BufWriter};
41 use std::path::{Path, PathBuf};
42 use std::process::{Output, Stdio};
43 use std::str;
44 use syntax::attr;
45
46 /// The LLVM module name containing crate-metadata. This includes a `.` on
47 /// purpose, so it cannot clash with the name of a user-defined module.
48 pub const METADATA_MODULE_NAME: &'static str = "crate.metadata";
49
50 // same as for metadata above, but for allocator shim
51 pub const ALLOCATOR_MODULE_NAME: &'static str = "crate.allocator";
52
53 pub use rustc_trans_utils::link::{find_crate_name, filename_for_input, default_output_for_target,
54                                   invalid_output_for_target, build_link_meta, out_filename,
55                                   check_file_is_writeable};
56
57 // The third parameter is for env vars, used on windows to set up the
58 // path for MSVC to find its DLLs, and gcc to find its bundled
59 // toolchain
60 pub fn get_linker(sess: &Session) -> (PathBuf, Command, Vec<(OsString, OsString)>) {
61     let envs = vec![("PATH".into(), command_path(sess))];
62
63     // If our linker looks like a batch script on Windows then to execute this
64     // we'll need to spawn `cmd` explicitly. This is primarily done to handle
65     // emscripten where the linker is `emcc.bat` and needs to be spawned as
66     // `cmd /c emcc.bat ...`.
67     //
68     // This worked historically but is needed manually since #42436 (regression
69     // was tagged as #42791) and some more info can be found on #44443 for
70     // emscripten itself.
71     let cmd = |linker: &Path| {
72         if cfg!(windows) && linker.ends_with(".bat") {
73             let mut cmd = Command::new("cmd");
74             cmd.arg("/c").arg(linker);
75             cmd
76         } else {
77             Command::new(linker)
78         }
79     };
80
81     if let Some(ref linker) = sess.opts.cg.linker {
82         (linker.clone(), cmd(linker), envs)
83     } else if sess.target.target.options.is_like_msvc {
84         let (cmd, envs) = msvc_link_exe_cmd(sess);
85         (PathBuf::from("link.exe"), cmd, envs)
86     } else {
87         let linker = PathBuf::from(&sess.target.target.options.linker);
88         let cmd = cmd(&linker);
89         (linker, cmd, envs)
90     }
91 }
92
93 #[cfg(windows)]
94 pub fn msvc_link_exe_cmd(sess: &Session) -> (Command, Vec<(OsString, OsString)>) {
95     use cc::windows_registry;
96
97     let target = &sess.opts.target_triple;
98     let tool = windows_registry::find_tool(target, "link.exe");
99
100     if let Some(tool) = tool {
101         let mut cmd = Command::new(tool.path());
102         cmd.args(tool.args());
103         for &(ref k, ref v) in tool.env() {
104             cmd.env(k, v);
105         }
106         let envs = tool.env().to_vec();
107         (cmd, envs)
108     } else {
109         debug!("Failed to locate linker.");
110         (Command::new("link.exe"), vec![])
111     }
112 }
113
114 #[cfg(not(windows))]
115 pub fn msvc_link_exe_cmd(_sess: &Session) -> (Command, Vec<(OsString, OsString)>) {
116     (Command::new("link.exe"), vec![])
117 }
118
119 fn command_path(sess: &Session) -> OsString {
120     // The compiler's sysroot often has some bundled tools, so add it to the
121     // PATH for the child.
122     let mut new_path = sess.host_filesearch(PathKind::All)
123                            .get_tools_search_paths();
124     if let Some(path) = env::var_os("PATH") {
125         new_path.extend(env::split_paths(&path));
126     }
127     env::join_paths(new_path).unwrap()
128 }
129
130 pub fn remove(sess: &Session, path: &Path) {
131     match fs::remove_file(path) {
132         Ok(..) => {}
133         Err(e) => {
134             sess.err(&format!("failed to remove {}: {}",
135                              path.display(),
136                              e));
137         }
138     }
139 }
140
141 /// Perform the linkage portion of the compilation phase. This will generate all
142 /// of the requested outputs for this compilation session.
143 pub fn link_binary(sess: &Session,
144                    trans: &CrateTranslation,
145                    outputs: &OutputFilenames,
146                    crate_name: &str) -> Vec<PathBuf> {
147     let mut out_filenames = Vec::new();
148     for &crate_type in sess.crate_types.borrow().iter() {
149         // Ignore executable crates if we have -Z no-trans, as they will error.
150         if (sess.opts.debugging_opts.no_trans ||
151             !sess.opts.output_types.should_trans()) &&
152            crate_type == config::CrateTypeExecutable {
153             continue;
154         }
155
156         if invalid_output_for_target(sess, crate_type) {
157            bug!("invalid output type `{:?}` for target os `{}`",
158                 crate_type, sess.opts.target_triple);
159         }
160         let mut out_files = link_binary_output(sess,
161                                                trans,
162                                                crate_type,
163                                                outputs,
164                                                crate_name);
165         out_filenames.append(&mut out_files);
166     }
167
168     // Remove the temporary object file and metadata if we aren't saving temps
169     if !sess.opts.cg.save_temps {
170         if sess.opts.output_types.should_trans() {
171             for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
172                 remove(sess, obj);
173             }
174         }
175         for obj in trans.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
176             remove(sess, obj);
177         }
178         if let Some(ref obj) = trans.metadata_module.object {
179             remove(sess, obj);
180         }
181         if let Some(ref allocator) = trans.allocator_module {
182             if let Some(ref obj) = allocator.object {
183                 remove(sess, obj);
184             }
185             if let Some(ref bc) = allocator.bytecode_compressed {
186                 remove(sess, bc);
187             }
188         }
189     }
190
191     out_filenames
192 }
193
194 fn filename_for_metadata(sess: &Session, crate_name: &str, outputs: &OutputFilenames) -> PathBuf {
195     let out_filename = outputs.single_output_file.clone()
196         .unwrap_or(outputs
197             .out_directory
198             .join(&format!("lib{}{}.rmeta", crate_name, sess.opts.cg.extra_filename)));
199     check_file_is_writeable(&out_filename, sess);
200     out_filename
201 }
202
203 pub fn each_linked_rlib(sess: &Session,
204                         info: &CrateInfo,
205                         f: &mut FnMut(CrateNum, &Path)) -> Result<(), String> {
206     let crates = info.used_crates_static.iter();
207     let fmts = sess.dependency_formats.borrow();
208     let fmts = fmts.get(&config::CrateTypeExecutable)
209                    .or_else(|| fmts.get(&config::CrateTypeStaticlib))
210                    .or_else(|| fmts.get(&config::CrateTypeCdylib))
211                    .or_else(|| fmts.get(&config::CrateTypeProcMacro));
212     let fmts = match fmts {
213         Some(f) => f,
214         None => return Err(format!("could not find formats for rlibs"))
215     };
216     for &(cnum, ref path) in crates {
217         match fmts.get(cnum.as_usize() - 1) {
218             Some(&Linkage::NotLinked) |
219             Some(&Linkage::IncludedFromDylib) => continue,
220             Some(_) => {}
221             None => return Err(format!("could not find formats for rlibs"))
222         }
223         let name = &info.crate_name[&cnum];
224         let path = match *path {
225             LibSource::Some(ref p) => p,
226             LibSource::MetadataOnly => {
227                 return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
228                                    name))
229             }
230             LibSource::None => {
231                 return Err(format!("could not find rlib for: `{}`", name))
232             }
233         };
234         f(cnum, &path);
235     }
236     Ok(())
237 }
238
239 /// Returns a boolean indicating whether the specified crate should be ignored
240 /// during LTO.
241 ///
242 /// Crates ignored during LTO are not lumped together in the "massive object
243 /// file" that we create and are linked in their normal rlib states. See
244 /// comments below for what crates do not participate in LTO.
245 ///
246 /// It's unusual for a crate to not participate in LTO. Typically only
247 /// compiler-specific and unstable crates have a reason to not participate in
248 /// LTO.
249 pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
250     // If our target enables builtin function lowering in LLVM then the
251     // crates providing these functions don't participate in LTO (e.g.
252     // no_builtins or compiler builtins crates).
253     !sess.target.target.options.no_builtins &&
254         (info.is_no_builtins.contains(&cnum) || info.compiler_builtins == Some(cnum))
255 }
256
257 fn link_binary_output(sess: &Session,
258                       trans: &CrateTranslation,
259                       crate_type: config::CrateType,
260                       outputs: &OutputFilenames,
261                       crate_name: &str) -> Vec<PathBuf> {
262     for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
263         check_file_is_writeable(obj, sess);
264     }
265
266     let mut out_filenames = vec![];
267
268     if outputs.outputs.contains_key(&OutputType::Metadata) {
269         let out_filename = filename_for_metadata(sess, crate_name, outputs);
270         // To avoid races with another rustc process scanning the output directory,
271         // we need to write the file somewhere else and atomically move it to its
272         // final destination, with a `fs::rename` call. In order for the rename to
273         // always succeed, the temporary file needs to be on the same filesystem,
274         // which is why we create it inside the output directory specifically.
275         let metadata_tmpdir = match TempDir::new_in(out_filename.parent().unwrap(), "rmeta") {
276             Ok(tmpdir) => tmpdir,
277             Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
278         };
279         let metadata = emit_metadata(sess, trans, &metadata_tmpdir);
280         if let Err(e) = fs::rename(metadata, &out_filename) {
281             sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
282         }
283         out_filenames.push(out_filename);
284     }
285
286     let tmpdir = match TempDir::new("rustc") {
287         Ok(tmpdir) => tmpdir,
288         Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
289     };
290
291     if outputs.outputs.should_trans() {
292         let out_filename = out_filename(sess, crate_type, outputs, crate_name);
293         match crate_type {
294             config::CrateTypeRlib => {
295                 link_rlib(sess,
296                           trans,
297                           RlibFlavor::Normal,
298                           &out_filename,
299                           &tmpdir).build();
300             }
301             config::CrateTypeStaticlib => {
302                 link_staticlib(sess, trans, &out_filename, &tmpdir);
303             }
304             _ => {
305                 link_natively(sess, crate_type, &out_filename, trans, tmpdir.path());
306             }
307         }
308         out_filenames.push(out_filename);
309     }
310
311     if sess.opts.cg.save_temps {
312         let _ = tmpdir.into_path();
313     }
314
315     out_filenames
316 }
317
318 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
319     let mut search = Vec::new();
320     sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
321         search.push(path.to_path_buf());
322     });
323     return search;
324 }
325
326 fn archive_config<'a>(sess: &'a Session,
327                       output: &Path,
328                       input: Option<&Path>) -> ArchiveConfig<'a> {
329     ArchiveConfig {
330         sess,
331         dst: output.to_path_buf(),
332         src: input.map(|p| p.to_path_buf()),
333         lib_search_paths: archive_search_paths(sess),
334     }
335 }
336
337 /// We use a temp directory here to avoid races between concurrent rustc processes,
338 /// such as builds in the same directory using the same filename for metadata while
339 /// building an `.rlib` (stomping over one another), or writing an `.rmeta` into a
340 /// directory being searched for `extern crate` (observing an incomplete file).
341 /// The returned path is the temporary file containing the complete metadata.
342 fn emit_metadata<'a>(sess: &'a Session, trans: &CrateTranslation, tmpdir: &TempDir)
343                      -> PathBuf {
344     let out_filename = tmpdir.path().join(METADATA_FILENAME);
345     let result = fs::File::create(&out_filename).and_then(|mut f| {
346         f.write_all(&trans.metadata.raw_data)
347     });
348
349     if let Err(e) = result {
350         sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
351     }
352
353     out_filename
354 }
355
356 enum RlibFlavor {
357     Normal,
358     StaticlibBase,
359 }
360
361 // Create an 'rlib'
362 //
363 // An rlib in its current incarnation is essentially a renamed .a file. The
364 // rlib primarily contains the object file of the crate, but it also contains
365 // all of the object files from native libraries. This is done by unzipping
366 // native libraries and inserting all of the contents into this archive.
367 fn link_rlib<'a>(sess: &'a Session,
368                  trans: &CrateTranslation,
369                  flavor: RlibFlavor,
370                  out_filename: &Path,
371                  tmpdir: &TempDir) -> ArchiveBuilder<'a> {
372     info!("preparing rlib to {:?}", out_filename);
373     let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
374
375     for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
376         ab.add_file(obj);
377     }
378
379     // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
380     // we may not be configured to actually include a static library if we're
381     // adding it here. That's because later when we consume this rlib we'll
382     // decide whether we actually needed the static library or not.
383     //
384     // To do this "correctly" we'd need to keep track of which libraries added
385     // which object files to the archive. We don't do that here, however. The
386     // #[link(cfg(..))] feature is unstable, though, and only intended to get
387     // liblibc working. In that sense the check below just indicates that if
388     // there are any libraries we want to omit object files for at link time we
389     // just exclude all custom object files.
390     //
391     // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
392     // feature then we'll need to figure out how to record what objects were
393     // loaded from the libraries found here and then encode that into the
394     // metadata of the rlib we're generating somehow.
395     for lib in trans.crate_info.used_libraries.iter() {
396         match lib.kind {
397             NativeLibraryKind::NativeStatic => {}
398             NativeLibraryKind::NativeStaticNobundle |
399             NativeLibraryKind::NativeFramework |
400             NativeLibraryKind::NativeUnknown => continue,
401         }
402         ab.add_native_library(&lib.name.as_str());
403     }
404
405     // After adding all files to the archive, we need to update the
406     // symbol table of the archive.
407     ab.update_symbols();
408
409     // Note that it is important that we add all of our non-object "magical
410     // files" *after* all of the object files in the archive. The reason for
411     // this is as follows:
412     //
413     // * When performing LTO, this archive will be modified to remove
414     //   objects from above. The reason for this is described below.
415     //
416     // * When the system linker looks at an archive, it will attempt to
417     //   determine the architecture of the archive in order to see whether its
418     //   linkable.
419     //
420     //   The algorithm for this detection is: iterate over the files in the
421     //   archive. Skip magical SYMDEF names. Interpret the first file as an
422     //   object file. Read architecture from the object file.
423     //
424     // * As one can probably see, if "metadata" and "foo.bc" were placed
425     //   before all of the objects, then the architecture of this archive would
426     //   not be correctly inferred once 'foo.o' is removed.
427     //
428     // Basically, all this means is that this code should not move above the
429     // code above.
430     match flavor {
431         RlibFlavor::Normal => {
432             // Instead of putting the metadata in an object file section, rlibs
433             // contain the metadata in a separate file.
434             ab.add_file(&emit_metadata(sess, trans, tmpdir));
435
436             // For LTO purposes, the bytecode of this library is also inserted
437             // into the archive.
438             for bytecode in trans.modules.iter().filter_map(|m| m.bytecode_compressed.as_ref()) {
439                 ab.add_file(bytecode);
440             }
441
442             // After adding all files to the archive, we need to update the
443             // symbol table of the archive. This currently dies on macOS (see
444             // #11162), and isn't necessary there anyway
445             if !sess.target.target.options.is_like_osx {
446                 ab.update_symbols();
447             }
448         }
449
450         RlibFlavor::StaticlibBase => {
451             let obj = trans.allocator_module
452                 .as_ref()
453                 .and_then(|m| m.object.as_ref());
454             if let Some(obj) = obj {
455                 ab.add_file(obj);
456             }
457         }
458     }
459
460     ab
461 }
462
463 // Create a static archive
464 //
465 // This is essentially the same thing as an rlib, but it also involves adding
466 // all of the upstream crates' objects into the archive. This will slurp in
467 // all of the native libraries of upstream dependencies as well.
468 //
469 // Additionally, there's no way for us to link dynamic libraries, so we warn
470 // about all dynamic library dependencies that they're not linked in.
471 //
472 // There's no need to include metadata in a static archive, so ensure to not
473 // link in the metadata object file (and also don't prepare the archive with a
474 // metadata file).
475 fn link_staticlib(sess: &Session,
476                   trans: &CrateTranslation,
477                   out_filename: &Path,
478                   tempdir: &TempDir) {
479     let mut ab = link_rlib(sess,
480                            trans,
481                            RlibFlavor::StaticlibBase,
482                            out_filename,
483                            tempdir);
484     let mut all_native_libs = vec![];
485
486     let res = each_linked_rlib(sess, &trans.crate_info, &mut |cnum, path| {
487         let name = &trans.crate_info.crate_name[&cnum];
488         let native_libs = &trans.crate_info.native_libraries[&cnum];
489
490         // Here when we include the rlib into our staticlib we need to make a
491         // decision whether to include the extra object files along the way.
492         // These extra object files come from statically included native
493         // libraries, but they may be cfg'd away with #[link(cfg(..))].
494         //
495         // This unstable feature, though, only needs liblibc to work. The only
496         // use case there is where musl is statically included in liblibc.rlib,
497         // so if we don't want the included version we just need to skip it. As
498         // a result the logic here is that if *any* linked library is cfg'd away
499         // we just skip all object files.
500         //
501         // Clearly this is not sufficient for a general purpose feature, and
502         // we'd want to read from the library's metadata to determine which
503         // object files come from where and selectively skip them.
504         let skip_object_files = native_libs.iter().any(|lib| {
505             lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
506         });
507         ab.add_rlib(path,
508                     &name.as_str(),
509                     sess.lto() && !ignored_for_lto(sess, &trans.crate_info, cnum),
510                     skip_object_files).unwrap();
511
512         all_native_libs.extend(trans.crate_info.native_libraries[&cnum].iter().cloned());
513     });
514     if let Err(e) = res {
515         sess.fatal(&e);
516     }
517
518     ab.update_symbols();
519     ab.build();
520
521     if !all_native_libs.is_empty() {
522         if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) {
523             print_native_static_libs(sess, &all_native_libs);
524         }
525     }
526 }
527
528 fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLibrary]) {
529     let lib_args: Vec<_> = all_native_libs.iter()
530         .filter(|l| relevant_lib(sess, l))
531         .filter_map(|lib| match lib.kind {
532             NativeLibraryKind::NativeStaticNobundle |
533             NativeLibraryKind::NativeUnknown => {
534                 if sess.target.target.options.is_like_msvc {
535                     Some(format!("{}.lib", lib.name))
536                 } else {
537                     Some(format!("-l{}", lib.name))
538                 }
539             },
540             NativeLibraryKind::NativeFramework => {
541                 // ld-only syntax, since there are no frameworks in MSVC
542                 Some(format!("-framework {}", lib.name))
543             },
544             // These are included, no need to print them
545             NativeLibraryKind::NativeStatic => None,
546         })
547         .collect();
548     if !lib_args.is_empty() {
549         sess.note_without_error("Link against the following native artifacts when linking \
550                                  against this static library. The order and any duplication \
551                                  can be significant on some platforms.");
552         // Prefix for greppability
553         sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
554     }
555 }
556
557 // Create a dynamic library or executable
558 //
559 // This will invoke the system linker/cc to create the resulting file. This
560 // links to all upstream files as well.
561 fn link_natively(sess: &Session,
562                  crate_type: config::CrateType,
563                  out_filename: &Path,
564                  trans: &CrateTranslation,
565                  tmpdir: &Path) {
566     info!("preparing {:?} to {:?}", crate_type, out_filename);
567     let flavor = sess.linker_flavor();
568
569     // The "binaryen linker" is massively special, so skip everything below.
570     if flavor == LinkerFlavor::Binaryen {
571         return link_binaryen(sess, crate_type, out_filename, trans, tmpdir);
572     }
573
574     // The invocations of cc share some flags across platforms
575     let (pname, mut cmd, envs) = get_linker(sess);
576     // This will set PATH on windows
577     cmd.envs(envs);
578
579     let root = sess.target_filesearch(PathKind::Native).get_lib_path();
580     if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
581         cmd.args(args);
582     }
583     if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
584         cmd.args(args);
585     }
586     cmd.args(&sess.opts.debugging_opts.pre_link_arg);
587
588     let pre_link_objects = if crate_type == config::CrateTypeExecutable {
589         &sess.target.target.options.pre_link_objects_exe
590     } else {
591         &sess.target.target.options.pre_link_objects_dll
592     };
593     for obj in pre_link_objects {
594         cmd.arg(root.join(obj));
595     }
596
597     if sess.target.target.options.is_like_emscripten {
598         cmd.arg("-s");
599         cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
600             "DISABLE_EXCEPTION_CATCHING=1"
601         } else {
602             "DISABLE_EXCEPTION_CATCHING=0"
603         });
604     }
605
606     {
607         let mut linker = trans.linker_info.to_linker(cmd, &sess);
608         link_args(&mut *linker, sess, crate_type, tmpdir,
609                   out_filename, trans);
610         cmd = linker.finalize();
611     }
612     if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
613         cmd.args(args);
614     }
615     for obj in &sess.target.target.options.post_link_objects {
616         cmd.arg(root.join(obj));
617     }
618     if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
619         cmd.args(args);
620     }
621     for &(ref k, ref v) in &sess.target.target.options.link_env {
622         cmd.env(k, v);
623     }
624
625     if sess.opts.debugging_opts.print_link_args {
626         println!("{:?}", &cmd);
627     }
628
629     // May have not found libraries in the right formats.
630     sess.abort_if_errors();
631
632     // Invoke the system linker
633     //
634     // Note that there's a terribly awful hack that really shouldn't be present
635     // in any compiler. Here an environment variable is supported to
636     // automatically retry the linker invocation if the linker looks like it
637     // segfaulted.
638     //
639     // Gee that seems odd, normally segfaults are things we want to know about!
640     // Unfortunately though in rust-lang/rust#38878 we're experiencing the
641     // linker segfaulting on Travis quite a bit which is causing quite a bit of
642     // pain to land PRs when they spuriously fail due to a segfault.
643     //
644     // The issue #38878 has some more debugging information on it as well, but
645     // this unfortunately looks like it's just a race condition in macOS's linker
646     // with some thread pool working in the background. It seems that no one
647     // currently knows a fix for this so in the meantime we're left with this...
648     info!("{:?}", &cmd);
649     let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
650     let mut prog;
651     let mut i = 0;
652     loop {
653         i += 1;
654         prog = time(sess.time_passes(), "running linker", || {
655             exec_linker(sess, &mut cmd, tmpdir)
656         });
657         if !retry_on_segfault || i > 3 {
658             break
659         }
660         let output = match prog {
661             Ok(ref output) => output,
662             Err(_) => break,
663         };
664         if output.status.success() {
665             break
666         }
667         let mut out = output.stderr.clone();
668         out.extend(&output.stdout);
669         let out = String::from_utf8_lossy(&out);
670         let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
671         let msg_bus  = "clang: error: unable to execute command: Bus error: 10";
672         if !(out.contains(msg_segv) || out.contains(msg_bus)) {
673             break
674         }
675
676         warn!(
677             "looks like the linker segfaulted when we tried to call it, \
678              automatically retrying again. cmd = {:?}, out = {}.",
679             cmd,
680             out,
681         );
682     }
683
684     match prog {
685         Ok(prog) => {
686             fn escape_string(s: &[u8]) -> String {
687                 str::from_utf8(s).map(|s| s.to_owned())
688                     .unwrap_or_else(|_| {
689                         let mut x = "Non-UTF-8 output: ".to_string();
690                         x.extend(s.iter()
691                                  .flat_map(|&b| ascii::escape_default(b))
692                                  .map(|b| char::from_u32(b as u32).unwrap()));
693                         x
694                     })
695             }
696             if !prog.status.success() {
697                 let mut output = prog.stderr.clone();
698                 output.extend_from_slice(&prog.stdout);
699                 sess.struct_err(&format!("linking with `{}` failed: {}",
700                                          pname.display(),
701                                          prog.status))
702                     .note(&format!("{:?}", &cmd))
703                     .note(&escape_string(&output))
704                     .emit();
705                 sess.abort_if_errors();
706             }
707             info!("linker stderr:\n{}", escape_string(&prog.stderr));
708             info!("linker stdout:\n{}", escape_string(&prog.stdout));
709         },
710         Err(e) => {
711             let linker_not_found = e.kind() == io::ErrorKind::NotFound;
712
713             let mut linker_error = {
714                 if linker_not_found {
715                     sess.struct_err(&format!("linker `{}` not found", pname.display()))
716                 } else {
717                     sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
718                 }
719             };
720
721             linker_error.note(&format!("{}", e));
722
723             if !linker_not_found {
724                 linker_error.note(&format!("{:?}", &cmd));
725             }
726
727             linker_error.emit();
728
729             if sess.target.target.options.is_like_msvc && linker_not_found {
730                 sess.note_without_error("the msvc targets depend on the msvc linker \
731                     but `link.exe` was not found");
732                 sess.note_without_error("please ensure that VS 2013 or VS 2015 was installed \
733                     with the Visual C++ option");
734             }
735             sess.abort_if_errors();
736         }
737     }
738
739
740     // On macOS, debuggers need this utility to get run to do some munging of
741     // the symbols
742     if sess.target.target.options.is_like_osx && sess.opts.debuginfo != NoDebugInfo {
743         match Command::new("dsymutil").arg(out_filename).output() {
744             Ok(..) => {}
745             Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
746         }
747     }
748 }
749
750 fn exec_linker(sess: &Session, cmd: &mut Command, tmpdir: &Path)
751     -> io::Result<Output>
752 {
753     // When attempting to spawn the linker we run a risk of blowing out the
754     // size limits for spawning a new process with respect to the arguments
755     // we pass on the command line.
756     //
757     // Here we attempt to handle errors from the OS saying "your list of
758     // arguments is too big" by reinvoking the linker again with an `@`-file
759     // that contains all the arguments. The theory is that this is then
760     // accepted on all linkers and the linker will read all its options out of
761     // there instead of looking at the command line.
762     match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
763         Ok(child) => return child.wait_with_output(),
764         Err(ref e) if command_line_too_big(e) => {}
765         Err(e) => return Err(e)
766     }
767
768     let file = tmpdir.join("linker-arguments");
769     let mut cmd2 = Command::new(cmd.get_program());
770     cmd2.arg(format!("@{}", file.display()));
771     for &(ref k, ref v) in cmd.get_env() {
772         cmd2.env(k, v);
773     }
774     let mut f = BufWriter::new(File::create(&file)?);
775     for arg in cmd.get_args() {
776         writeln!(f, "{}", Escape {
777             arg: arg.to_str().unwrap(),
778             is_like_msvc: sess.target.target.options.is_like_msvc,
779         })?;
780     }
781     f.into_inner()?;
782     return cmd2.output();
783
784     #[cfg(unix)]
785     fn command_line_too_big(err: &io::Error) -> bool {
786         err.raw_os_error() == Some(::libc::E2BIG)
787     }
788
789     #[cfg(windows)]
790     fn command_line_too_big(err: &io::Error) -> bool {
791         const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
792         err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
793     }
794
795     struct Escape<'a> {
796         arg: &'a str,
797         is_like_msvc: bool,
798     }
799
800     impl<'a> fmt::Display for Escape<'a> {
801         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
802             if self.is_like_msvc {
803                 // This is "documented" at
804                 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
805                 //
806                 // Unfortunately there's not a great specification of the
807                 // syntax I could find online (at least) but some local
808                 // testing showed that this seemed sufficient-ish to catch
809                 // at least a few edge cases.
810                 write!(f, "\"")?;
811                 for c in self.arg.chars() {
812                     match c {
813                         '"' => write!(f, "\\{}", c)?,
814                         c => write!(f, "{}", c)?,
815                     }
816                 }
817                 write!(f, "\"")?;
818             } else {
819                 // This is documented at https://linux.die.net/man/1/ld, namely:
820                 //
821                 // > Options in file are separated by whitespace. A whitespace
822                 // > character may be included in an option by surrounding the
823                 // > entire option in either single or double quotes. Any
824                 // > character (including a backslash) may be included by
825                 // > prefixing the character to be included with a backslash.
826                 //
827                 // We put an argument on each line, so all we need to do is
828                 // ensure the line is interpreted as one whole argument.
829                 for c in self.arg.chars() {
830                     match c {
831                         '\\' |
832                         ' ' => write!(f, "\\{}", c)?,
833                         c => write!(f, "{}", c)?,
834                     }
835                 }
836             }
837             Ok(())
838         }
839     }
840 }
841
842 fn link_args(cmd: &mut Linker,
843              sess: &Session,
844              crate_type: config::CrateType,
845              tmpdir: &Path,
846              out_filename: &Path,
847              trans: &CrateTranslation) {
848
849     // The default library location, we need this to find the runtime.
850     // The location of crates will be determined as needed.
851     let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
852
853     // target descriptor
854     let t = &sess.target.target;
855
856     cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
857     for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
858         cmd.add_object(obj);
859     }
860     cmd.output_filename(out_filename);
861
862     if crate_type == config::CrateTypeExecutable &&
863        sess.target.target.options.is_like_windows {
864         if let Some(ref s) = trans.windows_subsystem {
865             cmd.subsystem(s);
866         }
867     }
868
869     // If we're building a dynamic library then some platforms need to make sure
870     // that all symbols are exported correctly from the dynamic library.
871     if crate_type != config::CrateTypeExecutable ||
872        sess.target.target.options.is_like_emscripten {
873         cmd.export_symbols(tmpdir, crate_type);
874     }
875
876     // When linking a dynamic library, we put the metadata into a section of the
877     // executable. This metadata is in a separate object file from the main
878     // object file, so we link that in here.
879     if crate_type == config::CrateTypeDylib ||
880        crate_type == config::CrateTypeProcMacro {
881         if let Some(obj) = trans.metadata_module.object.as_ref() {
882             cmd.add_object(obj);
883         }
884     }
885
886     let obj = trans.allocator_module
887         .as_ref()
888         .and_then(|m| m.object.as_ref());
889     if let Some(obj) = obj {
890         cmd.add_object(obj);
891     }
892
893     // Try to strip as much out of the generated object by removing unused
894     // sections if possible. See more comments in linker.rs
895     if !sess.opts.cg.link_dead_code {
896         let keep_metadata = crate_type == config::CrateTypeDylib;
897         cmd.gc_sections(keep_metadata);
898     }
899
900     let used_link_args = &trans.crate_info.link_args;
901
902     if crate_type == config::CrateTypeExecutable &&
903        t.options.position_independent_executables {
904         let empty_vec = Vec::new();
905         let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
906         let more_args = &sess.opts.cg.link_arg;
907         let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
908
909         if get_reloc_model(sess) == llvm::RelocMode::PIC
910             && !sess.crt_static() && !args.any(|x| *x == "-static") {
911             cmd.position_independent_executable();
912         }
913     }
914
915     let relro_level = match sess.opts.debugging_opts.relro_level {
916         Some(level) => level,
917         None => t.options.relro_level,
918     };
919     match relro_level {
920         RelroLevel::Full => {
921             cmd.full_relro();
922         },
923         RelroLevel::Partial => {
924             cmd.partial_relro();
925         },
926         RelroLevel::Off => {},
927     }
928
929     // Pass optimization flags down to the linker.
930     cmd.optimize();
931
932     // Pass debuginfo flags down to the linker.
933     cmd.debuginfo();
934
935     // We want to prevent the compiler from accidentally leaking in any system
936     // libraries, so we explicitly ask gcc to not link to any libraries by
937     // default. Note that this does not happen for windows because windows pulls
938     // in some large number of libraries and I couldn't quite figure out which
939     // subset we wanted.
940     if t.options.no_default_libraries {
941         cmd.no_default_libraries();
942     }
943
944     // Take careful note of the ordering of the arguments we pass to the linker
945     // here. Linkers will assume that things on the left depend on things to the
946     // right. Things on the right cannot depend on things on the left. This is
947     // all formally implemented in terms of resolving symbols (libs on the right
948     // resolve unknown symbols of libs on the left, but not vice versa).
949     //
950     // For this reason, we have organized the arguments we pass to the linker as
951     // such:
952     //
953     //  1. The local object that LLVM just generated
954     //  2. Local native libraries
955     //  3. Upstream rust libraries
956     //  4. Upstream native libraries
957     //
958     // The rationale behind this ordering is that those items lower down in the
959     // list can't depend on items higher up in the list. For example nothing can
960     // depend on what we just generated (e.g. that'd be a circular dependency).
961     // Upstream rust libraries are not allowed to depend on our local native
962     // libraries as that would violate the structure of the DAG, in that
963     // scenario they are required to link to them as well in a shared fashion.
964     //
965     // Note that upstream rust libraries may contain native dependencies as
966     // well, but they also can't depend on what we just started to add to the
967     // link line. And finally upstream native libraries can't depend on anything
968     // in this DAG so far because they're only dylibs and dylibs can only depend
969     // on other dylibs (e.g. other native deps).
970     add_local_native_libraries(cmd, sess, trans);
971     add_upstream_rust_crates(cmd, sess, trans, crate_type, tmpdir);
972     add_upstream_native_libraries(cmd, sess, trans, crate_type);
973
974     // Tell the linker what we're doing.
975     if crate_type != config::CrateTypeExecutable {
976         cmd.build_dylib(out_filename);
977     }
978     if crate_type == config::CrateTypeExecutable && sess.crt_static() {
979         cmd.build_static_executable();
980     }
981
982     // FIXME (#2397): At some point we want to rpath our guesses as to
983     // where extern libraries might live, based on the
984     // addl_lib_search_paths
985     if sess.opts.cg.rpath {
986         let sysroot = sess.sysroot();
987         let target_triple = &sess.opts.target_triple;
988         let mut get_install_prefix_lib_path = || {
989             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
990             let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
991             let mut path = PathBuf::from(install_prefix);
992             path.push(&tlib);
993
994             path
995         };
996         let mut rpath_config = RPathConfig {
997             used_crates: &trans.crate_info.used_crates_dynamic,
998             out_filename: out_filename.to_path_buf(),
999             has_rpath: sess.target.target.options.has_rpath,
1000             is_like_osx: sess.target.target.options.is_like_osx,
1001             linker_is_gnu: sess.target.target.options.linker_is_gnu,
1002             get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1003         };
1004         cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1005     }
1006
1007     // Finally add all the linker arguments provided on the command line along
1008     // with any #[link_args] attributes found inside the crate
1009     if let Some(ref args) = sess.opts.cg.link_args {
1010         cmd.args(args);
1011     }
1012     cmd.args(&sess.opts.cg.link_arg);
1013     cmd.args(&used_link_args);
1014 }
1015
1016 // # Native library linking
1017 //
1018 // User-supplied library search paths (-L on the command line). These are
1019 // the same paths used to find Rust crates, so some of them may have been
1020 // added already by the previous crate linking code. This only allows them
1021 // to be found at compile time so it is still entirely up to outside
1022 // forces to make sure that library can be found at runtime.
1023 //
1024 // Also note that the native libraries linked here are only the ones located
1025 // in the current crate. Upstream crates with native library dependencies
1026 // may have their native library pulled in above.
1027 fn add_local_native_libraries(cmd: &mut Linker,
1028                               sess: &Session,
1029                               trans: &CrateTranslation) {
1030     sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1031         match k {
1032             PathKind::Framework => { cmd.framework_path(path); }
1033             _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1034         }
1035     });
1036
1037     let relevant_libs = trans.crate_info.used_libraries.iter().filter(|l| {
1038         relevant_lib(sess, l)
1039     });
1040
1041     let search_path = archive_search_paths(sess);
1042     for lib in relevant_libs {
1043         match lib.kind {
1044             NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1045             NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1046             NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&lib.name.as_str()),
1047             NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&lib.name.as_str(),
1048                                                                         &search_path)
1049         }
1050     }
1051 }
1052
1053 // # Rust Crate linking
1054 //
1055 // Rust crates are not considered at all when creating an rlib output. All
1056 // dependencies will be linked when producing the final output (instead of
1057 // the intermediate rlib version)
1058 fn add_upstream_rust_crates(cmd: &mut Linker,
1059                             sess: &Session,
1060                             trans: &CrateTranslation,
1061                             crate_type: config::CrateType,
1062                             tmpdir: &Path) {
1063     // All of the heavy lifting has previously been accomplished by the
1064     // dependency_format module of the compiler. This is just crawling the
1065     // output of that module, adding crates as necessary.
1066     //
1067     // Linking to a rlib involves just passing it to the linker (the linker
1068     // will slurp up the object files inside), and linking to a dynamic library
1069     // involves just passing the right -l flag.
1070
1071     let formats = sess.dependency_formats.borrow();
1072     let data = formats.get(&crate_type).unwrap();
1073
1074     // Invoke get_used_crates to ensure that we get a topological sorting of
1075     // crates.
1076     let deps = &trans.crate_info.used_crates_dynamic;
1077
1078     let mut compiler_builtins = None;
1079
1080     for &(cnum, _) in deps.iter() {
1081         // We may not pass all crates through to the linker. Some crates may
1082         // appear statically in an existing dylib, meaning we'll pick up all the
1083         // symbols from the dylib.
1084         let src = &trans.crate_info.used_crate_source[&cnum];
1085         match data[cnum.as_usize() - 1] {
1086             _ if trans.crate_info.profiler_runtime == Some(cnum) => {
1087                 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1088             }
1089             _ if trans.crate_info.sanitizer_runtime == Some(cnum) => {
1090                 link_sanitizer_runtime(cmd, sess, trans, tmpdir, cnum);
1091             }
1092             // compiler-builtins are always placed last to ensure that they're
1093             // linked correctly.
1094             _ if trans.crate_info.compiler_builtins == Some(cnum) => {
1095                 assert!(compiler_builtins.is_none());
1096                 compiler_builtins = Some(cnum);
1097             }
1098             Linkage::NotLinked |
1099             Linkage::IncludedFromDylib => {}
1100             Linkage::Static => {
1101                 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1102             }
1103             Linkage::Dynamic => {
1104                 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1105             }
1106         }
1107     }
1108
1109     // compiler-builtins are always placed last to ensure that they're
1110     // linked correctly.
1111     // We must always link the `compiler_builtins` crate statically. Even if it
1112     // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
1113     // is used)
1114     if let Some(cnum) = compiler_builtins {
1115         add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1116     }
1117
1118     // Converts a library file-stem into a cc -l argument
1119     fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1120         if stem.starts_with("lib") && !config.target.options.is_like_windows {
1121             &stem[3..]
1122         } else {
1123             stem
1124         }
1125     }
1126
1127     // We must link the sanitizer runtime using -Wl,--whole-archive but since
1128     // it's packed in a .rlib, it contains stuff that are not objects that will
1129     // make the linker error. So we must remove those bits from the .rlib before
1130     // linking it.
1131     fn link_sanitizer_runtime(cmd: &mut Linker,
1132                               sess: &Session,
1133                               trans: &CrateTranslation,
1134                               tmpdir: &Path,
1135                               cnum: CrateNum) {
1136         let src = &trans.crate_info.used_crate_source[&cnum];
1137         let cratepath = &src.rlib.as_ref().unwrap().0;
1138
1139         if sess.target.target.options.is_like_osx {
1140             // On Apple platforms, the sanitizer is always built as a dylib, and
1141             // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1142             // rpath to the library as well (the rpath should be absolute, see
1143             // PR #41352 for details).
1144             //
1145             // FIXME: Remove this logic into librustc_*san once Cargo supports it
1146             let rpath = cratepath.parent().unwrap();
1147             let rpath = rpath.to_str().expect("non-utf8 component in path");
1148             cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1149         }
1150
1151         let dst = tmpdir.join(cratepath.file_name().unwrap());
1152         let cfg = archive_config(sess, &dst, Some(cratepath));
1153         let mut archive = ArchiveBuilder::new(cfg);
1154         archive.update_symbols();
1155
1156         for f in archive.src_files() {
1157             if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1158                 archive.remove_file(&f);
1159                 continue
1160             }
1161         }
1162
1163         archive.build();
1164
1165         cmd.link_whole_rlib(&dst);
1166     }
1167
1168     // Adds the static "rlib" versions of all crates to the command line.
1169     // There's a bit of magic which happens here specifically related to LTO and
1170     // dynamic libraries. Specifically:
1171     //
1172     // * For LTO, we remove upstream object files.
1173     // * For dylibs we remove metadata and bytecode from upstream rlibs
1174     //
1175     // When performing LTO, almost(*) all of the bytecode from the upstream
1176     // libraries has already been included in our object file output. As a
1177     // result we need to remove the object files in the upstream libraries so
1178     // the linker doesn't try to include them twice (or whine about duplicate
1179     // symbols). We must continue to include the rest of the rlib, however, as
1180     // it may contain static native libraries which must be linked in.
1181     //
1182     // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1183     // their bytecode wasn't included. The object files in those libraries must
1184     // still be passed to the linker.
1185     //
1186     // When making a dynamic library, linkers by default don't include any
1187     // object files in an archive if they're not necessary to resolve the link.
1188     // We basically want to convert the archive (rlib) to a dylib, though, so we
1189     // *do* want everything included in the output, regardless of whether the
1190     // linker thinks it's needed or not. As a result we must use the
1191     // --whole-archive option (or the platform equivalent). When using this
1192     // option the linker will fail if there are non-objects in the archive (such
1193     // as our own metadata and/or bytecode). All in all, for rlibs to be
1194     // entirely included in dylibs, we need to remove all non-object files.
1195     //
1196     // Note, however, that if we're not doing LTO or we're not producing a dylib
1197     // (aka we're making an executable), we can just pass the rlib blindly to
1198     // the linker (fast) because it's fine if it's not actually included as
1199     // we're at the end of the dependency chain.
1200     fn add_static_crate(cmd: &mut Linker,
1201                         sess: &Session,
1202                         trans: &CrateTranslation,
1203                         tmpdir: &Path,
1204                         crate_type: config::CrateType,
1205                         cnum: CrateNum) {
1206         let src = &trans.crate_info.used_crate_source[&cnum];
1207         let cratepath = &src.rlib.as_ref().unwrap().0;
1208
1209         // See the comment above in `link_staticlib` and `link_rlib` for why if
1210         // there's a static library that's not relevant we skip all object
1211         // files.
1212         let native_libs = &trans.crate_info.native_libraries[&cnum];
1213         let skip_native = native_libs.iter().any(|lib| {
1214             lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1215         });
1216
1217         if (!sess.lto() || ignored_for_lto(sess, &trans.crate_info, cnum)) &&
1218            crate_type != config::CrateTypeDylib &&
1219            !skip_native {
1220             cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1221             return
1222         }
1223
1224         let dst = tmpdir.join(cratepath.file_name().unwrap());
1225         let name = cratepath.file_name().unwrap().to_str().unwrap();
1226         let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1227
1228         time(sess.time_passes(), &format!("altering {}.rlib", name), || {
1229             let cfg = archive_config(sess, &dst, Some(cratepath));
1230             let mut archive = ArchiveBuilder::new(cfg);
1231             archive.update_symbols();
1232
1233             let mut any_objects = false;
1234             for f in archive.src_files() {
1235                 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1236                     archive.remove_file(&f);
1237                     continue
1238                 }
1239
1240                 let canonical = f.replace("-", "_");
1241                 let canonical_name = name.replace("-", "_");
1242
1243                 // Look for `.rcgu.o` at the end of the filename to conclude
1244                 // that this is a Rust-related object file.
1245                 fn looks_like_rust(s: &str) -> bool {
1246                     let path = Path::new(s);
1247                     let ext = path.extension().and_then(|s| s.to_str());
1248                     if ext != Some(OutputType::Object.extension()) {
1249                         return false
1250                     }
1251                     let ext2 = path.file_stem()
1252                         .and_then(|s| Path::new(s).extension())
1253                         .and_then(|s| s.to_str());
1254                     ext2 == Some(RUST_CGU_EXT)
1255                 }
1256
1257                 let is_rust_object =
1258                     canonical.starts_with(&canonical_name) &&
1259                     looks_like_rust(&f);
1260
1261                 // If we've been requested to skip all native object files
1262                 // (those not generated by the rust compiler) then we can skip
1263                 // this file. See above for why we may want to do this.
1264                 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1265
1266                 // If we're performing LTO and this is a rust-generated object
1267                 // file, then we don't need the object file as it's part of the
1268                 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1269                 // though, so we let that object file slide.
1270                 let skip_because_lto = sess.lto() &&
1271                     is_rust_object &&
1272                     (sess.target.target.options.no_builtins ||
1273                      !trans.crate_info.is_no_builtins.contains(&cnum));
1274
1275                 if skip_because_cfg_say_so || skip_because_lto {
1276                     archive.remove_file(&f);
1277                 } else {
1278                     any_objects = true;
1279                 }
1280             }
1281
1282             if !any_objects {
1283                 return
1284             }
1285             archive.build();
1286
1287             // If we're creating a dylib, then we need to include the
1288             // whole of each object in our archive into that artifact. This is
1289             // because a `dylib` can be reused as an intermediate artifact.
1290             //
1291             // Note, though, that we don't want to include the whole of a
1292             // compiler-builtins crate (e.g. compiler-rt) because it'll get
1293             // repeatedly linked anyway.
1294             if crate_type == config::CrateTypeDylib &&
1295                 trans.crate_info.compiler_builtins != Some(cnum) {
1296                 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1297             } else {
1298                 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1299             }
1300         });
1301     }
1302
1303     // Same thing as above, but for dynamic crates instead of static crates.
1304     fn add_dynamic_crate(cmd: &mut Linker, sess: &Session, cratepath: &Path) {
1305         // If we're performing LTO, then it should have been previously required
1306         // that all upstream rust dependencies were available in an rlib format.
1307         assert!(!sess.lto());
1308
1309         // Just need to tell the linker about where the library lives and
1310         // what its name is
1311         let parent = cratepath.parent();
1312         if let Some(dir) = parent {
1313             cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1314         }
1315         let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1316         cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1317                             parent.unwrap_or(Path::new("")));
1318     }
1319 }
1320
1321 // Link in all of our upstream crates' native dependencies. Remember that
1322 // all of these upstream native dependencies are all non-static
1323 // dependencies. We've got two cases then:
1324 //
1325 // 1. The upstream crate is an rlib. In this case we *must* link in the
1326 // native dependency because the rlib is just an archive.
1327 //
1328 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1329 // have the dependency present on the system somewhere. Thus, we don't
1330 // gain a whole lot from not linking in the dynamic dependency to this
1331 // crate as well.
1332 //
1333 // The use case for this is a little subtle. In theory the native
1334 // dependencies of a crate are purely an implementation detail of the crate
1335 // itself, but the problem arises with generic and inlined functions. If a
1336 // generic function calls a native function, then the generic function must
1337 // be instantiated in the target crate, meaning that the native symbol must
1338 // also be resolved in the target crate.
1339 fn add_upstream_native_libraries(cmd: &mut Linker,
1340                                  sess: &Session,
1341                                  trans: &CrateTranslation,
1342                                  crate_type: config::CrateType) {
1343     // Be sure to use a topological sorting of crates because there may be
1344     // interdependencies between native libraries. When passing -nodefaultlibs,
1345     // for example, almost all native libraries depend on libc, so we have to
1346     // make sure that's all the way at the right (liblibc is near the base of
1347     // the dependency chain).
1348     //
1349     // This passes RequireStatic, but the actual requirement doesn't matter,
1350     // we're just getting an ordering of crate numbers, we're not worried about
1351     // the paths.
1352     let formats = sess.dependency_formats.borrow();
1353     let data = formats.get(&crate_type).unwrap();
1354
1355     let crates = &trans.crate_info.used_crates_static;
1356     for &(cnum, _) in crates {
1357         for lib in trans.crate_info.native_libraries[&cnum].iter() {
1358             if !relevant_lib(sess, &lib) {
1359                 continue
1360             }
1361             match lib.kind {
1362                 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1363                 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1364                 NativeLibraryKind::NativeStaticNobundle => {
1365                     // Link "static-nobundle" native libs only if the crate they originate from
1366                     // is being linked statically to the current crate.  If it's linked dynamically
1367                     // or is an rlib already included via some other dylib crate, the symbols from
1368                     // native libs will have already been included in that dylib.
1369                     if data[cnum.as_usize() - 1] == Linkage::Static {
1370                         cmd.link_staticlib(&lib.name.as_str())
1371                     }
1372                 },
1373                 // ignore statically included native libraries here as we've
1374                 // already included them when we included the rust library
1375                 // previously
1376                 NativeLibraryKind::NativeStatic => {}
1377             }
1378         }
1379     }
1380 }
1381
1382 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1383     match lib.cfg {
1384         Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
1385         None => true,
1386     }
1387 }
1388
1389 /// For now "linking with binaryen" is just "move the one module we generated in
1390 /// the backend to the final output"
1391 ///
1392 /// That is, all the heavy lifting happens during the `back::write` phase. Here
1393 /// we just clean up after that.
1394 ///
1395 /// Note that this is super temporary and "will not survive the night", this is
1396 /// guaranteed to get removed as soon as a linker for wasm exists. This should
1397 /// not be used for anything other than wasm.
1398 fn link_binaryen(sess: &Session,
1399                  _crate_type: config::CrateType,
1400                  out_filename: &Path,
1401                  trans: &CrateTranslation,
1402                  _tmpdir: &Path) {
1403     assert!(trans.allocator_module.is_none());
1404     assert_eq!(trans.modules.len(), 1);
1405
1406     let object = trans.modules[0].object.as_ref().expect("object must exist");
1407     let res = fs::hard_link(object, out_filename)
1408         .or_else(|_| fs::copy(object, out_filename).map(|_| ()));
1409     if let Err(e) = res {
1410         sess.fatal(&format!("failed to create `{}`: {}",
1411                             out_filename.display(),
1412                             e));
1413     }
1414 }