Skip to main content

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