Valhalla Legends Forums Archive | C/C++ Programming | LoadLibrary returning NULL - why?

AuthorMessageTime
warz
Well, okay. Maybe I need to specify a full path for LoadLibrary, as apposed to a path relative to the application. My function looks like so...

[code]
bool InjectionClass::InjectLibrary(LPCTSTR className, LPCTSTR library) {
    HINSTANCE hDll = LoadLibrary(library);
if(hDll == NULL) {
MessageBox(NULL, "Bad HINSTANCE", "error", MB_OK);
return false;
}

    HOOKPROC procAddr = (HOOKPROC)GetProcAddress(hDll, "CBTProc");
if(procAddr == NULL) {
MessageBox(NULL, "Bad HOOKPROC", "error", MB_OK);
return false;
}

HWND windowId = FindWindow(className, NULL);
if(windowId == NULL) {
MessageBox(NULL, "Bad HWND", "error", MB_OK);
return false;
}

    SetWindowsHookEx(WH_CBT, procAddr, hDll, GetWindowThreadProcessId(windowId, NULL));
    return true;
}
[/code]

Ofcourse, the call to LoadLibrary is always returning NULL. I'm calling InjectLibrary like this...

[code]
global->inject.InjectLibrary("SWarClass", "host.dll");
[/code]

Yes, host.dll is present. Inside of my host.dll, I have a MessageBox call for debugging purposes, and it's inside of the DLL_PROCESS_ATTACH handling. The message box appears, but LoadLibrary returns NULL. Why?

Also, GetLastError returns ERROR_NOACCESS (998). Invalid access to memory location. Huh? :-P
October 7, 2006, 7:26 AM
Myndfyr
There are a few things you can do to ferret out the root cause of the problem.

1.) Are you trying to load the file in the remote process or the local process?  If it's in the remote process, the DLL has to be in the search path of the remote process.  That is, the remote process's folder, %systemroot%, %systemroot%\system32, %PATH%, and a few others (you can find this search order linked from LoadLibrary() in MSDN). 
2.) If you're sure that your DLL is in the right path, download Filemon from sysinternals and monitor the file that's supposed to be opened.  If it's not showing up, it's either that you don't know where the file is, or you don't have permission to load a DLL into the remote process.

One other thing you can do is to attach to the remote process with a debugger and set a breakpoint on your DllMain's DLL_PROCESS_ATTACH handler.  When the library is loaded, the debugger should break the remote process and you can step through the handler.  It's possible that your DllMain function is trying to do something that's raising an exception that goes unhandled in the DLL, which is causing the DLL to not be successfully mapped into the process, but which would explain why your MessageBox call works.
October 7, 2006, 9:20 AM

Search