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