Skip to main content

rustc_codegen_ssa/back/
link.rs

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