rust-ndarray / ndarray

ndarray: an N-dimensional array with array views, multidimensional slicing, and efficient operations
https://docs.rs/ndarray/
Apache License 2.0
3.62k stars 307 forks source link

Unsound usages of `VecFromRawParts` #1426

Closed llooFlashooll closed 3 months ago

llooFlashooll commented 3 months ago

Hi, I am scanning the ndarray in the latest version with my own static analyzer tool.

Unsafe conversion found at: src/data_repr.rs#L137

fn take_as_vec(&mut self) -> Vec<A>
{
   let capacity = self.capacity;
   let len = self.len;
   self.len = 0;
   self.capacity = 0;
   unsafe { Vec::from_raw_parts(self.ptr.as_ptr(), len, capacity) }
}

This unsound implementation of Vec::from_raw_parts would create a dangling pointer issues if the ptr is dropped automatically or is empty. The 'mem::forget' function can be used to avoid the issue.

This would potentially cause undefined behaviors in Rust. If we further manipulate the problematic converted types, it would potentially lead to different consequences such as uaf or double free. I am reporting this issue for your attention.

bluss commented 3 months ago

Thanks for the note - do you think that's an issue here, could you demonstrate the problem? ManuallyDrop is used several places in the same file (preferable to mem::forget in most cases).

llooFlashooll commented 3 months ago

Since my static analyzer may not be aware of this kind of semantic code, let me manually and carefully review and reply to you.

bluss commented 3 months ago

OwnedRepr is created from a Vec (OwnedRepr::from), which should be the basis for why this conversion is sound.

llooFlashooll commented 3 months ago

Thanks! I understand. Then there's no issue here. Sorry for any inconvenience I have caused.

bluss commented 3 months ago

No worries, thank you for taking a look, it helps!