tmytのらくがき

個人の日記レベルです

Win32で自己書き換え

http://f4.aaa.livedoor.jp/~madprog/doc/self-mod.html

らしいですよ。


例によって例のごとくPascalで実践

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private 宣言 }
  public
    { Public 宣言 }
  end;

  TFunc = function (i: Integer): Integer;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function funcA(i: Integer): Integer;
begin
  Result := i * 2;
end;

function funcB(i: Integer): Integer;
begin
  Result := i * 4;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  pfA: Pointer;
  fA: TFunc;
  oldData: array [0..5] of Byte;
  oldProtect: DWORD;
begin
  pfA := @funcA;
  fA := pfA;

  // 自己書き換え
  CopyMemory(@oldData[0], pfA, 6);
  VirtualProtect(pfA, 6, PAGE_WRITECOPY, oldProtect);
  PByte(Integer(pfA)+0)^ := $ff;
  PByte(Integer(pfA)+1)^ := $25;
  PInteger(Integer(pfA)+2)^ := Integer(pfA);

  VirtualProtect(pfA, 6, PAGE_EXECUTE, oldProtect);

  FlushInstructionCache(GetCurrentProcess, pfA, 6);

  ShowMessage(IntToStr(fA(10)));
end;

end.


まぁなんだかうまくいかないんだけどね。