ROS cv_bridge::toCvCopy fails with segmentation fault - c++

I'm experiencing a weird segmentation fault. When executing cv_bridge::toCvCopy in a ROS node, it fails with segmentation fault. I'm sure that the given message has data, and the code is enclosed with try...catch.
ROS version: kinetic, OpenCV version: 2.4, Ubuntu version: 16.04.
Code:
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
void ImageCallback(const sensor_msgs::ImageConstPtr& msg)
{
std::cerr<<"msg->header: "<<msg->header<<std::endl;
std::cerr<<"msg->height: "<<msg->height<<std::endl;
std::cerr<<"msg->width: "<<msg->width<<std::endl;
std::cerr<<"msg->encoding: "<<msg->encoding<<std::endl;
std::cerr<<"msg->is_bigendian: "<<int(msg->is_bigendian)<<std::endl;
std::cerr<<"msg->step: "<<msg->step<<std::endl;
std::cerr<<"msg->data.size(): "<<msg->data.size()<<std::endl;
std::cerr<<"msg->data[0,1,2]: "<<int(msg->data[0])<<" "<<int(msg->data[1])<<" "<<int(msg->data[2])<<std::endl;
std::cerr<<"msg->data[size()-1]: "<<int(msg->data[msg->data.size()-1])<<std::endl;
std::cerr<<"msg->data[size()-2]: "<<int(msg->data[msg->data.size()-2])<<std::endl;
std::cerr<<"msg->data[size()-3]: "<<int(msg->data[msg->data.size()-3])<<std::endl;
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
std::cerr<<"debug.p1"<<std::endl;
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
std::cerr<<"cv_ptr: "<<cv_ptr<<std::endl;
std::cerr<<"cv_ptr->image: "<<cv_ptr->image<<std::endl;
cv::Mat frame= cv_ptr->image;
cv::imshow("camera",frame);
char c(cv::waitKey(1));
if(c=='\x1b'||c=='q') ros::shutdown();
}
int main(int argc, char**argv)
{
ros::init(argc, argv, "sub_img_node");
ros::NodeHandle node("~");
std::string img_topic("/camera/color/image_raw");
if(argc>1) img_topic= argv[1];
cv::namedWindow("camera",1);
ros::Subscriber sub_img= node.subscribe(img_topic, 1, &ImageCallback);
ros::spin();
return 0;
}
Output:
msg->header: seq: 352
stamp: 1610458354.727051013
frame_id: head_camera
msg->height: 480
msg->width: 640
msg->encoding: rgb8
msg->is_bigendian: 0
msg->step: 1920
msg->data.size(): 921600
msg->data[0,1,2]: 207 224 219
msg->data[size()-1]: 209
msg->data[size()-2]: 212
msg->data[size()-3]: 201
Segmentation fault (core dumped)
From the result, we can see that the topic msg has data correctly and the line next to cv_bridge::toCvCopy is not executed, so the segmentation fault happened at cv_bridge::toCvCopy.
Furthermore, I analyzed the core dump with gdb:
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from bin/sub_img_node...done.
[New LWP 101971]
[New LWP 101976]
[New LWP 101983]
[New LWP 101984]
[New LWP 101981]
[New LWP 101972]
[New LWP 101982]
[New LWP 101974]
[New LWP 101975]
warning: Unexpected size of section `.reg-xstate/101971' in core file.
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `bin/sub_img_node /usb_cam/image_raw'.
Program terminated with signal SIGSEGV, Segmentation fault.
warning: Unexpected size of section `.reg-xstate/101971' in core file.
#0 0x00007fb2f5026b44 in cv::_InputArray::type(int) const () from /usr/lib/x86_64-linux-gnu/libopencv_core.so.2.4
[Current thread is 1 (Thread 0x7fb2f628fac0 (LWP 101971))]
(gdb) bt
#0 0x00007fb2f5026b44 in cv::_InputArray::type(int) const () from /usr/lib/x86_64-linux-gnu/libopencv_core.so.2.4
#1 0x00007fb2efa655bc in cv::cvtColor(cv::_InputArray const&, cv::_OutputArray const&, int, int) ()
from /opt/ros/kinetic/lib/x86_64-linux-gnu/libopencv_imgproc3.so.3.3
#2 0x00007fb2f5505cf3 in cv_bridge::toCvCopyImpl(cv::Mat const&, std_msgs::Header_<std::allocator<void> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) ()
from /opt/ros/kinetic/lib/libcv_bridge.so
#3 0x00007fb2f5506103 in cv_bridge::toCvCopy(sensor_msgs::Image_<std::allocator<void> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () from /opt/ros/kinetic/lib/libcv_bridge.so
#4 0x00007fb2f55061e0 in cv_bridge::toCvCopy(boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () from /opt/ros/kinetic/lib/libcv_bridge.so
#5 0x00000000004074fb in ImageCallback (msg=...) at /home/akihikoy/prg/ay_test/ros/cpp_ros/test2/src/sub_img_node.cpp:49
#6 0x000000000040a91b in boost::function1<void, boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const> const&>::operator() (a0=...,
this=<optimized out>) at /usr/include/boost/function/function_template.hpp:773
#7 boost::detail::function::void_function_obj_invoker1<boost::function<void (boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const> const&)>, void, boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const> >::invoke(boost::detail::function::function_buffer&, boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const>) (function_obj_ptr=..., a0=...) at /usr/include/boost/function/function_template.hpp:159
#8 0x000000000040af63 in boost::function1<void, boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const> >::operator() (a0=..., this=<optimized out>)
at /usr/include/boost/function/function_template.hpp:773
#9 ros::SubscriptionCallbackHelperT<boost::shared_ptr<sensor_msgs::Image_<std::allocator<void> > const> const&, void>::call (this=0x12915e0, params=...)
at /opt/ros/kinetic/include/ros/subscription_callback_helper.h:144
#10 0x00007fb2f5ec2e2d in ros::SubscriptionQueue::call() () from /opt/ros/kinetic/lib/libroscpp.so
#11 0x00007fb2f5e686f8 in ros::CallbackQueue::callOneCB(ros::CallbackQueue::TLS*) () from /opt/ros/kinetic/lib/libroscpp.so
#12 0x00007fb2f5e6a0fb in ros::CallbackQueue::callAvailable(ros::WallDuration) () from /opt/ros/kinetic/lib/libroscpp.so
#13 0x00007fb2f5ec6ef9 in ros::SingleThreadedSpinner::spin(ros::CallbackQueue*) () from /opt/ros/kinetic/lib/libroscpp.so
#14 0x00007fb2f5eabedb in ros::spin() () from /opt/ros/kinetic/lib/libroscpp.so
#15 0x0000000000406276 in main (argc=2, argv=0x7ffe650933c8) at /home/akihikoy/prg/ay_test/ros/cpp_ros/test2/src/sub_img_node.cpp:78
However I could not find the reason of the error. Could anyone suggest a solution?

I do not why, but I solved this issue by replacing /opt/ros/kinetic/lib/libcv_bridge.so with libcv_bridge.so.0d in the libcv-bridge0d package.
Detailed procedure:
$ sudo apt-get -f install libcv-bridge0d
$ cd /opt/ros/kinetic/lib/
$ sudo mv libcv_bridge.so{,.trouble}
$ sudo ln -s /usr/lib/x86_64-linux-gnu/libcv_bridge.so.0d libcv_bridge.so
Also I had a similar trouble in Python, which could be solved by this:
$ sudo apt-get -f install python-cv-bridge

Related

How to debug a QString causing a bus error?

I have a Raspberry Pi 3B+ with my Qt code on it (Qt 5.12.5). When I run my code, it randomly crashes with a Bus Error after a few hours. I am not sure how to work out the exact cause. I cross compile on Ubuntu for the RPi using the latest Raspberry Pi OS (2020-05-27).
The core dump (I have replaced some irrelevant parts with ...)
pi#raspberrypi: $ gdb TEST core
GNU gdb (Raspbian 8.2.1-2) 8.2.1
...
Type "apropos word" to search for commands related to "word"...
Reading symbols from TEST...done.
[New LWP 1233]
...
[New LWP 1226]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/arm-linux-gnueabihf/libthread_db.so.1".
Core was generated by `./TEST'.
Program terminated with signal SIGBUS, Bus error.
#0 0x755b5b7c in QString::arg(long long, int, int, QChar) const () from /usr/local/qt5pi/lib/libQt5Core.so.5
[Current thread is 1 (Thread 0x6feff440 (LWP 1233))]
(gdb) bt full
#0 0x755b5b7c in QString::arg(long long, int, int, QChar) const () at /usr/local/qt5pi/lib/libQt5Core.so.5
#1 0x0001c0bc in QString::arg(int, int, int, QChar) const (this=0x6fefdc78, a=12, fieldWidth=0, base=10, fillChar=...) at ../raspi/qt5pi/include/QtCore/qstring.h:976
#2 0x00039ff8 in StageState::getStateString() (this=0x6fefdf00) at ../TEST/stage.h:35
...
#7 0x00142124 in TEST::timerExpired() (this=0x7ecd4708) at ../TEST/TEST.cpp:51
__PRETTY_FUNCTION__ = "void TEST::timerExpired()"
locker = {val = 2127384345}
#8 0x0015c188 in TEST::qt_static_metacall(QObject*, QMetaObject::Call, int, void**) (_o=0x7ecd4708, _c=QMetaObject::InvokeMetaMethod, _id=2, _a=0x6fefe9d8) at moc_TEST.cpp:122
_t = 0x7ecd4708
#9 0x75722b08 in QMetaObject::activate(QObject*, int, int, void**) () at /usr/local/qt5pi/lib/libQt5Core.so.5
#10 0x75730c1c in QTimer::timeout(QTimer::QPrivateSignal) () at /usr/local/qt5pi/lib/libQt5Core.so.5
#11 0x75730fc8 in QTimer::timerEvent(QTimerEvent*) () at /usr/local/qt5pi/lib/libQt5Core.so.5
#12 0x75724194 in QObject::event(QEvent*) () at /usr/local/qt5pi/lib/libQt5Core.so.5
#13 0x768c6b88 in QApplicationPrivate::notify_helper(QObject*, QEvent*) () at /usr/local/qt5pi/lib/libQt5Widgets.so.5
#14 0x768ce29c in QApplication::notify(QObject*, QEvent*) () at /usr/local/qt5pi/lib/libQt5Widgets.so.5
#15 0x759b62ec in QCoreApplication::self () at /usr/local/qt5pi/lib/libQt5Core.so.5
(gdb)
../TEST/stage.h:35 refers to this code:
return QString("text %1").arg(aInt);
Possible causes and fixes I am considering:
To me, from the stack trace, it looks like the crashes are occurring inside QString, possibly due to a Qt bug? However I am not sure. I can try a newer version of Qt.
I am also using a QTimer in a thread, maybe this could cause a issue, accessing a object from other threads? I am already using QMutex. I could instead only use the gui thread short term and test if crashes still occur.
Searching online, I found a comment to look a the dmesg output (below), maybe my MicroSD card is dying? I am waiting for a new one to arrive.
Anything else?
pi#raspberrypi:~ $ dmesg
[ 0.000000] Booting Linux on physical CPU 0x0
[ 0.000000] Linux version 5.4.44-v7+ (dom#buildbot) (gcc version 4.9.3 (crosstool-NG crosstool-ng-1.22.0-88-g8460611)) #1320 SMP Wed Jun 3 16:07:06 BST 2020
[ 0.000000] CPU: ARMv7 Processor [410fd034] revision 4 (ARMv7), cr=10c5383d
...
[ 17.898294] Bluetooth: BNEP filters: protocol multicast
[ 17.898313] Bluetooth: BNEP socket layer initialized
[16092.809350] Alignment trap: not handling instruction e1903f9f at [<755b5b78>]
[16092.809367] 8<--- cut here ---
[16092.815191] Unhandled fault: alignment exception (0x001) at 0x6f577277
[16092.820865] pgd = 6aa8fcbe
[16092.826468] [6f577277] *pgd=3278c835, *pte=2812175f, *ppte=28121c7f
Here is another bus error that is similar but not quite the same as previously:
pi#raspberrypi:~/TEST/bin $ gdb TEST core
GNU gdb (Raspbian 8.2.1-2) 8.2.1
...
Type "apropos word" to search for commands related to "word"...
Reading symbols from TEST...done.
[New LWP 767]
...
[New LWP 763]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/arm-linux-gnueabihf/libthread_db.so.1".
Core was generated by `./TEST'.
Program terminated with signal SIGBUS, Bus error.
#0 0x7568d470 in QString::fromAscii_helper(char const*, int) () from /usr/local/qt5pi/lib/libQt5Core.so.5
[Current thread is 1 (Thread 0x709bf440 (LWP 767))]
(gdb) bt
#0 0x7568d470 in QString::fromAscii_helper(char const*, int) () at /usr/local/qt5pi/lib/libQt5Core.so.5
#1 0x75830da4 in () at /usr/local/qt5pi/lib/libQt5Core.so.5
#2 0x0001c030 in QString::QString(char const*) (this=0x709be71c, ch=0x15fa88 "[0-9| ]{3}") at ../raspi/qt5pi/include/QtCore/qstring.h:700
#3 0x00029da8 in Measurement::doesRececivedDataFormatMatchRegex(QString) (this=0x709be7f4, receivedData=...) at ../TEST/Measurement.h:103
...
#12 0x7580c58c in QSocketNotifier::activated(int, QSocketNotifier::QPrivateSignal) () at /usr/local/qt5pi/lib/libQt5Core.so.5
#13 0x7580c90c in QSocketNotifier::event(QEvent*) () at /usr/local/qt5pi/lib/libQt5Core.so.5
#14 0x769a2b88 in QApplicationPrivate::notify_helper(QObject*, QEvent*) () at /usr/local/qt5pi/lib/libQt5Widgets.so.5
#15 0x769aa29c in QApplication::notify(QObject*, QEvent*) () at /usr/local/qt5pi/lib/libQt5Widgets.so.5
#16 0x75a922ec in QCoreApplication::self () at /usr/local/qt5pi/lib/libQt5Core.so.5
Edit: added getStateString() and doesRececivedDataFormatMatchRegex() functions
QString getStateString() {
switch (state) {
case StageState::AEnum:
return QString("text %1").arg(aInt);
...
default:
return QString("Unknown");
}
}
bool Measurement::doesRececivedDataFormatMatchRegex(QString receivedData)
{
QRegExp regExp("[0-9| ]{3}");
return receivedData.indexOf(regExp) != -1;
}

Segmentation fault when communicating with USB device using ftdi

I have a project requiring the use of Maxon EPOS under Linux. They provide libraries and code to integrate under Linux. Links are available below, 2 files libEposCmd.so and libftd2xx.so to copy into /etc/local/lib and /etc/lib and a Definition.h file.
After following the procedure, compiling the file HelloEposCmd.cpp and trying the program to test communication with hardware via USB, the code gets a Segmentation fault.
I have tried the same procedure on other machines, with Ubuntu 14.04 and 16.04 without trouble. So at this point I am not sure what is the problem, my machine, the code, issue with USB or something else.
If that can help, my laptop is a MSI Gl62 and running on Ubuntu 16.04LTS 64 bits. I am not very familiar with Ubuntu.
You can find the 2 library files, Definition.h file and the HelloEposCmd.cpp file.
http://www.maxonmotor.com/medias/sys_master/root/8815100330014/EPOS-Linux-Library-En.zip
And the installation guide: http://www.maxonmotor.com/medias/sys_master/root/8821690073118/EPOS-Command-Library-En.pdf at 9-Integration paragraph.
Here is a sample of the code:
#include <iostream>
#include "Definitions.h"
#include <string.h>
#include <sstream>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <list>
#include <math.h>
typedef void* HANDLE;
typedef int BOOL;
using namespace std;
void* g_pKeyHandle = 0;
unsigned short g_usNodeId = 1;
string g_deviceName;
string g_protocolStackName;
string g_interfaceName;
string g_portName;
int g_baudrate = 0;
const string g_programName = "HelloEposCmd";
#ifndef MMC_SUCCESS
#define MMC_SUCCESS 0
#endif
#ifndef MMC_FAILED
#define MMC_FAILED 1
#endif
#ifndef MMC_MAX_LOG_MSG_SIZE
#define MMC_MAX_LOG_MSG_SIZE 512
#endif
void LogError(string functionName, int p_lResult, unsigned int p_ulErrorCode);
void LogInfo(string message);
void PrintUsage();
void PrintHeader();
void PrintSettings();
int OpenDevice(unsigned int* p_pErrorCode);
int CloseDevice(unsigned int* p_pErrorCode);
void SetDefaultParameters();
int ParseArguments(int argc, char** argv);
int DemoProfilePositionMode(HANDLE p_DeviceHandle, unsigned short p_usNodeId, unsigned int & p_rlErrorCode);
int Demo(unsigned int* p_pErrorCode);
The function where the Segfault appears:
int OpenDevice(unsigned int* p_pErrorCode)
{
int lResult = MMC_FAILED;
char* pDeviceName = new char[255];
char* pProtocolStackName = new char[255];
char* pInterfaceName = new char[255];
char* pPortName = new char[255];
strcpy(pDeviceName, g_deviceName.c_str());
strcpy(pProtocolStackName, g_protocolStackName.c_str());
strcpy(pInterfaceName, g_interfaceName.c_str());
strcpy(pPortName, g_portName.c_str());
LogInfo("Open device...");
g_pKeyHandle = VCS_OpenDevice(pDeviceName, pProtocolStackName, pInterfaceName, pPortName, p_pErrorCode);
if(g_pKeyHandle!=0 && *p_pErrorCode == 0)
{
unsigned int lBaudrate = 0;
unsigned int lTimeout = 0;
if(VCS_GetProtocolStackSettings(g_pKeyHandle, &lBaudrate, &lTimeout, p_pErrorCode)!=0)
{
if(VCS_SetProtocolStackSettings(g_pKeyHandle, g_baudrate, lTimeout, p_pErrorCode)!=0)
{
if(VCS_GetProtocolStackSettings(g_pKeyHandle, &lBaudrate, &lTimeout, p_pErrorCode)!=0)
{
if(g_baudrate==(int)lBaudrate)
{
lResult = MMC_SUCCESS;
}
}
}
}
}
else
{
g_pKeyHandle = 0;
}
delete []pDeviceName;
delete []pProtocolStackName;
delete []pInterfaceName;
delete []pPortName;
return lResult;
}
The main:
int main(int argc, char** argv)
{
int lResult = MMC_FAILED;
unsigned int ulErrorCode = 0;
PrintHeader();
SetDefaultParameters();
if((lResult = ParseArguments(argc, argv))!=MMC_SUCCESS)
{
return lResult;
}
PrintSettings();
if((lResult = OpenDevice(&ulErrorCode))!=MMC_SUCCESS)
{
LogError("OpenDevice", lResult, ulErrorCode);
return lResult;
}
if((lResult = PrepareDemo(&ulErrorCode))!=MMC_SUCCESS)
{
LogError("PrepareDemo", lResult, ulErrorCode);
return lResult;
}
if((lResult = Demo(&ulErrorCode))!=MMC_SUCCESS)
{
LogError("Demo", lResult, ulErrorCode);
return lResult;
}
if((lResult = CloseDevice(&ulErrorCode))!=MMC_SUCCESS)
{
LogError("CloseDevice", lResult, ulErrorCode);
return lResult;
}
return lResult;
}
The result from gdb backtrace:
~/EPOS_Linux_Library/example/src$ gdb HelloEposCmd coreGNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from HelloEposCmd...(no debugging symbols found)...done.
[New LWP 2436]
[New LWP 2437]
[New LWP 2439]
[New LWP 2440]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./HelloEposCmd'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00007fc3eca0a960 in _xend ()
at ../sysdeps/unix/sysv/linux/x86/elision-unlock.c:33
33 ../sysdeps/unix/sysv/linux/x86/elision-unlock.c: No such file or directory.
[Current thread is 1 (Thread 0x7fc3edcbc740 (LWP 2436))]
(gdb) backtrace
#0 0x00007fc3eca0a960 in _xend ()
at ../sysdeps/unix/sysv/linux/x86/elision-unlock.c:33
#1 __lll_unlock_elision (lock=0x10a1138, private=0)
at ../sysdeps/unix/sysv/linux/x86/elision-unlock.c:29
#2 0x00007fc3ec7e2934 in EventDestroy () from /usr/local/lib/libftd2xx.so
#3 0x00007fc3ec7db2e8 in FT_Close () from /usr/local/lib/libftd2xx.so
#4 0x00007fc3ec7e166b in FT_CreateDeviceInfoList ()
from /usr/local/lib/libftd2xx.so
#5 0x00007fc3ed82c911 in CMmcFtd2xxHndlBase::CreateDeviceInfoList(unsigned int*) () from /usr/local/lib/libEposCmd.so
#6 0x00007fc3ed82ca88 in CMmcFtd2xxHndlBase::GetDeviceInfos(std::list<CUsbDeviceInfo*, std::allocator<CUsbDeviceInfo*> >&, unsigned short, unsigned short) ()
from /usr/local/lib/libEposCmd.so
#7 0x00007fc3ed7e2346 in CGatewayUSBToFtd2xxDrv::GetDeviceInfos(std::list<CUsbDeviceInfo*, std::allocator<CUsbDeviceInfo*> >&) ()
from /usr/local/lib/libEposCmd.so
#8 0x00007fc3ed7e2b48 in CGatewayUSBToFtd2xxDrv::InitPortList() ()
from /usr/local/lib/libEposCmd.so
#9 0x00007fc3ed7deed1 in CPort_USB::InitGateway(CStdStr<char>, CGatewayIToDrv*) () from /usr/local/lib/libEposCmd.so
#10 0x00007fc3ed7df232 in CPort_USB::InitPort(CStdStr<char>, CGatewayIToDrv*, CErrorInfo*) () from /usr/local/lib/libEposCmd.so
#11 0x00007fc3ed7cb04f in CInterface_USB::InitPort(CStdStr<char>, CErrorInfo*)
---Type <return> to continue, or q <return> to quit---
() from /usr/local/lib/libEposCmd.so
#12 0x00007fc3ed7cb19e in CInterface_USB::InitInterface(CStdStr<char>, CErrorInfo*) () from /usr/local/lib/libEposCmd.so
#13 0x00007fc3ed7caada in CInterface_USB::InitInterface(CErrorInfo*) ()
from /usr/local/lib/libEposCmd.so
#14 0x00007fc3ed7a6a92 in CInterfaceManager::I_InitInterface(CStdStr<char>, CErrorInfo*) () from /usr/local/lib/libEposCmd.so
#15 0x00007fc3ed7923ec in CProtocolStackBase::InitProtocolStack(CStdStr<char>, CErrorInfo*) () from /usr/local/lib/libEposCmd.so
#16 0x00007fc3ed7646e9 in CProtocolStackManager::PS_InitProtocolStack(CStdStr<char>, CStdStr<char>, CErrorInfo*) () from /usr/local/lib/libEposCmd.so
#17 0x00007fc3ed73ce84 in CDeviceBase::InitDevice(CStdStr<char>, CStdStr<char>, CErrorInfo*) () from /usr/local/lib/libEposCmd.so
#18 0x00007fc3ed6d06de in CDeviceCommandSetManager::DCS_InitDevice(CStdStr<char>, CStdStr<char>, CStdStr<char>, CErrorInfo*) ()
from /usr/local/lib/libEposCmd.so
#19 0x00007fc3ed6aebd6 in CVirtualDeviceBase::InitVirtualDevice(CStdStr<char>, CStdStr<char>, CStdStr<char>, CErrorInfo*) () from /usr/local/lib/libEposCmd.so
#20 0x00007fc3ed684deb in CVirtualCommandSet_Manager::VCS_InitVirtualDevice(CStdStr<char>, CStdStr<char>, CStdStr<char>, CStdStr<char>, CErrorInfo*) ()
from /usr/local/lib/libEposCmd.so
#21 0x00007fc3ed66d112 in CCommunicationModel::CreateVirtualCommandSetManager()
() from /usr/local/lib/libEposCmd.so
---Type <return> to continue, or q <return> to quit---
#22 0x00007fc3ed67ca75 in VCS_OpenDevice () from /usr/local/lib/libEposCmd.so
#23 0x000000000040206e in OpenDevice(unsigned int*) ()
#24 0x0000000000403a6c in main ()
For USB communication, I modified the 99-ftdi.rules file provided:
SUBSYSTEM=="usb|usb_device", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="a8b0", GROUP="dialout", MODE="666", SYMLINK+="ftd2xx%n"
and copied to "/etc/udev/rules.d/" (this works with other machines).
Thanks for the help
Update:
Using the newest version of FTDI (1.3.6) did not help.
Since it is specific to my machine, here are the specs, if that can help:
-Dual boot Windows 10 - Ubuntu 16.04LTS 64bits
- Intel Core i7-6700HQ CPU 2.60GHw
- Nividia GTX950M
I have read issues of elision-unlock with Intel cores and maybe also caused by the graphic card, though I don't fully understand the issues, and how this simple program is related to the graphic card, or even using multiple cores.
Make sure your USB device gets enough power from the USB port. Try supplying external power if possible.
If the device does not have external power supply, try using a USB hub with external power supply.
In my experience, if the USB device draws too much current, it can cause temporary shut down to USB powered device (e.g., 5V supply dips below 3v due to sudden high current draw, causing the device to reset, where the PC thinks it got unplugged).

Segmentation Fault with OpenCV 3.0.0 on Windows 8.1 with MinGW

I have a simple multi-threaded version with TBB which works fine on a linux machine but on occasions, not always, gives segmentation fault when executed on windows.
#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <math.h>
#include <dirent.h>
#include <string.h>
#include <chrono>
using namespace cv;
std::vector<std::string> fnames;
class Parallel_process : public cv::ParallelLoopBody
{
public:
Parallel_process() {}
void operator()(const cv::Range &r) const {
cv::Mat src, dst, color_dst;
if(!(src=imread(fnames[r.start], 0)).data)
{
return;
}
Canny( src, dst, 50, 200, 3 );
cvtColor( dst, color_dst, CV_GRAY2BGR );
std::vector<Vec4i> lines;
HoughLinesP( dst, lines, 1, CV_PI/180, 80, 30, 10 );
for( size_t i = 0; i < lines.size(); i++ )
line( color_dst, Point(lines[i][0], lines[i][1]), Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8 );
std::string ext = "_parallel.bmp";
std::size_t found = fnames[r.start].find_last_of("/\\");
std::string fname = fnames[r.start].substr(found+1);
std::string out_fname = fname.substr(0, fname.find(".")) + ext;
cv::imwrite(out_fname.c_str(), color_dst);
}
};
int main()
{
DIR *dir;
struct dirent *ent;
std::string prefix = "c:\\Users\\foo\\Desktop\\sample_code\\imgs";
if ((dir = opendir (prefix.c_str())) != NULL) {
while ((ent = readdir (dir)) != NULL) {
fnames.push_back(prefix + '\\' + std::string(ent->d_name));
}
closedir (dir);
}
auto begin = std::chrono::high_resolution_clock::now();
cv::parallel_for_(cv::Range(0, fnames.size()), Parallel_process());
auto end = std::chrono::high_resolution_clock::now();
std::cout<<std::chrono::duration_cast<std::chrono::seconds>(end-begin).count()<<"secs"<<std::endl;
return(0);
}
Compilation is done using:
g++ -o parallel -I"c:\opencv\mingw_bld\install\include" edge_detection_parallel.cpp -L"c:\opencv\mingw_bld\install\x86\mingw\lib" -lopencv_imgproc300 -lopencv_core300 -lopencv_imgcodecs300 -lopencv_highgui300 -std=c++11
TBB version:
// Marketing-driven product version
#define TBB_VERSION_MAJOR 4
#define TBB_VERSION_MINOR 4
// Engineering-focused interface version
#define TBB_INTERFACE_VERSION 9000
#define TBB_INTERFACE_VERSION_MAJOR TBB_INTERFACE_VERSION/1000
// The oldest major interface version still supported
// To be used in SONAME, manifests, etc.
#define TBB_COMPATIBLE_INTERFACE_VERSION 2
GDB output (two runs; one was fine and the other received the segmentation fault):
gdb parallel.exe
GNU gdb (GDB) 7.6.1
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "mingw32".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from C:\Users\foo\Desktop\sample_code\parallel.exe...(no
debugging symbols found)...done.
(gdb) r
Starting program: C:\Users\foo\Desktop\sample_code/parallel.exe
[New Thread 5788.0xb90]
[New Thread 5788.0x144c]
[New Thread 5788.0x168c]
[New Thread 5788.0xd1c]
30secs
[Inferior 1 (process 5788) exited normally]
(gdb) r
Starting program: C:\Users\foo\Desktop\sample_code/parallel.exe
[New Thread 620.0x1450]
[New Thread 620.0xf04]
[New Thread 620.0x100c]
[New Thread 620.0x159c]
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 620.0x159c]
0x777cd9e5 in ?? ()
(gdb) bt
#0 0x777cd9e5 in ?? ()
#1 0x777cd3d8 in ?? ()
#2 0x7787184a in ?? ()
#3 0x778319c7 in ?? ()
#4 0x777cd3d8 in ?? ()
#5 0x7541b0f9 in msvcrt!free () from C:\Windows\system32\msvcrt.dll
#6 0x00740000 in ?? ()
#7 0x6c372f3b in cv::Canny(cv::_InputArray const&, cv::_OutputArray const&, dou
ble, double, int, bool) ()
from C:\opencv\mingw_bld\bin\libopencv_imgproc300.dll
#8 0x00408ef6 in Parallel_process::operator()(cv::Range const&) const ()
#9 0x69824e46 in tbb::interface7::internal::start_for<tbb::blocked_range<int>,
(anonymous namespace)::ProxyLoopBody, tbb::auto_partitioner const>::execute()
() from C:\opencv\mingw_bld\bin\libopencv_core300.dll
#10 0x678d7e49 in tbb::internal::custom_scheduler<tbb::internal::IntelSchedulerT
raits>::local_wait_for_all (this=0x913e80, parent=..., child=0x947620)
at ../../src/tbb/custom_scheduler.h:463
#11 0x678cc94f in tbb::internal::arena::process (this=this#entry=0x93ed00,
s=...) at ../../src/tbb/arena.cpp:114
#12 0x678cbcc1 in tbb::internal::market::process (this=<optimized out>, j=...)
at ../../src/tbb/market.cpp:494
#13 0x678c86dc in tbb::internal::rml::private_worker::run (
this=this#entry=0x93fc00) at ../../src/tbb/private_server.cpp:275
#14 0x678c8893 in tbb::internal::rml::private_worker::thread_routine (
arg=0x93fc00) at ../../src/tbb/private_server.cpp:228
#15 0x75427fb0 in msvcrt!_cexit () from C:\Windows\system32\msvcrt.dll
#16 0x0093fc00 in ?? ()
#17 0x754280f5 in msvcrt!_beginthreadex () from C:\Windows\system32\msvcrt.dll
#18 0x75b04198 in KERNEL32!BaseThreadInitThunk ()
from C:\Windows\system32\kernel32.dll
#19 0x777e445d in ?? ()
#20 0x777e442b in ?? ()
#21 0x00000000 in ?? ()
OS details:

terminate called after throwing an instance of 'std::logic_error'

I am using C++ for a program retrieving informations about files. Among them, I want to find out the MIME type of a given file.
To do so I use libmagic as follow:
#include <iostream>
#include <string>
#include <magic.h>
void foo (std::string path)
{
magic_t magic;
magic = magic_open (MAGIC_MIME_TYPE);
magic_load(magic, NULL);
magic_compile(magic, NULL);
std::string filetype (magic_file(magic, path.c_str()));
magic_close(magic);
std::cout << filetype << std::endl;
}
int main(int argc, char *argv[])
{
std::string str = "test.cxx";
foo (str);
return 0;
}
Trying on a computer running on Debian Jessie with gcc 4.9.2 and glibc 2.19, it works just fine.
However, on another computer on arch linux with gcc 5.1.0 and glibc 2.21, I have the following at runtime:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
gdb gives me additional information:
Program received signal SIGABRT, Aborted.
0x00007ffff6fb1528 in raise () from /usr/lib/libc.so.6
#0 0x00007ffff6fb1528 in raise () from /usr/lib/libc.so.6
#1 0x00007ffff6fb293a in abort () from /usr/lib/libc.so.6
#2 0x00007ffff78c9b3d in __gnu_cxx::__verbose_terminate_handler ()
at /build/gcc/src/gcc-5-20150519/libstdc++-v3/libsupc++/vterminate.cc:95
#3 0x00007ffff78c7996 in __cxxabiv1::__terminate (handler=<optimized out>)
at /build/gcc/src/gcc-5-20150519/libstdc++-v3/libsupc++/eh_terminate.cc:47
#4 0x00007ffff78c79e1 in std::terminate ()
at /build/gcc/src/gcc-5-20150519/libstdc++-v3/libsupc++/eh_terminate.cc:57
#5 0x00007ffff78c7bf8 in __cxxabiv1::__cxa_throw (obj=0x613fb0,
tinfo=0x7ffff7baea78 <typeinfo for std::logic_error>,
dest=0x7ffff78dd040 <std::logic_error::~logic_error()>)
at /build/gcc/src/gcc-5-20150519/libstdc++-v3/libsupc++/eh_throw.cc:87
#6 0x00007ffff78f08bf in std::__throw_logic_error (
__s=__s#entry=0x7ffff7976100 "basic_string::_S_construct null not valid")
at /build/gcc/src/gcc-5-20150519/libstdc++-v3/src/c++11/functexcept.cc:74
#7 0x00007ffff790acef in std::string::_S_construct<char const*> (__beg=<optimized out>,
__end=<optimized out>, __a=...)
at /build/gcc/src/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/include/bits/basic_string.tcc:577
#8 0x00007ffff790b0e6 in _S_construct_aux<char const*> (__a=..., __end=<optimized out>,
__beg=0x0)
at /build/gcc/src/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/include/bits/basic_string.h:4136
#9 _S_construct<char const*> (__a=..., __end=<optimized out>, __beg=0x0)
at /build/gcc/src/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/include/bits/basic_string---Type <return> to continue, or q <return> to quit---
.h:4157
#10 std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string (
this=0x7fffffffe980, __s=0x0, __a=...)
at /build/gcc/src/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/include/bits/basic_string.tcc:659
#11 0x0000000000400df3 in foo (path="test.cxx") at test.cxx:11
#12 0x0000000000400ece in main (argc=1, argv=0x7fffffffeae8) at test.cxx:21
So I'm not quite sure if I can solve my problem, or is there a possible bug coming from glibc or libmagic?

opencv calls in shared library segfaults when used through python ctypes

Whenever I load a shared library (.so) into Python with ctypes and call one of it's procedures that uses the OpenCV filter engine (like cvErode or cvDilate), the interpreter segfaults deep inside the OpenCV code.
If I load the same library with dlopen inside a C program and call the same procedure everything works fine.
I've read in another post that it might have to do with the ABI that gcc utilizes and that python has to be compiled with the same version of gcc that the python interpreter was compiled with for this to work. However in my case it's both 4.4.5 so that shouldn't be an issue. The OpenCV libraries were also compiled with that same version of gcc.
How the shared library is built:
g++ -g -shared -lopencv_core -lopencv_imgproc -lopencv_calib3d -lopencv_video -lopencv_features2d -lopencv_ml -lopencv_highgui -lopencv_objdetect -lopencv_contrib -lopencv_legacy -o thumbsplit.so thumbsplit.cpp
How the shared library is wrapped:
extern "C" {
int is_thumbsheet(char * image_path){
Image image;
image.read(image_path);
int width = image.columns();
int height = image.rows();
int BOUND_CHANGE = 7000;
int test_height = 0;
if( width > height ){
return 0;
}else{
test_height = width;
}
vector<int> test_rows = getRows(image, width, test_height, BOUND_CHANGE);
vector<int> test_cols = getCols(image, width, test_height, BOUND_CHANGE);
vector<Box> test_boxes = createBoxes(test_rows,test_cols,width,height);
if( test_boxes.size() > 6 ){
return 1;
}else{
return 0;
}
}
int cut_thumbs(char * image_path, char * thumb_path){
Image image;
image.read(image_path);
int width = image.columns();
int height = image.rows();
int BOUND_CHANGE = 7000;
vector<int> rows = getRows(image, width, height, BOUND_CHANGE);
vector<int> cols = getCols(image, width, height, BOUND_CHANGE);
//drawDebugLines(rows, cols, width, height);
vector<Box> boxes = createBoxes(rows,cols,width,height);
//printBoxes(boxes);
char path[0x100];
for( int i=0 ; i < boxes.size() ; i++ ){
sprintf(path, "%s%d.jpg", thumb_path, i);
boxes[i].saveBox(image, path);
}
return 0;
}
} // C
How the shared library procedures are loaded in python:
import ctypes, os
def load_lib():
lib_path = "%s/%s"%(os.path.realpath(os.path.dirname(__file__)), "thumbsplit.so")
lib = ctypes.CDLL(lib_path)
return lib
def is_thumbsheet(image_path):
lib = load_lib()
if lib.is_thumbsheet(image_path):
return True
else:
return False
def cut_thumbs(image_path, thumbs_path):
lib = load_lib()
lib.cut_thumbs(image_path, thumbs_path)
is_thumbsheet("/home/rolf/test/imageproc/full9.jpg") # this segfaults
GDB output:
$ gdb python
GNU gdb (GDB) 7.0.1-debian
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /usr/bin/python...(no debugging symbols found)...done.
(gdb) run thumbsheet.py
Starting program: /usr/bin/python thumbsheet.py
[Thread debugging using libthread_db enabled]
0xb6330a12
Program received signal SIGSEGV, Segmentation fault.
0xb76fe2dc in cv::FilterEngine::start(cv::Size_<int>, cv::Rect_<int>, int) () from /usr/local/lib/libopencv_imgproc.so.2.3
(gdb) info stack
#0 0xb76fe2dc in cv::FilterEngine::start(cv::Size_<int>, cv::Rect_<int>, int) () from /usr/local/lib/libopencv_imgproc.so.2.3
#1 0xb76feb41 in cv::FilterEngine::start(cv::Mat const&, cv::Rect_<int> const&, bool, int) ()
from /usr/local/lib/libopencv_imgproc.so.2.3
#2 0xb770a52b in cv::FilterEngine::apply(cv::Mat const&, cv::Mat&, cv::Rect_<int> const&, cv::Point_<int>, bool) ()
from /usr/local/lib/libopencv_imgproc.so.2.3
#3 0xb764bf8a in cv::morphOp(int, cv::_InputArray const&, cv::_OutputArray const&, cv::_InputArray const&, cv::Point_<int>, int, int, cv::Scalar_<double> const&) () from /usr/local/lib/libopencv_imgproc.so.2.3
#4 0xb764d2ce in cv::erode(cv::_InputArray const&, cv::_OutputArray const&, cv::_InputArray const&, cv::Point_<int>, int, int, cv::Scalar_<double> const&) () from /usr/local/lib/libopencv_imgproc.so.2.3
#5 0xb764d62e in cvErode () from /usr/local/lib/libopencv_imgproc.so.2.3
#6 0xb7fd7adb in seperate::findSeperatedBoxes (img=0x8351d70) at seperate.cpp:189
#7 0xb7fd7fcf in seperate::trySeperatedBoxes (img=0x8351d70, percentage_boxed=0xbfffefec) at seperate.cpp:202
#8 0xb7fda00c in is_thumbsheet (image_path=0xb7c1bf74 "/home/rolf/test/imageproc/full9.jpg") at thumbsplit.cpp:39
#9 0xb7a047df in ffi_call_SYSV () from /usr/lib/python2.6/lib-dynload/_ctypes.so
#10 0xb7a0461e in ffi_call () from /usr/lib/python2.6/lib-dynload/_ctypes.so
#11 0xb79ff27d in _CallProc () from /usr/lib/python2.6/lib-dynload/_ctypes.so
#12 0xb79f6d7e in ?? () from /usr/lib/python2.6/lib-dynload/_ctypes.so
#13 0x0806232a in PyObject_Call ()
#14 0x080e016b in PyEval_EvalFrameEx ()
#15 0x080e18b0 in PyEval_EvalFrameEx ()
#16 0x080e2507 in PyEval_EvalCodeEx ()
#17 0x080e2607 in PyEval_EvalCode ()
#18 0x080ffcbd in PyRun_FileExFlags ()
#19 0x080fff22 in PyRun_SimpleFileExFlags ()
#20 0x0805dd81 in Py_Main ()
#21 0x0805cf6b in main ()
(gdb) x/i 0xb76fe2dc
0xb76fe2dc <_ZN2cv12FilterEngine5startENS_5Size_IiEENS_5Rect_IiEEi+1212>: movdqa %xmm3,0x30(%esp)
(gdb)
GCC/G++ versions:
$ python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
$ gcc --version
gcc (Debian 4.4.5-8) 4.4.5
$ g++ --version
g++ (Debian 4.4.5-8) 4.4.5
OpenCV is version 2.3.1 and was built from source using this version of gcc (4.4.5-8)
I've found the solution. The stack needs to be realigned to 16 bytes for SSE instructions. If I build the shared library with -mstackrealign it works perfectly loaded and called from python.
Qt, GCC, SSE and stack alignment