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 <dlfcn.h>
20 #include <setjmp.h>
21 #include <signal.h>
22 #include <sys/stat.h>
23 #include <unistd.h>
24
25 #include <algorithm>
26 #include <cstdio>
27 #include <cstdlib>
28 #include <vector>
29
30 #include <jni.h>
31 #include <nativebridge/native_bridge.h>
32
33 #include "base/macros.h"
34
35 struct NativeBridgeMethod {
36 const char* name;
37 const char* signature;
38 bool static_method;
39 void* fnPtr;
40 void* trampoline;
41 };
42
43 static NativeBridgeMethod* find_native_bridge_method(const char *name);
44 static const android::NativeBridgeRuntimeCallbacks* gNativeBridgeArtCallbacks;
45
trampoline_JNI_OnLoad(JavaVM * vm,void * reserved)46 static jint trampoline_JNI_OnLoad(JavaVM* vm, void* reserved) {
47 JNIEnv* env = nullptr;
48 using FnPtr_t = jint(*)(JavaVM*, void*);
49 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("JNI_OnLoad")->fnPtr);
50
51 vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6);
52 if (env == nullptr) {
53 return 0;
54 }
55
56 jclass klass = env->FindClass("Main");
57 if (klass != nullptr) {
58 int i, count1, count2;
59 count1 = gNativeBridgeArtCallbacks->getNativeMethodCount(env, klass);
60 std::unique_ptr<JNINativeMethod[]> methods(new JNINativeMethod[count1]);
61 if (methods == nullptr) {
62 return 0;
63 }
64 count2 = gNativeBridgeArtCallbacks->getNativeMethods(env, klass, methods.get(), count1);
65 if (count1 == count2) {
66 printf("Test ART callbacks: all JNI function number is %d.\n", count1);
67 }
68
69 for (i = 0; i < count1; i++) {
70 NativeBridgeMethod* nb_method = find_native_bridge_method(methods[i].name);
71 if (nb_method != nullptr) {
72 jmethodID mid = nullptr;
73 if (nb_method->static_method) {
74 mid = env->GetStaticMethodID(klass, methods[i].name, nb_method->signature);
75 } else {
76 mid = env->GetMethodID(klass, methods[i].name, nb_method->signature);
77 }
78 if (mid != nullptr) {
79 const char* shorty = gNativeBridgeArtCallbacks->getMethodShorty(env, mid);
80 if (strcmp(shorty, methods[i].signature) == 0) {
81 printf(" name:%s, signature:%s, shorty:%s.\n",
82 methods[i].name, nb_method->signature, shorty);
83 }
84 }
85 }
86 }
87 methods.release();
88 }
89
90 printf("%s called!\n", __FUNCTION__);
91 return fnPtr(vm, reserved);
92 }
93
trampoline_Java_Main_testFindClassOnAttachedNativeThread(JNIEnv * env,jclass klass)94 static void trampoline_Java_Main_testFindClassOnAttachedNativeThread(JNIEnv* env, jclass klass) {
95 using FnPtr_t = void(*)(JNIEnv*, jclass);
96 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
97 (find_native_bridge_method("testFindClassOnAttachedNativeThread")->fnPtr);
98 printf("%s called!\n", __FUNCTION__);
99 return fnPtr(env, klass);
100 }
101
trampoline_Java_Main_testFindFieldOnAttachedNativeThreadNative(JNIEnv * env,jclass klass)102 static void trampoline_Java_Main_testFindFieldOnAttachedNativeThreadNative(JNIEnv* env,
103 jclass klass) {
104 using FnPtr_t = void(*)(JNIEnv*, jclass);
105 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
106 (find_native_bridge_method("testFindFieldOnAttachedNativeThreadNative")->fnPtr);
107 printf("%s called!\n", __FUNCTION__);
108 return fnPtr(env, klass);
109 }
110
trampoline_Java_Main_testCallStaticVoidMethodOnSubClassNative(JNIEnv * env,jclass klass)111 static void trampoline_Java_Main_testCallStaticVoidMethodOnSubClassNative(JNIEnv* env,
112 jclass klass) {
113 using FnPtr_t = void(*)(JNIEnv*, jclass);
114 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
115 (find_native_bridge_method("testCallStaticVoidMethodOnSubClassNative")->fnPtr);
116 printf("%s called!\n", __FUNCTION__);
117 return fnPtr(env, klass);
118 }
119
trampoline_Java_Main_testGetMirandaMethodNative(JNIEnv * env,jclass klass)120 static jobject trampoline_Java_Main_testGetMirandaMethodNative(JNIEnv* env, jclass klass) {
121 using FnPtr_t = jobject(*)(JNIEnv*, jclass);
122 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
123 (find_native_bridge_method("testGetMirandaMethodNative")->fnPtr);
124 printf("%s called!\n", __FUNCTION__);
125 return fnPtr(env, klass);
126 }
127
trampoline_Java_Main_testNewStringObject(JNIEnv * env,jclass klass)128 static void trampoline_Java_Main_testNewStringObject(JNIEnv* env, jclass klass) {
129 using FnPtr_t = void(*)(JNIEnv*, jclass);
130 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
131 (find_native_bridge_method("testNewStringObject")->fnPtr);
132 printf("%s called!\n", __FUNCTION__);
133 return fnPtr(env, klass);
134 }
135
trampoline_Java_Main_testZeroLengthByteBuffers(JNIEnv * env,jclass klass)136 static void trampoline_Java_Main_testZeroLengthByteBuffers(JNIEnv* env, jclass klass) {
137 using FnPtr_t = void(*)(JNIEnv*, jclass);
138 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>
139 (find_native_bridge_method("testZeroLengthByteBuffers")->fnPtr);
140 printf("%s called!\n", __FUNCTION__);
141 return fnPtr(env, klass);
142 }
143
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)144 static jbyte trampoline_Java_Main_byteMethod(JNIEnv* env, jclass klass, jbyte b1, jbyte b2,
145 jbyte b3, jbyte b4, jbyte b5, jbyte b6,
146 jbyte b7, jbyte b8, jbyte b9, jbyte b10) {
147 using FnPtr_t = jbyte(*)(JNIEnv*, jclass, jbyte, jbyte, jbyte, jbyte, jbyte, jbyte, jbyte, jbyte,
148 jbyte, jbyte);
149 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("byteMethod")->fnPtr);
150 printf("%s called!\n", __FUNCTION__);
151 return fnPtr(env, klass, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10);
152 }
153
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)154 static jshort trampoline_Java_Main_shortMethod(JNIEnv* env, jclass klass, jshort s1, jshort s2,
155 jshort s3, jshort s4, jshort s5, jshort s6,
156 jshort s7, jshort s8, jshort s9, jshort s10) {
157 using FnPtr_t = jshort(*)(JNIEnv*, jclass, jshort, jshort, jshort, jshort, jshort, jshort, jshort,
158 jshort, jshort, jshort);
159 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("shortMethod")->fnPtr);
160 printf("%s called!\n", __FUNCTION__);
161 return fnPtr(env, klass, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10);
162 }
163
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)164 static jboolean trampoline_Java_Main_booleanMethod(JNIEnv* env, jclass klass, jboolean b1,
165 jboolean b2, jboolean b3, jboolean b4,
166 jboolean b5, jboolean b6, jboolean b7,
167 jboolean b8, jboolean b9, jboolean b10) {
168 using FnPtr_t = jboolean(*)(JNIEnv*, jclass, jboolean, jboolean, jboolean, jboolean, jboolean,
169 jboolean, jboolean, jboolean, jboolean, jboolean);
170 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("booleanMethod")->fnPtr);
171 printf("%s called!\n", __FUNCTION__);
172 return fnPtr(env, klass, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10);
173 }
174
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)175 static jchar trampoline_Java_Main_charMethod(JNIEnv* env, jclass klass, jchar c1, jchar c2,
176 jchar c3, jchar c4, jchar c5, jchar c6,
177 jchar c7, jchar c8, jchar c9, jchar c10) {
178 using FnPtr_t = jchar(*)(JNIEnv*, jclass, jchar, jchar, jchar, jchar, jchar, jchar, jchar, jchar,
179 jchar, jchar);
180 FnPtr_t fnPtr = reinterpret_cast<FnPtr_t>(find_native_bridge_method("charMethod")->fnPtr);
181 printf("%s called!\n", __FUNCTION__);
182 return fnPtr(env, klass, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10);
183 }
184
185 // This code is adapted from 004-SignalTest and causes a segfault.
186 char *go_away_compiler = nullptr;
187
test_sigaction_handler(int sig ATTRIBUTE_UNUSED,siginfo_t * info ATTRIBUTE_UNUSED,void * context ATTRIBUTE_UNUSED)188 [[ noreturn ]] static void test_sigaction_handler(int sig ATTRIBUTE_UNUSED,
189 siginfo_t* info ATTRIBUTE_UNUSED,
190 void* context ATTRIBUTE_UNUSED) {
191 printf("Should not reach the test sigaction handler.");
192 abort();
193 }
194
raise_sigsegv()195 static void raise_sigsegv() {
196 #if defined(__arm__) || defined(__i386__) || defined(__aarch64__)
197 *go_away_compiler = 'a';
198 #elif defined(__x86_64__)
199 // Cause a SEGV using an instruction known to be 2 bytes long to account for hardcoded jump
200 // in the signal handler
201 asm volatile("movl $0, %%eax;" "movb %%ah, (%%rax);" : : : "%eax");
202 #else
203 // On other architectures we simulate SEGV.
204 kill(getpid(), SIGSEGV);
205 #endif
206 }
207
trampoline_Java_Main_testSignal(JNIEnv *,jclass)208 static jint trampoline_Java_Main_testSignal(JNIEnv*, jclass) {
209 // Install the sigaction handler above, which should *not* be reached as the native-bridge
210 // handler should be called first. Note: we won't chain at all, if we ever get here, we'll die.
211 struct sigaction tmp;
212 sigemptyset(&tmp.sa_mask);
213 tmp.sa_sigaction = test_sigaction_handler;
214 #if !defined(__APPLE__) && !defined(__mips__)
215 tmp.sa_restorer = nullptr;
216 #endif
217
218 // Test segv
219 sigaction(SIGSEGV, &tmp, nullptr);
220 raise_sigsegv();
221
222 // Test sigill
223 sigaction(SIGILL, &tmp, nullptr);
224 kill(getpid(), SIGILL);
225
226 #if defined(__BIONIC__)
227 // Do the same again, but with sigaction64.
228 struct sigaction64 tmp2;
229 sigemptyset64(&tmp2.sa_mask);
230 tmp2.sa_sigaction = test_sigaction_handler;
231 #if defined(SA_RESTORER)
232 tmp2.sa_restorer = nullptr;
233 #endif
234
235 sigaction64(SIGSEGV, &tmp2, nullptr);
236 sigaction64(SIGILL, &tmp2, nullptr);
237 #endif
238
239 // Reraise SIGSEGV/SIGILL even on non-bionic, so that the expected output is
240 // the same.
241 raise_sigsegv();
242 kill(getpid(), SIGILL);
243
244 return 1234;
245 }
246
247 // Status of the tricky control path of testSignalHandlerNotReturn.
248 //
249 // "kNone" is the default status except testSignalHandlerNotReturn,
250 // others are used by testSignalHandlerNotReturn.
251 enum class TestStatus {
252 kNone,
253 kRaiseFirst,
254 kHandleFirst,
255 kRaiseSecond,
256 kHandleSecond,
257 };
258
259 // State transition helper for testSignalHandlerNotReturn.
260 class SignalHandlerTestStatus {
261 public:
SignalHandlerTestStatus()262 SignalHandlerTestStatus() : state_(TestStatus::kNone) {
263 }
264
Get()265 TestStatus Get() {
266 return state_;
267 }
268
Reset()269 void Reset() {
270 Set(TestStatus::kNone);
271 }
272
Set(TestStatus state)273 void Set(TestStatus state) {
274 switch (state) {
275 case TestStatus::kNone:
276 AssertState(TestStatus::kHandleSecond);
277 break;
278
279 case TestStatus::kRaiseFirst:
280 AssertState(TestStatus::kNone);
281 break;
282
283 case TestStatus::kHandleFirst:
284 AssertState(TestStatus::kRaiseFirst);
285 break;
286
287 case TestStatus::kRaiseSecond:
288 AssertState(TestStatus::kHandleFirst);
289 break;
290
291 case TestStatus::kHandleSecond:
292 AssertState(TestStatus::kRaiseSecond);
293 break;
294
295 default:
296 printf("ERROR: unknown state\n");
297 abort();
298 }
299
300 state_ = state;
301 }
302
303 private:
304 TestStatus state_;
305
AssertState(TestStatus expected)306 void AssertState(TestStatus expected) {
307 if (state_ != expected) {
308 printf("ERROR: unexpected state, was %d, expected %d\n", state_, expected);
309 }
310 }
311 };
312
313 static SignalHandlerTestStatus gSignalTestStatus;
314 // The context is used to jump out from signal handler.
315 static sigjmp_buf gSignalTestJmpBuf;
316
317 // Test whether NativeBridge can receive future signal when its handler doesn't return.
318 //
319 // Control path:
320 // 1. Raise first SIGSEGV in test function.
321 // 2. Raise another SIGSEGV in NativeBridge's signal handler which is handling
322 // the first SIGSEGV.
323 // 3. Expect that NativeBridge's signal handler invokes again. And jump back
324 // to test function in when handling second SIGSEGV.
325 // 4. Exit test.
326 //
327 // NOTE: sigchain should be aware that "special signal handler" may not return.
328 // Pay attention if this case fails.
trampoline_Java_Main_testSignalHandlerNotReturn(JNIEnv *,jclass)329 static void trampoline_Java_Main_testSignalHandlerNotReturn(JNIEnv*, jclass) {
330 if (gSignalTestStatus.Get() != TestStatus::kNone) {
331 printf("ERROR: test already started?\n");
332 return;
333 }
334 printf("start testSignalHandlerNotReturn\n");
335
336 if (sigsetjmp(gSignalTestJmpBuf, 1) == 0) {
337 gSignalTestStatus.Set(TestStatus::kRaiseFirst);
338 printf("raising first SIGSEGV\n");
339 raise_sigsegv();
340 } else {
341 // jump to here from signal handler when handling second SIGSEGV.
342 if (gSignalTestStatus.Get() != TestStatus::kHandleSecond) {
343 printf("ERROR: not jump from second SIGSEGV?\n");
344 return;
345 }
346 gSignalTestStatus.Reset();
347 printf("back to test from signal handler via siglongjmp(), and done!\n");
348 }
349 }
350
351 // Signal handler for testSignalHandlerNotReturn.
352 // This handler won't return.
NotReturnSignalHandler()353 static bool NotReturnSignalHandler() {
354 if (gSignalTestStatus.Get() == TestStatus::kRaiseFirst) {
355 // handling first SIGSEGV
356 gSignalTestStatus.Set(TestStatus::kHandleFirst);
357 printf("handling first SIGSEGV, will raise another\n");
358 sigset_t set;
359 sigemptyset(&set);
360 sigaddset(&set, SIGSEGV);
361 printf("unblock SIGSEGV in handler\n");
362 sigprocmask(SIG_UNBLOCK, &set, nullptr);
363 gSignalTestStatus.Set(TestStatus::kRaiseSecond);
364 printf("raising second SIGSEGV\n");
365 raise_sigsegv(); // raise second SIGSEGV
366 } else if (gSignalTestStatus.Get() == TestStatus::kRaiseSecond) {
367 // handling second SIGSEGV
368 gSignalTestStatus.Set(TestStatus::kHandleSecond);
369 printf("handling second SIGSEGV, will jump back to test function\n");
370 siglongjmp(gSignalTestJmpBuf, 1);
371 }
372 printf("ERROR: should not reach here!\n");
373 return false;
374 }
375
376 NativeBridgeMethod gNativeBridgeMethods[] = {
377 { "JNI_OnLoad", "", true, nullptr,
378 reinterpret_cast<void*>(trampoline_JNI_OnLoad) },
379 { "booleanMethod", "(ZZZZZZZZZZ)Z", true, nullptr,
380 reinterpret_cast<void*>(trampoline_Java_Main_booleanMethod) },
381 { "byteMethod", "(BBBBBBBBBB)B", true, nullptr,
382 reinterpret_cast<void*>(trampoline_Java_Main_byteMethod) },
383 { "charMethod", "(CCCCCCCCCC)C", true, nullptr,
384 reinterpret_cast<void*>(trampoline_Java_Main_charMethod) },
385 { "shortMethod", "(SSSSSSSSSS)S", true, nullptr,
386 reinterpret_cast<void*>(trampoline_Java_Main_shortMethod) },
387 { "testCallStaticVoidMethodOnSubClassNative", "()V", true, nullptr,
388 reinterpret_cast<void*>(trampoline_Java_Main_testCallStaticVoidMethodOnSubClassNative) },
389 { "testFindClassOnAttachedNativeThread", "()V", true, nullptr,
390 reinterpret_cast<void*>(trampoline_Java_Main_testFindClassOnAttachedNativeThread) },
391 { "testFindFieldOnAttachedNativeThreadNative", "()V", true, nullptr,
392 reinterpret_cast<void*>(trampoline_Java_Main_testFindFieldOnAttachedNativeThreadNative) },
393 { "testGetMirandaMethodNative", "()Ljava/lang/reflect/Method;", true, nullptr,
394 reinterpret_cast<void*>(trampoline_Java_Main_testGetMirandaMethodNative) },
395 { "testNewStringObject", "()V", true, nullptr,
396 reinterpret_cast<void*>(trampoline_Java_Main_testNewStringObject) },
397 { "testZeroLengthByteBuffers", "()V", true, nullptr,
398 reinterpret_cast<void*>(trampoline_Java_Main_testZeroLengthByteBuffers) },
399 { "testSignal", "()I", true, nullptr,
400 reinterpret_cast<void*>(trampoline_Java_Main_testSignal) },
401 { "testSignalHandlerNotReturn", "()V", true, nullptr,
402 reinterpret_cast<void*>(trampoline_Java_Main_testSignalHandlerNotReturn) },
403 };
404
find_native_bridge_method(const char * name)405 static NativeBridgeMethod* find_native_bridge_method(const char *name) {
406 const char* pname = name;
407 if (strncmp(name, "Java_Main_", 10) == 0) {
408 pname += 10;
409 }
410
411 for (size_t i = 0; i < sizeof(gNativeBridgeMethods) / sizeof(gNativeBridgeMethods[0]); i++) {
412 if (strcmp(pname, gNativeBridgeMethods[i].name) == 0) {
413 return &gNativeBridgeMethods[i];
414 }
415 }
416 return nullptr;
417 }
418
419 // NativeBridgeCallbacks implementations
native_bridge_initialize(const android::NativeBridgeRuntimeCallbacks * art_cbs,const char * app_code_cache_dir,const char * isa ATTRIBUTE_UNUSED)420 extern "C" bool native_bridge_initialize(const android::NativeBridgeRuntimeCallbacks* art_cbs,
421 const char* app_code_cache_dir,
422 const char* isa ATTRIBUTE_UNUSED) {
423 struct stat st;
424 if (app_code_cache_dir != nullptr) {
425 if (stat(app_code_cache_dir, &st) == 0) {
426 if (!S_ISDIR(st.st_mode)) {
427 printf("Code cache is not a directory.\n");
428 }
429 } else {
430 perror("Error when stat-ing the code_cache:");
431 }
432 }
433
434 if (art_cbs != nullptr) {
435 gNativeBridgeArtCallbacks = art_cbs;
436 printf("Native bridge initialized.\n");
437 }
438 return true;
439 }
440
native_bridge_loadLibrary(const char * libpath,int flag)441 extern "C" void* native_bridge_loadLibrary(const char* libpath, int flag) {
442 if (strstr(libpath, "libinvalid.so") != nullptr) {
443 printf("Was to load 'libinvalid.so', force fail.\n");
444 return nullptr;
445 }
446 size_t len = strlen(libpath);
447 char* tmp = new char[len + 10];
448 strncpy(tmp, libpath, len);
449 tmp[len - 3] = '2';
450 tmp[len - 2] = '.';
451 tmp[len - 1] = 's';
452 tmp[len] = 'o';
453 tmp[len + 1] = 0;
454 void* handle = dlopen(tmp, flag);
455 delete[] tmp;
456
457 if (handle == nullptr) {
458 printf("Handle = nullptr!\n");
459 printf("Was looking for %s.\n", libpath);
460 printf("Error = %s.\n", dlerror());
461 char cwd[1024] = {'\0'};
462 if (getcwd(cwd, sizeof(cwd)) != nullptr) {
463 printf("Current working dir: %s\n", cwd);
464 }
465 }
466 return handle;
467 }
468
native_bridge_getTrampoline(void * handle,const char * name,const char * shorty,uint32_t len ATTRIBUTE_UNUSED)469 extern "C" void* native_bridge_getTrampoline(void* handle, const char* name, const char* shorty,
470 uint32_t len ATTRIBUTE_UNUSED) {
471 printf("Getting trampoline for %s with shorty %s.\n", name, shorty);
472
473 // The name here is actually the JNI name, so we can directly do the lookup.
474 void* sym = dlsym(handle, name);
475 NativeBridgeMethod* method = find_native_bridge_method(name);
476 if (method == nullptr)
477 return nullptr;
478 method->fnPtr = sym;
479
480 return method->trampoline;
481 }
482
native_bridge_isSupported(const char * libpath)483 extern "C" bool native_bridge_isSupported(const char* libpath) {
484 printf("Checking for support.\n");
485
486 if (libpath == nullptr) {
487 return false;
488 }
489 // We don't want to hijack javacore. So we should get libarttest...
490 return strcmp(libpath, "libjavacore.so") != 0;
491 }
492
493 namespace android {
494
495 // Environment values required by the apps running with native bridge.
496 struct NativeBridgeRuntimeValues {
497 const char* os_arch;
498 const char* cpu_abi;
499 const char* cpu_abi2;
500 const char* *supported_abis;
501 int32_t abi_count;
502 };
503
504 } // namespace android
505
506 const char* supported_abis[] = {
507 "supported1", "supported2", "supported3"
508 };
509
510 const struct android::NativeBridgeRuntimeValues nb_env {
511 .os_arch = "os.arch",
512 .cpu_abi = "cpu_abi",
513 .cpu_abi2 = "cpu_abi2",
514 .supported_abis = supported_abis,
515 .abi_count = 3
516 };
517
native_bridge_getAppEnv(const char * abi)518 extern "C" const struct android::NativeBridgeRuntimeValues* native_bridge_getAppEnv(
519 const char* abi) {
520 printf("Checking for getEnvValues.\n");
521
522 if (abi == nullptr) {
523 return nullptr;
524 }
525
526 return &nb_env;
527 }
528
529 // v2 parts.
530
native_bridge_isCompatibleWith(uint32_t bridge_version ATTRIBUTE_UNUSED)531 extern "C" bool native_bridge_isCompatibleWith(uint32_t bridge_version ATTRIBUTE_UNUSED) {
532 return true;
533 }
534
535 #if defined(__i386__) || defined(__x86_64__)
536 #if defined(__APPLE__)
537 #define ucontext __darwin_ucontext
538
539 #if defined(__x86_64__)
540 // 64 bit mac build.
541 #define CTX_EIP uc_mcontext->__ss.__rip
542 #else
543 // 32 bit mac build.
544 #define CTX_EIP uc_mcontext->__ss.__eip
545 #endif
546
547 #elif defined(__x86_64__)
548 // 64 bit linux build.
549 #define CTX_EIP uc_mcontext.gregs[REG_RIP]
550 #else
551 // 32 bit linux build.
552 #define CTX_EIP uc_mcontext.gregs[REG_EIP]
553 #endif
554 #endif
555
StandardSignalHandler(int sig,siginfo_t * info ATTRIBUTE_UNUSED,void * context)556 static bool StandardSignalHandler(int sig, siginfo_t* info ATTRIBUTE_UNUSED,
557 void* context) {
558 if (sig == SIGSEGV) {
559 #if defined(__arm__)
560 struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
561 struct sigcontext *sc = reinterpret_cast<struct sigcontext*>(&uc->uc_mcontext);
562 sc->arm_pc += 2; // Skip instruction causing segv & sigill.
563 #elif defined(__aarch64__)
564 struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
565 struct sigcontext *sc = reinterpret_cast<struct sigcontext*>(&uc->uc_mcontext);
566 sc->pc += 4; // Skip instruction causing segv & sigill.
567 #elif defined(__i386__)
568 struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
569 uc->CTX_EIP += 3;
570 #elif defined(__x86_64__)
571 struct ucontext *uc = reinterpret_cast<struct ucontext*>(context);
572 uc->CTX_EIP += 2;
573 #else
574 UNUSED(context);
575 #endif
576 }
577
578 // We handled this...
579 return true;
580 }
581
582 // A dummy special handler, continueing after the faulting location. This code comes from
583 // 004-SignalTest.
nb_signalhandler(int sig,siginfo_t * info,void * context)584 static bool nb_signalhandler(int sig, siginfo_t* info, void* context) {
585 printf("NB signal handler with signal %d.\n", sig);
586
587 if (gSignalTestStatus.Get() == TestStatus::kNone) {
588 return StandardSignalHandler(sig, info, context);
589 } else if (sig == SIGSEGV) {
590 return NotReturnSignalHandler();
591 } else {
592 printf("ERROR: should not reach here!\n");
593 return false;
594 }
595 }
596
native_bridge_getSignalHandler(int signal)597 static ::android::NativeBridgeSignalHandlerFn native_bridge_getSignalHandler(int signal) {
598 // Test segv for already claimed signal, and sigill for not claimed signal
599 if ((signal == SIGSEGV) || (signal == SIGILL)) {
600 return &nb_signalhandler;
601 }
602 return nullptr;
603 }
604
native_bridge_unloadLibrary(void * handle ATTRIBUTE_UNUSED)605 extern "C" int native_bridge_unloadLibrary(void* handle ATTRIBUTE_UNUSED) {
606 printf("dlclose() in native bridge.\n");
607 return 0;
608 }
609
native_bridge_getError()610 extern "C" const char* native_bridge_getError() {
611 printf("getError() in native bridge.\n");
612 return "";
613 }
614
native_bridge_isPathSupported(const char * library_path ATTRIBUTE_UNUSED)615 extern "C" bool native_bridge_isPathSupported(const char* library_path ATTRIBUTE_UNUSED) {
616 printf("Checking for path support in native bridge.\n");
617 return false;
618 }
619
native_bridge_initAnonymousNamespace(const char * public_ns_sonames ATTRIBUTE_UNUSED,const char * anon_ns_library_path ATTRIBUTE_UNUSED)620 extern "C" bool native_bridge_initAnonymousNamespace(const char* public_ns_sonames ATTRIBUTE_UNUSED,
621 const char* anon_ns_library_path ATTRIBUTE_UNUSED) {
622 printf("Initializing anonymous namespace in native bridge.\n");
623 return false;
624 }
625
626 extern "C" android::native_bridge_namespace_t*
native_bridge_createNamespace(const char * name ATTRIBUTE_UNUSED,const char * ld_library_path ATTRIBUTE_UNUSED,const char * default_library_path ATTRIBUTE_UNUSED,uint64_t type ATTRIBUTE_UNUSED,const char * permitted_when_isolated_path ATTRIBUTE_UNUSED,android::native_bridge_namespace_t * parent_ns ATTRIBUTE_UNUSED)627 native_bridge_createNamespace(const char* name ATTRIBUTE_UNUSED,
628 const char* ld_library_path ATTRIBUTE_UNUSED,
629 const char* default_library_path ATTRIBUTE_UNUSED,
630 uint64_t type ATTRIBUTE_UNUSED,
631 const char* permitted_when_isolated_path ATTRIBUTE_UNUSED,
632 android::native_bridge_namespace_t* parent_ns ATTRIBUTE_UNUSED) {
633 printf("Creating namespace in native bridge.\n");
634 return nullptr;
635 }
636
native_bridge_linkNamespaces(android::native_bridge_namespace_t * from ATTRIBUTE_UNUSED,android::native_bridge_namespace_t * to ATTRIBUTE_UNUSED,const char * shared_libs_sonames ATTRIBUTE_UNUSED)637 extern "C" bool native_bridge_linkNamespaces(android::native_bridge_namespace_t* from ATTRIBUTE_UNUSED,
638 android::native_bridge_namespace_t* to ATTRIBUTE_UNUSED,
639 const char* shared_libs_sonames ATTRIBUTE_UNUSED) {
640 printf("Linking namespaces in native bridge.\n");
641 return false;
642 }
643
native_bridge_loadLibraryExt(const char * libpath ATTRIBUTE_UNUSED,int flag ATTRIBUTE_UNUSED,android::native_bridge_namespace_t * ns ATTRIBUTE_UNUSED)644 extern "C" void* native_bridge_loadLibraryExt(const char* libpath ATTRIBUTE_UNUSED,
645 int flag ATTRIBUTE_UNUSED,
646 android::native_bridge_namespace_t* ns ATTRIBUTE_UNUSED) {
647 printf("Loading library with Extension in native bridge.\n");
648 return nullptr;
649 }
650
651 // "NativeBridgeItf" is effectively an API (it is the name of the symbol that will be loaded
652 // by the native bridge library).
653 android::NativeBridgeCallbacks NativeBridgeItf {
654 // v1
655 .version = 3,
656 .initialize = &native_bridge_initialize,
657 .loadLibrary = &native_bridge_loadLibrary,
658 .getTrampoline = &native_bridge_getTrampoline,
659 .isSupported = &native_bridge_isSupported,
660 .getAppEnv = &native_bridge_getAppEnv,
661 // v2
662 .isCompatibleWith = &native_bridge_isCompatibleWith,
663 .getSignalHandler = &native_bridge_getSignalHandler,
664 // v3
665 .unloadLibrary = &native_bridge_unloadLibrary,
666 .getError = &native_bridge_getError,
667 .isPathSupported = &native_bridge_isPathSupported,
668 .initAnonymousNamespace = &native_bridge_initAnonymousNamespace,
669 .createNamespace = &native_bridge_createNamespace,
670 .linkNamespaces = &native_bridge_linkNamespaces,
671 .loadLibraryExt = &native_bridge_loadLibraryExt
672 };
673