How can I find actual path to a loaded DLL with in a windows process (XP /Windows 7) - windows

We create a DLL for other applications to load and use some of the functionality in the application. The DLL has dependency on the the actual path where it is loaded from.
<product_home>/bin/<DLL is here>
|
|----/configdir/configfile
|----/lib/<java jarfiles>
It needs the product_home location to read config files and load jar files etc
My windows application proloads a special DLL. I need to find actual path to a loaded DLL with in the process and use it to set a "HOME" variable. This will be used in rest of the processing. Using an externally set environment variable some time fails when there are multiple versions of dll present on the machine. To me it looks like DLL can figure out its own "product_home" as long it can get the actual loaded location.
The DLL This article Get Your DLL's Path/Name provides one such way- (yet to try it successfully. The generated exe crashes). Is this the correct approach?

Either I don't understand your need, or the link you mention is not what you need. If I understand you correctly, you'd like to get the full path of a certain DLL loaded by the process. So, say that DLL is "kernel32.dll", you'd like to get "c:\windows\system32\kernel32.dll". Please correct me if I'm wrong.
If that's what you want, the easiest way to do that would be:
HMODULE hModule = GetModuleHandle(_T("kernel32.dll"));
TCHAR dllPath[_MAX_PATH];
GetModuleFileName(hModule, dllPath, _MAX_PATH);
Failures checks omitted for brevity - read more about GetModuleHandle and GetModuleFileName.

Related

Optimum way to help windows find the dll I'm linking to?

