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