How can we replace a C standard library function with our own implementation of that function ?
For example, how can I replace strcpy()
with my own implementation of strcpy()
and have all calls link to the new implementations instead?
How can we replace a C standard library function with our own implementation of that function ?
For example, how can I replace strcpy()
with my own implementation of strcpy()
and have all calls link to the new implementations instead?
At least with GCC and glibc, the symbols for the standard C functions are weak and thus you can override them. For example,
strcpy.c:
#include <string.h>
#include <stdio.h>
char * strcpy(char *dst, const char *src)
{
char *d = dst;
while (*src) {
*d = *src;
d++;
src++;
}
printf("Called my strcpy()\n");
return (dst);
}
int main(void)
{
char foo[10];
strcpy(foo, "hello");
puts(foo);
return 0;
}
And build it like this:
gcc -fno-builtin -o strcpy strcpy.c
and then:
$ ./strcpy
Called my strcpy()
hello
Note the importance of -fno-builtin
here. If you don't use this, GCC will replace the strcpy()
call to a builtin function, of which GCC has a number.
I'm not sure if this works with other compilers/platforms.
You can try playing with LD_PRELOAD if you are on Linux.
I'm not sure how hard it will be to get the linker to do what you want, but here's a solution that doesn't involve changing any linker settings and uses preprocessor macros instead so that any code that tries to call strcpy actually calls a function called my_strcpy:
mystuff.h:
#define strcpy my_strcpy
char * my_strcpy(char * dst, const char * src);
my_strcpy.c:
#include <mystuff.h>
char * my_strcpy(char * dst, const char * src);
{
...
}
my_code.c:
#include <mystuff.h>
int main()
{
/* Any call to strcpy will look like a normal call to strcpy
but will actually call my_strcpy. */
}