One way to do it is to create a replacement function for pthread_create, and use the LD_PRELOAD.
Of course you don't want to reimplement pthread_create, so you have to call pthread_create somehow, but you can ask the dynamic loader to load it for you :
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <bits/pthreadtypes.h>
#include <dlfcn.h>
void store_id(pthread_t * id) {
fprintf(stderr, "new thread created with id 0x%lx
", (*id));
}
#undef pthread_create
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start)(void *), void * arg)
{
int rc;
static int (*real_create)(pthread_t * , pthread_attr_t *, void * (*start)(void *), void *) = NULL;
if (!real_create)
real_create = dlsym(RTLD_NEXT, "pthread_create");
rc = real_create(thread, attr, start, arg);
if(!rc) {
store_id(thread);
}
return rc;
}
Then you compile it to a shared library :
gcc -shared -ldl -fPIC pthread_interpose.c -o libmypthread.so
And you can use it with any dynamically linked prog :
LD_PRELOAD=/path/to/libmypthread.so someprog
Note : This is an adpated version of this blog post
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…