I have a C dll with exported functions
I can use the command-line tool dumpbin.exe /EXPORTS to extract the list of exported functions, and then use them in my C# code to (successfully) call these functions.
Is there a way to get this exported-functions-list directly from .NET, without having to use an external command-line tool?
Thanks
As far as I know there is no class in the .Net Framework that
provides the information you need.
However you can use the platform invocation services (PInvoke) of the .Net platform to
use the functions of the Win32 dbghelp.dll DLL. This DLL is part of
the Debugging Tools for the Windows platform. The dbghelp DLL provides
a function called SymEnumerateSymbols64 which allows you to enumerate all
exported symbols of a dynamic link library. There is also a
newer function called SymEnumSymbols which also allows to enumerate
exported symbols.
The code below shows a simple example on how to use the SymEnumerateSymbols64
function.
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SymInitialize(IntPtr hProcess, string UserSearchPath, [MarshalAs(UnmanagedType.Bool)]bool fInvadeProcess);
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SymCleanup(IntPtr hProcess);
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern ulong SymLoadModuleEx(IntPtr hProcess, IntPtr hFile,
string ImageName, string ModuleName, long BaseOfDll, int DllSize, IntPtr Data, int Flags);
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SymEnumerateSymbols64(IntPtr hProcess,
ulong BaseOfDll, SymEnumerateSymbolsProc64 EnumSymbolsCallback, IntPtr UserContext);
public delegate bool SymEnumerateSymbolsProc64(string SymbolName,
ulong SymbolAddress, uint SymbolSize, IntPtr UserContext);
public static bool EnumSyms(string name, ulong address, uint size, IntPtr context)
{
Console.Out.WriteLine(name);
return true;
}
static void Main(string[] args)
{
IntPtr hCurrentProcess = Process.GetCurrentProcess().Handle;
ulong baseOfDll;
bool status;
// Initialize sym.
// Please read the remarks on MSDN for the hProcess
// parameter.
status = SymInitialize(hCurrentProcess, null, false);
if (status == false)
{
Console.Out.WriteLine("Failed to initialize sym.");
return;
}
// Load dll.
baseOfDll = SymLoadModuleEx(hCurrentProcess,
IntPtr.Zero,
"c:\\windows\\system32\\user32.dll",
null,
0,
0,
IntPtr.Zero,
0);
if (baseOfDll == 0)
{
Console.Out.WriteLine("Failed to load module.");
SymCleanup(hCurrentProcess);
return;
}
// Enumerate symbols. For every symbol the
// callback method EnumSyms is called.
if (SymEnumerateSymbols64(hCurrentProcess,
BaseOfDll, EnumSyms, IntPtr.Zero) == false)
{
Console.Out.WriteLine("Failed to enum symbols.");
}
// Cleanup.
SymCleanup(hCurrentProcess);
}
In order to keep the example simple I did not use the
SymEnumSymbols function. I've also did the example
without using such classes as the SafeHandle class of
the .Net framework. If you need a example for the
SymEnumSymbols function, just let me know.
Related
I am trying to use EasyHook to detect native LoadLibrary calls.
It indeed detects the loading of libraries, however the process results in freezing.
This is because the LoadLibrary_Hook method below cannot load the dll or library since It returns 0 IntPtr (Probably can't find the library.).
I even tried setting the events to a "void" type but then the process simply crashes, this is probably because EasyHook expects me to return a value to overwrite the function.
Is there a way for me to return the exactly needed library to be loaded, or just simply get the name of the library that is being loaded without me having to load the library manually?
(There are also names like this which are loading in the process: 瑮汤汤l邐邐讐嗿謘ౕ㍓四襗ﱝ嶉觬嶉觰嶉㯨࿓トă謀ࡅ쌻萏Ͽ䶋㬔瓋㤉ᡝ萏ϯ팻Ѵ᪉ᢉ疋㬐ă㬀瓋謇ᡅᦉᢉ綋㬜 which is kinda odd...)
private static LocalHook hook;
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern IntPtr GetProcAddress(IntPtr handle, string varormethodname);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
public delegate IntPtr LoadLibraryDelegate(string lpFileName);
public TestHook()
{
IntPtr kernel32 = GetModuleHandle("kernel32.dll");
Logger.Log("Kernel: " + kernel32);
IntPtr address = GetProcAddress(kernel32, "LoadLibraryA");
Logger.Log("Address: " + address);
hook = LocalHook.Create(address,
new LoadLibraryDelegate(LoadLibrary_Hook),
null);
hook.ThreadACL.SetExclusiveACL(new Int32[] {0});
//RemoteHooking.WakeUpProcess();
}
public IntPtr LoadLibrary_Hook(string lpFileName)
{
Logger.Log("File load: " + lpFileName);
return LoadLibrary(lpFileName);
}
Solution was to call the original method using the original function address:
public IntPtr LoadLibrary_Hook(string lpFileName)
{
Logger.Log("File load: " + lpFileName);
LoadLibraryDelegate origMethod = (LoadLibraryDelegate)Marshal.GetDelegateForFunctionPointer(LoadLibraryAddress, typeof(LoadLibraryDelegate));
return origMethod(lpFileName);
}
I have a C++ dll for monitoring printers (using FindFirstPrinterChangeNotification). I am making C# Wrapper for it:
private static class NativeMethods {
[DllImport("kernel32", SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32", SetLastError = true)]
public static extern bool FreeLibrary(IntPtr hModule);
}
public string LibPath;
private IntPtr LibPtr;
private GBtMX GBtMain;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void GBtMX();
public GhostBuster() {
LibPath = AppDomain.CurrentDomain.BaseDirectory + #"\GhostBusterC.dll";
}
public string Init() {
if (!File.Exists(LibPath))
return "Incorrect path " + LibPath;
LibPtr = NativeMethods.LoadLibrary(LibPath);
if (LibPtr == IntPtr.Zero)
return "Couldn't import library. Error(GetLastWin32Error): " + Marshal.GetLastWin32Error().ToString();
IntPtr GBtMainPtr = NativeMethods.GetProcAddress(LibPtr, "tmain");
if (GBtMainPtr == IntPtr.Zero)
return "No access to GhostBuster.tmain. Error (GetLastWin32Error): " + Marshal.GetLastWin32Error().ToString();
GBtMain = (GBtMX)Marshal.GetDelegateForFunctionPointer(GBtMainPtr, typeof(GBtMX));
return "";
It returns "No access to GhostBuster.tmain. Error (GetLastWin32Error): 0".
What am i doing wrong?
Thanks in advance.
You don't specify SetLastError in your p/invoke, so that's why Marshal.GetLastWin32Error() is failing to return anything useful. The p/invoke should be
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetProcAddress(
IntPtr hModule,
[MarshalAs(UnmanagedType.LPStr)]
string lpProcName
);
Note also that it makes sense to be explicit about the marshaling of the procedure name. That is always an ANSI string, reflecting the PE format.
When you make this change I expect that the error will be ERROR_PROC_NOT_FOUND indicating that the DLL does not export anything with the name that you passed to GetProcAddress.
Check that you spelled the function name correctly. Did you get the letter case right? Is there any decoration or mangling applied when the DLL is built? Use a tool like dumpbin or Dependency Walker to check the names of the DLL's exports.
I'm trying to use late binding on CreateProcess function in kernel32.dll, however, it returns a null value unlike any other function.
Here's the code I'm using for the late binding
public abstract class LateBinding
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, BestFitMapping = false, SetLastError = true), SuppressUnmanagedCodeSecurity()]
private static extern LBHandle LoadLibrary(string fileName);
[DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity()]
private static extern IntPtr GetProcAddress(LBHandle hModule, string procname);
private Delegate Result = default(Delegate);
public Delegate Call(string library, string method, Type type)
{
LBHandle Lib = LoadLibrary(library);
if (!Lib.IsInvalid && !Lib.IsClosed)
{
Result = Marshal.GetDelegateForFunctionPointer(GetProcAddress(Lib, method), type);
Lib.Close();
}
return Result;
}
}
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public sealed class LBHandle : SafeHandleZeroOrMinusOneIsInvalid
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeLibrary(IntPtr hModule);
private LBHandle() : base(true) { }
protected override bool ReleaseHandle()
{
return FreeLibrary(handle);
}
}
and this how I invoke the function
private delegate bool dCreateProcess(string applicationName, string commandLine, IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUP_INFORMATION startupInfo, ref PROCESS_INFORMATION processInformation);
dCreateProcess CreateProcess = Call("kernel32.dll", "CreateProcess", typeof(dCreateProcess)) as dCreateProcess;
There is no function named CreateProcess in kernel32. It exists in two versions CreateProcessA (ANSI) and CreateProcessW (Unicode). You can see that at the button the documentation for CreateProcess on MSDN.
This is not unique to CreateProcess almost every Win32 API function that takes a string will have an A and a W version.
The following is what you want:
dCreateProcess CreateProcess = Call("kernel32.dll", "CreateProcessW", typeof(dCreateProcess)) as dCreateProcess;
See also What is the difference between CreateProcess and CreateProcessA?
kernel32.dll does not actually export a function entry point with the name CreateProcess - it's either CreateProcessA or in your case CreateProcessW for unicode (Wide) arguments.
Is there a way to call "IsWow64Process" function from kernel32 capitalized? Like "ISWOW64PROCESS"? Or completely lowered like "iswow64process"?
And if no, are there any hack-arrounds to achieve this task? Thanks!
C# is a case sensitive language, but you can define the pinvoke call any way you like, you just need to be consistent. You can map the EntryPoint in your PInvoke call and define the function to be all uppercase like this:
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi, EntryPoint = "IsWow64Process")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ISWOW64PROCESS([In] IntPtr processHandle,
[Out, MarshalAs(UnmanagedType.Bool)] out bool wow64Process);
private void button1_Click_2(object sender, EventArgs e)
{
bool is64;
ISWOW64PROCESS(Process.GetCurrentProcess().Handle, out is64);
MessageBox.Show(is64.ToString());
}
The DllImportAttribute.EntryPoint field allows you to specify the real name of the imported function.
Directly from the example at that link are two lines that show how you can rename the MessageBox function:
[DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "MessageBox")]
public static extern int MyNewMessageBoxMethod(IntPtr hWnd, String text, String caption, uint type);
I'am going to use a kernel32 dll in asp.net web application. This is the code:
//DllGetClassObject function pointer signature
private delegate int DllGetClassObject(ref Guid ClassId, ref Guid InterfaceId, [Out, MarshalAs(UnmanagedType.Interface)] out object ppunk);
//Some win32 methods to load\unload dlls and get a function pointer
private class Win32NativeMethods
{
[DllImport("kernel32.dll", CharSet=CharSet.Ansi)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string lpFileName);
}
public string GetTheDllHandle (dllName)
{
IntPtr dllHandle = Win32NativeMethods.LoadLibrary(dllName); // the dllHandle=IntPtr.Zero
return dllHandle.ToString();
}
The problem that when I call my function GetTheDllHandle, the dllHandle return zero
Did anybody out there made something similar? Or does anybody have any suggestions?
Returning 0 while loading DLLs is coming due to several reasons like , DLL is not there on specified path or DLLs is not supported with platform or dependent dlls are not loaded before you build your native DLL. so you can track these errors by set true for SetLastError property
DllImport("kernel32.dll", EntryPoint = "LoadLibrary", SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
public string GetTheDllHandle (dllName)
{
IntPtr dllHandle = Win32NativeMethods.LoadLibrary(dllName); // the dllHandle=IntPtr.Zero
if (dllHandle == IntPtr.Zero)
return Marshal.GetLastWin32Error().ToString(); // Error Code while loading DLL
else
return dllHandle.ToString(); // Loading done !
}