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