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