Skip to content

Fix panic when read/write out of bounds #1554

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions crates/core/src/memory/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
ty::{MemoryType, MemoryTypeBuilder},
};
use crate::{Fuel, FuelError, ResourceLimiterRef};
use core::ops::Range;

#[cfg(feature = "simd")]
pub use self::access::ExtendInto;
Expand Down Expand Up @@ -278,17 +279,25 @@
self.bytes.len
}

/// Returns the index span for the memory access at `start..(start+len)`.
fn access_span(start: usize, len: usize) -> Result<Range<usize>, MemoryError> {
let Some(end) = start.checked_add(len) else {
return Err(MemoryError::OutOfBoundsAccess);

Check warning on line 285 in crates/core/src/memory/mod.rs

View check run for this annotation

Codecov / codecov/patch

crates/core/src/memory/mod.rs#L285

Added line #L285 was not covered by tests
};
Ok(start..end)
}

/// Reads `n` bytes from `memory[offset..offset+n]` into `buffer`
/// where `n` is the length of `buffer`.
///
/// # Errors
///
/// If this operation accesses out of bounds linear memory.
pub fn read(&self, offset: usize, buffer: &mut [u8]) -> Result<(), MemoryError> {
let len_buffer = buffer.len();
let span = Self::access_span(offset, buffer.len())?;

Check warning on line 297 in crates/core/src/memory/mod.rs

View check run for this annotation

Codecov / codecov/patch

crates/core/src/memory/mod.rs#L297

Added line #L297 was not covered by tests
let slice = self
.data()
.get(offset..(offset + len_buffer))
.get(span)
.ok_or(MemoryError::OutOfBoundsAccess)?;
buffer.copy_from_slice(slice);
Ok(())
Expand All @@ -301,10 +310,10 @@
///
/// If this operation accesses out of bounds linear memory.
pub fn write(&mut self, offset: usize, buffer: &[u8]) -> Result<(), MemoryError> {
let len_buffer = buffer.len();
let span = Self::access_span(offset, buffer.len())?;
let slice = self
.data_mut()
.get_mut(offset..(offset + len_buffer))
.get_mut(span)
.ok_or(MemoryError::OutOfBoundsAccess)?;
slice.copy_from_slice(buffer);
Ok(())
Expand Down