DEV Community

chinmay chhajed
chinmay chhajed

Posted on

Example showing usage of LD_PRELOAD environment variable in UNIX

LD_PRELOAD

We can use LD_PRELOAD environment variable to set a location to fetch shared libraries. By setting this variable, we can overwrite the existing functions and make the standard command work differently, the way we want it to.

The linker links the libraries in the path provided by LD_PRELOAD for compiling the main file. Once a function is linked, when other instance of same function shows up, newer location is ignored and the previous (original) location is used.

For example, let us try to overwrite the puts function present in stdio.h file.

Consider a file main.c, with following content:

  #include <stdio.h>

  int theFunction(const char *s)
  {
      return puts(s);
  }

  int main (int argc, char** argv) {
      theFunction("Hello, this is traditional work flow.");
      printf("%s: puts location: %p\n", __FILE__, puts);
  }
Enter fullscreen mode Exit fullscreen mode

Compiling and running the main.c file gives following output with location of puts as 0x7f877af52ef0.

Image description

Create another file, unmain.c as follows:

  #include <stdio.h>

  int puts(const char *__s)
  {
      return printf("New puts, hackerman alert!\n");
  }
Enter fullscreen mode Exit fullscreen mode

Now, create a shared library of this unmain.c file with command:

  gcc -fPIC unmain.c -shared -o unmain.so
Enter fullscreen mode Exit fullscreen mode

Update the LD_PRELOAD with the location of the shared library, unmain.so:

  export LD_PRELOAD="$PWD/unmain.so"
Enter fullscreen mode Exit fullscreen mode

And then again run the first compiled main.c file's executable main.o to see that the location of the puts has been updated. For my case, new location has been set to 0x7f608b603ef0.

  ./main.o
Enter fullscreen mode Exit fullscreen mode

Image description

To remove the shared library, use unset to unset value of
LD_PRELOAD.

  unset LD_PRELOAD
Enter fullscreen mode Exit fullscreen mode

Image description

Same example to contribute on Github: https://github.com/chhajedji/ld-preload

Discussion (0)