From 5437a75b155f57a30920c4ba75f4d90d460a9902 Mon Sep 17 00:00:00 2001 From: Janos Follath Date: Mon, 26 Sep 2016 09:15:44 +0100 Subject: [PATCH] Add safety check to sample mutex implementation Due to inconsistent freeing strategy in pkparse.c the sample mutex implementation in threading.c could lead to undefined behaviour by destroying the same mutex several times. This fix prevents mutexes from being destroyed several times in the sample threading implementation. --- ChangeLog | 2 ++ library/threading.c | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index 60383a97b..8090a70ac 100644 --- a/ChangeLog +++ b/ChangeLog @@ -29,6 +29,8 @@ Bugfix a contribution from Tobias Tangemann. #541 * Fixed cert_app sample program for debug output and for use when no root certificates are provided. + * Fixed default threading implementation to avoid accidental double + initialisations and double frees. Changes * Extended test coverage of special cases, and added new timing test suite. diff --git a/library/threading.c b/library/threading.c index 1b6d9cd44..83ec01a45 100644 --- a/library/threading.c +++ b/library/threading.c @@ -32,7 +32,7 @@ #if defined(MBEDTLS_THREADING_PTHREAD) static void threading_mutex_init_pthread( mbedtls_threading_mutex_t *mutex ) { - if( mutex == NULL ) + if( mutex == NULL || mutex->is_valid ) return; mutex->is_valid = pthread_mutex_init( &mutex->mutex, NULL ) == 0; @@ -40,10 +40,11 @@ static void threading_mutex_init_pthread( mbedtls_threading_mutex_t *mutex ) static void threading_mutex_free_pthread( mbedtls_threading_mutex_t *mutex ) { - if( mutex == NULL ) + if( mutex == NULL || !mutex->is_valid ) return; (void) pthread_mutex_destroy( &mutex->mutex ); + mutex->is_valid = 0; } static int threading_mutex_lock_pthread( mbedtls_threading_mutex_t *mutex )