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