1 /*
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
17 #if defined(ART_TARGET_ANDROID)
18
19 #include "library_namespaces.h"
20
21 #include <dirent.h>
22 #include <dlfcn.h>
23
24 #include <regex>
25 #include <string>
26 #include <vector>
27
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/macros.h>
31 #include <android-base/result.h>
32 #include <android-base/strings.h>
33 #include <android-base/stringprintf.h>
34 #include <nativehelper/scoped_utf_chars.h>
35
36 #include "nativeloader/dlext_namespaces.h"
37 #include "public_libraries.h"
38 #include "utils.h"
39
40 namespace android::nativeloader {
41
42 namespace {
43
44 constexpr const char* kApexPath = "/apex/";
45
46 // The device may be configured to have the vendor libraries loaded to a separate namespace.
47 // For historical reasons this namespace was named sphal but effectively it is intended
48 // to use to load vendor libraries to separate namespace with controlled interface between
49 // vendor and system namespaces.
50 constexpr const char* kVendorNamespaceName = "sphal";
51 // Similar to sphal namespace, product namespace provides some product libraries.
52 constexpr const char* kProductNamespaceName = "product";
53
54 // vndk namespace for unbundled vendor apps
55 constexpr const char* kVndkNamespaceName = "vndk";
56 // vndk_product namespace for unbundled product apps
57 constexpr const char* kVndkProductNamespaceName = "vndk_product";
58
59 // clns-XX is a linker namespace that is created for normal apps installed in
60 // the data partition. To be specific, it is created for the app classloader.
61 // When System.load() is called from a Java class that is loaded from the
62 // classloader, the clns namespace associated with that classloader is selected
63 // for dlopen. The namespace is configured so that its search path is set to the
64 // app-local JNI directory and it is linked to the system namespace with the
65 // names of libs listed in the public.libraries.txt and other public libraries.
66 // This way an app can only load its own JNI libraries along with the public
67 // libs.
68 constexpr const char* kClassloaderNamespaceName = "clns";
69 // Same thing for unbundled APKs in the vendor partition.
70 constexpr const char* kVendorClassloaderNamespaceName = "vendor-clns";
71 // Same thing for unbundled APKs in the product partition.
72 constexpr const char* kProductClassloaderNamespaceName = "product-clns";
73 // If the namespace is shared then add this suffix to help identify it in debug
74 // messages. A shared namespace (cf. ANDROID_NAMESPACE_TYPE_SHARED) has
75 // inherited all the libraries of the parent classloader namespace, or the
76 // system namespace for the main app classloader. It is used to give full access
77 // to the platform libraries for apps bundled in the system image, including
78 // their later updates installed in /data.
79 constexpr const char* kSharedNamespaceSuffix = "-shared";
80
81 // (http://b/27588281) This is a workaround for apps using custom classloaders and calling
82 // System.load() with an absolute path which is outside of the classloader library search path.
83 // This list includes all directories app is allowed to access this way.
84 constexpr const char* kAlwaysPermittedDirectories = "/data:/mnt/expand";
85
86 constexpr const char* kVendorLibPath = "/vendor/" LIB;
87 // TODO(mast): It's unlikely that both paths are necessary for kProductLibPath
88 // below, because they can't be two separate directories - either one has to be
89 // a symlink to the other.
90 constexpr const char* kProductLibPath = "/product/" LIB ":/system/product/" LIB;
91
92 const std::regex kVendorDexPathRegex("(^|:)(/system)?/vendor/");
93 const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");
94
95 // Define origin partition of APK
96 using ApkOrigin = enum {
97 APK_ORIGIN_DEFAULT = 0,
98 APK_ORIGIN_VENDOR = 1, // Includes both /vendor and /system/vendor
99 APK_ORIGIN_PRODUCT = 2, // Includes both /product and /system/product
100 };
101
GetParentClassLoader(JNIEnv * env,jobject class_loader)102 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
103 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
104 jmethodID get_parent =
105 env->GetMethodID(class_loader_class, "getParent", "()Ljava/lang/ClassLoader;");
106
107 return env->CallObjectMethod(class_loader, get_parent);
108 }
109
GetApkOriginFromDexPath(const std::string & dex_path)110 ApkOrigin GetApkOriginFromDexPath(const std::string& dex_path) {
111 ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
112 if (std::regex_search(dex_path, kVendorDexPathRegex)) {
113 apk_origin = APK_ORIGIN_VENDOR;
114 }
115 if (std::regex_search(dex_path, kProductDexPathRegex)) {
116 LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
117 "Dex path contains both vendor and product partition : %s",
118 dex_path.c_str());
119
120 apk_origin = APK_ORIGIN_PRODUCT;
121 }
122 return apk_origin;
123 }
124
125 } // namespace
126
Initialize()127 void LibraryNamespaces::Initialize() {
128 // Once public namespace is initialized there is no
129 // point in running this code - it will have no effect
130 // on the current list of public libraries.
131 if (initialized_) {
132 return;
133 }
134
135 // Load the preloadable public libraries. Since libnativeloader is in the
136 // com_android_art namespace, use OpenSystemLibrary rather than dlopen to
137 // ensure the libraries are loaded in the system namespace.
138 //
139 // TODO(dimitry): this is a bit misleading since we do not know
140 // if the vendor public library is going to be opened from /vendor/lib
141 // we might as well end up loading them from /system/lib or /product/lib
142 // For now we rely on CTS test to catch things like this but
143 // it should probably be addressed in the future.
144 for (const std::string& soname : android::base::Split(preloadable_public_libraries(), ":")) {
145 void* handle = OpenSystemLibrary(soname.c_str(), RTLD_NOW | RTLD_NODELETE);
146 LOG_ALWAYS_FATAL_IF(handle == nullptr,
147 "Error preloading public library %s: %s", soname.c_str(), dlerror());
148 }
149 }
150
151 // "ALL" is a magic name that allows all public libraries even when the
152 // target SDK is > 30. Currently this is used for (Java) shared libraries
153 // which don't use <uses-native-library>
154 // TODO(b/142191088) remove this hack
155 static constexpr const char LIBRARY_ALL[] = "ALL";
156
157 // Returns the colon-separated list of library names by filtering uses_libraries from
158 // public_libraries. The returned names will actually be available to the app. If the app is pre-S
159 // (<= 30), the filtering is not done; the entire public_libraries are provided.
filter_public_libraries(uint32_t target_sdk_version,const std::vector<std::string> & uses_libraries,const std::string & public_libraries)160 static const std::string filter_public_libraries(
161 uint32_t target_sdk_version, const std::vector<std::string>& uses_libraries,
162 const std::string& public_libraries) {
163 // Apps targeting Android 11 or earlier gets all public libraries
164 if (target_sdk_version <= 30) {
165 return public_libraries;
166 }
167 if (std::find(uses_libraries.begin(), uses_libraries.end(), LIBRARY_ALL) !=
168 uses_libraries.end()) {
169 return public_libraries;
170 }
171 std::vector<std::string> filtered;
172 std::vector<std::string> orig = android::base::Split(public_libraries, ":");
173 for (const auto& lib : uses_libraries) {
174 if (std::find(orig.begin(), orig.end(), lib) != orig.end()) {
175 filtered.emplace_back(lib);
176 }
177 }
178 return android::base::Join(filtered, ":");
179 }
180
Create(JNIEnv * env,uint32_t target_sdk_version,jobject class_loader,bool is_shared,jstring dex_path_j,jstring java_library_path,jstring java_permitted_path,jstring uses_library_list)181 Result<NativeLoaderNamespace*> LibraryNamespaces::Create(JNIEnv* env, uint32_t target_sdk_version,
182 jobject class_loader, bool is_shared,
183 jstring dex_path_j,
184 jstring java_library_path,
185 jstring java_permitted_path,
186 jstring uses_library_list) {
187 std::string library_path; // empty string by default.
188 std::string dex_path;
189
190 if (java_library_path != nullptr) {
191 ScopedUtfChars library_path_utf_chars(env, java_library_path);
192 library_path = library_path_utf_chars.c_str();
193 }
194
195 if (dex_path_j != nullptr) {
196 ScopedUtfChars dex_path_chars(env, dex_path_j);
197 dex_path = dex_path_chars.c_str();
198 }
199
200 std::vector<std::string> uses_libraries;
201 if (uses_library_list != nullptr) {
202 ScopedUtfChars names(env, uses_library_list);
203 uses_libraries = android::base::Split(names.c_str(), ":");
204 } else {
205 // uses_library_list could be nullptr when System.loadLibrary is called from a
206 // custom classloader. In that case, we don't know the list of public
207 // libraries because we don't know which apk the classloader is for. Only
208 // choices we can have are 1) allowing all public libs (as before), or 2)
209 // not allowing all but NDK libs. Here we take #1 because #2 would surprise
210 // developers unnecessarily.
211 // TODO(b/142191088) finalize the policy here. We could either 1) allow all
212 // public libs, 2) disallow any lib, or 3) use the libs that were granted to
213 // the first (i.e. app main) classloader.
214 uses_libraries.emplace_back(LIBRARY_ALL);
215 }
216
217 ApkOrigin apk_origin = GetApkOriginFromDexPath(dex_path);
218
219 // (http://b/27588281) This is a workaround for apps using custom
220 // classloaders and calling System.load() with an absolute path which
221 // is outside of the classloader library search path.
222 //
223 // This part effectively allows such a classloader to access anything
224 // under /data and /mnt/expand
225 std::string permitted_path = kAlwaysPermittedDirectories;
226
227 if (java_permitted_path != nullptr) {
228 ScopedUtfChars path(env, java_permitted_path);
229 if (path.c_str() != nullptr && path.size() > 0) {
230 permitted_path = permitted_path + ":" + path.c_str();
231 }
232 }
233
234 LOG_ALWAYS_FATAL_IF(FindNamespaceByClassLoader(env, class_loader) != nullptr,
235 "There is already a namespace associated with this classloader");
236
237 std::string system_exposed_libraries = default_public_libraries();
238 std::string namespace_name = kClassloaderNamespaceName;
239 ApkOrigin unbundled_app_origin = APK_ORIGIN_DEFAULT;
240 const char* apk_origin_msg = "other apk"; // Only for debug logging.
241
242 if (!is_shared) {
243 if (apk_origin == APK_ORIGIN_VENDOR) {
244 unbundled_app_origin = APK_ORIGIN_VENDOR;
245 apk_origin_msg = "unbundled vendor apk";
246
247 // For vendor apks, give access to the vendor libs even though they are
248 // treated as unbundled; the libs and apks are still bundled together in the
249 // vendor partition.
250 library_path = library_path + ':' + kVendorLibPath;
251 permitted_path = permitted_path + ':' + kVendorLibPath;
252
253 // Also give access to LLNDK libraries since they are available to vendor.
254 system_exposed_libraries = system_exposed_libraries + ':' + llndk_libraries_vendor();
255
256 // Different name is useful for debugging
257 namespace_name = kVendorClassloaderNamespaceName;
258 } else if (apk_origin == APK_ORIGIN_PRODUCT && is_product_vndk_version_defined()) {
259 unbundled_app_origin = APK_ORIGIN_PRODUCT;
260 apk_origin_msg = "unbundled product apk";
261
262 // Like for vendor apks, give access to the product libs since they are
263 // bundled together in the same partition.
264 library_path = library_path + ':' + kProductLibPath;
265 permitted_path = permitted_path + ':' + kProductLibPath;
266
267 // Also give access to LLNDK libraries since they are available to product.
268 system_exposed_libraries = system_exposed_libraries + ':' + llndk_libraries_product();
269
270 // Different name is useful for debugging
271 namespace_name = kProductClassloaderNamespaceName;
272 }
273 }
274
275 if (is_shared) {
276 // Show in the name that the namespace was created as shared, for debugging
277 // purposes.
278 namespace_name = namespace_name + kSharedNamespaceSuffix;
279 }
280
281 // Append a unique number to the namespace name, to tell them apart when
282 // debugging linker issues, e.g. with debug.ld.all set to "dlopen,dlerror".
283 static int clns_count = 0;
284 namespace_name = android::base::StringPrintf("%s-%d", namespace_name.c_str(), ++clns_count);
285
286 ALOGD(
287 "Configuring %s for %s %s. target_sdk_version=%u, uses_libraries=%s, library_path=%s, "
288 "permitted_path=%s",
289 namespace_name.c_str(),
290 apk_origin_msg,
291 dex_path.c_str(),
292 static_cast<unsigned>(target_sdk_version),
293 android::base::Join(uses_libraries, ':').c_str(),
294 library_path.c_str(),
295 permitted_path.c_str());
296
297 if (unbundled_app_origin != APK_ORIGIN_VENDOR) {
298 // Extended public libraries are NOT available to unbundled vendor apks, but
299 // they are to other apps, including those in system, system_ext, and
300 // product partitions. The reason is that when GSI is used, the system
301 // partition may get replaced, and then vendor apps may fail. It's fine for
302 // product apps, because that partition isn't mounted in GSI tests.
303 auto libs =
304 filter_public_libraries(target_sdk_version, uses_libraries, extended_public_libraries());
305 if (!libs.empty()) {
306 ALOGD("Extending system_exposed_libraries: %s", libs.c_str());
307 system_exposed_libraries = system_exposed_libraries + ':' + libs;
308 }
309 }
310
311 // Create the app namespace
312 NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
313 // Heuristic: the first classloader with non-empty library_path is assumed to
314 // be the main classloader for app
315 // TODO(b/139178525) remove this heuristic by determining this in LoadedApk (or its
316 // friends) and then passing it down to here.
317 bool is_main_classloader = app_main_namespace_ == nullptr && !library_path.empty();
318 // Policy: the namespace for the main classloader is also used as the
319 // anonymous namespace.
320 bool also_used_as_anonymous = is_main_classloader;
321 // Note: this function is executed with g_namespaces_mutex held, thus no
322 // racing here.
323 auto app_ns = NativeLoaderNamespace::Create(
324 namespace_name, library_path, permitted_path, parent_ns, is_shared,
325 target_sdk_version < 24 /* is_exempt_list_enabled */, also_used_as_anonymous);
326 if (!app_ns.ok()) {
327 return app_ns.error();
328 }
329 // ... and link to other namespaces to allow access to some public libraries
330 bool is_bridged = app_ns->IsBridged();
331
332 auto system_ns = NativeLoaderNamespace::GetSystemNamespace(is_bridged);
333 if (!system_ns.ok()) {
334 return system_ns.error();
335 }
336
337 auto linked = app_ns->Link(&system_ns.value(), system_exposed_libraries);
338 if (!linked.ok()) {
339 return linked.error();
340 }
341
342 for (const auto&[apex_ns_name, public_libs] : apex_public_libraries()) {
343 auto ns = NativeLoaderNamespace::GetExportedNamespace(apex_ns_name, is_bridged);
344 // Even if APEX namespace is visible, it may not be available to bridged.
345 if (ns.ok()) {
346 linked = app_ns->Link(&ns.value(), public_libs);
347 if (!linked.ok()) {
348 return linked.error();
349 }
350 }
351 }
352
353 // Give access to VNDK-SP libraries from the 'vndk' namespace for unbundled vendor apps.
354 if (unbundled_app_origin == APK_ORIGIN_VENDOR && !vndksp_libraries_vendor().empty()) {
355 auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkNamespaceName, is_bridged);
356 if (vndk_ns.ok()) {
357 linked = app_ns->Link(&vndk_ns.value(), vndksp_libraries_vendor());
358 if (!linked.ok()) {
359 return linked.error();
360 }
361 }
362 }
363
364 // Give access to VNDK-SP libraries from the 'vndk_product' namespace for unbundled product apps.
365 if (unbundled_app_origin == APK_ORIGIN_PRODUCT && !vndksp_libraries_product().empty()) {
366 auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkProductNamespaceName, is_bridged);
367 if (vndk_ns.ok()) {
368 linked = app_ns->Link(&vndk_ns.value(), vndksp_libraries_product());
369 if (!linked.ok()) {
370 return linked.error();
371 }
372 }
373 }
374
375 for (const std::string& each_jar_path : android::base::Split(dex_path, ":")) {
376 auto apex_ns_name = FindApexNamespaceName(each_jar_path);
377 if (apex_ns_name.ok()) {
378 const auto& jni_libs = apex_jni_libraries(*apex_ns_name);
379 if (jni_libs != "") {
380 auto apex_ns = NativeLoaderNamespace::GetExportedNamespace(*apex_ns_name, is_bridged);
381 if (apex_ns.ok()) {
382 linked = app_ns->Link(&apex_ns.value(), jni_libs);
383 if (!linked.ok()) {
384 return linked.error();
385 }
386 }
387 }
388 }
389 }
390
391 auto vendor_libs = filter_public_libraries(target_sdk_version, uses_libraries,
392 vendor_public_libraries());
393 if (!vendor_libs.empty()) {
394 auto vendor_ns = NativeLoaderNamespace::GetExportedNamespace(kVendorNamespaceName, is_bridged);
395 // when vendor_ns is not configured, link to the system namespace
396 auto target_ns = vendor_ns.ok() ? vendor_ns : system_ns;
397 if (target_ns.ok()) {
398 linked = app_ns->Link(&target_ns.value(), vendor_libs);
399 if (!linked.ok()) {
400 return linked.error();
401 }
402 }
403 }
404
405 auto product_libs = filter_public_libraries(target_sdk_version, uses_libraries,
406 product_public_libraries());
407 if (!product_libs.empty()) {
408 auto target_ns = system_ns;
409 if (is_product_vndk_version_defined()) {
410 // If ro.product.vndk.version is defined, product namespace provides the product libraries.
411 target_ns = NativeLoaderNamespace::GetExportedNamespace(kProductNamespaceName, is_bridged);
412 }
413 if (target_ns.ok()) {
414 linked = app_ns->Link(&target_ns.value(), product_libs);
415 if (!linked.ok()) {
416 return linked.error();
417 }
418 } else {
419 // The linkerconfig must have a problem on defining the product namespace in the system
420 // section. Skip linking product namespace. This will not affect most of the apps. Only the
421 // apps that requires the product public libraries will fail.
422 ALOGW("Namespace for product libs not found: %s", target_ns.error().message().c_str());
423 }
424 }
425
426 auto& emplaced = namespaces_.emplace_back(
427 std::make_pair(env->NewWeakGlobalRef(class_loader), *app_ns));
428 if (is_main_classloader) {
429 app_main_namespace_ = &emplaced.second;
430 }
431 return &emplaced.second;
432 }
433
FindNamespaceByClassLoader(JNIEnv * env,jobject class_loader)434 NativeLoaderNamespace* LibraryNamespaces::FindNamespaceByClassLoader(JNIEnv* env,
435 jobject class_loader) {
436 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
437 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
438 return env->IsSameObject(value.first, class_loader);
439 });
440 if (it != namespaces_.end()) {
441 return &it->second;
442 }
443
444 return nullptr;
445 }
446
FindParentNamespaceByClassLoader(JNIEnv * env,jobject class_loader)447 NativeLoaderNamespace* LibraryNamespaces::FindParentNamespaceByClassLoader(JNIEnv* env,
448 jobject class_loader) {
449 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
450
451 while (parent_class_loader != nullptr) {
452 NativeLoaderNamespace* ns;
453 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
454 return ns;
455 }
456
457 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
458 }
459
460 return nullptr;
461 }
462
FindApexNamespaceName(const std::string & location)463 base::Result<std::string> FindApexNamespaceName(const std::string& location) {
464 // Lots of implicit assumptions here: we expect `location` to be of the form:
465 // /apex/modulename/...
466 //
467 // And we extract from it 'modulename', and then apply mangling rule to get namespace name for it.
468 if (android::base::StartsWith(location, kApexPath)) {
469 size_t start_index = strlen(kApexPath);
470 size_t slash_index = location.find_first_of('/', start_index);
471 LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
472 "Error finding namespace of apex: no slash in path %s", location.c_str());
473 std::string name = location.substr(start_index, slash_index - start_index);
474 std::replace(name.begin(), name.end(), '.', '_');
475 return name;
476 }
477 return base::Error();
478 }
479
480 } // namespace android::nativeloader
481
482 #endif // defined(ART_TARGET_ANDROID)
483