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