Inject 1 - OK.
Inject 2 - Crash.
If I restart the test app, it works fine again.
For it to work, I need to unload the DLL from the test app I hooked it into.
The crash is difficult to find.
Essentially, I do this:
First, inject the DLL with the hooking app:
Code:
const char strDll[] = "G:\\w00t\\Visual Studio 2005\\Projects\\Hooking\\Application\\Debug\\ThreadSpy.dll";
Stuff::ProcessVector pProcesses = Stuff::EnumerateProcesses();
for (std::vector<int>::size_type i = 0; i < pProcesses->size(); i++)
{
if (_tcscmp(pProcesses->at(i).szExeFile, _T("Hooked App.exe")) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, pProcesses->at(i).th32ProcessID);
CHandle hhProcess(hProcess);
void* pDllMem = VirtualAllocEx(hProcess, NULL, sizeof(strDll), MEM_COMMIT, PAGE_READWRITE);
ASSERT( WriteProcessMemory(hProcess, pDllMem, strDll, sizeof(strDll), NULL) );
typedef DWORD (WINAPI ThreadProc)(void*);
HMODULE hKernel32 = ::GetModuleHandle(_T("Kernel32"));
ThreadProc* pLoadLibrary = (ThreadProc*)GetProcAddress(hKernel32, "LoadLibraryA");
//FreeLibrary(hKernel32);
HANDLE hLoadLibraryThread = CreateRemoteThread(hProcess, NULL, 0, pLoadLibrary, pDllMem, NULL, NULL);
CHandle hhLoadLibraryThrad(hLoadLibraryThread);
WaitForSingleObject(hLoadLibraryThread, INFINITE);
HMODULE hDll;
ASSERT( GetExitCodeThread(hLoadLibraryThread, (DWORD*)&hDll) );
ASSERT( VirtualFreeEx(hProcess, pDllMem, 0, MEM_DECOMMIT) );
MessageBox(_T("App hooked successfully!"), _T("Success!"), MB_ICONINFORMATION);
}
}
Then unload the DLL from within the hooked app:
Code:
HMODULE hHookedDll = GetModuleHandle(_T("ThreadSpy.dll"));
ASSERT( FreeLibrary(hHookedDll) );
Then inject again, and boom - crash.
The crash happens inside CRT's DllInit from what I see. It's a call to GetProcAddress that kills it. I'll keep working on it.
On second notice, I think there's a bug in the hooking code. It seems that it jumps to an invalid address when calling GetProcAddress (which is hooked!). Do I smell the bug here?
The problem is, indeed, as I feared. The stupid thing is not unhooking functions correctly, thus causing crashes when the hooked functions are called and the DLL is unloaded.
And this isn't even my code... Nightmare... >_<
Ah, but application paths can cause so much trouble. It works fine now that I reconfigured the projects and made sure all paths are correct.
The fix didn't work because it was using the wrong build >_<