Situation - I am using a third party stack. I have a source code of the third party. This code is quite clumsy and a there are a lot of problems related to buffer over-run.
My Solution - In order to trace down this issue, I am overriding the existing functions like sprintf and memcpy to check if there is a buffer overrun.
Here is what I have done so far to override malloc and sprintf.
#define memcpy my_memcpy
void * my_memcpy(void *s1, const void *s2, size_t n)
{
void *(*libc_memcpy)(void*,const void*,size_t) = dlsym(RTLD_NEXT, "memcpy");
return libc_memcpy(s1,s2,n);
}
Next, I have used sprintf -
#define sprintf mysprintf
int mysprintf(char *str, const char *format, ...)
{
va_list args;
va_start(args, format);
vsprintf(str,format, args);
va_end(args);
return 0;
}
My problem - I want the overridden function to print when the buffer - destination is of less capacity, then what we are writing to it.
I need the solution, which will work for stack allocated memory like char buff[5]; and char *buff = (char *) malloc(5);
So, let's say, when we do memcpy on the buff with the string size 6 bytes, then the overriden memcpy should throw an error. Similarly, when we sprintf, the overriden sprintf should throw an error. The major problem is sprintf. I want to use snprintf rather than sprintf. It's difficult to look into every piece of code and change to snprintf. So, What I want to do here is to override sprintf with my version and internally call snprintf, where I will compute 'n' based on the size of the arg. Also, I will compare if the n is less than buffer size or not. The bottleneck is how to find the size of the buffer based on the pointer passed.