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