Before I start inventing the wheel, I've decided to do some searching to look if my desired feature is already implemented somewhere. Generally, I'd like to analyze my macOS kext and look for any memory issues (especially leaked memory).
More specifically, I wish to find a code based profiler (since an external profiler doesn't support debugging kernel modules) which used as a wrapper for malloc/free.
1. on every malloc it record where you allocated the memory (file/line)
2. on every free, it remove this meta data (along with the memory itself).
3. on tear-down, it scans for all left dynamic memory regions
and prints them out (along with their corresponding meta-data).
This analysis may be called when unloading the driver, which is the point
where all memory should be free.
Here's an implementation option using doubly linked list, that upon alloc request with some input size, the actual malloc is made for size + overhead
where the second part is intended to contain links to previous allocation and next allocation, and the meta data itself (getting filename using FILE macro and code line using LINE macro and maybe more info), the return address is the offset of overhead
from the actual allocation, so that the user may handle the read data only.
Upon free
, we use the input address - offset
as the actual input to free
since this is the original allocated memory, but before the freeing itself, the item should be properly removed from the linked list.
Upon analysis, we iterate the list and print each element.
Notice that there are some implementation details such as supporting multi-threaded environment by locking the code section and insert/remove item from the linked list.
Alternatively, perhaps there's a GDB/LLDB plug-in that scanned for all dynamically allocated memory (and prints its size)...
P.S
In windows there's such module called driver verifier
which gives your kernel module the abilities stated above, and you don't need to re-compile anything (it's activated on run-time flag)... is there any such tool on macOS ?