Skip to main content

rustc_codegen_ssa/back/
link.rs

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