Skip to content

Instantly share code, notes, and snippets.

@xorz57
Last active October 14, 2025 11:05
Show Gist options
  • Select an option

  • Save xorz57/c5e04751cafacf2338e4d34040161072 to your computer and use it in GitHub Desktop.

Select an option

Save xorz57/c5e04751cafacf2338e4d34040161072 to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <dlfcn.h>
#include <unistd.h>
extern "C" {
namespace {
std::once_flag init_flag;
using malloc_t = void*(*)(std::size_t);
using free_t = void(*)(void*);
using calloc_t = void*(*)(std::size_t, std::size_t);
using realloc_t = void*(*)(void*, std::size_t);
malloc_t native_malloc = nullptr;
free_t native_free = nullptr;
calloc_t native_calloc = nullptr;
realloc_t native_realloc = nullptr;
void init_hooks() noexcept {
native_malloc = reinterpret_cast<malloc_t>(dlsym(RTLD_NEXT, "malloc"));
native_free = reinterpret_cast<free_t>(dlsym(RTLD_NEXT, "free"));
native_calloc = reinterpret_cast<calloc_t>(dlsym(RTLD_NEXT, "calloc"));
native_realloc = reinterpret_cast<realloc_t>(dlsym(RTLD_NEXT, "realloc"));
}
inline void log(const char* msg) noexcept {
write(STDERR_FILENO, msg, std::strlen(msg));
}
}
void* malloc(std::size_t size) {
std::call_once(init_flag, init_hooks);
void* ptr = native_malloc(size);
char buf[128];
int len = std::snprintf(buf, sizeof(buf), "malloc(%zu) = %p\n", size, ptr);
write(STDERR_FILENO, buf, len > 0 ? len : 0);
return ptr;
}
void free(void* ptr) {
std::call_once(init_flag, init_hooks);
char buf[128];
int len = std::snprintf(buf, sizeof(buf), "free(%p)\n", ptr);
write(STDERR_FILENO, buf, len > 0 ? len : 0);
native_free(ptr);
}
void* calloc(std::size_t num, std::size_t size) {
std::call_once(init_flag, init_hooks);
void* ptr = native_calloc(num, size);
char buf[128];
int len = std::snprintf(buf, sizeof(buf), "calloc(%zu, %zu) = %p\n", num, size, ptr);
write(STDERR_FILENO, buf, len > 0 ? len : 0);
return ptr;
}
void* realloc(void* ptr, std::size_t size) {
std::call_once(init_flag, init_hooks);
void* new_ptr = native_realloc(ptr, size);
char buf[128];
int len = std::snprintf(buf, sizeof(buf), "realloc(%p, %zu) = %p\n", ptr, size, new_ptr);
write(STDERR_FILENO, buf, len > 0 ? len : 0);
return new_ptr;
}
} // extern "C"
@xorz57
Copy link
Author

xorz57 commented Mar 24, 2025

g++ -shared -fPIC -ldl lib.cpp -o lib.so
LD_PRELOAD=./lib.so ls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment