wasmtime-c-api: Don't create slices with null pointers (#1492)

It's a common idiom to pass in `NULL` for slices of zero-length in the C
API, but it's not safe to create a Rust `&[T]` slice with this `NULL`
pointer. Special-case this in the `as_slice()` method of incoming
vectors to return an empty slice so we don't violate Rust's invariants.
This commit is contained in:
Alex Crichton
2020-04-09 15:33:32 -05:00
committed by GitHub
parent de919382b3
commit 0aa94652a9

View File

@@ -42,7 +42,15 @@ macro_rules! declare_vecs {
} }
pub fn as_slice(&self) -> &[$elem_ty] { pub fn as_slice(&self) -> &[$elem_ty] {
unsafe { slice::from_raw_parts(self.data, self.size) } // Note that we're careful to not create a slice with a null
// pointer as the data pointer, since that isn't defined
// behavior in Rust.
if self.size == 0 {
&[]
} else {
assert!(!self.data.is_null());
unsafe { slice::from_raw_parts(self.data, self.size) }
}
} }
pub fn take(&mut self) -> Vec<$elem_ty> { pub fn take(&mut self) -> Vec<$elem_ty> {