tspooner / elementwise

Elementwise operations implemented for standard Rust containers.
MIT License
0 stars 0 forks source link

panic safety issue in impls of `ElementwiseMul` trait on arrays #1

Open JOE1994 opened 3 years ago

JOE1994 commented 3 years ago

Hello :crab: , we (Rust group @sslab-gatech) found a memory-safety/soundness issue in this crate while scanning Rust code on crates.io for potential vulnerabilities.

Issue Description

impl<$it: Copy + $ot<Output = $it>> $nt<$it> for [$it; $length] {
    fn $nm(&self, other: &$it) -> [$it; $length] {
        let mut items: [$it; $length] = unsafe { mem::uninitialized() };

        for i in 0..$length {
            unsafe {
                ptr::write(&mut items[i], self[i].$om(*other));
            }
        }

        items
    }
}

In https://docs.rs/elementwise/0.3.2/src/elementwise/macros/array.rs.html , std::mem::uninitialized is used in the macros. core::ops::Mul is a public trait that can be implmented on custom types, and users can provide Mul implementations that can potentially panic.

If a panic happens, the partially uninitialized items will be dropped, and dropping uninitialized memory will cause undefined behavior.

Thank you for checking out this issue :+1:

JOE1994 commented 3 years ago

Following the docs I tried writing a fix using MaybeUninit<T>, but I'm currently stuck with a known issue with mem::transmute. The Rust team is currently working on project-safe-transmute to solve the issue.