This is a static function which is an unmanaged function which I am trying to call from a managed CLR project. But everytime I add the erase an exception happens. Both classes are inside the same project
I keep getting an exception on the erase,
#pragma managed(push, off)
void MessageContainer::ParseByteStream(UINT8 *buf, int length)
{
s_RxBufVector.insert(s_RxBufVector.end(), buf, buf + length);
if (s_RxBufVector.size() >= sizeof(Msg_Struct) * 2)
{
int BytesConsumed = 0;
s_RxBufIterator = s_RxBufVector.begin();
while (BytesConsumed < (int)s_RxBufVector.size() - sizeof(Msg_Struct))
{
if (ntohl(*((UINT32 *)&s_RxBufVector[BytesConsumed + __PREAMBLE_OFFSET])) == PreambleVal)
{
switch (ntohl(*((UINT32 *)&s_RxBufVector[BytesConsumed + __COMMAND_ID_OFFSET])))
{
case eCommandIdRxMsg:
if (MsgRx != nullptr)
(*MsgRx)(ntohl(*((UINT32*)&s_RxBufVector[BytesConsumed + __ID_OFFSET])), ntohs(*((UINT16*)(&s_RxBufVector[BytesConsumed + __CHANNEL_OFFSET]))),
ntohs(*((UINT16*)&s_RxBufVector[BytesConsumed + __LENGTH_OFFSET])), &s_RxBufVector[BytesConsumed + __BUFFER_OFFSET]);
break;
case eCommandIdCmdAck:
if (CmdAck != nullptr)
//(*CmdAck())
break;
case eCommandIdSendAck:
if (TxConf != nullptr)
//(*TxConf())
break;
default:
break;
}
BytesConsumed += sizeof(Msg_Struct);
}
else
{
BytesConsumed++;
}
}
s_RxBufVector.erase(s_RxBufIterator, s_RxBufIterator + BytesConsumed);
}
}
private:
static std::vector<UINT8, std::allocator<UINT8>> s_RxBufVector;
static std::vector<UINT8>::iterator s_RxBufIterator;
Init()
{
s_RxBufVector.reserve(4096);
}
Is there something wrong with the Vector accessing.
An unhandled exception of type 'System.AccessViolationException' occurred
Break stops here
_Adopt(_Right._Myproxy->_Mycont);
Worse is that I was trying to delete 24 Bytes at the beginning when the size is already 48
EDIT:
Ok, I found commenting out the code for the callback to the managed code solves the Exception but does not help me either
(*MsgRx)(ntohl(*((UINT32*)&s_RxBufVector[BytesConsumed + __ID_OFFSET])), ntohs(* (UINT16*)(&s_RxBufVector[BytesConsumed + __CHANNEL_OFFSET]))), ntohs(*((UINT16*)&s_RxBufVector[BytesConsumed + __LENGTH_OFFSET])), &s_RxBufVector[BytesConsumed + __BUFFER_OFFSET]);
The Callback is declared here
delegate void MessageReceivedCallbackDelegate(UInt32 Id, UInt16 Channel, UInt16 len, Byte *data);
MessageContainer::SetMessageRxCB((void*)Marshal::GetFunctionPointerForDelegate(gcnew MessageReceivedCallbackDelegate(MessageReceived)));
unmanaged
void MessageContainer::SetMessageRxCB(void *fn)
{
MsgRx = (RxCbFn)fn;
}
Seems like the managed code is causing some problems to the vector. Probably something wrong with how I try to call the managed code, I need some hints :)
SOLVED:
Ok, I forgot to decorate the delegates
[UnmanagedFunctionPointerAttribute(CallingConvention::Cdecl)]
delegate void MessageReceivedCallbackDelegate(UInt32 Id, UInt16 Channel, UInt16 Dlc, Byte *data)
Related
I have an input QString that has HTML 4 entities, like õ that I’d like to decode. But I can’t find any facilities in Qt to do so. Is there a way to do so in Qt? If possible I’d like to avoid QTextDocument so I don’t have to bring in QtGui.
The HTML 4 entities are listed in this link:
https://www.w3schools.com/charsets/ref_html_entities_4.asp
Out of curiosity, I have looked a bit around.
I found this SO: How can i convert entity character(Escape character) to HTML in QT?. However, it uses QTextDocument (which is part of GUI) what OP wants to prevent.
The doc. of QTextDocument::setHtml() doesn't mention anything specific whether something is used which could be accessed directly (and is even part of the Qt core). Hence, I had a look into source code. I started with QTextDocument::setHtml() on woboq.org and followed the bread crumbs.
Finally, I ended up in qtbase/src/gui/text/qtexthtmlparser.cpp:
QString QTextHtmlParser::parseEntity()
{
const int recover = pos;
int entityLen = 0;
QStringRef entity;
while (pos < len) {
QChar c = txt.at(pos++);
if (c.isSpace() || pos - recover > 9) {
goto error;
}
if (c == QLatin1Char(';'))
break;
++entityLen;
}
if (entityLen) {
entity = QStringRef(&txt, recover, entityLen);
QChar resolved = resolveEntity(entity);
if (!resolved.isNull())
return QString(resolved);
if (entityLen > 1 && entity.at(0) == QLatin1Char('#')) {
entity = entity.mid(1); // removing leading #
int base = 10;
bool ok = false;
if (entity.at(0).toLower() == QLatin1Char('x')) { // hex entity?
entity = entity.mid(1);
base = 16;
}
uint uc = entity.toUInt(&ok, base);
if (ok) {
if (uc >= 0x80 && uc < 0x80 + (sizeof(windowsLatin1ExtendedCharacters)/sizeof(windowsLatin1ExtendedCharacters[0])))
uc = windowsLatin1ExtendedCharacters[uc - 0x80];
QString str;
if (QChar::requiresSurrogates(uc)) {
str += QChar(QChar::highSurrogate(uc));
str += QChar(QChar::lowSurrogate(uc));
} else {
str = QChar(uc);
}
return str;
}
}
}
error:
pos = recover;
return QLatin1String("&");
}
A table of named entities can be found in the same source file:
static const struct QTextHtmlEntity { const char name[9]; quint16 code; } entities[]= {
{ "AElig", 0x00c6 },
{ "AMP", 38 },
...
{ "zwj", 0x200d },
{ "zwnj", 0x200c }
};
Q_STATIC_ASSERT(MAX_ENTITY == sizeof entities / sizeof *entities);
These are bad news for OP:
The API of the QTextHtmlParser is private:
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
and it's part of Qt GUI.
If OP insists to prevent GUI dependencies, the only other chance I see is to duplicate the code (or just to re-implement it from scratch).
I'm new to QT and I'm trying to create an encrypted function.
Overall what you do in C / C ++ is:
Take pointer to function
make the function page rwx
Encrypt it (for the example I encrypt and decrypt in the same program)
Decrypt it and run it
A simple code in C will happen roughly like this:
void TestFunction()
{
printf("\nmsgbox test encrypted func\n");
}
// use this as a end label
void FunctionStub() { return; }
void XorBlock(DWORD dwStartAddress, DWORD dwSize)
{
char * addr = (char *)dwStartAddress;
for (int i = 0; i< dwSize; i++)
{
addr[i] ^= 0xff;
}
}
DWORD GetFuncSize(DWORD* Function, DWORD* StubFunction)
{
DWORD dwFunctionSize = 0, dwOldProtect;
DWORD *fnA = NULL, *fnB = NULL;
fnA = (DWORD *)Function;
fnB = (DWORD *)StubFunction;
dwFunctionSize = (fnB - fnA);
VirtualProtect(fnA, dwFunctionSize, PAGE_EXECUTE_READWRITE, &dwOldProtect); // make function page read write execute permission
return dwFunctionSize;
}
int main()
{
DWORD dwFuncSize = GetFuncSize((DWORD*)&TestFunction, (DWORD*)&FunctionStub);
printf("use func");
TestFunction();
XorBlock((DWORD)&TestFunction, dwFuncSize); // XOR encrypt the function
printf("after enc");
//TestFunction(); // If you try to run the encrypted function you will get Access Violation Exception.
XorBlock((DWORD)&TestFunction, dwFuncSize); // XOR decrypt the function
printf("after\n");
TestFunction(); // Fine here
getchar();
}
When I try to run such an example in QT I get a run time error.
Here is the code in QT:
void TestFunction()
{
QMessageBox::information(0, "Test", "msgbox test encrypted func");
}
void FunctionStub() { return; }
void XorBlock(DWORD dwStartAddress, DWORD dwSize)
{
char * addr = (char *)dwStartAddress;
for (int i = 0; i< dwSize; i++)
{
addr[i] ^= 0xff; // here i get seg. fault
}
}
DWORD GetFuncSize(DWORD* Function, DWORD* StubFunction)
{
DWORD dwFunctionSize = 0, dwOldProtect;
DWORD *fnA = NULL, *fnB = NULL;
fnA = (DWORD *)Function;
fnB = (DWORD *)StubFunction;
dwFunctionSize = (fnB - fnA);
VirtualProtect(fnA, dwFunctionSize, PAGE_EXECUTE_READWRITE, &dwOldProtect); // Need to modify our privileges to the memory
QMessageBox::information(0, "Test", "change func to read write execute ");
return dwFunctionSize;
}
void check_enc_function()
{
DWORD dwFuncSize = GetFuncSize((DWORD*)&TestFunction, (DWORD*)&FunctionStub);
QMessageBox::information(0, "Test", "use func");
TestFunction();
XorBlock((DWORD)&TestFunction, dwFuncSize); // XOR encrypt the function -> ### i get seg fault in here ###
QMessageBox::information(0, "Test", "after enc");
TestFunction(); // If you try to run the encrypted function you will get Access Violation Exception.
XorBlock((DWORD)&TestFunction, dwFuncSize); // XOR decrypt the function
QMessageBox::information(0, "Test", "after dec");
TestFunction(); // Fine here
getchar();
}
Why should this happen?
QT is supposed to behave like precision as standard C ++ ...
post Scriptum.
Interestingly in the same matter, what is the most legitimate way to keep an important function encrypted (the reason it is encrypted is DRM)?
Legitimately I mean that anti-viruses will not mistakenly mark me as a virus because I defend myself.
PS2
If I pass an encrypted function over the network (say, I will build a server client schema that the client asks for the function it needs to run from the server and the server sends it to it if it is approved) How can I arrange the symbols so that the function does not collapse?
PS3
How in QT can I turn off the DEP and ASLR defenses? (In my opinion so that I can execute PS 2. I have to cancel them)
Thanks
yoko
The example is undefined behaviour on my system.
The first and main issue in your code is:
void TestFunction() { /* ... */ }
void FunctionStub() { return; }
You assume that the compiler will put FunctionStub after TestFunction without any padding. I compiled your example and FunctionStub in my case was above TestFunction which resulted in a negative dwFunctionSize.
dwFunctionSize = (fnB - fnA);
TestFunction located at # 0xa11d90
FunctionStub located at # 0xa11b50
dwFunctionSize = -0x240
Also in XorBlock
addr[i] ^= 0xff;
Is doing nothing.
I assume you want to write in XorBlock to the memory location to XOR the entire TestFunction.
You could do something like this:
void XorBlock(DWORD dwStartAddress, DWORD dwSize)
{
DWORD dwEndAddress = dwStartAddress + dwSize;
for(DWORD i = dwStartAddress; i < dwEndAddress; i++) {
// ...
}
}
I can't see any Qt-specific in your example. Even if it's Qt function call it's just a call. So I guess you have undefined behaviour in both examples but only second one crashes.
I can't see any reason for compiler and linker to keep function order. For example GCC let you specify the code section for each function. So you can reorder it in executable without reordering in cpp.
I think you need some compiler specific things to make it work.
void ChangeStates(void)
{
int i;
for (i=0; i<CELLS; i++)
{
switch (state[i])
{
case IMMUNE:
timer[i]--;
if(timer[i]==0)
state[i] = HEALTHY;
break;
case INFECTED:
timer[i]--;
if(timer[i]==0)
{
state[i] = IMMUNE;
timer[i] = IMM_TIME;
}
break;
case EXPOSED:
timer[i]--;
if(timer[i]==0)
{
state[i] = INFECTED;
timer[i] = INF_TIME;
}
break;
default:
} //Here is the error
}
}
The program intend to do something about disease dynamics in plants, and use the switch function to change the state of cells.
I am using Qt Creator 5.5 as a beginner.
But I do not know how to fix this error.
Thanks in advance
'default' has to be followed by a statement, 'break;' will work. Or remove the default as was suggested, this might mean better warnings also (unhandled enumeration value in switch, which is always good to catch).
You could also do 'qFatal' in the default to again catch an unhandled state[] value in the switch.
I have been implementing the module to send the bytes in chunks, 20 bytes each onto the MCU device via BLE. When it comes to writing the bytes more than 60 bytes and so on, the last chunk of the bytes ( usually less than 20 bytes) is often missed. Hence, the MCU device cannot get the checksum and write the value. I have modified the call back to Thread.sleep(200) to change it but it sometimes works on writing 61 bytes or sometimes not. Would you please tell me are there any synchronous method to write the bytes in chunks ? The below is my working :
#Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
try {
Thread.sleep(300);
if (status != BluetoothGatt.GATT_SUCCESS) {
disconnect();
return;
}
if(status == BluetoothGatt.GATT_SUCCESS) {
System.out.println("ok");
broadcastUpdate(ACTION_DATA_READ, mReadCharacteristic, status);
}
else {
System.out.println("fail");
broadcastUpdate(ACTION_DATA_WRITE, characteristic, status);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized boolean writeCharacteristicData(BluetoothGattCharacteristic characteristic ,
byte [] byteResult ) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
return false;
}
boolean status = false;
characteristic.setValue(byteResult);
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
status = mBluetoothGatt.writeCharacteristic(characteristic);
return status;
}
private void sendCommandData(final byte [] commandByte) {
// TODO Auto-generated method stub
if(commandByte.length > 20 ){
final List<byte[]> bytestobeSent = splitInChunks(commandByte);
for(int i = 0 ; i < bytestobeSent.size() ; i ++){
for(int k = 0 ; k < bytestobeSent.get(i).length ; k++){
System.out.println("LumChar bytes : "+ bytestobeSent.get(i)[k] );
}
BluetoothGattService LumService = mBluetoothGatt.getService(A_SERVICE);
if (LumService == null) { return; }
BluetoothGattCharacteristic LumChar = LumService.getCharacteristic(AW_CHARACTERISTIC);
if (LumChar == null) { System.out.println("LumChar"); return; }
//Thread.sleep(500);
writeCharacteristicData(LumChar , bytestobeSent.get(i));
}
}else{
....
You need to wait for the onCharacteristicWrite() callback to be invoked before sending the next write. The typical solution is to make a job queue and pop a job off the queue for each callback you get to onCharacteristicWrite(), onCharacteristicRead(), etc.
In other words, you can't do it in a for loop unfortunately, unless you want to set up some kind of lock that waits for the callback before going on to the next iteration. In my experience a job queue is a cleaner general-purpose solution though.
i was trying to write a plugin for return RGB image stream from ASUS Xtion PRO LIVE using openni.
So in my Dll program i implement getdata() function of VideoFrameRef class to return pointer from image data. when i call this function from my test program it throws an exception.
hear is my dll code
void* MyRgbStrem::GetStream()
{
Device device;
VideoStream color;
VideoFrameRef vframeRef;
VideoMode vmode;
Status status = STATUS_OK;
status = openni::OpenNI::initialize ();
status = device.open(openni::ANY_DEVICE);
status = color.create (device, SENSOR_COLOR);
status = color.start();
while (true)
{
if (device.getSensorInfo(SENSOR_COLOR) != NULL)
{
status = color. readFrame(&vframeRef);
if (vframeRef.isValid())
{
return ( uint16_t*) vframeRef.getData();
}
}
}
}
and in the header file i declar class MyRgbStrem
namespace Rgbstream
{
class MyRgbStrem
{
public:
static __declspec(dllexport) void* GetStream();
};
}
in my test program i use opencv for image processing and to get frame width, height and size i declae few more functions in dll program and call them in test application
this is the program i use to call dll
{
Mat rgb,bgr;
int height, width, size;
height = Rgbstream::MyRgbStrem::GetFrameSize_H();
width = Rgbstream::MyRgbStrem::GetFrameSize_W();
size = Rgbstream::MyRgbStrem::getSizeOfData();
bgr.create ( height,width, CV_8UC3);
rgb.create (height,width, CV_8UC3);
while (true)
{
const void* imgbuff = Rgbstream::MyRgbStrem::GetStream();
memcpy (bgr.data, imgbuff, size );
cvtColor(rgb,bgr, CV_RGB2BGR);
namedWindow ("Color Video",CV_WINDOW_AUTOSIZE);
imshow ("Color Video", bgr);
char key = waitKey (10);
if (key == 27) break;
}
return 0;
}
when i run this program it throws an exception like this
Unhandled exception at 0x0F97E89A (msvcr110d.dll) in CallRgbStream.exe: 0xC0000005: Access violation reading location 0x00268000.
The program '[9544] CallRgbStream.exe' has exited with code 0 (0x0).
any help is appreciate. thanks