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