在Linux的应用态程序中,如何access 系统的physical memory呢?此时,就要用上/dev/mem了。

Introduction

利用/dev/mem,通过mmap可以将物理地址映射到用户空间的虚拟地址上,从而可以access physical memory。

Example code

Access physical memory from Linux user space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int mem_dev = open("/dev/mem", O_RDWR | O_SYNC);

const uint32_t mem_address = 0x10001234
const uint32_t mem_size = 0x100;

uint32_t alloc_mem_size, page_mask, page_size;
void *mem_pointer, *virt_addr;

page_size = sysconf(_SC_PAGESIZE);
alloc_mem_size = (((mem_size / page_size) + 1) * page_size);
page_mask = (page_size - 1);

mem_pointer = mmap(NULL,
alloc_mem_size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
mem_dev,
(mem_address & ~page_mask)
);

if(mem_pointer == MAP_FAILED)
{
// Error
}

virt_addr = (mem_pointer + (mem_address & page_mask));

At the end of this code, if no errors occurred, you have a pointer virt_addr to the physical memory space from address 0x10001234 to 0x10001334. You can use this pointer in read/write mode but be very carefully since an incorrect modify to some critical memory section will crash the system.


参考资料:

  1. Access physical memory from Linux user space
  2. /dev/mem可没那么简单