"Overload" malloc
-
Hi All, I would like to add my own functionality to malloc: Is it possible somehow to hook into this function (or between it and OS). Thanks in advance, boni
-
Hi All, I would like to add my own functionality to malloc: Is it possible somehow to hook into this function (or between it and OS). Thanks in advance, boni
I'm not sure if this technique is possible in Windows, but it is under Unix with ELF loaders. Write a shared library (.so - equivalent to .dll in Windows), in which you define
extern "C" void* malloc(size_t s)
. Then have the shared library to be preloaded before all other DLLs are loaded. Then the linker will not link the system malloc since it has already been loaded. To chain your malloc with the system's malloc, you simply load the system shared library dynamically in your shared library, and retrieve the pointer to the system's malloc. So, in your DLL you will have code kind of like this:void* (*real_malloc)(size_t);
DllMain() {
HANDLE h = LoadLibrary("whichever_dll_that_contains_malloc.dll");
real_malloc = (void*(*)(size_t))GetProcAddress("malloc");
}extern "C" __declspec(dllexport) void* malloc(size_t s) {
do_some_stuff();
void* ptr = real_malloc(s);
return do_something_more_perhaps(s);
}Then have the linker preload this DLL. I'm not sure it's possible in Windows, but I have a hunch it is. I know it's possible to hijack DLLs, and that's basically what this is. Needless to say, you'll need to link against the runtime dynamically. -- Suche Wissen über Alles. Der Student