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