blob: e460b1a308712d4bd277429d99ec1ae166608745 [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
Martin Stjernholmb9259a92019-04-29 20:57:16 +0000129// default namespace with the names of libs listed in the public.libraries.txt.
Martin Stjernholmb78f6ec2019-02-06 21:47:26 +0000130// 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
Andreas Gampeb9df7d92019-04-26 08:51:50 -0700223 // Initialize the anonymous namespace with the first non-empty library path.
224 if (!library_path.empty() && !initialized_ &&
225 !InitPublicNamespace(library_path.c_str(), error_msg)) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200226 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800227 }
228
Victor Khimenko1443ec42018-07-09 17:01:22 +0200229 bool found = FindNamespaceByClassLoader(env, class_loader);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800230
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800231 LOG_ALWAYS_FATAL_IF(found,
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700232 "There is already a namespace associated with this classloader");
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800233
Dimitry Ivanovd2a62202015-12-15 11:06:57 -0800234 uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
235 if (is_shared) {
236 namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
237 }
238
Dimitry Ivanov9e253ce2017-05-08 22:24:24 -0700239 if (target_sdk_version < 24) {
240 namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
241 }
242
Victor Khimenko1443ec42018-07-09 17:01:22 +0200243 NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700244
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800245 bool is_native_bridge = false;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800246
Victor Khimenko1443ec42018-07-09 17:01:22 +0200247 if (parent_ns != nullptr) {
248 is_native_bridge = !parent_ns->is_android_namespace();
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800249 } else if (!library_path.empty()) {
250 is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800251 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800252
Jiyong Parka07f3052017-08-22 10:26:10 +0900253 std::string system_exposed_libraries = system_public_libraries_;
254 const char* namespace_name = kClassloaderNamespaceName;
255 android_namespace_t* vndk_ns = nullptr;
Kiyoung Kim4639f692019-02-20 18:04:39 +0900256 if ((apk_origin == APK_ORIGIN_VENDOR ||
257 (apk_origin == APK_ORIGIN_PRODUCT && target_sdk_version > 29)) &&
258 !is_shared) {
259 LOG_FATAL_IF(is_native_bridge,
260 "Unbundled vendor / product apk must not use translated architecture");
Jiyong Parka07f3052017-08-22 10:26:10 +0900261
Kiyoung Kim4639f692019-02-20 18:04:39 +0900262 // For vendor / product apks, give access to the vendor / product lib even though
Jiyong Parka07f3052017-08-22 10:26:10 +0900263 // they are treated as unbundled; the libs and apks are still bundled
Kiyoung Kim4639f692019-02-20 18:04:39 +0900264 // together in the vendor / product partition.
265 const char* origin_partition;
266 const char* origin_lib_path;
267
268 switch (apk_origin) {
269 case APK_ORIGIN_VENDOR:
270 origin_partition = "vendor";
271 origin_lib_path = kVendorLibPath;
272 break;
273 case APK_ORIGIN_PRODUCT:
274 origin_partition = "product";
275 origin_lib_path = kProductLibPath;
276 break;
277 default:
278 origin_partition = "unknown";
279 origin_lib_path = "";
280 }
281
282 LOG_FATAL_IF(is_native_bridge, "Unbundled %s apk must not use translated architecture",
283 origin_partition);
284
285 library_path = library_path + ":" + origin_lib_path;
286 permitted_path = permitted_path + ":" + origin_lib_path;
Jiyong Parka07f3052017-08-22 10:26:10 +0900287
288 // Also give access to LLNDK libraries since they are available to vendors
289 system_exposed_libraries = system_exposed_libraries + ":" + system_llndk_libraries_.c_str();
290
291 // Give access to VNDK-SP libraries from the 'vndk' namespace.
292 vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
Kiyoung Kim23ff8eb2019-03-21 16:56:05 +0900293 if (vndk_ns == nullptr) {
294 ALOGW("Cannot find \"%s\" namespace for %s apks", kVndkNamespaceName, origin_partition);
295 }
Jiyong Parka07f3052017-08-22 10:26:10 +0900296
297 // Different name is useful for debugging
298 namespace_name = kVendorClassloaderNamespaceName;
Kiyoung Kim4639f692019-02-20 18:04:39 +0900299 ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
300 origin_partition, library_path.c_str());
Inseob Kim67cb0562018-05-04 11:39:12 +0900301 } else {
302 // oem and product public libraries are NOT available to vendor apks, otherwise it
Jiyong Parke0319942018-01-15 21:14:53 +0900303 // would be system->vendor violation.
Inseob Kim67cb0562018-05-04 11:39:12 +0900304 if (!oem_public_libraries_.empty()) {
305 system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries_;
306 }
307 if (!product_public_libraries_.empty()) {
308 system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries_;
309 }
Jiyong Parka07f3052017-08-22 10:26:10 +0900310 }
311
Martin Stjernholmb9259a92019-04-29 20:57:16 +0000312 std::string runtime_exposed_libraries = base::Join(kRuntimePublicLibraries, ":");
Victor Chang7a20a902019-01-28 18:43:24 +0000313
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800314 NativeLoaderNamespace native_loader_ns;
315 if (!is_native_bridge) {
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000316 android_namespace_t* android_parent_ns;
317 if (parent_ns != nullptr) {
318 android_parent_ns = parent_ns->get_android_ns();
319 } else {
Martin Stjernholmb9259a92019-04-29 20:57:16 +0000320 // Fall back to the platform namespace if no parent is found. It is
321 // called "default" for binaries in /system and "platform" for those in
322 // the Runtime APEX. Try "platform" first since "default" always exists.
323 android_parent_ns = android_get_exported_namespace(kPlatformNamespaceName);
324 if (android_parent_ns == nullptr) {
325 android_parent_ns = android_get_exported_namespace(kDefaultNamespaceName);
326 }
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000327 }
328
Jiyong Parka07f3052017-08-22 10:26:10 +0900329 android_namespace_t* ns = android_create_namespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800330 nullptr,
331 library_path.c_str(),
332 namespace_type,
333 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200334 android_parent_ns);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800335 if (ns == nullptr) {
336 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200337 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800338 }
339
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700340 // Note that when vendor_ns is not configured this function will return nullptr
341 // and it will result in linking vendor_public_libraries_ to the default namespace
342 // which is expected behavior in this case.
343 android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
344
Victor Chang7a20a902019-01-28 18:43:24 +0000345 android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
346
Martin Stjernholmb9259a92019-04-29 20:57:16 +0000347 if (!android_link_namespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800348 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200349 return nullptr;
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800350 }
351
Victor Chang7a20a902019-01-28 18:43:24 +0000352 // Runtime apex does not exist in host, and under certain build conditions.
353 if (runtime_ns != nullptr) {
354 if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
355 *error_msg = dlerror();
356 return nullptr;
357 }
358 }
359
Jiyong Parka07f3052017-08-22 10:26:10 +0900360 if (vndk_ns != nullptr && !system_vndksp_libraries_.empty()) {
361 // vendor apks are allowed to use VNDK-SP libraries.
362 if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries_.c_str())) {
363 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200364 return nullptr;
Jiyong Parka07f3052017-08-22 10:26:10 +0900365 }
366 }
367
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700368 if (!vendor_public_libraries_.empty()) {
369 if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
370 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200371 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700372 }
373 }
374
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800375 native_loader_ns = NativeLoaderNamespace(ns);
376 } else {
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000377 native_bridge_namespace_t* native_bridge_parent_namespace;
378 if (parent_ns != nullptr) {
379 native_bridge_parent_namespace = parent_ns->get_native_bridge_ns();
380 } else {
Martin Stjernholmb9259a92019-04-29 20:57:16 +0000381 native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kPlatformNamespaceName);
382 if (native_bridge_parent_namespace == nullptr) {
383 native_bridge_parent_namespace = NativeBridgeGetExportedNamespace(kDefaultNamespaceName);
384 }
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000385 }
386
Jiyong Parka07f3052017-08-22 10:26:10 +0900387 native_bridge_namespace_t* ns = NativeBridgeCreateNamespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800388 nullptr,
389 library_path.c_str(),
390 namespace_type,
391 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200392 native_bridge_parent_namespace);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800393 if (ns == nullptr) {
394 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200395 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800396 }
397
dimitryd2ace382019-02-04 15:06:43 +0100398 native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
Victor Chang7a20a902019-01-28 18:43:24 +0000399 native_bridge_namespace_t* runtime_ns =
400 NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700401
Martin Stjernholmb9259a92019-04-29 20:57:16 +0000402 if (!NativeBridgeLinkNamespaces(ns, nullptr, system_exposed_libraries.c_str())) {
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800403 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200404 return nullptr;
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800405 }
406
Victor Chang7a20a902019-01-28 18:43:24 +0000407 // Runtime apex does not exist in host, and under certain build conditions.
408 if (runtime_ns != nullptr) {
409 if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
410 *error_msg = NativeBridgeGetError();
411 return nullptr;
412 }
413 }
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700414 if (!vendor_public_libraries_.empty()) {
415 if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
416 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200417 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700418 }
419 }
420
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800421 native_loader_ns = NativeLoaderNamespace(ns);
422 }
423
424 namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
425
Victor Khimenko1443ec42018-07-09 17:01:22 +0200426 return &(namespaces_.back().second);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800427 }
428
Victor Khimenko1443ec42018-07-09 17:01:22 +0200429 NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800430 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800431 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800432 return env->IsSameObject(value.first, class_loader);
433 });
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800434 if (it != namespaces_.end()) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200435 return &it->second;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800436 }
437
Victor Khimenko1443ec42018-07-09 17:01:22 +0200438 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800439 }
440
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700441 void Initialize() {
Dimitry Ivanov80ddb8f2016-05-09 18:12:00 -0700442 // Once public namespace is initialized there is no
443 // point in running this code - it will have no effect
444 // on the current list of public libraries.
445 if (initialized_) {
446 return;
447 }
448
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700449 std::vector<std::string> sonames;
Dimitry Ivanov0b5651e2016-04-21 16:42:48 -0700450 const char* android_root_env = getenv("ANDROID_ROOT");
451 std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
452 std::string public_native_libraries_system_config =
453 root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
Jiyong Parka07f3052017-08-22 10:26:10 +0900454 std::string llndk_native_libraries_system_config =
455 root_dir + kLlndkNativeLibrariesSystemConfigPathFromRoot;
456 std::string vndksp_native_libraries_system_config =
457 root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700458
Inseob Kim67cb0562018-05-04 11:39:12 +0900459 std::string product_public_native_libraries_dir = "/product/etc";
460
Christopher Ferris39da84b2016-06-21 16:11:23 -0700461 std::string error_msg;
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900462 LOG_ALWAYS_FATAL_IF(
463 !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
464 "Error reading public native library list from \"%s\": %s",
465 public_native_libraries_system_config.c_str(), error_msg.c_str());
466
Jiyong Parke0319942018-01-15 21:14:53 +0900467 // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
468 // variable to add libraries to the list. This is intended for platform tests only.
469 if (is_debuggable()) {
470 const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
471 if (additional_libs != nullptr && additional_libs[0] != '\0') {
472 std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
473 std::copy(additional_libs_vector.begin(), additional_libs_vector.end(),
474 std::back_inserter(sonames));
475 }
476 }
477
Victor Changf70a2fe2019-02-01 20:01:27 +0000478 // Remove the public libs in the runtime namespace.
479 // These libs are listed in public.android.txt, but we don't want the rest of android
480 // in default namespace to dlopen the libs.
481 // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
482 // Unfortunately, it does not have stable C symbols, and default namespace should only use
483 // stable symbols in libandroidicu.so. http://b/120786417
484 removePublicLibsIfExistsInRuntimeApex(sonames);
485
Jiyong Parke0319942018-01-15 21:14:53 +0900486 // android_init_namespaces() expects all the public libraries
487 // to be loaded so that they can be found by soname alone.
488 //
489 // TODO(dimitry): this is a bit misleading since we do not know
490 // if the vendor public library is going to be opened from /vendor/lib
Inseob Kim67cb0562018-05-04 11:39:12 +0900491 // we might as well end up loading them from /system/lib or /product/lib
Jiyong Parke0319942018-01-15 21:14:53 +0900492 // For now we rely on CTS test to catch things like this but
493 // it should probably be addressed in the future.
494 for (const auto& soname : sonames) {
495 LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
496 "Error preloading public library %s: %s", soname.c_str(), dlerror());
497 }
498
499 system_public_libraries_ = base::Join(sonames, ':');
500
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900501 // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
502 // system libs that are exposed to apps. The libs in the txt files must be
503 // named as lib<name>.<companyname>.so.
Jiyong Parke0319942018-01-15 21:14:53 +0900504 sonames.clear();
Inseob Kim67cb0562018-05-04 11:39:12 +0900505 ReadExtensionLibraries(base::Dirname(public_native_libraries_system_config).c_str(), &sonames);
Jiyong Parke0319942018-01-15 21:14:53 +0900506 oem_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700507
Inseob Kim67cb0562018-05-04 11:39:12 +0900508 // read /product/etc/public.libraries-<companyname>.txt which contain partner defined
509 // product libs that are exposed to apps.
510 sonames.clear();
511 ReadExtensionLibraries(product_public_native_libraries_dir.c_str(), &sonames);
512 product_public_libraries_ = base::Join(sonames, ':');
513
Justin Yun4a1d1102017-11-27 17:04:14 +0900514 // Insert VNDK version to llndk and vndksp config file names.
515 insert_vndk_version_str(&llndk_native_libraries_system_config);
516 insert_vndk_version_str(&vndksp_native_libraries_system_config);
517
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700518 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900519 ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900520 system_llndk_libraries_ = base::Join(sonames, ':');
521
522 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900523 ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900524 system_vndksp_libraries_ = base::Join(sonames, ':');
525
526 sonames.clear();
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700527 // This file is optional, quietly ignore if the file does not exist.
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900528 ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700529
530 vendor_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700531 }
532
Inseob Kim67cb0562018-05-04 11:39:12 +0900533 void Reset() { namespaces_.clear(); }
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700534
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700535 private:
Inseob Kim67cb0562018-05-04 11:39:12 +0900536 void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
537 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
538 if (dir != nullptr) {
539 // Failing to opening the dir is not an error, which can happen in
540 // webview_zygote.
541 while (struct dirent* ent = readdir(dir.get())) {
542 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
543 continue;
544 }
545 const std::string filename(ent->d_name);
546 if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
547 android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
548 const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
549 const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
550 const std::string company_name = filename.substr(start, end - start);
551 const std::string config_file_path = dirname + "/"s + filename;
552 LOG_ALWAYS_FATAL_IF(
553 company_name.empty(),
554 "Error extracting company name from public native library list file path \"%s\"",
555 config_file_path.c_str());
556
557 std::string error_msg;
558
559 LOG_ALWAYS_FATAL_IF(
560 !ReadConfig(
561 config_file_path, sonames,
562 [&company_name](const std::string& soname, std::string* error_msg) {
563 if (android::base::StartsWith(soname, "lib") &&
564 android::base::EndsWith(soname, "." + company_name + ".so")) {
565 return true;
566 } else {
567 *error_msg = "Library name \"" + soname +
568 "\" does not end with the company name: " + company_name + ".";
569 return false;
570 }
571 },
572 &error_msg),
573 "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
574 error_msg.c_str());
575 }
576 }
577 }
578 }
579
Victor Changf70a2fe2019-02-01 20:01:27 +0000580 /**
581 * Remove the public libs in runtime namespace
582 */
583 void removePublicLibsIfExistsInRuntimeApex(std::vector<std::string>& sonames) {
584 for (const std::string& lib_name : kRuntimePublicLibraries) {
585 std::string path(kRuntimeApexLibPath);
586 path.append("/").append(lib_name);
587
588 struct stat s;
589 // Do nothing if the path in /apex does not exist.
590 // Runtime APEX must be mounted since libnativeloader is in the same APEX
591 if (stat(path.c_str(), &s) != 0) {
592 continue;
593 }
594
595 auto it = std::find(sonames.begin(), sonames.end(), lib_name);
596 if (it != sonames.end()) {
597 sonames.erase(it);
598 }
599 }
600 }
Inseob Kim67cb0562018-05-04 11:39:12 +0900601
Christopher Ferris39da84b2016-06-21 16:11:23 -0700602 bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900603 const std::function<bool(const std::string& /* soname */,
604 std::string* /* error_msg */)>& check_soname,
Christopher Ferris39da84b2016-06-21 16:11:23 -0700605 std::string* error_msg = nullptr) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700606 // Read list of public native libraries from the config file.
607 std::string file_content;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700608 if(!base::ReadFileToString(configFile, &file_content)) {
Christopher Ferris39da84b2016-06-21 16:11:23 -0700609 if (error_msg) *error_msg = strerror(errno);
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700610 return false;
611 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700612
613 std::vector<std::string> lines = base::Split(file_content, "\n");
614
Christopher Ferris39da84b2016-06-21 16:11:23 -0700615 for (auto& line : lines) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700616 auto trimmed_line = base::Trim(line);
617 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
618 continue;
619 }
Christopher Ferris39da84b2016-06-21 16:11:23 -0700620 size_t space_pos = trimmed_line.rfind(' ');
621 if (space_pos != std::string::npos) {
622 std::string type = trimmed_line.substr(space_pos + 1);
623 if (type != "32" && type != "64") {
624 if (error_msg) *error_msg = "Malformed line: " + line;
625 return false;
626 }
627#if defined(__LP64__)
628 // Skip 32 bit public library.
629 if (type == "32") {
630 continue;
631 }
632#else
633 // Skip 64 bit public library.
634 if (type == "64") {
635 continue;
636 }
637#endif
638 trimmed_line.resize(space_pos);
639 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700640
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900641 if (check_soname(trimmed_line, error_msg)) {
642 sonames->push_back(trimmed_line);
643 } else {
644 return false;
645 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700646 }
647
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700648 return true;
Dimitry Ivanovd68c8e92016-02-10 14:09:22 -0800649 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800650
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800651 bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
652 // Ask native bride if this apps library path should be handled by it
653 bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
654
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700655 // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
656 // code is one example) unknown to linker in which case linker uses anonymous
657 // namespace. The second argument specifies the search path for the anonymous
658 // namespace which is the library_path of the classloader.
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700659 initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800660 is_native_bridge ? nullptr : library_path);
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700661 if (!initialized_) {
662 *error_msg = dlerror();
663 return false;
664 }
665
666 // and now initialize native bridge namespaces if necessary.
667 if (NativeBridgeInitialized()) {
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700668 initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800669 is_native_bridge ? library_path : nullptr);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800670 if (!initialized_) {
671 *error_msg = NativeBridgeGetError();
672 }
673 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800674
675 return initialized_;
676 }
677
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700678 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
679 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
680 jmethodID get_parent = env->GetMethodID(class_loader_class,
681 "getParent",
682 "()Ljava/lang/ClassLoader;");
683
684 return env->CallObjectMethod(class_loader, get_parent);
685 }
686
Victor Khimenko1443ec42018-07-09 17:01:22 +0200687 NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700688 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
689
690 while (parent_class_loader != nullptr) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200691 NativeLoaderNamespace* ns;
692 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
693 return ns;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700694 }
695
696 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
697 }
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800698
Victor Khimenko1443ec42018-07-09 17:01:22 +0200699 return nullptr;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700700 }
701
Kiyoung Kim4639f692019-02-20 18:04:39 +0900702 ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
703 ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
704
705 if (dex_path != nullptr) {
706 ScopedUtfChars dex_path_utf_chars(env, dex_path);
707
708 if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
709 apk_origin = APK_ORIGIN_VENDOR;
710 }
711
712 if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
713 LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
714 "Dex path contains both vendor and product partition : %s",
715 dex_path_utf_chars.c_str());
716
717 apk_origin = APK_ORIGIN_PRODUCT;
718 }
719 }
720
721 return apk_origin;
722 }
723
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800724 bool initialized_;
Victor Khimenko1443ec42018-07-09 17:01:22 +0200725 std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700726 std::string system_public_libraries_;
727 std::string vendor_public_libraries_;
Jiyong Parke0319942018-01-15 21:14:53 +0900728 std::string oem_public_libraries_;
Inseob Kim67cb0562018-05-04 11:39:12 +0900729 std::string product_public_libraries_;
Jiyong Parka07f3052017-08-22 10:26:10 +0900730 std::string system_llndk_libraries_;
731 std::string system_vndksp_libraries_;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800732
733 DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
734};
735
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800736static std::mutex g_namespaces_mutex;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800737static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
738#endif
739
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700740void InitializeNativeLoader() {
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800741#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800742 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700743 g_namespaces->Initialize();
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800744#endif
745}
746
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700747void ResetNativeLoader() {
748#if defined(__ANDROID__)
749 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
750 g_namespaces->Reset();
751#endif
752}
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800753
Kiyoung Kim4639f692019-02-20 18:04:39 +0900754jstring CreateClassLoaderNamespace(JNIEnv* env, int32_t target_sdk_version, jobject class_loader,
755 bool is_shared, jstring dex_path, jstring library_path,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800756 jstring permitted_path) {
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800757#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800758 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800759
760 std::string error_msg;
Kiyoung Kim4639f692019-02-20 18:04:39 +0900761 bool success = g_namespaces->Create(env, target_sdk_version, class_loader, is_shared, dex_path,
762 library_path, permitted_path, &error_msg) != nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800763 if (!success) {
764 return env->NewStringUTF(error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800765 }
766#else
Kiyoung Kim4639f692019-02-20 18:04:39 +0900767 UNUSED(env, target_sdk_version, class_loader, is_shared, dex_path, library_path, permitted_path);
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800768#endif
769 return nullptr;
770}
771
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000772#if defined(__ANDROID__)
773static android_namespace_t* FindExportedNamespace(const char* caller_location) {
774 std::string location = caller_location;
775 // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
776 // /apex/com.android...modulename/...
777 //
778 // And we extract from it 'modulename', which is the name of the linker namespace.
779 if (android::base::StartsWith(location, kApexPath)) {
780 size_t slash_index = location.find_first_of('/', strlen(kApexPath));
781 LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
782 "Error finding namespace of apex: no slash in path %s", caller_location);
783 size_t dot_index = location.find_last_of('.', slash_index);
784 LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
785 "Error finding namespace of apex: no dot in apex name %s", caller_location);
786 std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
787 android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
788 LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
789 "Error finding namespace of apex: no namespace called %s", name.c_str());
790 return boot_namespace;
791 }
792 return nullptr;
793}
794#endif
795
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000796void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
Nicolas Geoffray53535022019-01-18 10:05:13 +0000797 jobject class_loader, const char* caller_location, jstring library_path,
798 bool* needs_native_bridge, char** error_msg) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800799#if defined(__ANDROID__)
Dimitry Ivanov5539db02016-04-20 16:07:30 -0700800 UNUSED(target_sdk_version);
801 if (class_loader == nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800802 *needs_native_bridge = false;
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000803 if (caller_location != nullptr) {
804 android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
805 if (boot_namespace != nullptr) {
806 const android_dlextinfo dlextinfo = {
807 .flags = ANDROID_DLEXT_USE_NAMESPACE,
808 .library_namespace = boot_namespace,
809 };
810 void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
811 if (handle == nullptr) {
812 *error_msg = strdup(dlerror());
813 }
814 return handle;
815 }
816 }
Pete Bentley632f1422018-12-19 13:33:33 +0000817 void* handle = dlopen(path, RTLD_NOW);
818 if (handle == nullptr) {
Nicolas Geoffrayd06cb942019-01-16 20:20:27 +0000819 *error_msg = strdup(dlerror());
Pete Bentley632f1422018-12-19 13:33:33 +0000820 }
821 return handle;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800822 }
823
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800824 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200825 NativeLoaderNamespace* ns;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800826
Victor Khimenko1443ec42018-07-09 17:01:22 +0200827 if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800828 // This is the case where the classloader was not created by ApplicationLoaders
829 // In this case we create an isolated not-shared namespace for it.
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000830 std::string create_error_msg;
831 if ((ns = g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */,
Kiyoung Kim4639f692019-02-20 18:04:39 +0900832 nullptr, library_path, nullptr, &create_error_msg)) == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000833 *error_msg = strdup(create_error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800834 return nullptr;
835 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800836 }
837
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000838 return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800839#else
Nicolas Geoffray53535022019-01-18 10:05:13 +0000840 UNUSED(env, target_sdk_version, class_loader, caller_location);
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800841
842 // Do some best effort to emulate library-path support. It will not
843 // work for dependencies.
844 //
845 // Note: null has a special meaning and must be preserved.
846 std::string c_library_path; // Empty string by default.
847 if (library_path != nullptr && path != nullptr && path[0] != '/') {
848 ScopedUtfChars library_path_utf_chars(env, library_path);
849 c_library_path = library_path_utf_chars.c_str();
850 }
851
852 std::vector<std::string> library_paths = base::Split(c_library_path, ":");
853
854 for (const std::string& lib_path : library_paths) {
855 *needs_native_bridge = false;
856 const char* path_arg;
857 std::string complete_path;
858 if (path == nullptr) {
859 // Preserve null.
860 path_arg = nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800861 } else {
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800862 complete_path = lib_path;
863 if (!complete_path.empty()) {
864 complete_path.append("/");
865 }
866 complete_path.append(path);
867 path_arg = complete_path.c_str();
868 }
869 void* handle = dlopen(path_arg, RTLD_NOW);
870 if (handle != nullptr) {
871 return handle;
872 }
873 if (NativeBridgeIsSupported(path_arg)) {
874 *needs_native_bridge = true;
875 handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
876 if (handle != nullptr) {
877 return handle;
878 }
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000879 *error_msg = strdup(NativeBridgeGetError());
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800880 } else {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000881 *error_msg = strdup(dlerror());
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800882 }
883 }
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800884 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800885#endif
886}
887
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000888bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
dimitry3150f7c2018-09-12 01:09:19 +0200889 bool success;
890 if (needs_native_bridge) {
891 success = (NativeBridgeUnloadLibrary(handle) == 0);
892 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000893 *error_msg = strdup(NativeBridgeGetError());
dimitry3150f7c2018-09-12 01:09:19 +0200894 }
895 } else {
896 success = (dlclose(handle) == 0);
897 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000898 *error_msg = strdup(dlerror());
dimitry3150f7c2018-09-12 01:09:19 +0200899 }
900 }
901
902 return success;
Dimitry Ivanov09a516b2016-05-03 14:55:25 -0700903}
904
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000905void NativeLoaderFreeErrorMessage(char* msg) {
906 // The error messages get allocated through strdup, so we must call free on them.
907 free(msg);
908}
909
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800910#if defined(__ANDROID__)
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000911void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
912 bool* needs_native_bridge, char** error_msg) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200913 if (ns->is_android_namespace()) {
914 android_dlextinfo extinfo;
915 extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
916 extinfo.library_namespace = ns->get_android_ns();
917
918 void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
919 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000920 *error_msg = strdup(dlerror());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200921 }
922 *needs_native_bridge = false;
923 return handle;
924 } else {
925 void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
926 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000927 *error_msg = strdup(NativeBridgeGetError());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200928 }
929 *needs_native_bridge = true;
930 return handle;
931 }
932}
933
Dimitry Ivanov800083d2016-11-01 14:17:00 -0700934// native_bridge_namespaces are not supported for callers of this function.
935// This function will return nullptr in the case when application is running
936// on native bridge.
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800937android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800938 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200939 NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
940 if (ns != nullptr) {
941 return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800942 }
943
944 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800945}
Victor Khimenko1443ec42018-07-09 17:01:22 +0200946NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
947 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
948 return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
949}
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800950#endif
951
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800952}; // android namespace