Skip to main content

rustc_codegen_ssa/back/
link.rs

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