Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a Windows module handle is still valid?

A module can be unloaded, so how can I tell for sure if it is still in memory? I have a handle to it, obtained from GetModuleHandle. When I tried calling GetHandleInformation on it I see error 0xc0000008 - "An invalid HANDLE was specified." This happened before it could have been unloaded.

like image 370
Two Bit Gangster Avatar asked Jul 10 '09 20:07

Two Bit Gangster


1 Answers

The term "handle" is a bit overloaded here - lots of different classes of objects in the Win32 API are called "Handles".

GetHandleInformation is used for handles to kernel objects - files, registry keys, mutexes, etc.

The HMODULE returned by GetModuleHandle is used by the loader and is not an actual kernel object, hence GetHandleInformation fails. Neither of the flags you get in GetHandleInformation makes sense for HMODULE though.

If you want to check if the HMODULE is still loaded in memory, you can just call GetModuleHandle - this API should be quick enough to call many times. However, the result of GetModuleHandle can be invalid the moment it returns - another thread could have called FreeLibrary. It is better to ensure that the DLL does stay loaded. You can do this by calling LoadLibrary yourself, or by calling GetModuleHandleEx which will increment the reference count of the DLL.

like image 84
Michael Avatar answered Sep 23 '22 17:09

Michael