PE解析之一、判断一个文件是否为PE文件(已经更新到PE解析之二)
程序代码:
#include <stdio.h> #include <windows.h> //内存映像结构 typedef struct _MAP_FILE_STRUCT { HANDLE hfile; HANDLE hmapping; LPVOID imagebase; } MAP_FILE_STRUCT; //判断是否是一个pe文件 BOOL ispefile(LPVOID imagebase) { PIMAGE_DOS_HEADER pdh=NULL; PIMAGE_NT_HEADERS pnth=NULL; if(!imagebase) return FALSE; pdh=(PIMAGE_DOS_HEADER)imagebase; if(pdh->e_magic!=IMAGE_DOS_SIGNATURE) return FALSE; pnth=(PIMAGE_NT_HEADERS32)((DWORD)pdh+pdh->e_lfanew); if(pnth->Signature !=IMAGE_NT_SIGNATURE) return FALSE; return TRUE; } //主程序入口处//使用命令行参数获取待检测的pe文件名 int main(int argc,char *argv[]) { if (argc<2) return 0; //使用createfile、createfilemapping 、MapViewOfFile获取imagebase HANDLE hFile = CreateFile(argv[1],GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL,OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN,NULL); if (hFile == INVALID_HANDLE_VALUE) { printf("创建文件对象失败,错误代码:%d ", GetLastError()); return 0; } HANDLE hFileMapping = CreateFileMapping(hFile,NULL,PAGE_READONLY, 0, 0, NULL); if (hFileMapping == NULL) { DWORD dw=GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,NULL,dw,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR) &lpMsgBuf,0, NULL); wsprintf(szBuf,("%s 出错信息 (出错码=%d): %s"),("CreateFileMapping"), dw, lpMsgBuf); printf("%s",szBuf); LocalFree(lpMsgBuf); return 0; } LPVOID lpMemory = MapViewOfFile(hFileMapping,FILE_MAP_READ,0, 0, 0); if (lpMemory==NULL) { printf("创建文件视图对象失败,错误代码:%d ", GetLastError()); return 0; } if(!ispefile(lpMemory)) printf("%s不是一个有效的pe文件\n",argv[1]); else printf("%s是一个有效的PE文件\n",argv[1]); // 释放文件内核对象 UnmapViewOfFile(lpMemory); CloseHandle(hFileMapping); CloseHandle(hFile); return 0; }
[ 本帖最后由 wp231957 于 2012-11-29 18:01 编辑 ]