Oracle Solaris Security for Developers Guide

Avoiding Data Cleanup Collisions in User-Level Providers

User-level libraries that plug into the cryptographic framework should supply a _fini() function. The _fini() function is called by the loader when the library is unloaded. The _fini() function is required to ensure that all cleanup is done correctly at the right time. Libraries that use libpkcs11 are not supposed to call C_Finalize(), because libpkcs11 is a shared library that could potentially be in use by the application.

To supply a _fini() function, you need to create a .fini section in the program data section of a relocatable object. The .fini section provides a runtime termination code block. See Linker and Libraries Guide. The following code sample demonstrates how to design a .fini section.

Example 8–1 Supplying _fini() to PKCS #11 Libraries

#pragma fini(pkcs11_fini)
static void pkcs11_fini();

/* [... (other library code omitted)] */

static void
        (void) pthread_mutex_lock(&pkcs11mutex);
        /* If CRYPTOKI is not initialized, do not clean up */
        if (!initialized) {
                (void) pthread_mutex_unlock(&pkcs11mutex);
        (void) finalize_routine(NULL_PTR);
        (void) pthread_mutex_unlock(&pkcs11mutex);