jni_test.cc revision 848f70a3d73833fc1bf3032a9ff6812e429661d9
1/*
2 * Copyright (C) 2013 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#include <assert.h>
18#include <stdio.h>
19#include <pthread.h>
20#include <vector>
21
22#include "jni.h"
23
24#if defined(NDEBUG)
25#error test code compiled without NDEBUG
26#endif
27
28static JavaVM* jvm = nullptr;
29
30extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *) {
31  assert(vm != nullptr);
32  assert(jvm == nullptr);
33  jvm = vm;
34  return JNI_VERSION_1_6;
35}
36
37static void* AttachHelper(void* arg) {
38  assert(jvm != nullptr);
39
40  JNIEnv* env = nullptr;
41  JavaVMAttachArgs args = { JNI_VERSION_1_6, __FUNCTION__, nullptr };
42  int attach_result = jvm->AttachCurrentThread(&env, &args);
43  assert(attach_result == 0);
44
45  typedef void (*Fn)(JNIEnv*);
46  Fn fn = reinterpret_cast<Fn>(arg);
47  fn(env);
48
49  int detach_result = jvm->DetachCurrentThread();
50  assert(detach_result == 0);
51  return nullptr;
52}
53
54static void PthreadHelper(void (*fn)(JNIEnv*)) {
55  pthread_t pthread;
56  int pthread_create_result = pthread_create(&pthread, nullptr, AttachHelper,
57                                             reinterpret_cast<void*>(fn));
58  assert(pthread_create_result == 0);
59  int pthread_join_result = pthread_join(pthread, nullptr);
60  assert(pthread_join_result == 0);
61}
62
63static void testFindClassOnAttachedNativeThread(JNIEnv* env) {
64  jclass clazz = env->FindClass("Main");
65  assert(clazz != nullptr);
66  assert(!env->ExceptionCheck());
67
68  jobjectArray array = env->NewObjectArray(0, clazz, nullptr);
69  assert(array != nullptr);
70  assert(!env->ExceptionCheck());
71}
72
73// http://b/10994325
74extern "C" JNIEXPORT void JNICALL Java_Main_testFindClassOnAttachedNativeThread(JNIEnv*, jclass) {
75  PthreadHelper(&testFindClassOnAttachedNativeThread);
76}
77
78static void testFindFieldOnAttachedNativeThread(JNIEnv* env) {
79  jclass clazz = env->FindClass("Main");
80  assert(clazz != nullptr);
81  assert(!env->ExceptionCheck());
82
83  jfieldID field = env->GetStaticFieldID(clazz, "testFindFieldOnAttachedNativeThreadField", "Z");
84  assert(field != nullptr);
85  assert(!env->ExceptionCheck());
86
87  env->SetStaticBooleanField(clazz, field, JNI_TRUE);
88}
89
90extern "C" JNIEXPORT void JNICALL Java_Main_testFindFieldOnAttachedNativeThreadNative(JNIEnv*,
91                                                                                      jclass) {
92  PthreadHelper(&testFindFieldOnAttachedNativeThread);
93}
94
95static void testReflectFieldGetFromAttachedNativeThread(JNIEnv* env) {
96  jclass clazz = env->FindClass("Main");
97  assert(clazz != nullptr);
98  assert(!env->ExceptionCheck());
99
100  jclass class_clazz = env->FindClass("java/lang/Class");
101  assert(class_clazz != nullptr);
102  assert(!env->ExceptionCheck());
103
104  jmethodID getFieldMetodId = env->GetMethodID(class_clazz, "getField",
105                                               "(Ljava/lang/String;)Ljava/lang/reflect/Field;");
106  assert(getFieldMetodId != nullptr);
107  assert(!env->ExceptionCheck());
108
109  jstring field_name = env->NewStringUTF("testReflectFieldGetFromAttachedNativeThreadField");
110  assert(field_name != nullptr);
111  assert(!env->ExceptionCheck());
112
113  jobject field = env->CallObjectMethod(clazz, getFieldMetodId, field_name);
114  assert(field != nullptr);
115  assert(!env->ExceptionCheck());
116
117  jclass field_clazz = env->FindClass("java/lang/reflect/Field");
118  assert(field_clazz != nullptr);
119  assert(!env->ExceptionCheck());
120
121  jmethodID getBooleanMetodId = env->GetMethodID(field_clazz, "getBoolean",
122                                                 "(Ljava/lang/Object;)Z");
123  assert(getBooleanMetodId != nullptr);
124  assert(!env->ExceptionCheck());
125
126  jboolean value = env->CallBooleanMethod(field, getBooleanMetodId, /* ignored */ clazz);
127  assert(value == false);
128  assert(!env->ExceptionCheck());
129}
130
131// http://b/15539150
132extern "C" JNIEXPORT void JNICALL Java_Main_testReflectFieldGetFromAttachedNativeThreadNative(
133    JNIEnv*, jclass) {
134  PthreadHelper(&testReflectFieldGetFromAttachedNativeThread);
135}
136
137
138// http://b/11243757
139extern "C" JNIEXPORT void JNICALL Java_Main_testCallStaticVoidMethodOnSubClassNative(JNIEnv* env,
140                                                                                     jclass) {
141  jclass super_class = env->FindClass("Main$testCallStaticVoidMethodOnSubClass_SuperClass");
142  assert(super_class != nullptr);
143
144  jmethodID execute = env->GetStaticMethodID(super_class, "execute", "()V");
145  assert(execute != nullptr);
146
147  jclass sub_class = env->FindClass("Main$testCallStaticVoidMethodOnSubClass_SubClass");
148  assert(sub_class != nullptr);
149
150  env->CallStaticVoidMethod(sub_class, execute);
151}
152
153extern "C" JNIEXPORT jobject JNICALL Java_Main_testGetMirandaMethodNative(JNIEnv* env, jclass) {
154  jclass abstract_class = env->FindClass("Main$testGetMirandaMethod_MirandaAbstract");
155  assert(abstract_class != nullptr);
156  jmethodID miranda_method = env->GetMethodID(abstract_class, "inInterface", "()Z");
157  assert(miranda_method != nullptr);
158  return env->ToReflectedMethod(abstract_class, miranda_method, JNI_FALSE);
159}
160
161// https://code.google.com/p/android/issues/detail?id=63055
162extern "C" void JNICALL Java_Main_testZeroLengthByteBuffers(JNIEnv* env, jclass) {
163  std::vector<uint8_t> buffer(1);
164  jobject byte_buffer = env->NewDirectByteBuffer(&buffer[0], 0);
165  assert(byte_buffer != nullptr);
166  assert(!env->ExceptionCheck());
167
168  assert(env->GetDirectBufferAddress(byte_buffer) == &buffer[0]);
169  assert(env->GetDirectBufferCapacity(byte_buffer) == 0);
170}
171
172constexpr size_t kByteReturnSize = 7;
173jbyte byte_returns[kByteReturnSize] = { 0, 1, 2, 127, -1, -2, -128 };
174
175extern "C" jbyte JNICALL Java_Main_byteMethod(JNIEnv*, jclass, jbyte b1, jbyte b2,
176                                              jbyte b3, jbyte b4, jbyte b5, jbyte b6,
177                                              jbyte b7, jbyte b8, jbyte b9, jbyte b10) {
178  // We use b1 to drive the output.
179  assert(b2 == 2);
180  assert(b3 == -3);
181  assert(b4 == 4);
182  assert(b5 == -5);
183  assert(b6 == 6);
184  assert(b7 == -7);
185  assert(b8 == 8);
186  assert(b9 == -9);
187  assert(b10 == 10);
188
189  assert(0 <= b1);
190  assert(b1 < static_cast<jbyte>(kByteReturnSize));
191
192  return byte_returns[b1];
193}
194
195constexpr size_t kShortReturnSize = 9;
196jshort short_returns[kShortReturnSize] = { 0, 1, 2, 127, 32767, -1, -2, -128,
197    static_cast<jshort>(0x8000) };
198// The weird static_cast is because short int is only guaranteed down to -32767, not Java's -32768.
199
200extern "C" jshort JNICALL Java_Main_shortMethod(JNIEnv*, jclass, jshort s1, jshort s2,
201                                                jshort s3, jshort s4, jshort s5, jshort s6,
202                                                jshort s7, jshort s8, jshort s9, jshort s10) {
203  // We use s1 to drive the output.
204  assert(s2 == 2);
205  assert(s3 == -3);
206  assert(s4 == 4);
207  assert(s5 == -5);
208  assert(s6 == 6);
209  assert(s7 == -7);
210  assert(s8 == 8);
211  assert(s9 == -9);
212  assert(s10 == 10);
213
214  assert(0 <= s1);
215  assert(s1 < static_cast<jshort>(kShortReturnSize));
216
217  return short_returns[s1];
218}
219
220extern "C" jboolean JNICALL Java_Main_booleanMethod(JNIEnv*, jclass, jboolean b1,
221                                                    jboolean b2, jboolean b3, jboolean b4,
222                                                    jboolean b5, jboolean b6, jboolean b7,
223                                                    jboolean b8, jboolean b9, jboolean b10) {
224  // We use b1 to drive the output.
225  assert(b2 == JNI_TRUE);
226  assert(b3 == JNI_FALSE);
227  assert(b4 == JNI_TRUE);
228  assert(b5 == JNI_FALSE);
229  assert(b6 == JNI_TRUE);
230  assert(b7 == JNI_FALSE);
231  assert(b8 == JNI_TRUE);
232  assert(b9 == JNI_FALSE);
233  assert(b10 == JNI_TRUE);
234
235  assert(b1 == JNI_TRUE || b1 == JNI_FALSE);
236  return b1;
237}
238
239constexpr size_t kCharReturnSize = 8;
240jchar char_returns[kCharReturnSize] = { 0, 1, 2, 127, 255, 256, 15000, 34000 };
241
242extern "C" jchar JNICALL Java_Main_charMethod(JNIEnv*, jclass, jchar c1, jchar c2,
243                                              jchar c3, jchar c4, jchar c5, jchar c6, jchar c7,
244                                              jchar c8, jchar c9, jchar c10) {
245  // We use c1 to drive the output.
246  assert(c2 == 'a');
247  assert(c3 == 'b');
248  assert(c4 == 'c');
249  assert(c5 == '0');
250  assert(c6 == '1');
251  assert(c7 == '2');
252  assert(c8 == 1234);
253  assert(c9 == 2345);
254  assert(c10 == 3456);
255
256  assert(c1 < static_cast<jchar>(kCharReturnSize));
257
258  return char_returns[c1];
259}
260
261extern "C" JNIEXPORT jboolean JNICALL Java_Main_nativeIsAssignableFrom(JNIEnv* env, jclass,
262                                                                       jclass from, jclass to) {
263  return env->IsAssignableFrom(from, to);
264}
265
266static void testShallowGetCallingClassLoader(JNIEnv* env) {
267  // Test direct call.
268  {
269    jclass vmstack_clazz = env->FindClass("dalvik/system/VMStack");
270    assert(vmstack_clazz != nullptr);
271    assert(!env->ExceptionCheck());
272
273    jmethodID getCallingClassLoaderMethodId = env->GetStaticMethodID(vmstack_clazz,
274                                                                     "getCallingClassLoader",
275                                                                     "()Ljava/lang/ClassLoader;");
276    assert(getCallingClassLoaderMethodId != nullptr);
277    assert(!env->ExceptionCheck());
278
279    jobject class_loader = env->CallStaticObjectMethod(vmstack_clazz,
280                                                       getCallingClassLoaderMethodId);
281    assert(class_loader == nullptr);
282    assert(!env->ExceptionCheck());
283  }
284
285  // Test one-level call. Use System.loadLibrary().
286  {
287    jclass system_clazz = env->FindClass("java/lang/System");
288    assert(system_clazz != nullptr);
289    assert(!env->ExceptionCheck());
290
291    jmethodID loadLibraryMethodId = env->GetStaticMethodID(system_clazz, "loadLibrary",
292                                                           "(Ljava/lang/String;)V");
293    assert(loadLibraryMethodId != nullptr);
294    assert(!env->ExceptionCheck());
295
296    // Create a string object.
297    jobject library_string = env->NewStringUTF("non_existing_library");
298    assert(library_string != nullptr);
299    assert(!env->ExceptionCheck());
300
301    env->CallStaticVoidMethod(system_clazz, loadLibraryMethodId, library_string);
302    assert(env->ExceptionCheck());
303
304    // We expect UnsatisfiedLinkError.
305    jthrowable thrown = env->ExceptionOccurred();
306    env->ExceptionClear();
307
308    jclass unsatisfied_link_error_clazz = env->FindClass("java/lang/UnsatisfiedLinkError");
309    jclass thrown_class = env->GetObjectClass(thrown);
310    assert(env->IsSameObject(unsatisfied_link_error_clazz, thrown_class));
311  }
312}
313
314// http://b/16867274
315extern "C" JNIEXPORT void JNICALL Java_Main_nativeTestShallowGetCallingClassLoader(JNIEnv*,
316                                                                                   jclass) {
317  PthreadHelper(&testShallowGetCallingClassLoader);
318}
319
320static void testShallowGetStackClass2(JNIEnv* env) {
321  jclass vmstack_clazz = env->FindClass("dalvik/system/VMStack");
322  assert(vmstack_clazz != nullptr);
323  assert(!env->ExceptionCheck());
324
325  // Test direct call.
326  {
327    jmethodID getStackClass2MethodId = env->GetStaticMethodID(vmstack_clazz, "getStackClass2",
328                                                              "()Ljava/lang/Class;");
329    assert(getStackClass2MethodId != nullptr);
330    assert(!env->ExceptionCheck());
331
332    jobject caller_class = env->CallStaticObjectMethod(vmstack_clazz, getStackClass2MethodId);
333    assert(caller_class == nullptr);
334    assert(!env->ExceptionCheck());
335  }
336
337  // Test one-level call. Use VMStack.getStackClass1().
338  {
339    jmethodID getStackClass1MethodId = env->GetStaticMethodID(vmstack_clazz, "getStackClass1",
340                                                              "()Ljava/lang/Class;");
341    assert(getStackClass1MethodId != nullptr);
342    assert(!env->ExceptionCheck());
343
344    jobject caller_class = env->CallStaticObjectMethod(vmstack_clazz, getStackClass1MethodId);
345    assert(caller_class == nullptr);
346    assert(!env->ExceptionCheck());
347  }
348
349  // For better testing we would need to compile against libcore and have a two-deep stack
350  // ourselves.
351}
352
353extern "C" JNIEXPORT void JNICALL Java_Main_nativeTestShallowGetStackClass2(JNIEnv*, jclass) {
354  PthreadHelper(&testShallowGetStackClass2);
355}
356
357class JniCallNonvirtualVoidMethodTest {
358 public:
359  explicit JniCallNonvirtualVoidMethodTest(JNIEnv* env)
360      : env_(env),
361        check_jni_ri_(true),
362        check_jni_android_(true),
363        super_(GetClass("JniCallNonvirtualTest")),
364        sub_(GetClass("JniCallNonvirtualTestSubclass")),
365        super_constructor_(GetMethodID(super_, true, "<init>")),
366        super_static_(GetMethodID(super_, false, "staticMethod")),
367        super_nonstatic_(GetMethodID(super_, true, "nonstaticMethod")),
368        sub_constructor_(GetMethodID(sub_, true, "<init>")),
369        sub_static_(GetMethodID(sub_, false, "staticMethod")),
370        sub_nonstatic_(GetMethodID(sub_, true, "nonstaticMethod")),
371        super_field_(GetFieldID(super_, "nonstaticMethodSuperCalled")),
372        sub_field_(GetFieldID(super_, "nonstaticMethodSubCalled")) {}
373
374  void Test() {
375    TestStaticCallNonvirtualMethod();
376    TestNewObject();
377    TestnonstaticCallNonvirtualMethod();
378  }
379
380  JNIEnv* const env_;
381
382  bool const check_jni_ri_;
383  bool const check_jni_android_;
384
385  jclass const super_;
386  jclass const sub_;
387
388  jmethodID const super_constructor_;
389  jmethodID const super_static_;
390  jmethodID const super_nonstatic_;
391  jmethodID const sub_constructor_;
392  jmethodID const sub_static_;
393  jmethodID const sub_nonstatic_;
394
395  jfieldID const super_field_;
396  jfieldID const sub_field_;
397
398 private:
399  jclass GetClass(const char* class_name) {
400    jclass c = env_->FindClass(class_name);
401    if (env_->ExceptionCheck()) {
402      env_->ExceptionDescribe();
403      env_->FatalError(__FUNCTION__);
404    }
405    assert(!env_->ExceptionCheck());
406    assert(c != nullptr);
407    return c;
408  }
409
410  jmethodID GetMethodID(jclass c, bool nonstatic, const char* method_name) {
411    jmethodID m = ((nonstatic) ?
412                   env_->GetMethodID(c, method_name, "()V") :
413                   env_->GetStaticMethodID(c, method_name, "()V"));
414    if (env_->ExceptionCheck()) {
415      env_->ExceptionDescribe();
416      env_->FatalError(__FUNCTION__);
417    }
418    assert(m != nullptr);
419    return m;
420  }
421
422  jobject CallConstructor(jclass c, jmethodID m) {
423    jobject o = env_->NewObject(c, m);
424    if (env_->ExceptionCheck()) {
425      env_->ExceptionDescribe();
426      env_->FatalError(__FUNCTION__);
427    }
428    assert(o != nullptr);
429    return o;
430  }
431
432  void CallMethod(jobject o, jclass c, jmethodID m, bool nonstatic, const char* test_case) {
433    printf("RUNNING %s\n", test_case);
434    env_->CallNonvirtualVoidMethod(o, c, m);
435    bool exception_check = env_->ExceptionCheck();
436    if (c == nullptr || !nonstatic) {
437      if (!exception_check) {
438        printf("FAILED %s due to missing exception\n", test_case);
439        env_->FatalError("Expected NullPointerException with null jclass");
440      }
441      env_->ExceptionClear();
442    } else if (exception_check) {
443      printf("FAILED %s due to pending exception\n", test_case);
444      env_->ExceptionDescribe();
445      env_->FatalError(test_case);
446    }
447    printf("PASSED %s\n", test_case);
448  }
449
450  jfieldID GetFieldID(jclass c, const char* field_name) {
451    jfieldID m = env_->GetFieldID(c, field_name, "Z");
452    if (env_->ExceptionCheck()) {
453      env_->ExceptionDescribe();
454      env_->FatalError(__FUNCTION__);
455    }
456    assert(m != nullptr);
457    return m;
458  }
459
460  jboolean GetBooleanField(jobject o, jfieldID f) {
461    jboolean b = env_->GetBooleanField(o, f);
462    if (env_->ExceptionCheck()) {
463      env_->ExceptionDescribe();
464      env_->FatalError(__FUNCTION__);
465    }
466    return b;
467  }
468
469  void TestStaticCallNonvirtualMethod() {
470    if (!check_jni_ri_&& !check_jni_android_) {
471      CallMethod(nullptr, nullptr, super_static_, false, "null object, null class, super static");
472    }
473    if (!check_jni_android_) {
474      CallMethod(nullptr, super_, super_static_, false, "null object, super class, super static");
475    }
476    if (!check_jni_android_) {
477      CallMethod(nullptr, sub_, super_static_, false, "null object, sub class, super static");
478    }
479
480    if (!check_jni_ri_ && !check_jni_android_) {
481      CallMethod(nullptr, nullptr, sub_static_, false, "null object, null class, sub static");
482    }
483    if (!check_jni_android_) {
484      CallMethod(nullptr, sub_, sub_static_, false, "null object, super class, sub static");
485    }
486    if (!check_jni_android_) {
487      CallMethod(nullptr, super_, sub_static_, false, "null object, super class, sub static");
488    }
489  }
490
491  void TestNewObject() {
492    jobject super_super = CallConstructor(super_, super_constructor_);
493    jobject super_sub = CallConstructor(super_, sub_constructor_);
494    jobject sub_super = CallConstructor(sub_, super_constructor_);
495    jobject sub_sub = CallConstructor(sub_, sub_constructor_);
496
497    assert(env_->IsInstanceOf(super_super, super_));
498    assert(!env_->IsInstanceOf(super_super, sub_));
499
500    // Note that even though we called (and ran) the subclass
501    // constructor, we are not the subclass.
502    assert(env_->IsInstanceOf(super_sub, super_));
503    assert(!env_->IsInstanceOf(super_sub, sub_));
504
505    // Note that even though we called the superclass constructor, we
506    // are still the subclass.
507    assert(env_->IsInstanceOf(sub_super, super_));
508    assert(env_->IsInstanceOf(sub_super, sub_));
509
510    assert(env_->IsInstanceOf(sub_sub, super_));
511    assert(env_->IsInstanceOf(sub_sub, sub_));
512  }
513
514  void TestnonstaticCallNonvirtualMethod(bool super_object, bool super_class, bool super_method, const char* test_case) {
515    if (check_jni_android_) {
516      if (super_object && !super_method) {
517        return;  // We don't allow a call with sub class method on the super class instance.
518      }
519      if (super_class && !super_method) {
520        return;  // We don't allow a call with the sub class method with the super class argument.
521      }
522    }
523    jobject o = ((super_object) ?
524                 CallConstructor(super_, super_constructor_) :
525                 CallConstructor(sub_, sub_constructor_));
526    jclass c = (super_class) ? super_ : sub_;
527    jmethodID m = (super_method) ? super_nonstatic_ : sub_nonstatic_;
528    CallMethod(o, c, m, true, test_case);
529    jboolean super_field = GetBooleanField(o, super_field_);
530    jboolean sub_field = GetBooleanField(o, sub_field_);
531    assert(super_field == super_method);
532    assert(sub_field != super_method);
533  }
534
535  void TestnonstaticCallNonvirtualMethod() {
536    TestnonstaticCallNonvirtualMethod(true, true, true, "super object, super class, super nonstatic");
537    TestnonstaticCallNonvirtualMethod(true, false, true, "super object, sub class, super nonstatic");
538    TestnonstaticCallNonvirtualMethod(true, false, false, "super object, sub class, sub nonstatic");
539    TestnonstaticCallNonvirtualMethod(true, true, false, "super object, super class, sub nonstatic");
540
541    TestnonstaticCallNonvirtualMethod(false, true, true, "sub object, super class, super nonstatic");
542    TestnonstaticCallNonvirtualMethod(false, false, true, "sub object, sub class, super nonstatic");
543    TestnonstaticCallNonvirtualMethod(false, false, false, "sub object, sub class, sub nonstatic");
544    TestnonstaticCallNonvirtualMethod(false, true, false, "sub object, super class, sub nonstatic");
545  }
546};
547
548extern "C" void JNICALL Java_Main_testCallNonvirtual(JNIEnv* env, jclass) {
549  JniCallNonvirtualVoidMethodTest(env).Test();
550}
551
552extern "C" JNIEXPORT void JNICALL Java_Main_testNewStringObject(JNIEnv* env, jclass) {
553  const char* string = "Test";
554  int length = strlen(string);
555  jclass c = env->FindClass("java/lang/String");
556  assert(c != NULL);
557  jmethodID method = env->GetMethodID(c, "<init>", "([B)V");
558  assert(method != NULL);
559  assert(!env->ExceptionCheck());
560  jbyteArray array = env->NewByteArray(length);
561  env->SetByteArrayRegion(array, 0, length, reinterpret_cast<const jbyte*>(string));
562  jobject o = env->NewObject(c, method, array);
563  assert(o != NULL);
564  jstring s = reinterpret_cast<jstring>(o);
565  assert(env->GetStringLength(s) == length);
566  assert(env->GetStringUTFLength(s) == length);
567  const char* chars = env->GetStringUTFChars(s, nullptr);
568  assert(strcmp(string, chars) == 0);
569  env->ReleaseStringUTFChars(s, chars);
570}
571