1 /*
2  * Copyright (C) 2021 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 #ifndef ART_LIBNATIVELOADER_NATIVE_LOADER_TEST_H_
18 #define ART_LIBNATIVELOADER_NATIVE_LOADER_TEST_H_
19 
20 #include <string>
21 #include <unordered_map>
22 
23 #include <android-base/stringprintf.h>
24 #include <gmock/gmock.h>
25 #include <jni.h>
26 
27 #include "native_loader_namespace.h"
28 #include "nativeloader/dlext_namespaces.h"
29 
30 namespace android {
31 namespace nativeloader {
32 
33 using ::testing::Return;
34 using ::testing::_;
35 
36 // gmock interface that represents interested platform APIs on libdl_android and libnativebridge
37 class Platform {
38  public:
~Platform()39   virtual ~Platform() {}
40 
41   // These mock_* are the APIs semantically the same across libdl_android and libnativebridge.
42   // Instead of having two set of mock APIs for the two, define only one set with an additional
43   // argument 'bool bridged' to identify the context (i.e., called for libdl_android or
44   // libnativebridge).
45   typedef char* mock_namespace_handle;
46   virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
47                                              const char* search_paths) = 0;
48   virtual mock_namespace_handle mock_create_namespace(
49       bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
50       uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
51   virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
52                                     mock_namespace_handle to, const char* sonames) = 0;
53   virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
54   virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
55                                 mock_namespace_handle ns) = 0;
56 
57   // libnativebridge APIs for which libdl_android has no corresponding APIs
58   virtual bool NativeBridgeInitialized() = 0;
59   virtual const char* NativeBridgeGetError() = 0;
60   virtual bool NativeBridgeIsPathSupported(const char*) = 0;
61   virtual bool NativeBridgeIsSupported(const char*) = 0;
62 
63   // To mock "ClassLoader Object.getParent()"
64   virtual const char* JniObject_getParent(const char*) = 0;
65 };
66 
67 // The mock does not actually create a namespace object. But simply casts the pointer to the
68 // string for the namespace name as the handle to the namespace object.
69 #define TO_ANDROID_NAMESPACE(str) \
70   reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
71 
72 #define TO_BRIDGED_NAMESPACE(str) \
73   reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
74 
75 #define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
76 
77 // These represents built-in namespaces created by the linker according to ld.config.txt
78 static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
79 #define NAMESPACE_ENTRY(ns) {ns, TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(ns))}
80   NAMESPACE_ENTRY("com_android_i18n"),
81   NAMESPACE_ENTRY("com_android_neuralnetworks"),
82   NAMESPACE_ENTRY("com_android_art"),
83 
84   // TODO(b/191644631) This can be removed when the test becomes more test-friendly.
85   // This is added so that the test can exercise the JNI lib related behavior.
86   NAMESPACE_ENTRY("com_android_conscrypt"),
87 
88   NAMESPACE_ENTRY("default"),
89   NAMESPACE_ENTRY("sphal"),
90   NAMESPACE_ENTRY("system"),
91   NAMESPACE_ENTRY("vndk"),
92   NAMESPACE_ENTRY("vndk_product"),
93 #undef NAMESPACE_ENTRY
94 };
95 
96 // The actual gmock object
97 class MockPlatform : public Platform {
98  public:
MockPlatform(bool is_bridged)99   explicit MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
100     ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
101     ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
102     ON_CALL(*this, mock_get_exported_namespace(_, _))
103         .WillByDefault(testing::Invoke([](bool, const char* name) -> mock_namespace_handle {
104           if (namespaces.find(name) != namespaces.end()) {
105             return namespaces[name];
106           }
107           std::string msg = android::base::StringPrintf("(namespace %s not found)", name);
108           // The strdup'ed string will leak, but the test is already failing if we get here.
109           return TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(strdup(msg.c_str())));
110         }));
111   }
112 
113   // Mocking the common APIs
114   MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
115   MOCK_METHOD7(mock_create_namespace,
116                mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
117                                      const char*, mock_namespace_handle));
118   MOCK_METHOD4(mock_link_namespaces,
119                bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
120   MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
121   MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
122 
123   // Mocking libnativebridge APIs
124   MOCK_METHOD0(NativeBridgeInitialized, bool());
125   MOCK_METHOD0(NativeBridgeGetError, const char*());
126   MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
127   MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
128 
129   // Mocking "ClassLoader Object.getParent()"
130   MOCK_METHOD1(JniObject_getParent, const char*(const char*));
131 
132  private:
133   bool is_bridged_;
134 };
135 
136 static std::unique_ptr<MockPlatform> mock;
137 
138 // Provide C wrappers for the mock object. These symbols must be exported by ld
139 // to be able to override the real symbols in the shared libs.
140 extern "C" {
141 
142 // libdl_android APIs
143 
android_init_anonymous_namespace(const char * sonames,const char * search_path)144 bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
145   return mock->mock_init_anonymous_namespace(false, sonames, search_path);
146 }
147 
android_create_namespace(const char * name,const char * ld_library_path,const char * default_library_path,uint64_t type,const char * permitted_when_isolated_path,struct android_namespace_t * parent)148 struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
149                                                      const char* default_library_path,
150                                                      uint64_t type,
151                                                      const char* permitted_when_isolated_path,
152                                                      struct android_namespace_t* parent) {
153   return TO_ANDROID_NAMESPACE(
154       mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
155                                   permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
156 }
157 
android_link_namespaces(struct android_namespace_t * from,struct android_namespace_t * to,const char * sonames)158 bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
159                              const char* sonames) {
160   return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
161 }
162 
android_get_exported_namespace(const char * name)163 struct android_namespace_t* android_get_exported_namespace(const char* name) {
164   return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
165 }
166 
android_dlopen_ext(const char * filename,int flags,const android_dlextinfo * info)167 void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
168   return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
169 }
170 
171 // libnativebridge APIs
172 
NativeBridgeIsSupported(const char * libpath)173 bool NativeBridgeIsSupported(const char* libpath) {
174   return mock->NativeBridgeIsSupported(libpath);
175 }
176 
NativeBridgeGetExportedNamespace(const char * name)177 struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
178   return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
179 }
180 
NativeBridgeCreateNamespace(const char * name,const char * ld_library_path,const char * default_library_path,uint64_t type,const char * permitted_when_isolated_path,struct native_bridge_namespace_t * parent)181 struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
182     const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
183     const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
184   return TO_BRIDGED_NAMESPACE(
185       mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
186                                   permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
187 }
188 
NativeBridgeLinkNamespaces(struct native_bridge_namespace_t * from,struct native_bridge_namespace_t * to,const char * sonames)189 bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
190                                 struct native_bridge_namespace_t* to, const char* sonames) {
191   return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
192 }
193 
NativeBridgeLoadLibraryExt(const char * libpath,int flag,struct native_bridge_namespace_t * ns)194 void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
195                                  struct native_bridge_namespace_t* ns) {
196   return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
197 }
198 
NativeBridgeInitialized()199 bool NativeBridgeInitialized() {
200   return mock->NativeBridgeInitialized();
201 }
202 
NativeBridgeInitAnonymousNamespace(const char * public_ns_sonames,const char * anon_ns_library_path)203 bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
204                                         const char* anon_ns_library_path) {
205   return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
206 }
207 
NativeBridgeGetError()208 const char* NativeBridgeGetError() {
209   return mock->NativeBridgeGetError();
210 }
211 
NativeBridgeIsPathSupported(const char * path)212 bool NativeBridgeIsPathSupported(const char* path) {
213   return mock->NativeBridgeIsPathSupported(path);
214 }
215 
216 }  // extern "C"
217 
218 // A very simple JNI mock.
219 // jstring is a pointer to utf8 char array. We don't need utf16 char here.
220 // jobject, jclass, and jmethodID are also a pointer to utf8 char array
221 // Only a few JNI methods that are actually used in libnativeloader are mocked.
CreateJNINativeInterface()222 JNINativeInterface* CreateJNINativeInterface() {
223   JNINativeInterface* inf = new JNINativeInterface();
224   memset(inf, 0, sizeof(JNINativeInterface));
225 
226   inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
227     return reinterpret_cast<const char*>(s);
228   };
229 
230   inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
231 
232   inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
233     return reinterpret_cast<jstring>(const_cast<char*>(bytes));
234   };
235 
236   inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
237     return reinterpret_cast<jclass>(const_cast<char*>(name));
238   };
239 
240   inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
241     if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
242       // JniObject_getParent can be a valid jobject or nullptr if there is
243       // no parent classloader.
244       const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
245       return reinterpret_cast<jobject>(const_cast<char*>(ret));
246     }
247     return nullptr;
248   };
249 
250   inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
251     return reinterpret_cast<jmethodID>(const_cast<char*>(name));
252   };
253 
254   inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
255 
256   inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
257     return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
258   };
259 
260   return inf;
261 }
262 
263 }  // namespace nativeloader
264 }  // namespace android
265 
266 #endif  // ART_LIBNATIVELOADER_NATIVE_LOADER_TEST_H_
267