Dll error return pointer from openni - pointers

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

Related

decrypt function at run time and use it QT c++

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.

STL Vector Exception on Erase in unmanaged code

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)

QtInputContextFactory returning NULL on embedded target

On my embedded system I don't have X11, Mac, Win, S60, etc. I keep getting a NULL ( 0 ) pointer returned from the create method of the QInputContextFactory class. I verified that QT_NO_LIBRARY is not defined.
On my Desktop Qt Build this works just fine.
I also verified that my custom key and parent are being passed to the method.
What could cause this to fail? -->
if (QInputContextFactoryInterface *factory =
qobject_cast<QInputContextFactoryInterface*>(loader()->instance(key))) {
result = factory->create(key);
}
Here is the entire method:
QInputContext *QInputContextFactory::create( const QString& key, QObject *parent )
{
QInputContext *result = 0;
#if defined(Q_WS_X11) && !defined(QT_NO_XIM)
if (key == QLatin1String("xim")) {
result = new QXIMInputContext;
}
#endif
#if defined(Q_WS_WIN)
if (key == QLatin1String("win")) {
result = new QWinInputContext;
}
#endif
#if defined(Q_WS_MAC)
if (key == QLatin1String("mac")) {
result = new QMacInputContext;
}
#endif
#if defined(Q_WS_S60)
if (key == QLatin1String("coefep")) {
result = new QCoeFepInputContext;
}
#endif
#ifdef QT_NO_LIBRARY
Q_UNUSED(key);
#else
qDebug() << "Here we are";
if (QInputContextFactoryInterface *factory =
qobject_cast<QInputContextFactoryInterface*>(loader()->instance(key))) {
result = factory->create(key);
}
#endif
if (result)
result->setParent(parent);
return result;
}
Within Qt, the QInputContextFactory class is front-end on loading input context plug-ins. It will fail to load an input context plug-in if it fails to exist, or hasn't been deployed properly. Input context plug-ins are typically stored under $QT_PLUGIN_PATH/inputmethods. As such, if there is no plug-in within that directory, the create method of the QInputContextFactory will return NULL.
Of note, Qt does provide a few mechanisms for customizing the location of plug-ins. Refer to the following for more detail on this:
http://qt-project.org/doc/qt-4.8/deployment-plugins.html

Qt moc_file issues

