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