0

I would like to override strcpy and to supply my own implementation, in my strcpy I want to do something and call to the original strcpy. How can I do that?

I'm working on linux, compiling with gcc, so I read about built in functions provided by gcc, I'm not sure if that's the way to do what I need, but I tried to use the flag -fno-builtin-strcpy, and in my strcpy call to __builtin_strcpy, but somehow it doesn't work as expected and cause some problemes:

char *strcpy(char *dest, const char *src)
{
    if(......)
    {
          ----do something---
    }

     return __builtin_strcpy(dest,src);

}
almog
  • 51
  • 9

2 Answers2

1

You can do this using gcc function wrappers:

  1. Prefix your strcpy implementation with __wrap_ (i.e. name it __wrap_strcpy).
  2. In your function implementation, call the internal library function with __real_ prefix (i.e. __real_strcpy).
  3. In the link stage, add the switch -wrap=strcpy. This will cause each time the linker finds a strcpy call, it will call __wrap_strcpy instead if available.

Your program should be like this:

char *__wrap_strcpy(char *dest, const char *src)
{
    if(......) {
          ----do something---
    }

     return __real_strcpy(dest,src);
}

And you should add this to your LDFLAGS:

LDFLAGS+="-wrap=strcpy"

Hope this helps

Jesús Alonso
  • 301
  • 3
  • 6
-1

I guess you might be able to do that by playing with linking order or excluding some standard libraries but I would not do that. If your SW has long life and multiple maintainers, there will be some maintenance problems at some point.

Why don't you create a new strcpy instead?

char *my_new_strcpy(char *dest, const char *src)
{
    if(......)
    {
          ----do something---
    }

    return strcpy(dest,src);

}

And use that where you need. Or does that not meet your requirements?

diidu
  • 2,823
  • 17
  • 32
  • Actually what I really need is to check where in my code there is an overlapping between the src and dest that sent to strcpy. I want to check overlap and than call to the default strcpy, in order to locate cases of overlaping in my code. so- "use that where you need" is every call to strcpy in our code. – almog Jul 14 '15 at 11:28
  • Since you are working on linux with gcc it should be very easy for you to check that with valgrind (http://valgrind.org/). It is very useful tool and may reveal also other memory handling issues. – diidu Jul 14 '15 at 11:46