Issue
We are using C libraries in our Android-NDK project. We are using dlopen( ) & dlclose( ) to work with our libraries in Android NDK. When we are calling the dlopen( ), the library's _init( ) is getting called as expected. But on the contrary, when we close the library with dlclose( ) call, the _fini( ) function is not getting called. We don't want to explicitly call the _fini( ) function after calling the dlclose( ) API. I'm testing these on API 24.
As per linux, the two functions _init( ) & _fini( ) should be called when we invoke dlopen( ) & dlclose( ) respectively.
void func( ){
...
int ret = -1;
handle = dlopen( "mylib.so", RTLD_NOW | RTLD_GLOBAL );
ret = dlclose( handle ); // dlclose() is returning 0.
...
}
void _init( ){
log("dlopen is loading the library");
}
void _fini( ){
log("dlclose is unloading the library");
}
I have also tried changing the syntax of _fini( ) as below, but with no luck.
void _fini() __attribute__((destructor));
Even with the 'destructor' attribute as in the previous line, the _fini( ) is not getting called upon dlclose( ).
Since the _init( ) function is getting called upon dlopen( ), I'm sure that _fini( ) should also be called upon dlclose( ), so I should be missing something. We are using Android Studio to build the apk. Can anyone please help me out on this. Thanks in advance.
Solution
The best advice I can give about dlclose
is to never use dlclose
.
dlclose
is not specified to do anything other than inform the runtime that it may unload the library; the runtime does not have to do anything about it. For systems that do implement unloading (Android included) are not always able to do so because things like atexit
handlers (or thread exit handlers, etc) cannot be run until the whole program exits, so any time a library registers such a handler it cannot be unloaded. That appears to be the case here.
The exact use case can cause the answer to vary, but for the cases we've seen where this sort of behavior cannot be removed (a plug in interface where plugins are expected to unload, then reload with all their state reset), the fix is to add explicit Initialize()
and ShutDown()
functions to the library. These need to be called by the library user rather than relying on dlopen
/dlclose
.
Answered By - Dan Albert
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.