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