Unload DLL From Self

All questions regarding Windows programming, post here. API,COM, ActiveX, DirectX, OpenGL, MFC and so on...

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Unload DLL From Self

Postby Emery » Thu Jun 16, 2005 3:54 pm

You can't call FreeLibrary(GetModuleHandle(0)) clearly. If the DLL has been unmapped from memory then FreeLibrary would have nothing to return to. But, I just thought of a way to unload a DLL from inside itself but it doesn't work...

Code: Select all
void UnloadSelf()
{
   LPVOID FP_ExitThread = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "ExitThread");
   HMODULE hmod = GetModuleHandle(0);
   __asm
   {
      push hmod
      push FP_ExitThread
      jmp dword ptr [FreeLibrary]
   }
}


Instead of a call, I push on a pointer to ExitThread as the return address of the function call and jump to FreeLibrary. I am pretty sure it isn't working just because FreeLibrary checks if the module you are freeing is the same as the current and doesn't go through with it. Anyone have any ideas how to force FreeLibrary to go through with it or maybe if that isn't the problem?
--~~~~
User avatar
Emery
 
Posts: 4313
Joined: Sat Mar 19, 2005 9:16 am

Postby pstr » Fri Jun 17, 2005 7:08 am

I don't know if what you want to do works, but it looks like you're using the wrong handle anyway: GetModuleHandle(0) returns the handle to the process (the EXE file) not the DLL. However, looking at the remarks for GetModuleHandle it says:
...use care when passing the handle to the FreeLibrary function, because doing so can cause a DLL module to be unmapped prematurely.

which makes me think it'll 'work' but then probably crash when the function returns...
pstr
 
Posts: 43
Joined: Fri Feb 11, 2005 11:55 am

Postby Emery » Fri Jun 17, 2005 1:01 pm

Oh, your right... what was I thinking? I'll fix it when I get home from school and see if it works. I kinda subconciously knew there was something wrong with the module handle but couldn't put my finger on what it was... :? Just used to using GetModuleHandle(0) to grab the current module handle when in the main module.


[edit] Works, BTW.
--~~~~
User avatar
Emery
 
Posts: 4313
Joined: Sat Mar 19, 2005 9:16 am


Return to Windows Programming

Who is online

Users browsing this forum: Google [Bot] and 1 guest