@@ -75,6 +75,8 @@ struct util_ctx_st {
7575
7676};
7777
78+ static int g_shutdown_mode = 0 ;
79+
7880/******************************************************************************/
7981/* Initialization */
8082/******************************************************************************/
@@ -139,8 +141,19 @@ static int util_ctx_enumerate_slots_unlocked(UTIL_CTX *ctx)
139141 return 1 ;
140142}
141143
142- /* Initialize libp11 data: ctx->pkcs11_ctx and ctx->slot_list */
144+ /*
145+ * PKCS#11 modules that register their own atexit() callbacks may already have
146+ * been cleaned up by the time OpenSSL's atexit() callback is executed.
147+ * As a result, a crash occurs with certain versions of OpenSSL and SoftHSM2.
148+ * The workaround skips libp11 cleanup during OpenSSL's cleanup, converting
149+ * the crash into a harmless memory leak at exit.
150+ */
151+ static void exit_callback (void )
152+ {
153+ g_shutdown_mode = 1 ;
154+ }
143155
156+ /* Initialize libp11 data: ctx->pkcs11_ctx and ctx->slot_list */
144157static int util_ctx_init_libp11 (UTIL_CTX * ctx )
145158{
146159 if (ctx -> pkcs11_ctx && ctx -> slot_list && ctx -> slot_count > 0 )
@@ -163,6 +176,7 @@ static int util_ctx_init_libp11(UTIL_CTX *ctx)
163176 UTIL_CTX_free_libp11 (ctx );
164177 return -1 ;
165178 }
179+ atexit (exit_callback );
166180 return 0 ;
167181}
168182
@@ -182,14 +196,17 @@ int UTIL_CTX_enumerate_slots(UTIL_CTX *ctx)
182196void UTIL_CTX_free_libp11 (UTIL_CTX * ctx )
183197{
184198 if (ctx -> slot_list ) {
185- PKCS11_release_all_slots (ctx -> pkcs11_ctx ,
186- ctx -> slot_list , ctx -> slot_count );
199+ if (!g_shutdown_mode )
200+ PKCS11_release_all_slots (ctx -> pkcs11_ctx ,
201+ ctx -> slot_list , ctx -> slot_count );
187202 ctx -> slot_list = NULL ;
188203 ctx -> slot_count = 0 ;
189204 }
190205 if (ctx -> pkcs11_ctx ) {
191- PKCS11_CTX_unload (ctx -> pkcs11_ctx );
192- PKCS11_CTX_free (ctx -> pkcs11_ctx );
206+ if (!g_shutdown_mode ) {
207+ PKCS11_CTX_unload (ctx -> pkcs11_ctx );
208+ PKCS11_CTX_free (ctx -> pkcs11_ctx );
209+ }
193210 ctx -> pkcs11_ctx = NULL ;
194211 }
195212}
0 commit comments