Segmentation fault when using dlclose(...) on android platform

Viewed 7813

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.

  1. Without using of STL everything is working fine.
  2. When use STL and do not call dlclose() at the end, everything is working fine.
  3. 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?

5 Answers
Related