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