|
From: Amir S. <ki...@gm...> - 2012-10-24 01:29:16
|
That works perfectly. Thanks John!
I had to add a Valgrind suppression as dlsym() always leaves 20-bytes
"still reachable" block.
---------
{
dlsym in malloc_fail.cpp:malloc()
Memcheck:Leak
fun:calloc
obj:/lib/libdl-2.5.so
fun:dlsym
fun:malloc
...
}
---------
For anyone interested, this is the code I ended up using:
---------
/*
* Copyright (c) 2012, Juniper Networks, Inc.
* All rights reserved.
*/
#include "malloc_fail.h"
#include <cxxtest/TestSuite.h>
#define _GNU_SOURCE 1
#include <dlfcn.h>
static unsigned int malloc_num_to_fail = 0;
void malloc_dbg_set_num_to_fail(unsigned int num)
{
malloc_num_to_fail = num;
}
void *malloc(size_t size)
{
if (malloc_num_to_fail)
{
if (--malloc_num_to_fail == 0)
{
printf("Deliberate memory allocation failure [size=%zu]\n", size);
return NULL;
}
}
void * (*real_malloc) (size_t) = (void * (*) (size_t))
dlsym(RTLD_NEXT, "malloc");
return real_malloc(size);
}
-------
> The intended way to do this is by "intercepting", "superseding",
> or "over-riding" the symbol 'malloc': Make your own shared library
> containing a malloc() routine, and load it into your app via
> environment variable LD_PRELOAD, so that calls from the app to
> malloc() go to your LD_PRELOADed library. Your malloc can do
> whatever it wants, probably including finding the "real" malloc
> by dlsym(RTLD_NEXT, "malloc") and calling that as a subroutine.
> See the manual page for dlsym. Remember to "#define _GNU_SOURCE 1"
> before "#include <dlfcn.h>".
|