Skip to content

Instantly share code, notes, and snippets.

@yalue
Last active June 4, 2021 17:02
Show Gist options
  • Save yalue/681ef4b84a020af195e162d4a47c75c1 to your computer and use it in GitHub Desktop.
Save yalue/681ef4b84a020af195e162d4a47c75c1 to your computer and use it in GitHub Desktop.
Example of hooking pthread_create
// TO COMPILE:
// gcc -shared -fPIC -o thread_create_hook.so thread_create_hook.c -ldl
// TO USE (needs an absolute path):
// LD_PRELOAD=`pwd`/thread_create_hook.so ./application_to_hook
#define _GNU_SOURCE
#include <dlfcn.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef void* (*StartRoutine)(void*);
typedef int (*PthreadCreateFunction)(pthread_t*, const pthread_attr_t *,
StartRoutine, void*);
typedef struct {
StartRoutine function;
void *arg;
} OriginalStartRoutine;
void *StartRoutineHook(void *arg) {
StartRoutine original_function = NULL;
void *original_arg = NULL;
OriginalStartRoutine *original = (OriginalStartRoutine *) arg;
// The OriginalStartRoutine struct was allocated when our pthread_create hook was called, so
// copy the contents and free it here.
original_function = original->function;
original_arg = original->arg;
free(original);
printf("In new thread! Orig=%p, arg=%p\n", original_function, original_arg);
return original_function(original_arg);
}
int pthread_create(pthread_t *thread, const pthread_attr_t *attrs,
void* (*start_routine)(void*), void *arg) {
OriginalStartRoutine *start_info = (OriginalStartRoutine *) malloc(sizeof(OriginalStartRoutine));
if (!start_info) {
printf("malloc failed\n");
return 1;
}
PthreadCreateFunction original = dlsym(RTLD_NEXT, "pthread_create");
if (!original) {
printf("Failed looking up original pthread_create.\n");
return 1;
}
printf("Creating thread! Start routine: %p, arg: %p\n", start_routine, arg);
start_info->function = start_routine;
start_info->arg = arg;
return original(thread, attrs, StartRoutineHook, start_info);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment