Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux dlopen: can a library be "notified" when it is loaded?

Is there a way for a shared library to be "notified" when it is loaded?

In other words, let's say I use dlopen on a shared library, is there a function that is automatically called (if present) on the shared library (e.g. main?)

like image 264
jldupont Avatar asked Oct 21 '09 17:10

jldupont


People also ask

How do you check if a shared library is loaded in Linux?

To find the list of processes and their loaded libraries, use "genld -ld" command. The -l option reports the lists of loaded objects for each process running on the system.

What library is Dlopen in?

dlopen() and dlclose() are present in glibc 2.0 and later.


2 Answers

Libraries should export initialization and cleanup routines using the gcc __attribute__((constructor)) and __attribute__((destructor)) function attributes. See the gcc info pages for information on these. Constructor routines are executed before dlopen returns (or before main() is started if the library is loaded at load time). Destructor routines are executed before dlclose returns (or after exit() or completion of main() if the library is loaded at load time). The C prototypes for these functions are:

 void __attribute__ ((constructor))  my_init(void);  
 void __attribute__  ((destructor)) my_fini(void);

Taken from http://tldp.org/HOWTO/Program-Library-HOWTO/index.html

THat is, you just tack on __attribute__ ((constructor)) to the functions you want to be called when the shared library is loaded. The above docuemtn also notes that the older _ini and _fini functions are considered obsolete.

like image 126
nos Avatar answered Oct 30 '22 09:10

nos


Yes. When a library is opened, all static construction takes place... so, if you use C++, you can do:

// mylibrary.cpp
namespace
{
    class dynamic_library_load_unload_handler
    {
         public:
              dynamic_library_load_unload_handler(){
                    // Code to execute when the library is loaded
              }
              ~dynamic_library_load_unload_handler(){
                    // Code to execute when the library is unloaded
              }
    } dynamic_library_load_unload_handler_hook;
}

Unlike the __attribute__ ((constructor)) solutions given, this will be portable. Note, though, that if you have multiple objects like this, there is no guarantee with respect to the construction/destruction order.

like image 17
Michael Aaron Safyan Avatar answered Oct 30 '22 10:10

Michael Aaron Safyan