0

I have overloaded malloc and free as below:

#include <stdio.h>
#include <dlfcn.h>
typedef void* (*MALLOCFN)(size_t);
typedef void (*FREEFN)(void *);
MALLOCFN real_malloc = (MALLOCFN) 0;
FREEFN real_free = (FREEFN) 0;
void *get_realfn(char *fnm)
{
  void *pfunc = (void *) NULL;
  void *h = dlopen("libc.so", RTLD_LAZY|RTLD_NODELETE|RTLD_NOLOAD);
  printf("loading .so to search original %s\n", fnm);
  if (h) {
    printf("searching for original %s\n", fnm);
    pfunc = dlsym(h, fnm);
    dlclose(h);
  }
  else {
    printf(".so could not be loaded to search original %s\n", fnm);
    return (void *) NULL;
  }
  if (pfunc)
    printf("found original %s\n", fnm);
  else
    printf("not found original %s\n", fnm);
  return pfunc;
}
void *malloc(size_t s)
{
  printf("called malloc\n");
  if(real_malloc == NULL) {
    real_malloc = (MALLOCFN) get_realfn("malloc");
  }
  if (real_malloc)
    return real_malloc(s);
  else
    return NULL;
}

void free(void *p)
{
  printf("called free\n");
  if(real_free == NULL) {
    real_free = (FREEFN) get_realfn("free");
  }
  if (real_free)
    real_free(p);
}

int main()
{
  char * c = (char *) malloc(400);
  free(c);
  return 0;
}

I am getting the following output:

called malloc
loading .so to search original malloc
.so could not be loaded to search original malloc
called free
loading .so to search original free
.so could not be loaded to search original free

I am using gcc 4.9.2 on Linux. I tried to debug, and found that apparently the logic looks ok, but whenever dlopen is called, it goes into calling malloc again, resulting in an infinite loop searching for the original_maloc. Any suggestion? (LD_LIBRARY_PATH is set properly to have access to libc.so which is soft linked to libc-2.17.so) This is the call stack from the core:

(gdb) bt
#0  0x000000000066232c in malloc (
    s=<error reading variable: Cannot access memory at address 0x7ffd768118f8>)
    at mallocmgr.mtc:190
#1  0x00007fe8d6541fb1 in _dl_signal_error () from /lib64/ld-linux-x86-64.so.2
#2  0x00007fe8d653bcce in _dl_map_object () from /lib64/ld-linux-x86-64.so.2
#3  0x00007fe8d6546844 in dl_open_worker () from /lib64/ld-linux-x86-64.so.2
#4  0x00007fe8d65421b4 in _dl_catch_error () from /lib64/ld-linux-x86-64.so.2
#5  0x00007fe8d65461ab in _dl_open () from /lib64/ld-linux-x86-64.so.2
#6  0x00007fe8d358002b in dlopen_doit () from /lib64/libdl.so.2
#7  0x00007fe8d65421b4 in _dl_catch_error () from /lib64/ld-linux-x86-64.so.2
#8  0x00007fe8d358062d in _dlerror_run () from /lib64/libdl.so.2
#9  0x00007fe8d35800c1 in dlopen@@GLIBC_2.2.5 () from /lib64/libdl.so.2
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69

0 Answers0