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