Author: Jonas Bilinkevicius
How to determine the size of an executable from its exe header
Answer:
This code does not work with 16 bit executables. It assumes that the application is
trying to find the size of itself, but could easily be modified to find the size of
any 32bit exe loaded into a stream.
1 {$IFDEF VER100}2 3 {TImageDosHeader isn't defined in Delphi 3 so here's an an abbreviated structure 4 definition}5 type6 PImageDosHeader = ^TImageDosHeader;
7 TImageDosHeader = packedrecord8 e_ignore: packedarray[0..29] of WORD;
9 _lfanew: Longint;
10 end;
11 12 {$ENDIF}13 14 function GetExeSize: cardinal;
15 var16 p: PChar;
17 i, NumSections: integer;
18 begin19 result := 0;
20 {hInstance is actually a pointer to the exe's image base in memory}21 p := pointer(hinstance);
22 inc(p, PImageDosHeader(p)._lfanew);
23 inc(p, sizeof(dword));
24 NumSections := PImageFileHeader(p).NumberOfSections;
25 inc(p, sizeof(TImageFileHeader) + sizeof(TImageOptionalHeader));
26 for i := 1 to NumSections do27 begin28 with PImageSectionHeader(p)^ do29 if PointerToRawData + SizeOfRawData > result then30 result := PointerToRawData + SizeOfRawData;
31 inc(p, sizeof(TImageSectionHeader));
32 end;
33 end;