• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 <dlfcn.h>
22 #include <errno.h>
23 #include <jni.h>
24 #include <libgen.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/mman.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 
32 #include <string>
33 
34 #include "nativehelper/scoped_local_ref.h"
35 #include "nativehelper/scoped_utf_chars.h"
36 
37 static constexpr const char* kTestLibName = "libjni_test_dlclose.so";
38 
run_test(std::string * error_msg)39 static bool run_test(std::string* error_msg) {
40   void* handle = dlopen(kTestLibName, RTLD_NOW);
41   if (handle == nullptr) {
42     *error_msg = dlerror();
43     return false;
44   }
45 
46   void* taxicab_number = dlsym(handle, "dlopen_testlib_taxicab_number");
47   if (taxicab_number == nullptr) {
48     *error_msg = dlerror();
49     dlclose(handle);
50     return false;
51   }
52 
53   dlclose(handle);
54 
55   uintptr_t page_start = reinterpret_cast<uintptr_t>(taxicab_number) & ~(PAGE_SIZE - 1);
56   if (mprotect(reinterpret_cast<void*>(page_start), PAGE_SIZE, PROT_NONE) == 0) {
57     *error_msg = std::string("The library \"") +
58                  kTestLibName +
59                  "\" has not been unloaded on dlclose()";
60     return false;
61   }
62 
63   if (errno != ENOMEM) {
64     *error_msg = std::string("Unexpected error on mprotect: ") + strerror(errno);
65     return false;
66   }
67 
68   return true;
69 }
70 
Java_android_jni_cts_BasicLoaderTestHelper_nativeRunTests(JNIEnv * env)71 extern "C" JNIEXPORT jstring JNICALL Java_android_jni_cts_BasicLoaderTestHelper_nativeRunTests(
72         JNIEnv* env) {
73   std::string error_str;
74 
75   if (!run_test(&error_str)) {
76     return env->NewStringUTF(error_str.c_str());
77   }
78 
79   return nullptr;
80 }
81 
82