How to correctly dispose of injected DLL thread?

2019-08-04 07:12发布

问题:

I'm injecting a DLL into a target process to act as a helper while playing an MMORPG (currently functionality converts key press into mouse clicks, as the MMORPG requires the user to move their mouse for certain functionality, something I despise.)

Let's say I want to uninject my DLL for whatever reason, how would I go about it? Is this method clean?

bool running = true;
while (running) // This is the only thread I'm using, and it is running in "realtime"
{
    // Do keyboard handing stuff in switch statement
    case keys.EscapeKey: // If the escape key is pressed
        running = false; // Set the running bool to false, and break the loop
        break;
}

Is this clean? The thread ends, so does my dll "uninject" itself? Or does it still loiter and continue to consume the memory that I allocated when injecting?

Thanks Josh

回答1:

I assume that you used CreateRemoteThread with a start address set to LoadLibrary, and that you start a thread in the DllMain of the injected DLL.

First, in DllMain DLL_PROCESS_ATTACH save in a global variable the HMODULE of the DLL.

Second, pass this HMODULE to FreeLibraryAndExitThread when you want your thread to exit and unload the Dll.

Beware! you must NOT have "living code" left behind you, that is, no callback address passed to whatever API, if the callback is trigered after the unload, that will be immediate crash (or worse).



回答2:

Basically Dll will auto detach from process when it's main thread ends unless you send it to an infinite loop, so yes you do it right

You can put a MessageBox in DLL_PROCESS_DETACH event to see that if it get called or not