Skip to main content

rustc_codegen_ssa/back/
metadata.rs

1//! Reading of the rustc metadata for rlibs and dylibs
2
3use std::borrow::Cow;
4use std::fs::File;
5use std::io::Write;
6use std::path::Path;
7
8use itertools::Itertools;
9use object::write::{self, StandardSegment, Symbol, SymbolSection};
10use object::{
11    Architecture, BinaryFormat, Endianness, FileFlags, Object, ObjectSection, ObjectSymbol,
12    SectionFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope, elf, pe, xcoff,
13};
14use rustc_abi::Endian;
15use rustc_data_structures::memmap::Mmap;
16use rustc_data_structures::owned_slice::{OwnedSlice, try_slice_owned};
17use rustc_metadata::EncodedMetadata;
18use rustc_metadata::creader::MetadataLoader;
19use rustc_metadata::fs::METADATA_FILENAME;
20use rustc_session::Session;
21use rustc_span::{bug, sym};
22use rustc_target::spec::{CfgAbi, LlvmAbi, Os, RelocModel, Target, ef_avr_arch};
23use tracing::debug;
24
25use super::apple;
26use crate::diagnostics;
27
28/// The default metadata loader. This is used by cg_llvm and cg_clif.
29///
30/// # Metadata location
31///
32/// <dl>
33/// <dt>rlib</dt>
34/// <dd>The metadata can be found in the `lib.rmeta` file inside of the ar archive.</dd>
35/// <dt>dylib</dt>
36/// <dd>The metadata can be found in the `.rustc` section of the shared library.</dd>
37/// </dl>
38#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DefaultMetadataLoader {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "DefaultMetadataLoader")
    }
}Debug)]
39pub struct DefaultMetadataLoader;
40
41static AIX_METADATA_SYMBOL_NAME: &'static str = "__aix_rust_metadata";
42
43fn load_metadata_with(
44    path: &Path,
45    f: impl for<'a> FnOnce(&'a [u8]) -> Result<&'a [u8], String>,
46) -> Result<OwnedSlice, String> {
47    let file =
48        File::open(path).map_err(|e| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to open file \'{0}\': {1}",
                path.display(), e))
    })format!("failed to open file '{}': {}", path.display(), e))?;
49
50    unsafe { Mmap::map(file) }
51        .map_err(|e| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to mmap file \'{0}\': {1}",
                path.display(), e))
    })format!("failed to mmap file '{}': {}", path.display(), e))
52        .and_then(|mmap| try_slice_owned(mmap, |mmap| f(mmap)))
53}
54
55impl MetadataLoader for DefaultMetadataLoader {
56    fn get_rlib_metadata(&self, target: &Target, path: &Path) -> Result<OwnedSlice, String> {
57        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/back/metadata.rs:57",
                        "rustc_codegen_ssa::back::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/back/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(57u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::metadata"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("getting rlib metadata for {0}",
                                                    path.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("getting rlib metadata for {}", path.display());
58        load_metadata_with(path, |data| {
59            let archive = object::read::archive::ArchiveFile::parse(&*data)
60                .map_err(|e| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse rlib \'{0}\': {1}",
                path.display(), e))
    })format!("failed to parse rlib '{}': {}", path.display(), e))?;
61
62            for entry_result in archive.members() {
63                let entry = entry_result
64                    .map_err(|e| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse rlib \'{0}\': {1}",
                path.display(), e))
    })format!("failed to parse rlib '{}': {}", path.display(), e))?;
65                if entry.name() == METADATA_FILENAME.as_bytes() {
66                    let data = entry
67                        .data(data)
68                        .map_err(|e| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse rlib \'{0}\': {1}",
                path.display(), e))
    })format!("failed to parse rlib '{}': {}", path.display(), e))?;
69                    if target.is_like_aix {
70                        return get_metadata_xcoff(path, data);
71                    } else {
72                        return search_for_section(path, data, ".rmeta");
73                    }
74                }
75            }
76
77            Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("metadata not found in rlib \'{0}\'",
                path.display()))
    })format!("metadata not found in rlib '{}'", path.display()))
