Skip to content

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

cranelift-jit: assert that relocations stay within their definition (#14788)

Ilyas Mallaha42ca332e60d
diff --git a/cranelift/codegen/src/binemit/mod.rs b/cranelift/codegen/src/binemit/mod.rs
index 5ffa00efe1..9d06df6caa 100644
--- a/cranelift/codegen/src/binemit/mod.rs
+++ b/cranelift/codegen/src/binemit/mod.rs
@@ -146,6 +146,53 @@ pub enum Reloc {
PulleyCallIndirectHost,
}
+impl Reloc {
+ /// The number of bytes from the relocation's offset that applying it, or a
+ /// linker relaxing it, may read or write.
+ ///
+ /// This runs to the end of the instruction, or of the whole sequence for
+ /// relocations such as [`Reloc::ElfX86_64TlsGd`] that a linker rewrites
+ /// together. Bytes before the offset are not counted.
+ pub fn patched_len(self) -> u32 {
+ match self {
+ Self::Abs4
+ | Self::X86PCRel4
+ | Self::X86CallPCRel4
+ | Self::X86CallPLTRel4
+ | Self::X86GOTPCRel4
+ | Self::X86SecRel
+ | Self::Arm32Call
+ | Self::Arm64Call
+ | Self::S390xPCRel32Dbl
+ | Self::S390xPLTRel32Dbl
+ | Self::MachOX86_64Tlv
+ | Self::MachOAarch64TlsAdrPage21
+ | Self::MachOAarch64TlsAdrPageOff12
+ | Self::Aarch64TlsDescAdrPage21
+ | Self::Aarch64TlsDescLd64Lo12
+ | Self::Aarch64TlsDescAddLo12
+ | Self::Aarch64TlsDescCall
+ | Self::Aarch64AdrGotPage21
+ | Self::Aarch64AdrPrelPgHi21
+ | Self::Aarch64AddAbsLo12Nc
+ | Self::Aarch64Ld64GotLo12Nc
+ | Self::RiscvTlsGdHi20
+ | Self::RiscvPCRelLo12I
+ | Self::RiscvGotHi20
+ | Self::RiscvPCRelHi20
+ | Self::PulleyPcRel
+ | Self::PulleyCallIndirectHost => 4,
+ // The `lea` displacement and the `call` after it. The linker rewrites
+ // the whole general-dynamic sequence when it relaxes it.
+ Self::ElfX86_64TlsGd => 12,
+ // The `brasl` that the marker is attached to.
+ Self::S390xTlsGdCall => 6,
+ // `RiscvCallPlt` patches the `auipc` and `jalr` pair of a call.
+ Self::Abs8 | Self::S390xTlsGd64 | Self::RiscvCallPlt => 8,
+ }
+ }
+}
+
impl fmt::Display for Reloc {
/// Display trait implementation drops the arch, since its used in contexts where the arch is
/// already unambiguous, e.g. clif syntax with isa specified. In other contexts, use Debug.
diff --git a/cranelift/jit/src/compiled_blob.rs b/cranelift/jit/src/compiled_blob.rs
index a873f7a914..e23e6f5cbe 100644
--- a/cranelift/jit/src/compiled_blob.rs
+++ b/cranelift/jit/src/compiled_blob.rs
@@ -156,7 +156,13 @@ impl CompiledBlob {
},
) in self.relocs.iter().enumerate()
{
- debug_assert!((offset as usize) < self.size);
+ // The writes below rely on the relocation lying within the definition.
+ let end = (offset as usize).checked_add(kind.patched_len() as usize);
+ assert!(
+ end.is_some_and(|end| end <= self.size),
+ "{kind:?} relocation at offset {offset} is out of bounds of a {}-byte definition",
+ self.size,
+ );
let at = unsafe { self.ptr.offset(isize::try_from(offset).unwrap()) };
match kind {
Reloc::Abs4 => {
diff --git a/cranelift/jit/tests/basic.rs b/cranelift/jit/tests/basic.rs
index 4a5bfbfea9..0b75b405d8 100644
--- a/cranelift/jit/tests/basic.rs
+++ b/cranelift/jit/tests/basic.rs
@@ -226,6 +226,104 @@ fn empty_data_object() {
module.define_data(data_id, &data).unwrap();
}
+/// Defines a data object of `size` bytes holding the address of another data
+/// object at `offset`, then finalizes the module and returns the object and
+/// its target.
+fn finalize_data_with_reloc(
+ isa: OwnedTargetIsa,
+ zeroed: bool,
+ size: usize,
+ offset: u32,
+) -> (JITModule, DataId, DataId) {
+ let mut module = JITModule::new(JITBuilder::with_isa(isa, default_libcall_names()));
+
+ let target = module.declare_anonymous_data(false, false).unwrap();
+ let mut data = DataDescription::new();
+ data.define(Box::new([1]));
+ module.define_data(target, &data).unwrap();
+
+ let id = module.declare_anonymous_data(true, false).unwrap();
+ let mut data = DataDescription::new();
+ if zeroed {
+ data.define_zeroinit(size);
+ } else {
+ data.define(vec![0; size].into_boxed_slice());
+ }
+ let target_ref = module.declare_data_in_data(target, &mut data);
+ data.write_data_addr(offset, target_ref, 0);
+ module.define_data(id, &data).unwrap();
+ module.finalize_definitions().unwrap();
+ (module, id, target)
+}
+
+/// Asserts that `f` panics because a relocation is out of bounds.
+fn assert_reloc_out_of_bounds_panic(f: impl FnOnce()) {
+ let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
+ .expect_err("finalizing should panic");
+ let msg = payload.downcast_ref::<String>().expect("string panic");
+ assert!(
+ msg.contains("relocation at offset"),
+ "unexpected panic: {msg}"
+ );
+}
+
+#[test]
+fn data_reloc_out_of_bounds_panics_when_finalized() {
+ let Some(host_isa) = isa() else {
+ return;
+ };
+ let ptr_bytes = usize::from(host_isa.pointer_bytes());
+
+ // A pointer that ends exactly at the end of the object is fine.
+ let offset = u32::try_from(ptr_bytes).unwrap();
+ let (module, id, target) = finalize_data_with_reloc(host_isa, false, 2 * ptr_bytes, offset);
+ let (target_ptr, _) = module.get_finalized_data(target);
+ let (ptr, size) = module.get_finalized_data(id);
+ assert_eq!(size, 2 * ptr_bytes);
+ let written = unsafe { ptr.add(ptr_bytes).cast::<usize>().read_unaligned() };
+ assert_eq!(written, target_ptr.addr());
+
+ for zeroed in [false, true] {
+ // The pointer starts inside the object but ends past it.
+ assert_reloc_out_of_bounds_panic(|| {
+ finalize_data_with_reloc(isa().unwrap(), zeroed, ptr_bytes, 1);
+ });
+ // The pointer starts past the object.
+ assert_reloc_out_of_bounds_panic(|| {
+ finalize_data_with_reloc(isa().unwrap(), zeroed, ptr_bytes, u32::MAX);
+ });
+ }
+}
+
+#[test]
+fn function_bytes_reloc_out_of_bounds_panics_when_finalized() {
+ use cranelift_codegen::binemit::Reloc;
+
+ for (kind, offset) in [
+ (Reloc::Abs4, 1),
+ (Reloc::Abs8, 0),
+ (Reloc::Abs4, 64),
+ (Reloc::ElfX86_64TlsGd, 0),
+ ] {
+ let Some(isa) = isa() else {
+ return;
+ };
+ let mut module = JITModule::new(JITBuilder::with_isa(isa, default_libcall_names()));
+ let sig = module.make_signature();
+ let func_id = module.declare_anonymous_function(&sig).unwrap();
+ let reloc = ModuleReloc {
+ offset,
+ kind,
+ name: ModuleRelocTarget::FunctionOffset(func_id, 0),
+ addend: 0,
+ };
+ module
+ .define_function_bytes(func_id, 1, &[0; 4], &[reloc])
+ .unwrap();
+ assert_reloc_out_of_bounds_panic(|| module.finalize_definitions().unwrap());
+ }
+}
+
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
mod far_x86_memory {
use std::collections::VecDeque;