Mutation, soundness, safety in FFI code

Hi there, I've been using sdl3-sys and writing some simple SDL3 wrappers. My current (WIP) code looks like this:

    let sdl_system = SDLSystem::new(&sdl_metadata)
        .map_err(|err| format!("Failed to create SDL system: {}", err))?;
    let sdl_window = SDLWindow::new(&sdl_system, &sdl_window_settings)
        .map_err(|err| format!("Failed to create SDL window: {}", err))?;
    let sdl_opengl = SDLOpenGL::new(&sdl_window)
        .map_err(|err| format!("Failed to create OpenGL context: {}", err))?;

With this for the SDLSystem code;


// Represents an initialized SDL and subsystems
pub struct SDLSystem;

impl SDLSystem {
    fn init_subsystems() -> Result<(), SDLError> {
        // SAFETY: Fixed input, no sharing
        let inited = unsafe { SDL_InitSubSystem(SDL_INIT_VIDEO) };
        SDLError::result_err(SDLErrorType::Init, inited)?;

        // SAFETY: Fixed input, no sharing
        let gl_loaded = unsafe { SDL_GL_LoadLibrary(std::ptr::null()) };
        SDLError::result_err(SDLErrorType::Init, gl_loaded)
    }

    fn set_metadata(key: &str, value: &str) -> Result<(), SDLError> {
        let key_cstr = CString::new(key).expect("CString::new failed");
        let value_cstr = CString::new(value).expect("CString::new failed");
        let key_ptr = key_cstr.as_ptr();
        let value_ptr = value_cstr.as_ptr();

        // SAFETY: Pointers are valid, SDL copies the values given
        let success = unsafe { SDL_SetAppMetadataProperty(key_ptr, value_ptr) };
        SDLError::result_err(SDLErrorType::Metadata, success)
    }

    pub fn new(metadata: &SDLMetadata) -> Result<SDLSystem, SDLError> {
        Self::set_metadata("SDL.app.metadata.name", &metadata.name)?;
        Self::set_metadata("SDL.app.metadata.version", &metadata.version)?;
        Self::set_metadata("SDL.app.metadata.identifier", &metadata.identifier)?;
        Self::set_metadata("SDL.app.metadata.creator", &metadata.creator)?;
        Self::set_metadata("SDL.app.metadata.copyright", &metadata.copyright)?;
        Self::set_metadata("SDL.app.metadata.url", &metadata.url)?;
        Self::set_metadata("SDL.app.metadata.type", "game")?;
        // TODO: Add openGL version
        Self::init_subsystems()?;
        Ok(SDLSystem {})
    }
}

and this for the SDLWindow:


pub struct SDLWindow<'a> {
    window: *mut SDL_Window,
    system_marker: PhantomData<&'a SDLSystem>,
}

impl<'a> SDLWindow<'a> {
    fn create_with_properties(
        _system: &'a SDLSystem,
        properties: SDLProperties<'a>,
    ) -> Result<SDLWindow<'a>, SDLError> {
        // SAFETY: Video subsystem is ready, properties is valid
        let window = unsafe { SDL_CreateWindowWithProperties(properties.id) };
        let success = !window.is_null();
        SDLError::result_err(SDLErrorType::Window, success)?;
        Ok(SDLWindow {
            window: window,
            system_marker: PhantomData,
        })
    }

    pub fn new(
        system: &'a SDLSystem,
        settings: &SDLWindowSettings,
    ) -> Result<SDLWindow<'a>, SDLError> {
        let mut properties = SDLProperties::new(&system)?;
        properties.set_string("SDL.window.create.title", &settings.title)?;
        properties.set_number("SDL.window.create.width", settings.width as i64)?;
        properties.set_number("SDL.window.create.height", settings.height as i64)?;
        properties.set_number("SDL.window.create.x", SDL_WINDOWPOS_CENTERED.into())?;
        properties.set_number("SDL.window.create.y", SDL_WINDOWPOS_CENTERED.into())?;
        properties.set_bool("SDL.window.create.opengl", true)?;
        properties.set_bool("SDL.window.create.resizable", true)?;
        Self::create_with_properties(system, properties)
    }
}

Things are going well so far (I've omitted some more of the messy details) but I do have a few questions about this.

The first is how I should enforce SDLSystem being a singleton. It's unsound to create another SDLSystem as it will drop before the other and invalidate all my references. I plan to just use a global variable and assert, but something with lifetimes sounds better. I was thinking of having SDLSystem be a mutable global object you borrow on success?

The second is that I think my idea of 'SAFETY' here is wrong. SAFETY is for memory safety, right? I'm writing a lot of invariants like 'Video subsystem is ready' which is more of a runtime safety check that lifetimes help me enforce. If the subsystem wasn't ready it would just generate an error.

The third is whether I should be using 'mut' for SDLSystem and friends. This wouldn't work very well at all because I need multiple references to different objects, which makes exclusivity not possible. So at the very least I'm modelling interior mutability.

But doesn't that kind of defeat some purposes of mutability? Even interior mutability? If it's possible to have SDLSystem change something, that's action at a distance.

I'm sorry for the somewhat silly questions but when there are terms thrown around like 'unsafe', 'unsound', 'memory safety', I find it hard to understand how it applies to code like this where yes I'm not doing anything memory unsafe (SDL might though), but I'm also side stepping what people might expect from an object being immutable.

Another question to throw in is that I want to make it impossible to use my structures across threads. I've seen this struct value in the sdl3 crate source:

marker: PhantomData<*mut ()>,

My understanding is that pointers automatically disable Send/Sync and PhantomData lets us have that for free at the type level. But why the mut?

Sorry for the barrage of questions.

The borrow checker does not have any mechanism to check borrows of global things. (This is why static mut items are unsafe to use.) You must have some sort of “global variable and assert”, though you can frame it in many ways; for example, this (overkill) way constructs the singleton value at compile time and only lets it be moved, not constructed, at run time:

use std::sync::Mutex;
pub struct System {/* private fields */}

static SYSTEM: Mutex<Option<System>> = Mutex::new(Some(System {/*...*/}));

pub fn get_system() -> System {
    SYSTEM
        .lock()
        .unwrap()
        .take()
        .expect("get_system must be called only once")
}

But given that what you actually need to do is (I assume) make a FFI call, this is a bit of a silly use of Rust ownership, which spends more resources than it needs to for no benefit. Practically, you should instead guard your constructor with an atomic boolean and that’s all.

I’m not familiar with SDL, but in general, if a library’s unsafe fns have documented preconditions for being called, then whatever those preconditions are, it is appropriate for you to write // SAFETY comments explaining how your call in fact meets those preconditions. However, it looks like you’re not doing that quite right; you should say how the conditions are ensured, not just that they are.

When interacting with resources outside the process, or data that is accessed from multiple threads, API-level[1] interior mutability is a fact of life. You should usually not make functions take &mut just to mark that mutation is happening. Think of &mut as a sort of “locking a mutex, but checked at compile time”: a function should only do it if it needs that assurance, or if doing so would improve the guarantees offered to the caller, not solely for documentation purposes.

Given that the pointee type is (), and this is in PhantomData and no pointer actually exists, the choice of *mut () vs. *const () makes no difference. But if you had an actual pointer pointing to data that might be mutated, it would be appropriate to use an *mut pointer rather than an *const pointer, so maybe that was their logic.


  1. as opposed to “this type has UnsafeCell inside it” ↩︎

Thank you so much for the response. I'll dwell on it. Regarding the SAFETY lines I knew I wasn't doing a good job on them. :sweat_smile: They are very handwavey.

For example this code:

        // SAFETY: Video subsystem is ready, properties is valid
        let window = unsafe { SDL_CreateWindowWithProperties(properties.id) };

I need to ensure:

  • This is on the 'main thread'
  • The video subsystem is inited
  • The properties are a valid value

Assuming that I make SDLSystem and friends not Send/Sync, that should ensure all the SDL code stays on one thread (the main thread).

So my argument is that:

  • Having access to SDLSystem guarantees we are on the main thread
  • Having access to SDLSystem guarantees the video subsystem is inited
  • Having access to a SDLProperties guarantees that the properties is valid

Would I put that in some kind of SAFETY note?

You can swap a static AtomicBool (that starts false) with true and panic if its true at the start of the function,
If it's called a second time it'll panic, if 2 threads call it at once one of them will panic (or both if a third call happened before).

If the only issue is drop invalidating other instances of it (in which case it isn't really a singleton), and having multiple SDLSystem's at once is sound (until they are dropped),
then you can use reference counting similar to Arc (using a static atomic) to skip drop code if another instance already exists,

just make sure to abort the process if the reference count would overflow, rust's arc had a soundness bug due to not doing that.

Assuming that I make SDLSystem and friends not Send/Sync, that should ensure all the SDL code stays on one thread (the main thread).

non-Send/Sync structs can still be constructed on other threads,
you need to also ensure that all constructors panic or return an error on other threads.
(unless SDL already does that)

Sorry for the barrage of questions.

The point of this category is to ask questions,
there's no need to apologize for doing so.

No, I would have to do that with the singleton. An atomic counter and panic seems like it would work well. Though I did see this code: Singletons - The Embedded Rust Book

struct Peripherals {
    serial: Option<SerialPort>,
}
impl Peripherals {
    fn take_serial(&mut self) -> SerialPort {
        let p = replace(&mut self.serial, None);
        p.unwrap()
    }
}
static mut PERIPHERALS: Peripherals = Peripherals {
    serial: Some(SerialPort),
};

This seems to assume replace is an atomic operation? I guess it's not intended for multiple threads. Can you just accidentally write a race like that if take_serial runs on two threads?


I did some looking at the sdl3 crate for reference.

  • The Sdl type in the crate is !Send and !Sync, so it can't be used by other threads
  • However you can create an EventPump using which implements Sync. My reading is this allows you to pass a reference across thread boundaries
  • I could then call pump_events which calls SDL_PumpEvents which is only allowed on the main thread

This reasoning seems wrong to me? Otherwise there's a bug here.


I also had a look at the code that makes sdl3 use a singleton. I won't link too much here, but:

  • It uses a thread-local IS_MAIN_THREAD and global a IS_MAIN_THREAD_DECLARED. Together both ensure you can only create an Sdl instance on the main thread
  • Reference counting is used to handle SDL_Init and SDL_Drop
  • Reference counting uses relaxed operations, which is a little confusing to me:

We have this code:

        // Initialize SDL.
        if SDL_COUNT.fetch_add(1, Ordering::Relaxed) == 0 {
            let result;

            unsafe {
                result = sys::init::SDL_Init(sys::init::SDL_InitFlags::default());
            }

            if !result {
                SDL_COUNT.store(0, Ordering::Relaxed);
                return Err(get_error());
            }
        }
impl Drop for SdlDrop {
    #[inline]
    #[doc(alias = "SDL_Quit")]
    fn drop(&mut self) {
        let prev_count = SDL_COUNT.fetch_sub(1, Ordering::Relaxed);
        assert!(prev_count > 0);
        if prev_count == 1 {
            unsafe {
                sys::init::SDL_Quit();
            }
            IS_MAIN_THREAD_DECLARED.store(false, Ordering::SeqCst);
        }
    }
}

This may be a bit nitpicking to me but if everything's on one thread, the atomic reference counting for SDL_COUNT shouldn't be needed should it? In general I see a lot of atomics being used in places that run on the same thread.

The only place I can see that allows cross-thread action is the EventPump which seems to be not correct?

pump_events requires &mut self, not &self. (T: Sync if and only if &T: Send: you can pass a shared reference (&T) across threads, not an exclusive reference (&mut T).)

There are a few methods that only need &self. I didn't look into them to see if they're problematic or not.

I see, the mut there makes sense. I'm glad I pointed that out to try to understand what went wrong. Is it common to use &mut self for thread safety? Is that something I would note in a // SAFETY section?

Thinking more about what Kevin said, thinking of mut as a lock makes a lot of sense in that situation.

Looking through EventPump seems like things are fine mostly. Though I found that you can call mouse_state which calls MouseState::new which calls SDL_GetMouseState. I don't see what would prevent this from causing issues? (If it's a bug I'll report it)

Regardless,

That does look like a bug to me.

I opened a bug report at KeyboardState, MouseState and RelativeMouseState can be called outside the main thread · Issue #485 · vhspace/sdl3-rs · GitHub . I now understand why Rust APIs are marked as stable a lot later in their life than what I would expect, because under a stable API this couldn't easily be fixed to make the states mutable or replace them with new objects/proxies or a new design.

SDL_GetKeyboardState is thread safe according to the docs.

Oh good catch!

Edit: I looked in to the SDL_GetKeyboardState function and it doesn't look thread-safe to me?

typedef struct SDL_Keyboard
{
    // Data common to all keyboards
    SDL_Window *focus;
    SDL_Keymod modstate;
    Uint8 keysource[SDL_SCANCODE_COUNT];
    bool keystate[SDL_SCANCODE_COUNT];
    SDL_Keymap *keymap;
    Uint32 keycode_options;
    bool autorelease_pending;
    Uint64 hardware_timestamp;
} SDL_Keyboard;

const bool *SDL_GetKeyboardState(int *numkeys)
{
    SDL_Keyboard *keyboard = &SDL_keyboard;

    if (numkeys) {
        *numkeys = SDL_SCANCODE_COUNT;
    }
    return keyboard->keystate;
}

static bool SDL_SendKeyboardKeyInternal(Uint64 timestamp, Uint32 flags, SDL_KeyboardID keyboardID, int rawcode, SDL_Scancode scancode, bool down)
{
...
        // Update internal keyboard state
        keyboard->keystate[scancode] = down;

I guess they assume this is an atomic operation in C?

(Written before your edit; we raced.)

I guess I should point out that I don't know if the docs are right about that, lol. Or if they are... perhaps the docs are incomplete.

In particular, it says

The pointer returned is a pointer to an internal SDL array. It will be valid for the whole lifetime of the application and should not be freed by the caller.

Which means reading the value on another thread would be a data race with SDL writing to it's internal array.

It might technically be thread safe to acquire the pointer, but unsound to dereference the pointer on another thread. Which is presumably what KeyboardState<'_> does, so probably it's still a bug in that library.

The pointer is to a static struct in C, so it will always return a value. But it assumes reads and writes to bools are atomic. So it's a potential race condition, but probably not big impact.

Edit: I didn't realize it's returning a pointer to keystate, I was focusing on how it writes to keystate.

Edit: I'm not even sure how you'd work with the application developer to synchronize reads here.

Edit 2: I opened a bug here: (link removed)

Edit 3: Is it safe Rust to wrap code that does unsafe things like this? Or are we responsible for all the things the function does?

I believe on all major ISAs aligned reads and writes up to pointer size are atomic in the "relaxed" sense of they won't tear, but not necessarily in the often more useful sense of "a read that sees a write from another thread will see other writes made earlier by that thread". x86 in particular is rather infamous for it's very strong by default memory ordering, though apparently ARM v8 closed the gap there?

But the real risk with UB isn't the hardware but the optimizer. For example with using non-atomics across threads it is likely to notice you aren't writing to a value being read from in a loop and hoist the read outside the loop, since it's not defined to write to it from another thread. Atomics are a combination of selecting appropriate instructions for the CPU and limiting optimizations by the compiler.

In this case, though, going through an FFI call is a pretty effective block on the optimizer, at least outside some pretty specific setups involving link time codegen that are probably pretty tough to get set up.

Still, best to avoid leaving the door open for the nasal demons!

(edit, noticed I managed three different flip-flops - sorry about that :sweat_smile:)

Alright, as an update the SDL authors have closed my bug as invalid. I guess my question here is, does knowingly wrapping buggy code like that make Rust code unsound or unsafe? Does memory safety only apply on Rust's side of things?

Edit: I removed the link to the bug report, if anyone's considering it please don't go bother the SDL devs about this. This thread is intended for me to try and learn things and I don't want it to get too off topic, only learn more things.

There will be a problem if your wrapper library is included twice as a dependency (at different versions); as they cannot know about each other, the obligation of uniqueness should be on programmer, and thus your constructor must still be unsafe.

Or export a symbol that will collide at linking different copies of the lib into the executable, with #[unsafe(link_name=...)].

One view of the borrow checker is that it enforces, at compile time, RwLock-like semantics. In this view, &mut T equates to having a compile-time check that you own the equivalent of a write lock on the T, and &T maps to equates to having a compile-time check that you own the equivalent of a read lock read lock on the T. If you have a T itself, you can create an &T or &mut T, so you own the lock until such time as you create a borrow.

The RwLock does not, of course, exist - you're just looking at a compile time check of equivalent strength. As a result, however, if you take &mut T, you know that you have exclusive access to the underlying T - it might be a result of putting the underlying T behind an RwLock or a Mutex and taking the lock, or it might be a simple matter of control flow such that no other thread can possibly have access to the T.

Your // SAFETY comment might well refer to this - "we have exclusive access to foo" or similar.

Interesting, I didn't think about how my code could be included twice. This isn't going in a library but I had assumed you could only have one version of a library at a time. Is the unsafe link_name guaranteed to help with this or is it just an implementation detail? Is there anywhere I could read more about this problem?