# Linux Kernel Module Cheat

##### 17.12.2.1. Userland physical address experiments

Only tested in x86_64.

The Linux kernel exposes physical addresses to userland through:

- `/proc/<pid>/maps`

- `/proc/<pid>/pagemap`

- `/dev/mem`

In this section we will play with them.

The following files contain examples to access that data and test it out:

- lkmc/pagemap.h

- rootfs_overlay/lkmc/virt_to_phys.sh

- userland/linux/virt_to_phys_user.c

- userland/posix/virt_to_phys_test.c

First get a virtual address to play with:

    ./posix/virt_to_phys_test.out &

Source: userland/posix/virt_to_phys_test.c

Sample output:

    vaddr 0x600800
    pid 110

The program:

- allocates a `volatile` variable and sets is value to `0x12345678`

- prints the virtual address of the variable, and the program PID

- runs a while loop until until the value of the variable gets mysteriously changed somehow, e.g. by nasty tinkerers like us

Then, translate the virtual address to physical using `/proc/<pid>/maps` and `/proc/<pid>/pagemap`:

    ./linux/virt_to_phys_user.out 110 0x600800

Sample output physical address:

    0x7c7b800

Now we can verify that `linux/virt_to_phys_user.out` gave the correct physical address in the following ways:

- QEMU xp

- /dev/mem

Bibliography:

- https://stackoverflow.com/questions/17021214/decode-proc-pid-pagemap-entry/45126141#45126141

- https://stackoverflow.com/questions/6284810/proc-pid-pagemaps-and-proc-pid-maps-linux/45500208#45500208

- QEMU xp

- /dev/mem

- pagemap_dump.out