Jump to content
Nytro

[C] Add a section to an executable

Recommended Posts

BOOL AddSection(char *szFileName,char *szSectionName,DWORD dwDesiredSectionSize){
HANDLE hFile = CreateFile(szFileName,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (hFile == INVALID_HANDLE_VALUE) return FALSE;
DWORD dwFileSize = GetFileSize(hFile,NULL);
BYTE *pByte = new BYTE[dwFileSize];
DWORD dwUseLess;
ReadFile(hFile,pByte,dwFileSize,&dwUseLess,NULL);
IMAGE_DOS_HEADER *pDosHeader = (IMAGE_DOS_HEADER*)pByte;
IMAGE_FILE_HEADER *pFileHeader = (IMAGE_FILE_HEADER*)(pByte + pDosHeader->e_lfanew + sizeof(DWORD));
IMAGE_OPTIONAL_HEADER *pOptionalHeader = (IMAGE_OPTIONAL_HEADER*)(pByte + pDosHeader->e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER));
IMAGE_SECTION_HEADER *pSectionHeader = (IMAGE_SECTION_HEADER*)(pByte + pDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS));
ZeroMemory(&pSectionHeader[pFileHeader->NumberOfSections],sizeof(IMAGE_SECTION_HEADER));
CopyMemory(&pSectionHeader[pFileHeader->NumberOfSections].Name,szSectionName,8);
pSectionHeader[pFileHeader->NumberOfSections].Misc.VirtualSize = round(dwDesiredSectionSize,pOptionalHeader->SectionAlignment,0);
pSectionHeader[pFileHeader->NumberOfSections].VirtualAddress = round(pSectionHeader[pFileHeader->NumberOfSections-1].Misc.VirtualSize,pOptionalHeader->SectionAlignment,pSectionHeader[pFileHeader->NumberOfSections - 1].VirtualAddress);
pSectionHeader[pFileHeader->NumberOfSections].SizeOfRawData = round(dwDesiredSectionSize,pOptionalHeader->FileAlignment,0);
pSectionHeader[pFileHeader->NumberOfSections].PointerToRawData = round(pSectionHeader[pFileHeader->NumberOfSections - 1].SizeOfRawData,pOptionalHeader->FileAlignment,pSectionHeader[pFileHeader->NumberOfSections - 1].PointerToRawData);
pSectionHeader[pFileHeader->NumberOfSections].Characteristics = 0xE00000E0;
SetFilePointer(hFile,pSectionHeader[pFileHeader->NumberOfSections].PointerToRawData + pSectionHeader[pFileHeader->NumberOfSections].SizeOfRawData ,NULL,FILE_BEGIN);
SetEndOfFile(hFile);
pOptionalHeader->SizeOfImage = pSectionHeader[pFileHeader->NumberOfSections].VirtualAddress + pSectionHeader[pFileHeader->NumberOfSections].Misc.VirtualSize;
pFileHeader->NumberOfSections = pFileHeader->NumberOfSections + 1;
SetFilePointer(hFile,0,NULL,FILE_BEGIN);
WriteFile(hFile,pByte,dwFileSize,&dwUseLess,NULL);
CloseHandle(hFile);
return TRUE;
}

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...