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