How to get function address from loader DLL? - c++

I have got 2 DLLs. DLL1 will be presented as MyDLL.dll and DLL2 is just a DLL containing extensions to MyDLL.
So to get these extensions from DLL2 to MyDLL, I need to load DLL2 inside MyDLL using LoadLibrary(). But here comes the problem. MyDLL contains one function, which will be very important in DLL2. And I need to reach that function. How do I do it?
#include <Windows.h>
#include <stdio.h>
#include "DLL1API.h"
typedef DLL1API* (*PGetDLL1API)();
DLL1API *g_API;
void Init();
BOOL WINAPI DllMain(HINSTANCE hMod, DWORD dwReason, LPVOID reserve){
switch(dwReason){
case DLL_PROCESS_ATTACH:
Init();
break;
}
}
void Init(){
PGetDLL1API GetDLL1API;
HMODULE mainDllMod=GetModuleHandleA("MyDLL.dll"); //how do I reach module of DLL1?
GetDLL1API=(PGetDLL1API)GetProcAddress(mainDllMod,"GetDLL1API");
if(GetDLL1API){
g_API=GetDLL1API();
printf("DLL1API: %p",g_API);
} else { //always gets to this result :(
printf("Error, failed to get GetDLL1API()!\n");
}
}
Other thing is, that I am scared to use LoadLibrary("MyDLL.dll") inside DLL2, because I think it would cause one big infinite loadLibrary loop (MyDll => DLL2 => MyDLL ...)

Calling LoadLibrary from inside DllMain is not recommended. Fix that, and your circular loading concerns will go away as well.
BTW DLL2 doesn't need to load DLL1. It can use GetModuleHandle to find the already-loaded DLL to pass to GetProcAddress, use a static import, or DLL1 can call a function exported from DLL2 passing a function pointer.
More suggested reading, with specific notes on LoadLibrary: http://blog.barthe.ph/2009/07/30/no-stdlib-in-dllmai/

You are right to not want to use LoadLibrary in DllMain. Using LoadLibrary in DllMain is expressly forbidden according to this Microsoft page. Also, GetModuleHandle only works if the DLL has already been loaded by the current process.
Are you really sure you need to load the DLL from your DllMain? You could just call GetModuleHandle from your exported functions, assuming of course that the module has been loaded by the program already.

Related

Why is it CString::LoadString works in the main module(.exe) of my app but will not work in my extensionDLL?

I have this MFC app that loads strings from string resource using CString::LoadString function. Each of the apps dialogue box's classes and its associated resources are contained in an MFC extension DLL.
CString::LoadString loads strings from the main module's(.exe) resource's string resource successfully but fails to load string from the DLL's resource's string resource.
In each case I get my instance handle for load string from CWinApp object by calling :
CWinApp *WinApp = AfxGetApp(),
and of course the instance's handle is WinApp->m_hInstance which I use as the first argument in my call to CString::LoadString function.
What could be the cause and what could be the solution.
Are you passing the EXE's HINSTANCE to load a string from the extension library? Sounds like it.
With MFC, if you have extension libraries and you make sure your string identifiers are unique, you just need to call the CString::LoadString(UINT nID) version. Because extension libraries create CDynLinkLibrary structures that go into a global linked list, the LoadString(UINT) function will search through all your MFC libraries until it finds the HINSTANCE that contains that string, and then it will load from there. If you insist on using the LoadString() function with an HINSTANCE argument, be sure to use the HINSTANCE of the extension DLL, and not the extension of the EXE when you want to load a string or dialog from the DLL.
For small projects, like less than a dozen DLLs, you probably manage to just use unique IDs for everything. When you get into the insanely large projects like 100+ DLLs, then you have to use other techniques like specially named functions in your DLL that call AfxSetResourceHandle() or know to always use the HINSTANCE of the DLL. That's another topic.
Just to complement Joe Willcoxson's answer, be sure to check that every MFC Extension DLL you are using,needs a special initialization code, similar to the example below:
#include "stdafx.h"
#include <afxdllx.h>
static AFX_EXTENSION_MODULE MyExtDLL = { NULL, NULL };
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
TRACE0("MyExt.DLL Initializing!\n");
// Extension DLL one-time initialization
if (!AfxInitExtensionModule(MyExtDLL, hInstance))
return 0;
new CDynLinkLibrary(MyExtDLL);
}
else if (dwReason == DLL_PROCESS_DETACH)
{
TRACE0("MyExt.DLL Terminating!\n");
// Terminate the library before destructors are called
AfxTermExtensionModule(MyExtDLL);
}
return 1; // ok
}
This code just takes care of CDynLinkLibrary creation, the key to share resources between MFC modules.
If all this are setup correctly -- and without ID clashes -- then it's simply a mather of calling:
CString str;
str.LoadString(IDS_MY_STRING_ID);
anywhere in your code, no matter where the string actually persists.
A good start point on resource IDs and numbering can be found in this link.

