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