#include "stdafx.h" #include <malloc.h> #include <windows.h> LPVOID readPEFile(LPSTR peFile) //LPVOID是一个没有类型的指针 LPSTR",其相当于char*针 { FILE * pFile = NULL; DWORD fileSize = 0; LPVOID pfileBuffer = NULL; pFile = fopen(peFile,"rb"); if(!pFile) { printf("da kai shi bai"); return NULL; } fseek(pFile,0,SEEK_END); fileSize = ftell(pFile); fseek(pFile,0,SEEK_SET); pfileBuffer = malloc(fileSize); if(!pfileBuffer) { printf("内存分配失败"); free(pfileBuffer); fclose(pFile); return NULL; } size_t n = fread(pfileBuffer,fileSize,1,pFile);//写数据到堆栈区 if(!n) { printf("数据读取失败"); free(pfileBuffer); fclose(pFile); return NULL; } fclose(pFile); return pfileBuffer;//返回堆栈的指针 } VOID printNTHeaders() //遍历PE头函数 { //定义PE头结构体指针 LPVOID pfileBuffer = NULL; PIMAGE_DOS_HEADER pDosHeader = NULL; PIMAGE_NT_HEADERS pNTHeader = NULL; PIMAGE_FILE_HEADER pPEHeader = NULL; PIMAGE_OPTIONAL_HEADER32 pOptionHeader = NULL; pfileBuffer = readPEFile("C:\\windows\\system32\\notepad.exe"); //返回堆栈的指针 if(!pfileBuffer) { printf("da kai shi bai"); return; } if(*((PWORD)pfileBuffer) != IMAGE_DOS_SIGNATURE) //先把pFileBuffer转换成PWORD类型的指针 { printf("不是有效的MZ标志\n"); free(pfileBuffer); return; } pDosHeader = (PIMAGE_DOS_HEADER)pfileBuffer; //把pFileBuffer转换成DOS头结构体指针类型 printf("********************DOC头********************\n"); printf("MZ标志:%X\n",pDosHeader->e_magic); printf("PE偏移:%x\n",pDosHeader->e_lfanew); if(*(PWORD)((DWORD)pfileBuffer+pDosHeader->e_lfanew) != IMAGE_NT_SIGNATURE) { printf("不是有效的PE标志\n"); free(pfileBuffer); return; } pNTHeader = (PIMAGE_NT_HEADERS)((DWORD)pfileBuffer+pDosHeader->e_lfanew); printf("********************NT头********************\n"); printf("NT:%x\n",pNTHeader->Signature); pPEHeader = (PIMAGE_FILE_HEADER)(((DWORD)pNTHeader)+4); printf("********************PE头********************\n"); printf("PE:%x\n",pPEHeader->Machine); printf("节的数量:%x\n",pPEHeader->NumberOfSections); printf("SizeOfOptionalHeader:%x\n",pPEHeader->SizeOfOptionalHeader); pOptionHeader = (PIMAGE_OPTIONAL_HEADER32)((DWORD)pPEHeader+IMAGE_SIZEOF_FILE_HEADER);//这里的IMAGE_SIZEOF_FILE_HEADER是二十个字节。 printf("********************OPTIOIN_PE头********************\n"); printf("OPTION_PE:%x\n",pOptionHeader->Magic); printf("sizeofcode=%x\n",pOptionHeader->SizeOfCode); printf("baseofcode=%x\n",pOptionHeader->BaseOfCode); printf("baseofdata=%x\n",pOptionHeader->BaseOfData); printf("imagebase=%x\n",pOptionHeader->ImageBase); printf("sectionalignment=%x\n",pOptionHeader->SectionAlignment); printf("filealignment=%x\n",pOptionHeader->FileAlignment); printf("sizeofimage=%x\n",pOptionHeader->SizeOfImage); printf("sizeofheader=%x\n",pOptionHeader->SizeOfHeaders); printf("checksum=%x\n",pOptionHeader->CheckSum); free(pfileBuffer); } int main(int argc,char* argv[]) { printNTHeaders(); }
标签:printf,pFile,pfileBuffer,节表,PIMAGE,pOptionHeader,DOS,NULL,NT From: https://www.cnblogs.com/cspecialr/p/17224268.html