Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6861

linux munmap not working (or at least not working instantly)

I called munmap without error, but the mapping was still visibe in /proc/<pid>/maps and when I tried to mmap(address_overlapping_with_what_I_tried_to_munmap, ...) I did not get the address I requested.

Is that a bug or a feature? Is there something I can do to make sure something is unmapped?

Details: 32-bit Linux 4.1.18

EDIT

Initially, the maps entry is

bfe50000-bfe71000 rw-p 00000000 00:00 0

then after I call munmap with arguments 0xbfe50000, 0x21000

the entry is

bfe50000-bfe50000 rw-p 00000000 00:00 0

Upvotes: 2

Views: 1133

Answers (1)

when I tried to mmap(address_overlapping_with_what_I_tried_to_munmap, ...) I did not get the address I requested.

Read mmap(2) carefully again:

If addr is NULL, then the kernel chooses the address at which to create the mapping; this is the most portable method of creating a new mapping. If addr is not NULL, then the kernel takes it as a hint about where to place the mapping

and later:

MAP_FIXED Don't interpret addr as a hint: place the mapping at exactly that address. addr must be a multiple of the page size.

So if you really need to have the address passed to mmap as a useful address, you should use MAP_FIXED (with caution, since it can overwrite and "crush" a very useful pre-existing memory map).

In other words, I understand that the address to mmap should better be 0, unless you say MAP_FIXED. Otherwise, it is just a "hint" and I don't know what that practically means (especially with ASLR).

AFAIU, the /proc/self/maps or /proc/1234/maps reflect instantaneously the kernel's perception of your process virtual address space. Of course, you need to open that pseudo-file, read it quickly and sequentially, and close it as soon as possible (don't keep a file descriptor to an open-ed /proc/self/maps for several seconds). What happens if your process is mmap-ing or munmap-ing (or changing its address space in some other way) between the open & the close of that /proc/*/maps file is IMHO undefined behavior -or at least unspecified behavior- on which you should not depend.

But mmap & munmap are effective as soon as that system call is returned from; there is no "delay" in changing the virtual address space. The virtual memory machinery may give some delay (e.g. when fetching some page from some remote network ...) but that delay is not accessible to applications (the process would be in D state). Read also about thrashing.

Upvotes: 1

Related Questions