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