App fails to find unmanaged dll when deployed - c#

I am running a Web API Asp.Net 4.6 app running in Any CPU mode (though I've also tried this specifying x64) and it makes a call to an unmanaged x64 C dll. This works fine when running within Visual Studio (using default IIS Express settings) though I get Windows Error 126 (The specified module could not be found.) when I deploy to another server and run in IIS or IIS Express even though I am sure that the path to the DLL is correct. Is there something else I can try?
My Native Methods Wrapper:
public static class NativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
}
My Load DLL Method:
private static void LoadDll()
{
UnloadDLL(); //Unload the module first
if (string.IsNullOrEmpty(DllDirectory))
throw new ApplicationException("DPI DLL directory not specified.");
if (!File.Exists(DllPath))
throw new ApplicationException("Could not find DPI DLL.");
pDll = NativeMethods.LoadLibrary(DllPath);
//Fails Here
if (pDll == IntPtr.Zero)
throw new ApplicationException(string.Format("Failed to load library <{0}> (ErrorCode: {1})", DllPath, Marshal.GetLastWin32Error()));
}
Let me know if I can make anything else more clear, thanks!

Use Dependency Walker to get the list of module's dependencies (module with path DllPath). Also check do you need install Visual C++ Redistributable on the server.
By ikenread: Need to check unmanaged DLL compilation mode. If it compiled in Debug mode, it will be dependent on Debug versions of Visual C++ Redistributable dlls and they will be absent (most likely) on the production server.

Related

Why does LoadLibrary fail while DllImportAttribute works?

I'm creating a .NET application for a client that performs I/O with one of their third-party systems. As they regularly change the password of this system, I should retrieve it dynamically by calling a native DLL that they provide in a dedicated directory (not besides my EXE file).
However, I have trouble loading the DLL dynamically using LoadLibraryEx. The weird thing is that I can call the library using the DllImportAttribute.
This is what I have done so far:
According to this SO answer, I use the following code (in a constructor) to try to load the DLL dynamically:
public PasswordProvider(string dllPath)
{
if (!File.Exists(dllPath))
throw new FileNotFoundException($"The DLL \"{dllPath}\" does not exist.");
_dllHandle = NativeMethods.LoadLibraryEx(dllPath, IntPtr.Zero, LoadLibraryFlags.None);
if (_dllHandle == IntPtr.Zero)
throw CreateWin32Exception($"Could not load DLL from \"{dllPath}\".");
var procedureHandle = NativeMethods.GetProcAddress(_dllHandle, GetPasswordEntryPoint);
if (procedureHandle == IntPtr.Zero)
throw CreateWin32Exception("Could not retrieve GetPassword function from DLL.");
_getPassword = Marshal.GetDelegateForFunctionPointer<GetPasswordDelegate>(procedureHandle);
}
When LoadLibraryEx is called, the resulting handle is null, the error code is 126 which usually means that the DLL or one of its dependencies could not be found.
When I call LoadLibraryEx with DoNotResolveDllReferences, then I get a working handle but afterwards, I cannot call GetProcAddress (error code 127) - I suspect that I have to fully load the DLL for this.
When I open the native DLL in Dependencies (which essentially is Dependency Walker for Win10), I can clearly see that one of the statically linked DLLs is missing
However, if I copy the DLL besides my EXE file and use the DllImportAttribute, I can call into the DLL
[DllImport(DllPath, EntryPoint = GetPasswordEntryPoint, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern long GetPassword(long systemId, string user, byte[] password);
How is this possible? I thought that the mechanism behind DllImportAttribute uses LoadLibary internally, too. Where does my code differ? Am I missing something obvious?
Just some notes:
I can't just use DllImportAttribute as I cannot specify searching in a dedicated directory this way (the DLL must lie beside my EXE file or in a common Windows location for this to work).
I also tried LoadLibrary instead of LoadLibraryEx but with the same results.
EDIT after Simons comment:
NativeMethods is defined as followed:
private static class NativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr LoadLibrary(string dllName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr LoadLibraryEx(string dllFileName, IntPtr reservedNull, LoadLibraryFlags flags);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr moduleHandle, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr moduleHandle);
}
[Flags]
private enum LoadLibraryFlags : uint
{
None = 0,
DoNotResolveDllReferences = 0x00000001,
LoadIgnoreCodeAuthorizationLevel = 0x00000010,
LoadLibraryAsDatafile = 0x00000002,
LoadLibraryAsDatafileExclusive = 0x00000040,
LoadLibraryAsImageResource = 0x00000020,
LoadLibrarySearchApplicationDir = 0x00000200,
LoadLibrarySearchDefaultDirs = 0x00001000,
LoadLibrarySearchDllLoadDir = 0x00000100,
LoadLibrarySearchSystem32 = 0x00000800,
LoadLibrarySearchUserDirs = 0x00000400,
LoadWithAlteredSearchPath = 0x00000008
}
EDIT after Hans Passant's comment:
The overall goal is the ability to replace / update the native DLL while my application (a Windows Service) is running. I detect a file change and then reload the DLL. I am not quite sure if this is possible with DllImportAttribute without restarting the service.
And I should be more specific on the actual problem: I couldn't load the native DLL using LoadLibraryEx, no matter if it was placed next to my EXE, or in another random folder, or in SysWow64. Why does it work with DllImportAttribute? I'm pretty sure that the missing FastMM subdependency DLL is not present on my system (neither next to the actual DLL, nor in any Windows directory).
It's because the DLL search order path. In windows when application try to load a DLL the underlying system automatically search some path for the DLL ,So let's pretend Windows's DLL search path looks something like this:
A) . <-- current working directory of the executable, highest priority, first check
B) \Windows
C) \Windows\system32
D) \Windows\syswow64 <-- lowest priority, last check
You can read more about the underlying mechanism in this Microsoft documentation.
Search for DLL which your main DLL has dependency to it and find where it store on system, add the directory of it to DLL search path of Windows using AddDllDirectory or SetDllDirectory.
If the dll already loaded into memory by any of running process Windows automatically use it instead of searching, so you can load FastMM DLL into memory using LoadLibrary manually and then try to load the main DLL and it should solve the problem too.
#HansPassant and #David Heffernan are right: I actually tried to load two different versions of the DLL (one of them had the FastMM subdependency, one did not). Thanks for your help and sorry for the inconvenience.

