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