用Delphi内联汇编获取机器码

点击下载演示工程

用Delphi内联汇编获取机器码

可以用Ollydbg打开程序对照一下机器码是否取对,如下图:

用Delphi内联汇编获取机器码

unit Unit1;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls;



type

  TForm1 = class(TForm)

    Button1: TButton;

    Edit1: TEdit;

    Memo1: TMemo;

    procedure Button1Click(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

type

    pFunction=function():Integer;

var

  Form1: TForm1;

  function code():Integer;

  function codeEnd():Integer;



implementation



{$R *.dfm}

function code():Integer;

var

  i,j,k:Integer;

begin

      i:=10;

      j:=50;

      k:=i+j;

      result:=k;

end;

function codeEnd():Integer; begin

end;



procedure TForm1.Button1Click(Sender: TObject);

var

  func1,func2,func3:pFunction;

  myCode:array of char;

  codeSize:Integer;

  i:Integer;

begin

      ASM

         PUSH EAX;

         PUSH EBX;

         LEA EAX,codeEnd; {获取codeEnd函数的地址}

         LEA EBX,code;    {获取code函数的地址}

         SUB EAX,EBX;     {用codeEnd函数的地址减code函数的地址则可得出code函数的}

                          {大小,因为codeEnd函数刚好位于codeEnd函数的下面。}

         MOV codeSize,EAX;{把code函数的大小保存在变量codeSize中}

         POP EBX;

         POP EAX;

      END;

      SetLength(myCode,codeSize);

      {下面这段如看不明白请参考我的另一篇文章}

      {http://www.cnblogs.com/JiangHuakey/archive/2010/09/25/1834378.html}

      ASM

         PUSH ESI;

         PUSH EDI;

         CLD;

         LEA ESI,byte ptr[code];

         MOV EDI,myCode;

         MOV ECX,codeSize;

         REP MOVSB;

         POP EDI;

         POP ESI;

      END;

      for i:=0 to HIGH(myCode)-1 do begin

          Memo1.Text:=Memo1.Text+Format('$%x',[Integer(myCode[i])]);

      end;

      func3:=pFunction(myCode);

      i:=func3;

      Edit1.Text:=IntToStr(i);

end;



end.



 

你可能感兴趣的:(Delphi)