Run-time library interposition for sleep() function in C

371 views Asked by At

I'm having a slight problem with interpositioning the sleep function at run time. I'm currently trying to test library interpositioning at runtime using a simple source code, "sleepdemo.c" and "wakeup.c".

The code(wakeup.c) I have wrote is as following:

  1 #ifdef RUNTIME
  2 #define _GNU_SOURCE
  3 #include <stdio.h>
  4 #include <unistd.h>
  5 #include <dlfcn.h>
  6 #include <stdlib.h>
  7
  8 /* sleep wrapper function*/
  9 unsigned int wakeup(unsigned int secs)
 10 {
 11         unsigned int (*wakeupp)(unsigned int secs);
 12         char *error;
 13
 14         wakeupp = dlsym(RTLD_NEXT, "sleep"); //Get address of sleep
 15         if((error = dlerror()) != NULL){
 16                 fputs(error, stderr);
 17                 exit(1);
 18         }
 19
 20         unsigned int elapsed = sleep(secs);
 21         printf("Woke up at %d secs.\n", secs - elapsed+1);
 22         return elapsed;
 23 }
 24
 25 #endif

And this is the code I'm trying to interpose:

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <unistd.h>
  4
  5 int main()
  6 {
  7         int secs = 1;
  8
  9         printf("This is sleep demo program.\n");
 10         sleep(secs);
 11         return 0;
 12 }

And I have given following instructions to my gcc to create an shared library:

gcc -DRUNTIME -shared -fpic -o mysleep.so wakeup.c -ldl
LD_PRELOAD="./mysleep.so" ./wakeup
0

There are 0 answers