'how can shared library get its own base address

I have the offset address's of all symbols (obtained with libelf executing on its own binary .so). Now, at runtime, I would need to calculate the absolutue address's of all those symbols and for that I would need to get the base address (where the shared library is loaded) and do a calculation:

symbol_address = base_address + symbol_offset

How can a shared lib get its own base address? On Windows I would use the parameter passed to DllMain, is there some equivalent in linux?



Solution 1:[1]

This is an old question, but still relevant.

I found this example code from ubuntu to be very useful. It will print all your shared libraries and their segments.

http://manpages.ubuntu.com/manpages/bionic/man3/dl_iterate_phdr.3.html

Solution 2:[2]

After some research I managed to find out the method of discovering the address of the library loading by its descriptor, which is returned by the dlopen() function. It is performed with the help of such macro:

#define  LIBRARY_ADDRESS_BY_HANDLE(dlhandle) ((NULL == dlhandle) ? NULL :  (void*)*(size_t const*)(dlhandle))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 randoms
Solution 2 shoumikhin