blob: 043f0380fb9c95b38f41016e618237f1bca86f54 [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
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000118static constexpr const char* kDefaultNamespaceName = "default";
119static constexpr const char* kPlatformNamespaceName = "platform";
Victor Chang7a20a902019-01-28 18:43:24 +0000120static constexpr const char* kRuntimeNamespaceName = "runtime";
121
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000122// classloader-namespace is a linker namespace that is created for the loaded
123// app. To be specific, it is created for the app classloader. When
124// System.load() is called from a Java class that is loaded from the
125// classloader, the classloader-namespace namespace associated with that
126// classloader is selected for dlopen. The namespace is configured so that its
127// search path is set to the app-local JNI directory and it is linked to the
128// default namespace with the names of libs listed in the public.libraries.txt.
129// This way an app can only load its own JNI libraries along with the public libs.
Jiyong Parka07f3052017-08-22 10:26:10 +0900130static constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000131// Same thing for vendor APKs.
Jiyong Parka07f3052017-08-22 10:26:10 +0900132static constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
133
Dimitry Ivanovf334cbf2016-05-10 10:39:48 -0700134// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
135// System.load() with an absolute path which is outside of the classloader library search path.
136// This list includes all directories app is allowed to access this way.
137static constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
138
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000139static constexpr const char* kApexPath = "/apex/";
140
Victor Changf70a2fe2019-02-01 20:01:27 +0000141#if defined(__LP64__)
142static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib64";
143#else
144static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib";
145#endif
146
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700147static bool is_debuggable() {
Orion Hodson34b126b2019-02-21 17:18:44 +0000148 bool debuggable = false;
149#ifdef __BIONIC__
150 debuggable = android::base::GetBoolProperty("ro.debuggable", false);
151#endif
152 return debuggable;
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700153}
154
Justin Yun4a1d1102017-11-27 17:04:14 +0900155static std::string vndk_version_str() {
156#ifdef __BIONIC__
157 std::string version = android::base::GetProperty("ro.vndk.version", "");
158 if (version != "" && version != "current") {
159 return "." + version;
160 }
161#endif
162 return "";
163}
164
165static void insert_vndk_version_str(std::string* file_name) {
166 CHECK(file_name != nullptr);
167 size_t insert_pos = file_name->find_last_of(".");
168 if (insert_pos == std::string::npos) {
169 insert_pos = file_name->length();
170 }
171 file_name->insert(insert_pos, vndk_version_str());
172}
173
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900174static const std::function<bool(const std::string&, std::string*)> always_true =
175 [](const std::string&, std::string*) { return true; };
176
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800177class LibraryNamespaces {
178 public:
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800179 LibraryNamespaces() : initialized_(false) { }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800180
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000181 NativeLoaderNamespace* Create(JNIEnv* env, uint32_t target_sdk_version, jobject class_loader,
182 bool is_shared, bool is_for_vendor, jstring java_library_path,
183 jstring java_permitted_path, std::string* error_msg) {
Dimitry Ivanovcf9892b2016-05-09 10:55:50 -0700184 std::string library_path; // empty string by default.
185
186 if (java_library_path != nullptr) {
187 ScopedUtfChars library_path_utf_chars(env, java_library_path);
188 library_path = library_path_utf_chars.c_str();
189 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800190
Dimitry Ivanovf334cbf2016-05-10 10:39:48 -0700191 // (http://b/27588281) This is a workaround for apps using custom
192 // classloaders and calling System.load() with an absolute path which
193 // is outside of the classloader library search path.
194 //
195 // This part effectively allows such a classloader to access anything
196 // under /data and /mnt/expand
197 std::string permitted_path = kWhitelistedDirectories;
198
Dimitry Ivanov0d6e5942015-12-08 11:16:56 -0800199 if (java_permitted_path != nullptr) {
200 ScopedUtfChars path(env, java_permitted_path);
Dimitry Ivanovd0b15312016-05-10 16:21:25 -0700201 if (path.c_str() != nullptr && path.size() > 0) {
202 permitted_path = permitted_path + ":" + path.c_str();
203 }
Dimitry Ivanov0d6e5942015-12-08 11:16:56 -0800204 }
205
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800206 if (!initialized_ && !InitPublicNamespace(library_path.c_str(), error_msg)) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200207 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800208 }
209
Victor Khimenko1443ec42018-07-09 17:01:22 +0200210 bool found = FindNamespaceByClassLoader(env, class_loader);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800211
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800212 LOG_ALWAYS_FATAL_IF(found,
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700213 "There is already a namespace associated with this classloader");
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800214
Dimitry Ivanovd2a62202015-12-15 11:06:57 -0800215 uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
216 if (is_shared) {
217 namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
218 }
219
Dimitry Ivanov9e253ce2017-05-08 22:24:24 -0700220 if (target_sdk_version < 24) {
221 namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
222 }
223
Victor Khimenko1443ec42018-07-09 17:01:22 +0200224 NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700225
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800226 bool is_native_bridge = false;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800227
Victor Khimenko1443ec42018-07-09 17:01:22 +0200228 if (parent_ns != nullptr) {
229 is_native_bridge = !parent_ns->is_android_namespace();
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800230 } else if (!library_path.empty()) {
231 is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800232 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800233
Jiyong Parka07f3052017-08-22 10:26:10 +0900234 std::string system_exposed_libraries = system_public_libraries_;
235 const char* namespace_name = kClassloaderNamespaceName;
236 android_namespace_t* vndk_ns = nullptr;
237 if (is_for_vendor && !is_shared) {
238 LOG_FATAL_IF(is_native_bridge, "Unbundled vendor apk must not use translated architecture");
239
240 // For vendor apks, give access to the vendor lib even though
241 // they are treated as unbundled; the libs and apks are still bundled
242 // together in the vendor partition.
243#if defined(__LP64__)
244 std::string vendor_lib_path = "/vendor/lib64";
245#else
246 std::string vendor_lib_path = "/vendor/lib";
247#endif
248 library_path = library_path + ":" + vendor_lib_path.c_str();
249 permitted_path = permitted_path + ":" + vendor_lib_path.c_str();
250
251 // Also give access to LLNDK libraries since they are available to vendors
252 system_exposed_libraries = system_exposed_libraries + ":" + system_llndk_libraries_.c_str();
253
254 // Give access to VNDK-SP libraries from the 'vndk' namespace.
255 vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
256 LOG_ALWAYS_FATAL_IF(vndk_ns == nullptr,
257 "Cannot find \"%s\" namespace for vendor apks", kVndkNamespaceName);
258
259 // Different name is useful for debugging
260 namespace_name = kVendorClassloaderNamespaceName;
261 ALOGD("classloader namespace configured for unbundled vendor apk. library_path=%s", library_path.c_str());
Inseob Kim67cb0562018-05-04 11:39:12 +0900262 } else {
263 // oem and product public libraries are NOT available to vendor apks, otherwise it
Jiyong Parke0319942018-01-15 21:14:53 +0900264 // would be system->vendor violation.
Inseob Kim67cb0562018-05-04 11:39:12 +0900265 if (!oem_public_libraries_.empty()) {
266 system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries_;
267 }
268 if (!product_public_libraries_.empty()) {
269 system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries_;
270 }
Jiyong Parka07f3052017-08-22 10:26:10 +0900271 }
272
Victor Chang7a20a902019-01-28 18:43:24 +0000273 std::string runtime_exposed_libraries = base::Join(kRuntimePublicLibraries, ":");
274
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800275 NativeLoaderNamespace native_loader_ns;
276 if (!is_native_bridge) {
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000277 android_namespace_t* android_parent_ns;
278 if (parent_ns != nullptr) {
279 android_parent_ns = parent_ns->get_android_ns();
280 } else {
281 // Fall back to the platform namespace if no parent is found. It is
282 // called "default" for binaries in /system and "platform" for those in
283 // the Runtime APEX. Try "platform" first since "default" always exists.
284 android_parent_ns = android_get_exported_namespace(kPlatformNamespaceName);
285 if (android_parent_ns == nullptr) {
286 android_parent_ns = android_get_exported_namespace(kDefaultNamespaceName);
287 }
288 }
289
Jiyong Parka07f3052017-08-22 10:26:10 +0900290 android_namespace_t* ns = android_create_namespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800291 nullptr,
292 library_path.c_str(),
293 namespace_type,
294 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200295 android_parent_ns);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800296 if (ns == nullptr) {
297 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200298 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800299 }
300
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700301 // Note that when vendor_ns is not configured this function will return nullptr
302 // and it will result in linking vendor_public_libraries_ to the default namespace
303 // which is expected behavior in this case.
304 android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
305
Victor Chang7a20a902019-01-28 18:43:24 +0000306 android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
307
Jiyong Parka07f3052017-08-22 10:26:10 +0900308 if (!android_link_namespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800309 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200310 return nullptr;
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800311 }
312
Victor Chang7a20a902019-01-28 18:43:24 +0000313 // Runtime apex does not exist in host, and under certain build conditions.
314 if (runtime_ns != nullptr) {
315 if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
316 *error_msg = dlerror();
317 return nullptr;
318 }
319 }
320
Jiyong Parka07f3052017-08-22 10:26:10 +0900321 if (vndk_ns != nullptr && !system_vndksp_libraries_.empty()) {
322 // vendor apks are allowed to use VNDK-SP libraries.
323 if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries_.c_str())) {
324 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200325 return nullptr;
Jiyong Parka07f3052017-08-22 10:26:10 +0900326 }
327 }
328
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700329 if (!vendor_public_libraries_.empty()) {
330 if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
331 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200332 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700333 }
334 }
335
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800336 native_loader_ns = NativeLoaderNamespace(ns);
337 } else {
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000338 native_bridge_namespace_t* native_bridge_parent_namespace;
339 if (parent_ns != nullptr) {
340 native_bridge_parent_namespace = parent_ns->get_native_bridge_ns();
341 } else {
342 native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kPlatformNamespaceName);
343 if (native_bridge_parent_namespace == nullptr) {
344 native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kDefaultNamespaceName);
345 }
346 }
347
Jiyong Parka07f3052017-08-22 10:26:10 +0900348 native_bridge_namespace_t* ns = NativeBridgeCreateNamespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800349 nullptr,
350 library_path.c_str(),
351 namespace_type,
352 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200353 native_bridge_parent_namespace);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800354 if (ns == nullptr) {
355 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200356 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800357 }
358
dimitryd2ace382019-02-04 15:06:43 +0100359 native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
Victor Chang7a20a902019-01-28 18:43:24 +0000360 native_bridge_namespace_t* runtime_ns =
361 NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700362
Jiyong Parka07f3052017-08-22 10:26:10 +0900363 if (!NativeBridgeLinkNamespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800364 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200365 return nullptr;
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800366 }
367
Victor Chang7a20a902019-01-28 18:43:24 +0000368 // Runtime apex does not exist in host, and under certain build conditions.
369 if (runtime_ns != nullptr) {
370 if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
371 *error_msg = NativeBridgeGetError();
372 return nullptr;
373 }
374 }
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700375 if (!vendor_public_libraries_.empty()) {
376 if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
377 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200378 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700379 }
380 }
381
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800382 native_loader_ns = NativeLoaderNamespace(ns);
383 }
384
385 namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
386
Victor Khimenko1443ec42018-07-09 17:01:22 +0200387 return &(namespaces_.back().second);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800388 }
389
Victor Khimenko1443ec42018-07-09 17:01:22 +0200390 NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800391 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800392 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800393 return env->IsSameObject(value.first, class_loader);
394 });
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800395 if (it != namespaces_.end()) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200396 return &it->second;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800397 }
398
Victor Khimenko1443ec42018-07-09 17:01:22 +0200399 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800400 }
401
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700402 void Initialize() {
Dimitry Ivanov80ddb8f2016-05-09 18:12:00 -0700403 // Once public namespace is initialized there is no
404 // point in running this code - it will have no effect
405 // on the current list of public libraries.
406 if (initialized_) {
407 return;
408 }
409
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700410 std::vector<std::string> sonames;
Dimitry Ivanov0b5651e2016-04-21 16:42:48 -0700411 const char* android_root_env = getenv("ANDROID_ROOT");
412 std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
413 std::string public_native_libraries_system_config =
414 root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
Jiyong Parka07f3052017-08-22 10:26:10 +0900415 std::string llndk_native_libraries_system_config =
416 root_dir + kLlndkNativeLibrariesSystemConfigPathFromRoot;
417 std::string vndksp_native_libraries_system_config =
418 root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700419
Inseob Kim67cb0562018-05-04 11:39:12 +0900420 std::string product_public_native_libraries_dir = "/product/etc";
421
Christopher Ferris39da84b2016-06-21 16:11:23 -0700422 std::string error_msg;
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900423 LOG_ALWAYS_FATAL_IF(
424 !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
425 "Error reading public native library list from \"%s\": %s",
426 public_native_libraries_system_config.c_str(), error_msg.c_str());
427
Jiyong Parke0319942018-01-15 21:14:53 +0900428 // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
429 // variable to add libraries to the list. This is intended for platform tests only.
430 if (is_debuggable()) {
431 const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
432 if (additional_libs != nullptr && additional_libs[0] != '\0') {
433 std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
434 std::copy(additional_libs_vector.begin(), additional_libs_vector.end(),
435 std::back_inserter(sonames));
436 }
437 }
438
Victor Changf70a2fe2019-02-01 20:01:27 +0000439 // Remove the public libs in the runtime namespace.
440 // These libs are listed in public.android.txt, but we don't want the rest of android
441 // in default namespace to dlopen the libs.
442 // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
443 // Unfortunately, it does not have stable C symbols, and default namespace should only use
444 // stable symbols in libandroidicu.so. http://b/120786417
445 removePublicLibsIfExistsInRuntimeApex(sonames);
446
Jiyong Parke0319942018-01-15 21:14:53 +0900447 // android_init_namespaces() expects all the public libraries
448 // to be loaded so that they can be found by soname alone.
449 //
450 // TODO(dimitry): this is a bit misleading since we do not know
451 // if the vendor public library is going to be opened from /vendor/lib
Inseob Kim67cb0562018-05-04 11:39:12 +0900452 // we might as well end up loading them from /system/lib or /product/lib
Jiyong Parke0319942018-01-15 21:14:53 +0900453 // For now we rely on CTS test to catch things like this but
454 // it should probably be addressed in the future.
455 for (const auto& soname : sonames) {
456 LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
457 "Error preloading public library %s: %s", soname.c_str(), dlerror());
458 }
459
460 system_public_libraries_ = base::Join(sonames, ':');
461
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900462 // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
463 // system libs that are exposed to apps. The libs in the txt files must be
464 // named as lib<name>.<companyname>.so.
Jiyong Parke0319942018-01-15 21:14:53 +0900465 sonames.clear();
Inseob Kim67cb0562018-05-04 11:39:12 +0900466 ReadExtensionLibraries(base::Dirname(public_native_libraries_system_config).c_str(), &sonames);
Jiyong Parke0319942018-01-15 21:14:53 +0900467 oem_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700468
Inseob Kim67cb0562018-05-04 11:39:12 +0900469 // read /product/etc/public.libraries-<companyname>.txt which contain partner defined
470 // product libs that are exposed to apps.
471 sonames.clear();
472 ReadExtensionLibraries(product_public_native_libraries_dir.c_str(), &sonames);
473 product_public_libraries_ = base::Join(sonames, ':');
474
Justin Yun4a1d1102017-11-27 17:04:14 +0900475 // Insert VNDK version to llndk and vndksp config file names.
476 insert_vndk_version_str(&llndk_native_libraries_system_config);
477 insert_vndk_version_str(&vndksp_native_libraries_system_config);
478
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700479 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900480 ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900481 system_llndk_libraries_ = base::Join(sonames, ':');
482
483 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900484 ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900485 system_vndksp_libraries_ = base::Join(sonames, ':');
486
487 sonames.clear();
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700488 // This file is optional, quietly ignore if the file does not exist.
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900489 ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700490
491 vendor_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700492 }
493
Inseob Kim67cb0562018-05-04 11:39:12 +0900494 void Reset() { namespaces_.clear(); }
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700495
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700496 private:
Inseob Kim67cb0562018-05-04 11:39:12 +0900497 void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
498 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
499 if (dir != nullptr) {
500 // Failing to opening the dir is not an error, which can happen in
501 // webview_zygote.
502 while (struct dirent* ent = readdir(dir.get())) {
503 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
504 continue;
505 }
506 const std::string filename(ent->d_name);
507 if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
508 android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
509 const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
510 const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
511 const std::string company_name = filename.substr(start, end - start);
512 const std::string config_file_path = dirname + "/"s + filename;
513 LOG_ALWAYS_FATAL_IF(
514 company_name.empty(),
515 "Error extracting company name from public native library list file path \"%s\"",
516 config_file_path.c_str());
517
518 std::string error_msg;
519
520 LOG_ALWAYS_FATAL_IF(
521 !ReadConfig(
522 config_file_path, sonames,
523 [&company_name](const std::string& soname, std::string* error_msg) {
524 if (android::base::StartsWith(soname, "lib") &&
525 android::base::EndsWith(soname, "." + company_name + ".so")) {
526 return true;
527 } else {
528 *error_msg = "Library name \"" + soname +
529 "\" does not end with the company name: " + company_name + ".";
530 return false;
531 }
532 },
533 &error_msg),
534 "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
535 error_msg.c_str());
536 }
537 }
538 }
539 }
540
Victor Changf70a2fe2019-02-01 20:01:27 +0000541 /**
542 * Remove the public libs in runtime namespace
543 */
544 void removePublicLibsIfExistsInRuntimeApex(std::vector<std::string>& sonames) {
545 for (const std::string& lib_name : kRuntimePublicLibraries) {
546 std::string path(kRuntimeApexLibPath);
547 path.append("/").append(lib_name);
548
549 struct stat s;
550 // Do nothing if the path in /apex does not exist.
551 // Runtime APEX must be mounted since libnativeloader is in the same APEX
552 if (stat(path.c_str(), &s) != 0) {
553 continue;
554 }
555
556 auto it = std::find(sonames.begin(), sonames.end(), lib_name);
557 if (it != sonames.end()) {
558 sonames.erase(it);
559 }
560 }
561 }
Inseob Kim67cb0562018-05-04 11:39:12 +0900562
Christopher Ferris39da84b2016-06-21 16:11:23 -0700563 bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900564 const std::function<bool(const std::string& /* soname */,
565 std::string* /* error_msg */)>& check_soname,
Christopher Ferris39da84b2016-06-21 16:11:23 -0700566 std::string* error_msg = nullptr) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700567 // Read list of public native libraries from the config file.
568 std::string file_content;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700569 if(!base::ReadFileToString(configFile, &file_content)) {
Christopher Ferris39da84b2016-06-21 16:11:23 -0700570 if (error_msg) *error_msg = strerror(errno);
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700571 return false;
572 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700573
574 std::vector<std::string> lines = base::Split(file_content, "\n");
575
Christopher Ferris39da84b2016-06-21 16:11:23 -0700576 for (auto& line : lines) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700577 auto trimmed_line = base::Trim(line);
578 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
579 continue;
580 }
Christopher Ferris39da84b2016-06-21 16:11:23 -0700581 size_t space_pos = trimmed_line.rfind(' ');
582 if (space_pos != std::string::npos) {
583 std::string type = trimmed_line.substr(space_pos + 1);
584 if (type != "32" && type != "64") {
585 if (error_msg) *error_msg = "Malformed line: " + line;
586 return false;
587 }
588#if defined(__LP64__)
589 // Skip 32 bit public library.
590 if (type == "32") {
591 continue;
592 }
593#else
594 // Skip 64 bit public library.
595 if (type == "64") {
596 continue;
597 }
598#endif
599 trimmed_line.resize(space_pos);
600 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700601
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900602 if (check_soname(trimmed_line, error_msg)) {
603 sonames->push_back(trimmed_line);
604 } else {
605 return false;
606 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700607 }
608
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700609 return true;
Dimitry Ivanovd68c8e92016-02-10 14:09:22 -0800610 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800611
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800612 bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
613 // Ask native bride if this apps library path should be handled by it
614 bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
615
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700616 // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
617 // code is one example) unknown to linker in which case linker uses anonymous
618 // namespace. The second argument specifies the search path for the anonymous
619 // namespace which is the library_path of the classloader.
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700620 initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800621 is_native_bridge ? nullptr : library_path);
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700622 if (!initialized_) {
623 *error_msg = dlerror();
624 return false;
625 }
626
627 // and now initialize native bridge namespaces if necessary.
628 if (NativeBridgeInitialized()) {
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700629 initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800630 is_native_bridge ? library_path : nullptr);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800631 if (!initialized_) {
632 *error_msg = NativeBridgeGetError();
633 }
634 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800635
636 return initialized_;
637 }
638
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700639 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
640 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
641 jmethodID get_parent = env->GetMethodID(class_loader_class,
642 "getParent",
643 "()Ljava/lang/ClassLoader;");
644
645 return env->CallObjectMethod(class_loader, get_parent);
646 }
647
Victor Khimenko1443ec42018-07-09 17:01:22 +0200648 NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700649 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
650
651 while (parent_class_loader != nullptr) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200652 NativeLoaderNamespace* ns;
653 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
654 return ns;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700655 }
656
657 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
658 }
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800659
Victor Khimenko1443ec42018-07-09 17:01:22 +0200660 return nullptr;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700661 }
662
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800663 bool initialized_;
Victor Khimenko1443ec42018-07-09 17:01:22 +0200664 std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700665 std::string system_public_libraries_;
666 std::string vendor_public_libraries_;
Jiyong Parke0319942018-01-15 21:14:53 +0900667 std::string oem_public_libraries_;
Inseob Kim67cb0562018-05-04 11:39:12 +0900668 std::string product_public_libraries_;
Jiyong Parka07f3052017-08-22 10:26:10 +0900669 std::string system_llndk_libraries_;
670 std::string system_vndksp_libraries_;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800671
672 DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
673};
674
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800675static std::mutex g_namespaces_mutex;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800676static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
677#endif
678
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700679void InitializeNativeLoader() {
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800680#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800681 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700682 g_namespaces->Initialize();
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800683#endif
684}
685
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700686void ResetNativeLoader() {
687#if defined(__ANDROID__)
688 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
689 g_namespaces->Reset();
690#endif
691}
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800692
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800693jstring CreateClassLoaderNamespace(JNIEnv* env,
694 int32_t target_sdk_version,
695 jobject class_loader,
696 bool is_shared,
Jiyong Parka07f3052017-08-22 10:26:10 +0900697 bool is_for_vendor,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800698 jstring library_path,
699 jstring permitted_path) {
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800700#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800701 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800702
703 std::string error_msg;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800704 bool success = g_namespaces->Create(env,
Dimitry Ivanov9e253ce2017-05-08 22:24:24 -0700705 target_sdk_version,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800706 class_loader,
707 is_shared,
Jiyong Parka07f3052017-08-22 10:26:10 +0900708 is_for_vendor,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800709 library_path,
710 permitted_path,
Victor Khimenko1443ec42018-07-09 17:01:22 +0200711 &error_msg) != nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800712 if (!success) {
713 return env->NewStringUTF(error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800714 }
715#else
Jiyong Parka07f3052017-08-22 10:26:10 +0900716 UNUSED(env, target_sdk_version, class_loader, is_shared, is_for_vendor,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800717 library_path, permitted_path);
718#endif
719 return nullptr;
720}
721
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000722#if defined(__ANDROID__)
723static android_namespace_t* FindExportedNamespace(const char* caller_location) {
724 std::string location = caller_location;
725 // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
726 // /apex/com.android...modulename/...
727 //
728 // And we extract from it 'modulename', which is the name of the linker namespace.
729 if (android::base::StartsWith(location, kApexPath)) {
730 size_t slash_index = location.find_first_of('/', strlen(kApexPath));
731 LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
732 "Error finding namespace of apex: no slash in path %s", caller_location);
733 size_t dot_index = location.find_last_of('.', slash_index);
734 LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
735 "Error finding namespace of apex: no dot in apex name %s", caller_location);
736 std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
737 android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
738 LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
739 "Error finding namespace of apex: no namespace called %s", name.c_str());
740 return boot_namespace;
741 }
742 return nullptr;
743}
744#endif
745
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000746void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
Nicolas Geoffray53535022019-01-18 10:05:13 +0000747 jobject class_loader, const char* caller_location, jstring library_path,
748 bool* needs_native_bridge, char** error_msg) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800749#if defined(__ANDROID__)
Dimitry Ivanov5539db02016-04-20 16:07:30 -0700750 UNUSED(target_sdk_version);
751 if (class_loader == nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800752 *needs_native_bridge = false;
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000753 if (caller_location != nullptr) {
754 android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
755 if (boot_namespace != nullptr) {
756 const android_dlextinfo dlextinfo = {
757 .flags = ANDROID_DLEXT_USE_NAMESPACE,
758 .library_namespace = boot_namespace,
759 };
760 void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
761 if (handle == nullptr) {
762 *error_msg = strdup(dlerror());
763 }
764 return handle;
765 }
766 }
Pete Bentley632f1422018-12-19 13:33:33 +0000767 void* handle = dlopen(path, RTLD_NOW);
768 if (handle == nullptr) {
Nicolas Geoffrayd06cb942019-01-16 20:20:27 +0000769 *error_msg = strdup(dlerror());
Pete Bentley632f1422018-12-19 13:33:33 +0000770 }
771 return handle;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800772 }
773
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800774 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200775 NativeLoaderNamespace* ns;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800776
Victor Khimenko1443ec42018-07-09 17:01:22 +0200777 if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800778 // This is the case where the classloader was not created by ApplicationLoaders
779 // In this case we create an isolated not-shared namespace for it.
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000780 std::string create_error_msg;
781 if ((ns = g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */,
782 false /* is_for_vendor */, library_path, nullptr,
783 &create_error_msg)) == nullptr) {
784 *error_msg = strdup(create_error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800785 return nullptr;
786 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800787 }
788
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000789 return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800790#else
Nicolas Geoffray53535022019-01-18 10:05:13 +0000791 UNUSED(env, target_sdk_version, class_loader, caller_location);
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800792
793 // Do some best effort to emulate library-path support. It will not
794 // work for dependencies.
795 //
796 // Note: null has a special meaning and must be preserved.
797 std::string c_library_path; // Empty string by default.
798 if (library_path != nullptr && path != nullptr && path[0] != '/') {
799 ScopedUtfChars library_path_utf_chars(env, library_path);
800 c_library_path = library_path_utf_chars.c_str();
801 }
802
803 std::vector<std::string> library_paths = base::Split(c_library_path, ":");
804
805 for (const std::string& lib_path : library_paths) {
806 *needs_native_bridge = false;
807 const char* path_arg;
808 std::string complete_path;
809 if (path == nullptr) {
810 // Preserve null.
811 path_arg = nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800812 } else {
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800813 complete_path = lib_path;
814 if (!complete_path.empty()) {
815 complete_path.append("/");
816 }
817 complete_path.append(path);
818 path_arg = complete_path.c_str();
819 }
820 void* handle = dlopen(path_arg, RTLD_NOW);
821 if (handle != nullptr) {
822 return handle;
823 }
824 if (NativeBridgeIsSupported(path_arg)) {
825 *needs_native_bridge = true;
826 handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
827 if (handle != nullptr) {
828 return handle;
829 }
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000830 *error_msg = strdup(NativeBridgeGetError());
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800831 } else {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000832 *error_msg = strdup(dlerror());
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800833 }
834 }
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800835 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800836#endif
837}
838
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000839bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
dimitry3150f7c2018-09-12 01:09:19 +0200840 bool success;
841 if (needs_native_bridge) {
842 success = (NativeBridgeUnloadLibrary(handle) == 0);
843 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000844 *error_msg = strdup(NativeBridgeGetError());
dimitry3150f7c2018-09-12 01:09:19 +0200845 }
846 } else {
847 success = (dlclose(handle) == 0);
848 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000849 *error_msg = strdup(dlerror());
dimitry3150f7c2018-09-12 01:09:19 +0200850 }
851 }
852
853 return success;
Dimitry Ivanov09a516b2016-05-03 14:55:25 -0700854}
855
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000856void NativeLoaderFreeErrorMessage(char* msg) {
857 // The error messages get allocated through strdup, so we must call free on them.
858 free(msg);
859}
860
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800861#if defined(__ANDROID__)
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000862void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
863 bool* needs_native_bridge, char** error_msg) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200864 if (ns->is_android_namespace()) {
865 android_dlextinfo extinfo;
866 extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
867 extinfo.library_namespace = ns->get_android_ns();
868
869 void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
870 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000871 *error_msg = strdup(dlerror());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200872 }
873 *needs_native_bridge = false;
874 return handle;
875 } else {
876 void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
877 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000878 *error_msg = strdup(NativeBridgeGetError());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200879 }
880 *needs_native_bridge = true;
881 return handle;
882 }
883}
884
Dimitry Ivanov800083d2016-11-01 14:17:00 -0700885// native_bridge_namespaces are not supported for callers of this function.
886// This function will return nullptr in the case when application is running
887// on native bridge.
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800888android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800889 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200890 NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
891 if (ns != nullptr) {
892 return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800893 }
894
895 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800896}
Victor Khimenko1443ec42018-07-09 17:01:22 +0200897NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
898 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
899 return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
900}
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800901#endif
902
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800903}; // android namespace