blob: cb33d93175fa4a26f5f8d243895d7cd0c7f17cb9 [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)
Elliott Hughes78090d12011-10-07 14:31:47 -0700371 * u - const char* (Modified UTF-8)
Elliott Hughesa2501992011-08-26 19:39:54 -0700372 * 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 }
Elliott Hughes78090d12011-10-07 14:31:47 -0700489 } else if (ch == 'u') { // const char* (Modified UTF-8)
Elliott Hughesa2501992011-08-26 19:39:54 -0700490 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 /*
Elliott Hughes78090d12011-10-07 14:31:47 -0700735 * Verify that "bytes" points to valid Modified UTF-8 data.
Elliott Hughesa2501992011-08-26 19:39:54 -0700736 */
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) {
Elliott Hughes78090d12011-10-07 14:31:47 -0700750 LOG(ERROR) << "JNI ERROR: input is not valid Modified UTF-8: "
751 << "illegal " << errorKind << " byte " << StringPrintf("%#x", utf8) << "\n"
752 << " string: '" << bytes << "'";
Elliott Hughesa2501992011-08-26 19:39:54 -0700753 JniAbort();
754 return;
755 }
756 }
757
758 enum InstanceKind {
759 kClass,
760 kDirectByteBuffer,
761 kString,
762 kThrowable,
763 };
764
765 /*
766 * Verify that "jobj" is a valid non-NULL object reference, and points to
767 * an instance of expectedClass.
768 *
769 * Because we're looking at an object on the GC heap, we have to switch
770 * to "running" mode before doing the checks.
771 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700772 void CheckInstance(InstanceKind kind, jobject java_object) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700773 const char* what = NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700774 switch (kind) {
775 case kClass:
776 what = "jclass";
777 break;
778 case kDirectByteBuffer:
779 what = "direct ByteBuffer";
780 break;
781 case kString:
782 what = "jstring";
783 break;
784 case kThrowable:
785 what = "jthrowable";
786 break;
787 default:
788 CHECK(false) << static_cast<int>(kind);
789 }
790
791 if (java_object == NULL) {
792 LOG(ERROR) << "JNI ERROR: received null " << what;
793 JniAbort();
794 return;
795 }
796
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700797 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700798 Object* obj = Decode<Object*>(ts, java_object);
799 if (!Heap::IsHeapAddress(obj)) {
800 LOG(ERROR) << "JNI ERROR: " << what << " is an invalid " << GetIndirectRefKind(java_object) << ": " << java_object;
801 JniAbort();
802 return;
803 }
804
805 bool okay = true;
806 switch (kind) {
807 case kClass:
808 okay = obj->IsClass();
809 break;
810 case kDirectByteBuffer:
811 // TODO
812 break;
813 case kString:
814 okay = obj->IsString();
815 break;
816 case kThrowable:
817 // TODO
818 break;
819 }
820 if (!okay) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700821 LOG(ERROR) << "JNI ERROR: " << what << " has wrong type: " << PrettyTypeOf(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700822 JniAbort();
823 }
824 }
825
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700826 static uint8_t CheckUtfBytes(const char* bytes, const char** errorKind) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700827 while (*bytes != '\0') {
828 uint8_t utf8 = *(bytes++);
829 // Switch on the high four bits.
830 switch (utf8 >> 4) {
831 case 0x00:
832 case 0x01:
833 case 0x02:
834 case 0x03:
835 case 0x04:
836 case 0x05:
837 case 0x06:
838 case 0x07:
839 // Bit pattern 0xxx. No need for any extra bytes.
840 break;
841 case 0x08:
842 case 0x09:
843 case 0x0a:
844 case 0x0b:
845 case 0x0f:
846 /*
847 * Bit pattern 10xx or 1111, which are illegal start bytes.
848 * Note: 1111 is valid for normal UTF-8, but not the
Elliott Hughes78090d12011-10-07 14:31:47 -0700849 * Modified UTF-8 used here.
Elliott Hughesa2501992011-08-26 19:39:54 -0700850 */
851 *errorKind = "start";
852 return utf8;
853 case 0x0e:
854 // Bit pattern 1110, so there are two additional bytes.
855 utf8 = *(bytes++);
856 if ((utf8 & 0xc0) != 0x80) {
857 *errorKind = "continuation";
858 return utf8;
859 }
860 // Fall through to take care of the final byte.
861 case 0x0c:
862 case 0x0d:
863 // Bit pattern 110x, so there is one additional byte.
864 utf8 = *(bytes++);
865 if ((utf8 & 0xc0) != 0x80) {
866 *errorKind = "continuation";
867 return utf8;
868 }
869 break;
870 }
871 }
872 return 0;
873 }
874
875 void JniAbort() {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700876 ::art::JniAbort(function_name_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700877 }
878
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700879 JNIEnvExt* env_;
880 JavaVMExt* vm_;
881 const char* function_name_;
882 int flags_;
883 bool has_method_;
884 size_t indent_;
Elliott Hughesa2501992011-08-26 19:39:54 -0700885
886 DISALLOW_COPY_AND_ASSIGN(ScopedCheck);
887};
888
889#define CHECK_JNI_ENTRY(flags, types, args...) \
890 ScopedCheck sc(env, flags, __FUNCTION__); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700891 sc.Check(true, types, ##args)
Elliott Hughesa2501992011-08-26 19:39:54 -0700892
893#define CHECK_JNI_EXIT(type, exp) ({ \
894 typeof (exp) _rc = (exp); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700895 sc.Check(false, type, _rc); \
Elliott Hughesa2501992011-08-26 19:39:54 -0700896 _rc; })
897#define CHECK_JNI_EXIT_VOID() \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700898 sc.Check(false, "V")
Elliott Hughesa2501992011-08-26 19:39:54 -0700899
900/*
901 * ===========================================================================
902 * Guarded arrays
903 * ===========================================================================
904 */
905
906#define kGuardLen 512 /* must be multiple of 2 */
907#define kGuardPattern 0xd5e3 /* uncommon values; d5e3d5e3 invalid addr */
908#define kGuardMagic 0xffd5aa96
909
910/* this gets tucked in at the start of the buffer; struct size must be even */
911struct GuardedCopy {
912 uint32_t magic;
913 uLong adler;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700914 size_t original_length;
915 const void* original_ptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700916
917 /* find the GuardedCopy given the pointer into the "live" data */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700918 static inline const GuardedCopy* FromData(const void* dataBuf) {
919 return reinterpret_cast<const GuardedCopy*>(ActualBuffer(dataBuf));
Elliott Hughesa2501992011-08-26 19:39:54 -0700920 }
921
922 /*
923 * Create an over-sized buffer to hold the contents of "buf". Copy it in,
924 * filling in the area around it with guard data.
925 *
926 * We use a 16-bit pattern to make a rogue memset less likely to elude us.
927 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700928 static void* Create(const void* buf, size_t len, bool modOkay) {
929 size_t newLen = ActualLength(len);
930 uint8_t* newBuf = DebugAlloc(newLen);
Elliott Hughesa2501992011-08-26 19:39:54 -0700931
932 /* fill it in with a pattern */
933 uint16_t* pat = (uint16_t*) newBuf;
934 for (size_t i = 0; i < newLen / 2; i++) {
935 *pat++ = kGuardPattern;
936 }
937
938 /* copy the data in; note "len" could be zero */
939 memcpy(newBuf + kGuardLen / 2, buf, len);
940
941 /* if modification is not expected, grab a checksum */
942 uLong adler = 0;
943 if (!modOkay) {
944 adler = adler32(0L, Z_NULL, 0);
945 adler = adler32(adler, (const Bytef*)buf, len);
946 *(uLong*)newBuf = adler;
947 }
948
949 GuardedCopy* pExtra = reinterpret_cast<GuardedCopy*>(newBuf);
950 pExtra->magic = kGuardMagic;
951 pExtra->adler = adler;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700952 pExtra->original_ptr = buf;
953 pExtra->original_length = len;
Elliott Hughesa2501992011-08-26 19:39:54 -0700954
955 return newBuf + kGuardLen / 2;
956 }
957
958 /*
959 * Free up the guard buffer, scrub it, and return the original pointer.
960 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700961 static void* Destroy(void* dataBuf) {
962 const GuardedCopy* pExtra = GuardedCopy::FromData(dataBuf);
963 void* original_ptr = (void*) pExtra->original_ptr;
964 size_t len = pExtra->original_length;
965 DebugFree(dataBuf, len);
966 return original_ptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700967 }
968
969 /*
970 * Verify the guard area and, if "modOkay" is false, that the data itself
971 * has not been altered.
972 *
973 * The caller has already checked that "dataBuf" is non-NULL.
974 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700975 static void Check(const char* functionName, const void* dataBuf, bool modOkay) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700976 static const uint32_t kMagicCmp = kGuardMagic;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700977 const uint8_t* fullBuf = ActualBuffer(dataBuf);
978 const GuardedCopy* pExtra = GuardedCopy::FromData(dataBuf);
Elliott Hughesa2501992011-08-26 19:39:54 -0700979
980 /*
981 * Before we do anything with "pExtra", check the magic number. We
982 * do the check with memcmp rather than "==" in case the pointer is
983 * unaligned. If it points to completely bogus memory we're going
984 * to crash, but there's no easy way around that.
985 */
986 if (memcmp(&pExtra->magic, &kMagicCmp, 4) != 0) {
987 uint8_t buf[4];
988 memcpy(buf, &pExtra->magic, 4);
989 LOG(ERROR) << StringPrintf("JNI: guard magic does not match "
990 "(found 0x%02x%02x%02x%02x) -- incorrect data pointer %p?",
991 buf[3], buf[2], buf[1], buf[0], dataBuf); /* assume little endian */
992 JniAbort(functionName);
993 }
994
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700995 size_t len = pExtra->original_length;
Elliott Hughesa2501992011-08-26 19:39:54 -0700996
997 /* check bottom half of guard; skip over optional checksum storage */
998 const uint16_t* pat = (uint16_t*) fullBuf;
999 for (size_t i = sizeof(GuardedCopy) / 2; i < (kGuardLen / 2 - sizeof(GuardedCopy)) / 2; i++) {
1000 if (pat[i] != kGuardPattern) {
1001 LOG(ERROR) << "JNI: guard pattern(1) disturbed at " << (void*) fullBuf << " + " << (i*2);
1002 JniAbort(functionName);
1003 }
1004 }
1005
1006 int offset = kGuardLen / 2 + len;
1007 if (offset & 0x01) {
1008 /* odd byte; expected value depends on endian-ness of host */
1009 const uint16_t patSample = kGuardPattern;
1010 if (fullBuf[offset] != ((const uint8_t*) &patSample)[1]) {
1011 LOG(ERROR) << "JNI: guard pattern disturbed in odd byte after "
1012 << (void*) fullBuf << " (+" << offset << ") "
1013 << StringPrintf("0x%02x 0x%02x", fullBuf[offset], ((const uint8_t*) &patSample)[1]);
1014 JniAbort(functionName);
1015 }
1016 offset++;
1017 }
1018
1019 /* check top half of guard */
1020 pat = (uint16_t*) (fullBuf + offset);
1021 for (size_t i = 0; i < kGuardLen / 4; i++) {
1022 if (pat[i] != kGuardPattern) {
1023 LOG(ERROR) << "JNI: guard pattern(2) disturbed at " << (void*) fullBuf << " + " << (offset + i*2);
1024 JniAbort(functionName);
1025 }
1026 }
1027
1028 /*
1029 * If modification is not expected, verify checksum. Strictly speaking
1030 * this is wrong: if we told the client that we made a copy, there's no
1031 * reason they can't alter the buffer.
1032 */
1033 if (!modOkay) {
1034 uLong adler = adler32(0L, Z_NULL, 0);
1035 adler = adler32(adler, (const Bytef*)dataBuf, len);
1036 if (pExtra->adler != adler) {
1037 LOG(ERROR) << StringPrintf("JNI: buffer modified (0x%08lx vs 0x%08lx) at addr %p", pExtra->adler, adler, dataBuf);
1038 JniAbort(functionName);
1039 }
1040 }
1041 }
1042
1043 private:
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001044 static uint8_t* DebugAlloc(size_t len) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001045 void* result = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
1046 if (result == MAP_FAILED) {
1047 PLOG(FATAL) << "GuardedCopy::create mmap(" << len << ") failed";
1048 }
1049 return reinterpret_cast<uint8_t*>(result);
1050 }
1051
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001052 static void DebugFree(void* dataBuf, size_t len) {
1053 uint8_t* fullBuf = ActualBuffer(dataBuf);
1054 size_t totalByteCount = ActualLength(len);
Elliott Hughesa2501992011-08-26 19:39:54 -07001055 // TODO: we could mprotect instead, and keep the allocation around for a while.
1056 // This would be even more expensive, but it might catch more errors.
1057 // if (mprotect(fullBuf, totalByteCount, PROT_NONE) != 0) {
1058 // LOGW("mprotect(PROT_NONE) failed: %s", strerror(errno));
1059 // }
1060 if (munmap(fullBuf, totalByteCount) != 0) {
1061 PLOG(FATAL) << "munmap(" << (void*) fullBuf << ", " << totalByteCount << ") failed";
1062 }
1063 }
1064
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001065 static const uint8_t* ActualBuffer(const void* dataBuf) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001066 return reinterpret_cast<const uint8_t*>(dataBuf) - kGuardLen / 2;
1067 }
1068
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001069 static uint8_t* ActualBuffer(void* dataBuf) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001070 return reinterpret_cast<uint8_t*>(dataBuf) - kGuardLen / 2;
1071 }
1072
1073 // Underlying length of a user allocation of 'length' bytes.
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001074 static size_t ActualLength(size_t length) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001075 return (length + kGuardLen + 1) & ~0x01;
1076 }
1077};
1078
1079/*
1080 * Create a guarded copy of a primitive array. Modifications to the copied
1081 * data are allowed. Returns a pointer to the copied data.
1082 */
1083void* CreateGuardedPACopy(JNIEnv* env, const jarray java_array, jboolean* isCopy) {
1084 ScopedJniThreadState ts(env);
1085
1086 Array* a = Decode<Array*>(ts, java_array);
1087 size_t byte_count = a->GetLength() * a->GetClass()->GetComponentSize();
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001088 void* result = GuardedCopy::Create(a->GetRawData(), byte_count, true);
Elliott Hughesa2501992011-08-26 19:39:54 -07001089 if (isCopy != NULL) {
1090 *isCopy = JNI_TRUE;
1091 }
1092 return result;
1093}
1094
1095/*
1096 * Perform the array "release" operation, which may or may not copy data
1097 * back into the VM, and may or may not release the underlying storage.
1098 */
1099void ReleaseGuardedPACopy(JNIEnv* env, jarray java_array, void* dataBuf, int mode) {
1100 if (reinterpret_cast<uintptr_t>(dataBuf) == kNoCopyMagic) {
1101 return;
1102 }
1103
1104 ScopedJniThreadState ts(env);
1105 Array* a = Decode<Array*>(ts, java_array);
1106
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001107 GuardedCopy::Check(__FUNCTION__, dataBuf, true);
Elliott Hughesa2501992011-08-26 19:39:54 -07001108
1109 if (mode != JNI_ABORT) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001110 size_t len = GuardedCopy::FromData(dataBuf)->original_length;
Elliott Hughesbf86d042011-08-31 17:53:14 -07001111 memcpy(a->GetRawData(), dataBuf, len);
Elliott Hughesa2501992011-08-26 19:39:54 -07001112 }
1113 if (mode != JNI_COMMIT) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001114 GuardedCopy::Destroy(dataBuf);
Elliott Hughesa2501992011-08-26 19:39:54 -07001115 }
1116}
1117
1118/*
1119 * ===========================================================================
1120 * JNI functions
1121 * ===========================================================================
1122 */
1123
1124class CheckJNI {
1125 public:
1126 static jint GetVersion(JNIEnv* env) {
1127 CHECK_JNI_ENTRY(kFlag_Default, "E", env);
1128 return CHECK_JNI_EXIT("I", baseEnv(env)->GetVersion(env));
1129 }
1130
1131 static jclass DefineClass(JNIEnv* env, const char* name, jobject loader, const jbyte* buf, jsize bufLen) {
1132 CHECK_JNI_ENTRY(kFlag_Default, "EuLpz", env, name, loader, buf, bufLen);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001133 sc.CheckClassName(name);
Elliott Hughesa2501992011-08-26 19:39:54 -07001134 return CHECK_JNI_EXIT("c", baseEnv(env)->DefineClass(env, name, loader, buf, bufLen));
1135 }
1136
1137 static jclass FindClass(JNIEnv* env, const char* name) {
1138 CHECK_JNI_ENTRY(kFlag_Default, "Eu", env, name);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001139 sc.CheckClassName(name);
Elliott Hughesa2501992011-08-26 19:39:54 -07001140 return CHECK_JNI_EXIT("c", baseEnv(env)->FindClass(env, name));
1141 }
1142
1143 static jclass GetSuperclass(JNIEnv* env, jclass clazz) {
1144 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1145 return CHECK_JNI_EXIT("c", baseEnv(env)->GetSuperclass(env, clazz));
1146 }
1147
1148 static jboolean IsAssignableFrom(JNIEnv* env, jclass clazz1, jclass clazz2) {
1149 CHECK_JNI_ENTRY(kFlag_Default, "Ecc", env, clazz1, clazz2);
1150 return CHECK_JNI_EXIT("b", baseEnv(env)->IsAssignableFrom(env, clazz1, clazz2));
1151 }
1152
1153 static jmethodID FromReflectedMethod(JNIEnv* env, jobject method) {
1154 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, method);
1155 // TODO: check that 'field' is a java.lang.reflect.Method.
1156 return CHECK_JNI_EXIT("m", baseEnv(env)->FromReflectedMethod(env, method));
1157 }
1158
1159 static jfieldID FromReflectedField(JNIEnv* env, jobject field) {
1160 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, field);
1161 // TODO: check that 'field' is a java.lang.reflect.Field.
1162 return CHECK_JNI_EXIT("f", baseEnv(env)->FromReflectedField(env, field));
1163 }
1164
1165 static jobject ToReflectedMethod(JNIEnv* env, jclass cls, jmethodID mid, jboolean isStatic) {
1166 CHECK_JNI_ENTRY(kFlag_Default, "Ecmb", env, cls, mid, isStatic);
1167 return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedMethod(env, cls, mid, isStatic));
1168 }
1169
1170 static jobject ToReflectedField(JNIEnv* env, jclass cls, jfieldID fid, jboolean isStatic) {
1171 CHECK_JNI_ENTRY(kFlag_Default, "Ecfb", env, cls, fid, isStatic);
1172 return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedField(env, cls, fid, isStatic));
1173 }
1174
1175 static jint Throw(JNIEnv* env, jthrowable obj) {
1176 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1177 // TODO: check that 'obj' is a java.lang.Throwable.
1178 return CHECK_JNI_EXIT("I", baseEnv(env)->Throw(env, obj));
1179 }
1180
1181 static jint ThrowNew(JNIEnv* env, jclass clazz, const char* message) {
1182 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Ecu", env, clazz, message);
1183 return CHECK_JNI_EXIT("I", baseEnv(env)->ThrowNew(env, clazz, message));
1184 }
1185
1186 static jthrowable ExceptionOccurred(JNIEnv* env) {
1187 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1188 return CHECK_JNI_EXIT("L", baseEnv(env)->ExceptionOccurred(env));
1189 }
1190
1191 static void ExceptionDescribe(JNIEnv* env) {
1192 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1193 baseEnv(env)->ExceptionDescribe(env);
1194 CHECK_JNI_EXIT_VOID();
1195 }
1196
1197 static void ExceptionClear(JNIEnv* env) {
1198 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1199 baseEnv(env)->ExceptionClear(env);
1200 CHECK_JNI_EXIT_VOID();
1201 }
1202
1203 static void FatalError(JNIEnv* env, const char* msg) {
1204 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, msg);
1205 baseEnv(env)->FatalError(env, msg);
1206 CHECK_JNI_EXIT_VOID();
1207 }
1208
1209 static jint PushLocalFrame(JNIEnv* env, jint capacity) {
1210 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EI", env, capacity);
1211 return CHECK_JNI_EXIT("I", baseEnv(env)->PushLocalFrame(env, capacity));
1212 }
1213
1214 static jobject PopLocalFrame(JNIEnv* env, jobject res) {
1215 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, res);
1216 return CHECK_JNI_EXIT("L", baseEnv(env)->PopLocalFrame(env, res));
1217 }
1218
1219 static jobject NewGlobalRef(JNIEnv* env, jobject obj) {
1220 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1221 return CHECK_JNI_EXIT("L", baseEnv(env)->NewGlobalRef(env, obj));
1222 }
1223
1224 static jobject NewLocalRef(JNIEnv* env, jobject ref) {
1225 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, ref);
1226 return CHECK_JNI_EXIT("L", baseEnv(env)->NewLocalRef(env, ref));
1227 }
1228
1229 static void DeleteGlobalRef(JNIEnv* env, jobject globalRef) {
1230 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, globalRef);
1231 if (globalRef != NULL && GetIndirectRefKind(globalRef) != kGlobal) {
1232 LOG(ERROR) << "JNI ERROR: DeleteGlobalRef on " << GetIndirectRefKind(globalRef) << ": " << globalRef;
1233 JniAbort(__FUNCTION__);
1234 } else {
1235 baseEnv(env)->DeleteGlobalRef(env, globalRef);
1236 CHECK_JNI_EXIT_VOID();
1237 }
1238 }
1239
1240 static void DeleteWeakGlobalRef(JNIEnv* env, jweak weakGlobalRef) {
1241 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, weakGlobalRef);
1242 if (weakGlobalRef != NULL && GetIndirectRefKind(weakGlobalRef) != kWeakGlobal) {
1243 LOG(ERROR) << "JNI ERROR: DeleteWeakGlobalRef on " << GetIndirectRefKind(weakGlobalRef) << ": " << weakGlobalRef;
1244 JniAbort(__FUNCTION__);
1245 } else {
1246 baseEnv(env)->DeleteWeakGlobalRef(env, weakGlobalRef);
1247 CHECK_JNI_EXIT_VOID();
1248 }
1249 }
1250
1251 static void DeleteLocalRef(JNIEnv* env, jobject localRef) {
1252 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, localRef);
1253 if (localRef != NULL && GetIndirectRefKind(localRef) != kLocal) {
1254 LOG(ERROR) << "JNI ERROR: DeleteLocalRef on " << GetIndirectRefKind(localRef) << ": " << localRef;
1255 JniAbort(__FUNCTION__);
1256 } else {
1257 baseEnv(env)->DeleteLocalRef(env, localRef);
1258 CHECK_JNI_EXIT_VOID();
1259 }
1260 }
1261
1262 static jint EnsureLocalCapacity(JNIEnv *env, jint capacity) {
1263 CHECK_JNI_ENTRY(kFlag_Default, "EI", env, capacity);
1264 return CHECK_JNI_EXIT("I", baseEnv(env)->EnsureLocalCapacity(env, capacity));
1265 }
1266
1267 static jboolean IsSameObject(JNIEnv* env, jobject ref1, jobject ref2) {
1268 CHECK_JNI_ENTRY(kFlag_Default, "ELL", env, ref1, ref2);
1269 return CHECK_JNI_EXIT("b", baseEnv(env)->IsSameObject(env, ref1, ref2));
1270 }
1271
1272 static jobject AllocObject(JNIEnv* env, jclass clazz) {
1273 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1274 return CHECK_JNI_EXIT("L", baseEnv(env)->AllocObject(env, clazz));
1275 }
1276
1277 static jobject NewObject(JNIEnv* env, jclass clazz, jmethodID mid, ...) {
1278 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1279 va_list args;
1280 va_start(args, mid);
1281 jobject result = baseEnv(env)->NewObjectV(env, clazz, mid, args);
1282 va_end(args);
1283 return CHECK_JNI_EXIT("L", result);
1284 }
1285
1286 static jobject NewObjectV(JNIEnv* env, jclass clazz, jmethodID mid, va_list args) {
1287 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1288 return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectV(env, clazz, mid, args));
1289 }
1290
1291 static jobject NewObjectA(JNIEnv* env, jclass clazz, jmethodID mid, jvalue* args) {
1292 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1293 return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectA(env, clazz, mid, args));
1294 }
1295
1296 static jclass GetObjectClass(JNIEnv* env, jobject obj) {
1297 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1298 return CHECK_JNI_EXIT("c", baseEnv(env)->GetObjectClass(env, obj));
1299 }
1300
1301 static jboolean IsInstanceOf(JNIEnv* env, jobject obj, jclass clazz) {
1302 CHECK_JNI_ENTRY(kFlag_Default, "ELc", env, obj, clazz);
1303 return CHECK_JNI_EXIT("b", baseEnv(env)->IsInstanceOf(env, obj, clazz));
1304 }
1305
1306 static jmethodID GetMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1307 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1308 return CHECK_JNI_EXIT("m", baseEnv(env)->GetMethodID(env, clazz, name, sig));
1309 }
1310
1311 static jfieldID GetFieldID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1312 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1313 return CHECK_JNI_EXIT("f", baseEnv(env)->GetFieldID(env, clazz, name, sig));
1314 }
1315
1316 static jmethodID GetStaticMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1317 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1318 return CHECK_JNI_EXIT("m", baseEnv(env)->GetStaticMethodID(env, clazz, name, sig));
1319 }
1320
1321 static jfieldID GetStaticFieldID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1322 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1323 return CHECK_JNI_EXIT("f", baseEnv(env)->GetStaticFieldID(env, clazz, name, sig));
1324 }
1325
1326#define FIELD_ACCESSORS(_ctype, _jname, _type) \
1327 static _ctype GetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fid) { \
1328 CHECK_JNI_ENTRY(kFlag_Default, "Ecf", env, clazz, fid); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001329 sc.CheckStaticFieldID(clazz, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001330 return CHECK_JNI_EXIT(_type, baseEnv(env)->GetStatic##_jname##Field(env, clazz, fid)); \
1331 } \
1332 static _ctype Get##_jname##Field(JNIEnv* env, jobject obj, jfieldID fid) { \
1333 CHECK_JNI_ENTRY(kFlag_Default, "ELf", env, obj, fid); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001334 sc.CheckInstanceFieldID(obj, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001335 return CHECK_JNI_EXIT(_type, baseEnv(env)->Get##_jname##Field(env, obj, fid)); \
1336 } \
1337 static void SetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fid, _ctype value) { \
1338 CHECK_JNI_ENTRY(kFlag_Default, "Ecf" _type, env, clazz, fid, value); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001339 sc.CheckStaticFieldID(clazz, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001340 /* "value" arg only used when type == ref */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001341 sc.CheckFieldType((jobject)(uint32_t)value, fid, _type[0], true); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001342 baseEnv(env)->SetStatic##_jname##Field(env, clazz, fid, value); \
1343 CHECK_JNI_EXIT_VOID(); \
1344 } \
1345 static void Set##_jname##Field(JNIEnv* env, jobject obj, jfieldID fid, _ctype value) { \
1346 CHECK_JNI_ENTRY(kFlag_Default, "ELf" _type, env, obj, fid, value); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001347 sc.CheckInstanceFieldID(obj, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001348 /* "value" arg only used when type == ref */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001349 sc.CheckFieldType((jobject)(uint32_t) value, fid, _type[0], false); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001350 baseEnv(env)->Set##_jname##Field(env, obj, fid, value); \
1351 CHECK_JNI_EXIT_VOID(); \
1352 }
1353
1354FIELD_ACCESSORS(jobject, Object, "L");
1355FIELD_ACCESSORS(jboolean, Boolean, "Z");
1356FIELD_ACCESSORS(jbyte, Byte, "B");
1357FIELD_ACCESSORS(jchar, Char, "C");
1358FIELD_ACCESSORS(jshort, Short, "S");
1359FIELD_ACCESSORS(jint, Int, "I");
1360FIELD_ACCESSORS(jlong, Long, "J");
1361FIELD_ACCESSORS(jfloat, Float, "F");
1362FIELD_ACCESSORS(jdouble, Double, "D");
1363
1364#define CALL(_ctype, _jname, _retdecl, _retasgn, _retok, _retsig) \
1365 /* Virtual... */ \
1366 static _ctype Call##_jname##Method(JNIEnv* env, jobject obj, \
1367 jmethodID mid, ...) \
1368 { \
1369 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001370 sc.CheckSig(mid, _retsig, false); \
1371 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001372 _retdecl; \
1373 va_list args; \
1374 va_start(args, mid); \
1375 _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, mid, args); \
1376 va_end(args); \
1377 _retok; \
1378 } \
1379 static _ctype Call##_jname##MethodV(JNIEnv* env, jobject obj, \
1380 jmethodID mid, va_list args) \
1381 { \
1382 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001383 sc.CheckSig(mid, _retsig, false); \
1384 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001385 _retdecl; \
1386 _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, mid, args); \
1387 _retok; \
1388 } \
1389 static _ctype Call##_jname##MethodA(JNIEnv* env, jobject obj, \
1390 jmethodID mid, jvalue* args) \
1391 { \
1392 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001393 sc.CheckSig(mid, _retsig, false); \
1394 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001395 _retdecl; \
1396 _retasgn baseEnv(env)->Call##_jname##MethodA(env, obj, mid, args); \
1397 _retok; \
1398 } \
1399 /* Non-virtual... */ \
1400 static _ctype CallNonvirtual##_jname##Method(JNIEnv* env, \
1401 jobject obj, jclass clazz, jmethodID mid, ...) \
1402 { \
1403 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001404 sc.CheckSig(mid, _retsig, false); \
1405 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001406 _retdecl; \
1407 va_list args; \
1408 va_start(args, mid); \
1409 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, mid, args); \
1410 va_end(args); \
1411 _retok; \
1412 } \
1413 static _ctype CallNonvirtual##_jname##MethodV(JNIEnv* env, \
1414 jobject obj, jclass clazz, jmethodID mid, va_list args) \
1415 { \
1416 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001417 sc.CheckSig(mid, _retsig, false); \
1418 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001419 _retdecl; \
1420 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, mid, args); \
1421 _retok; \
1422 } \
1423 static _ctype CallNonvirtual##_jname##MethodA(JNIEnv* env, \
1424 jobject obj, jclass clazz, jmethodID mid, jvalue* args) \
1425 { \
1426 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001427 sc.CheckSig(mid, _retsig, false); \
1428 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001429 _retdecl; \
1430 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodA(env, obj, clazz, mid, args); \
1431 _retok; \
1432 } \
1433 /* Static... */ \
1434 static _ctype CallStatic##_jname##Method(JNIEnv* env, \
1435 jclass clazz, jmethodID mid, ...) \
1436 { \
1437 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001438 sc.CheckSig(mid, _retsig, true); \
1439 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001440 _retdecl; \
1441 va_list args; \
1442 va_start(args, mid); \
1443 _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, mid, args); \
1444 va_end(args); \
1445 _retok; \
1446 } \
1447 static _ctype CallStatic##_jname##MethodV(JNIEnv* env, \
1448 jclass clazz, jmethodID mid, va_list args) \
1449 { \
1450 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001451 sc.CheckSig(mid, _retsig, true); \
1452 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001453 _retdecl; \
1454 _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, mid, args); \
1455 _retok; \
1456 } \
1457 static _ctype CallStatic##_jname##MethodA(JNIEnv* env, \
1458 jclass clazz, jmethodID mid, jvalue* args) \
1459 { \
1460 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001461 sc.CheckSig(mid, _retsig, true); \
1462 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001463 _retdecl; \
1464 _retasgn baseEnv(env)->CallStatic##_jname##MethodA(env, clazz, mid, args); \
1465 _retok; \
1466 }
1467
1468#define NON_VOID_RETURN(_retsig, _ctype) return CHECK_JNI_EXIT(_retsig, (_ctype) result)
1469#define VOID_RETURN CHECK_JNI_EXIT_VOID()
1470
1471CALL(jobject, Object, Object* result, result=(Object*), NON_VOID_RETURN("L", jobject), "L");
1472CALL(jboolean, Boolean, jboolean result, result=, NON_VOID_RETURN("Z", jboolean), "Z");
1473CALL(jbyte, Byte, jbyte result, result=, NON_VOID_RETURN("B", jbyte), "B");
1474CALL(jchar, Char, jchar result, result=, NON_VOID_RETURN("C", jchar), "C");
1475CALL(jshort, Short, jshort result, result=, NON_VOID_RETURN("S", jshort), "S");
1476CALL(jint, Int, jint result, result=, NON_VOID_RETURN("I", jint), "I");
1477CALL(jlong, Long, jlong result, result=, NON_VOID_RETURN("J", jlong), "J");
1478CALL(jfloat, Float, jfloat result, result=, NON_VOID_RETURN("F", jfloat), "F");
1479CALL(jdouble, Double, jdouble result, result=, NON_VOID_RETURN("D", jdouble), "D");
1480CALL(void, Void, , , VOID_RETURN, "V");
1481
1482 static jstring NewString(JNIEnv* env, const jchar* unicodeChars, jsize len) {
1483 CHECK_JNI_ENTRY(kFlag_Default, "Epz", env, unicodeChars, len);
1484 return CHECK_JNI_EXIT("s", baseEnv(env)->NewString(env, unicodeChars, len));
1485 }
1486
1487 static jsize GetStringLength(JNIEnv* env, jstring string) {
1488 CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1489 return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringLength(env, string));
1490 }
1491
1492 static const jchar* GetStringChars(JNIEnv* env, jstring java_string, jboolean* isCopy) {
1493 CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, java_string, isCopy);
1494 const jchar* result = baseEnv(env)->GetStringChars(env, java_string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001495 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001496 ScopedJniThreadState ts(env);
1497 String* s = Decode<String*>(ts, java_string);
1498 int byteCount = s->GetLength() * 2;
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001499 result = (const jchar*) GuardedCopy::Create(result, byteCount, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001500 if (isCopy != NULL) {
1501 *isCopy = JNI_TRUE;
1502 }
1503 }
1504 return CHECK_JNI_EXIT("p", result);
1505 }
1506
1507 static void ReleaseStringChars(JNIEnv* env, jstring string, const jchar* chars) {
1508 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Esp", env, string, chars);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001509 sc.CheckNonNull(chars);
1510 if (sc.ForceCopy()) {
1511 GuardedCopy::Check(__FUNCTION__, chars, false);
1512 chars = (const jchar*) GuardedCopy::Destroy((jchar*)chars);
Elliott Hughesa2501992011-08-26 19:39:54 -07001513 }
1514 baseEnv(env)->ReleaseStringChars(env, string, chars);
1515 CHECK_JNI_EXIT_VOID();
1516 }
1517
1518 static jstring NewStringUTF(JNIEnv* env, const char* bytes) {
1519 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, bytes); // TODO: show pointer and truncate string.
1520 return CHECK_JNI_EXIT("s", baseEnv(env)->NewStringUTF(env, bytes));
1521 }
1522
1523 static jsize GetStringUTFLength(JNIEnv* env, jstring string) {
1524 CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1525 return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringUTFLength(env, string));
1526 }
1527
1528 static const char* GetStringUTFChars(JNIEnv* env, jstring string, jboolean* isCopy) {
1529 CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
1530 const char* result = baseEnv(env)->GetStringUTFChars(env, string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001531 if (sc.ForceCopy() && result != NULL) {
1532 result = (const char*) GuardedCopy::Create(result, strlen(result) + 1, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001533 if (isCopy != NULL) {
1534 *isCopy = JNI_TRUE;
1535 }
1536 }
1537 return CHECK_JNI_EXIT("u", result); // TODO: show pointer and truncate string.
1538 }
1539
1540 static void ReleaseStringUTFChars(JNIEnv* env, jstring string, const char* utf) {
1541 CHECK_JNI_ENTRY(kFlag_ExcepOkay | kFlag_Release, "Esu", env, string, utf); // TODO: show pointer and truncate string.
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001542 if (sc.ForceCopy()) {
1543 GuardedCopy::Check(__FUNCTION__, utf, false);
1544 utf = (const char*) GuardedCopy::Destroy((char*)utf);
Elliott Hughesa2501992011-08-26 19:39:54 -07001545 }
1546 baseEnv(env)->ReleaseStringUTFChars(env, string, utf);
1547 CHECK_JNI_EXIT_VOID();
1548 }
1549
1550 static jsize GetArrayLength(JNIEnv* env, jarray array) {
1551 CHECK_JNI_ENTRY(kFlag_CritOkay, "Ea", env, array);
1552 return CHECK_JNI_EXIT("I", baseEnv(env)->GetArrayLength(env, array));
1553 }
1554
1555 static jobjectArray NewObjectArray(JNIEnv* env, jsize length, jclass elementClass, jobject initialElement) {
1556 CHECK_JNI_ENTRY(kFlag_Default, "EzcL", env, length, elementClass, initialElement);
1557 return CHECK_JNI_EXIT("a", baseEnv(env)->NewObjectArray(env, length, elementClass, initialElement));
1558 }
1559
1560 static jobject GetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index) {
1561 CHECK_JNI_ENTRY(kFlag_Default, "EaI", env, array, index);
1562 return CHECK_JNI_EXIT("L", baseEnv(env)->GetObjectArrayElement(env, array, index));
1563 }
1564
1565 static void SetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, jobject value) {
1566 CHECK_JNI_ENTRY(kFlag_Default, "EaIL", env, array, index, value);
1567 baseEnv(env)->SetObjectArrayElement(env, array, index, value);
1568 CHECK_JNI_EXIT_VOID();
1569 }
1570
1571#define NEW_PRIMITIVE_ARRAY(_artype, _jname) \
1572 static _artype New##_jname##Array(JNIEnv* env, jsize length) { \
1573 CHECK_JNI_ENTRY(kFlag_Default, "Ez", env, length); \
1574 return CHECK_JNI_EXIT("a", baseEnv(env)->New##_jname##Array(env, length)); \
1575 }
1576NEW_PRIMITIVE_ARRAY(jbooleanArray, Boolean);
1577NEW_PRIMITIVE_ARRAY(jbyteArray, Byte);
1578NEW_PRIMITIVE_ARRAY(jcharArray, Char);
1579NEW_PRIMITIVE_ARRAY(jshortArray, Short);
1580NEW_PRIMITIVE_ARRAY(jintArray, Int);
1581NEW_PRIMITIVE_ARRAY(jlongArray, Long);
1582NEW_PRIMITIVE_ARRAY(jfloatArray, Float);
1583NEW_PRIMITIVE_ARRAY(jdoubleArray, Double);
1584
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001585struct ForceCopyGetChecker {
Elliott Hughesa2501992011-08-26 19:39:54 -07001586public:
1587 ForceCopyGetChecker(ScopedCheck& sc, jboolean* isCopy) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001588 force_copy = sc.ForceCopy();
1589 no_copy = 0;
1590 if (force_copy && isCopy != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001591 /* capture this before the base call tramples on it */
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001592 no_copy = *(uint32_t*) isCopy;
Elliott Hughesa2501992011-08-26 19:39:54 -07001593 }
1594 }
1595
1596 template<typename ResultT>
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001597 ResultT Check(JNIEnv* env, jarray array, jboolean* isCopy, ResultT result) {
1598 if (force_copy && result != NULL) {
1599 if (no_copy != kNoCopyMagic) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001600 result = reinterpret_cast<ResultT>(CreateGuardedPACopy(env, array, isCopy));
1601 }
1602 }
1603 return result;
1604 }
1605
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001606 uint32_t no_copy;
1607 bool force_copy;
Elliott Hughesa2501992011-08-26 19:39:54 -07001608};
1609
1610#define GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1611 static _ctype* Get##_jname##ArrayElements(JNIEnv* env, _ctype##Array array, jboolean* isCopy) { \
1612 CHECK_JNI_ENTRY(kFlag_Default, "Eap", env, array, isCopy); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001613 _ctype* result = ForceCopyGetChecker(sc, isCopy).Check(env, array, isCopy, baseEnv(env)->Get##_jname##ArrayElements(env, array, isCopy)); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001614 return CHECK_JNI_EXIT("p", result); \
1615 }
1616
1617#define RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1618 static void Release##_jname##ArrayElements(JNIEnv* env, _ctype##Array array, _ctype* elems, jint mode) { \
1619 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Eapr", env, array, elems, mode); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001620 sc.CheckNonNull(elems); \
1621 if (sc.ForceCopy()) { \
Elliott Hughesa2501992011-08-26 19:39:54 -07001622 ReleaseGuardedPACopy(env, array, elems, mode); \
1623 } \
1624 baseEnv(env)->Release##_jname##ArrayElements(env, array, elems, mode); \
1625 CHECK_JNI_EXIT_VOID(); \
1626 }
1627
1628#define GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1629 static void Get##_jname##ArrayRegion(JNIEnv* env, _ctype##Array array, jsize start, jsize len, _ctype* buf) { \
1630 CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1631 baseEnv(env)->Get##_jname##ArrayRegion(env, array, start, len, buf); \
1632 CHECK_JNI_EXIT_VOID(); \
1633 }
1634
1635#define SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1636 static void Set##_jname##ArrayRegion(JNIEnv* env, _ctype##Array array, jsize start, jsize len, const _ctype* buf) { \
1637 CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1638 baseEnv(env)->Set##_jname##ArrayRegion(env, array, start, len, buf); \
1639 CHECK_JNI_EXIT_VOID(); \
1640 }
1641
1642#define PRIMITIVE_ARRAY_FUNCTIONS(_ctype, _jname, _typechar) \
1643 GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1644 RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1645 GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname); \
1646 SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname);
1647
1648/* TODO: verify primitive array type matches call type */
1649PRIMITIVE_ARRAY_FUNCTIONS(jboolean, Boolean, 'Z');
1650PRIMITIVE_ARRAY_FUNCTIONS(jbyte, Byte, 'B');
1651PRIMITIVE_ARRAY_FUNCTIONS(jchar, Char, 'C');
1652PRIMITIVE_ARRAY_FUNCTIONS(jshort, Short, 'S');
1653PRIMITIVE_ARRAY_FUNCTIONS(jint, Int, 'I');
1654PRIMITIVE_ARRAY_FUNCTIONS(jlong, Long, 'J');
1655PRIMITIVE_ARRAY_FUNCTIONS(jfloat, Float, 'F');
1656PRIMITIVE_ARRAY_FUNCTIONS(jdouble, Double, 'D');
1657
1658 static jint RegisterNatives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
1659 CHECK_JNI_ENTRY(kFlag_Default, "EcpI", env, clazz, methods, nMethods);
1660 return CHECK_JNI_EXIT("I", baseEnv(env)->RegisterNatives(env, clazz, methods, nMethods));
1661 }
1662
1663 static jint UnregisterNatives(JNIEnv* env, jclass clazz) {
1664 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1665 return CHECK_JNI_EXIT("I", baseEnv(env)->UnregisterNatives(env, clazz));
1666 }
1667
1668 static jint MonitorEnter(JNIEnv* env, jobject obj) {
1669 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1670 return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorEnter(env, obj));
1671 }
1672
1673 static jint MonitorExit(JNIEnv* env, jobject obj) {
1674 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
1675 return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorExit(env, obj));
1676 }
1677
1678 static jint GetJavaVM(JNIEnv *env, JavaVM **vm) {
1679 CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, vm);
1680 return CHECK_JNI_EXIT("I", baseEnv(env)->GetJavaVM(env, vm));
1681 }
1682
1683 static void GetStringRegion(JNIEnv* env, jstring str, jsize start, jsize len, jchar* buf) {
1684 CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1685 baseEnv(env)->GetStringRegion(env, str, start, len, buf);
1686 CHECK_JNI_EXIT_VOID();
1687 }
1688
1689 static void GetStringUTFRegion(JNIEnv* env, jstring str, jsize start, jsize len, char* buf) {
1690 CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1691 baseEnv(env)->GetStringUTFRegion(env, str, start, len, buf);
1692 CHECK_JNI_EXIT_VOID();
1693 }
1694
1695 static void* GetPrimitiveArrayCritical(JNIEnv* env, jarray array, jboolean* isCopy) {
1696 CHECK_JNI_ENTRY(kFlag_CritGet, "Eap", env, array, isCopy);
1697 void* result = baseEnv(env)->GetPrimitiveArrayCritical(env, array, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001698 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001699 result = CreateGuardedPACopy(env, array, isCopy);
1700 }
1701 return CHECK_JNI_EXIT("p", result);
1702 }
1703
1704 static void ReleasePrimitiveArrayCritical(JNIEnv* env, jarray array, void* carray, jint mode) {
1705 CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Eapr", env, array, carray, mode);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001706 sc.CheckNonNull(carray);
1707 if (sc.ForceCopy()) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001708 ReleaseGuardedPACopy(env, array, carray, mode);
1709 }
1710 baseEnv(env)->ReleasePrimitiveArrayCritical(env, array, carray, mode);
1711 CHECK_JNI_EXIT_VOID();
1712 }
1713
1714 static const jchar* GetStringCritical(JNIEnv* env, jstring java_string, jboolean* isCopy) {
1715 CHECK_JNI_ENTRY(kFlag_CritGet, "Esp", env, java_string, isCopy);
1716 const jchar* result = baseEnv(env)->GetStringCritical(env, java_string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001717 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001718 ScopedJniThreadState ts(env);
1719 String* s = Decode<String*>(ts, java_string);
1720 int byteCount = s->GetLength() * 2;
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001721 result = (const jchar*) GuardedCopy::Create(result, byteCount, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001722 if (isCopy != NULL) {
1723 *isCopy = JNI_TRUE;
1724 }
1725 }
1726 return CHECK_JNI_EXIT("p", result);
1727 }
1728
1729 static void ReleaseStringCritical(JNIEnv* env, jstring string, const jchar* carray) {
1730 CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Esp", env, string, carray);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001731 sc.CheckNonNull(carray);
1732 if (sc.ForceCopy()) {
1733 GuardedCopy::Check(__FUNCTION__, carray, false);
1734 carray = (const jchar*) GuardedCopy::Destroy((jchar*)carray);
Elliott Hughesa2501992011-08-26 19:39:54 -07001735 }
1736 baseEnv(env)->ReleaseStringCritical(env, string, carray);
1737 CHECK_JNI_EXIT_VOID();
1738 }
1739
1740 static jweak NewWeakGlobalRef(JNIEnv* env, jobject obj) {
1741 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1742 return CHECK_JNI_EXIT("L", baseEnv(env)->NewWeakGlobalRef(env, obj));
1743 }
1744
1745 static jboolean ExceptionCheck(JNIEnv* env) {
1746 CHECK_JNI_ENTRY(kFlag_CritOkay | kFlag_ExcepOkay, "E", env);
1747 return CHECK_JNI_EXIT("b", baseEnv(env)->ExceptionCheck(env));
1748 }
1749
1750 static jobjectRefType GetObjectRefType(JNIEnv* env, jobject obj) {
1751 // Note: we use "Ep" rather than "EL" because this is the one JNI function
1752 // that it's okay to pass an invalid reference to.
1753 CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, obj);
1754 // TODO: proper decoding of jobjectRefType!
1755 return CHECK_JNI_EXIT("I", baseEnv(env)->GetObjectRefType(env, obj));
1756 }
1757
1758 static jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
1759 CHECK_JNI_ENTRY(kFlag_Default, "EpJ", env, address, capacity);
1760 if (address == NULL) {
1761 LOG(ERROR) << "JNI ERROR: non-nullable address is NULL";
1762 JniAbort(__FUNCTION__);
1763 }
1764 if (capacity <= 0) {
1765 LOG(ERROR) << "JNI ERROR: capacity must be greater than 0: " << capacity;
1766 JniAbort(__FUNCTION__);
1767 }
1768 return CHECK_JNI_EXIT("L", baseEnv(env)->NewDirectByteBuffer(env, address, capacity));
1769 }
1770
1771 static void* GetDirectBufferAddress(JNIEnv* env, jobject buf) {
1772 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1773 // TODO: check that 'buf' is a java.nio.Buffer.
1774 return CHECK_JNI_EXIT("p", baseEnv(env)->GetDirectBufferAddress(env, buf));
1775 }
1776
1777 static jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf) {
1778 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1779 // TODO: check that 'buf' is a java.nio.Buffer.
1780 return CHECK_JNI_EXIT("J", baseEnv(env)->GetDirectBufferCapacity(env, buf));
1781 }
1782
1783 private:
1784 static inline const JNINativeInterface* baseEnv(JNIEnv* env) {
1785 return reinterpret_cast<JNIEnvExt*>(env)->unchecked_functions;
1786 }
1787};
1788
1789const JNINativeInterface gCheckNativeInterface = {
1790 NULL, // reserved0.
1791 NULL, // reserved1.
1792 NULL, // reserved2.
1793 NULL, // reserved3.
1794 CheckJNI::GetVersion,
1795 CheckJNI::DefineClass,
1796 CheckJNI::FindClass,
1797 CheckJNI::FromReflectedMethod,
1798 CheckJNI::FromReflectedField,
1799 CheckJNI::ToReflectedMethod,
1800 CheckJNI::GetSuperclass,
1801 CheckJNI::IsAssignableFrom,
1802 CheckJNI::ToReflectedField,
1803 CheckJNI::Throw,
1804 CheckJNI::ThrowNew,
1805 CheckJNI::ExceptionOccurred,
1806 CheckJNI::ExceptionDescribe,
1807 CheckJNI::ExceptionClear,
1808 CheckJNI::FatalError,
1809 CheckJNI::PushLocalFrame,
1810 CheckJNI::PopLocalFrame,
1811 CheckJNI::NewGlobalRef,
1812 CheckJNI::DeleteGlobalRef,
1813 CheckJNI::DeleteLocalRef,
1814 CheckJNI::IsSameObject,
1815 CheckJNI::NewLocalRef,
1816 CheckJNI::EnsureLocalCapacity,
1817 CheckJNI::AllocObject,
1818 CheckJNI::NewObject,
1819 CheckJNI::NewObjectV,
1820 CheckJNI::NewObjectA,
1821 CheckJNI::GetObjectClass,
1822 CheckJNI::IsInstanceOf,
1823 CheckJNI::GetMethodID,
1824 CheckJNI::CallObjectMethod,
1825 CheckJNI::CallObjectMethodV,
1826 CheckJNI::CallObjectMethodA,
1827 CheckJNI::CallBooleanMethod,
1828 CheckJNI::CallBooleanMethodV,
1829 CheckJNI::CallBooleanMethodA,
1830 CheckJNI::CallByteMethod,
1831 CheckJNI::CallByteMethodV,
1832 CheckJNI::CallByteMethodA,
1833 CheckJNI::CallCharMethod,
1834 CheckJNI::CallCharMethodV,
1835 CheckJNI::CallCharMethodA,
1836 CheckJNI::CallShortMethod,
1837 CheckJNI::CallShortMethodV,
1838 CheckJNI::CallShortMethodA,
1839 CheckJNI::CallIntMethod,
1840 CheckJNI::CallIntMethodV,
1841 CheckJNI::CallIntMethodA,
1842 CheckJNI::CallLongMethod,
1843 CheckJNI::CallLongMethodV,
1844 CheckJNI::CallLongMethodA,
1845 CheckJNI::CallFloatMethod,
1846 CheckJNI::CallFloatMethodV,
1847 CheckJNI::CallFloatMethodA,
1848 CheckJNI::CallDoubleMethod,
1849 CheckJNI::CallDoubleMethodV,
1850 CheckJNI::CallDoubleMethodA,
1851 CheckJNI::CallVoidMethod,
1852 CheckJNI::CallVoidMethodV,
1853 CheckJNI::CallVoidMethodA,
1854 CheckJNI::CallNonvirtualObjectMethod,
1855 CheckJNI::CallNonvirtualObjectMethodV,
1856 CheckJNI::CallNonvirtualObjectMethodA,
1857 CheckJNI::CallNonvirtualBooleanMethod,
1858 CheckJNI::CallNonvirtualBooleanMethodV,
1859 CheckJNI::CallNonvirtualBooleanMethodA,
1860 CheckJNI::CallNonvirtualByteMethod,
1861 CheckJNI::CallNonvirtualByteMethodV,
1862 CheckJNI::CallNonvirtualByteMethodA,
1863 CheckJNI::CallNonvirtualCharMethod,
1864 CheckJNI::CallNonvirtualCharMethodV,
1865 CheckJNI::CallNonvirtualCharMethodA,
1866 CheckJNI::CallNonvirtualShortMethod,
1867 CheckJNI::CallNonvirtualShortMethodV,
1868 CheckJNI::CallNonvirtualShortMethodA,
1869 CheckJNI::CallNonvirtualIntMethod,
1870 CheckJNI::CallNonvirtualIntMethodV,
1871 CheckJNI::CallNonvirtualIntMethodA,
1872 CheckJNI::CallNonvirtualLongMethod,
1873 CheckJNI::CallNonvirtualLongMethodV,
1874 CheckJNI::CallNonvirtualLongMethodA,
1875 CheckJNI::CallNonvirtualFloatMethod,
1876 CheckJNI::CallNonvirtualFloatMethodV,
1877 CheckJNI::CallNonvirtualFloatMethodA,
1878 CheckJNI::CallNonvirtualDoubleMethod,
1879 CheckJNI::CallNonvirtualDoubleMethodV,
1880 CheckJNI::CallNonvirtualDoubleMethodA,
1881 CheckJNI::CallNonvirtualVoidMethod,
1882 CheckJNI::CallNonvirtualVoidMethodV,
1883 CheckJNI::CallNonvirtualVoidMethodA,
1884 CheckJNI::GetFieldID,
1885 CheckJNI::GetObjectField,
1886 CheckJNI::GetBooleanField,
1887 CheckJNI::GetByteField,
1888 CheckJNI::GetCharField,
1889 CheckJNI::GetShortField,
1890 CheckJNI::GetIntField,
1891 CheckJNI::GetLongField,
1892 CheckJNI::GetFloatField,
1893 CheckJNI::GetDoubleField,
1894 CheckJNI::SetObjectField,
1895 CheckJNI::SetBooleanField,
1896 CheckJNI::SetByteField,
1897 CheckJNI::SetCharField,
1898 CheckJNI::SetShortField,
1899 CheckJNI::SetIntField,
1900 CheckJNI::SetLongField,
1901 CheckJNI::SetFloatField,
1902 CheckJNI::SetDoubleField,
1903 CheckJNI::GetStaticMethodID,
1904 CheckJNI::CallStaticObjectMethod,
1905 CheckJNI::CallStaticObjectMethodV,
1906 CheckJNI::CallStaticObjectMethodA,
1907 CheckJNI::CallStaticBooleanMethod,
1908 CheckJNI::CallStaticBooleanMethodV,
1909 CheckJNI::CallStaticBooleanMethodA,
1910 CheckJNI::CallStaticByteMethod,
1911 CheckJNI::CallStaticByteMethodV,
1912 CheckJNI::CallStaticByteMethodA,
1913 CheckJNI::CallStaticCharMethod,
1914 CheckJNI::CallStaticCharMethodV,
1915 CheckJNI::CallStaticCharMethodA,
1916 CheckJNI::CallStaticShortMethod,
1917 CheckJNI::CallStaticShortMethodV,
1918 CheckJNI::CallStaticShortMethodA,
1919 CheckJNI::CallStaticIntMethod,
1920 CheckJNI::CallStaticIntMethodV,
1921 CheckJNI::CallStaticIntMethodA,
1922 CheckJNI::CallStaticLongMethod,
1923 CheckJNI::CallStaticLongMethodV,
1924 CheckJNI::CallStaticLongMethodA,
1925 CheckJNI::CallStaticFloatMethod,
1926 CheckJNI::CallStaticFloatMethodV,
1927 CheckJNI::CallStaticFloatMethodA,
1928 CheckJNI::CallStaticDoubleMethod,
1929 CheckJNI::CallStaticDoubleMethodV,
1930 CheckJNI::CallStaticDoubleMethodA,
1931 CheckJNI::CallStaticVoidMethod,
1932 CheckJNI::CallStaticVoidMethodV,
1933 CheckJNI::CallStaticVoidMethodA,
1934 CheckJNI::GetStaticFieldID,
1935 CheckJNI::GetStaticObjectField,
1936 CheckJNI::GetStaticBooleanField,
1937 CheckJNI::GetStaticByteField,
1938 CheckJNI::GetStaticCharField,
1939 CheckJNI::GetStaticShortField,
1940 CheckJNI::GetStaticIntField,
1941 CheckJNI::GetStaticLongField,
1942 CheckJNI::GetStaticFloatField,
1943 CheckJNI::GetStaticDoubleField,
1944 CheckJNI::SetStaticObjectField,
1945 CheckJNI::SetStaticBooleanField,
1946 CheckJNI::SetStaticByteField,
1947 CheckJNI::SetStaticCharField,
1948 CheckJNI::SetStaticShortField,
1949 CheckJNI::SetStaticIntField,
1950 CheckJNI::SetStaticLongField,
1951 CheckJNI::SetStaticFloatField,
1952 CheckJNI::SetStaticDoubleField,
1953 CheckJNI::NewString,
1954 CheckJNI::GetStringLength,
1955 CheckJNI::GetStringChars,
1956 CheckJNI::ReleaseStringChars,
1957 CheckJNI::NewStringUTF,
1958 CheckJNI::GetStringUTFLength,
1959 CheckJNI::GetStringUTFChars,
1960 CheckJNI::ReleaseStringUTFChars,
1961 CheckJNI::GetArrayLength,
1962 CheckJNI::NewObjectArray,
1963 CheckJNI::GetObjectArrayElement,
1964 CheckJNI::SetObjectArrayElement,
1965 CheckJNI::NewBooleanArray,
1966 CheckJNI::NewByteArray,
1967 CheckJNI::NewCharArray,
1968 CheckJNI::NewShortArray,
1969 CheckJNI::NewIntArray,
1970 CheckJNI::NewLongArray,
1971 CheckJNI::NewFloatArray,
1972 CheckJNI::NewDoubleArray,
1973 CheckJNI::GetBooleanArrayElements,
1974 CheckJNI::GetByteArrayElements,
1975 CheckJNI::GetCharArrayElements,
1976 CheckJNI::GetShortArrayElements,
1977 CheckJNI::GetIntArrayElements,
1978 CheckJNI::GetLongArrayElements,
1979 CheckJNI::GetFloatArrayElements,
1980 CheckJNI::GetDoubleArrayElements,
1981 CheckJNI::ReleaseBooleanArrayElements,
1982 CheckJNI::ReleaseByteArrayElements,
1983 CheckJNI::ReleaseCharArrayElements,
1984 CheckJNI::ReleaseShortArrayElements,
1985 CheckJNI::ReleaseIntArrayElements,
1986 CheckJNI::ReleaseLongArrayElements,
1987 CheckJNI::ReleaseFloatArrayElements,
1988 CheckJNI::ReleaseDoubleArrayElements,
1989 CheckJNI::GetBooleanArrayRegion,
1990 CheckJNI::GetByteArrayRegion,
1991 CheckJNI::GetCharArrayRegion,
1992 CheckJNI::GetShortArrayRegion,
1993 CheckJNI::GetIntArrayRegion,
1994 CheckJNI::GetLongArrayRegion,
1995 CheckJNI::GetFloatArrayRegion,
1996 CheckJNI::GetDoubleArrayRegion,
1997 CheckJNI::SetBooleanArrayRegion,
1998 CheckJNI::SetByteArrayRegion,
1999 CheckJNI::SetCharArrayRegion,
2000 CheckJNI::SetShortArrayRegion,
2001 CheckJNI::SetIntArrayRegion,
2002 CheckJNI::SetLongArrayRegion,
2003 CheckJNI::SetFloatArrayRegion,
2004 CheckJNI::SetDoubleArrayRegion,
2005 CheckJNI::RegisterNatives,
2006 CheckJNI::UnregisterNatives,
2007 CheckJNI::MonitorEnter,
2008 CheckJNI::MonitorExit,
2009 CheckJNI::GetJavaVM,
2010 CheckJNI::GetStringRegion,
2011 CheckJNI::GetStringUTFRegion,
2012 CheckJNI::GetPrimitiveArrayCritical,
2013 CheckJNI::ReleasePrimitiveArrayCritical,
2014 CheckJNI::GetStringCritical,
2015 CheckJNI::ReleaseStringCritical,
2016 CheckJNI::NewWeakGlobalRef,
2017 CheckJNI::DeleteWeakGlobalRef,
2018 CheckJNI::ExceptionCheck,
2019 CheckJNI::NewDirectByteBuffer,
2020 CheckJNI::GetDirectBufferAddress,
2021 CheckJNI::GetDirectBufferCapacity,
2022 CheckJNI::GetObjectRefType,
2023};
2024
2025const JNINativeInterface* GetCheckJniNativeInterface() {
2026 return &gCheckNativeInterface;
2027}
2028
2029class CheckJII {
2030public:
2031 static jint DestroyJavaVM(JavaVM* vm) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002032 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002033 sc.Check(true, "v", vm);
2034 return CHECK_JNI_EXIT("I", BaseVm(vm)->DestroyJavaVM(vm));
Elliott Hughesa2501992011-08-26 19:39:54 -07002035 }
2036
2037 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002038 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002039 sc.Check(true, "vpp", vm, p_env, thr_args);
2040 return CHECK_JNI_EXIT("I", BaseVm(vm)->AttachCurrentThread(vm, p_env, thr_args));
Elliott Hughesa2501992011-08-26 19:39:54 -07002041 }
2042
2043 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002044 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002045 sc.Check(true, "vpp", vm, p_env, thr_args);
2046 return CHECK_JNI_EXIT("I", BaseVm(vm)->AttachCurrentThreadAsDaemon(vm, p_env, thr_args));
Elliott Hughesa2501992011-08-26 19:39:54 -07002047 }
2048
2049 static jint DetachCurrentThread(JavaVM* vm) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002050 ScopedCheck sc(vm, true, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002051 sc.Check(true, "v", vm);
2052 return CHECK_JNI_EXIT("I", BaseVm(vm)->DetachCurrentThread(vm));
Elliott Hughesa2501992011-08-26 19:39:54 -07002053 }
2054
2055 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002056 ScopedCheck sc(vm, true, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002057 sc.Check(true, "v", vm);
2058 return CHECK_JNI_EXIT("I", BaseVm(vm)->GetEnv(vm, env, version));
Elliott Hughesa2501992011-08-26 19:39:54 -07002059 }
2060
2061 private:
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002062 static inline const JNIInvokeInterface* BaseVm(JavaVM* vm) {
Elliott Hughesa2501992011-08-26 19:39:54 -07002063 return reinterpret_cast<JavaVMExt*>(vm)->unchecked_functions;
2064 }
2065};
2066
2067const JNIInvokeInterface gCheckInvokeInterface = {
2068 NULL, // reserved0
2069 NULL, // reserved1
2070 NULL, // reserved2
2071 CheckJII::DestroyJavaVM,
2072 CheckJII::AttachCurrentThread,
2073 CheckJII::DetachCurrentThread,
2074 CheckJII::GetEnv,
2075 CheckJII::AttachCurrentThreadAsDaemon
2076};
2077
2078const JNIInvokeInterface* GetCheckJniInvokeInterface() {
2079 return &gCheckInvokeInterface;
2080}
2081
2082} // namespace art