Executable loads same dll as already loaded dll - windows

I'm about to start making major modification to my project and I just want to clarify something as I think my design maybe somewhat complicated.
I have an executable that loads a dll, lets call this dll1, this then loads dll2.
The executable also loads dll2.
What I'm asking is do I have two instances of dll2's global and static member variables, does the second load of dll2 happen or can an execuable only ever load 1 of dll2 even if dll2 was loaded by a different dll?
I know I should only have one copy of dll2's code in memory this is fine. It is the global and static variables I'm interested in.

You can only have one instance of any particular DLL loaded per process.

You can of course load different instances of the same DLL, this is practice is not common, but it is technically possible. Have a try with Process Explorer. See the snapshot below.

Related

Is it possible to load a DLL into the address space not from a file-system file?

I have to create a wrapper DLL that exports some symbols (functions). Within its resources it contains another encrypted DLL that actually does the job.
Upon the wrapper DLL initialization it decrypts the original one, saves it in a file, and loads into the address space by LoadLibrary. However I'd like to avoid saving this DLL in a file.
I know that this doesn't guarantee a bullet-proof protection, actually one may dump the process virtual memory and see it there. I also know that it's possible to create a file with FILE_FLAG_DELETE_ON_CLOSE attribute, which ensures this file will be deleted as soon as the process terminates. But still I'd like to know if there's an option to load the DLL "not from a file".
So far I thought about the following:
Allocate a virtual memory block with adequate protection (PAGE_EXECUTE_READ or PAGE_EXECUTE_READWRITE). Preferrably at the image preferred base address.
Extract/decrypt the DLL image there.
If the image base address isn't its preferred address - do the relocation "manually". I.e. - analyze the relocation table and patch the image in-place.
Handle the image imports. Load its dependency DLLs and fill symbol addresses.
Invoke its initialization function (DllMain).
That is, I can do the work of the loader. But unfortunately there are some areas where the DLL loaded by the above trick will behave differently, since it's not a properly-loaded DLL from the OS's perspective. This includes the following:
The DllMain requires the DLL "module handle", which is just its base address. It may use this handle in calls to various API functions, such as LoadResource. Those calls will probably fail.
There will be problems with exception handling. The OS won't see the DLL's SAFESEH section, hence its internal exception handling code won't be invoked (it's a 64-bit DLL, means SAFESEH is mandatory for exception handling).
Here's my question: Is there an API to properly load the DLL into the process address space without the need for it to be in a file? An alternative variant of LoadLibrary that works, say, on a file mapping instead of a file-system file?
Thanks in advance.
Yes, it is possible to load a DLL which is located in the resources of another image and execute it without needing a file! Take a look at this article, this is exactly what you want. It works, I tried it.

debugging a dynamically loaded executable

I've been handed an application to support, and I'm trying to figure out how to do it. I do have the source, and can make some changes, but I obviously don't want to completely change the architecture of the application.
The app is in a VS2010 solution composed of 9 different projects. The main one is a Windows Form application, but it spins off others in other threads.
Here's the difficulty. Even though the different projects are parts of the same solution, they are separate executables, not DLLs. When the main program starts one of the other projects, it does so by creating a new process, setting the filename of the executeable, the startup arguments and other assorted parameters into the process.StartInfo object, and then calls process.Start().
How can I set breakpoints and debug subordinate executables? I can't attach to them until they are loaded, but they don't get loaded until process.Start() is called, and by then it's too late. Is there a method call I can insert into the main program to get it to load the executable (so I can set breakpoints in it) before it actually begins execution?
Thanks.
Are you able to recompile the other executables? If so, have you tried putting DebugBreak in suitable places? (or _asm int 3).
You can't load the process (usefully), since by definition it will be run in a different addres space from the one you are debugging before it starts.
One simple solution could be adding a call to DebugActiveProcess function to the "main" function of every process which participates in your application.

Can I safely rename/move a dll that is already loaded by a process?

I have a dll that is loaded and file-locked by a process, and I would like to update it with a newer version. I'm looking for an alternative to terminating the process to release the file lock before updating the dll. It is okay that the existing live processes still uses the old version, as long as newly instantiated ones pick up the new logic.
It seems that I can simply rename/move the dll and the live process still seems to work well. Is it safe to do this? If the dll's code has already been loaded into the process then why does it still need to lock the dll?
It is not always ok to move all dll's used by any random application. Some applications, like asp.net, use a shadow copy concept where they actually copy the dll and use the copy leaving you free to modify the original. In the case of asp.net, if you modify the original asp.net will automatically spool up a new app domain using the new dll and gracefully shut down the old one.
If the application you're referring to has a lock on the dll, then you can't safely change it.
It depends on your dll/application. For example, dll may use shared memory, or implement inter-process communication. New dll version may implement it differently. So once new instance will start, you'll have two conflicting versions in memory.
So it's not safe in general case, though in your particular case it may be OK.

