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