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