Skip to content

Unsoundness: Use-After-Free on PixelFormat possible #1521

@t1mlange

Description

@t1mlange

Hi,

PixelFormat is owned by Surface but is missing a lifetime specifier (or any other reference to it's owner). Therefore, it's possible to write a use-after-free in purely safe Rust:

use anyhow::anyhow;

fn main() -> anyhow::Result<()> {
    sdl2::init().map_err(|e| anyhow!(e))?;

    let pfmt;
    {
        let surface =
            sdl2::surface::Surface::new(1024, 1024, sdl2::pixels::PixelFormatEnum::RGB888)
                .map_err(|e| anyhow!(e))?;
        pfmt = surface.pixel_format();
    }
    let penum = sdl2::pixels::PixelFormatEnum::from(pfmt);
    println!("Pixel Format: {:#?}", penum);

    Ok(())
}

My suggested fix would be to add a phantom lifetime to PixelFormat:

pub struct PixelFormat<'a> {
    raw: *mut sys::SDL_PixelFormat,
    marker: PhantomData<&'a Surface<'a>>
}

Kind Regards
Tim

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions