Skip to content

atomic: Fix missing full memory barrier on GCC/Clang#15367

Open
cgutman wants to merge 1 commit intolibsdl-org:mainfrom
cgutman:atomic_set
Open

atomic: Fix missing full memory barrier on GCC/Clang#15367
cgutman wants to merge 1 commit intolibsdl-org:mainfrom
cgutman:atomic_set

Conversation

@cgutman
Copy link
Copy Markdown
Collaborator

@cgutman cgutman commented Apr 11, 2026

Description

__sync_lock_test_and_set() is designed for creating locks, not as a general atomic exchange function like we use it for in SDL_SetAtomicInt(), SDL_SetAtomicU32(), and SDL_SetAtomicPointer(). As a result, it only provides an acquire memory barrier and isn't guaranteed to actually store the provided value (though it does on architectures we care about).

__atomic_exchange_n() is supported on GCC/Clang for the last ~10 years, so let's use that instead if available. We will keep the __sync_lock_test_and_set() fallback around for ancient platforms, but add a full memory barrier to match the documented behavior.

I also removed the ancient #ifndef SDL_PLATFORM_ANDROID check since this is hopefully fixed in modern NDKs.

Existing Issue(s)

__sync_lock_test_and_set() is designed for creating locks, not as
a general atomic exchange function. As a result, it only provides
an acquire memory barrier and isn't guaranteed to actually store
the provided value (though it does on architectures we care about).

__atomic_exchange_n() is supported on GCC/Clang for the last ~10
years, so let's use that instead if available. We will keep the
__sync_lock_test_and_set() fallback around for ancient platforms,
but add a full memory barrier to match the documented behavior.
#ifndef SDL_PLATFORM_ANDROID
#define HAVE_ATOMIC_LOAD_N 1
#endif
#if __has_builtin(__atomic_exchange_n) || defined(HAVE_GCC_ATOMICS)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe use SDL_HAS_BUILTIN to be safe? (_SDL_HAS_BUILTIN for SDL2.)

Copy link
Copy Markdown
Collaborator Author

@cgutman cgutman Apr 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pulled this change (and the change to use __atomic_load() on Android) into #15374

@sezero sezero requested review from madebr and slouken April 12, 2026 12:21
@sezero
Copy link
Copy Markdown
Contributor

sezero commented Apr 12, 2026

If accepted, should probably be backported to SDL2.

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 this pull request may close these issues.

2 participants