blob: 1c2581f08a45b4a7cb49eb88ba7e87bbb09f09b6 [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>
Kiyoung Kim4639f692019-02-20 18:04:39 +090034#include <regex>
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
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000119static constexpr const char* kDefaultNamespaceName = "default";
120static constexpr const char* kPlatformNamespaceName = "platform";
Victor Chang7a20a902019-01-28 18:43:24 +0000121static constexpr const char* kRuntimeNamespaceName = "runtime";
122
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000123// classloader-namespace is a linker namespace that is created for the loaded
124// app. To be specific, it is created for the app classloader. When
125// System.load() is called from a Java class that is loaded from the
126// classloader, the classloader-namespace namespace associated with that
127// classloader is selected for dlopen. The namespace is configured so that its
128// search path is set to the app-local JNI directory and it is linked to the
129// default namespace with the names of libs listed in the public.libraries.txt.
130// This way an app can only load its own JNI libraries along with the public libs.
Jiyong Parka07f3052017-08-22 10:26:10 +0900131static constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000132// Same thing for vendor APKs.
Jiyong Parka07f3052017-08-22 10:26:10 +0900133static constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
134
Dimitry Ivanovf334cbf2016-05-10 10:39:48 -0700135// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
136// System.load() with an absolute path which is outside of the classloader library search path.
137// This list includes all directories app is allowed to access this way.
138static constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
139
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000140static constexpr const char* kApexPath = "/apex/";
141
Victor Changf70a2fe2019-02-01 20:01:27 +0000142#if defined(__LP64__)
143static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib64";
Kiyoung Kim4639f692019-02-20 18:04:39 +0900144static constexpr const char* kVendorLibPath = "/vendor/lib64";
145static constexpr const char* kProductLibPath = "/product/lib64:/system/product/lib64";
Victor Changf70a2fe2019-02-01 20:01:27 +0000146#else
147static constexpr const char* kRuntimeApexLibPath = "/apex/com.android.runtime/lib";
Kiyoung Kim4639f692019-02-20 18:04:39 +0900148static constexpr const char* kVendorLibPath = "/vendor/lib";
149static constexpr const char* kProductLibPath = "/product/lib:/system/product/lib";
Victor Changf70a2fe2019-02-01 20:01:27 +0000150#endif
151
Kiyoung Kim4639f692019-02-20 18:04:39 +0900152static const std::regex kVendorDexPathRegex("(^|:)/vendor/");
153static const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");
154
155// Define origin of APK if it is from vendor partition or product partition
156typedef enum {
157 APK_ORIGIN_DEFAULT = 0,
158 APK_ORIGIN_VENDOR = 1,
159 APK_ORIGIN_PRODUCT = 2,
160} ApkOrigin;
161
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700162static bool is_debuggable() {
Orion Hodson34b126b2019-02-21 17:18:44 +0000163 bool debuggable = false;
164#ifdef __BIONIC__
165 debuggable = android::base::GetBoolProperty("ro.debuggable", false);
166#endif
167 return debuggable;
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700168}
169
Justin Yun4a1d1102017-11-27 17:04:14 +0900170static std::string vndk_version_str() {
171#ifdef __BIONIC__
172 std::string version = android::base::GetProperty("ro.vndk.version", "");
173 if (version != "" && version != "current") {
174 return "." + version;
175 }
176#endif
177 return "";
178}
179
180static void insert_vndk_version_str(std::string* file_name) {
181 CHECK(file_name != nullptr);
182 size_t insert_pos = file_name->find_last_of(".");
183 if (insert_pos == std::string::npos) {
184 insert_pos = file_name->length();
185 }
186 file_name->insert(insert_pos, vndk_version_str());
187}
188
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900189static const std::function<bool(const std::string&, std::string*)> always_true =
190 [](const std::string&, std::string*) { return true; };
191
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800192class LibraryNamespaces {
193 public:
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800194 LibraryNamespaces() : initialized_(false) { }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800195
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000196 NativeLoaderNamespace* Create(JNIEnv* env, uint32_t target_sdk_version, jobject class_loader,
Kiyoung Kim4639f692019-02-20 18:04:39 +0900197 bool is_shared, jstring dex_path, jstring java_library_path,
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000198 jstring java_permitted_path, std::string* error_msg) {
Dimitry Ivanovcf9892b2016-05-09 10:55:50 -0700199 std::string library_path; // empty string by default.
200
201 if (java_library_path != nullptr) {
202 ScopedUtfChars library_path_utf_chars(env, java_library_path);
203 library_path = library_path_utf_chars.c_str();
204 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800205
Kiyoung Kim4639f692019-02-20 18:04:39 +0900206 ApkOrigin apk_origin = GetApkOriginFromDexPath(env, dex_path);
207
Dimitry Ivanovf334cbf2016-05-10 10:39:48 -0700208 // (http://b/27588281) This is a workaround for apps using custom
209 // classloaders and calling System.load() with an absolute path which
210 // is outside of the classloader library search path.
211 //
212 // This part effectively allows such a classloader to access anything
213 // under /data and /mnt/expand
214 std::string permitted_path = kWhitelistedDirectories;
215
Dimitry Ivanov0d6e5942015-12-08 11:16:56 -0800216 if (java_permitted_path != nullptr) {
217 ScopedUtfChars path(env, java_permitted_path);
Dimitry Ivanovd0b15312016-05-10 16:21:25 -0700218 if (path.c_str() != nullptr && path.size() > 0) {
219 permitted_path = permitted_path + ":" + path.c_str();
220 }
Dimitry Ivanov0d6e5942015-12-08 11:16:56 -0800221 }
222
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800223 if (!initialized_ && !InitPublicNamespace(library_path.c_str(), error_msg)) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200224 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800225 }
226
Victor Khimenko1443ec42018-07-09 17:01:22 +0200227 bool found = FindNamespaceByClassLoader(env, class_loader);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800228
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800229 LOG_ALWAYS_FATAL_IF(found,
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700230 "There is already a namespace associated with this classloader");
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800231
Dimitry Ivanovd2a62202015-12-15 11:06:57 -0800232 uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
233 if (is_shared) {
234 namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
235 }
236
Dimitry Ivanov9e253ce2017-05-08 22:24:24 -0700237 if (target_sdk_version < 24) {
238 namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
239 }
240
Victor Khimenko1443ec42018-07-09 17:01:22 +0200241 NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700242
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800243 bool is_native_bridge = false;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800244
Victor Khimenko1443ec42018-07-09 17:01:22 +0200245 if (parent_ns != nullptr) {
246 is_native_bridge = !parent_ns->is_android_namespace();
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800247 } else if (!library_path.empty()) {
248 is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800249 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800250
Jiyong Parka07f3052017-08-22 10:26:10 +0900251 std::string system_exposed_libraries = system_public_libraries_;
252 const char* namespace_name = kClassloaderNamespaceName;
253 android_namespace_t* vndk_ns = nullptr;
Kiyoung Kim4639f692019-02-20 18:04:39 +0900254 if ((apk_origin == APK_ORIGIN_VENDOR ||
255 (apk_origin == APK_ORIGIN_PRODUCT && target_sdk_version > 29)) &&
256 !is_shared) {
257 LOG_FATAL_IF(is_native_bridge,
258 "Unbundled vendor / product apk must not use translated architecture");
Jiyong Parka07f3052017-08-22 10:26:10 +0900259
Kiyoung Kim4639f692019-02-20 18:04:39 +0900260 // For vendor / product apks, give access to the vendor / product lib even though
Jiyong Parka07f3052017-08-22 10:26:10 +0900261 // they are treated as unbundled; the libs and apks are still bundled
Kiyoung Kim4639f692019-02-20 18:04:39 +0900262 // together in the vendor / product partition.
263 const char* origin_partition;
264 const char* origin_lib_path;
265
266 switch (apk_origin) {
267 case APK_ORIGIN_VENDOR:
268 origin_partition = "vendor";
269 origin_lib_path = kVendorLibPath;
270 break;
271 case APK_ORIGIN_PRODUCT:
272 origin_partition = "product";
273 origin_lib_path = kProductLibPath;
274 break;
275 default:
276 origin_partition = "unknown";
277 origin_lib_path = "";
278 }
279
280 LOG_FATAL_IF(is_native_bridge, "Unbundled %s apk must not use translated architecture",
281 origin_partition);
282
283 library_path = library_path + ":" + origin_lib_path;
284 permitted_path = permitted_path + ":" + origin_lib_path;
Jiyong Parka07f3052017-08-22 10:26:10 +0900285
286 // Also give access to LLNDK libraries since they are available to vendors
287 system_exposed_libraries = system_exposed_libraries + ":" + system_llndk_libraries_.c_str();
288
289 // Give access to VNDK-SP libraries from the 'vndk' namespace.
290 vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
Kiyoung Kim4639f692019-02-20 18:04:39 +0900291 LOG_ALWAYS_FATAL_IF(vndk_ns == nullptr, "Cannot find \"%s\" namespace for %s apks",
292 kVndkNamespaceName, origin_partition);
Jiyong Parka07f3052017-08-22 10:26:10 +0900293
294 // Different name is useful for debugging
295 namespace_name = kVendorClassloaderNamespaceName;
Kiyoung Kim4639f692019-02-20 18:04:39 +0900296 ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
297 origin_partition, library_path.c_str());
Inseob Kim67cb0562018-05-04 11:39:12 +0900298 } else {
299 // oem and product public libraries are NOT available to vendor apks, otherwise it
Jiyong Parke0319942018-01-15 21:14:53 +0900300 // would be system->vendor violation.
Inseob Kim67cb0562018-05-04 11:39:12 +0900301 if (!oem_public_libraries_.empty()) {
302 system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries_;
303 }
304 if (!product_public_libraries_.empty()) {
305 system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries_;
306 }
Jiyong Parka07f3052017-08-22 10:26:10 +0900307 }
308
Victor Chang7a20a902019-01-28 18:43:24 +0000309 std::string runtime_exposed_libraries = base::Join(kRuntimePublicLibraries, ":");
310
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800311 NativeLoaderNamespace native_loader_ns;
312 if (!is_native_bridge) {
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000313 android_namespace_t* android_parent_ns;
314 if (parent_ns != nullptr) {
315 android_parent_ns = parent_ns->get_android_ns();
316 } else {
317 // Fall back to the platform namespace if no parent is found. It is
318 // called "default" for binaries in /system and "platform" for those in
319 // the Runtime APEX. Try "platform" first since "default" always exists.
320 android_parent_ns = android_get_exported_namespace(kPlatformNamespaceName);
321 if (android_parent_ns == nullptr) {
322 android_parent_ns = android_get_exported_namespace(kDefaultNamespaceName);
323 }
324 }
325
Jiyong Parka07f3052017-08-22 10:26:10 +0900326 android_namespace_t* ns = android_create_namespace(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 android_parent_ns);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800332 if (ns == nullptr) {
333 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200334 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800335 }
336
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700337 // Note that when vendor_ns is not configured this function will return nullptr
338 // and it will result in linking vendor_public_libraries_ to the default namespace
339 // which is expected behavior in this case.
340 android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
341
Victor Chang7a20a902019-01-28 18:43:24 +0000342 android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
343
Jiyong Parka07f3052017-08-22 10:26:10 +0900344 if (!android_link_namespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800345 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200346 return nullptr;
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800347 }
348
Victor Chang7a20a902019-01-28 18:43:24 +0000349 // Runtime apex does not exist in host, and under certain build conditions.
350 if (runtime_ns != nullptr) {
351 if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
352 *error_msg = dlerror();
353 return nullptr;
354 }
355 }
356
Jiyong Parka07f3052017-08-22 10:26:10 +0900357 if (vndk_ns != nullptr && !system_vndksp_libraries_.empty()) {
358 // vendor apks are allowed to use VNDK-SP libraries.
359 if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries_.c_str())) {
360 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200361 return nullptr;
Jiyong Parka07f3052017-08-22 10:26:10 +0900362 }
363 }
364
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700365 if (!vendor_public_libraries_.empty()) {
366 if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
367 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200368 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700369 }
370 }
371
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800372 native_loader_ns = NativeLoaderNamespace(ns);
373 } else {
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000374 native_bridge_namespace_t* native_bridge_parent_namespace;
375 if (parent_ns != nullptr) {
376 native_bridge_parent_namespace = parent_ns->get_native_bridge_ns();
377 } else {
378 native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kPlatformNamespaceName);
379 if (native_bridge_parent_namespace == nullptr) {
380 native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kDefaultNamespaceName);
381 }
382 }
383
Jiyong Parka07f3052017-08-22 10:26:10 +0900384 native_bridge_namespace_t* ns = NativeBridgeCreateNamespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800385 nullptr,
386 library_path.c_str(),
387 namespace_type,
388 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200389 native_bridge_parent_namespace);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800390 if (ns == nullptr) {
391 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200392 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800393 }
394
dimitryd2ace382019-02-04 15:06:43 +0100395 native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
Victor Chang7a20a902019-01-28 18:43:24 +0000396 native_bridge_namespace_t* runtime_ns =
397 NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700398
Jiyong Parka07f3052017-08-22 10:26:10 +0900399 if (!NativeBridgeLinkNamespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800400 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200401 return nullptr;
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800402 }
403
Victor Chang7a20a902019-01-28 18:43:24 +0000404 // Runtime apex does not exist in host, and under certain build conditions.
405 if (runtime_ns != nullptr) {
406 if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
407 *error_msg = NativeBridgeGetError();
408 return nullptr;
409 }
410 }
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700411 if (!vendor_public_libraries_.empty()) {
412 if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
413 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200414 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700415 }
416 }
417
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800418 native_loader_ns = NativeLoaderNamespace(ns);
419 }
420
421 namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
422
Victor Khimenko1443ec42018-07-09 17:01:22 +0200423 return &(namespaces_.back().second);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800424 }
425
Victor Khimenko1443ec42018-07-09 17:01:22 +0200426 NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800427 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800428 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800429 return env->IsSameObject(value.first, class_loader);
430 });
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800431 if (it != namespaces_.end()) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200432 return &it->second;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800433 }
434
Victor Khimenko1443ec42018-07-09 17:01:22 +0200435 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800436 }
437
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700438 void Initialize() {
Dimitry Ivanov80ddb8f2016-05-09 18:12:00 -0700439 // Once public namespace is initialized there is no
440 // point in running this code - it will have no effect
441 // on the current list of public libraries.
442 if (initialized_) {
443 return;
444 }
445
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700446 std::vector<std::string> sonames;
Dimitry Ivanov0b5651e2016-04-21 16:42:48 -0700447 const char* android_root_env = getenv("ANDROID_ROOT");
448 std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
449 std::string public_native_libraries_system_config =
450 root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
Jiyong Parka07f3052017-08-22 10:26:10 +0900451 std::string llndk_native_libraries_system_config =
452 root_dir + kLlndkNativeLibrariesSystemConfigPathFromRoot;
453 std::string vndksp_native_libraries_system_config =
454 root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700455
Inseob Kim67cb0562018-05-04 11:39:12 +0900456 std::string product_public_native_libraries_dir = "/product/etc";
457
Christopher Ferris39da84b2016-06-21 16:11:23 -0700458 std::string error_msg;
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900459 LOG_ALWAYS_FATAL_IF(
460 !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
461 "Error reading public native library list from \"%s\": %s",
462 public_native_libraries_system_config.c_str(), error_msg.c_str());
463
Jiyong Parke0319942018-01-15 21:14:53 +0900464 // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
465 // variable to add libraries to the list. This is intended for platform tests only.
466 if (is_debuggable()) {
467 const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
468 if (additional_libs != nullptr && additional_libs[0] != '\0') {
469 std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
470 std::copy(additional_libs_vector.begin(), additional_libs_vector.end(),
471 std::back_inserter(sonames));
472 }
473 }
474
Victor Changf70a2fe2019-02-01 20:01:27 +0000475 // Remove the public libs in the runtime namespace.
476 // These libs are listed in public.android.txt, but we don't want the rest of android
477 // in default namespace to dlopen the libs.
478 // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
479 // Unfortunately, it does not have stable C symbols, and default namespace should only use
480 // stable symbols in libandroidicu.so. http://b/120786417
481 removePublicLibsIfExistsInRuntimeApex(sonames);
482
Jiyong Parke0319942018-01-15 21:14:53 +0900483 // android_init_namespaces() expects all the public libraries
484 // to be loaded so that they can be found by soname alone.
485 //
486 // TODO(dimitry): this is a bit misleading since we do not know
487 // if the vendor public library is going to be opened from /vendor/lib
Inseob Kim67cb0562018-05-04 11:39:12 +0900488 // we might as well end up loading them from /system/lib or /product/lib
Jiyong Parke0319942018-01-15 21:14:53 +0900489 // For now we rely on CTS test to catch things like this but
490 // it should probably be addressed in the future.
491 for (const auto& soname : sonames) {
492 LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
493 "Error preloading public library %s: %s", soname.c_str(), dlerror());
494 }
495
496 system_public_libraries_ = base::Join(sonames, ':');
497
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900498 // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
499 // system libs that are exposed to apps. The libs in the txt files must be
500 // named as lib<name>.<companyname>.so.
Jiyong Parke0319942018-01-15 21:14:53 +0900501 sonames.clear();
Inseob Kim67cb0562018-05-04 11:39:12 +0900502 ReadExtensionLibraries(base::Dirname(public_native_libraries_system_config).c_str(), &sonames);
Jiyong Parke0319942018-01-15 21:14:53 +0900503 oem_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700504
Inseob Kim67cb0562018-05-04 11:39:12 +0900505 // read /product/etc/public.libraries-<companyname>.txt which contain partner defined
506 // product libs that are exposed to apps.
507 sonames.clear();
508 ReadExtensionLibraries(product_public_native_libraries_dir.c_str(), &sonames);
509 product_public_libraries_ = base::Join(sonames, ':');
510
Justin Yun4a1d1102017-11-27 17:04:14 +0900511 // Insert VNDK version to llndk and vndksp config file names.
512 insert_vndk_version_str(&llndk_native_libraries_system_config);
513 insert_vndk_version_str(&vndksp_native_libraries_system_config);
514
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700515 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900516 ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900517 system_llndk_libraries_ = base::Join(sonames, ':');
518
519 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900520 ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900521 system_vndksp_libraries_ = base::Join(sonames, ':');
522
523 sonames.clear();
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700524 // This file is optional, quietly ignore if the file does not exist.
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900525 ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700526
527 vendor_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700528 }
529
Inseob Kim67cb0562018-05-04 11:39:12 +0900530 void Reset() { namespaces_.clear(); }
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700531
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700532 private:
Inseob Kim67cb0562018-05-04 11:39:12 +0900533 void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
534 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
535 if (dir != nullptr) {
536 // Failing to opening the dir is not an error, which can happen in
537 // webview_zygote.
538 while (struct dirent* ent = readdir(dir.get())) {
539 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
540 continue;
541 }
542 const std::string filename(ent->d_name);
543 if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
544 android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
545 const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
546 const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
547 const std::string company_name = filename.substr(start, end - start);
548 const std::string config_file_path = dirname + "/"s + filename;
549 LOG_ALWAYS_FATAL_IF(
550 company_name.empty(),
551 "Error extracting company name from public native library list file path \"%s\"",
552 config_file_path.c_str());
553
554 std::string error_msg;
555
556 LOG_ALWAYS_FATAL_IF(
557 !ReadConfig(
558 config_file_path, sonames,
559 [&company_name](const std::string& soname, std::string* error_msg) {
560 if (android::base::StartsWith(soname, "lib") &&
561 android::base::EndsWith(soname, "." + company_name + ".so")) {
562 return true;
563 } else {
564 *error_msg = "Library name \"" + soname +
565 "\" does not end with the company name: " + company_name + ".";
566 return false;
567 }
568 },
569 &error_msg),
570 "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
571 error_msg.c_str());
572 }
573 }
574 }
575 }
576
Victor Changf70a2fe2019-02-01 20:01:27 +0000577 /**
578 * Remove the public libs in runtime namespace
579 */
580 void removePublicLibsIfExistsInRuntimeApex(std::vector<std::string>& sonames) {
581 for (const std::string& lib_name : kRuntimePublicLibraries) {
582 std::string path(kRuntimeApexLibPath);
583 path.append("/").append(lib_name);
584
585 struct stat s;
586 // Do nothing if the path in /apex does not exist.
587 // Runtime APEX must be mounted since libnativeloader is in the same APEX
588 if (stat(path.c_str(), &s) != 0) {
589 continue;
590 }
591
592 auto it = std::find(sonames.begin(), sonames.end(), lib_name);
593 if (it != sonames.end()) {
594 sonames.erase(it);
595 }
596 }
597 }
Inseob Kim67cb0562018-05-04 11:39:12 +0900598
Christopher Ferris39da84b2016-06-21 16:11:23 -0700599 bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900600 const std::function<bool(const std::string& /* soname */,
601 std::string* /* error_msg */)>& check_soname,
Christopher Ferris39da84b2016-06-21 16:11:23 -0700602 std::string* error_msg = nullptr) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700603 // Read list of public native libraries from the config file.
604 std::string file_content;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700605 if(!base::ReadFileToString(configFile, &file_content)) {
Christopher Ferris39da84b2016-06-21 16:11:23 -0700606 if (error_msg) *error_msg = strerror(errno);
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700607 return false;
608 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700609
610 std::vector<std::string> lines = base::Split(file_content, "\n");
611
Christopher Ferris39da84b2016-06-21 16:11:23 -0700612 for (auto& line : lines) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700613 auto trimmed_line = base::Trim(line);
614 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
615 continue;
616 }
Christopher Ferris39da84b2016-06-21 16:11:23 -0700617 size_t space_pos = trimmed_line.rfind(' ');
618 if (space_pos != std::string::npos) {
619 std::string type = trimmed_line.substr(space_pos + 1);
620 if (type != "32" && type != "64") {
621 if (error_msg) *error_msg = "Malformed line: " + line;
622 return false;
623 }
624#if defined(__LP64__)
625 // Skip 32 bit public library.
626 if (type == "32") {
627 continue;
628 }
629#else
630 // Skip 64 bit public library.
631 if (type == "64") {
632 continue;
633 }
634#endif
635 trimmed_line.resize(space_pos);
636 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700637
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900638 if (check_soname(trimmed_line, error_msg)) {
639 sonames->push_back(trimmed_line);
640 } else {
641 return false;
642 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700643 }
644
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700645 return true;
Dimitry Ivanovd68c8e92016-02-10 14:09:22 -0800646 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800647
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800648 bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
649 // Ask native bride if this apps library path should be handled by it
650 bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
651
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700652 // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
653 // code is one example) unknown to linker in which case linker uses anonymous
654 // namespace. The second argument specifies the search path for the anonymous
655 // namespace which is the library_path of the classloader.
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700656 initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800657 is_native_bridge ? nullptr : library_path);
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700658 if (!initialized_) {
659 *error_msg = dlerror();
660 return false;
661 }
662
663 // and now initialize native bridge namespaces if necessary.
664 if (NativeBridgeInitialized()) {
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700665 initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800666 is_native_bridge ? library_path : nullptr);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800667 if (!initialized_) {
668 *error_msg = NativeBridgeGetError();
669 }
670 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800671
672 return initialized_;
673 }
674
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700675 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
676 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
677 jmethodID get_parent = env->GetMethodID(class_loader_class,
678 "getParent",
679 "()Ljava/lang/ClassLoader;");
680
681 return env->CallObjectMethod(class_loader, get_parent);
682 }
683
Victor Khimenko1443ec42018-07-09 17:01:22 +0200684 NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700685 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
686
687 while (parent_class_loader != nullptr) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200688 NativeLoaderNamespace* ns;
689 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
690 return ns;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700691 }
692
693 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
694 }
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800695
Victor Khimenko1443ec42018-07-09 17:01:22 +0200696 return nullptr;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700697 }
698
Kiyoung Kim4639f692019-02-20 18:04:39 +0900699 ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
700 ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
701
702 if (dex_path != nullptr) {
703 ScopedUtfChars dex_path_utf_chars(env, dex_path);
704
705 if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
706 apk_origin = APK_ORIGIN_VENDOR;
707 }
708
709 if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
710 LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
711 "Dex path contains both vendor and product partition : %s",
712 dex_path_utf_chars.c_str());
713
714 apk_origin = APK_ORIGIN_PRODUCT;
715 }
716 }
717
718 return apk_origin;
719 }
720
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800721 bool initialized_;
Victor Khimenko1443ec42018-07-09 17:01:22 +0200722 std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700723 std::string system_public_libraries_;
724 std::string vendor_public_libraries_;
Jiyong Parke0319942018-01-15 21:14:53 +0900725 std::string oem_public_libraries_;
Inseob Kim67cb0562018-05-04 11:39:12 +0900726 std::string product_public_libraries_;
Jiyong Parka07f3052017-08-22 10:26:10 +0900727 std::string system_llndk_libraries_;
728 std::string system_vndksp_libraries_;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800729
730 DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
731};
732
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800733static std::mutex g_namespaces_mutex;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800734static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
735#endif
736
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700737void InitializeNativeLoader() {
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800738#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800739 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700740 g_namespaces->Initialize();
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800741#endif
742}
743
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700744void ResetNativeLoader() {
745#if defined(__ANDROID__)
746 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
747 g_namespaces->Reset();
748#endif
749}
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800750
Kiyoung Kim4639f692019-02-20 18:04:39 +0900751jstring CreateClassLoaderNamespace(JNIEnv* env, int32_t target_sdk_version, jobject class_loader,
752 bool is_shared, jstring dex_path, jstring library_path,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800753 jstring permitted_path) {
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800754#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800755 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800756
757 std::string error_msg;
Kiyoung Kim4639f692019-02-20 18:04:39 +0900758 bool success = g_namespaces->Create(env, target_sdk_version, class_loader, is_shared, dex_path,
759 library_path, permitted_path, &error_msg) != nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800760 if (!success) {
761 return env->NewStringUTF(error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800762 }
763#else
Kiyoung Kim4639f692019-02-20 18:04:39 +0900764 UNUSED(env, target_sdk_version, class_loader, is_shared, dex_path, library_path, permitted_path);
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800765#endif
766 return nullptr;
767}
768
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000769#if defined(__ANDROID__)
770static android_namespace_t* FindExportedNamespace(const char* caller_location) {
771 std::string location = caller_location;
772 // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
773 // /apex/com.android...modulename/...
774 //
775 // And we extract from it 'modulename', which is the name of the linker namespace.
776 if (android::base::StartsWith(location, kApexPath)) {
777 size_t slash_index = location.find_first_of('/', strlen(kApexPath));
778 LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
779 "Error finding namespace of apex: no slash in path %s", caller_location);
780 size_t dot_index = location.find_last_of('.', slash_index);
781 LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
782 "Error finding namespace of apex: no dot in apex name %s", caller_location);
783 std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
784 android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
785 LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
786 "Error finding namespace of apex: no namespace called %s", name.c_str());
787 return boot_namespace;
788 }
789 return nullptr;
790}
791#endif
792
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000793void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
Nicolas Geoffray53535022019-01-18 10:05:13 +0000794 jobject class_loader, const char* caller_location, jstring library_path,
795 bool* needs_native_bridge, char** error_msg) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800796#if defined(__ANDROID__)
Dimitry Ivanov5539db02016-04-20 16:07:30 -0700797 UNUSED(target_sdk_version);
798 if (class_loader == nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800799 *needs_native_bridge = false;
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000800 if (caller_location != nullptr) {
801 android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
802 if (boot_namespace != nullptr) {
803 const android_dlextinfo dlextinfo = {
804 .flags = ANDROID_DLEXT_USE_NAMESPACE,
805 .library_namespace = boot_namespace,
806 };
807 void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
808 if (handle == nullptr) {
809 *error_msg = strdup(dlerror());
810 }
811 return handle;
812 }
813 }
Pete Bentley632f1422018-12-19 13:33:33 +0000814 void* handle = dlopen(path, RTLD_NOW);
815 if (handle == nullptr) {
Nicolas Geoffrayd06cb942019-01-16 20:20:27 +0000816 *error_msg = strdup(dlerror());
Pete Bentley632f1422018-12-19 13:33:33 +0000817 }
818 return handle;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800819 }
820
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800821 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200822 NativeLoaderNamespace* ns;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800823
Victor Khimenko1443ec42018-07-09 17:01:22 +0200824 if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800825 // This is the case where the classloader was not created by ApplicationLoaders
826 // In this case we create an isolated not-shared namespace for it.
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000827 std::string create_error_msg;
828 if ((ns = g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */,
Kiyoung Kim4639f692019-02-20 18:04:39 +0900829 nullptr, library_path, nullptr, &create_error_msg)) == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000830 *error_msg = strdup(create_error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800831 return nullptr;
832 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800833 }
834
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000835 return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800836#else
Nicolas Geoffray53535022019-01-18 10:05:13 +0000837 UNUSED(env, target_sdk_version, class_loader, caller_location);
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800838
839 // Do some best effort to emulate library-path support. It will not
840 // work for dependencies.
841 //
842 // Note: null has a special meaning and must be preserved.
843 std::string c_library_path; // Empty string by default.
844 if (library_path != nullptr && path != nullptr && path[0] != '/') {
845 ScopedUtfChars library_path_utf_chars(env, library_path);
846 c_library_path = library_path_utf_chars.c_str();
847 }
848
849 std::vector<std::string> library_paths = base::Split(c_library_path, ":");
850
851 for (const std::string& lib_path : library_paths) {
852 *needs_native_bridge = false;
853 const char* path_arg;
854 std::string complete_path;
855 if (path == nullptr) {
856 // Preserve null.
857 path_arg = nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800858 } else {
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800859 complete_path = lib_path;
860 if (!complete_path.empty()) {
861 complete_path.append("/");
862 }
863 complete_path.append(path);
864 path_arg = complete_path.c_str();
865 }
866 void* handle = dlopen(path_arg, RTLD_NOW);
867 if (handle != nullptr) {
868 return handle;
869 }
870 if (NativeBridgeIsSupported(path_arg)) {
871 *needs_native_bridge = true;
872 handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
873 if (handle != nullptr) {
874 return handle;
875 }
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000876 *error_msg = strdup(NativeBridgeGetError());
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800877 } else {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000878 *error_msg = strdup(dlerror());
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800879 }
880 }
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800881 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800882#endif
883}
884
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000885bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
dimitry3150f7c2018-09-12 01:09:19 +0200886 bool success;
887 if (needs_native_bridge) {
888 success = (NativeBridgeUnloadLibrary(handle) == 0);
889 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000890 *error_msg = strdup(NativeBridgeGetError());
dimitry3150f7c2018-09-12 01:09:19 +0200891 }
892 } else {
893 success = (dlclose(handle) == 0);
894 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000895 *error_msg = strdup(dlerror());
dimitry3150f7c2018-09-12 01:09:19 +0200896 }
897 }
898
899 return success;
Dimitry Ivanov09a516b2016-05-03 14:55:25 -0700900}
901
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000902void NativeLoaderFreeErrorMessage(char* msg) {
903 // The error messages get allocated through strdup, so we must call free on them.
904 free(msg);
905}
906
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800907#if defined(__ANDROID__)
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000908void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
909 bool* needs_native_bridge, char** error_msg) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200910 if (ns->is_android_namespace()) {
911 android_dlextinfo extinfo;
912 extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
913 extinfo.library_namespace = ns->get_android_ns();
914
915 void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
916 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000917 *error_msg = strdup(dlerror());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200918 }
919 *needs_native_bridge = false;
920 return handle;
921 } else {
922 void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
923 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000924 *error_msg = strdup(NativeBridgeGetError());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200925 }
926 *needs_native_bridge = true;
927 return handle;
928 }
929}
930
Dimitry Ivanov800083d2016-11-01 14:17:00 -0700931// native_bridge_namespaces are not supported for callers of this function.
932// This function will return nullptr in the case when application is running
933// on native bridge.
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800934android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800935 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200936 NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
937 if (ns != nullptr) {
938 return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800939 }
940
941 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800942}
Victor Khimenko1443ec42018-07-09 17:01:22 +0200943NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
944 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
945 return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
946}
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800947#endif
948
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800949}; // android namespace