Making a clone'd thread pthread compatible

Viewed 88

I am programming in C on Linux x86-64. I'm using a library which creates a number of threads via a raw clone system call rather than using pthread_create. These threads run low-level code internal to the library.

I would like to hook one of these threads to introspect its behavior. Hooking the code is easy enough, but I've discovered that I can't call almost anything in libc because the thread state is not configured. pthread_create normally inserts a bunch of data into the thread-local storage area indexed by fs:. Some of that data, for example, is essential to libc's function, such as the function pointer encryption key (pointer_guard) and locale pointer.

So my question is: can I upgrade a clone'd thread to a full pthread via any mechanism? If not, is there any way that I can call C functions from a clone'd thread (such as printf, toupper, etc. which require libc's thread-local data)?

1 Answers

Some of that data, for example, is essential to libc's function, such as the function pointer encryption key (pointer_guard) and locale pointer.

Correct. Don't forget about errno, which is also in there.

can I upgrade a clone'd thread to a full pthread via any mechanism?

No.

is there any way that I can call C functions from a clone'd thread

No.

If you have sources to the library, it should be relatively easy to replace direct clone calls with pthread_create.

If you do not, but the library is available in archive form, you may be able to use obcopy --rename-symbol to redirect its clone calls to a replacement (e.g. my_clone), which can then create a new thread via pthread_create and invoke the target function in that thread. Whether this will succeed greatly depends on how much the library cares about details of the clone.

It's also probably not worth the trouble.


A better alternative may be to implement the introspection without calling into libc. Since your printf and toupper probably only need to deal with ASCII and C locale, it's not hard to implement limited versions of these functions and use direct system calls to write the output.

Related