My code is using a library which is a static/implicitly linked DLL (let's call it DLLB) but on runtime it can't find it.
This is despite locating DLLB in the same directory as the code that calls it. (The calling code is itself a DLL, DLLA which is called from python, which is called from arcpy. I'm not quite sure why the python finds DLLA fine but DLLA doesn't find DLLB, despite them being in the same directory).
If I put the library DLL somewhere on the system path, everything works just fine.
But what's the best approach for deployment? Add an entry to the system path on the client machine, at install time? Modify the system path at runtime, from python, before loading the DLL? Something else?
Python must be specifying the full path to the DLL in the LoadLibrary call. This is recommended practice. If you specify only a module name, there is a risk of loading the wrong DLL, possibly introducing a binary planting vulnerability.
Note that although the default search path includes the directory the executable was loaded from, it does not include the directory other DLLs were loaded from. So the behaviour you're seeing is as expected.
If you can use dynamic loading, you can look up the path to DLLA and use it to construct the path to DLLB.
To get a module handle for DLLA, call GetModuleHandleEx. To get the full path to DLLA from the module handle, call GetModuleFileName. Check that the last element is DLLA.dll and replace it with DLLB.dll. You can then call LoadLibrary.

Win32 module loading from multiple directories

I have a program which stores plugins in multiple directories, like so:
root/
core/bin/
app.exe
core.dll
plugin.dll
support.dll
a/bin/
a.dll
a_support.dll
In this example, a.dll imports core.dll, support.dll, and a_support.dll (they are in that order in the import table). a_support.dll imports support.dll. I can change all but the support modules, those are redists of a third-party library.
My code calls LoadLibraryEx(name, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) to load each plugin. For core.dll and plugin.dll, this works fine.
When I try to load a.dll, it fails saying a_support.dll was not found. No errors about core.dll or support.dll, perhaps because they're already in memory.
My suspicion is that when a_support.dll is loaded, support.dll cannot be found, but this seems unusual as a.dll appears to import support.dll before a_support.dll.
Is this layout of modules even possible to use? Will the system be able to use the already-loaded support DLLs, or will it go searching for them and fail? Would there be a way to handle this through manifests? Is there a way to make this work, or will I have to relocate all modules into a single directory?
Edit: At Adrian McCarthy's suggestion, I ran the loading sequence with Process Monitor tracking, and it seems that when I call LoadLibrary("root/a/bin/a.dll", ...), it starts by searching the root directory, then system directories, then down through the path. For some reason, it never searches a/bin/, which it very much should.
I double-checked the paths, and noticed that my calls to load plugin.dll where using the wrong path (root, instead of root/core/bin). Either way, core.dll was loading correctly. After fixing that, I tried it again and this time a.dll does find a_support.dll and seems to load. However, that makes absolutely no sense, unless the loader is successfully using support.dll from... somewhere. The procmon log doesn't show it even attempting to load support.dll again, so I'm not entirely sure at this point if there actually is a problem (besides behavior from the loader that makes no sense).
I suggest using Process Monitor to see what's really happening. You'll see if it's looking in the right place, whether a_support.dll is opened but not loadable because something else is missing, etc.
Certainly one solution would be to place all DLLs in the same directory, the same directory as the .exe. If you can bring yourself to do that it would be the simplest approach for sure.
If not then you will have a bit more work on your hands. I guess you are expecting that the loader will search in the directory where the DLL lives. Sadly it doesn't. Instead the loader will look first in the executable file's directory, and then the rest of the DLL search order. This is why a_support.dll fails to load, because it is not in the same directory as the executable.
The fact that modules are already in memory is beside the point. The loader goes looking for the file. When it finds the file that it wants it then checks to see if it is already loaded. If so then it simply bumps the reference count to that module. Otherwise it loads it into the process.
You could switch to using LoadLibrary for all DLL loads and always being explicit about the path. That's probably inconvenient.
You could use side-by-side assemblies but that doesn't sound very compatible with a plugin architecture.
So I think the main remaining option is SetDllDirectory. Call this just before you load the plugin. You only need to add a/bin to the search path since the rest of the modules are in the executable directory and so will be found without trouble. Restore this setting to its default by calling SetDllDirectory again, passing NULL, once the plugin has loaded and resolved all of its imports.
If you have multiple sub-directories then use AddDllDirectory.
This is a rather confusing application.
Some questions then:
Which dll's does app.exe implicitly import?
core.dll is both implicitly loaded by a.dll AND as a plugin via LoadLibraryEx?
How was the call to LoadLibraryEx on /plugin.dll ever succeeding? If the path was FQ and did not point at an actual dll, LoadLibrary should have failed outright on that dll.
I can't tell if you're giving sample code or real code. You wrote:
LoadLibrary("root/a/bin/a.dll", ...)
If that's the real code, there are two problems here.
First, LoadLibrary doesn't do what you'd expect with a relative path. From MSDN:
To load a module from a relative path without searching any other
path, use GetFullPathName to get a nonrelative path and call
LoadLibrary with the nonrelative path. For more information on the DLL
search order, see Dynamic-Link Library Search Order.
Basically, you give it a full path and get that file, or you let it search for a name in all the "usual" locations. If you give it a relative path, it basically ignores that path, grabs the name, and looks in the usual locations.
If you really meant LoadLibraryEx, note that when you use LOAD_WITH_ALTERED_SEARCH_PATH you get "undefined behavior" if handed a relative path. Again quoting MSDN:
If this value is used and lpFileName specifies a relative path, the behavior is undefined.
Second, you have forward slashes instead of backslashes. Neither LoadLibrary nor LoadLibraryEx likes those.

Is there a better way to make a dll accessible for use on the system than modifying %PATH%?

I want to make a dll with an exposed C function accessible to applications on the system.
Is there a better way to make it available than modifying %PATH%?
Because people don't like adding it to %PATH% here.
You have three options if you want to allow implicit linking to the dll :-
Create a native Win32 assembly that contains the dll and install it to WinSxS. This requires creating a simple .manifest file, the use of some crypto tools to sign the assembly (being the manifest file and the dll), and creating an MSI installer - or call IAssemblyCache directly to perform the actual install.
Install the dll to System32 - with this option you need to ensure the dll has a relativly unique name.
Ad the path to the dll to the someplace on the PATH (or modify path to point to the dll).
Other options if implicit linking to the C Function isn't critical:-
Create an COM interface that exposes the c-method. Register the path to the dll in the registry and users of the dll use CoCreateInstance to get the interface containing the function.
Store the path to the dll in the registry, and expect users of the dll to use that path with LoadLibrary, and GetProcAddress to load the dll.
Put it somewhere in your PATH. (C:\Windows\System32\ comes to mind). If it's only needed by one application, just stick it in the same directory.
If you call the DLL using an import library, then it looks in the current directory, and then in the PATH.
But, you don't need to call it that way. You can use LoadLibrary() and GetProcAddress() yourself and then do whatever you want. If you call LoadLibrary with just the dll name, it uses the same algorithm as with the import library (current dir + PATH) -- if you pass a full path, it will use it.
COM uses this technique to load a DLL based on a full path to the DLL which is in the registry -- you could do this too without COM.
You could search for it in some other way besides the PATH -- you could call with no path, see if it finds it, and then try the registry, and then look elsewhere (every drive's program files directory, etc).
Basically, if you call LoadLibrary and GetProcAddress yourself, you can do whatever you want.
I guess that it would be best to install it into system32 folder and forget about %PATH% modification...

Get DLL's directory

I have a question about getting DLL's directory on Windows system.
The situation is like this :
I have a DLL and an EXE file. The exe file must load the DLL to run.
These 2 modules are in different directories.
Moreover, the directory of the DLL is changeable.
Now I have to get the directory of the DLL in "run time".
How could I do this?
Thanks in advance.
Do you need to find where the DLL is to load it or find the the path where it was loaded from?
The DLL path search algorithm is documented on MSDN and you can use the SearchPath function to search the system path.
If you need to find the path where a DLL was loaded, after it was loaded, use the GetModuleFileName function. That takes the module handle that is returned by LoadLibrary, GetModuleHandle, or passed in as hinstDLL to DllMain and returns the full path to the DLL.
I guess you need to implement some custom search algorithm. Only your exe knows which one DLL is needed and where it can be. So find the path and use it with LoadLibrary().
BTW, if possible, I would consider using COM. In this way you will use DLL stuff by some CLSID, which is completely independent from file path.

Difference between .dll and .exe?

I want to know the exact difference between the dll and exe file.
I don't know why everybody is answering this question in context of .NET. The question was a general one and didn't mention .NET anywhere.
Well, the major differences are:
EXE
An exe always runs in its own address space i.e., It is a separate process.
The purpose of an EXE is to launch a separate application of its own.
DLL
A dll always needs a host exe to run. i.e., it can never run in its own address space.
The purpose of a DLL is to have a collection of methods/classes which can be re-used from some other application.
DLL is Microsoft's implementation of a shared library.
The file format of DLL and exe is essentially the same. Windows recognizes the difference between DLL and EXE through PE Header in the file. For details of PE Header, You can have a look at this Article on MSDN
EXE:
It's a executable file
When loading an executable, no export is called, but only the module entry point.
When a system launches new executable, a new process is created
The entry thread is called in context of main thread of that process.
DLL:
It's a Dynamic Link Library
There are multiple exported symbols.
The system loads a DLL into the context of an existing process.
For More Details: http://www.c-sharpcorner.com/Interviews/Answer/Answers.aspxQuestionId=1431&MajorCategoryId=1&MinorCategoryId=1
http://wiki.answers.com/Q/What_is_the_difference_between_an_EXE_and_a_DLL
Reference: http://www.dotnetspider.com/forum/34260-What-difference-between-dll-exe.aspx
The difference is that an EXE has an entry point, a "main" method that will run on execution.
The code within a DLL needs to be called from another application.
There are a few more differences regarding the structure you could mention.
Both DLL and EXE share the same file structure - Portable Executable, or PE. To differentiate between the two, one can look in the Characteristics member of IMAGE_FILE_HEADER inside IMAGE_NT_HEADERS. For a DLL, it has the IMAGE_FILE_DLL (0x2000) flag turned on. For a EXE it's the IMAGE_FILE_EXECUTABLE_IMAGE (0x2) flag.
PE files consist of some headers and a number of sections. There's usually a section for code, a section for data, a section listing imported functions and a section for resources. Some sections may contain more than one thing. The header also describes a list of data directories that are located in the sections. Those data directories are what enables Windows to find what it needs in the PE. But one type of data directory that an EXE will never have (unless you're building a frankenstein EXE) is the export directory. This is where DLL files have a list of functions they export and can be used by other EXE or DLL files. On the other side, each DLL and EXE has an import directory where it lists the functions and DLL files it requires to run.
Also in the PE headers (IMAGE_OPTIONAL_HEADER) is the ImageBase member. It specifies the virtual address at which the PE assumes it will be loaded. If it is loaded at another address, some pointers could point to the wrong memory. As EXE files are amongst the first to be loaded into their new address space, the Windows loader can assure a constant load address and that's usually 0x00400000. That luxury doesn't exist for a DLL. Two DLL files loaded into the same process can request the same address. This is why a DLL has another data directory called Base Relocation Directory that usually resides in its own section - .reloc. This directory contains a list of places in the DLL that need to be rebased/patched so they'll point to the right memory. Most EXE files don't have this directory, but some old compilers do generate them.
You can read more on this topic # MSDN.
This answer was a little more detailed than I thought but read it through.
DLL:
In most cases, a DLL file is a library. There are a couple of types of libraries, dynamic and static - read about the difference. DLL stands for dynamic link library which tells us that it's a part of the program but not the whole thing. It's made of reusable software components (library) which you could use for more than a single program. Bear in mind that it's always possible to use the library source code in many applications using copy-paste, but the idea of a DLL/Static Library is that you could update the code of a library and at the same time update all the applications using it - without compiling.
For example:
Imagine you're creating a Windows GUI component like a Button. In most cases you'd want to re-use the code you've written because it's a complex but a common component - You want many applications to use it but you don't want to give them the source code You can't copy-paste the code for the button in every program, so you decide you want to create a DL-Library (DLL).
This "button" library is required by EXEcutables to run, and without it they will not run because they don't know how to create the button, only how to talk to it.
Likewise, a DLL cannot be executed - run, because it's only a part of the program but doesn't have the information required to create a "process".
EXE:
An executable is the program. It knows how to create a process and how to talk to the DLL. It needs the DLL to create a button, and without it the application doesn't run - ERROR.
hope this helps....
Both DLL and EXE are Portable Executable(PE) Formats
A Dynamic-link library (DLL) is a library and therefore can not be executed directly. If you try to run it you will get an error about a missing entry point. It needs an entry point (main function) to get executed, that entry point can be any application or exe. DLL binding occurs at run-time. That is why its called "Dynamic Link" library.
An Executable (EXE) is a program that can be executed. It has its own entry point. A flag inside the PE header indicates which type of file it is (irrelevant of file extension). The PE header has a field where the entry point for the program resides. In DLLs it isn't used (or at least not as an entry point).
There are many software available to check header information. The only difference causing both to work differently is the bit in header as shown in below diagram.
EXE file has only single main entry means it is isolated application, when a system launches exe, a new process is created while DLLs have many entry points so when application use it no new process started, DLL can be reused and versioned. DLL reduces storage space as different programs can use the same dll.
Dll v/s Exe
1)DLL file is a dynamic link library which can be used in exe files and
other dll files.
EXE file is a executable file which runs in a separate
process which is managed by OS.
2)DLLs are not directly executable . They are separate files containing functions that can be called by programs and other DLLs to perform computations and functions.
An EXE is a program that can be executed . Ex :Windows program
3)Reusability
DLL: They can be reused for some other application. As long as the coder knows the names and parameters of the functions and procedures in the DLL file .
EXE: Only for specific purpose .
4)A DLL would share the same process and memory space of the calling application while an
EXE creates its separate process and memory space.
5)Uses
DLL: You want many applications to use it but you don't want to give them the source code You can't copy-paste the code for the button in every program, so you decide you want to create a DL-Library (DLL).
EXE: When we work with project templates like Windows Forms Applications, Console Applications, WPF Applications and Windows Services they generate an exe assembly when compiled.
6)Similarities :
Both DLL and EXE are binary files have a complex nested structure defined by the Portable Executable format, and they are not intended to be editable by users.
Two things: the extension and the header flag stored in the file.
Both files are PE files. Both contain the exact same layout. A DLL is a library and therefore can not be executed. If you try to run it you'll get an error about a missing entry point. An EXE is a program that can be executed. It has an entry point. A flag inside the PE header indicates which file type it is (irrelevant of file extension). The PE header has a field where the entry point for the program resides. In DLLs it isn't used (or at least not as an entry point).
One minor difference is that in most cases DLLs have an export section where symbols are exported. EXEs should never have an export section since they aren't libraries but nothing prevents that from happening. The Win32 loader doesn't care either way.
Other than that they are identical. So, in summary, EXEs are executable programs while DLLs are libraries loaded into a process and contain some sort of useful functionality like security, database access or something.
The .exe is the program. The .dll is a library that a .exe (or another .dll) may call into.
What sakthivignesh says can be true in that one .exe can use another as if it were a library, and this is done (for example) with some COM components. In this case, the "slave" .exe is a separate program (strictly speaking, a separate process - perhaps running on a separate machine), but one that accepts and handles requests from other programs/components/whatever.
However, if you just pick a random .exe and .dll from a folder in your Program Files, odds are that COM isn't relevant - they are just a program and its dynamically-linked libraries.
Using Win32 APIs, a program can load and use a DLL using the LoadLibrary and GetProcAddress API functions, IIRC. There were similar functions in Win16.
COM is in many ways an evolution of the DLL idea, originally concieved as the basis for OLE2, whereas .NET is the descendant of COM. DLLs have been around since Windows 1, IIRC. They were originally a way of sharing binary code (particularly system APIs) between multiple running programs in order to minimise memory use.
An EXE is visible to the system as a regular Win32 executable. Its entry
point refers to a small loader which initializes the .NET runtime and tells
it to load and execute the assembly contained in the EXE.
A DLL is visible to the system as a Win32 DLL but most likely without any
entry points. The .NET runtime stores information about the contained
assembly in its own header.
dll is a collection of reusable
functions where as an .exe is an
executable which may call these
functions
An exe is an executible program whereas A DLL is a file that can be loaded and executed by programs dynamically.
● .exe and dll are the compiled version of c# code which are also called as
assemblies.
● .exe is a stand alone executable file, which means it can executed directly.
● .dll is a reusable component which cannot be executed directly and it requires
other programs to execute it.
For those looking a concise answer,
If an assembly is compiled as a class library and provides types for other assemblies to use, then it has the ifle extension .dll (dynamic link library), and it cannot be executed standalone.
Likewise, if an assembly is compiled as an application, then it has the file extension .exe (executable) and can be executed standalone. Before .NET Core 3.0, console apps were compiled to .dll fles and had to be executed by the dotnet run command or a host executable. - Source
Difference in DLL and EXE:
1) DLL is an In-Process Component which means running in the same memory space as the client process. EXE is an Out-Process Component which means it runs in its own separate memory space.
2) The DLL contains functions and procedures that other programs can use (promotes reuability) while EXE cannot be shared with other programs.
3) DLL cannot be directly executed as they're designed to be loaded and run by other programs. EXE is a program that is executed directly.
The major exact difference between DLL and EXE that DLL hasn't got an entry point and EXE does. If you are familiar with c++ you can see that build EXE has main() entry function and DLL doesn't :)

Resources