worldcoin / semaphore-rs

🦀 Rust support library for semaphore

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unsafe usage of `from_raw_parts` and `from_raw_parts_mut`

Dzejkop opened this issue · comments

We use these functions in a few places without ensuring that the types we're converting into can be converted to.

For example:

    pub fn new_with_initial_values(
        file_path: PathBuf,
        initial_value: &H::Hash,
        storage_size: usize,
    ) -> Result<Self, DenseMMapError> {
        let size_of_val = std::mem::size_of_val(initial_value);
        let initial_vals: Vec<H::Hash> = vec![initial_value.clone(); storage_size];

        // cast Hash pointer to u8 pointer
        let ptr = initial_vals.as_ptr().cast::<u8>();

        let size_of_buffer: usize = storage_size * size_of_val;

        let buf: &[u8] = unsafe {
            // moving pointer by u8 for storage_size * size of hash would get us the full
            // buffer
            std::slice::from_raw_parts(ptr, size_of_buffer)
        };

H::Hash could be a type that contains padding which would put as in UB land.

We should use the bytemuck crate and demand that H::Hash is Pod

This also applies to the Deref and DerefMut impls.