blob: f9c161c6d3432c16fcc956c99703627ebd8607c4 [file] [log] [blame]
Dimitry Ivanovac1b1912015-12-01 13:56:44 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "nativeloader/native_loader.h"
Steven Moreland00fe3ad2017-07-18 16:53:54 -070018#include <nativehelper/ScopedUtfChars.h>
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080019
20#include <dlfcn.h>
21#ifdef __ANDROID__
Dimitry Ivanov7f9a1aa2016-03-22 13:59:59 -070022#define LOG_TAG "libnativeloader"
Jesse Hallb75d82b2017-01-09 16:04:28 -080023#include "nativeloader/dlext_namespaces.h"
Mark Salyzyn30f991f2017-01-10 13:19:54 -080024#include "log/log.h"
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080025#endif
Jiyong Parkd1006fe2017-11-08 18:44:09 +090026#include <dirent.h>
27#include <sys/types.h>
Zhenhua WANGf2804e52016-05-30 11:16:08 +080028#include "nativebridge/native_bridge.h"
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080029
30#include <algorithm>
Victor Khimenko1443ec42018-07-09 17:01:22 +020031#include <list>
Jiyong Parkd1006fe2017-11-08 18:44:09 +090032#include <memory>
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080033#include <mutex>
Jiyong Parkd1006fe2017-11-08 18:44:09 +090034#include <string>
35#include <vector>
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080036
Mark Salyzynff2dcd92016-09-28 15:54:45 -070037#include <android-base/file.h>
38#include <android-base/macros.h>
39#include <android-base/strings.h>
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080040
Justin Yun4a1d1102017-11-27 17:04:14 +090041#ifdef __BIONIC__
42#include <android-base/properties.h>
43#endif
44
Zhenhua WANGf2804e52016-05-30 11:16:08 +080045#define CHECK(predicate) LOG_ALWAYS_FATAL_IF(!(predicate),\
46 "%s:%d: %s CHECK '" #predicate "' failed.",\
47 __FILE__, __LINE__, __FUNCTION__)
48
Inseob Kim67cb0562018-05-04 11:39:12 +090049using namespace std::string_literals;
50
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080051namespace android {
52
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -070053#if defined(__ANDROID__)
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +000054struct NativeLoaderNamespace {
Zhenhua WANGf2804e52016-05-30 11:16:08 +080055 public:
56 NativeLoaderNamespace()
57 : android_ns_(nullptr), native_bridge_ns_(nullptr) { }
58
59 explicit NativeLoaderNamespace(android_namespace_t* ns)
60 : android_ns_(ns), native_bridge_ns_(nullptr) { }
61
62 explicit NativeLoaderNamespace(native_bridge_namespace_t* ns)
63 : android_ns_(nullptr), native_bridge_ns_(ns) { }
64
65 NativeLoaderNamespace(NativeLoaderNamespace&& that) = default;
66 NativeLoaderNamespace(const NativeLoaderNamespace& that) = default;
67
68 NativeLoaderNamespace& operator=(const NativeLoaderNamespace& that) = default;
69
70 android_namespace_t* get_android_ns() const {
71 CHECK(native_bridge_ns_ == nullptr);
72 return android_ns_;
73 }
74
75 native_bridge_namespace_t* get_native_bridge_ns() const {
76 CHECK(android_ns_ == nullptr);
77 return native_bridge_ns_;
78 }
79
80 bool is_android_namespace() const {
81 return native_bridge_ns_ == nullptr;
82 }
83
84 private:
85 // Only one of them can be not null
86 android_namespace_t* android_ns_;
87 native_bridge_namespace_t* native_bridge_ns_;
88};
89
Jiyong Parkd1006fe2017-11-08 18:44:09 +090090static constexpr const char kPublicNativeLibrariesSystemConfigPathFromRoot[] =
91 "/etc/public.libraries.txt";
92static constexpr const char kPublicNativeLibrariesExtensionConfigPrefix[] = "public.libraries-";
93static constexpr const size_t kPublicNativeLibrariesExtensionConfigPrefixLen =
94 sizeof(kPublicNativeLibrariesExtensionConfigPrefix) - 1;
95static constexpr const char kPublicNativeLibrariesExtensionConfigSuffix[] = ".txt";
96static constexpr const size_t kPublicNativeLibrariesExtensionConfigSuffixLen =
97 sizeof(kPublicNativeLibrariesExtensionConfigSuffix) - 1;
98static constexpr const char kPublicNativeLibrariesVendorConfig[] =
99 "/vendor/etc/public.libraries.txt";
100static constexpr const char kLlndkNativeLibrariesSystemConfigPathFromRoot[] =
101 "/etc/llndk.libraries.txt";
102static constexpr const char kVndkspNativeLibrariesSystemConfigPathFromRoot[] =
103 "/etc/vndksp.libraries.txt";
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800104
Victor Chang7a20a902019-01-28 18:43:24 +0000105static const std::vector<const std::string> kRuntimePublicLibraries = {
106 "libicuuc.so",
107 "libicui18n.so",
108};
109
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700110// The device may be configured to have the vendor libraries loaded to a separate namespace.
111// For historical reasons this namespace was named sphal but effectively it is intended
112// to use to load vendor libraries to separate namespace with controlled interface between
113// vendor and system namespaces.
114static constexpr const char* kVendorNamespaceName = "sphal";
115
Jiyong Parka07f3052017-08-22 10:26:10 +0900116static constexpr const char* kVndkNamespaceName = "vndk";
117
Victor Chang7a20a902019-01-28 18:43:24 +0000118static constexpr const char* kRuntimeNamespaceName = "runtime";
119
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000120// classloader-namespace is a linker namespace that is created for the loaded
121// app. To be specific, it is created for the app classloader. When
122// System.load() is called from a Java class that is loaded from the
123// classloader, the classloader-namespace namespace associated with that
124// classloader is selected for dlopen. The namespace is configured so that its
125// search path is set to the app-local JNI directory and it is linked to the
126// default namespace with the names of libs listed in the public.libraries.txt.
127// This way an app can only load its own JNI libraries along with the public libs.
Jiyong Parka07f3052017-08-22 10:26:10 +0900128static constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000129// Same thing for vendor APKs.
Jiyong Parka07f3052017-08-22 10:26:10 +0900130static constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
131
Dimitry Ivanovf334cbf2016-05-10 10:39:48 -0700132// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
133// System.load() with an absolute path which is outside of the classloader library search path.
134// This list includes all directories app is allowed to access this way.
135static constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
136
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000137static constexpr const char* kApexPath = "/apex/";
138
Victor Changf70a2fe2019-02-01 20:01:27 +0000139#if defined(__LP64__)
140static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib64";
141#else
142static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib";
143#endif
144
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700145static bool is_debuggable() {
Orion Hodson34b126b2019-02-21 17:18:44 +0000146 bool debuggable = false;
147#ifdef __BIONIC__
148 debuggable = android::base::GetBoolProperty("ro.debuggable", false);
149#endif
150 return debuggable;
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700151}
152
Justin Yun4a1d1102017-11-27 17:04:14 +0900153static std::string vndk_version_str() {
154#ifdef __BIONIC__
155 std::string version = android::base::GetProperty("ro.vndk.version", "");
156 if (version != "" && version != "current") {
157 return "." + version;
158 }
159#endif
160 return "";
161}
162
163static void insert_vndk_version_str(std::string* file_name) {
164 CHECK(file_name != nullptr);
165 size_t insert_pos = file_name->find_last_of(".");
166 if (insert_pos == std::string::npos) {
167 insert_pos = file_name->length();
168 }
169 file_name->insert(insert_pos, vndk_version_str());
170}
171
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900172static const std::function<bool(const std::string&, std::string*)> always_true =
173 [](const std::string&, std::string*) { return true; };
174
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800175class LibraryNamespaces {
176 public:
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800177 LibraryNamespaces() : initialized_(false) { }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800178
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000179 NativeLoaderNamespace* Create(JNIEnv* env, uint32_t target_sdk_version, jobject class_loader,
180 bool is_shared, bool is_for_vendor, jstring java_library_path,
181 jstring java_permitted_path, std::string* error_msg) {
Dimitry Ivanovcf9892b2016-05-09 10:55:50 -0700182 std::string library_path; // empty string by default.
183
184 if (java_library_path != nullptr) {
185 ScopedUtfChars library_path_utf_chars(env, java_library_path);
186 library_path = library_path_utf_chars.c_str();
187 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800188
Dimitry Ivanovf334cbf2016-05-10 10:39:48 -0700189 // (http://b/27588281) This is a workaround for apps using custom
190 // classloaders and calling System.load() with an absolute path which
191 // is outside of the classloader library search path.
192 //
193 // This part effectively allows such a classloader to access anything
194 // under /data and /mnt/expand
195 std::string permitted_path = kWhitelistedDirectories;
196
Dimitry Ivanov0d6e5942015-12-08 11:16:56 -0800197 if (java_permitted_path != nullptr) {
198 ScopedUtfChars path(env, java_permitted_path);
Dimitry Ivanovd0b15312016-05-10 16:21:25 -0700199 if (path.c_str() != nullptr && path.size() > 0) {
200 permitted_path = permitted_path + ":" + path.c_str();
201 }
Dimitry Ivanov0d6e5942015-12-08 11:16:56 -0800202 }
203
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800204 if (!initialized_ && !InitPublicNamespace(library_path.c_str(), error_msg)) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200205 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800206 }
207
Victor Khimenko1443ec42018-07-09 17:01:22 +0200208 bool found = FindNamespaceByClassLoader(env, class_loader);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800209
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800210 LOG_ALWAYS_FATAL_IF(found,
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700211 "There is already a namespace associated with this classloader");
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800212
Dimitry Ivanovd2a62202015-12-15 11:06:57 -0800213 uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
214 if (is_shared) {
215 namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
216 }
217
Dimitry Ivanov9e253ce2017-05-08 22:24:24 -0700218 if (target_sdk_version < 24) {
219 namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
220 }
221
Victor Khimenko1443ec42018-07-09 17:01:22 +0200222 NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700223
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800224 bool is_native_bridge = false;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800225
Victor Khimenko1443ec42018-07-09 17:01:22 +0200226 if (parent_ns != nullptr) {
227 is_native_bridge = !parent_ns->is_android_namespace();
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800228 } else if (!library_path.empty()) {
229 is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800230 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800231
Jiyong Parka07f3052017-08-22 10:26:10 +0900232 std::string system_exposed_libraries = system_public_libraries_;
233 const char* namespace_name = kClassloaderNamespaceName;
234 android_namespace_t* vndk_ns = nullptr;
235 if (is_for_vendor && !is_shared) {
236 LOG_FATAL_IF(is_native_bridge, "Unbundled vendor apk must not use translated architecture");
237
238 // For vendor apks, give access to the vendor lib even though
239 // they are treated as unbundled; the libs and apks are still bundled
240 // together in the vendor partition.
241#if defined(__LP64__)
242 std::string vendor_lib_path = "/vendor/lib64";
243#else
244 std::string vendor_lib_path = "/vendor/lib";
245#endif
246 library_path = library_path + ":" + vendor_lib_path.c_str();
247 permitted_path = permitted_path + ":" + vendor_lib_path.c_str();
248
249 // Also give access to LLNDK libraries since they are available to vendors
250 system_exposed_libraries = system_exposed_libraries + ":" + system_llndk_libraries_.c_str();
251
252 // Give access to VNDK-SP libraries from the 'vndk' namespace.
253 vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
254 LOG_ALWAYS_FATAL_IF(vndk_ns == nullptr,
255 "Cannot find \"%s\" namespace for vendor apks", kVndkNamespaceName);
256
257 // Different name is useful for debugging
258 namespace_name = kVendorClassloaderNamespaceName;
259 ALOGD("classloader namespace configured for unbundled vendor apk. library_path=%s", library_path.c_str());
Inseob Kim67cb0562018-05-04 11:39:12 +0900260 } else {
261 // oem and product public libraries are NOT available to vendor apks, otherwise it
Jiyong Parke0319942018-01-15 21:14:53 +0900262 // would be system->vendor violation.
Inseob Kim67cb0562018-05-04 11:39:12 +0900263 if (!oem_public_libraries_.empty()) {
264 system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries_;
265 }
266 if (!product_public_libraries_.empty()) {
267 system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries_;
268 }
Jiyong Parka07f3052017-08-22 10:26:10 +0900269 }
270
Victor Chang7a20a902019-01-28 18:43:24 +0000271 std::string runtime_exposed_libraries = base::Join(kRuntimePublicLibraries, ":");
272
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800273 NativeLoaderNamespace native_loader_ns;
274 if (!is_native_bridge) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200275 android_namespace_t* android_parent_ns =
276 parent_ns == nullptr ? nullptr : parent_ns->get_android_ns();
Jiyong Parka07f3052017-08-22 10:26:10 +0900277 android_namespace_t* ns = android_create_namespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800278 nullptr,
279 library_path.c_str(),
280 namespace_type,
281 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200282 android_parent_ns);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800283 if (ns == nullptr) {
284 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200285 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800286 }
287
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700288 // Note that when vendor_ns is not configured this function will return nullptr
289 // and it will result in linking vendor_public_libraries_ to the default namespace
290 // which is expected behavior in this case.
291 android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
292
Victor Chang7a20a902019-01-28 18:43:24 +0000293 android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
294
Jiyong Parka07f3052017-08-22 10:26:10 +0900295 if (!android_link_namespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800296 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200297 return nullptr;
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800298 }
299
Victor Chang7a20a902019-01-28 18:43:24 +0000300 // Runtime apex does not exist in host, and under certain build conditions.
301 if (runtime_ns != nullptr) {
302 if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
303 *error_msg = dlerror();
304 return nullptr;
305 }
306 }
307
Jiyong Parka07f3052017-08-22 10:26:10 +0900308 if (vndk_ns != nullptr && !system_vndksp_libraries_.empty()) {
309 // vendor apks are allowed to use VNDK-SP libraries.
310 if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries_.c_str())) {
311 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200312 return nullptr;
Jiyong Parka07f3052017-08-22 10:26:10 +0900313 }
314 }
315
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700316 if (!vendor_public_libraries_.empty()) {
317 if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
318 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200319 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700320 }
321 }
322
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800323 native_loader_ns = NativeLoaderNamespace(ns);
324 } else {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200325 native_bridge_namespace_t* native_bridge_parent_namespace =
326 parent_ns == nullptr ? nullptr : parent_ns->get_native_bridge_ns();
Jiyong Parka07f3052017-08-22 10:26:10 +0900327 native_bridge_namespace_t* ns = NativeBridgeCreateNamespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800328 nullptr,
329 library_path.c_str(),
330 namespace_type,
331 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200332 native_bridge_parent_namespace);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800333 if (ns == nullptr) {
334 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200335 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800336 }
337
dimitryd2ace382019-02-04 15:06:43 +0100338 native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
Victor Chang7a20a902019-01-28 18:43:24 +0000339 native_bridge_namespace_t* runtime_ns =
340 NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700341
Jiyong Parka07f3052017-08-22 10:26:10 +0900342 if (!NativeBridgeLinkNamespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800343 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200344 return nullptr;
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800345 }
346
Victor Chang7a20a902019-01-28 18:43:24 +0000347 // Runtime apex does not exist in host, and under certain build conditions.
348 if (runtime_ns != nullptr) {
349 if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
350 *error_msg = NativeBridgeGetError();
351 return nullptr;
352 }
353 }
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700354 if (!vendor_public_libraries_.empty()) {
355 if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
356 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200357 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700358 }
359 }
360
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800361 native_loader_ns = NativeLoaderNamespace(ns);
362 }
363
364 namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
365
Victor Khimenko1443ec42018-07-09 17:01:22 +0200366 return &(namespaces_.back().second);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800367 }
368
Victor Khimenko1443ec42018-07-09 17:01:22 +0200369 NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800370 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800371 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800372 return env->IsSameObject(value.first, class_loader);
373 });
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800374 if (it != namespaces_.end()) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200375 return &it->second;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800376 }
377
Victor Khimenko1443ec42018-07-09 17:01:22 +0200378 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800379 }
380
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700381 void Initialize() {
Dimitry Ivanov80ddb8f2016-05-09 18:12:00 -0700382 // Once public namespace is initialized there is no
383 // point in running this code - it will have no effect
384 // on the current list of public libraries.
385 if (initialized_) {
386 return;
387 }
388
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700389 std::vector<std::string> sonames;
Dimitry Ivanov0b5651e2016-04-21 16:42:48 -0700390 const char* android_root_env = getenv("ANDROID_ROOT");
391 std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
392 std::string public_native_libraries_system_config =
393 root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
Jiyong Parka07f3052017-08-22 10:26:10 +0900394 std::string llndk_native_libraries_system_config =
395 root_dir + kLlndkNativeLibrariesSystemConfigPathFromRoot;
396 std::string vndksp_native_libraries_system_config =
397 root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700398
Inseob Kim67cb0562018-05-04 11:39:12 +0900399 std::string product_public_native_libraries_dir = "/product/etc";
400
Christopher Ferris39da84b2016-06-21 16:11:23 -0700401 std::string error_msg;
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900402 LOG_ALWAYS_FATAL_IF(
403 !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
404 "Error reading public native library list from \"%s\": %s",
405 public_native_libraries_system_config.c_str(), error_msg.c_str());
406
Jiyong Parke0319942018-01-15 21:14:53 +0900407 // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
408 // variable to add libraries to the list. This is intended for platform tests only.
409 if (is_debuggable()) {
410 const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
411 if (additional_libs != nullptr && additional_libs[0] != '\0') {
412 std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
413 std::copy(additional_libs_vector.begin(), additional_libs_vector.end(),
414 std::back_inserter(sonames));
415 }
416 }
417
Victor Changf70a2fe2019-02-01 20:01:27 +0000418 // Remove the public libs in the runtime namespace.
419 // These libs are listed in public.android.txt, but we don't want the rest of android
420 // in default namespace to dlopen the libs.
421 // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
422 // Unfortunately, it does not have stable C symbols, and default namespace should only use
423 // stable symbols in libandroidicu.so. http://b/120786417
424 removePublicLibsIfExistsInRuntimeApex(sonames);
425
Jiyong Parke0319942018-01-15 21:14:53 +0900426 // android_init_namespaces() expects all the public libraries
427 // to be loaded so that they can be found by soname alone.
428 //
429 // TODO(dimitry): this is a bit misleading since we do not know
430 // if the vendor public library is going to be opened from /vendor/lib
Inseob Kim67cb0562018-05-04 11:39:12 +0900431 // we might as well end up loading them from /system/lib or /product/lib
Jiyong Parke0319942018-01-15 21:14:53 +0900432 // For now we rely on CTS test to catch things like this but
433 // it should probably be addressed in the future.
434 for (const auto& soname : sonames) {
435 LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
436 "Error preloading public library %s: %s", soname.c_str(), dlerror());
437 }
438
439 system_public_libraries_ = base::Join(sonames, ':');
440
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900441 // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
442 // system libs that are exposed to apps. The libs in the txt files must be
443 // named as lib<name>.<companyname>.so.
Jiyong Parke0319942018-01-15 21:14:53 +0900444 sonames.clear();
Inseob Kim67cb0562018-05-04 11:39:12 +0900445 ReadExtensionLibraries(base::Dirname(public_native_libraries_system_config).c_str(), &sonames);
Jiyong Parke0319942018-01-15 21:14:53 +0900446 oem_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700447
Inseob Kim67cb0562018-05-04 11:39:12 +0900448 // read /product/etc/public.libraries-<companyname>.txt which contain partner defined
449 // product libs that are exposed to apps.
450 sonames.clear();
451 ReadExtensionLibraries(product_public_native_libraries_dir.c_str(), &sonames);
452 product_public_libraries_ = base::Join(sonames, ':');
453
Justin Yun4a1d1102017-11-27 17:04:14 +0900454 // Insert VNDK version to llndk and vndksp config file names.
455 insert_vndk_version_str(&llndk_native_libraries_system_config);
456 insert_vndk_version_str(&vndksp_native_libraries_system_config);
457
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700458 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900459 ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900460 system_llndk_libraries_ = base::Join(sonames, ':');
461
462 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900463 ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900464 system_vndksp_libraries_ = base::Join(sonames, ':');
465
466 sonames.clear();
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700467 // This file is optional, quietly ignore if the file does not exist.
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900468 ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700469
470 vendor_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700471 }
472
Inseob Kim67cb0562018-05-04 11:39:12 +0900473 void Reset() { namespaces_.clear(); }
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700474
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700475 private:
Inseob Kim67cb0562018-05-04 11:39:12 +0900476 void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
477 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
478 if (dir != nullptr) {
479 // Failing to opening the dir is not an error, which can happen in
480 // webview_zygote.
481 while (struct dirent* ent = readdir(dir.get())) {
482 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
483 continue;
484 }
485 const std::string filename(ent->d_name);
486 if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
487 android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
488 const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
489 const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
490 const std::string company_name = filename.substr(start, end - start);
491 const std::string config_file_path = dirname + "/"s + filename;
492 LOG_ALWAYS_FATAL_IF(
493 company_name.empty(),
494 "Error extracting company name from public native library list file path \"%s\"",
495 config_file_path.c_str());
496
497 std::string error_msg;
498
499 LOG_ALWAYS_FATAL_IF(
500 !ReadConfig(
501 config_file_path, sonames,
502 [&company_name](const std::string& soname, std::string* error_msg) {
503 if (android::base::StartsWith(soname, "lib") &&
504 android::base::EndsWith(soname, "." + company_name + ".so")) {
505 return true;
506 } else {
507 *error_msg = "Library name \"" + soname +
508 "\" does not end with the company name: " + company_name + ".";
509 return false;
510 }
511 },
512 &error_msg),
513 "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
514 error_msg.c_str());
515 }
516 }
517 }
518 }
519
Victor Changf70a2fe2019-02-01 20:01:27 +0000520 /**
521 * Remove the public libs in runtime namespace
522 */
523 void removePublicLibsIfExistsInRuntimeApex(std::vector<std::string>& sonames) {
524 for (const std::string& lib_name : kRuntimePublicLibraries) {
525 std::string path(kRuntimeApexLibPath);
526 path.append("/").append(lib_name);
527
528 struct stat s;
529 // Do nothing if the path in /apex does not exist.
530 // Runtime APEX must be mounted since libnativeloader is in the same APEX
531 if (stat(path.c_str(), &s) != 0) {
532 continue;
533 }
534
535 auto it = std::find(sonames.begin(), sonames.end(), lib_name);
536 if (it != sonames.end()) {
537 sonames.erase(it);
538 }
539 }
540 }
Inseob Kim67cb0562018-05-04 11:39:12 +0900541
Christopher Ferris39da84b2016-06-21 16:11:23 -0700542 bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900543 const std::function<bool(const std::string& /* soname */,
544 std::string* /* error_msg */)>& check_soname,
Christopher Ferris39da84b2016-06-21 16:11:23 -0700545 std::string* error_msg = nullptr) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700546 // Read list of public native libraries from the config file.
547 std::string file_content;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700548 if(!base::ReadFileToString(configFile, &file_content)) {
Christopher Ferris39da84b2016-06-21 16:11:23 -0700549 if (error_msg) *error_msg = strerror(errno);
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700550 return false;
551 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700552
553 std::vector<std::string> lines = base::Split(file_content, "\n");
554
Christopher Ferris39da84b2016-06-21 16:11:23 -0700555 for (auto& line : lines) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700556 auto trimmed_line = base::Trim(line);
557 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
558 continue;
559 }
Christopher Ferris39da84b2016-06-21 16:11:23 -0700560 size_t space_pos = trimmed_line.rfind(' ');
561 if (space_pos != std::string::npos) {
562 std::string type = trimmed_line.substr(space_pos + 1);
563 if (type != "32" && type != "64") {
564 if (error_msg) *error_msg = "Malformed line: " + line;
565 return false;
566 }
567#if defined(__LP64__)
568 // Skip 32 bit public library.
569 if (type == "32") {
570 continue;
571 }
572#else
573 // Skip 64 bit public library.
574 if (type == "64") {
575 continue;
576 }
577#endif
578 trimmed_line.resize(space_pos);
579 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700580
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900581 if (check_soname(trimmed_line, error_msg)) {
582 sonames->push_back(trimmed_line);
583 } else {
584 return false;
585 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700586 }
587
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700588 return true;
Dimitry Ivanovd68c8e92016-02-10 14:09:22 -0800589 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800590
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800591 bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
592 // Ask native bride if this apps library path should be handled by it
593 bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
594
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700595 // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
596 // code is one example) unknown to linker in which case linker uses anonymous
597 // namespace. The second argument specifies the search path for the anonymous
598 // namespace which is the library_path of the classloader.
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700599 initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800600 is_native_bridge ? nullptr : library_path);
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700601 if (!initialized_) {
602 *error_msg = dlerror();
603 return false;
604 }
605
606 // and now initialize native bridge namespaces if necessary.
607 if (NativeBridgeInitialized()) {
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700608 initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800609 is_native_bridge ? library_path : nullptr);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800610 if (!initialized_) {
611 *error_msg = NativeBridgeGetError();
612 }
613 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800614
615 return initialized_;
616 }
617
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700618 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
619 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
620 jmethodID get_parent = env->GetMethodID(class_loader_class,
621 "getParent",
622 "()Ljava/lang/ClassLoader;");
623
624 return env->CallObjectMethod(class_loader, get_parent);
625 }
626
Victor Khimenko1443ec42018-07-09 17:01:22 +0200627 NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700628 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
629
630 while (parent_class_loader != nullptr) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200631 NativeLoaderNamespace* ns;
632 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
633 return ns;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700634 }
635
636 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
637 }
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800638
Victor Khimenko1443ec42018-07-09 17:01:22 +0200639 return nullptr;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700640 }
641
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800642 bool initialized_;
Victor Khimenko1443ec42018-07-09 17:01:22 +0200643 std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700644 std::string system_public_libraries_;
645 std::string vendor_public_libraries_;
Jiyong Parke0319942018-01-15 21:14:53 +0900646 std::string oem_public_libraries_;
Inseob Kim67cb0562018-05-04 11:39:12 +0900647 std::string product_public_libraries_;
Jiyong Parka07f3052017-08-22 10:26:10 +0900648 std::string system_llndk_libraries_;
649 std::string system_vndksp_libraries_;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800650
651 DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
652};
653
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800654static std::mutex g_namespaces_mutex;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800655static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
656#endif
657
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700658void InitializeNativeLoader() {
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800659#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800660 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700661 g_namespaces->Initialize();
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800662#endif
663}
664
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700665void ResetNativeLoader() {
666#if defined(__ANDROID__)
667 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
668 g_namespaces->Reset();
669#endif
670}
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800671
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800672jstring CreateClassLoaderNamespace(JNIEnv* env,
673 int32_t target_sdk_version,
674 jobject class_loader,
675 bool is_shared,
Jiyong Parka07f3052017-08-22 10:26:10 +0900676 bool is_for_vendor,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800677 jstring library_path,
678 jstring permitted_path) {
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800679#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800680 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800681
682 std::string error_msg;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800683 bool success = g_namespaces->Create(env,
Dimitry Ivanov9e253ce2017-05-08 22:24:24 -0700684 target_sdk_version,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800685 class_loader,
686 is_shared,
Jiyong Parka07f3052017-08-22 10:26:10 +0900687 is_for_vendor,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800688 library_path,
689 permitted_path,
Victor Khimenko1443ec42018-07-09 17:01:22 +0200690 &error_msg) != nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800691 if (!success) {
692 return env->NewStringUTF(error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800693 }
694#else
Jiyong Parka07f3052017-08-22 10:26:10 +0900695 UNUSED(env, target_sdk_version, class_loader, is_shared, is_for_vendor,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800696 library_path, permitted_path);
697#endif
698 return nullptr;
699}
700
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000701#if defined(__ANDROID__)
702static android_namespace_t* FindExportedNamespace(const char* caller_location) {
703 std::string location = caller_location;
704 // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
705 // /apex/com.android...modulename/...
706 //
707 // And we extract from it 'modulename', which is the name of the linker namespace.
708 if (android::base::StartsWith(location, kApexPath)) {
709 size_t slash_index = location.find_first_of('/', strlen(kApexPath));
710 LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
711 "Error finding namespace of apex: no slash in path %s", caller_location);
712 size_t dot_index = location.find_last_of('.', slash_index);
713 LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
714 "Error finding namespace of apex: no dot in apex name %s", caller_location);
715 std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
716 android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
717 LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
718 "Error finding namespace of apex: no namespace called %s", name.c_str());
719 return boot_namespace;
720 }
721 return nullptr;
722}
723#endif
724
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000725void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
Nicolas Geoffray53535022019-01-18 10:05:13 +0000726 jobject class_loader, const char* caller_location, jstring library_path,
727 bool* needs_native_bridge, char** error_msg) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800728#if defined(__ANDROID__)
Dimitry Ivanov5539db02016-04-20 16:07:30 -0700729 UNUSED(target_sdk_version);
730 if (class_loader == nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800731 *needs_native_bridge = false;
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000732 if (caller_location != nullptr) {
733 android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
734 if (boot_namespace != nullptr) {
735 const android_dlextinfo dlextinfo = {
736 .flags = ANDROID_DLEXT_USE_NAMESPACE,
737 .library_namespace = boot_namespace,
738 };
739 void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
740 if (handle == nullptr) {
741 *error_msg = strdup(dlerror());
742 }
743 return handle;
744 }
745 }
Pete Bentley632f1422018-12-19 13:33:33 +0000746 void* handle = dlopen(path, RTLD_NOW);
747 if (handle == nullptr) {
Nicolas Geoffrayd06cb942019-01-16 20:20:27 +0000748 *error_msg = strdup(dlerror());
Pete Bentley632f1422018-12-19 13:33:33 +0000749 }
750 return handle;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800751 }
752
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800753 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200754 NativeLoaderNamespace* ns;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800755
Victor Khimenko1443ec42018-07-09 17:01:22 +0200756 if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800757 // This is the case where the classloader was not created by ApplicationLoaders
758 // In this case we create an isolated not-shared namespace for it.
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000759 std::string create_error_msg;
760 if ((ns = g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */,
761 false /* is_for_vendor */, library_path, nullptr,
762 &create_error_msg)) == nullptr) {
763 *error_msg = strdup(create_error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800764 return nullptr;
765 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800766 }
767
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000768 return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800769#else
Nicolas Geoffray53535022019-01-18 10:05:13 +0000770 UNUSED(env, target_sdk_version, class_loader, caller_location);
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800771
772 // Do some best effort to emulate library-path support. It will not
773 // work for dependencies.
774 //
775 // Note: null has a special meaning and must be preserved.
776 std::string c_library_path; // Empty string by default.
777 if (library_path != nullptr && path != nullptr && path[0] != '/') {
778 ScopedUtfChars library_path_utf_chars(env, library_path);
779 c_library_path = library_path_utf_chars.c_str();
780 }
781
782 std::vector<std::string> library_paths = base::Split(c_library_path, ":");
783
784 for (const std::string& lib_path : library_paths) {
785 *needs_native_bridge = false;
786 const char* path_arg;
787 std::string complete_path;
788 if (path == nullptr) {
789 // Preserve null.
790 path_arg = nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800791 } else {
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800792 complete_path = lib_path;
793 if (!complete_path.empty()) {
794 complete_path.append("/");
795 }
796 complete_path.append(path);
797 path_arg = complete_path.c_str();
798 }
799 void* handle = dlopen(path_arg, RTLD_NOW);
800 if (handle != nullptr) {
801 return handle;
802 }
803 if (NativeBridgeIsSupported(path_arg)) {
804 *needs_native_bridge = true;
805 handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
806 if (handle != nullptr) {
807 return handle;
808 }
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000809 *error_msg = strdup(NativeBridgeGetError());
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800810 } else {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000811 *error_msg = strdup(dlerror());
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800812 }
813 }
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800814 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800815#endif
816}
817
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000818bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
dimitry3150f7c2018-09-12 01:09:19 +0200819 bool success;
820 if (needs_native_bridge) {
821 success = (NativeBridgeUnloadLibrary(handle) == 0);
822 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000823 *error_msg = strdup(NativeBridgeGetError());
dimitry3150f7c2018-09-12 01:09:19 +0200824 }
825 } else {
826 success = (dlclose(handle) == 0);
827 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000828 *error_msg = strdup(dlerror());
dimitry3150f7c2018-09-12 01:09:19 +0200829 }
830 }
831
832 return success;
Dimitry Ivanov09a516b2016-05-03 14:55:25 -0700833}
834
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000835void NativeLoaderFreeErrorMessage(char* msg) {
836 // The error messages get allocated through strdup, so we must call free on them.
837 free(msg);
838}
839
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800840#if defined(__ANDROID__)
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000841void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
842 bool* needs_native_bridge, char** error_msg) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200843 if (ns->is_android_namespace()) {
844 android_dlextinfo extinfo;
845 extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
846 extinfo.library_namespace = ns->get_android_ns();
847
848 void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
849 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000850 *error_msg = strdup(dlerror());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200851 }
852 *needs_native_bridge = false;
853 return handle;
854 } else {
855 void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
856 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000857 *error_msg = strdup(NativeBridgeGetError());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200858 }
859 *needs_native_bridge = true;
860 return handle;
861 }
862}
863
Dimitry Ivanov800083d2016-11-01 14:17:00 -0700864// native_bridge_namespaces are not supported for callers of this function.
865// This function will return nullptr in the case when application is running
866// on native bridge.
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800867android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800868 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200869 NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
870 if (ns != nullptr) {
871 return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800872 }
873
874 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800875}
Victor Khimenko1443ec42018-07-09 17:01:22 +0200876NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
877 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
878 return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
879}
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800880#endif
881
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800882}; // android namespace