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