The NetBSD libc malloc implementation uses a memory-mapped area for
its page directory. Since the process heap is reconstructed upon
state transfer for live update, this memory-mapped area must not be
transferred to the new process. However, as the new instance of the
process being updated inherits all memory-mapped areas of the old
instance, it also automatically inherits the malloc implementation's
page directory. Thus, we must explicitly free this area in order to
avoid a memory leak.
The magic pass already detects (de)allocation functions called from
within other (de)allocation functions, which is why the mmap(2) and
munmap(2) calls of the malloc code are not instrumented as it is.
This patch changes that particular case to allow a different hook
function to be called for such "nested" allocation calls, for a
particular set of nested calls. In particular, the malloc(3) code's
mmap(2) and munmap(2) calls are replaced with magic_nested_mmap and
magic_nested_munmap calls, respectively. The magic library then
tracks memory mapping allocations of the malloc code by providing an
implementation for these two wrappers, and frees the allocations upon
state transfer.
This approach was chosen over various alternatives:
- While it appears that nesting could be established by setting a
flag while the malloc(3) wrapper is active, and testing the flag in
the mmap(2)/munmap(2) wrappers, this approach would fail to detect
memory-mapped allocations made from uninstrumented malloc(3) calls,
and therefore not a viable option.
- It would be possible to obtain the value of the variables that
store the information about the memory-mapped area in the malloc
code. However, this is rather difficult in practice due to the way
the libc malloc implementation stores the size of the are, and it
would make the solution more dependent on the specific libc malloc
implementation.
- It would be possible to use the special "nested" instrumentation
for allocations made from certain marked sections. Since we mark
the data section of the malloc code already, this would not be hard
to do. Switching to this alternative would change very little, and
if for any reason this approach yields more advantages in the
future, we can still choose to do so.