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 )
157161int aarch64_use_sb = 0 ;
@@ -164,7 +168,8 @@ WOLFSSL_ABI
164168int 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
469482int 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,11 +574,18 @@ int wolfCrypt_Cleanup(void)
564574 * must be freed. */
565575 wc_MemZero_Free ();
566576 #endif
567- }
577+
578+ (void )wolfSSL_Atomic_Int_SubFetch (& initRefCount , 1 );
568579
569580#if defined(HAVE_LIBOQS )
570- wolfSSL_liboqsClose ();
581+ wolfSSL_liboqsClose ();
571582#endif
583+ }
584+ else if (my_initRefCount < 0 ) {
585+ (void )wolfSSL_Atomic_Int_AddFetch (& initRefCount , 1 );
586+ WOLFSSL_MSG ("wolfCrypt_Cleanup() called with initRefCount <= 0." );
587+ ret = ALREADY_E ;
588+ }
572589
573590 return ret ;
574591}
@@ -1462,9 +1479,17 @@ int wolfSSL_Atomic_Ptr_CompareExchange(
14621479 * atomic_compare_exchange_strong_explicit(), to sidestep _Atomic type
14631480 * requirements.
14641481 */
1465- return __atomic_compare_exchange_n (
1466- c , expected_ptr , new_ptr , 0 /* weak */ ,
1467- __ATOMIC_SEQ_CST , __ATOMIC_ACQUIRE );
1482+ if (__atomic_compare_exchange_n (
1483+ c , expected_ptr , new_ptr ,
1484+ #ifdef WOLF_C89
1485+ 0 /* weak */ ,
1486+ #else
1487+ (_Bool )0 /* weak */ ,
1488+ #endif
1489+ __ATOMIC_SEQ_CST , __ATOMIC_ACQUIRE ))
1490+ return 1 ;
1491+ else
1492+ return 0 ;
14681493}
14691494
14701495#elif defined(__GNUC__ ) && defined(__ATOMIC_RELAXED )
0 commit comments