本帖最后由 52_pojie_52 于 2024-4-27 10:47 编辑
最近学习pe文件格式,感觉比较难记忆,用C++写几个小程序帮助理解
pe dump程序的代码如下:
#include <iostream>
#include <bitset>
#include <cstddef>
#include <fstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(int argc, char* argv[]) {
/*--------------- read args --------------------*/
if (2!=argc) {
cout<<"please input one file name"<<endl;
exit(1);
}
/*--------------- open file --------------------*/
char* filename=argv[1];
ifstream infile(filename, ios::binary | ios::in);
if (! infile) {
cerr << "open failed" << endl;
exit(1);
}
/*--------------- read file --------------------*/
// get length of file
infile.seekg(0,infile.end); // seek to end of stream
int fileLen=infile.tellg(); // length of stream
infile.seekg(0,infile.beg); // need go back the begin of stream or read error
unsigned char * bin = new unsigned char[fileLen];
infile.read((char*)bin, fileLen);
infile.close();
if (!infile.good()) {
cout<<"error occurred at read time"<<endl;
exit(1);
}
/*--------------- dump file --------------------*/
// open file
ofstream outfile;
outfile.open("pedump.txt", ios::out | ios.trunc);
// print title
outfile << hex << setiosflags(ios::uppercase); // set hex base,just need set only once at the begin
outfile << setfill('0'); // fill with 0
outfile << "Address ";
int i=0;
for (i=0; i<0x10; i++) {
outfile << setfill('0') << setw(2) << i << " ";
}
outfile << " " << "ASCII"<<endl;
// dump data
int row = 0, rowEnd=ceil((float)fileLen/0x10);
for (row=0; row < rowEnd; row++) {
// 1. print addr
int col=0;
outfile << setw(8) << row * 0x10 << " ";
// 2. dump byte data
for (col=0; col<0x10; col++) {
if ((row * 0x10 + col)<fileLen) {
outfile << setw(2) << (int)bin[row * 0x10 + col];
if (7==col) {
outfile << '-';
} else {
outfile << ' ';
}
} else {
outfile << " ";
}
}
outfile << " ";
// 3. print ascii
char c;
for (col=0; col<0x10; col++) {
if ((row * 0x10 + col)<fileLen) {
c=bin[row*0x10+col];
// dont print 0x00-0x1f
if ((int)c>=0x20) {
outfile << c;
} else {
outfile<<'.';
}
} else {
outfile << ' ';
}
if (7==col) {
outfile<<' ';
}
}
outfile<<endl;
}
outfile.close();
return 0;
}
主要代码说明都在注释里了,主要思路就是:
- 输入参数(文件名)
- 打开pe文件
- 读取文件内容到文件流
- 打开要输出的文件
- 第一行打印“Address”、00-0F、”ASCII“几个title
- 后面按一行16个字节来打印:左侧一栏是address、中间是16个字节(转成了16进制大写),右侧是对应的ASCII码(0x00-0x1F的ASCII码是控制字符,所以都改成了'.')
|