78        })
79    }
80
81    fn get_dylib_metadata(&self, target: &Target, path: &Path) -> Result<OwnedSlice, String> {
82        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/back/metadata.rs:82",
                        "rustc_codegen_ssa::back::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/back/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(82u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::metadata"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("getting dylib metadata for {0}",
                                                    path.display()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("getting dylib metadata for {}", path.display());
83        if target.is_like_aix {
84            load_metadata_with(path, |data| {
85                let archive = object::read::archive::ArchiveFile::parse(&*data).map_err(|e| {
86                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse aix dylib \'{0}\': {1}",
                path.display(), e))
    })format!("failed to parse aix dylib '{}': {}", path.display(), e)
87                })?;
88
89                match archive.members().exactly_one() {
90                    Ok(lib) => {
91                        let lib = lib.map_err(|e| {
92                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse aix dylib \'{0}\': {1}",
                path.display(), e))
    })format!("failed to parse aix dylib '{}': {}", path.display(), e)
93                        })?;
94                        let data = lib.data(data).map_err(|e| {
95                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse aix dylib \'{0}\': {1}",
                path.display(), e))
    })format!("failed to parse aix dylib '{}': {}", path.display(), e)
96                        })?;
97                        get_metadata_xcoff(path, data)
98                    }
99                    Err(e) => Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse aix dylib \'{0}\': {1}",
                path.display(), e))
    })format!("failed to parse aix dylib '{}': {}", path.display(), e)),
