From 6a7c3df4d521716a014b11e9e7462e13184096f1 Mon Sep 17 00:00:00 2001 From: Mounir IDRASSI Date: Fri, 15 May 2026 18:49:26 +0900 Subject: [PATCH] win32: make compile lock initialization thread-safe Use interlocked state transitions around the lazily initialized Windows CRITICAL_SECTION so concurrent first-time callers cannot race into a double initialization. --- tcc.h | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tcc.h b/tcc.h index 63881991..24713356 100644 --- a/tcc.h +++ b/tcc.h @@ -1918,10 +1918,15 @@ dwarf_read_sleb128(unsigned char **ln, unsigned char *end) /********************************************************/ #if CONFIG_TCC_SEMLOCK #if defined _WIN32 -typedef struct { int init; CRITICAL_SECTION cs; } TCCSem; +typedef struct { volatile LONG init; CRITICAL_SECTION cs; } TCCSem; static inline void wait_sem(TCCSem *p) { - if (!p->init) - InitializeCriticalSection(&p->cs), p->init = 1; + if (InterlockedCompareExchange(&p->init, 1, 0) == 0) { + InitializeCriticalSection(&p->cs); + InterlockedExchange(&p->init, 2); + } else { + while (InterlockedCompareExchange(&p->init, 2, 2) != 2) + Sleep(0); + } EnterCriticalSection(&p->cs); } static inline void post_sem(TCCSem *p) {