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