A small but useful trick: a self-erasing executable. In the MS-DOS days, nobody could be surprised by such a trick: an operating system there allowed to write anything you like, and even delete executable at runtime (hehe). With the advent of Windows, the freedoms ceased. If a file is running, nothing can be done with it before it terminates. However, there is one exception to this rule: so-called batch or bat-files. They are not run as standalone applications but as a set of instructions for a shell processor and therefore can easily delete themselves. We will use this to do our job. Here is an example of a batch file that first tries to remove a file in a given path and then destroys itself.
The check and loop are needed to wait until the file is free and available for elimination. The command del %0 deletes the bat-file, in which it is executed, without reference to its name. Now for our executable to self-delete, it should do the following steps: get the name and path of the executable, generate the bat-file, run it and terminate it. The bat-file will wait for the executable to finish, delete it, then delete itself.
All that remains is to translate the human words into Assembler language. The code is simple enough, I won’t comment on it further.
Let me make one point clear though. Path and filename are converted to DOS short form 8.3 in case it contains any special characters or non-Latin alphabet letters. With normal paths, batch files may not work correctly in this case.
Where can this be used? For good reason, this is how a good uninstaller should work. A good uninstaller should not ask the user to clean up their mess manually, or worse, silently quit, leaving at least the installation directory with the uninstaller file inside. A good uninstaller will thoroughly remove everything behind it, including the uninstaller itself. In this case, the bat-file will have to be supplemented with a command to remove the directory with the program and run it outside this directory. On the dark side of the Force, there are also uses for uninstaller files. For example some spyware program can silently self-destruct after performing its direct tasks in order not to raise the victim’s suspicions and not to leave any samples for investigation.
Attached is an example of such a self-deleting source file. After launching it immediately disappears without giving out any messages or opening any windows.
Example source program (FASM): http://www.manhunter.ru/download/23733/Self.Delete.File.Demo.zip