blob: 26068fdda9f5fad6204c59a495fbc946b888c395 [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)) {
Elliott Hughes726079d2011-10-07 18:43:44 -0700271 LOG(ERROR) << "JNI ERROR: the return type of " << function_name_ << " does not match "
272 << PrettyMethod(m);
Elliott Hughesa2501992011-08-26 19:39:54 -0700273 JniAbort();
274 } else if (isStatic && !m->IsStatic()) {
275 if (isStatic) {
Elliott Hughes726079d2011-10-07 18:43:44 -0700276 LOG(ERROR) << "JNI ERROR: calling non-static method "
277 << PrettyMethod(m) << " with " << function_name_;
Elliott Hughesa2501992011-08-26 19:39:54 -0700278 } else {
Elliott Hughes726079d2011-10-07 18:43:44 -0700279 LOG(ERROR) << "JNI ERROR: calling static method "
280 << PrettyMethod(m) << " with non-static " << function_name_;
Elliott Hughesa2501992011-08-26 19:39:54 -0700281 }
282 JniAbort();
283 }
284 }
285
286 /*
287 * Verify that this static field ID is valid for this class.
288 *
289 * Assumes "java_class" has already been validated.
290 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700291 void CheckStaticFieldID(jclass java_class, jfieldID fid) {
292 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700293 Class* c = Decode<Class*>(ts, java_class);
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700294 const Field* f = CheckFieldID(fid);
295 if (f == NULL) {
296 return;
297 }
Elliott Hughesa2501992011-08-26 19:39:54 -0700298 if (f->GetDeclaringClass() != c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700299 LOG(ERROR) << "JNI ERROR: static jfieldID " << fid << " not valid for class " << PrettyClass(c);
Elliott Hughesa2501992011-08-26 19:39:54 -0700300 JniAbort();
301 }
302 }
303
304 /*
305 * Verify that "mid" is appropriate for "clazz".
306 *
307 * A mismatch isn't dangerous, because the jmethodID defines the class. In
308 * fact, jclazz is unused in the implementation. It's best if we don't
309 * allow bad code in the system though.
310 *
311 * Instances of "jclazz" must be instances of the method's declaring class.
312 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700313 void CheckStaticMethod(jclass java_class, jmethodID mid) {
314 ScopedJniThreadState ts(env_);
315 const Method* m = CheckMethodID(mid);
316 if (m == NULL) {
317 return;
318 }
Elliott Hughesa2501992011-08-26 19:39:54 -0700319 Class* c = Decode<Class*>(ts, java_class);
Elliott Hughesa2501992011-08-26 19:39:54 -0700320 if (!c->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700321 LOG(ERROR) << "JNI ERROR: can't call static " << PrettyMethod(m) << " on class " << PrettyClass(c);
Elliott Hughesa2501992011-08-26 19:39:54 -0700322 JniAbort();
323 }
324 }
325
326 /*
327 * Verify that "mid" is appropriate for "jobj".
328 *
329 * Make sure the object is an instance of the method's declaring class.
330 * (Note the mid might point to a declaration in an interface; this
331 * will be handled automatically by the instanceof check.)
332 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700333 void CheckVirtualMethod(jobject java_object, jmethodID mid) {
334 ScopedJniThreadState ts(env_);
335 const Method* m = CheckMethodID(mid);
336 if (m == NULL) {
337 return;
338 }
Elliott Hughesa2501992011-08-26 19:39:54 -0700339 Object* o = Decode<Object*>(ts, java_object);
Elliott Hughesa2501992011-08-26 19:39:54 -0700340 if (!o->InstanceOf(m->GetDeclaringClass())) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700341 LOG(ERROR) << "JNI ERROR: can't call " << PrettyMethod(m) << " on instance of " << PrettyTypeOf(o);
Elliott Hughesa2501992011-08-26 19:39:54 -0700342 JniAbort();
343 }
344 }
345
346 /**
347 * The format string is a sequence of the following characters,
348 * and must be followed by arguments of the corresponding types
349 * in the same order.
350 *
351 * Java primitive types:
352 * B - jbyte
353 * C - jchar
354 * D - jdouble
355 * F - jfloat
356 * I - jint
357 * J - jlong
358 * S - jshort
359 * Z - jboolean (shown as true and false)
360 * V - void
361 *
362 * Java reference types:
363 * L - jobject
364 * a - jarray
365 * c - jclass
366 * s - jstring
367 *
368 * JNI types:
369 * b - jboolean (shown as JNI_TRUE and JNI_FALSE)
370 * f - jfieldID
371 * m - jmethodID
372 * p - void*
373 * r - jint (for release mode arguments)
Elliott Hughes78090d12011-10-07 14:31:47 -0700374 * u - const char* (Modified UTF-8)
Elliott Hughesa2501992011-08-26 19:39:54 -0700375 * z - jsize (for lengths; use i if negative values are okay)
376 * v - JavaVM*
377 * E - JNIEnv*
378 * . - no argument; just print "..." (used for varargs JNI calls)
379 *
380 * Use the kFlag_NullableUtf flag where 'u' field(s) are nullable.
381 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700382 void Check(bool entry, const char* fmt0, ...) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700383 va_list ap;
384
Elliott Hughesa0957642011-09-02 14:27:33 -0700385 const Method* traceMethod = NULL;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700386 if ((!vm_->trace.empty() || vm_->log_third_party_jni) && has_method_) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700387 // We need to guard some of the invocation interface's calls: a bad caller might
388 // use DetachCurrentThread or GetEnv on a thread that's not yet attached.
Elliott Hughesa0957642011-09-02 14:27:33 -0700389 Thread* self = Thread::Current();
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700390 if ((flags_ & kFlag_Invocation) == 0 || self != NULL) {
Elliott Hughesa0957642011-09-02 14:27:33 -0700391 traceMethod = self->GetCurrentMethod();
Elliott Hughesa2501992011-08-26 19:39:54 -0700392 }
393 }
Elliott Hughesa0957642011-09-02 14:27:33 -0700394
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700395 if (traceMethod != NULL && ShouldTrace(vm_, traceMethod)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700396 va_start(ap, fmt0);
397 std::string msg;
398 for (const char* fmt = fmt0; *fmt;) {
399 char ch = *fmt++;
400 if (ch == 'B') { // jbyte
401 jbyte b = va_arg(ap, int);
402 if (b >= 0 && b < 10) {
403 StringAppendF(&msg, "%d", b);
404 } else {
405 StringAppendF(&msg, "%#x (%d)", b, b);
406 }
407 } else if (ch == 'C') { // jchar
408 jchar c = va_arg(ap, int);
409 if (c < 0x7f && c >= ' ') {
410 StringAppendF(&msg, "U+%x ('%c')", c, c);
411 } else {
412 StringAppendF(&msg, "U+%x", c);
413 }
414 } else if (ch == 'F' || ch == 'D') { // jfloat, jdouble
415 StringAppendF(&msg, "%g", va_arg(ap, double));
416 } else if (ch == 'I' || ch == 'S') { // jint, jshort
417 StringAppendF(&msg, "%d", va_arg(ap, int));
418 } else if (ch == 'J') { // jlong
419 StringAppendF(&msg, "%lld", va_arg(ap, jlong));
420 } else if (ch == 'Z') { // jboolean
421 StringAppendF(&msg, "%s", va_arg(ap, int) ? "true" : "false");
422 } else if (ch == 'V') { // void
423 msg += "void";
424 } else if (ch == 'v') { // JavaVM*
425 JavaVM* vm = va_arg(ap, JavaVM*);
426 StringAppendF(&msg, "(JavaVM*)%p", vm);
427 } else if (ch == 'E') { // JNIEnv*
428 JNIEnv* env = va_arg(ap, JNIEnv*);
429 StringAppendF(&msg, "(JNIEnv*)%p", env);
430 } else if (ch == 'L' || ch == 'a' || ch == 's') { // jobject, jarray, jstring
431 // For logging purposes, these are identical.
432 jobject o = va_arg(ap, jobject);
433 if (o == NULL) {
434 msg += "NULL";
435 } else {
436 StringAppendF(&msg, "%p", o);
437 }
438 } else if (ch == 'b') { // jboolean (JNI-style)
439 jboolean b = va_arg(ap, int);
440 msg += (b ? "JNI_TRUE" : "JNI_FALSE");
441 } else if (ch == 'c') { // jclass
442 jclass jc = va_arg(ap, jclass);
443 Class* c = reinterpret_cast<Class*>(Thread::Current()->DecodeJObject(jc));
444 if (c == NULL) {
445 msg += "NULL";
446 } else if (c == kInvalidIndirectRefObject || !Heap::IsHeapAddress(c)) {
447 StringAppendF(&msg, "%p(INVALID)", jc);
448 } else {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700449 msg += PrettyClass(c);
Elliott Hughesa2501992011-08-26 19:39:54 -0700450 if (!entry) {
451 StringAppendF(&msg, " (%p)", jc);
452 }
453 }
454 } else if (ch == 'f') { // jfieldID
455 jfieldID fid = va_arg(ap, jfieldID);
Elliott Hughes5ee7a8b2011-09-13 16:40:07 -0700456 Field* f = reinterpret_cast<Field*>(fid);
Elliott Hughesa2501992011-08-26 19:39:54 -0700457 msg += PrettyField(f);
458 if (!entry) {
459 StringAppendF(&msg, " (%p)", fid);
460 }
461 } else if (ch == 'z') { // non-negative jsize
462 // You might expect jsize to be size_t, but it's not; it's the same as jint.
463 // We only treat this specially so we can do the non-negative check.
464 // TODO: maybe this wasn't worth it?
465 jint i = va_arg(ap, jint);
466 StringAppendF(&msg, "%d", i);
467 } else if (ch == 'm') { // jmethodID
468 jmethodID mid = va_arg(ap, jmethodID);
Elliott Hughes5ee7a8b2011-09-13 16:40:07 -0700469 Method* m = reinterpret_cast<Method*>(mid);
Elliott Hughesa2501992011-08-26 19:39:54 -0700470 msg += PrettyMethod(m);
471 if (!entry) {
472 StringAppendF(&msg, " (%p)", mid);
473 }
474 } else if (ch == 'p') { // void* ("pointer")
475 void* p = va_arg(ap, void*);
476 if (p == NULL) {
477 msg += "NULL";
478 } else {
479 StringAppendF(&msg, "(void*) %p", p);
480 }
481 } else if (ch == 'r') { // jint (release mode)
482 jint releaseMode = va_arg(ap, jint);
483 if (releaseMode == 0) {
484 msg += "0";
485 } else if (releaseMode == JNI_ABORT) {
486 msg += "JNI_ABORT";
487 } else if (releaseMode == JNI_COMMIT) {
488 msg += "JNI_COMMIT";
489 } else {
490 StringAppendF(&msg, "invalid release mode %d", releaseMode);
491 }
Elliott Hughes78090d12011-10-07 14:31:47 -0700492 } else if (ch == 'u') { // const char* (Modified UTF-8)
Elliott Hughesa2501992011-08-26 19:39:54 -0700493 const char* utf = va_arg(ap, const char*);
494 if (utf == NULL) {
495 msg += "NULL";
496 } else {
497 StringAppendF(&msg, "\"%s\"", utf);
498 }
499 } else if (ch == '.') {
500 msg += "...";
501 } else {
502 LOG(ERROR) << "unknown trace format specifier: " << ch;
503 JniAbort();
504 return;
505 }
506 if (*fmt) {
507 StringAppendF(&msg, ", ");
508 }
509 }
510 va_end(ap);
511
512 if (entry) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700513 if (has_method_) {
Elliott Hughesa0957642011-09-02 14:27:33 -0700514 std::string methodName(PrettyMethod(traceMethod, false));
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700515 LOG(INFO) << "JNI: " << methodName << " -> " << function_name_ << "(" << msg << ")";
516 indent_ = methodName.size() + 1;
Elliott Hughesa2501992011-08-26 19:39:54 -0700517 } else {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700518 LOG(INFO) << "JNI: -> " << function_name_ << "(" << msg << ")";
519 indent_ = 0;
Elliott Hughesa2501992011-08-26 19:39:54 -0700520 }
521 } else {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700522 LOG(INFO) << StringPrintf("JNI: %*s<- %s returned %s", indent_, "", function_name_, msg.c_str());
Elliott Hughesa2501992011-08-26 19:39:54 -0700523 }
524 }
525
526 // We always do the thorough checks on entry, and never on exit...
527 if (entry) {
528 va_start(ap, fmt0);
529 for (const char* fmt = fmt0; *fmt; ++fmt) {
530 char ch = *fmt;
531 if (ch == 'a') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700532 CheckArray(va_arg(ap, jarray));
Elliott Hughesa2501992011-08-26 19:39:54 -0700533 } else if (ch == 'c') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700534 CheckInstance(kClass, va_arg(ap, jclass));
Elliott Hughesa2501992011-08-26 19:39:54 -0700535 } else if (ch == 'L') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700536 CheckObject(va_arg(ap, jobject));
Elliott Hughesa2501992011-08-26 19:39:54 -0700537 } else if (ch == 'r') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700538 CheckReleaseMode(va_arg(ap, jint));
Elliott Hughesa2501992011-08-26 19:39:54 -0700539 } else if (ch == 's') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700540 CheckInstance(kString, va_arg(ap, jstring));
Elliott Hughesa2501992011-08-26 19:39:54 -0700541 } else if (ch == 'u') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700542 if ((flags_ & kFlag_Release) != 0) {
543 CheckNonNull(va_arg(ap, const char*));
Elliott Hughesa2501992011-08-26 19:39:54 -0700544 } else {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700545 bool nullable = ((flags_ & kFlag_NullableUtf) != 0);
546 CheckUtfString(va_arg(ap, const char*), nullable);
Elliott Hughesa2501992011-08-26 19:39:54 -0700547 }
548 } else if (ch == 'z') {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700549 CheckLengthPositive(va_arg(ap, jsize));
Elliott Hughesa2501992011-08-26 19:39:54 -0700550 } else if (strchr("BCISZbfmpEv", ch) != NULL) {
551 va_arg(ap, int); // Skip this argument.
552 } else if (ch == 'D' || ch == 'F') {
553 va_arg(ap, double); // Skip this argument.
554 } else if (ch == 'J') {
555 va_arg(ap, long); // Skip this argument.
556 } else if (ch == '.') {
557 } else {
558 LOG(FATAL) << "unknown check format specifier: " << ch;
559 }
560 }
561 va_end(ap);
562 }
563 }
564
565private:
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700566 void Init(JNIEnv* env, JavaVM* vm, int flags, const char* functionName, bool hasMethod) {
567 env_ = reinterpret_cast<JNIEnvExt*>(env);
568 vm_ = reinterpret_cast<JavaVMExt*>(vm);
569 flags_ = flags;
570 function_name_ = functionName;
Elliott Hughesa2501992011-08-26 19:39:54 -0700571
572 // Set "hasMethod" to true if we have a valid thread with a method pointer.
573 // We won't have one before attaching a thread, after detaching a thread, or
574 // after destroying the VM.
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700575 has_method_ = hasMethod;
Elliott Hughesa2501992011-08-26 19:39:54 -0700576 }
577
578 /*
579 * Verify that "array" is non-NULL and points to an Array object.
580 *
581 * Since we're dealing with objects, switch to "running" mode.
582 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700583 void CheckArray(jarray java_array) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700584 if (java_array == NULL) {
585 LOG(ERROR) << "JNI ERROR: received null array";
586 JniAbort();
587 return;
588 }
589
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700590 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700591 Array* a = Decode<Array*>(ts, java_array);
592 if (!Heap::IsHeapAddress(a)) {
593 LOG(ERROR) << "JNI ERROR: jarray is an invalid " << GetIndirectRefKind(java_array) << ": " << reinterpret_cast<void*>(java_array);
594 JniAbort();
595 } else if (!a->IsArrayInstance()) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700596 LOG(ERROR) << "JNI ERROR: jarray argument has non-array type: " << PrettyTypeOf(a);
Elliott Hughesa2501992011-08-26 19:39:54 -0700597 JniAbort();
598 }
599 }
600
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700601 void CheckLengthPositive(jsize length) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700602 if (length < 0) {
603 LOG(ERROR) << "JNI ERROR: negative jsize: " << length;
604 JniAbort();
605 }
606 }
607
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700608 Field* CheckFieldID(jfieldID fid) {
609 if (fid == NULL) {
610 LOG(ERROR) << "JNI ERROR: null jfieldID";
611 JniAbort();
612 return NULL;
613 }
614 Field* f = DecodeField(fid);
615 if (!Heap::IsHeapAddress(f)) {
616 LOG(ERROR) << "JNI ERROR: invalid jfieldID: " << fid;
617 JniAbort();
618 return NULL;
619 }
620 return f;
621 }
622
623 Method* CheckMethodID(jmethodID mid) {
624 if (mid == NULL) {
625 LOG(ERROR) << "JNI ERROR: null jmethodID";
626 JniAbort();
627 return NULL;
628 }
629 Method* m = DecodeMethod(mid);
630 if (!Heap::IsHeapAddress(m)) {
631 LOG(ERROR) << "JNI ERROR: invalid jmethodID: " << mid;
632 JniAbort();
633 return NULL;
634 }
635 return m;
636 }
637
Elliott Hughesa2501992011-08-26 19:39:54 -0700638 /*
639 * Verify that "jobj" is a valid object, and that it's an object that JNI
640 * is allowed to know about. We allow NULL references.
641 *
642 * Switches to "running" mode before performing checks.
643 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700644 void CheckObject(jobject java_object) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700645 if (java_object == NULL) {
646 return;
647 }
648
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700649 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700650
651 Object* o = Decode<Object*>(ts, java_object);
652 if (o != NULL && !Heap::IsHeapAddress(o)) {
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700653 // TODO: when we remove work_around_app_jni_bugs, this should be impossible.
Elliott Hughesa2501992011-08-26 19:39:54 -0700654 LOG(ERROR) << "JNI ERROR: native code passing in reference to invalid " << GetIndirectRefKind(java_object) << ": " << java_object;
655 JniAbort();
656 }
657 }
658
659 /*
660 * Verify that the "mode" argument passed to a primitive array Release
661 * function is one of the valid values.
662 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700663 void CheckReleaseMode(jint mode) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700664 if (mode != 0 && mode != JNI_COMMIT && mode != JNI_ABORT) {
665 LOG(ERROR) << "JNI ERROR: bad value for release mode: " << mode;
666 JniAbort();
667 }
668 }
669
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700670 void CheckThread(int flags) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700671 Thread* self = Thread::Current();
672 if (self == NULL) {
673 LOG(ERROR) << "JNI ERROR: non-VM thread making JNI calls";
674 JniAbort();
675 return;
676 }
677
678 // Get the *correct* JNIEnv by going through our TLS pointer.
679 JNIEnvExt* threadEnv = self->GetJniEnv();
680
681 /*
682 * Verify that the current thread is (a) attached and (b) associated with
683 * this particular instance of JNIEnv.
684 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700685 if (env_ != threadEnv) {
686 LOG(ERROR) << "JNI ERROR: thread " << *self << " using JNIEnv* from thread " << *env_->self;
Elliott Hughesa2501992011-08-26 19:39:54 -0700687 // If we're keeping broken code limping along, we need to suppress the abort...
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700688 if (!env_->work_around_app_jni_bugs) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700689 JniAbort();
690 return;
691 }
692 }
693
694 /*
695 * Verify that, if this thread previously made a critical "get" call, we
696 * do the corresponding "release" call before we try anything else.
697 */
698 switch (flags & kFlag_CritMask) {
699 case kFlag_CritOkay: // okay to call this method
700 break;
701 case kFlag_CritBad: // not okay to call
702 if (threadEnv->critical) {
703 LOG(ERROR) << "JNI ERROR: thread " << *self << " using JNI after critical get";
704 JniAbort();
705 return;
706 }
707 break;
708 case kFlag_CritGet: // this is a "get" call
709 /* don't check here; we allow nested gets */
710 threadEnv->critical++;
711 break;
712 case kFlag_CritRelease: // this is a "release" call
713 threadEnv->critical--;
714 if (threadEnv->critical < 0) {
715 LOG(ERROR) << "JNI ERROR: thread " << *self << " called too many critical releases";
716 JniAbort();
717 return;
718 }
719 break;
720 default:
721 LOG(FATAL) << "bad flags (internal error): " << flags;
722 }
723
724 /*
725 * Verify that, if an exception has been raised, the native code doesn't
726 * make any JNI calls other than the Exception* methods.
727 */
728 if ((flags & kFlag_ExcepOkay) == 0 && self->IsExceptionPending()) {
Elliott Hughes726079d2011-10-07 18:43:44 -0700729 LOG(ERROR) << "JNI ERROR: JNI " << function_name_ << " called with "
730 << PrettyTypeOf(self->GetException()) << " pending";
Elliott Hughese6087632011-09-26 12:18:25 -0700731 LOG(ERROR) << "Pending exception is:";
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700732 LOG(ERROR) << jniGetStackTrace(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700733 JniAbort();
734 return;
735 }
736 }
737
738 /*
Elliott Hughes78090d12011-10-07 14:31:47 -0700739 * Verify that "bytes" points to valid Modified UTF-8 data.
Elliott Hughesa2501992011-08-26 19:39:54 -0700740 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700741 void CheckUtfString(const char* bytes, bool nullable) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700742 if (bytes == NULL) {
743 if (!nullable) {
744 LOG(ERROR) << "JNI ERROR: non-nullable const char* was NULL";
745 JniAbort();
746 return;
747 }
748 return;
749 }
750
751 const char* errorKind = NULL;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700752 uint8_t utf8 = CheckUtfBytes(bytes, &errorKind);
Elliott Hughesa2501992011-08-26 19:39:54 -0700753 if (errorKind != NULL) {
Elliott Hughes78090d12011-10-07 14:31:47 -0700754 LOG(ERROR) << "JNI ERROR: input is not valid Modified UTF-8: "
755 << "illegal " << errorKind << " byte " << StringPrintf("%#x", utf8) << "\n"
756 << " string: '" << bytes << "'";
Elliott Hughesa2501992011-08-26 19:39:54 -0700757 JniAbort();
758 return;
759 }
760 }
761
762 enum InstanceKind {
763 kClass,
764 kDirectByteBuffer,
765 kString,
766 kThrowable,
767 };
768
769 /*
770 * Verify that "jobj" is a valid non-NULL object reference, and points to
771 * an instance of expectedClass.
772 *
773 * Because we're looking at an object on the GC heap, we have to switch
774 * to "running" mode before doing the checks.
775 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700776 void CheckInstance(InstanceKind kind, jobject java_object) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700777 const char* what = NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700778 switch (kind) {
779 case kClass:
780 what = "jclass";
781 break;
782 case kDirectByteBuffer:
783 what = "direct ByteBuffer";
784 break;
785 case kString:
786 what = "jstring";
787 break;
788 case kThrowable:
789 what = "jthrowable";
790 break;
791 default:
792 CHECK(false) << static_cast<int>(kind);
793 }
794
795 if (java_object == NULL) {
796 LOG(ERROR) << "JNI ERROR: received null " << what;
797 JniAbort();
798 return;
799 }
800
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700801 ScopedJniThreadState ts(env_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700802 Object* obj = Decode<Object*>(ts, java_object);
803 if (!Heap::IsHeapAddress(obj)) {
804 LOG(ERROR) << "JNI ERROR: " << what << " is an invalid " << GetIndirectRefKind(java_object) << ": " << java_object;
805 JniAbort();
806 return;
807 }
808
809 bool okay = true;
810 switch (kind) {
811 case kClass:
812 okay = obj->IsClass();
813 break;
814 case kDirectByteBuffer:
815 // TODO
816 break;
817 case kString:
818 okay = obj->IsString();
819 break;
820 case kThrowable:
821 // TODO
822 break;
823 }
824 if (!okay) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700825 LOG(ERROR) << "JNI ERROR: " << what << " has wrong type: " << PrettyTypeOf(obj);
Elliott Hughesa2501992011-08-26 19:39:54 -0700826 JniAbort();
827 }
828 }
829
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700830 static uint8_t CheckUtfBytes(const char* bytes, const char** errorKind) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700831 while (*bytes != '\0') {
832 uint8_t utf8 = *(bytes++);
833 // Switch on the high four bits.
834 switch (utf8 >> 4) {
835 case 0x00:
836 case 0x01:
837 case 0x02:
838 case 0x03:
839 case 0x04:
840 case 0x05:
841 case 0x06:
842 case 0x07:
843 // Bit pattern 0xxx. No need for any extra bytes.
844 break;
845 case 0x08:
846 case 0x09:
847 case 0x0a:
848 case 0x0b:
849 case 0x0f:
850 /*
851 * Bit pattern 10xx or 1111, which are illegal start bytes.
852 * Note: 1111 is valid for normal UTF-8, but not the
Elliott Hughes78090d12011-10-07 14:31:47 -0700853 * Modified UTF-8 used here.
Elliott Hughesa2501992011-08-26 19:39:54 -0700854 */
855 *errorKind = "start";
856 return utf8;
857 case 0x0e:
858 // Bit pattern 1110, so there are two additional bytes.
859 utf8 = *(bytes++);
860 if ((utf8 & 0xc0) != 0x80) {
861 *errorKind = "continuation";
862 return utf8;
863 }
864 // Fall through to take care of the final byte.
865 case 0x0c:
866 case 0x0d:
867 // Bit pattern 110x, so there is one additional byte.
868 utf8 = *(bytes++);
869 if ((utf8 & 0xc0) != 0x80) {
870 *errorKind = "continuation";
871 return utf8;
872 }
873 break;
874 }
875 }
876 return 0;
877 }
878
879 void JniAbort() {
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700880 ::art::JniAbort(function_name_);
Elliott Hughesa2501992011-08-26 19:39:54 -0700881 }
882
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700883 JNIEnvExt* env_;
884 JavaVMExt* vm_;
885 const char* function_name_;
886 int flags_;
887 bool has_method_;
888 size_t indent_;
Elliott Hughesa2501992011-08-26 19:39:54 -0700889
890 DISALLOW_COPY_AND_ASSIGN(ScopedCheck);
891};
892
893#define CHECK_JNI_ENTRY(flags, types, args...) \
894 ScopedCheck sc(env, flags, __FUNCTION__); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700895 sc.Check(true, types, ##args)
Elliott Hughesa2501992011-08-26 19:39:54 -0700896
897#define CHECK_JNI_EXIT(type, exp) ({ \
898 typeof (exp) _rc = (exp); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700899 sc.Check(false, type, _rc); \
Elliott Hughesa2501992011-08-26 19:39:54 -0700900 _rc; })
901#define CHECK_JNI_EXIT_VOID() \
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700902 sc.Check(false, "V")
Elliott Hughesa2501992011-08-26 19:39:54 -0700903
904/*
905 * ===========================================================================
906 * Guarded arrays
907 * ===========================================================================
908 */
909
910#define kGuardLen 512 /* must be multiple of 2 */
911#define kGuardPattern 0xd5e3 /* uncommon values; d5e3d5e3 invalid addr */
912#define kGuardMagic 0xffd5aa96
913
914/* this gets tucked in at the start of the buffer; struct size must be even */
915struct GuardedCopy {
916 uint32_t magic;
917 uLong adler;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700918 size_t original_length;
919 const void* original_ptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700920
921 /* find the GuardedCopy given the pointer into the "live" data */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700922 static inline const GuardedCopy* FromData(const void* dataBuf) {
923 return reinterpret_cast<const GuardedCopy*>(ActualBuffer(dataBuf));
Elliott Hughesa2501992011-08-26 19:39:54 -0700924 }
925
926 /*
927 * Create an over-sized buffer to hold the contents of "buf". Copy it in,
928 * filling in the area around it with guard data.
929 *
930 * We use a 16-bit pattern to make a rogue memset less likely to elude us.
931 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700932 static void* Create(const void* buf, size_t len, bool modOkay) {
933 size_t newLen = ActualLength(len);
934 uint8_t* newBuf = DebugAlloc(newLen);
Elliott Hughesa2501992011-08-26 19:39:54 -0700935
936 /* fill it in with a pattern */
937 uint16_t* pat = (uint16_t*) newBuf;
938 for (size_t i = 0; i < newLen / 2; i++) {
939 *pat++ = kGuardPattern;
940 }
941
942 /* copy the data in; note "len" could be zero */
943 memcpy(newBuf + kGuardLen / 2, buf, len);
944
945 /* if modification is not expected, grab a checksum */
946 uLong adler = 0;
947 if (!modOkay) {
948 adler = adler32(0L, Z_NULL, 0);
949 adler = adler32(adler, (const Bytef*)buf, len);
950 *(uLong*)newBuf = adler;
951 }
952
953 GuardedCopy* pExtra = reinterpret_cast<GuardedCopy*>(newBuf);
954 pExtra->magic = kGuardMagic;
955 pExtra->adler = adler;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700956 pExtra->original_ptr = buf;
957 pExtra->original_length = len;
Elliott Hughesa2501992011-08-26 19:39:54 -0700958
959 return newBuf + kGuardLen / 2;
960 }
961
962 /*
963 * Free up the guard buffer, scrub it, and return the original pointer.
964 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700965 static void* Destroy(void* dataBuf) {
966 const GuardedCopy* pExtra = GuardedCopy::FromData(dataBuf);
967 void* original_ptr = (void*) pExtra->original_ptr;
968 size_t len = pExtra->original_length;
969 DebugFree(dataBuf, len);
970 return original_ptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700971 }
972
973 /*
974 * Verify the guard area and, if "modOkay" is false, that the data itself
975 * has not been altered.
976 *
977 * The caller has already checked that "dataBuf" is non-NULL.
978 */
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700979 static void Check(const char* functionName, const void* dataBuf, bool modOkay) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700980 static const uint32_t kMagicCmp = kGuardMagic;
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700981 const uint8_t* fullBuf = ActualBuffer(dataBuf);
982 const GuardedCopy* pExtra = GuardedCopy::FromData(dataBuf);
Elliott Hughesa2501992011-08-26 19:39:54 -0700983
984 /*
985 * Before we do anything with "pExtra", check the magic number. We
986 * do the check with memcmp rather than "==" in case the pointer is
987 * unaligned. If it points to completely bogus memory we're going
988 * to crash, but there's no easy way around that.
989 */
990 if (memcmp(&pExtra->magic, &kMagicCmp, 4) != 0) {
991 uint8_t buf[4];
992 memcpy(buf, &pExtra->magic, 4);
993 LOG(ERROR) << StringPrintf("JNI: guard magic does not match "
994 "(found 0x%02x%02x%02x%02x) -- incorrect data pointer %p?",
995 buf[3], buf[2], buf[1], buf[0], dataBuf); /* assume little endian */
996 JniAbort(functionName);
997 }
998
Elliott Hughes32ae6e32011-09-27 10:46:50 -0700999 size_t len = pExtra->original_length;
Elliott Hughesa2501992011-08-26 19:39:54 -07001000
1001 /* check bottom half of guard; skip over optional checksum storage */
1002 const uint16_t* pat = (uint16_t*) fullBuf;
1003 for (size_t i = sizeof(GuardedCopy) / 2; i < (kGuardLen / 2 - sizeof(GuardedCopy)) / 2; i++) {
1004 if (pat[i] != kGuardPattern) {
1005 LOG(ERROR) << "JNI: guard pattern(1) disturbed at " << (void*) fullBuf << " + " << (i*2);
1006 JniAbort(functionName);
1007 }
1008 }
1009
1010 int offset = kGuardLen / 2 + len;
1011 if (offset & 0x01) {
1012 /* odd byte; expected value depends on endian-ness of host */
1013 const uint16_t patSample = kGuardPattern;
1014 if (fullBuf[offset] != ((const uint8_t*) &patSample)[1]) {
1015 LOG(ERROR) << "JNI: guard pattern disturbed in odd byte after "
1016 << (void*) fullBuf << " (+" << offset << ") "
1017 << StringPrintf("0x%02x 0x%02x", fullBuf[offset], ((const uint8_t*) &patSample)[1]);
1018 JniAbort(functionName);
1019 }
1020 offset++;
1021 }
1022
1023 /* check top half of guard */
1024 pat = (uint16_t*) (fullBuf + offset);
1025 for (size_t i = 0; i < kGuardLen / 4; i++) {
1026 if (pat[i] != kGuardPattern) {
1027 LOG(ERROR) << "JNI: guard pattern(2) disturbed at " << (void*) fullBuf << " + " << (offset + i*2);
1028 JniAbort(functionName);
1029 }
1030 }
1031
1032 /*
1033 * If modification is not expected, verify checksum. Strictly speaking
1034 * this is wrong: if we told the client that we made a copy, there's no
1035 * reason they can't alter the buffer.
1036 */
1037 if (!modOkay) {
1038 uLong adler = adler32(0L, Z_NULL, 0);
1039 adler = adler32(adler, (const Bytef*)dataBuf, len);
1040 if (pExtra->adler != adler) {
1041 LOG(ERROR) << StringPrintf("JNI: buffer modified (0x%08lx vs 0x%08lx) at addr %p", pExtra->adler, adler, dataBuf);
1042 JniAbort(functionName);
1043 }
1044 }
1045 }
1046
1047 private:
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001048 static uint8_t* DebugAlloc(size_t len) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001049 void* result = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
1050 if (result == MAP_FAILED) {
1051 PLOG(FATAL) << "GuardedCopy::create mmap(" << len << ") failed";
1052 }
1053 return reinterpret_cast<uint8_t*>(result);
1054 }
1055
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001056 static void DebugFree(void* dataBuf, size_t len) {
1057 uint8_t* fullBuf = ActualBuffer(dataBuf);
1058 size_t totalByteCount = ActualLength(len);
Elliott Hughesa2501992011-08-26 19:39:54 -07001059 // TODO: we could mprotect instead, and keep the allocation around for a while.
1060 // This would be even more expensive, but it might catch more errors.
1061 // if (mprotect(fullBuf, totalByteCount, PROT_NONE) != 0) {
1062 // LOGW("mprotect(PROT_NONE) failed: %s", strerror(errno));
1063 // }
1064 if (munmap(fullBuf, totalByteCount) != 0) {
1065 PLOG(FATAL) << "munmap(" << (void*) fullBuf << ", " << totalByteCount << ") failed";
1066 }
1067 }
1068
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001069 static const uint8_t* ActualBuffer(const void* dataBuf) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001070 return reinterpret_cast<const uint8_t*>(dataBuf) - kGuardLen / 2;
1071 }
1072
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001073 static uint8_t* ActualBuffer(void* dataBuf) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001074 return reinterpret_cast<uint8_t*>(dataBuf) - kGuardLen / 2;
1075 }
1076
1077 // Underlying length of a user allocation of 'length' bytes.
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001078 static size_t ActualLength(size_t length) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001079 return (length + kGuardLen + 1) & ~0x01;
1080 }
1081};
1082
1083/*
1084 * Create a guarded copy of a primitive array. Modifications to the copied
1085 * data are allowed. Returns a pointer to the copied data.
1086 */
1087void* CreateGuardedPACopy(JNIEnv* env, const jarray java_array, jboolean* isCopy) {
1088 ScopedJniThreadState ts(env);
1089
1090 Array* a = Decode<Array*>(ts, java_array);
1091 size_t byte_count = a->GetLength() * a->GetClass()->GetComponentSize();
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001092 void* result = GuardedCopy::Create(a->GetRawData(), byte_count, true);
Elliott Hughesa2501992011-08-26 19:39:54 -07001093 if (isCopy != NULL) {
1094 *isCopy = JNI_TRUE;
1095 }
1096 return result;
1097}
1098
1099/*
1100 * Perform the array "release" operation, which may or may not copy data
1101 * back into the VM, and may or may not release the underlying storage.
1102 */
1103void ReleaseGuardedPACopy(JNIEnv* env, jarray java_array, void* dataBuf, int mode) {
1104 if (reinterpret_cast<uintptr_t>(dataBuf) == kNoCopyMagic) {
1105 return;
1106 }
1107
1108 ScopedJniThreadState ts(env);
1109 Array* a = Decode<Array*>(ts, java_array);
1110
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001111 GuardedCopy::Check(__FUNCTION__, dataBuf, true);
Elliott Hughesa2501992011-08-26 19:39:54 -07001112
1113 if (mode != JNI_ABORT) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001114 size_t len = GuardedCopy::FromData(dataBuf)->original_length;
Elliott Hughesbf86d042011-08-31 17:53:14 -07001115 memcpy(a->GetRawData(), dataBuf, len);
Elliott Hughesa2501992011-08-26 19:39:54 -07001116 }
1117 if (mode != JNI_COMMIT) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001118 GuardedCopy::Destroy(dataBuf);
Elliott Hughesa2501992011-08-26 19:39:54 -07001119 }
1120}
1121
1122/*
1123 * ===========================================================================
1124 * JNI functions
1125 * ===========================================================================
1126 */
1127
1128class CheckJNI {
1129 public:
1130 static jint GetVersion(JNIEnv* env) {
1131 CHECK_JNI_ENTRY(kFlag_Default, "E", env);
1132 return CHECK_JNI_EXIT("I", baseEnv(env)->GetVersion(env));
1133 }
1134
1135 static jclass DefineClass(JNIEnv* env, const char* name, jobject loader, const jbyte* buf, jsize bufLen) {
1136 CHECK_JNI_ENTRY(kFlag_Default, "EuLpz", env, name, loader, buf, bufLen);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001137 sc.CheckClassName(name);
Elliott Hughesa2501992011-08-26 19:39:54 -07001138 return CHECK_JNI_EXIT("c", baseEnv(env)->DefineClass(env, name, loader, buf, bufLen));
1139 }
1140
1141 static jclass FindClass(JNIEnv* env, const char* name) {
1142 CHECK_JNI_ENTRY(kFlag_Default, "Eu", env, name);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001143 sc.CheckClassName(name);
Elliott Hughesa2501992011-08-26 19:39:54 -07001144 return CHECK_JNI_EXIT("c", baseEnv(env)->FindClass(env, name));
1145 }
1146
1147 static jclass GetSuperclass(JNIEnv* env, jclass clazz) {
1148 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1149 return CHECK_JNI_EXIT("c", baseEnv(env)->GetSuperclass(env, clazz));
1150 }
1151
1152 static jboolean IsAssignableFrom(JNIEnv* env, jclass clazz1, jclass clazz2) {
1153 CHECK_JNI_ENTRY(kFlag_Default, "Ecc", env, clazz1, clazz2);
1154 return CHECK_JNI_EXIT("b", baseEnv(env)->IsAssignableFrom(env, clazz1, clazz2));
1155 }
1156
1157 static jmethodID FromReflectedMethod(JNIEnv* env, jobject method) {
1158 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, method);
1159 // TODO: check that 'field' is a java.lang.reflect.Method.
1160 return CHECK_JNI_EXIT("m", baseEnv(env)->FromReflectedMethod(env, method));
1161 }
1162
1163 static jfieldID FromReflectedField(JNIEnv* env, jobject field) {
1164 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, field);
1165 // TODO: check that 'field' is a java.lang.reflect.Field.
1166 return CHECK_JNI_EXIT("f", baseEnv(env)->FromReflectedField(env, field));
1167 }
1168
1169 static jobject ToReflectedMethod(JNIEnv* env, jclass cls, jmethodID mid, jboolean isStatic) {
1170 CHECK_JNI_ENTRY(kFlag_Default, "Ecmb", env, cls, mid, isStatic);
1171 return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedMethod(env, cls, mid, isStatic));
1172 }
1173
1174 static jobject ToReflectedField(JNIEnv* env, jclass cls, jfieldID fid, jboolean isStatic) {
1175 CHECK_JNI_ENTRY(kFlag_Default, "Ecfb", env, cls, fid, isStatic);
1176 return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedField(env, cls, fid, isStatic));
1177 }
1178
1179 static jint Throw(JNIEnv* env, jthrowable obj) {
1180 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1181 // TODO: check that 'obj' is a java.lang.Throwable.
1182 return CHECK_JNI_EXIT("I", baseEnv(env)->Throw(env, obj));
1183 }
1184
1185 static jint ThrowNew(JNIEnv* env, jclass clazz, const char* message) {
1186 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Ecu", env, clazz, message);
1187 return CHECK_JNI_EXIT("I", baseEnv(env)->ThrowNew(env, clazz, message));
1188 }
1189
1190 static jthrowable ExceptionOccurred(JNIEnv* env) {
1191 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1192 return CHECK_JNI_EXIT("L", baseEnv(env)->ExceptionOccurred(env));
1193 }
1194
1195 static void ExceptionDescribe(JNIEnv* env) {
1196 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1197 baseEnv(env)->ExceptionDescribe(env);
1198 CHECK_JNI_EXIT_VOID();
1199 }
1200
1201 static void ExceptionClear(JNIEnv* env) {
1202 CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1203 baseEnv(env)->ExceptionClear(env);
1204 CHECK_JNI_EXIT_VOID();
1205 }
1206
1207 static void FatalError(JNIEnv* env, const char* msg) {
1208 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, msg);
1209 baseEnv(env)->FatalError(env, msg);
1210 CHECK_JNI_EXIT_VOID();
1211 }
1212
1213 static jint PushLocalFrame(JNIEnv* env, jint capacity) {
1214 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EI", env, capacity);
1215 return CHECK_JNI_EXIT("I", baseEnv(env)->PushLocalFrame(env, capacity));
1216 }
1217
1218 static jobject PopLocalFrame(JNIEnv* env, jobject res) {
1219 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, res);
1220 return CHECK_JNI_EXIT("L", baseEnv(env)->PopLocalFrame(env, res));
1221 }
1222
1223 static jobject NewGlobalRef(JNIEnv* env, jobject obj) {
1224 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1225 return CHECK_JNI_EXIT("L", baseEnv(env)->NewGlobalRef(env, obj));
1226 }
1227
1228 static jobject NewLocalRef(JNIEnv* env, jobject ref) {
1229 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, ref);
1230 return CHECK_JNI_EXIT("L", baseEnv(env)->NewLocalRef(env, ref));
1231 }
1232
1233 static void DeleteGlobalRef(JNIEnv* env, jobject globalRef) {
1234 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, globalRef);
1235 if (globalRef != NULL && GetIndirectRefKind(globalRef) != kGlobal) {
1236 LOG(ERROR) << "JNI ERROR: DeleteGlobalRef on " << GetIndirectRefKind(globalRef) << ": " << globalRef;
1237 JniAbort(__FUNCTION__);
1238 } else {
1239 baseEnv(env)->DeleteGlobalRef(env, globalRef);
1240 CHECK_JNI_EXIT_VOID();
1241 }
1242 }
1243
1244 static void DeleteWeakGlobalRef(JNIEnv* env, jweak weakGlobalRef) {
1245 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, weakGlobalRef);
1246 if (weakGlobalRef != NULL && GetIndirectRefKind(weakGlobalRef) != kWeakGlobal) {
1247 LOG(ERROR) << "JNI ERROR: DeleteWeakGlobalRef on " << GetIndirectRefKind(weakGlobalRef) << ": " << weakGlobalRef;
1248 JniAbort(__FUNCTION__);
1249 } else {
1250 baseEnv(env)->DeleteWeakGlobalRef(env, weakGlobalRef);
1251 CHECK_JNI_EXIT_VOID();
1252 }
1253 }
1254
1255 static void DeleteLocalRef(JNIEnv* env, jobject localRef) {
1256 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, localRef);
1257 if (localRef != NULL && GetIndirectRefKind(localRef) != kLocal) {
1258 LOG(ERROR) << "JNI ERROR: DeleteLocalRef on " << GetIndirectRefKind(localRef) << ": " << localRef;
1259 JniAbort(__FUNCTION__);
1260 } else {
1261 baseEnv(env)->DeleteLocalRef(env, localRef);
1262 CHECK_JNI_EXIT_VOID();
1263 }
1264 }
1265
1266 static jint EnsureLocalCapacity(JNIEnv *env, jint capacity) {
1267 CHECK_JNI_ENTRY(kFlag_Default, "EI", env, capacity);
1268 return CHECK_JNI_EXIT("I", baseEnv(env)->EnsureLocalCapacity(env, capacity));
1269 }
1270
1271 static jboolean IsSameObject(JNIEnv* env, jobject ref1, jobject ref2) {
1272 CHECK_JNI_ENTRY(kFlag_Default, "ELL", env, ref1, ref2);
1273 return CHECK_JNI_EXIT("b", baseEnv(env)->IsSameObject(env, ref1, ref2));
1274 }
1275
1276 static jobject AllocObject(JNIEnv* env, jclass clazz) {
1277 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1278 return CHECK_JNI_EXIT("L", baseEnv(env)->AllocObject(env, clazz));
1279 }
1280
1281 static jobject NewObject(JNIEnv* env, jclass clazz, jmethodID mid, ...) {
1282 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1283 va_list args;
1284 va_start(args, mid);
1285 jobject result = baseEnv(env)->NewObjectV(env, clazz, mid, args);
1286 va_end(args);
1287 return CHECK_JNI_EXIT("L", result);
1288 }
1289
1290 static jobject NewObjectV(JNIEnv* env, jclass clazz, jmethodID mid, va_list args) {
1291 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1292 return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectV(env, clazz, mid, args));
1293 }
1294
1295 static jobject NewObjectA(JNIEnv* env, jclass clazz, jmethodID mid, jvalue* args) {
1296 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid);
1297 return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectA(env, clazz, mid, args));
1298 }
1299
1300 static jclass GetObjectClass(JNIEnv* env, jobject obj) {
1301 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1302 return CHECK_JNI_EXIT("c", baseEnv(env)->GetObjectClass(env, obj));
1303 }
1304
1305 static jboolean IsInstanceOf(JNIEnv* env, jobject obj, jclass clazz) {
1306 CHECK_JNI_ENTRY(kFlag_Default, "ELc", env, obj, clazz);
1307 return CHECK_JNI_EXIT("b", baseEnv(env)->IsInstanceOf(env, obj, clazz));
1308 }
1309
1310 static jmethodID GetMethodID(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("m", baseEnv(env)->GetMethodID(env, clazz, name, sig));
1313 }
1314
1315 static jfieldID GetFieldID(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("f", baseEnv(env)->GetFieldID(env, clazz, name, sig));
1318 }
1319
1320 static jmethodID GetStaticMethodID(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("m", baseEnv(env)->GetStaticMethodID(env, clazz, name, sig));
1323 }
1324
1325 static jfieldID GetStaticFieldID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1326 CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1327 return CHECK_JNI_EXIT("f", baseEnv(env)->GetStaticFieldID(env, clazz, name, sig));
1328 }
1329
1330#define FIELD_ACCESSORS(_ctype, _jname, _type) \
1331 static _ctype GetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fid) { \
1332 CHECK_JNI_ENTRY(kFlag_Default, "Ecf", env, clazz, fid); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001333 sc.CheckStaticFieldID(clazz, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001334 return CHECK_JNI_EXIT(_type, baseEnv(env)->GetStatic##_jname##Field(env, clazz, fid)); \
1335 } \
1336 static _ctype Get##_jname##Field(JNIEnv* env, jobject obj, jfieldID fid) { \
1337 CHECK_JNI_ENTRY(kFlag_Default, "ELf", env, obj, fid); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001338 sc.CheckInstanceFieldID(obj, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001339 return CHECK_JNI_EXIT(_type, baseEnv(env)->Get##_jname##Field(env, obj, fid)); \
1340 } \
1341 static void SetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fid, _ctype value) { \
1342 CHECK_JNI_ENTRY(kFlag_Default, "Ecf" _type, env, clazz, fid, value); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001343 sc.CheckStaticFieldID(clazz, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001344 /* "value" arg only used when type == ref */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001345 sc.CheckFieldType((jobject)(uint32_t)value, fid, _type[0], true); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001346 baseEnv(env)->SetStatic##_jname##Field(env, clazz, fid, value); \
1347 CHECK_JNI_EXIT_VOID(); \
1348 } \
1349 static void Set##_jname##Field(JNIEnv* env, jobject obj, jfieldID fid, _ctype value) { \
1350 CHECK_JNI_ENTRY(kFlag_Default, "ELf" _type, env, obj, fid, value); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001351 sc.CheckInstanceFieldID(obj, fid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001352 /* "value" arg only used when type == ref */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001353 sc.CheckFieldType((jobject)(uint32_t) value, fid, _type[0], false); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001354 baseEnv(env)->Set##_jname##Field(env, obj, fid, value); \
1355 CHECK_JNI_EXIT_VOID(); \
1356 }
1357
1358FIELD_ACCESSORS(jobject, Object, "L");
1359FIELD_ACCESSORS(jboolean, Boolean, "Z");
1360FIELD_ACCESSORS(jbyte, Byte, "B");
1361FIELD_ACCESSORS(jchar, Char, "C");
1362FIELD_ACCESSORS(jshort, Short, "S");
1363FIELD_ACCESSORS(jint, Int, "I");
1364FIELD_ACCESSORS(jlong, Long, "J");
1365FIELD_ACCESSORS(jfloat, Float, "F");
1366FIELD_ACCESSORS(jdouble, Double, "D");
1367
1368#define CALL(_ctype, _jname, _retdecl, _retasgn, _retok, _retsig) \
1369 /* Virtual... */ \
1370 static _ctype Call##_jname##Method(JNIEnv* env, jobject obj, \
1371 jmethodID mid, ...) \
1372 { \
1373 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001374 sc.CheckSig(mid, _retsig, false); \
1375 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001376 _retdecl; \
1377 va_list args; \
1378 va_start(args, mid); \
1379 _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, mid, args); \
1380 va_end(args); \
1381 _retok; \
1382 } \
1383 static _ctype Call##_jname##MethodV(JNIEnv* env, jobject obj, \
1384 jmethodID mid, va_list args) \
1385 { \
1386 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001387 sc.CheckSig(mid, _retsig, false); \
1388 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001389 _retdecl; \
1390 _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, mid, args); \
1391 _retok; \
1392 } \
1393 static _ctype Call##_jname##MethodA(JNIEnv* env, jobject obj, \
1394 jmethodID mid, jvalue* args) \
1395 { \
1396 CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001397 sc.CheckSig(mid, _retsig, false); \
1398 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001399 _retdecl; \
1400 _retasgn baseEnv(env)->Call##_jname##MethodA(env, obj, mid, args); \
1401 _retok; \
1402 } \
1403 /* Non-virtual... */ \
1404 static _ctype CallNonvirtual##_jname##Method(JNIEnv* env, \
1405 jobject obj, jclass clazz, jmethodID mid, ...) \
1406 { \
1407 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001408 sc.CheckSig(mid, _retsig, false); \
1409 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001410 _retdecl; \
1411 va_list args; \
1412 va_start(args, mid); \
1413 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, mid, args); \
1414 va_end(args); \
1415 _retok; \
1416 } \
1417 static _ctype CallNonvirtual##_jname##MethodV(JNIEnv* env, \
1418 jobject obj, jclass clazz, jmethodID mid, va_list args) \
1419 { \
1420 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001421 sc.CheckSig(mid, _retsig, false); \
1422 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001423 _retdecl; \
1424 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, mid, args); \
1425 _retok; \
1426 } \
1427 static _ctype CallNonvirtual##_jname##MethodA(JNIEnv* env, \
1428 jobject obj, jclass clazz, jmethodID mid, jvalue* args) \
1429 { \
1430 CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001431 sc.CheckSig(mid, _retsig, false); \
1432 sc.CheckVirtualMethod(obj, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001433 _retdecl; \
1434 _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodA(env, obj, clazz, mid, args); \
1435 _retok; \
1436 } \
1437 /* Static... */ \
1438 static _ctype CallStatic##_jname##Method(JNIEnv* env, \
1439 jclass clazz, jmethodID mid, ...) \
1440 { \
1441 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001442 sc.CheckSig(mid, _retsig, true); \
1443 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001444 _retdecl; \
1445 va_list args; \
1446 va_start(args, mid); \
1447 _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, mid, args); \
1448 va_end(args); \
1449 _retok; \
1450 } \
1451 static _ctype CallStatic##_jname##MethodV(JNIEnv* env, \
1452 jclass clazz, jmethodID mid, va_list args) \
1453 { \
1454 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001455 sc.CheckSig(mid, _retsig, true); \
1456 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001457 _retdecl; \
1458 _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, mid, args); \
1459 _retok; \
1460 } \
1461 static _ctype CallStatic##_jname##MethodA(JNIEnv* env, \
1462 jclass clazz, jmethodID mid, jvalue* args) \
1463 { \
1464 CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, mid); /* TODO: args! */ \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001465 sc.CheckSig(mid, _retsig, true); \
1466 sc.CheckStaticMethod(clazz, mid); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001467 _retdecl; \
1468 _retasgn baseEnv(env)->CallStatic##_jname##MethodA(env, clazz, mid, args); \
1469 _retok; \
1470 }
1471
1472#define NON_VOID_RETURN(_retsig, _ctype) return CHECK_JNI_EXIT(_retsig, (_ctype) result)
1473#define VOID_RETURN CHECK_JNI_EXIT_VOID()
1474
1475CALL(jobject, Object, Object* result, result=(Object*), NON_VOID_RETURN("L", jobject), "L");
1476CALL(jboolean, Boolean, jboolean result, result=, NON_VOID_RETURN("Z", jboolean), "Z");
1477CALL(jbyte, Byte, jbyte result, result=, NON_VOID_RETURN("B", jbyte), "B");
1478CALL(jchar, Char, jchar result, result=, NON_VOID_RETURN("C", jchar), "C");
1479CALL(jshort, Short, jshort result, result=, NON_VOID_RETURN("S", jshort), "S");
1480CALL(jint, Int, jint result, result=, NON_VOID_RETURN("I", jint), "I");
1481CALL(jlong, Long, jlong result, result=, NON_VOID_RETURN("J", jlong), "J");
1482CALL(jfloat, Float, jfloat result, result=, NON_VOID_RETURN("F", jfloat), "F");
1483CALL(jdouble, Double, jdouble result, result=, NON_VOID_RETURN("D", jdouble), "D");
1484CALL(void, Void, , , VOID_RETURN, "V");
1485
1486 static jstring NewString(JNIEnv* env, const jchar* unicodeChars, jsize len) {
1487 CHECK_JNI_ENTRY(kFlag_Default, "Epz", env, unicodeChars, len);
1488 return CHECK_JNI_EXIT("s", baseEnv(env)->NewString(env, unicodeChars, len));
1489 }
1490
1491 static jsize GetStringLength(JNIEnv* env, jstring string) {
1492 CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1493 return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringLength(env, string));
1494 }
1495
1496 static const jchar* GetStringChars(JNIEnv* env, jstring java_string, jboolean* isCopy) {
1497 CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, java_string, isCopy);
1498 const jchar* result = baseEnv(env)->GetStringChars(env, java_string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001499 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001500 ScopedJniThreadState ts(env);
1501 String* s = Decode<String*>(ts, java_string);
1502 int byteCount = s->GetLength() * 2;
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001503 result = (const jchar*) GuardedCopy::Create(result, byteCount, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001504 if (isCopy != NULL) {
1505 *isCopy = JNI_TRUE;
1506 }
1507 }
1508 return CHECK_JNI_EXIT("p", result);
1509 }
1510
1511 static void ReleaseStringChars(JNIEnv* env, jstring string, const jchar* chars) {
1512 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Esp", env, string, chars);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001513 sc.CheckNonNull(chars);
1514 if (sc.ForceCopy()) {
1515 GuardedCopy::Check(__FUNCTION__, chars, false);
1516 chars = (const jchar*) GuardedCopy::Destroy((jchar*)chars);
Elliott Hughesa2501992011-08-26 19:39:54 -07001517 }
1518 baseEnv(env)->ReleaseStringChars(env, string, chars);
1519 CHECK_JNI_EXIT_VOID();
1520 }
1521
1522 static jstring NewStringUTF(JNIEnv* env, const char* bytes) {
1523 CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, bytes); // TODO: show pointer and truncate string.
1524 return CHECK_JNI_EXIT("s", baseEnv(env)->NewStringUTF(env, bytes));
1525 }
1526
1527 static jsize GetStringUTFLength(JNIEnv* env, jstring string) {
1528 CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1529 return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringUTFLength(env, string));
1530 }
1531
1532 static const char* GetStringUTFChars(JNIEnv* env, jstring string, jboolean* isCopy) {
1533 CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
1534 const char* result = baseEnv(env)->GetStringUTFChars(env, string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001535 if (sc.ForceCopy() && result != NULL) {
1536 result = (const char*) GuardedCopy::Create(result, strlen(result) + 1, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001537 if (isCopy != NULL) {
1538 *isCopy = JNI_TRUE;
1539 }
1540 }
1541 return CHECK_JNI_EXIT("u", result); // TODO: show pointer and truncate string.
1542 }
1543
1544 static void ReleaseStringUTFChars(JNIEnv* env, jstring string, const char* utf) {
1545 CHECK_JNI_ENTRY(kFlag_ExcepOkay | kFlag_Release, "Esu", env, string, utf); // TODO: show pointer and truncate string.
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001546 if (sc.ForceCopy()) {
1547 GuardedCopy::Check(__FUNCTION__, utf, false);
1548 utf = (const char*) GuardedCopy::Destroy((char*)utf);
Elliott Hughesa2501992011-08-26 19:39:54 -07001549 }
1550 baseEnv(env)->ReleaseStringUTFChars(env, string, utf);
1551 CHECK_JNI_EXIT_VOID();
1552 }
1553
1554 static jsize GetArrayLength(JNIEnv* env, jarray array) {
1555 CHECK_JNI_ENTRY(kFlag_CritOkay, "Ea", env, array);
1556 return CHECK_JNI_EXIT("I", baseEnv(env)->GetArrayLength(env, array));
1557 }
1558
1559 static jobjectArray NewObjectArray(JNIEnv* env, jsize length, jclass elementClass, jobject initialElement) {
1560 CHECK_JNI_ENTRY(kFlag_Default, "EzcL", env, length, elementClass, initialElement);
1561 return CHECK_JNI_EXIT("a", baseEnv(env)->NewObjectArray(env, length, elementClass, initialElement));
1562 }
1563
1564 static jobject GetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index) {
1565 CHECK_JNI_ENTRY(kFlag_Default, "EaI", env, array, index);
1566 return CHECK_JNI_EXIT("L", baseEnv(env)->GetObjectArrayElement(env, array, index));
1567 }
1568
1569 static void SetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, jobject value) {
1570 CHECK_JNI_ENTRY(kFlag_Default, "EaIL", env, array, index, value);
1571 baseEnv(env)->SetObjectArrayElement(env, array, index, value);
1572 CHECK_JNI_EXIT_VOID();
1573 }
1574
1575#define NEW_PRIMITIVE_ARRAY(_artype, _jname) \
1576 static _artype New##_jname##Array(JNIEnv* env, jsize length) { \
1577 CHECK_JNI_ENTRY(kFlag_Default, "Ez", env, length); \
1578 return CHECK_JNI_EXIT("a", baseEnv(env)->New##_jname##Array(env, length)); \
1579 }
1580NEW_PRIMITIVE_ARRAY(jbooleanArray, Boolean);
1581NEW_PRIMITIVE_ARRAY(jbyteArray, Byte);
1582NEW_PRIMITIVE_ARRAY(jcharArray, Char);
1583NEW_PRIMITIVE_ARRAY(jshortArray, Short);
1584NEW_PRIMITIVE_ARRAY(jintArray, Int);
1585NEW_PRIMITIVE_ARRAY(jlongArray, Long);
1586NEW_PRIMITIVE_ARRAY(jfloatArray, Float);
1587NEW_PRIMITIVE_ARRAY(jdoubleArray, Double);
1588
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001589struct ForceCopyGetChecker {
Elliott Hughesa2501992011-08-26 19:39:54 -07001590public:
1591 ForceCopyGetChecker(ScopedCheck& sc, jboolean* isCopy) {
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001592 force_copy = sc.ForceCopy();
1593 no_copy = 0;
1594 if (force_copy && isCopy != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001595 /* capture this before the base call tramples on it */
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001596 no_copy = *(uint32_t*) isCopy;
Elliott Hughesa2501992011-08-26 19:39:54 -07001597 }
1598 }
1599
1600 template<typename ResultT>
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001601 ResultT Check(JNIEnv* env, jarray array, jboolean* isCopy, ResultT result) {
1602 if (force_copy && result != NULL) {
1603 if (no_copy != kNoCopyMagic) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001604 result = reinterpret_cast<ResultT>(CreateGuardedPACopy(env, array, isCopy));
1605 }
1606 }
1607 return result;
1608 }
1609
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001610 uint32_t no_copy;
1611 bool force_copy;
Elliott Hughesa2501992011-08-26 19:39:54 -07001612};
1613
1614#define GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1615 static _ctype* Get##_jname##ArrayElements(JNIEnv* env, _ctype##Array array, jboolean* isCopy) { \
1616 CHECK_JNI_ENTRY(kFlag_Default, "Eap", env, array, isCopy); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001617 _ctype* result = ForceCopyGetChecker(sc, isCopy).Check(env, array, isCopy, baseEnv(env)->Get##_jname##ArrayElements(env, array, isCopy)); \
Elliott Hughesa2501992011-08-26 19:39:54 -07001618 return CHECK_JNI_EXIT("p", result); \
1619 }
1620
1621#define RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1622 static void Release##_jname##ArrayElements(JNIEnv* env, _ctype##Array array, _ctype* elems, jint mode) { \
1623 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Eapr", env, array, elems, mode); \
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001624 sc.CheckNonNull(elems); \
1625 if (sc.ForceCopy()) { \
Elliott Hughesa2501992011-08-26 19:39:54 -07001626 ReleaseGuardedPACopy(env, array, elems, mode); \
1627 } \
1628 baseEnv(env)->Release##_jname##ArrayElements(env, array, elems, mode); \
1629 CHECK_JNI_EXIT_VOID(); \
1630 }
1631
1632#define GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1633 static void Get##_jname##ArrayRegion(JNIEnv* env, _ctype##Array array, jsize start, jsize len, _ctype* buf) { \
1634 CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1635 baseEnv(env)->Get##_jname##ArrayRegion(env, array, start, len, buf); \
1636 CHECK_JNI_EXIT_VOID(); \
1637 }
1638
1639#define SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1640 static void Set##_jname##ArrayRegion(JNIEnv* env, _ctype##Array array, jsize start, jsize len, const _ctype* buf) { \
1641 CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1642 baseEnv(env)->Set##_jname##ArrayRegion(env, array, start, len, buf); \
1643 CHECK_JNI_EXIT_VOID(); \
1644 }
1645
1646#define PRIMITIVE_ARRAY_FUNCTIONS(_ctype, _jname, _typechar) \
1647 GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1648 RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1649 GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname); \
1650 SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname);
1651
1652/* TODO: verify primitive array type matches call type */
1653PRIMITIVE_ARRAY_FUNCTIONS(jboolean, Boolean, 'Z');
1654PRIMITIVE_ARRAY_FUNCTIONS(jbyte, Byte, 'B');
1655PRIMITIVE_ARRAY_FUNCTIONS(jchar, Char, 'C');
1656PRIMITIVE_ARRAY_FUNCTIONS(jshort, Short, 'S');
1657PRIMITIVE_ARRAY_FUNCTIONS(jint, Int, 'I');
1658PRIMITIVE_ARRAY_FUNCTIONS(jlong, Long, 'J');
1659PRIMITIVE_ARRAY_FUNCTIONS(jfloat, Float, 'F');
1660PRIMITIVE_ARRAY_FUNCTIONS(jdouble, Double, 'D');
1661
1662 static jint RegisterNatives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
1663 CHECK_JNI_ENTRY(kFlag_Default, "EcpI", env, clazz, methods, nMethods);
1664 return CHECK_JNI_EXIT("I", baseEnv(env)->RegisterNatives(env, clazz, methods, nMethods));
1665 }
1666
1667 static jint UnregisterNatives(JNIEnv* env, jclass clazz) {
1668 CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1669 return CHECK_JNI_EXIT("I", baseEnv(env)->UnregisterNatives(env, clazz));
1670 }
1671
1672 static jint MonitorEnter(JNIEnv* env, jobject obj) {
1673 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1674 return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorEnter(env, obj));
1675 }
1676
1677 static jint MonitorExit(JNIEnv* env, jobject obj) {
1678 CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
1679 return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorExit(env, obj));
1680 }
1681
1682 static jint GetJavaVM(JNIEnv *env, JavaVM **vm) {
1683 CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, vm);
1684 return CHECK_JNI_EXIT("I", baseEnv(env)->GetJavaVM(env, vm));
1685 }
1686
1687 static void GetStringRegion(JNIEnv* env, jstring str, jsize start, jsize len, jchar* buf) {
1688 CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1689 baseEnv(env)->GetStringRegion(env, str, start, len, buf);
1690 CHECK_JNI_EXIT_VOID();
1691 }
1692
1693 static void GetStringUTFRegion(JNIEnv* env, jstring str, jsize start, jsize len, char* buf) {
1694 CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1695 baseEnv(env)->GetStringUTFRegion(env, str, start, len, buf);
1696 CHECK_JNI_EXIT_VOID();
1697 }
1698
1699 static void* GetPrimitiveArrayCritical(JNIEnv* env, jarray array, jboolean* isCopy) {
1700 CHECK_JNI_ENTRY(kFlag_CritGet, "Eap", env, array, isCopy);
1701 void* result = baseEnv(env)->GetPrimitiveArrayCritical(env, array, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001702 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001703 result = CreateGuardedPACopy(env, array, isCopy);
1704 }
1705 return CHECK_JNI_EXIT("p", result);
1706 }
1707
1708 static void ReleasePrimitiveArrayCritical(JNIEnv* env, jarray array, void* carray, jint mode) {
1709 CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Eapr", env, array, carray, mode);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001710 sc.CheckNonNull(carray);
1711 if (sc.ForceCopy()) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001712 ReleaseGuardedPACopy(env, array, carray, mode);
1713 }
1714 baseEnv(env)->ReleasePrimitiveArrayCritical(env, array, carray, mode);
1715 CHECK_JNI_EXIT_VOID();
1716 }
1717
1718 static const jchar* GetStringCritical(JNIEnv* env, jstring java_string, jboolean* isCopy) {
1719 CHECK_JNI_ENTRY(kFlag_CritGet, "Esp", env, java_string, isCopy);
1720 const jchar* result = baseEnv(env)->GetStringCritical(env, java_string, isCopy);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001721 if (sc.ForceCopy() && result != NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001722 ScopedJniThreadState ts(env);
1723 String* s = Decode<String*>(ts, java_string);
1724 int byteCount = s->GetLength() * 2;
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001725 result = (const jchar*) GuardedCopy::Create(result, byteCount, false);
Elliott Hughesa2501992011-08-26 19:39:54 -07001726 if (isCopy != NULL) {
1727 *isCopy = JNI_TRUE;
1728 }
1729 }
1730 return CHECK_JNI_EXIT("p", result);
1731 }
1732
1733 static void ReleaseStringCritical(JNIEnv* env, jstring string, const jchar* carray) {
1734 CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Esp", env, string, carray);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07001735 sc.CheckNonNull(carray);
1736 if (sc.ForceCopy()) {
1737 GuardedCopy::Check(__FUNCTION__, carray, false);
1738 carray = (const jchar*) GuardedCopy::Destroy((jchar*)carray);
Elliott Hughesa2501992011-08-26 19:39:54 -07001739 }
1740 baseEnv(env)->ReleaseStringCritical(env, string, carray);
1741 CHECK_JNI_EXIT_VOID();
1742 }
1743
1744 static jweak NewWeakGlobalRef(JNIEnv* env, jobject obj) {
1745 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1746 return CHECK_JNI_EXIT("L", baseEnv(env)->NewWeakGlobalRef(env, obj));
1747 }
1748
1749 static jboolean ExceptionCheck(JNIEnv* env) {
1750 CHECK_JNI_ENTRY(kFlag_CritOkay | kFlag_ExcepOkay, "E", env);
1751 return CHECK_JNI_EXIT("b", baseEnv(env)->ExceptionCheck(env));
1752 }
1753
1754 static jobjectRefType GetObjectRefType(JNIEnv* env, jobject obj) {
1755 // Note: we use "Ep" rather than "EL" because this is the one JNI function
1756 // that it's okay to pass an invalid reference to.
1757 CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, obj);
1758 // TODO: proper decoding of jobjectRefType!
1759 return CHECK_JNI_EXIT("I", baseEnv(env)->GetObjectRefType(env, obj));
1760 }
1761
1762 static jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
1763 CHECK_JNI_ENTRY(kFlag_Default, "EpJ", env, address, capacity);
1764 if (address == NULL) {
1765 LOG(ERROR) << "JNI ERROR: non-nullable address is NULL";
1766 JniAbort(__FUNCTION__);
1767 }
1768 if (capacity <= 0) {
1769 LOG(ERROR) << "JNI ERROR: capacity must be greater than 0: " << capacity;
1770 JniAbort(__FUNCTION__);
1771 }
1772 return CHECK_JNI_EXIT("L", baseEnv(env)->NewDirectByteBuffer(env, address, capacity));
1773 }
1774
1775 static void* GetDirectBufferAddress(JNIEnv* env, jobject buf) {
1776 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1777 // TODO: check that 'buf' is a java.nio.Buffer.
1778 return CHECK_JNI_EXIT("p", baseEnv(env)->GetDirectBufferAddress(env, buf));
1779 }
1780
1781 static jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf) {
1782 CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1783 // TODO: check that 'buf' is a java.nio.Buffer.
1784 return CHECK_JNI_EXIT("J", baseEnv(env)->GetDirectBufferCapacity(env, buf));
1785 }
1786
1787 private:
1788 static inline const JNINativeInterface* baseEnv(JNIEnv* env) {
1789 return reinterpret_cast<JNIEnvExt*>(env)->unchecked_functions;
1790 }
1791};
1792
1793const JNINativeInterface gCheckNativeInterface = {
1794 NULL, // reserved0.
1795 NULL, // reserved1.
1796 NULL, // reserved2.
1797 NULL, // reserved3.
1798 CheckJNI::GetVersion,
1799 CheckJNI::DefineClass,
1800 CheckJNI::FindClass,
1801 CheckJNI::FromReflectedMethod,
1802 CheckJNI::FromReflectedField,
1803 CheckJNI::ToReflectedMethod,
1804 CheckJNI::GetSuperclass,
1805 CheckJNI::IsAssignableFrom,
1806 CheckJNI::ToReflectedField,
1807 CheckJNI::Throw,
1808 CheckJNI::ThrowNew,
1809 CheckJNI::ExceptionOccurred,
1810 CheckJNI::ExceptionDescribe,
1811 CheckJNI::ExceptionClear,
1812 CheckJNI::FatalError,
1813 CheckJNI::PushLocalFrame,
1814 CheckJNI::PopLocalFrame,
1815 CheckJNI::NewGlobalRef,
1816 CheckJNI::DeleteGlobalRef,
1817 CheckJNI::DeleteLocalRef,
1818 CheckJNI::IsSameObject,
1819 CheckJNI::NewLocalRef,
1820 CheckJNI::EnsureLocalCapacity,
1821 CheckJNI::AllocObject,
1822 CheckJNI::NewObject,
1823 CheckJNI::NewObjectV,
1824 CheckJNI::NewObjectA,
1825 CheckJNI::GetObjectClass,
1826 CheckJNI::IsInstanceOf,
1827 CheckJNI::GetMethodID,
1828 CheckJNI::CallObjectMethod,
1829 CheckJNI::CallObjectMethodV,
1830 CheckJNI::CallObjectMethodA,
1831 CheckJNI::CallBooleanMethod,
1832 CheckJNI::CallBooleanMethodV,
1833 CheckJNI::CallBooleanMethodA,
1834 CheckJNI::CallByteMethod,
1835 CheckJNI::CallByteMethodV,
1836 CheckJNI::CallByteMethodA,
1837 CheckJNI::CallCharMethod,
1838 CheckJNI::CallCharMethodV,
1839 CheckJNI::CallCharMethodA,
1840 CheckJNI::CallShortMethod,
1841 CheckJNI::CallShortMethodV,
1842 CheckJNI::CallShortMethodA,
1843 CheckJNI::CallIntMethod,
1844 CheckJNI::CallIntMethodV,
1845 CheckJNI::CallIntMethodA,
1846 CheckJNI::CallLongMethod,
1847 CheckJNI::CallLongMethodV,
1848 CheckJNI::CallLongMethodA,
1849 CheckJNI::CallFloatMethod,
1850 CheckJNI::CallFloatMethodV,
1851 CheckJNI::CallFloatMethodA,
1852 CheckJNI::CallDoubleMethod,
1853 CheckJNI::CallDoubleMethodV,
1854 CheckJNI::CallDoubleMethodA,
1855 CheckJNI::CallVoidMethod,
1856 CheckJNI::CallVoidMethodV,
1857 CheckJNI::CallVoidMethodA,
1858 CheckJNI::CallNonvirtualObjectMethod,
1859 CheckJNI::CallNonvirtualObjectMethodV,
1860 CheckJNI::CallNonvirtualObjectMethodA,
1861 CheckJNI::CallNonvirtualBooleanMethod,
1862 CheckJNI::CallNonvirtualBooleanMethodV,
1863 CheckJNI::CallNonvirtualBooleanMethodA,
1864 CheckJNI::CallNonvirtualByteMethod,
1865 CheckJNI::CallNonvirtualByteMethodV,
1866 CheckJNI::CallNonvirtualByteMethodA,
1867 CheckJNI::CallNonvirtualCharMethod,
1868 CheckJNI::CallNonvirtualCharMethodV,
1869 CheckJNI::CallNonvirtualCharMethodA,
1870 CheckJNI::CallNonvirtualShortMethod,
1871 CheckJNI::CallNonvirtualShortMethodV,
1872 CheckJNI::CallNonvirtualShortMethodA,
1873 CheckJNI::CallNonvirtualIntMethod,
1874 CheckJNI::CallNonvirtualIntMethodV,
1875 CheckJNI::CallNonvirtualIntMethodA,
1876 CheckJNI::CallNonvirtualLongMethod,
1877 CheckJNI::CallNonvirtualLongMethodV,
1878 CheckJNI::CallNonvirtualLongMethodA,
1879 CheckJNI::CallNonvirtualFloatMethod,
1880 CheckJNI::CallNonvirtualFloatMethodV,
1881 CheckJNI::CallNonvirtualFloatMethodA,
1882 CheckJNI::CallNonvirtualDoubleMethod,
1883 CheckJNI::CallNonvirtualDoubleMethodV,
1884 CheckJNI::CallNonvirtualDoubleMethodA,
1885 CheckJNI::CallNonvirtualVoidMethod,
1886 CheckJNI::CallNonvirtualVoidMethodV,
1887 CheckJNI::CallNonvirtualVoidMethodA,
1888 CheckJNI::GetFieldID,
1889 CheckJNI::GetObjectField,
1890 CheckJNI::GetBooleanField,
1891 CheckJNI::GetByteField,
1892 CheckJNI::GetCharField,
1893 CheckJNI::GetShortField,
1894 CheckJNI::GetIntField,
1895 CheckJNI::GetLongField,
1896 CheckJNI::GetFloatField,
1897 CheckJNI::GetDoubleField,
1898 CheckJNI::SetObjectField,
1899 CheckJNI::SetBooleanField,
1900 CheckJNI::SetByteField,
1901 CheckJNI::SetCharField,
1902 CheckJNI::SetShortField,
1903 CheckJNI::SetIntField,
1904 CheckJNI::SetLongField,
1905 CheckJNI::SetFloatField,
1906 CheckJNI::SetDoubleField,
1907 CheckJNI::GetStaticMethodID,
1908 CheckJNI::CallStaticObjectMethod,
1909 CheckJNI::CallStaticObjectMethodV,
1910 CheckJNI::CallStaticObjectMethodA,
1911 CheckJNI::CallStaticBooleanMethod,
1912 CheckJNI::CallStaticBooleanMethodV,
1913 CheckJNI::CallStaticBooleanMethodA,
1914 CheckJNI::CallStaticByteMethod,
1915 CheckJNI::CallStaticByteMethodV,
1916 CheckJNI::CallStaticByteMethodA,
1917 CheckJNI::CallStaticCharMethod,
1918 CheckJNI::CallStaticCharMethodV,
1919 CheckJNI::CallStaticCharMethodA,
1920 CheckJNI::CallStaticShortMethod,
1921 CheckJNI::CallStaticShortMethodV,
1922 CheckJNI::CallStaticShortMethodA,
1923 CheckJNI::CallStaticIntMethod,
1924 CheckJNI::CallStaticIntMethodV,
1925 CheckJNI::CallStaticIntMethodA,
1926 CheckJNI::CallStaticLongMethod,
1927 CheckJNI::CallStaticLongMethodV,
1928 CheckJNI::CallStaticLongMethodA,
1929 CheckJNI::CallStaticFloatMethod,
1930 CheckJNI::CallStaticFloatMethodV,
1931 CheckJNI::CallStaticFloatMethodA,
1932 CheckJNI::CallStaticDoubleMethod,
1933 CheckJNI::CallStaticDoubleMethodV,
1934 CheckJNI::CallStaticDoubleMethodA,
1935 CheckJNI::CallStaticVoidMethod,
1936 CheckJNI::CallStaticVoidMethodV,
1937 CheckJNI::CallStaticVoidMethodA,
1938 CheckJNI::GetStaticFieldID,
1939 CheckJNI::GetStaticObjectField,
1940 CheckJNI::GetStaticBooleanField,
1941 CheckJNI::GetStaticByteField,
1942 CheckJNI::GetStaticCharField,
1943 CheckJNI::GetStaticShortField,
1944 CheckJNI::GetStaticIntField,
1945 CheckJNI::GetStaticLongField,
1946 CheckJNI::GetStaticFloatField,
1947 CheckJNI::GetStaticDoubleField,
1948 CheckJNI::SetStaticObjectField,
1949 CheckJNI::SetStaticBooleanField,
1950 CheckJNI::SetStaticByteField,
1951 CheckJNI::SetStaticCharField,
1952 CheckJNI::SetStaticShortField,
1953 CheckJNI::SetStaticIntField,
1954 CheckJNI::SetStaticLongField,
1955 CheckJNI::SetStaticFloatField,
1956 CheckJNI::SetStaticDoubleField,
1957 CheckJNI::NewString,
1958 CheckJNI::GetStringLength,
1959 CheckJNI::GetStringChars,
1960 CheckJNI::ReleaseStringChars,
1961 CheckJNI::NewStringUTF,
1962 CheckJNI::GetStringUTFLength,
1963 CheckJNI::GetStringUTFChars,
1964 CheckJNI::ReleaseStringUTFChars,
1965 CheckJNI::GetArrayLength,
1966 CheckJNI::NewObjectArray,
1967 CheckJNI::GetObjectArrayElement,
1968 CheckJNI::SetObjectArrayElement,
1969 CheckJNI::NewBooleanArray,
1970 CheckJNI::NewByteArray,
1971 CheckJNI::NewCharArray,
1972 CheckJNI::NewShortArray,
1973 CheckJNI::NewIntArray,
1974 CheckJNI::NewLongArray,
1975 CheckJNI::NewFloatArray,
1976 CheckJNI::NewDoubleArray,
1977 CheckJNI::GetBooleanArrayElements,
1978 CheckJNI::GetByteArrayElements,
1979 CheckJNI::GetCharArrayElements,
1980 CheckJNI::GetShortArrayElements,
1981 CheckJNI::GetIntArrayElements,
1982 CheckJNI::GetLongArrayElements,
1983 CheckJNI::GetFloatArrayElements,
1984 CheckJNI::GetDoubleArrayElements,
1985 CheckJNI::ReleaseBooleanArrayElements,
1986 CheckJNI::ReleaseByteArrayElements,
1987 CheckJNI::ReleaseCharArrayElements,
1988 CheckJNI::ReleaseShortArrayElements,
1989 CheckJNI::ReleaseIntArrayElements,
1990 CheckJNI::ReleaseLongArrayElements,
1991 CheckJNI::ReleaseFloatArrayElements,
1992 CheckJNI::ReleaseDoubleArrayElements,
1993 CheckJNI::GetBooleanArrayRegion,
1994 CheckJNI::GetByteArrayRegion,
1995 CheckJNI::GetCharArrayRegion,
1996 CheckJNI::GetShortArrayRegion,
1997 CheckJNI::GetIntArrayRegion,
1998 CheckJNI::GetLongArrayRegion,
1999 CheckJNI::GetFloatArrayRegion,
2000 CheckJNI::GetDoubleArrayRegion,
2001 CheckJNI::SetBooleanArrayRegion,
2002 CheckJNI::SetByteArrayRegion,
2003 CheckJNI::SetCharArrayRegion,
2004 CheckJNI::SetShortArrayRegion,
2005 CheckJNI::SetIntArrayRegion,
2006 CheckJNI::SetLongArrayRegion,
2007 CheckJNI::SetFloatArrayRegion,
2008 CheckJNI::SetDoubleArrayRegion,
2009 CheckJNI::RegisterNatives,
2010 CheckJNI::UnregisterNatives,
2011 CheckJNI::MonitorEnter,
2012 CheckJNI::MonitorExit,
2013 CheckJNI::GetJavaVM,
2014 CheckJNI::GetStringRegion,
2015 CheckJNI::GetStringUTFRegion,
2016 CheckJNI::GetPrimitiveArrayCritical,
2017 CheckJNI::ReleasePrimitiveArrayCritical,
2018 CheckJNI::GetStringCritical,
2019 CheckJNI::ReleaseStringCritical,
2020 CheckJNI::NewWeakGlobalRef,
2021 CheckJNI::DeleteWeakGlobalRef,
2022 CheckJNI::ExceptionCheck,
2023 CheckJNI::NewDirectByteBuffer,
2024 CheckJNI::GetDirectBufferAddress,
2025 CheckJNI::GetDirectBufferCapacity,
2026 CheckJNI::GetObjectRefType,
2027};
2028
2029const JNINativeInterface* GetCheckJniNativeInterface() {
2030 return &gCheckNativeInterface;
2031}
2032
2033class CheckJII {
2034public:
2035 static jint DestroyJavaVM(JavaVM* vm) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002036 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002037 sc.Check(true, "v", vm);
2038 return CHECK_JNI_EXIT("I", BaseVm(vm)->DestroyJavaVM(vm));
Elliott Hughesa2501992011-08-26 19:39:54 -07002039 }
2040
2041 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002042 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002043 sc.Check(true, "vpp", vm, p_env, thr_args);
2044 return CHECK_JNI_EXIT("I", BaseVm(vm)->AttachCurrentThread(vm, p_env, thr_args));
Elliott Hughesa2501992011-08-26 19:39:54 -07002045 }
2046
2047 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002048 ScopedCheck sc(vm, false, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002049 sc.Check(true, "vpp", vm, p_env, thr_args);
2050 return CHECK_JNI_EXIT("I", BaseVm(vm)->AttachCurrentThreadAsDaemon(vm, p_env, thr_args));
Elliott Hughesa2501992011-08-26 19:39:54 -07002051 }
2052
2053 static jint DetachCurrentThread(JavaVM* vm) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002054 ScopedCheck sc(vm, true, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002055 sc.Check(true, "v", vm);
2056 return CHECK_JNI_EXIT("I", BaseVm(vm)->DetachCurrentThread(vm));
Elliott Hughesa2501992011-08-26 19:39:54 -07002057 }
2058
2059 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Elliott Hughesa0957642011-09-02 14:27:33 -07002060 ScopedCheck sc(vm, true, __FUNCTION__);
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002061 sc.Check(true, "v", vm);
2062 return CHECK_JNI_EXIT("I", BaseVm(vm)->GetEnv(vm, env, version));
Elliott Hughesa2501992011-08-26 19:39:54 -07002063 }
2064
2065 private:
Elliott Hughes32ae6e32011-09-27 10:46:50 -07002066 static inline const JNIInvokeInterface* BaseVm(JavaVM* vm) {
Elliott Hughesa2501992011-08-26 19:39:54 -07002067 return reinterpret_cast<JavaVMExt*>(vm)->unchecked_functions;
2068 }
2069};
2070
2071const JNIInvokeInterface gCheckInvokeInterface = {
2072 NULL, // reserved0
2073 NULL, // reserved1
2074 NULL, // reserved2
2075 CheckJII::DestroyJavaVM,
2076 CheckJII::AttachCurrentThread,
2077 CheckJII::DetachCurrentThread,
2078 CheckJII::GetEnv,
2079 CheckJII::AttachCurrentThreadAsDaemon
2080};
2081
2082const JNIInvokeInterface* GetCheckJniInvokeInterface() {
2083 return &gCheckInvokeInterface;
2084}
2085
2086} // namespace art