Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to the thread spawned by a shared library, upon dlclose

This is the scenario:

I have an application (main.exe) which dynamically loads a library libA.so using dlopen(). libA.so has dependency on another library libB.so.

Now libB.so has a constructor that spawns a thread (in detached state) and blocks on reading from a named pipe.

What happens to the thread , when libA.so is unloaded using dlclose() - (i assume this will unload libB.so as well)?.

I get segmentation fault in the thread after the dlclose(libA.so).

Pseudo code:

main.c (main.exe):

handle = dlopen(libA.so)
// function calls
dlclose(handle)

libA.so depends on libB.so

b.c (libB.so):

__attribute_constructor__void start() {
    pthread_create(ThreadFunction)

void ThreadFunction() {
    while(1) {
    fd = open("path_to_pipe", READONLY)
    read(fd, buffer, size)
    //Process the content
    }
like image 991
MSK Avatar asked Oct 29 '25 13:10

MSK


1 Answers

Unloading a shared library which is still in use is Undefined Behaviour. Calling dlclose() on a handle is a declaration that neither the functions nor the data objects provided through that handle are still required.

There is no way for dlclose() to verify this fact. If you still have a pointer to a function or data object in the loadable module, those pointers become invalid and may not be used. If there is a pointer into a loaded function on the call stack of any thread -- which will be the case if the thread is waiting on a file descriptor -- then that thread may not return into that call frame. (Longjmp to a prior frame might work, if the stack can be unwound without reference to the unloaded module. That will likely work in C, but throwing a C++ exception to escape from an unloaded function is likely to fail.

like image 82
rici Avatar answered Nov 01 '25 12:11

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!