How to get activity object? (Android, Qt 5.2) - java-native-interface

I need to get main activity, and I tried:
QAndroidJniEnvironment jniEnv;
jclass clsAct = jniEnv->FindClass("android/app/Activity");
qDebug() << "Activity: " << clsAct;
if( QAndroidJniObject::isClassAvailable("org/qtproject/qt5/android/bindings/QtActivity") )
{
jclass clsApp = jniEnv->FindClass("org/qtproject/qt5/android/bindings/QtActivity");
qDebug() << "QtActivity: " << clsApp;
if( clsApp && clsAct )
{
jobject objAct = NULL;
jmethodID mid = jniEnv->GetStaticMethodID( clsApp, "activity", "()Landroid/app/Activity;" );
qDebug() << "activityMID: " << mid;
if( mid )
{
objAct = jniEnv->CallStaticObjectMethod( clsApp, mid );
qDebug() << "activityObj: " << objAct;
}
}
}
But on jniEnv->FindClass(“org/qtproject/qt5/android/bindings/QtActivity”) shoots error:
D/Qt ( 4074): mainwindow.cpp:32
(MainWindow::MainWindow(QWidget*)): >>>>>> QtActivity: 0x0
W/dalvikvm( 4074): JNI WARNING: JNI function CallStaticVoidMethodV
called with exception pending W/dalvikvm( 4074): in
Ldalvik/system/NativeStart;.run:()V (CallStaticVoidMethodV)
W/dalvikvm( 4074): Pending exception is: I/dalvikvm( 4074):
java.lang.NoClassDefFoundError:
org/qtproject/qt5/android/bindings/QtActivity I/dalvikvm( 4074): at
dalvik.system.NativeStart.run(Native Method) I/dalvikvm( 4074): Caused
by: I/dalvikvm( 4074): java.lang.ClassNotFoundException: Didn't find
class "org.qtproject.qt5.android.bindings.QtActivity" on path:
DexPathList[[directory "."],nativeLibraryDirectories=[/system/lib]]

Related

boost log working in exe but crashing in dll

I have developed an application (application1) that uses boost::log with
severity_channel_logger_mt and two sinks (syslog_backend &
text_file_backend).
When I run the application as an .exe, the sinks work fine and I am able to see log text files generate from messages being passed across a network, but when
I link application1 as a .dll inside of another application (mainapp), I get
the following errors after about 20 seconds:
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: [rethrow] at memory location 0x0000000000000000.
Exception thrown at 0x00007FFA9E03CD29 in mainapp.exe: Microsoft C++ exception: boost::wrapexcept<boost::system::system_error> at memory location 0x000000F9BD9FF220.
After debugging, the exception happens in basic_sink_frontend.hpp and core.hpp between these two calls:
basic_sink_frontend.hpp
backend.consume(rec, context->m_FormattedRecord);
core.hpp
BOOST_FORCEINLINE void push_record(BOOST_RV_REF(record) rec)
{
push_record_move(static_cast< record& >(rec));
}
I have verified that the "rec" variable is not NULL.
The application1 DLL loads wihout error and I am able to run application1 functions from mainapp.
I still see message being passed across network from syslog sink, however text_file sink logs are not generated...
I built boost as a shared library and have the following libs in boost_1_80_0/stage/lib:
boost_log_setup-vc142-mt-x64-1_80
boost_log-vc142-mt-gd-x64-1_80
boost_log-vc142-mt-x64-1_80
Snippets from my code on how I use the loggers and sinks are below. Application1 uses boost::log and MainApp loads Application1 as DLL:
Application1:
#define DEFAULT_PORT 13000
#define DEFAULT_PORT_STRING "13000"
#define DEFAULT_IP "127.0.0.1"
enum class severity_levels
{
info,
warning,
error
};
void Application1::init_builtin_syslog()
{
// Create a syslog sink
boost::shared_ptr< sinks::synchronous_sink< sinks::syslog_backend > > sys_sink(
new sinks::synchronous_sink< sinks::syslog_backend >());
sys_sink->set_formatter
(
expr::stream << "Application 1 Log - ID: " << expr::attr< unsigned int >("RecordID")
<< "| " << expr::attr< severity_levels >("Severity") << ": " << expr::smessage
);
// We'll have to map our custom levels to the syslog levels
sinks::syslog::custom_severity_mapping< severity_levels > mapping("Severity");
mapping[severity_levels::info] = sinks::syslog::info;
mapping[severity_levels::warning] = sinks::syslog::warning;
mapping[severity_levels::error] = sinks::syslog::critical;
sys_sink->locked_backend()->set_severity_mapper(mapping);
#if !defined(BOOST_LOG_NO_ASIO)
// Set the remote address to send syslog messages to
sys_sink->locked_backend()->set_target_address(DEFAULT_IP, DEFAULT_PORT);
#endif
//Create a text file sink
boost::shared_ptr< sinks::synchronous_sink< sinks::text_file_backend > > file_sink(
new sinks::synchronous_sink< sinks::text_file_backend >(
keywords::file_name = "application1.log", // file name pattern
keywords::target_file_name = "application1_%Y%m%d_%H%M%S_%2N.log",
keywords::rotation_size = 16384
));
// Set up where the rotated files will be stored
file_sink->locked_backend()->set_file_collector(sinks::file::make_collector(
keywords::target = "logs",
keywords::max_size = 64 * 1024 * 1024,
keywords::min_free_space = 100 * 1024 * 1024,
keywords::max_files = 512
));
// Upon restart, scan the target directory for files matching the file_name pattern
file_sink->locked_backend()->scan_for_files();
file_sink->set_formatter
(
expr::format("%1% Application 1 Log - ID: %2% | %3% : \"%4%\"")
% expr::attr< boost::posix_time::ptime >("TimeStamp")
% expr::attr< unsigned int >("RecordID")
% expr::attr< severity_levels >("Severity")
% expr::smessage
);
// Add the sinks to the core
logging::core::get()->add_sink(sys_sink);
logging::core::get()->add_sink(file_sink);
// Add logging attributes
logging::core::get()->add_global_attribute("RecordID", attrs::counter< unsigned int >());
logging::core::get()->add_global_attribute("TimeStamp", attrs::utc_clock());
}
int start()
{
init_builtin_syslog();
src::severity_channel_logger_mt\< severity_levels \> lg(keywords::severity = severity_levels::info, keywords::channel = "Application 1");
for (int i = 0; i \< 10000; ++i)
{
BOOST_LOG_SEV(lg, severity_levels::info) \<\< infoLog;
if(runexe) std::cout \<\< "App1 sent: " \<\< infoLog \<\< std::endl;
boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
}
return 0;
}
MainApp:
bool loadedApp1 = false;
std::atomic<bool> startApp1 = true;
std::atomic<char*> app1Err((char*)"");
HINSTANCE app1dll;
void printError( const TCHAR* msg );
typedef void (*MYPROC2)(std::atomic<bool>&, std::atomic<char*>&);
MYPROC2 app1start;
int main()
{
std::cout << "Starting application 1... " << std::endl;
try
{
app1dll = LoadLibrary(TEXT("application1.dll"));
if(app1dll == NULL)
{
std::cerr << "Application 1 DLL load library failure." << GetLastError() << '\n';
loadedApp1 = false;
}
else
{
loadedApp1 = true;
app1start = (MYPROC2) GetProcAddress(app1dll, MAKEINTRESOURCEA(1));
if (NULL != app1start)
{
std::thread t1(app1start, std::ref(startApp1), std::ref(app1Err));
t1.detach();
std::this_thread::sleep_for(std::chrono::milliseconds(4000));
}
if(startApp1.load() == false)
{
std::cout << "Error starting Application 1: " << app1Err.load() << std::endl;
}
}
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
return 1;
}
return 0;
}

JavaVM::GetEnv crashes when getting called

my dll crashes when I call this :
JavaVM *vm;
jint vm_count;
JNI_GetCreatedJavaVMs(&vm, 1, &vm_count);
jvmtiEnv *env = NULL;
vm->GetEnv((void**) &env, JVMTI_VERSION_1_2);
std::cout << env << '\n'; // never print
I don't see any problem so I'm confused

C++ MySQL Connector PrepareStatement Bad_Access

