How do I auto-delete, my Delphi program? I tried this code:
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;
But it does not work, do not delete the file. My program is console. Thanks!
Your code only will work under Windows NT and 2000. Because in these OSs the system keeps a usermode handle reference to the memory mapped file which backs the executable image on disk. This handle always has a value 0x4 in these Windows versions.
The most effective way to delete your own exe, is creating a child process in suspended state, inject the code to wait for the parent process (the exe to delete) , then detect when the parent process exits, delete the parent process and finally kill the child process.
You can found more about this topic in these recommendded resources.
Self deleting executables
Ranju. V.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With