1

I am using LD_PRELOAD to log malloc calls from an application and map out the virtual address space however malloc is used internally by fopen/printf. Is there a way I can fix this issue?

I know about glibc's hooks but I want to avoid changing the source code of the application.

bnm
  • 108
  • 6

1 Answers1

1

My issue was caused by the fact that malloc is used internally by glibc so when I use LD_PRELOAD to override malloc any attempt to log caused malloc to be called resulting in a recursive call to malloc itself

Solution: call original malloc whenever the TLS needs memory allocation providing code:

static __thread int no_hook;
static void *(*real_malloc)(size_t) = NULL;
static void __attribute__((constructor))init(void) {
    real_malloc = (void * (*)(size_t))dlsym(RTLD_NEXT, "malloc");
}

void * malloc(size_t len) {
    void* ret;
    void* caller;

    if (no_hook) {
        return (*real_malloc)(len);
    }

    no_hook = 1;
    caller = (void*)(long) __builtin_return_address(0);
    printf("malloc call %zu from %lu\n", len, (long)caller);
    ret = (*real_malloc)(len); 
    // fprintf(logfp, ") -> %pn", ret); 
    no_hook = 0; 
    return ret; 
}

bnm
  • 108
  • 6
  • 1
    With `-fsanitizer=address` compiler argument `malloc()` is called before `init()`. Therefore, add the check: `if (!real_malloc) init();` to the custom malloc. – basin Jun 15 '18 at 11:57