Created
December 10, 2019 00:57
-
-
Save srivatsan-ramesh/6e9f10e0a455ee855857638a8550b5a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <dlfcn.h> | |
#include <stdio.h> | |
#include <pthread.h> | |
#include <time.h> | |
#include <stdlib.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.27.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(); | |
} | |
static int count = 0; | |
if(count == 0) { | |
srand(time(NULL)); | |
count++; | |
} | |
struct sched_param rr_param; | |
pthread_attr_t custom_sched_attr; | |
if(!attr) | |
pthread_attr_init(&custom_sched_attr); | |
else | |
custom_sched_attr = *attr; | |
pthread_attr_setscope(&custom_sched_attr, PTHREAD_SCOPE_PROCESS); | |
pthread_attr_setinheritsched(&custom_sched_attr, PTHREAD_EXPLICIT_SCHED); | |
pthread_attr_setschedpolicy(&custom_sched_attr, SCHED_RR); | |
int rr_max_prio = sched_get_priority_max(SCHED_RR); | |
int rr_min_prio = sched_get_priority_min(SCHED_RR); | |
int prio = rand()%(rr_max_prio - rr_min_prio + 1) + rr_min_prio; | |
rr_param.sched_priority = prio; | |
pthread_attr_setschedparam(&custom_sched_attr, &rr_param); | |
int ret = original_pthread_create(thread, &custom_sched_attr, start_routine, arg); | |
printf("%lu %d\n", *thread, prio); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A wrapper to pthread_create function call which randomly assigns a priority to a thread. This can be used to detect concurrency bugs. Change pthread library version in line 11 to the one the application binary uses.
Compile
gcc pthread.c -o libmypthread.so -shared -fpic -ldl
Run
sudo LD_PRELOAD=./libmypthread.so ./<application_binary_you_want_to_test>