Fix unprotected access in refcount_context_num_refs

This commit is contained in:
2025-09-08 17:59:50 -07:00
parent b18b59eeb0
commit 52008a0110
2 changed files with 14 additions and 7 deletions

View File

@ -3,10 +3,4 @@
#cmakedefine REFCOUNT_HAS_THREADS
#if defined(REFCOUNT_HAS_THREADS) \
&& (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112L)
# error \
"RefCount needs to be compiled with at least C11 for thread support to work."
#endif
#endif

View File

@ -162,8 +162,21 @@ static inline bool refcount_context_is_static(const RefcountContext *ctx,
*/
static inline uint64_t refcount_context_num_refs(const RefcountContext *ctx,
void *obj) {
#ifdef REFCOUNT_HAS_THREADS
if (!mtx_lock(&REFCOUNT_OBJECT_ENTRY(ctx, obj)->weak_ref->mtx)) {
// just try our best to estimate, if we are on a platform where 64bit
// stores are not atomic (or this is not aligned properly), this might
// race and give a bogus number
return REFCOUNT_OBJECT_ENTRY(ctx, obj)->impl.counted.ref_count;
}
#endif
const uint64_t count =
REFCOUNT_OBJECT_ENTRY(ctx, obj)->impl.counted.ref_count;
#ifdef REFCOUNT_HAS_THREADS
mtx_unlock(&REFCOUNT_OBJECT_ENTRY(ctx, obj)->weak_ref->mtx);
#endif
return count;
}
bool refcount_context_init_obj(const RefcountContext *ctx, void *obj);