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