Use MMAP/dev/MEM to read and write Linux memory
Category:
Linux Kernel
114 reading comments (1)
Favorites
Report
Use hexedit/dev/MEM to display information in all physical memory. Use MMAP to map/dev/MEM, and then directly read and write it to implement kernel operations in the user space.
Below is a sample I wrote
View plain
- # Include <stdio. h>
- # Include <unistd. h>
- # Include <sys/Mman. h>
- # Include <sys/types. h>
- # Include <sys/STAT. h>
- # Include <fcntl. h>
- Int main ()
- {
- Unsigned char * map_base;
- File * F;
- Int N, FD;
- FD = open ("/dev/mem", o_rdwr | o_sync );
- If (FD =-1)
- {
- Return (-1 );
- }
- Map_base = MMAP (null, 0xff, prot_read | prot_write, map_shared, FD, 0x20000 );
- If (map_base = 0)
- {
- Printf ("null pointer! \ N ");
- }
- Else
- {
- Printf ("successfull! \ N ");
- }
- Unsigned long ADDR;
- Unsigned char content;
- Int I = 0;
- For (; I <0xff; ++ I)
- {
- ADDR = (unsigned long) (map_base + I );
- Content = map_base [I];
- Printf ("Address: 0x % lx content 0x % x \ t", ADDR, (unsigned INT) content );
- Map_base [I] = (unsigned char) I;
- Content = map_base [I];
- Printf ("updated address: 0x % lx content 0x % x \ n", ADDR, (unsigned INT) content );
- }
- Close (FD );
- Munmap (map_base, 0xff );
- Return (1 );
- }
In the preceding example, the starting address 0x20000 (physical address) is mapped to 0xff. Then you can operate the memory like an ordinary array.
The output result is as follows:
Address: 0x7f3f95391000 content 0x0 updated address: 0x7f3f95391000 content 0x0
Address: 0x7f3f95391001 content 0x0 updated address: 0x7f3f95391001 content 0x1
Address: 0x7f3f95391002 content 0x0 updated address: 0x7f3f95391002 content 0x2
Address: 0x7f3f95391003 content 0x0 updated address: 0x7f3f95391003 content 0x3
Address: 0x7f3f95391004 content 0x0 updated address: 0x7f3f95391004 content 0x4
...
My testing machine is a 64-bit machine. In this example, the physical address 0x20000 is mapped to the virtual address 0x7f3f95391000.
First, output the content under the current address, and then write a new value.
You can use hexedit/dev/MEM to verify that the new value has been written.
This can be done if you want to process the address allocated by the kernel in user mode. First, use pai_addr = get_free_pages (gfp_kernel, order) to allocate memory, use phy_addr = _ Pa (pai_addr) to obtain the physical address, and then map/dev/MEM with MMAP in the user State, offset is phy_addr, and length is set to 2 ^ order. Now you can read and write the memory allocated by the kernel in user mode.
Note: This operation requires the root permission.