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