blob: 4989f231423568a3a8eb6b88db314652080cf7a5 [file] [log] [blame]
Elliott Hughesa2501992011-08-26 19:39:54 -07001/*
2 * Copyright (C) 2008 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 "jni_internal.h"
18
19#include <sys/mman.h>
20#include <zlib.h>
21
22#include "class_linker.h"
23#include "logging.h"
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070024#include "scoped_jni_thread_state.h"
Elliott Hughesa2501992011-08-26 19:39:54 -070025#include "thread.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070026#include "runtime.h"
Elliott Hughesa2501992011-08-26 19:39:54 -070027
Elliott Hughese6087632011-09-26 12:18:25 -070028#define LIBCORE_CPP_JNI_HELPERS
29#include <JNIHelp.h> // from libcore
30#undef LIBCORE_CPP_JNI_HELPERS
31
Elliott Hughesa2501992011-08-26 19:39:54 -070032namespace art {
33
34void JniAbort(const char* jni_function_name) {
Elliott Hughesa0957642011-09-02 14:27:33 -070035 Thread* self = Thread::Current();
36 const Method* current_method = self->GetCurrentMethod();
Elliott Hughesa2501992011-08-26 19:39:54 -070037
Elliott Hughesa0957642011-09-02 14:27:33 -070038 std::stringstream os;
Elliott Hughese6087632011-09-26 12:18:25 -070039 os << "Aborting because JNI app bug detected (see above for details)";
Elliott Hughesa2501992011-08-26 19:39:54 -070040
41 if (jni_function_name != NULL) {
42 os << "\n in call to " << jni_function_name;
43 }
Elliott Hughesa0957642011-09-02 14:27:33 -070044 // TODO: is this useful given that we're about to dump the calling thread's stack?
45 if (current_method != NULL) {
46 os << "\n from " << PrettyMethod(current_method);
47 }
48 os << "\n";
49 self->Dump(os);
Elliott Hughesa2501992011-08-26 19:39:54 -070050
51 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
52 if (vm->check_jni_abort_hook != NULL) {
53 vm->check_jni_abort_hook(os.str());
54 } else {
55 LOG(FATAL) << os.str();
56 }
57}
58
59/*
60 * ===========================================================================
61 * JNI function helpers
62 * ===========================================================================
63 */
64
Elliott Hughesa2501992011-08-26 19:39:54 -070065template<typename T>
66T Decode(ScopedJniThreadState& ts, jobject obj) {
67 return reinterpret_cast<T>(ts.Self()->DecodeJObject(obj));
68}
69
Elliott Hughesa2501992011-08-26 19:39:54 -070070/*
71 * Hack to allow forcecopy to work with jniGetNonMovableArrayElements.
72 * The code deliberately uses an invalid sequence of operations, so we
73 * need to pass it through unmodified. Review that code before making
74 * any changes here.
75 */
76#define kNoCopyMagic 0xd5aab57f
77
78/*
79 * Flags passed into ScopedCheck.
80 */
81#define kFlag_Default 0x0000
82
83#define kFlag_CritBad 0x0000 /* calling while in critical is bad */
84#define kFlag_CritOkay 0x0001 /* ...okay */
85#define kFlag_CritGet 0x0002 /* this is a critical "get" */
86#define kFlag_CritRelease 0x0003 /* this is a critical "release" */
87#define kFlag_CritMask 0x0003 /* bit mask to get "crit" value */
88
89#define kFlag_ExcepBad 0x0000 /* raised exceptions are bad */
90#define kFlag_ExcepOkay 0x0004 /* ...okay */
91
92#define kFlag_Release 0x0010 /* are we in a non-critical release function? */
93#define kFlag_NullableUtf 0x0020 /* are our UTF parameters nullable? */
94
95#define kFlag_Invocation 0x8000 /* Part of the invocation interface (JavaVM*) */
96
Elliott Hughesa0957642011-09-02 14:27:33 -070097static const char* gBuiltInPrefixes[] = {
98 "Landroid/",
99 "Lcom/android/",
100 "Lcom/google/android/",
101 "Ldalvik/",
102 "Ljava/",
103 "Ljavax/",
104 "Llibcore/",
105 "Lorg/apache/harmony/",
106 NULL
107};
108
109bool ShouldTrace(JavaVMExt* vm, const Method* method) {
110 // If both "-Xcheck:jni" and "-Xjnitrace:" are enabled, we print trace messages
111 // when a native method that matches the -Xjnitrace argument calls a JNI function
112 // such as NewByteArray.
113 // If -verbose:third-party-jni is on, we want to log any JNI function calls
114 // made by a third-party native method.
115 std::string classNameStr(method->GetDeclaringClass()->GetDescriptor()->ToModifiedUtf8());
116 if (!vm->trace.empty() && classNameStr.find(vm->trace) != std::string::npos) {
117 return true;
118 }
119 if (vm->log_third_party_jni) {
120 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
121 // like part of Android.
122 StringPiece className(classNameStr);
123 for (size_t i = 0; gBuiltInPrefixes[i] != NULL; ++i) {
124 if (className.starts_with(gBuiltInPrefixes[i])) {
125 return false;
126 }
127 }
128 return true;
129 }
130 return false;
131}
132
Elliott Hughesa2501992011-08-26 19:39:54 -0700133class ScopedCheck {
134public:
135 // For JNIEnv* functions.
136 explicit ScopedCheck(JNIEnv* env, int flags, const char* functionName) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700137 Init(env, reinterpret_cast<JNIEnvExt*>(env)->vm, flags, functionName, true);
138 CheckThread(flags);
Elliott Hughesa2501992011-08-26 19:39:54 -0700139 }
140
141 // For JavaVM* functions.
Elliott Hughesa0957642011-09-02 14:27:33 -0700142 explicit ScopedCheck(JavaVM* vm, bool hasMethod, const char* functionName) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700143 Init(NULL, vm, kFlag_Invocation, functionName, hasMethod);
Elliott Hughesa2501992011-08-26 19:39:54 -0700144 }
145
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700146 bool ForceCopy() {
Elliott Hughesa2501992011-08-26 19:39:54 -0700147 return Runtime::Current()->GetJavaVM()->force_copy;
148 }
149
150 /*
151 * In some circumstances the VM will screen class names, but it doesn't
152 * for class lookup. When things get bounced through a class loader, they
153 * can actually get normalized a couple of times; as a result, passing in
154 * a class name like "java.lang.Thread" instead of "java/lang/Thread" will
155 * work in some circumstances.
156 *
157 * This is incorrect and could cause strange behavior or compatibility
158 * problems, so we want to screen that out here.
159 *
160 * We expect "fully-qualified" class names, like "java/lang/Thread" or
161 * "[Ljava/lang/Object;".
162 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700163 void CheckClassName(const char* className) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700164 if (!IsValidClassName(className, true, false)) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700165 LOG(ERROR) << "JNI ERROR: illegal class name '" << className << "' (" << function_name_ << ")\n"
Elliott Hughesa2501992011-08-26 19:39:54 -0700166 << " (should be of the form 'java/lang/String', [Ljava/lang/String;' or '[[B')\n";
167 JniAbort();
168 }
169 }
170
171 /*
172 * Verify that the field is of the appropriate type. If the field has an
173 * object type, "java_object" is the object we're trying to assign into it.
174 *
175 * Works for both static and instance fields.
176 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700177 void CheckFieldType(jobject java_object, jfieldID fid, char prim, bool isStatic) {
178 ScopedJniThreadState ts(env_);
179 Field* f = CheckFieldID(fid);
180 if (f == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700181 return;
182 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700183 Class* field_type = f->GetType();
184 if (!field_type->IsPrimitive()) {
185 if (java_object != NULL) {
186 Object* obj = Decode<Object*>(ts, java_object);
187 /*
188 * If java_object is a weak global ref whose referent has been cleared,
189 * obj will be NULL. Otherwise, obj should always be non-NULL
190 * and valid.
191 */
192 if (obj != NULL && !Heap::IsHeapAddress(obj)) {
193 LOG(ERROR) << "JNI ERROR: field operation on invalid " << GetIndirectRefKind(java_object) << ": " << java_object;
Elliott Hughesa2501992011-08-26 19:39:54 -0700194 JniAbort();
195 return;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700196 } else {
Brian Carlstrom16192862011-09-12 17:50:06 -0700197 if (!obj->InstanceOf(field_type)) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700198 LOG(ERROR) << "JNI ERROR: attempt to set field " << PrettyField(f) << " with value of wrong type: " << PrettyTypeOf(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199 JniAbort();
200 return;
201 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700202 }
Elliott Hughesa2501992011-08-26 19:39:54 -0700203 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700204 } else if (field_type != Runtime::Current()->GetClassLinker()->FindPrimitiveClass(prim)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700205 LOG(ERROR) << "JNI ERROR: attempt to set field " << PrettyField(f) << " with value of wrong type: " << prim;
206 JniAbort();
207 return;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700208 }
209
210 if (isStatic && !f->IsStatic()) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700211 if (isStatic) {
212 LOG(ERROR) << "JNI ERROR: accessing non-static field " << PrettyField(f) << " as static";
213 } else {
214 LOG(ERROR) << "JNI ERROR: accessing static field " << PrettyField(f) << " as non-static";
215 }
216 JniAbort();
217 return;
218 }
219 }
220
221 /*
222 * Verify that this instance field ID is valid for this object.
223 *
224 * Assumes "jobj" has already been validated.
225 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700226 void CheckInstanceFieldID(jobject java_object, jfieldID fid) {
227 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700228
229 Object* o = Decode<Object*>(ts, java_object);
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700230 if (o == NULL || !Heap::IsHeapAddress(o)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700231 LOG(ERROR) << "JNI ERROR: field operation on invalid " << GetIndirectRefKind(java_object) << ": " << java_object;
232 JniAbort();
233 return;
234 }
235
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700236 Field* f = CheckFieldID(fid);
237 if (f == NULL) {
238 return;
239 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700240 Class* f_type = f->GetType();
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700241 // check invariant that all jfieldIDs have resolved types
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 DCHECK(f_type != NULL);
Elliott Hughesa2501992011-08-26 19:39:54 -0700243 Class* c = o->GetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700244 if (c->FindInstanceField(f->GetName()->ToModifiedUtf8(), f_type) == NULL) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700245 LOG(ERROR) << "JNI ERROR: jfieldID " << PrettyField(f) << " not valid for an object of class " << PrettyTypeOf(o);
Elliott Hughesa2501992011-08-26 19:39:54 -0700246 JniAbort();
247 }
248 }
249
250 /*
251 * Verify that the pointer value is non-NULL.
252 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700253 void CheckNonNull(const void* ptr) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700254 if (ptr == NULL) {
255 LOG(ERROR) << "JNI ERROR: invalid null pointer";
256 JniAbort();
257 }
258 }
259
260 /*
261 * Verify that the method's return type matches the type of call.
262 * 'expectedType' will be "L" for all objects, including arrays.
263 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700264 void CheckSig(jmethodID mid, const char* expectedType, bool isStatic) {
265 ScopedJniThreadState ts(env_);
266 const Method* m = CheckMethodID(mid);
267 if (m == NULL) {
268 return;
269 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700270 if (*expectedType != m->GetShorty()->CharAt(0)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700271 LOG(ERROR) << "JNI ERROR: expected return type '" << *expectedType << "' calling " << PrettyMethod(m);
Elliott Hughesa2501992011-08-26 19:39:54 -0700272 JniAbort();
273 } else if (isStatic && !m->IsStatic()) {
274 if (isStatic) {
275 LOG(ERROR) << "JNI ERROR: calling non-static method " << PrettyMethod(m) << " with static call";
276 } else {
277 LOG(ERROR) << "JNI ERROR: calling static method " << PrettyMethod(m) << " with non-static call";
278 }
279 JniAbort();
280 }
281 }
282
283 /*
284 * Verify that this static field ID is valid for this class.
285 *
286 * Assumes "java_class" has already been validated.
287 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700288 void CheckStaticFieldID(jclass java_class, jfieldID fid) {
289 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700290 Class* c = Decode<Class*>(ts, java_class);
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700291 const Field* f = CheckFieldID(fid);
292 if (f == NULL) {
293 return;
294 }
Elliott Hughesa2501992011-08-26 19:39:54 -0700295 if (f->GetDeclaringClass() != c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700296 LOG(ERROR) << "JNI ERROR: static jfieldID " << fid << " not valid for class " << PrettyClass(c);
Elliott Hughesa2501992011-08-26 19:39:54 -0700297 JniAbort();
298 }
299 }
300
301 /*
302 * Verify that "mid" is appropriate for "clazz".
303 *
304 * A mismatch isn't dangerous, because the jmethodID defines the class. In
305 * fact, jclazz is unused in the implementation. It's best if we don't
306 * allow bad code in the system though.
307 *
308 * Instances of "jclazz" must be instances of the method's declaring class.
309 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700310 void CheckStaticMethod(jclass java_class, jmethodID mid) {
311 ScopedJniThreadState ts(env_);
312 const Method* m = CheckMethodID(mid);
313 if (m == NULL) {
314 return;
315 }
Elliott Hughesa2501992011-08-26 19:39:54 -0700316 Class* c = Decode<Class*>(ts, java_class);
Elliott Hughesa2501992011-08-26 19:39:54 -0700317 if (!c->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700318 LOG(ERROR) << "JNI ERROR: can't call static " << PrettyMethod(m) << " on class " << PrettyClass(c);
Elliott Hughesa2501992011-08-26 19:39:54 -0700319 JniAbort();
320 }
321 }
322
323 /*
324 * Verify that "mid" is appropriate for "jobj".
325 *
326 * Make sure the object is an instance of the method's declaring class.
327 * (Note the mid might point to a declaration in an interface; this
328 * will be handled automatically by the instanceof check.)
329 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700330 void CheckVirtualMethod(jobject java_object, jmethodID mid) {
331 ScopedJniThreadState ts(env_);
332 const Method* m = CheckMethodID(mid);
333 if (m == NULL) {
334 return;
335 }
Elliott Hughesa2501992011-08-26 19:39:54 -0700336 Object* o = Decode<Object*>(ts, java_object);
Elliott Hughesa2501992011-08-26 19:39:54 -0700337 if (!o->InstanceOf(m->GetDeclaringClass())) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700338 LOG(ERROR) << "JNI ERROR: can't call " << PrettyMethod(m) << " on instance of " << PrettyTypeOf(o);
Elliott Hughesa2501992011-08-26 19:39:54 -0700339 JniAbort();
340 }
341 }
342
343 /**
344 * The format string is a sequence of the following characters,
345 * and must be followed by arguments of the corresponding types
346 * in the same order.
347 *
348 * Java primitive types:
349 * B - jbyte
350 * C - jchar
351 * D - jdouble
352 * F - jfloat
353 * I - jint
354 * J - jlong
355 * S - jshort
356 * Z - jboolean (shown as true and false)
357 * V - void
358 *
359 * Java reference types:
360 * L - jobject
361 * a - jarray
362 * c - jclass
363 * s - jstring
364 *
365 * JNI types:
366 * b - jboolean (shown as JNI_TRUE and JNI_FALSE)
367 * f - jfieldID
368 * m - jmethodID
369 * p - void*
370 * r - jint (for release mode arguments)
371 * u - const char* (modified UTF-8)
372 * z - jsize (for lengths; use i if negative values are okay)
373 * v - JavaVM*
374 * E - JNIEnv*
375 * . - no argument; just print "..." (used for varargs JNI calls)
376 *
377 * Use the kFlag_NullableUtf flag where 'u' field(s) are nullable.
378 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700379 void Check(bool entry, const char* fmt0, ...) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700380 va_list ap;
381
Elliott Hughesa0957642011-09-02 14:27:33 -0700382 const Method* traceMethod = NULL;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700383 if ((!vm_->trace.empty() || vm_->log_third_party_jni) && has_method_) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700384 // We need to guard some of the invocation interface's calls: a bad caller might
385 // use DetachCurrentThread or GetEnv on a thread that's not yet attached.
Elliott Hughesa0957642011-09-02 14:27:33 -0700386 Thread* self = Thread::Current();
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700387 if ((flags_ & kFlag_Invocation) == 0 || self != NULL) {
Elliott Hughesa0957642011-09-02 14:27:33 -0700388 traceMethod = self->GetCurrentMethod();
Elliott Hughesa2501992011-08-26 19:39:54 -0700389 }
390 }
Elliott Hughesa0957642011-09-02 14:27:33 -0700391
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700392 if (traceMethod != NULL && ShouldTrace(vm_, traceMethod)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700393 va_start(ap, fmt0);
394 std::string msg;
395 for (const char* fmt = fmt0; *fmt;) {
396 char ch = *fmt++;
397 if (ch == 'B') { // jbyte
398 jbyte b = va_arg(ap, int);
399 if (b >= 0 && b < 10) {
400 StringAppendF(&msg, "%d", b);
401 } else {
402 StringAppendF(&msg, "%#x (%d)", b, b);
403 }
404 } else if (ch == 'C') { // jchar
405 jchar c = va_arg(ap, int);
406 if (c < 0x7f && c >= ' ') {
407 StringAppendF(&msg, "U+%x ('%c')", c, c);
408 } else {
409 StringAppendF(&msg, "U+%x", c);
410 }
411 } else if (ch == 'F' || ch == 'D') { // jfloat, jdouble
412 StringAppendF(&msg, "%g", va_arg(ap, double));
413 } else if (ch == 'I' || ch == 'S') { // jint, jshort
414 StringAppendF(&msg, "%d", va_arg(ap, int));
415 } else if (ch == 'J') { // jlong
416 StringAppendF(&msg, "%lld", va_arg(ap, jlong));
417 } else if (ch == 'Z') { // jboolean
418 StringAppendF(&msg, "%s", va_arg(ap, int) ? "true" : "false");
419 } else if (ch == 'V') { // void
420 msg += "void";
421 } else if (ch == 'v') { // JavaVM*
422 JavaVM* vm = va_arg(ap, JavaVM*);
423 StringAppendF(&msg, "(JavaVM*)%p", vm);
424 } else if (ch == 'E') { // JNIEnv*
425 JNIEnv* env = va_arg(ap, JNIEnv*);
426 StringAppendF(&msg, "(JNIEnv*)%p", env);
427 } else if (ch == 'L' || ch == 'a' || ch == 's') { // jobject, jarray, jstring
428 // For logging purposes, these are identical.
429 jobject o = va_arg(ap, jobject);
430 if (o == NULL) {
431 msg += "NULL";
432 } else {
433 StringAppendF(&msg, "%p", o);
434 }
435 } else if (ch == 'b') { // jboolean (JNI-style)
436 jboolean b = va_arg(ap, int);
437 msg += (b ? "JNI_TRUE" : "JNI_FALSE");
438 } else if (ch == 'c') { // jclass
439 jclass jc = va_arg(ap, jclass);
440 Class* c = reinterpret_cast<Class*>(Thread::Current()->DecodeJObject(jc));
441 if (c == NULL) {
442 msg += "NULL";
443 } else if (c == kInvalidIndirectRefObject || !Heap::IsHeapAddress(c)) {
444 StringAppendF(&msg, "%p(INVALID)", jc);
445 } else {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700446 msg += PrettyClass(c);
Elliott Hughesa2501992011-08-26 19:39:54 -0700447 if (!entry) {
448 StringAppendF(&msg, " (%p)", jc);
449 }
450 }
451 } else if (ch == 'f') { // jfieldID
452 jfieldID fid = va_arg(ap, jfieldID);
Elliott Hughes5ee7a8b2011-09-13 16:40:07 -0700453 Field* f = reinterpret_cast<Field*>(fid);
Elliott Hughesa2501992011-08-26 19:39:54 -0700454 msg += PrettyField(f);
455 if (!entry) {
456 StringAppendF(&msg, " (%p)", fid);
457 }
458 } else if (ch == 'z') { // non-negative jsize
459 // You might expect jsize to be size_t, but it's not; it's the same as jint.
460 // We only treat this specially so we can do the non-negative check.
461 // TODO: maybe this wasn't worth it?
462 jint i = va_arg(ap, jint);
463 StringAppendF(&msg, "%d", i);
464 } else if (ch == 'm') { // jmethodID
465 jmethodID mid = va_arg(ap, jmethodID);
Elliott Hughes5ee7a8b2011-09-13 16:40:07 -0700466 Method* m = reinterpret_cast<Method*>(mid);
Elliott Hughesa2501992011-08-26 19:39:54 -0700467 msg += PrettyMethod(m);
468 if (!entry) {
469 StringAppendF(&msg, " (%p)", mid);
470 }
471 } else if (ch == 'p') { // void* ("pointer")
472 void* p = va_arg(ap, void*);
473 if (p == NULL) {
474 msg += "NULL";
475 } else {
476 StringAppendF(&msg, "(void*) %p", p);
477 }
478 } else if (ch == 'r') { // jint (release mode)
479 jint releaseMode = va_arg(ap, jint);
480 if (releaseMode == 0) {
481 msg += "0";
482 } else if (releaseMode == JNI_ABORT) {
483 msg += "JNI_ABORT";
484 } else if (releaseMode == JNI_COMMIT) {
485 msg += "JNI_COMMIT";
486 } else {
487 StringAppendF(&msg, "invalid release mode %d", releaseMode);
488 }
489 } else if (ch == 'u') { // const char* (modified UTF-8)
490 const char* utf = va_arg(ap, const char*);
491 if (utf == NULL) {
492 msg += "NULL";
493 } else {
494 StringAppendF(&msg, "\"%s\"", utf);
495 }
496 } else if (ch == '.') {
497 msg += "...";
498 } else {
499 LOG(ERROR) << "unknown trace format specifier: " << ch;
500 JniAbort();
501 return;
502 }
503 if (*fmt) {
504 StringAppendF(&msg, ", ");
505 }
506 }
507 va_end(ap);
508
509 if (entry) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700510 if (has_method_) {
Elliott Hughesa0957642011-09-02 14:27:33 -0700511 std::string methodName(PrettyMethod(traceMethod, false));
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700512 LOG(INFO) << "JNI: " << methodName << " -> " << function_name_ << "(" << msg << ")";
513 indent_ = methodName.size() + 1;
Elliott Hughesa2501992011-08-26 19:39:54 -0700514 } else {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700515 LOG(INFO) << "JNI: -> " << function_name_ << "(" << msg << ")";
516 indent_ = 0;
Elliott Hughesa2501992011-08-26 19:39:54 -0700517 }
518 } else {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700519 LOG(INFO) << StringPrintf("JNI: %*s<- %s returned %s", indent_, "", function_name_, msg.c_str());
Elliott Hughesa2501992011-08-26 19:39:54 -0700520 }
521 }
522
523 // We always do the thorough checks on entry, and never on exit...
524 if (entry) {
525 va_start(ap, fmt0);
526 for (const char* fmt = fmt0; *fmt; ++fmt) {
527 char ch = *fmt;
528 if (ch == 'a') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700529 CheckArray(va_arg(ap, jarray));
Elliott Hughesa2501992011-08-26 19:39:54 -0700530 } else if (ch == 'c') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700531 CheckInstance(kClass, va_arg(ap, jclass));
Elliott Hughesa2501992011-08-26 19:39:54 -0700532 } else if (ch == 'L') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700533 CheckObject(va_arg(ap, jobject));
Elliott Hughesa2501992011-08-26 19:39:54 -0700534 } else if (ch == 'r') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700535 CheckReleaseMode(va_arg(ap, jint));
Elliott Hughesa2501992011-08-26 19:39:54 -0700536 } else if (ch == 's') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700537 CheckInstance(kString, va_arg(ap, jstring));
Elliott Hughesa2501992011-08-26 19:39:54 -0700538 } else if (ch == 'u') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700539 if ((flags_ & kFlag_Release) != 0) {
540 CheckNonNull(va_arg(ap, const char*));
Elliott Hughesa2501992011-08-26 19:39:54 -0700541 } else {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700542 bool nullable = ((flags_ & kFlag_NullableUtf) != 0);
543 CheckUtfString(va_arg(ap, const char*), nullable);
Elliott Hughesa2501992011-08-26 19:39:54 -0700544 }
545 } else if (ch == 'z') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700546 CheckLengthPositive(va_arg(ap, jsize));
Elliott Hughesa2501992011-08-26 19:39:54 -0700547 } else if (strchr("BCISZbfmpEv", ch) != NULL) {
548 va_arg(ap, int); // Skip this argument.
549 } else if (ch == 'D' || ch == 'F') {
550 va_arg(ap, double); // Skip this argument.
551 } else if (ch == 'J') {
552 va_arg(ap, long); // Skip this argument.
553 } else if (ch == '.') {
554 } else {
555 LOG(FATAL) << "unknown check format specifier: " << ch;
556 }
557 }
558 va_end(ap);
559 }
560 }
561
562private:
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700563 void Init(JNIEnv* env, JavaVM* vm, int flags, const char* functionName, bool hasMethod) {
564 env_ = reinterpret_cast<JNIEnvExt*>(env);
565 vm_ = reinterpret_cast<JavaVMExt*>(vm);
566 flags_ = flags;
567 function_name_ = functionName;
Elliott Hughesa2501992011-08-26 19:39:54 -0700568
569 // Set "hasMethod" to true if we have a valid thread with a method pointer.
570 // We won't have one before attaching a thread, after detaching a thread, or
571 // after destroying the VM.
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700572 has_method_ = hasMethod;
Elliott Hughesa2501992011-08-26 19:39:54 -0700573 }
574
575 /*
576 * Verify that "array" is non-NULL and points to an Array object.
577 *
578 * Since we're dealing with objects, switch to "running" mode.
579 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700580 void CheckArray(jarray java_array) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700581 if (java_array == NULL) {
582 LOG(ERROR) << "JNI ERROR: received null array";
583 JniAbort();
584 return;
585 }
586
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700587 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700588 Array* a = Decode<Array*>(ts, java_array);
589 if (!Heap::IsHeapAddress(a)) {
590 LOG(ERROR) << "JNI ERROR: jarray is an invalid " << GetIndirectRefKind(java_array) << ": " << reinterpret_cast<void*>(java_array);
591 JniAbort();
592 } else if (!a->IsArrayInstance()) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700593 LOG(ERROR) << "JNI ERROR: jarray argument has non-array type: " << PrettyTypeOf(a);
Elliott Hughesa2501992011-08-26 19:39:54 -0700594 JniAbort();
595 }
596 }
597
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700598 void CheckLengthPositive(jsize length) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700599 if (length < 0) {
600 LOG(ERROR) << "JNI ERROR: negative jsize: " << length;
601 JniAbort();
602 }
603 }
604
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700605 Field* CheckFieldID(jfieldID fid) {
606 if (fid == NULL) {
607 LOG(ERROR) << "JNI ERROR: null jfieldID";
608 JniAbort();
609 return NULL;
610 }
611 Field* f = DecodeField(fid);
612 if (!Heap::IsHeapAddress(f)) {
613 LOG(ERROR) << "JNI ERROR: invalid jfieldID: " << fid;
614 JniAbort();
615 return NULL;
616 }
617 return f;
618 }
619
620 Method* CheckMethodID(jmethodID mid) {
621 if (mid == NULL) {
622 LOG(ERROR) << "JNI ERROR: null jmethodID";
623 JniAbort();
624 return NULL;
625 }
626 Method* m = DecodeMethod(mid);
627 if (!Heap::IsHeapAddress(m)) {
628 LOG(ERROR) << "JNI ERROR: invalid jmethodID: " << mid;
629 JniAbort();
630 return NULL;
631 }
632 return m;
633 }
634
Elliott Hughesa2501992011-08-26 19:39:54 -0700635 /*
636 * Verify that "jobj" is a valid object, and that it's an object that JNI
637 * is allowed to know about. We allow NULL references.
638 *
639 * Switches to "running" mode before performing checks.
640 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700641 void CheckObject(jobject java_object) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700642 if (java_object == NULL) {
643 return;
644 }
645
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700646 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700647
648 Object* o = Decode<Object*>(ts, java_object);
649 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700650 // TODO: when we remove work_around_app_jni_bugs, this should be impossible.
Elliott Hughesa2501992011-08-26 19:39:54 -0700651 LOG(ERROR) << "JNI ERROR: native code passing in reference to invalid " << GetIndirectRefKind(java_object) << ": " << java_object;
652 JniAbort();
653 }
654 }
655
656 /*
657 * Verify that the "mode" argument passed to a primitive array Release
658 * function is one of the valid values.
659 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700660 void CheckReleaseMode(jint mode) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700661 if (mode != 0 && mode != JNI_COMMIT && mode != JNI_ABORT) {
662 LOG(ERROR) << "JNI ERROR: bad value for release mode: " << mode;
663 JniAbort();
664 }
665 }
666
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700667 void CheckThread(int flags) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700668 Thread* self = Thread::Current();
669 if (self == NULL) {
670 LOG(ERROR) << "JNI ERROR: non-VM thread making JNI calls";
671 JniAbort();
672 return;
673 }
674
675 // Get the *correct* JNIEnv by going through our TLS pointer.
676 JNIEnvExt* threadEnv = self->GetJniEnv();
677
678 /*
679 * Verify that the current thread is (a) attached and (b) associated with
680 * this particular instance of JNIEnv.
681 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700682 if (env_ != threadEnv) {
683 LOG(ERROR) << "JNI ERROR: thread " << *self << " using JNIEnv* from thread " << *env_->self;
Elliott Hughesa2501992011-08-26 19:39:54 -0700684 // If we're keeping broken code limping along, we need to suppress the abort...
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700685 if (!env_->work_around_app_jni_bugs) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700686 JniAbort();
687 return;
688 }
689 }
690
691 /*
692 * Verify that, if this thread previously made a critical "get" call, we
693 * do the corresponding "release" call before we try anything else.
694 */
695 switch (flags & kFlag_CritMask) {
696 case kFlag_CritOkay: // okay to call this method
697 break;
698 case kFlag_CritBad: // not okay to call
699 if (threadEnv->critical) {
700 LOG(ERROR) << "JNI ERROR: thread " << *self << " using JNI after critical get";
701 JniAbort();
702 return;
703 }
704 break;
705 case kFlag_CritGet: // this is a "get" call
706 /* don't check here; we allow nested gets */
707 threadEnv->critical++;
708 break;
709 case kFlag_CritRelease: // this is a "release" call
710 threadEnv->critical--;
711 if (threadEnv->critical < 0) {
712 LOG(ERROR) << "JNI ERROR: thread " << *self << " called too many critical releases";
713 JniAbort();
714 return;
715 }
716 break;
717 default:
718 LOG(FATAL) << "bad flags (internal error): " << flags;
719 }
720
721 /*
722 * Verify that, if an exception has been raised, the native code doesn't
723 * make any JNI calls other than the Exception* methods.
724 */
725 if ((flags & kFlag_ExcepOkay) == 0 && self->IsExceptionPending()) {
726 LOG(ERROR) << "JNI ERROR: JNI method called with exception pending";
Elliott Hughese6087632011-09-26 12:18:25 -0700727 LOG(ERROR) << "Pending exception is:";
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700728 LOG(ERROR) << jniGetStackTrace(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700729 JniAbort();
730 return;
731 }
732 }
733
734 /*
735 * Verify that "bytes" points to valid "modified UTF-8" data.
736 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700737 void CheckUtfString(const char* bytes, bool nullable) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700738 if (bytes == NULL) {
739 if (!nullable) {
740 LOG(ERROR) << "JNI ERROR: non-nullable const char* was NULL";
741 JniAbort();
742 return;
743 }
744 return;
745 }
746
747 const char* errorKind = NULL;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700748 uint8_t utf8 = CheckUtfBytes(bytes, &errorKind);
Elliott Hughesa2501992011-08-26 19:39:54 -0700749 if (errorKind != NULL) {
750 LOG(ERROR) << "JNI ERROR: input is not valid UTF-8: illegal " << errorKind << " byte " << StringPrintf("%#x", utf8);
751 LOG(ERROR) << " string: '" << bytes << "'";
752 JniAbort();
753 return;
754 }
755 }
756
757 enum InstanceKind {
758 kClass,
759 kDirectByteBuffer,
760 kString,
761 kThrowable,
762 };
763
764 /*
765 * Verify that "jobj" is a valid non-NULL object reference, and points to
766 * an instance of expectedClass.
767 *
768 * Because we're looking at an object on the GC heap, we have to switch
769 * to "running" mode before doing the checks.
770 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700771 void CheckInstance(InstanceKind kind, jobject java_object) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700772 const char* what = NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700773 switch (kind) {
774 case kClass:
775 what = "jclass";
776 break;
777 case kDirectByteBuffer:
778 what = "direct ByteBuffer";
779 break;
780 case kString:
781 what = "jstring";
782 break;
783 case kThrowable:
784 what = "jthrowable";
785 break;
786 default:
787 CHECK(false) << static_cast<int>(kind);
788 }
789
790 if (java_object == NULL) {
791 LOG(ERROR) << "JNI ERROR: received null " << what;
792 JniAbort();
793 return;
794 }
795
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700796 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700797 Object* obj = Decode<Object*>(ts, java_object);
798 if (!Heap::IsHeapAddress(obj)) {
799 LOG(ERROR) << "JNI ERROR: " << what << " is an invalid " << GetIndirectRefKind(java_object) << ": " << java_object;
800 JniAbort();
801 return;
802 }
803
804 bool okay = true;
805 switch (kind) {
806 case kClass:
807 okay = obj->IsClass();
808 break;
809 case kDirectByteBuffer:
810 // TODO
811 break;
812 case kString:
813 okay = obj->IsString();
814 break;
815 case kThrowable:
816 // TODO
817 break;
818 }
819 if (!okay) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700820 LOG(ERROR) << "JNI ERROR: " << what << " has wrong type: " << PrettyTypeOf(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700821 JniAbort();
822 }
823 }
824
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700825 static uint8_t CheckUtfBytes(const char* bytes, const char** errorKind) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700826 while (*bytes != '\0') {
827 uint8_t utf8 = *(bytes++);
828 // Switch on the high four bits.
829 switch (utf8 >> 4) {
830 case 0x00:
831 case 0x01:
832 case 0x02:
833 case 0x03:
834 case 0x04:
835 case 0x05:
836 case 0x06:
837 case 0x07:
838 // Bit pattern 0xxx. No need for any extra bytes.
839 break;
840 case 0x08:
841 case 0x09:
842 case 0x0a:
843 case 0x0b:
844 case 0x0f:
845 /*
846 * Bit pattern 10xx or 1111, which are illegal start bytes.
847 * Note: 1111 is valid for normal UTF-8, but not the
848 * modified UTF-8 used here.
849 */
850 *errorKind = "start";
851 return utf8;
852 case 0x0e:
853 // Bit pattern 1110, so there are two additional bytes.
854 utf8 = *(bytes++);
855 if ((utf8 & 0xc0) != 0x80) {
856 *errorKind = "continuation";
857 return utf8;
858 }
859 // Fall through to take care of the final byte.
860 case 0x0c:
861 case 0x0d:
862 // Bit pattern 110x, so there is one additional byte.
863 utf8 = *(bytes++);
864 if ((utf8 & 0xc0) != 0x80) {
865 *errorKind = "continuation";
866 return utf8;
867 }
868 break;
869 }
870 }
871 return 0;
872 }
873
874 void JniAbort() {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700875 ::art::JniAbort(function_name_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700876 }
877
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700878 JNIEnvExt* env_;
879 JavaVMExt* vm_;
880 const char* function_name_;
881 int flags_;
882 bool has_method_;
883 size_t indent_;
Elliott Hughesa2501992011-08-26 19:39:54 -0700884
885 DISALLOW_COPY_AND_ASSIGN(ScopedCheck);
886};
887
888#define CHECK_JNI_ENTRY(flags, types, args...) \
889 ScopedCheck sc(env, flags, __FUNCTION__); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700890 sc.Check(true, types, ##args)
Elliott Hughesa2501992011-08-26 19:39:54 -0700891
892#define CHECK_JNI_EXIT(type, exp) ({ \
893 typeof (exp) _rc = (exp); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700894 sc.Check(false, type, _rc); \
Elliott Hughesa2501992011-08-26 19:39:54 -0700895 _rc; })
896#define CHECK_JNI_EXIT_VOID() \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700897 sc.Check(false, "V")
Elliott Hughesa2501992011-08-26 19:39:54 -0700898
899/*
900 * ===========================================================================
901 * Guarded arrays
902 * ===========================================================================
903 */
904
905#define kGuardLen 512 /* must be multiple of 2 */
906#define kGuardPattern 0xd5e3 /* uncommon values; d5e3d5e3 invalid addr */
907#define kGuardMagic 0xffd5aa96
908
909/* this gets tucked in at the start of the buffer; struct size must be even */
910struct GuardedCopy {
911 uint32_t magic;
912 uLong adler;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700913 size_t original_length;
914 const void* original_ptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700915
916 /* find the GuardedCopy given the pointer into the "live" data */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700917 static inline const GuardedCopy* FromData(const void* dataBuf) {
918 return reinterpret_cast<const GuardedCopy*>(ActualBuffer(dataBuf));
Elliott Hughesa2501992011-08-26 19:39:54 -0700919 }
920
921 /*
922 * Create an over-sized buffer to hold the contents of "buf". Copy it in,
923 * filling in the area around it with guard data.
924 *
925 * We use a 16-bit pattern to make a rogue memset less likely to elude us.
926 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700927 static void* Create(const void* buf, size_t len, bool modOkay) {
928 size_t newLen = ActualLength(len);
929 uint8_t* newBuf = DebugAlloc(newLen);
Elliott Hughesa2501992011-08-26 19:39:54 -0700930
931 /* fill it in with a pattern */
932 uint16_t* pat = (uint16_t*) newBuf;
933 for (size_t i = 0; i < newLen / 2; i++) {
934 *pat++ = kGuardPattern;
935 }
936
937 /* copy the data in; note "len" could be zero */
938 memcpy(newBuf + kGuardLen / 2, buf, len);
939
940 /* if modification is not expected, grab a checksum */
941 uLong adler = 0;
942 if (!modOkay) {
943 adler = adler32(0L, Z_NULL, 0);
944 adler = adler32(adler, (const Bytef*)buf, len);
945 *(uLong*)newBuf = adler;
946 }
947
948 GuardedCopy* pExtra = reinterpret_cast<GuardedCopy*>(newBuf);
949 pExtra->magic = kGuardMagic;
950 pExtra->adler = adler;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700951 pExtra->original_ptr = buf;
952 pExtra->original_length = len;
Elliott Hughesa2501992011-08-26 19:39:54 -0700953
954 return newBuf + kGuardLen / 2;
955 }
956
957 /*
958 * Free up the guard buffer, scrub it, and return the original pointer.
959 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700960 static void* Destroy(void* dataBuf) {
961 const GuardedCopy* pExtra = GuardedCopy::FromData(dataBuf);
962 void* original_ptr = (void*) pExtra->original_ptr;
963 size_t len = pExtra->original_length;
964 DebugFree(dataBuf, len);
965 return original_ptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700966 }
967
968 /*
969 * Verify the guard area and, if "modOkay" is false, that the data itself
970 * has not been altered.
971 *
972 * The caller has already checked that "dataBuf" is non-NULL.
973 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700974 static void Check(const char* functionName, const void* dataBuf, bool modOkay) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700975 static const uint32_t kMagicCmp = kGuardMagic;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700976 const uint8_t* fullBuf = ActualBuffer(dataBuf);
977 const GuardedCopy* pExtra = GuardedCopy::FromData(dataBuf);
Elliott Hughesa2501992011-08-26 19:39:54 -0700978
979 /*
980 * Before we do anything with "pExtra", check the magic number. We
981 * do the check with memcmp rather than "==" in case the pointer is
982 * unaligned. If it points to completely bogus memory we're going
983 * to crash, but there's no easy way around that.
984 */
985 if (memcmp(&pExtra->magic, &kMagicCmp, 4) != 0) {
986 uint8_t buf[4];
987 memcpy(buf, &pExtra->magic, 4);
988 LOG(ERROR) << StringPrintf("JNI: guard magic does not match "
989 "(found 0x%02x%02x%02x%02x) -- incorrect data pointer %p?",
990 buf[3], buf[2], buf[1], buf[0], dataBuf); /* assume little endian */
991 JniAbort(functionName);
992 }
993
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700994 size_t len = pExtra->original_length;
Elliott Hughesa2501992011-08-26 19:39:54 -0700995
996 /* check bottom half of guard; skip over optional checksum storage */
997 const uint16_t* pat = (uint16_t*) fullBuf;
998 for (size_t i = sizeof(GuardedCopy) / 2; i < (kGuardLen / 2 - sizeof(GuardedCopy)) / 2; i++) {
999 if (pat[i] != kGuardPattern) {
1000 LOG(ERROR) << "JNI: guard pattern(1) disturbed at " << (void*) fullBuf << " + " << (i*2);
1001 JniAbort(functionName);
1002 }
1003 }
1004
1005 int offset = kGuardLen / 2 + len;
1006 if (offset & 0x01) {
1007 /* odd byte; expected value depends on endian-ness of host */
1008 const uint16_t patSample = kGuardPattern;
1009 if (fullBuf[offset] != ((const uint8_t*) &patSample)[1]) {
1010 LOG(ERROR) << "JNI: guard pattern disturbed in odd byte after "
1011 << (void*) fullBuf << " (+" << offset << ") "
1012 << StringPrintf("0x%02x 0x%02x", fullBuf[offset], ((const uint8_t*) &patSample)[1]);
1013 JniAbort(functionName);
1014 }
1015 offset++;
1016 }
1017
1018 /* check top half of guard */
1019 pat = (uint16_t*) (fullBuf + offset);
1020 for (size_t i = 0; i < kGuardLen / 4; i++) {
1021 if (pat[i] != kGuardPattern) {
1022 LOG(ERROR) << "JNI: guard pattern(2) disturbed at " << (void*) fullBuf << " + " << (offset + i*2);
1023 JniAbort(functionName);
1024 }
1025 }
1026
1027 /*
1028 * If modification is not expected, verify checksum. Strictly speaking
1029 * this is wrong: if we told the client that we made a copy, there's no
1030 * reason they can't alter the buffer.
1031 */
1032 if (!modOkay) {
1033 uLong adler = adler32(0L, Z_NULL, 0);
1034 adler = adler32(adler, (const Bytef*)dataBuf, len);
1035 if (pExtra->adler != adler) {
1036 LOG(ERROR) << StringPrintf("JNI: buffer modified (0x%08lx vs 0x%08lx) at addr %p", pExtra->adler, adler, dataBuf);
1037 JniAbort(functionName);
1038 }
1039 }
1040 }
1041
1042 private:
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001043 static uint8_t* DebugAlloc(size_t len) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001044 void* result = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
1045 if (result == MAP_FAILED) {
1046 PLOG(FATAL) << "GuardedCopy::create mmap(" << len << ") failed";
1047 }
1048 return reinterpret_cast<uint8_t*>(result);
1049 }
1050
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001051 static void DebugFree(void* dataBuf, size_t len) {
1052 uint8_t* fullBuf = ActualBuffer(dataBuf);
1053 size_t totalByteCount = ActualLength(len);
Elliott Hughesa2501992011-08-26 19:39:54 -07001054 // TODO: we could mprotect instead, and keep the allocation around for a while.
1055 // This would be even more expensive, but it might catch more errors.
1056 // if (mprotect(fullBuf, totalByteCount, PROT_NONE) != 0) {
1057 // LOGW("mprotect(PROT_NONE) failed: %s", strerror(errno));
1058 // }
1059 if (munmap(fullBuf, totalByteCount) != 0) {
1060 PLOG(FATAL) << "munmap(" << (void*) fullBuf << ", " << totalByteCount << ") failed";
1061 }
1062 }
1063
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001064 static const uint8_t* ActualBuffer(const void* dataBuf) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001065 return reinterpret_cast<const uint8_t*>(dataBuf) - kGuardLen / 2;
1066 }
1067
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001068 static uint8_t* ActualBuffer(void* dataBuf) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001069 return reinterpret_cast<uint8_t*>(dataBuf) - kGuardLen / 2;
1070 }
1071
1072 // Underlying length of a user allocation of 'length' bytes.
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001073 static size_t ActualLength(size_t length) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001074 return (length + kGuardLen + 1) & ~0x01;
1075 }
1076};
1077
1078/*
1079 * Create a guarded copy of a primitive array. Modifications to the copied
1080 * data are allowed. Returns a pointer to the copied data.
1081 */
1082void* CreateGuardedPACopy(JNIEnv* env, const jarray java_array, jboolean* isCopy) {
1083 ScopedJniThreadState ts(env);
1084
1085 Array* a = Decode<Array*>(ts, java_array);
1086 size_t byte_count = a->GetLength() * a->GetClass()->GetComponentSize();
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001087 void* result = GuardedCopy::Create(a->GetRawData(), byte_count, true);
Elliott Hughesa2501992011-08-26 19:39:54 -07001088 if (isCopy != NULL) {
1089 *isCopy = JNI_TRUE;
1090 }
1091 return result;
1092}
1093
1094/*
1095 * Perform the array "release" operation, which may or may not copy data
1096 * back into the VM, and may or may not release the underlying storage.
1097 */
1098void ReleaseGuardedPACopy(JNIEnv* env, jarray java_array, void* dataBuf, int mode) {
1099 if (reinterpret_cast<uintptr_t>(dataBuf) == kNoCopyMagic) {
1100 return;
1101 }
1102
1103 ScopedJniThreadState ts(env);
1104 Array* a = Decode<Array*>(ts, java_array);
1105
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001106 GuardedCopy::Check(__FUNCTION__, dataBuf, true);
Elliott Hughesa2501992011-08-26 19:39:54 -07001107
1108 if (mode != JNI_ABORT) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001109 size_t len = GuardedCopy::FromData(dataBuf)->original_length;
Elliott Hughesbf86d042011-08-31 17:53:14 -07001110 memcpy(a->GetRawData(), dataBuf, len);
Elliott Hughesa2501992011-08-26 19:39:54 -07001111 }
1112 if (mode != JNI_COMMIT) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001113 GuardedCopy::Destroy(dataBuf);
Elliott Hughesa2501992011-08-26 19:39:54 -07001114 }
1115}
1116
1117/*
1118 * ===========================================================================
1119 * JNI functions
1120 * ===========================================================================
1121 */
1122
1123class CheckJNI {
1124 public:
1125 static jint GetVersion(JNIEnv* env) {
1126 CHECK_JNI_ENTRY(kFlag_Default, "E", env);
1127 return CHECK_JNI_EXIT("I", baseEnv(env)->GetVersion(env));
1128 }
1129
1130 static jclass DefineClass(JNIEnv* env, const char* name, jobject loader, const jbyte* buf, jsize bufLen) {
1131 CHECK_JNI_ENTRY(kFlag_Default, "EuLpz", env, name, loader, buf, bufLen);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001132 sc.CheckClassName(name);
Elliott Hughesa2501992011-08-26 19:39:54 -07001133 return CHECK_JNI_EXIT("c", baseEnv(env)->DefineClass(env, name, loader, buf, bufLen));
1134 }
1135
1136 static jclass FindClass(JNIEnv* env, const char* name) {
1137 CHECK_JNI_ENTRY(kFlag_Default, "Eu", env, name);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001138 sc.CheckClassName(name);
Elliott Hughesa2501992011-08-26 19:39:54 -07001139 return CHECK_JNI_EXIT("c", baseEnv(env)->FindClass(env, name));
1140 }
1141
1142 static jclass GetSuperclass(JNIEnv* env, jclass clazz) {
1143 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1144 return CHECK_JNI_EXIT("c", baseEnv(env)->GetSuperclass(env, clazz));
1145 }
1146
1147 static jboolean IsAssignableFrom(JNIEnv* env, jclass clazz1, jclass clazz2) {
1148 CHECK_JNI_ENTRY(kFlag_Default, "Ecc", env, clazz1, clazz2);
1149 return CHECK_JNI_EXIT("b", baseEnv(env)->IsAssignableFrom(env, clazz1, clazz2));
1150 }
1151
1152 static jmethodID FromReflectedMethod(JNIEnv* env, jobject method) {
1153 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, method);
1154 // TODO: check that 'field' is a java.lang.reflect.Method.
1155 return CHECK_JNI_EXIT("m", baseEnv(env)->FromReflectedMethod(env, method));
1156 }
1157
1158 static jfieldID FromReflectedField(JNIEnv* env, jobject field) {
1159 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, field);
1160 // TODO: check that 'field' is a java.lang.reflect.Field.
1161 return CHECK_JNI_EXIT("f", baseEnv(env)->FromReflectedField(env, field));
1162 }
1163
1164 static jobject ToReflectedMethod(JNIEnv* env, jclass cls, jmethodID mid, jboolean isStatic) {
1165 CHECK_JNI_ENTRY(kFlag_Default, "Ecmb", env, cls, mid, isStatic);
1166 return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedMethod(env, cls, mid, isStatic));
1167 }
1168
1169 static jobject ToReflectedField(JNIEnv* env, jclass cls, jfieldID fid, jboolean isStatic) {
1170 CHECK_JNI_ENTRY(kFlag_Default, "Ecfb", env, cls, fid, isStatic);
1171 return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedField(env, cls, fid, isStatic));
1172 }
1173
1174 static jint Throw(JNIEnv* env, jthrowable obj) {
1175 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1176 // TODO: check that 'obj' is a java.lang.Throwable.
1177 return CHECK_JNI_EXIT("I", baseEnv(env)->Throw(env, obj));
1178 }
1179
1180 static jint ThrowNew(JNIEnv* env, jclass clazz, const char* message) {
1181 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Ecu", env, clazz, message);
1182 return CHECK_JNI_EXIT("I", baseEnv(env)->ThrowNew(env, clazz, message));
1183 }
1184
1185 static jthrowable ExceptionOccurred(JNIEnv* env) {
1186 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1187 return CHECK_JNI_EXIT("L", baseEnv(env)->ExceptionOccurred(env));
1188 }
1189
1190 static void ExceptionDescribe(JNIEnv* env) {
1191 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1192 baseEnv(env)->ExceptionDescribe(env);
1193 CHECK_JNI_EXIT_VOID();
1194 }
1195
1196 static void ExceptionClear(JNIEnv* env) {
1197 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1198 baseEnv(env)->ExceptionClear(env);
1199 CHECK_JNI_EXIT_VOID();
1200 }
1201
1202 static void FatalError(JNIEnv* env, const char* msg) {
1203 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, msg);
1204 baseEnv(env)->FatalError(env, msg);
1205 CHECK_JNI_EXIT_VOID();
1206 }
1207
1208 static jint PushLocalFrame(JNIEnv* env, jint capacity) {
1209 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EI", env, capacity);
1210 return CHECK_JNI_EXIT("I", baseEnv(env)->PushLocalFrame(env, capacity));
1211 }
1212
1213 static jobject PopLocalFrame(JNIEnv* env, jobject res) {
1214 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, res);
1215 return CHECK_JNI_EXIT("L", baseEnv(env)->PopLocalFrame(env, res));
1216 }
1217
1218 static jobject NewGlobalRef(JNIEnv* env, jobject obj) {
1219 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1220 return CHECK_JNI_EXIT("L", baseEnv(env)->NewGlobalRef(env, obj));
1221 }
1222
1223 static jobject NewLocalRef(JNIEnv* env, jobject ref) {
1224 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, ref);
1225 return CHECK_JNI_EXIT("L", baseEnv(env)->NewLocalRef(env, ref));
1226 }
1227
1228 static void DeleteGlobalRef(JNIEnv* env, jobject globalRef) {
1229 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, globalRef);
1230 if (globalRef != NULL && GetIndirectRefKind(globalRef) != kGlobal) {
1231 LOG(ERROR) << "JNI ERROR: DeleteGlobalRef on " << GetIndirectRefKind(globalRef) << ": " << globalRef;
1232 JniAbort(__FUNCTION__);
1233 } else {
1234 baseEnv(env)->DeleteGlobalRef(env, globalRef);
1235 CHECK_JNI_EXIT_VOID();
1236 }
1237 }
1238
1239 static void DeleteWeakGlobalRef(JNIEnv* env, jweak weakGlobalRef) {
1240 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, weakGlobalRef);
1241 if (weakGlobalRef != NULL && GetIndirectRefKind(weakGlobalRef) != kWeakGlobal) {
1242 LOG(ERROR) << "JNI ERROR: DeleteWeakGlobalRef on " << GetIndirectRefKind(weakGlobalRef) << ": " << weakGlobalRef;
1243 JniAbort(__FUNCTION__);
1244 } else {
1245 baseEnv(env)->DeleteWeakGlobalRef(env, weakGlobalRef);
1246 CHECK_JNI_EXIT_VOID();
1247 }
1248 }
1249
1250 static void DeleteLocalRef(JNIEnv* env, jobject localRef) {
1251 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, localRef);
1252 if (localRef != NULL && GetIndirectRefKind(localRef) != kLocal) {
1253 LOG(ERROR) << "JNI ERROR: DeleteLocalRef on " << GetIndirectRefKind(localRef) << ": " << localRef;
1254 JniAbort(__FUNCTION__);
1255 } else {
1256 baseEnv(env)->DeleteLocalRef(env, localRef);
1257 CHECK_JNI_EXIT_VOID();
1258 }
1259 }
1260
1261 static jint EnsureLocalCapacity(JNIEnv *env, jint capacity) {
1262 CHECK_JNI_ENTRY(kFlag_Default, "EI", env, capacity);
1263 return CHECK_JNI_EXIT("I", baseEnv(env)->EnsureLocalCapacity(env, capacity));
1264 }
1265
1266 static jboolean IsSameObject(JNIEnv* env, jobject ref1, jobject ref2) {
1267 CHECK_JNI_ENTRY(kFlag_Default, "ELL", env, ref1, ref2);
1268 return CHECK_JNI_EXIT("b", baseEnv(env)->IsSameObject(env, ref1, ref2));
1269 }
1270
1271 static jobject AllocObject(JNIEnv* env, jclass clazz) {
1272 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1273 return CHECK_JNI_EXIT("L", baseEnv(env)->AllocObject(env, clazz));
1274 }
1275
1276 static jobject NewObject(JNIEnv* env, jclass clazz, jmethodID mid, ...) {
1277 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1278 va_list args;
1279 va_start(args, mid);
1280 jobject result = baseEnv(env)->NewObjectV(env, clazz, mid, args);
1281 va_end(args);
1282 return CHECK_JNI_EXIT("L", result);
1283 }
1284
1285 static jobject NewObjectV(JNIEnv* env, jclass clazz, jmethodID mid, va_list args) {
1286 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1287 return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectV(env, clazz, mid, args));
1288 }
1289
1290 static jobject NewObjectA(JNIEnv* env, jclass clazz, jmethodID mid, jvalue* args) {
1291 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1292 return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectA(env, clazz, mid, args));
1293 }
1294
1295 static jclass GetObjectClass(JNIEnv* env, jobject obj) {
1296 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1297 return CHECK_JNI_EXIT("c", baseEnv(env)->GetObjectClass(env, obj));
1298 }
1299
1300 static jboolean IsInstanceOf(JNIEnv* env, jobject obj, jclass clazz) {
1301 CHECK_JNI_ENTRY(kFlag_Default, "ELc", env, obj, clazz);
1302 return CHECK_JNI_EXIT("b", baseEnv(env)->IsInstanceOf(env, obj, clazz));
1303 }
1304
1305 static jmethodID GetMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1306 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1307 return CHECK_JNI_EXIT("m", baseEnv(env)->GetMethodID(env, clazz, name, sig));
1308 }
1309
1310 static jfieldID GetFieldID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1311 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1312 return CHECK_JNI_EXIT("f", baseEnv(env)->GetFieldID(env, clazz, name, sig));
1313 }
1314
1315 static jmethodID GetStaticMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1316 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1317 return CHECK_JNI_EXIT("m", baseEnv(env)->GetStaticMethodID(env, clazz, name, sig));
1318 }
1319
1320 static jfieldID GetStaticFieldID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1321 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1322 return CHECK_JNI_EXIT("f", baseEnv(env)->GetStaticFieldID(env, clazz, name, sig));
1323 }
1324
1325#define FIELD_ACCESSORS(_ctype, _jname, _type) \
1326 static _ctype GetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fid) { \
1327 CHECK_JNI_ENTRY(kFlag_Default, "Ecf", env, clazz, fid); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001328 sc.CheckStaticFieldID(clazz, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001329 return CHECK_JNI_EXIT(_type, baseEnv(env)->GetStatic##_jname##Field(env, clazz, fid)); \
1330 } \
1331 static _ctype Get##_jname##Field(JNIEnv* env, jobject obj, jfieldID fid) { \
1332 CHECK_JNI_ENTRY(kFlag_Default, "ELf", env, obj, fid); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001333 sc.CheckInstanceFieldID(obj, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001334 return CHECK_JNI_EXIT(_type, baseEnv(env)->Get##_jname##Field(env, obj, fid)); \
1335 } \
1336 static void SetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fid, _ctype value) { \
1337 CHECK_JNI_ENTRY(kFlag_Default, "Ecf" _type, env, clazz, fid, value); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001338 sc.CheckStaticFieldID(clazz, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001339 /* "value" arg only used when type == ref */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001340 sc.CheckFieldType((jobject)(uint32_t)value, fid, _type[0], true); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001341 baseEnv(env)->SetStatic##_jname##Field(env, clazz, fid, value); \
1342 CHECK_JNI_EXIT_VOID(); \
1343 } \
1344 static void Set##_jname##Field(JNIEnv* env, jobject obj, jfieldID fid, _ctype value) { \
1345 CHECK_JNI_ENTRY(kFlag_Default, "ELf" _type, env, obj, fid, value); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001346 sc.CheckInstanceFieldID(obj, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001347 /* "value" arg only used when type == ref */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001348 sc.CheckFieldType((jobject)(uint32_t) value, fid, _type[0], false); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001349 baseEnv(env)->Set##_jname##Field(env, obj, fid, value); \
1350 CHECK_JNI_EXIT_VOID(); \
1351 }
1352
1353FIELD_ACCESSORS(jobject, Object, "L");
1354FIELD_ACCESSORS(jboolean, Boolean, "Z");
1355FIELD_ACCESSORS(jbyte, Byte, "B");
1356FIELD_ACCESSORS(jchar, Char, "C");
1357FIELD_ACCESSORS(jshort, Short, "S");
1358FIELD_ACCESSORS(jint, Int, "I");
1359FIELD_ACCESSORS(jlong, Long, "J");
1360FIELD_ACCESSORS(jfloat, Float, "F");
1361FIELD_ACCESSORS(jdouble, Double, "D");
1362
1363#define CALL(_ctype, _jname, _retdecl, _retasgn, _retok, _retsig) \
1364 /* Virtual... */ \
1365 static _ctype Call##_jname##Method(JNIEnv* env, jobject obj, \
1366 jmethodID mid, ...) \
1367 { \
1368 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001369 sc.CheckSig(mid, _retsig, false); \
1370 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001371 _retdecl; \
1372 va_list args; \
1373 va_start(args, mid); \
1374 _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, mid, args); \
1375 va_end(args); \
1376 _retok; \
1377 } \
1378 static _ctype Call##_jname##MethodV(JNIEnv* env, jobject obj, \
1379 jmethodID mid, va_list args) \
1380 { \
1381 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001382 sc.CheckSig(mid, _retsig, false); \
1383 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001384 _retdecl; \
1385 _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, mid, args); \
1386 _retok; \
1387 } \
1388 static _ctype Call##_jname##MethodA(JNIEnv* env, jobject obj, \
1389 jmethodID mid, jvalue* args) \
1390 { \
1391 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001392 sc.CheckSig(mid, _retsig, false); \
1393 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001394 _retdecl; \
1395 _retasgn baseEnv(env)->Call##_jname##MethodA(env, obj, mid, args); \
1396 _retok; \
1397 } \
1398 /* Non-virtual... */ \
1399 static _ctype CallNonvirtual##_jname##Method(JNIEnv* env, \
1400 jobject obj, jclass clazz, jmethodID mid, ...) \
1401 { \
1402 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001403 sc.CheckSig(mid, _retsig, false); \
1404 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001405 _retdecl; \
1406 va_list args; \
1407 va_start(args, mid); \
1408 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, mid, args); \
1409 va_end(args); \
1410 _retok; \
1411 } \
1412 static _ctype CallNonvirtual##_jname##MethodV(JNIEnv* env, \
1413 jobject obj, jclass clazz, jmethodID mid, va_list args) \
1414 { \
1415 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001416 sc.CheckSig(mid, _retsig, false); \
1417 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001418 _retdecl; \
1419 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, mid, args); \
1420 _retok; \
1421 } \
1422 static _ctype CallNonvirtual##_jname##MethodA(JNIEnv* env, \
1423 jobject obj, jclass clazz, jmethodID mid, jvalue* args) \
1424 { \
1425 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001426 sc.CheckSig(mid, _retsig, false); \
1427 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001428 _retdecl; \
1429 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodA(env, obj, clazz, mid, args); \
1430 _retok; \
1431 } \
1432 /* Static... */ \
1433 static _ctype CallStatic##_jname##Method(JNIEnv* env, \
1434 jclass clazz, jmethodID mid, ...) \
1435 { \
1436 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001437 sc.CheckSig(mid, _retsig, true); \
1438 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001439 _retdecl; \
1440 va_list args; \
1441 va_start(args, mid); \
1442 _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, mid, args); \
1443 va_end(args); \
1444 _retok; \
1445 } \
1446 static _ctype CallStatic##_jname##MethodV(JNIEnv* env, \
1447 jclass clazz, jmethodID mid, va_list args) \
1448 { \
1449 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001450 sc.CheckSig(mid, _retsig, true); \
1451 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001452 _retdecl; \
1453 _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, mid, args); \
1454 _retok; \
1455 } \
1456 static _ctype CallStatic##_jname##MethodA(JNIEnv* env, \
1457 jclass clazz, jmethodID mid, jvalue* args) \
1458 { \
1459 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001460 sc.CheckSig(mid, _retsig, true); \
1461 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001462 _retdecl; \
1463 _retasgn baseEnv(env)->CallStatic##_jname##MethodA(env, clazz, mid, args); \
1464 _retok; \
1465 }
1466
1467#define NON_VOID_RETURN(_retsig, _ctype) return CHECK_JNI_EXIT(_retsig, (_ctype) result)
1468#define VOID_RETURN CHECK_JNI_EXIT_VOID()
1469
1470CALL(jobject, Object, Object* result, result=(Object*), NON_VOID_RETURN("L", jobject), "L");
1471CALL(jboolean, Boolean, jboolean result, result=, NON_VOID_RETURN("Z", jboolean), "Z");
1472CALL(jbyte, Byte, jbyte result, result=, NON_VOID_RETURN("B", jbyte), "B");
1473CALL(jchar, Char, jchar result, result=, NON_VOID_RETURN("C", jchar), "C");
1474CALL(jshort, Short, jshort result, result=, NON_VOID_RETURN("S", jshort), "S");
1475CALL(jint, Int, jint result, result=, NON_VOID_RETURN("I", jint), "I");
1476CALL(jlong, Long, jlong result, result=, NON_VOID_RETURN("J", jlong), "J");
1477CALL(jfloat, Float, jfloat result, result=, NON_VOID_RETURN("F", jfloat), "F");
1478CALL(jdouble, Double, jdouble result, result=, NON_VOID_RETURN("D", jdouble), "D");
1479CALL(void, Void, , , VOID_RETURN, "V");
1480
1481 static jstring NewString(JNIEnv* env, const jchar* unicodeChars, jsize len) {
1482 CHECK_JNI_ENTRY(kFlag_Default, "Epz", env, unicodeChars, len);
1483 return CHECK_JNI_EXIT("s", baseEnv(env)->NewString(env, unicodeChars, len));
1484 }
1485
1486 static jsize GetStringLength(JNIEnv* env, jstring string) {
1487 CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1488 return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringLength(env, string));
1489 }
1490
1491 static const jchar* GetStringChars(JNIEnv* env, jstring java_string, jboolean* isCopy) {
1492 CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, java_string, isCopy);
1493 const jchar* result = baseEnv(env)->GetStringChars(env, java_string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001494 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001495 ScopedJniThreadState ts(env);
1496 String* s = Decode<String*>(ts, java_string);
1497 int byteCount = s->GetLength() * 2;
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001498 result = (const jchar*) GuardedCopy::Create(result, byteCount, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001499 if (isCopy != NULL) {
1500 *isCopy = JNI_TRUE;
1501 }
1502 }
1503 return CHECK_JNI_EXIT("p", result);
1504 }
1505
1506 static void ReleaseStringChars(JNIEnv* env, jstring string, const jchar* chars) {
1507 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Esp", env, string, chars);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001508 sc.CheckNonNull(chars);
1509 if (sc.ForceCopy()) {
1510 GuardedCopy::Check(__FUNCTION__, chars, false);
1511 chars = (const jchar*) GuardedCopy::Destroy((jchar*)chars);
Elliott Hughesa2501992011-08-26 19:39:54 -07001512 }
1513 baseEnv(env)->ReleaseStringChars(env, string, chars);
1514 CHECK_JNI_EXIT_VOID();
1515 }
1516
1517 static jstring NewStringUTF(JNIEnv* env, const char* bytes) {
1518 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, bytes); // TODO: show pointer and truncate string.
1519 return CHECK_JNI_EXIT("s", baseEnv(env)->NewStringUTF(env, bytes));
1520 }
1521
1522 static jsize GetStringUTFLength(JNIEnv* env, jstring string) {
1523 CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1524 return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringUTFLength(env, string));
1525 }
1526
1527 static const char* GetStringUTFChars(JNIEnv* env, jstring string, jboolean* isCopy) {
1528 CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
1529 const char* result = baseEnv(env)->GetStringUTFChars(env, string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001530 if (sc.ForceCopy() && result != NULL) {
1531 result = (const char*) GuardedCopy::Create(result, strlen(result) + 1, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001532 if (isCopy != NULL) {
1533 *isCopy = JNI_TRUE;
1534 }
1535 }
1536 return CHECK_JNI_EXIT("u", result); // TODO: show pointer and truncate string.
1537 }
1538
1539 static void ReleaseStringUTFChars(JNIEnv* env, jstring string, const char* utf) {
1540 CHECK_JNI_ENTRY(kFlag_ExcepOkay | kFlag_Release, "Esu", env, string, utf); // TODO: show pointer and truncate string.
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001541 if (sc.ForceCopy()) {
1542 GuardedCopy::Check(__FUNCTION__, utf, false);
1543 utf = (const char*) GuardedCopy::Destroy((char*)utf);
Elliott Hughesa2501992011-08-26 19:39:54 -07001544 }
1545 baseEnv(env)->ReleaseStringUTFChars(env, string, utf);
1546 CHECK_JNI_EXIT_VOID();
1547 }
1548
1549 static jsize GetArrayLength(JNIEnv* env, jarray array) {
1550 CHECK_JNI_ENTRY(kFlag_CritOkay, "Ea", env, array);
1551 return CHECK_JNI_EXIT("I", baseEnv(env)->GetArrayLength(env, array));
1552 }
1553
1554 static jobjectArray NewObjectArray(JNIEnv* env, jsize length, jclass elementClass, jobject initialElement) {
1555 CHECK_JNI_ENTRY(kFlag_Default, "EzcL", env, length, elementClass, initialElement);
1556 return CHECK_JNI_EXIT("a", baseEnv(env)->NewObjectArray(env, length, elementClass, initialElement));
1557 }
1558
1559 static jobject GetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index) {
1560 CHECK_JNI_ENTRY(kFlag_Default, "EaI", env, array, index);
1561 return CHECK_JNI_EXIT("L", baseEnv(env)->GetObjectArrayElement(env, array, index));
1562 }
1563
1564 static void SetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, jobject value) {
1565 CHECK_JNI_ENTRY(kFlag_Default, "EaIL", env, array, index, value);
1566 baseEnv(env)->SetObjectArrayElement(env, array, index, value);
1567 CHECK_JNI_EXIT_VOID();
1568 }
1569
1570#define NEW_PRIMITIVE_ARRAY(_artype, _jname) \
1571 static _artype New##_jname##Array(JNIEnv* env, jsize length) { \
1572 CHECK_JNI_ENTRY(kFlag_Default, "Ez", env, length); \
1573 return CHECK_JNI_EXIT("a", baseEnv(env)->New##_jname##Array(env, length)); \
1574 }
1575NEW_PRIMITIVE_ARRAY(jbooleanArray, Boolean);
1576NEW_PRIMITIVE_ARRAY(jbyteArray, Byte);
1577NEW_PRIMITIVE_ARRAY(jcharArray, Char);
1578NEW_PRIMITIVE_ARRAY(jshortArray, Short);
1579NEW_PRIMITIVE_ARRAY(jintArray, Int);
1580NEW_PRIMITIVE_ARRAY(jlongArray, Long);
1581NEW_PRIMITIVE_ARRAY(jfloatArray, Float);
1582NEW_PRIMITIVE_ARRAY(jdoubleArray, Double);
1583
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001584struct ForceCopyGetChecker {
Elliott Hughesa2501992011-08-26 19:39:54 -07001585public:
1586 ForceCopyGetChecker(ScopedCheck& sc, jboolean* isCopy) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001587 force_copy = sc.ForceCopy();
1588 no_copy = 0;
1589 if (force_copy && isCopy != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001590 /* capture this before the base call tramples on it */
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001591 no_copy = *(uint32_t*) isCopy;
Elliott Hughesa2501992011-08-26 19:39:54 -07001592 }
1593 }
1594
1595 template<typename ResultT>
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001596 ResultT Check(JNIEnv* env, jarray array, jboolean* isCopy, ResultT result) {
1597 if (force_copy && result != NULL) {
1598 if (no_copy != kNoCopyMagic) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001599 result = reinterpret_cast<ResultT>(CreateGuardedPACopy(env, array, isCopy));
1600 }
1601 }
1602 return result;
1603 }
1604
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001605 uint32_t no_copy;
1606 bool force_copy;
Elliott Hughesa2501992011-08-26 19:39:54 -07001607};
1608
1609#define GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1610 static _ctype* Get##_jname##ArrayElements(JNIEnv* env, _ctype##Array array, jboolean* isCopy) { \
1611 CHECK_JNI_ENTRY(kFlag_Default, "Eap", env, array, isCopy); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001612 _ctype* result = ForceCopyGetChecker(sc, isCopy).Check(env, array, isCopy, baseEnv(env)->Get##_jname##ArrayElements(env, array, isCopy)); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001613 return CHECK_JNI_EXIT("p", result); \
1614 }
1615
1616#define RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1617 static void Release##_jname##ArrayElements(JNIEnv* env, _ctype##Array array, _ctype* elems, jint mode) { \
1618 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Eapr", env, array, elems, mode); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001619 sc.CheckNonNull(elems); \
1620 if (sc.ForceCopy()) { \
Elliott Hughesa2501992011-08-26 19:39:54 -07001621 ReleaseGuardedPACopy(env, array, elems, mode); \
1622 } \
1623 baseEnv(env)->Release##_jname##ArrayElements(env, array, elems, mode); \
1624 CHECK_JNI_EXIT_VOID(); \
1625 }
1626
1627#define GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1628 static void Get##_jname##ArrayRegion(JNIEnv* env, _ctype##Array array, jsize start, jsize len, _ctype* buf) { \
1629 CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1630 baseEnv(env)->Get##_jname##ArrayRegion(env, array, start, len, buf); \
1631 CHECK_JNI_EXIT_VOID(); \
1632 }
1633
1634#define SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1635 static void Set##_jname##ArrayRegion(JNIEnv* env, _ctype##Array array, jsize start, jsize len, const _ctype* buf) { \
1636 CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1637 baseEnv(env)->Set##_jname##ArrayRegion(env, array, start, len, buf); \
1638 CHECK_JNI_EXIT_VOID(); \
1639 }
1640
1641#define PRIMITIVE_ARRAY_FUNCTIONS(_ctype, _jname, _typechar) \
1642 GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1643 RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1644 GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname); \
1645 SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname);
1646
1647/* TODO: verify primitive array type matches call type */
1648PRIMITIVE_ARRAY_FUNCTIONS(jboolean, Boolean, 'Z');
1649PRIMITIVE_ARRAY_FUNCTIONS(jbyte, Byte, 'B');
1650PRIMITIVE_ARRAY_FUNCTIONS(jchar, Char, 'C');
1651PRIMITIVE_ARRAY_FUNCTIONS(jshort, Short, 'S');
1652PRIMITIVE_ARRAY_FUNCTIONS(jint, Int, 'I');
1653PRIMITIVE_ARRAY_FUNCTIONS(jlong, Long, 'J');
1654PRIMITIVE_ARRAY_FUNCTIONS(jfloat, Float, 'F');
1655PRIMITIVE_ARRAY_FUNCTIONS(jdouble, Double, 'D');
1656
1657 static jint RegisterNatives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
1658 CHECK_JNI_ENTRY(kFlag_Default, "EcpI", env, clazz, methods, nMethods);
1659 return CHECK_JNI_EXIT("I", baseEnv(env)->RegisterNatives(env, clazz, methods, nMethods));
1660 }
1661
1662 static jint UnregisterNatives(JNIEnv* env, jclass clazz) {
1663 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1664 return CHECK_JNI_EXIT("I", baseEnv(env)->UnregisterNatives(env, clazz));
1665 }
1666
1667 static jint MonitorEnter(JNIEnv* env, jobject obj) {
1668 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1669 return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorEnter(env, obj));
1670 }
1671
1672 static jint MonitorExit(JNIEnv* env, jobject obj) {
1673 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
1674 return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorExit(env, obj));
1675 }
1676
1677 static jint GetJavaVM(JNIEnv *env, JavaVM **vm) {
1678 CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, vm);
1679 return CHECK_JNI_EXIT("I", baseEnv(env)->GetJavaVM(env, vm));
1680 }
1681
1682 static void GetStringRegion(JNIEnv* env, jstring str, jsize start, jsize len, jchar* buf) {
1683 CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1684 baseEnv(env)->GetStringRegion(env, str, start, len, buf);
1685 CHECK_JNI_EXIT_VOID();
1686 }
1687
1688 static void GetStringUTFRegion(JNIEnv* env, jstring str, jsize start, jsize len, char* buf) {
1689 CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1690 baseEnv(env)->GetStringUTFRegion(env, str, start, len, buf);
1691 CHECK_JNI_EXIT_VOID();
1692 }
1693
1694 static void* GetPrimitiveArrayCritical(JNIEnv* env, jarray array, jboolean* isCopy) {
1695 CHECK_JNI_ENTRY(kFlag_CritGet, "Eap", env, array, isCopy);
1696 void* result = baseEnv(env)->GetPrimitiveArrayCritical(env, array, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001697 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001698 result = CreateGuardedPACopy(env, array, isCopy);
1699 }
1700 return CHECK_JNI_EXIT("p", result);
1701 }
1702
1703 static void ReleasePrimitiveArrayCritical(JNIEnv* env, jarray array, void* carray, jint mode) {
1704 CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Eapr", env, array, carray, mode);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001705 sc.CheckNonNull(carray);
1706 if (sc.ForceCopy()) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001707 ReleaseGuardedPACopy(env, array, carray, mode);
1708 }
1709 baseEnv(env)->ReleasePrimitiveArrayCritical(env, array, carray, mode);
1710 CHECK_JNI_EXIT_VOID();
1711 }
1712
1713 static const jchar* GetStringCritical(JNIEnv* env, jstring java_string, jboolean* isCopy) {
1714 CHECK_JNI_ENTRY(kFlag_CritGet, "Esp", env, java_string, isCopy);
1715 const jchar* result = baseEnv(env)->GetStringCritical(env, java_string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001716 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001717 ScopedJniThreadState ts(env);
1718 String* s = Decode<String*>(ts, java_string);
1719 int byteCount = s->GetLength() * 2;
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001720 result = (const jchar*) GuardedCopy::Create(result, byteCount, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001721 if (isCopy != NULL) {
1722 *isCopy = JNI_TRUE;
1723 }
1724 }
1725 return CHECK_JNI_EXIT("p", result);
1726 }
1727
1728 static void ReleaseStringCritical(JNIEnv* env, jstring string, const jchar* carray) {
1729 CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Esp", env, string, carray);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001730 sc.CheckNonNull(carray);
1731 if (sc.ForceCopy()) {
1732 GuardedCopy::Check(__FUNCTION__, carray, false);
1733 carray = (const jchar*) GuardedCopy::Destroy((jchar*)carray);
Elliott Hughesa2501992011-08-26 19:39:54 -07001734 }
1735 baseEnv(env)->ReleaseStringCritical(env, string, carray);
1736 CHECK_JNI_EXIT_VOID();
1737 }
1738
1739 static jweak NewWeakGlobalRef(JNIEnv* env, jobject obj) {
1740 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1741 return CHECK_JNI_EXIT("L", baseEnv(env)->NewWeakGlobalRef(env, obj));
1742 }
1743
1744 static jboolean ExceptionCheck(JNIEnv* env) {
1745 CHECK_JNI_ENTRY(kFlag_CritOkay | kFlag_ExcepOkay, "E", env);
1746 return CHECK_JNI_EXIT("b", baseEnv(env)->ExceptionCheck(env));
1747 }
1748
1749 static jobjectRefType GetObjectRefType(JNIEnv* env, jobject obj) {
1750 // Note: we use "Ep" rather than "EL" because this is the one JNI function
1751 // that it's okay to pass an invalid reference to.
1752 CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, obj);
1753 // TODO: proper decoding of jobjectRefType!
1754 return CHECK_JNI_EXIT("I", baseEnv(env)->GetObjectRefType(env, obj));
1755 }
1756
1757 static jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
1758 CHECK_JNI_ENTRY(kFlag_Default, "EpJ", env, address, capacity);
1759 if (address == NULL) {
1760 LOG(ERROR) << "JNI ERROR: non-nullable address is NULL";
1761 JniAbort(__FUNCTION__);
1762 }
1763 if (capacity <= 0) {
1764 LOG(ERROR) << "JNI ERROR: capacity must be greater than 0: " << capacity;
1765 JniAbort(__FUNCTION__);
1766 }
1767 return CHECK_JNI_EXIT("L", baseEnv(env)->NewDirectByteBuffer(env, address, capacity));
1768 }
1769
1770 static void* GetDirectBufferAddress(JNIEnv* env, jobject buf) {
1771 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1772 // TODO: check that 'buf' is a java.nio.Buffer.
1773 return CHECK_JNI_EXIT("p", baseEnv(env)->GetDirectBufferAddress(env, buf));
1774 }
1775
1776 static jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf) {
1777 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1778 // TODO: check that 'buf' is a java.nio.Buffer.
1779 return CHECK_JNI_EXIT("J", baseEnv(env)->GetDirectBufferCapacity(env, buf));
1780 }
1781
1782 private:
1783 static inline const JNINativeInterface* baseEnv(JNIEnv* env) {
1784 return reinterpret_cast<JNIEnvExt*>(env)->unchecked_functions;
1785 }
1786};
1787
1788const JNINativeInterface gCheckNativeInterface = {
1789 NULL, // reserved0.
1790 NULL, // reserved1.
1791 NULL, // reserved2.
1792 NULL, // reserved3.
1793 CheckJNI::GetVersion,
1794 CheckJNI::DefineClass,
1795 CheckJNI::FindClass,
1796 CheckJNI::FromReflectedMethod,
1797 CheckJNI::FromReflectedField,
1798 CheckJNI::ToReflectedMethod,
1799 CheckJNI::GetSuperclass,
1800 CheckJNI::IsAssignableFrom,
1801 CheckJNI::ToReflectedField,
1802 CheckJNI::Throw,
1803 CheckJNI::ThrowNew,
1804 CheckJNI::ExceptionOccurred,
1805 CheckJNI::ExceptionDescribe,
1806 CheckJNI::ExceptionClear,
1807 CheckJNI::FatalError,
1808 CheckJNI::PushLocalFrame,
1809 CheckJNI::PopLocalFrame,
1810 CheckJNI::NewGlobalRef,
1811 CheckJNI::DeleteGlobalRef,
1812 CheckJNI::DeleteLocalRef,
1813 CheckJNI::IsSameObject,
1814 CheckJNI::NewLocalRef,
1815 CheckJNI::EnsureLocalCapacity,
1816 CheckJNI::AllocObject,
1817 CheckJNI::NewObject,
1818 CheckJNI::NewObjectV,
1819 CheckJNI::NewObjectA,
1820 CheckJNI::GetObjectClass,
1821 CheckJNI::IsInstanceOf,
1822 CheckJNI::GetMethodID,
1823 CheckJNI::CallObjectMethod,
1824 CheckJNI::CallObjectMethodV,
1825 CheckJNI::CallObjectMethodA,
1826 CheckJNI::CallBooleanMethod,
1827 CheckJNI::CallBooleanMethodV,
1828 CheckJNI::CallBooleanMethodA,
1829 CheckJNI::CallByteMethod,
1830 CheckJNI::CallByteMethodV,
1831 CheckJNI::CallByteMethodA,
1832 CheckJNI::CallCharMethod,
1833 CheckJNI::CallCharMethodV,
1834 CheckJNI::CallCharMethodA,
1835 CheckJNI::CallShortMethod,
1836 CheckJNI::CallShortMethodV,
1837 CheckJNI::CallShortMethodA,
1838 CheckJNI::CallIntMethod,
1839 CheckJNI::CallIntMethodV,
1840 CheckJNI::CallIntMethodA,
1841 CheckJNI::CallLongMethod,
1842 CheckJNI::CallLongMethodV,
1843 CheckJNI::CallLongMethodA,
1844 CheckJNI::CallFloatMethod,
1845 CheckJNI::CallFloatMethodV,
1846 CheckJNI::CallFloatMethodA,
1847 CheckJNI::CallDoubleMethod,
1848 CheckJNI::CallDoubleMethodV,
1849 CheckJNI::CallDoubleMethodA,
1850 CheckJNI::CallVoidMethod,
1851 CheckJNI::CallVoidMethodV,
1852 CheckJNI::CallVoidMethodA,
1853 CheckJNI::CallNonvirtualObjectMethod,
1854 CheckJNI::CallNonvirtualObjectMethodV,
1855 CheckJNI::CallNonvirtualObjectMethodA,
1856 CheckJNI::CallNonvirtualBooleanMethod,
1857 CheckJNI::CallNonvirtualBooleanMethodV,
1858 CheckJNI::CallNonvirtualBooleanMethodA,
1859 CheckJNI::CallNonvirtualByteMethod,
1860 CheckJNI::CallNonvirtualByteMethodV,
1861 CheckJNI::CallNonvirtualByteMethodA,
1862 CheckJNI::CallNonvirtualCharMethod,
1863 CheckJNI::CallNonvirtualCharMethodV,
1864 CheckJNI::CallNonvirtualCharMethodA,
1865 CheckJNI::CallNonvirtualShortMethod,
1866 CheckJNI::CallNonvirtualShortMethodV,
1867 CheckJNI::CallNonvirtualShortMethodA,
1868 CheckJNI::CallNonvirtualIntMethod,
1869 CheckJNI::CallNonvirtualIntMethodV,
1870 CheckJNI::CallNonvirtualIntMethodA,
1871 CheckJNI::CallNonvirtualLongMethod,
1872 CheckJNI::CallNonvirtualLongMethodV,
1873 CheckJNI::CallNonvirtualLongMethodA,
1874 CheckJNI::CallNonvirtualFloatMethod,
1875 CheckJNI::CallNonvirtualFloatMethodV,
1876 CheckJNI::CallNonvirtualFloatMethodA,
1877 CheckJNI::CallNonvirtualDoubleMethod,
1878 CheckJNI::CallNonvirtualDoubleMethodV,
1879 CheckJNI::CallNonvirtualDoubleMethodA,
1880 CheckJNI::CallNonvirtualVoidMethod,
1881 CheckJNI::CallNonvirtualVoidMethodV,
1882 CheckJNI::CallNonvirtualVoidMethodA,
1883 CheckJNI::GetFieldID,
1884 CheckJNI::GetObjectField,
1885 CheckJNI::GetBooleanField,
1886 CheckJNI::GetByteField,
1887 CheckJNI::GetCharField,
1888 CheckJNI::GetShortField,
1889 CheckJNI::GetIntField,
1890 CheckJNI::GetLongField,
1891 CheckJNI::GetFloatField,
1892 CheckJNI::GetDoubleField,
1893 CheckJNI::SetObjectField,
1894 CheckJNI::SetBooleanField,
1895 CheckJNI::SetByteField,
1896 CheckJNI::SetCharField,
1897 CheckJNI::SetShortField,
1898 CheckJNI::SetIntField,
1899 CheckJNI::SetLongField,
1900 CheckJNI::SetFloatField,
1901 CheckJNI::SetDoubleField,
1902 CheckJNI::GetStaticMethodID,
1903 CheckJNI::CallStaticObjectMethod,
1904 CheckJNI::CallStaticObjectMethodV,
1905 CheckJNI::CallStaticObjectMethodA,
1906 CheckJNI::CallStaticBooleanMethod,
1907 CheckJNI::CallStaticBooleanMethodV,
1908 CheckJNI::CallStaticBooleanMethodA,
1909 CheckJNI::CallStaticByteMethod,
1910 CheckJNI::CallStaticByteMethodV,
1911 CheckJNI::CallStaticByteMethodA,
1912 CheckJNI::CallStaticCharMethod,
1913 CheckJNI::CallStaticCharMethodV,
1914 CheckJNI::CallStaticCharMethodA,
1915 CheckJNI::CallStaticShortMethod,
1916 CheckJNI::CallStaticShortMethodV,
1917 CheckJNI::CallStaticShortMethodA,
1918 CheckJNI::CallStaticIntMethod,
1919 CheckJNI::CallStaticIntMethodV,
1920 CheckJNI::CallStaticIntMethodA,
1921 CheckJNI::CallStaticLongMethod,
1922 CheckJNI::CallStaticLongMethodV,
1923 CheckJNI::CallStaticLongMethodA,
1924 CheckJNI::CallStaticFloatMethod,
1925 CheckJNI::CallStaticFloatMethodV,
1926 CheckJNI::CallStaticFloatMethodA,
1927 CheckJNI::CallStaticDoubleMethod,
1928 CheckJNI::CallStaticDoubleMethodV,
1929 CheckJNI::CallStaticDoubleMethodA,
1930 CheckJNI::CallStaticVoidMethod,
1931 CheckJNI::CallStaticVoidMethodV,
1932 CheckJNI::CallStaticVoidMethodA,
1933 CheckJNI::GetStaticFieldID,
1934 CheckJNI::GetStaticObjectField,
1935 CheckJNI::GetStaticBooleanField,
1936 CheckJNI::GetStaticByteField,
1937 CheckJNI::GetStaticCharField,
1938 CheckJNI::GetStaticShortField,
1939 CheckJNI::GetStaticIntField,
1940 CheckJNI::GetStaticLongField,
1941 CheckJNI::GetStaticFloatField,
1942 CheckJNI::GetStaticDoubleField,
1943 CheckJNI::SetStaticObjectField,
1944 CheckJNI::SetStaticBooleanField,
1945 CheckJNI::SetStaticByteField,
1946 CheckJNI::SetStaticCharField,
1947 CheckJNI::SetStaticShortField,
1948 CheckJNI::SetStaticIntField,
1949 CheckJNI::SetStaticLongField,
1950 CheckJNI::SetStaticFloatField,
1951 CheckJNI::SetStaticDoubleField,
1952 CheckJNI::NewString,
1953 CheckJNI::GetStringLength,
1954 CheckJNI::GetStringChars,
1955 CheckJNI::ReleaseStringChars,
1956 CheckJNI::NewStringUTF,
1957 CheckJNI::GetStringUTFLength,
1958 CheckJNI::GetStringUTFChars,
1959 CheckJNI::ReleaseStringUTFChars,
1960 CheckJNI::GetArrayLength,
1961 CheckJNI::NewObjectArray,
1962 CheckJNI::GetObjectArrayElement,
1963 CheckJNI::SetObjectArrayElement,
1964 CheckJNI::NewBooleanArray,
1965 CheckJNI::NewByteArray,
1966 CheckJNI::NewCharArray,
1967 CheckJNI::NewShortArray,
1968 CheckJNI::NewIntArray,
1969 CheckJNI::NewLongArray,
1970 CheckJNI::NewFloatArray,
1971 CheckJNI::NewDoubleArray,
1972 CheckJNI::GetBooleanArrayElements,
1973 CheckJNI::GetByteArrayElements,
1974 CheckJNI::GetCharArrayElements,
1975 CheckJNI::GetShortArrayElements,
1976 CheckJNI::GetIntArrayElements,
1977 CheckJNI::GetLongArrayElements,
1978 CheckJNI::GetFloatArrayElements,
1979 CheckJNI::GetDoubleArrayElements,
1980 CheckJNI::ReleaseBooleanArrayElements,
1981 CheckJNI::ReleaseByteArrayElements,
1982 CheckJNI::ReleaseCharArrayElements,
1983 CheckJNI::ReleaseShortArrayElements,
1984 CheckJNI::ReleaseIntArrayElements,
1985 CheckJNI::ReleaseLongArrayElements,
1986 CheckJNI::ReleaseFloatArrayElements,
1987 CheckJNI::ReleaseDoubleArrayElements,
1988 CheckJNI::GetBooleanArrayRegion,
1989 CheckJNI::GetByteArrayRegion,
1990 CheckJNI::GetCharArrayRegion,
1991 CheckJNI::GetShortArrayRegion,
1992 CheckJNI::GetIntArrayRegion,
1993 CheckJNI::GetLongArrayRegion,
1994 CheckJNI::GetFloatArrayRegion,
1995 CheckJNI::GetDoubleArrayRegion,
1996 CheckJNI::SetBooleanArrayRegion,
1997 CheckJNI::SetByteArrayRegion,
1998 CheckJNI::SetCharArrayRegion,
1999 CheckJNI::SetShortArrayRegion,
2000 CheckJNI::SetIntArrayRegion,
2001 CheckJNI::SetLongArrayRegion,
2002 CheckJNI::SetFloatArrayRegion,
2003 CheckJNI::SetDoubleArrayRegion,
2004 CheckJNI::RegisterNatives,
2005 CheckJNI::UnregisterNatives,
2006 CheckJNI::MonitorEnter,
2007 CheckJNI::MonitorExit,
2008 CheckJNI::GetJavaVM,
2009 CheckJNI::GetStringRegion,
2010 CheckJNI::GetStringUTFRegion,
2011 CheckJNI::GetPrimitiveArrayCritical,
2012 CheckJNI::ReleasePrimitiveArrayCritical,
2013 CheckJNI::GetStringCritical,
2014 CheckJNI::ReleaseStringCritical,
2015 CheckJNI::NewWeakGlobalRef,
2016 CheckJNI::DeleteWeakGlobalRef,
2017 CheckJNI::ExceptionCheck,
2018 CheckJNI::NewDirectByteBuffer,
2019 CheckJNI::GetDirectBufferAddress,
2020 CheckJNI::GetDirectBufferCapacity,
2021 CheckJNI::GetObjectRefType,
2022};
2023
2024const JNINativeInterface* GetCheckJniNativeInterface() {
2025 return &gCheckNativeInterface;
2026}
2027
2028class CheckJII {
2029public:
2030 static jint DestroyJavaVM(JavaVM* vm) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002031 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002032 sc.Check(true, "v", vm);
2033 return CHECK_JNI_EXIT("I", BaseVm(vm)->DestroyJavaVM(vm));
Elliott Hughesa2501992011-08-26 19:39:54 -07002034 }
2035
2036 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002037 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002038 sc.Check(true, "vpp", vm, p_env, thr_args);
2039 return CHECK_JNI_EXIT("I", BaseVm(vm)->AttachCurrentThread(vm, p_env, thr_args));
Elliott Hughesa2501992011-08-26 19:39:54 -07002040 }
2041
2042 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002043 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002044 sc.Check(true, "vpp", vm, p_env, thr_args);
2045 return CHECK_JNI_EXIT("I", BaseVm(vm)->AttachCurrentThreadAsDaemon(vm, p_env, thr_args));
Elliott Hughesa2501992011-08-26 19:39:54 -07002046 }
2047
2048 static jint DetachCurrentThread(JavaVM* vm) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002049 ScopedCheck sc(vm, true, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002050 sc.Check(true, "v", vm);
2051 return CHECK_JNI_EXIT("I", BaseVm(vm)->DetachCurrentThread(vm));
Elliott Hughesa2501992011-08-26 19:39:54 -07002052 }
2053
2054 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002055 ScopedCheck sc(vm, true, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002056 sc.Check(true, "v", vm);
2057 return CHECK_JNI_EXIT("I", BaseVm(vm)->GetEnv(vm, env, version));
Elliott Hughesa2501992011-08-26 19:39:54 -07002058 }
2059
2060 private:
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002061 static inline const JNIInvokeInterface* BaseVm(JavaVM* vm) {
Elliott Hughesa2501992011-08-26 19:39:54 -07002062 return reinterpret_cast<JavaVMExt*>(vm)->unchecked_functions;
2063 }
2064};
2065
2066const JNIInvokeInterface gCheckInvokeInterface = {
2067 NULL, // reserved0
2068 NULL, // reserved1
2069 NULL, // reserved2
2070 CheckJII::DestroyJavaVM,
2071 CheckJII::AttachCurrentThread,
2072 CheckJII::DetachCurrentThread,
2073 CheckJII::GetEnv,
2074 CheckJII::AttachCurrentThreadAsDaemon
2075};
2076
2077const JNIInvokeInterface* GetCheckJniInvokeInterface() {
2078 return &gCheckInvokeInterface;
2079}
2080
2081} // namespace art