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