Friday, April 12, 2013

Initialization and Uninitialization functions in shared library

When writing a shared library, it is sometimes useful to have a set of functions that get called when the library is loaded and unloaded.

Windows:

In Windows, this is done by implementing the DllMain function. This function is called by the loader whenever a DLL is loaded or unloaded into the address space of a process (and also when the process creates a new thread). A value is passed in as an argument to the DllMain function that indicates which event is occurring: DLL load or unload.


 BOOL WINAPI DllMain(HINSTANCE hinstDLL,  // DLL module handle
    DWORD fdwReason,              // reason called
    LPVOID lpvReserved)           // reserved
{
    hinstDLL  = NULL ;
    lpvReserved  = NULL ;

    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
               break;
        case DLL_THREAD_ATTACH:
               break;
        case DLL_THREAD_DETACH:
              break ;
        case DLL_PROCESS_DETACH:
            break;
     }
    return TRUE;
}

Linux:

On Linux, one must use the GCC __attribute__((constructor)) and __attribute__((destructor)) keywords to explicitly declare functions to be called on load and unload. These keywords cause the compiler/linker to add the specified functions to the __CTOR_LIST__ and __DTOR_LIST__ (“ConstrucTOR LIST” and “DestrucTOR LIST” respectively) in the object file. Functions on the __CTOR_LIST__ are called by the loader when the library is loaded (either implicitly or by dlopen()). The main purpose for this list is to call the constructors on global objects in the library. Conversely, functions on the __DTOR_LIST__ are called when the library is unloaded (either implicitly or by dlclose()). By adding initialization and clean-up functions to this list, one can effectively replicate the DllMain functionality on Linux.

void __attribute__ ((constructor)) my_load(void);
void __attribute__ ((destructor)) my_unload(void);

// Called when the library is loaded and before dlopen() returns
void my_load(void)
{
    // Add initialization code…
}
// Called when the library is unloaded and before dlclose() returns
void my_unload(void)
{
    // Add clean-up code…
}

 
References:
  1. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583%28v=vs.85%29.aspx 

No comments:

Post a Comment