From df2fd4ec065c3fdff7bf4137f3481efbfa7024c0 Mon Sep 17 00:00:00 2001 From: rizlik Date: Thu, 30 Apr 2026 17:02:41 +0200 Subject: [PATCH] swdev: refcount swdev Init/Cleanup --- tests/api.c | 4 +--- tests/swdev/swdev_loader.c | 26 +++++++++++++++----------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/tests/api.c b/tests/api.c index bd55810dc1..7530b58e51 100644 --- a/tests/api.c +++ b/tests/api.c @@ -40796,9 +40796,7 @@ TEST_CASE testCases[] = { static void TestSetup(void) { -#ifdef WOLFSSL_SWDEV - (void)wc_SwDev_Init(); -#endif +/* Stub, for now. Add common test setup code here. */ } static void TestCleanup(void) diff --git a/tests/swdev/swdev_loader.c b/tests/swdev/swdev_loader.c index a1af81db06..0abda7e084 100644 --- a/tests/swdev/swdev_loader.c +++ b/tests/swdev/swdev_loader.c @@ -11,13 +11,14 @@ /* resolved at link time from swdev.o */ extern int wc_SwDev_Callback(int devId, wc_CryptoInfo* info, void* ctx); -static int swdev_registered = 0; +/* Init always (re)registers because wolfCrypt_Cleanup wipes the cryptocb + * table; only the final Cleanup unregisters. */ +static wolfSSL_Atomic_Int swdev_refCount = WOLFSSL_ATOMIC_INITIALIZER(0); int wc_SwDev_Init(void) { int ret; - /* always re-register: cryptocb table is wiped by wolfCrypt_Cleanup */ ret = wc_CryptoCb_RegisterDevice(WC_SWDEV_ID, wc_SwDev_Callback, NULL); if (ret != 0) return ret; @@ -26,21 +27,24 @@ int wc_SwDev_Init(void) wc_CryptoCb_SetDeviceFindCb(wc_SwDev_FindCb); #endif - swdev_registered = 1; + (void)wolfSSL_Atomic_Int_FetchAdd(&swdev_refCount, 1); return 0; } void wc_SwDev_Cleanup(void) { - if (!swdev_registered) - return; + int my_refCount = wolfSSL_Atomic_Int_SubFetch(&swdev_refCount, 1); -#ifdef WOLF_CRYPTO_CB_FIND - wc_CryptoCb_SetDeviceFindCb(NULL); -#endif - - wc_CryptoCb_UnRegisterDevice(WC_SWDEV_ID); - swdev_registered = 0; + if (my_refCount == 0) { + #ifdef WOLF_CRYPTO_CB_FIND + wc_CryptoCb_SetDeviceFindCb(NULL); + #endif + wc_CryptoCb_UnRegisterDevice(WC_SWDEV_ID); + } + else if (my_refCount < 0) { + /* called more times than Init; restore floor */ + (void)wolfSSL_Atomic_Int_AddFetch(&swdev_refCount, 1); + } } #ifdef WOLF_CRYPTO_CB_FIND