Unsoundness in cast_ptr_to_slice

I think there is a unsound problem in cast _ptr_to_slice. But the author don't think so. See Unsoundness in cast_ptr_to_slice · Issue #444 · nervosnetwork/ckb-vm · GitHub for detail.
The fn is below

pub fn cast_ptr_to_slice(&self, ptr: u64, offset: usize, size: usize) -> &[u8] {
let ptr = ptr as *const u8;
let ptr = ptr.add(offset);
std::slice::from_raw_parts(ptr, size)
}

You proved it by example, even.

You're correct that the way to make that function sound is to mark the function unsafe and document the requirements that the caller must uphold.

The author is wrong about how unsafe is intended to be used in this scenario.

Soundness (of code / of a library)

Soundness is a type system concept (actually originating from the study of logics) and means that the type system is "correct" in the sense that well-typed programs actually have the desired properties. For Rust, this means well-typed programs cannot cause Undefined Behavior. This promise only extends to safe code however; for unsafe code, it is up to the programmer to uphold this contract.

Accordingly, we say that a library (or an individual function) is sound if it is impossible for safe code to cause Undefined Behavior using its public API. Conversely, the library/function is unsound if safe code can cause Undefined Behavior.

(Bold emphasis added.)

1 Like