From da8b1db793f4dd4d847a3bd7d8ed069cd70d7566 Mon Sep 17 00:00:00 2001 From: Gleb Popov <6yearold@gmail.com> Date: Sat, 20 Jan 2024 14:52:04 +0300 Subject: [PATCH] Fix mutex locking in _pkcs11h_threading_cond{Init,Wait} functions. According to pthread_cond_wait manpage, the mutex has to be locked by the same thread that is going to call pthread_cond_wait afterwards. This was not true before this change and was causing test-slotevent to busy-loop on FreeBSD. Sponsored by: Serenity Cybersecurity, LLC --- lib/pkcs11h-threading.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/pkcs11h-threading.c b/lib/pkcs11h-threading.c index cbba2f68..0124a9df 100644 --- a/lib/pkcs11h-threading.c +++ b/lib/pkcs11h-threading.c @@ -388,8 +388,7 @@ _pkcs11h_threading_condInit ( if ( ( pthread_mutex_init (&cond->mut, NULL) || - pthread_cond_init (&cond->cond, NULL) || - pthread_mutex_lock (&cond->mut) + pthread_cond_init (&cond->cond, NULL) ) ) { rv = CKR_FUNCTION_FAILED; @@ -423,7 +422,13 @@ _pkcs11h_threading_condWait ( goto cleanup; } #else + int unlock_mutex = 0; if (milli == PKCS11H_COND_INFINITE) { + if (pthread_mutex_lock (&cond->mut)) { + rv = CKR_FUNCTION_FAILED; + goto cleanup; + } + unlock_mutex = 1; if (pthread_cond_wait (&cond->cond, &cond->mut) ) { rv = CKR_FUNCTION_FAILED; goto cleanup; @@ -441,6 +446,11 @@ _pkcs11h_threading_condWait ( timeout.tv_sec = now.tv_sec + milli/1000; timeout.tv_nsec = now.tv_usec*1000 + milli%1000; + if (pthread_mutex_trylock (&cond->mut)) { + rv = CKR_FUNCTION_FAILED; + goto cleanup; + } + unlock_mutex = 1; if (pthread_cond_timedwait (&cond->cond, &cond->mut, &timeout)) { rv = CKR_FUNCTION_FAILED; goto cleanup; @@ -449,6 +459,9 @@ _pkcs11h_threading_condWait ( #endif rv = CKR_OK; cleanup: + if (unlock_mutex) { + pthread_mutex_unlock (&cond->mut); + } return rv; }