linuxmemorymemory-managementlinux-kernelmmap

Is it possible to add a customized name for the (non file-backed) mmap region?


Just curious whether it is possible to specify a name for the non file-backed mmap region? Some thing like the [New VMA area] in the following example:

$ cat /proc/12345/maps
...
7fc062ef2000-7fc062f84000 r-xp 00000000 08:01 22688328                   /usr/local/musl/lib/libc.so
7fc062f85000-7fc062f86000 r--p 00092000 08:01 22688328                   /usr/local/musl/lib/libc.so
7fc062f86000-7fc062f87000 rw-p 00093000 08:01 22688328                   /usr/local/musl/lib/libc.so
7fc062f87000-7fc062f8a000 rw-p 00000000 00:00 0                          [New VMA area]
7fff6c384000-7fff6c3a5000 rw-p 00000000 00:00 0                          [stack]
7fff6c3bd000-7fff6c3c0000 r--p 00000000 00:00 0                          [vvar]

Solution

  • The content of maps comes from the show_map_vma function in fs/proc/task_mmu.c. Looking at it, if you want a custom name for a non-file-backed mapping, it'd need to come from either vma->vm_ops->name or arch_vma_name. arch_vm_name is architecture-specific (as you'd expect from the name) and serves only to add a few hardcoded names for certain regions, so it's not useful to you. That leaves vma->vm_ops->name as your only possibility, but when you call mmap with MAP_ANONYMOUS, vma_set_anonymous sets vma->vm_ops to NULL. Thus, strictly what you asked for is impossible without custom kernel code.

    EDIT: The preceding paragraph is no longer true as of Linux 5.17 (see Samuel A's answer). The following paragraph is still useful as a workaround if you're stuck on a system with an older kernel, or without CONFIG_ANON_VMA_NAME.

    However, it may still be possible to do what you want. If you actually just want the memory to not be backed by disk, you can create an FD with the memfd_create syscall or a file in a non-disk-backed filesystem such as a tmpfs (e.g., /dev/shm, like shm_open uses). Either of these approaches will give you control over the filename that is used (e.g., /memfd:some_name (deleted) or /dev/shm/some_name).