I wrote this function to inject DLL into running process:
DLL_Results CDLL_Loader::InjectDll()
{
DWORD ThreadTeminationStatus;
LPVOID VirtualMem;
On 32-bit systems, the value of ThreadTeminationStatus
after GetExitCodeThread
contains the return value of LoadLibraryA
in the remote process.
This is the module handle of the newly loaded dll.
You can use it as the parameter to FreeLibrary
in the remote thread.
If you want to use the code on 64-bit Windows, the thread exit code is truncated to a 32-bit DWORD
, so it's unusable.
You have to create a callable routine in the remote process (as Necrolis suggested) or resort to finding the module base of the DLL via psapi or the Toolhelp API (CreateToolhelp32Snapshot
, Module32First
, Module32Next
).
You need to pass it the HANDLE
of the dll you injected, else you can pass it VirtualMem
but then your remote thread routine would need to be:
DWORD WINAPI UnloadDll(void* pMem)
{
FreeLibrary(GetModuleHandleA((const char*)pMem));
return 0;
}
However, generally the dll you inject should unload itself (see how DllMain works), either manually or automatically when the host is closed.