Issue
I need to write a little library, to be loaded by setting LD_PRELOAD, and which will override some functions in the standard C library but also call those functions in the standard library. Specifically, I want my shiny new library to let users provide their own resolv.conf so they can, eg, specify their default domain, or set aliases in it for long hostnames. I'm going to need a good understanding of how the linker works if I'm to do this, so can anyone point me at some good documentation, that doesn't assume that I know it all already and just need a reference, but also doesn't assume that I'm a complete idiot?
Solution
If you are using the GNU linker, one thing you need to know about is RTLD_NEXT. This allows you to "find the next occurrence of a function in the search order after the current library".
This way, you can override a standard function and still be able to call the original version.
I used this function in a version of malloc that tracks allocation stats. I needed to override malloc to collect the stats but I still wanted the original version of malloc to do the allocation:
static void *(*next_malloc)(size_t) = NULL;
__attribute__ ((constructor))
static void
bootstrap()
{
next_malloc = dlsym(RTLD_NEXT, "malloc");
}
void *
malloc(size_t size)
{
void *ptr = next_malloc(size);
// collect some stats
return ptr;
}
Answered By - R Samuel Klatchko Answer Checked By - Terry (WPSolving Volunteer)