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