读取的字段都是一样的,只是一个直接从PE文件中读取,一个映射到内存后再读取
1.文件直接访问法
[cpp] view plain copy
- BOOL ReadOEPByFile(LPCTSTR szFileName)
- {
- HANDLE hFile;
- hFile=CreateFile(szFileName,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,0);
- if (INVALID_HANDLE_VALUE==hFile)
- {
- AfxMessageBox(_T("打开文件失败!"));
- return FALSE;
- }
- DWORD dwOEP,cbRead;
- IMAGE_DOS_HEADER dos_header[sizeof(IMAGE_DOS_HEADER)];//IMAGE_DOS_HEADER dos_header[1];
- if (!ReadFile(hFile,dos_header,sizeof(IMAGE_DOS_HEADER),&cbRead,NULL))
- {
- AfxMessageBox(_T("读取DOS头部失败!"));
- CloseHandle(hFile);
- return FALSE;
- }
- int nEntryPos=dos_header->e_lfanew+40;
- SetFilePointer(hFile,nEntryPos,NULL,FILE_BEGIN);
- if (!ReadFile(hFile,&dwOEP,sizeof(dwOEP),&cbRead,NULL))
- {
- CloseHandle(hFile);
- return FALSE;
- }
- CloseHandle(hFile);
- CString strOEP;
- strOEP.Format(_T("OEP:0x%X"),dwOEP);
- AfxMessageBox(strOEP);
- return TRUE;
- }
2.通过内存映射读取
[cpp] view plain copy
- BOOL ReadOEPByMemory(LPCTSTR szFileName)
- {
- HANDLE hFile;
- HANDLE hMapping;
- PVOID pBaseAddr;
- if ((hFile=CreateFile(szFileName,GENERIC_READ,FILE_SHARE_READ,
- 0,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,0))==INVALID_HANDLE_VALUE)
- {
- AfxMessageBox(_T("打开文件失败!"));
- return FALSE;
- }
- //创建内存映射文件
- if (!(hMapping=CreateFileMapping(hFile,0,PAGE_READONLY|SEC_COMMIT,0,0,0)))
- {
- AfxMessageBox(_T("Mapping failed."));
- CloseHandle(hFile);
- return FALSE;
- }
- //把文件映像存入pBaseAddr
- if (!(pBaseAddr=MapViewOfFile(hMapping,FILE_MAP_READ,0,0,0)))
- {
- AfxMessageBox(_T("View Failed."));
- CloseHandle(hMapping);
- CloseHandle(hFile);
- return FALSE;
- }
- IMAGE_DOS_HEADER *dos_header=(IMAGE_DOS_HEADER *)pBaseAddr;
- IMAGE_NT_HEADERS *nt_header=(IMAGE_NT_HEADERS *)((DWORD)pBaseAddr+dos_header->e_lfanew);
- DWORD dwOEP=nt_header->OptionalHeader.AddressOfEntryPoint;
- //清除内存映射和关闭文件
- UnmapViewOfFile(pBaseAddr);
- CloseHandle(hMapping);
- CloseHandle(hFile);
- CString strOEP;
- strOEP.Format(_T("OEP:0x%X"),dwOEP);
- AfxMessageBox(strOEP);
- return TRUE;
- }
第二种方法要注意DOS STUP与PE头不一定是紧挨着的,一定要通过(DWORD)pBaseAddr+dos_header->e_lfanew定位到IMAGE_NT_HEADERS
如果还要读入口点的代码或其它东西,把PAGE_READONLY|SEC_COMMIT换成PAGE_READONLY|SEC_COMMIT|SEC_IMAGE会给你带来很大的便利
谢谢列宁。