Reinterpret_cast sent data - c++

The code below is just an example.
Function1 is a dllexport, how do I properly convert/read the value of data inside of Foo2?
When I print the value, it returns 000001DFA1C501F3.
Function1(PVOID InPassThruBuffer, ULONG InPassThruSize);
void Foo(std::wstring* data) {
Function1(&data, sizeof(wchar_t))
}
// ==============================================
typedef struct _REMOTE_ENTRY_INFO_
{
UCHAR* UserData;
ULONG UserDataSize;
}REMOTE_ENTRY_INFO;
void __stdcall Foo2(REMOTE_ENTRY_INFO* inRemoteInfo)
{
std::wstring wdata;
if (inRemoteInfo->UserDataSize == sizeof(wchar_t))
wdata = reinterpret_cast<wchar_t *>(inRemoteInfo->UserData);
}

Try something more like this instead:
void Foo(std::wstring* data)
{
Function1(const_cast<wchar_t*>(data->c_str()), data->size() * sizeof(wchar_t));
// or, in C++17 and later:
// Function1(data->data(), data->size() * sizeof(wchar_t));
}
void __stdcall Foo2(REMOTE_ENTRY_INFO* inRemoteInfo)
{
wchar_t *wdata = reinterpret_cast<wchar_t*>(inRemoteInfo->UserData);
int wdatalen = inRemoteInfo->UserDataSize / sizeof(wchar_t);
}
Or, if Foo2() in called in the context of Function1() before Foo() exits, then you can just pass the std::wstring* pointer itself instead:
void Foo(std::wstring* data)
{
Function1(&data, sizeof(data));
// or, if Function1() does not *copy* the data,
// merely passes around the provided pointer as-is:
//
// Function1(data, sizeof(*data));
}
void __stdcall Foo2(REMOTE_ENTRY_INFO* inRemoteInfo)
{
std::wstring *wdata = *reinterpret_cast<std::wstring**>(inRemoteInfo->UserData);
// or:
// std::wstring *wdata = reinterpret_cast<std::wstring*>(inRemoteInfo->UserData);
}

Related

Using std::string in ImGui::InputText(...)

