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