blob: 0441bbbb945af48426362c49b774fb05023afc3d [file] [log] [blame]
Jiyong Park6291da22019-04-26 18:55:48 +09001/*
2 * Copyright (C) 2019 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#include "library_namespaces.h"
17
18#include <dirent.h>
19#include <dlfcn.h>
20
21#include <regex>
22#include <string>
23#include <vector>
24
25#include "android-base/file.h"
26#include "android-base/logging.h"
27#include "android-base/macros.h"
28#include "android-base/properties.h"
29#include "android-base/strings.h"
30#include "nativehelper/ScopedUtfChars.h"
31#include "nativeloader/dlext_namespaces.h"
Jiyong Park40a60772019-05-03 16:21:31 +090032#include "public_libraries.h"
Jiyong Parkf8802e52019-05-03 16:34:56 +090033#include "utils.h"
Jiyong Park6291da22019-04-26 18:55:48 +090034
Jiyong Park40a60772019-05-03 16:21:31 +090035namespace android::nativeloader {
Jiyong Park6291da22019-04-26 18:55:48 +090036
37namespace {
Jiyong Park6291da22019-04-26 18:55:48 +090038// The device may be configured to have the vendor libraries loaded to a separate namespace.
39// For historical reasons this namespace was named sphal but effectively it is intended
40// to use to load vendor libraries to separate namespace with controlled interface between
41// vendor and system namespaces.
42constexpr const char* kVendorNamespaceName = "sphal";
43constexpr const char* kVndkNamespaceName = "vndk";
44constexpr const char* kDefaultNamespaceName = "default";
45constexpr const char* kPlatformNamespaceName = "platform";
46constexpr const char* kRuntimeNamespaceName = "runtime";
47
48// classloader-namespace is a linker namespace that is created for the loaded
49// app. To be specific, it is created for the app classloader. When
50// System.load() is called from a Java class that is loaded from the
51// classloader, the classloader-namespace namespace associated with that
52// classloader is selected for dlopen. The namespace is configured so that its
53// search path is set to the app-local JNI directory and it is linked to the
54// platform namespace with the names of libs listed in the public.libraries.txt.
55// This way an app can only load its own JNI libraries along with the public libs.
56constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
57// Same thing for vendor APKs.
58constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
59
60// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
61// System.load() with an absolute path which is outside of the classloader library search path.
62// This list includes all directories app is allowed to access this way.
63constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
64
Jiyong Parkf8802e52019-05-03 16:34:56 +090065constexpr const char* kVendorLibPath = "/vendor/" LIB;
66constexpr const char* kProductLibPath = "/product/" LIB ":/system/product/" LIB;
Jiyong Park6291da22019-04-26 18:55:48 +090067
68const std::regex kVendorDexPathRegex("(^|:)/vendor/");
69const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");
70
71// Define origin of APK if it is from vendor partition or product partition
72typedef enum {
73 APK_ORIGIN_DEFAULT = 0,
74 APK_ORIGIN_VENDOR = 1,
75 APK_ORIGIN_PRODUCT = 2,
76} ApkOrigin;
77
Jiyong Park6291da22019-04-26 18:55:48 +090078jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
79 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
80 jmethodID get_parent =
81 env->GetMethodID(class_loader_class, "getParent", "()Ljava/lang/ClassLoader;");
82
83 return env->CallObjectMethod(class_loader, get_parent);
84}
85
86ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
87 ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
88
89 if (dex_path != nullptr) {
90 ScopedUtfChars dex_path_utf_chars(env, dex_path);
91
92 if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
93 apk_origin = APK_ORIGIN_VENDOR;
94 }
95
96 if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
97 LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
98 "Dex path contains both vendor and product partition : %s",
99 dex_path_utf_chars.c_str());
100
101 apk_origin = APK_ORIGIN_PRODUCT;
102 }
103 }
104 return apk_origin;
105}
106
107} // namespace
108
109void LibraryNamespaces::Initialize() {
110 // Once public namespace is initialized there is no
111 // point in running this code - it will have no effect
112 // on the current list of public libraries.
113 if (initialized_) {
114 return;
115 }
116
Jiyong Park6291da22019-04-26 18:55:48 +0900117 // android_init_namespaces() expects all the public libraries
118 // to be loaded so that they can be found by soname alone.
119 //
120 // TODO(dimitry): this is a bit misleading since we do not know
121 // if the vendor public library is going to be opened from /vendor/lib
122 // we might as well end up loading them from /system/lib or /product/lib
123 // For now we rely on CTS test to catch things like this but
124 // it should probably be addressed in the future.
Jiyong Park40a60772019-05-03 16:21:31 +0900125 for (const auto& soname : android::base::Split(system_public_libraries(), ":")) {
Jiyong Park6291da22019-04-26 18:55:48 +0900126 LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
127 "Error preloading public library %s: %s", soname.c_str(), dlerror());
128 }
Jiyong Park6291da22019-04-26 18:55:48 +0900129}
130
131NativeLoaderNamespace* LibraryNamespaces::Create(JNIEnv* env, uint32_t target_sdk_version,
132 jobject class_loader, bool is_shared,
133 jstring dex_path, jstring java_library_path,
134 jstring java_permitted_path,
135 std::string* error_msg) {
136 std::string library_path; // empty string by default.
137
138 if (java_library_path != nullptr) {
139 ScopedUtfChars library_path_utf_chars(env, java_library_path);
140 library_path = library_path_utf_chars.c_str();
141 }
142
143 ApkOrigin apk_origin = GetApkOriginFromDexPath(env, dex_path);
144
145 // (http://b/27588281) This is a workaround for apps using custom
146 // classloaders and calling System.load() with an absolute path which
147 // is outside of the classloader library search path.
148 //
149 // This part effectively allows such a classloader to access anything
150 // under /data and /mnt/expand
151 std::string permitted_path = kWhitelistedDirectories;
152
153 if (java_permitted_path != nullptr) {
154 ScopedUtfChars path(env, java_permitted_path);
155 if (path.c_str() != nullptr && path.size() > 0) {
156 permitted_path = permitted_path + ":" + path.c_str();
157 }
158 }
159
160 // Initialize the anonymous namespace with the first non-empty library path.
161 if (!library_path.empty() && !initialized_ &&
162 !InitPublicNamespace(library_path.c_str(), error_msg)) {
163 return nullptr;
164 }
165
166 bool found = FindNamespaceByClassLoader(env, class_loader);
167
168 LOG_ALWAYS_FATAL_IF(found, "There is already a namespace associated with this classloader");
169
170 uint64_t namespace_type = ANDROID_NAMESPACE_TYPE_ISOLATED;
171 if (is_shared) {
172 namespace_type |= ANDROID_NAMESPACE_TYPE_SHARED;
173 }
174
175 if (target_sdk_version < 24) {
176 namespace_type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
177 }
178
179 NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
180
181 bool is_native_bridge = false;
182
183 if (parent_ns != nullptr) {
184 is_native_bridge = !parent_ns->is_android_namespace();
185 } else if (!library_path.empty()) {
186 is_native_bridge = NativeBridgeIsPathSupported(library_path.c_str());
187 }
188
Jiyong Park40a60772019-05-03 16:21:31 +0900189 std::string system_exposed_libraries = system_public_libraries();
Jiyong Park6291da22019-04-26 18:55:48 +0900190 const char* namespace_name = kClassloaderNamespaceName;
191 android_namespace_t* vndk_ns = nullptr;
192 if ((apk_origin == APK_ORIGIN_VENDOR ||
193 (apk_origin == APK_ORIGIN_PRODUCT && target_sdk_version > 29)) &&
194 !is_shared) {
195 LOG_FATAL_IF(is_native_bridge,
196 "Unbundled vendor / product apk must not use translated architecture");
197
198 // For vendor / product apks, give access to the vendor / product lib even though
199 // they are treated as unbundled; the libs and apks are still bundled
200 // together in the vendor / product partition.
201 const char* origin_partition;
202 const char* origin_lib_path;
203
204 switch (apk_origin) {
205 case APK_ORIGIN_VENDOR:
206 origin_partition = "vendor";
207 origin_lib_path = kVendorLibPath;
208 break;
209 case APK_ORIGIN_PRODUCT:
210 origin_partition = "product";
211 origin_lib_path = kProductLibPath;
212 break;
213 default:
214 origin_partition = "unknown";
215 origin_lib_path = "";
216 }
217
218 LOG_FATAL_IF(is_native_bridge, "Unbundled %s apk must not use translated architecture",
219 origin_partition);
220
221 library_path = library_path + ":" + origin_lib_path;
222 permitted_path = permitted_path + ":" + origin_lib_path;
223
224 // Also give access to LLNDK libraries since they are available to vendors
Jiyong Park40a60772019-05-03 16:21:31 +0900225 system_exposed_libraries = system_exposed_libraries + ":" + system_llndk_libraries().c_str();
Jiyong Park6291da22019-04-26 18:55:48 +0900226
227 // Give access to VNDK-SP libraries from the 'vndk' namespace.
228 vndk_ns = android_get_exported_namespace(kVndkNamespaceName);
229 if (vndk_ns == nullptr) {
230 ALOGW("Cannot find \"%s\" namespace for %s apks", kVndkNamespaceName, origin_partition);
231 }
232
233 // Different name is useful for debugging
234 namespace_name = kVendorClassloaderNamespaceName;
235 ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
236 origin_partition, library_path.c_str());
237 } else {
238 // oem and product public libraries are NOT available to vendor apks, otherwise it
239 // would be system->vendor violation.
Jiyong Park40a60772019-05-03 16:21:31 +0900240 if (!oem_public_libraries().empty()) {
241 system_exposed_libraries = system_exposed_libraries + ':' + oem_public_libraries();
Jiyong Park6291da22019-04-26 18:55:48 +0900242 }
Jiyong Park40a60772019-05-03 16:21:31 +0900243 if (!product_public_libraries().empty()) {
244 system_exposed_libraries = system_exposed_libraries + ':' + product_public_libraries();
Jiyong Park6291da22019-04-26 18:55:48 +0900245 }
246 }
Jiyong Park40a60772019-05-03 16:21:31 +0900247 std::string runtime_exposed_libraries = runtime_public_libraries();
Jiyong Park6291da22019-04-26 18:55:48 +0900248
249 NativeLoaderNamespace native_loader_ns;
250 if (!is_native_bridge) {
251 // The platform namespace is called "default" for binaries in /system and
252 // "platform" for those in the Runtime APEX. Try "platform" first since
253 // "default" always exists.
254 android_namespace_t* platform_ns = android_get_exported_namespace(kPlatformNamespaceName);
255 if (platform_ns == nullptr) {
256 platform_ns = android_get_exported_namespace(kDefaultNamespaceName);
257 }
258
259 android_namespace_t* android_parent_ns;
260 if (parent_ns != nullptr) {
261 android_parent_ns = parent_ns->get_android_ns();
262 } else {
263 // Fall back to the platform namespace if no parent is found.
264 android_parent_ns = platform_ns;
265 }
266
267 android_namespace_t* ns =
268 android_create_namespace(namespace_name, nullptr, library_path.c_str(), namespace_type,
269 permitted_path.c_str(), android_parent_ns);
270 if (ns == nullptr) {
271 *error_msg = dlerror();
272 return nullptr;
273 }
274
275 // Note that when vendor_ns is not configured this function will return nullptr
276 // and it will result in linking vendor_public_libraries_ to the default namespace
277 // which is expected behavior in this case.
278 android_namespace_t* vendor_ns = android_get_exported_namespace(kVendorNamespaceName);
279
280 android_namespace_t* runtime_ns = android_get_exported_namespace(kRuntimeNamespaceName);
281
282 if (!android_link_namespaces(ns, platform_ns, system_exposed_libraries.c_str())) {
283 *error_msg = dlerror();
284 return nullptr;
285 }
286
287 // Runtime apex does not exist in host, and under certain build conditions.
288 if (runtime_ns != nullptr) {
289 if (!android_link_namespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
290 *error_msg = dlerror();
291 return nullptr;
292 }
293 }
294
Jiyong Park40a60772019-05-03 16:21:31 +0900295 if (vndk_ns != nullptr && !system_vndksp_libraries().empty()) {
Jiyong Park6291da22019-04-26 18:55:48 +0900296 // vendor apks are allowed to use VNDK-SP libraries.
Jiyong Park40a60772019-05-03 16:21:31 +0900297 if (!android_link_namespaces(ns, vndk_ns, system_vndksp_libraries().c_str())) {
Jiyong Park6291da22019-04-26 18:55:48 +0900298 *error_msg = dlerror();
299 return nullptr;
300 }
301 }
302
Jiyong Park40a60772019-05-03 16:21:31 +0900303 if (!vendor_public_libraries().empty()) {
304 if (!android_link_namespaces(ns, vendor_ns, vendor_public_libraries().c_str())) {
Jiyong Park6291da22019-04-26 18:55:48 +0900305 *error_msg = dlerror();
306 return nullptr;
307 }
308 }
309
310 native_loader_ns = NativeLoaderNamespace(ns);
311 } else {
312 // Same functionality as in the branch above, but calling through native bridge.
313
314 native_bridge_namespace_t* platform_ns =
315 NativeBridgeGetExportedNamespace(kPlatformNamespaceName);
316 if (platform_ns == nullptr) {
317 platform_ns = NativeBridgeGetExportedNamespace(kDefaultNamespaceName);
318 }
319
320 native_bridge_namespace_t* native_bridge_parent_namespace;
321 if (parent_ns != nullptr) {
322 native_bridge_parent_namespace = parent_ns->get_native_bridge_ns();
323 } else {
324 native_bridge_parent_namespace = platform_ns;
325 }
326
327 native_bridge_namespace_t* ns =
328 NativeBridgeCreateNamespace(namespace_name, nullptr, library_path.c_str(), namespace_type,
329 permitted_path.c_str(), native_bridge_parent_namespace);
330 if (ns == nullptr) {
331 *error_msg = NativeBridgeGetError();
332 return nullptr;
333 }
334
335 native_bridge_namespace_t* vendor_ns = NativeBridgeGetExportedNamespace(kVendorNamespaceName);
336 native_bridge_namespace_t* runtime_ns = NativeBridgeGetExportedNamespace(kRuntimeNamespaceName);
337
338 if (!NativeBridgeLinkNamespaces(ns, platform_ns, system_exposed_libraries.c_str())) {
339 *error_msg = NativeBridgeGetError();
340 return nullptr;
341 }
342
343 // Runtime apex does not exist in host, and under certain build conditions.
344 if (runtime_ns != nullptr) {
345 if (!NativeBridgeLinkNamespaces(ns, runtime_ns, runtime_exposed_libraries.c_str())) {
346 *error_msg = NativeBridgeGetError();
347 return nullptr;
348 }
349 }
Jiyong Park40a60772019-05-03 16:21:31 +0900350 if (!vendor_public_libraries().empty()) {
351 if (!NativeBridgeLinkNamespaces(ns, vendor_ns, vendor_public_libraries().c_str())) {
Jiyong Park6291da22019-04-26 18:55:48 +0900352 *error_msg = NativeBridgeGetError();
353 return nullptr;
354 }
355 }
356
357 native_loader_ns = NativeLoaderNamespace(ns);
358 }
359
360 namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), native_loader_ns));
361
362 return &(namespaces_.back().second);
363}
364
365NativeLoaderNamespace* LibraryNamespaces::FindNamespaceByClassLoader(JNIEnv* env,
366 jobject class_loader) {
367 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
368 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
369 return env->IsSameObject(value.first, class_loader);
370 });
371 if (it != namespaces_.end()) {
372 return &it->second;
373 }
374
375 return nullptr;
376}
377
378bool LibraryNamespaces::InitPublicNamespace(const char* library_path, std::string* error_msg) {
379 // Ask native bride if this apps library path should be handled by it
380 bool is_native_bridge = NativeBridgeIsPathSupported(library_path);
381
382 // (http://b/25844435) - Some apps call dlopen from generated code (mono jited
383 // code is one example) unknown to linker in which case linker uses anonymous
384 // namespace. The second argument specifies the search path for the anonymous
385 // namespace which is the library_path of the classloader.
Jiyong Park40a60772019-05-03 16:21:31 +0900386 initialized_ = android_init_anonymous_namespace(system_public_libraries().c_str(),
Jiyong Park6291da22019-04-26 18:55:48 +0900387 is_native_bridge ? nullptr : library_path);
388 if (!initialized_) {
389 *error_msg = dlerror();
390 return false;
391 }
392
393 // and now initialize native bridge namespaces if necessary.
394 if (NativeBridgeInitialized()) {
Jiyong Park40a60772019-05-03 16:21:31 +0900395 initialized_ = NativeBridgeInitAnonymousNamespace(system_public_libraries().c_str(),
Jiyong Park6291da22019-04-26 18:55:48 +0900396 is_native_bridge ? library_path : nullptr);
397 if (!initialized_) {
398 *error_msg = NativeBridgeGetError();
399 }
400 }
401
402 return initialized_;
403}
404
405NativeLoaderNamespace* LibraryNamespaces::FindParentNamespaceByClassLoader(JNIEnv* env,
406 jobject class_loader) {
407 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
408
409 while (parent_class_loader != nullptr) {
410 NativeLoaderNamespace* ns;
411 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
412 return ns;
413 }
414
415 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
416 }
417
418 return nullptr;
419}
420
Jiyong Park40a60772019-05-03 16:21:31 +0900421} // namespace android::nativeloader