Fix memory leak in test_suite_x509write with PSA crypto
The documentation of mbedtls_pk_wrap_as_opaque is quite clear:
* \param handle Output: a PSA key handle.
* It's the caller's responsibility to call
* psa_destroy_key() on that handle after calling
* mbedtls_pk_free() on the PK context.
But the test failed to call psa_destroy_key().
While at it, also use PSA_DONE(): it ensures that if we fail to destroy the
key, we'll get an explicit error message about it without the need for
valgrind.
This is a preliminary to adding a valgrind-based test for constant-flow code:
we need to make sure the rest of the tests are fully valgrind-clean, which
they weren't.
Signed-off-by: Manuel Pégourié-Gonnard <manuel.pegourie-gonnard@arm.com>
diff --git a/tests/suites/test_suite_x509write.function b/tests/suites/test_suite_x509write.function
index be9e0ae..b205b74 100644
--- a/tests/suites/test_suite_x509write.function
+++ b/tests/suites/test_suite_x509write.function
@@ -5,12 +5,20 @@
#include "mbedtls/pem.h"
#include "mbedtls/oid.h"
#include "mbedtls/rsa.h"
+
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#include "psa/crypto.h"
#include "mbedtls/psa_util.h"
+#include "test/psa_crypto_helpers.h"
+#define PSA_INIT( ) PSA_ASSERT( psa_crypto_init( ) )
+#else
+/* Define empty macros so that we can use them in the preamble and teardown
+ * of every test function that uses PSA conditionally based on
+ * MBEDTLS_USE_PSA_CRYPTO. */
+#define PSA_INIT( ) ( (void) 0 )
+#define PSA_DONE( ) ( (void) 0 )
#endif
-
#if defined(MBEDTLS_RSA_C)
int mbedtls_rsa_decrypt_func( void *ctx, int mode, size_t *olen,
const unsigned char *input, unsigned char *output,
@@ -156,7 +164,7 @@
const char *subject_name = "C=NL,O=PolarSSL,CN=PolarSSL Server 1";
mbedtls_test_rnd_pseudo_info rnd_info;
- psa_crypto_init();
+ PSA_INIT( );
memset( &rnd_info, 0x2a, sizeof( mbedtls_test_rnd_pseudo_info ) );
md_alg_psa = mbedtls_psa_translate_md( (mbedtls_md_type_t) md_type );
@@ -184,9 +192,12 @@
buf[pem_len] = '\0';
TEST_ASSERT( x509_crt_verifycsr( buf, pem_len + 1 ) == 0 );
+
exit:
mbedtls_x509write_csr_free( &req );
mbedtls_pk_free( &key );
+ psa_destroy_key( slot );
+ PSA_DONE( );
}
/* END_CASE */