How can I calculate the members "SizeOfImage" and "SizeOfHeaders" belonging to the PE Optional Header?
I want to remove the debug section of my executables compiled with DigitalMars;that's why I
need some infos.Could somebody demonstrate the calculations on a real

Posted on 2003-03-25 10:06:01 by Vortex
	invoke	CreateFile, ADDR szInputFile, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0

mov [hFile], eax
invoke GetFileSize, eax, 0 ; get the size
mov [dwFileSize], eax
invoke GlobalAlloc, GMEM_MOVEABLE, eax ; allocate memory needed
mov [hMemory], eax
invoke GlobalLock, eax ; lock the allocated memory
mov [dwFile], eax
invoke ReadFile, [hFile], eax, [dwFileSize], esp, 0 ; read the file

push esi
push edi
push ebx
; check for the file for validity
mov esi, [dwFile]
; check the standard EXE header (MZ)
cmp word ptr [esi], "ZM"
jne @@done
; jump to the new PE header
add esi, [esi][IMAGE_DOS_HEADER.e_lfanew]
; check the PE header signature
cmp word ptr [esi], "EP"
jne @@done
; initialize registers
movsx ecx, [esi][IMAGE_NT_HEADERS.FileHeader.NumberOfSections]
mov edi, esi
add esi, [IMAGE_NT_HEADERS.OptionalHeader]
add edi, sizeof IMAGE_NT_HEADERS
@@sect: push ecx
push edx
;jz @@nocr
; pad the section's VirtualSize (size when its loaded) to the next section's start
mov eax, [edi][sizeof IMAGE_SECTION_HEADER][IMAGE_SECTION_HEADER.VirtualAddress]
test eax, eax
jz @@nocr ; no section to padd it up to
sub eax, [edi][IMAGE_SECTION_HEADER.VirtualAddress]
mov [edi][IMAGE_SECTION_HEADER.Misc.VirtualSize], eax
@@nocr: xor edx, edx
mov eax, [edi][IMAGE_SECTION_HEADER.Misc.VirtualSize]
div [esi][IMAGE_OPTIONAL_HEADER.SectionAlignment] ; make sure VirtualSize is a multiple of SectionAlignment
test edx, edx
.if !zero? ; round up VirtualSize to the SectionAlignment
sub edx, [esi][IMAGE_OPTIONAL_HEADER.SectionAlignment]
neg edx
add [edi][IMAGE_SECTION_HEADER.Misc.VirtualSize], edx
pop edx
add edx, [edi][IMAGE_SECTION_HEADER.Misc.VirtualSize]
; next section (if there are any)
pop ecx
add edi, sizeof IMAGE_SECTION_HEADER
dec ecx
jnz @@sect

; correct SizeOfImage in the OptionalHeader (all sections' correct VirtualSize + rounded up SizeOfHeaders to SectionAlignment)
push edx
mov edi, [dwFile]
add edi, [edi][IMAGE_DOS_HEADER.e_lfanew]
xor edx, edx
mov eax, [edi][IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeaders]
div dword ptr [edi][IMAGE_NT_HEADERS.OptionalHeader.SectionAlignment]
test edx, edx
.if !zero? ; pad the SizeOfHeaders to the SectionAlignment, but do not store it
sub edx, [edi][IMAGE_NT_HEADERS.OptionalHeader.SectionAlignment]
neg edx
pop eax
add eax, edx
; save our new SizeOfImage
mov [edi][IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage], eax

invoke CreateFile, ADDR szOutputFile, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0
mov [hFileOut], eax
invoke WriteFile, eax, [dwFile], [dwFileSize], esp, 0
invoke CloseHandle, [hFileOut]
pop ebx
pop edi
pop esi
Posted on 2003-03-25 20:56:00 by comrade