I'm a student programmer and I am using Qt to build some GUI applications for work and I have been running into moc issues over and over again. I was hoping for a solution to the current problem that I am having; however, if anyone more veteraned in Qt could shed some light on how to properly handle these files while making changes to your cpp file(s) I'd appreciate any help. In my most recent change (sorry I can't post what it did look like, because it's obviously been restructured) I was validating data by nesting a function inside of my checkData function. Because I would like a specific error to appear for each field that might be invalid I began to create a function for each QLineEdit. I realized that this would not work (or at least make more work) then instead of just providing sequenced checks of information. Below is the new code without the original nested function:
void InjectionDialog::checkData() {
bool validateFluidVelocity;
QString tempStrFluidVelocity;
tempStrFluidVelocity = ui->lineEditFluidVelocity->text();
double convertedFluidVelocity =
tempStrFluidVelocity.toDouble(&validateFluidVelocity);
if (validateFluidVelocity == false) {
QErrorMessage validateErrorFluidVelocityError;
validateErrorFluidVelocityError.
showMessage("Fluid velocity input is invalid");
validateErrorFluidVelocityError.exec();
}
else {
transData.lineEditFluidVelocity = convertedFluidVelocity;
}
bool validateFluidMassFlow;
QString tempStrFluidMassFlow;
tempStrFluidMassFlow = ui->lineEditFluidMassFlow->text();
double convertedFluidMassFlow =
tempStrFluidMassFlow.toDouble(&validateFluidMassFlow);
if (validateFluidMassFlow == false) {
QErrorMessage validateErrorFluidMassFlowError;
validateErrorFluidMassFlowError.
showMessage("Fluid mass flow input is invalid");
validateErrorFluidMassFlowError.exec();
}
else {
transData.lineEditFluidMassFlow = convertedFluidMassFlow;
}
bool validateParticleVelocity;
QString tempStrParticleVelocity;
tempStrParticleVelocity = ui->lineEditParticleVelocity->text();
double convertedParticleVelocity =
tempStrParticleVelocity.toDouble(&validateParticleVelocity);
if (validateParticleVelocity == false) {
QErrorMessage validateErrorParticleVelocity;
validateErrorParticleVelocity.
showMessage("Particle velocity input is invalid");
validateErrorParticleVelocity.exec();
}
else {
transData.lineEditParitcle_sic_Velocity = convertedParticleVelocity;
}
bool validateParticleMassFlow;
QString tempStrParticleMassFlow;
tempStrParticleMassFlow = ui->lineEditParticleMassFlow->text();
double convertedParticleMassFlow =
tempStrParticleMassFlow.toDouble(&validateParticleMassFlow);
if (validateParticleMassFlow == false) {
QErrorMessage validateErrorParticleMassFlow;
validateErrorParticleMassFlow.
showMessage("Particle mass flow input is invalid");
validateErrorParticleMassFlow.exec();
}
else {
transData.lineEditParticleMassFlow = convertedParticleMassFlow;
}
}
Initially I had InjectionDialog::checkFluidVelociy for the first check but decided against it pretty quickly. Now with the code restructured I receive the error:
In function 'InjectionDialog::checkFluidVelocity(QMetaObject::Call, int, void**)':
this error is referenced to moc_injectionDialog.o
unidentified reference to 'InjectionDialog::checkFluidVelocity()'
this error is referenced to moc_injectiondialog.cpp
In moc_injectiondialog I have the following I have the following listed:
/****************************************************************************
** Meta object code from reading C++ file 'injectiondialog.h'
**
** Created: Sat Jan 7 21:58:22 2012
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.4)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../InjectionGUI/injectiondialog.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'injectiondialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.4. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_InjectionDialog[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
17, 16, 16, 16, 0x08,
29, 16, 16, 16, 0x08,
0 // eod
};
static const char qt_meta_stringdata_InjectionDialog[] = {
"InjectionDialog\0\0checkData()\0"
"checkFluidVelocity()\0"
};
const QMetaObject InjectionDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_InjectionDialog,
qt_meta_data_InjectionDialog, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &InjectionDialog::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *InjectionDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *InjectionDialog::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_InjectionDialog))
return static_cast<void*>(const_cast< InjectionDialog*>(this));
return QDialog::qt_metacast(_clname);
}
int InjectionDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: checkData(); break;
case 1: checkFluidVelocity(); break;
default: ;
}
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
I have looked over some of the other moc_file posts and most of them say to have Qt clean and rebuild the project. I have ran a project clean up and rebuild all to try to overhaul this moc file but have not had any success in getting rid of the error. It seems like a bug but I couldn't find anything online about it so maybe it's something I don't know about. Thanks in advance for any help you can offer.
Whenever I have MOC problems, I Build->Clean All and then Build->Run qmake (Qt Creator IDE). If that doesn't solve my problem, I go into my project folder and delete moc_* files and any other junk that Clean doesn't remove - basically leaving nothing but headers, source and resources.
Go to you moc file which is throwing the error. At the top, there will be an include statement, which includes the header file for that window, NOT ui_.h, just .h
check in that file if there is a reference to the widget which is causing the error.

segfault after return 0;

I wrote a program to test my binary tree and when I run it, the program seems to crash (btree.exe has stopped working, Windows is checking for a solution ...).
When I ran it through my debugger and placed the breakpoint on the function I suspect is causing it, destroy_tree(), it seemed to run as expected and returned back to the main function. Main, in turn, returned from the program but then the cursor jumped back to destroy_tree() and looped recusively within itself.
The minimal code sample is below so it can be ran instantly. My compiler is MinGW and my debugger is gdb (I'm using Code::Blocks).
#include <iostream>
using namespace std;
struct node
{
int key_value;
node *left;
node *right;
};
class Btree
{
public:
Btree();
~Btree();
void insert(int key);
void destroy_tree();
private:
node *root;
void destroy_tree(node *leaf);
void insert(int key, node *leaf);
};
Btree::Btree()
{
root = NULL;
}
Btree::~Btree()
{
destroy_tree();
}
void Btree::destroy_tree()
{
destroy_tree(root);
cout<<"tree destroyed\n"<<endl;
}
void Btree::destroy_tree(node *leaf)
{
if(leaf!=NULL)
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
}
}
void Btree::insert(int key, node *leaf)
{
if(key < leaf->key_value)
{
if(leaf->left!=NULL)
insert(key, leaf->left);
else
{
leaf->left = new node;
leaf->left->key_value = key;
leaf->left->left = NULL;
leaf->left->right = NULL;
}
}
else if (key >= leaf->key_value)
{
if(leaf->right!=NULL)
insert(key, leaf->right);
else
{
leaf->right = new node;
leaf->right->key_value = key;
leaf->right->left = NULL;
leaf->right->right = NULL;
}
}
}
void Btree::insert(int key)
{
if(root!=NULL)
{
insert(key, root);
}
else
{
root = new node;
root->key_value = key;
root->left = NULL;
root->right = NULL;
}
}
int main()
{
Btree tree;
int i;
tree.insert(1);
tree.destroy_tree();
return 0;
}
As an aside, I'm planning to switch from Code::Blocks built-in debugger to DDD for debugging these problems. I heard DDD can display visually pointers to objects instead of just displaying the pointer's address. Do you think making the switch will help with solving these types of problems (data structure and algorithm problems)?
Your destroy_tree() is called twice, you call it once and then it gets called after the execution leaves main() from the destructor.
You may think it should work anyway, because you check whether leaf!=NULL, but delete does not set the pointer to NULL. So your root is not NULL when destroy_tree() is called for the second time,
Not directly related (or maybe it is) to your problem, but it's good practice to give structs a constructor. For example:
struct node
{
int key_value;
node *left;
node *right;
node( int val ) : key_val( val ), left(NULL), right(NULL) {}
};
If you do this, your code becomes simpler, because you don't need worry about setting the pointers when you create a node, and it is not possible to forget to initialise them.
Regarding DDD, it;'s a fine debugger, but frankly the secret of debugging is to write correct code in the first place, so you don't have to do it. C++ gives you a lot of help in this direction (like the use of constructors), but you have to understand and use the facilities it provides.
Btree::destroy_tree doesn't set 'root' to 0 after successfully nuking the tree. As a result, the destructor class destroy_tree() again and you're trying to destroy already destroyed objects.
That'll be undefined behaviour then :).
Once you destroy the root.
Make sure it is NULL so it does not try to do it again (from the destructor)
void Btree::destroy_tree(node *leaf)
{
if(leaf!=NULL)
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
leaf = NULL; // add this line
}
}

Resources