-
Notifications
You must be signed in to change notification settings - Fork 15
Description
hello, thank you for your contribution in this project, I am scanning the unsoundness problem in rust project.
I notice the following code:
Line 6 in 74b7fa2
| data: &'data [u8], |
pub fn buffer_as_slice<'data, T: 'data>(
data: &'data [u8],
byte_offset: usize,
elements: usize,
) -> &'data [T] {
unsafe {
std::slice::from_raw_parts::<T>(
std::mem::transmute::<*const u8, *const T>(data.as_ptr().add(byte_offset)),
elements,
)
}
}
In my opinion, buffer_as_slice is a function that can cause undefined behavior in several ways:
Out-of-bounds access: The function doesn't validate that byte_offset is within the bounds of data, which can lead to accessing memory beyond the slice boundaries when calling data.as_ptr().add(byte_offset).
Insufficient memory size: There's no check to ensure that data contains enough bytes starting from byte_offset to accommodate elements number of T values (requires elements * size_of::() bytes).
Memory alignment violation: The function doesn't verify that data.as_ptr().add(byte_offset) is properly aligned for type T, which can cause hardware faults on some architectures.
Type safety violation: Reinterpreting &[u8] as &[T] is unsafe when T has validity constraints (e.g., bool, char, or types containing references).
Since this is a library published on crates.io, I thought it might be worth reporting this issue. According to Rust's safety specification, any code that could cause UB should either be marked as unsafe or include proper safety checks.
The function should either add comprehensive bounds checking, alignment verification, and type safety constraints, or require callers to ensure these preconditions and document them clearly.
I'm opening this issue for the author's reference to improve the memory safety of this function.