Skip to main content

rustc_codegen_ssa/back/
link.rs

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