Using LD_PRELOAD to override a function

For some reason, people seem to get this quite wrong a lot of the time. Certainly one should not be playing with symbols that start with __ unless you really know what you're doing with them.

ianw@lime:~/tmp/override$ cat override.c
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dlfcn.h>

pid_t getpid(void)
{
        pid_t (*orig_getpid)(void) = dlsym(RTLD_NEXT, "getpid");
        printf("Calling GETPID\n");

        return orig_getpid();
}

ianw@lime:~/tmp/override$ cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
        printf("%d\n", getpid());
}

ianw@lime:~/tmp/override$ gcc -shared -fPIC -o liboverride.so override.c -ldl
ianw@lime:~/tmp/override$ gcc -o test test.c
ianw@lime:~/tmp/override$ LD_PRELOAD=./liboverride.so ./test
Calling GETPID
15187