基于开源的devmem2
用法:
gcc dump_mem.c -o dump_mem
# 注意内存地址和大小必须是4K对齐
./dump_mem 0x80000000 0x1000
// 修改自开源的 devmem2.c :https://bootlin.com/pub/mirror/devmem2.c
// custom_devmem2 addr size
// 从addr开始,读取size个数据,并判断其值是否为feature_data
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
#define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
__LINE__, __FILE__, errno, strerror(errno)); exit(1); } while(0)
#define MAP_SIZE 4096UL
#define MAP_MASK (MAP_SIZE - 1)
int main(int argc, char **argv) {
int fd;
void *map_base, *virt_addr;
//在arm64上,long代表8个字节
unsigned long read_result, high32, low32;
off_t target;
int access_type = 'w';
size_t size=0;
int offset = 0;
int i=0;
printf("sizeof(unsigned long):%d\n",sizeof( unsigned long));
if(argc < 2) {
fprintf(stderr, "\nUsage:\t%s address size\n"
"\taddress : memory address to act upon\n"
"\tsize : size\n",
argv[0]);
exit(1);
}
target = strtoul(argv[1], 0, 0);
if(argc > 2)
size = strtoul(argv[2], 0, 0);
//每次只能映射4K
int map_time = size / 4096;
int map_count = 0;
printf("rmr addr:0x%llx size:0x%llx map_time:%d\n", target, size, map_time);
if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) FATAL;
printf("/dev/mem opened.\n");
fflush(stdout);
for(map_count = 0;map_count < map_time;map_count++) {
// target = target+map_count*MAP_SIZE;
printf("target:0x%llx %d/%d\r",target, map_count, map_time);
offset=0;
while(offset < MAP_SIZE){
/* Map one page */
//printf("Memory mapped pa:0x%llx at address %p.\n", target & ~MAP_MASK, map_base);
map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, target & ~MAP_MASK);
if(map_base == (void *) -1) FATAL;
fflush(stdout);
virt_addr = map_base + (target & MAP_MASK);
read_result = *((unsigned long *) virt_addr);
high32 = read_result >> 32;
low32 = read_result & 0xFFFFFFFF;
// printf("debug addr:0x%p value:0x%llx offset:0x%x high32:0x%llx low32:0x%llx \n",
// virt_addr, read_result, offset, high32,low32);
for(i=0;i<sizeof(feature_data)/sizeof(unsigned long);i++){
if (high32 == feature_data[i]){
printf("found feature_data:0x%llx at addr:0x%llx map_count:%d offset:0x%llx target:0x%llx\n",
feature_data[i], virt_addr, map_count, offset, target);
}
if (low32 == feature_data[i]){
printf("found feature_data:0x%llx at addr:0x%llx map_count:%d offset:0x%llx target:0x%llx\n",
feature_data[i], virt_addr, map_count, offset, target);
}
}
offset+=8;
target+=8;
if(munmap(map_base, MAP_SIZE) == -1) FATAL;
}
}
virt_addr = map_base + (target & MAP_MASK) + offset;
read_result = *((unsigned long *) virt_addr);
printf("Value at address 0x%X (%p): 0x%X\n", target, virt_addr, read_result);
fflush(stdout);
close(fd);
return 0;
}