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