Alex Rivera | Logout

Detect when a Module (DLL) is unloaded

Asked 2010-11-22T05:10:25.757
12

Is there a way to progammatically detect when a module - specifically a DLL - has been unloaded from a process?

I don't have the DLL source, so I can't change it's DLL entry point. Nor can I poll if the DLL is currently loaded because the DLL may be unloaded and then reloaded between polling.

RESULTS:

I ended up using jimharks solution of detouring the dll entry point and catching DLL_PROCESS_DETACH. I found detouring FreeLibrary() to work as well but code must be added to detect when the module is actually unloaded or if the reference count is just being decreased. Necrolis' link about finding the reference count was handy for on method of doing so.

I should note that I had problems with MSDetours not actually unloading the module from memory if a detour existed within it.

Edit
Report

2 Answers

10

One very bad way(which was used by starcraft 2), is to make your program attach to itsself then monitor for the dll unload debug event(http://msdn.microsoft.com/en-us/library/ms679302(VS.85).aspx), else you'd either need to IAT hook FreeLibrary and FreeLibraryEx in the process or hotpatch the functions in kernel32 them monitor the names being passed and the global reference counts.

answered 2010-11-22T06:39:50.807
9

Try using LdrRegisterDllNotification if you're on Vista or above. It does require using GetProcAddress to find the function address from ntdll.dll, but it's the proper way of doing it.

answered 2010-11-22T08:17:21.403

Your Answer