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