Skip to content

Publicly exporting SdlDrop is unsafe #1247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
daggerbot opened this issue Aug 20, 2022 · 1 comment · Fixed by #1254
Closed

Publicly exporting SdlDrop is unsafe #1247

daggerbot opened this issue Aug 20, 2022 · 1 comment · Fixed by #1254

Comments

@daggerbot
Copy link
Contributor

daggerbot commented Aug 20, 2022

SdlDrop is hidden from documentation but is still publicly exported. It can be used to call SDL_Quit in safe code, causing undefined behavior when using objects that are expected to still be valid. Example:

{
    let _ = sdl2::SdlDrop;
} // Invokes SDL_Quit

To fix this, I recommend changing the visibility of SdlDrop to pub(crate). If it's intended to be used by outside crates like other SDL extension bindings, then I'd recommend protecting SdlDrop behind the IS_SDL_CONTEXT_ALIVE flag instead of Sdl. If any of these changes are desired, I'll open a pull request.

@Cobrand
Copy link
Member

Cobrand commented Aug 23, 2022

I think it's intended to be pub for other modules, (it was probably used when sdl2-ttf, sdl2-image and so on were in separate repositories).

I think we can do better than that though for a fix.

The current solution in the repository uses an atomic boolean and an Rc<_> to decrease a count, when it reaches 0 SDL is destroyed with a SdlDrop. But since rust 1.34.0 we have Atomic integers.

Instead of having an Rc<SdlDrop>, we could have a SdlDrop, which on creation would increase the counter by one, and on Drop decrease it by one. Once the counter reaches 0, call SDL_Quit.

Since it might be used by other libraries, we need to keep SdlDrop public. But we could make it impossible to build without a ref to &Sdl. Like pub struct SdlDrop { _anticonstructor: () }, and like in the actual code it could only be created via sdl.sdldrop().

That way no matter how many SdlDrop structs are created, it will always be safe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants