Skip to content

Commit 1cfdc2c

Browse files
committed
rust: allow empty slices on empty memory (but ensure memory exists)
1 parent 997a44b commit 1cfdc2c

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

bindings/rust/src/lib.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -297,12 +297,13 @@ impl Instance {
297297
) -> Result<core::ops::Range<usize>, ()> {
298298
// This should be safe given usize::BITS >= u32::BITS, see https://doc.rust-lang.org/std/primitive.usize.html.
299299
let offset = offset as usize;
300+
let has_memory = unsafe { sys::fizzy_module_has_memory(self.get_module()) };
300301
let memory_size = self.memory_size();
301302
// Empty slices are allowed, but ensure both starting and ending offsets are valid.
302-
if memory_size == 0 || offset.checked_add(size).is_none() || (offset + size) > memory_size {
303+
if !has_memory || offset.checked_add(size).is_none() || (offset + size) > memory_size {
303304
return Err(());
304305
}
305-
debug_assert!(memory_size != 0);
306+
// Slices allow len=0, but data must be a valid pointer.
306307
debug_assert!(
307308
unsafe { sys::fizzy_get_instance_memory_data(self.0.as_ptr()) } != std::ptr::null_mut()
308309
);
@@ -888,8 +889,8 @@ mod tests {
888889

889890
// If there is no memory, do not allow any slice.
890891
unsafe {
891-
assert!(instance.checked_memory_slice(0, 0).is_err());
892-
assert!(instance.checked_memory_slice_mut(0, 0).is_err());
892+
assert!(instance.checked_memory_slice(0, 0).is_ok());
893+
assert!(instance.checked_memory_slice_mut(0, 0).is_ok());
893894
assert!(instance.checked_memory_slice(0, 65536).is_err());
894895
assert!(instance.checked_memory_slice_mut(0, 65536).is_err());
895896
assert!(instance.checked_memory_slice(65535, 1).is_err());
@@ -903,13 +904,13 @@ mod tests {
903904
}
904905

905906
// Set memory via safe helper.
906-
assert!(instance.memory_set(0, &[]).is_err());
907+
assert!(instance.memory_set(0, &[]).is_ok());
907908
assert!(instance.memory_set(0, &[0x11, 0x22]).is_err());
908909
// Get memory via safe helper.
909910
let mut dst: Vec<u8> = Vec::new();
910911
dst.resize(65536, 0);
911912
// Reading empty slice.
912-
assert!(instance.memory_get(0, &mut dst[0..0]).is_err());
913+
assert!(instance.memory_get(0, &mut dst[0..0]).is_ok());
913914
// Reading 65536 bytes.
914915
assert!(instance.memory_get(0, &mut dst).is_err());
915916
}

0 commit comments

Comments
 (0)