Search code examples
delphiexedisassemblyportable-executableentry-point

EntryPoint, Pointer and Disassembling by means of a TDisAsm instance


Using DisAsm32 by Russell Libby, disassembling a procedure/function/method is just a matter of passing a (consistent) Pointer to the procedure TDisAsm.Disassemble(Address: Pointer; Size: Cardinal = 0);.

So far, I have managed to disassemble any arbitrary procedure/method, even from a loaded external module (BPL/DLL) provided they are appropriately exported.

From the current process (The EXE image loaded by windows loader), I want to get a valid pointer to the entrypoint.

I want to come up with something akin to IDR (Interactive Delphi Compiler) provides through it's Code Viewer Tab but from the Exe running instance itself.

enter image description here

How can it be done? I'm not very comfortable with PE structures for the time being (but I am striving to, trust me) and wonder wether they are relevant for the purpose.


Solution

  • My own answer:

    I came up with the working solution as follows

    function TForm1.GetEntryPoint: Pointer;
    var
      DosHeader: PImageDosHeader;
      NtHeaders : PImageNtHeaders;
      OptionalHeader: PImageOptionalHeader;
    begin
      DosHeader := PImageDosHeader(HInstance + 0);
      NtHeaders := PImageNtHeaders(HInstance + Cardinal(DosHeader^._lfanew));
      OptionalHeader := PImageOptionalHeader(Cardinal(NtHeaders) + SizeOf(DWORD) + IMAGE_SIZEOF_FILE_HEADER);
      //
      Result := Pointer(HInstance + OptionalHeader^.AddressOfEntryPoint);
    end;
    

    Side Note:

    SysInit.HInstance is the same as System.MainInstance: My preference goes for it as it sounds more C/C++ and find that more meaningfull for the case.

    DisAsm32 goes beyond the call @Halt0 instruction when disassembling from the EntryPoint: It is designed to disassemble function/procedure/method and considers a ret instruction as the end.

    The moral of it:

    I will look for other more appealing disassembler such as BeaEngine and will keep the ball rolling.