Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pin a dll in memory to prevent unloading?

Tags:

c++

windows

dll

Is there some way in Windows to prevent unloading of our dll via FreeLibrary? I.e. to "pin" it in memory for the life of the process?

like image 396
Two Bit Gangster Avatar asked Aug 10 '10 23:08

Two Bit Gangster


People also ask

Can a DLL unload itself?

If your asking if you can safely unload/unmap a DLL loaded in a process from code in the DLL itself, the answer is no - there isn't really a safe way to do this. Think about it this way: Unloading a DLL is done by decrementing it's reference count using FreeLibrary().

How are DLL loaded into memory?

DLL files may be explicitly loaded at run-time, a process referred to simply as run-time dynamic linking by Microsoft, by using the LoadLibrary (or LoadLibraryEx ) API function. The GetProcAddress API function is used to look up exported symbols by name, and FreeLibrary – to unload the DLL.

Does a DLL have its own heap?

Each DLL and exe you create has a its own heap, i.e. _crtheap. The allocations and de-allocations has to happen from respective heap. That a dynamically allocated from DLL, cannot be de-allocated from executable and vice-versa.


1 Answers

I know it's an old thread, but there is a 'proper' way to do this:

Call GetModuleHandleEx with the GET_MODULE_HANDLE_EX_FLAG_PIN flag.

From MSDN:

The module stays loaded until the process is terminated, no matter how many times FreeLibrary is called.

Just in case anyone else finds this thread...

like image 183
parrowdice Avatar answered Oct 05 '22 22:10

parrowdice