100                }
101            })
102        } else {
103            load_metadata_with(path, |data| search_for_section(path, data, ".rustc"))
104        }
105    }
106}
107
108pub(super) fn search_for_section<'a>(
109    path: &Path,
110    bytes: &'a [u8],
111    section: &str,
112) -> Result<&'a [u8], String> {
113    let Ok(file) = object::File::parse(bytes) else {
114        // The parse above could fail for odd reasons like corruption, but for
115        // now we just interpret it as this target doesn't support metadata
116        // emission in object files so the entire byte slice itself is probably
117        // a metadata file. Ideally though if necessary we could at least check
118        // the prefix of bytes to see if it's an actual metadata object and if
119        // not forward the error along here.
120        return Ok(bytes);
121    };
122    file.section_by_name(section)
123        .ok_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` section in \'{1}\'",
                section, path.display()))
    })format!("no `{}` section in '{}'", section, path.display()))?
124        .data()
125        .map_err(|e| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to read {0} section in \'{1}\': {2}",
                section, path.display(), e))
    })format!("failed to read {} section in '{}': {}", section, path.display(), e))
126}
127
128fn add_gnu_property_note(
129    file: &mut write::Object<'static>,
130    architecture: Architecture,
131    endianness: Endianness,
132) {
133    // Only X86_64 and Aarch64 require a GNU property note.
134    if !#[allow(non_exhaustive_omitted_patterns)] match architecture {
    Architecture::X86_64 | Architecture::Aarch64 => true,
    _ => false,
}matches!(architecture, Architecture::X86_64 | Architecture::Aarch64) {
135        return;
136    }
137
138    let section = file.add_section(
139        file.segment_name(StandardSegment::Data).to_vec(),
140        b".note.gnu.property".to_vec(),
141        SectionKind::Note,
142    );
143    let mut data: Vec<u8> = Vec::new();
144    let n_namsz: u32 = 4; // Size of the n_name field
145    let n_descsz: u32 = 16; // Size of the n_desc field
146    let n_type: u32 = object::elf::NT_GNU_PROPERTY_TYPE_0; // Type of note descriptor
147    let header_values = [n_namsz, n_descsz, n_type];
148    header_values.iter().for_each(|v| {
149        data.extend_from_slice(&match endianness {
150            Endianness::Little => v.to_le_bytes(),
151            Endianness::Big => v.to_be_bytes(),
152        })
153    });
154    data.extend_from_slice(b"GNU\0"); // Owner of the program property note
155    let pr_type: u32 = match architecture {
156        Architecture::X86_64 => object::elf::GNU_PROPERTY_X86_FEATURE_1_AND,
157        Architecture::Aarch64 => object::elf::GNU_PROPERTY_AARCH64_FEATURE_1_AND,
158        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
159    };
160    let pr_datasz: u32 = 4; //size of the pr_data field
161    let pr_data: u32 = 3; //program property descriptor
162    let pr_padding: u32 = 0;
163    let property_values = [pr_type, pr_datasz, pr_data, pr_padding];
164    property_values.iter().for_each(|v| {
165        data.extend_from_slice(&match endianness {
166            Endianness::Little => v.to_le_bytes(),
167            Endianness::Big => v.to_be_bytes(),
168        })
169    });
170    file.append_section_data(section, &data, 8);
171}
172
173pub(super) fn get_metadata_xcoff<'a>(path: &Path, data: &'a [u8]) -> Result<&'a [u8], String> {
174    let Ok(file) = object::File::parse(data) else {
175        return Ok(data);
176    };
177    let info_data = search_for_section(path, data, ".info")?;
178    if let Some(metadata_symbol) =
179        file.symbols().find(|sym| sym.name() == Ok(AIX_METADATA_SYMBOL_NAME))
180    {
181        let offset = metadata_symbol.address() as usize;
182        // The offset specifies the location of rustc metadata in the .info section of XCOFF.
183        // Each string stored in .info section of XCOFF is preceded by a 4-byte length field.
184        if offset < 4 {
185            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Invalid metadata symbol offset: {0}",
                offset))
    })format!("Invalid metadata symbol offset: {offset}"));
186        }
187        // XCOFF format uses big-endian byte order.
188        let len = u32::from_be_bytes(info_data[(offset - 4)..offset].try_into().unwrap()) as usize;
189        if offset + len > (info_data.len() as usize) {
190            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Metadata at offset {0} with size {1} is beyond .info section",
                offset, len))
    })format!(
191                "Metadata at offset {offset} with size {len} is beyond .info section"
192            ));
193        }
194        Ok(&info_data[offset..(offset + len)])
195    } else {
196        Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Unable to find symbol {0}",
                AIX_METADATA_SYMBOL_NAME))
    })format!("Unable to find symbol {AIX_METADATA_SYMBOL_NAME}"))
197    }
198}
199
200pub(crate) fn create_object_file(sess: &Session) -> Option<write::Object<'static>> {
201    let endianness = match sess.target.options.endian {
202        Endian::Little => Endianness::Little,
203        Endian::Big => Endianness::Big,
204    };
205    let Some((architecture, sub_architecture)) =
206        sess.target.object_architecture(&sess.internal_target_features)
207    else {
208        return None;
209    };
210    let binary_format = sess.target.binary_format.to_object();
211
212    let mut file = write::Object::new(binary_format, architecture, endianness);
213    file.set_sub_architecture(sub_architecture);
214    if sess.target.is_like_darwin {
215        if macho_is_arm64e(&sess.target) {
216            file.set_macho_cpu_subtype(
217                object::macho::CPU_SUBTYPE_ARM64E | object::macho::CPU_SUBTYPE_PTRAUTH_ABI,
218            );
219        }
220
221        file.set_macho_build_version(macho_object_build_version_for_target(sess))
222    }
223    if binary_format == BinaryFormat::Coff {
224        // Disable the default mangler to avoid mangling the special "@feat.00" symbol name.
225        let original_mangling = file.mangling();
226        file.set_mangling(object::write::Mangling::None);
227
228        let mut feature = 0;
229
230        if file.architecture() == object::Architecture::I386 {
231            // When linking with /SAFESEH on x86, lld requires that all linker inputs be marked as
232            // safe exception handling compatible. Metadata files masquerade as regular COFF
233            // objects and are treated as linker inputs, despite containing no actual code. Thus,
234            // they still need to be marked as safe exception handling compatible. See #96498.
235            // Reference: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
236            feature |= 1;
237        }
238
239        file.add_symbol(object::write::Symbol {
240            name: "@feat.00".into(),
241            value: feature,
242            size: 0,
243            kind: object::SymbolKind::Data,
244            scope: object::SymbolScope::Compilation,
245            weak: false,
246            section: object::write::SymbolSection::Absolute,
247            flags: object::SymbolFlags::None,
248        });
249
250        file.set_mangling(original_mangling);
251    }
252    if binary_format == BinaryFormat::Elf {
253        let e_flags = elf_e_flags(architecture, sess);
254        // adapted from LLVM's `MCELFObjectTargetWriter::getOSABI`
255        let os_abi = elf_os_abi(sess);
256        let abi_version = 0;
257        add_gnu_property_note(&mut file, architecture, endianness);
258        file.flags = FileFlags::Elf { os_abi, abi_version, e_flags };
259    }
260    Some(file)
261}
262
263pub(super) fn elf_os_abi(sess: &Session) -> u8 {
264    match sess.target.options.os {
265        Os::Hermit => elf::ELFOSABI_STANDALONE,
266        Os::FreeBsd => elf::ELFOSABI_FREEBSD,
267        Os::Solaris => elf::ELFOSABI_SOLARIS,
268        _ => elf::ELFOSABI_NONE,
269    }
270}
271
272pub(super) fn elf_e_flags(architecture: Architecture, sess: &Session) -> u32 {
273    match architecture {
274        Architecture::Mips | Architecture::Mips64 | Architecture::Mips64_N32 => {
275            // "N32" indicates an "ILP32" data model on a 64-bit MIPS CPU
276            // like SPARC's "v8+", x86_64's "x32", or the watchOS "arm64_32".
277            let is_32bit = architecture == Architecture::Mips;
278            let mut e_flags = match sess.target.options.cpu.as_ref() {
279                "mips1" if is_32bit => elf::EF_MIPS_ARCH_1,
280                "mips2" if is_32bit => elf::EF_MIPS_ARCH_2,
281                "mips3" => elf::EF_MIPS_ARCH_3,
282                "mips4" => elf::EF_MIPS_ARCH_4,
283                "mips5" => elf::EF_MIPS_ARCH_5,
284                "mips32r2" if is_32bit => elf::EF_MIPS_ARCH_32R2,
285                "mips32r6" if is_32bit => elf::EF_MIPS_ARCH_32R6,
286                "mips64r2" if !is_32bit => elf::EF_MIPS_ARCH_64R2,
287                "mips64r6" if !is_32bit => elf::EF_MIPS_ARCH_64R6,
288                s if s.starts_with("mips32") && !is_32bit => {
289                    sess.dcx().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid CPU `{0}` for 64-bit MIPS target",
                s))
    })format!("invalid CPU `{}` for 64-bit MIPS target", s))
290                }
291                s if s.starts_with("mips64") && is_32bit => {
292                    sess.dcx().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid CPU `{0}` for 32-bit MIPS target",
                s))
    })format!("invalid CPU `{}` for 32-bit MIPS target", s))
293                }
294                _ if is_32bit => elf::EF_MIPS_ARCH_32R2,
295                _ => elf::EF_MIPS_ARCH_64R2,
296            };
297
298            // Use the explicitly given ABI.
299            match &sess.target.options.llvm_abiname {
300                LlvmAbi::O32 if is_32bit => e_flags |= elf::EF_MIPS_ABI_O32,
301                LlvmAbi::N32 if !is_32bit => e_flags |= elf::EF_MIPS_ABI2,
302                LlvmAbi::N64 if !is_32bit => {}
303                // The rest is invalid (which is already ensured by the target spec check).
304                s => bug_impl(None, format_args!("invalid LLVM ABI `{0}` for MIPS target", s),
    Location::caller())bug!("invalid LLVM ABI `{}` for MIPS target", s),
305            };
306
307            if sess.target.options.relocation_model != RelocModel::Static {
308                // PIC means position-independent code. CPIC means "calls PIC".
309                // CPIC was mutually exclusive with PIC according to
310                // the SVR4 MIPS ABI https://refspecs.linuxfoundation.org/elf/mipsabi.pdf
311                // and should have only appeared on static objects with dynamically calls.
312                // At some point someone (GCC?) decided to set CPIC even for PIC.
313                // Nowadays various things expect both set on the same object file
314                // and may even error if you mix CPIC and non-CPIC object files,
315                // despite that being the entire point of the CPIC ABI extension!
316                // As we are in Rome, we do as the Romans do.
317                e_flags |= elf::EF_MIPS_PIC | elf::EF_MIPS_CPIC;
318            }
319            if sess.target.options.cpu.contains("r6") {
320                e_flags |= elf::EF_MIPS_NAN2008;
321            }
322            e_flags
323        }
324        Architecture::Riscv32 | Architecture::Riscv64 => {
325            // Source: https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/079772828bd10933d34121117a222b4cc0ee2200/riscv-elf.adoc
326            let mut e_flags: u32 = 0x0;
327
328            // Check if compression is enabled
329            if sess.internal_target_features.contains(&sym::zca) {
330                e_flags |= elf::EF_RISCV_RVC;
331            }
332
333            // Check if RVTSO is enabled
334            if sess.internal_target_features.contains(&sym::ztso) {
335                e_flags |= elf::EF_RISCV_TSO;
336            }
337
338            // Set the appropriate flag based on ABI
339            // This needs to match LLVM `RISCVELFStreamer.cpp`
340            match &sess.target.llvm_abiname {
341                LlvmAbi::Ilp32 | LlvmAbi::Lp64 => (),
342                LlvmAbi::Ilp32f | LlvmAbi::Lp64f => e_flags |= elf::EF_RISCV_FLOAT_ABI_SINGLE,
343                LlvmAbi::Ilp32d | LlvmAbi::Lp64d => e_flags |= elf::EF_RISCV_FLOAT_ABI_DOUBLE,
344                // Note that the `lp64e` is still unstable as it's not (yet) part of the ELF psABI.
345                LlvmAbi::Ilp32e | LlvmAbi::Lp64e => e_flags |= elf::EF_RISCV_RVE,
346                _ => bug_impl(None, format_args!("unknown RISC-V ABI name"), Location::caller())bug!("unknown RISC-V ABI name"),
347            }
348
349            e_flags
350        }
351        Architecture::LoongArch32 | Architecture::LoongArch64 => {
352            // Source: https://github.com/loongson/la-abi-specs/blob/release/laelf.adoc#e_flags-identifies-abi-type-and-version
353            let mut e_flags: u32 = elf::EF_LARCH_OBJABI_V1;
354
355            // Set the appropriate flag based on ABI
356            // This needs to match LLVM `LoongArchELFStreamer.cpp`
357            match &sess.target.llvm_abiname {
358                LlvmAbi::Ilp32s | LlvmAbi::Lp64s => e_flags |= elf::EF_LARCH_ABI_SOFT_FLOAT,
359                LlvmAbi::Ilp32f | LlvmAbi::Lp64f => e_flags |= elf::EF_LARCH_ABI_SINGLE_FLOAT,
360                LlvmAbi::Ilp32d | LlvmAbi::Lp64d => e_flags |= elf::EF_LARCH_ABI_DOUBLE_FLOAT,
361                _ => bug_impl(None, format_args!("unknown LoongArch ABI name"), Location::caller())bug!("unknown LoongArch ABI name"),
362            }
363
364            e_flags
365        }
366        Architecture::Avr => {
367            // Resolve the ISA revision and set
368            // the appropriate EF_AVR_ARCH flag.
369            if let Some(ref cpu) = sess.opts.cg.target_cpu {
370                ef_avr_arch(cpu)
371            } else {
372                sess.dcx().emit_fatal(diagnostics::CpuRequired)
373            }
374        }
375        Architecture::Csky => {
376            if #[allow(non_exhaustive_omitted_patterns)] match sess.target.options.cfg_abi {
    CfgAbi::AbiV2 => true,
    _ => false,
}matches!(sess.target.options.cfg_abi, CfgAbi::AbiV2) {
377                elf::EF_CSKY_ABIV2
378            } else {
379                elf::EF_CSKY_ABIV1
380            }
381        }
382        Architecture::PowerPc64 => {
383            const EF_PPC64_ABI_ELF_V1: u32 = 1;
384            const EF_PPC64_ABI_ELF_V2: u32 = 2;
385
386            match sess.target.options.llvm_abiname {
387                // If the flags do not correctly indicate the ABI,
388                // linkers such as ld.lld assume that the ppc64 object files are always ELFv2
389                // which leads to broken binaries if ELFv1 is used for the object files.
390                LlvmAbi::ElfV1 => EF_PPC64_ABI_ELF_V1,
391                LlvmAbi::ElfV2 => EF_PPC64_ABI_ELF_V2,
392                _ => bug_impl(None,
    format_args!("invalid ABI specified for this PPC64 ELF target"),
    Location::caller())bug!("invalid ABI specified for this PPC64 ELF target"),
393            }
394        }
395        Architecture::Sparc32Plus => elf::EF_SPARC_32PLUS,
396        _ => 0,
397    }
398}
399
400/// Mach-O files contain information about:
401/// - The platform/OS they were built for (macOS/watchOS/Mac Catalyst/iOS simulator etc).
402/// - The minimum OS version / deployment target.
403/// - The version of the SDK they were targetting.
404///
405/// In the past, this was accomplished using the LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
406/// LC_VERSION_MIN_TVOS or LC_VERSION_MIN_WATCHOS load commands, which each contain information
407/// about the deployment target and SDK version, and implicitly, by their presence, which OS they
408/// target. Simulator targets were determined if the architecture was x86_64, but there was e.g. a
409/// LC_VERSION_MIN_IPHONEOS present.
410///
411/// This is of course brittle and limited, so modern tooling emit the LC_BUILD_VERSION load
412/// command (which contains all three pieces of information in one) when the deployment target is
413/// high enough, or the target is something that wouldn't be encodable with the old load commands
414/// (such as Mac Catalyst, or Aarch64 iOS simulator).
415///
416/// Since Xcode 15, Apple's LD apparently requires object files to use this load command, so this
417/// returns the `MachOBuildVersion` for the target to do so.
418fn macho_object_build_version_for_target(sess: &Session) -> object::write::MachOBuildVersion {
419    /// The `object` crate demands "X.Y.Z encoded in nibbles as xxxx.yy.zz"
420    /// e.g. minOS 14.0 = 0x000E0000, or SDK 16.2 = 0x00100200
421    fn pack_version(apple::OSVersion { major, minor, patch }: apple::OSVersion) -> u32 {
422        let (major, minor, patch) = (major as u32, minor as u32, patch as u32);
423        (major << 16) | (minor << 8) | patch
424    }
425
426    let platform = apple::macho_platform(&sess.target);
427    let min_os = sess.apple_deployment_target();
428
429    let mut build_version = object::write::MachOBuildVersion::default();
430    build_version.platform = platform;
431    build_version.minos = pack_version(min_os);
432    // The version here does not _really_ matter, since it is only used at runtime, and we specify
433    // it when linking the final binary, so we will omit the version. This is also what LLVM does,
434    // and the tooling also allows this (and shows the SDK version as `n/a`). Finally, it is the
435    // semantically correct choice, as the SDK has not influenced the binary generated by rustc at
436    // this point in time.
437    build_version.sdk = 0;
438
439    build_version
440}
441
442/// Is Apple's CPU subtype `arm64e`s
443fn macho_is_arm64e(target: &Target) -> bool {
444    target.llvm_target.starts_with("arm64e")
445}
446
447pub(crate) enum MetadataPosition {
448    First,
449    Last,
450}
451
452/// For rlibs we "pack" rustc metadata into a dummy object file.
453///
454/// Historically it was needed because rustc linked rlibs as whole-archive in some cases.
455/// In that case linkers try to include all files located in an archive, so if metadata is stored
456/// in an archive then it needs to be of a form that the linker is able to process.
457/// Now it's not clear whether metadata still needs to be wrapped into an object file or not.
458///
459/// Note, though, that we don't actually want this metadata to show up in any
460/// final output of the compiler. Instead this is purely for rustc's own
461/// metadata tracking purposes.
462///
463/// With the above in mind, each "flavor" of object format gets special
464/// handling here depending on the target:
465///
466/// * MachO - macos-like targets will insert the metadata into a section that
467///   is sort of fake dwarf debug info. Inspecting the source of the macos
468///   linker this causes these sections to be skipped automatically because
469///   it's not in an allowlist of otherwise well known dwarf section names to
470///   go into the final artifact.
471///
472/// * WebAssembly - this uses wasm files themselves as the object file format
473///   so an empty file with no linking metadata but a single custom section is
474///   created holding our metadata.
475///
476/// * COFF - Windows-like targets create an object with a section that has
477///   the `IMAGE_SCN_LNK_REMOVE` flag set which ensures that if the linker
478///   ever sees the section it doesn't process it and it's removed.
479///
480/// * ELF - All other targets are similar to Windows in that there's a
481///   `SHF_EXCLUDE` flag we can set on sections in an object file to get
482///   automatically removed from the final output.
483pub(crate) fn create_wrapper_file(
484    sess: &Session,
485    section_name: String,
486    data: &[u8],
487) -> (Vec<u8>, MetadataPosition) {
488    let Some(mut file) = create_object_file(sess) else {
489        if sess.target.is_like_wasm {
490            return (
491                create_metadata_file_for_wasm(sess, data, &section_name),
492                MetadataPosition::First,
493            );
494        }
495
496        // Targets using this branch don't have support implemented here yet or
497        // they're not yet implemented in the `object` crate and will likely
498        // fill out this module over time.
499        return (data.to_vec(), MetadataPosition::Last);
500    };
501    let section = if file.format() == BinaryFormat::Xcoff {
502        file.add_section(Vec::new(), b".info".to_vec(), SectionKind::Debug)
503    } else {
504        file.add_section(
505            file.segment_name(StandardSegment::Debug).to_vec(),
506            section_name.into_bytes(),
507            SectionKind::Debug,
508        )
509    };
510    match file.format() {
511        BinaryFormat::Coff => {
512            file.section_mut(section).flags =
513                SectionFlags::Coff { characteristics: pe::IMAGE_SCN_LNK_REMOVE };
514        }
515        BinaryFormat::Elf => {
516            file.section_mut(section).flags =
517                SectionFlags::Elf { sh_flags: elf::SHF_EXCLUDE as u64 };
518        }
519        BinaryFormat::Xcoff => {
520            // AIX system linker may aborts if it meets a valid XCOFF file in archive with no .text, no .data and no .bss.
521            file.add_section(Vec::new(), b".text".to_vec(), SectionKind::Text);
522            file.section_mut(section).flags =
523                SectionFlags::Xcoff { s_flags: xcoff::STYP_INFO as u32 };
524            // Encode string stored in .info section of XCOFF.
525            // FIXME: The length of data here is not guaranteed to fit in a u32.
526            // We may have to split the data into multiple pieces in order to
527            // store in .info section.
528            let len: u32 = data.len().try_into().unwrap();
529            let offset = file.append_section_data(section, &len.to_be_bytes(), 1);
530            // Add a symbol referring to the data in .info section.
531            file.add_symbol(Symbol {
532                name: AIX_METADATA_SYMBOL_NAME.into(),
533                value: offset + 4,
534                size: 0,
535                kind: SymbolKind::Unknown,
536                scope: SymbolScope::Compilation,
537                weak: false,
538                section: SymbolSection::Section(section),
539                flags: SymbolFlags::Xcoff {
540                    n_sclass: xcoff::C_INFO,
541                    x_smtyp: xcoff::C_HIDEXT,
542                    x_smclas: xcoff::C_HIDEXT,
543                    containing_csect: None,
544                },
545            });
546        }
547        _ => {}
548    };
549    file.append_section_data(section, data, 1);
550    (file.write().unwrap(), MetadataPosition::First)
551}
552
553// Historical note:
554//
555// When using link.exe it was seen that the section name `.note.rustc`
556// was getting shortened to `.note.ru`, and according to the PE and COFF
557// specification:
558//
559// > Executable images do not use a string table and do not support
560// > section names longer than 8 characters
561//
562// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
563//
564// As a result, we choose a slightly shorter name! As to why
565// `.note.rustc` works on MinGW, see
566// https://github.com/llvm/llvm-project/blob/llvmorg-12.0.0/lld/COFF/Writer.cpp#L1190-L1197
567pub fn create_compressed_metadata_file(
568    sess: &Session,
569    metadata: &EncodedMetadata,
570    symbol_name: &str,
571) -> Vec<u8> {
572    let mut packed_metadata = rustc_metadata::METADATA_HEADER.to_vec();
573    packed_metadata.write_all(&(metadata.stub_or_full().len() as u64).to_le_bytes()).unwrap();
574    packed_metadata.extend(metadata.stub_or_full());
575
576    let Some(mut file) = create_object_file(sess) else {
577        if sess.target.is_like_wasm {
578            return create_metadata_file_for_wasm(sess, &packed_metadata, ".rustc");
579        }
580        return packed_metadata.to_vec();
581    };
582    if file.format() == BinaryFormat::Xcoff {
583        return create_compressed_metadata_file_for_xcoff(file, &packed_metadata, symbol_name);
584    }
585    let section = file.add_section(
586        file.segment_name(StandardSegment::Data).to_vec(),
587        b".rustc".to_vec(),
588        SectionKind::ReadOnlyData,
589    );
590    match file.format() {
591        BinaryFormat::Elf => {
592            // Explicitly set no flags to avoid SHF_ALLOC default for data section.
593            file.section_mut(section).flags = SectionFlags::Elf { sh_flags: 0 };
594        }
595        _ => {}
596    };
597    let offset = file.append_section_data(section, &packed_metadata, 1);
598
599    // For MachO and probably PE this is necessary to prevent the linker from throwing away the
600    // .rustc section. For ELF this isn't necessary, but it also doesn't harm.
601    file.add_symbol(Symbol {
602        name: symbol_name.as_bytes().to_vec(),
603        value: offset,
604        size: packed_metadata.len() as u64,
605        kind: SymbolKind::Data,
606        scope: SymbolScope::Dynamic,
607        weak: false,
608        section: SymbolSection::Section(section),
609        flags: SymbolFlags::None,
610    });
611
612    file.write().unwrap()
613}
614
615/// * Xcoff - On AIX, custom sections are merged into predefined sections,
616///   so custom .rustc section is not preserved during linking.
617///   For this reason, we store metadata in predefined .info section, and
618///   define a symbol to reference the metadata. To preserve metadata during
619///   linking on AIX, we have to
620///   1. Create an empty .text section, a empty .data section.
621///   2. Define an empty symbol named `symbol_name` inside .data section.
622///   3. Define an symbol named `AIX_METADATA_SYMBOL_NAME` referencing
623///      data inside .info section.
624///   From XCOFF's view, (2) creates a csect entry in the symbol table, the
625///   symbol created by (3) is a info symbol for the preceding csect. Thus
626///   two symbols are preserved during linking and we can use the second symbol
627///   to reference the metadata.
628pub fn create_compressed_metadata_file_for_xcoff(
629    mut file: write::Object<'_>,
630    data: &[u8],
631    symbol_name: &str,
632) -> Vec<u8> {
633    if !(file.format() == BinaryFormat::Xcoff) {
    ::core::panicking::panic("assertion failed: file.format() == BinaryFormat::Xcoff")
};assert!(file.format() == BinaryFormat::Xcoff);
634    // AIX system linker may aborts if it meets a valid XCOFF file in archive with no .text, no .data and no .bss.
635    file.add_section(Vec::new(), b".text".to_vec(), SectionKind::Text);
636    let data_section = file.add_section(Vec::new(), b".data".to_vec(), SectionKind::Data);
637    let section = file.add_section(Vec::new(), b".info".to_vec(), SectionKind::Debug);
638    file.add_file_symbol("lib.rmeta".into());
639    file.section_mut(section).flags = SectionFlags::Xcoff { s_flags: xcoff::STYP_INFO as u32 };
640    // Add a global symbol to data_section.
641    file.add_symbol(Symbol {
642        name: symbol_name.as_bytes().into(),
643        value: 0,
644        size: 0,
645        kind: SymbolKind::Data,
646        scope: SymbolScope::Dynamic,
647        weak: true,
648        section: SymbolSection::Section(data_section),
649        flags: SymbolFlags::None,
650    });
651    let len: u32 = data.len().try_into().unwrap();
652    let offset = file.append_section_data(section, &len.to_be_bytes(), 1);
653    // Add a symbol referring to the rustc metadata.
654    file.add_symbol(Symbol {
655        name: AIX_METADATA_SYMBOL_NAME.into(),
656        value: offset + 4, // The metadata is preceded by a 4-byte length field.
657        size: 0,
658        kind: SymbolKind::Unknown,
659        scope: SymbolScope::Dynamic,
660        weak: false,
661        section: SymbolSection::Section(section),
662        flags: SymbolFlags::Xcoff {
663            n_sclass: xcoff::C_INFO,
664            x_smtyp: xcoff::C_HIDEXT,
665            x_smclas: xcoff::C_HIDEXT,
666            containing_csect: None,
667        },
668    });
669    file.append_section_data(section, data, 1);
670    file.write().unwrap()
671}
672
673/// Creates a simple WebAssembly object file, which is itself a wasm module,
674/// that contains a custom section of the name `section_name` with contents
675/// `data`.
676///
677/// NB: the `object` crate does not yet have support for writing the wasm
678/// object file format. In lieu of that the `wasm-encoder` crate is used to
679/// build a wasm file by hand.
680///
681/// The wasm object file format is defined at
682/// <https://github.com/WebAssembly/tool-conventions/blob/main/Linking.md>
683/// and mainly consists of a `linking` custom section. In this case the custom
684/// section there is empty except for a version marker indicating what format
685/// it's in.
686///
687/// The main purpose of this is to contain a custom section with `section_name`,
688/// which is then appended after `linking`.
689///
690/// As a further detail the object needs to have a 64-bit memory if `wasm64` is
691/// the target or otherwise it's interpreted as a 32-bit object which is
692/// incompatible with 64-bit ones.
693pub fn create_metadata_file_for_wasm(sess: &Session, data: &[u8], section_name: &str) -> Vec<u8> {
694    if !sess.target.is_like_wasm {
    ::core::panicking::panic("assertion failed: sess.target.is_like_wasm")
};assert!(sess.target.is_like_wasm);
695    let mut module = wasm_encoder::Module::new();
696    let mut imports = wasm_encoder::ImportSection::new();
697
698    if sess.target.pointer_width == 64 {
699        imports.import(
700            "env",
701            "__linear_memory",
702            wasm_encoder::MemoryType {
703                minimum: 0,
704                maximum: None,
705                memory64: true,
706                shared: false,
707                page_size_log2: None,
708            },
709        );
710    }
711
712    if imports.len() > 0 {
713        module.section(&imports);
714    }
715    module.section(&wasm_encoder::CustomSection {
716        name: "linking".into(),
717        data: Cow::Borrowed(&[2]),
718    });
719    module.section(&wasm_encoder::CustomSection { name: section_name.into(), data: data.into() });
720    module.finish()
721}