从内存文件中搜索指针环

/*
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值