blob: 6666937b44333a083ccaef96d980d57df77b02ab [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 Stjernholm4ca0ca62019-04-25 16:20:32 +0100129// platform 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
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 Kim23ff8eb2019-03-21 16:56:05 +0900291 if (vndk_ns == nullptr) {
292 ALOGW("Cannot find \"%s\" namespace for %s apks", kVndkNamespaceName, origin_partition);
293 }
Jiyong Parka07f3052017-08-22 10:26:10 +0900294
295 // Different name is useful for debugging
296 namespace_name = kVendorClassloaderNamespaceName;
Kiyoung Kim4639f692019-02-20 18:04:39 +0900297 ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
298 origin_partition, library_path.c_str());
Inseob Kim67cb0562018-05-04 11:39:12 +0900299 } else {
300 // oem and product public libraries are NOT available to vendor apks, otherwise it
Jiyong Parke0319942018-01-15 21:14:53 +0900301 // would be system->vendor violation.
Inseob Kim67cb0562018-05-04 11:39:12 +0900302 if (!oem_public_libraries_.empty()) {
303 system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries_;
304 }
305 if (!product_public_libraries_.empty()) {
306 system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries_;
307 }
Jiyong Parka07f3052017-08-22 10:26:10 +0900308 }
309
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100310 std::string runtime_exposed_libraries = runtime_public_libraries_;
Victor Chang7a20a902019-01-28 18:43:24 +0000311
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800312 NativeLoaderNamespace native_loader_ns;
313 if (!is_native_bridge) {
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100314 // The platform namespace is called "default" for binaries in /system and
315 // "platform" for those in the Runtime APEX. Try "platform" first since
316 // "default" always exists.
317 android_namespace_t* platform_ns = android_get_exported_namespace(kPlatformNamespaceName);
318 if (platform_ns == nullptr) {
319 platform_ns = android_get_exported_namespace(kDefaultNamespaceName);
320 }
321
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000322 android_namespace_t* android_parent_ns;
323 if (parent_ns != nullptr) {
324 android_parent_ns = parent_ns->get_android_ns();
325 } else {
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100326 // Fall back to the platform namespace if no parent is found.
327 android_parent_ns = platform_ns;
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000328 }
329
Jiyong Parka07f3052017-08-22 10:26:10 +0900330 android_namespace_t* ns = android_create_namespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800331 nullptr,
332 library_path.c_str(),
333 namespace_type,
334 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200335 android_parent_ns);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800336 if (ns == nullptr) {
337 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200338 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800339 }
340
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700341 // Note that when vendor_ns is not configured this function will return nullptr
342 // and it will result in linking vendor_public_libraries_ to the default namespace
343 // which is expected behavior in this case.
344 android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
345
Victor Chang7a20a902019-01-28 18:43:24 +0000346 android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
347
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100348 if (!android_link_namespaces(ns, platform_ns, system_exposed_libraries.c_str())) {
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800349 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200350 return nullptr;
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800351 }
352
Victor Chang7a20a902019-01-28 18:43:24 +0000353 // Runtime apex does not exist in host, and under certain build conditions.
354 if (runtime_ns != nullptr) {
355 if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
356 *error_msg = dlerror();
357 return nullptr;
358 }
359 }
360
Jiyong Parka07f3052017-08-22 10:26:10 +0900361 if (vndk_ns != nullptr && !system_vndksp_libraries_.empty()) {
362 // vendor apks are allowed to use VNDK-SP libraries.
363 if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries_.c_str())) {
364 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200365 return nullptr;
Jiyong Parka07f3052017-08-22 10:26:10 +0900366 }
367 }
368
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700369 if (!vendor_public_libraries_.empty()) {
370 if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
371 *error_msg = dlerror();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200372 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700373 }
374 }
375
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800376 native_loader_ns = NativeLoaderNamespace(ns);
377 } else {
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100378 // Same functionality as in the branch above, but calling through native bridge.
379
380 native_bridge_namespace_t* platform_ns =
381 NativeBridgeGetExportedNamespace(kPlatformNamespaceName);
382 if (platform_ns == nullptr) {
383 platform_ns = NativeBridgeGetExportedNamespace(kDefaultNamespaceName);
384 }
385
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000386 native_bridge_namespace_t* native_bridge_parent_namespace;
387 if (parent_ns != nullptr) {
388 native_bridge_parent_namespace = parent_ns->get_native_bridge_ns();
389 } else {
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100390 native_bridge_parent_namespace = platform_ns;
Martin Stjernholm7888b5c2019-02-23 02:10:14 +0000391 }
392
Jiyong Parka07f3052017-08-22 10:26:10 +0900393 native_bridge_namespace_t* ns = NativeBridgeCreateNamespace(namespace_name,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800394 nullptr,
395 library_path.c_str(),
396 namespace_type,
397 permitted_path.c_str(),
Victor Khimenko1443ec42018-07-09 17:01:22 +0200398 native_bridge_parent_namespace);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800399 if (ns == nullptr) {
400 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200401 return nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800402 }
403
dimitryd2ace382019-02-04 15:06:43 +0100404 native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
Victor Chang7a20a902019-01-28 18:43:24 +0000405 native_bridge_namespace_t* runtime_ns =
406 NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700407
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100408 if (!NativeBridgeLinkNamespaces(ns, platform_ns, system_exposed_libraries.c_str())) {
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800409 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200410 return nullptr;
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800411 }
412
Victor Chang7a20a902019-01-28 18:43:24 +0000413 // Runtime apex does not exist in host, and under certain build conditions.
414 if (runtime_ns != nullptr) {
415 if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
416 *error_msg = NativeBridgeGetError();
417 return nullptr;
418 }
419 }
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700420 if (!vendor_public_libraries_.empty()) {
421 if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries_.c_str())) {
422 *error_msg = NativeBridgeGetError();
Victor Khimenko1443ec42018-07-09 17:01:22 +0200423 return nullptr;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700424 }
425 }
426
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800427 native_loader_ns = NativeLoaderNamespace(ns);
428 }
429
430 namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
431
Victor Khimenko1443ec42018-07-09 17:01:22 +0200432 return &(namespaces_.back().second);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800433 }
434
Victor Khimenko1443ec42018-07-09 17:01:22 +0200435 NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800436 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800437 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800438 return env->IsSameObject(value.first, class_loader);
439 });
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800440 if (it != namespaces_.end()) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200441 return &it->second;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800442 }
443
Victor Khimenko1443ec42018-07-09 17:01:22 +0200444 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800445 }
446
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700447 void Initialize() {
Dimitry Ivanov80ddb8f2016-05-09 18:12:00 -0700448 // Once public namespace is initialized there is no
449 // point in running this code - it will have no effect
450 // on the current list of public libraries.
451 if (initialized_) {
452 return;
453 }
454
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700455 std::vector<std::string> sonames;
Dimitry Ivanov0b5651e2016-04-21 16:42:48 -0700456 const char* android_root_env = getenv("ANDROID_ROOT");
457 std::string root_dir = android_root_env != nullptr ? android_root_env : "/system";
458 std::string public_native_libraries_system_config =
459 root_dir + kPublicNativeLibrariesSystemConfigPathFromRoot;
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100460 std::string runtime_public_libraries = base::Join(kRuntimePublicLibraries, ":");
Jiyong Parka07f3052017-08-22 10:26:10 +0900461 std::string llndk_native_libraries_system_config =
462 root_dir + kLlndkNativeLibrariesSystemConfigPathFromRoot;
463 std::string vndksp_native_libraries_system_config =
464 root_dir + kVndkspNativeLibrariesSystemConfigPathFromRoot;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700465
Inseob Kim67cb0562018-05-04 11:39:12 +0900466 std::string product_public_native_libraries_dir = "/product/etc";
467
Christopher Ferris39da84b2016-06-21 16:11:23 -0700468 std::string error_msg;
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900469 LOG_ALWAYS_FATAL_IF(
470 !ReadConfig(public_native_libraries_system_config, &sonames, always_true, &error_msg),
471 "Error reading public native library list from \"%s\": %s",
472 public_native_libraries_system_config.c_str(), error_msg.c_str());
473
Jiyong Parke0319942018-01-15 21:14:53 +0900474 // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
475 // variable to add libraries to the list. This is intended for platform tests only.
476 if (is_debuggable()) {
477 const char* additional_libs = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
478 if (additional_libs != nullptr && additional_libs[0] != '\0') {
479 std::vector<std::string> additional_libs_vector = base::Split(additional_libs, ":");
480 std::copy(additional_libs_vector.begin(), additional_libs_vector.end(),
481 std::back_inserter(sonames));
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100482 // Apply the same list to the runtime namespace, since some libraries
483 // might reside there.
484 CHECK(sizeof(kRuntimePublicLibraries) > 0);
485 runtime_public_libraries = runtime_public_libraries + ':' + additional_libs;
Jiyong Parke0319942018-01-15 21:14:53 +0900486 }
487 }
488
Victor Changf70a2fe2019-02-01 20:01:27 +0000489 // Remove the public libs in the runtime namespace.
490 // These libs are listed in public.android.txt, but we don't want the rest of android
491 // in default namespace to dlopen the libs.
492 // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
493 // Unfortunately, it does not have stable C symbols, and default namespace should only use
494 // stable symbols in libandroidicu.so. http://b/120786417
495 removePublicLibsIfExistsInRuntimeApex(sonames);
496
Jiyong Parke0319942018-01-15 21:14:53 +0900497 // android_init_namespaces() expects all the public libraries
498 // to be loaded so that they can be found by soname alone.
499 //
500 // TODO(dimitry): this is a bit misleading since we do not know
501 // if the vendor public library is going to be opened from /vendor/lib
Inseob Kim67cb0562018-05-04 11:39:12 +0900502 // we might as well end up loading them from /system/lib or /product/lib
Jiyong Parke0319942018-01-15 21:14:53 +0900503 // For now we rely on CTS test to catch things like this but
504 // it should probably be addressed in the future.
505 for (const auto& soname : sonames) {
506 LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
507 "Error preloading public library %s: %s", soname.c_str(), dlerror());
508 }
509
510 system_public_libraries_ = base::Join(sonames, ':');
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100511 runtime_public_libraries_ = runtime_public_libraries;
Jiyong Parke0319942018-01-15 21:14:53 +0900512
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900513 // read /system/etc/public.libraries-<companyname>.txt which contain partner defined
514 // system libs that are exposed to apps. The libs in the txt files must be
515 // named as lib<name>.<companyname>.so.
Jiyong Parke0319942018-01-15 21:14:53 +0900516 sonames.clear();
Inseob Kim67cb0562018-05-04 11:39:12 +0900517 ReadExtensionLibraries(base::Dirname(public_native_libraries_system_config).c_str(), &sonames);
Jiyong Parke0319942018-01-15 21:14:53 +0900518 oem_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanov7d028292016-05-05 17:30:24 -0700519
Inseob Kim67cb0562018-05-04 11:39:12 +0900520 // read /product/etc/public.libraries-<companyname>.txt which contain partner defined
521 // product libs that are exposed to apps.
522 sonames.clear();
523 ReadExtensionLibraries(product_public_native_libraries_dir.c_str(), &sonames);
524 product_public_libraries_ = base::Join(sonames, ':');
525
Justin Yun4a1d1102017-11-27 17:04:14 +0900526 // Insert VNDK version to llndk and vndksp config file names.
527 insert_vndk_version_str(&llndk_native_libraries_system_config);
528 insert_vndk_version_str(&vndksp_native_libraries_system_config);
529
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700530 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900531 ReadConfig(llndk_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900532 system_llndk_libraries_ = base::Join(sonames, ':');
533
534 sonames.clear();
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900535 ReadConfig(vndksp_native_libraries_system_config, &sonames, always_true);
Jiyong Parka07f3052017-08-22 10:26:10 +0900536 system_vndksp_libraries_ = base::Join(sonames, ':');
537
538 sonames.clear();
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700539 // This file is optional, quietly ignore if the file does not exist.
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900540 ReadConfig(kPublicNativeLibrariesVendorConfig, &sonames, always_true, nullptr);
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700541
542 vendor_public_libraries_ = base::Join(sonames, ':');
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700543 }
544
Inseob Kim67cb0562018-05-04 11:39:12 +0900545 void Reset() { namespaces_.clear(); }
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700546
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700547 private:
Inseob Kim67cb0562018-05-04 11:39:12 +0900548 void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
549 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
550 if (dir != nullptr) {
551 // Failing to opening the dir is not an error, which can happen in
552 // webview_zygote.
553 while (struct dirent* ent = readdir(dir.get())) {
554 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
555 continue;
556 }
557 const std::string filename(ent->d_name);
558 if (android::base::StartsWith(filename, kPublicNativeLibrariesExtensionConfigPrefix) &&
559 android::base::EndsWith(filename, kPublicNativeLibrariesExtensionConfigSuffix)) {
560 const size_t start = kPublicNativeLibrariesExtensionConfigPrefixLen;
561 const size_t end = filename.size() - kPublicNativeLibrariesExtensionConfigSuffixLen;
562 const std::string company_name = filename.substr(start, end - start);
563 const std::string config_file_path = dirname + "/"s + filename;
564 LOG_ALWAYS_FATAL_IF(
565 company_name.empty(),
566 "Error extracting company name from public native library list file path \"%s\"",
567 config_file_path.c_str());
568
569 std::string error_msg;
570
571 LOG_ALWAYS_FATAL_IF(
572 !ReadConfig(
573 config_file_path, sonames,
574 [&company_name](const std::string& soname, std::string* error_msg) {
575 if (android::base::StartsWith(soname, "lib") &&
576 android::base::EndsWith(soname, "." + company_name + ".so")) {
577 return true;
578 } else {
579 *error_msg = "Library name \"" + soname +
580 "\" does not end with the company name: " + company_name + ".";
581 return false;
582 }
583 },
584 &error_msg),
585 "Error reading public native library list from \"%s\": %s", config_file_path.c_str(),
586 error_msg.c_str());
587 }
588 }
589 }
590 }
591
Victor Changf70a2fe2019-02-01 20:01:27 +0000592 /**
593 * Remove the public libs in runtime namespace
594 */
595 void removePublicLibsIfExistsInRuntimeApex(std::vector<std::string>& sonames) {
596 for (const std::string& lib_name : kRuntimePublicLibraries) {
597 std::string path(kRuntimeApexLibPath);
598 path.append("/").append(lib_name);
599
600 struct stat s;
601 // Do nothing if the path in /apex does not exist.
602 // Runtime APEX must be mounted since libnativeloader is in the same APEX
603 if (stat(path.c_str(), &s) != 0) {
604 continue;
605 }
606
607 auto it = std::find(sonames.begin(), sonames.end(), lib_name);
608 if (it != sonames.end()) {
609 sonames.erase(it);
610 }
611 }
612 }
Inseob Kim67cb0562018-05-04 11:39:12 +0900613
Christopher Ferris39da84b2016-06-21 16:11:23 -0700614 bool ReadConfig(const std::string& configFile, std::vector<std::string>* sonames,
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900615 const std::function<bool(const std::string& /* soname */,
616 std::string* /* error_msg */)>& check_soname,
Christopher Ferris39da84b2016-06-21 16:11:23 -0700617 std::string* error_msg = nullptr) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700618 // Read list of public native libraries from the config file.
619 std::string file_content;
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700620 if(!base::ReadFileToString(configFile, &file_content)) {
Christopher Ferris39da84b2016-06-21 16:11:23 -0700621 if (error_msg) *error_msg = strerror(errno);
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700622 return false;
623 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700624
625 std::vector<std::string> lines = base::Split(file_content, "\n");
626
Christopher Ferris39da84b2016-06-21 16:11:23 -0700627 for (auto& line : lines) {
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700628 auto trimmed_line = base::Trim(line);
629 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
630 continue;
631 }
Christopher Ferris39da84b2016-06-21 16:11:23 -0700632 size_t space_pos = trimmed_line.rfind(' ');
633 if (space_pos != std::string::npos) {
634 std::string type = trimmed_line.substr(space_pos + 1);
635 if (type != "32" && type != "64") {
636 if (error_msg) *error_msg = "Malformed line: " + line;
637 return false;
638 }
639#if defined(__LP64__)
640 // Skip 32 bit public library.
641 if (type == "32") {
642 continue;
643 }
644#else
645 // Skip 64 bit public library.
646 if (type == "64") {
647 continue;
648 }
649#endif
650 trimmed_line.resize(space_pos);
651 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700652
Jiyong Parkd1006fe2017-11-08 18:44:09 +0900653 if (check_soname(trimmed_line, error_msg)) {
654 sonames->push_back(trimmed_line);
655 } else {
656 return false;
657 }
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700658 }
659
Dimitry Ivanovb6140452016-04-06 18:24:08 -0700660 return true;
Dimitry Ivanovd68c8e92016-02-10 14:09:22 -0800661 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800662
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800663 bool InitPublicNamespace(const char* library_path, std::string* error_msg) {
664 // Ask native bride if this apps library path should be handled by it
665 bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
666
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700667 // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
668 // code is one example) unknown to linker in which case linker uses anonymous
669 // namespace. The second argument specifies the search path for the anonymous
670 // namespace which is the library_path of the classloader.
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700671 initialized_ = android_init_anonymous_namespace(system_public_libraries_.c_str(),
Dimitry Ivanov26e1a842017-02-03 14:11:27 -0800672 is_native_bridge ? nullptr : library_path);
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700673 if (!initialized_) {
674 *error_msg = dlerror();
675 return false;
676 }
677
678 // and now initialize native bridge namespaces if necessary.
679 if (NativeBridgeInitialized()) {
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700680 initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries_.c_str(),
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800681 is_native_bridge ? library_path : nullptr);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800682 if (!initialized_) {
683 *error_msg = NativeBridgeGetError();
684 }
685 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800686
687 return initialized_;
688 }
689
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700690 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
691 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
692 jmethodID get_parent = env->GetMethodID(class_loader_class,
693 "getParent",
694 "()Ljava/lang/ClassLoader;");
695
696 return env->CallObjectMethod(class_loader, get_parent);
697 }
698
Victor Khimenko1443ec42018-07-09 17:01:22 +0200699 NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700700 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
701
702 while (parent_class_loader != nullptr) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200703 NativeLoaderNamespace* ns;
704 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
705 return ns;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700706 }
707
708 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
709 }
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800710
Victor Khimenko1443ec42018-07-09 17:01:22 +0200711 return nullptr;
Dimitry Ivanov24db75c2016-05-12 15:34:41 -0700712 }
713
Kiyoung Kim4639f692019-02-20 18:04:39 +0900714 ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
715 ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
716
717 if (dex_path != nullptr) {
718 ScopedUtfChars dex_path_utf_chars(env, dex_path);
719
720 if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
721 apk_origin = APK_ORIGIN_VENDOR;
722 }
723
724 if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
725 LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
726 "Dex path contains both vendor and product partition : %s",
727 dex_path_utf_chars.c_str());
728
729 apk_origin = APK_ORIGIN_PRODUCT;
730 }
731 }
732
733 return apk_origin;
734 }
735
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800736 bool initialized_;
Victor Khimenko1443ec42018-07-09 17:01:22 +0200737 std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700738 std::string system_public_libraries_;
Martin Stjernholm4ca0ca62019-04-25 16:20:32 +0100739 std::string runtime_public_libraries_;
Dimitry Ivanov882cad22017-05-01 15:12:49 -0700740 std::string vendor_public_libraries_;
Jiyong Parke0319942018-01-15 21:14:53 +0900741 std::string oem_public_libraries_;
Inseob Kim67cb0562018-05-04 11:39:12 +0900742 std::string product_public_libraries_;
Jiyong Parka07f3052017-08-22 10:26:10 +0900743 std::string system_llndk_libraries_;
744 std::string system_vndksp_libraries_;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800745
746 DISALLOW_COPY_AND_ASSIGN(LibraryNamespaces);
747};
748
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800749static std::mutex g_namespaces_mutex;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800750static LibraryNamespaces* g_namespaces = new LibraryNamespaces;
751#endif
752
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700753void InitializeNativeLoader() {
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800754#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800755 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Dimitry Ivanov4b0e9632016-03-15 13:51:26 -0700756 g_namespaces->Initialize();
Dimitry Ivanov426799d2016-02-22 11:27:48 -0800757#endif
758}
759
Dimitry Ivanovbe4ca3a2016-05-02 10:43:16 -0700760void ResetNativeLoader() {
761#if defined(__ANDROID__)
762 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
763 g_namespaces->Reset();
764#endif
765}
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800766
Kiyoung Kim4639f692019-02-20 18:04:39 +0900767jstring CreateClassLoaderNamespace(JNIEnv* env, int32_t target_sdk_version, jobject class_loader,
768 bool is_shared, jstring dex_path, jstring library_path,
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800769 jstring permitted_path) {
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800770#if defined(__ANDROID__)
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800771 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800772
773 std::string error_msg;
Kiyoung Kim4639f692019-02-20 18:04:39 +0900774 bool success = g_namespaces->Create(env, target_sdk_version, class_loader, is_shared, dex_path,
775 library_path, permitted_path, &error_msg) != nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800776 if (!success) {
777 return env->NewStringUTF(error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800778 }
779#else
Kiyoung Kim4639f692019-02-20 18:04:39 +0900780 UNUSED(env, target_sdk_version, class_loader, is_shared, dex_path, library_path, permitted_path);
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800781#endif
782 return nullptr;
783}
784
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000785#if defined(__ANDROID__)
786static android_namespace_t* FindExportedNamespace(const char* caller_location) {
787 std::string location = caller_location;
788 // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
789 // /apex/com.android...modulename/...
790 //
791 // And we extract from it 'modulename', which is the name of the linker namespace.
792 if (android::base::StartsWith(location, kApexPath)) {
793 size_t slash_index = location.find_first_of('/', strlen(kApexPath));
794 LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
795 "Error finding namespace of apex: no slash in path %s", caller_location);
796 size_t dot_index = location.find_last_of('.', slash_index);
797 LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
798 "Error finding namespace of apex: no dot in apex name %s", caller_location);
799 std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
800 android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
801 LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
802 "Error finding namespace of apex: no namespace called %s", name.c_str());
803 return boot_namespace;
804 }
805 return nullptr;
806}
807#endif
808
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000809void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
Nicolas Geoffray53535022019-01-18 10:05:13 +0000810 jobject class_loader, const char* caller_location, jstring library_path,
811 bool* needs_native_bridge, char** error_msg) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800812#if defined(__ANDROID__)
Dimitry Ivanov5539db02016-04-20 16:07:30 -0700813 UNUSED(target_sdk_version);
814 if (class_loader == nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800815 *needs_native_bridge = false;
Nicolas Geoffray890e3bf2019-01-22 09:11:57 +0000816 if (caller_location != nullptr) {
817 android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
818 if (boot_namespace != nullptr) {
819 const android_dlextinfo dlextinfo = {
820 .flags = ANDROID_DLEXT_USE_NAMESPACE,
821 .library_namespace = boot_namespace,
822 };
823 void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
824 if (handle == nullptr) {
825 *error_msg = strdup(dlerror());
826 }
827 return handle;
828 }
829 }
Pete Bentley632f1422018-12-19 13:33:33 +0000830 void* handle = dlopen(path, RTLD_NOW);
831 if (handle == nullptr) {
Nicolas Geoffrayd06cb942019-01-16 20:20:27 +0000832 *error_msg = strdup(dlerror());
Pete Bentley632f1422018-12-19 13:33:33 +0000833 }
834 return handle;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800835 }
836
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800837 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200838 NativeLoaderNamespace* ns;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800839
Victor Khimenko1443ec42018-07-09 17:01:22 +0200840 if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800841 // This is the case where the classloader was not created by ApplicationLoaders
842 // In this case we create an isolated not-shared namespace for it.
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000843 std::string create_error_msg;
844 if ((ns = g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */,
Kiyoung Kim4639f692019-02-20 18:04:39 +0900845 nullptr, library_path, nullptr, &create_error_msg)) == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000846 *error_msg = strdup(create_error_msg.c_str());
Dimitry Ivanovd047c922016-02-23 14:23:51 -0800847 return nullptr;
848 }
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800849 }
850
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000851 return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800852#else
Nicolas Geoffray53535022019-01-18 10:05:13 +0000853 UNUSED(env, target_sdk_version, class_loader, caller_location);
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800854
855 // Do some best effort to emulate library-path support. It will not
856 // work for dependencies.
857 //
858 // Note: null has a special meaning and must be preserved.
859 std::string c_library_path; // Empty string by default.
860 if (library_path != nullptr && path != nullptr && path[0] != '/') {
861 ScopedUtfChars library_path_utf_chars(env, library_path);
862 c_library_path = library_path_utf_chars.c_str();
863 }
864
865 std::vector<std::string> library_paths = base::Split(c_library_path, ":");
866
867 for (const std::string& lib_path : library_paths) {
868 *needs_native_bridge = false;
869 const char* path_arg;
870 std::string complete_path;
871 if (path == nullptr) {
872 // Preserve null.
873 path_arg = nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800874 } else {
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800875 complete_path = lib_path;
876 if (!complete_path.empty()) {
877 complete_path.append("/");
878 }
879 complete_path.append(path);
880 path_arg = complete_path.c_str();
881 }
882 void* handle = dlopen(path_arg, RTLD_NOW);
883 if (handle != nullptr) {
884 return handle;
885 }
886 if (NativeBridgeIsSupported(path_arg)) {
887 *needs_native_bridge = true;
888 handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
889 if (handle != nullptr) {
890 return handle;
891 }
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000892 *error_msg = strdup(NativeBridgeGetError());
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800893 } else {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000894 *error_msg = strdup(dlerror());
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800895 }
896 }
Andreas Gampe5c7d5822017-12-28 19:08:13 -0800897 return nullptr;
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800898#endif
899}
900
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000901bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
dimitry3150f7c2018-09-12 01:09:19 +0200902 bool success;
903 if (needs_native_bridge) {
904 success = (NativeBridgeUnloadLibrary(handle) == 0);
905 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000906 *error_msg = strdup(NativeBridgeGetError());
dimitry3150f7c2018-09-12 01:09:19 +0200907 }
908 } else {
909 success = (dlclose(handle) == 0);
910 if (!success) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000911 *error_msg = strdup(dlerror());
dimitry3150f7c2018-09-12 01:09:19 +0200912 }
913 }
914
915 return success;
Dimitry Ivanov09a516b2016-05-03 14:55:25 -0700916}
917
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000918void NativeLoaderFreeErrorMessage(char* msg) {
919 // The error messages get allocated through strdup, so we must call free on them.
920 free(msg);
921}
922
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800923#if defined(__ANDROID__)
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000924void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
925 bool* needs_native_bridge, char** error_msg) {
Victor Khimenko1443ec42018-07-09 17:01:22 +0200926 if (ns->is_android_namespace()) {
927 android_dlextinfo extinfo;
928 extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
929 extinfo.library_namespace = ns->get_android_ns();
930
931 void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
932 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000933 *error_msg = strdup(dlerror());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200934 }
935 *needs_native_bridge = false;
936 return handle;
937 } else {
938 void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns->get_native_bridge_ns());
939 if (handle == nullptr) {
Nicolas Geoffrayc3a73dc2019-01-12 15:01:20 +0000940 *error_msg = strdup(NativeBridgeGetError());
Victor Khimenko1443ec42018-07-09 17:01:22 +0200941 }
942 *needs_native_bridge = true;
943 return handle;
944 }
945}
946
Dimitry Ivanov800083d2016-11-01 14:17:00 -0700947// native_bridge_namespaces are not supported for callers of this function.
948// This function will return nullptr in the case when application is running
949// on native bridge.
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800950android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
Dimitry Ivanov34d5a202016-02-29 13:21:43 -0800951 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
Victor Khimenko1443ec42018-07-09 17:01:22 +0200952 NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
953 if (ns != nullptr) {
954 return ns->is_android_namespace() ? ns->get_android_ns() : nullptr;
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800955 }
956
957 return nullptr;
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800958}
Victor Khimenko1443ec42018-07-09 17:01:22 +0200959NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
960 std::lock_guard<std::mutex> guard(g_namespaces_mutex);
961 return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
962}
Dimitry Ivanovf44ecde2016-02-22 13:48:22 -0800963#endif
964
Dimitry Ivanovac1b1912015-12-01 13:56:44 -0800965}; // android namespace