How to unload an injected DLL from target process, from the DLL when done?
-
23-06-2021 - |
Question
I have a DLL that injects itself using the CreateRemoteThread/LoadLibrary method.
It is cumbersome to quit the target application and restart it (it has a loading time of 10-20 seconds) when debugging and developing the DLL, so I want to unload the DLL when I have checked that what my code does works, to recompile / re-inject it.
I want to avoid creating a new DLL with a framework for loading and unloading said DLL.
How is this possible?
Solution
In the case where DllMain spawns a thread, and when that thread is complete with whatever it is doing, you can use FreeLibraryAndExitThread:
The FreeLibraryAndExitThread function allows threads that are executing within a DLL to safely free the DLL in which they are executing and terminate themselves. If they were to call FreeLibrary and ExitThread separately, a race condition would exist. The library could be unloaded before ExitThread is called.
From that quote, I state in plain english that you should not call this function from within DllMain.