Skip to content

Commit

Permalink
wasmtime-c-api: Don't create slices with null pointers (bytecodeallia…
Browse files Browse the repository at this point in the history
…nce#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.
  • Loading branch information
alexcrichton authored Apr 9, 2020
1 parent de91938 commit 0aa9465
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion crates/c-api/src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ macro_rules! declare_vecs {
}

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> {
Expand Down

0 comments on commit 0aa9465

Please sign in to comment.