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