At runtime in loop by twice, crashed by Bad_Access in while calling PrepareStatement by requesting query.
So I checked the all ResultSet memory and release it all but there is no idea
any idea solve this problem?
Description about member value;
PrepareStatement* pstmt;
ResultSet* res;
and the full code
bool laskdjlaskdj12::RaspBerry::grup_pw_chk(const Json::Value j){
//check the id and group is valid
try{
string group = j["Group"].asString();
const char* id = j["id"].asCString();
string grp;
string pub;
BIO* tmp; //BIO structor to change the RSA* structor
if(group == "NULL"){
group = "";
}
//request the Client is existence
pstmt = con->prepareStatement("SELECT * FROM `raspberry_cli` WHERE `Cli_id` = (?) AND `Cli_Group` = (?)");
pstmt->setString(1, id);
pstmt->setString(2, group);
res = pstmt->executeQuery();
//if query reply is NULL
if(res->next() == false){
std::cout<<"[INFO] : There is no query about raspberry_cli"<<std::endl;
return false;
}
//if query Reply
grp = res->getString("Cli_Group");
pub = res->getString("Cli_Pub");
//if There is no group in Raspberry_pi
if(ras.grp.compare(grp) == false){
//sql의 버퍼 flush
this->SQL_Flush();
return false;
}
// if the group is equal
else{
//save the client information
acc_cli.S_id = id;
acc_cli.S_Group = grp;
//save the client public_key
tmp = BIO_new_mem_buf(pub.c_str(), -1);
acc_cli.Pub_key = PEM_read_bio_RSA_PUBKEY(tmp, NULL, 0, NULL);
//if public key is not wright in section
if(acc_cli.Pub_key == NULL){
return false;
}
delete[] tmp;
//flush SQL_flush = delete ResultSet
this->SQL_Flush();
return true;
}
}catch(sql::SQLException& e){
std::cout << "# ERR: SQLException in " << __FILE__;
std::cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << std::endl;
std::cout << "# ERR: " << e.what();
std::cout << " (MySQL error code: " << e.getErrorCode();
std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl;
return false;
}
The Detal StackTrace is this
* thread #1: tid = 0x2778b, 0x00000001000e29c3 RaspBerry`list_add(root=0x0000000100903e38, element=0x00000001009043e8) + 19 at list.c:33, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
frame #0: 0x00000001000e29c3 RaspBerry`list_add(root=0x0000000100903e38, element=0x00000001009043e8) + 19 at list.c:33 [opt]
frame #1: 0x00000001000de27f RaspBerry`mysql_stmt_init(mysql=0x0000000102802220) + 143 at libmysql.c:1568 [opt]
frame #2: 0x0000000100168f41 RaspBerry`sql::mysql::NativeAPI::MySQL_NativeConnectionWrapper::stmt_init(this=0x0000000100a00580) + 33 at mysql_native_connection_wrapper.cpp:421 [opt]
frame #3: 0x000000010011c415 RaspBerry`sql::mysql::MySQL_Connection::prepareStatement(this=0x0000000100a00550, sql=0x00007fff5fbfe138) + 53 at mysql_connection.cpp:1137 [opt]
* frame #4: 0x0000000100073071 RaspBerry`laskdjlaskdj12::RaspBerry::grup_pw_chk(this=0x00007fff5fbfeba0, j=const Json::Value # 0x00007fff5fbfea30) + 881 at RaspBerry.cpp:438
frame #5: 0x000000010007c222 RaspBerry`main(argc=1, argv=0x00007fff5fbff7f8) + 3474 at main.cpp:81
frame #6: 0x00007fffced8b255 libdyld.dylib`start + 1
frame #7: 0x00007fffced8b255 libdyld.dylib`start + 1
Find the answer
pstmt = con->prepareStatement("SELECT * FROM `raspberry_cli` WHERE `Cli_id` = (?) AND `Cli_Group` = (?)");
pstmt->setString(1, id);
pstmt->setString(2, group);
res = pstmt->executeQuery();
[delete pstmt;] //===================> This part is missing
in this section i didn't delete pstmt(sql::preparestatement*)
so the sql have send that malloc error.
So Be careful about allocating memory.

Uncaught exception that causes Abort

I'm using my own Exception class that inherits from std::exception. I'm pretty sure the class is okay since it has always worked up until now. I'm trying to throw an error from a constructor:
DataBase::DataBase()
: _result(NULL)
{
mysql_init(&_mysql);
mysql_options(&_mysql,MYSQL_READ_DEFAULT_GROUP,"option");
if(!mysql_real_connect(&_mysql,"localhost","root","","keylogger",0,NULL,0))
throw Exception(__LINE__ - 1, __FILE__, __FUNCTION__, "Can't connect to DB");
}
Here is my try/catch block :
int main(int, char **)
{
//[...]
Server server([...]); // DB is a private member in Server
try
{
server.fdMonitor();
}
catch (Exception &e)
{
std::cout << "Error: in " << e.file() << ", " << "function " << e.function()
<< "(line " << e.line() << ") : " << std::endl
<< "\t" << e.what() << std::endl;
}
return (1);
}
The problem is that the Exception thrown from my DB constructor isn't caught. Here's the abort message:
terminate called after throwing an instance of 'Exception'
what(): Can't connect to DB
Aborted
Any ideas?
Thanks in advance.
From your description, it sounds like the DataBase constructor is called from the Server constructor.
So, you need to move that line into the try block :
try
{
Server server([...]); // DB is a private member in Server
server.fdMonitor();
}
catch (Exception &e)
{
// ...
}
The problem is that the place which throws (construction of server) is not within the try block.

Segmentation fault when catching exceptions in a libpthread linked app ( linux, C++ )

I have this piece of code here:
These are functions used to create and stop a pthread:
void WatchdogController::conscious_process_handler_start() {
if ( debug ) cout << "WatchdogController: starting conscious process thread" << endl;
cn_pr_thread_active = true;
if ( pthread_create( &cn_pr_thread, NULL, conscious_process_handler, this ) < 0 ) {
cn_pr_thread_active = false;
throw WatchdogException( "Unable to start new thread" );
}
}
void WatchdogController::conscious_process_handler_stop() {
if ( debug ) cout << "WatchdogController: stopping conscious process thread" << endl;
cn_pr_thread_active = false;
int *retval;
pthread_join( cn_pr_thread, ( void ** )&retval );
if ( *retval < 0 ) {
delete retval;
string err = string( "Error returned by conscious_process_handler(): " ) + string( pthread_err );
throw WatchdogException( err.c_str() );
}
delete retval;
}
I use select() in function passed to pthread, and when stopped it returns an error resulting in return value from pthread being negative, but that's not the issue, I'll fix it later - problem is, that when the exception is thrown here:
throw WatchdogException( err.c_str() );
and caught here:
try {
watchdog_controller->hardware_watchdog_stop();
watchdog_controller->unconscious_process_handler_stop();
watchdog_controller->conscious_process_handler_stop();
}
catch ( HardwareWatchdogException &e ) {
cerr << "Error stopping hardware watchdog!" << endl;
cerr << e.get_reason() << endl;
string err = string( "Exception thrown by hardware watchdog controller" ) + string( e.get_reason() );
if ( log ) write_log( err.c_str() );
delete watchdog_controller;
return -1;
}
catch ( WatchdogException &e ) {
cerr << "Exception cought when exiting!" << endl;
cerr << e.get_reason() << endl;
string err = string( "Exception cought when exiting" ) + string( e.get_reason() );
if ( log ) write_log( err.c_str() );
delete watchdog_controller;
return -1;
}
I get segmentation fault then trying to access the object at this point:
cerr << e.get_reason() << endl;
What could be the reason?
Reference &e points to something, but it seems as if the address was invalid.
Here's the exception class:
class WatchdogException {
public:
/**
#brief Default constructor
*/
WatchdogException() : reason() {
}
/**
#brief Overloaded constructor - setting the error message
#param why Error message
*/
WatchdogException( const char *why ) : reason( why ) {
}
/**
#brief The destructor
*/
virtual ~WatchdogException() {
}
/**
#brief A getter for the error message
#return Returns a string containing error description
*/
virtual std::string get_reason() const {
return reason;
}
protected:
/**
#var reason String containing the error message
*/
std::string reason;
};
I am guessing that you are not properly allocating memory for retval, or that somehow you are returning an invalid pointer from cn_pr_thread, and that is why you get a segmentation fault when you call pthread_join.
In WatchDogException's constructor, are you remembering the pointer to the c-string passed in or are you making a copy of it.
If you're simply storing the pointer then when "err" goes out of scope when the exception is thrown the pointer returned by c_str() will be bad, hence your seg fault when you try and use it.