Skip to content

Commit fc68137

Browse files
committed
wolfcrypt/src/wc_port.c:
* fixes for readability-implicit-bool-conversion in wolfSSL_Atomic_Ptr_CompareExchange(). * refactor initRefCount as a wolfSSL_Atomic_Int, unless !WOLFSSL_ATOMIC_OPS, for thread safety.
1 parent e0db992 commit fc68137

1 file changed

Lines changed: 31 additions & 11 deletions

File tree

wolfcrypt/src/wc_port.c

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,11 @@
151151
#endif
152152

153153
/* prevent multiple mutex initializations */
154-
static volatile int initRefCount = 0;
154+
#ifdef WOLFSSL_ATOMIC_OPS
155+
wolfSSL_Atomic_Int initRefCount = WOLFSSL_ATOMIC_INITIALIZER(0);
156+
#else
157+
static int initRefCount = 0;
158+
#endif
155159

156160
#if defined(__aarch64__) && defined(WOLFSSL_ARMASM_BARRIER_DETECT)
157161
int aarch64_use_sb = 0;
@@ -164,7 +168,8 @@ WOLFSSL_ABI
164168
int wolfCrypt_Init(void)
165169
{
166170
int ret = 0;
167-
if (initRefCount == 0) {
171+
int my_initRefCount = wolfSSL_Atomic_Int_FetchAdd(&initRefCount, 1);
172+
if (my_initRefCount == 0) {
168173
WOLFSSL_ENTER("wolfCrypt_Init");
169174

170175
#if defined(__aarch64__) && defined(WOLFSSL_ARMASM_BARRIER_DETECT)
@@ -444,8 +449,16 @@ int wolfCrypt_Init(void)
444449
return ret;
445450
}
446451
#endif
452+
453+
/* increment to 2, to signify successful initialization: */
454+
(void)wolfSSL_Atomic_Int_FetchAdd(&initRefCount, 1);
455+
}
456+
else {
457+
if (my_initRefCount < 2) {
458+
(void)wolfSSL_Atomic_Int_FetchSub(&initRefCount, 1);
459+
ret = BUSY_E;
460+
}
447461
}
448-
initRefCount++;
449462

450463
return ret;
451464
}
@@ -469,12 +482,9 @@ WOLFSSL_ABI
469482
int wolfCrypt_Cleanup(void)
470483
{
471484
int ret = 0;
485+
int my_initRefCount = wolfSSL_Atomic_Int_SubFetch(&initRefCount, 1);
472486

473-
initRefCount--;
474-
if (initRefCount < 0)
475-
initRefCount = 0;
476-
477-
if (initRefCount == 0) {
487+
if (my_initRefCount == 1) {
478488
WOLFSSL_ENTER("wolfCrypt_Cleanup");
479489

480490
#ifdef HAVE_ECC
@@ -564,6 +574,8 @@ int wolfCrypt_Cleanup(void)
564574
* must be freed. */
565575
wc_MemZero_Free();
566576
#endif
577+
578+
(void)wolfSSL_Atomic_Int_SubFetch(&initRefCount, 1);
567579
}
568580

569581
#if defined(HAVE_LIBOQS)
@@ -1462,9 +1474,17 @@ int wolfSSL_Atomic_Ptr_CompareExchange(
14621474
* atomic_compare_exchange_strong_explicit(), to sidestep _Atomic type
14631475
* requirements.
14641476
*/
1465-
return __atomic_compare_exchange_n(
1466-
c, expected_ptr, new_ptr, 0 /* weak */,
1467-
__ATOMIC_SEQ_CST, __ATOMIC_ACQUIRE);
1477+
if (__atomic_compare_exchange_n(
1478+
c, expected_ptr, new_ptr,
1479+
#ifdef WOLF_C89
1480+
0 /* weak */,
1481+
#else
1482+
(_Bool)0 /* weak */,
1483+
#endif
1484+
__ATOMIC_SEQ_CST, __ATOMIC_ACQUIRE))
1485+
return 1;
1486+
else
1487+
return 0;
14681488
}
14691489

14701490
#elif defined(__GNUC__) && defined(__ATOMIC_RELAXED)

0 commit comments

Comments
 (0)