Device: Google Nexus 7 (2013).
logcat contains
I/DEBUG ( 176): Abort message: '### ABORTING: invalid address or address of corrupt block 0x5c6b0 passed to dlfree'.
I think there is a problem with static libgnustl. Am I right? How can I force to use ibgnustl_shared using GNU Build System? I uses android-ndk-r9b installed into $HOME/android-ndk-r9b. Firstly I made standalone toolchain
$HOME/android-ndk-r9b/build/tools/make-standalone-toolchain.sh --platform=android-9 --install-dir=$HOME/android-toolchain
I wrote simple test that contains shared library and console program that uses it. It crashes on device.
// libtest.h
#ifndef TEST_H
#define TEST_H
#include <stddef.h>
#include <string>
namespace test
{
enum { MSG_LEN_BYTES = 3, MSG_LEN_MAX = 0xFFF };
int encodeMsgLength(std::string &encoded_length, size_t length);
}
#endif
// libtest.cpp
#include "libtest.h"
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
int test::encodeMsgLength(std::string &encoded_length, size_t length)
{
encoded_length.clear();
if (length > MSG_LEN_MAX) {
return E2BIG;
}
char buf[MSG_LEN_BYTES + 1] = {0};
int cnt = snprintf(buf, sizeof(buf), "%03zX", length);
if (cnt == MSG_LEN_BYTES && static_cast<size_t>(cnt) < sizeof(buf)) {
encoded_length.assign(buf, cnt);
return 0;
}
assert(!"encodeMsgLength");
return EBADF;
}
// test.cpp
#include <iostream>
#include <stdlib.h>
#include "libtest.h"
int main(int argc, char* argv[])
{
if (argc != 2) {
std::cout << "Usage: test <number>\n";
return 1;
}
size_t len = atoi(argv[1]);
std::cout << "encodeMsgLength(" << len << ") => ";
std::string str;
int err = test::encodeMsgLength(str, len);
std::cout << str << ", error " << err << std::endl;
return 0;
}
Makefile.am
lib_LTLIBRARIES = libtest.la
libtest_la_LDFLAGS = -shared -avoid-version
libtest_la_SOURCES = libtest.cpp
bin_PROGRAMS = test
test_LDADD = libtest.la
test_SOURCES = test.cpp
Build your app using the default : ndk-build --TARGET_PLATFORM android-9
To make sure that only shared library is taken edit your Android.mk and put appropriate library like LOCAL_SHARED_LIBS := libgnustl
There are various other tools that you can use to debug your issue:
1. gdb [search for remote debugging android native app]
2. strace [ if not directly available use busybox strace ]
3. valgrind
Also in many cases the memory stack during crash are stores in /data/tombstones. Locate your errror file, pull it and show the details here of the same.
Instead of linking to libgnustl-static.a, use libgnustl-shared.so. Your observation makes sense: when both libtest.so and test are linked with the static version, then the std::string class will have two different vtables, and the program may crash on shutdown. libstlport uses internally system stl (always shared) for new/delete, and thus behaves better in your test case. This, naturally, does not protect from other clashes, which may also be lethal. That's why you should use shared version of stl if you use it in two or more dynamically linked components.
In CPLUSPLUS-SUPPORT.html
"II.3. Static runtimes:
Please keep in mind that the static library variant of a given C++ runtime SHALL ONLY BE LINKED INTO A SINGLE BINARY for optimal conditions."
I had an issue with this where malloc was crashing.
Related
I have a.so which defines void a() and b.so which defines void b(). They are both put in the .apk so they are available to the Android application.
Now suppose that I'm calling a() through JNI. Is it possible to call b() from a() while completely bypassing JNI?
Can I do it this way in Android (the code is only for illustration, so it might have some errors)?
void a() {
void *handle = dlopen("b.so", RTLD_LAZY);
void (*b)() = dlsym(handle, "b");
b();
}
Would I need to add the fully qualified path, or is b.so already in LD_LIBRARY_PATH for the app?
You can do it this way on Android, though take care of where the shared library has been put in Android folders. It can change from a version to another.
On api 17 for example, it remains in /data/app-lib/. You can hardwrite it, but the best is to make calls to Java (through JNI) to know where the libraries should be.
We're doing something like this in our project :
JNIEnv* env;
const char* temp;
jobject oActivity = state->activity->clazz;
jclass cActivity = env->GetObjectClass(oActivity);
// get the path to where android extracts native libraries to
jmethodID midActivityGetApplicationInfo = env->GetMethodID(cActivity, "getApplicationInfo", "()Landroid/content/pm/ApplicationInfo;");
jobject oApplicationInfo = env->CallObjectMethod(oActivity, midActivityGetApplicationInfo);
jclass cApplicationInfo = env->GetObjectClass(oApplicationInfo);
jfieldID fidApplicationInfoNativeLibraryDir = env->GetFieldID(cApplicationInfo, "nativeLibraryDir", "Ljava/lang/String;");
jstring sNativeLibraryDir = (jstring)env->GetObjectField(oApplicationInfo, fidApplicationInfoNativeLibraryDir);
temp = env->GetStringUTFChars(sNativeLibraryDir, NULL);
strcpy(libpath, temp);
strcat(libpath, "/");
Then you push your dlopen + dlsym combo in the fight and it should work.
As mentioned here : How do I load a shared object in C++?
There are two ways of loading shared objects in C++
For either of these methods you would always need the header file for the object you want to use. The header will contain the definitions of the classes or objects you want to use in your code.
#include "blah.h"
int main()
{
ClassFromBlah a;
a.DoSomething();
}
gcc yourfile.cpp -lblah
Dynamically (In Linux):
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("libm.so", RTLD_LAZY);
if (!handle) {
fprintf (stderr, "%s\n", dlerror());
exit(1);
}
dlerror(); /* Clear any existing error */
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "%s\n", error);
exit(1);
}
printf ("%f\n", (*cosine)(2.0));
dlclose(handle);
return 0;
}
PS : for the dynamic approach, it depends on platform : on Linux, you use dlopen, on windows, you use LoadLibrary.
I want to create an android application which can locate a video file (which is more than 300 mb) and compress it to lower size mp4 file.
i already tried to do it with this
This tutorial is a very effective since you 're compressing a small size video (below than 100 mb)
So i tried to implement it using JNI .
i managed to build ffmpeg using this
But currently what I want to do is to compress videos . I don't have very good knowledge on JNI. But i tried to understand it using following link
If some one can guide me the steps to compress video after open file it using JNI that whould really great , thanks
Assuming you've got the String path of the input file, we can accomplish your task fairly easily. I'll assume you have an understanding of the NDK basics: How to connect a native .c file to native methods in a corresponding .java file (Let me know if that's part of your question). Instead I'll focus on how to use FFmpeg within the context of Android / JNI.
High-Level Overview:
#include <jni.h>
#include <android/log.h>
#include <string.h>
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#define LOG_TAG "FFmpegWrapper"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
void Java_com_example_yourapp_yourJavaClass_compressFile(JNIEnv *env, jobject obj, jstring jInputPath, jstring jInputFormat, jstring jOutputPath, jstring JOutputFormat){
// One-time FFmpeg initialization
av_register_all();
avformat_network_init();
avcodec_register_all();
const char* inputPath = (*env)->GetStringUTFChars(env, jInputPath, NULL);
const char* outputPath = (*env)->GetStringUTFChars(env, jOutputPath, NULL);
// format names are hints. See available options on your host machine via $ ffmpeg -formats
const char* inputFormat = (*env)->GetStringUTFChars(env, jInputFormat, NULL);
const char* outputFormat = (*env)->GetStringUTFChars(env, jOutputFormat, NULL);
AVFormatContext *outputFormatContext = avFormatContextForOutputPath(outputPath, outputFormat);
AVFormatContext *inputFormatContext = avFormatContextForInputPath(inputPath, inputFormat /* not necessary since file can be inspected */);
copyAVFormatContext(&outputFormatContext, &inputFormatContext);
// Modify outputFormatContext->codec parameters per your liking
// See http://ffmpeg.org/doxygen/trunk/structAVCodecContext.html
int result = openFileForWriting(outputFormatContext, outputPath);
if(result < 0){
LOGE("openFileForWriting error: %d", result);
}
writeFileHeader(outputFormatContext);
// Copy input to output frame by frame
AVPacket *inputPacket;
inputPacket = av_malloc(sizeof(AVPacket));
int continueRecording = 1;
int avReadResult = 0;
int writeFrameResult = 0;
int frameCount = 0;
while(continueRecording == 1){
avReadResult = av_read_frame(inputFormatContext, inputPacket);
frameCount++;
if(avReadResult != 0){
if (avReadResult != AVERROR_EOF) {
LOGE("av_read_frame error: %s", stringForAVErrorNumber(avReadResult));
}else{
LOGI("End of input file");
}
continueRecording = 0;
}
AVStream *outStream = outputFormatContext->streams[inputPacket->stream_index];
writeFrameResult = av_interleaved_write_frame(outputFormatContext, inputPacket);
if(writeFrameResult < 0){
LOGE("av_interleaved_write_frame error: %s", stringForAVErrorNumber(avReadResult));
}
}
// Finalize the output file
int writeTrailerResult = writeFileTrailer(outputFormatContext);
if(writeTrailerResult < 0){
LOGE("av_write_trailer error: %s", stringForAVErrorNumber(writeTrailerResult));
}
LOGI("Wrote trailer");
}
For the full content of all the auxillary functions (the ones in camelCase), see my full project on Github. Got questions? I'm happy to elaborate.
I am trying too build a samples which using opencv for android. Here is my C++ code:
Header file:
#ifdef __cplusplus
extern "C" {
#endif
#include "jni.h"
#include "opencv2/core/core.hpp"
namespace openCVFuncs
{
cv::Mat contrastFilter(cv::Mat inputMatm, float contrastValue);
}
#ifdef __cplusplus
}
#endif
Cpp file:
namespace openCVFuncs
{
cv::Mat contrastFilter(cv::Mat inputMat, float contrastValue)
{
contrastValue = pow(2,contrastValue);
cv::Mat outMat = inputMat.clone();
uchar* data_img_in=(uchar*)inputMat.data;
uchar* data_img_out=(uchar*)outMat.data;
int temp = 0;
for(int i=0;i<inputMat.size().height;i++)
for(int j=0;j<inputMat.size().width;j++)
for (int c=0;c<inputMat.channels();c++)
{
temp = (data_img_in+inputMat.step[0]*i)[j*inputMat.channels()+c];
temp = (int)((temp - 128.0) * contrastValue) +128;
if (temp < 5) temp = 5;
if (temp > 255) temp = 255;
(data_img_out+outMat.step[0]*i)[j*outMat.channels()+c] = temp;
}
return outMat;
};
}
And I got many errors like that :
/opt/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.6/include/bits/valarray_before.h:652:3: error: template with C linkage
What wrong with my code ?
When using an "extern C"-block, you can only use the things that are available to C, so that rules out function overloading/polymorphism, namespaces, amongst other things.
In the header file you posted you include a .hpp file (which could possibly include one of the unusable definitions) and define a namespace.
This page gives some nice pointers on the subject on what you can and cannot do and how you can wrap calls to C++ namespaces / overloaded functions for use in a library compiled by a C compiler, see "Accessing C++ Code from Within C Source":
http://www.oracle.com/technetwork/articles/servers-storage-dev/mixingcandcpluspluscode-305840.html
I have compiled static libcurl for android but continuously receiving the CurlRes code 6 i.e. CURLE_COULDNT_RESOLVE_HOST.
Android.mk
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := Curl
LOCAL_SRC_FILES := prebuild/libcurl.a
include $(PREBUILT_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := ccSharedLib
LOCAL_SRC_FILES := main-jni.cpp
LOCAL_STATIC_LIBRARIES := Curl
include $(BUILD_SHARED_LIBRARY)
main-jni.cpp
extern "C" {
size_t write_data(void *ptr, size_t size, size_t count, FILE *stream)
{
size_t written;
written = fwrite(ptr, size, count, stream);
printf("data sent, size = %lu",written);
return written;
}
jint
Java_com_example_testlibcurl_MainActivity_test1( JNIEnv* env,
jobject thiz, jstring downloadDirectoryPath)
{
CURLcode res;
res = curl_global_init(CURL_GLOBAL_ALL);
jint temp = 3;
printf("Method called");
const char *nativeDownloadDirPath = env->GetStringUTFChars(downloadDirectoryPath,0);
// Test code for calling methods of libCURL
CURL *curl;
FILE *fp;
std::string s = "http://travel.paintedstork.com/blog/wp-content/uploads/2012/10/2013-calendar-images-1.jpg";
curl = curl_easy_init();
if(curl)
{
fp = fopen(nativeDownloadDirPath, "wb");
res = curl_easy_setopt(curl, CURLOPT_URL, s.c_str());
res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(fp)
fclose(fp);
}
return res;
}
}
This code is downloading the image from a web source, but every time when "curl_easy_perform" method is called it gives the error code 6. I have checked this with different URL but still unsuccessful :( ...
"android.permission.INTERNET" and "android.permission.WRITE_EXTERNAL_STORAGE" permissions already given in Manifest file.
Any pointer to solve this will be a great help.
Make sure that you pass a valid file name and writable directory path to fopen.
I was getting
Fatal signal 11 (SIGSEGV) at 0x00000010 (code=1) ...
because fopen was trying to open a directory instead of a file.
Check the logs in LogCat from Eclipse or using adb logcat for other possible errors.
I've tested your code with the following modifications and it works.
MainActivity.java:
public class MainActivity
{
private static final String TAG = MainActivity.class.getName();
static
{
try
{
System.loadLibrary("mynativelib");
}
catch (UnsatisfiedLinkError ex)
{
Log.e(TAG, "WARNING: Could not load native library: " + ex.getMessage());
}
}
public static native int DownloadFile(String downloadDirectoryPath);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int res = DownloadFile(Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator
+ "test.jpg");
Log.d(TAG, "Result Code: " + res);
}
}
main-jni.cpp
#include <jni.h>
#include <android/log.h>
#include <string>
#include <curl/curl.h>
#define LOG_TAG "native"
#define LOG_INFO(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOG_ERROR(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOG_WARN(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOG_DEBUG(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#ifdef __cplusplus
extern "C"
{
#endif
// [FIX for Android 4.2.x]
// "WARNING: Could not load native library:
// Cannot load library: soinfo_relocate(linker.cpp:975): cannot locate symbol "__exidx_end" referenced by"
// http://stackoverflow.com/a/14501998/313113
void __exidx_start()
{
}
void __exidx_end()
{
}
size_t write_data(void *ptr, size_t size, size_t count, FILE *stream)
{
size_t written;
written = fwrite(ptr, size, count, stream);
LOG_DEBUG("Writing data to file stream %u", written);
return written;
}
jint Java_com_company_awesomeapp_MainActivity_DownloadFile(JNIEnv* env, jobject thiz,
jstring downloadDirectoryPath)
{
CURLcode res;
res = curl_global_init(CURL_GLOBAL_ALL);
jint temp = 3;
LOG_DEBUG("Downloading file");
const char *nativeDownloadDirPath = env->GetStringUTFChars(downloadDirectoryPath, 0);
LOG_DEBUG(nativeDownloadDirPath);
CURL *curl;
FILE *fp;
std::string url = "http://travel.paintedstork.com/blog/wp-content/uploads/2012/10/2013-calendar-images-1.jpg";
curl = curl_easy_init();
if (curl)
{
fp = fopen(nativeDownloadDirPath, "wb");
res = curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
LOG_DEBUG("Before write function");
res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
LOG_DEBUG("After write function");
LOG_DEBUG("Before write data");
res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
LOG_DEBUG("After write data");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (fp) fclose(fp);
}
env->ReleaseStringUTFChars(downloadDirectoryPath, nativeDownloadDirPath);
return res;
}
/**
* The VM calls JNI_OnLoad when the native library is loaded (for example, through System.loadLibrary).
* JNI_OnLoad must return the JNI version needed by the native library.
*
* #see http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html#JNI_OnLoad
*/JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK)
{
return -1;
}
// [*] Get jclass with env->FindClass.
// [*] Register methods with env->RegisterNatives.
//jniRegisterNativeMethods(env, "dev/android/sample/AndroidNDKSampleActivity", sMethods, NELEM(sMethods));
return JNI_VERSION_1_6;
}
/**
* The VM calls JNI_OnUnload when the class loader containing the native library is garbage collected.
* This function can be used to perform cleanup operations.
*
* Because this function is called in an unknown context (such as from a finalizer),
* the programmer should be conservative on using Java VM services, and refrain from arbitrary
* Java call-backs.
* #see http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html#JNI_OnUnload
*/JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved)
{
}
#ifdef __cplusplus
}
#endif
The file will be saved at: /storage/emulated/0/Download/test.jpg
This can also happen if you compile libcurl without threaded resolver (CMake option ENABLE_THREADED_RESOLVER) while targeting Android API level less than 23.
The problem is because implementation of CMake/CurlTests.c contains this line:
#ifndef gethostbyaddr_r
(void)gethostbyaddr_r;
#endif
However, if you check the netdb.h header in Android NDK, you will see
#if __ANDROID_API__ >= 23
int gethostbyaddr_r(const void* __addr, socklen_t __length, int __type, struct hostent* __ret, char* __buf, size_t __buf_size, struct hostent** __result, int* __h_errno_ptr) __INTRODUCED_IN(23);
#endif /* __ANDROID_API__ >= 23 */
This means that this function is not available when targeting Android older than Marshmallow. This is problematic, as testing for HAVE_GETHOSTBYNAME_R succeeds, while testing for HAVE_GETHOSTBYNAME_R_6 fails (but should succeed) with following error (observable in CMakeError.log):
/path/to/curl/CMake/CurlTests.c:128:9: error: use of undeclared identifier 'gethostbyaddr_r'
(void)gethostbyaddr_r;
^
1 error generated.
This then results with no-op behaviour in function Curl_ipv4_resolve_r in file hostip4.c, as it expects that after HAVE_GETHOSTBYNAME_R is defined, that at least one of HAVE_GETHOSTBYNAME_R_5, HAVE_GETHOSTBYNAME_R_6 or HAVE_GETHOSTBYNAME_R_3. Therefore, curl doesn't even try to resolve the host.
To fix this problem, simply remove those problematic lines from CMake/CurlTest.c.
I didn't try building curl with configure script, as in official documentation, but even if you do, it clearly states that you should target Android M or above if you plan on supporting SSL via OpenSSL, but AFAIK for simple HTTP support it should work.
The problem is gone if you use threaded resolver, as it uses different system API for performing the DNS resolution (getaddrinfo in function Curl_getaddrinfo_ex in curl_addrinfo.c). getaddrinfo is more modern API, but may not be available on all platform curl targets, such as embedded systems, which may also lack thread support. Therefore, curl uses the traditional approach in DNS resolution when threads are disabled.
P.S. Sorry for resurrecting this question after more than 7 years, but after facing the exact same problem as you, this StackOverflow question was the only similar Google search result 😛
I have some problems when using the dynamic loading API (<dlfcn.h>: dlopen(), dlclose(), etc) on Android.
I'm using NDK standalone toolchain (version 8) to compile the applications and libraries.
The Android version is 2.2.1 Froyo.
Here is the source code of the simple shared library.
#include <stdio.h>
int iii = 0;
int *ptr = NULL;
__attribute__((constructor))
static void init()
{
iii = 653;
}
__attribute__((destructor))
static void cleanup()
{
}
int aaa(int i)
{
printf("aaa %d\n", iii);
}
Here is the program source code which uses the mentioned library.
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
void *handle;
typedef int (*func)(int);
func bbb;
printf("start...\n");
handle = dlopen("/data/testt/test.so", RTLD_LAZY);
if (!handle)
{
return 0;
}
bbb = (func)dlsym(handle, "aaa");
if (bbb == NULL)
{
return 0;
}
bbb(1);
dlclose(handle);
printf("exit...\n");
return 0;
}
With these sources everything is working fine, but when I try to use some STL functions or classes, the program crashes with a segmentation fault, when the main() function exits, for example when using this source code for the shared library.
#include <iostream>
using namespace std;
int iii = 0;
int *ptr = NULL;
__attribute__((constructor))
static void init()
{
iii = 653;
}
__attribute__((destructor))
static void cleanup()
{
}
int aaa(int i)
{
cout << iii << endl;
}
With this code, the program crashes with segmentation fault after or the during main() function exit.
I have tried couple of tests and found the following results.
Without using of STL everything is working fine.
When use STL and do not call dlclose() at the end, everything is working fine.
I tried to compile with various compilation flags like -fno-use-cxa-atexit or -fuse-cxa-atexit, the result is the same.
What is wrong in my code that uses the STL?
Looks like I found the reason of the bug. I have tried another example with the following source files:
Here is the source code of the simple class:
myclass.h
class MyClass
{
public:
MyClass();
~MyClass();
void Set();
void Show();
private:
int *pArray;
};
myclass.cpp
#include <stdio.h>
#include <stdlib.h>
#include "myclass.h"
MyClass::MyClass()
{
pArray = (int *)malloc(sizeof(int) * 5);
}
MyClass::~MyClass()
{
free(pArray);
pArray = NULL;
}
void MyClass::Set()
{
if (pArray != NULL)
{
pArray[0] = 0;
pArray[1] = 1;
pArray[2] = 2;
pArray[3] = 3;
pArray[4] = 4;
}
}
void MyClass::Show()
{
if (pArray != NULL)
{
for (int i = 0; i < 5; i++)
{
printf("pArray[%d] = %d\n", i, pArray[i]);
}
}
}
As you can see from the code I did not used any STL related stuff.
Here is the source files of the functions library exports.
func.h
#ifdef __cplusplus
extern "C" {
#endif
int SetBabe(int);
int ShowBabe(int);
#ifdef __cplusplus
}
#endif
func.cpp
#include <stdio.h>
#include "myclass.h"
#include "func.h"
MyClass cls;
__attribute__((constructor))
static void init()
{
}
__attribute__((destructor))
static void cleanup()
{
}
int SetBabe(int i)
{
cls.Set();
return i;
}
int ShowBabe(int i)
{
cls.Show();
return i;
}
And finally this is the source code of the programm that uses the library.
main.cpp
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include "../simple_lib/func.h"
int main()
{
void *handle;
typedef int (*func)(int);
func bbb;
printf("start...\n");
handle = dlopen("/data/testt/test.so", RTLD_LAZY);
if (!handle)
{
printf("%s\n", dlerror());
return 0;
}
bbb = (func)dlsym(handle, "SetBabe");
if (bbb == NULL)
{
printf("%s\n", dlerror());
return 0;
}
bbb(1);
bbb = (func)dlsym(handle, "ShowBabe");
if (bbb == NULL)
{
printf("%s\n", dlerror());
return 0;
}
bbb(1);
dlclose(handle);
printf("exit...\n");
return 0;
}
Again as you can see the program using the library also does not using any STL related stuff, but after run of the program I got the same segmentation fault during main(...) function exit. So the issue is not connected to STL itself, and it is hidden in some other place. Then after some long research I found the bug.
Normally the destructors of static C++ variables are called immediately before main(...) function exit, if they are defined in main program, or if they are defined in some library and you are using it, then the destructors should be called immediately before dlclose(...).
On Android OS all destructors(defined in main program or in some library you are using) of static C++ variables are called during main(...) function exit. So what happens in our case? We have cls static C++ variable defined in library we are using. Then immediately before main(...) function exit we call dlclose(...) function, as a result library closed and cls becomes non valid. But the pointer of cls is stored somewhere and it's destructor should be called during main(...) function exit, and because at the time of call it is already invalid, we get segmentation fault. So the solution is to not call dlclose(...) and everything should be fine. Unfortunately with this solution we cannot use attribute((destructor)) for deinitializing of something we want to deinitialize, because it is called as a result of dlclose(...) call.
I have a general aversion to calling dlclose(). The problem is that you must ensure that nothing will try to execute code in the shared library after it has been unmapped, or you will get a segmentation fault.
The most common way to fail is to create an object whose destructor is defined in or calls code defined in the shared library. If the object still exists after dlclose(), your app will crash when the object is deleted.
If you look at logcat you should see a debuggerd stack trace. If you can decode that with the arm-eabi-addr2line tool you should be able to determine if it's in a destructor, and if so, for what class. Alternatively, take the crash address, strip off the high 12 bits, and use that as an offset into the library that was dlclose()d and try to figure out what code lives at that address.
I encountered the same headache on Linux. A work-around that fixes my segfault is to put these lines in the same file as main(), so that dlclose() is called after main returns:
static void* handle = 0;
void myDLClose(void) __attribute__ ((destructor));
void myDLClose(void)
{
dlclose(handle);
}
int main()
{
handle = dlopen(...);
/* ... real work ... */
return 0;
}
The root cause of dlclose-induced segfault may be that a particular implementation of dlclose() does not clean up the global variables inside the shared object.
You need to compile with -fpic as a compiler flag for the application that is using dlopen() and dlclose(). You should also try error handling via dlerror() and perhaps checking if the assignment of your function pointer is valid, even if it's not NULL the function pointer could be pointing to something invalid from the initialization, dlsym() is not guaranteed to return NULL on android if it cannot find a symbol. Refer to the android documentation opposed to the posix compliant stuff, not everything is posix compliant on android.
You should use extern "C" to declare you function aaa()