2005. augusztus 22., hétfő

How to determine the size of an executable from its exe header


Problem/Question/Abstract:

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.

{$IFDEF VER100}

{TImageDosHeader isn't defined in Delphi 3 so here's an an abbreviated structure definition}
type
  PImageDosHeader = ^TImageDosHeader;
  TImageDosHeader = packed record
    e_ignore: packed array[0..29] of WORD;
    _lfanew: Longint;
  end;

{$ENDIF}

function GetExeSize: cardinal;
var
  p: PChar;
  i, NumSections: integer;
begin
  result := 0;
  {hInstance is actually a pointer to the exe's image base in memory}
  p := pointer(hinstance);
  inc(p, PImageDosHeader(p)._lfanew);
  inc(p, sizeof(dword));
  NumSections := PImageFileHeader(p).NumberOfSections;
  inc(p, sizeof(TImageFileHeader) + sizeof(TImageOptionalHeader));
  for i := 1 to NumSections do
  begin
    with PImageSectionHeader(p)^ do
      if PointerToRawData + SizeOfRawData > result then
        result := PointerToRawData + SizeOfRawData;
    inc(p, sizeof(TImageSectionHeader));
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése