Is it possible for a function that is inside a DLL to unload the DLL? I need to do this so I can make sure the DLL is not in use, then write to the DLL's file.
As I understand it, it CAN be done and is MEANT to be done sometimes (for example in case of dll injection by CreateRemoteThread and other methods). So,
FreeLibraryAndExitThread(hModule, 0)
will do precisely that.
On the other hand, calling
FreeLibrary(hModule)
will not do here - from MSDN: "If they were to call FreeLibrary and ExitThread separately, a race condition would exist. The library could be unloaded before ExitThread is called." As a remark, ExitThread does some bookkeeping besides just returning from the thread function.
All this assumes that Your Dll obtained the hModule itself by calling LoadLibrary from inside the loaded Dll, or rather, by calling from inside the loaded Dll the following function:
GetModuleHandleEx
(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)DllMain,
&hModule
)
This increments the reference count of the Dll so You know that if You free the library later using that handle and if the library is really unloaded then You had the last reference to it.
If You instead skip incrementing the Dll's reference count and obtain the hModule just from the argument to DllMain during DLL_PROCESS_ATTACH then You should not call FreeLibraryAndExitThread since the code that loaded the Dll is still using it and this module handle really isn't Yours to manage.
Use this when the dll has done it job:
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 the __ImageBase is your dll's PE header structure:
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
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(). The problem of course is that once the reference count of the DLL hits zero, the module is unmapped. Which means that the code in the DLL that called FreeLibrary() is gone.
Even if you could do this, you'd still need to ensure that there are no other threads executing any exported functions from the DLL.
I don't think it will work. Calling FreeLibrary with a handle from the outside (LoadLibrary would have been called from an area outside the DLL) as the code runs in a memory location that will not be valid anymore.
Even if this is possible, it smells like a bad design. Maybe you want to make some updater or alike. Explain a bit more what is the result you expect. Unloading a DLL from within itself is not the way to go.
Related
I want to load special dll without execute dllmain function.
I think, set a breakpoint at dllmain can solve this problem.
But I don't know How can I do?
Also I want call dll's export function.
I have tried to use LoadLibraryEx with dont_resolve_dll_references, but it occurs error with dll's function call.
How can I solve this? Please give me your idea.
Thanks.
As explained in this question: Win32 API to enumerate dll export functions?
You can use LoadLibraryEx with the DONT_RESOLVE_DLL_REFERENCES flag, even though use of that flag is strongly discouraged.
If so you will likely have to free and reload the dll if you actually want to use it.
Well as explained here:
An optional entry point into a dynamic-link library (DLL). When the system starts or terminates a process or thread, it calls the entry-point function for each loaded DLL using the first thread of the process. The system also calls the entry-point function for a DLL when it is loaded or unloaded using the LoadLibrary and FreeLibrary functions.
calling the DllMain is an OS feature mandatory (although implementing that function is optional) if you use the standard way in loading and executing a dynamic library. So there is no official way in doing this.
I have already added delay loading to my project, using the instructions in
http://msdn.microsoft.com/en-us/library/151kt790.aspx
In the "delayhlp.cpp" (a sample implementation of the DLL load helper) __HrLoadAllImportsForDll, I saw that the writer avoids using any Standard C Library (MSVCRT) functions. Do I need to do the same in my handler function, which will be called by the sample DLL load helper?
I think the writer's reason is that someone might try to delay-load MSVCRT itself. I'm not going to do this. Will it then be safe for me to use MSVCRT functions?
Background Info. The reason for delay-loading the 3rd party DLL is because there is a function signature change between two versions, and I need to run my program using either version. I then provide a simple wrapper function to adapt the DLL's function signature to the one needed. This function is registered by the Delay-Load Handler (__pfnDliFailureHook2), when GetProcAddress fails.
Some testing. I added a breakpoint at the beginning of my handler function. I found that when the breakpoint is hit, the msvcrt.dll and msvcr90d.dll etc are already loaded (from Visual Studio's Modules pane). Does it mean that I can call CRT functions safely?
// Check to see if it is the DLL we want to load.
// Intentionally case sensitive to avoid complication of using the CRT
// for those that don't use the CRT...the user can replace this with
// a variant of a case insenstive comparison routine.
//
That's the more relevant comment, for those that don't use the CRT. You won't have a problem, the CRT is always loaded by the startup code.
It can be used to run arbitary Dynamic Link Library in windows,
how can it possibly know the entry point of an arbitary dll?
The answer depends on how much details you need. Basically, it comes down to this:
A DLL can optionally specify an entry-point function. If present, the system calls the entry-point function whenever a process or thread loads or unloads the DLL.
[...] If you are providing your own entry-point, see the DllMain function. The name DllMain is a placeholder for a user-defined function. You must specify the actual name you use when you build your DLL.
(Taken from the MSDN article Dynamic-Link Library Entry-Point Function.)
So basically, the entry point can be specified inside the DLL, and the operating system's DLL loader knows how to look this up.
The IMAGE_OPTIONAL_HEADER (part of the portable executable's header on Windows machines) contains an RVA of the AddressOfEntryPoint that is called by programs looking for an entry point to call (e.g., the loader).
More information on the IMAGE_OPTIONAL_HEADER can be found here. And this paper is good for just general PE knowledge.
What do you mean by "run a DLL"? DLLs aren't normal programs, they are just a collection of functions. The entry point itself usually doesn't do much apart from initializing stuff required by other functions in the DLL. The entry point is automatically called when the DLL is loaded (you can use LoadLibrary to do this).
If you want to call a specific function after loading the DLL, you can use GetProcAddress to get a pointer to the function you want.
I have an unmanaged c++ application that provides a custom _matherr handler. When this application loads and runs code in unmanaged DLLs, if there is a Math error ( e.g. asin( 100.0 ) ) the custom _matherr function is called and everything works.
However, I'm now trying to create a NUnit Test DLL in C++/CLI that loads the same unmanaged DLL and runs the same code as the application above. What I want to do is add the _matherr function to the C++/CLI dll such that when math errors occur I can perform some custom handler logic.
The C++/CLI dll compiles just fine with the _matherr function defined, but when I force a math error from the unmanaged dll, the _matherr function is not called.
Is this not supported by C++/CLI? The MSDN documentation seems to say _matherr is supported by all C Run times, (with a link to a list of runtimes including the /clr runtime. )
My experience is that defining _matherr does not work if done in a dll. It must be defined in the executable.
I've even seen compilers that when you try to add _matherr in a dll, will not link it in because they don't see anybody making a reference to it.
Maybe you need something like a proxy dll, passing through each function call to the original dll excepting those you want to be handled extra.
Is it valid to develop a DLL in C++ that returns boost shared pointers and uses them as parameters?
So, is it ok to export functions like this?
1.) boost::shared_ptr<Connection> startConnection();
2.) void sendToConnection(boost::shared_ptr<Connection> conn, byte* data, int len);
In special: Does the reference count work across DLL boundaries or would the requirement be that exe and dll use the same runtime?
The intention is to overcome the problems with object ownership. So the object gets deleted when both dll and exe don't reference it any more.
According to Scott Meyers in Effective C++ (3rd Edition), shared_ptrs are safe across dll boundaries. The shared_ptr object keeps a pointer to the destructor from the dll that created it.
In his book in Item 18 he states, "An especially nice feature of
tr1::shared_ptr is that it automatically uses its per-pointer deleter
to eliminate another potential client error, the "cross-DLL problem."
This problem crops up when an object is created using new in one
dynamically linked library (DLL) but is deleted in a different DLL. On
many platforms, such cross-DLL new/delete pairs lead to runtime
errors. tr1::shared_ptr avoid the problem, because its default deleter
uses delete from the same DLL where the tr1::shared_ptr is created."
Tim Lesher has an interesting gotcha to watch for, though, that he mentions here. You need to make sure that the DLL that created the shared_ptr isn't unloaded before the shared_ptr finally goes out of scope. I would say that in most cases this isn't something you have to watch for, but if you're creating dlls that will be loosely coupled then I would recommend against using a shared_ptr.
Another potential downside is making sure both sides are created with compatible versions of the boost library. Boost's shared_ptr has been stable for a long while. At least since 1.34 it's been tr1 compatible.
In my opinion, if it's not in the standard and it's not an object/mechanism provided by your library, then it shouldn't be part of the interface to the library. You can create your own object to do the reference counting, and perhaps use boost underneath, but it shouldn't be explicitly exposed in the interface.
DLLs do not normally own resources - the resources are owned by the processes that use the DLL. You are probably better off returning a plain pointer, which you then store in a shared pointer on the calling side. But without more info it's hard to be 100% certain about this.
Something to lookout for if you expose raw pointers from a dll interface. It forces you to use the shared dll CRT, memory allocated in one CRT cannot be deallocated in a different CRT. If you use the shared dll CRT in all your modules ( dll's & exe's ) then you are fine, they all share the same heap, if you dont you will be crossing CRT's and the world will meltdown.
Aside from that issue, I agree with the accepted answer. The creation factory probably shouldn't define ownership & lifecycle management for the client code.
No it is not.
The layout of boost::shared_ptr<T> might not be the same on both sides of the DLL boundary. (Layout is influenced by compiler version, packing pragmas, and other compiler options, as well as the actual version of the Boost source code.)
Only "standard layout" (a new concept in C++11, related to the old "POD = plain old data" concept) types can safely be passed between separately-built modules.