I want to write a shared library in such a way that it is possible to isolate it’s memory usage from the application it is linked against. That is, if the shared library, let’s call it libmemory.so
, calls malloc
, I want to maintain that memory in a separate heap from the heap that is used to service calls to malloc
made in the application. This question isn't about writing memory allocators, it more about linking and loading the library and application together.
So far I’ve been experimenting with combinations of function interposition, symbol visibility, and linking tricks. So far, I can’t get this right because of one thing: the standard library. I cannot find a way to distinguish between calls to the standard library that internally use malloc
that happen in libmemory.so
versus the application. This causes an issue since then any standard library usage within libmemory.so
pollutes the application heap.
My current strategy is to interpose definitions of malloc
in the shared library as a hidden symbol. This works nicely and all of the library code works as expected except, of course, the standard library which is loaded dynamically at runtime. Naturally, I’ve been trying to find a way to statically embed the standard library usage so that it would use the interposed malloc
in libmemory.so
at compile time. I’ve tried -static-libgcc
and -static-libstdc++
without success (and anyway, it seems this is discouraged). Is this the right answer?
What do?
P.s., further reading is always appreciated, and help on the question tagging front would be nice.
malloc
in the same process is liable to cause catastrophic malfunctions, because nobody worries about matching A_malloc with A_free and B_malloc with B_free, the implementations might get in a fight over which of them is allowed to callsbrk
with a nonzero argument, etc. etc. etc. etc. – Driskelllibmemory.so
does and which C and C++ library functions it uses. – Driskellfopen
orgmtime_r
might internally call malloc, thereby using the application's heap allocator to be used. – Medicate