From 0aa94652a9bf151dd3e8ec743f5aa6078e7236ca Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 9 Apr 2020 15:33:32 -0500 Subject: [PATCH] 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. --- crates/c-api/src/vec.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/c-api/src/vec.rs b/crates/c-api/src/vec.rs index 252c7987ea..15918b29c9 100644 --- a/crates/c-api/src/vec.rs +++ b/crates/c-api/src/vec.rs @@ -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> {