blob: 03e081421130b29aa950ca731c160e544ec17827 [file] [log] [blame]
Orion Hodson9b16e342019-10-09 13:29:16 +01001/*
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
32#include "nativeloader/dlext_namespaces.h"
33#include "public_libraries.h"
34#include "utils.h"
35
Orion Hodson9b16e342019-10-09 13:29:16 +010036namespace android::nativeloader {
37
38namespace {
39// The device may be configured to have the vendor libraries loaded to a separate namespace.
40// For historical reasons this namespace was named sphal but effectively it is intended
41// to use to load vendor libraries to separate namespace with controlled interface between
42// vendor and system namespaces.
43constexpr const char* kVendorNamespaceName = "sphal";
44constexpr const char* kVndkNamespaceName = "vndk";
45constexpr const char* kArtNamespaceName = "art";
46constexpr const char* kNeuralNetworksNamespaceName = "neuralnetworks";
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";
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +010059// If the namespace is shared then add this suffix to form
60// "classloader-namespace-shared" or "vendor-classloader-namespace-shared",
61// respectively. A shared namespace (cf. ANDROID_NAMESPACE_TYPE_SHARED) has
62// inherited all the libraries of the parent classloader namespace, or the
63// platform namespace for the main app classloader. It is used to give full
64// access to the platform libraries for apps bundled in the system image,
65// including their later updates installed in /data.
66constexpr const char* kSharedNamespaceSuffix = "-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +010067
68// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
69// System.load() with an absolute path which is outside of the classloader library search path.
70// This list includes all directories app is allowed to access this way.
71constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
72
73constexpr const char* kVendorLibPath = "/vendor/" LIB;
74constexpr const char* kProductLibPath = "/product/" LIB ":/system/product/" LIB;
75
76const std::regex kVendorDexPathRegex("(^|:)/vendor/");
77const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");
78
79// Define origin of APK if it is from vendor partition or product partition
Martin Stjernholm3bb009a2019-10-17 21:29:01 +010080using ApkOrigin = enum {
Orion Hodson9b16e342019-10-09 13:29:16 +010081 APK_ORIGIN_DEFAULT = 0,
82 APK_ORIGIN_VENDOR = 1,
83 APK_ORIGIN_PRODUCT = 2,
Martin Stjernholm3bb009a2019-10-17 21:29:01 +010084};
Orion Hodson9b16e342019-10-09 13:29:16 +010085
86jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
87 jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
88 jmethodID get_parent =
89 env->GetMethodID(class_loader_class, "getParent", "()Ljava/lang/ClassLoader;");
90
91 return env->CallObjectMethod(class_loader, get_parent);
92}
93
94ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
95 ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
96
97 if (dex_path != nullptr) {
98 ScopedUtfChars dex_path_utf_chars(env, dex_path);
99
100 if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
101 apk_origin = APK_ORIGIN_VENDOR;
102 }
103
104 if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
105 LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
106 "Dex path contains both vendor and product partition : %s",
107 dex_path_utf_chars.c_str());
108
109 apk_origin = APK_ORIGIN_PRODUCT;
110 }
111 }
112 return apk_origin;
113}
114
115} // namespace
116
117void LibraryNamespaces::Initialize() {
118 // Once public namespace is initialized there is no
119 // point in running this code - it will have no effect
120 // on the current list of public libraries.
121 if (initialized_) {
122 return;
123 }
124
125 // android_init_namespaces() expects all the public libraries
126 // to be loaded so that they can be found by soname alone.
127 //
128 // TODO(dimitry): this is a bit misleading since we do not know
129 // if the vendor public library is going to be opened from /vendor/lib
130 // we might as well end up loading them from /system/lib or /product/lib
131 // For now we rely on CTS test to catch things like this but
132 // it should probably be addressed in the future.
133 for (const auto& soname : android::base::Split(preloadable_public_libraries(), ":")) {
134 LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
135 "Error preloading public library %s: %s", soname.c_str(), dlerror());
136 }
137}
138
139Result<NativeLoaderNamespace*> LibraryNamespaces::Create(JNIEnv* env, uint32_t target_sdk_version,
140 jobject class_loader, bool is_shared,
141 jstring dex_path,
142 jstring java_library_path,
143 jstring java_permitted_path) {
144 std::string library_path; // empty string by default.
145
146 if (java_library_path != nullptr) {
147 ScopedUtfChars library_path_utf_chars(env, java_library_path);
148 library_path = library_path_utf_chars.c_str();
149 }
150
151 ApkOrigin apk_origin = GetApkOriginFromDexPath(env, dex_path);
152
153 // (http://b/27588281) This is a workaround for apps using custom
154 // classloaders and calling System.load() with an absolute path which
155 // is outside of the classloader library search path.
156 //
157 // This part effectively allows such a classloader to access anything
158 // under /data and /mnt/expand
159 std::string permitted_path = kWhitelistedDirectories;
160
161 if (java_permitted_path != nullptr) {
162 ScopedUtfChars path(env, java_permitted_path);
163 if (path.c_str() != nullptr && path.size() > 0) {
164 permitted_path = permitted_path + ":" + path.c_str();
165 }
166 }
167
168 LOG_ALWAYS_FATAL_IF(FindNamespaceByClassLoader(env, class_loader) != nullptr,
169 "There is already a namespace associated with this classloader");
170
171 std::string system_exposed_libraries = default_public_libraries();
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100172 std::string namespace_name = kClassloaderNamespaceName;
Orion Hodson9b16e342019-10-09 13:29:16 +0100173 bool unbundled_vendor_or_product_app = false;
174 if ((apk_origin == APK_ORIGIN_VENDOR ||
175 (apk_origin == APK_ORIGIN_PRODUCT && target_sdk_version > 29)) &&
176 !is_shared) {
177 unbundled_vendor_or_product_app = true;
178 // For vendor / product apks, give access to the vendor / product lib even though
179 // they are treated as unbundled; the libs and apks are still bundled
180 // together in the vendor / product partition.
181 const char* origin_partition;
182 const char* origin_lib_path;
183
184 switch (apk_origin) {
185 case APK_ORIGIN_VENDOR:
186 origin_partition = "vendor";
187 origin_lib_path = kVendorLibPath;
188 break;
189 case APK_ORIGIN_PRODUCT:
190 origin_partition = "product";
191 origin_lib_path = kProductLibPath;
192 break;
193 default:
194 origin_partition = "unknown";
195 origin_lib_path = "";
196 }
197 library_path = library_path + ":" + origin_lib_path;
198 permitted_path = permitted_path + ":" + origin_lib_path;
199
200 // Also give access to LLNDK libraries since they are available to vendors
201 system_exposed_libraries = system_exposed_libraries + ":" + llndk_libraries().c_str();
202
203 // Different name is useful for debugging
204 namespace_name = kVendorClassloaderNamespaceName;
205 ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
206 origin_partition, library_path.c_str());
207 } else {
208 // extended public libraries are NOT available to vendor apks, otherwise it
209 // would be system->vendor violation.
210 if (!extended_public_libraries().empty()) {
211 system_exposed_libraries = system_exposed_libraries + ':' + extended_public_libraries();
212 }
213 }
214
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100215 if (is_shared) {
216 // Show in the name that the namespace was created as shared, for debugging
217 // purposes.
218 namespace_name = namespace_name + kSharedNamespaceSuffix;
219 }
220
Orion Hodson9b16e342019-10-09 13:29:16 +0100221 // Create the app namespace
222 NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
223 // Heuristic: the first classloader with non-empty library_path is assumed to
224 // be the main classloader for app
225 // TODO(b/139178525) remove this heuristic by determining this in LoadedApk (or its
226 // friends) and then passing it down to here.
227 bool is_main_classloader = app_main_namespace_ == nullptr && !library_path.empty();
228 // Policy: the namespace for the main classloader is also used as the
229 // anonymous namespace.
230 bool also_used_as_anonymous = is_main_classloader;
231 // Note: this function is executed with g_namespaces_mutex held, thus no
232 // racing here.
233 auto app_ns = NativeLoaderNamespace::Create(
234 namespace_name, library_path, permitted_path, parent_ns, is_shared,
235 target_sdk_version < 24 /* is_greylist_enabled */, also_used_as_anonymous);
236 if (!app_ns) {
237 return app_ns.error();
238 }
239 // ... and link to other namespaces to allow access to some public libraries
240 bool is_bridged = app_ns->IsBridged();
241
242 auto platform_ns = NativeLoaderNamespace::GetPlatformNamespace(is_bridged);
243 if (!platform_ns) {
244 return platform_ns.error();
245 }
246
247 auto linked = app_ns->Link(*platform_ns, system_exposed_libraries);
248 if (!linked) {
249 return linked.error();
250 }
251
252 auto art_ns = NativeLoaderNamespace::GetExportedNamespace(kArtNamespaceName, is_bridged);
253 // ART APEX does not exist on host, and under certain build conditions.
254 if (art_ns) {
255 linked = app_ns->Link(*art_ns, art_public_libraries());
256 if (!linked) {
257 return linked.error();
258 }
259 }
260
261 // Give access to NNAPI libraries (apex-updated LLNDK library).
262 auto nnapi_ns =
263 NativeLoaderNamespace::GetExportedNamespace(kNeuralNetworksNamespaceName, is_bridged);
264 if (nnapi_ns) {
265 linked = app_ns->Link(*nnapi_ns, neuralnetworks_public_libraries());
266 if (!linked) {
267 return linked.error();
268 }
269 }
270
271 // Give access to VNDK-SP libraries from the 'vndk' namespace.
272 if (unbundled_vendor_or_product_app && !vndksp_libraries().empty()) {
273 auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkNamespaceName, is_bridged);
274 if (vndk_ns) {
275 linked = app_ns->Link(*vndk_ns, vndksp_libraries());
276 if (!linked) {
277 return linked.error();
278 }
279 }
280 }
281
282 if (!vendor_public_libraries().empty()) {
283 auto vendor_ns = NativeLoaderNamespace::GetExportedNamespace(kVendorNamespaceName, is_bridged);
284 // when vendor_ns is not configured, link to the platform namespace
285 auto target_ns = vendor_ns ? vendor_ns : platform_ns;
286 if (target_ns) {
287 linked = app_ns->Link(*target_ns, vendor_public_libraries());
288 if (!linked) {
289 return linked.error();
290 }
291 }
292 }
293
294 namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), *app_ns));
295 if (is_main_classloader) {
296 app_main_namespace_ = &(*app_ns);
297 }
298
299 return &(namespaces_.back().second);
300}
301
302NativeLoaderNamespace* LibraryNamespaces::FindNamespaceByClassLoader(JNIEnv* env,
303 jobject class_loader) {
304 auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
305 [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
306 return env->IsSameObject(value.first, class_loader);
307 });
308 if (it != namespaces_.end()) {
309 return &it->second;
310 }
311
312 return nullptr;
313}
314
315NativeLoaderNamespace* LibraryNamespaces::FindParentNamespaceByClassLoader(JNIEnv* env,
316 jobject class_loader) {
317 jobject parent_class_loader = GetParentClassLoader(env, class_loader);
318
319 while (parent_class_loader != nullptr) {
320 NativeLoaderNamespace* ns;
321 if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
322 return ns;
323 }
324
325 parent_class_loader = GetParentClassLoader(env, parent_class_loader);
326 }
327
328 return nullptr;
329}
330
331} // namespace android::nativeloader