c# - using LoadLibrary returns 0 with Win32Error 193

I'm building a c# class library that calls third party DLLs supplied by a vendor we're working with. The vendors examples are all in vc++ and are running and working.
I'm trying to load one of the DLLs and it's returning an IntPtr 0. When I call Marshal.GetLastWin32Error() I get 193 which from what I've read means that I'm trying to load a 32-bit DLL in 64-bit app. But I checked again and again and both my class library is set to x86 and my console application that makes the call to that class library is set to x86.
I can successfully load other DLL files by the same vendor (which are also 32-bit).
This is my Native helper class:
class NativeHelper
{
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary", SetLastError = true)]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll", EntryPoint = "LoadLibraryEx", SetLastError = true)]
public static extern IntPtr LoadLibraryEx(string dllToLoad, IntPtr hFile, LoadLibraryFlags flags);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
[System.Flags]
public enum LoadLibraryFlags : uint
{
DONT_RESOLVE_DLL_REFERENCES = 0x00000001,
LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010,
LOAD_LIBRARY_AS_DATAFILE = 0x00000002,
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040,
LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020,
LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008,
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x00000100,
LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800,
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000
}
}
And this is how I make the call:
IntPtr pDll = NativeHelper.LoadLibrary(#"dhplay.dll"); // returns 0
if (pDll == IntPtr.Zero)
{
var err = Marshal.GetLastWin32Error().ToString(); // returns 193
Console.WriteLine(err);
}
What am I missing here? If I'm running x86 why is that DLL not loaded and others do?
Edit (Additional information):
IntPtr.Size is 4
dumpbin returns 8664 machine (x64) - That means it's 64-bit? I checked for other DLL used and they are 8664 machine (x86)
As far as dependencies, it's working on a vc++ application on my machine.
If there is smoke, there is often fire. Some dll is probably x64 while your app is x32 (or the reverse).
Check in you app IntPtr.Size. 4 → x86, 32 bits, 8 → x64, 64 bits
If you use the Visual Studio Command Prompt, you should be able to use dumpbin. Do a dumpbin /headers yourdll.dll | more for your dlls. One of the first rows should be machine (...). In the (...) it should be written if it is x86 (so 32 bits) or x64 (so 64 bits)
To the second question, you can't in any way mix 32 and 64 bit dlls in a single process. Some programs "cheat" and create a secondary process with the correct bits to load the dlls and then do IPC (inter-process-communication) between the primary process and the secondary process to use the dll. Clearly it is complex.

Loading a 32-bit dll in a 64-bit process [duplicate]

This question already has answers here:
Target 32 Bit or 64 Bit native DLL depending on environment
(3 answers)
DllImport - An attempt was made to load a program with an incorrect format [duplicate]
(1 answer)
Closed 8 years ago.
The community reviewed whether to reopen this question 8 months ago and left it closed:
Original close reason(s) were not resolved
I want my C# application to conditionally run a native method, conditionally choosing to run either the x86 or the x64 version of the dll. Whenever I try to load the 32 bit dll I get the below error:
Unhandled Exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
at <exeName>.MiniDumpMethods.MiniDumpWriteDumpX86(IntPtr hProcess, UInt32 processId, SafeHandle hFile, MINIDUMP_TYPE dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam)
Background context: I want my binary to take a memory dump of a given process. Based on whether or not the process it's taking a memory dump of is 32 or 64 bit it'll choose to run the MiniDumpwriteDump method from the x86 or x64 version of dbghelp.dll.
I'm currently doing the following:
[SuppressUnmanagedCodeSecurity]
internal static class MiniDumpMethods
{
[DllImport("dbghelp.dll",
EntryPoint = "MiniDumpWriteDump",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode,
ExactSpelling = true,
SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MiniDumpWriteDump(
IntPtr hProcess,
uint processId,
SafeHandle hFile,
MINIDUMP_TYPE dumpType,
IntPtr expParam,
IntPtr userStreamParam,
IntPtr callbackParam);
[DllImport("dbghelpx86.dll",
EntryPoint = "MiniDumpWriteDump",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Unicode,
ExactSpelling = true,
SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MiniDumpWriteDumpX86(
IntPtr hProcess,
uint processId,
SafeHandle hFile,
MINIDUMP_TYPE dumpType,
IntPtr expParam,
IntPtr userStreamParam,
IntPtr callbackParam);
}
Any idea how I can conditionally load either the x86 or the x64 version of the dll?
(Note: dbghelpx86.dll is the x86 version of dbghelp.dll that I renamed)
Thanks
You cannot load a 32 bit DLL into a 64 bit process. To support this you will have to have two different EXE's, one compiled as 64 bit and one compiled as 32 bit.
If you run the 64 bit process and encounter a 32 bit dump, you'll have to launch the 32 bit version of the EXE to process the dump file. Once it is processed you can use some sort of IPC (Interprocess Communication) mechanism to send the results back to the 64 bit process.

32-bit Java Accessibility on a 64-bit machine

I have a 32-bit app that makes use of Java Accessibility (WindowsAccessBridge-32.dll, via the Java Access Bridge), and works perfectly on a 32-bit machine, but fails on an x64 machine.
I believe I have tracked it down to one of the first calls after Windows_run:
getAccessibleContextFromHWND(hwnd, out vmId, out context)
defined as follows:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("WindowsAccessBridge-32.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static bool getAccessibleContextFromHWND(IntPtr hwnd, out Int32 vmID, out IntPtr acParent);
This call works fine on the 32-bit system, returning True, populating both vmId (with some 5-digit value, which), and context - whereas on the 64-bit system, it returns True, populates 'context', but returns '0' for vmId.
If I assume that 0 is valid (even though it's a random 5-digit number resembling a pointer on the 32-bit system), the next call still fails:
AccessibleContextInfo aci = new API.AccessibleContextInfo();
if (!getAccessibleContextInfo(vmId, context, ref aci))
throw new Exception();
where:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("WindowsAccessBridge-32.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static bool getAccessibleContextInfo(Int32 vmID, IntPtr ac, ref AccessibleContextInfo info);
(I'm omitting the AccessibleContextInfo struct for brevity, but I can provide it if necessary).
I know that the libraries are working, because both JavaMonkey and JavaFerret work correctly. Furthermore, call to isJavaWindow works, returning 'true', or 'false' as appropriate, and I am linking to the correct DLL (WindowsAccessBridge-32).
Can anyone suggest what may be wrong here?
It appears that the problem is in the type of AccessibilityContext:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("WindowsAccessBridge-32.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static bool getAccessibleContextFromHWND(IntPtr hwnd, out Int32 vmID, out IntPtr acParent);
AccessibilityContext (acParent above), which I had incorrectly mapped as an IntPtr, is actually an Int32 when using the "legacy" WindowsAccessBridge.dll library (used under x86), and an Int64 when using the WOW64 WindowsAccessBridge-32.dll library.
So the upshot is, the code has to differ between x86 and WOW x64, and must be compiled separately for each. I do this by #define'ing WOW64 during x64 builds, always referencing the Int64 methods, and using "shim" methods on x86:
#if WOW64 // using x64
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("WindowsAccessBridge-32.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static bool getAccessibleContextFromHWND(IntPtr hwnd, out Int32 vmID, out Int64 acParent);
#else // using x86
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("WindowsAccessBridge.dll", EntryPoint = "getAccessibleContextFromHWND", CallingConvention = CallingConvention.Cdecl)]
private extern static bool _getAccessibleContextFromHWND(IntPtr hwnd, out Int32 vmID, out Int32 acParent);
public static bool getAccessibleContextFromHWND(IntPtr hwnd, out Int32 vmID, out Int64 acParent)
{
Int32 _acParent;
bool retVal = _getAccessibleContextFromHWND(hwnd, out vmID, out _acParent);
acParent = _acParent;
return retVal;
}
#endif
If your using a 64 bit JVM with a 32 bit version of the Java Access bridge it won't work correctly. You need a 64 bit version of the access bridge which has recently been released. see
http://blogs.oracle.com/korn/entry/java_access_bridge_v2_0
For instructions on installing a 32 bit copy of the access bridge for use with 32 bit JRE's under 64 bit windows see
http://www.travisroth.com/2009/07/03/java-access-bridge-and-64-bit-windows/
The call to 'initializeAccessBridge' REQUIRES you to have an active windows message pump.
Inside 'initializeAccessBridge', it (eventually) creates a hidden dialog window (using CreateDialog). Once the dialog is created, it performs a PostMessage with a registered message. The JavaVM side of the access bridge responds to this message, and posts back another message to the dialog that was created (it appears to be a 'hello' type handshake between your app and the java VM). As such, if your application doesn't have an active message pump, the return message from the JavaVM never gets received by your app.

LoadLibrary call from MVC application running in IIS

I'm having trouble executing this line of code in my MVC application:
IntPtr hModule = LoadLibrary(BondProbeSettings.AssemblyFilePath);
The problem is that hModule is always 0.
If I run the same code with the same value for BondProbeSettings.AssemblyFilePath but from a console application instead of the MVC app hModule is non-zero.
Are there any security issues I need to consider?
The signature for LoadLibrary is:
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);
Change the declaration to:
[DllImport("kernel32.dll", CharSet = CharSet.Auto), SetLastError = true)]
static extern IntPtr LoadLibrary(string lpFileName);
And your code to:
IntPtr hModule = LoadLibrary(BondProbeSettings.AssemblyFilePath);
if (hModule == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();
Now you'll know why it doesn't work.
Yep you need to run the site assembly in full trust. I haven't configured this myself but I reckon you need:
to GAC the dll (meaning it has to be strongnamed)
to perhaps configure the application pool in IIS (assuming IIS) to allow full trust (?)
I'm on linux so I can't really help you with screenshots right now

Categories