Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading and Unloading shared libraries in Mac OSX

I am sorry if this question has been repeated before in this forum. I am having a problem where, Loading and Unloading of dylibs arent working as expected in Mac(esp the unloading part.). The question is if I have an executable and if I load a shared library say A.dylib and then use the loaded shared library to load an library say B.dylib. When I try unloading the library B.dylib at a later stage, the there is no error code returned(the return int value is 0 - as I am using a regular dlopen and dlclose functions to load and unload libraries, 0 means unloaded successfully), but when I check to make sure using the activity monitor or lsof the b.dylib is still in the memory.

Now the we are porting this code for windows, linux & mac. Windows and Linux works as expected, but only mac is giving me problems.

I was reading in the mac developer library and found out that: " There are a couple of cases in which a dynamic library will never be unloaded: 1) the main executable links against it, 2) An API that does not supoort unloading (e.g. NSAddImage()) was used to load it or some other dynamic library that depends on it, 3) the dynamic library is in dyld's shared cache."

In my case I dont fall either of the first 2 cases. I am suspecting on case3.
Here is my question: 1. What can I do to make sure I have case 3? 2. If yes, how to fix it? 3. If not, how to fix it? 4. Why is mac so different?

Any help in this regard is appreciated!

Thanks, Jan

like image 816
jan Avatar asked Oct 06 '22 07:10

jan


1 Answers

When you load a shared library into an executable, all of the symbols exported by that library are candidates to resolve symbols required by the executable, causing the library to remain loaded if the DYLD linker binds to an unintended symbol. You can list the symbols in a shared library by using nm, and you can set environment variables to enable debugging output for the dynamic linker (see this man page on dyld). You need to set the DYLD_PRINT_BINDINGS environment variable.

Most likely, you need to limit the exported symbols to a specific subset that is used by the executable, so that only those symbols you intend to use are bound. This can be done by placing the required symbols in a file and passing it to the linker via the -exported_symbols_list option. Without doing so, you can end up binding a symbol in the dyloaded library, and it will not be unloaded since they are required to resolve a symbol in the executable and won't unload when dlclose() is called.

like image 65
Dennis Ward Avatar answered Oct 10 '22 03:10

Dennis Ward