Link to home
Start Free TrialLog in
Avatar of guitarmanchu
guitarmanchu

asked on

FreeLibrary and DLLMain

Now, I have a DLL (DLL A) that calls a second DLL (DLL B) to build a function upcall table.  These functions are used throughout the life of DLL A by other external processes.  Now, my question is...  since this upcall table needs to be valid for the lifetime of DLL A, how can I free the reference to DLL B since I cannot call FreeLibrary from DllMain during PROCESS_DETACH?

I do not have access to the other applications that use this upcall table, so the idea of having a special function called prior to unload that would clean everything up isn't going to work.

How can I cleanly unload DLL B when DLL A is about to exit?
Avatar of aib_42
aib_42

I'm not sure why exactly calling LoadLibrary/FreeLibrary from DllMain is a problem, but if it's only to prevent deadlocks due to dependencies/freeing orders, you might just get away with calling FreeLibrary, probably with even more luck if A is the only module getting unloaded (i.e. DLL_PROCESS_DETACH was signalled due to FreeLibrary(A), lpvReserved=NULL)

I was going to suggest having B free itself (with a call from A), but if you stick to the API documentation, you are not supposed to call functions that may call functions that may call FreeLibrary... Which, as far as I understand, means you HAVE TO free B before or after A's DllMain is called.

I would suggest allocating some executable memory (VirtualAlloc?), populating it with the 6-byte code needed to free B and exit, and calling it using CreateThread...only if it wasn't a horrible, horrible hack.
you can make use of thread synchronization using events or posting message to a thread using PostThreadMessage API and listen for the event / message in a thread in DLL B and unload the DLL when you receive the event / message.
ASKER CERTIFIED SOLUTION
Avatar of DFPercush
DFPercush

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
WaitForSingleObject() takes 2 parameters, my mistake. The second is a time-out in ms, and I would recommend setting it to INFINITE.

WaitForSingleObject(hWaitableObject, INFINITE);
Avatar of guitarmanchu

ASKER

Fantastic answer, thanks!