1 /*
2 * Copyright (C) 2016 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 /*
18 * Tests accessibility of platform native libraries
19 */
20
21 #include <dirent.h>
22 #include <dlfcn.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <jni.h>
26 #include <libgen.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32
33 #include <queue>
34 #include <regex>
35 #include <string>
36 #include <unordered_set>
37 #include <vector>
38
39 #include <android-base/file.h>
40 #include <android-base/properties.h>
41 #include <android-base/strings.h>
42 #include <nativehelper/scoped_local_ref.h>
43 #include <nativehelper/scoped_utf_chars.h>
44
45 #if defined(__LP64__)
46 #define LIB_DIR "lib64"
47 #else
48 #define LIB_DIR "lib"
49 #endif
50
51 static const std::string kSystemLibraryPath = "/system/" LIB_DIR;
52 static const std::string kVendorLibraryPath = "/vendor/" LIB_DIR;
53 static const std::string kProductLibraryPath = "/product/" LIB_DIR;
54
55 // APEX library paths to check for either presence or absence of public
56 // libraries.
57 static const std::vector<std::string> kApexLibraryPaths = {
58 "/apex/com.android.art/" LIB_DIR,
59 "/apex/com.android.i18n/" LIB_DIR,
60 "/apex/com.android.neuralnetworks/" LIB_DIR,
61 "/apex/com.android.runtime/" LIB_DIR,
62 };
63
64 static const std::vector<std::regex> kSystemPathRegexes = {
65 std::regex("/system/lib(64)?"),
66 std::regex("/apex/com\\.android\\.[^/]*/lib(64)?"),
67 std::regex("/system/(lib/arm|lib64/arm64)"), // when CTS runs in ARM ABI on non-ARM CPU. http://b/149852946
68 };
69
70 // Full paths to libraries in system or APEX search paths that are not public
71 // but still may or may not be possible to load in an app.
72 static const std::vector<std::string> kOtherLoadableLibrariesInSearchPaths = {
73 // This library may be loaded using DF_1_GLOBAL into the global group in
74 // app_process, which is necessary to make it override some symbols in libc in
75 // all DSO's. As a side effect it also gets inherited into the classloader
76 // namespaces constructed in libnativeloader, and is hence possible to dlopen
77 // even though there is no linker namespace link for it.
78 "/apex/com.android.art/" LIB_DIR "/libsigchain.so",
79 };
80
81 static const std::string kWebViewPlatSupportLib = "libwebviewchromium_plat_support.so";
82
not_accessible(const std::string & err)83 static bool not_accessible(const std::string& err) {
84 return err.find("dlopen failed: library \"") == 0 &&
85 err.find("is not accessible for the namespace \"") != std::string::npos;
86 }
87
not_found(const std::string & err)88 static bool not_found(const std::string& err) {
89 return err.find("dlopen failed: library \"") == 0 &&
90 err.find("\" not found") != std::string::npos;
91 }
92
wrong_arch(const std::string & library,const std::string & err)93 static bool wrong_arch(const std::string& library, const std::string& err) {
94 // https://issuetracker.google.com/37428428
95 // It's okay to not be able to load a library because it's for another
96 // architecture (typically on an x86 device, when we come across an arm library).
97 return err.find("dlopen failed: \"" + library + "\" has unexpected e_machine: ") == 0;
98 }
99
is_library_on_path(const std::unordered_set<std::string> & library_search_paths,const std::string & baselib,const std::string & path)100 static bool is_library_on_path(const std::unordered_set<std::string>& library_search_paths,
101 const std::string& baselib,
102 const std::string& path) {
103 std::string tail = '/' + baselib;
104 if (!android::base::EndsWith(path, tail)) return false;
105 return library_search_paths.count(path.substr(0, path.size() - tail.size())) > 0;
106 }
107
try_dlopen(const std::string & path)108 static std::string try_dlopen(const std::string& path) {
109 // try to load the lib using dlopen().
110 void *handle = dlopen(path.c_str(), RTLD_NOW);
111 std::string error;
112
113 bool loaded_in_native = handle != nullptr;
114 if (loaded_in_native) {
115 dlclose(handle);
116 } else {
117 error = dlerror();
118 }
119 return error;
120 }
121
122 // Tests if a file can be loaded or not. Returns empty string on success. On any failure
123 // returns the error message from dlerror().
load_library(JNIEnv * env,jclass clazz,const std::string & path,bool test_system_load_library)124 static std::string load_library(JNIEnv* env, jclass clazz, const std::string& path,
125 bool test_system_load_library) {
126 std::string error = try_dlopen(path);
127 bool loaded_in_native = error.empty();
128
129 if (android::base::EndsWith(path, '/' + kWebViewPlatSupportLib)) {
130 // Don't try to load this library from Java. Otherwise, the lib is initialized via
131 // JNI_OnLoad and it fails since WebView is not loaded in this test process.
132 return error;
133 }
134
135 // try to load the same lib using System.load() in Java to see if it gives consistent
136 // result with dlopen.
137 static jmethodID java_load =
138 env->GetStaticMethodID(clazz, "loadWithSystemLoad", "(Ljava/lang/String;)Ljava/lang/String;");
139 ScopedLocalRef<jstring> jpath(env, env->NewStringUTF(path.c_str()));
140 jstring java_load_errmsg = jstring(env->CallStaticObjectMethod(clazz, java_load, jpath.get()));
141 bool java_load_ok = env->GetStringLength(java_load_errmsg) == 0;
142
143 jstring java_load_lib_errmsg;
144 bool java_load_lib_ok = java_load_ok;
145 if (test_system_load_library && java_load_ok) {
146 // If System.load() works then test System.loadLibrary() too. Cannot test
147 // the other way around since System.loadLibrary() might very well find the
148 // library somewhere else and hence work when System.load() fails.
149 std::string baselib = basename(path.c_str());
150 ScopedLocalRef<jstring> jname(env, env->NewStringUTF(baselib.c_str()));
151 static jmethodID java_load_lib = env->GetStaticMethodID(
152 clazz, "loadWithSystemLoadLibrary", "(Ljava/lang/String;)Ljava/lang/String;");
153 java_load_lib_errmsg = jstring(env->CallStaticObjectMethod(clazz, java_load_lib, jname.get()));
154 java_load_lib_ok = env->GetStringLength(java_load_lib_errmsg) == 0;
155 }
156
157 if (loaded_in_native != java_load_ok || java_load_ok != java_load_lib_ok) {
158 const std::string java_load_error(ScopedUtfChars(env, java_load_errmsg).c_str());
159 error = "Inconsistent result for library \"" + path + "\": dlopen() " +
160 (loaded_in_native ? "succeeded" : "failed (" + error + ")") +
161 ", System.load() " +
162 (java_load_ok ? "succeeded" : "failed (" + java_load_error + ")");
163 if (test_system_load_library) {
164 const std::string java_load_lib_error(ScopedUtfChars(env, java_load_lib_errmsg).c_str());
165 error += ", System.loadLibrary() " +
166 (java_load_lib_ok ? "succeeded" : "failed (" + java_load_lib_error + ")");
167 }
168 }
169
170 if (loaded_in_native && java_load_ok) {
171 // Unload the shared lib loaded in Java. Since we don't have a method in Java for unloading a
172 // lib other than destroying the classloader, here comes a trick; we open the same library
173 // again with dlopen to get the handle for the lib and then calls dlclose twice (since we have
174 // opened the lib twice; once in Java, once in here). This works because dlopen returns the
175 // the same handle for the same shared lib object.
176 void* handle = dlopen(path.c_str(), RTLD_NOW);
177 dlclose(handle);
178 dlclose(handle); // don't delete this line. it's not a mistake (see comment above).
179 }
180
181 return error;
182 }
183
skip_subdir_load_check(const std::string & path)184 static bool skip_subdir_load_check(const std::string& path) {
185 static bool vndk_lite = android::base::GetBoolProperty("ro.vndk.lite", false);
186 static const std::string system_vndk_dir = kSystemLibraryPath + "/vndk-sp-";
187 return vndk_lite && android::base::StartsWith(path, system_vndk_dir);
188 }
189
190 // Checks that a .so library can or cannot be loaded with dlopen() and
191 // System.load(), as appropriate by the other settings:
192 // - clazz: The java class instance of android.jni.cts.LinkerNamespacesHelper,
193 // used for calling System.load() and System.loadLibrary().
194 // - path: Full path to the library to load.
195 // - library_search_paths: Directories that should be searched for public
196 // libraries. They should not be loaded from a subdirectory of these.
197 // - public_library_basenames: File names without paths of expected public
198 // libraries.
199 // - test_system_load_library: Try loading with System.loadLibrary() as well.
200 // - check_absence: Raise an error if it is a non-public library but still is
201 // loaded successfully from a searched directory.
check_lib(JNIEnv * env,jclass clazz,const std::string & path,const std::unordered_set<std::string> & library_search_paths,const std::unordered_set<std::string> & public_library_basenames,bool test_system_load_library,bool check_absence,std::vector<std::string> * errors)202 static bool check_lib(JNIEnv* env,
203 jclass clazz,
204 const std::string& path,
205 const std::unordered_set<std::string>& library_search_paths,
206 const std::unordered_set<std::string>& public_library_basenames,
207 bool test_system_load_library,
208 bool check_absence,
209 /*out*/ std::vector<std::string>* errors) {
210 std::string err = load_library(env, clazz, path, test_system_load_library);
211 bool loaded = err.empty();
212
213 // The current restrictions on public libraries:
214 // - It must exist only in the top level directory of "library_search_paths".
215 // - No library with the same name can be found in a sub directory.
216 // - Each public library does not contain any directory components.
217
218 std::string baselib = basename(path.c_str());
219 bool is_public = public_library_basenames.find(baselib) != public_library_basenames.end();
220
221 // Special casing for symlinks in APEXes. For bundled APEXes, some files in
222 // the APEXes could be symlinks pointing to libraries in /system/lib to save
223 // storage. In that case, use the realpath so that `is_in_search_path` is
224 // correctly determined
225 bool is_in_search_path;
226 std::string realpath;
227 if (android::base::StartsWith(path, "/apex/") && android::base::Realpath(path, &realpath)) {
228 is_in_search_path = is_library_on_path(library_search_paths, baselib, realpath);
229 } else {
230 is_in_search_path = is_library_on_path(library_search_paths, baselib, path);
231 }
232
233 if (is_public) {
234 if (is_in_search_path) {
235 if (!loaded) {
236 errors->push_back("The library \"" + path +
237 "\" is a public library but it cannot be loaded: " + err);
238 return false;
239 }
240 } else { // !is_in_search_path
241 if (loaded && !skip_subdir_load_check(path)) {
242 errors->push_back("The library \"" + path +
243 "\" is a public library that was loaded from a subdirectory.");
244 return false;
245 }
246 }
247 } else { // !is_public
248 // If the library loaded successfully but is in a subdirectory then it is
249 // still not public. That is the case e.g. for
250 // /apex/com.android.runtime/lib{,64}/bionic/lib*.so.
251 if (loaded && is_in_search_path && check_absence &&
252 (std::find(kOtherLoadableLibrariesInSearchPaths.begin(),
253 kOtherLoadableLibrariesInSearchPaths.end(), path) ==
254 kOtherLoadableLibrariesInSearchPaths.end())) {
255 errors->push_back("The library \"" + path + "\" is not a public library but it loaded.");
256 return false;
257 }
258 }
259
260 if (!loaded && !not_accessible(err) && !not_found(err) && !wrong_arch(path, err)) {
261 errors->push_back("unexpected dlerror: " + err);
262 return false;
263 }
264
265 return true;
266 }
267
268 // Calls check_lib for every file found recursively within library_path.
check_path(JNIEnv * env,jclass clazz,const std::string & library_path,const std::unordered_set<std::string> & library_search_paths,const std::unordered_set<std::string> & public_library_basenames,bool test_system_load_library,bool check_absence,std::vector<std::string> * errors)269 static bool check_path(JNIEnv* env,
270 jclass clazz,
271 const std::string& library_path,
272 const std::unordered_set<std::string>& library_search_paths,
273 const std::unordered_set<std::string>& public_library_basenames,
274 bool test_system_load_library,
275 bool check_absence,
276 /*out*/ std::vector<std::string>* errors) {
277 bool success = true;
278 std::queue<std::string> dirs;
279 dirs.push(library_path);
280 while (!dirs.empty()) {
281 std::string dir = dirs.front();
282 dirs.pop();
283
284 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(dir.c_str()), closedir);
285 if (dirp == nullptr) {
286 errors->push_back("Failed to open " + dir + ": " + strerror(errno));
287 success = false;
288 continue;
289 }
290
291 dirent* dp;
292 while ((dp = readdir(dirp.get())) != nullptr) {
293 // skip "." and ".."
294 if (strcmp(".", dp->d_name) == 0 || strcmp("..", dp->d_name) == 0) {
295 continue;
296 }
297
298 std::string path = dir + "/" + dp->d_name;
299 // We cannot just load hwasan libraries into a non-hwasan process, so
300 // we are skipping those.
301 if (path.find("hwasan") != std::string::npos) {
302 continue;
303 }
304 struct stat sb;
305 // Use lstat to not dereference a symlink. If it links out of library_path
306 // it can be ignored because the Bionic linker derefences symlinks before
307 // checking the path. If it links inside library_path we'll get to the
308 // link target anyway.
309 if (lstat(path.c_str(), &sb) != -1) {
310 if (S_ISDIR(sb.st_mode)) {
311 dirs.push(path);
312 } else if (!S_ISLNK(sb.st_mode) &&
313 !check_lib(env, clazz, path, library_search_paths, public_library_basenames,
314 test_system_load_library, check_absence, errors)) {
315 success = false;
316 }
317 }
318 }
319 }
320
321 return success;
322 }
323
jobject_array_to_set(JNIEnv * env,jobjectArray java_libraries_array,std::unordered_set<std::string> * libraries,std::string * error_msgs)324 static bool jobject_array_to_set(JNIEnv* env,
325 jobjectArray java_libraries_array,
326 std::unordered_set<std::string>* libraries,
327 std::string* error_msgs) {
328 error_msgs->clear();
329 size_t size = env->GetArrayLength(java_libraries_array);
330 bool success = true;
331 for (size_t i = 0; i<size; ++i) {
332 ScopedLocalRef<jstring> java_soname(
333 env, (jstring) env->GetObjectArrayElement(java_libraries_array, i));
334 std::string soname(ScopedUtfChars(env, java_soname.get()).c_str());
335
336 // Verify that the name doesn't contain any directory components.
337 if (soname.rfind('/') != std::string::npos) {
338 *error_msgs += "\n---Illegal value, no directories allowed: " + soname;
339 continue;
340 }
341
342 // Check to see if the string ends in " 32" or " 64" to indicate the
343 // library is only public for one bitness.
344 size_t space_pos = soname.rfind(' ');
345 if (space_pos != std::string::npos) {
346 std::string type = soname.substr(space_pos + 1);
347 if (type != "32" && type != "64") {
348 *error_msgs += "\n---Illegal value at end of line (only 32 or 64 allowed): " + soname;
349 success = false;
350 continue;
351 }
352 #if defined(__LP64__)
353 if (type == "32") {
354 // Skip this, it's a 32 bit only public library.
355 continue;
356 }
357 #else
358 if (type == "64") {
359 // Skip this, it's a 64 bit only public library.
360 continue;
361 }
362 #endif
363 soname.resize(space_pos);
364 }
365
366 libraries->insert(soname);
367 }
368
369 return success;
370 }
371
372 // This is not public function but only known way to get search path of the default namespace.
373 extern "C" void android_get_LD_LIBRARY_PATH(char*, size_t) __attribute__((__weak__));
374
375 extern "C" JNIEXPORT jstring JNICALL
Java_android_jni_cts_LinkerNamespacesHelper_runAccessibilityTestImpl(JNIEnv * env,jclass clazz,jobjectArray java_system_public_libraries,jobjectArray java_apex_public_libraries)376 Java_android_jni_cts_LinkerNamespacesHelper_runAccessibilityTestImpl(
377 JNIEnv* env,
378 jclass clazz,
379 jobjectArray java_system_public_libraries,
380 jobjectArray java_apex_public_libraries) {
381 bool success = true;
382 std::vector<std::string> errors;
383 std::string error_msgs;
384 std::unordered_set<std::string> system_public_libraries;
385 if (!jobject_array_to_set(env, java_system_public_libraries, &system_public_libraries,
386 &error_msgs)) {
387 success = false;
388 errors.push_back("Errors in system public library list:" + error_msgs);
389 }
390 std::unordered_set<std::string> apex_public_libraries;
391 if (!jobject_array_to_set(env, java_apex_public_libraries, &apex_public_libraries,
392 &error_msgs)) {
393 success = false;
394 errors.push_back("Errors in APEX public library list:" + error_msgs);
395 }
396
397 // Check the system libraries.
398
399 // Check current search path and add the rest of search path configured for
400 // the default namepsace.
401 char default_search_paths[PATH_MAX];
402 android_get_LD_LIBRARY_PATH(default_search_paths, sizeof(default_search_paths));
403
404 std::vector<std::string> library_search_paths = android::base::Split(default_search_paths, ":");
405
406 // Remove everything pointing outside of /system/lib* and
407 // /apex/com.android.*/lib*.
408 std::unordered_set<std::string> system_library_search_paths;
409
410 for (const std::string& path : library_search_paths) {
411 for (const std::regex& regex : kSystemPathRegexes) {
412 if (std::regex_match(path, regex)) {
413 system_library_search_paths.insert(path);
414 break;
415 }
416 }
417 }
418
419 // These paths should be tested too - this is because apps may rely on some
420 // libraries being available there.
421 system_library_search_paths.insert(kSystemLibraryPath);
422 system_library_search_paths.insert(kApexLibraryPaths.begin(), kApexLibraryPaths.end());
423
424 if (!check_path(env, clazz, kSystemLibraryPath, system_library_search_paths,
425 system_public_libraries,
426 /*test_system_load_library=*/false, /*check_absence=*/true, &errors)) {
427 success = false;
428 }
429
430 // Pre-Treble devices use ld.config.vndk_lite.txt, where the default namespace
431 // isn't isolated. That means it can successfully load libraries in /apex, so
432 // don't complain about that in that case.
433 bool check_absence = !android::base::GetBoolProperty("ro.vndk.lite", false);
434
435 // Check the APEX libraries.
436 for (const std::string& apex_path : kApexLibraryPaths) {
437 if (!check_path(env, clazz, apex_path, {apex_path},
438 apex_public_libraries,
439 /*test_system_load_library=*/true,
440 check_absence, &errors)) {
441 success = false;
442 }
443 }
444
445 if (!success) {
446 std::string error_str;
447 for (const std::string& line : errors) {
448 error_str += line + '\n';
449 }
450 return env->NewStringUTF(error_str.c_str());
451 }
452
453 return nullptr;
454 }
455
Java_android_jni_cts_LinkerNamespacesHelper_tryDlopen(JNIEnv * env,jclass clazz,jstring lib)456 extern "C" JNIEXPORT jstring JNICALL Java_android_jni_cts_LinkerNamespacesHelper_tryDlopen(
457 JNIEnv* env,
458 jclass clazz,
459 jstring lib) {
460 ScopedUtfChars soname(env, lib);
461 std::string error_str = try_dlopen(soname.c_str());
462
463 if (!error_str.empty()) {
464 return env->NewStringUTF(error_str.c_str());
465 }
466 return nullptr;
467 }
468
Java_android_jni_cts_LinkerNamespacesHelper_getLibAbi(JNIEnv * env,jclass clazz)469 extern "C" JNIEXPORT jint JNICALL Java_android_jni_cts_LinkerNamespacesHelper_getLibAbi(
470 JNIEnv* env,
471 jclass clazz) {
472 #ifdef __aarch64__
473 return 1; // ARM64
474 #elif __arm__
475 return 2;
476 #elif __x86_64__
477 return 3;
478 #elif i386
479 return 4;
480 #else
481 return 0;
482 #endif
483 }
484