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