rustc_codegen_ssa/back/
link.rs

1mod raw_dylib;
2
3use std::collections::BTreeSet;
4use std::ffi::OsString;
5use std::fs::{File, OpenOptions, read};
6use std::io::{BufReader, BufWriter, Write};
7use std::ops::{ControlFlow, Deref};
8use std::path::{Path, PathBuf};
9use std::process::{Output, Stdio};
10use std::{env, fmt, fs, io, mem, str};
11
12use cc::windows_registry;
13use itertools::Itertools;
14use regex::Regex;
15use rustc_arena::TypedArena;
16use rustc_ast::CRATE_NODE_ID;
17use rustc_attr_parsing::{ShouldEmit, eval_config_entry};
18use rustc_data_structures::fx::FxIndexSet;
19use rustc_data_structures::memmap::Mmap;
20use rustc_data_structures::temp_dir::MaybeTempDir;
21use rustc_errors::{DiagCtxtHandle, LintDiagnostic};
22use rustc_fs_util::{TempDirBuilder, fix_windows_verbatim_for_gcc, try_canonicalize};
23use rustc_hir::attrs::NativeLibKind;
24use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
25use rustc_macros::LintDiagnostic;
26use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
27use rustc_metadata::{
28    EncodedMetadata, NativeLibSearchFallback, find_native_static_library,
29    walk_native_lib_search_dirs,
30};
31use rustc_middle::bug;
32use rustc_middle::lint::lint_level;
33use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
34use rustc_middle::middle::dependency_format::Linkage;
35use rustc_middle::middle::exported_symbols::SymbolExportKind;
36use rustc_session::config::{
37    self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames,
38    OutputType, PrintKind, SplitDwarfKind, Strip,
39};
40use rustc_session::lint::builtin::LINKER_MESSAGES;
41use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
42use rustc_session::search_paths::PathKind;
43/// For all the linkers we support, and information they might
44/// need out of the shared crate context before we get rid of it.
45use rustc_session::{Session, filesearch};
46use rustc_span::Symbol;
47use rustc_target::spec::crt_objects::CrtObjects;
48use rustc_target::spec::{
49    BinaryFormat, Cc, LinkOutputKind, LinkSelfContainedComponents, LinkSelfContainedDefault,
50    LinkerFeatures, LinkerFlavor, LinkerFlavorCli, Lld, PanicStrategy, RelocModel, RelroLevel,
51    SanitizerSet, SplitDebuginfo,
52};
53use tracing::{debug, info, warn};
54
55use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
56use super::command::Command;
57use super::linker::{self, Linker};
58use super::metadata::{MetadataPosition, create_wrapper_file};
59use super::rpath::{self, RPathConfig};
60use super::{apple, versioned_llvm_target};
61use crate::{
62    CodegenResults, CompiledModule, CrateInfo, NativeLib, errors, looks_like_rust_object_file,
63};
64
65pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
66    if let Err(e) = fs::remove_file(path) {
67        if e.kind() != io::ErrorKind::NotFound {
68            dcx.err(format!("failed to remove {}: {}", path.display(), e));
69        }
70    }
71}
72
73/// Performs the linkage portion of the compilation phase. This will generate all
74/// of the requested outputs for this compilation session.
75pub fn link_binary(
76    sess: &Session,
77    archive_builder_builder: &dyn ArchiveBuilderBuilder,
78    codegen_results: CodegenResults,
79    metadata: EncodedMetadata,
80    outputs: &OutputFilenames,
81) {
82    let _timer = sess.timer("link_binary");
83    let output_metadata = sess.opts.output_types.contains_key(&OutputType::Metadata);
84    let mut tempfiles_for_stdout_output: Vec<PathBuf> = Vec::new();
85    for &crate_type in &codegen_results.crate_info.crate_types {
86        // Ignore executable crates if we have -Z no-codegen, as they will error.
87        if (sess.opts.unstable_opts.no_codegen || !sess.opts.output_types.should_codegen())
88            && !output_metadata
89            && crate_type == CrateType::Executable
90        {
91            continue;
92        }
93
94        if invalid_output_for_target(sess, crate_type) {
95            bug!("invalid output type `{:?}` for target `{}`", crate_type, sess.opts.target_triple);
96        }
97
98        sess.time("link_binary_check_files_are_writeable", || {
99            for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
100                check_file_is_writeable(obj, sess);
101            }
102        });
103
104        if outputs.outputs.should_link() {
105            let tmpdir = TempDirBuilder::new()
106                .prefix("rustc")
107                .tempdir()
108                .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
109            let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
110            let output = out_filename(
111                sess,
112                crate_type,
113                outputs,
114                codegen_results.crate_info.local_crate_name,
115            );
116            let crate_name = format!("{}", codegen_results.crate_info.local_crate_name);
117            let out_filename = output.file_for_writing(
118                outputs,
119                OutputType::Exe,
120                &crate_name,
121                sess.invocation_temp.as_deref(),
122            );
123            match crate_type {
124                CrateType::Rlib => {
125                    let _timer = sess.timer("link_rlib");
126                    info!("preparing rlib to {:?}", out_filename);
127                    link_rlib(
128                        sess,
129                        archive_builder_builder,
130                        &codegen_results,
131                        &metadata,
132                        RlibFlavor::Normal,
133                        &path,
134                    )
135                    .build(&out_filename);
136                }
137                CrateType::Staticlib => {
138                    link_staticlib(
139                        sess,
140                        archive_builder_builder,
141                        &codegen_results,
142                        &metadata,
143                        &out_filename,
144                        &path,
145                    );
146                }
147                _ => {
148                    link_natively(
149                        sess,
150                        archive_builder_builder,
151                        crate_type,
152                        &out_filename,
153                        &codegen_results,
154                        &metadata,
155                        path.as_ref(),
156                    );
157                }
158            }
159            if sess.opts.json_artifact_notifications {
160                sess.dcx().emit_artifact_notification(&out_filename, "link");
161            }
162
163            if sess.prof.enabled()
164                && let Some(artifact_name) = out_filename.file_name()
165            {
166                // Record size for self-profiling
167                let file_size = std::fs::metadata(&out_filename).map(|m| m.len()).unwrap_or(0);
168
169                sess.prof.artifact_size(
170                    "linked_artifact",
171                    artifact_name.to_string_lossy(),
172                    file_size,
173                );
174            }
175
176            if sess.target.binary_format == BinaryFormat::Elf {
177                if let Err(err) = warn_if_linked_with_gold(sess, &out_filename) {
178                    info!(?err, "Error while checking if gold was the linker");
179                }
180            }
181
182            if output.is_stdout() {
183                if output.is_tty() {
184                    sess.dcx().emit_err(errors::BinaryOutputToTty {
185                        shorthand: OutputType::Exe.shorthand(),
186                    });
187                } else if let Err(e) = copy_to_stdout(&out_filename) {
188                    sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
189                }
190                tempfiles_for_stdout_output.push(out_filename);
191            }
192        }
193    }
194
195    // Remove the temporary object file and metadata if we aren't saving temps.
196    sess.time("link_binary_remove_temps", || {
197        // If the user requests that temporaries are saved, don't delete any.
198        if sess.opts.cg.save_temps {
199            return;
200        }
201
202        let maybe_remove_temps_from_module =
203            |preserve_objects: bool, preserve_dwarf_objects: bool, module: &CompiledModule| {
204                if !preserve_objects && let Some(ref obj) = module.object {
205                    ensure_removed(sess.dcx(), obj);
206                }
207
208                if !preserve_dwarf_objects && let Some(ref dwo_obj) = module.dwarf_object {
209                    ensure_removed(sess.dcx(), dwo_obj);
210                }
211            };
212
213        let remove_temps_from_module =
214            |module: &CompiledModule| maybe_remove_temps_from_module(false, false, module);
215
216        // Otherwise, always remove the allocator module temporaries.
217        if let Some(ref allocator_module) = codegen_results.allocator_module {
218            remove_temps_from_module(allocator_module);
219        }
220
221        // Remove the temporary files if output goes to stdout
222        for temp in tempfiles_for_stdout_output {
223            ensure_removed(sess.dcx(), &temp);
224        }
225
226        // If no requested outputs require linking, then the object temporaries should
227        // be kept.
228        if !sess.opts.output_types.should_link() {
229            return;
230        }
231
232        // Potentially keep objects for their debuginfo.
233        let (preserve_objects, preserve_dwarf_objects) = preserve_objects_for_their_debuginfo(sess);
234        debug!(?preserve_objects, ?preserve_dwarf_objects);
235
236        for module in &codegen_results.modules {
237            maybe_remove_temps_from_module(preserve_objects, preserve_dwarf_objects, module);
238        }
239    });
240}
241
242// Crate type is not passed when calculating the dylibs to include for LTO. In that case all
243// crate types must use the same dependency formats.
244pub fn each_linked_rlib(
245    info: &CrateInfo,
246    crate_type: Option<CrateType>,
247    f: &mut dyn FnMut(CrateNum, &Path),
248) -> Result<(), errors::LinkRlibError> {
249    let fmts = if let Some(crate_type) = crate_type {
250        let Some(fmts) = info.dependency_formats.get(&crate_type) else {
251            return Err(errors::LinkRlibError::MissingFormat);
252        };
253
254        fmts
255    } else {
256        let mut dep_formats = info.dependency_formats.iter();
257        let (ty1, list1) = dep_formats.next().ok_or(errors::LinkRlibError::MissingFormat)?;
258        if let Some((ty2, list2)) = dep_formats.find(|(_, list2)| list1 != *list2) {
259            return Err(errors::LinkRlibError::IncompatibleDependencyFormats {
260                ty1: format!("{ty1:?}"),
261                ty2: format!("{ty2:?}"),
262                list1: format!("{list1:?}"),
263                list2: format!("{list2:?}"),
264            });
265        }
266        list1
267    };
268
269    let used_dep_crates = info.used_crates.iter();
270    for &cnum in used_dep_crates {
271        match fmts.get(cnum) {
272            Some(&Linkage::NotLinked | &Linkage::Dynamic | &Linkage::IncludedFromDylib) => continue,
273            Some(_) => {}
274            None => return Err(errors::LinkRlibError::MissingFormat),
275        }
276        let crate_name = info.crate_name[&cnum];
277        let used_crate_source = &info.used_crate_source[&cnum];
278        if let Some((path, _)) = &used_crate_source.rlib {
279            f(cnum, path);
280        } else if used_crate_source.rmeta.is_some() {
281            return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
282        } else {
283            return Err(errors::LinkRlibError::NotFound { crate_name });
284        }
285    }
286    Ok(())
287}
288
289/// Create an 'rlib'.
290///
291/// An rlib in its current incarnation is essentially a renamed .a file (with "dummy" object files).
292/// The rlib primarily contains the object file of the crate, but it also some of the object files
293/// from native libraries.
294fn link_rlib<'a>(
295    sess: &'a Session,
296    archive_builder_builder: &dyn ArchiveBuilderBuilder,
297    codegen_results: &CodegenResults,
298    metadata: &EncodedMetadata,
299    flavor: RlibFlavor,
300    tmpdir: &MaybeTempDir,
301) -> Box<dyn ArchiveBuilder + 'a> {
302    let mut ab = archive_builder_builder.new_archive_builder(sess);
303
304    let trailing_metadata = match flavor {
305        RlibFlavor::Normal => {
306            let (metadata, metadata_position) =
307                create_wrapper_file(sess, ".rmeta".to_string(), metadata.stub_or_full());
308            let metadata = emit_wrapper_file(sess, &metadata, tmpdir.as_ref(), METADATA_FILENAME);
309            match metadata_position {
310                MetadataPosition::First => {
311                    // Most of the time metadata in rlib files is wrapped in a "dummy" object
312                    // file for the target platform so the rlib can be processed entirely by
313                    // normal linkers for the platform. Sometimes this is not possible however.
314                    // If it is possible however, placing the metadata object first improves
315                    // performance of getting metadata from rlibs.
316                    ab.add_file(&metadata);
317                    None
318                }
319                MetadataPosition::Last => Some(metadata),
320            }
321        }
322
323        RlibFlavor::StaticlibBase => None,
324    };
325
326    for m in &codegen_results.modules {
327        if let Some(obj) = m.object.as_ref() {
328            ab.add_file(obj);
329        }
330
331        if let Some(dwarf_obj) = m.dwarf_object.as_ref() {
332            ab.add_file(dwarf_obj);
333        }
334    }
335
336    match flavor {
337        RlibFlavor::Normal => {}
338        RlibFlavor::StaticlibBase => {
339            let obj = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref());
340            if let Some(obj) = obj {
341                ab.add_file(obj);
342            }
343        }
344    }
345
346    // Used if packed_bundled_libs flag enabled.
347    let mut packed_bundled_libs = Vec::new();
348
349    // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
350    // we may not be configured to actually include a static library if we're
351    // adding it here. That's because later when we consume this rlib we'll
352    // decide whether we actually needed the static library or not.
353    //
354    // To do this "correctly" we'd need to keep track of which libraries added
355    // which object files to the archive. We don't do that here, however. The
356    // #[link(cfg(..))] feature is unstable, though, and only intended to get
357    // liblibc working. In that sense the check below just indicates that if
358    // there are any libraries we want to omit object files for at link time we
359    // just exclude all custom object files.
360    //
361    // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
362    // feature then we'll need to figure out how to record what objects were
363    // loaded from the libraries found here and then encode that into the
364    // metadata of the rlib we're generating somehow.
365    for lib in codegen_results.crate_info.used_libraries.iter() {
366        let NativeLibKind::Static { bundle: None | Some(true), .. } = lib.kind else {
367            continue;
368        };
369        if flavor == RlibFlavor::Normal
370            && let Some(filename) = lib.filename
371        {
372            let path = find_native_static_library(filename.as_str(), true, sess);
373            let src = read(path)
374                .unwrap_or_else(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }));
375            let (data, _) = create_wrapper_file(sess, ".bundled_lib".to_string(), &src);
376            let wrapper_file = emit_wrapper_file(sess, &data, tmpdir.as_ref(), filename.as_str());
377            packed_bundled_libs.push(wrapper_file);
378        } else {
379            let path = find_native_static_library(lib.name.as_str(), lib.verbatim, sess);
380            ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
381                sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
382            });
383        }
384    }
385
386    // On Windows, we add the raw-dylib import libraries to the rlibs already.
387    // But on ELF, this is not possible, as a shared object cannot be a member of a static library.
388    // Instead, we add all raw-dylibs to the final link on ELF.
389    if sess.target.is_like_windows {
390        for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
391            sess,
392            archive_builder_builder,
393            codegen_results.crate_info.used_libraries.iter(),
394            tmpdir.as_ref(),
395            true,
396        ) {
397            ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
398                sess.dcx()
399                    .emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
400            });
401        }
402    }
403
404    if let Some(trailing_metadata) = trailing_metadata {
405        // Note that it is important that we add all of our non-object "magical
406        // files" *after* all of the object files in the archive. The reason for
407        // this is as follows:
408        //
409        // * When performing LTO, this archive will be modified to remove
410        //   objects from above. The reason for this is described below.
411        //
412        // * When the system linker looks at an archive, it will attempt to
413        //   determine the architecture of the archive in order to see whether its
414        //   linkable.
415        //
416        //   The algorithm for this detection is: iterate over the files in the
417        //   archive. Skip magical SYMDEF names. Interpret the first file as an
418        //   object file. Read architecture from the object file.
419        //
420        // * As one can probably see, if "metadata" and "foo.bc" were placed
421        //   before all of the objects, then the architecture of this archive would
422        //   not be correctly inferred once 'foo.o' is removed.
423        //
424        // * Most of the time metadata in rlib files is wrapped in a "dummy" object
425        //   file for the target platform so the rlib can be processed entirely by
426        //   normal linkers for the platform. Sometimes this is not possible however.
427        //
428        // Basically, all this means is that this code should not move above the
429        // code above.
430        ab.add_file(&trailing_metadata);
431    }
432
433    // Add all bundled static native library dependencies.
434    // Archives added to the end of .rlib archive, see comment above for the reason.
435    for lib in packed_bundled_libs {
436        ab.add_file(&lib)
437    }
438
439    ab
440}
441
442/// Create a static archive.
443///
444/// This is essentially the same thing as an rlib, but it also involves adding all of the upstream
445/// crates' objects into the archive. This will slurp in all of the native libraries of upstream
446/// dependencies as well.
447///
448/// Additionally, there's no way for us to link dynamic libraries, so we warn about all dynamic
449/// library dependencies that they're not linked in.
450///
451/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
452/// object file (and also don't prepare the archive with a metadata file).
453fn link_staticlib(
454    sess: &Session,
455    archive_builder_builder: &dyn ArchiveBuilderBuilder,
456    codegen_results: &CodegenResults,
457    metadata: &EncodedMetadata,
458    out_filename: &Path,
459    tempdir: &MaybeTempDir,
460) {
461    info!("preparing staticlib to {:?}", out_filename);
462    let mut ab = link_rlib(
463        sess,
464        archive_builder_builder,
465        codegen_results,
466        metadata,
467        RlibFlavor::StaticlibBase,
468        tempdir,
469    );
470    let mut all_native_libs = vec![];
471
472    let res = each_linked_rlib(
473        &codegen_results.crate_info,
474        Some(CrateType::Staticlib),
475        &mut |cnum, path| {
476            let lto = are_upstream_rust_objects_already_included(sess)
477                && !ignored_for_lto(sess, &codegen_results.crate_info, cnum);
478
479            let native_libs = codegen_results.crate_info.native_libraries[&cnum].iter();
480            let relevant = native_libs.clone().filter(|lib| relevant_lib(sess, lib));
481            let relevant_libs: FxIndexSet<_> = relevant.filter_map(|lib| lib.filename).collect();
482
483            let bundled_libs: FxIndexSet<_> = native_libs.filter_map(|lib| lib.filename).collect();
484            ab.add_archive(
485                path,
486                Box::new(move |fname: &str| {
487                    // Ignore metadata files, no matter the name.
488                    if fname == METADATA_FILENAME {
489                        return true;
490                    }
491
492                    // Don't include Rust objects if LTO is enabled
493                    if lto && looks_like_rust_object_file(fname) {
494                        return true;
495                    }
496
497                    // Skip objects for bundled libs.
498                    if bundled_libs.contains(&Symbol::intern(fname)) {
499                        return true;
500                    }
501
502                    false
503                }),
504            )
505            .unwrap();
506
507            archive_builder_builder
508                .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
509                .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
510
511            for filename in relevant_libs.iter() {
512                let joined = tempdir.as_ref().join(filename.as_str());
513                let path = joined.as_path();
514                ab.add_archive(path, Box::new(|_| false)).unwrap();
515            }
516
517            all_native_libs
518                .extend(codegen_results.crate_info.native_libraries[&cnum].iter().cloned());
519        },
520    );
521    if let Err(e) = res {
522        sess.dcx().emit_fatal(e);
523    }
524
525    ab.build(out_filename);
526
527    let crates = codegen_results.crate_info.used_crates.iter();
528
529    let fmts = codegen_results
530        .crate_info
531        .dependency_formats
532        .get(&CrateType::Staticlib)
533        .expect("no dependency formats for staticlib");
534
535    let mut all_rust_dylibs = vec![];
536    for &cnum in crates {
537        let Some(Linkage::Dynamic) = fmts.get(cnum) else {
538            continue;
539        };
540        let crate_name = codegen_results.crate_info.crate_name[&cnum];
541        let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
542        if let Some((path, _)) = &used_crate_source.dylib {
543            all_rust_dylibs.push(&**path);
544        } else if used_crate_source.rmeta.is_some() {
545            sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
546        } else {
547            sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
548        }
549    }
550
551    all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
552
553    for print in &sess.opts.prints {
554        if print.kind == PrintKind::NativeStaticLibs {
555            print_native_static_libs(sess, &print.out, &all_native_libs, &all_rust_dylibs);
556        }
557    }
558}
559
560/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
561/// DWARF package.
562fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out_filename: &Path) {
563    let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
564    dwp_out_filename.push(".dwp");
565    debug!(?dwp_out_filename, ?executable_out_filename);
566
567    #[derive(Default)]
568    struct ThorinSession<Relocations> {
569        arena_data: TypedArena<Vec<u8>>,
570        arena_mmap: TypedArena<Mmap>,
571        arena_relocations: TypedArena<Relocations>,
572    }
573
574    impl<Relocations> ThorinSession<Relocations> {
575        fn alloc_mmap(&self, data: Mmap) -> &Mmap {
576            &*self.arena_mmap.alloc(data)
577        }
578    }
579
580    impl<Relocations> thorin::Session<Relocations> for ThorinSession<Relocations> {
581        fn alloc_data(&self, data: Vec<u8>) -> &[u8] {
582            &*self.arena_data.alloc(data)
583        }
584
585        fn alloc_relocation(&self, data: Relocations) -> &Relocations {
586            &*self.arena_relocations.alloc(data)
587        }
588
589        fn read_input(&self, path: &Path) -> std::io::Result<&[u8]> {
590            let file = File::open(&path)?;
591            let mmap = (unsafe { Mmap::map(file) })?;
592            Ok(self.alloc_mmap(mmap))
593        }
594    }
595
596    match sess.time("run_thorin", || -> Result<(), thorin::Error> {
597        let thorin_sess = ThorinSession::default();
598        let mut package = thorin::DwarfPackage::new(&thorin_sess);
599
600        // Input objs contain .o/.dwo files from the current crate.
601        match sess.opts.unstable_opts.split_dwarf_kind {
602            SplitDwarfKind::Single => {
603                for input_obj in cg_results.modules.iter().filter_map(|m| m.object.as_ref()) {
604                    package.add_input_object(input_obj)?;
605                }
606            }
607            SplitDwarfKind::Split => {
608                for input_obj in cg_results.modules.iter().filter_map(|m| m.dwarf_object.as_ref()) {
609                    package.add_input_object(input_obj)?;
610                }
611            }
612        }
613
614        // Input rlibs contain .o/.dwo files from dependencies.
615        let input_rlibs = cg_results
616            .crate_info
617            .used_crate_source
618            .items()
619            .filter_map(|(_, csource)| csource.rlib.as_ref())
620            .map(|(path, _)| path)
621            .into_sorted_stable_ord();
622
623        for input_rlib in input_rlibs {
624            debug!(?input_rlib);
625            package.add_input_object(input_rlib)?;
626        }
627
628        // Failing to read the referenced objects is expected for dependencies where the path in the
629        // executable will have been cleaned by Cargo, but the referenced objects will be contained
630        // within rlibs provided as inputs.
631        //
632        // If paths have been remapped, then .o/.dwo files from the current crate also won't be
633        // found, but are provided explicitly above.
634        //
635        // Adding an executable is primarily done to make `thorin` check that all the referenced
636        // dwarf objects are found in the end.
637        package.add_executable(
638            executable_out_filename,
639            thorin::MissingReferencedObjectBehaviour::Skip,
640        )?;
641
642        let output_stream = BufWriter::new(
643            OpenOptions::new()
644                .read(true)
645                .write(true)
646                .create(true)
647                .truncate(true)
648                .open(dwp_out_filename)?,
649        );
650        let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream);
651        package.finish()?.emit(&mut output_stream)?;
652        output_stream.result()?;
653        output_stream.into_inner().flush()?;
654
655        Ok(())
656    }) {
657        Ok(()) => {}
658        Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
659    }
660}
661
662#[derive(LintDiagnostic)]
663#[diag(codegen_ssa_linker_output)]
664/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
665/// end up with inconsistent languages within the same diagnostic.
666struct LinkerOutput {
667    inner: String,
668}
669
670/// Create a dynamic library or executable.
671///
672/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
673/// files as well.
674fn link_natively(
675    sess: &Session,
676    archive_builder_builder: &dyn ArchiveBuilderBuilder,
677    crate_type: CrateType,
678    out_filename: &Path,
679    codegen_results: &CodegenResults,
680    metadata: &EncodedMetadata,
681    tmpdir: &Path,
682) {
683    info!("preparing {:?} to {:?}", crate_type, out_filename);
684    let (linker_path, flavor) = linker_and_flavor(sess);
685    let self_contained_components = self_contained_components(sess, crate_type, &linker_path);
686
687    // On AIX, we ship all libraries as .a big_af archive
688    // the expected format is lib<name>.a(libname.so) for the actual
689    // dynamic library. So we link to a temporary .so file to be archived
690    // at the final out_filename location
691    let should_archive = crate_type != CrateType::Executable && sess.target.is_like_aix;
692    let archive_member =
693        should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
694    let temp_filename = archive_member.as_deref().unwrap_or(out_filename);
695
696    let mut cmd = linker_with_args(
697        &linker_path,
698        flavor,
699        sess,
700        archive_builder_builder,
701        crate_type,
702        tmpdir,
703        temp_filename,
704        codegen_results,
705        metadata,
706        self_contained_components,
707    );
708
709    linker::disable_localization(&mut cmd);
710
711    for (k, v) in sess.target.link_env.as_ref() {
712        cmd.env(k.as_ref(), v.as_ref());
713    }
714    for k in sess.target.link_env_remove.as_ref() {
715        cmd.env_remove(k.as_ref());
716    }
717
718    for print in &sess.opts.prints {
719        if print.kind == PrintKind::LinkArgs {
720            let content = format!("{cmd:?}\n");
721            print.out.overwrite(&content, sess);
722        }
723    }
724
725    // May have not found libraries in the right formats.
726    sess.dcx().abort_if_errors();
727
728    // Invoke the system linker
729    info!("{cmd:?}");
730    let unknown_arg_regex =
731        Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
732    let mut prog;
733    loop {
734        prog = sess.time("run_linker", || exec_linker(sess, &cmd, out_filename, flavor, tmpdir));
735        let Ok(ref output) = prog else {
736            break;
737        };
738        if output.status.success() {
739            break;
740        }
741        let mut out = output.stderr.clone();
742        out.extend(&output.stdout);
743        let out = String::from_utf8_lossy(&out);
744
745        // Check to see if the link failed with an error message that indicates it
746        // doesn't recognize the -no-pie option. If so, re-perform the link step
747        // without it. This is safe because if the linker doesn't support -no-pie
748        // then it should not default to linking executables as pie. Different
749        // versions of gcc seem to use different quotes in the error message so
750        // don't check for them.
751        if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
752            && unknown_arg_regex.is_match(&out)
753            && out.contains("-no-pie")
754            && cmd.get_args().iter().any(|e| e == "-no-pie")
755        {
756            info!("linker output: {:?}", out);
757            warn!("Linker does not support -no-pie command line option. Retrying without.");
758            for arg in cmd.take_args() {
759                if arg != "-no-pie" {
760                    cmd.arg(arg);
761                }
762            }
763            info!("{cmd:?}");
764            continue;
765        }
766
767        // Check if linking failed with an error message that indicates the driver didn't recognize
768        // the `-fuse-ld=lld` option. If so, re-perform the link step without it. This avoids having
769        // to spawn multiple instances on the happy path to do version checking, and ensures things
770        // keep working on the tier 1 baseline of GLIBC 2.17+. That is generally understood as GCCs
771        // circa RHEL/CentOS 7, 4.5 or so, whereas lld support was added in GCC 9.
772        if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, Lld::Yes))
773            && unknown_arg_regex.is_match(&out)
774            && out.contains("-fuse-ld=lld")
775            && cmd.get_args().iter().any(|e| e.to_string_lossy() == "-fuse-ld=lld")
776        {
777            info!("linker output: {:?}", out);
778            info!("The linker driver does not support `-fuse-ld=lld`. Retrying without it.");
779            for arg in cmd.take_args() {
780                if arg.to_string_lossy() != "-fuse-ld=lld" {
781                    cmd.arg(arg);
782                }
783            }
784            info!("{cmd:?}");
785            continue;
786        }
787
788        // Detect '-static-pie' used with an older version of gcc or clang not supporting it.
789        // Fallback from '-static-pie' to '-static' in that case.
790        if matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
791            && unknown_arg_regex.is_match(&out)
792            && (out.contains("-static-pie") || out.contains("--no-dynamic-linker"))
793            && cmd.get_args().iter().any(|e| e == "-static-pie")
794        {
795            info!("linker output: {:?}", out);
796            warn!(
797                "Linker does not support -static-pie command line option. Retrying with -static instead."
798            );
799            // Mirror `add_(pre,post)_link_objects` to replace CRT objects.
800            let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
801            let opts = &sess.target;
802            let pre_objects = if self_contained_crt_objects {
803                &opts.pre_link_objects_self_contained
804            } else {
805                &opts.pre_link_objects
806            };
807            let post_objects = if self_contained_crt_objects {
808                &opts.post_link_objects_self_contained
809            } else {
810                &opts.post_link_objects
811            };
812            let get_objects = |objects: &CrtObjects, kind| {
813                objects
814                    .get(&kind)
815                    .iter()
816                    .copied()
817                    .flatten()
818                    .map(|obj| {
819                        get_object_file_path(sess, obj, self_contained_crt_objects).into_os_string()
820                    })
821                    .collect::<Vec<_>>()
822            };
823            let pre_objects_static_pie = get_objects(pre_objects, LinkOutputKind::StaticPicExe);
824            let post_objects_static_pie = get_objects(post_objects, LinkOutputKind::StaticPicExe);
825            let mut pre_objects_static = get_objects(pre_objects, LinkOutputKind::StaticNoPicExe);
826            let mut post_objects_static = get_objects(post_objects, LinkOutputKind::StaticNoPicExe);
827            // Assume that we know insertion positions for the replacement arguments from replaced
828            // arguments, which is true for all supported targets.
829            assert!(pre_objects_static.is_empty() || !pre_objects_static_pie.is_empty());
830            assert!(post_objects_static.is_empty() || !post_objects_static_pie.is_empty());
831            for arg in cmd.take_args() {
832                if arg == "-static-pie" {
833                    // Replace the output kind.
834                    cmd.arg("-static");
835                } else if pre_objects_static_pie.contains(&arg) {
836                    // Replace the pre-link objects (replace the first and remove the rest).
837                    cmd.args(mem::take(&mut pre_objects_static));
838                } else if post_objects_static_pie.contains(&arg) {
839                    // Replace the post-link objects (replace the first and remove the rest).
840                    cmd.args(mem::take(&mut post_objects_static));
841                } else {
842                    cmd.arg(arg);
843                }
844            }
845            info!("{cmd:?}");
846            continue;
847        }
848
849        break;
850    }
851
852    match prog {
853        Ok(prog) => {
854            let is_msvc_link_exe = sess.target.is_like_msvc
855                && flavor == LinkerFlavor::Msvc(Lld::No)
856                // Match exactly "link.exe"
857                && linker_path.to_str() == Some("link.exe");
858
859            if !prog.status.success() {
860                let mut output = prog.stderr.clone();
861                output.extend_from_slice(&prog.stdout);
862                let escaped_output = escape_linker_output(&output, flavor);
863                let err = errors::LinkingFailed {
864                    linker_path: &linker_path,
865                    exit_status: prog.status,
866                    command: cmd,
867                    escaped_output,
868                    verbose: sess.opts.verbose,
869                    sysroot_dir: sess.opts.sysroot.path().to_owned(),
870                };
871                sess.dcx().emit_err(err);
872                // If MSVC's `link.exe` was expected but the return code
873                // is not a Microsoft LNK error then suggest a way to fix or
874                // install the Visual Studio build tools.
875                if let Some(code) = prog.status.code() {
876                    // All Microsoft `link.exe` linking ror codes are
877                    // four digit numbers in the range 1000 to 9999 inclusive
878                    if is_msvc_link_exe && (code < 1000 || code > 9999) {
879                        let is_vs_installed = windows_registry::find_vs_version().is_ok();
880                        let has_linker =
881                            windows_registry::find_tool(&sess.target.arch, "link.exe").is_some();
882
883                        sess.dcx().emit_note(errors::LinkExeUnexpectedError);
884
885                        // STATUS_STACK_BUFFER_OVERRUN is also used for fast abnormal program termination, e.g. abort().
886                        // Emit a special diagnostic to let people know that this most likely doesn't indicate a stack buffer overrun.
887                        const STATUS_STACK_BUFFER_OVERRUN: i32 = 0xc0000409u32 as _;
888                        if code == STATUS_STACK_BUFFER_OVERRUN {
889                            sess.dcx().emit_note(errors::LinkExeStatusStackBufferOverrun);
890                        }
891
892                        if is_vs_installed && has_linker {
893                            // the linker is broken
894                            sess.dcx().emit_note(errors::RepairVSBuildTools);
895                            sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
896                        } else if is_vs_installed {
897                            // the linker is not installed
898                            sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
899                        } else {
900                            // visual studio is not installed
901                            sess.dcx().emit_note(errors::VisualStudioNotInstalled);
902                        }
903                    }
904                }
905
906                sess.dcx().abort_if_errors();
907            }
908
909            let stderr = escape_string(&prog.stderr);
910            let mut stdout = escape_string(&prog.stdout);
911            info!("linker stderr:\n{}", &stderr);
912            info!("linker stdout:\n{}", &stdout);
913
914            // Hide some progress messages from link.exe that we don't care about.
915            // See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
916            if is_msvc_link_exe {
917                if let Ok(str) = str::from_utf8(&prog.stdout) {
918                    let mut output = String::with_capacity(str.len());
919                    for line in stdout.lines() {
920                        if line.starts_with("   Creating library")
921                            || line.starts_with("Generating code")
922                            || line.starts_with("Finished generating code")
923                        {
924                            continue;
925                        }
926                        output += line;
927                        output += "\r\n"
928                    }
929                    stdout = escape_string(output.trim().as_bytes())
930                }
931            }
932
933            let level = codegen_results.crate_info.lint_levels.linker_messages;
934            let lint = |msg| {
935                lint_level(sess, LINKER_MESSAGES, level, None, |diag| {
936                    LinkerOutput { inner: msg }.decorate_lint(diag)
937                })
938            };
939
940            if !prog.stderr.is_empty() {
941                // We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
942                let stderr = stderr
943                    .strip_prefix("warning: ")
944                    .unwrap_or(&stderr)
945                    .replace(": warning: ", ": ");
946                lint(format!("linker stderr: {stderr}"));
947            }
948            if !stdout.is_empty() {
949                lint(format!("linker stdout: {}", stdout))
950            }
951        }
952        Err(e) => {
953            let linker_not_found = e.kind() == io::ErrorKind::NotFound;
954
955            let err = if linker_not_found {
956                sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e })
957            } else {
958                sess.dcx().emit_err(errors::UnableToExeLinker {
959                    linker_path,
960                    error: e,
961                    command_formatted: format!("{cmd:?}"),
962                })
963            };
964
965            if sess.target.is_like_msvc && linker_not_found {
966                sess.dcx().emit_note(errors::MsvcMissingLinker);
967                sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
968                sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
969            }
970            err.raise_fatal();
971        }
972    }
973
974    match sess.split_debuginfo() {
975        // If split debug information is disabled or located in individual files
976        // there's nothing to do here.
977        SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {}
978
979        // If packed split-debuginfo is requested, but the final compilation
980        // doesn't actually have any debug information, then we skip this step.
981        SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {}
982
983        // On macOS the external `dsymutil` tool is used to create the packed
984        // debug information. Note that this will read debug information from
985        // the objects on the filesystem which we'll clean up later.
986        SplitDebuginfo::Packed if sess.target.is_like_darwin => {
987            let prog = Command::new("dsymutil").arg(out_filename).output();
988            match prog {
989                Ok(prog) => {
990                    if !prog.status.success() {
991                        let mut output = prog.stderr.clone();
992                        output.extend_from_slice(&prog.stdout);
993                        sess.dcx().emit_warn(errors::ProcessingDymutilFailed {
994                            status: prog.status,
995                            output: escape_string(&output),
996                        });
997                    }
998                }
999                Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
1000            }
1001        }
1002
1003        // On MSVC packed debug information is produced by the linker itself so
1004        // there's no need to do anything else here.
1005        SplitDebuginfo::Packed if sess.target.is_like_windows => {}
1006
1007        // ... and otherwise we're processing a `*.dwp` packed dwarf file.
1008        //
1009        // We cannot rely on the .o paths in the executable because they may have been
1010        // remapped by --remap-path-prefix and therefore invalid, so we need to provide
1011        // the .o/.dwo paths explicitly.
1012        SplitDebuginfo::Packed => link_dwarf_object(sess, codegen_results, out_filename),
1013    }
1014
1015    let strip = sess.opts.cg.strip;
1016
1017    if sess.target.is_like_darwin {
1018        let stripcmd = "rust-objcopy";
1019        match (strip, crate_type) {
1020            (Strip::Debuginfo, _) => {
1021                strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-debug"])
1022            }
1023
1024            // Per the manpage, --discard-all is the maximum safe strip level for dynamic libraries. (#93988)
1025            (
1026                Strip::Symbols,
1027                CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib,
1028            ) => strip_with_external_utility(sess, stripcmd, out_filename, &["--discard-all"]),
1029            (Strip::Symbols, _) => {
1030                strip_with_external_utility(sess, stripcmd, out_filename, &["--strip-all"])
1031            }
1032            (Strip::None, _) => {}
1033        }
1034    }
1035
1036    if sess.target.is_like_solaris {
1037        // Many illumos systems will have both the native 'strip' utility and
1038        // the GNU one. Use the native version explicitly and do not rely on
1039        // what's in the path.
1040        //
1041        // If cross-compiling and there is not a native version, then use
1042        // `llvm-strip` and hope.
1043        let stripcmd = if !sess.host.is_like_solaris { "rust-objcopy" } else { "/usr/bin/strip" };
1044        match strip {
1045            // Always preserve the symbol table (-x).
1046            Strip::Debuginfo => strip_with_external_utility(sess, stripcmd, out_filename, &["-x"]),
1047            // Strip::Symbols is handled via the --strip-all linker option.
1048            Strip::Symbols => {}
1049            Strip::None => {}
1050        }
1051    }
1052
1053    if sess.target.is_like_aix {
1054        // `llvm-strip` doesn't work for AIX - their strip must be used.
1055        if !sess.host.is_like_aix {
1056            sess.dcx().emit_warn(errors::AixStripNotUsed);
1057        }
1058        let stripcmd = "/usr/bin/strip";
1059        match strip {
1060            Strip::Debuginfo => {
1061                // FIXME: AIX's strip utility only offers option to strip line number information.
1062                strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-l"])
1063            }
1064            Strip::Symbols => {
1065                // Must be noted this option might remove symbol __aix_rust_metadata and thus removes .info section which contains metadata.
1066                strip_with_external_utility(sess, stripcmd, temp_filename, &["-X32_64", "-r"])
1067            }
1068            Strip::None => {}
1069        }
1070    }
1071
1072    if should_archive {
1073        let mut ab = archive_builder_builder.new_archive_builder(sess);
1074        ab.add_file(temp_filename);
1075        ab.build(out_filename);
1076    }
1077}
1078
1079fn strip_with_external_utility(sess: &Session, util: &str, out_filename: &Path, options: &[&str]) {
1080    let mut cmd = Command::new(util);
1081    cmd.args(options);
1082
1083    let mut new_path = sess.get_tools_search_paths(false);
1084    if let Some(path) = env::var_os("PATH") {
1085        new_path.extend(env::split_paths(&path));
1086    }
1087    cmd.env("PATH", env::join_paths(new_path).unwrap());
1088
1089    let prog = cmd.arg(out_filename).output();
1090    match prog {
1091        Ok(prog) => {
1092            if !prog.status.success() {
1093                let mut output = prog.stderr.clone();
1094                output.extend_from_slice(&prog.stdout);
1095                sess.dcx().emit_warn(errors::StrippingDebugInfoFailed {
1096                    util,
1097                    status: prog.status,
1098                    output: escape_string(&output),
1099                });
1100            }
1101        }
1102        Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
1103    }
1104}
1105
1106fn escape_string(s: &[u8]) -> String {
1107    match str::from_utf8(s) {
1108        Ok(s) => s.to_owned(),
1109        Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1110    }
1111}
1112
1113#[cfg(not(windows))]
1114fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String {
1115    escape_string(s)
1116}
1117
1118/// If the output of the msvc linker is not UTF-8 and the host is Windows,
1119/// then try to convert the string from the OEM encoding.
1120#[cfg(windows)]
1121fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String {
1122    // This only applies to the actual MSVC linker.
1123    if flavour != LinkerFlavor::Msvc(Lld::No) {
1124        return escape_string(s);
1125    }
1126    match str::from_utf8(s) {
1127        Ok(s) => return s.to_owned(),
1128        Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) {
1129            Some(s) => s,
1130            // The string is not UTF-8 and isn't valid for the OEM code page
1131            None => format!("Non-UTF-8 output: {}", s.escape_ascii()),
1132        },
1133    }
1134}
1135
1136/// Wrappers around the Windows API.
1137#[cfg(windows)]
1138mod win {
1139    use windows::Win32::Globalization::{
1140        CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT,
1141        LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar,
1142    };
1143
1144    /// Get the Windows system OEM code page. This is most notably the code page
1145    /// used for link.exe's output.
1146    pub(super) fn oem_code_page() -> u32 {
1147        unsafe {
1148            let mut cp: u32 = 0;
1149            // We're using the `LOCALE_RETURN_NUMBER` flag to return a u32.
1150            // But the API requires us to pass the data as though it's a [u16] string.
1151            let len = size_of::<u32>() / size_of::<u16>();
1152            let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len);
1153            let len_written = GetLocaleInfoEx(
1154                LOCALE_NAME_SYSTEM_DEFAULT,
1155                LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
1156                Some(data),
1157            );
1158            if len_written as usize == len { cp } else { CP_OEMCP }
1159        }
1160    }
1161    /// Try to convert a multi-byte string to a UTF-8 string using the given code page
1162    /// The string does not need to be null terminated.
1163    ///
1164    /// This is implemented as a wrapper around `MultiByteToWideChar`.
1165    /// See <https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar>
1166    ///
1167    /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains
1168    /// any invalid bytes for the expected encoding.
1169    pub(super) fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option<String> {
1170        // `MultiByteToWideChar` requires a length to be a "positive integer".
1171        if s.len() > isize::MAX as usize {
1172            return None;
1173        }
1174        // Error if the string is not valid for the expected code page.
1175        let flags = MB_ERR_INVALID_CHARS;
1176        // Call MultiByteToWideChar twice.
1177        // First to calculate the length then to convert the string.
1178        let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) };
1179        if len > 0 {
1180            let mut utf16 = vec![0; len as usize];
1181            len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) };
1182            if len > 0 {
1183                return utf16.get(..len as usize).map(String::from_utf16_lossy);
1184            }
1185        }
1186        None
1187    }
1188}
1189
1190fn add_sanitizer_libraries(
1191    sess: &Session,
1192    flavor: LinkerFlavor,
1193    crate_type: CrateType,
1194    linker: &mut dyn Linker,
1195) {
1196    if sess.target.is_like_android {
1197        // Sanitizer runtime libraries are provided dynamically on Android
1198        // targets.
1199        return;
1200    }
1201
1202    if sess.opts.unstable_opts.external_clangrt {
1203        // Linking against in-tree sanitizer runtimes is disabled via
1204        // `-Z external-clangrt`
1205        return;
1206    }
1207
1208    if matches!(crate_type, CrateType::Rlib | CrateType::Staticlib) {
1209        return;
1210    }
1211
1212    // On macOS and Windows using MSVC the runtimes are distributed as dylibs
1213    // which should be linked to both executables and dynamic libraries.
1214    // Everywhere else the runtimes are currently distributed as static
1215    // libraries which should be linked to executables only.
1216    if matches!(
1217        crate_type,
1218        CrateType::Dylib | CrateType::Cdylib | CrateType::ProcMacro | CrateType::Sdylib
1219    ) && !(sess.target.is_like_darwin || sess.target.is_like_msvc)
1220    {
1221        return;
1222    }
1223
1224    let sanitizer = sess.opts.unstable_opts.sanitizer;
1225    if sanitizer.contains(SanitizerSet::ADDRESS) {
1226        link_sanitizer_runtime(sess, flavor, linker, "asan");
1227    }
1228    if sanitizer.contains(SanitizerSet::DATAFLOW) {
1229        link_sanitizer_runtime(sess, flavor, linker, "dfsan");
1230    }
1231    if sanitizer.contains(SanitizerSet::LEAK)
1232        && !sanitizer.contains(SanitizerSet::ADDRESS)
1233        && !sanitizer.contains(SanitizerSet::HWADDRESS)
1234    {
1235        link_sanitizer_runtime(sess, flavor, linker, "lsan");
1236    }
1237    if sanitizer.contains(SanitizerSet::MEMORY) {
1238        link_sanitizer_runtime(sess, flavor, linker, "msan");
1239    }
1240    if sanitizer.contains(SanitizerSet::THREAD) {
1241        link_sanitizer_runtime(sess, flavor, linker, "tsan");
1242    }
1243    if sanitizer.contains(SanitizerSet::HWADDRESS) {
1244        link_sanitizer_runtime(sess, flavor, linker, "hwasan");
1245    }
1246    if sanitizer.contains(SanitizerSet::SAFESTACK) {
1247        link_sanitizer_runtime(sess, flavor, linker, "safestack");
1248    }
1249}
1250
1251fn link_sanitizer_runtime(
1252    sess: &Session,
1253    flavor: LinkerFlavor,
1254    linker: &mut dyn Linker,
1255    name: &str,
1256) {
1257    fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
1258        let path = sess.target_tlib_path.dir.join(filename);
1259        if path.exists() {
1260            sess.target_tlib_path.dir.clone()
1261        } else {
1262            filesearch::make_target_lib_path(
1263                &sess.opts.sysroot.default,
1264                sess.opts.target_triple.tuple(),
1265            )
1266        }
1267    }
1268
1269    let channel =
1270        option_env!("CFG_RELEASE_CHANNEL").map(|channel| format!("-{channel}")).unwrap_or_default();
1271
1272    if sess.target.is_like_darwin {
1273        // On Apple platforms, the sanitizer is always built as a dylib, and
1274        // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1275        // rpath to the library as well (the rpath should be absolute, see
1276        // PR #41352 for details).
1277        let filename = format!("rustc{channel}_rt.{name}");
1278        let path = find_sanitizer_runtime(sess, &filename);
1279        let rpath = path.to_str().expect("non-utf8 component in path");
1280        linker.link_args(&["-rpath", rpath]);
1281        linker.link_dylib_by_name(&filename, false, true);
1282    } else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
1283        // MSVC provides the `/INFERASANLIBS` argument to automatically find the
1284        // compatible ASAN library.
1285        linker.link_arg("/INFERASANLIBS");
1286    } else {
1287        let filename = format!("librustc{channel}_rt.{name}.a");
1288        let path = find_sanitizer_runtime(sess, &filename).join(&filename);
1289        linker.link_staticlib_by_path(&path, true);
1290    }
1291}
1292
1293/// Returns a boolean indicating whether the specified crate should be ignored
1294/// during LTO.
1295///
1296/// Crates ignored during LTO are not lumped together in the "massive object
1297/// file" that we create and are linked in their normal rlib states. See
1298/// comments below for what crates do not participate in LTO.
1299///
1300/// It's unusual for a crate to not participate in LTO. Typically only
1301/// compiler-specific and unstable crates have a reason to not participate in
1302/// LTO.
1303pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
1304    // If our target enables builtin function lowering in LLVM then the
1305    // crates providing these functions don't participate in LTO (e.g.
1306    // no_builtins or compiler builtins crates).
1307    !sess.target.no_builtins
1308        && (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
1309}
1310
1311/// This functions tries to determine the appropriate linker (and corresponding LinkerFlavor) to use
1312pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
1313    fn infer_from(
1314        sess: &Session,
1315        linker: Option<PathBuf>,
1316        flavor: Option<LinkerFlavor>,
1317        features: LinkerFeaturesCli,
1318    ) -> Option<(PathBuf, LinkerFlavor)> {
1319        let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
1320        match (linker, flavor) {
1321            (Some(linker), Some(flavor)) => Some((linker, flavor)),
1322            // only the linker flavor is known; use the default linker for the selected flavor
1323            (None, Some(flavor)) => Some((
1324                PathBuf::from(match flavor {
1325                    LinkerFlavor::Gnu(Cc::Yes, _)
1326                    | LinkerFlavor::Darwin(Cc::Yes, _)
1327                    | LinkerFlavor::WasmLld(Cc::Yes)
1328                    | LinkerFlavor::Unix(Cc::Yes) => {
1329                        if cfg!(any(target_os = "solaris", target_os = "illumos")) {
1330                            // On historical Solaris systems, "cc" may have
1331                            // been Sun Studio, which is not flag-compatible
1332                            // with "gcc". This history casts a long shadow,
1333                            // and many modern illumos distributions today
1334                            // ship GCC as "gcc" without also making it
1335                            // available as "cc".
1336                            "gcc"
1337                        } else {
1338                            "cc"
1339                        }
1340                    }
1341                    LinkerFlavor::Gnu(_, Lld::Yes)
1342                    | LinkerFlavor::Darwin(_, Lld::Yes)
1343                    | LinkerFlavor::WasmLld(..)
1344                    | LinkerFlavor::Msvc(Lld::Yes) => "lld",
1345                    LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
1346                        "ld"
1347                    }
1348                    LinkerFlavor::Msvc(..) => "link.exe",
1349                    LinkerFlavor::EmCc => {
1350                        if cfg!(windows) {
1351                            "emcc.bat"
1352                        } else {
1353                            "emcc"
1354                        }
1355                    }
1356                    LinkerFlavor::Bpf => "bpf-linker",
1357                    LinkerFlavor::Llbc => "llvm-bitcode-linker",
1358                    LinkerFlavor::Ptx => "rust-ptx-linker",
1359                }),
1360                flavor,
1361            )),
1362            (Some(linker), None) => {
1363                let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1364                    sess.dcx().emit_fatal(errors::LinkerFileStem);
1365                });
1366                let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1367                let flavor = adjust_flavor_to_features(flavor, features);
1368                Some((linker, flavor))
1369            }
1370            (None, None) => None,
1371        }
1372    }
1373
1374    // While linker flavors and linker features are isomorphic (and thus targets don't need to
1375    // define features separately), we use the flavor as the root piece of data and have the
1376    // linker-features CLI flag influence *that*, so that downstream code does not have to check for
1377    // both yet.
1378    fn adjust_flavor_to_features(
1379        flavor: LinkerFlavor,
1380        features: LinkerFeaturesCli,
1381    ) -> LinkerFlavor {
1382        // Note: a linker feature cannot be both enabled and disabled on the CLI.
1383        if features.enabled.contains(LinkerFeatures::LLD) {
1384            flavor.with_lld_enabled()
1385        } else if features.disabled.contains(LinkerFeatures::LLD) {
1386            flavor.with_lld_disabled()
1387        } else {
1388            flavor
1389        }
1390    }
1391
1392    let features = sess.opts.cg.linker_features;
1393
1394    // linker and linker flavor specified via command line have precedence over what the target
1395    // specification specifies
1396    let linker_flavor = match sess.opts.cg.linker_flavor {
1397        // The linker flavors that are non-target specific can be directly translated to LinkerFlavor
1398        Some(LinkerFlavorCli::Llbc) => Some(LinkerFlavor::Llbc),
1399        Some(LinkerFlavorCli::Ptx) => Some(LinkerFlavor::Ptx),
1400        // The linker flavors that corresponds to targets needs logic that keeps the base LinkerFlavor
1401        _ => sess
1402            .opts
1403            .cg
1404            .linker_flavor
1405            .map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor)),
1406    };
1407    if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
1408        return ret;
1409    }
1410
1411    if let Some(ret) = infer_from(
1412        sess,
1413        sess.target.linker.as_deref().map(PathBuf::from),
1414        Some(sess.target.linker_flavor),
1415        features,
1416    ) {
1417        return ret;
1418    }
1419
1420    bug!("Not enough information provided to determine how to invoke the linker");
1421}
1422
1423/// Returns a pair of boolean indicating whether we should preserve the object and
1424/// dwarf object files on the filesystem for their debug information. This is often
1425/// useful with split-dwarf like schemes.
1426fn preserve_objects_for_their_debuginfo(sess: &Session) -> (bool, bool) {
1427    // If the objects don't have debuginfo there's nothing to preserve.
1428    if sess.opts.debuginfo == config::DebugInfo::None {
1429        return (false, false);
1430    }
1431
1432    match (sess.split_debuginfo(), sess.opts.unstable_opts.split_dwarf_kind) {
1433        // If there is no split debuginfo then do not preserve objects.
1434        (SplitDebuginfo::Off, _) => (false, false),
1435        // If there is packed split debuginfo, then the debuginfo in the objects
1436        // has been packaged and the objects can be deleted.
1437        (SplitDebuginfo::Packed, _) => (false, false),
1438        // If there is unpacked split debuginfo and the current target can not use
1439        // split dwarf, then keep objects.
1440        (SplitDebuginfo::Unpacked, _) if !sess.target_can_use_split_dwarf() => (true, false),
1441        // If there is unpacked split debuginfo and the target can use split dwarf, then
1442        // keep the object containing that debuginfo (whether that is an object file or
1443        // dwarf object file depends on the split dwarf kind).
1444        (SplitDebuginfo::Unpacked, SplitDwarfKind::Single) => (true, false),
1445        (SplitDebuginfo::Unpacked, SplitDwarfKind::Split) => (false, true),
1446    }
1447}
1448
1449#[derive(PartialEq)]
1450enum RlibFlavor {
1451    Normal,
1452    StaticlibBase,
1453}
1454
1455fn print_native_static_libs(
1456    sess: &Session,
1457    out: &OutFileName,
1458    all_native_libs: &[NativeLib],
1459    all_rust_dylibs: &[&Path],
1460) {
1461    let mut lib_args: Vec<_> = all_native_libs
1462        .iter()
1463        .filter(|l| relevant_lib(sess, l))
1464        .filter_map(|lib| {
1465            let name = lib.name;
1466            match lib.kind {
1467                NativeLibKind::Static { bundle: Some(false), .. }
1468                | NativeLibKind::Dylib { .. }
1469                | NativeLibKind::Unspecified => {
1470                    let verbatim = lib.verbatim;
1471                    if sess.target.is_like_msvc {
1472                        let (prefix, suffix) = sess.staticlib_components(verbatim);
1473                        Some(format!("{prefix}{name}{suffix}"))
1474                    } else if sess.target.linker_flavor.is_gnu() {
1475                        Some(format!("-l{}{}", if verbatim { ":" } else { "" }, name))
1476                    } else {
1477                        Some(format!("-l{name}"))
1478                    }
1479                }
1480                NativeLibKind::Framework { .. } => {
1481                    // ld-only syntax, since there are no frameworks in MSVC
1482                    Some(format!("-framework {name}"))
1483                }
1484                // These are included, no need to print them
1485                NativeLibKind::Static { bundle: None | Some(true), .. }
1486                | NativeLibKind::LinkArg
1487                | NativeLibKind::WasmImportModule
1488                | NativeLibKind::RawDylib => None,
1489            }
1490        })
1491        // deduplication of consecutive repeated libraries, see rust-lang/rust#113209
1492        .dedup()
1493        .collect();
1494    for path in all_rust_dylibs {
1495        // FIXME deduplicate with add_dynamic_crate
1496
1497        // Just need to tell the linker about where the library lives and
1498        // what its name is
1499        let parent = path.parent();
1500        if let Some(dir) = parent {
1501            let dir = fix_windows_verbatim_for_gcc(dir);
1502            if sess.target.is_like_msvc {
1503                let mut arg = String::from("/LIBPATH:");
1504                arg.push_str(&dir.display().to_string());
1505                lib_args.push(arg);
1506            } else {
1507                lib_args.push("-L".to_owned());
1508                lib_args.push(dir.display().to_string());
1509            }
1510        }
1511        let stem = path.file_stem().unwrap().to_str().unwrap();
1512        // Convert library file-stem into a cc -l argument.
1513        let lib = if let Some(lib) = stem.strip_prefix("lib")
1514            && !sess.target.is_like_windows
1515        {
1516            lib
1517        } else {
1518            stem
1519        };
1520        let path = parent.unwrap_or_else(|| Path::new(""));
1521        if sess.target.is_like_msvc {
1522            // When producing a dll, the MSVC linker may not actually emit a
1523            // `foo.lib` file if the dll doesn't actually export any symbols, so we
1524            // check to see if the file is there and just omit linking to it if it's
1525            // not present.
1526            let name = format!("{lib}.dll.lib");
1527            if path.join(&name).exists() {
1528                lib_args.push(name);
1529            }
1530        } else {
1531            lib_args.push(format!("-l{lib}"));
1532        }
1533    }
1534
1535    match out {
1536        OutFileName::Real(path) => {
1537            out.overwrite(&lib_args.join(" "), sess);
1538            sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
1539        }
1540        OutFileName::Stdout => {
1541            sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
1542            // Prefix for greppability
1543            // Note: This must not be translated as tools are allowed to depend on this exact string.
1544            sess.dcx().note(format!("native-static-libs: {}", lib_args.join(" ")));
1545        }
1546    }
1547}
1548
1549fn get_object_file_path(sess: &Session, name: &str, self_contained: bool) -> PathBuf {
1550    let file_path = sess.target_tlib_path.dir.join(name);
1551    if file_path.exists() {
1552        return file_path;
1553    }
1554    // Special directory with objects used only in self-contained linkage mode
1555    if self_contained {
1556        let file_path = sess.target_tlib_path.dir.join("self-contained").join(name);
1557        if file_path.exists() {
1558            return file_path;
1559        }
1560    }
1561    for search_path in sess.target_filesearch().search_paths(PathKind::Native) {
1562        let file_path = search_path.dir.join(name);
1563        if file_path.exists() {
1564            return file_path;
1565        }
1566    }
1567    PathBuf::from(name)
1568}
1569
1570fn exec_linker(
1571    sess: &Session,
1572    cmd: &Command,
1573    out_filename: &Path,
1574    flavor: LinkerFlavor,
1575    tmpdir: &Path,
1576) -> io::Result<Output> {
1577    // When attempting to spawn the linker we run a risk of blowing out the
1578    // size limits for spawning a new process with respect to the arguments
1579    // we pass on the command line.
1580    //
1581    // Here we attempt to handle errors from the OS saying "your list of
1582    // arguments is too big" by reinvoking the linker again with an `@`-file
1583    // that contains all the arguments (aka 'response' files).
1584    // The theory is that this is then accepted on all linkers and the linker
1585    // will read all its options out of there instead of looking at the command line.
1586    if !cmd.very_likely_to_exceed_some_spawn_limit() {
1587        match cmd.command().stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
1588            Ok(child) => {
1589                let output = child.wait_with_output();
1590                flush_linked_file(&output, out_filename)?;
1591                return output;
1592            }
1593            Err(ref e) if command_line_too_big(e) => {
1594                info!("command line to linker was too big: {}", e);
1595            }
1596            Err(e) => return Err(e),
1597        }
1598    }
1599
1600    info!("falling back to passing arguments to linker via an @-file");
1601    let mut cmd2 = cmd.clone();
1602    let mut args = String::new();
1603    for arg in cmd2.take_args() {
1604        args.push_str(
1605            &Escape {
1606                arg: arg.to_str().unwrap(),
1607                // Windows-style escaping for @-files is used by
1608                // - all linkers targeting MSVC-like targets, including LLD
1609                // - all LLD flavors running on Windows hosts
1610                // С/С++ compilers use Posix-style escaping (except clang-cl, which we do not use).
1611                is_like_msvc: sess.target.is_like_msvc
1612                    || (cfg!(windows) && flavor.uses_lld() && !flavor.uses_cc()),
1613            }
1614            .to_string(),
1615        );
1616        args.push('\n');
1617    }
1618    let file = tmpdir.join("linker-arguments");
1619    let bytes = if sess.target.is_like_msvc {
1620        let mut out = Vec::with_capacity((1 + args.len()) * 2);
1621        // start the stream with a UTF-16 BOM
1622        for c in std::iter::once(0xFEFF).chain(args.encode_utf16()) {
1623            // encode in little endian
1624            out.push(c as u8);
1625            out.push((c >> 8) as u8);
1626        }
1627        out
1628    } else {
1629        args.into_bytes()
1630    };
1631    fs::write(&file, &bytes)?;
1632    cmd2.arg(format!("@{}", file.display()));
1633    info!("invoking linker {:?}", cmd2);
1634    let output = cmd2.output();
1635    flush_linked_file(&output, out_filename)?;
1636    return output;
1637
1638    #[cfg(not(windows))]
1639    fn flush_linked_file(_: &io::Result<Output>, _: &Path) -> io::Result<()> {
1640        Ok(())
1641    }
1642
1643    #[cfg(windows)]
1644    fn flush_linked_file(
1645        command_output: &io::Result<Output>,
1646        out_filename: &Path,
1647    ) -> io::Result<()> {
1648        // On Windows, under high I/O load, output buffers are sometimes not flushed,
1649        // even long after process exit, causing nasty, non-reproducible output bugs.
1650        //
1651        // File::sync_all() calls FlushFileBuffers() down the line, which solves the problem.
1652        //
1653        // А full writeup of the original Chrome bug can be found at
1654        // randomascii.wordpress.com/2018/02/25/compiler-bug-linker-bug-windows-kernel-bug/amp
1655
1656        if let &Ok(ref out) = command_output {
1657            if out.status.success() {
1658                if let Ok(of) = fs::OpenOptions::new().write(true).open(out_filename) {
1659                    of.sync_all()?;
1660                }
1661            }
1662        }
1663
1664        Ok(())
1665    }
1666
1667    #[cfg(unix)]
1668    fn command_line_too_big(err: &io::Error) -> bool {
1669        err.raw_os_error() == Some(::libc::E2BIG)
1670    }
1671
1672    #[cfg(windows)]
1673    fn command_line_too_big(err: &io::Error) -> bool {
1674        const ERROR_FILENAME_EXCED_RANGE: i32 = 206;
1675        err.raw_os_error() == Some(ERROR_FILENAME_EXCED_RANGE)
1676    }
1677
1678    #[cfg(not(any(unix, windows)))]
1679    fn command_line_too_big(_: &io::Error) -> bool {
1680        false
1681    }
1682
1683    struct Escape<'a> {
1684        arg: &'a str,
1685        is_like_msvc: bool,
1686    }
1687
1688    impl<'a> fmt::Display for Escape<'a> {
1689        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1690            if self.is_like_msvc {
1691                // This is "documented" at
1692                // https://docs.microsoft.com/en-us/cpp/build/reference/at-specify-a-linker-response-file
1693                //
1694                // Unfortunately there's not a great specification of the
1695                // syntax I could find online (at least) but some local
1696                // testing showed that this seemed sufficient-ish to catch
1697                // at least a few edge cases.
1698                write!(f, "\"")?;
1699                for c in self.arg.chars() {
1700                    match c {
1701                        '"' => write!(f, "\\{c}")?,
1702                        c => write!(f, "{c}")?,
1703                    }
1704                }
1705                write!(f, "\"")?;
1706            } else {
1707                // This is documented at https://linux.die.net/man/1/ld, namely:
1708                //
1709                // > Options in file are separated by whitespace. A whitespace
1710                // > character may be included in an option by surrounding the
1711                // > entire option in either single or double quotes. Any
1712                // > character (including a backslash) may be included by
1713                // > prefixing the character to be included with a backslash.
1714                //
1715                // We put an argument on each line, so all we need to do is
1716                // ensure the line is interpreted as one whole argument.
1717                for c in self.arg.chars() {
1718                    match c {
1719                        '\\' | ' ' => write!(f, "\\{c}")?,
1720                        c => write!(f, "{c}")?,
1721                    }
1722                }
1723            }
1724            Ok(())
1725        }
1726    }
1727}
1728
1729fn link_output_kind(sess: &Session, crate_type: CrateType) -> LinkOutputKind {
1730    let kind = match (crate_type, sess.crt_static(Some(crate_type)), sess.relocation_model()) {
1731        (CrateType::Executable, _, _) if sess.is_wasi_reactor() => LinkOutputKind::WasiReactorExe,
1732        (CrateType::Executable, false, RelocModel::Pic | RelocModel::Pie) => {
1733            LinkOutputKind::DynamicPicExe
1734        }
1735        (CrateType::Executable, false, _) => LinkOutputKind::DynamicNoPicExe,
1736        (CrateType::Executable, true, RelocModel::Pic | RelocModel::Pie) => {
1737            LinkOutputKind::StaticPicExe
1738        }
1739        (CrateType::Executable, true, _) => LinkOutputKind::StaticNoPicExe,
1740        (_, true, _) => LinkOutputKind::StaticDylib,
1741        (_, false, _) => LinkOutputKind::DynamicDylib,
1742    };
1743
1744    // Adjust the output kind to target capabilities.
1745    let opts = &sess.target;
1746    let pic_exe_supported = opts.position_independent_executables;
1747    let static_pic_exe_supported = opts.static_position_independent_executables;
1748    let static_dylib_supported = opts.crt_static_allows_dylibs;
1749    match kind {
1750        LinkOutputKind::DynamicPicExe if !pic_exe_supported => LinkOutputKind::DynamicNoPicExe,
1751        LinkOutputKind::StaticPicExe if !static_pic_exe_supported => LinkOutputKind::StaticNoPicExe,
1752        LinkOutputKind::StaticDylib if !static_dylib_supported => LinkOutputKind::DynamicDylib,
1753        _ => kind,
1754    }
1755}
1756
1757// Returns true if linker is located within sysroot
1758fn detect_self_contained_mingw(sess: &Session, linker: &Path) -> bool {
1759    // Assume `-C linker=rust-lld` as self-contained mode
1760    if linker == Path::new("rust-lld") {
1761        return true;
1762    }
1763    let linker_with_extension = if cfg!(windows) && linker.extension().is_none() {
1764        linker.with_extension("exe")
1765    } else {
1766        linker.to_path_buf()
1767    };
1768    for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
1769        let full_path = dir.join(&linker_with_extension);
1770        // If linker comes from sysroot assume self-contained mode
1771        if full_path.is_file() && !full_path.starts_with(sess.opts.sysroot.path()) {
1772            return false;
1773        }
1774    }
1775    true
1776}
1777
1778/// Various toolchain components used during linking are used from rustc distribution
1779/// instead of being found somewhere on the host system.
1780/// We only provide such support for a very limited number of targets.
1781fn self_contained_components(
1782    sess: &Session,
1783    crate_type: CrateType,
1784    linker: &Path,
1785) -> LinkSelfContainedComponents {
1786    // Turn the backwards compatible bool values for `self_contained` into fully inferred
1787    // `LinkSelfContainedComponents`.
1788    let self_contained =
1789        if let Some(self_contained) = sess.opts.cg.link_self_contained.explicitly_set {
1790            // Emit an error if the user requested self-contained mode on the CLI but the target
1791            // explicitly refuses it.
1792            if sess.target.link_self_contained.is_disabled() {
1793                sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
1794            }
1795            self_contained
1796        } else {
1797            match sess.target.link_self_contained {
1798                LinkSelfContainedDefault::False => false,
1799                LinkSelfContainedDefault::True => true,
1800
1801                LinkSelfContainedDefault::WithComponents(components) => {
1802                    // For target specs with explicitly enabled components, we can return them
1803                    // directly.
1804                    return components;
1805                }
1806
1807                // FIXME: Find a better heuristic for "native musl toolchain is available",
1808                // based on host and linker path, for example.
1809                // (https://github.com/rust-lang/rust/pull/71769#issuecomment-626330237).
1810                LinkSelfContainedDefault::InferredForMusl => sess.crt_static(Some(crate_type)),
1811                LinkSelfContainedDefault::InferredForMingw => {
1812                    sess.host == sess.target
1813                        && sess.target.vendor != "uwp"
1814                        && detect_self_contained_mingw(sess, linker)
1815                }
1816            }
1817        };
1818    if self_contained {
1819        LinkSelfContainedComponents::all()
1820    } else {
1821        LinkSelfContainedComponents::empty()
1822    }
1823}
1824
1825/// Add pre-link object files defined by the target spec.
1826fn add_pre_link_objects(
1827    cmd: &mut dyn Linker,
1828    sess: &Session,
1829    flavor: LinkerFlavor,
1830    link_output_kind: LinkOutputKind,
1831    self_contained: bool,
1832) {
1833    // FIXME: we are currently missing some infra here (per-linker-flavor CRT objects),
1834    // so Fuchsia has to be special-cased.
1835    let opts = &sess.target;
1836    let empty = Default::default();
1837    let objects = if self_contained {
1838        &opts.pre_link_objects_self_contained
1839    } else if !(sess.target.os == "fuchsia" && matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))) {
1840        &opts.pre_link_objects
1841    } else {
1842        &empty
1843    };
1844    for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1845        cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1846    }
1847}
1848
1849/// Add post-link object files defined by the target spec.
1850fn add_post_link_objects(
1851    cmd: &mut dyn Linker,
1852    sess: &Session,
1853    link_output_kind: LinkOutputKind,
1854    self_contained: bool,
1855) {
1856    let objects = if self_contained {
1857        &sess.target.post_link_objects_self_contained
1858    } else {
1859        &sess.target.post_link_objects
1860    };
1861    for obj in objects.get(&link_output_kind).iter().copied().flatten() {
1862        cmd.add_object(&get_object_file_path(sess, obj, self_contained));
1863    }
1864}
1865
1866/// Add arbitrary "pre-link" args defined by the target spec or from command line.
1867/// FIXME: Determine where exactly these args need to be inserted.
1868fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1869    if let Some(args) = sess.target.pre_link_args.get(&flavor) {
1870        cmd.verbatim_args(args.iter().map(Deref::deref));
1871    }
1872
1873    cmd.verbatim_args(&sess.opts.unstable_opts.pre_link_args);
1874}
1875
1876/// Add a link script embedded in the target, if applicable.
1877fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_type: CrateType) {
1878    match (crate_type, &sess.target.link_script) {
1879        (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
1880            if !sess.target.linker_flavor.is_gnu() {
1881                sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
1882            }
1883
1884            let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
1885
1886            let path = tmpdir.join(file_name);
1887            if let Err(error) = fs::write(&path, script.as_ref()) {
1888                sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
1889            }
1890
1891            cmd.link_arg("--script").link_arg(path);
1892        }
1893        _ => {}
1894    }
1895}
1896
1897/// Add arbitrary "user defined" args defined from command line.
1898/// FIXME: Determine where exactly these args need to be inserted.
1899fn add_user_defined_link_args(cmd: &mut dyn Linker, sess: &Session) {
1900    cmd.verbatim_args(&sess.opts.cg.link_args);
1901}
1902
1903/// Add arbitrary "late link" args defined by the target spec.
1904/// FIXME: Determine where exactly these args need to be inserted.
1905fn add_late_link_args(
1906    cmd: &mut dyn Linker,
1907    sess: &Session,
1908    flavor: LinkerFlavor,
1909    crate_type: CrateType,
1910    codegen_results: &CodegenResults,
1911) {
1912    let any_dynamic_crate = crate_type == CrateType::Dylib
1913        || crate_type == CrateType::Sdylib
1914        || codegen_results.crate_info.dependency_formats.iter().any(|(ty, list)| {
1915            *ty == crate_type && list.iter().any(|&linkage| linkage == Linkage::Dynamic)
1916        });
1917    if any_dynamic_crate {
1918        if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
1919            cmd.verbatim_args(args.iter().map(Deref::deref));
1920        }
1921    } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
1922        cmd.verbatim_args(args.iter().map(Deref::deref));
1923    }
1924    if let Some(args) = sess.target.late_link_args.get(&flavor) {
1925        cmd.verbatim_args(args.iter().map(Deref::deref));
1926    }
1927}
1928
1929/// Add arbitrary "post-link" args defined by the target spec.
1930/// FIXME: Determine where exactly these args need to be inserted.
1931fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
1932    if let Some(args) = sess.target.post_link_args.get(&flavor) {
1933        cmd.verbatim_args(args.iter().map(Deref::deref));
1934    }
1935}
1936
1937/// Add a synthetic object file that contains reference to all symbols that we want to expose to
1938/// the linker.
1939///
1940/// Background: we implement rlibs as static library (archives). Linkers treat archives
1941/// differently from object files: all object files participate in linking, while archives will
1942/// only participate in linking if they can satisfy at least one undefined reference (version
1943/// scripts doesn't count). This causes `#[no_mangle]` or `#[used]` items to be ignored by the
1944/// linker, and since they never participate in the linking, using `KEEP` in the linker scripts
1945/// can't keep them either. This causes #47384.
1946///
1947/// To keep them around, we could use `--whole-archive`, `-force_load` and equivalents to force rlib
1948/// to participate in linking like object files, but this proves to be expensive (#93791). Therefore
1949/// we instead just introduce an undefined reference to them. This could be done by `-u` command
1950/// line option to the linker or `EXTERN(...)` in linker scripts, however they does not only
1951/// introduce an undefined reference, but also make them the GC roots, preventing `--gc-sections`
1952/// from removing them, and this is especially problematic for embedded programming where every
1953/// byte counts.
1954///
1955/// This method creates a synthetic object file, which contains undefined references to all symbols
1956/// that are necessary for the linking. They are only present in symbol table but not actually
1957/// used in any sections, so the linker will therefore pick relevant rlibs for linking, but
1958/// unused `#[no_mangle]` or `#[used(compiler)]` can still be discard by GC sections.
1959///
1960/// There's a few internal crates in the standard library (aka libcore and
1961/// libstd) which actually have a circular dependence upon one another. This
1962/// currently arises through "weak lang items" where libcore requires things
1963/// like `rust_begin_unwind` but libstd ends up defining it. To get this
1964/// circular dependence to work correctly we declare some of these things
1965/// in this synthetic object.
1966fn add_linked_symbol_object(
1967    cmd: &mut dyn Linker,
1968    sess: &Session,
1969    tmpdir: &Path,
1970    symbols: &[(String, SymbolExportKind)],
1971) {
1972    if symbols.is_empty() {
1973        return;
1974    }
1975
1976    let Some(mut file) = super::metadata::create_object_file(sess) else {
1977        return;
1978    };
1979
1980    if file.format() == object::BinaryFormat::Coff {
1981        // NOTE(nbdd0121): MSVC will hang if the input object file contains no sections,
1982        // so add an empty section.
1983        file.add_section(Vec::new(), ".text".into(), object::SectionKind::Text);
1984
1985        // We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the
1986        // default mangler in `object` crate.
1987        file.set_mangling(object::write::Mangling::None);
1988    }
1989
1990    if file.format() == object::BinaryFormat::MachO {
1991        // Divide up the sections into sub-sections via symbols for dead code stripping.
1992        // Without this flag, unused `#[no_mangle]` or `#[used(compiler)]` cannot be
1993        // discard on MachO targets.
1994        file.set_subsections_via_symbols();
1995    }
1996
1997    // ld64 requires a relocation to load undefined symbols, see below.
1998    // Not strictly needed if linking with lld, but might as well do it there too.
1999    let ld64_section_helper = if file.format() == object::BinaryFormat::MachO {
2000        Some(file.add_section(
2001            file.segment_name(object::write::StandardSegment::Data).to_vec(),
2002            "__data".into(),
2003            object::SectionKind::Data,
2004        ))
2005    } else {
2006        None
2007    };
2008
2009    for (sym, kind) in symbols.iter() {
2010        let symbol = file.add_symbol(object::write::Symbol {
2011            name: sym.clone().into(),
2012            value: 0,
2013            size: 0,
2014            kind: match kind {
2015                SymbolExportKind::Text => object::SymbolKind::Text,
2016                SymbolExportKind::Data => object::SymbolKind::Data,
2017                SymbolExportKind::Tls => object::SymbolKind::Tls,
2018            },
2019            scope: object::SymbolScope::Unknown,
2020            weak: false,
2021            section: object::write::SymbolSection::Undefined,
2022            flags: object::SymbolFlags::None,
2023        });
2024
2025        // The linker shipped with Apple's Xcode, ld64, works a bit differently from other linkers.
2026        //
2027        // Code-wise, the relevant parts of ld64 are roughly:
2028        // 1. Find the `ArchiveLoadMode` based on commandline options, default to `parseObjects`.
2029        //    https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.cpp#L924-L932
2030        //    https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/Options.h#L55
2031        //
2032        // 2. Read the archive table of contents (__.SYMDEF file).
2033        //    https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L294-L325
2034        //
2035        // 3. Begin linking by loading "atoms" from input files.
2036        //    https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/doc/design/linker.html
2037        //    https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1349
2038        //
2039        //   a. Directly specified object files (`.o`) are parsed immediately.
2040        //      https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L4611-L4627
2041        //
2042        //     - Undefined symbols are not atoms (`n_value > 0` denotes a common symbol).
2043        //       https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/macho_relocatable_file.cpp#L2455-L2468
2044        //       https://maskray.me/blog/2022-02-06-all-about-common-symbols
2045        //
2046        //     - Relocations/fixups are atoms.
2047        //       https://github.com/apple-oss-distributions/ld64/blob/ce6341ae966b3451aa54eeb049f2be865afbd578/src/ld/parsers/macho_relocatable_file.cpp#L2088-L2114
2048        //
2049        //   b. Archives are not parsed yet.
2050        //      https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L467-L577
2051        //
2052        // 4. When a symbol is needed by an atom, parse the object file that contains the symbol.
2053        //    https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/InputFiles.cpp#L1417-L1491
2054        //    https://github.com/apple-oss-distributions/ld64/blob/ld64-954.16/src/ld/parsers/archive_file.cpp#L579-L597
2055        //
2056        // All of the steps above are fairly similar to other linkers, except that **it completely
2057        // ignores undefined symbols**.
2058        //
2059        // So to make this trick work on ld64, we need to do something else to load the relevant
2060        // object files. We do this by inserting a relocation (fixup) for each symbol.
2061        if let Some(section) = ld64_section_helper {
2062            apple::add_data_and_relocation(&mut file, section, symbol, &sess.target, *kind)
2063                .expect("failed adding relocation");
2064        }
2065    }
2066
2067    let path = tmpdir.join("symbols.o");
2068    let result = std::fs::write(&path, file.write().unwrap());
2069    if let Err(error) = result {
2070        sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
2071    }
2072    cmd.add_object(&path);
2073}
2074
2075/// Add object files containing code from the current crate.
2076fn add_local_crate_regular_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2077    for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) {
2078        cmd.add_object(obj);
2079    }
2080}
2081
2082/// Add object files for allocator code linked once for the whole crate tree.
2083fn add_local_crate_allocator_objects(cmd: &mut dyn Linker, codegen_results: &CodegenResults) {
2084    if let Some(obj) = codegen_results.allocator_module.as_ref().and_then(|m| m.object.as_ref()) {
2085        cmd.add_object(obj);
2086    }
2087}
2088
2089/// Add object files containing metadata for the current crate.
2090fn add_local_crate_metadata_objects(
2091    cmd: &mut dyn Linker,
2092    sess: &Session,
2093    archive_builder_builder: &dyn ArchiveBuilderBuilder,
2094    crate_type: CrateType,
2095    tmpdir: &Path,
2096    codegen_results: &CodegenResults,
2097    metadata: &EncodedMetadata,
2098) {
2099    // When linking a dynamic library, we put the metadata into a section of the
2100    // executable. This metadata is in a separate object file from the main
2101    // object file, so we create and link it in here.
2102    if matches!(crate_type, CrateType::Dylib | CrateType::ProcMacro) {
2103        let data = archive_builder_builder.create_dylib_metadata_wrapper(
2104            sess,
2105            &metadata,
2106            &codegen_results.crate_info.metadata_symbol,
2107        );
2108        let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");
2109
2110        cmd.add_object(&obj);
2111    }
2112}
2113
2114/// Add sysroot and other globally set directories to the directory search list.
2115fn add_library_search_dirs(
2116    cmd: &mut dyn Linker,
2117    sess: &Session,
2118    self_contained_components: LinkSelfContainedComponents,
2119    apple_sdk_root: Option<&Path>,
2120) {
2121    if !sess.opts.unstable_opts.link_native_libraries {
2122        return;
2123    }
2124
2125    let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
2126    let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
2127        if is_framework {
2128            cmd.framework_path(dir);
2129        } else {
2130            cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
2131        }
2132        ControlFlow::<()>::Continue(())
2133    });
2134}
2135
2136/// Add options making relocation sections in the produced ELF files read-only
2137/// and suppressing lazy binding.
2138fn add_relro_args(cmd: &mut dyn Linker, sess: &Session) {
2139    match sess.opts.cg.relro_level.unwrap_or(sess.target.relro_level) {
2140        RelroLevel::Full => cmd.full_relro(),
2141        RelroLevel::Partial => cmd.partial_relro(),
2142        RelroLevel::Off => cmd.no_relro(),
2143        RelroLevel::None => {}
2144    }
2145}
2146
2147/// Add library search paths used at runtime by dynamic linkers.
2148fn add_rpath_args(
2149    cmd: &mut dyn Linker,
2150    sess: &Session,
2151    codegen_results: &CodegenResults,
2152    out_filename: &Path,
2153) {
2154    if !sess.target.has_rpath {
2155        return;
2156    }
2157
2158    // FIXME (#2397): At some point we want to rpath our guesses as to
2159    // where extern libraries might live, based on the
2160    // add_lib_search_paths
2161    if sess.opts.cg.rpath {
2162        let libs = codegen_results
2163            .crate_info
2164            .used_crates
2165            .iter()
2166            .filter_map(|cnum| {
2167                codegen_results.crate_info.used_crate_source[cnum]
2168                    .dylib
2169                    .as_ref()
2170                    .map(|(path, _)| &**path)
2171            })
2172            .collect::<Vec<_>>();
2173        let rpath_config = RPathConfig {
2174            libs: &*libs,
2175            out_filename: out_filename.to_path_buf(),
2176            is_like_darwin: sess.target.is_like_darwin,
2177            linker_is_gnu: sess.target.linker_flavor.is_gnu(),
2178        };
2179        cmd.link_args(&rpath::get_rpath_linker_args(&rpath_config));
2180    }
2181}
2182
2183/// Produce the linker command line containing linker path and arguments.
2184///
2185/// When comments in the function say "order-(in)dependent" they mean order-dependence between
2186/// options and libraries/object files. For example `--whole-archive` (order-dependent) applies
2187/// to specific libraries passed after it, and `-o` (output file, order-independent) applies
2188/// to the linking process as a whole.
2189/// Order-independent options may still override each other in order-dependent fashion,
2190/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2191fn linker_with_args(
2192    path: &Path,
2193    flavor: LinkerFlavor,
2194    sess: &Session,
2195    archive_builder_builder: &dyn ArchiveBuilderBuilder,
2196    crate_type: CrateType,
2197    tmpdir: &Path,
2198    out_filename: &Path,
2199    codegen_results: &CodegenResults,
2200    metadata: &EncodedMetadata,
2201    self_contained_components: LinkSelfContainedComponents,
2202) -> Command {
2203    let self_contained_crt_objects = self_contained_components.is_crt_objects_enabled();
2204    let cmd = &mut *super::linker::get_linker(
2205        sess,
2206        path,
2207        flavor,
2208        self_contained_components.are_any_components_enabled(),
2209        &codegen_results.crate_info.target_cpu,
2210    );
2211    let link_output_kind = link_output_kind(sess, crate_type);
2212
2213    // ------------ Early order-dependent options ------------
2214
2215    // If we're building something like a dynamic library then some platforms
2216    // need to make sure that all symbols are exported correctly from the
2217    // dynamic library.
2218    // Must be passed before any libraries to prevent the symbols to export from being thrown away,
2219    // at least on some platforms (e.g. windows-gnu).
2220    cmd.export_symbols(
2221        tmpdir,
2222        crate_type,
2223        &codegen_results.crate_info.exported_symbols[&crate_type],
2224    );
2225
2226    // Can be used for adding custom CRT objects or overriding order-dependent options above.
2227    // FIXME: In practice built-in target specs use this for arbitrary order-independent options,
2228    // introduce a target spec option for order-independent linker options and migrate built-in
2229    // specs to it.
2230    add_pre_link_args(cmd, sess, flavor);
2231
2232    // ------------ Object code and libraries, order-dependent ------------
2233
2234    // Pre-link CRT objects.
2235    add_pre_link_objects(cmd, sess, flavor, link_output_kind, self_contained_crt_objects);
2236
2237    add_linked_symbol_object(
2238        cmd,
2239        sess,
2240        tmpdir,
2241        &codegen_results.crate_info.linked_symbols[&crate_type],
2242    );
2243
2244    // Sanitizer libraries.
2245    add_sanitizer_libraries(sess, flavor, crate_type, cmd);
2246
2247    // Object code from the current crate.
2248    // Take careful note of the ordering of the arguments we pass to the linker
2249    // here. Linkers will assume that things on the left depend on things to the
2250    // right. Things on the right cannot depend on things on the left. This is
2251    // all formally implemented in terms of resolving symbols (libs on the right
2252    // resolve unknown symbols of libs on the left, but not vice versa).
2253    //
2254    // For this reason, we have organized the arguments we pass to the linker as
2255    // such:
2256    //
2257    // 1. The local object that LLVM just generated
2258    // 2. Local native libraries
2259    // 3. Upstream rust libraries
2260    // 4. Upstream native libraries
2261    //
2262    // The rationale behind this ordering is that those items lower down in the
2263    // list can't depend on items higher up in the list. For example nothing can
2264    // depend on what we just generated (e.g., that'd be a circular dependency).
2265    // Upstream rust libraries are not supposed to depend on our local native
2266    // libraries as that would violate the structure of the DAG, in that
2267    // scenario they are required to link to them as well in a shared fashion.
2268    //
2269    // Note that upstream rust libraries may contain native dependencies as
2270    // well, but they also can't depend on what we just started to add to the
2271    // link line. And finally upstream native libraries can't depend on anything
2272    // in this DAG so far because they can only depend on other native libraries
2273    // and such dependencies are also required to be specified.
2274    add_local_crate_regular_objects(cmd, codegen_results);
2275    add_local_crate_metadata_objects(
2276        cmd,
2277        sess,
2278        archive_builder_builder,
2279        crate_type,
2280        tmpdir,
2281        codegen_results,
2282        metadata,
2283    );
2284    add_local_crate_allocator_objects(cmd, codegen_results);
2285
2286    // Avoid linking to dynamic libraries unless they satisfy some undefined symbols
2287    // at the point at which they are specified on the command line.
2288    // Must be passed before any (dynamic) libraries to have effect on them.
2289    // On Solaris-like systems, `-z ignore` acts as both `--as-needed` and `--gc-sections`
2290    // so it will ignore unreferenced ELF sections from relocatable objects.
2291    // For that reason, we put this flag after metadata objects as they would otherwise be removed.
2292    // FIXME: Support more fine-grained dead code removal on Solaris/illumos
2293    // and move this option back to the top.
2294    cmd.add_as_needed();
2295
2296    // Local native libraries of all kinds.
2297    add_local_native_libraries(
2298        cmd,
2299        sess,
2300        archive_builder_builder,
2301        codegen_results,
2302        tmpdir,
2303        link_output_kind,
2304    );
2305
2306    // Upstream rust crates and their non-dynamic native libraries.
2307    add_upstream_rust_crates(
2308        cmd,
2309        sess,
2310        archive_builder_builder,
2311        codegen_results,
2312        crate_type,
2313        tmpdir,
2314        link_output_kind,
2315    );
2316
2317    // Dynamic native libraries from upstream crates.
2318    add_upstream_native_libraries(
2319        cmd,
2320        sess,
2321        archive_builder_builder,
2322        codegen_results,
2323        tmpdir,
2324        link_output_kind,
2325    );
2326
2327    // Raw-dylibs from all crates.
2328    let raw_dylib_dir = tmpdir.join("raw-dylibs");
2329    if sess.target.binary_format == BinaryFormat::Elf {
2330        // On ELF we can't pass the raw-dylibs stubs to the linker as a path,
2331        // instead we need to pass them via -l. To find the stub, we need to add
2332        // the directory of the stub to the linker search path.
2333        // We make an extra directory for this to avoid polluting the search path.
2334        if let Err(error) = fs::create_dir(&raw_dylib_dir) {
2335            sess.dcx().emit_fatal(errors::CreateTempDir { error })
2336        }
2337        cmd.include_path(&raw_dylib_dir);
2338    }
2339
2340    // Link with the import library generated for any raw-dylib functions.
2341    if sess.target.is_like_windows {
2342        for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2343            sess,
2344            archive_builder_builder,
2345            codegen_results.crate_info.used_libraries.iter(),
2346            tmpdir,
2347            true,
2348        ) {
2349            cmd.add_object(&output_path);
2350        }
2351    } else {
2352        for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2353            sess,
2354            codegen_results.crate_info.used_libraries.iter(),
2355            &raw_dylib_dir,
2356        ) {
2357            // Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2358            cmd.link_dylib_by_name(&link_path, true, false);
2359        }
2360    }
2361    // As with add_upstream_native_libraries, we need to add the upstream raw-dylib symbols in case
2362    // they are used within inlined functions or instantiated generic functions. We do this *after*
2363    // handling the raw-dylib symbols in the current crate to make sure that those are chosen first
2364    // by the linker.
2365    let dependency_linkage = codegen_results
2366        .crate_info
2367        .dependency_formats
2368        .get(&crate_type)
2369        .expect("failed to find crate type in dependency format list");
2370
2371    // We sort the libraries below
2372    #[allow(rustc::potential_query_instability)]
2373    let mut native_libraries_from_nonstatics = codegen_results
2374        .crate_info
2375        .native_libraries
2376        .iter()
2377        .filter_map(|(&cnum, libraries)| {
2378            if sess.target.is_like_windows {
2379                (dependency_linkage[cnum] != Linkage::Static).then_some(libraries)
2380            } else {
2381                Some(libraries)
2382            }
2383        })
2384        .flatten()
2385        .collect::<Vec<_>>();
2386    native_libraries_from_nonstatics.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
2387
2388    if sess.target.is_like_windows {
2389        for output_path in raw_dylib::create_raw_dylib_dll_import_libs(
2390            sess,
2391            archive_builder_builder,
2392            native_libraries_from_nonstatics,
2393            tmpdir,
2394            false,
2395        ) {
2396            cmd.add_object(&output_path);
2397        }
2398    } else {
2399        for link_path in raw_dylib::create_raw_dylib_elf_stub_shared_objects(
2400            sess,
2401            native_libraries_from_nonstatics,
2402            &raw_dylib_dir,
2403        ) {
2404            // Always use verbatim linkage, see comments in create_raw_dylib_elf_stub_shared_objects.
2405            cmd.link_dylib_by_name(&link_path, true, false);
2406        }
2407    }
2408
2409    // Library linking above uses some global state for things like `-Bstatic`/`-Bdynamic` to make
2410    // command line shorter, reset it to default here before adding more libraries.
2411    cmd.reset_per_library_state();
2412
2413    // FIXME: Built-in target specs occasionally use this for linking system libraries,
2414    // eliminate all such uses by migrating them to `#[link]` attributes in `lib(std,c,unwind)`
2415    // and remove the option.
2416    add_late_link_args(cmd, sess, flavor, crate_type, codegen_results);
2417
2418    // ------------ Arbitrary order-independent options ------------
2419
2420    // Add order-independent options determined by rustc from its compiler options,
2421    // target properties and source code.
2422    add_order_independent_options(
2423        cmd,
2424        sess,
2425        link_output_kind,
2426        self_contained_components,
2427        flavor,
2428        crate_type,
2429        codegen_results,
2430        out_filename,
2431        tmpdir,
2432    );
2433
2434    // Can be used for arbitrary order-independent options.
2435    // In practice may also be occasionally used for linking native libraries.
2436    // Passed after compiler-generated options to support manual overriding when necessary.
2437    add_user_defined_link_args(cmd, sess);
2438
2439    // ------------ Builtin configurable linker scripts ------------
2440    // The user's link args should be able to overwrite symbols in the compiler's
2441    // linker script that were weakly defined (i.e. defined with `PROVIDE()`). For this
2442    // to work correctly, the user needs to be able to specify linker arguments like
2443    // `--defsym` and `--script` *before* any builtin linker scripts are evaluated.
2444    add_link_script(cmd, sess, tmpdir, crate_type);
2445
2446    // ------------ Object code and libraries, order-dependent ------------
2447
2448    // Post-link CRT objects.
2449    add_post_link_objects(cmd, sess, link_output_kind, self_contained_crt_objects);
2450
2451    // ------------ Late order-dependent options ------------
2452
2453    // Doesn't really make sense.
2454    // FIXME: In practice built-in target specs use this for arbitrary order-independent options.
2455    // Introduce a target spec option for order-independent linker options, migrate built-in specs
2456    // to it and remove the option. Currently the last holdout is wasm32-unknown-emscripten.
2457    add_post_link_args(cmd, sess, flavor);
2458
2459    cmd.take_cmd()
2460}
2461
2462fn add_order_independent_options(
2463    cmd: &mut dyn Linker,
2464    sess: &Session,
2465    link_output_kind: LinkOutputKind,
2466    self_contained_components: LinkSelfContainedComponents,
2467    flavor: LinkerFlavor,
2468    crate_type: CrateType,
2469    codegen_results: &CodegenResults,
2470    out_filename: &Path,
2471    tmpdir: &Path,
2472) {
2473    // Take care of the flavors and CLI options requesting the `lld` linker.
2474    add_lld_args(cmd, sess, flavor, self_contained_components);
2475
2476    add_apple_link_args(cmd, sess, flavor);
2477
2478    let apple_sdk_root = add_apple_sdk(cmd, sess, flavor);
2479
2480    if sess.target.os == "fuchsia"
2481        && crate_type == CrateType::Executable
2482        && !matches!(flavor, LinkerFlavor::Gnu(Cc::Yes, _))
2483    {
2484        let prefix = if sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::ADDRESS) {
2485            "asan/"
2486        } else {
2487            ""
2488        };
2489        cmd.link_arg(format!("--dynamic-linker={prefix}ld.so.1"));
2490    }
2491
2492    if sess.target.eh_frame_header {
2493        cmd.add_eh_frame_header();
2494    }
2495
2496    // Make the binary compatible with data execution prevention schemes.
2497    cmd.add_no_exec();
2498
2499    if self_contained_components.is_crt_objects_enabled() {
2500        cmd.no_crt_objects();
2501    }
2502
2503    if sess.target.os == "emscripten" {
2504        cmd.cc_arg(if sess.opts.unstable_opts.emscripten_wasm_eh {
2505            "-fwasm-exceptions"
2506        } else if sess.panic_strategy() == PanicStrategy::Abort {
2507            "-sDISABLE_EXCEPTION_CATCHING=1"
2508        } else {
2509            "-sDISABLE_EXCEPTION_CATCHING=0"
2510        });
2511    }
2512
2513    if flavor == LinkerFlavor::Llbc {
2514        cmd.link_args(&[
2515            "--target",
2516            &versioned_llvm_target(sess),
2517            "--target-cpu",
2518            &codegen_results.crate_info.target_cpu,
2519        ]);
2520        if codegen_results.crate_info.target_features.len() > 0 {
2521            cmd.link_arg(&format!(
2522                "--target-feature={}",
2523                &codegen_results.crate_info.target_features.join(",")
2524            ));
2525        }
2526    } else if flavor == LinkerFlavor::Ptx {
2527        cmd.link_args(&["--fallback-arch", &codegen_results.crate_info.target_cpu]);
2528    } else if flavor == LinkerFlavor::Bpf {
2529        cmd.link_args(&["--cpu", &codegen_results.crate_info.target_cpu]);
2530        if let Some(feat) = [sess.opts.cg.target_feature.as_str(), &sess.target.options.features]
2531            .into_iter()
2532            .find(|feat| !feat.is_empty())
2533        {
2534            cmd.link_args(&["--cpu-features", feat]);
2535        }
2536    }
2537
2538    cmd.linker_plugin_lto();
2539
2540    add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref());
2541
2542    cmd.output_filename(out_filename);
2543
2544    if crate_type == CrateType::Executable
2545        && sess.target.is_like_windows
2546        && let Some(s) = &codegen_results.crate_info.windows_subsystem
2547    {
2548        cmd.subsystem(s);
2549    }
2550
2551    // Try to strip as much out of the generated object by removing unused
2552    // sections if possible. See more comments in linker.rs
2553    if !sess.link_dead_code() {
2554        // If PGO is enabled sometimes gc_sections will remove the profile data section
2555        // as it appears to be unused. This can then cause the PGO profile file to lose
2556        // some functions. If we are generating a profile we shouldn't strip those metadata
2557        // sections to ensure we have all the data for PGO.
2558        let keep_metadata =
2559            crate_type == CrateType::Dylib || sess.opts.cg.profile_generate.enabled();
2560        cmd.gc_sections(keep_metadata);
2561    }
2562
2563    cmd.set_output_kind(link_output_kind, crate_type, out_filename);
2564
2565    add_relro_args(cmd, sess);
2566
2567    // Pass optimization flags down to the linker.
2568    cmd.optimize();
2569
2570    // Gather the set of NatVis files, if any, and write them out to a temp directory.
2571    let natvis_visualizers = collect_natvis_visualizers(
2572        tmpdir,
2573        sess,
2574        &codegen_results.crate_info.local_crate_name,
2575        &codegen_results.crate_info.natvis_debugger_visualizers,
2576    );
2577
2578    // Pass debuginfo, NatVis debugger visualizers and strip flags down to the linker.
2579    cmd.debuginfo(sess.opts.cg.strip, &natvis_visualizers);
2580
2581    // We want to prevent the compiler from accidentally leaking in any system libraries,
2582    // so by default we tell linkers not to link to any default libraries.
2583    if !sess.opts.cg.default_linker_libraries && sess.target.no_default_libraries {
2584        cmd.no_default_libraries();
2585    }
2586
2587    if sess.opts.cg.profile_generate.enabled() || sess.instrument_coverage() {
2588        cmd.pgo_gen();
2589    }
2590
2591    if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
2592        cmd.control_flow_guard();
2593    }
2594
2595    // OBJECT-FILES-NO, AUDIT-ORDER
2596    if sess.opts.unstable_opts.ehcont_guard {
2597        cmd.ehcont_guard();
2598    }
2599
2600    add_rpath_args(cmd, sess, codegen_results, out_filename);
2601}
2602
2603// Write the NatVis debugger visualizer files for each crate to the temp directory and gather the file paths.
2604fn collect_natvis_visualizers(
2605    tmpdir: &Path,
2606    sess: &Session,
2607    crate_name: &Symbol,
2608    natvis_debugger_visualizers: &BTreeSet<DebuggerVisualizerFile>,
2609) -> Vec<PathBuf> {
2610    let mut visualizer_paths = Vec::with_capacity(natvis_debugger_visualizers.len());
2611
2612    for (index, visualizer) in natvis_debugger_visualizers.iter().enumerate() {
2613        let visualizer_out_file = tmpdir.join(format!("{}-{}.natvis", crate_name.as_str(), index));
2614
2615        match fs::write(&visualizer_out_file, &visualizer.src) {
2616            Ok(()) => {
2617                visualizer_paths.push(visualizer_out_file);
2618            }
2619            Err(error) => {
2620                sess.dcx().emit_warn(errors::UnableToWriteDebuggerVisualizer {
2621                    path: visualizer_out_file,
2622                    error,
2623                });
2624            }
2625        };
2626    }
2627    visualizer_paths
2628}
2629
2630fn add_native_libs_from_crate(
2631    cmd: &mut dyn Linker,
2632    sess: &Session,
2633    archive_builder_builder: &dyn ArchiveBuilderBuilder,
2634    codegen_results: &CodegenResults,
2635    tmpdir: &Path,
2636    bundled_libs: &FxIndexSet<Symbol>,
2637    cnum: CrateNum,
2638    link_static: bool,
2639    link_dynamic: bool,
2640    link_output_kind: LinkOutputKind,
2641) {
2642    if !sess.opts.unstable_opts.link_native_libraries {
2643        // If `-Zlink-native-libraries=false` is set, then the assumption is that an
2644        // external build system already has the native dependencies defined, and it
2645        // will provide them to the linker itself.
2646        return;
2647    }
2648
2649    if link_static && cnum != LOCAL_CRATE && !bundled_libs.is_empty() {
2650        // If rlib contains native libs as archives, unpack them to tmpdir.
2651        let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0;
2652        archive_builder_builder
2653            .extract_bundled_libs(rlib, tmpdir, bundled_libs)
2654            .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
2655    }
2656
2657    let native_libs = match cnum {
2658        LOCAL_CRATE => &codegen_results.crate_info.used_libraries,
2659        _ => &codegen_results.crate_info.native_libraries[&cnum],
2660    };
2661
2662    let mut last = (None, NativeLibKind::Unspecified, false);
2663    for lib in native_libs {
2664        if !relevant_lib(sess, lib) {
2665            continue;
2666        }
2667
2668        // Skip if this library is the same as the last.
2669        last = if (Some(lib.name), lib.kind, lib.verbatim) == last {
2670            continue;
2671        } else {
2672            (Some(lib.name), lib.kind, lib.verbatim)
2673        };
2674
2675        let name = lib.name.as_str();
2676        let verbatim = lib.verbatim;
2677        match lib.kind {
2678            NativeLibKind::Static { bundle, whole_archive } => {
2679                if link_static {
2680                    let bundle = bundle.unwrap_or(true);
2681                    let whole_archive = whole_archive == Some(true);
2682                    if bundle && cnum != LOCAL_CRATE {
2683                        if let Some(filename) = lib.filename {
2684                            // If rlib contains native libs as archives, they are unpacked to tmpdir.
2685                            let path = tmpdir.join(filename.as_str());
2686                            cmd.link_staticlib_by_path(&path, whole_archive);
2687                        }
2688                    } else {
2689                        cmd.link_staticlib_by_name(name, verbatim, whole_archive);
2690                    }
2691                }
2692            }
2693            NativeLibKind::Dylib { as_needed } => {
2694                if link_dynamic {
2695                    cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
2696                }
2697            }
2698            NativeLibKind::Unspecified => {
2699                // If we are generating a static binary, prefer static library when the
2700                // link kind is unspecified.
2701                if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
2702                    if link_static {
2703                        cmd.link_staticlib_by_name(name, verbatim, false);
2704                    }
2705                } else if link_dynamic {
2706                    cmd.link_dylib_by_name(name, verbatim, true);
2707                }
2708            }
2709            NativeLibKind::Framework { as_needed } => {
2710                if link_dynamic {
2711                    cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
2712                }
2713            }
2714            NativeLibKind::RawDylib => {
2715                // Handled separately in `linker_with_args`.
2716            }
2717            NativeLibKind::WasmImportModule => {}
2718            NativeLibKind::LinkArg => {
2719                if link_static {
2720                    if verbatim {
2721                        cmd.verbatim_arg(name);
2722                    } else {
2723                        cmd.link_arg(name);
2724                    }
2725                }
2726            }
2727        }
2728    }
2729}
2730
2731fn add_local_native_libraries(
2732    cmd: &mut dyn Linker,
2733    sess: &Session,
2734    archive_builder_builder: &dyn ArchiveBuilderBuilder,
2735    codegen_results: &CodegenResults,
2736    tmpdir: &Path,
2737    link_output_kind: LinkOutputKind,
2738) {
2739    // All static and dynamic native library dependencies are linked to the local crate.
2740    let link_static = true;
2741    let link_dynamic = true;
2742    add_native_libs_from_crate(
2743        cmd,
2744        sess,
2745        archive_builder_builder,
2746        codegen_results,
2747        tmpdir,
2748        &Default::default(),
2749        LOCAL_CRATE,
2750        link_static,
2751        link_dynamic,
2752        link_output_kind,
2753    );
2754}
2755
2756fn add_upstream_rust_crates(
2757    cmd: &mut dyn Linker,
2758    sess: &Session,
2759    archive_builder_builder: &dyn ArchiveBuilderBuilder,
2760    codegen_results: &CodegenResults,
2761    crate_type: CrateType,
2762    tmpdir: &Path,
2763    link_output_kind: LinkOutputKind,
2764) {
2765    // All of the heavy lifting has previously been accomplished by the
2766    // dependency_format module of the compiler. This is just crawling the
2767    // output of that module, adding crates as necessary.
2768    //
2769    // Linking to a rlib involves just passing it to the linker (the linker
2770    // will slurp up the object files inside), and linking to a dynamic library
2771    // involves just passing the right -l flag.
2772    let data = codegen_results
2773        .crate_info
2774        .dependency_formats
2775        .get(&crate_type)
2776        .expect("failed to find crate type in dependency format list");
2777
2778    if sess.target.is_like_aix {
2779        // Unlike ELF linkers, AIX doesn't feature `DT_SONAME` to override
2780        // the dependency name when outputting a shared library. Thus, `ld` will
2781        // use the full path to shared libraries as the dependency if passed it
2782        // by default unless `noipath` is passed.
2783        // https://www.ibm.com/docs/en/aix/7.3?topic=l-ld-command.
2784        cmd.link_or_cc_arg("-bnoipath");
2785    }
2786
2787    for &cnum in &codegen_results.crate_info.used_crates {
2788        // We may not pass all crates through to the linker. Some crates may appear statically in
2789        // an existing dylib, meaning we'll pick up all the symbols from the dylib.
2790        // We must always link crates `compiler_builtins` and `profiler_builtins` statically.
2791        // Even if they were already included into a dylib
2792        // (e.g. `libstd` when `-C prefer-dynamic` is used).
2793        // FIXME: `dependency_formats` can report `profiler_builtins` as `NotLinked` for some
2794        // reason, it shouldn't do that because `profiler_builtins` should indeed be linked.
2795        let linkage = data[cnum];
2796        let link_static_crate = linkage == Linkage::Static
2797            || (linkage == Linkage::IncludedFromDylib || linkage == Linkage::NotLinked)
2798                && (codegen_results.crate_info.compiler_builtins == Some(cnum)
2799                    || codegen_results.crate_info.profiler_runtime == Some(cnum));
2800
2801        let mut bundled_libs = Default::default();
2802        match linkage {
2803            Linkage::Static | Linkage::IncludedFromDylib | Linkage::NotLinked => {
2804                if link_static_crate {
2805                    bundled_libs = codegen_results.crate_info.native_libraries[&cnum]
2806                        .iter()
2807                        .filter_map(|lib| lib.filename)
2808                        .collect();
2809                    add_static_crate(
2810                        cmd,
2811                        sess,
2812                        archive_builder_builder,
2813                        codegen_results,
2814                        tmpdir,
2815                        cnum,
2816                        &bundled_libs,
2817                    );
2818                }
2819            }
2820            Linkage::Dynamic => {
2821                let src = &codegen_results.crate_info.used_crate_source[&cnum];
2822                add_dynamic_crate(cmd, sess, &src.dylib.as_ref().unwrap().0);
2823            }
2824        }
2825
2826        // Static libraries are linked for a subset of linked upstream crates.
2827        // 1. If the upstream crate is a directly linked rlib then we must link the native library
2828        // because the rlib is just an archive.
2829        // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we do not link
2830        // the native library because it is already linked into the dylib, and even if
2831        // inline/const/generic functions from the dylib can refer to symbols from the native
2832        // library, those symbols should be exported and available from the dylib anyway.
2833        // 3. Libraries bundled into `(compiler,profiler)_builtins` are special, see above.
2834        let link_static = link_static_crate;
2835        // Dynamic libraries are not linked here, see the FIXME in `add_upstream_native_libraries`.
2836        let link_dynamic = false;
2837        add_native_libs_from_crate(
2838            cmd,
2839            sess,
2840            archive_builder_builder,
2841            codegen_results,
2842            tmpdir,
2843            &bundled_libs,
2844            cnum,
2845            link_static,
2846            link_dynamic,
2847            link_output_kind,
2848        );
2849    }
2850}
2851
2852fn add_upstream_native_libraries(
2853    cmd: &mut dyn Linker,
2854    sess: &Session,
2855    archive_builder_builder: &dyn ArchiveBuilderBuilder,
2856    codegen_results: &CodegenResults,
2857    tmpdir: &Path,
2858    link_output_kind: LinkOutputKind,
2859) {
2860    for &cnum in &codegen_results.crate_info.used_crates {
2861        // Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
2862        // FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
2863        // are linked together with their respective upstream crates, and in their originally
2864        // specified order. This is slightly breaking due to our use of `--as-needed` (see crater
2865        // results in https://github.com/rust-lang/rust/pull/102832#issuecomment-1279772306).
2866        let link_static = false;
2867        // Dynamic libraries are linked for all linked upstream crates.
2868        // 1. If the upstream crate is a directly linked rlib then we must link the native library
2869        // because the rlib is just an archive.
2870        // 2. If the upstream crate is a dylib or a rlib linked through dylib, then we have to link
2871        // the native library too because inline/const/generic functions from the dylib can refer
2872        // to symbols from the native library, so the native library providing those symbols should
2873        // be available when linking our final binary.
2874        let link_dynamic = true;
2875        add_native_libs_from_crate(
2876            cmd,
2877            sess,
2878            archive_builder_builder,
2879            codegen_results,
2880            tmpdir,
2881            &Default::default(),
2882            cnum,
2883            link_static,
2884            link_dynamic,
2885            link_output_kind,
2886        );
2887    }
2888}
2889
2890// Rehome lib paths (which exclude the library file name) that point into the sysroot lib directory
2891// to be relative to the sysroot directory, which may be a relative path specified by the user.
2892//
2893// If the sysroot is a relative path, and the sysroot libs are specified as an absolute path, the
2894// linker command line can be non-deterministic due to the paths including the current working
2895// directory. The linker command line needs to be deterministic since it appears inside the PDB
2896// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
2897//
2898// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
2899fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
2900    let sysroot_lib_path = &sess.target_tlib_path.dir;
2901    let canonical_sysroot_lib_path =
2902        { try_canonicalize(sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
2903
2904    let canonical_lib_dir = try_canonicalize(lib_dir).unwrap_or_else(|_| lib_dir.to_path_buf());
2905    if canonical_lib_dir == canonical_sysroot_lib_path {
2906        // This path already had `fix_windows_verbatim_for_gcc()` applied if needed.
2907        sysroot_lib_path.clone()
2908    } else {
2909        fix_windows_verbatim_for_gcc(lib_dir)
2910    }
2911}
2912
2913fn rehome_lib_path(sess: &Session, path: &Path) -> PathBuf {
2914    if let Some(dir) = path.parent() {
2915        let file_name = path.file_name().expect("library path has no file name component");
2916        rehome_sysroot_lib_dir(sess, dir).join(file_name)
2917    } else {
2918        fix_windows_verbatim_for_gcc(path)
2919    }
2920}
2921
2922// Adds the static "rlib" versions of all crates to the command line.
2923// There's a bit of magic which happens here specifically related to LTO,
2924// namely that we remove upstream object files.
2925//
2926// When performing LTO, almost(*) all of the bytecode from the upstream
2927// libraries has already been included in our object file output. As a
2928// result we need to remove the object files in the upstream libraries so
2929// the linker doesn't try to include them twice (or whine about duplicate
2930// symbols). We must continue to include the rest of the rlib, however, as
2931// it may contain static native libraries which must be linked in.
2932//
2933// (*) Crates marked with `#![no_builtins]` don't participate in LTO and
2934// their bytecode wasn't included. The object files in those libraries must
2935// still be passed to the linker.
2936//
2937// Note, however, that if we're not doing LTO we can just pass the rlib
2938// blindly to the linker (fast) because it's fine if it's not actually
2939// included as we're at the end of the dependency chain.
2940fn add_static_crate(
2941    cmd: &mut dyn Linker,
2942    sess: &Session,
2943    archive_builder_builder: &dyn ArchiveBuilderBuilder,
2944    codegen_results: &CodegenResults,
2945    tmpdir: &Path,
2946    cnum: CrateNum,
2947    bundled_lib_file_names: &FxIndexSet<Symbol>,
2948) {
2949    let src = &codegen_results.crate_info.used_crate_source[&cnum];
2950    let cratepath = &src.rlib.as_ref().unwrap().0;
2951
2952    let mut link_upstream =
2953        |path: &Path| cmd.link_staticlib_by_path(&rehome_lib_path(sess, path), false);
2954
2955    if !are_upstream_rust_objects_already_included(sess)
2956        || ignored_for_lto(sess, &codegen_results.crate_info, cnum)
2957    {
2958        link_upstream(cratepath);
2959        return;
2960    }
2961
2962    let dst = tmpdir.join(cratepath.file_name().unwrap());
2963    let name = cratepath.file_name().unwrap().to_str().unwrap();
2964    let name = &name[3..name.len() - 5]; // chop off lib/.rlib
2965    let bundled_lib_file_names = bundled_lib_file_names.clone();
2966
2967    sess.prof.generic_activity_with_arg("link_altering_rlib", name).run(|| {
2968        let canonical_name = name.replace('-', "_");
2969        let upstream_rust_objects_already_included =
2970            are_upstream_rust_objects_already_included(sess);
2971        let is_builtins =
2972            sess.target.no_builtins || !codegen_results.crate_info.is_no_builtins.contains(&cnum);
2973
2974        let mut archive = archive_builder_builder.new_archive_builder(sess);
2975        if let Err(error) = archive.add_archive(
2976            cratepath,
2977            Box::new(move |f| {
2978                if f == METADATA_FILENAME {
2979                    return true;
2980                }
2981
2982                let canonical = f.replace('-', "_");
2983
2984                let is_rust_object =
2985                    canonical.starts_with(&canonical_name) && looks_like_rust_object_file(f);
2986
2987                // If we're performing LTO and this is a rust-generated object
2988                // file, then we don't need the object file as it's part of the
2989                // LTO module. Note that `#![no_builtins]` is excluded from LTO,
2990                // though, so we let that object file slide.
2991                if upstream_rust_objects_already_included && is_rust_object && is_builtins {
2992                    return true;
2993                }
2994
2995                // We skip native libraries because:
2996                // 1. This native libraries won't be used from the generated rlib,
2997                //    so we can throw them away to avoid the copying work.
2998                // 2. We can't allow it to be a single remaining entry in archive
2999                //    as some linkers may complain on that.
3000                if bundled_lib_file_names.contains(&Symbol::intern(f)) {
3001                    return true;
3002                }
3003
3004                false
3005            }),
3006        ) {
3007            sess.dcx()
3008                .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error });
3009        }
3010        if archive.build(&dst) {
3011            link_upstream(&dst);
3012        }
3013    });
3014}
3015
3016// Same thing as above, but for dynamic crates instead of static crates.
3017fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
3018    cmd.link_dylib_by_path(&rehome_lib_path(sess, cratepath), true);
3019}
3020
3021fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
3022    match lib.cfg {
3023        Some(ref cfg) => {
3024            eval_config_entry(sess, cfg, CRATE_NODE_ID, None, ShouldEmit::ErrorsAndLints).as_bool()
3025        }
3026        None => true,
3027    }
3028}
3029
3030pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
3031    match sess.lto() {
3032        config::Lto::Fat => true,
3033        config::Lto::Thin => {
3034            // If we defer LTO to the linker, we haven't run LTO ourselves, so
3035            // any upstream object files have not been copied yet.
3036            !sess.opts.cg.linker_plugin_lto.enabled()
3037        }
3038        config::Lto::No | config::Lto::ThinLocal => false,
3039    }
3040}
3041
3042/// We need to communicate five things to the linker on Apple/Darwin targets:
3043/// - The architecture.
3044/// - The operating system (and that it's an Apple platform).
3045/// - The environment.
3046/// - The deployment target.
3047/// - The SDK version.
3048fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
3049    if !sess.target.is_like_darwin {
3050        return;
3051    }
3052    let LinkerFlavor::Darwin(cc, _) = flavor else {
3053        return;
3054    };
3055
3056    // `sess.target.arch` (`target_arch`) is not detailed enough.
3057    let llvm_arch = sess.target.llvm_target.split_once('-').expect("LLVM target must have arch").0;
3058    let target_os = &*sess.target.os;
3059    let target_env = &*sess.target.env;
3060
3061    // The architecture name to forward to the linker.
3062    //
3063    // Supported architecture names can be found in the source:
3064    // https://github.com/apple-oss-distributions/ld64/blob/ld64-951.9/src/abstraction/MachOFileAbstraction.hpp#L578-L648
3065    //
3066    // Intentionally verbose to ensure that the list always matches correctly
3067    // with the list in the source above.
3068    let ld64_arch = match llvm_arch {
3069        "armv7k" => "armv7k",
3070        "armv7s" => "armv7s",
3071        "arm64" => "arm64",
3072        "arm64e" => "arm64e",
3073        "arm64_32" => "arm64_32",
3074        // ld64 doesn't understand i686, so fall back to i386 instead.
3075        //
3076        // Same story when linking with cc, since that ends up invoking ld64.
3077        "i386" | "i686" => "i386",
3078        "x86_64" => "x86_64",
3079        "x86_64h" => "x86_64h",
3080        _ => bug!("unsupported architecture in Apple target: {}", sess.target.llvm_target),
3081    };
3082
3083    if cc == Cc::No {
3084        // From the man page for ld64 (`man ld`):
3085        // > The linker accepts universal (multiple-architecture) input files,
3086        // > but always creates a "thin" (single-architecture), standard
3087        // > Mach-O output file. The architecture for the output file is
3088        // > specified using the -arch option.
3089        //
3090        // The linker has heuristics to determine the desired architecture,
3091        // but to be safe, and to avoid a warning, we set the architecture
3092        // explicitly.
3093        cmd.link_args(&["-arch", ld64_arch]);
3094
3095        // Man page says that ld64 supports the following platform names:
3096        // > - macos
3097        // > - ios
3098        // > - tvos
3099        // > - watchos
3100        // > - bridgeos
3101        // > - visionos
3102        // > - xros
3103        // > - mac-catalyst
3104        // > - ios-simulator
3105        // > - tvos-simulator
3106        // > - watchos-simulator
3107        // > - visionos-simulator
3108        // > - xros-simulator
3109        // > - driverkit
3110        let platform_name = match (target_os, target_env) {
3111            (os, "") => os,
3112            ("ios", "macabi") => "mac-catalyst",
3113            ("ios", "sim") => "ios-simulator",
3114            ("tvos", "sim") => "tvos-simulator",
3115            ("watchos", "sim") => "watchos-simulator",
3116            ("visionos", "sim") => "visionos-simulator",
3117            _ => bug!("invalid OS/env combination for Apple target: {target_os}, {target_env}"),
3118        };
3119
3120        let min_version = sess.apple_deployment_target().fmt_full().to_string();
3121
3122        // The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
3123        // - By dyld to give extra warnings and errors, see e.g.:
3124        //   <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3029>
3125        //   <https://github.com/apple-oss-distributions/dyld/blob/dyld-1165.3/common/MachOFile.cpp#L3738-L3857>
3126        // - By system frameworks to change certain behaviour. For example, the default value of
3127        //   `-[NSView wantsBestResolutionOpenGLSurface]` is `YES` when the SDK version is >= 10.15.
3128        //   <https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc>
3129        //
3130        // We do not currently know the actual SDK version though, so we have a few options:
3131        // 1. Use the minimum version supported by rustc.
3132        // 2. Use the same as the deployment target.
3133        // 3. Use an arbitrary recent version.
3134        // 4. Omit the version.
3135        //
3136        // The first option is too low / too conservative, and means that users will not get the
3137        // same behaviour from a binary compiled with rustc as with one compiled by clang.
3138        //
3139        // The second option is similarly conservative, and also wrong since if the user specified a
3140        // higher deployment target than the SDK they're compiling/linking with, the runtime might
3141        // make invalid assumptions about the capabilities of the binary.
3142        //
3143        // The third option requires that `rustc` is periodically kept up to date with Apple's SDK
3144        // version, and is also wrong for similar reasons as above.
3145        //
3146        // The fourth option is bad because while `ld`, `otool`, `vtool` and such understand it to
3147        // mean "absent" or `n/a`, dyld doesn't actually understand it, and will end up interpreting
3148        // it as 0.0, which is again too low/conservative.
3149        //
3150        // Currently, we lie about the SDK version, and choose the second option.
3151        //
3152        // FIXME(madsmtm): Parse the SDK version from the SDK root instead.
3153        // <https://github.com/rust-lang/rust/issues/129432>
3154        let sdk_version = &*min_version;
3155
3156        // From the man page for ld64 (`man ld`):
3157        // > This is set to indicate the platform, oldest supported version of
3158        // > that platform that output is to be used on, and the SDK that the
3159        // > output was built against.
3160        //
3161        // Like with `-arch`, the linker can figure out the platform versions
3162        // itself from the binaries being linked, but to be safe, we specify
3163        // the desired versions here explicitly.
3164        cmd.link_args(&["-platform_version", platform_name, &*min_version, sdk_version]);
3165    } else {
3166        // cc == Cc::Yes
3167        //
3168        // We'd _like_ to use `-target` everywhere, since that can uniquely
3169        // communicate all the required details except for the SDK version
3170        // (which is read by Clang itself from the SDKROOT), but that doesn't
3171        // work on GCC, and since we don't know whether the `cc` compiler is
3172        // Clang, GCC, or something else, we fall back to other options that
3173        // also work on GCC when compiling for macOS.
3174        //
3175        // Targets other than macOS are ill-supported by GCC (it doesn't even
3176        // support e.g. `-miphoneos-version-min`), so in those cases we can
3177        // fairly safely use `-target`. See also the following, where it is
3178        // made explicit that the recommendation by LLVM developers is to use
3179        // `-target`: <https://github.com/llvm/llvm-project/issues/88271>
3180        if target_os == "macos" {
3181            // `-arch` communicates the architecture.
3182            //
3183            // CC forwards the `-arch` to the linker, so we use the same value
3184            // here intentionally.
3185            cmd.cc_args(&["-arch", ld64_arch]);
3186
3187            // The presence of `-mmacosx-version-min` makes CC default to
3188            // macOS, and it sets the deployment target.
3189            let version = sess.apple_deployment_target().fmt_full();
3190            // Intentionally pass this as a single argument, Clang doesn't
3191            // seem to like it otherwise.
3192            cmd.cc_arg(&format!("-mmacosx-version-min={version}"));
3193
3194            // macOS has no environment, so with these two, we've told CC the
3195            // four desired parameters.
3196            //
3197            // We avoid `-m32`/`-m64`, as this is already encoded by `-arch`.
3198        } else {
3199            cmd.cc_args(&["-target", &versioned_llvm_target(sess)]);
3200        }
3201    }
3202}
3203
3204fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option<PathBuf> {
3205    if !sess.target.is_like_darwin {
3206        return None;
3207    }
3208    let LinkerFlavor::Darwin(cc, _) = flavor else {
3209        return None;
3210    };
3211
3212    // The default compiler driver on macOS is at `/usr/bin/cc`. This is a trampoline binary that
3213    // effectively invokes `xcrun cc` internally to look up both the compiler binary and the SDK
3214    // root from the current Xcode installation. When cross-compiling, when `rustc` is invoked
3215    // inside Xcode, or when invoking the linker directly, this default logic is unsuitable, so
3216    // instead we invoke `xcrun` manually.
3217    //
3218    // (Note that this doesn't mean we get a duplicate lookup here - passing `SDKROOT` below will
3219    // cause the trampoline binary to skip looking up the SDK itself).
3220    let sdkroot = sess.time("get_apple_sdk_root", || get_apple_sdk_root(sess))?;
3221
3222    if cc == Cc::Yes {
3223        // There are a few options to pass the SDK root when linking with a C/C++ compiler:
3224        // - The `--sysroot` flag.
3225        // - The `-isysroot` flag.
3226        // - The `SDKROOT` environment variable.
3227        //
3228        // `--sysroot` isn't actually enough to get Clang to treat it as a platform SDK, you need
3229        // to specify `-isysroot`. This is admittedly a bit strange, as on most targets `-isysroot`
3230        // only applies to include header files, but on Apple targets it also applies to libraries
3231        // and frameworks.
3232        //
3233        // This leaves the choice between `-isysroot` and `SDKROOT`. Both are supported by Clang and
3234        // GCC, though they may not be supported by all compiler drivers. We choose `SDKROOT`,
3235        // primarily because that is the same interface that is used when invoking the tool under
3236        // `xcrun -sdk macosx $tool`.
3237        //
3238        // In that sense, if a given compiler driver does not support `SDKROOT`, the blame is fairly
3239        // clearly in the tool in question, since they also don't support being run under `xcrun`.
3240        //
3241        // Additionally, `SDKROOT` is an environment variable and thus optional. It also has lower
3242        // precedence than `-isysroot`, so a custom compiler driver that does not support it and
3243        // instead figures out the SDK on their own can easily do so by using `-isysroot`.
3244        //
3245        // (This in particular affects Clang built with the `DEFAULT_SYSROOT` CMake flag, such as
3246        // the one provided by some versions of Homebrew's `llvm` package. Those will end up
3247        // ignoring the value we set here, and instead use their built-in sysroot).
3248        cmd.cmd().env("SDKROOT", &sdkroot);
3249    } else {
3250        // When invoking the linker directly, we use the `-syslibroot` parameter. `SDKROOT` is not
3251        // read by the linker, so it's really the only option.
3252        //
3253        // This is also what Clang does.
3254        cmd.link_arg("-syslibroot");
3255        cmd.link_arg(&sdkroot);
3256    }
3257
3258    Some(sdkroot)
3259}
3260
3261fn get_apple_sdk_root(sess: &Session) -> Option<PathBuf> {
3262    if let Ok(sdkroot) = env::var("SDKROOT") {
3263        let p = PathBuf::from(&sdkroot);
3264
3265        // Ignore invalid SDKs, similar to what clang does:
3266        // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.6/clang/lib/Driver/ToolChains/Darwin.cpp#L2212-L2229
3267        //
3268        // NOTE: Things are complicated here by the fact that `rustc` can be run by Cargo to compile
3269        // build scripts and proc-macros for the host, and thus we need to ignore SDKROOT if it's
3270        // clearly set for the wrong platform.
3271        //
3272        // FIXME(madsmtm): Make this more robust (maybe read `SDKSettings.json` like Clang does?).
3273        match &*apple::sdk_name(&sess.target).to_lowercase() {
3274            "appletvos"
3275                if sdkroot.contains("TVSimulator.platform")
3276                    || sdkroot.contains("MacOSX.platform") => {}
3277            "appletvsimulator"
3278                if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3279            "iphoneos"
3280                if sdkroot.contains("iPhoneSimulator.platform")
3281                    || sdkroot.contains("MacOSX.platform") => {}
3282            "iphonesimulator"
3283                if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => {
3284            }
3285            "macosx"
3286                if sdkroot.contains("iPhoneOS.platform")
3287                    || sdkroot.contains("iPhoneSimulator.platform")
3288                    || sdkroot.contains("AppleTVOS.platform")
3289                    || sdkroot.contains("AppleTVSimulator.platform")
3290                    || sdkroot.contains("WatchOS.platform")
3291                    || sdkroot.contains("WatchSimulator.platform")
3292                    || sdkroot.contains("XROS.platform")
3293                    || sdkroot.contains("XRSimulator.platform") => {}
3294            "watchos"
3295                if sdkroot.contains("WatchSimulator.platform")
3296                    || sdkroot.contains("MacOSX.platform") => {}
3297            "watchsimulator"
3298                if sdkroot.contains("WatchOS.platform") || sdkroot.contains("MacOSX.platform") => {}
3299            "xros"
3300                if sdkroot.contains("XRSimulator.platform")
3301                    || sdkroot.contains("MacOSX.platform") => {}
3302            "xrsimulator"
3303                if sdkroot.contains("XROS.platform") || sdkroot.contains("MacOSX.platform") => {}
3304            // Ignore `SDKROOT` if it's not a valid path.
3305            _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {}
3306            _ => return Some(p),
3307        }
3308    }
3309
3310    apple::get_sdk_root(sess)
3311}
3312
3313/// When using the linker flavors opting in to `lld`, add the necessary paths and arguments to
3314/// invoke it:
3315/// - when the self-contained linker flag is active: the build of `lld` distributed with rustc,
3316/// - or any `lld` available to `cc`.
3317fn add_lld_args(
3318    cmd: &mut dyn Linker,
3319    sess: &Session,
3320    flavor: LinkerFlavor,
3321    self_contained_components: LinkSelfContainedComponents,
3322) {
3323    debug!(
3324        "add_lld_args requested, flavor: '{:?}', target self-contained components: {:?}",
3325        flavor, self_contained_components,
3326    );
3327
3328    // If the flavor doesn't use a C/C++ compiler to invoke the linker, or doesn't opt in to `lld`,
3329    // we don't need to do anything.
3330    if !(flavor.uses_cc() && flavor.uses_lld()) {
3331        return;
3332    }
3333
3334    // 1. Implement the "self-contained" part of this feature by adding rustc distribution
3335    // directories to the tool's search path, depending on a mix between what users can specify on
3336    // the CLI, and what the target spec enables (as it can't disable components):
3337    // - if the self-contained linker is enabled on the CLI or by the target spec,
3338    // - and if the self-contained linker is not disabled on the CLI.
3339    let self_contained_cli = sess.opts.cg.link_self_contained.is_linker_enabled();
3340    let self_contained_target = self_contained_components.is_linker_enabled();
3341
3342    let self_contained_linker = self_contained_cli || self_contained_target;
3343    if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() {
3344        let mut linker_path_exists = false;
3345        for path in sess.get_tools_search_paths(false) {
3346            let linker_path = path.join("gcc-ld");
3347            linker_path_exists |= linker_path.exists();
3348            cmd.cc_arg({
3349                let mut arg = OsString::from("-B");
3350                arg.push(linker_path);
3351                arg
3352            });
3353        }
3354        if !linker_path_exists {
3355            // As a sanity check, we emit an error if none of these paths exist: we want
3356            // self-contained linking and have no linker.
3357            sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing);
3358        }
3359    }
3360
3361    // 2. Implement the "linker flavor" part of this feature by asking `cc` to use some kind of
3362    // `lld` as the linker.
3363    //
3364    // Note that wasm targets skip this step since the only option there anyway
3365    // is to use LLD but the `wasm32-wasip2` target relies on a wrapper around
3366    // this, `wasm-component-ld`, which is overridden if this option is passed.
3367    if !sess.target.is_like_wasm {
3368        cmd.cc_arg("-fuse-ld=lld");
3369    }
3370
3371    if !flavor.is_gnu() {
3372        // Tell clang to use a non-default LLD flavor.
3373        // Gcc doesn't understand the target option, but we currently assume
3374        // that gcc is not used for Apple and Wasm targets (#97402).
3375        //
3376        // Note that we don't want to do that by default on macOS: e.g. passing a
3377        // 10.7 target to LLVM works, but not to recent versions of clang/macOS, as
3378        // shown in issue #101653 and the discussion in PR #101792.
3379        //
3380        // It could be required in some cases of cross-compiling with
3381        // LLD, but this is generally unspecified, and we don't know
3382        // which specific versions of clang, macOS SDK, host and target OS
3383        // combinations impact us here.
3384        //
3385        // So we do a simple first-approximation until we know more of what the
3386        // Apple targets require (and which would be handled prior to hitting this
3387        // LLD codepath anyway), but the expectation is that until then
3388        // this should be manually passed if needed. We specify the target when
3389        // targeting a different linker flavor on macOS, and that's also always
3390        // the case when targeting WASM.
3391        if sess.target.linker_flavor != sess.host.linker_flavor {
3392            cmd.cc_arg(format!("--target={}", versioned_llvm_target(sess)));
3393        }
3394    }
3395}
3396
3397// gold has been deprecated with binutils 2.44
3398// and is known to behave incorrectly around Rust programs.
3399// There have been reports of being unable to bootstrap with gold:
3400// https://github.com/rust-lang/rust/issues/139425
3401// Additionally, gold miscompiles SHF_GNU_RETAIN sections, which are
3402// emitted with `#[used(linker)]`.
3403fn warn_if_linked_with_gold(sess: &Session, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
3404    use object::read::elf::{FileHeader, SectionHeader};
3405    use object::read::{ReadCache, ReadRef, Result};
3406    use object::{Endianness, elf};
3407
3408    fn elf_has_gold_version_note<'a>(
3409        elf: &impl FileHeader,
3410        data: impl ReadRef<'a>,
3411    ) -> Result<bool> {
3412        let endian = elf.endian()?;
3413
3414        let section =
3415            elf.sections(endian, data)?.section_by_name(endian, b".note.gnu.gold-version");
3416        if let Some((_, section)) = section
3417            && let Some(mut notes) = section.notes(endian, data)?
3418        {
3419            return Ok(notes.any(|note| {
3420                note.is_ok_and(|note| note.n_type(endian) == elf::NT_GNU_GOLD_VERSION)
3421            }));
3422        }
3423
3424        Ok(false)
3425    }
3426
3427    let data = ReadCache::new(BufReader::new(File::open(path)?));
3428
3429    let was_linked_with_gold = if sess.target.pointer_width == 64 {
3430        let elf = elf::FileHeader64::<Endianness>::parse(&data)?;
3431        elf_has_gold_version_note(elf, &data)?
3432    } else if sess.target.pointer_width == 32 {
3433        let elf = elf::FileHeader32::<Endianness>::parse(&data)?;
3434        elf_has_gold_version_note(elf, &data)?
3435    } else {
3436        return Ok(());
3437    };
3438
3439    if was_linked_with_gold {
3440        let mut warn =
3441            sess.dcx().struct_warn("the gold linker is deprecated and has known bugs with Rust");
3442        warn.help("consider using LLD or ld from GNU binutils instead");
3443        warn.emit();
3444    }
3445    Ok(())
3446}