The following code is written by Gary Nebbett. Gary Nebbett is the author of the Windows NT / 2000 Native API Reference. It is a master of the NT system. The following is analyzed some of his code.
This code is deleted before the Process has not ended.
INT Main (int Argc, char * argv []) {hmodule module = getModuleHandle (0); char buf [max_path]; getModuleFileName (Module, BUF, SIZEOF BUF); CloseHandle (Handle (4)); __ASM {Lea Eax, BUF Push 0 Push 0 Push Eax Push EXITPROCESS PUSH MODULE PUSH Deletefile Push UnmapViewOffile Ret} Return 0;} Now let's take a look at the stack
Offset content 24 0 20 0 16 Offset BUF 12 Address of EXIXTPROCESS 8 MODULE 4 Address of Deletefile 0 Address of unmapViewoffile
Call RET returns to unmapViewoffile, which is part of the offset 0 in the stack. When entering the unmapviewoffile process, the stack is shown in the stack to return the address deletefile and hmodul module. That is to say, return to the entrance of Deletefile after completion. Address. When returning to deletefile, see the address of EXITPROCESS, that is, return address. And parameter EAX, and EAX is the file name of EXE. Buffer. It is returned by getModuleFileName (Module, BUF, SIZEOF BUF) After executing Deletefile, return to the EXITPROCESS function portal. And the parameter is 0 and the return address is also 0.0 is an illegal address. If returned to address 0, it will be wrong. And call EXITPROCESS should not return. This code is exquisite The point is: 1. If there is a handle of the file, the file delete will fail, so CloseHandle (Handle (4)); is a very clever one. Handle4 is the hardcod of the OS, corresponding to the image of EXE. In addition, OS assumes that there is no call to turn off the image section of Handle, and now, the handle is turned off. Deleting a file will release a handle corresponding to the file. 2. Because unmapViewoffile released another handle, The image is released in memory. So, any code behind will not reference any code within the image map address. Otherwise, the OS will report an error. After unmapViewoffile, just not reference the code in any image. 3. Before EXITPROCESS, the EXE file is deleted. That is, the process is still in, and the exe file in the main thread is already gone. (WinNT / 9x protects these Win32 images that are mapped to memory is not deleted. )
Gary Nebbett is one of the top masters of the WIN series platform. You can write this code. Unique way :)
BTW, this article did not receive the consent of Lu Lin before reposting, I am sorry here. But you have to say it with everyone, the content in his homepage is really good, like to study the low-level friends should go see lu0.126.com