Created
January 10, 2018 08:02
-
-
Save moritz89/e3782343e5ecd8c5c7064a45e9eed8b0 to your computer and use it in GitHub Desktop.
Map physical memory from /dev/mem to user space and print value of memroy location specified in command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cinttypes> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <sys/mman.h> | |
#include <unistd.h> | |
int main(int argc, char *argv[]) { | |
if (argc < 3) { | |
printf("Usage: %s <phys_addr> <offset>\n", argv[0]); | |
return 0; | |
} | |
off_t offset = strtoul(argv[1], NULL, 0); | |
size_t len = strtoul(argv[2], NULL, 0); | |
// Truncate offset to a multiple of the page size, or mmap will fail. | |
size_t pagesize = sysconf(_SC_PAGE_SIZE); | |
off_t page_base = (offset / pagesize) * pagesize; | |
off_t page_offset = offset - page_base; | |
int fd = open("/dev/iomem", O_SYNC); | |
uint8_t* mem = static_cast<uint8_t*>(mmap(NULL, page_offset + len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, page_base)); | |
if (mem == MAP_FAILED) { | |
perror("Can't map memory"); | |
return -1; | |
} | |
size_t i; | |
for (i = 0; i < len; ++i) | |
printf("%02x ", (int)mem[page_offset + i]); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment