How to replace pthread_create during connection

I want to keep a list of all running threads with some additional information about each thread. This answer mentioned that you could provide my own version of pthread_create and associate a program with it. It is also important that I want to call the original pthread_create at the end of my overridden version.

Can someone explain in detail how this can be done and / or provide sample code?

+4
source share
2 answers

You can find the symbol of the original pthread_create function by calling:

pthread_create_orig = dlsym(RTLD_NEXT, "pthread_create");

Then the wrapper will look like this:

#include <dlfcn.h>

int (*pthread_create_orig)(pthread_t *, const pthread_attr_t *, void *(*) (void *), void *);

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start) (void *), void *arg) {
       if (!pthread_create_orig)
           pthread_create_orig = dlsym(RTLD_NEXT, "pthread_create");
       return pthread_create_orig(thread, attr, start, arg);
}

.

: dlsym() , dlopen(). RTLD_NEXT , .. , . libpthread, , .

+4

, pthread_create, phtread_create.

pthread.c:

#include <dlfcn.h>
#include <stdio.h>
#include <pthread.h>

int (*original_pthread_create)(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) = NULL;

void load_original_pthread_create() {
    void *handle = dlopen("libpthread-2.15.so", RTLD_LAZY);
    char *err = dlerror();
    if (err) {
        printf("%s\n", err);
    }
    original_pthread_create = dlsym(handle, "pthread_create");
    err = dlerror();
    if (err) {
        printf("%s\n", err);
    }
}
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) {
    if (original_pthread_create == NULL) {
        load_original_pthread_create();
    }
    printf("I am creating thread from my pthread_create\n");
    return original_pthread_create(thread, attr, start_routine, arg);
}

: gcc pthread.c -o libmypthread.so -shared -fpic -ldl

: LD_PRELOAD=./libmypthread.so some_program_using_pthread_create

some_program_using_pthread_create , pthread_create .

: pthread dlopen.

+3

Source: https://habr.com/ru/post/1624670/


All Articles