GetModuleHandle(NULL) vs hInstance

When programming using the Windows API, I've always made the HINSTANCE from WinMain a global variable immediately. If I want to make an OK button, I'd do it like so (given global HINSTANCE g_hInstance):
return CreateWindow("BUTTON", "OK", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 10, 10, 100, 30, exampleParentWindow, EXAMPLECHILDID, g_hInstance, NULL);
but lately I've been seeing the instance handle determined without having to be passed as a parameter or clogging up the global namespace, using a call to GetModuleHandle(NULL)*. So, the example above would look like this:
return CreateWindow("BUTTON", "OK", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 10, 10, 100, 30, exampleParentWindow, EXAMPLECHILDID, GetModuleHandle(NULL), NULL);
*If your compiler supports it, you can write GetModuleHandle(nullptr) and the statement will have the same result.
What's the advantage (if any) of calling GetModuleHandle(NULL) over explicitly specifying the instance handle?
Fine Print: I know this has an answer, but it has not been phrased as its own question on StackOverflow.
In an EXE, it does not make any difference. hInstance from WinMain() and GetModuleHandle(NULL) both refer to the same HINSTANCE (the module of the .exe file). But it does make a difference if you are creating windows inside of a DLL instead, since you have to use the DLL's hInstance but GetModuleHandle(NULL) will still return the HINSTANCE of the EXE that loaded the DLL.
HMODULE WINAPI GetModuleHandle( _In_opt_ LPCTSTR lpModuleName );
Give the module handle of the module name passed.If you are passing NULL, the you get the module handle of the EXE which is currently running.
If you specifically name the module name, you get the module handle of that dll which is mapped to the process address space.
The use is that when you are trying to call a function exported by the dll, or trying to use a dialog template in side that dll.At that time if you use the HMODULE returned form GetMoudleHandle(NULL) your code wont work.
Just to add my two-cents to these answers. In case you need to get the module handle from within a DLL (and don't want to, or can't save it in a global variable from the DllMain call) you can use this function to get it instead:
HMODULE getThisModuleHandle()
{
//Returns module handle where this function is running in: EXE or DLL
HMODULE hModule = NULL;
::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCTSTR)getThisModuleHandle, &hModule);
return hModule;
}
One potential gain you get from using GetModuleHandle(NULL) over directly using the WinMain HINSTANCE comes more from architecture. If you want to provide a platform-independent system that runs on linux/windows/whatever you can have a layer that does platform-dependent translations. If that's the case you don't want platform dependent objects such as HINSTANCE showing up in the main application code. So, to circumvent that platform-dependence I put GetModuleHandle(NULL) in the constructor of the platform-dependent class which has the same effect that direct use of the WinMain HINSTANCE does but that abstracts that specific functionality out of the main codebase itself.

Start Application within a DLL

So I want to create a Dll that contains an application. My code:
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
StartApp();
break;
}
return TRUE;
}
And the StartApp function:
void StartApp()
{
//some declartions
iPtr->Start();
}
The thing is that the function Start() is running in a continuous loop (sth like while(true)) and I think that's the problem cause the dll never gets to break and return true. I tried to run it in a different thread but this isn't working.
So my question is what can I do to use the dll?
Is there a problem if DllMain doesnt finish and doesn't return TRUE?
Yes, there is a problem is DllMain doesn't return, as the documentation states:
When a DLL entry-point function is called because a process is loading, the function returns TRUE to indicate success. For processes using load-time linking, a return value of FALSE causes the process initialization to fail and the process terminates. For processes using run-time linking, a return value of FALSE causes the LoadLibrary or LoadLibraryEx function to return NULL, indicating failure. (The system immediately calls your entry-point function with DLL_PROCESS_DETACH and unloads the DLL.) The return value of the entry-point function is disregarded when the function is called for any other reason.
Source.
You may create a wrapper function for the StartApp function, and expose it via your dll. After that you can call the exported StartApp function from your executable (after you loaded the dll). Make sure you call it from a different thread as it will block.

In MFC APP, if I call "LoadLibraryA" from "InitInstance", it calls "InitInstance" again and again

