日期:2014-05-16 浏览次数:20908 次
#include <stdio.h>
#include <mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/io.h>
#include <stdlib.h>
//memory dump
//: dump memory ranging from addr to len+addr-1 do a file
//: memdump addr len filename
void main(unsigned char argc, unsigned char *argv[]) {
int fd;
FILE * outfile;
off_t addr;
off_t len=256;
char filename[256]="memdumpout.bin";
off_t startaddr;
off_t offset;
int numpages;
size_t size=0x1000; //4k is page size of mem
off_t mapped_startaddr;
// Test first if arguments are OK
// first argument is executable name, which must be "memdump"
if(strcmp(argv[0],"memdump")!=0)
return -1;
// OK, we support default len=256 and filename $PWD/memdumpout.bin
// but addr is a must
if(argc<2||argc>4)
return -2;//Error, Invalid number of parameters
sscanf(argv[2],"%x",&addr);
startaddr=addr&(~(size-1));
offset=addr-startaddr;
numpages=(len+offset-1)/0x1000;
size*=numpages;
if(argc>=3)
sscanf(argv[2],"%d",&len);
if(argc==4)
sscanf(argv[3],"%s",&filename);
if( argc==4) {
sscanf(argv[3],"%x",&len);
outfile=fopen(filename,"wb");
fd=open("/dev/mem",O_RDWR|O_SYNC);
mapped_startaddr=mmap(0,size,PROT_READ|PROT_WRITE, MAP_SHARED,fd,startaddr);
fwrite((unsigned char *)(mapped_staraddr+offset),1,len,outfile);
munmap(mapped_startaddr,size);
fclose(outfile);
close(fd);
}