noritada / grib-rs

GRIB format parser for Rust
Apache License 2.0
56 stars 9 forks source link

Seg Fault on JPEG2000 decoding #3

Closed cetra3 closed 3 years ago

cetra3 commented 3 years ago

Simple Description on the Bug

There is a segmentation fault when reading JPEG2000 streams due to unsafe code. This is due to the image struct being dropped at the end of the function, so the pointer given to from_raw_parts is no longer valid.

https://github.com/noritada/grib-rs/blob/1b3d559bf6215acf656063fa51bbdb4c5b83ee4b/src/decoders/jpeg2000/mod.rs#L113-L119

I found this when trying to read data from the ECMWF provided files (namely the U/V components of wind)

Steps to Reproduce

  1. Download some of the U/V component files from ECMWF

  2. Run gribber decode <file.grib2.bin> 0

Expected Behavior

I get a nice array of values

Actual Behavior

Segfault on Linux

Additional Context

A trivial way would be to create a vec so that the values are owned:

        let vec = unsafe {
            std::slice::from_raw_parts(comp_gray.data, (width * height) as usize)
                .iter()
                .map(|x| *x as i32)
                .collect::<Vec<_>>()
        };
        Ok(vec.into_iter())

Or the SimplePackingDecodeIterator could be inlined into the function, ensuring the slice memory is alive until the return

noritada commented 3 years ago

@cetra3 Thank you very much for your report and suggestion! I have fixed the issue using the simple method you suggested.

I was aware of this problem, but didn't have time to investigate for a while. Thank you very much.