![]() |
PMMM - The Poor Man's Memory Monitor | |
---|---|---|
was written by Burton M. Strauss III (BStrauss@acm.org) |
PMMM is based in large part on a concept and code from Luca Deri's leaks.c, part of NTop.
Why a special memory monitor and a low-rent (a/k/a light weight) one at that?
The big problem I was attempting to solve with The Poor Man's Memory Monitor (PMMM) was Ntop failures. When Ntop runs out of memory, one of two completely contradictory events occurs:
Not all memory allocation failures have to be fatal. In many cases, we could continue processing - albeit with slightly less accurate information or a disabled feature - if we explicitly handled a failure to allocate memory. The allocations, that could fail and not be fatal, I call "mayfail" allocations.
While mayfail allocations are conceptually easy - malloc returns NULL if it can't give you the memory you asked for - the problem is that you have to put failure handling coding after EVERY SINGLE allocation call, even if it's just a simple call to a failure routine in the "send a message and die" situations. It's all but impossible to generically handle these failures anyway - if I can't allocate this table, I have to set this flag so that that routine doesn't run. But this failure I can ignore if I treat it as though it hit the hard-coded limit on that table. etc. It just takes TOO much program specific knowledge to handle generically.
So: some hand-coding is required for every mayfail situation. S'be'it.
Back to Ntop. I tried it - even sent some poor SOB a patch to Ntop to run it on his system! It became ugly and a nightmare, to put code after every allocation, just to test the pointer and exit if it was NULL.
To solve the basic problems (allocation failures and mayfail), it would have been enough to wrap the allocation routines in something terribly simple and - in the wrapper - invoke Ntop's cleanup routines if the system allocate failed. Poking around in Ntop, I saw that leaks.c almost had what I was looking for.
Although the simple version didn't quite do it and the complex one wouldn't compile, it was almost there - I could smell it:
#define malloc(a) _mymalloc(a, __FILE__, __LINE__)
void * _mymalloc(int a, char * file, int line) { void * x; x = malloc(a); if (x == NULL) { message die } }
I also knew that if I were to fix enough of the failing allocations, do some case-specific coding for the 1 or 2 that might fail and yet still makes sense to continue after, the problem I started out trying to solve goes away.
Of course, that was too simple!
But the concept - a malloc "shim" - was so attractive. I emailed Luca Deri and he responded that the concept might have applicability beyond Ntop - and PMMM was born.
Credits to other things I've ripped off making this work: