Debian Codegraph @

crt/aws-c-common/source/windows/mutex.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/common/mutex.h>
7 #include <aws/common/thread.h>
8
9 #include <windows.h>
10
11 /* Convert a string from a macro to a wide string */
12 #define WIDEN2(s) L## #s
13 #define WIDEN(s) WIDEN2(s)
14
15 int aws_mutex_init(struct aws_mutex *mutex) {
16 /* Ensure our mutex and Windows' mutex are the same size */
17 AWS_STATIC_ASSERT(sizeof(SRWLOCK) == sizeof(mutex->mutex_handle));
18
19 InitializeSRWLock(AWSMUTEX_TO_WINDOWS(mutex));
20 mutex->initialized = true;
21 return AWS_OP_SUCCESS;
22 }
23
24 /* turn off unused named parameter warning on msvc.*/
25 #ifdef _MSC_VER
26 # pragma warning(push)
27 # pragma warning(disable : 4100)
28 #endif
29
30 void aws_mutex_clean_up(struct aws_mutex *mutex) {
31 AWS_PRECONDITION(mutex);
32 AWS_ZERO_STRUCT(*mutex);
33 }
34
35 int aws_mutex_lock(struct aws_mutex *mutex) {
36 AWS_PRECONDITION(mutex && mutex->initialized);
37 AcquireSRWLockExclusive(AWSMUTEX_TO_WINDOWS(mutex));
38 return AWS_OP_SUCCESS;
39 }
40 /* Check for functions that don't exist on ancient windows */
41 static aws_thread_once s_check_functions_once = INIT_ONCE_STATIC_INIT;
42
43 typedef BOOLEAN WINAPI TryAcquireSRWLockExclusive_fn(PSRWLOCK SRWLock);
44 static TryAcquireSRWLockExclusive_fn *s_TryAcquireSRWLockExclusive;
45
46 static void s_check_try_lock_function(void *user_data) {
47 (void)user_data;
48
49 s_TryAcquireSRWLockExclusive = (TryAcquireSRWLockExclusive_fn *)GetProcAddress(
50 GetModuleHandleW(WIDEN(WINDOWS_KERNEL_LIB) L".dll"), "TryAcquireSRWLockExclusive");
51 }
52
53 int aws_mutex_try_lock(struct aws_mutex *mutex) {
54 AWS_PRECONDITION(mutex && mutex->initialized);
55 /* Check for functions that don't exist on ancient Windows */
56 aws_thread_call_once(&s_check_functions_once, s_check_try_lock_function, NULL);
57
58 if (!s_TryAcquireSRWLockExclusive) {
59 return aws_raise_error(AWS_ERROR_UNSUPPORTED_OPERATION);
60 }
61 BOOL res = s_TryAcquireSRWLockExclusive(AWSMUTEX_TO_WINDOWS(mutex));
62 /*
63 * Per Windows documentation, a return value of zero indicates a failure to acquire the lock.
64 */
65 if (!res) {
66 return aws_raise_error(AWS_ERROR_MUTEX_TIMEOUT);
67 }
68
69 return AWS_OP_SUCCESS;
70 }
71
72 int aws_mutex_unlock(struct aws_mutex *mutex) {
73 AWS_PRECONDITION(mutex && mutex->initialized);
74 ReleaseSRWLockExclusive(AWSMUTEX_TO_WINDOWS(mutex));
75 return AWS_OP_SUCCESS;
76 }
77
78 #ifdef _MSC_VER
79 # pragma warning(pop)
80 #endif