Unloading the DLL itself

Is it possible for a function inside a DLL to unload a DLL? I need to do this so that I can make sure that the DLL is not in use and then write to the DLL file.

+2
source share
4 answers

I do not think this will work. Calling FreeLibrary with a handle from the outside (LoadLibrary is called from an area outside the DLL), because the code runs in a memory location that will no longer be valid.

Even if it is possible, it smells of poor design. Perhaps you want to make some kind of updater or similar. Explain a little more what is the result you expect. Unloading the DLL from the inside is not the way to go.

+1
source

As I understand it, it MAY be executed and MEANT to be executed sometimes (for example, in case of dll injection using CreateRemoteThread and other methods). In this way,

FreeLibraryAndExitThread(hModule, 0) 

will do just that.

On the other hand, causing

 FreeLibrary(hModule) 

will not be here - from MSDN: "If they called FreeLibrary and ExitThread separately, the race condition would exist. The library could be unloaded before calling ExitThread." As a remark, ExitThread does some accounting, and not just returns a stream function.

All this assumes that your Dll received the hModule itself by calling LoadLibrary from the loaded Dll, or rather by calling the following function from within the loaded Dll:

 GetModuleHandleEx ( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)DllMain, &hModule ) 

This increases the reference counter for the Dll, so you know that if you later free the library using this descriptor, and if the library is really unloaded, then you had the last link to it.
If you instead skip the increment of the Dll reference counter and get hModule only from argument to DllMain during DLL_PROCESS_ATTACH , then you should not call FreeLibraryAndExitThread , since the code that loaded the Dll still uses it, and this module does not really control yours.

+12
source

Use this when the dll has completed the task:

  CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)FreeLibrary, &__ImageBase, 0, NULL); // terminate if dll run in a separate thread ExitThread(0); // or just return out the dll 

And __ImageBase is the header structure of the PE DLL:

 EXTERN_C IMAGE_DOS_HEADER __ImageBase; 
+4
source

If you ask if you can safely unload / deactivate a DLL loaded into a process from the code of the DLL itself, there will be no answer - in fact there is no reliable way to do this.

Think of it this way: Unloading a DLL is done by reducing its number of links using FreeLibrary (). The problem, of course, is that after the DLL reference count reaches zero, the module will not be displayed. This means that the code in the DLL that called FreeLibrary () has disappeared.

Even if you can do this, you still need to make sure that there are no other threads that perform exported functions from the DLL.

0
source

Source: https://habr.com/ru/post/1388168/


All Articles