The call to ImGui::InputText() takes a char array which I need to initialise from a std::string and then transfer the contents back to the std::string. In it's simplest form:
char buf[255]{};
std::string s{"foo"};
void fn() {
strncpy( buf, s.c_str(), sizeof(buf)-1 );
ImGui::InputText( "Text", buf, sizeof(buf) );
s=buf;
}
However, it appears wasteful to have two buffers (buf and the buffer allocated within std::string) both doing much the same thing. Can I avoid the buf buffer and the copying to and from it by using just the std::string and a simple wrapper "X".
I don't care about efficiency, I just want the simplest code at the call site.
This code does work but is it safe and is there a better way?
class X {
public:
X(std::string& s) : s_{s} { s.resize(len_); }
~X() { s_.resize(strlen(s_.c_str())); }
operator char*(){ return s_.data(); }
static constexpr auto len() { return len_-1; }
private:
std::string& s_;
static constexpr auto len_=255;
};
std::string s{"foo"};
void fn() {
ImGui::InputText( "Text", X(s), X::len() );
}
If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp.
misc/cpp/imgui_stdlib.h
namespace ImGui
{
// ImGui::InputText() with std::string
// Because text input needs dynamic resizing, we need to setup a callback to grow the capacity
IMGUI_API bool InputText(const char* label, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextMultiline(const char* label, std::string* str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
}
Your first code
std::string s{"foo"};
void fn() {
ImGui::InputText( "Text", &s );
}
Reading manuals works wonders.

How convert char * (char pointer) to PCSZ?

I have a method that has a mandatory parameter as char* and I want convert to PCSZ before RtlInitiAnsiString() and the result of uName after RtlAnsiStringToUnicodeString() to be the correct value.
How can I do this?
NTSTATUS myMethod(char *myName)
{
ANSI_STRING aName;
UNICODE_STRING uName;
OBJECT_ATTRIBUTES ObjAttr;
RtlInitAnsiString(&aName, myName);
status = RtlAnsiStringToUnicodeString(&uName, &aName, TRUE);
if(!NT_SUCCESS(status))
{
DbgPrint("RtlAnsiStringToUnicodeString Error");
return status;
}
InitializeObjectAttributes(&ObjAttr, &uName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
// some code here
//...
RtlFreeUnicodeString(&uName);
return status;
}
EDITION 01:
To a better understand here is how MyMethod() is used in my kernel driver:
struct MyData
{
ULONG Value[3];
char *Str1;
char *Str2;
};
NTSTATUS Function_IRP_DEVICE_CONTROL(PDEVICE_OBJECT pDeviceObject, PIRP Irp)
{
PIO_STACK_LOCATION pIoStackLocation;
struct MyData *pData = (struct MyData*) Irp->AssociatedIrp.SystemBuffer;
pIoStackLocation = IoGetCurrentIrpStackLocation(Irp);
switch (pIoStackLocation->Parameters.DeviceIoControl.IoControlCode)
{
case IOCTL_DATA :
DbgPrint("IOCTL DATA");
DbgPrint("%lu \n %lu \n %lu \n %s \n %s", pData->Value[0], pData->Value[1], pData->Value[2], pData->Str1, pData->Str2);
...
break;
}
...
//////////// Calling MyMethod() //////////////
myMethod(pData->Str1);
There's nothing to convert. PCSZ is a Pointer to Constant String Zero-terminated. So, it's just const char *. char * is implicitly convertible to const char *.
I consider such typedefs horrible, but unfortunately, Microsoft APIs make heavy use of them.

Can't figure out syntax to call multiple object functions as separate threads

I have an array of objects and want each one to call a member function in a separate thread (so they run concurrently). I'm using _beginthreadex and can get it to work fine for a standard function but can't figure out the syntax to pass the member function to the _beginthreadex call. Here's an example of what I'm doing (the block of code after the second comment does not compile):
#include <Windows.h>
#include <process.h>
#include <stdio.h>
unsigned __stdcall mythread(void* data) {
printf("\nThread %d", GetCurrentThreadId());
return 0;
}
class myClass {
public:
unsigned __stdcall myClass::myThread(void* data);
};
unsigned __stdcall myClass::myThread(void* data) {
printf("\nThread %d", GetCurrentThreadId());
return(0);
}
int main(int argc, char* argv[]) {
int i, numThreads = 5;
// this works
HANDLE *myHandle = new HANDLE[numThreads];
for(i=0;i<numThreads;i++) myHandle[i] = (HANDLE)_beginthreadex(0, 0, &mythread, 0, 0, 0);
WaitForMultipleObjects(numThreads, myHandle, true, INFINITE);
for(i=0;i<numThreads;i++) CloseHandle(myHandle[i]);
getchar();
delete myHandle;
// this does not compile - not sure of syntax to call myObject[i].myThread in _beginthreadex
HANDLE *myHandle2 = new HANDLE[numThreads];
myClass *myObject = new myClass[numThreads];
for(i=0;i<numThreads;i++) myHandle2[i] = (HANDLE)_beginthreadex(0, 0, &myObject[i].myThread, 0, 0, 0);
WaitForMultipleObjects(numThreads, myHandle2, true, INFINITE);
for(i=0;i<numThreads;i++) CloseHandle(myHandle2[i]);
getchar();
delete myObject;
delete myHandle2;
return 0;
}
Thanks in advance for any help!
rgames
You cannot get address of member fuinction using
&myObject[i].myThread
correct way is like this
&myClass::myThread
In C++ functions and member functions have different signature like
/* pointer for this function would have type void(*)(int, float) */
void foo(int, float) { /* ... */ }
class A {
public:
/* pointer for this function would have type void(A::*)(int, float) */
void foo(int, float) { /* ... */ }
};
they are have different type even they both return void and take int and float.
As you can see in msdn the _beginthread function takes function as
unsigned (__stdcall *)( void * )
but you are trying to pass
unsigned (__stdcall myClass::*)( void* )
So to correct your code you can do:
Method 1: you need to write another function, something like
unsigned __stdcall mymemberthread(void* data) {
if (data != NULL) {
myClass* m = (myClass*)data;
m->myThread(m + 1);
}
return 0;
}
And create thread like
(HANDLE)_beginthreadex(0, 0, &mymemberthread, &myObject[i], 0, 0);
Method 2: make function myClass::myThread static
class myClass {
public:
static unsigned __stdcall myThread(void* data);
};
unsigned __stdcall myClass::myThread(void* data) {
printf("\nThread %d", GetCurrentThreadId());
if (data != NULL) {
myClass* m = (myClass*)data;
m->myThread(m + 1);
}
return(0);
}
...
(HANDLE)_beginthreadex(0, 0, &myClass::myThread, &myObject[i], 0, 0);
Method 3: if this is acceptabe use STL and std::thread, this will make you code more generic.

How to wrap a char* buffer in a WinRT IBuffer in C++

I want to implement a C++ WinRT IBuffer that wraps a char* buffer, so i can use it with WinRT WriteAsync/ReadAsync operations that accept an IBuffer^ parameter.
EDIT 1 (clarification)
I want to avoid data copy.
Mostly copied from http://jeremiahmorrill.wordpress.com/2012/05/11/http-winrt-client-for-c/ but adapted to directly wrap my own byte[]:
NativeBuffer.h:
#pragma once
#include <wrl.h>
#include <wrl/implements.h>
#include <windows.storage.streams.h>
#include <robuffer.h>
#include <vector>
// todo: namespace
class NativeBuffer :
public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::WinRtClassicComMix>,
ABI::Windows::Storage::Streams::IBuffer,
Windows::Storage::Streams::IBufferByteAccess>
{
public:
virtual ~NativeBuffer()
{
}
STDMETHODIMP RuntimeClassInitialize(byte *buffer, UINT totalSize)
{
m_length = totalSize;
m_buffer = buffer;
return S_OK;
}
STDMETHODIMP Buffer(byte **value)
{
*value = m_buffer;
return S_OK;
}
STDMETHODIMP get_Capacity(UINT32 *value)
{
*value = m_length;
return S_OK;
}
STDMETHODIMP get_Length(UINT32 *value)
{
*value = m_length;
return S_OK;
}
STDMETHODIMP put_Length(UINT32 value)
{
m_length = value;
return S_OK;
}
private:
UINT32 m_length;
byte *m_buffer;
};
To create the IBuffer:
Streams::IBuffer ^CreateNativeBuffer(LPVOID lpBuffer, DWORD nNumberOfBytes)
{
Microsoft::WRL::ComPtr<NativeBuffer> nativeBuffer;
Microsoft::WRL::Details::MakeAndInitialize<NativeBuffer>(&nativeBuffer, (byte *)lpBuffer, nNumberOfBytes);
auto iinspectable = (IInspectable *)reinterpret_cast<IInspectable *>(nativeBuffer.Get());
Streams::IBuffer ^buffer = reinterpret_cast<Streams::IBuffer ^>(iinspectable);
return buffer;
}
And the call to read data (lpBuffer is the byte[]):
Streams::IBuffer ^buffer = CreateNativeBuffer(lpBuffer, nNumberOfbytes);
create_task(randomAccessStream->ReadAsync(buffer, (unsigned int)nNumberOfBytesToRead, Streams::InputStreamOptions::None)).wait();
I am not so sure if the ComPtr needs some cleanup, so any suggestions regarding memory management are welcome.
This should work:
// Windows::Storage::Streams::DataWriter
// Windows::Storage::Streams::IBuffer
// BYTE = unsigned char (could be char too)
BYTE input[1024] {};
DataWriter ^writer = ref new DataWriter();
writer->WriteBytes(Platform::ArrayReference<BYTE>(input, sizeof(input));
IBuffer ^buffer = writer->DetachBuffer();

Can we implement c++ thunk in linux?

I want to use class member functions as callbacks, I don't use libsigc, because it's slow.
In ATL, we can use member function for C-style callback(http://www.codeproject.com/KB/cpp/SoloGenericCallBack.aspx), so can we implement c++ thunk in linux?
The code below will crash:
#include <assert.h>
#include <stdio.h>
#include <sys/mman.h>
typedef char BYTE;
typedef int DWORD;
typedef int* DWORD_PTR;
typedef int* INT_PTR;
typedef bool BOOL;
typedef unsigned long ULONG;
typedef unsigned long* ULONG_PTR;
#define PtrToUlong( p ) ((ULONG)(ULONG_PTR) (p) )
#define __stdcall __attribute__((__stdcall__))
//#pragma pack( push, 1 )
struct MemFunToStdCallThunk
{
BYTE m_mov;
DWORD m_this;
BYTE m_pushEax;
BYTE m_jmp;
DWORD m_relproc;
void Init( DWORD_PTR proc, void* pThis )
{
printf("proc=%x\n", proc);
m_mov = 0xB8; // mov eax
m_this = PtrToUlong(pThis);
m_pushEax = 0xc3;// push eax
m_jmp = 0xe9; //jmp
m_relproc = DWORD((INT_PTR)proc - ((INT_PTR)this+sizeof(MemFunToStdCallThunk)));
printf("m_relproc = %x\n", m_relproc);
mprotect(this, sizeof(MemFunToStdCallThunk), PROT_READ|PROT_WRITE|PROT_EXEC);
}
void* GetCodeAddress()
{
return this;
}
}__attribute__ ((packed));
//#pragma pack( pop )
template< typename TDst, typename TSrc >
TDst UnionCastType( TSrc src )
{
union
{
struct
{
int* pfn; //function,index
long delta; // offset,
}funcPtr;
TSrc uSrc;
}uMedia;
uMedia.uSrc = src;
return uMedia.funcPtr.pfn;
}
typedef int ( __stdcall *StdCallFun)(int, int);
class CTestClass
{
public:
int m_nBase;
MemFunToStdCallThunk m_thunk;
int memFun( int m, int n )
{
int nSun = m_nBase + m + n;
printf("m=%d,n=%d,nSun=%d\n", m, n, nSun);
return 1234;
}
public:
CTestClass()
{
m_nBase = 10;
}
void Test()
{
printf("%x\n", &CTestClass::memFun);
m_thunk.Init(UnionCastType<DWORD_PTR>(&CTestClass::memFun), this );
StdCallFun fun = (StdCallFun)m_thunk.GetCodeAddress();
assert( fun != NULL );
int ret = fun( 9, 3 );
printf("ret = %x\n", ret);
}
};
int main()
{
CTestClass test;
test.Test();
return 0;
}
EDIT:
Thanks to user786653, I get the right answer:
#include <assert.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
typedef char BYTE;
typedef int DWORD;
typedef int* DWORD_PTR;
typedef int* INT_PTR;
typedef bool BOOL;
typedef unsigned long ULONG;
typedef unsigned long* ULONG_PTR;
#define PtrToUlong(p) ((ULONG)(ULONG_PTR) (p) )
#define __stdcall __attribute__((__stdcall__))
struct MemFunToStdCallThunk
{
BYTE m_repairStack[10];
DWORD m_mov;
DWORD m_this;
BYTE m_jmp;
DWORD m_relproc;
void Init( DWORD_PTR proc, void* pThis )
{
printf("proc=%p\n", proc);
m_repairStack[0] = 0x83; //sub esp, 0x4
m_repairStack[1] = 0xec;
m_repairStack[2] = 0x04;
m_repairStack[3] = 0x8b; //mov eax,[esp + 0x4]
m_repairStack[4] = 0x44;
m_repairStack[5] = 0x24;
m_repairStack[6] = 0x04;
m_repairStack[7] = 0x89;//mov [esp], eax
m_repairStack[8] = 0x04;
m_repairStack[9] = 0x24;
m_mov = 0x042444C7; // mov dword ptr [esp+0x4],
m_this = PtrToUlong(pThis);
m_jmp = 0xe9; //jmp
m_relproc = (DWORD)proc - ((DWORD)this+sizeof(MemFunToStdCallThunk));
printf("m_relproc = %d\n", m_relproc);
//long page_size = sysconf(_SC_PAGE_SIZE);
//mprotect((void*)(PtrToUlong(this) & -page_size), 2*page_size, PROT_READ|PROT_WRITE|PROT_EXEC);
}
void* GetCodeAddress()
{
return this;
}
}__attribute__ ((packed));
template< typename TDst, typename TSrc >
TDst UnionCastType( TSrc src )
{
union
{
struct
{
int* pfn; //function or index
long delta; // offset
}funcPtr;
TSrc uSrc;
}uMedia;
uMedia.uSrc = src;
return uMedia.funcPtr.pfn;
}
typedef int ( __stdcall *StdCallFun)(int, int);
class CTestClass
{
public:
int m_nBase;
MemFunToStdCallThunk m_thunk;
int memFun( int m, int n )
{
printf("this=%p\n", this);
int nSun = m_nBase + m + n;
printf("m=%d,n=%d,nSun=%d\n", m, n, nSun);
return nSun;
}
public:
CTestClass()
{
m_nBase = 10;
}
void Test()
{
int (CTestClass::*abc)(int, int);
printf("sizeof(MemFunToStdCallThunk)=%d,sizeof(abc)=%d\n", sizeof(MemFunToStdCallThunk), sizeof(abc));
printf("memFun=%p\n", &CTestClass::memFun);
m_thunk.Init(UnionCastType<DWORD_PTR>(&CTestClass::memFun), this );
StdCallFun fun = (StdCallFun)m_thunk.GetCodeAddress();
assert( fun != NULL );
int ret = memFun(2, 3);
printf("ret 1= %d\n", ret);
ret = fun( 9, 3 );
printf("ret 2= %d\n", ret);
}
};
int main()
{
CTestClass test;
test.Test();
return 0;
}
Yes, but I wouldn't recommend it. It will (obviously) make your code a lot less portable and you're potentially opening a security hole if you're not careful.
You will need to make the code executable with mprotect(2). Something like mprotect(&thunk_struct, sizeof(struct _CallBackProcThunk), PROT_READ|PROT_WRITE|PROT_EXEC).
Also the normal GCC syntax for structure packing is struct S { /* ... */ } __attribute__ ((packed)) though newer versions might support the #pragma pack syntax.
You will probably also want to substitute DWORD with uint32_t from stdint.h and BYTE with uint8_t (or just stick a typedef in there).
EDIT:
From the man page on mprotect "[..]addr must be aligned to a page boundary". You should check the return value. Try doing something like this instead:
long page_size = sysconf(_SC_PAGE_SIZE);
uintptr_t addr = ((uintptr_t)this) & -page_size;
if (mprotect((void*)addr, 2*page_size, PROT_READ|PROT_WRITE|PROT_EXEC)) {
perror("mprotect");
/* handle error */
}
The following calculation is wrong:
DWORD((INT_PTR)proc - ((INT_PTR)this+sizeof(MemFunToStdCallThunk)))
It's doing its calculations on int*'s.
(DWORD)proc - ((DWORD)this+sizeof(MemFunToStdCallThunk)
should be sufficient here.
A very ugly (non-portable etc. etc.), but small and self-contained example follows:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/mman.h>
struct thunk {
uint32_t mov;
uint32_t this_ptr;
uint8_t jmp;
uint32_t rel;
} __attribute__((packed));
class Test {
public:
virtual int foo(void) {
printf("foo! %p\n", (void*)this);
return 42;
}
};
int main()
{
Test test;
printf("%d\n", test.foo());
thunk t;
t.mov = 0x042444C7;
t.this_ptr = (uint32_t)&test;
t.jmp = 0xe9;
t.rel = ((uint32_t)(void*)&Test::foo) - ((uint32_t)&t + sizeof(thunk));
uint32_t addr = (uint32_t)&t;
long page_size = sysconf(_SC_PAGE_SIZE);
if (mprotect((void*)(addr & -page_size), 2*page_size, PROT_READ|PROT_WRITE|PROT_EXEC)) {
perror("mprotect");
return 1;
}
union {
void* p;
int (*foo)(int);
} u;
u.p = &t;
printf("%d\n", u.foo(0));
return 0;
}
A reasonable approach is something like this:
struct Foo {
void doit();
};
extern "C" {
void callback(void *handle) {
reinterpret_cast<Foo*>(handle)->doit();
}
}
The assembly of callback looks like this here (x64):
callback:
jmpq _ZN3Foo4doitEv
You can't pass pointer-to-member pointers to C callbacks directly, but there are portable tricks (i.e. not restricted to one target OS) that work very well.
The easiest way to do that is just to use a wrapper non-member function whose only purpose is to call your member function.
void wrapper()
{
object->callWhatever();
}
You can pass wrapper() as a function pointer.
See also for example Cast member function for create_pthread() call for how to handle cases where you get a void* parameter with the callback and want to use that to store (directly or not) a reference/pointer to the object you want to operate on.
I want to use class member functions as callbacks, I don't use libsigc, because it's slow. In ATL, we can use member function for C-style callback(http://www.codeproject.com/KB/cpp/SoloGenericCallBack.aspx), so can we implement c++ thunk in linux?
You probably can. However, there is no need to.
Most asynchronous APIs allow to pass a void* argument when registering for an asynchronous event. When the event gets reported this void* is reported as well and can be used to call a member function of an object. (Vague language because APIs like epoll_wait() don't actually call you back, where as pthread_create() does.).