Some basic questions about the DLL file

When does Windows Operating System load a DLL into memory?
Does the operation occur when the application starts or when the application first calls one of the procedures in the DLL?
Could a DLL be unloaded once it has been loaded?
When does Windows Operating System
load a DLL into memory?
If you've linked your EXE to a DLL implicitly through a .lib file, like you normally do for most windows apis such as user32.dll and kernel32.dll, then the defautl behavior is for the DLL to get loaded when the process starts and before your WinMain/main function is called. See below for delay loading...
If one DLL depends on another, it will load its dependencies first if they are not already loaded.
If you are explicitly loading code through a DLL (LoadLibrary, CoCreateInstance, etc...), then it will get loaded upon making these calls
Does the operation occur when the
application starts or when the
application first calls one of the
procedures in the DLL?
You can have it both ways. By default, DLL is loaded at app startup. If you used the /DELAYLOAD linker flag, the DLL may be able to defer being loaded until its actually needed. This is "best effort" - if there are weird export dependencies with global variables, it may not work.
Could a DLL be unloaded once it has been loaded?
Short answer is "no" for implicit DLL dependencies that you've linked. FreeLibrary and CoFreeUnusedLibrary can be used for LoadLibrary/CoCreateInstance calls.
I'm going to assume we are talking .net. It is garanteed to happen before you need the code. But you can use late binding to do it at some other time. See this pagelink text
In the windows API, you can explicitly control the loading and unloading of a .dll.
See LoadLibrary and FreeLibrary as a starting point.
Depending on the language/tools you are using many of the details of loading libraries will be taken care of for you, but usually you can still get explicit control if you really want it.

Internal Mechanism of Dynamic Loading DLL's in C++ in OS perpective?

I am not able to get much information about dynamic loading of DLL files from C++ .
I know it does use some functions like LoadLibrary and FreeLibrary with GetProcAddress . But how it works actually internally in the OS perspective like where it actually looks for the DLL file and where it loads like Memory ? can someone help me on that with some diagrams ?
DLL search order is described on the MSDN, and there's an article on DLL loading, and two-part article describing PE format (part two here) (they're slightly old, but I don't think they're outdated). Look through MSDN Magazine and MSJ archives and you'll probably find more.
There's two ways to use a DLL. You can load it dynamically at run-time or statically link against it at link-time.
If you load dynamically it using LoadLibrary, the OS has some mechanism to determine where to look for DLLs. It then attempts to load them. Then you can try to get function pointers to the functions you name (by string or ordinary) and call these functions.
If you link statically, basically the linker adds a reference to the DLL and some jump table with an entry for each of the DLL's functions. When the OS loads your application, it finds references to those DLLs, attempts to load these, and patches the loaded DLL's function's addresses into the jump table. Only then is your application considered loaded and will start.
Note that in reality this is a bit more complicated. For example, DLLs can in turn reference other DLLs. So when the loader loads a DLL, before the DLL can be considered loaded, it will need to (possibly recursively) load other DLLs as well.
For Win32, loader details are on MSDN. See here.
From your C++ code, you're right (for Windows), you load with ::LoadLibrary and resolve function pointers with ::GetProcAddress. Typically you'll cast the result of GetProcAddress into the type that you know the entry point function to be, and then use it in your program.
For example, if you have a plug-in architecture like a browser, you'd decide what your plug-in directory is, get the filename list for that directory, and call ::LoadLibrary for each DLL (filtering filenames would be up to you). For each, you'd resolve the required entry points with GetProcAddress, store them in a structure for that library, and put them in some plug-in list. Later, you'd call through those function pointers to let the plug-in do its work.
If you specify a relative path (e.g. "foo.dll" rather than "c:\foo.dll"), the OS library search path kicks in. Details at MSDN.
Also, DLLs get loaded into your process's address space. Typically you don't care about where, but in the past, you could get faster load times by "rebasing" your DLLs. I don't think there are any guarantees about how the OS loader places libraries in memory, but you can always get the base address in your process's address space.
Your DLL's entry point (dllmain) can also respond to various messages -- thread attach, process attach -- to do initialization in a sensible way.

Resources