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