I'm using a Silicon Labs VCP (CP2105) under Windows (7/8/10) and I am trying to obtain some info from it using the Silicon Labs runtime DLL - which is unmanaged.
This is my implementation:
[DllImport("CP210xRuntime.dll")]
private static extern Int32 CP210xRT_GetDeviceProductString(IntPtr handle, IntPtr bfPtr, ref uint len, bool convert);
public static Int32 GetProduct(IntPtr handle)
{
var buff = new char[100];
GCHandle hnd = GCHandle.Alloc(buff);
IntPtr bfPtr = (IntPtr)hnd;
uint bytesRead = 0;
var r = CP210xRT_GetDeviceProductString(handle, bfPtr, ref bytesRead, true);
hnd.Free();
return r;
}
I am getting the device handle for the ports using:
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateFile(
string FileName,
uint DesiredAccess,
uint ShareMode,
IntPtr SecurityAttributes,
uint CreationDisposition,
uint FlagsAndAttributes,
IntPtr hTemplateFile
);
When I run this it works - of sorts, that is to say the return value is 0 which, according to the Silicon Labs docs, indicates all is well, and I have confirmed this by using a handle to another device and I got 3 back, which confirms invalid handle.
The bytesRead ref value is also ammended as expected to 36 which is what the length of the product name should be. But the buff array never fills with any data (just to be sure I have written values to each element as well but they dont change). If I leave the program running the whole thing throws an exception:
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in********
Additional information: The runtime has encountered a fatal error. The address of the error was at 0x70338780, on thread 0x1f5c. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
This is also the program does, if I comment out the line where I call the function from the dll - the program does not fail.
I'm not massively familar with invoke unmanged code using C# so if someone could help me out with where I am going wrong / point me in the right direction I would be most grateful!
This is from the Silicon Labs Docs:
CP210x_STATUS CP210xRT_GetDeviceProductString(HANDLE cyHandle,
LPVOID lpProduct, LPBYTE lpbLength, BOOL bConvertToASCII = TRUE)
Related
On a system with a non-US keyboard / culture, I am receiving a Barcode from a scanner as keyboard input. The scanner can be set to different cultures. In my case it is set to en-US. In this case the system language and the barcode scanner language encoding are different.
I have declared this function to decode:
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int ToUnicodeEx(uint virtualKeyCode, uint scanCode, byte[] keyboardState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)] StringBuilder receivingBuffer, int bufferSize, uint flags, IntPtr dwhkl);
I use the method below to load a keyboard layout:
[DllImport("user32.dll")]
private static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags);
I use the method like below:
// loads the interpretation of the key into buf.
ToUnicodeEx(key, scankey, keyboardState, buf, 256, 0, LoadKeyboardLayout("00000409", 1));
My usage of the method works - the interpretation is correct - BUT I have a side effect that my system language setting is affected. Before method call it looks like this:
And after the method call it looks like this:
How can I fix my code so that my system's language is not affected?
I have tried to change flags parameter of the LoadKeyboardLayout to 0, but then ToUnicodeEx uses the system language, not the loaded en-US.
I'm sure that almost four years later you've either solved this or no longer care. I'll put the answer here in case someone else comes across this, though.
The last parameter of LoadKeyboardLayout is dwFlags. You gave it 1, which is equivalent to KLF_ACTIVATE, or "load this bad boy up and make it my keyboard!"
You want to call it with 0, which tells it to just load the layout, give you a handle (IntPtr) to it, and do nothing else.
I'm sorry I couldn't help you back when you posted this. :-)
I'm trying to read a process's memory, but the address I would like to start reading from exceeds the IntPtr and UIntPtr limit.
[DllImport("kernel32.dll", EntryPoint = "ReadProcessMemory")]
private static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, [Out] int lpNumberOfBytesRead);
ReadProcessMemory(ProcessHandle, (IntPtr)0x14EC7B38A, buffer, buffer.Length, bytesused);
Doing this produces a OverflowException exception even if I use a UIntPtr. I have tried using a ulong, but this produces an AccessViolationException exception. What other data type should I use?
Windows is a 64-bit OS. UInt is 64bits wide. I assume the problem is that your application is either built for 32bit or is built to "Prefer 32bit" (the Visual Studio defaults).
This answer has the details of the setting you want to change.
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.
I've noticed something very strange. I was trying to call the CRT function "putchar", and was unable to get it to work. So I double-checked that I wasn't missing something, and I copied the code directly from the P/Invoke tutorial on MSDN to see if it worked.
http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx
You'll notice that they import "puts".
So I tested the exact code copied from MSDN. It didn't work! So now I got frustrated. I've never had this problem before.
Then I just so happened to run WITHOUT debugging (hit ctrl+f5), and it worked! I tested other functions which output to the console too, and none of them work when debugging but all work when not debugging.
I then wrote a simple C dll which exports a function called "PrintChar(char c)". When I call that function from C#, it works even if I'm debugging or not, without any problems.
What is the deal with this?
The Visual Studio hosting process is capable of redirecting console output to the Output window. How exactly it manages to do this is not documented at all, but it gets in the way here. It intercepts the WriteFile() call that generates the output of puts().
Project + Properties, Debug tab, untick "Enable the Visual Studio hosting process". On that same page, enabling unmanaged debugging also fixes the problem.
It's a bad example, using the C-Runtime Library DLL to call puts. Keep reading the tutorial as there is good info there, but try making Win32 API calls instead.
Here is a better introduction to p/invoke: http://msdn.microsoft.com/en-us/magazine/cc164123.aspx
It's old, but the information is still good.
Edited
My explaination was wrong.
I went looking for a correct explaination and I discovered that the C-Runtime puts method and the .NET Framework Console.Write method differ in how they write to the console (Console.Write works where the p/invoke to puts does not). I thought maybe the answer was in there, so I whipped up this demonstration:
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
class Program
{
public static void Main()
{
int written;
string outputString = "Hello, World!\r\n";
byte[] outputBytes = Encoding.Default.GetBytes(outputString);
//
// This is the way the C-Runtime Library method puts does it
IntPtr conOutHandle = CreateFile("CONOUT$", 0x40000000, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
WriteConsole(conOutHandle, outputBytes, outputString.Length, out written, IntPtr.Zero);
//
// This is the way Console.Write does it
IntPtr stdOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
WriteFile(stdOutputHandle, outputBytes, outputBytes.Length, out written, IntPtr.Zero);
// Pause if running under debugger
if (Debugger.IsAttached)
{
Console.Write("Press any key to continue . . . ");
Console.ReadKey();
}
}
const int STD_OUTPUT_HANDLE = -11;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int WriteFile(IntPtr handle, [In] byte[] bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
static extern bool WriteConsole(IntPtr hConsoleOutput, [In] byte[] lpBuffer, int nNumberOfCharsToWrite, out int lpNumberOfCharsWritten, IntPtr mustBeZero);
}
Both of those successfully output under the debugger, even with the hosting process enabled. So that is a dead end.
I wanted to share it in case it leads someone else to figuring out why it happens -- Hans?
I'm trying to run an executable directly from a byte[] representation of this executable as a resource in C#.
So basically i want to run a byte[] of an PE directly without touching the harddisk.
The code I'm using for this used to work but it doesn't anymore.
The code creates a process with a frozen main thread, changes the whole process data and finally resumes it so it runs the byte[] of the PE. But it seems like the process dies if the thread is resumed, i don't really know whats wrong.
So here is the code in a pastebin because its too long for here i guess...
http://pastebin.com/18hfFvHm
EDIT:
I want to run non-managed code !
Any PE File ...
Here is some code to execute native code (inside a byte array). Note that it is not exactly what you are asking for (it's not a PE file bytes, but a native procedure bytes ie. in assembly language)
using System;
using System.Runtime.InteropServices;
namespace Native
{
class Program
{
private const UInt32 MEM_COMMIT = 0x1000;
private const UInt32 PAGE_EXECUTE_READWRITE = 0x40;
private const UInt32 MEM_RELEASE = 0x8000;
[DllImport("kernel32")] private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
[DllImport("kernel32")] private static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, UInt32 dwFreeType);
[DllImport("kernel32")]
private static extern IntPtr CreateThread(
UInt32 lpThreadAttributes,
UInt32 dwStackSize,
UInt32 lpStartAddress,
IntPtr param,
UInt32 dwCreationFlags,
ref UInt32 lpThreadId
);
[DllImport("kernel32")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
static void Main(string[] args)
{
byte[] nativecode = new byte[] { /* here your native bytes */ };
UInt32 funcAddr = VirtualAlloc(0, (UInt32)nativecode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(nativecode, 0, (IntPtr)(funcAddr), nativecode.Length);
IntPtr hThread = IntPtr.Zero;
UInt32 threadId = 0;
hThread = CreateThread(0, 0, funcAddr, IntPtr.Zero, 0, ref threadId);
WaitForSingleObject(hThread, 0xFFFFFFFF);
CloseHandle(hThread);
VirtualFree((IntPtr)funcAddr, 0, MEM_RELEASE);
}
}
}
This code may help:
Dynamic Process Forking of Portable Executable by Vrillon / Venus:
http://forum.gamedeception.net/threads/16557-Process-Forking-Running-Process-From-Memory
Leaving this here for everyone.
USE RUNPE
Look it up, works great :) I suggest self inject.
i found that sample, hope it will be useful for you.
http://www.cyberhackers.mybbnew.com/showthread.php?tid=178
I haven't tried this, so it's purely specutive, but I believe you want to load in into the AppDomain:
byte[] myAssm = ...
AppDomain.CurrentDomain.Load(myAssm);
AppDomain.CurrentDomain.ExecuteAssemblyByName(nameOfMyAssm);
I'm not sure if this will be much help, but here is where I answer running straight x86/x64 assembly opcodes from a C# program.
I believe your problem is that you are asking for a security hole.
To run any PE, you are asking -- "Let my secure/managed .NET app run an insecure/unmanaged app -- In a way which bypasses normal security".
Let's say I run you application (which I assume is secure). I've not given it permission to write to sensitive folder; it can't overrun buffers; it can't touch my win32 mode code. You then build, byte-by-byte, a malicious application in a byts[], and launch that. Where does Windows step in to ask me if I want to let this happen? And what does that warning say ? "Is that array of bytes from a trusted source?"
In theory, if you are running full trust, there is nothing stopping you from doing CreateProcess on rundll32.exe, unmapping rundll32.exe, and performing the initial EXE load yourself.
The way I'd go about it is inject a thread into the target process that does the work in an unmanaged way. Yes, this means piles of relocatable assembly.
The general idea is to call LdrUnloadModule to get rid of rundll32.exe, call LdrLoadModule to load the EXE, fixup the load chain to indicate it was loaded first, then restart the main thread.
Good luck to you.
Repost of Load an EXE file and run it from memory
Not tested but looks like to be the only way to do this (2nd answer)