Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

cranelift-object: emit .eh_frame for System V unwind info (#13383)

HueCodesf77276f33b07
diff --git a/Cargo.lock b/Cargo.lock
index da04e90013..bfe232bfcf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -963,6 +963,7 @@ dependencies = [
"cranelift-entity",
"cranelift-frontend",
"cranelift-module",
+ "gimli 0.33.0",
"log",
"object 0.39.0",
"target-lexicon",
diff --git a/cranelift/object/Cargo.toml b/cranelift/object/Cargo.toml
index 43d255b15d..f635bb309a 100644
--- a/cranelift/object/Cargo.toml
+++ b/cranelift/object/Cargo.toml
@@ -21,6 +21,13 @@ object = { workspace = true, features = ["write", "std"] }
target-lexicon = { workspace = true }
anyhow = { workspace = true }
log = { workspace = true }
+gimli = { workspace = true, features = ["write"], optional = true }
+
+[features]
+default = ["unwind"]
+
+# Enables `.eh_frame` section emission via `ObjectBuilder::unwind_info`.
+unwind = ["dep:gimli", "cranelift-codegen/unwind"]
[dev-dependencies]
cranelift-frontend = { workspace = true }
diff --git a/cranelift/object/src/backend.rs b/cranelift/object/src/backend.rs
index c9bb0b3699..33ec3b4bbf 100644
--- a/cranelift/object/src/backend.rs
+++ b/cranelift/object/src/backend.rs
@@ -34,6 +34,8 @@ pub struct ObjectBuilder {
libcall_names: Box<dyn Fn(ir::LibCall) -> String + Send + Sync>,
per_function_section: bool,
per_data_object_section: bool,
+ #[cfg(feature = "unwind")]
+ unwind_info: bool,
}
impl ObjectBuilder {
@@ -121,6 +123,8 @@ impl ObjectBuilder {
libcall_names,
per_function_section: false,
per_data_object_section: false,
+ #[cfg(feature = "unwind")]
+ unwind_info: false,
})
}
@@ -135,6 +139,36 @@ impl ObjectBuilder {
self.per_data_object_section = per_data_object_section;
self
}
+
+ /// Emit a DWARF `.eh_frame` section describing the unwind information for
+ /// each compiled function.
+ ///
+ /// When enabled, ELF and COFF object files gain a `.eh_frame` section
+ /// containing one Common Information Entry and one Frame Description
+ /// Entry per function, suitable for unwinding by libgcc / libunwind.
+ ///
+ /// On Windows targets cranelift emits `.pdata`/`.xdata`-style info rather
+ /// than System V FDEs, so enabling this option is a silent no-op there.
+ /// Mach-O `__TEXT,__eh_frame` emission is not yet implemented; calling
+ /// `finish` on a Mach-O target with this enabled will panic with a
+ /// descriptive error.
+ ///
+ /// Only functions defined through [`Module::define_function`] are
+ /// captured. Functions provided as pre-compiled bytes through
+ /// [`Module::define_function_bytes`] are skipped, since their unwind
+ /// information is not available to the backend.
+ ///
+ /// Requires the `unwind` feature (enabled by default). Without it this
+ /// method does not exist, mirroring `cranelift-codegen`'s gating of
+ /// `CompiledCode::create_unwind_info`.
+ ///
+ /// [`Module::define_function`]: cranelift_module::Module::define_function
+ /// [`Module::define_function_bytes`]: cranelift_module::Module::define_function_bytes
+ #[cfg(feature = "unwind")]
+ pub fn unwind_info(&mut self, unwind_info: bool) -> &mut Self {
+ self.unwind_info = unwind_info;
+ self
+ }
}
/// See the following for details:
@@ -215,6 +249,8 @@ pub struct ObjectModule {
known_labels: HashMap<(FuncId, CodeOffset), SymbolId>,
per_function_section: bool,
per_data_object_section: bool,
+ #[cfg(feature = "unwind")]
+ unwind: Option<crate::unwind::UnwindBuilder>,
}
impl ObjectModule {
@@ -231,6 +267,10 @@ impl ObjectModule {
// https://github.com/bytecodealliance/wasmtime/issues/8730
object.set_macho_build_version(info);
}
+ #[cfg(feature = "unwind")]
+ let unwind = builder
+ .unwind_info
+ .then(|| crate::unwind::UnwindBuilder::new(builder.endian));
Self {
isa: builder.isa,
object,
@@ -244,6 +284,8 @@ impl ObjectModule {
known_labels: HashMap::new(),
per_function_section: builder.per_function_section,
per_data_object_section: builder.per_data_object_section,
+ #[cfg(feature = "unwind")]
+ unwind,
}
}
}
@@ -410,7 +452,14 @@ impl Module for ObjectModule {
let res = ctx.compile(self.isa(), ctrl_plane)?;
let alignment = res.buffer.alignment as u64;
- let buffer = &ctx.compiled_code().unwrap().buffer;
+ let compiled = ctx.compiled_code().unwrap();
+ #[cfg(feature = "unwind")]
+ let unwind_info = if self.unwind.is_some() {
+ compiled.create_unwind_info(self.isa())?
+ } else {
+ None
+ };
+ let buffer = &compiled.buffer;
let relocs = buffer
.relocs()
.iter()
@@ -418,7 +467,13 @@ impl Module for ObjectModule {
self.process_reloc(&ModuleReloc::from_mach_reloc(&reloc, &ctx.func, func_id))
})
.collect::<Vec<_>>();
- self.define_function_inner(func_id, alignment, buffer.data(), relocs)
+ self.define_function_inner(func_id, alignment, buffer.data(), relocs)?;
+ #[cfg(feature = "unwind")]
+ if let (Some(builder), Some(info)) = (self.unwind.as_mut(), unwind_info) {
+ let symbol = self.functions[func_id].unwrap().0;
+ builder.add_function(&*self.isa, symbol, info);
+ }
+ Ok(())
}
fn define_function_bytes(
@@ -684,6 +739,13 @@ impl ObjectModule {
);
}
+ #[cfg(feature = "unwind")]
+ if let Some(unwind) = self.unwind.take() {
+ unwind
+ .finish(&mut self.object, &*self.isa)
+ .expect("failed to emit .eh_frame section");
+ }
+
ObjectProduct {
object: self.object,
functions: self.functions,
diff --git a/cranelift/object/src/lib.rs b/cranelift/object/src/lib.rs
index 6967f890df..736fa46a3b 100644
--- a/cranelift/object/src/lib.rs
+++ b/cranelift/object/src/lib.rs
@@ -5,6 +5,8 @@
#![deny(missing_docs)]
mod backend;
+#[cfg(feature = "unwind")]
+mod unwind;
pub use crate::backend::{ObjectBuilder, ObjectModule, ObjectProduct};
diff --git a/cranelift/object/src/unwind.rs b/cranelift/object/src/unwind.rs
new file mode 100644
index 0000000000..3b7c176bde
--- /dev/null
+++ b/cranelift/object/src/unwind.rs
@@ -0,0 +1,287 @@
+//! `.eh_frame` section emission for [`ObjectModule`].
+//!
+//! Cranelift's code generator already produces per-function `UnwindInfo`. On
+//! System V targets that information is enough to construct a DWARF Call Frame
+//! Information `.eh_frame` section consumable by libgcc/libunwind. This module
+//! aggregates the generated FDEs into a single per-object section, with
+//! relocations against each function's text symbol.
+//!
+//! [`ObjectModule`]: crate::ObjectModule
+
+use anyhow::{Result, anyhow};
+use cranelift_codegen::isa::TargetIsa;
+use cranelift_codegen::isa::unwind::UnwindInfo;
+use gimli::write::{
+ Address, CieId, EhFrame, EndianVec, FrameTable, RelocateWriter, Relocation, RelocationTarget,
+};
+use object::write::{Object, Relocation as ObjectRelocation, StandardSection, SymbolId};
+use object::{BinaryFormat, RelocationEncoding, RelocationFlags, RelocationKind};
+
+pub(crate) struct UnwindBuilder {
+ section: EhFrameSection,
+ frame_table: FrameTable,
+ cie_id: Option<CieId>,
+ /// Maps gimli's opaque symbol indices back to `object` `SymbolId`s.
+ symbols: Vec<SymbolId>,
+}
+
+impl UnwindBuilder {
+ pub(crate) fn new(endian: object::Endianness) -> Self {
+ let endian = match endian {
+ object::Endianness::Little => gimli::RunTimeEndian::Little,
+ object::Endianness::Big => gimli::RunTimeEndian::Big,
+ };
+ Self {
+ section: EhFrameSection {
+ writer: EndianVec::new(endian),
+ relocations: Vec::new(),
+ },
+ frame_table: FrameTable::default(),
+ cie_id: None,
+ symbols: Vec::new(),
+ }
+ }
+
+ /// Record an FDE for the given function.
+ ///
+ /// Windows-flavored unwind info is silently ignored: `.pdata`/`.xdata`
+ /// emission lives on a separate code path. The CIE is created lazily on
+ /// the first System V FDE so that an unwind builder shared across many
+ /// objects does not pay for an empty CIE when the target produces no
+ /// System V info at all.
+ pub(crate) fn add_function(
+ &mut self,
+ isa: &dyn TargetIsa,
+ func_symbol: SymbolId,
+ info: UnwindInfo,
+ ) {
+ let UnwindInfo::SystemV(sysv) = info else {
+ return;
+ };
+ let cie_id = match self.cie_id {
+ Some(id) => id,
+ None => {
+ let Some(cie) = isa.create_systemv_cie() else {
+ return;
+ };
+ let id = self.frame_table.add_cie(cie);
+ self.cie_id = Some(id);
+ id
+ }
+ };
+ let symbol_index = self.symbols.len();
+ self.symbols.push(func_symbol);
+ let address = Address::Symbol {
+ symbol: symbol_index,
+ addend: 0,
+ };
+ self.frame_table.add_fde(cie_id, sysv.to_fde(address));
+ }
+
+ /// Serialize all collected FDEs into an `.eh_frame` section on `object`.
+ ///
+ /// Returns without writing anything if no FDE was ever added (e.g. when
+ /// the user enabled unwind info on a target that does not produce System V
+ /// frames). The pointer-width unwrap is safe because [`ObjectBuilder`]
+ /// has already rejected unknown architectures during construction.
+ ///
+ /// [`ObjectBuilder`]: crate::ObjectBuilder
+ pub(crate) fn finish(self, object: &mut Object<'static>, isa: &dyn TargetIsa) -> Result<()> {
+ let UnwindBuilder {
+ section,
+ frame_table,
+ cie_id,
+ symbols,
+ } = self;
+ if cie_id.is_none() {
+ return Ok(());
+ }
+ let mut eh_frame = EhFrame(section);
+ frame_table
+ .write_eh_frame(&mut eh_frame)
+ .map_err(|err| anyhow!("failed to write .eh_frame: {err}"))?;
+ let EhFrame(EhFrameSection {
+ writer,
+ relocations,
+ }) = eh_frame;
+
+ let section_id = object.section_id(StandardSection::EhFrame);
+ let alignment = u64::from(isa.triple().pointer_width().unwrap().bytes());
+ object.append_section_data(section_id, &writer.into_vec(), alignment);
+
+ let format = object.format();
+ for reloc in relocations {
+ let symbol_id = match reloc.target {
+ RelocationTarget::Symbol(index) => symbols[index],
+ // gimli's writer only emits section-relative relocations for
+ // DWARF debug sections, never for `.eh_frame`. Skip defensively.
+ RelocationTarget::Section(_) => continue,
+ };
+ let flags = translate_eh_pe(reloc.eh_pe, reloc.size, format)?;
+ object
+ .add_relocation(
+ section_id,
+ ObjectRelocation {
+ offset: reloc.offset as u64,
+ symbol: symbol_id,
+ addend: reloc.addend,
+ flags,
+ },
+ )
+ .map_err(|err| anyhow!("failed to record .eh_frame relocation: {err}"))?;
+ }
+ Ok(())
+ }
+}
+
+struct EhFrameSection {
+ writer: EndianVec<gimli::RunTimeEndian>,
+ relocations: Vec<Relocation>,
+}
+
+impl RelocateWriter for EhFrameSection {
+ type Writer = EndianVec<gimli::RunTimeEndian>;
+
+ fn writer(&self) -> &Self::Writer {
+ &self.writer
+ }
+
+ fn writer_mut(&mut self) -> &mut Self::Writer {
+ &mut self.writer
+ }
+
+ fn relocate(&mut self, relocation: Relocation) {
+ self.relocations.push(relocation);
+ }
+}
+
+/// Translate a gimli `.eh_frame` relocation request into the `object` crate's
+/// relocation flags for the target binary format.
+///
+/// `eh_pe` is `None` for non-pointer relocations (rare in `.eh_frame`); in that
+/// case we treat the request as an absolute pointer of the requested width.
+fn translate_eh_pe(
+ eh_pe: Option<gimli::constants::DwEhPe>,
+ size: u8,
+ format: BinaryFormat,
+) -> Result<RelocationFlags> {
+ use gimli::constants::*;
+
+ let Some(pe) = eh_pe else {
+ return Ok(RelocationFlags::Generic {
+ kind: RelocationKind::Absolute,
+ encoding: RelocationEncoding::Generic,
+ size: size * 8,
+ });
+ };
+
+ let application = pe.application();
+ let kind = if application == DW_EH_PE_absptr {
+ RelocationKind::Absolute
+ } else if application == DW_EH_PE_pcrel {
+ RelocationKind::Relative
+ } else {
+ return Err(anyhow!(
+ "unsupported eh_frame pointer application {application:?}"
+ ));
+ };
+ let format_byte = pe.format();
+ let bit_size = if format_byte == DW_EH_PE_absptr {
+ size * 8
+ } else if format_byte == DW_EH_PE_udata2 || format_byte == DW_EH_PE_sdata2 {
+ 16
+ } else if format_byte == DW_EH_PE_udata4 || format_byte == DW_EH_PE_sdata4 {
+ 32
+ } else if format_byte == DW_EH_PE_udata8 || format_byte == DW_EH_PE_sdata8 {
+ 64
+ } else {
+ return Err(anyhow!(
+ "unsupported eh_frame pointer format {format_byte:?}"
+ ));
+ };
+
+ // Mach-O encodes PC-relative `.eh_frame` references as a SUBTRACTOR /
+ // UNSIGNED relocation pair, which is out of scope here. Surface a clear
+ // error rather than emitting the wrong relocation.
+ //
+ // TODO: arm64 Mach-O `__TEXT,__eh_frame` is feasible via that reloc pair;
+ // see rust-lang/rustc_codegen_cranelift#1634 for the approach.
+ if matches!(format, BinaryFormat::MachO) && kind == RelocationKind::Relative {
+ return Err(anyhow!("Mach-O .eh_frame emission is not yet supported"));
+ }
+
+ Ok(RelocationFlags::Generic {
+ kind,
+ encoding: RelocationEncoding::Generic,
+ size: bit_size,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use gimli::constants::*;
+
+ #[track_caller]
+ fn assert_generic(flags: RelocationFlags, expected_kind: RelocationKind, expected_size: u8) {
+ match flags {
+ RelocationFlags::Generic {
+ kind,
+ encoding,
+ size,
+ } => {
+ assert_eq!(kind, expected_kind, "wrong relocation kind");
+ assert_eq!(
+ encoding,
+ RelocationEncoding::Generic,
+ "wrong relocation encoding"
+ );
+ assert_eq!(size, expected_size, "wrong relocation size in bits");
+ }
+ other => panic!("expected RelocationFlags::Generic, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn missing_eh_pe_falls_back_to_absolute_pointer() {
+ let flags = translate_eh_pe(None, 8, BinaryFormat::Elf).unwrap();
+ assert_generic(flags, RelocationKind::Absolute, 64);
+ }
+
+ #[test]
+ fn absolute_eh_pointer_on_elf() {
+ let flags = translate_eh_pe(Some(DW_EH_PE_absptr), 8, BinaryFormat::Elf).unwrap();
+ assert_generic(flags, RelocationKind::Absolute, 64);
+ }
+
+ #[test]
+ fn pcrel_sdata4_on_elf() {
+ let pe = DwEhPe(DW_EH_PE_pcrel.0 | DW_EH_PE_sdata4.0);
+ let flags = translate_eh_pe(Some(pe), 8, BinaryFormat::Elf).unwrap();
+ assert_generic(flags, RelocationKind::Relative, 32);
+ }
+
+ #[test]
+ fn pcrel_sdata4_on_coff() {
+ let pe = DwEhPe(DW_EH_PE_pcrel.0 | DW_EH_PE_sdata4.0);
+ let flags = translate_eh_pe(Some(pe), 8, BinaryFormat::Coff).unwrap();
+ assert_generic(flags, RelocationKind::Relative, 32);
+ }
+
+ #[test]
+ fn pcrel_on_macho_is_rejected() {
+ let pe = DwEhPe(DW_EH_PE_pcrel.0 | DW_EH_PE_sdata4.0);
+ let err = translate_eh_pe(Some(pe), 8, BinaryFormat::MachO).unwrap_err();
+ assert!(
+ err.to_string().contains("Mach-O"),
+ "expected Mach-O scoping error, got: {err}"
+ );
+ }
+
+ #[test]
+ fn unknown_pointer_application_errors() {
+ let pe = DwEhPe(0xee); // DW_EH_PE_indirect plus garbage; not handled.
+ let err = translate_eh_pe(Some(pe), 8, BinaryFormat::Elf).unwrap_err();
+ assert!(err.to_string().contains("application"));
+ }
+}
diff --git a/cranelift/object/tests/basic.rs b/cranelift/object/tests/basic.rs
index bdc03886a4..2555221493 100644
--- a/cranelift/object/tests/basic.rs
+++ b/cranelift/object/tests/basic.rs
@@ -309,3 +309,253 @@ fn aarch64_colocated_data_symbol_reloc() {
let product = module.finish();
product.emit().expect("emit object file");
}
+
+// ---------- `.eh_frame` emission tests ----------
+
+#[cfg(feature = "unwind")]
+mod eh_frame {
+ use super::*;
+ use cranelift_codegen::settings::Configurable as _;
+ use gimli::UnwindSection as _;
+ use object::Object as _;
+ use object::ObjectSection as _;
+
+ /// Build an `ObjectModule` for `triple` with the unwind-info builder flag
+ /// set to `unwind_info`. Frame pointers are forced on so cranelift emits
+ /// a non-trivial prologue (and therefore unwind info) for every function.
+ fn module_for(triple: &str, unwind_info: bool) -> ObjectModule {
+ let mut flag_builder = settings::builder();
+ flag_builder.set("preserve_frame_pointers", "true").unwrap();
+ let isa = cranelift_codegen::isa::lookup_by_name(triple)
+ .unwrap()
+ .finish(settings::Flags::new(flag_builder))
+ .unwrap();
+ let mut builder = ObjectBuilder::new(isa, "test", default_libcall_names()).unwrap();
+ builder.unwind_info(unwind_info);
+ ObjectModule::new(builder)
+ }
+
+ /// Define a leaf function that just returns. With `preserve_frame_pointers`
+ /// on, this is enough to make cranelift emit a System V FDE for it.
+ fn define_leaf(module: &mut ObjectModule, name: &str) -> FuncId {
+ let sig = Signature {
+ params: vec![],
+ returns: vec![],
+ call_conv: CallConv::SystemV,
+ };
+ let func_id = module.declare_function(name, Linkage::Local, &sig).unwrap();
+ let mut ctx = Context::new();
+ ctx.func = Function::with_name_signature(UserFuncName::user(0, func_id.as_u32()), sig);
+ let mut func_ctx = FunctionBuilderContext::new();
+ {
+ let mut bcx = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
+ let block = bcx.create_block();
+ bcx.switch_to_block(block);
+ bcx.ins().return_(&[]);
+ bcx.seal_all_blocks();
+ bcx.finalize();
+ }
+ module.define_function(func_id, &mut ctx).unwrap();
+ func_id
+ }
+
+ /// Iterate the entries in `.eh_frame` bytes, returning `(cie_count, fde_count)`.
+ fn count_entries(data: &[u8]) -> (usize, usize) {
+ let mut eh_frame = gimli::EhFrame::new(data, gimli::LittleEndian);
+ eh_frame.set_address_size(8);
+ let bases = gimli::BaseAddresses::default();
+ let mut entries = eh_frame.entries(&bases);
+ let (mut cies, mut fdes) = (0, 0);
+ while let Some(entry) = entries.next().expect("walk eh_frame entries") {
+ match entry {
+ gimli::CieOrFde::Cie(_) => cies += 1,
+ gimli::CieOrFde::Fde(_) => fdes += 1,
+ }
+ }
+ (cies, fdes)
+ }
+
+ #[test]
+ fn emits_eh_frame_for_x86_64_systemv_target() {
+ let mut module = module_for("x86_64-unknown-linux-gnu", true);
+ define_leaf(&mut module, "leaf");
+
+ let bytes = module.finish().emit().expect("emit object file");
+ let file = object::File::parse(&*bytes).expect("parse emitted object");
+ let section = file
+ .section_by_name(".eh_frame")
+ .expect(".eh_frame section is present");
+ let data = section.data().expect("read .eh_frame data");
+ assert!(!data.is_empty(), ".eh_frame must not be empty");
+
+ let (cies, fdes) = count_entries(data);
+ assert_eq!(cies, 1, "expected exactly one CIE");
+ assert_eq!(fdes, 1, "expected exactly one FDE");
+
+ let relocations: Vec<_> = section.relocations().collect();
+ assert!(
+ !relocations.is_empty(),
+ ".eh_frame must carry symbol relocations"
+ );
+ }
+
+ #[test]
+ fn emits_eh_frame_for_aarch64_target() {
+ let mut module = module_for("aarch64-unknown-linux-gnu", true);
+ define_leaf(&mut module, "leaf");
+
+ let bytes = module.finish().emit().expect("emit object file");
+ let file = object::File::parse(&*bytes).expect("parse emitted object");
+ let data = file
+ .section_by_name(".eh_frame")
+ .expect(".eh_frame section is present")
+ .data()
+ .expect("read .eh_frame data");
+
+ let (cies, fdes) = count_entries(data);
+ assert_eq!(cies, 1, "expected exactly one CIE");
+ assert_eq!(fdes, 1, "expected exactly one FDE");
+ }
+
+ #[test]
+ fn unwind_info_disabled_by_default_emits_no_eh_frame() {
+ let flag_builder = settings::builder();
+ let isa = cranelift_codegen::isa::lookup_by_name("x86_64-unknown-linux-gnu")
+ .unwrap()
+ .finish(settings::Flags::new(flag_builder))
+ .unwrap();
+ let mut module =
+ ObjectModule::new(ObjectBuilder::new(isa, "no_eh", default_libcall_names()).unwrap());
+ define_simple_function(&mut module);
+
+ let bytes = module.finish().emit().expect("emit object file");
+ let file = object::File::parse(&*bytes).expect("parse emitted object");
+ assert!(
+ file.section_by_name(".eh_frame").is_none(),
+ "no .eh_frame section should be emitted when unwind_info is off"
+ );
+ }
+
+ #[test]
+ fn cie_is_shared_across_multiple_functions() {
+ let mut module = module_for("x86_64-unknown-linux-gnu", true);
+ define_leaf(&mut module, "leaf_a");
+ define_leaf(&mut module, "leaf_b");
+ define_leaf(&mut module, "leaf_c");
+
+ let bytes = module.finish().emit().expect("emit object file");
+ let file = object::File::parse(&*bytes).expect("parse emitted object");
+ let data = file
+ .section_by_name(".eh_frame")
+ .expect(".eh_frame section is present")
+ .data()
+ .expect("read .eh_frame data");
+
+ let (cies, fdes) = count_entries(data);
+ assert_eq!(cies, 1, "all functions must share a single CIE, got {cies}");
+ assert_eq!(fdes, 3, "expected one FDE per function, got {fdes}");
+ }
+
+ #[test]
+ fn fde_relocations_target_function_symbols() {
+ use object::ObjectSymbol as _;
+
+ let mut module = module_for("x86_64-unknown-linux-gnu", true);
+ define_leaf(&mut module, "leaf");
+
+ let bytes = module.finish().emit().expect("emit object file");
+ let file = object::File::parse(&*bytes).expect("parse emitted object");
+ let section = file
+ .section_by_name(".eh_frame")
+ .expect(".eh_frame section is present");
+
+ let leaf_symbol_index = file
+ .symbols()
+ .find(|s| s.name() == Ok("leaf"))
+ .expect("function symbol present in object")
+ .index();
+
+ let (_, reloc) = section
+ .relocations()
+ .next()
+ .expect(".eh_frame must carry at least one relocation");
+ let object::read::RelocationTarget::Symbol(target_index) = reloc.target() else {
+ panic!(
+ "expected symbol-targeted relocation, got {:?}",
+ reloc.target()
+ );
+ };
+ assert_eq!(
+ target_index, leaf_symbol_index,
+ "FDE relocation must target the function's text symbol"
+ );
+ }
+
+ #[test]
+ fn per_function_section_combines_with_unwind_info() {
+ // With every function in its own subsection, the FDE relocations must
+ // still resolve because they target function symbols rather than the
+ // shared `.text` section. Just walking the entries should succeed and
+ // produce one FDE per function.
+ let mut flag_builder = settings::builder();
+ flag_builder.set("preserve_frame_pointers", "true").unwrap();
+ let isa = cranelift_codegen::isa::lookup_by_name("x86_64-unknown-linux-gnu")
+ .unwrap()
+ .finish(settings::Flags::new(flag_builder))
+ .unwrap();
+ let mut builder = ObjectBuilder::new(isa, "test", default_libcall_names()).unwrap();
+ builder.unwind_info(true);
+ builder.per_function_section(true);
+ let mut module = ObjectModule::new(builder);
+ define_leaf(&mut module, "leaf_a");
+ define_leaf(&mut module, "leaf_b");
+
+ let bytes = module.finish().emit().expect("emit object file");
+ let file = object::File::parse(&*bytes).expect("parse emitted object");
+ let data = file
+ .section_by_name(".eh_frame")
+ .expect(".eh_frame section is present")
+ .data()
+ .expect("read .eh_frame data");
+ let (cies, fdes) = count_entries(data);
+ assert_eq!(cies, 1);
+ assert_eq!(fdes, 2);
+ }
+
+ #[test]
+ fn no_eh_frame_emitted_for_windows_target() {
+ // On Windows targets cranelift produces `UnwindInfo::WindowsX64`
+ // rather than System V info, and the unwind builder ignores those
+ // variants. With no FDE ever added, no `.eh_frame` section should
+ // appear in the resulting object even though `unwind_info(true)` was
+ // set on the builder.
+ let mut module = module_for("x86_64-pc-windows-msvc", true);
+ let sig = Signature {
+ params: vec![],
+ returns: vec![],
+ call_conv: CallConv::WindowsFastcall,
+ };
+ let func_id = module
+ .declare_function("leaf", Linkage::Local, &sig)
+ .unwrap();
+ let mut ctx = Context::new();
+ ctx.func = Function::with_name_signature(UserFuncName::user(0, func_id.as_u32()), sig);
+ let mut func_ctx = FunctionBuilderContext::new();
+ {
+ let mut bcx = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);
+ let block = bcx.create_block();
+ bcx.switch_to_block(block);
+ bcx.ins().return_(&[]);
+ bcx.seal_all_blocks();
+ bcx.finalize();
+ }
+ module.define_function(func_id, &mut ctx).unwrap();
+
+ let bytes = module.finish().emit().expect("emit object file");
+ let file = object::File::parse(&*bytes).expect("parse emitted object");
+ assert!(
+ file.section_by_name(".eh_frame").is_none(),
+ "no .eh_frame should be emitted for Windows targets"
+ );
+ }
+}