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