Use file static variables in WEBP_DSP_INIT_FUNC()

Function static variables are initialized on the first call to the
function. In C the initialization of function static variables is not
thread-safe. Use file static variables instead in the
WEBP_DSP_INIT_FUNC() macro.

Remove the volatile qualifier for the pthread version of the
func##_last_cpuinfo_used variable because the variable is only accessed
while holding the mutex.

Change-Id: I1237904a49d2467d7ce79fc53f9e7f966aa7a5c1
This commit is contained in:
Wan-Teh Chang
2025-08-01 19:07:41 -07:00
parent 484991ce3f
commit 313692d51e

View File

@@ -193,23 +193,25 @@
#include <pthread.h> // NOLINT #include <pthread.h> // NOLINT
// clang-format off // clang-format off
#define WEBP_DSP_INIT(func) \ #define WEBP_DSP_INIT_VARS(func) \
do { \ static VP8CPUInfo func##_last_cpuinfo_used = \
static volatile VP8CPUInfo func##_last_cpuinfo_used = \ (VP8CPUInfo)&func##_last_cpuinfo_used; \
(VP8CPUInfo)&func##_last_cpuinfo_used; \ static pthread_mutex_t func##_lock = PTHREAD_MUTEX_INITIALIZER
static pthread_mutex_t func##_lock = PTHREAD_MUTEX_INITIALIZER; \ #define WEBP_DSP_INIT(func) \
if (pthread_mutex_lock(&func##_lock)) break; \ do { \
if (func##_last_cpuinfo_used != VP8GetCPUInfo) func(); \ if (pthread_mutex_lock(&func##_lock)) break; \
func##_last_cpuinfo_used = VP8GetCPUInfo; \ if (func##_last_cpuinfo_used != VP8GetCPUInfo) func(); \
(void)pthread_mutex_unlock(&func##_lock); \ func##_last_cpuinfo_used = VP8GetCPUInfo; \
(void)pthread_mutex_unlock(&func##_lock); \
} while (0) } while (0)
// clang-format on // clang-format on
#else // !(defined(WEBP_USE_THREAD) && !defined(_WIN32)) #else // !(defined(WEBP_USE_THREAD) && !defined(_WIN32))
// clang-format off // clang-format off
#define WEBP_DSP_INIT_VARS(func) \
static volatile VP8CPUInfo func##_last_cpuinfo_used = \
(VP8CPUInfo)&func##_last_cpuinfo_used
#define WEBP_DSP_INIT(func) \ #define WEBP_DSP_INIT(func) \
do { \ do { \
static volatile VP8CPUInfo func##_last_cpuinfo_used = \
(VP8CPUInfo)&func##_last_cpuinfo_used; \
if (func##_last_cpuinfo_used == VP8GetCPUInfo) break; \ if (func##_last_cpuinfo_used == VP8GetCPUInfo) break; \
func(); \ func(); \
func##_last_cpuinfo_used = VP8GetCPUInfo; \ func##_last_cpuinfo_used = VP8GetCPUInfo; \
@@ -225,6 +227,7 @@
} }
*/ */
#define WEBP_DSP_INIT_FUNC(name) \ #define WEBP_DSP_INIT_FUNC(name) \
WEBP_DSP_INIT_VARS(name##_body); \
static WEBP_TSAN_IGNORE_FUNCTION void name##_body(void); \ static WEBP_TSAN_IGNORE_FUNCTION void name##_body(void); \
WEBP_TSAN_IGNORE_FUNCTION void name(void) { WEBP_DSP_INIT(name##_body); } \ WEBP_TSAN_IGNORE_FUNCTION void name(void) { WEBP_DSP_INIT(name##_body); } \
static WEBP_TSAN_IGNORE_FUNCTION void name##_body(void) static WEBP_TSAN_IGNORE_FUNCTION void name##_body(void)