您的位置:首页 > 编程语言 > Delphi

Self-Delete程序之Delphi版本,终于搞定了

2009-04-29 21:39 323 查看
//转贴者:以前看过陆麟先生翻译过一篇这样的文章,是c版本的,我用delphi改写了没成功,今天去清华bbs转悠看见了这篇delphi版本的,特贴出来
发信人: Litoad (Rick), 信区: Delphi
标 题: Self-Delete程序之Delphi版本,终于搞定了。 (转载)
发信站: BBS 水木清华站 (Mon Jun 4 20:51:55 2001)
【 以下文字转载自 Programming 讨论区 】
发信人: Litoad (Rick), 信区: Programming
标 题: Self-Delete程序之Delphi版本,终于搞定了。
发信站: BBS 水木清华站 (Mon Jun 4 20:50:42 2001)

到Borland的论坛去问了问,确实跟laoduan说得一样,要自己GetProcAddress。代码如下:

uses
Windows;

procedure DeleteSelf;
var
hModule: THandle;
buff:    array[0..255] of Char;
hKernel32: THandle;
pExitProcess, pDeleteFileA, pUnmapViewOfFile: Pointer;
begin
hModule := GetModuleHandle(nil);
GetModuleFileName(hModule, buff, sizeof(buff));

CloseHandle(THandle(4));

hKernel32        := GetModuleHandle('KERNEL32');
pExitProcess     := GetProcAddress(hKernel32, 'ExitProcess');
pDeleteFileA     := GetProcAddress(hKernel32, 'DeleteFileA');
pUnmapViewOfFile := GetProcAddress(hKernel32, 'UnmapViewOfFile');

asm
LEA         EAX, buff
PUSH        0
PUSH        0
PUSH        EAX
PUSH        pExitProcess
PUSH        hModule
PUSH        pDeleteFileA
PUSH        pUnmapViewOfFile
RET
end;
end;

begin
DeleteSelf;
end.


现在有一点比较古怪,那就是必须把代码放在一个Procedure里,直接放在begin ... end.中间是不行的。也许是全局变量不能使用的缘故,但为什么不能使用,还是不是很清楚。还有,不GetProcAddress,直接如下写:
PUSH OFFSET UnmapViewOfFile
trace的结果是执行进入了KERNEL32.UnmapViewOfFile的,只是在函数内RET $4出就出错了,跳到了一个莫名其妙的地方。为什么会这样?难道是Delphi的编译器的问题吗?
另外,Borland论坛上RE的代码不是上面的,不过效果跟我写的一样。但是FreeLibrary(p)跟UnmapViewOfFile(hModule)效果一样吗?

代码如下:

program Project1;
uses
windows;

procedure DeleteSelf;
var
module : HMODULE;
buf : array [ 0 .. MAX_PATH - 1 ] of char;
p : ULONG;
hKrnl32 : HMODULE;
pExitProcess, pDeleteFile, pFreeLibrary : pointer;
begin
module := GetModuleHandle ( nil );
GetModuleFileName ( module, buf, sizeof ( buf ) );
CloseHandle ( THandle ( 4 ) );

p := ULONG ( module ) + 1;
//上面这一句什么意思?

hKrnl32 := GetModuleHandle ( 'kernel32' );
pExitProcess := GetProcAddress ( hKrnl32, 'ExitProcess' );
pDeleteFile := GetProcAddress  ( hKrnl32, 'DeleteFileA' );
pFreeLibrary := GetProcAddress ( hKrnl32, 'FreeLibrary' );

asm
lea eax, buf
push 0
push 0
push eax
push pExitProcess
push p
push pDeleteFile
push pFreeLibrary
ret
end;
end;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: