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