/*
Author: Xhao
function: 取出内存中的环
Algorithm:
从0开始为当前地址,直到文件尾,取出当前位置的值
loop:
如果小于当前位置,则当前位置无环(即使有环,前面位置中也已经取过了)
如果大于当前位置,则以取出的值为新位置继续向前搜索,goto loop
如果等于当前位置,则当前位置有环
Notice:
1.地址超过filesize - 4;
2.当前位置指向的后面的地址中产生环;
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
//取出infile文件在addr位置上的值,取4Byte
unsigned int getvalue(unsigned int addr, ifstream &infile)
{
unsigned int value;
infile.seekg(addr);
infile.read((char*)&value, sizeof(value));
return value;
}
int main(int argc, char ** argv)
{
// 第一个命令行参数必须为输入文件,第二个为结果输出文件
if (argc != 3)
{
puts("Please input intfile and outfile!");
return -1;
}
// 打开输入文件
ifstream infile(argv[1], ios::in | ios::binary);
ofstream outfile(argv[2], ios::out);
// ifstream infile("f:\\mem\\xp_whole_memory", ios::in | ios::binary);
// ofstream outfile("f:\\mem\\result.txt", ios::out);
unsigned int address, current, value;
infile.seekg(0, ios::end);
long long filesize = infile.tellg(); //输入文件的大小,单位:Byte
int RingCount = 0; //环的个数
cout << "Input file size: 0x" << hex << filesize << " Byte" << endl;
for (address = 0x00000000; address < filesize - 4; address += 4)
{
current = address;
vector<unsigned int> addrarray; //保存当前位置开始的指针链
while (true)
{
value = getvalue(current, infile);
if (value < address || value > filesize - 4) break;
else if (value == address)
{
if (getvalue(address, infile) != address) //指向自己的指针就不保存了
{
cout << "Ring " << dec << ++RingCount << " found: " << endl << "0x" << hex << address;
outfile << "Ring " << dec << RingCount << " found: " << endl << "0x" << hex << address;
int RingSize = 1; //环内指针个数
unsigned loop = getvalue(address, infile);
while (loop != address) //打印环
{
cout << " -> 0x" << hex << loop;
outfile << " -> 0x" << hex << loop;
loop = getvalue(loop, infile);
++RingSize;
}
cout << endl << "Ring Size: " << dec << RingSize << endl << endl;
outfile << endl << "Ring Size: " << dec << RingSize << endl << endl;
}
break;
}
else
{
if (find(addrarray.begin(), addrarray.end(), value) != addrarray.end()) break; //如果是在当前位置的后面产生环(环不包括当前位置),就暂且不管
current = value;
addrarray.push_back(current);
}
}
if ((address & 0xffff) == 0) cout << "Compute to 0x" << hex << address << " ..." << endl; //看看程序的运行进度
// cout << "Compute to 0x" << hex << address << " ..." << endl;
}
system("PAUSE");
return 0;
}
从内存文件中搜索指针环
最新推荐文章于 2023-03-11 21:18:13 发布