blob: 09998f027be4ae3f427ecd8d097f25d898a50c4f [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 Salyzynff2dcd92016-09-28 15:54:45 -070024#include "cutils/properties.h"
Mark Salyzyn30f991f2017-01-10 13:19:54 -080025#include "log/log.h"
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080026#endif
Jiyong Parkd1006fe2017-11-08 18:44:09 +090027#include <dirent.h>
28#include <sys/types.h>
Zhenhua WANGf2804e52016-05-30 11:16:08 +080029#include "nativebridge/native_bridge.h"
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080030
31#include <algorithm>
Victor Khimenko1443ec42018-07-09 17:01:22 +020032#include <list>
Jiyong Parkd1006fe2017-11-08 18:44:09 +090033#include <memory>
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080034#include <mutex>
Jiyong Parkd1006fe2017-11-08 18:44:09 +090035#include <string>
36#include <vector>
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080037
Mark Salyzynff2dcd92016-09-28 15:54:45 -070038#include <android-base/file.h>
39#include <android-base/macros.h>
40#include <android-base/strings.h>
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080041
Justin Yun4a1d1102017-11-27 17:04:14 +090042#ifdef __BIONIC__
43#include <android-base/properties.h>
44#endif
45
Zhenhua WANGf2804e52016-05-30 11:16:08 +080046#define CHECK(predicate) LOG_ALWAYS_FATAL_IF(!(predicate),\
47 "%s:%d: %s CHECK '" #predicate "' failed.",\
48 __FILE__, __LINE__, __FUNCTION__)
49
Inseob Kim67cb0562018-05-04 11:39:12 +090050using namespace std::string_literals;
51
Dimitry Ivanovac1b1912015-12-01 13:56:44 -080052namespace android {
53
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -070054#if defined(__ANDROID__)
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +000055struct NativeLoaderNamespace {
Zhenhua WANGf2804e52016-05-30 11:16:08 +080056 public:
57 NativeLoaderNamespace()
58 : android_ns_(nullptr), native_bridge_ns_(nullptr) { }
59
60 explicit NativeLoaderNamespace(android_namespace_t* ns)
61 : android_ns_(ns), native_bridge_ns_(nullptr) { }
62
63 explicit NativeLoaderNamespace(native_bridge_namespace_t* ns)
64 : android_ns_(nullptr), native_bridge_ns_(ns) { }
65
66 NativeLoaderNamespace(NativeLoaderNamespace&& that) = default;
67 NativeLoaderNamespace(const NativeLoaderNamespace& that) = default;
68
69 NativeLoaderNamespace& operator=(const NativeLoaderNamespace& that) = default;
70
71 android_namespace_t* get_android_ns() const {
72 CHECK(native_bridge_ns_ == nullptr);
73 return android_ns_;
74 }
75
76 native_bridge_namespace_t* get_native_bridge_ns() const {
77 CHECK(android_ns_ == nullptr);
78 return native_bridge_ns_;
79 }
80
81 bool is_android_namespace() const {
82 return native_bridge_ns_ == nullptr;
83 }
84
85 private:
86 // Only one of them can be not null
87 android_namespace_t* android_ns_;
88 native_bridge_namespace_t* native_bridge_ns_;
89};
90
Jiyong Parkd1006fe2017-11-08 18:44:09 +090091static constexpr const char kPublicNativeLibrariesSystemConfigPathFromRoot[] =
92 "/etc/public.libraries.txt";
93static constexpr const char kPublicNativeLibrariesExtensionConfigPrefix[] = "public.libraries-";
94static constexpr const size_t kPublicNativeLibrariesExtensionConfigPrefixLen =
95 sizeof(kPublicNativeLibrariesExtensionConfigPrefix) - 1;
96static constexpr const char kPublicNativeLibrariesExtensionConfigSuffix[] = ".txt";
97static constexpr const size_t kPublicNativeLibrariesExtensionConfigSuffixLen =
98 sizeof(kPublicNativeLibrariesExtensionConfigSuffix) - 1;
99static constexpr const char kPublicNativeLibrariesVendorConfig[] =
100 "/vendor/etc/public.libraries.txt";
101static constexpr const char kLlndkNativeLibrariesSystemConfigPathFromRoot[] =
102 "/etc/llndk.libraries.txt";
103static constexpr const char kVndkspNativeLibrariesSystemConfigPathFromRoot[] =
104 "/etc/vndksp.libraries.txt";
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800105
Victor Chang7a20a902019-01-28 18:43:24 +0000106static const std::vector<const std::string> kRuntimePublicLibraries = {
107 "libicuuc.so",
108 "libicui18n.so",
109};
110
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700111// The device may be configured to have the vendor libraries loaded to a separate namespace.
112// For historical reasons this namespace was named sphal but effectively it is intended
113// to use to load vendor libraries to separate namespace with controlled interface between
114// vendor and system namespaces.
115static constexpr const char* kVendorNamespaceName = "sphal";
116
Jiyong Parka07f3052017-08-22 10:26:10 +0900117static constexpr const char* kVndkNamespaceName = "vndk";
118
Victor Chang7a20a902019-01-28 18:43:24 +0000119static constexpr const char* kRuntimeNamespaceName = "runtime";
120
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000121// classloader-namespace is a linker namespace that is created for the loaded
122// app. To be specific, it is created for the app classloader. When
123// System.load() is called from a Java class that is loaded from the
124// classloader, the classloader-namespace namespace associated with that
125// classloader is selected for dlopen. The namespace is configured so that its
126// search path is set to the app-local JNI directory and it is linked to the
127// default namespace with the names of libs listed in the public.libraries.txt.
128// This way an app can only load its own JNI libraries along with the public libs.
Jiyong Parka07f3052017-08-22 10:26:10 +0900129static constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000130// Same thing for vendor APKs.
Jiyong Parka07f3052017-08-22 10:26:10 +0900131static constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
132
Dimitry Ivanovf334cbf2016-05-10 10:39:48 -0700133// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
134// System.load() with an absolute path which is outside of the classloader library search path.
135// This list includes all directories app is allowed to access this way.
136static constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
137
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000138static constexpr const char* kApexPath = "/apex/";
139
Victor Changf70a2fe2019-02-01 20:01:27 +0000140#if defined(__LP64__)
141static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib64";
142#else
143static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib";
144#endif
145
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700146static bool is_debuggable() {
147 char debuggable[PROP_VALUE_MAX];
148 property_get("ro.debuggable", debuggable, "0");
149 return std::string(debuggable) == "1";
150}
151
Justin Yun4a1d1102017-11-27 17:04:14 +0900152static std::string vndk_version_str() {
153#ifdef __BIONIC__
154 std::string version = android::base::GetProperty("ro.vndk.version", "");
155 if (version != "" && version != "current") {
156 return "." + version;
157 }
158#endif
159 return "";
160}
161
162static void insert_vndk_version_str(std::string* file_name) {
163 CHECK(file_name != nullptr);
164 size_t insert_pos = file_name->find_last_of(".");
165 if (insert_pos == std::string::npos) {
166 insert_pos = file_name->length();
167 }
168 file_name->insert(insert_pos, vndk_version_str());
169}
170
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900171static const std::function<bool(const std::string&, std::string*)> always_true =
172 [](const std::string&, std::string*) { return true; };
173
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800174class LibraryNamespaces {
175 public:
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800176 LibraryNamespaces() : initialized_(false) { }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800177
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000178 NativeLoaderNamespace* Create(JNIEnv* env, uint32_t target_sdk_version, jobject class_loader,
179 bool is_shared, bool is_for_vendor, jstring java_library_path,
180 jstring java_permitted_path, std::string* error_msg) {
Dimitry Ivanovcf9892b2016-05-09 10:55:50 -0700181 std::string library_path; // empty string by default.
182
183 if (java_library_path != nullptr) {
184 ScopedUtfChars library_path_utf_chars(env, java_library_path);
185 library_path = library_path_utf_chars.c_str();
186 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800187
Dimitry Ivanovf334cbf2016-05-10 10:39:48 -0700188 // (http://b/27588281) This is a workaround for apps using custom
189 // classloaders and calling System.load() with an absolute path which
190 // is outside of the classloader library search path.
191 //
192 // This part effectively allows such a classloader to access anything
193 // under /data and /mnt/expand
194 std::string permitted_path = kWhitelistedDirectories;
195
Dimitry Ivanov0d6e5942015-12-08 11:16:56 -0800196 if (java_permitted_path != nullptr) {
197 ScopedUtfChars path(env, java_permitted_path);
Dimitry Ivanovd0b15312016-05-10 16:21:25 -0700198 if (path.c_str() != nullptr && path.size() > 0) {
199 permitted_path = permitted_path + ":" + path.c_str();
200 }
Dimitry Ivanov0d6e5942015-12-08 11:16:56 -0800201 }
202
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800203 if (!initialized_ && !InitPublicNamespace(library_path.c_str(), error_msg)) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200204 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800205 }
206
Victor Khimenko1443ec42018-07-09 17:01:22 +0200207 bool found = FindNamespaceByClassLoader(env, class_loader);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800208
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800209 LOG_ALWAYS_FATAL_IF(found,
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700210 "There is already a namespace associated with this classloader");
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800211
Dimitry Ivanovd2a62202015-12-15 11:06:57 -0800212 uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
213 if (is_shared) {
214 namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
215 }
216
Dimitry Ivanov9e253ce2017-05-08 22:24:24 -0700217 if (target_sdk_version < 24) {
218 namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
219 }
220
Victor Khimenko1443ec42018-07-09 17:01:22 +0200221 NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700222
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800223 bool is_native_bridge = false;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800224
Victor Khimenko1443ec42018-07-09 17:01:22 +0200225 if (parent_ns != nullptr) {
226 is_native_bridge = !parent_ns->is_android_namespace();
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800227 } else if (!library_path.empty()) {
228 is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800229 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800230
Jiyong Parka07f3052017-08-22 10:26:10 +0900231 std::string system_exposed_libraries = system_public_libraries_;
232 const char* namespace_name = kClassloaderNamespaceName;
233 android_namespace_t* vndk_ns = nullptr;
234 if (is_for_vendor && !is_shared) {
235 LOG_FATAL_IF(is_native_bridge, "Unbundled vendor apk must not use translated architecture");
236
237 // For vendor apks, give access to the vendor lib even though
238 // they are treated as unbundled; the libs and apks are still bundled
239 // together in the vendor partition.
240#if defined(__LP64__)
241 std::string vendor_lib_path = "/vendor/lib64";
242#else
243 std::string vendor_lib_path = "/vendor/lib";
244#endif
245 library_path = library_path + ":" + vendor_lib_path.c_str();
246 permitted_path = permitted_path + ":" + vendor_lib_path.c_str();
247
248 // Also give access to LLNDK libraries since they are available to vendors
249 system_exposed_libraries = system_exposed_libraries + ":" + system_llndk_libraries_.c_str();
250
251 // Give access to VNDK-SP libraries from the 'vndk' namespace.
252 vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
253 LOG_ALWAYS_FATAL_IF(vndk_ns == nullptr,
254 "Cannot find \"%s\" namespace for vendor apks", kVndkNamespaceName);
255
256 // Different name is useful for debugging
257 namespace_name = kVendorClassloaderNamespaceName;
258 ALOGD("classloader namespace configured for unbundled vendor apk. library_path=%s", library_path.c_str());
Inseob Kim67cb0562018-05-04 11:39:12 +0900259 } else {
260 // oem and product public libraries are NOT available to vendor apks, otherwise it
Jiyong Parke0319942018-01-15 21:14:53 +0900261 // would be system->vendor violation.
Inseob Kim67cb0562018-05-04 11:39:12 +0900262 if (!oem_public_libraries_.empty()) {
263 system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries_;
264 }
265 if (!product_public_libraries_.empty()) {
266 system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries_;
267 }
Jiyong Parka07f3052017-08-22 10:26:10 +0900268 }
269
Victor Chang7a20a902019-01-28 18:43:24 +0000270 std::string runtime_exposed_libraries = base::Join(kRuntimePublicLibraries, ":");
271
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800272 NativeLoaderNamespace native_loader_ns;
273 if (!is_native_bridge) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200274 android_namespace_t* android_parent_ns =
275 parent_ns == nullptr ? nullptr : parent_ns->get_android_ns();
Jiyong Parka07f3052017-08-22 10:26:10 +0900276 android_namespace_t* ns = android_create_namespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800277 nullptr,
278 library_path.c_str(),
279 namespace_type,
280 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200281 android_parent_ns);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800282 if (ns == nullptr) {
283 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200284 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800285 }
286
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700287 // Note that when vendor_ns is not configured this function will return nullptr
288 // and it will result in linking vendor_public_libraries_ to the default namespace
289 // which is expected behavior in this case.
290 android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
291
Victor Chang7a20a902019-01-28 18:43:24 +0000292 android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
293
Jiyong Parka07f3052017-08-22 10:26:10 +0900294 if (!android_link_namespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800295 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200296 return nullptr;
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800297 }
298
Victor Chang7a20a902019-01-28 18:43:24 +0000299 // Runtime apex does not exist in host, and under certain build conditions.
300 if (runtime_ns != nullptr) {
301 if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
302 *error_msg = dlerror();
303 return nullptr;
304 }
305 }
306
Jiyong Parka07f3052017-08-22 10:26:10 +0900307 if (vndk_ns != nullptr && !system_vndksp_libraries_.empty()) {
308 // vendor apks are allowed to use VNDK-SP libraries.
309 if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries_.c_str())) {
310 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200311 return nullptr;
Jiyong Parka07f3052017-08-22 10:26:10 +0900312 }
313 }
314
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700315 if (!vendor_public_libraries_.empty()) {
316 if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
317 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200318 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700319 }
320 }
321
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800322 native_loader_ns = NativeLoaderNamespace(ns);
323 } else {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200324 native_bridge_namespace_t* native_bridge_parent_namespace =
325 parent_ns == nullptr ? nullptr : parent_ns->get_native_bridge_ns();
Jiyong Parka07f3052017-08-22 10:26:10 +0900326 native_bridge_namespace_t* ns = NativeBridgeCreateNamespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800327 nullptr,
328 library_path.c_str(),
329 namespace_type,
330 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200331 native_bridge_parent_namespace);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800332 if (ns == nullptr) {
333 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200334 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800335 }
336
dimitryd2ace382019-02-04 15:06:43 +0100337 native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
Victor Chang7a20a902019-01-28 18:43:24 +0000338 native_bridge_namespace_t* runtime_ns =
339 NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700340
Jiyong Parka07f3052017-08-22 10:26:10 +0900341 if (!NativeBridgeLinkNamespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800342 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200343 return nullptr;
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800344 }
345
Victor Chang7a20a902019-01-28 18:43:24 +0000346 // Runtime apex does not exist in host, and under certain build conditions.
347 if (runtime_ns != nullptr) {
348 if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
349 *error_msg = NativeBridgeGetError();
350 return nullptr;
351 }
352 }
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700353 if (!vendor_public_libraries_.empty()) {
354 if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
355 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200356 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700357 }
358 }
359
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800360 native_loader_ns = NativeLoaderNamespace(ns);
361 }
362
363 namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
364
Victor Khimenko1443ec42018-07-09 17:01:22 +0200365 return &(namespaces_.back().second);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800366 }
367
Victor Khimenko1443ec42018-07-09 17:01:22 +0200368 NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800369 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800370 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800371 return env->IsSameObject(value.first, class_loader);
372 });
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800373 if (it != namespaces_.end()) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200374 return &it->second;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800375 }
376
Victor Khimenko1443ec42018-07-09 17:01:22 +0200377 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800378 }
379
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700380 void Initialize() {
Dimitry Ivanov80ddb8f2016-05-09 18:12:00 -0700381 // Once public namespace is initialized there is no
382 // point in running this code - it will have no effect
383 // on the current list of public libraries.
384 if (initialized_) {
385 return;
386 }
387
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700388 std::vector<std::string> sonames;
Dimitry Ivanov0b5651e2016-04-21 16:42:48 -0700389 const char* android_root_env = getenv("ANDROID_ROOT");
390 std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
391 std::string public_native_libraries_system_config =
392 root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
Jiyong Parka07f3052017-08-22 10:26:10 +0900393 std::string llndk_native_libraries_system_config =
394 root_dir + kLlndkNativeLibrariesSystemConfigPathFromRoot;
395 std::string vndksp_native_libraries_system_config =
396 root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700397
Inseob Kim67cb0562018-05-04 11:39:12 +0900398 std::string product_public_native_libraries_dir = "/product/etc";
399
Christopher Ferris39da84b2016-06-21 16:11:23 -0700400 std::string error_msg;
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900401 LOG_ALWAYS_FATAL_IF(
402 !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
403 "Error reading public native library list from \"%s\": %s",
404 public_native_libraries_system_config.c_str(), error_msg.c_str());
405
Jiyong Parke0319942018-01-15 21:14:53 +0900406 // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
407 // variable to add libraries to the list. This is intended for platform tests only.
408 if (is_debuggable()) {
409 const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
410 if (additional_libs != nullptr && additional_libs[0] != '\0') {
411 std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
412 std::copy(additional_libs_vector.begin(), additional_libs_vector.end(),
413 std::back_inserter(sonames));
414 }
415 }
416
Victor Changf70a2fe2019-02-01 20:01:27 +0000417 // Remove the public libs in the runtime namespace.
418 // These libs are listed in public.android.txt, but we don't want the rest of android
419 // in default namespace to dlopen the libs.
420 // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
421 // Unfortunately, it does not have stable C symbols, and default namespace should only use
422 // stable symbols in libandroidicu.so. http://b/120786417
423 removePublicLibsIfExistsInRuntimeApex(sonames);
424
Jiyong Parke0319942018-01-15 21:14:53 +0900425 // android_init_namespaces() expects all the public libraries
426 // to be loaded so that they can be found by soname alone.
427 //
428 // TODO(dimitry): this is a bit misleading since we do not know
429 // if the vendor public library is going to be opened from /vendor/lib
Inseob Kim67cb0562018-05-04 11:39:12 +0900430 // we might as well end up loading them from /system/lib or /product/lib
Jiyong Parke0319942018-01-15 21:14:53 +0900431 // For now we rely on CTS test to catch things like this but
432 // it should probably be addressed in the future.
433 for (const auto& soname : sonames) {
434 LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
435 "Error preloading public library %s: %s", soname.c_str(), dlerror());
436 }
437
438 system_public_libraries_ = base::Join(sonames, ':');
439
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900440 // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
441 // system libs that are exposed to apps. The libs in the txt files must be
442 // named as lib<name>.<companyname>.so.
Jiyong Parke0319942018-01-15 21:14:53 +0900443 sonames.clear();
Inseob Kim67cb0562018-05-04 11:39:12 +0900444 ReadExtensionLibraries(base::Dirname(public_native_libraries_system_config).c_str(), &sonames);
Jiyong Parke0319942018-01-15 21:14:53 +0900445 oem_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700446
Inseob Kim67cb0562018-05-04 11:39:12 +0900447 // read /product/etc/public.libraries-<companyname>.txt which contain partner defined
448 // product libs that are exposed to apps.
449 sonames.clear();
450 ReadExtensionLibraries(product_public_native_libraries_dir.c_str(), &sonames);
451 product_public_libraries_ = base::Join(sonames, ':');
452
Justin Yun4a1d1102017-11-27 17:04:14 +0900453 // Insert VNDK version to llndk and vndksp config file names.
454 insert_vndk_version_str(&llndk_native_libraries_system_config);
455 insert_vndk_version_str(&vndksp_native_libraries_system_config);
456
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700457 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900458 ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900459 system_llndk_libraries_ = base::Join(sonames, ':');
460
461 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900462 ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900463 system_vndksp_libraries_ = base::Join(sonames, ':');
464
465 sonames.clear();
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700466 // This file is optional, quietly ignore if the file does not exist.
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900467 ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700468
469 vendor_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700470 }
471
Inseob Kim67cb0562018-05-04 11:39:12 +0900472 void Reset() { namespaces_.clear(); }
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700473
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700474 private:
Inseob Kim67cb0562018-05-04 11:39:12 +0900475 void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
476 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
477 if (dir != nullptr) {
478 // Failing to opening the dir is not an error, which can happen in
479 // webview_zygote.
480 while (struct dirent* ent = readdir(dir.get())) {
481 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
482 continue;
483 }
484 const std::string filename(ent->d_name);
485 if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
486 android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
487 const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
488 const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
489 const std::string company_name = filename.substr(start, end - start);
490 const std::string config_file_path = dirname + "/"s + filename;
491 LOG_ALWAYS_FATAL_IF(
492 company_name.empty(),
493 "Error extracting company name from public native library list file path \"%s\"",
494 config_file_path.c_str());
495
496 std::string error_msg;
497
498 LOG_ALWAYS_FATAL_IF(
499 !ReadConfig(
500 config_file_path, sonames,
501 [&company_name](const std::string& soname, std::string* error_msg) {
502 if (android::base::StartsWith(soname, "lib") &&
503 android::base::EndsWith(soname, "." + company_name + ".so")) {
504 return true;
505 } else {
506 *error_msg = "Library name \"" + soname +
507 "\" does not end with the company name: " + company_name + ".";
508 return false;
509 }
510 },
511 &error_msg),
512 "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
513 error_msg.c_str());
514 }
515 }
516 }
517 }
518
Victor Changf70a2fe2019-02-01 20:01:27 +0000519 /**
520 * Remove the public libs in runtime namespace
521 */
522 void removePublicLibsIfExistsInRuntimeApex(std::vector<std::string>& sonames) {
523 for (const std::string& lib_name : kRuntimePublicLibraries) {
524 std::string path(kRuntimeApexLibPath);
525 path.append("/").append(lib_name);
526
527 struct stat s;
528 // Do nothing if the path in /apex does not exist.
529 // Runtime APEX must be mounted since libnativeloader is in the same APEX
530 if (stat(path.c_str(), &s) != 0) {
531 continue;
532 }
533
534 auto it = std::find(sonames.begin(), sonames.end(), lib_name);
535 if (it != sonames.end()) {
536 sonames.erase(it);
537 }
538 }
539 }
Inseob Kim67cb0562018-05-04 11:39:12 +0900540
Christopher Ferris39da84b2016-06-21 16:11:23 -0700541 bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900542 const std::function<bool(const std::string& /* soname */,
543 std::string* /* error_msg */)>& check_soname,
Christopher Ferris39da84b2016-06-21 16:11:23 -0700544 std::string* error_msg = nullptr) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700545 // Read list of public native libraries from the config file.
546 std::string file_content;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700547 if(!base::ReadFileToString(configFile, &file_content)) {
Christopher Ferris39da84b2016-06-21 16:11:23 -0700548 if (error_msg) *error_msg = strerror(errno);
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700549 return false;
550 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700551
552 std::vector<std::string> lines = base::Split(file_content, "\n");
553
Christopher Ferris39da84b2016-06-21 16:11:23 -0700554 for (auto& line : lines) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700555 auto trimmed_line = base::Trim(line);
556 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
557 continue;
558 }
Christopher Ferris39da84b2016-06-21 16:11:23 -0700559 size_t space_pos = trimmed_line.rfind(' ');
560 if (space_pos != std::string::npos) {
561 std::string type = trimmed_line.substr(space_pos + 1);
562 if (type != "32" && type != "64") {
563 if (error_msg) *error_msg = "Malformed line: " + line;
564 return false;
565 }
566#if defined(__LP64__)
567 // Skip 32 bit public library.
568 if (type == "32") {
569 continue;
570 }
571#else
572 // Skip 64 bit public library.
573 if (type == "64") {
574 continue;
575 }
576#endif
577 trimmed_line.resize(space_pos);
578 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700579
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900580 if (check_soname(trimmed_line, error_msg)) {
581 sonames->push_back(trimmed_line);
582 } else {
583 return false;
584 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700585 }
586
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700587 return true;
Dimitry Ivanovd68c8e92016-02-10 14:09:22 -0800588 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800589
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800590 bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
591 // Ask native bride if this apps library path should be handled by it
592 bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
593
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700594 // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
595 // code is one example) unknown to linker in which case linker uses anonymous
596 // namespace. The second argument specifies the search path for the anonymous
597 // namespace which is the library_path of the classloader.
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700598 initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800599 is_native_bridge ? nullptr : library_path);
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700600 if (!initialized_) {
601 *error_msg = dlerror();
602 return false;
603 }
604
605 // and now initialize native bridge namespaces if necessary.
606 if (NativeBridgeInitialized()) {
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700607 initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800608 is_native_bridge ? library_path : nullptr);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800609 if (!initialized_) {
610 *error_msg = NativeBridgeGetError();
611 }
612 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800613
614 return initialized_;
615 }
616
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700617 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
618 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
619 jmethodID get_parent = env->GetMethodID(class_loader_class,
620 "getParent",
621 "()Ljava/lang/ClassLoader;");
622
623 return env->CallObjectMethod(class_loader, get_parent);
624 }
625
Victor Khimenko1443ec42018-07-09 17:01:22 +0200626 NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700627 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
628
629 while (parent_class_loader != nullptr) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200630 NativeLoaderNamespace* ns;
631 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
632 return ns;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700633 }
634
635 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
636 }
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800637
Victor Khimenko1443ec42018-07-09 17:01:22 +0200638 return nullptr;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700639 }
640
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800641 bool initialized_;
Victor Khimenko1443ec42018-07-09 17:01:22 +0200642 std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700643 std::string system_public_libraries_;
644 std::string vendor_public_libraries_;
Jiyong Parke0319942018-01-15 21:14:53 +0900645 std::string oem_public_libraries_;
Inseob Kim67cb0562018-05-04 11:39:12 +0900646 std::string product_public_libraries_;
Jiyong Parka07f3052017-08-22 10:26:10 +0900647 std::string system_llndk_libraries_;
648 std::string system_vndksp_libraries_;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800649
650 DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
651};
652
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800653static std::mutex g_namespaces_mutex;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800654static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
655#endif
656
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700657void InitializeNativeLoader() {
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800658#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800659 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700660 g_namespaces->Initialize();
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800661#endif
662}
663
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700664void ResetNativeLoader() {
665#if defined(__ANDROID__)
666 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
667 g_namespaces->Reset();
668#endif
669}
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800670
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800671jstring CreateClassLoaderNamespace(JNIEnv* env,
672 int32_t target_sdk_version,
673 jobject class_loader,
674 bool is_shared,
Jiyong Parka07f3052017-08-22 10:26:10 +0900675 bool is_for_vendor,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800676 jstring library_path,
677 jstring permitted_path) {
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800678#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800679 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800680
681 std::string error_msg;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800682 bool success = g_namespaces->Create(env,
Dimitry Ivanov9e253ce2017-05-08 22:24:24 -0700683 target_sdk_version,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800684 class_loader,
685 is_shared,
Jiyong Parka07f3052017-08-22 10:26:10 +0900686 is_for_vendor,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800687 library_path,
688 permitted_path,
Victor Khimenko1443ec42018-07-09 17:01:22 +0200689 &error_msg) != nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800690 if (!success) {
691 return env->NewStringUTF(error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800692 }
693#else
Jiyong Parka07f3052017-08-22 10:26:10 +0900694 UNUSED(env, target_sdk_version, class_loader, is_shared, is_for_vendor,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800695 library_path, permitted_path);
696#endif
697 return nullptr;
698}
699
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000700#if defined(__ANDROID__)
701static android_namespace_t* FindExportedNamespace(const char* caller_location) {
702 std::string location = caller_location;
703 // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
704 // /apex/com.android...modulename/...
705 //
706 // And we extract from it 'modulename', which is the name of the linker namespace.
707 if (android::base::StartsWith(location, kApexPath)) {
708 size_t slash_index = location.find_first_of('/', strlen(kApexPath));
709 LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
710 "Error finding namespace of apex: no slash in path %s", caller_location);
711 size_t dot_index = location.find_last_of('.', slash_index);
712 LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
713 "Error finding namespace of apex: no dot in apex name %s", caller_location);
714 std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
715 android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
716 LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
717 "Error finding namespace of apex: no namespace called %s", name.c_str());
718 return boot_namespace;
719 }
720 return nullptr;
721}
722#endif
723
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000724void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
Nicolas Geoffray53535022019-01-18 10:05:13 +0000725 jobject class_loader, const char* caller_location, jstring library_path,
726 bool* needs_native_bridge, char** error_msg) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800727#if defined(__ANDROID__)
Dimitry Ivanov5539db02016-04-20 16:07:30 -0700728 UNUSED(target_sdk_version);
729 if (class_loader == nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800730 *needs_native_bridge = false;
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000731 if (caller_location != nullptr) {
732 android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
733 if (boot_namespace != nullptr) {
734 const android_dlextinfo dlextinfo = {
735 .flags = ANDROID_DLEXT_USE_NAMESPACE,
736 .library_namespace = boot_namespace,
737 };
738 void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
739 if (handle == nullptr) {
740 *error_msg = strdup(dlerror());
741 }
742 return handle;
743 }
744 }
Pete Bentley632f1422018-12-19 13:33:33 +0000745 void* handle = dlopen(path, RTLD_NOW);
746 if (handle == nullptr) {
Nicolas Geoffrayd06cb942019-01-16 20:20:27 +0000747 *error_msg = strdup(dlerror());
Pete Bentley632f1422018-12-19 13:33:33 +0000748 }
749 return handle;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800750 }
751
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800752 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200753 NativeLoaderNamespace* ns;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800754
Victor Khimenko1443ec42018-07-09 17:01:22 +0200755 if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800756 // This is the case where the classloader was not created by ApplicationLoaders
757 // In this case we create an isolated not-shared namespace for it.
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000758 std::string create_error_msg;
759 if ((ns = g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */,
760 false /* is_for_vendor */, library_path, nullptr,
761 &create_error_msg)) == nullptr) {
762 *error_msg = strdup(create_error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800763 return nullptr;
764 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800765 }
766
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000767 return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800768#else
Nicolas Geoffray53535022019-01-18 10:05:13 +0000769 UNUSED(env, target_sdk_version, class_loader, caller_location);
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800770
771 // Do some best effort to emulate library-path support. It will not
772 // work for dependencies.
773 //
774 // Note: null has a special meaning and must be preserved.
775 std::string c_library_path; // Empty string by default.
776 if (library_path != nullptr && path != nullptr && path[0] != '/') {
777 ScopedUtfChars library_path_utf_chars(env, library_path);
778 c_library_path = library_path_utf_chars.c_str();
779 }
780
781 std::vector<std::string> library_paths = base::Split(c_library_path, ":");
782
783 for (const std::string& lib_path : library_paths) {
784 *needs_native_bridge = false;
785 const char* path_arg;
786 std::string complete_path;
787 if (path == nullptr) {
788 // Preserve null.
789 path_arg = nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800790 } else {
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800791 complete_path = lib_path;
792 if (!complete_path.empty()) {
793 complete_path.append("/");
794 }
795 complete_path.append(path);
796 path_arg = complete_path.c_str();
797 }
798 void* handle = dlopen(path_arg, RTLD_NOW);
799 if (handle != nullptr) {
800 return handle;
801 }
802 if (NativeBridgeIsSupported(path_arg)) {
803 *needs_native_bridge = true;
804 handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
805 if (handle != nullptr) {
806 return handle;
807 }
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000808 *error_msg = strdup(NativeBridgeGetError());
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800809 } else {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000810 *error_msg = strdup(dlerror());
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800811 }
812 }
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800813 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800814#endif
815}
816
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000817bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
dimitry3150f7c2018-09-12 01:09:19 +0200818 bool success;
819 if (needs_native_bridge) {
820 success = (NativeBridgeUnloadLibrary(handle) == 0);
821 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000822 *error_msg = strdup(NativeBridgeGetError());
dimitry3150f7c2018-09-12 01:09:19 +0200823 }
824 } else {
825 success = (dlclose(handle) == 0);
826 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000827 *error_msg = strdup(dlerror());
dimitry3150f7c2018-09-12 01:09:19 +0200828 }
829 }
830
831 return success;
Dimitry Ivanov09a516b2016-05-03 14:55:25 -0700832}
833
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000834void NativeLoaderFreeErrorMessage(char* msg) {
835 // The error messages get allocated through strdup, so we must call free on them.
836 free(msg);
837}
838
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800839#if defined(__ANDROID__)
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000840void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
841 bool* needs_native_bridge, char** error_msg) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200842 if (ns->is_android_namespace()) {
843 android_dlextinfo extinfo;
844 extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
845 extinfo.library_namespace = ns->get_android_ns();
846
847 void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
848 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000849 *error_msg = strdup(dlerror());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200850 }
851 *needs_native_bridge = false;
852 return handle;
853 } else {
854 void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
855 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000856 *error_msg = strdup(NativeBridgeGetError());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200857 }
858 *needs_native_bridge = true;
859 return handle;
860 }
861}
862
Dimitry Ivanov800083d2016-11-01 14:17:00 -0700863// native_bridge_namespaces are not supported for callers of this function.
864// This function will return nullptr in the case when application is running
865// on native bridge.
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800866android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800867 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200868 NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
869 if (ns != nullptr) {
870 return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800871 }
872
873 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800874}
Victor Khimenko1443ec42018-07-09 17:01:22 +0200875NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
876 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
877 return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
878}
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800879#endif
880
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800881}; // android namespace