replace a dynamic shared library in run time replace a dynamic shared library in run time c c

replace a dynamic shared library in run time


From "man dlclose":

The function dlclose() decrements the reference count on the dynamiclibrary handle handle.  If the reference count drops to zero andno other loaded libraries use symbols in it, then the dynamic libraryis unloaded.

I am guessing that you are running afoul of the "no other loaded libraries use symbols in it" part.

To debug, run your program with LD_DEBUG=bindings, and look for messages like:

binding file <some.so> [0] to libdynamicTest.so.1 [0]: normal symbol `<symbol>'

Update:

You have several bugs:

  1. You are linking test_agent against libdynamic.so.1 directly:
    cc -o test_agent -L. ...-ldl build/test_agent/hello.o libdynamic.so.1

    Once you've done this, you can no longer expect this library to be ever unloaded.

  2. By doing this:

    *((int *)handle) = 0;

    you are actually corrupting the state of the dynamic loader, and that causes subsequent dlsym to give you bogus address, which causes your SIGSEGV when you try to use it.

Once you fix problem #2, your program will no longer crash, though it will still not unload the library. To actually get the library to unload, you need to also fix problem #1.

If you fix problem #1 first, then problem #2 will no longer corrupt the dynamic loader. It will corrupt heap instead, and you can trivially observe that with Valgrind.


According to man 8 ld.so:

BUGS       Currently ld.so has no means of unloading and searching for com‐       patible or newer version of libraries.

I'm not 100% sure this is related, but it sounds like it may be.