1 /*
2  * Copyright (C) 2014 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 // A simple implementation of the native-bridge interface.
18 
19 #include <algorithm>
20 #include <dlfcn.h>
21 #include <jni.h>
22 #include <stdlib.h>
23 #include <signal.h>
24 #include <vector>
25 
26 #include "stdio.h"
27 #include "unistd.h"
28 #include "sys/stat.h"
29 
30 #include "base/macros.h"
31 #include "nativebridge/native_bridge.h"
32 
33 struct NativeBridgeMethod {
34   const char* name;
35   const char* signature;
36   bool static_method;
37   void* fnPtr;
38   void* trampoline;
39 };
40 
41 static NativeBridgeMethod* find_native_bridge_method(const char *name);
42 static const android::NativeBridgeRuntimeCallbacks* gNativeBridgeArtCallbacks;
43 
trampoline_JNI_OnLoad(JavaVM * vm,void * reserved)44 static jint trampoline_JNI_OnLoad(JavaVM* vm, void* reserved) {
45   JNIEnv* env = nullptr;
46   typedef jint (*FnPtr_t)(JavaVM*, void*);
47   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("JNI_OnLoad")->fnPtr);
48 
49   vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6);
50   if (env == nullptr) {
51     return 0;
52   }
53 
54   jclass klass = env->FindClass("Main");
55   if (klass != nullptr) {
56     int i, count1, count2;
57     count1 = gNativeBridgeArtCallbacks->getNativeMethodCount(env, klass);
58     std::unique_ptr<JNINativeMethod[]> methods(new JNINativeMethod[count1]);
59     if (methods == nullptr) {
60       return 0;
61     }
62     count2 = gNativeBridgeArtCallbacks->getNativeMethods(env, klass, methods.get(), count1);
63     if (count1 == count2) {
64       printf("Test ART callbacks: all JNI function number is %d.\n", count1);
65     }
66 
67     for (i = 0; i < count1; i++) {
68       NativeBridgeMethod* nb_method = find_native_bridge_method(methods[i].name);
69       if (nb_method != nullptr) {
70         jmethodID mid = nullptr;
71         if (nb_method->static_method) {
72           mid = env->GetStaticMethodID(klass, methods[i].name, nb_method->signature);
73         } else {
74           mid = env->GetMethodID(klass, methods[i].name, nb_method->signature);
75         }
76         if (mid != nullptr) {
77           const char* shorty = gNativeBridgeArtCallbacks->getMethodShorty(env, mid);
78           if (strcmp(shorty, methods[i].signature) == 0) {
79             printf("    name:%s, signature:%s, shorty:%s.\n",
80                    methods[i].name, nb_method->signature, shorty);
81           }
82         }
83       }
84     }
85     methods.release();
86   }
87 
88   printf("%s called!\n", __FUNCTION__);
89   return fnPtr(vm, reserved);
90 }
91 
trampoline_Java_Main_testFindClassOnAttachedNativeThread(JNIEnv * env,jclass klass)92 static void trampoline_Java_Main_testFindClassOnAttachedNativeThread(JNIEnv* env,
93                                                                      jclass klass) {
94   typedef void (*FnPtr_t)(JNIEnv*, jclass);
95   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
96     (find_native_bridge_method("testFindClassOnAttachedNativeThread")->fnPtr);
97   printf("%s called!\n", __FUNCTION__);
98   return fnPtr(env, klass);
99 }
100 
trampoline_Java_Main_testFindFieldOnAttachedNativeThreadNative(JNIEnv * env,jclass klass)101 static void trampoline_Java_Main_testFindFieldOnAttachedNativeThreadNative(JNIEnv* env,
102                                                                            jclass klass) {
103   typedef void (*FnPtr_t)(JNIEnv*, jclass);
104   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
105     (find_native_bridge_method("testFindFieldOnAttachedNativeThreadNative")->fnPtr);
106   printf("%s called!\n", __FUNCTION__);
107   return fnPtr(env, klass);
108 }
109 
trampoline_Java_Main_testCallStaticVoidMethodOnSubClassNative(JNIEnv * env,jclass klass)110 static void trampoline_Java_Main_testCallStaticVoidMethodOnSubClassNative(JNIEnv* env,
111                                                                           jclass klass) {
112   typedef void (*FnPtr_t)(JNIEnv*, jclass);
113   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
114     (find_native_bridge_method("testCallStaticVoidMethodOnSubClassNative")->fnPtr);
115   printf("%s called!\n", __FUNCTION__);
116   return fnPtr(env, klass);
117 }
118 
trampoline_Java_Main_testGetMirandaMethodNative(JNIEnv * env,jclass klass)119 static jobject trampoline_Java_Main_testGetMirandaMethodNative(JNIEnv* env, jclass klass) {
120   typedef jobject (*FnPtr_t)(JNIEnv*, jclass);
121   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
122     (find_native_bridge_method("testGetMirandaMethodNative")->fnPtr);
123   printf("%s called!\n", __FUNCTION__);
124   return fnPtr(env, klass);
125 }
126 
trampoline_Java_Main_testNewStringObject(JNIEnv * env,jclass klass)127 static void trampoline_Java_Main_testNewStringObject(JNIEnv* env, jclass klass) {
128   typedef void (*FnPtr_t)(JNIEnv*, jclass);
129   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
130     (find_native_bridge_method("testNewStringObject")->fnPtr);
131   printf("%s called!\n", __FUNCTION__);
132   return fnPtr(env, klass);
133 }
134 
trampoline_Java_Main_testZeroLengthByteBuffers(JNIEnv * env,jclass klass)135 static void trampoline_Java_Main_testZeroLengthByteBuffers(JNIEnv* env, jclass klass) {
136   typedef void (*FnPtr_t)(JNIEnv*, jclass);
137   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
138     (find_native_bridge_method("testZeroLengthByteBuffers")->fnPtr);
139   printf("%s called!\n", __FUNCTION__);
140   return fnPtr(env, klass);
141 }
142 
trampoline_Java_Main_byteMethod(JNIEnv * env,jclass klass,jbyte b1,jbyte b2,jbyte b3,jbyte b4,jbyte b5,jbyte b6,jbyte b7,jbyte b8,jbyte b9,jbyte b10)143 static jbyte trampoline_Java_Main_byteMethod(JNIEnv* env, jclass klass, jbyte b1, jbyte b2,
144                                              jbyte b3, jbyte b4, jbyte b5, jbyte b6,
145                                              jbyte b7, jbyte b8, jbyte b9, jbyte b10) {
146   typedef jbyte (*FnPtr_t)(JNIEnv*, jclass, jbyte, jbyte, jbyte, jbyte, jbyte,
147                            jbyte, jbyte, jbyte, jbyte, jbyte);
148   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("byteMethod")->fnPtr);
149   printf("%s called!\n", __FUNCTION__);
150   return fnPtr(env, klass, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10);
151 }
152 
trampoline_Java_Main_shortMethod(JNIEnv * env,jclass klass,jshort s1,jshort s2,jshort s3,jshort s4,jshort s5,jshort s6,jshort s7,jshort s8,jshort s9,jshort s10)153 static jshort trampoline_Java_Main_shortMethod(JNIEnv* env, jclass klass, jshort s1, jshort s2,
154                                                jshort s3, jshort s4, jshort s5, jshort s6,
155                                                jshort s7, jshort s8, jshort s9, jshort s10) {
156   typedef jshort (*FnPtr_t)(JNIEnv*, jclass, jshort, jshort, jshort, jshort, jshort,
157                             jshort, jshort, jshort, jshort, jshort);
158   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("shortMethod")->fnPtr);
159   printf("%s called!\n", __FUNCTION__);
160   return fnPtr(env, klass, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10);
161 }
162 
trampoline_Java_Main_booleanMethod(JNIEnv * env,jclass klass,jboolean b1,jboolean b2,jboolean b3,jboolean b4,jboolean b5,jboolean b6,jboolean b7,jboolean b8,jboolean b9,jboolean b10)163 static jboolean trampoline_Java_Main_booleanMethod(JNIEnv* env, jclass klass, jboolean b1,
164                                                    jboolean b2, jboolean b3, jboolean b4,
165                                                    jboolean b5, jboolean b6, jboolean b7,
166                                                    jboolean b8, jboolean b9, jboolean b10) {
167   typedef jboolean (*FnPtr_t)(JNIEnv*, jclass, jboolean, jboolean, jboolean, jboolean, jboolean,
168                               jboolean, jboolean, jboolean, jboolean, jboolean);
169   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("booleanMethod")->fnPtr);
170   printf("%s called!\n", __FUNCTION__);
171   return fnPtr(env, klass, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10);
172 }
173 
trampoline_Java_Main_charMethod(JNIEnv * env,jclass klass,jchar c1,jchar c2,jchar c3,jchar c4,jchar c5,jchar c6,jchar c7,jchar c8,jchar c9,jchar c10)174 static jchar trampoline_Java_Main_charMethod(JNIEnv* env, jclass klass, jchar c1, jchar c2,
175                                              jchar c3, jchar c4, jchar c5, jchar c6,
176                                              jchar c7, jchar c8, jchar c9, jchar c10) {
177   typedef jchar (*FnPtr_t)(JNIEnv*, jclass, jchar, jchar, jchar, jchar, jchar,
178                            jchar, jchar, jchar, jchar, jchar);
179   FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("charMethod")->fnPtr);
180   printf("%s called!\n", __FUNCTION__);
181   return fnPtr(env, klass, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10);
182 }
183 
184 // This code is adapted from 004-SignalTest and causes a segfault.
185 char *go_away_compiler = nullptr;
186 
test_sigaction_handler(int sig ATTRIBUTE_UNUSED,siginfo_t * info ATTRIBUTE_UNUSED,void * context ATTRIBUTE_UNUSED)187 [[ noreturn ]] static void test_sigaction_handler(int sig ATTRIBUTE_UNUSED,
188                                                   siginfo_t* info ATTRIBUTE_UNUSED,
189                                                   void* context ATTRIBUTE_UNUSED) {
190   printf("Should not reach the test sigaction handler.");
191   abort();
192 }
193 
trampoline_Java_Main_testSignal(JNIEnv *,jclass)194 static jint trampoline_Java_Main_testSignal(JNIEnv*, jclass) {
195   // Install the sigaction handler above, which should *not* be reached as the native-bridge
196   // handler should be called first. Note: we won't chain at all, if we ever get here, we'll die.
197   struct sigaction tmp;
198   sigemptyset(&tmp.sa_mask);
199   tmp.sa_sigaction = test_sigaction_handler;
200 #if !defined(__APPLE__) && !defined(__mips__)
201   tmp.sa_restorer = nullptr;
202 #endif
203   sigaction(SIGSEGV, &tmp, nullptr);
204 
205 #if defined(__arm__) || defined(__i386__) || defined(__x86_64__) || defined(__aarch64__)
206   // On supported architectures we cause a real SEGV.
207   *go_away_compiler = 'a';
208 #else
209   // On other architectures we simulate SEGV.
210   kill(getpid(), SIGSEGV);
211 #endif
212   return 1234;
213 }
214 
215 NativeBridgeMethod gNativeBridgeMethods[] = {
216   { "JNI_OnLoad", "", true, nullptr,
217     reinterpret_cast<void*>(trampoline_JNI_OnLoad) },
218   { "booleanMethod", "(ZZZZZZZZZZ)Z", true, nullptr,
219     reinterpret_cast<void*>(trampoline_Java_Main_booleanMethod) },
220   { "byteMethod", "(BBBBBBBBBB)B", true, nullptr,
221     reinterpret_cast<void*>(trampoline_Java_Main_byteMethod) },
222   { "charMethod", "(CCCCCCCCCC)C", true, nullptr,
223     reinterpret_cast<void*>(trampoline_Java_Main_charMethod) },
224   { "shortMethod", "(SSSSSSSSSS)S", true, nullptr,
225     reinterpret_cast<void*>(trampoline_Java_Main_shortMethod) },
226   { "testCallStaticVoidMethodOnSubClassNative", "()V", true, nullptr,
227     reinterpret_cast<void*>(trampoline_Java_Main_testCallStaticVoidMethodOnSubClassNative) },
228   { "testFindClassOnAttachedNativeThread", "()V", true, nullptr,
229     reinterpret_cast<void*>(trampoline_Java_Main_testFindClassOnAttachedNativeThread) },
230   { "testFindFieldOnAttachedNativeThreadNative", "()V", true, nullptr,
231     reinterpret_cast<void*>(trampoline_Java_Main_testFindFieldOnAttachedNativeThreadNative) },
232   { "testGetMirandaMethodNative", "()Ljava/lang/reflect/Method;", true, nullptr,
233     reinterpret_cast<void*>(trampoline_Java_Main_testGetMirandaMethodNative) },
234   { "testNewStringObject", "()V", true, nullptr,
235     reinterpret_cast<void*>(trampoline_Java_Main_testNewStringObject) },
236   { "testZeroLengthByteBuffers", "()V", true, nullptr,
237     reinterpret_cast<void*>(trampoline_Java_Main_testZeroLengthByteBuffers) },
238   { "testSignal", "()I", true, nullptr,
239     reinterpret_cast<void*>(trampoline_Java_Main_testSignal) },
240 };
241 
find_native_bridge_method(const char * name)242 static NativeBridgeMethod* find_native_bridge_method(const char *name) {
243   const char* pname = name;
244   if (strncmp(name, "Java_Main_", 10) == 0) {
245     pname += 10;
246   }
247 
248   for (size_t i = 0; i < sizeof(gNativeBridgeMethods) / sizeof(gNativeBridgeMethods[0]); i++) {
249     if (strcmp(pname, gNativeBridgeMethods[i].name) == 0) {
250       return &gNativeBridgeMethods[i];
251     }
252   }
253   return nullptr;
254 }
255 
256 // NativeBridgeCallbacks implementations
native_bridge_initialize(const android::NativeBridgeRuntimeCallbacks * art_cbs,const char * app_code_cache_dir,const char * isa ATTRIBUTE_UNUSED)257 extern "C" bool native_bridge_initialize(const android::NativeBridgeRuntimeCallbacks* art_cbs,
258                                          const char* app_code_cache_dir,
259                                          const char* isa ATTRIBUTE_UNUSED) {
260   struct stat st;
261   if ((app_code_cache_dir != nullptr)
262       && (stat(app_code_cache_dir, &st) == 0)
263       && S_ISDIR(st.st_mode)) {
264     printf("Code cache exists: '%s'.\n", app_code_cache_dir);
265   }
266   if (art_cbs != nullptr) {
267     gNativeBridgeArtCallbacks = art_cbs;
268     printf("Native bridge initialized.\n");
269   }
270   return true;
271 }
272 
native_bridge_loadLibrary(const char * libpath,int flag)273 extern "C" void* native_bridge_loadLibrary(const char* libpath, int flag) {
274   size_t len = strlen(libpath);
275   char* tmp = new char[len + 10];
276   strncpy(tmp, libpath, len);
277   tmp[len - 3] = '2';
278   tmp[len - 2] = '.';
279   tmp[len - 1] = 's';
280   tmp[len] = 'o';
281   tmp[len + 1] = 0;
282   void* handle = dlopen(tmp, flag);
283   delete[] tmp;
284 
285   if (handle == nullptr) {
286     printf("Handle = nullptr!\n");
287     printf("Was looking for %s.\n", libpath);
288     printf("Error = %s.\n", dlerror());
289     char cwd[1024];
290     if (getcwd(cwd, sizeof(cwd)) != nullptr) {
291       printf("Current working dir: %s\n", cwd);
292     }
293   }
294   return handle;
295 }
296 
native_bridge_getTrampoline(void * handle,const char * name,const char * shorty,uint32_t len ATTRIBUTE_UNUSED)297 extern "C" void* native_bridge_getTrampoline(void* handle, const char* name, const char* shorty,
298                                              uint32_t len ATTRIBUTE_UNUSED) {
299   printf("Getting trampoline for %s with shorty %s.\n", name, shorty);
300 
301   // The name here is actually the JNI name, so we can directly do the lookup.
302   void* sym = dlsym(handle, name);
303   NativeBridgeMethod* method = find_native_bridge_method(name);
304   if (method == nullptr)
305     return nullptr;
306   method->fnPtr = sym;
307 
308   return method->trampoline;
309 }
310 
native_bridge_isSupported(const char * libpath)311 extern "C" bool native_bridge_isSupported(const char* libpath) {
312   printf("Checking for support.\n");
313 
314   if (libpath == nullptr) {
315     return false;
316   }
317   // We don't want to hijack javacore. So we should get libarttest...
318   return strcmp(libpath, "libjavacore.so") != 0;
319 }
320 
321 namespace android {
322 
323 // Environment values required by the apps running with native bridge.
324 struct NativeBridgeRuntimeValues {
325   const char* os_arch;
326   const char* cpu_abi;
327   const char* cpu_abi2;
328   const char* *supported_abis;
329   int32_t abi_count;
330 };
331 
332 }  // namespace android
333 
334 const char* supported_abis[] = {
335     "supported1", "supported2", "supported3"
336 };
337 
338 const struct android::NativeBridgeRuntimeValues nb_env {
339     .os_arch = "os.arch",
340     .cpu_abi = "cpu_abi",
341     .cpu_abi2 = "cpu_abi2",
342     .supported_abis = supported_abis,
343     .abi_count = 3
344 };
345 
native_bridge_getAppEnv(const char * abi)346 extern "C" const struct android::NativeBridgeRuntimeValues* native_bridge_getAppEnv(
347     const char* abi) {
348   printf("Checking for getEnvValues.\n");
349 
350   if (abi == nullptr) {
351     return nullptr;
352   }
353 
354   return &nb_env;
355 }
356 
357 // v2 parts.
358 
nb_is_compatible(uint32_t bridge_version ATTRIBUTE_UNUSED)359 extern "C" bool nb_is_compatible(uint32_t bridge_version ATTRIBUTE_UNUSED) {
360   return true;
361 }
362 
363 #if defined(__i386__) || defined(__x86_64__)
364 #if defined(__APPLE__)
365 #define ucontext __darwin_ucontext
366 
367 #if defined(__x86_64__)
368 // 64 bit mac build.
369 #define CTX_EIP uc_mcontext->__ss.__rip
370 #else
371 // 32 bit mac build.
372 #define CTX_EIP uc_mcontext->__ss.__eip
373 #endif
374 
375 #elif defined(__x86_64__)
376 // 64 bit linux build.
377 #define CTX_EIP uc_mcontext.gregs[REG_RIP]
378 #else
379 // 32 bit linux build.
380 #define CTX_EIP uc_mcontext.gregs[REG_EIP]
381 #endif
382 #endif
383 
384 // A dummy special handler, continueing after the faulting location. This code comes from
385 // 004-SignalTest.
nb_signalhandler(int sig,siginfo_t * info ATTRIBUTE_UNUSED,void * context)386 static bool nb_signalhandler(int sig, siginfo_t* info ATTRIBUTE_UNUSED, void* context) {
387   printf("NB signal handler with signal %d.\n", sig);
388 #if defined(__arm__)
389   struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
390   struct sigcontext *sc = reinterpret_cast<struct sigcontext*>(&uc->uc_mcontext);
391   sc->arm_pc += 2;          // Skip instruction causing segv.
392 #elif defined(__aarch64__)
393   struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
394   struct sigcontext *sc = reinterpret_cast<struct sigcontext*>(&uc->uc_mcontext);
395   sc->pc += 4;          // Skip instruction causing segv.
396 #elif defined(__i386__) || defined(__x86_64__)
397   struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
398   uc->CTX_EIP += 3;
399 #else
400   UNUSED(context);
401 #endif
402   // We handled this...
403   return true;
404 }
405 
native_bridge_get_signal_handler(int signal)406 static ::android::NativeBridgeSignalHandlerFn native_bridge_get_signal_handler(int signal) {
407   // Only test segfault handler.
408   if (signal == SIGSEGV) {
409     return &nb_signalhandler;
410   }
411   return nullptr;
412 }
413 
414 
415 // "NativeBridgeItf" is effectively an API (it is the name of the symbol that will be loaded
416 // by the native bridge library).
417 android::NativeBridgeCallbacks NativeBridgeItf {
418   .version = 2,
419   .initialize = &native_bridge_initialize,
420   .loadLibrary = &native_bridge_loadLibrary,
421   .getTrampoline = &native_bridge_getTrampoline,
422   .isSupported = &native_bridge_isSupported,
423   .getAppEnv = &native_bridge_getAppEnv,
424   .isCompatibleWith = &nb_is_compatible,
425   .getSignalHandler = &native_bridge_get_signal_handler
426 };
427