PE 合并节
前言:这将近半年准备大二专升本考试,在前几天终于考完了,不管好还是坏,等下个月初出成绩吧,自己现在就开始先复习知识点先
2021.5.20 反馈下 湖州学院-计科
先开始复习的是PE,在PE的学习中忘记了写PE的合并节,所以这里重新写下
void MerageSection(PVOID pFileBuffer,PDWORD OldBufferSize,PVOID* pNewBuffer){
PIMAGE_DOS_HEADER pImageDosHeader = NULL;
PIMAGE_FILE_HEADER pImageFileHeader = NULL;
PIMAGE_OPTIONAL_HEADER32 pImageOptionalHeader = NULL;
PIMAGE_SECTION_HEADER pImageSectionHeaderGroup = NULL;
PIMAGE_SECTION_HEADER NewSec = NULL;
DWORD dwSectionAlignmentSizeOfHeaders = 0;
DWORD dwMaxSizeOfRawDataOrVirtualSize = 0;
int i = 0;
*pNewBuffer = (PVOID)malloc(*OldBufferSize);
memset(*pNewBuffer, *OldBufferSize, 0);
memcpy(*pNewBuffer, pFileBuffer, *OldBufferSize);
pImageDosHeader = (PIMAGE_DOS_HEADER)*pNewBuffer;
pImageFileHeader = (PIMAGE_FILE_HEADER)((DWORD)pImageDosHeader + pImageDosHeader->e_lfanew + 4);
pImageOptionalHeader = (PIMAGE_OPTIONAL_HEADER32)((DWORD)pImageFileHeader + sizeof(IMAGE_FILE_HEADER));
pImageSectionHeaderGroup = (PIMAGE_SECTION_HEADER)((DWORD)pImageOptionalHeader + pImageFileHeader->SizeOfOptionalHeader);
/*
1、拉伸到内存
2、将第一个节的内存大小、文件大小改成一样
Max = SizeOfRawData>VirtualSize?SizeOfRawData:VirtualSize
SizeOfRawData = VirtualSize = 最后一个节的VirtualAddress + Max - SizeOfHeaders内存对齐后的大小
3、将第一个节的属性改为包含所有节的属性
4、修改节的数量为1
*/
dwSectionAlignmentSizeOfHeaders = ((pImageOptionalHeader->SizeOfHeaders%pImageOptionalHeader->SectionAlignment)+1)*pImageOptionalHeader->SectionAlignment;
dwMaxSizeOfRawDataOrVirtualSize = pImageSectionHeaderGroup[pImageFileHeader->NumberOfSections-1].SizeOfRawData
> pImageSectionHeaderGroup[pImageFileHeader->NumberOfSections-1].Misc.VirtualSize
? pImageSectionHeaderGroup[pImageFileHeader->NumberOfSections-1].SizeOfRawData
: pImageSectionHeaderGroup[pImageFileHeader->NumberOfSections-1].Misc.VirtualSize;
printf("%x\n", dwMaxSizeOfRawDataOrVirtualSize);
printf("%x\n", pImageSectionHeaderGroup[pImageFileHeader->NumberOfSections-1].VirtualAddress
+ dwMaxSizeOfRawDataOrVirtualSize - dwSectionAlignmentSizeOfHeaders);
pImageSectionHeaderGroup[0].SizeOfRawData = pImageSectionHeaderGroup[pImageFileHeader->NumberOfSections-1].VirtualAddress
+ dwMaxSizeOfRawDataOrVirtualSize - dwSectionAlignmentSizeOfHeaders;
pImageSectionHeaderGroup[0].Misc.VirtualSize = pImageSectionHeaderGroup[pImageFileHeader->NumberOfSections-1].VirtualAddress
+ dwMaxSizeOfRawDataOrVirtualSize - dwSectionAlignmentSizeOfHeaders;
for(i=1;i<pImageFileHeader->NumberOfSections;i++){
pImageSectionHeaderGroup[0].Characteristics |= pImageSectionHeaderGroup[i].Characteristics;
}
pImageFileHeader->NumberOfSections = 1;
}