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