From df7fa52b7b5c5464602606403dd6e6ac1eba03ed Mon Sep 17 00:00:00 2001 From: Saleem Abdulrasool Date: Tue, 23 May 2023 14:07:43 -0700 Subject: [PATCH] shims: fix a subtle bug in semaphore initialisation on Windows This function is the initializer for the semaphore. The seamphore storage itself may be stack allocated (or heap allocated) but without guarantee of 0-initialisation. As a result, the subsequent CAS for the atomic replacement will fail silently, leaving the previously non-zero value in place, indicating that the value is a valid handle. This would fail randomly and would ultimately result in a crash in the `CloseHandle` call associated with the clean up. This issue was identified by SwiftLint on Windows. --- src/shims/lock.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/shims/lock.c b/src/shims/lock.c index 62fa6f385..88fb8f8b6 100644 --- a/src/shims/lock.c +++ b/src/shims/lock.c @@ -266,6 +266,7 @@ void _dispatch_sema4_init(_dispatch_sema4_t *sema, int policy DISPATCH_UNUSED) // lazily allocate the semaphore port + os_atomic_cmpxchg(sema, *sema, 0, relaxed); while (!dispatch_assume(tmp = CreateSemaphore(NULL, 0, LONG_MAX, NULL))) { _dispatch_temporary_resource_shortage(); }