1. 说明
Android 7.0 后使用 dlopen 函数无法获取 soinfo 对应,因此也无法使用 dlsym 函数去调用第三方的 so 内的函数。这里给出 dlopen() 函数的源码分析。
2. 源码分析
1. dlopen 函数
函数调用会首先走到 dlfcn.cpp 类内的 dlopen 函数(/bionic/linker/dlfcn.cpp)
85void* dlopen(const char* filename, int flags) {
86 void* caller_addr = __builtin_return_address(0);
87 return dlopen_ext(filename, flags, nullptr, caller_addr);
88}
69static void* dlopen_ext(const char* filename, int flags,
70 const android_dlextinfo* extinfo, void* caller_addr) {
71 ScopedPthreadMutexLocker locker(&g_dl_mutex);
72 void* result = do_dlopen(filename, flags, extinfo, caller_addr); // 调到 linker.cpp 类内
73 if (result == nullptr) {
74 __bionic_format_dlerror("dlopen failed", linker_get_error_buffer());
75 return nullptr;
76 }
77 return result;
78}
2. do_dlopen() 函数
这个函数实现在 linker.cpp 类内。do_dlopen 函数会调用 find_library 函数返回 soinfo 对象,并最终调用 si->to_handle() 函数返回 handle_。(/bionic/linker/linker.cpp)
2333void* do_dlopen(const char* name, int flags, const android_dlextinfo* extinfo,
2334 void* caller_addr) {
2335 soinfo* const caller = find_containing_library(caller_addr);
2336
2337 if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
2338 DL_ERR("invalid flags to dlopen: %x", flags);
2339 return nullptr;
2340 }
2341
2342 android_namespace_t* ns = get_caller_namespace(caller);
2343
2344 if (extinfo != nullptr) {
2345 if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
2346 DL_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
2347 return nullptr;
2348 }
2349
2350 if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
2351 (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
2352 DL_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
2353 "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
2354 return nullptr;
2355 }
2356
2357 if ((extinfo->flags & ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS) != 0 &&
2358 (extinfo->flags & (ANDROID_DLEXT_RESERVED_ADDRESS | ANDROID_DLEXT_RESERVED_ADDRESS_HINT)) != 0) {
2359 DL_ERR("invalid extended flag combination: ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS is not "
2360 "compatible with ANDROID_DLEXT_RESERVED_ADDRESS/ANDROID_DLEXT_RESERVED_ADDRESS_HINT");
2361 return nullptr;
2362 }
2363
2364 if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2365 if (extinfo->library_namespace == nullptr) {
2366 DL_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
2367 return nullptr;
2368 }
2369 ns = extinfo->library_namespace;
2370 }
2371 }
2372
2373 ProtectedDataGuard guard;
2374 soinfo* si = find_library(ns, name, flags, extinfo, caller); // 这里往下调用返回 soinfo 对象
2375 if (si != nullptr) {
2376 si->call_constructors();
2377 return si->to_handle(); // 这里返回的是 调用 to_handle() 函数
2378 }</