2121#include <string.h>
2222
2323/* Global number of active PKCS11_CTX objects */
24- int pkcs11_global_data_refs = 0 ;
24+ static int pkcs11_global_data_refs = 0 ;
25+
26+ /*
27+ * Free global ex_data indexes and methods
28+ */
29+ static void libp11_global_free ()
30+ {
31+ #ifndef OPENSSL_NO_RSA
32+ pkcs11_rsa_method_free ();
33+ #endif
34+ #if OPENSSL_VERSION_NUMBER >= 0x10100002L
35+ #ifndef OPENSSL_NO_EC
36+ pkcs11_ec_key_method_free ();
37+ # if OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L
38+ pkcs11_ed_key_method_free ();
39+ # endif /* OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L */
40+ #endif /* OPENSSL_NO_EC */
41+ #else /* OPENSSL_VERSION_NUMBER */
42+ #ifndef OPENSSL_NO_ECDSA
43+ pkcs11_ecdsa_method_free ();
44+ #endif /* OPENSSL_NO_ECDSA */
45+ #ifndef OPENSSL_NO_ECDH
46+ pkcs11_ecdh_method_free ();
47+ #endif /* OPENSSL_NO_ECDH */
48+ # if OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L
49+ pkcs11_rsa_key_method_free ();
50+ # endif /* OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L */
51+ #endif /* OPENSSL_VERSION_NUMBER */
52+ }
53+
54+ /*
55+ * Free global data if some PKCS11_CTX objects were not freed by the user
56+ */
57+ static void libp11_atexit ()
58+ {
59+ if (pkcs11_global_data_refs > 0 ) {
60+ pkcs11_global_data_refs = 0 ;
61+ libp11_global_free ();
62+ }
63+ }
2564
2665/*
2766 * Create a new context
@@ -46,7 +85,8 @@ PKCS11_CTX *pkcs11_CTX_new(void)
4685 cpriv -> forkid = get_forkid ();
4786 pthread_mutex_init (& cpriv -> fork_lock , 0 );
4887
49- pkcs11_global_data_refs ++ ;
88+ if (pkcs11_global_data_refs ++ == 0 )
89+ atexit (libp11_atexit );
5090
5191 return ctx ;
5292fail :
@@ -177,28 +217,8 @@ void pkcs11_CTX_free(PKCS11_CTX *ctx)
177217 OPENSSL_free (ctx -> _private );
178218 OPENSSL_free (ctx );
179219
180- pkcs11_global_data_refs -- ;
181- #ifndef OPENSSL_NO_RSA
182- pkcs11_rsa_method_free ();
183- #endif
184- #if OPENSSL_VERSION_NUMBER >= 0x10100002L
185- #ifndef OPENSSL_NO_EC
186- pkcs11_ec_key_method_free ();
187- # if OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L
188- pkcs11_ed_key_method_free ();
189- # endif /* OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L */
190- #endif /* OPENSSL_NO_EC */
191- #else /* OPENSSL_VERSION_NUMBER */
192- #ifndef OPENSSL_NO_ECDSA
193- pkcs11_ecdsa_method_free ();
194- #endif /* OPENSSL_NO_ECDSA */
195- #ifndef OPENSSL_NO_ECDH
196- pkcs11_ecdh_method_free ();
197- #endif /* OPENSSL_NO_ECDH */
198- # if OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L
199- pkcs11_rsa_key_method_free ();
200- # endif /* OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L */
201- #endif /* OPENSSL_VERSION_NUMBER */
220+ if (-- pkcs11_global_data_refs == 0 )
221+ libp11_global_free ();
202222}
203223
204224/* vim: set noexpandtab: */
0 commit comments