一、如何 hook calloc
dlsym 内部可能使用 calloc 分配内存。如果 hook calloc 的时候,使用 dlsym 可能会导致出现死循环。
如下是一种解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
static unsigned char calloc_ptr_buffer[8192] = {0}; static calloc_type real_calloc = nullptr; static bool is_gather_calloc_ptr_error = false; static bool is_init_calloc = false;
__attribute__((constructor(101))) static void my_init_calloc_hook(void) { is_init_calloc = true; static calloc_type tmp_calloc_ptr = reinterpret_cast<calloc_type>(dlsym(RTLD_NEXT, "calloc")); if (tmp_calloc_ptr != nullptr) { real_calloc = tmp_calloc_ptr; } else { is_gather_calloc_ptr_error = true; } }
void* calloc(size_t nmemb, size_t size) __THROW { if (real_calloc == nullptr) { if (is_gather_calloc_ptr_error) return nullptr; if (is_init_calloc) return calloc_ptr_buffer; return nullptr; } void* point = real_calloc(nmemb, size); if (point) { default_malloc_size_func(_msize(point), true); } return point; }
|