Find physical memory address from virtual memory address

c, linux, memory-management, unix

Solution

On Linux you can do it by parsing files in `/proc/<pid>`, namely, `maps` and `pagemap`. There is a little user-space tool that does it for you here.

Compile it (no special options are needed), run `page-types -p <pid> -l -N`, find the virtual page address in the first column, read the physical address in the second column.

It should be straightforward to turn this into a library and use programmatically. Bear in mind that some operations of the utility require root access (such as reading `/proc/kpageflags`), however, none is needed for this task.

Problem

- On Unix systems, can I find the physical memory address for a given virtual memory address? If yes, how? The real problem I'm trying to solve is, how can I find out if the OS maps two virtual addresses to the exact same physical region? E.g. in the below `smaps` example, how do I know if both memory regions are, in fact, physically identical? ``` cat /proc/<pid>/smaps ... 7f7165d42000-7f7265d42000 r--p 00000000 00:14 641846 /run/shm/test (deleted) Size: 4194304 kB Rss: 4194304 kB Pss: 2097152 kB ... VmFlags: rd mr mw me nr sd 7f7265d42000-7f7365d42000 rw-s 00000000 00:14 641846 /run/shm/test Size: 4194304 kB Rss: 4194304 kB Pss: 2097152 kB ... VmFlags: rd wr sh mr mw me ms sd ... ``` Bonus: Is there a way to simply do it programmatically in C ? I tried to look for duplicates but could not find a pertinent one.

Original source