kornelski / lodepng-rust

All-in-one PNG image encoder/decoder in pure Rust
https://lib.rs/lodepng
zlib License
100 stars 23 forks source link

CSlice seems to be horribly unsafe? #22

Closed quadrupleslap closed 7 years ago

quadrupleslap commented 7 years ago

Pretty sure that CSlice leads to a use-after-free in entirely safe code. It should be bound to the lifetime of the CVec, but honestly I'm not sure why it exists when CVec::as_ref exists.

fn use_after_free() {
    // Calls to as_ref are just for formatting purposes.
    let x = make_a_vec();
    let y = x.as_cslice();
    println!("{:?}", x.as_ref());
    println!("{:?}", y.as_ref());
    drop(x);
    println!("{:?}", y.as_ref());

    fn make_a_vec() -> CVec<u8> {
        unsafe {
            let mut vec = vec![0, 1, 2].into_boxed_slice();
            let start = vec.as_mut_ptr();
            let raw = Box::into_raw(vec);

            CVec::new_with_dtor(
                start,
                3,
                move |_| {
                    println!("FREED.");
                    drop(Box::from_raw(start))
                }
            )
        }
    }
}
kornelski commented 7 years ago

Yup, it is :(

quadrupleslap commented 7 years ago

Bump: The patch broke the build.

kornelski commented 7 years ago

Fixed. Thanks.