I have created an MFCApp using VS2008 wizard. Inside my application's "InitInstance()" I'm calling "LoadLibraryA()" method as I need to load a few dll files. But as soon as I call "LoadLibraryA()", it again calls "InitInstance()" of my application and hence it becomes a infinite recursion stuff. Is there something I'm doing wrong?
// CLoader_MFCApp initialization
BOOL CLoader_MFCApp::InitInstance()
{
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance();
SetRegistryKey(_T("MyApp"));
HMODULE hm = LoadLibraryA("./abc/def.dll");
// after above line InitInstance() gets called again
// more code
return FALSE;
}
Call Stack:
MyApp.exe!CLoader_MFCApp::InitInstance() C++
CORE.dll!InternalDllMain(HINSTANCE__ *, unsigned long, void *) C++
CORE.dll!__DllMainCRTStartup(void *, unsigned long, void *) C
CORE.dll!_DllMainCRTStartup(void *, unsigned long, void *) C
ntdll.dll!_LdrpCallInitRoutine#16()
ntdll.dll!_LdrpRunInitializeRoutines#4()
ntdll.dll!_LdrpLoadDll#24()
ntdll.dll!_LdrLoadDll#16()
kernel32.dll!_LoadLibraryExW#12()
kernel32.dll!_LoadLibraryExA#12()
kernel32.dll!_LoadLibraryA#4()
MyApp.exe!CLoader_MFCApp::InitInstance() C++
mfc90.dll!AfxWinMain(HINSTANCE__ *, HINSTANCE__ *, char *, int) C++
MyApp.exe!__tmainCRTStartup() C
kernel32.dll!_BaseProcessStart#4()
"Def.dll" is any other dll and completely unrelated from MyApp. In this case, I'm trying to load another dll "CORE.dll"
All I can figure out is that I'm calling LoadLibrary before InitInstance routine is over. Is there any other (overridable) method which is called after InitInstance??? If so, I can try moving LoadLibrary calls to that method...
Yes, you are doing something wrong.
You are in mfc90.dll's DllMain and it is not safe to call LoadLibrary from DllMain, says so right here:
http://msdn.microsoft.com/en-us/library/ms684175%28v=vs.85%29.aspx
This is more of a workaround than a true solution (i.e. I don't know the rules for LoadLibrary in MFC, as I've never read anything to say you can't, nor do I happen to use this technique in our MFC code).
However, Generally speaking, if windows coughs up a hairball due to order of operations, I just move the calls out to another message handler. You can even post a thread message to your application, and write a handler for that message.
Something like:
// in InitInstance - post a message to our main thread to handle after init instance...
PostMessage(NULL, WM_PostInit);
// in your message table
ON_THREAD_MESSAGE(WM_PostInit, OnPostInit)
// in your app
void MyApp::OnPostInit(WPARAM,LPARAM) // both args unused
{
// try load library now...!
}
NOTE: The above is "brain code" - untested. Details undoubtedly need to be massaged for full compilability.
References:
http://msdn.microsoft.com/en-us/library/ms644944%28v=VS.85%29.aspx
I've just had the same issue, caused by the Configuration type being incorrectly set to exe not dll for the dll to be loaded.
Fix: Project -> Configuration Properties -> General -> Configuration Type = Dynamic Library (.dll) (was incorrectly set to Application (.exe))

Explicit Linking DLL and Program Hangs

I've the following piece of code in my program which dynamically links wtsapi32.dll file for session notifications like WTS_SESSION_LOCK and WTS_SESSION_UNLOCK and runs in background. After the first lock/unlock the program hangs and not responding.
Is this a right way of doing explicit linking ?
void RegisterSession(HWND hwnd)
{
typedef DWORD (WINAPI *tWTSRegisterSessionNotification)( HWND,DWORD );
tWTSRegisterSessionNotification pWTSRegisterSessionNotification=0;
HINSTANCE handle = ::LoadLibrary("wtsapi32.dll");
pWTSRegisterSessionNotification = (tWTSRegisterSessionNotification) :: GetProcAddress(handle,"WTSRegisterSessionNotification");
if (pWTSRegisterSessionNotification)
{
pWTSRegisterSessionNotification(hwnd,NOTIFY_FOR_THIS_SESSION);
}
::FreeLibrary(handle);
handle = NULL;
}
Edited:
I have another method UnRegisterSession() function which calls WTSUnRegisterSessionNotification, I am calling the RegisterSession() in WinMain method ( removed FreeLibrary as suggested by 1800) and calling UnRegisterSession() in WM_DESTROY of CALLBACK WindowProcedure function. But still the application hangs.
I'd say you probably cannot safely call FreeLibrary like that - you will be unloading the code you want to have call you. You should probably ensure not to free the dll until after you are finished getting notifications.
MS documentation suggests that you must call WTSUnRegisterSessionNotification before re-registering the session - as it only happens on your second attempt to lock it perhaps this is your issue?
With 1800 wrt the free library - you must keep this library loaded while you use it.
According to the documentation (http://msdn.microsoft.com/en-us/library/aa383841(VS.85).aspx):
"When a window no longer requires these notifications, it must call WTSUnRegisterSessionNotification before being destroyed."
I would try unregistering the notification during WM___CLOSE instead of WM_DESTROY.