]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/link.rs
musl: don't use the included startfiles with -crt-static
[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
649     if sess.target.target.options.is_like_emscripten {
650         cmd.arg("-s");
651         cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
652             "DISABLE_EXCEPTION_CATCHING=1"
653         } else {
654             "DISABLE_EXCEPTION_CATCHING=0"
655         });
656     }
657
658     {
659         let mut linker = trans.linker_info.to_linker(cmd, &sess);
660         link_args(&mut *linker, sess, crate_type, tmpdir,
661                   out_filename, trans);
662         cmd = linker.finalize();
663     }
664     if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
665         cmd.args(args);
666     }
667     for obj in &sess.target.target.options.post_link_objects {
668         cmd.arg(root.join(obj));
669     }
670     if sess.crt_static() {
671         for obj in &sess.target.target.options.post_link_objects_crt {
672             cmd.arg(root.join(obj));
673         }
674     }
675     if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
676         cmd.args(args);
677     }
678     for &(ref k, ref v) in &sess.target.target.options.link_env {
679         cmd.env(k, v);
680     }
681
682     if sess.opts.debugging_opts.print_link_args {
683         println!("{:?}", &cmd);
684     }
685
686     // May have not found libraries in the right formats.
687     sess.abort_if_errors();
688
689     // Invoke the system linker
690     //
691     // Note that there's a terribly awful hack that really shouldn't be present
692     // in any compiler. Here an environment variable is supported to
693     // automatically retry the linker invocation if the linker looks like it
694     // segfaulted.
695     //
696     // Gee that seems odd, normally segfaults are things we want to know about!
697     // Unfortunately though in rust-lang/rust#38878 we're experiencing the
698     // linker segfaulting on Travis quite a bit which is causing quite a bit of
699     // pain to land PRs when they spuriously fail due to a segfault.
700     //
701     // The issue #38878 has some more debugging information on it as well, but
702     // this unfortunately looks like it's just a race condition in macOS's linker
703     // with some thread pool working in the background. It seems that no one
704     // currently knows a fix for this so in the meantime we're left with this...
705     info!("{:?}", &cmd);
706     let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
707     let mut prog;
708     let mut i = 0;
709     loop {
710         i += 1;
711         prog = time(sess, "running linker", || {
712             exec_linker(sess, &mut cmd, out_filename, tmpdir)
713         });
714         let output = match prog {
715             Ok(ref output) => output,
716             Err(_) => break,
717         };
718         if output.status.success() {
719             break
720         }
721         let mut out = output.stderr.clone();
722         out.extend(&output.stdout);
723         let out = String::from_utf8_lossy(&out);
724
725         // Check to see if the link failed with "unrecognized command line option:
726         // '-no-pie'" for gcc or "unknown argument: '-no-pie'" for clang. If so,
727         // reperform the link step without the -no-pie option. This is safe because
728         // if the linker doesn't support -no-pie then it should not default to
729         // linking executables as pie. Different versions of gcc seem to use
730         // different quotes in the error message so don't check for them.
731         if sess.target.target.options.linker_is_gnu &&
732            sess.linker_flavor() != LinkerFlavor::Ld &&
733            (out.contains("unrecognized command line option") ||
734             out.contains("unknown argument")) &&
735            out.contains("-no-pie") &&
736            cmd.get_args().iter().any(|e| e.to_string_lossy() == "-no-pie") {
737             info!("linker output: {:?}", out);
738             warn!("Linker does not support -no-pie command line option. Retrying without.");
739             for arg in cmd.take_args() {
740                 if arg.to_string_lossy() != "-no-pie" {
741                     cmd.arg(arg);
742                 }
743             }
744             info!("{:?}", &cmd);
745             continue;
746         }
747         if !retry_on_segfault || i > 3 {
748             break
749         }
750         let msg_segv = "clang: error: unable to execute command: Segmentation fault: 11";
751         let msg_bus  = "clang: error: unable to execute command: Bus error: 10";
752         if !(out.contains(msg_segv) || out.contains(msg_bus)) {
753             break
754         }
755
756         warn!(
757             "looks like the linker segfaulted when we tried to call it, \
758              automatically retrying again. cmd = {:?}, out = {}.",
759             cmd,
760             out,
761         );
762     }
763
764     match prog {
765         Ok(prog) => {
766             fn escape_string(s: &[u8]) -> String {
767                 str::from_utf8(s).map(|s| s.to_owned())
768                     .unwrap_or_else(|_| {
769                         let mut x = "Non-UTF-8 output: ".to_string();
770                         x.extend(s.iter()
771                                  .flat_map(|&b| ascii::escape_default(b))
772                                  .map(|b| char::from_u32(b as u32).unwrap()));
773                         x
774                     })
775             }
776             if !prog.status.success() {
777                 let mut output = prog.stderr.clone();
778                 output.extend_from_slice(&prog.stdout);
779                 sess.struct_err(&format!("linking with `{}` failed: {}",
780                                          pname.display(),
781                                          prog.status))
782                     .note(&format!("{:?}", &cmd))
783                     .note(&escape_string(&output))
784                     .emit();
785                 sess.abort_if_errors();
786             }
787             info!("linker stderr:\n{}", escape_string(&prog.stderr));
788             info!("linker stdout:\n{}", escape_string(&prog.stdout));
789         },
790         Err(e) => {
791             let linker_not_found = e.kind() == io::ErrorKind::NotFound;
792
793             let mut linker_error = {
794                 if linker_not_found {
795                     sess.struct_err(&format!("linker `{}` not found", pname.display()))
796                 } else {
797                     sess.struct_err(&format!("could not exec the linker `{}`", pname.display()))
798                 }
799             };
800
801             linker_error.note(&format!("{}", e));
802
803             if !linker_not_found {
804                 linker_error.note(&format!("{:?}", &cmd));
805             }
806
807             linker_error.emit();
808
809             if sess.target.target.options.is_like_msvc && linker_not_found {
810                 sess.note_without_error("the msvc targets depend on the msvc linker \
811                     but `link.exe` was not found");
812                 sess.note_without_error("please ensure that VS 2013 or VS 2015 was installed \
813                     with the Visual C++ option");
814             }
815             sess.abort_if_errors();
816         }
817     }
818
819
820     // On macOS, debuggers need this utility to get run to do some munging of
821     // the symbols. Note, though, that if the object files are being preserved
822     // for their debug information there's no need for us to run dsymutil.
823     if sess.target.target.options.is_like_osx &&
824         sess.opts.debuginfo != NoDebugInfo &&
825         !preserve_objects_for_their_debuginfo(sess)
826     {
827         match Command::new("dsymutil").arg(out_filename).output() {
828             Ok(..) => {}
829             Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
830         }
831     }
832
833     if sess.opts.target_triple == TargetTriple::from_triple("wasm32-unknown-unknown") {
834         wasm::rewrite_imports(&out_filename, &trans.crate_info.wasm_imports);
835         wasm::add_custom_sections(&out_filename,
836                                   &trans.crate_info.wasm_custom_sections);
837     }
838 }
839
840 fn exec_linker(sess: &Session, cmd: &mut Command, out_filename: &Path, tmpdir: &Path)
841     -> io::Result<Output>
842 {
843     // When attempting to spawn the linker we run a risk of blowing out the
844     // size limits for spawning a new process with respect to the arguments
845     // we pass on the command line.
846     //
847     // Here we attempt to handle errors from the OS saying "your list of
848     // arguments is too big" by reinvoking the linker again with an `@`-file
849     // that contains all the arguments. The theory is that this is then
850     // accepted on all linkers and the linker will read all its options out of
851     // there instead of looking at the command line.
852     if !cmd.very_likely_to_exceed_some_spawn_limit() {
853         match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
854             Ok(child) => {
855                 let output = child.wait_with_output();
856                 flush_linked_file(&output, out_filename)?;
857                 return output;
858             }
859             Err(ref e) if command_line_too_big(e) => {
860                 info!("command line to linker was too big: {}", e);
861             }
862             Err(e) => return Err(e)
863         }
864     }
865
866     info!("falling back to passing arguments to linker via an @-file");
867     let mut cmd2 = cmd.clone();
868     let mut args = String::new();
869     for arg in cmd2.take_args() {
870         args.push_str(&Escape {
871             arg: arg.to_str().unwrap(),
872             is_like_msvc: sess.target.target.options.is_like_msvc,
873         }.to_string());
874         args.push_str("\n");
875     }
876     let file = tmpdir.join("linker-arguments");
877     let bytes = if sess.target.target.options.is_like_msvc {
878         let mut out = vec![];
879         // start the stream with a UTF-16 BOM
880         for c in vec![0xFEFF].into_iter().chain(args.encode_utf16()) {
881             // encode in little endian
882             out.push(c as u8);
883             out.push((c >> 8) as u8);
884         }
885         out
886     } else {
887         args.into_bytes()
888     };
889     fs::write(&file, &bytes)?;
890     cmd2.arg(format!("@{}", file.display()));
891     info!("invoking linker {:?}", cmd2);
892     let output = cmd2.output();
893     flush_linked_file(&output, out_filename)?;
894     return output;
895
896     #[cfg(unix)]
897     fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
898         Ok(())
899     }
900
901     #[cfg(windows)]
902     fn flush_linked_file(command_output: &io::Result<Output>, out_filename: &Path)
903         -> io::Result<()>
904     {
905         // On Windows, under high I/O load, output buffers are sometimes not flushed,
906         // even long after process exit, causing nasty, non-reproducible output bugs.
907         //
908         // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
909         //
910         // А full writeup of the original Chrome bug can be found at
911         // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
912
913         if let &Ok(ref out) = command_output {
914             if out.status.success() {
915                 if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
916                     of.sync_all()?;
917                 }
918             }
919         }
920
921         Ok(())
922     }
923
924     #[cfg(unix)]
925     fn command_line_too_big(err: &io::Error) -> bool {
926         err.raw_os_error() == Some(::libc::E2BIG)
927     }
928
929     #[cfg(windows)]
930     fn command_line_too_big(err: &io::Error) -> bool {
931         const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
932         err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
933     }
934
935     struct Escape<'a> {
936         arg: &'a str,
937         is_like_msvc: bool,
938     }
939
940     impl<'a> fmt::Display for Escape<'a> {
941         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
942             if self.is_like_msvc {
943                 // This is "documented" at
944                 // https://msdn.microsoft.com/en-us/library/4xdcbak7.aspx
945                 //
946                 // Unfortunately there's not a great specification of the
947                 // syntax I could find online (at least) but some local
948                 // testing showed that this seemed sufficient-ish to catch
949                 // at least a few edge cases.
950                 write!(f, "\"")?;
951                 for c in self.arg.chars() {
952                     match c {
953                         '"' => write!(f, "\\{}", c)?,
954                         c => write!(f, "{}", c)?,
955                     }
956                 }
957                 write!(f, "\"")?;
958             } else {
959                 // This is documented at https://linux.die.net/man/1/ld, namely:
960                 //
961                 // > Options in file are separated by whitespace. A whitespace
962                 // > character may be included in an option by surrounding the
963                 // > entire option in either single or double quotes. Any
964                 // > character (including a backslash) may be included by
965                 // > prefixing the character to be included with a backslash.
966                 //
967                 // We put an argument on each line, so all we need to do is
968                 // ensure the line is interpreted as one whole argument.
969                 for c in self.arg.chars() {
970                     match c {
971                         '\\' |
972                         ' ' => write!(f, "\\{}", c)?,
973                         c => write!(f, "{}", c)?,
974                     }
975                 }
976             }
977             Ok(())
978         }
979     }
980 }
981
982 fn link_args(cmd: &mut Linker,
983              sess: &Session,
984              crate_type: config::CrateType,
985              tmpdir: &Path,
986              out_filename: &Path,
987              trans: &CrateTranslation) {
988
989     // The default library location, we need this to find the runtime.
990     // The location of crates will be determined as needed.
991     let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
992
993     // target descriptor
994     let t = &sess.target.target;
995
996     cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
997     for obj in trans.modules.iter().filter_map(|m| m.object.as_ref()) {
998         cmd.add_object(obj);
999     }
1000     cmd.output_filename(out_filename);
1001
1002     if crate_type == config::CrateTypeExecutable &&
1003        sess.target.target.options.is_like_windows {
1004         if let Some(ref s) = trans.windows_subsystem {
1005             cmd.subsystem(s);
1006         }
1007     }
1008
1009     // If we're building a dynamic library then some platforms need to make sure
1010     // that all symbols are exported correctly from the dynamic library.
1011     if crate_type != config::CrateTypeExecutable ||
1012        sess.target.target.options.is_like_emscripten {
1013         cmd.export_symbols(tmpdir, crate_type);
1014     }
1015
1016     // When linking a dynamic library, we put the metadata into a section of the
1017     // executable. This metadata is in a separate object file from the main
1018     // object file, so we link that in here.
1019     if crate_type == config::CrateTypeDylib ||
1020        crate_type == config::CrateTypeProcMacro {
1021         if let Some(obj) = trans.metadata_module.object.as_ref() {
1022             cmd.add_object(obj);
1023         }
1024     }
1025
1026     let obj = trans.allocator_module
1027         .as_ref()
1028         .and_then(|m| m.object.as_ref());
1029     if let Some(obj) = obj {
1030         cmd.add_object(obj);
1031     }
1032
1033     // Try to strip as much out of the generated object by removing unused
1034     // sections if possible. See more comments in linker.rs
1035     if !sess.opts.cg.link_dead_code {
1036         let keep_metadata = crate_type == config::CrateTypeDylib;
1037         cmd.gc_sections(keep_metadata);
1038     }
1039
1040     let used_link_args = &trans.crate_info.link_args;
1041
1042     if crate_type == config::CrateTypeExecutable {
1043         let mut position_independent_executable = false;
1044
1045         if t.options.position_independent_executables {
1046             let empty_vec = Vec::new();
1047             let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
1048             let more_args = &sess.opts.cg.link_arg;
1049             let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
1050
1051             if get_reloc_model(sess) == llvm::RelocMode::PIC
1052                 && !sess.crt_static() && !args.any(|x| *x == "-static") {
1053                 position_independent_executable = true;
1054             }
1055         }
1056
1057         if position_independent_executable {
1058             cmd.position_independent_executable();
1059         } else {
1060             // recent versions of gcc can be configured to generate position
1061             // independent executables by default. We have to pass -no-pie to
1062             // explicitly turn that off. Not applicable to ld.
1063             if sess.target.target.options.linker_is_gnu
1064                 && sess.linker_flavor() != LinkerFlavor::Ld {
1065                 cmd.no_position_independent_executable();
1066             }
1067         }
1068     }
1069
1070     let relro_level = match sess.opts.debugging_opts.relro_level {
1071         Some(level) => level,
1072         None => t.options.relro_level,
1073     };
1074     match relro_level {
1075         RelroLevel::Full => {
1076             cmd.full_relro();
1077         },
1078         RelroLevel::Partial => {
1079             cmd.partial_relro();
1080         },
1081         RelroLevel::Off => {
1082             cmd.no_relro();
1083         },
1084         RelroLevel::None => {
1085         },
1086     }
1087
1088     // Pass optimization flags down to the linker.
1089     cmd.optimize();
1090
1091     // Pass debuginfo flags down to the linker.
1092     cmd.debuginfo();
1093
1094     // We want to prevent the compiler from accidentally leaking in any system
1095     // libraries, so we explicitly ask gcc to not link to any libraries by
1096     // default. Note that this does not happen for windows because windows pulls
1097     // in some large number of libraries and I couldn't quite figure out which
1098     // subset we wanted.
1099     if t.options.no_default_libraries {
1100         cmd.no_default_libraries();
1101     }
1102
1103     // Take careful note of the ordering of the arguments we pass to the linker
1104     // here. Linkers will assume that things on the left depend on things to the
1105     // right. Things on the right cannot depend on things on the left. This is
1106     // all formally implemented in terms of resolving symbols (libs on the right
1107     // resolve unknown symbols of libs on the left, but not vice versa).
1108     //
1109     // For this reason, we have organized the arguments we pass to the linker as
1110     // such:
1111     //
1112     //  1. The local object that LLVM just generated
1113     //  2. Local native libraries
1114     //  3. Upstream rust libraries
1115     //  4. Upstream native libraries
1116     //
1117     // The rationale behind this ordering is that those items lower down in the
1118     // list can't depend on items higher up in the list. For example nothing can
1119     // depend on what we just generated (e.g. that'd be a circular dependency).
1120     // Upstream rust libraries are not allowed to depend on our local native
1121     // libraries as that would violate the structure of the DAG, in that
1122     // scenario they are required to link to them as well in a shared fashion.
1123     //
1124     // Note that upstream rust libraries may contain native dependencies as
1125     // well, but they also can't depend on what we just started to add to the
1126     // link line. And finally upstream native libraries can't depend on anything
1127     // in this DAG so far because they're only dylibs and dylibs can only depend
1128     // on other dylibs (e.g. other native deps).
1129     add_local_native_libraries(cmd, sess, trans);
1130     add_upstream_rust_crates(cmd, sess, trans, crate_type, tmpdir);
1131     add_upstream_native_libraries(cmd, sess, trans, crate_type);
1132
1133     // Tell the linker what we're doing.
1134     if crate_type != config::CrateTypeExecutable {
1135         cmd.build_dylib(out_filename);
1136     }
1137     if crate_type == config::CrateTypeExecutable && sess.crt_static() {
1138         cmd.build_static_executable();
1139     }
1140
1141     if sess.opts.debugging_opts.pgo_gen.is_some() {
1142         cmd.pgo_gen();
1143     }
1144
1145     // FIXME (#2397): At some point we want to rpath our guesses as to
1146     // where extern libraries might live, based on the
1147     // addl_lib_search_paths
1148     if sess.opts.cg.rpath {
1149         let sysroot = sess.sysroot();
1150         let target_triple = sess.opts.target_triple.triple();
1151         let mut get_install_prefix_lib_path = || {
1152             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1153             let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1154             let mut path = PathBuf::from(install_prefix);
1155             path.push(&tlib);
1156
1157             path
1158         };
1159         let mut rpath_config = RPathConfig {
1160             used_crates: &trans.crate_info.used_crates_dynamic,
1161             out_filename: out_filename.to_path_buf(),
1162             has_rpath: sess.target.target.options.has_rpath,
1163             is_like_osx: sess.target.target.options.is_like_osx,
1164             linker_is_gnu: sess.target.target.options.linker_is_gnu,
1165             get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1166         };
1167         cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1168     }
1169
1170     // Finally add all the linker arguments provided on the command line along
1171     // with any #[link_args] attributes found inside the crate
1172     if let Some(ref args) = sess.opts.cg.link_args {
1173         cmd.args(args);
1174     }
1175     cmd.args(&sess.opts.cg.link_arg);
1176     cmd.args(&used_link_args);
1177 }
1178
1179 // # Native library linking
1180 //
1181 // User-supplied library search paths (-L on the command line). These are
1182 // the same paths used to find Rust crates, so some of them may have been
1183 // added already by the previous crate linking code. This only allows them
1184 // to be found at compile time so it is still entirely up to outside
1185 // forces to make sure that library can be found at runtime.
1186 //
1187 // Also note that the native libraries linked here are only the ones located
1188 // in the current crate. Upstream crates with native library dependencies
1189 // may have their native library pulled in above.
1190 fn add_local_native_libraries(cmd: &mut Linker,
1191                               sess: &Session,
1192                               trans: &CrateTranslation) {
1193     sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1194         match k {
1195             PathKind::Framework => { cmd.framework_path(path); }
1196             _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1197         }
1198     });
1199
1200     let relevant_libs = trans.crate_info.used_libraries.iter().filter(|l| {
1201         relevant_lib(sess, l)
1202     });
1203
1204     let search_path = archive_search_paths(sess);
1205     for lib in relevant_libs {
1206         match lib.kind {
1207             NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1208             NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1209             NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&lib.name.as_str()),
1210             NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&lib.name.as_str(),
1211                                                                         &search_path)
1212         }
1213     }
1214 }
1215
1216 // # Rust Crate linking
1217 //
1218 // Rust crates are not considered at all when creating an rlib output. All
1219 // dependencies will be linked when producing the final output (instead of
1220 // the intermediate rlib version)
1221 fn add_upstream_rust_crates(cmd: &mut Linker,
1222                             sess: &Session,
1223                             trans: &CrateTranslation,
1224                             crate_type: config::CrateType,
1225                             tmpdir: &Path) {
1226     // All of the heavy lifting has previously been accomplished by the
1227     // dependency_format module of the compiler. This is just crawling the
1228     // output of that module, adding crates as necessary.
1229     //
1230     // Linking to a rlib involves just passing it to the linker (the linker
1231     // will slurp up the object files inside), and linking to a dynamic library
1232     // involves just passing the right -l flag.
1233
1234     let formats = sess.dependency_formats.borrow();
1235     let data = formats.get(&crate_type).unwrap();
1236
1237     // Invoke get_used_crates to ensure that we get a topological sorting of
1238     // crates.
1239     let deps = &trans.crate_info.used_crates_dynamic;
1240
1241     // There's a few internal crates in the standard library (aka libcore and
1242     // libstd) which actually have a circular dependence upon one another. This
1243     // currently arises through "weak lang items" where libcore requires things
1244     // like `rust_begin_unwind` but libstd ends up defining it. To get this
1245     // circular dependence to work correctly in all situations we'll need to be
1246     // sure to correctly apply the `--start-group` and `--end-group` options to
1247     // GNU linkers, otherwise if we don't use any other symbol from the standard
1248     // library it'll get discarded and the whole application won't link.
1249     //
1250     // In this loop we're calculating the `group_end`, after which crate to
1251     // pass `--end-group` and `group_start`, before which crate to pass
1252     // `--start-group`. We currently do this by passing `--end-group` after
1253     // the first crate (when iterating backwards) that requires a lang item
1254     // defined somewhere else. Once that's set then when we've defined all the
1255     // necessary lang items we'll pass `--start-group`.
1256     //
1257     // Note that this isn't amazing logic for now but it should do the trick
1258     // for the current implementation of the standard library.
1259     let mut group_end = None;
1260     let mut group_start = None;
1261     let mut end_with = FxHashSet();
1262     let info = &trans.crate_info;
1263     for &(cnum, _) in deps.iter().rev() {
1264         if let Some(missing) = info.missing_lang_items.get(&cnum) {
1265             end_with.extend(missing.iter().cloned());
1266             if end_with.len() > 0 && group_end.is_none() {
1267                 group_end = Some(cnum);
1268             }
1269         }
1270         end_with.retain(|item| info.lang_item_to_crate.get(item) != Some(&cnum));
1271         if end_with.len() == 0 && group_end.is_some() {
1272             group_start = Some(cnum);
1273             break
1274         }
1275     }
1276
1277     // If we didn't end up filling in all lang items from upstream crates then
1278     // we'll be filling it in with our crate. This probably means we're the
1279     // standard library itself, so skip this for now.
1280     if group_end.is_some() && group_start.is_none() {
1281         group_end = None;
1282     }
1283
1284     let mut compiler_builtins = None;
1285
1286     for &(cnum, _) in deps.iter() {
1287         if group_start == Some(cnum) {
1288             cmd.group_start();
1289         }
1290
1291         // We may not pass all crates through to the linker. Some crates may
1292         // appear statically in an existing dylib, meaning we'll pick up all the
1293         // symbols from the dylib.
1294         let src = &trans.crate_info.used_crate_source[&cnum];
1295         match data[cnum.as_usize() - 1] {
1296             _ if trans.crate_info.profiler_runtime == Some(cnum) => {
1297                 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1298             }
1299             _ if trans.crate_info.sanitizer_runtime == Some(cnum) => {
1300                 link_sanitizer_runtime(cmd, sess, trans, tmpdir, cnum);
1301             }
1302             // compiler-builtins are always placed last to ensure that they're
1303             // linked correctly.
1304             _ if trans.crate_info.compiler_builtins == Some(cnum) => {
1305                 assert!(compiler_builtins.is_none());
1306                 compiler_builtins = Some(cnum);
1307             }
1308             Linkage::NotLinked |
1309             Linkage::IncludedFromDylib => {}
1310             Linkage::Static => {
1311                 add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1312             }
1313             Linkage::Dynamic => {
1314                 add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0)
1315             }
1316         }
1317
1318         if group_end == Some(cnum) {
1319             cmd.group_end();
1320         }
1321     }
1322
1323     // compiler-builtins are always placed last to ensure that they're
1324     // linked correctly.
1325     // We must always link the `compiler_builtins` crate statically. Even if it
1326     // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
1327     // is used)
1328     if let Some(cnum) = compiler_builtins {
1329         add_static_crate(cmd, sess, trans, tmpdir, crate_type, cnum);
1330     }
1331
1332     // Converts a library file-stem into a cc -l argument
1333     fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1334         if stem.starts_with("lib") && !config.target.options.is_like_windows {
1335             &stem[3..]
1336         } else {
1337             stem
1338         }
1339     }
1340
1341     // We must link the sanitizer runtime using -Wl,--whole-archive but since
1342     // it's packed in a .rlib, it contains stuff that are not objects that will
1343     // make the linker error. So we must remove those bits from the .rlib before
1344     // linking it.
1345     fn link_sanitizer_runtime(cmd: &mut Linker,
1346                               sess: &Session,
1347                               trans: &CrateTranslation,
1348                               tmpdir: &Path,
1349                               cnum: CrateNum) {
1350         let src = &trans.crate_info.used_crate_source[&cnum];
1351         let cratepath = &src.rlib.as_ref().unwrap().0;
1352
1353         if sess.target.target.options.is_like_osx {
1354             // On Apple platforms, the sanitizer is always built as a dylib, and
1355             // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1356             // rpath to the library as well (the rpath should be absolute, see
1357             // PR #41352 for details).
1358             //
1359             // FIXME: Remove this logic into librustc_*san once Cargo supports it
1360             let rpath = cratepath.parent().unwrap();
1361             let rpath = rpath.to_str().expect("non-utf8 component in path");
1362             cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1363         }
1364
1365         let dst = tmpdir.join(cratepath.file_name().unwrap());
1366         let cfg = archive_config(sess, &dst, Some(cratepath));
1367         let mut archive = ArchiveBuilder::new(cfg);
1368         archive.update_symbols();
1369
1370         for f in archive.src_files() {
1371             if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1372                 archive.remove_file(&f);
1373                 continue
1374             }
1375         }
1376
1377         archive.build();
1378
1379         cmd.link_whole_rlib(&dst);
1380     }
1381
1382     // Adds the static "rlib" versions of all crates to the command line.
1383     // There's a bit of magic which happens here specifically related to LTO and
1384     // dynamic libraries. Specifically:
1385     //
1386     // * For LTO, we remove upstream object files.
1387     // * For dylibs we remove metadata and bytecode from upstream rlibs
1388     //
1389     // When performing LTO, almost(*) all of the bytecode from the upstream
1390     // libraries has already been included in our object file output. As a
1391     // result we need to remove the object files in the upstream libraries so
1392     // the linker doesn't try to include them twice (or whine about duplicate
1393     // symbols). We must continue to include the rest of the rlib, however, as
1394     // it may contain static native libraries which must be linked in.
1395     //
1396     // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1397     // their bytecode wasn't included. The object files in those libraries must
1398     // still be passed to the linker.
1399     //
1400     // When making a dynamic library, linkers by default don't include any
1401     // object files in an archive if they're not necessary to resolve the link.
1402     // We basically want to convert the archive (rlib) to a dylib, though, so we
1403     // *do* want everything included in the output, regardless of whether the
1404     // linker thinks it's needed or not. As a result we must use the
1405     // --whole-archive option (or the platform equivalent). When using this
1406     // option the linker will fail if there are non-objects in the archive (such
1407     // as our own metadata and/or bytecode). All in all, for rlibs to be
1408     // entirely included in dylibs, we need to remove all non-object files.
1409     //
1410     // Note, however, that if we're not doing LTO or we're not producing a dylib
1411     // (aka we're making an executable), we can just pass the rlib blindly to
1412     // the linker (fast) because it's fine if it's not actually included as
1413     // we're at the end of the dependency chain.
1414     fn add_static_crate(cmd: &mut Linker,
1415                         sess: &Session,
1416                         trans: &CrateTranslation,
1417                         tmpdir: &Path,
1418                         crate_type: config::CrateType,
1419                         cnum: CrateNum) {
1420         let src = &trans.crate_info.used_crate_source[&cnum];
1421         let cratepath = &src.rlib.as_ref().unwrap().0;
1422
1423         // See the comment above in `link_staticlib` and `link_rlib` for why if
1424         // there's a static library that's not relevant we skip all object
1425         // files.
1426         let native_libs = &trans.crate_info.native_libraries[&cnum];
1427         let skip_native = native_libs.iter().any(|lib| {
1428             lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1429         });
1430
1431         if (!is_full_lto_enabled(sess) ||
1432             ignored_for_lto(sess, &trans.crate_info, cnum)) &&
1433            crate_type != config::CrateTypeDylib &&
1434            !skip_native {
1435             cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1436             return
1437         }
1438
1439         let dst = tmpdir.join(cratepath.file_name().unwrap());
1440         let name = cratepath.file_name().unwrap().to_str().unwrap();
1441         let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1442
1443         time(sess, &format!("altering {}.rlib", name), || {
1444             let cfg = archive_config(sess, &dst, Some(cratepath));
1445             let mut archive = ArchiveBuilder::new(cfg);
1446             archive.update_symbols();
1447
1448             let mut any_objects = false;
1449             for f in archive.src_files() {
1450                 if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME {
1451                     archive.remove_file(&f);
1452                     continue
1453                 }
1454
1455                 let canonical = f.replace("-", "_");
1456                 let canonical_name = name.replace("-", "_");
1457
1458                 // Look for `.rcgu.o` at the end of the filename to conclude
1459                 // that this is a Rust-related object file.
1460                 fn looks_like_rust(s: &str) -> bool {
1461                     let path = Path::new(s);
1462                     let ext = path.extension().and_then(|s| s.to_str());
1463                     if ext != Some(OutputType::Object.extension()) {
1464                         return false
1465                     }
1466                     let ext2 = path.file_stem()
1467                         .and_then(|s| Path::new(s).extension())
1468                         .and_then(|s| s.to_str());
1469                     ext2 == Some(RUST_CGU_EXT)
1470                 }
1471
1472                 let is_rust_object =
1473                     canonical.starts_with(&canonical_name) &&
1474                     looks_like_rust(&f);
1475
1476                 // If we've been requested to skip all native object files
1477                 // (those not generated by the rust compiler) then we can skip
1478                 // this file. See above for why we may want to do this.
1479                 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1480
1481                 // If we're performing LTO and this is a rust-generated object
1482                 // file, then we don't need the object file as it's part of the
1483                 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1484                 // though, so we let that object file slide.
1485                 let skip_because_lto = is_full_lto_enabled(sess) &&
1486                     is_rust_object &&
1487                     (sess.target.target.options.no_builtins ||
1488                      !trans.crate_info.is_no_builtins.contains(&cnum));
1489
1490                 if skip_because_cfg_say_so || skip_because_lto {
1491                     archive.remove_file(&f);
1492                 } else {
1493                     any_objects = true;
1494                 }
1495             }
1496
1497             if !any_objects {
1498                 return
1499             }
1500             archive.build();
1501
1502             // If we're creating a dylib, then we need to include the
1503             // whole of each object in our archive into that artifact. This is
1504             // because a `dylib` can be reused as an intermediate artifact.
1505             //
1506             // Note, though, that we don't want to include the whole of a
1507             // compiler-builtins crate (e.g. compiler-rt) because it'll get
1508             // repeatedly linked anyway.
1509             if crate_type == config::CrateTypeDylib &&
1510                 trans.crate_info.compiler_builtins != Some(cnum) {
1511                 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1512             } else {
1513                 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1514             }
1515         });
1516     }
1517
1518     // Same thing as above, but for dynamic crates instead of static crates.
1519     fn add_dynamic_crate(cmd: &mut Linker, sess: &Session, cratepath: &Path) {
1520         // If we're performing LTO, then it should have been previously required
1521         // that all upstream rust dependencies were available in an rlib format.
1522         assert!(!is_full_lto_enabled(sess));
1523
1524         // Just need to tell the linker about where the library lives and
1525         // what its name is
1526         let parent = cratepath.parent();
1527         if let Some(dir) = parent {
1528             cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1529         }
1530         let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1531         cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1532                             parent.unwrap_or(Path::new("")));
1533     }
1534 }
1535
1536 // Link in all of our upstream crates' native dependencies. Remember that
1537 // all of these upstream native dependencies are all non-static
1538 // dependencies. We've got two cases then:
1539 //
1540 // 1. The upstream crate is an rlib. In this case we *must* link in the
1541 // native dependency because the rlib is just an archive.
1542 //
1543 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1544 // have the dependency present on the system somewhere. Thus, we don't
1545 // gain a whole lot from not linking in the dynamic dependency to this
1546 // crate as well.
1547 //
1548 // The use case for this is a little subtle. In theory the native
1549 // dependencies of a crate are purely an implementation detail of the crate
1550 // itself, but the problem arises with generic and inlined functions. If a
1551 // generic function calls a native function, then the generic function must
1552 // be instantiated in the target crate, meaning that the native symbol must
1553 // also be resolved in the target crate.
1554 fn add_upstream_native_libraries(cmd: &mut Linker,
1555                                  sess: &Session,
1556                                  trans: &CrateTranslation,
1557                                  crate_type: config::CrateType) {
1558     // Be sure to use a topological sorting of crates because there may be
1559     // interdependencies between native libraries. When passing -nodefaultlibs,
1560     // for example, almost all native libraries depend on libc, so we have to
1561     // make sure that's all the way at the right (liblibc is near the base of
1562     // the dependency chain).
1563     //
1564     // This passes RequireStatic, but the actual requirement doesn't matter,
1565     // we're just getting an ordering of crate numbers, we're not worried about
1566     // the paths.
1567     let formats = sess.dependency_formats.borrow();
1568     let data = formats.get(&crate_type).unwrap();
1569
1570     let crates = &trans.crate_info.used_crates_static;
1571     for &(cnum, _) in crates {
1572         for lib in trans.crate_info.native_libraries[&cnum].iter() {
1573             if !relevant_lib(sess, &lib) {
1574                 continue
1575             }
1576             match lib.kind {
1577                 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1578                 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1579                 NativeLibraryKind::NativeStaticNobundle => {
1580                     // Link "static-nobundle" native libs only if the crate they originate from
1581                     // is being linked statically to the current crate.  If it's linked dynamically
1582                     // or is an rlib already included via some other dylib crate, the symbols from
1583                     // native libs will have already been included in that dylib.
1584                     if data[cnum.as_usize() - 1] == Linkage::Static {
1585                         cmd.link_staticlib(&lib.name.as_str())
1586                     }
1587                 },
1588                 // ignore statically included native libraries here as we've
1589                 // already included them when we included the rust library
1590                 // previously
1591                 NativeLibraryKind::NativeStatic => {}
1592             }
1593         }
1594     }
1595 }
1596
1597 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1598     match lib.cfg {
1599         Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
1600         None => true,
1601     }
1602 }
1603
1604 fn is_full_lto_enabled(sess: &Session) -> bool {
1605     match sess.lto() {
1606         Lto::Yes |
1607         Lto::Thin |
1608         Lto::Fat => true,
1609         Lto::No |
1610         Lto::ThinLocal => false,
1611     }
1612 }