Stubing the libc functions.

by groleo

I tried to use Mockpp[1] one day to test a scheduling queue.
The queue used gettimeofday to see when a packet expired.
This would prove imposible to test with stub-testing, unless I would wrap gettimeofday
in another class, and then change the code to use that class which would be difficult.

After some googling I found about the GNU ld “-wrap” parameter.

From `man 1 ld`:

--wrap symbol
Use a wrapper function for symbol. Any undefined reference to
symbol will be resolved to "__wrap_symbol".

Any undefined reference to "__real_symbol" will be
resolved to symbol.

So I put up a little test, made out of two files:
malloc_wrapper.c and test_ld_wrap.c

/* malloc_wrapper.c */
#include <stdio.h>
void *__real_malloc (int);

void * __wrap_malloc (size_t c)
{
	void *lptr = __real_malloc(size);
	printf("@ %s:[%p] + %p %#x\n", program_invocation_short_name, __builtin_return_address(0), lptr, size );
	return lptr;
}
/* test_ld_wrap.c */
#include <stdio.h>
int main()
{
    malloc(1);
}

Putting the whole thing together

gcc -c malloc_wrapper.c
gcc -c test_ld_wrap.c
gcc -Wl,-wrap,malloc test_ld_wrap.o malloc_wrapper.o

Running the test will yield:

~/mine> ./a.out
malloc called with 1

Yey, success!

I prefer this method on architectures where LD_PRELOAD is not available,
and this usually happens in the Embedded world.
You will have to recompile your application though.
This parameter can be used either for testing or for memory leak detection, when the C library doesn’t provide
support. ( see `man 3 mtrace` for GNU libc).

———–
[1] http://mockpp.sourceforge.net/

Advertisements