pe结构学习心得(三)--获取节表信息
// PESectionHeaders.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <time.h>
#include <imagehlp.h>
#pragma comment (lib, "imagehlp.lib")
int _tmain(int argc, _TCHAR* argv[])
{
while (TRUE) {
WCHAR cFile[256] = {0};
printf("Please enter the file name and path:");
wscanf(L"%s",cFile);
HANDLE hFile = NULL;
hFile = ::CreateFile((LPCWSTR)cFile,GENERIC_READ,0,NULL,OPEN_EXISTING,NULL,NULL);
if (hFile == INVALID_HANDLE_VALUE){
printf("Create file failed! (%d).\n\n", GetLastError());
system("pause");
return 0;
}
//创建文件映射
HANDLE hMap = NULL;
hMap = ::CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,0);
if (!hMap){
printf("Create file mapping failed! (%d).\n\n", GetLastError());
system("pause");
return 0;
}
//映射要自己进程的空间
LPVOID pMap = NULL;
pMap = ::MapViewOfFile(hMap,FILE_MAP_READ,0,0,0);
if (!pMap){
printf("Mapping file failed (%d).\n\n", GetLastError());
system("pause");
return 0;
}
//获得DOS头文件指针
PIMAGE_DOS_HEADER pDosHeader = NULL;//DOS头文件
pDosHeader = (PIMAGE_DOS_HEADER)pMap;
//判断DOS头标志 IMAGE_DOS_SIGNATURE 0x5A4D MZ
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE){
printf("Not DOS Header! (%d).\n\n", GetLastError());
system("pause");
return 0;
}
//获得PE头文件指针
PIMAGE_NT_HEADERS pPeHeaders = NULL;//PE头文件
pPeHeaders = (PIMAGE_NT_HEADERS)((LONG)pMap + pDosHeader->e_lfanew);
//判断PE头标志 IMAGE_NT_SIGNATURE 0x00004550 PE00
if (pPeHeaders->Signature != IMAGE_NT_SIGNATURE){
printf("Not PE Header! (%d).\n\n", GetLastError());
system("pause");
return 0;
}
//获得Section头文件指针
PIMAGE_SECTION_HEADER pSectionHeaders = NULL;//Section节区
pSectionHeaders = (PIMAGE_SECTION_HEADER)((LONG)pPeHeaders + sizeof(pPeHeaders->Signature) + sizeof(pPeHeaders->FileHeader) + pPeHeaders->FileHeader.SizeOfOptionalHeader);
//打印节的名称
printf("Section Infomation: (%d)\n",pPeHeaders->FileHeader.NumberOfSections);
printf("---------------------------------------------------------------------------------------------------------------------------------\n");
printf("|Name \t|VirtualAddress\t\t|Misc.VirtualSize\t|SizeOfRawData\t\t|PointerToRawData\t|Characteristics\n");
printf("---------------------------------------------------------------------------------------------------------------------------------\n");
for (int i = 0;i < pPeHeaders->FileHeader.NumberOfSections; i++){
printf("|%s \t|0x%08x\t\t|0x%08x\t\t|0x%08x\t\t|0x%08x\t\t\t|0x%08x\n",
pSectionHeaders->Name,
pSectionHeaders->VirtualAddress,
pSectionHeaders->Misc.VirtualSize,
pSectionHeaders->PointerToRawData,
pSectionHeaders->SizeOfRawData,
pSectionHeaders->Characteristics);
printf("---------------------------------------------------------------------------------------------------------------------------------\n");
pSectionHeaders++;
}
printf("\n");
//关闭打开的句柄,释放资源
::UnmapViewOfFile(pMap);
::CloseHandle(hMap);
::CloseHandle(hFile);
}
system("pause");
return 0;
}
