CheckJni.cpp revision 363e154170d0879ccebf4160f8d57433d40673a2
1/*
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/*
18 * Support for -Xcheck:jni (the "careful" version of the JNI interfaces).
19 *
20 * We want to verify types, make sure class and field IDs are valid, and
21 * ensure that JNI's semantic expectations are being met.  JNI seems to
22 * be relatively lax when it comes to requirements for permission checks,
23 * e.g. access to private methods is generally allowed from anywhere.
24 */
25
26#include "Dalvik.h"
27#include "JniInternal.h"
28
29#include <sys/mman.h>
30#include <zlib.h>
31
32/*
33 * Abort if we are configured to bail out on JNI warnings.
34 */
35static void abortMaybe() {
36    if (!gDvmJni.warnOnly) {
37        dvmDumpThread(dvmThreadSelf(), false);
38        dvmAbort();
39    }
40}
41
42/*
43 * ===========================================================================
44 *      JNI call bridge wrapper
45 * ===========================================================================
46 */
47
48/*
49 * Check the result of a native method call that returns an object reference.
50 *
51 * The primary goal here is to verify that native code is returning the
52 * correct type of object.  If it's declared to return a String but actually
53 * returns a byte array, things will fail in strange ways later on.
54 *
55 * This can be a fairly expensive operation, since we have to look up the
56 * return type class by name in method->clazz' class loader.  We take a
57 * shortcut here and allow the call to succeed if the descriptor strings
58 * match.  This will allow some false-positives when a class is redefined
59 * by a class loader, but that's rare enough that it doesn't seem worth
60 * testing for.
61 *
62 * At this point, pResult->l has already been converted to an object pointer.
63 */
64static void checkCallResultCommon(const u4* args, const JValue* pResult,
65        const Method* method, Thread* self)
66{
67    assert(pResult->l != NULL);
68    const Object* resultObj = (const Object*) pResult->l;
69
70    if (resultObj == kInvalidIndirectRefObject) {
71        LOGW("JNI WARNING: invalid reference returned from native code");
72        const Method* method = dvmGetCurrentJNIMethod();
73        char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
74        LOGW("             in %s.%s:%s", method->clazz->descriptor, method->name, desc);
75        free(desc);
76        abortMaybe();
77        return;
78    }
79
80    ClassObject* objClazz = resultObj->clazz;
81
82    /*
83     * Make sure that pResult->l is an instance of the type this
84     * method was expected to return.
85     */
86    const char* declType = dexProtoGetReturnType(&method->prototype);
87    const char* objType = objClazz->descriptor;
88    if (strcmp(declType, objType) == 0) {
89        /* names match; ignore class loader issues and allow it */
90        LOGV("Check %s.%s: %s io %s (FAST-OK)",
91            method->clazz->descriptor, method->name, objType, declType);
92    } else {
93        /*
94         * Names didn't match.  We need to resolve declType in the context
95         * of method->clazz->classLoader, and compare the class objects
96         * for equality.
97         *
98         * Since we're returning an instance of declType, it's safe to
99         * assume that it has been loaded and initialized (or, for the case
100         * of an array, generated).  However, the current class loader may
101         * not be listed as an initiating loader, so we can't just look for
102         * it in the loaded-classes list.
103         */
104        ClassObject* declClazz = dvmFindClassNoInit(declType, method->clazz->classLoader);
105        if (declClazz == NULL) {
106            LOGW("JNI WARNING: method declared to return '%s' returned '%s'",
107                declType, objType);
108            LOGW("             failed in %s.%s ('%s' not found)",
109                method->clazz->descriptor, method->name, declType);
110            abortMaybe();
111            return;
112        }
113        if (!dvmInstanceof(objClazz, declClazz)) {
114            LOGW("JNI WARNING: method declared to return '%s' returned '%s'",
115                declType, objType);
116            LOGW("             failed in %s.%s",
117                method->clazz->descriptor, method->name);
118            abortMaybe();
119            return;
120        } else {
121            LOGV("Check %s.%s: %s io %s (SLOW-OK)",
122                method->clazz->descriptor, method->name, objType, declType);
123        }
124    }
125}
126
127/*
128 * Determine if we need to check the return type coming out of the call.
129 *
130 * (We don't simply do this at the top of checkCallResultCommon() because
131 * this is on the critical path for native method calls.)
132 */
133static inline bool callNeedsCheck(const u4* args, JValue* pResult,
134    const Method* method, Thread* self)
135{
136    return (method->shorty[0] == 'L' && !dvmCheckException(self) && pResult->l != NULL);
137}
138
139/*
140 * Check a call into native code.
141 */
142void dvmCheckCallJNIMethod(const u4* args, JValue* pResult,
143    const Method* method, Thread* self)
144{
145    dvmCallJNIMethod(args, pResult, method, self);
146    if (callNeedsCheck(args, pResult, method, self)) {
147        checkCallResultCommon(args, pResult, method, self);
148    }
149}
150
151/*
152 * ===========================================================================
153 *      JNI function helpers
154 * ===========================================================================
155 */
156
157static inline const JNINativeInterface* baseEnv(JNIEnv* env) {
158    return ((JNIEnvExt*) env)->baseFuncTable;
159}
160
161static inline const JNIInvokeInterface* baseVm(JavaVM* vm) {
162    return ((JavaVMExt*) vm)->baseFuncTable;
163}
164
165class ScopedJniThreadState {
166public:
167    explicit ScopedJniThreadState(JNIEnv* env) {
168        dvmChangeStatus(NULL, THREAD_RUNNING);
169    }
170
171    ~ScopedJniThreadState() {
172        dvmChangeStatus(NULL, THREAD_NATIVE);
173    }
174
175private:
176    // Disallow copy and assignment.
177    ScopedJniThreadState(const ScopedJniThreadState&);
178    void operator=(const ScopedJniThreadState&);
179};
180
181/*
182 * Flags passed into ScopedCheck.
183 */
184#define kFlag_Default       0x0000
185
186#define kFlag_CritBad       0x0000      /* calling while in critical is bad */
187#define kFlag_CritOkay      0x0001      /* ...okay */
188#define kFlag_CritGet       0x0002      /* this is a critical "get" */
189#define kFlag_CritRelease   0x0003      /* this is a critical "release" */
190#define kFlag_CritMask      0x0003      /* bit mask to get "crit" value */
191
192#define kFlag_ExcepBad      0x0000      /* raised exceptions are bad */
193#define kFlag_ExcepOkay     0x0004      /* ...okay */
194
195#define kFlag_Release       0x0010      /* are we in a non-critical release function? */
196#define kFlag_NullableUtf   0x0020      /* are our UTF parameters nullable? */
197
198#define kFlag_Invocation    0x8000      /* Part of the invocation interface (JavaVM*) */
199
200static const char* indirectRefKindName(IndirectRef iref)
201{
202    return indirectRefKindToString(indirectRefKind(iref));
203}
204
205class ScopedCheck {
206public:
207    // For JNIEnv* functions.
208    explicit ScopedCheck(JNIEnv* env, int flags, const char* functionName) {
209        init(env, flags, functionName, true);
210        checkThread(flags);
211    }
212
213    // For JavaVM* functions.
214    explicit ScopedCheck(bool hasMethod, const char* functionName) {
215        init(NULL, kFlag_Invocation, functionName, hasMethod);
216    }
217
218    /*
219     * In some circumstances the VM will screen class names, but it doesn't
220     * for class lookup.  When things get bounced through a class loader, they
221     * can actually get normalized a couple of times; as a result, passing in
222     * a class name like "java.lang.Thread" instead of "java/lang/Thread" will
223     * work in some circumstances.
224     *
225     * This is incorrect and could cause strange behavior or compatibility
226     * problems, so we want to screen that out here.
227     *
228     * We expect "fully-qualified" class names, like "java/lang/Thread" or
229     * "[Ljava/lang/Object;".
230     */
231    void checkClassName(const char* className) {
232        if (!dexIsValidClassName(className, false)) {
233            LOGW("JNI WARNING: illegal class name '%s' (%s)", className, mFunctionName);
234            LOGW("             (should be formed like 'dalvik/system/DexFile')");
235            LOGW("             or '[Ldalvik/system/DexFile;' or '[[B')");
236            abortMaybe();
237        }
238    }
239
240    /*
241     * Verify that the field is of the appropriate type.  If the field has an
242     * object type, "jobj" is the object we're trying to assign into it.
243     *
244     * Works for both static and instance fields.
245     */
246    void checkFieldType(jobject jobj, jfieldID fieldID, PrimitiveType prim, bool isStatic) {
247        if (fieldID == NULL) {
248            LOGW("JNI WARNING: null field ID");
249            showLocation();
250            abortMaybe();
251        }
252
253        bool printWarn = false;
254        Field* field = (Field*) fieldID;
255        if ((field->signature[0] == 'L' || field->signature[0] == '[') && jobj != NULL) {
256            ScopedJniThreadState ts(mEnv);
257            Object* obj = dvmDecodeIndirectRef(mEnv, jobj);
258            /*
259             * If jobj is a weak global ref whose referent has been cleared,
260             * obj will be NULL.  Otherwise, obj should always be non-NULL
261             * and valid.
262             */
263            if (obj != NULL && !dvmIsValidObject(obj)) {
264                LOGW("JNI WARNING: field operation on invalid %s reference (%p)",
265                        indirectRefKindName(jobj), jobj);
266                printWarn = true;
267            } else {
268                ClassObject* fieldClass = dvmFindLoadedClass(field->signature);
269                ClassObject* objClass = obj->clazz;
270
271                assert(fieldClass != NULL);
272                assert(objClass != NULL);
273
274                if (!dvmInstanceof(objClass, fieldClass)) {
275                    LOGW("JNI WARNING: set field '%s' expected type %s, got %s",
276                            field->name, field->signature, objClass->descriptor);
277                    printWarn = true;
278                }
279            }
280        } else if (dexGetPrimitiveTypeFromDescriptorChar(field->signature[0]) != prim) {
281            LOGW("JNI WARNING: set field '%s' expected type %s, got %s",
282                    field->name, field->signature, primitiveTypeToName(prim));
283            printWarn = true;
284        } else if (isStatic && !dvmIsStaticField(field)) {
285            if (isStatic) {
286                LOGW("JNI WARNING: accessing non-static field %s as static", field->name);
287            } else {
288                LOGW("JNI WARNING: accessing static field %s as non-static", field->name);
289            }
290            printWarn = true;
291        }
292
293        if (printWarn) {
294            showLocation();
295            abortMaybe();
296        }
297    }
298
299    /*
300     * Verify that this instance field ID is valid for this object.
301     *
302     * Assumes "jobj" has already been validated.
303     */
304    void checkInstanceFieldID(jobject jobj, jfieldID fieldID) {
305        ScopedJniThreadState ts(mEnv);
306
307        Object* obj = dvmDecodeIndirectRef(mEnv, jobj);
308        if (!dvmIsValidObject(obj)) {
309            LOGW("JNI ERROR: field operation on invalid reference (%p)", jobj);
310            dvmAbort();
311        }
312
313        /*
314         * Check this class and all of its superclasses for a matching field.
315         * Don't need to scan interfaces.
316         */
317        ClassObject* clazz = obj->clazz;
318        while (clazz != NULL) {
319            if ((InstField*) fieldID >= clazz->ifields &&
320                    (InstField*) fieldID < clazz->ifields + clazz->ifieldCount) {
321                return;
322            }
323
324            clazz = clazz->super;
325        }
326
327        LOGW("JNI WARNING: instance fieldID %p not valid for class %s",
328                fieldID, obj->clazz->descriptor);
329        showLocation();
330        abortMaybe();
331    }
332
333    /*
334     * Verify that the pointer value is non-NULL.
335     */
336    void checkNonNull(const void* ptr) {
337        if (ptr == NULL) {
338            LOGW("JNI WARNING: invalid null pointer (%s)", mFunctionName);
339            abortMaybe();
340        }
341    }
342
343    /*
344     * Verify that the method's return type matches the type of call.
345     * 'expectedType' will be "L" for all objects, including arrays.
346     */
347    void checkSig(jmethodID methodID, const char* expectedType, bool isStatic) {
348        const Method* method = (const Method*) methodID;
349        bool printWarn = false;
350
351        if (*expectedType != method->shorty[0]) {
352            LOGW("JNI WARNING: expected return type '%s'", expectedType);
353            printWarn = true;
354        } else if (isStatic && !dvmIsStaticMethod(method)) {
355            if (isStatic) {
356                LOGW("JNI WARNING: calling non-static method with static call");
357            } else {
358                LOGW("JNI WARNING: calling static method with non-static call");
359            }
360            printWarn = true;
361        }
362
363        if (printWarn) {
364            char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
365            LOGW("             calling %s.%s %s", method->clazz->descriptor, method->name, desc);
366            free(desc);
367            showLocation();
368            abortMaybe();
369        }
370    }
371
372    /*
373     * Verify that this static field ID is valid for this class.
374     *
375     * Assumes "jclazz" has already been validated.
376     */
377    void checkStaticFieldID(jclass jclazz, jfieldID fieldID) {
378        ScopedJniThreadState ts(mEnv);
379        ClassObject* clazz = (ClassObject*) dvmDecodeIndirectRef(mEnv, jclazz);
380        StaticField* base = &clazz->sfields[0];
381        int fieldCount = clazz->sfieldCount;
382        if ((StaticField*) fieldID < base || (StaticField*) fieldID >= base + fieldCount) {
383            LOGW("JNI WARNING: static fieldID %p not valid for class %s",
384                    fieldID, clazz->descriptor);
385            LOGW("             base=%p count=%d", base, fieldCount);
386            showLocation();
387            abortMaybe();
388        }
389    }
390
391    /*
392     * Verify that "methodID" is appropriate for "clazz".
393     *
394     * A mismatch isn't dangerous, because the jmethodID defines the class.  In
395     * fact, jclazz is unused in the implementation.  It's best if we don't
396     * allow bad code in the system though.
397     *
398     * Instances of "jclazz" must be instances of the method's declaring class.
399     */
400    void checkStaticMethod(jclass jclazz, jmethodID methodID) {
401        ScopedJniThreadState ts(mEnv);
402
403        ClassObject* clazz = (ClassObject*) dvmDecodeIndirectRef(mEnv, jclazz);
404        const Method* method = (const Method*) methodID;
405
406        if (!dvmInstanceof(clazz, method->clazz)) {
407            LOGW("JNI WARNING: can't call static %s.%s on class %s",
408                    method->clazz->descriptor, method->name, clazz->descriptor);
409            showLocation();
410            // no abort?
411        }
412    }
413
414    /*
415     * Verify that "methodID" is appropriate for "jobj".
416     *
417     * Make sure the object is an instance of the method's declaring class.
418     * (Note the methodID might point to a declaration in an interface; this
419     * will be handled automatically by the instanceof check.)
420     */
421    void checkVirtualMethod(jobject jobj, jmethodID methodID) {
422        ScopedJniThreadState ts(mEnv);
423
424        Object* obj = dvmDecodeIndirectRef(mEnv, jobj);
425        const Method* method = (const Method*) methodID;
426
427        if (!dvmInstanceof(obj->clazz, method->clazz)) {
428            LOGW("JNI WARNING: can't call %s.%s on instance of %s",
429                    method->clazz->descriptor, method->name, obj->clazz->descriptor);
430            showLocation();
431            abortMaybe();
432        }
433    }
434
435    /**
436     * The format string is a sequence of the following characters,
437     * and must be followed by arguments of the corresponding types
438     * in the same order.
439     *
440     * Java primitive types:
441     * B - jbyte
442     * C - jchar
443     * D - jdouble
444     * F - jfloat
445     * I - jint
446     * J - jlong
447     * S - jshort
448     * Z - jboolean (shown as true and false)
449     * V - void
450     *
451     * Java reference types:
452     * L - jobject
453     * a - jarray
454     * c - jclass
455     * s - jstring
456     *
457     * JNI types:
458     * b - jboolean (shown as JNI_TRUE and JNI_FALSE)
459     * f - jfieldID
460     * m - jmethodID
461     * p - void*
462     * r - jint (for release mode arguments)
463     * u - const char* (modified UTF-8)
464     * z - jsize (for lengths; use i if negative values are okay)
465     * v - JavaVM*
466     * E - JNIEnv*
467     * . - no argument; just print "..." (used for varargs JNI calls)
468     *
469     * Use the kFlag_NullableUtf flag where 'u' field(s) are nullable.
470     */
471    void check(bool entry, const char* fmt0, ...) {
472        va_list ap;
473
474        bool shouldTrace = false;
475        const Method* method = NULL;
476        if ((gDvm.jniTrace || gDvmJni.logThirdPartyJni) && mHasMethod) {
477            // We need to guard some of the invocation interface's calls: a bad caller might
478            // use DetachCurrentThread or GetEnv on a thread that's not yet attached.
479            if ((mFlags & kFlag_Invocation) == 0 || dvmThreadSelf() != NULL) {
480                method = dvmGetCurrentJNIMethod();
481            }
482        }
483        if (method != NULL) {
484            // If both "-Xcheck:jni" and "-Xjnitrace:" are enabled, we print trace messages
485            // when a native method that matches the Xjnitrace argument calls a JNI function
486            // such as NewByteArray.
487            if (gDvm.jniTrace && strstr(method->clazz->descriptor, gDvm.jniTrace) != NULL) {
488                shouldTrace = true;
489            }
490            // If -Xjniopts:logThirdPartyJni is on, we want to log any JNI function calls
491            // made by a third-party native method.
492            if (gDvmJni.logThirdPartyJni) {
493                shouldTrace |= method->shouldTrace;
494            }
495        }
496
497        if (shouldTrace) {
498            va_start(ap, fmt0);
499            std::string msg;
500            for (const char* fmt = fmt0; *fmt;) {
501                char ch = *fmt++;
502                if (ch == 'B') { // jbyte
503                    jbyte b = va_arg(ap, int);
504                    if (b >= 0 && b < 10) {
505                        StringAppendF(&msg, "%d", b);
506                    } else {
507                        StringAppendF(&msg, "%#x (%d)", b, b);
508                    }
509                } else if (ch == 'C') { // jchar
510                    jchar c = va_arg(ap, int);
511                    if (c < 0x7f && c >= ' ') {
512                        StringAppendF(&msg, "U+%x ('%c')", c, c);
513                    } else {
514                        StringAppendF(&msg, "U+%x", c);
515                    }
516                } else if (ch == 'F' || ch == 'D') { // jfloat, jdouble
517                    StringAppendF(&msg, "%g", va_arg(ap, double));
518                } else if (ch == 'I' || ch == 'S') { // jint, jshort
519                    StringAppendF(&msg, "%d", va_arg(ap, int));
520                } else if (ch == 'J') { // jlong
521                    StringAppendF(&msg, "%lld", va_arg(ap, jlong));
522                } else if (ch == 'Z') { // jboolean
523                    StringAppendF(&msg, "%s", va_arg(ap, int) ? "true" : "false");
524                } else if (ch == 'V') { // void
525                    msg += "void";
526                } else if (ch == 'v') { // JavaVM*
527                    JavaVM* vm = va_arg(ap, JavaVM*);
528                    StringAppendF(&msg, "(JavaVM*)%p", vm);
529                } else if (ch == 'E') { // JNIEnv*
530                    JNIEnv* env = va_arg(ap, JNIEnv*);
531                    StringAppendF(&msg, "(JNIEnv*)%p", env);
532                } else if (ch == 'L' || ch == 'a' || ch == 's') { // jobject, jarray, jstring
533                    // For logging purposes, these are identical.
534                    jobject o = va_arg(ap, jobject);
535                    if (o == NULL) {
536                        msg += "NULL";
537                    } else {
538                        StringAppendF(&msg, "%p", o);
539                    }
540                } else if (ch == 'b') { // jboolean (JNI-style)
541                    jboolean b = va_arg(ap, int);
542                    msg += (b ? "JNI_TRUE" : "JNI_FALSE");
543                } else if (ch == 'c') { // jclass
544                    jclass jc = va_arg(ap, jclass);
545                    Object* c = dvmDecodeIndirectRef(mEnv, jc);
546                    if (c == NULL) {
547                        msg += "NULL";
548                    } else if (c == kInvalidIndirectRefObject || !dvmIsValidObject(c)) {
549                        StringAppendF(&msg, "%p(INVALID)", jc);
550                    } else {
551                        std::string className(dvmHumanReadableType(c));
552                        StringAppendF(&msg, "%s", className.c_str());
553                        if (!entry) {
554                            StringAppendF(&msg, " (%p)", jc);
555                        }
556                    }
557                } else if (ch == 'f') { // jfieldID
558                    jfieldID fid = va_arg(ap, jfieldID);
559                    std::string name(dvmHumanReadableField((Field*) fid));
560                    StringAppendF(&msg, "%s", name.c_str());
561                    if (!entry) {
562                        StringAppendF(&msg, " (%p)", fid);
563                    }
564                } else if (ch == 'z') { // non-negative jsize
565                    // You might expect jsize to be size_t, but it's not; it's the same as jint.
566                    // We only treat this specially so we can do the non-negative check.
567                    // TODO: maybe this wasn't worth it?
568                    jint i = va_arg(ap, jint);
569                    StringAppendF(&msg, "%d", i);
570                } else if (ch == 'm') { // jmethodID
571                    jmethodID mid = va_arg(ap, jmethodID);
572                    std::string name(dvmHumanReadableMethod((Method*) mid, true));
573                    StringAppendF(&msg, "%s", name.c_str());
574                    if (!entry) {
575                        StringAppendF(&msg, " (%p)", mid);
576                    }
577                } else if (ch == 'p') { // void* ("pointer")
578                    void* p = va_arg(ap, void*);
579                    if (p == NULL) {
580                        msg += "NULL";
581                    } else {
582                        StringAppendF(&msg, "(void*) %p", p);
583                    }
584                } else if (ch == 'r') { // jint (release mode)
585                    jint releaseMode = va_arg(ap, jint);
586                    if (releaseMode == 0) {
587                        msg += "0";
588                    } else if (releaseMode == JNI_ABORT) {
589                        msg += "JNI_ABORT";
590                    } else if (releaseMode == JNI_COMMIT) {
591                        msg += "JNI_COMMIT";
592                    } else {
593                        StringAppendF(&msg, "invalid release mode %d", releaseMode);
594                    }
595                } else if (ch == 'u') { // const char* (modified UTF-8)
596                    const char* utf = va_arg(ap, const char*);
597                    if (utf == NULL) {
598                        msg += "NULL";
599                    } else {
600                        StringAppendF(&msg, "\"%s\"", utf);
601                    }
602                } else if (ch == '.') {
603                    msg += "...";
604                } else {
605                    LOGE("unknown trace format specifier %c", ch);
606                    dvmAbort();
607                }
608                if (*fmt) {
609                    StringAppendF(&msg, ", ");
610                }
611            }
612            va_end(ap);
613
614            if (entry) {
615                if (mHasMethod) {
616                    std::string methodName(dvmHumanReadableMethod(method, false));
617                    LOGI("JNI: %s -> %s(%s)", methodName.c_str(), mFunctionName, msg.c_str());
618                    mIndent = methodName.size() + 1;
619                } else {
620                    LOGI("JNI: -> %s(%s)", mFunctionName, msg.c_str());
621                    mIndent = 0;
622                }
623            } else {
624                LOGI("JNI: %*s<- %s returned %s", mIndent, "", mFunctionName, msg.c_str());
625            }
626        }
627
628        // We always do the thorough checks on entry, and never on exit...
629        if (entry) {
630            va_start(ap, fmt0);
631            for (const char* fmt = fmt0; *fmt; ++fmt) {
632                char ch = *fmt;
633                if (ch == 'a') {
634                    checkArray(va_arg(ap, jarray));
635                } else if (ch == 'c') {
636                    checkClass(va_arg(ap, jclass));
637                } else if (ch == 'L') {
638                    checkObject(va_arg(ap, jobject));
639                } else if (ch == 'r') {
640                    checkReleaseMode(va_arg(ap, jint));
641                } else if (ch == 's') {
642                    checkString(va_arg(ap, jstring));
643                } else if (ch == 'u') {
644                    if ((mFlags & kFlag_Release) != 0) {
645                        checkNonNull(va_arg(ap, const char*));
646                    } else {
647                        bool nullable = ((mFlags & kFlag_NullableUtf) != 0);
648                        checkUtfString(va_arg(ap, const char*), nullable);
649                    }
650                } else if (ch == 'z') {
651                    checkLengthPositive(va_arg(ap, jsize));
652                } else if (strchr("BCISZbfmpEv", ch) != NULL) {
653                    va_arg(ap, int); // Skip this argument.
654                } else if (ch == 'D' || ch == 'F') {
655                    va_arg(ap, double); // Skip this argument.
656                } else if (ch == 'J') {
657                    va_arg(ap, long); // Skip this argument.
658                } else if (ch == '.') {
659                } else {
660                    LOGE("unknown check format specifier %c", ch);
661                    dvmAbort();
662                }
663            }
664            va_end(ap);
665        }
666    }
667
668private:
669    JNIEnv* mEnv;
670    const char* mFunctionName;
671    int mFlags;
672    bool mHasMethod;
673    size_t mIndent;
674
675    void init(JNIEnv* env, int flags, const char* functionName, bool hasMethod) {
676        mEnv = env;
677        mFlags = flags;
678
679        // Use +6 to drop the leading "Check_"...
680        mFunctionName = functionName + 6;
681
682        // Set "hasMethod" to true if we have a valid thread with a method pointer.
683        // We won't have one before attaching a thread, after detaching a thread, or
684        // after destroying the VM.
685        mHasMethod = hasMethod;
686    }
687
688    /*
689     * Verify that "array" is non-NULL and points to an Array object.
690     *
691     * Since we're dealing with objects, switch to "running" mode.
692     */
693    void checkArray(jarray jarr) {
694        if (jarr == NULL) {
695            LOGW("JNI WARNING: received null array");
696            showLocation();
697            abortMaybe();
698            return;
699        }
700
701        ScopedJniThreadState ts(mEnv);
702        bool printWarn = false;
703
704        Object* obj = dvmDecodeIndirectRef(mEnv, jarr);
705
706        if (!dvmIsValidObject(obj)) {
707            LOGW("JNI WARNING: jarray is an invalid %s reference (%p)",
708            indirectRefKindName(jarr), jarr);
709            printWarn = true;
710        } else if (obj->clazz->descriptor[0] != '[') {
711            LOGW("JNI WARNING: jarray arg has wrong type (expected array, got %s)",
712            obj->clazz->descriptor);
713            printWarn = true;
714        }
715
716        if (printWarn) {
717            showLocation();
718            abortMaybe();
719        }
720    }
721
722    void checkClass(jclass c) {
723        checkInstance(c, gDvm.classJavaLangClass, "jclass");
724    }
725
726    void checkLengthPositive(jsize length) {
727        if (length < 0) {
728            LOGW("JNI WARNING: negative jsize (%s)", mFunctionName);
729            abortMaybe();
730        }
731    }
732
733    /*
734     * Verify that "jobj" is a valid object, and that it's an object that JNI
735     * is allowed to know about.  We allow NULL references.
736     *
737     * Switches to "running" mode before performing checks.
738     */
739    void checkObject(jobject jobj) {
740        if (jobj == NULL) {
741            return;
742        }
743
744        ScopedJniThreadState ts(mEnv);
745
746        bool printWarn = false;
747        if (dvmGetJNIRefType(mEnv, jobj) == JNIInvalidRefType) {
748            LOGW("JNI WARNING: %p is not a valid JNI reference", jobj);
749            printWarn = true;
750        } else {
751            Object* obj = dvmDecodeIndirectRef(mEnv, jobj);
752            if (obj == kInvalidIndirectRefObject) {
753                LOGW("JNI WARNING: native code passing in invalid reference %p", jobj);
754                printWarn = true;
755            } else if (obj != NULL && !dvmIsValidObject(obj)) {
756                // TODO: when we remove workAroundAppJniBugs, this should be impossible.
757                LOGW("JNI WARNING: native code passing in reference to invalid object %p %p",
758                        jobj, obj);
759                printWarn = true;
760            }
761        }
762
763        if (printWarn) {
764            showLocation();
765            abortMaybe();
766        }
767    }
768
769    /*
770     * Verify that the "mode" argument passed to a primitive array Release
771     * function is one of the valid values.
772     */
773    void checkReleaseMode(jint mode) {
774        if (mode != 0 && mode != JNI_COMMIT && mode != JNI_ABORT) {
775            LOGW("JNI WARNING: bad value for mode (%d) (%s)", mode, mFunctionName);
776            abortMaybe();
777        }
778    }
779
780    void checkString(jstring s) {
781        checkInstance(s, gDvm.classJavaLangString, "jstring");
782    }
783
784    void checkThread(int flags) {
785        // Get the *correct* JNIEnv by going through our TLS pointer.
786        JNIEnvExt* threadEnv = dvmGetJNIEnvForThread();
787
788        /*
789         * Verify that the current thread is (a) attached and (b) associated with
790         * this particular instance of JNIEnv.
791         */
792        bool printWarn = false;
793        if (threadEnv == NULL) {
794            LOGE("JNI ERROR: non-VM thread making JNI calls");
795            // don't set printWarn -- it'll try to call showLocation()
796            dvmAbort();
797        } else if ((JNIEnvExt*) mEnv != threadEnv) {
798            if (dvmThreadSelf()->threadId != threadEnv->envThreadId) {
799                LOGE("JNI: threadEnv != thread->env?");
800                dvmAbort();
801            }
802
803            LOGW("JNI WARNING: threadid=%d using env from threadid=%d",
804                    threadEnv->envThreadId, ((JNIEnvExt*) mEnv)->envThreadId);
805            printWarn = true;
806
807            // If we're keeping broken code limping along, we need to suppress the abort...
808            if (!gDvmJni.workAroundAppJniBugs) {
809                printWarn = false;
810            }
811
812            /* this is a bad idea -- need to throw as we exit, or abort func */
813            //dvmThrowRuntimeException("invalid use of JNI env ptr");
814        } else if (((JNIEnvExt*) mEnv)->self != dvmThreadSelf()) {
815            /* correct JNIEnv*; make sure the "self" pointer is correct */
816            LOGE("JNI ERROR: env->self != thread-self (%p vs. %p)",
817                    ((JNIEnvExt*) mEnv)->self, dvmThreadSelf());
818            dvmAbort();
819        }
820
821        /*
822         * Verify that, if this thread previously made a critical "get" call, we
823         * do the corresponding "release" call before we try anything else.
824         */
825        switch (flags & kFlag_CritMask) {
826        case kFlag_CritOkay:    // okay to call this method
827            break;
828        case kFlag_CritBad:     // not okay to call
829            if (threadEnv->critical) {
830                LOGW("JNI WARNING: threadid=%d using JNI after critical get",
831                        threadEnv->envThreadId);
832                printWarn = true;
833            }
834            break;
835        case kFlag_CritGet:     // this is a "get" call
836            /* don't check here; we allow nested gets */
837            threadEnv->critical++;
838            break;
839        case kFlag_CritRelease: // this is a "release" call
840            threadEnv->critical--;
841            if (threadEnv->critical < 0) {
842                LOGW("JNI WARNING: threadid=%d called too many crit releases",
843                        threadEnv->envThreadId);
844                printWarn = true;
845            }
846            break;
847        default:
848            assert(false);
849        }
850
851        /*
852         * Verify that, if an exception has been raised, the native code doesn't
853         * make any JNI calls other than the Exception* methods.
854         */
855        bool printException = false;
856        if ((flags & kFlag_ExcepOkay) == 0 && dvmCheckException(dvmThreadSelf())) {
857            LOGW("JNI WARNING: JNI method called with exception pending");
858            printWarn = true;
859            printException = true;
860        }
861
862        if (printWarn) {
863            showLocation();
864        }
865        if (printException) {
866            LOGW("Pending exception is:");
867            dvmLogExceptionStackTrace();
868        }
869        if (printWarn) {
870            abortMaybe();
871        }
872    }
873
874    /*
875     * Verify that "bytes" points to valid "modified UTF-8" data.
876     */
877    void checkUtfString(const char* bytes, bool nullable) {
878        if (bytes == NULL) {
879            if (!nullable) {
880                LOGW("JNI WARNING: non-nullable const char* was NULL");
881                showLocation();
882                abortMaybe();
883            }
884            return;
885        }
886
887        const char* errorKind = NULL;
888        u1 utf8 = checkUtfBytes(bytes, &errorKind);
889        if (errorKind != NULL) {
890            LOGW("JNI WARNING: input is not valid UTF-8: illegal %s byte %#x", errorKind, utf8);
891            LOGW("             string: '%s'", bytes);
892            showLocation();
893            abortMaybe();
894        }
895    }
896
897    /*
898     * Verify that "jobj" is a valid non-NULL object reference, and points to
899     * an instance of expectedClass.
900     *
901     * Because we're looking at an object on the GC heap, we have to switch
902     * to "running" mode before doing the checks.
903     */
904    void checkInstance(jobject jobj, ClassObject* expectedClass, const char* argName) {
905        if (jobj == NULL) {
906            LOGW("JNI WARNING: received null %s", argName);
907            showLocation();
908            abortMaybe();
909            return;
910        }
911
912        ScopedJniThreadState ts(mEnv);
913        bool printWarn = false;
914
915        Object* obj = dvmDecodeIndirectRef(mEnv, jobj);
916
917        if (!dvmIsValidObject(obj)) {
918            LOGW("JNI WARNING: %s is an invalid %s reference (%p)",
919                    argName, indirectRefKindName(jobj), jobj);
920            printWarn = true;
921        } else if (obj->clazz != expectedClass) {
922            LOGW("JNI WARNING: %s arg has wrong type (expected %s, got %s)",
923                    argName, expectedClass->descriptor, obj->clazz->descriptor);
924            printWarn = true;
925        }
926
927        if (printWarn) {
928            showLocation();
929            abortMaybe();
930        }
931    }
932
933    static u1 checkUtfBytes(const char* bytes, const char** errorKind) {
934        while (*bytes != '\0') {
935            u1 utf8 = *(bytes++);
936            // Switch on the high four bits.
937            switch (utf8 >> 4) {
938            case 0x00:
939            case 0x01:
940            case 0x02:
941            case 0x03:
942            case 0x04:
943            case 0x05:
944            case 0x06:
945            case 0x07:
946                // Bit pattern 0xxx. No need for any extra bytes.
947                break;
948            case 0x08:
949            case 0x09:
950            case 0x0a:
951            case 0x0b:
952            case 0x0f:
953                /*
954                 * Bit pattern 10xx or 1111, which are illegal start bytes.
955                 * Note: 1111 is valid for normal UTF-8, but not the
956                 * modified UTF-8 used here.
957                 */
958                *errorKind = "start";
959                return utf8;
960            case 0x0e:
961                // Bit pattern 1110, so there are two additional bytes.
962                utf8 = *(bytes++);
963                if ((utf8 & 0xc0) != 0x80) {
964                    *errorKind = "continuation";
965                    return utf8;
966                }
967                // Fall through to take care of the final byte.
968            case 0x0c:
969            case 0x0d:
970                // Bit pattern 110x, so there is one additional byte.
971                utf8 = *(bytes++);
972                if ((utf8 & 0xc0) != 0x80) {
973                    *errorKind = "continuation";
974                    return utf8;
975                }
976                break;
977            }
978        }
979        return 0;
980    }
981
982    /**
983     * Returns a human-readable name for the given primitive type.
984     */
985    static const char* primitiveTypeToName(PrimitiveType primType) {
986        switch (primType) {
987        case PRIM_VOID:    return "void";
988        case PRIM_BOOLEAN: return "boolean";
989        case PRIM_BYTE:    return "byte";
990        case PRIM_SHORT:   return "short";
991        case PRIM_CHAR:    return "char";
992        case PRIM_INT:     return "int";
993        case PRIM_LONG:    return "long";
994        case PRIM_FLOAT:   return "float";
995        case PRIM_DOUBLE:  return "double";
996        case PRIM_NOT:     return "Object/array";
997        default:           return "???";
998        }
999    }
1000
1001    void showLocation() {
1002        const Method* method = dvmGetCurrentJNIMethod();
1003        char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
1004        LOGW("             in %s.%s:%s (%s)", method->clazz->descriptor, method->name, desc, mFunctionName);
1005        free(desc);
1006    }
1007
1008    // Disallow copy and assignment.
1009    ScopedCheck(const ScopedCheck&);
1010    void operator=(const ScopedCheck&);
1011};
1012
1013/*
1014 * ===========================================================================
1015 *      Guarded arrays
1016 * ===========================================================================
1017 */
1018
1019#define kGuardLen       512         /* must be multiple of 2 */
1020#define kGuardPattern   0xd5e3      /* uncommon values; d5e3d5e3 invalid addr */
1021#define kGuardMagic     0xffd5aa96
1022
1023/* this gets tucked in at the start of the buffer; struct size must be even */
1024struct GuardedCopy {
1025    u4          magic;
1026    uLong       adler;
1027    size_t      originalLen;
1028    const void* originalPtr;
1029
1030    /* find the GuardedCopy given the pointer into the "live" data */
1031    static inline const GuardedCopy* fromData(const void* dataBuf) {
1032        return reinterpret_cast<const GuardedCopy*>(actualBuffer(dataBuf));
1033    }
1034
1035    /*
1036     * Create an over-sized buffer to hold the contents of "buf".  Copy it in,
1037     * filling in the area around it with guard data.
1038     *
1039     * We use a 16-bit pattern to make a rogue memset less likely to elude us.
1040     */
1041    static void* create(const void* buf, size_t len, bool modOkay) {
1042        size_t newLen = actualLength(len);
1043        u1* newBuf = debugAlloc(newLen);
1044
1045        /* fill it in with a pattern */
1046        u2* pat = (u2*) newBuf;
1047        for (size_t i = 0; i < newLen / 2; i++) {
1048            *pat++ = kGuardPattern;
1049        }
1050
1051        /* copy the data in; note "len" could be zero */
1052        memcpy(newBuf + kGuardLen / 2, buf, len);
1053
1054        /* if modification is not expected, grab a checksum */
1055        uLong adler = 0;
1056        if (!modOkay) {
1057            adler = adler32(0L, Z_NULL, 0);
1058            adler = adler32(adler, (const Bytef*)buf, len);
1059            *(uLong*)newBuf = adler;
1060        }
1061
1062        GuardedCopy* pExtra = reinterpret_cast<GuardedCopy*>(newBuf);
1063        pExtra->magic = kGuardMagic;
1064        pExtra->adler = adler;
1065        pExtra->originalPtr = buf;
1066        pExtra->originalLen = len;
1067
1068        return newBuf + kGuardLen / 2;
1069    }
1070
1071    /*
1072     * Free up the guard buffer, scrub it, and return the original pointer.
1073     */
1074    static void* destroy(void* dataBuf) {
1075        const GuardedCopy* pExtra = GuardedCopy::fromData(dataBuf);
1076        void* originalPtr = (void*) pExtra->originalPtr;
1077        size_t len = pExtra->originalLen;
1078        debugFree(dataBuf, len);
1079        return originalPtr;
1080    }
1081
1082    /*
1083     * Verify the guard area and, if "modOkay" is false, that the data itself
1084     * has not been altered.
1085     *
1086     * The caller has already checked that "dataBuf" is non-NULL.
1087     */
1088    static bool check(const void* dataBuf, bool modOkay) {
1089        static const u4 kMagicCmp = kGuardMagic;
1090        const u1* fullBuf = actualBuffer(dataBuf);
1091        const GuardedCopy* pExtra = GuardedCopy::fromData(dataBuf);
1092
1093        /*
1094         * Before we do anything with "pExtra", check the magic number.  We
1095         * do the check with memcmp rather than "==" in case the pointer is
1096         * unaligned.  If it points to completely bogus memory we're going
1097         * to crash, but there's no easy way around that.
1098         */
1099        if (memcmp(&pExtra->magic, &kMagicCmp, 4) != 0) {
1100            u1 buf[4];
1101            memcpy(buf, &pExtra->magic, 4);
1102            LOGE("JNI: guard magic does not match (found 0x%02x%02x%02x%02x) -- incorrect data pointer %p?",
1103                    buf[3], buf[2], buf[1], buf[0], dataBuf); /* assume little endian */
1104            return false;
1105        }
1106
1107        size_t len = pExtra->originalLen;
1108
1109        /* check bottom half of guard; skip over optional checksum storage */
1110        const u2* pat = (u2*) fullBuf;
1111        for (size_t i = sizeof(GuardedCopy) / 2; i < (kGuardLen / 2 - sizeof(GuardedCopy)) / 2; i++) {
1112            if (pat[i] != kGuardPattern) {
1113                LOGE("JNI: guard pattern(1) disturbed at %p + %d", fullBuf, i*2);
1114                return false;
1115            }
1116        }
1117
1118        int offset = kGuardLen / 2 + len;
1119        if (offset & 0x01) {
1120            /* odd byte; expected value depends on endian-ness of host */
1121            const u2 patSample = kGuardPattern;
1122            if (fullBuf[offset] != ((const u1*) &patSample)[1]) {
1123                LOGE("JNI: guard pattern disturbed in odd byte after %p (+%d) 0x%02x 0x%02x",
1124                        fullBuf, offset, fullBuf[offset], ((const u1*) &patSample)[1]);
1125                return false;
1126            }
1127            offset++;
1128        }
1129
1130        /* check top half of guard */
1131        pat = (u2*) (fullBuf + offset);
1132        for (size_t i = 0; i < kGuardLen / 4; i++) {
1133            if (pat[i] != kGuardPattern) {
1134                LOGE("JNI: guard pattern(2) disturbed at %p + %d", fullBuf, offset + i*2);
1135                return false;
1136            }
1137        }
1138
1139        /*
1140         * If modification is not expected, verify checksum.  Strictly speaking
1141         * this is wrong: if we told the client that we made a copy, there's no
1142         * reason they can't alter the buffer.
1143         */
1144        if (!modOkay) {
1145            uLong adler = adler32(0L, Z_NULL, 0);
1146            adler = adler32(adler, (const Bytef*)dataBuf, len);
1147            if (pExtra->adler != adler) {
1148                LOGE("JNI: buffer modified (0x%08lx vs 0x%08lx) at addr %p",
1149                        pExtra->adler, adler, dataBuf);
1150                return false;
1151            }
1152        }
1153
1154        return true;
1155    }
1156
1157private:
1158    static u1* debugAlloc(size_t len) {
1159        void* result = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
1160        if (result == MAP_FAILED) {
1161            LOGE("GuardedCopy::create mmap(%d) failed: %s", len, strerror(errno));
1162            dvmAbort();
1163        }
1164        return reinterpret_cast<u1*>(result);
1165    }
1166
1167    static void debugFree(void* dataBuf, size_t len) {
1168        u1* fullBuf = actualBuffer(dataBuf);
1169        size_t totalByteCount = actualLength(len);
1170        // TODO: we could mprotect instead, and keep the allocation around for a while.
1171        // This would be even more expensive, but it might catch more errors.
1172        // if (mprotect(fullBuf, totalByteCount, PROT_NONE) != 0) {
1173        //     LOGW("mprotect(PROT_NONE) failed: %s", strerror(errno));
1174        // }
1175        if (munmap(fullBuf, totalByteCount) != 0) {
1176            LOGW("munmap failed: %s", strerror(errno));
1177            dvmAbort();
1178        }
1179    }
1180
1181    static const u1* actualBuffer(const void* dataBuf) {
1182        return reinterpret_cast<const u1*>(dataBuf) - kGuardLen / 2;
1183    }
1184
1185    static u1* actualBuffer(void* dataBuf) {
1186        return reinterpret_cast<u1*>(dataBuf) - kGuardLen / 2;
1187    }
1188
1189    // Underlying length of a user allocation of 'length' bytes.
1190    static size_t actualLength(size_t length) {
1191        return (length + kGuardLen + 1) & ~0x01;
1192    }
1193};
1194
1195/*
1196 * Return the width, in bytes, of a primitive type.
1197 */
1198static int dvmPrimitiveTypeWidth(PrimitiveType primType) {
1199    switch (primType) {
1200        case PRIM_BOOLEAN: return 1;
1201        case PRIM_BYTE:    return 1;
1202        case PRIM_SHORT:   return 2;
1203        case PRIM_CHAR:    return 2;
1204        case PRIM_INT:     return 4;
1205        case PRIM_LONG:    return 8;
1206        case PRIM_FLOAT:   return 4;
1207        case PRIM_DOUBLE:  return 8;
1208        case PRIM_VOID:
1209        default: {
1210            assert(false);
1211            return -1;
1212        }
1213    }
1214}
1215
1216/*
1217 * Create a guarded copy of a primitive array.  Modifications to the copied
1218 * data are allowed.  Returns a pointer to the copied data.
1219 */
1220static void* createGuardedPACopy(JNIEnv* env, const jarray jarr, jboolean* isCopy) {
1221    ScopedJniThreadState ts(env);
1222
1223    ArrayObject* arrObj = (ArrayObject*) dvmDecodeIndirectRef(env, jarr);
1224    PrimitiveType primType = arrObj->clazz->elementClass->primitiveType;
1225    int len = arrObj->length * dvmPrimitiveTypeWidth(primType);
1226    void* result = GuardedCopy::create(arrObj->contents, len, true);
1227    if (isCopy != NULL) {
1228        *isCopy = JNI_TRUE;
1229    }
1230    return result;
1231}
1232
1233/*
1234 * Perform the array "release" operation, which may or may not copy data
1235 * back into the VM, and may or may not release the underlying storage.
1236 */
1237static void* releaseGuardedPACopy(JNIEnv* env, jarray jarr, void* dataBuf, int mode) {
1238    ScopedJniThreadState ts(env);
1239    ArrayObject* arrObj = (ArrayObject*) dvmDecodeIndirectRef(env, jarr);
1240
1241    if (!GuardedCopy::check(dataBuf, true)) {
1242        LOGE("JNI: failed guarded copy check in releaseGuardedPACopy");
1243        abortMaybe();
1244        return NULL;
1245    }
1246
1247    if (mode != JNI_ABORT) {
1248        size_t len = GuardedCopy::fromData(dataBuf)->originalLen;
1249        memcpy(arrObj->contents, dataBuf, len);
1250    }
1251
1252    u1* result = NULL;
1253    if (mode != JNI_COMMIT) {
1254        result = (u1*) GuardedCopy::destroy(dataBuf);
1255    } else {
1256        result = (u1*) (void*) GuardedCopy::fromData(dataBuf)->originalPtr;
1257    }
1258
1259    /* pointer is to the array contents; back up to the array object */
1260    result -= OFFSETOF_MEMBER(ArrayObject, contents);
1261    return result;
1262}
1263
1264
1265/*
1266 * ===========================================================================
1267 *      JNI functions
1268 * ===========================================================================
1269 */
1270
1271#define CHECK_JNI_ENTRY(flags, types, args...) \
1272    ScopedCheck sc(env, flags, __FUNCTION__); \
1273    sc.check(true, types, ##args)
1274
1275#define CHECK_JNI_EXIT(type, exp) ({ \
1276    typeof (exp) _rc = (exp); \
1277    sc.check(false, type, _rc); \
1278    _rc; })
1279#define CHECK_JNI_EXIT_VOID() \
1280    sc.check(false, "V")
1281
1282static jint Check_GetVersion(JNIEnv* env) {
1283    CHECK_JNI_ENTRY(kFlag_Default, "E", env);
1284    return CHECK_JNI_EXIT("I", baseEnv(env)->GetVersion(env));
1285}
1286
1287static jclass Check_DefineClass(JNIEnv* env, const char* name, jobject loader,
1288    const jbyte* buf, jsize bufLen)
1289{
1290    CHECK_JNI_ENTRY(kFlag_Default, "EuLpz", env, name, loader, buf, bufLen);
1291    sc.checkClassName(name);
1292    return CHECK_JNI_EXIT("c", baseEnv(env)->DefineClass(env, name, loader, buf, bufLen));
1293}
1294
1295static jclass Check_FindClass(JNIEnv* env, const char* name) {
1296    CHECK_JNI_ENTRY(kFlag_Default, "Eu", env, name);
1297    sc.checkClassName(name);
1298    return CHECK_JNI_EXIT("c", baseEnv(env)->FindClass(env, name));
1299}
1300
1301static jclass Check_GetSuperclass(JNIEnv* env, jclass clazz) {
1302    CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1303    return CHECK_JNI_EXIT("c", baseEnv(env)->GetSuperclass(env, clazz));
1304}
1305
1306static jboolean Check_IsAssignableFrom(JNIEnv* env, jclass clazz1, jclass clazz2) {
1307    CHECK_JNI_ENTRY(kFlag_Default, "Ecc", env, clazz1, clazz2);
1308    return CHECK_JNI_EXIT("b", baseEnv(env)->IsAssignableFrom(env, clazz1, clazz2));
1309}
1310
1311static jmethodID Check_FromReflectedMethod(JNIEnv* env, jobject method) {
1312    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, method);
1313    // TODO: check that 'field' is a java.lang.reflect.Method.
1314    return CHECK_JNI_EXIT("m", baseEnv(env)->FromReflectedMethod(env, method));
1315}
1316
1317static jfieldID Check_FromReflectedField(JNIEnv* env, jobject field) {
1318    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, field);
1319    // TODO: check that 'field' is a java.lang.reflect.Field.
1320    return CHECK_JNI_EXIT("f", baseEnv(env)->FromReflectedField(env, field));
1321}
1322
1323static jobject Check_ToReflectedMethod(JNIEnv* env, jclass cls,
1324        jmethodID methodID, jboolean isStatic)
1325{
1326    CHECK_JNI_ENTRY(kFlag_Default, "Ecmb", env, cls, methodID, isStatic);
1327    return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedMethod(env, cls, methodID, isStatic));
1328}
1329
1330static jobject Check_ToReflectedField(JNIEnv* env, jclass cls,
1331        jfieldID fieldID, jboolean isStatic)
1332{
1333    CHECK_JNI_ENTRY(kFlag_Default, "Ecfb", env, cls, fieldID, isStatic);
1334    return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedField(env, cls, fieldID, isStatic));
1335}
1336
1337static jint Check_Throw(JNIEnv* env, jthrowable obj) {
1338    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1339    // TODO: check that 'obj' is a java.lang.Throwable.
1340    return CHECK_JNI_EXIT("I", baseEnv(env)->Throw(env, obj));
1341}
1342
1343static jint Check_ThrowNew(JNIEnv* env, jclass clazz, const char* message) {
1344    CHECK_JNI_ENTRY(kFlag_NullableUtf, "Ecu", env, clazz, message);
1345    return CHECK_JNI_EXIT("I", baseEnv(env)->ThrowNew(env, clazz, message));
1346}
1347
1348static jthrowable Check_ExceptionOccurred(JNIEnv* env) {
1349    CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1350    return CHECK_JNI_EXIT("L", baseEnv(env)->ExceptionOccurred(env));
1351}
1352
1353static void Check_ExceptionDescribe(JNIEnv* env) {
1354    CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1355    baseEnv(env)->ExceptionDescribe(env);
1356    CHECK_JNI_EXIT_VOID();
1357}
1358
1359static void Check_ExceptionClear(JNIEnv* env) {
1360    CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1361    baseEnv(env)->ExceptionClear(env);
1362    CHECK_JNI_EXIT_VOID();
1363}
1364
1365static void Check_FatalError(JNIEnv* env, const char* msg) {
1366    CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, msg);
1367    baseEnv(env)->FatalError(env, msg);
1368    CHECK_JNI_EXIT_VOID();
1369}
1370
1371static jint Check_PushLocalFrame(JNIEnv* env, jint capacity) {
1372    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EI", env, capacity);
1373    return CHECK_JNI_EXIT("I", baseEnv(env)->PushLocalFrame(env, capacity));
1374}
1375
1376static jobject Check_PopLocalFrame(JNIEnv* env, jobject res) {
1377    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, res);
1378    return CHECK_JNI_EXIT("L", baseEnv(env)->PopLocalFrame(env, res));
1379}
1380
1381static jobject Check_NewGlobalRef(JNIEnv* env, jobject obj) {
1382    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1383    return CHECK_JNI_EXIT("L", baseEnv(env)->NewGlobalRef(env, obj));
1384}
1385
1386static void Check_DeleteGlobalRef(JNIEnv* env, jobject globalRef) {
1387    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, globalRef);
1388    if (globalRef != NULL && dvmGetJNIRefType(env, globalRef) != JNIGlobalRefType) {
1389        LOGW("JNI WARNING: DeleteGlobalRef on non-global %p (type=%d)",
1390                globalRef, dvmGetJNIRefType(env, globalRef));
1391        abortMaybe();
1392    } else {
1393        baseEnv(env)->DeleteGlobalRef(env, globalRef);
1394        CHECK_JNI_EXIT_VOID();
1395    }
1396}
1397
1398static jobject Check_NewLocalRef(JNIEnv* env, jobject ref) {
1399    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, ref);
1400    return CHECK_JNI_EXIT("L", baseEnv(env)->NewLocalRef(env, ref));
1401}
1402
1403static void Check_DeleteLocalRef(JNIEnv* env, jobject localRef) {
1404    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, localRef);
1405    if (localRef != NULL && dvmGetJNIRefType(env, localRef) != JNILocalRefType) {
1406        LOGW("JNI WARNING: DeleteLocalRef on non-local %p (type=%d)",
1407                localRef, dvmGetJNIRefType(env, localRef));
1408        abortMaybe();
1409    } else {
1410        baseEnv(env)->DeleteLocalRef(env, localRef);
1411        CHECK_JNI_EXIT_VOID();
1412    }
1413}
1414
1415static jint Check_EnsureLocalCapacity(JNIEnv *env, jint capacity) {
1416    CHECK_JNI_ENTRY(kFlag_Default, "EI", env, capacity);
1417    return CHECK_JNI_EXIT("I", baseEnv(env)->EnsureLocalCapacity(env, capacity));
1418}
1419
1420static jboolean Check_IsSameObject(JNIEnv* env, jobject ref1, jobject ref2) {
1421    CHECK_JNI_ENTRY(kFlag_Default, "ELL", env, ref1, ref2);
1422    return CHECK_JNI_EXIT("b", baseEnv(env)->IsSameObject(env, ref1, ref2));
1423}
1424
1425static jobject Check_AllocObject(JNIEnv* env, jclass clazz) {
1426    CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1427    return CHECK_JNI_EXIT("L", baseEnv(env)->AllocObject(env, clazz));
1428}
1429
1430static jobject Check_NewObject(JNIEnv* env, jclass clazz, jmethodID methodID, ...) {
1431    CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
1432    va_list args;
1433    va_start(args, methodID);
1434    jobject result = baseEnv(env)->NewObjectV(env, clazz, methodID, args);
1435    va_end(args);
1436    return CHECK_JNI_EXIT("L", result);
1437}
1438
1439static jobject Check_NewObjectV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) {
1440    CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
1441    return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectV(env, clazz, methodID, args));
1442}
1443
1444static jobject Check_NewObjectA(JNIEnv* env, jclass clazz, jmethodID methodID, jvalue* args) {
1445    CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
1446    return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectA(env, clazz, methodID, args));
1447}
1448
1449static jclass Check_GetObjectClass(JNIEnv* env, jobject obj) {
1450    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1451    return CHECK_JNI_EXIT("c", baseEnv(env)->GetObjectClass(env, obj));
1452}
1453
1454static jboolean Check_IsInstanceOf(JNIEnv* env, jobject obj, jclass clazz) {
1455    CHECK_JNI_ENTRY(kFlag_Default, "ELc", env, obj, clazz);
1456    return CHECK_JNI_EXIT("b", baseEnv(env)->IsInstanceOf(env, obj, clazz));
1457}
1458
1459static jmethodID Check_GetMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1460    CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1461    return CHECK_JNI_EXIT("m", baseEnv(env)->GetMethodID(env, clazz, name, sig));
1462}
1463
1464static jfieldID Check_GetFieldID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1465    CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1466    return CHECK_JNI_EXIT("f", baseEnv(env)->GetFieldID(env, clazz, name, sig));
1467}
1468
1469static jmethodID Check_GetStaticMethodID(JNIEnv* env, jclass clazz,
1470        const char* name, const char* sig)
1471{
1472    CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1473    return CHECK_JNI_EXIT("m", baseEnv(env)->GetStaticMethodID(env, clazz, name, sig));
1474}
1475
1476static jfieldID Check_GetStaticFieldID(JNIEnv* env, jclass clazz,
1477        const char* name, const char* sig)
1478{
1479    CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1480    return CHECK_JNI_EXIT("f", baseEnv(env)->GetStaticFieldID(env, clazz, name, sig));
1481}
1482
1483#define FIELD_ACCESSORS(_ctype, _jname, _ftype, _type) \
1484    static _ctype Check_GetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fieldID) { \
1485        CHECK_JNI_ENTRY(kFlag_Default, "Ecf", env, clazz, fieldID); \
1486        sc.checkStaticFieldID(clazz, fieldID); \
1487        return CHECK_JNI_EXIT(_type, baseEnv(env)->GetStatic##_jname##Field(env, clazz, fieldID)); \
1488    } \
1489    static _ctype Check_Get##_jname##Field(JNIEnv* env, jobject obj, jfieldID fieldID) { \
1490        CHECK_JNI_ENTRY(kFlag_Default, "ELf", env, obj, fieldID); \
1491        sc.checkInstanceFieldID(obj, fieldID); \
1492        return CHECK_JNI_EXIT(_type, baseEnv(env)->Get##_jname##Field(env, obj, fieldID)); \
1493    } \
1494    static void Check_SetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fieldID, _ctype value) { \
1495        CHECK_JNI_ENTRY(kFlag_Default, "Ecf" _type, env, clazz, fieldID, value); \
1496        sc.checkStaticFieldID(clazz, fieldID); \
1497        /* "value" arg only used when type == ref */ \
1498        sc.checkFieldType((jobject)(u4)value, fieldID, _ftype, true); \
1499        baseEnv(env)->SetStatic##_jname##Field(env, clazz, fieldID, value); \
1500        CHECK_JNI_EXIT_VOID(); \
1501    } \
1502    static void Check_Set##_jname##Field(JNIEnv* env, jobject obj, jfieldID fieldID, _ctype value) { \
1503        CHECK_JNI_ENTRY(kFlag_Default, "ELf" _type, env, obj, fieldID, value); \
1504        sc.checkInstanceFieldID(obj, fieldID); \
1505        /* "value" arg only used when type == ref */ \
1506        sc.checkFieldType((jobject)(u4) value, fieldID, _ftype, false); \
1507        baseEnv(env)->Set##_jname##Field(env, obj, fieldID, value); \
1508        CHECK_JNI_EXIT_VOID(); \
1509    }
1510
1511FIELD_ACCESSORS(jobject, Object, PRIM_NOT, "L");
1512FIELD_ACCESSORS(jboolean, Boolean, PRIM_BOOLEAN, "Z");
1513FIELD_ACCESSORS(jbyte, Byte, PRIM_BYTE, "B");
1514FIELD_ACCESSORS(jchar, Char, PRIM_CHAR, "C");
1515FIELD_ACCESSORS(jshort, Short, PRIM_SHORT, "S");
1516FIELD_ACCESSORS(jint, Int, PRIM_INT, "I");
1517FIELD_ACCESSORS(jlong, Long, PRIM_LONG, "J");
1518FIELD_ACCESSORS(jfloat, Float, PRIM_FLOAT, "F");
1519FIELD_ACCESSORS(jdouble, Double, PRIM_DOUBLE, "D");
1520
1521#define CALL(_ctype, _jname, _retdecl, _retasgn, _retok, _retsig) \
1522    /* Virtual... */ \
1523    static _ctype Check_Call##_jname##Method(JNIEnv* env, jobject obj, \
1524        jmethodID methodID, ...) \
1525    { \
1526        CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
1527        sc.checkSig(methodID, _retsig, false); \
1528        sc.checkVirtualMethod(obj, methodID); \
1529        _retdecl; \
1530        va_list args; \
1531        va_start(args, methodID); \
1532        _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, methodID, args); \
1533        va_end(args); \
1534        _retok; \
1535    } \
1536    static _ctype Check_Call##_jname##MethodV(JNIEnv* env, jobject obj, \
1537        jmethodID methodID, va_list args) \
1538    { \
1539        CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
1540        sc.checkSig(methodID, _retsig, false); \
1541        sc.checkVirtualMethod(obj, methodID); \
1542        _retdecl; \
1543        _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, methodID, args); \
1544        _retok; \
1545    } \
1546    static _ctype Check_Call##_jname##MethodA(JNIEnv* env, jobject obj, \
1547        jmethodID methodID, jvalue* args) \
1548    { \
1549        CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
1550        sc.checkSig(methodID, _retsig, false); \
1551        sc.checkVirtualMethod(obj, methodID); \
1552        _retdecl; \
1553        _retasgn baseEnv(env)->Call##_jname##MethodA(env, obj, methodID, args); \
1554        _retok; \
1555    } \
1556    /* Non-virtual... */ \
1557    static _ctype Check_CallNonvirtual##_jname##Method(JNIEnv* env, \
1558        jobject obj, jclass clazz, jmethodID methodID, ...) \
1559    { \
1560        CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
1561        sc.checkSig(methodID, _retsig, false); \
1562        sc.checkVirtualMethod(obj, methodID); \
1563        _retdecl; \
1564        va_list args; \
1565        va_start(args, methodID); \
1566        _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, methodID, args); \
1567        va_end(args); \
1568        _retok; \
1569    } \
1570    static _ctype Check_CallNonvirtual##_jname##MethodV(JNIEnv* env, \
1571        jobject obj, jclass clazz, jmethodID methodID, va_list args) \
1572    { \
1573        CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
1574        sc.checkSig(methodID, _retsig, false); \
1575        sc.checkVirtualMethod(obj, methodID); \
1576        _retdecl; \
1577        _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, methodID, args); \
1578        _retok; \
1579    } \
1580    static _ctype Check_CallNonvirtual##_jname##MethodA(JNIEnv* env, \
1581        jobject obj, jclass clazz, jmethodID methodID, jvalue* args) \
1582    { \
1583        CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
1584        sc.checkSig(methodID, _retsig, false); \
1585        sc.checkVirtualMethod(obj, methodID); \
1586        _retdecl; \
1587        _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodA(env, obj, clazz, methodID, args); \
1588        _retok; \
1589    } \
1590    /* Static... */ \
1591    static _ctype Check_CallStatic##_jname##Method(JNIEnv* env, \
1592        jclass clazz, jmethodID methodID, ...) \
1593    { \
1594        CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
1595        sc.checkSig(methodID, _retsig, true); \
1596        sc.checkStaticMethod(clazz, methodID); \
1597        _retdecl; \
1598        va_list args; \
1599        va_start(args, methodID); \
1600        _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, methodID, args); \
1601        va_end(args); \
1602        _retok; \
1603    } \
1604    static _ctype Check_CallStatic##_jname##MethodV(JNIEnv* env, \
1605        jclass clazz, jmethodID methodID, va_list args) \
1606    { \
1607        CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
1608        sc.checkSig(methodID, _retsig, true); \
1609        sc.checkStaticMethod(clazz, methodID); \
1610        _retdecl; \
1611        _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, methodID, args); \
1612        _retok; \
1613    } \
1614    static _ctype Check_CallStatic##_jname##MethodA(JNIEnv* env, \
1615        jclass clazz, jmethodID methodID, jvalue* args) \
1616    { \
1617        CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
1618        sc.checkSig(methodID, _retsig, true); \
1619        sc.checkStaticMethod(clazz, methodID); \
1620        _retdecl; \
1621        _retasgn baseEnv(env)->CallStatic##_jname##MethodA(env, clazz, methodID, args); \
1622        _retok; \
1623    }
1624
1625#define NON_VOID_RETURN(_retsig, _ctype) return CHECK_JNI_EXIT(_retsig, (_ctype) result)
1626#define VOID_RETURN CHECK_JNI_EXIT_VOID()
1627
1628CALL(jobject, Object, Object* result, result=(Object*), NON_VOID_RETURN("L", jobject), "L");
1629CALL(jboolean, Boolean, jboolean result, result=, NON_VOID_RETURN("Z", jboolean), "Z");
1630CALL(jbyte, Byte, jbyte result, result=, NON_VOID_RETURN("B", jbyte), "B");
1631CALL(jchar, Char, jchar result, result=, NON_VOID_RETURN("C", jchar), "C");
1632CALL(jshort, Short, jshort result, result=, NON_VOID_RETURN("S", jshort), "S");
1633CALL(jint, Int, jint result, result=, NON_VOID_RETURN("I", jint), "I");
1634CALL(jlong, Long, jlong result, result=, NON_VOID_RETURN("J", jlong), "J");
1635CALL(jfloat, Float, jfloat result, result=, NON_VOID_RETURN("F", jfloat), "F");
1636CALL(jdouble, Double, jdouble result, result=, NON_VOID_RETURN("D", jdouble), "D");
1637CALL(void, Void, , , VOID_RETURN, "V");
1638
1639static jstring Check_NewString(JNIEnv* env, const jchar* unicodeChars, jsize len) {
1640    CHECK_JNI_ENTRY(kFlag_Default, "Epz", env, unicodeChars, len);
1641    return CHECK_JNI_EXIT("s", baseEnv(env)->NewString(env, unicodeChars, len));
1642}
1643
1644static jsize Check_GetStringLength(JNIEnv* env, jstring string) {
1645    CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1646    return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringLength(env, string));
1647}
1648
1649static const jchar* Check_GetStringChars(JNIEnv* env, jstring string, jboolean* isCopy) {
1650    CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
1651    const jchar* result = baseEnv(env)->GetStringChars(env, string, isCopy);
1652    if (gDvmJni.forceCopy && result != NULL) {
1653        ScopedJniThreadState ts(env);
1654        StringObject* strObj = (StringObject*) dvmDecodeIndirectRef(env, string);
1655        int byteCount = strObj->length() * 2;
1656        result = (const jchar*) GuardedCopy::create(result, byteCount, false);
1657        if (isCopy != NULL) {
1658            *isCopy = JNI_TRUE;
1659        }
1660    }
1661    return CHECK_JNI_EXIT("p", result);
1662}
1663
1664static void Check_ReleaseStringChars(JNIEnv* env, jstring string, const jchar* chars) {
1665    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Esp", env, string, chars);
1666    sc.checkNonNull(chars);
1667    if (gDvmJni.forceCopy) {
1668        if (!GuardedCopy::check(chars, false)) {
1669            LOGE("JNI: failed guarded copy check in ReleaseStringChars");
1670            abortMaybe();
1671            return;
1672        }
1673        chars = (const jchar*) GuardedCopy::destroy((jchar*)chars);
1674    }
1675    baseEnv(env)->ReleaseStringChars(env, string, chars);
1676    CHECK_JNI_EXIT_VOID();
1677}
1678
1679static jstring Check_NewStringUTF(JNIEnv* env, const char* bytes) {
1680    CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, bytes); // TODO: show pointer and truncate string.
1681    return CHECK_JNI_EXIT("s", baseEnv(env)->NewStringUTF(env, bytes));
1682}
1683
1684static jsize Check_GetStringUTFLength(JNIEnv* env, jstring string) {
1685    CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1686    return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringUTFLength(env, string));
1687}
1688
1689static const char* Check_GetStringUTFChars(JNIEnv* env, jstring string, jboolean* isCopy) {
1690    CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
1691    const char* result = baseEnv(env)->GetStringUTFChars(env, string, isCopy);
1692    if (gDvmJni.forceCopy && result != NULL) {
1693        result = (const char*) GuardedCopy::create(result, strlen(result) + 1, false);
1694        if (isCopy != NULL) {
1695            *isCopy = JNI_TRUE;
1696        }
1697    }
1698    return CHECK_JNI_EXIT("u", result); // TODO: show pointer and truncate string.
1699}
1700
1701static void Check_ReleaseStringUTFChars(JNIEnv* env, jstring string, const char* utf) {
1702    CHECK_JNI_ENTRY(kFlag_ExcepOkay | kFlag_Release, "Esu", env, string, utf); // TODO: show pointer and truncate string.
1703    if (gDvmJni.forceCopy) {
1704        if (!GuardedCopy::check(utf, false)) {
1705            LOGE("JNI: failed guarded copy check in ReleaseStringUTFChars");
1706            abortMaybe();
1707            return;
1708        }
1709        utf = (const char*) GuardedCopy::destroy((char*)utf);
1710    }
1711    baseEnv(env)->ReleaseStringUTFChars(env, string, utf);
1712    CHECK_JNI_EXIT_VOID();
1713}
1714
1715static jsize Check_GetArrayLength(JNIEnv* env, jarray array) {
1716    CHECK_JNI_ENTRY(kFlag_CritOkay, "Ea", env, array);
1717    return CHECK_JNI_EXIT("I", baseEnv(env)->GetArrayLength(env, array));
1718}
1719
1720static jobjectArray Check_NewObjectArray(JNIEnv* env, jsize length,
1721        jclass elementClass, jobject initialElement)
1722{
1723    CHECK_JNI_ENTRY(kFlag_Default, "EzcL", env, length, elementClass, initialElement);
1724    return CHECK_JNI_EXIT("a", baseEnv(env)->NewObjectArray(env, length, elementClass, initialElement));
1725}
1726
1727static jobject Check_GetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index) {
1728    CHECK_JNI_ENTRY(kFlag_Default, "EaI", env, array, index);
1729    return CHECK_JNI_EXIT("L", baseEnv(env)->GetObjectArrayElement(env, array, index));
1730}
1731
1732static void Check_SetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, jobject value)
1733{
1734    CHECK_JNI_ENTRY(kFlag_Default, "EaIL", env, array, index, value);
1735    baseEnv(env)->SetObjectArrayElement(env, array, index, value);
1736    CHECK_JNI_EXIT_VOID();
1737}
1738
1739#define NEW_PRIMITIVE_ARRAY(_artype, _jname) \
1740    static _artype Check_New##_jname##Array(JNIEnv* env, jsize length) { \
1741        CHECK_JNI_ENTRY(kFlag_Default, "Ez", env, length); \
1742        return CHECK_JNI_EXIT("a", baseEnv(env)->New##_jname##Array(env, length)); \
1743    }
1744NEW_PRIMITIVE_ARRAY(jbooleanArray, Boolean);
1745NEW_PRIMITIVE_ARRAY(jbyteArray, Byte);
1746NEW_PRIMITIVE_ARRAY(jcharArray, Char);
1747NEW_PRIMITIVE_ARRAY(jshortArray, Short);
1748NEW_PRIMITIVE_ARRAY(jintArray, Int);
1749NEW_PRIMITIVE_ARRAY(jlongArray, Long);
1750NEW_PRIMITIVE_ARRAY(jfloatArray, Float);
1751NEW_PRIMITIVE_ARRAY(jdoubleArray, Double);
1752
1753
1754/*
1755 * Hack to allow forcecopy to work with jniGetNonMovableArrayElements.
1756 * The code deliberately uses an invalid sequence of operations, so we
1757 * need to pass it through unmodified.  Review that code before making
1758 * any changes here.
1759 */
1760#define kNoCopyMagic    0xd5aab57f
1761
1762#define GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1763    static _ctype* Check_Get##_jname##ArrayElements(JNIEnv* env, \
1764        _ctype##Array array, jboolean* isCopy) \
1765    { \
1766        CHECK_JNI_ENTRY(kFlag_Default, "Eap", env, array, isCopy); \
1767        u4 noCopy = 0; \
1768        if (gDvmJni.forceCopy && isCopy != NULL) { \
1769            /* capture this before the base call tramples on it */ \
1770            noCopy = *(u4*) isCopy; \
1771        } \
1772        _ctype* result = baseEnv(env)->Get##_jname##ArrayElements(env, array, isCopy); \
1773        if (gDvmJni.forceCopy && result != NULL) { \
1774            if (noCopy == kNoCopyMagic) { \
1775                LOGV("FC: not copying %p %x", array, noCopy); \
1776            } else { \
1777                result = (_ctype*) createGuardedPACopy(env, array, isCopy); \
1778            } \
1779        } \
1780        return CHECK_JNI_EXIT("p", result); \
1781    }
1782
1783#define RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1784    static void Check_Release##_jname##ArrayElements(JNIEnv* env, \
1785        _ctype##Array array, _ctype* elems, jint mode) \
1786    { \
1787        CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Eapr", env, array, elems, mode); \
1788        sc.checkNonNull(elems); \
1789        if (gDvmJni.forceCopy) { \
1790            if ((uintptr_t)elems == kNoCopyMagic) { \
1791                LOGV("FC: not freeing %p", array); \
1792                elems = NULL;   /* base JNI call doesn't currently need */ \
1793            } else { \
1794                elems = (_ctype*) releaseGuardedPACopy(env, array, elems, mode); \
1795            } \
1796        } \
1797        baseEnv(env)->Release##_jname##ArrayElements(env, array, elems, mode); \
1798        CHECK_JNI_EXIT_VOID(); \
1799    }
1800
1801#define GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1802    static void Check_Get##_jname##ArrayRegion(JNIEnv* env, \
1803            _ctype##Array array, jsize start, jsize len, _ctype* buf) { \
1804        CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1805        baseEnv(env)->Get##_jname##ArrayRegion(env, array, start, len, buf); \
1806        CHECK_JNI_EXIT_VOID(); \
1807    }
1808
1809#define SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1810    static void Check_Set##_jname##ArrayRegion(JNIEnv* env, \
1811            _ctype##Array array, jsize start, jsize len, const _ctype* buf) { \
1812        CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1813        baseEnv(env)->Set##_jname##ArrayRegion(env, array, start, len, buf); \
1814        CHECK_JNI_EXIT_VOID(); \
1815    }
1816
1817#define PRIMITIVE_ARRAY_FUNCTIONS(_ctype, _jname, _typechar) \
1818    GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1819    RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1820    GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname); \
1821    SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname);
1822
1823/* TODO: verify primitive array type matches call type */
1824PRIMITIVE_ARRAY_FUNCTIONS(jboolean, Boolean, 'Z');
1825PRIMITIVE_ARRAY_FUNCTIONS(jbyte, Byte, 'B');
1826PRIMITIVE_ARRAY_FUNCTIONS(jchar, Char, 'C');
1827PRIMITIVE_ARRAY_FUNCTIONS(jshort, Short, 'S');
1828PRIMITIVE_ARRAY_FUNCTIONS(jint, Int, 'I');
1829PRIMITIVE_ARRAY_FUNCTIONS(jlong, Long, 'J');
1830PRIMITIVE_ARRAY_FUNCTIONS(jfloat, Float, 'F');
1831PRIMITIVE_ARRAY_FUNCTIONS(jdouble, Double, 'D');
1832
1833static jint Check_RegisterNatives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods,
1834        jint nMethods)
1835{
1836    CHECK_JNI_ENTRY(kFlag_Default, "EcpI", env, clazz, methods, nMethods);
1837    return CHECK_JNI_EXIT("I", baseEnv(env)->RegisterNatives(env, clazz, methods, nMethods));
1838}
1839
1840static jint Check_UnregisterNatives(JNIEnv* env, jclass clazz) {
1841    CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1842    return CHECK_JNI_EXIT("I", baseEnv(env)->UnregisterNatives(env, clazz));
1843}
1844
1845static jint Check_MonitorEnter(JNIEnv* env, jobject obj) {
1846    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1847    return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorEnter(env, obj));
1848}
1849
1850static jint Check_MonitorExit(JNIEnv* env, jobject obj) {
1851    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
1852    return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorExit(env, obj));
1853}
1854
1855static jint Check_GetJavaVM(JNIEnv *env, JavaVM **vm) {
1856    CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, vm);
1857    return CHECK_JNI_EXIT("I", baseEnv(env)->GetJavaVM(env, vm));
1858}
1859
1860static void Check_GetStringRegion(JNIEnv* env, jstring str, jsize start, jsize len, jchar* buf) {
1861    CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1862    baseEnv(env)->GetStringRegion(env, str, start, len, buf);
1863    CHECK_JNI_EXIT_VOID();
1864}
1865
1866static void Check_GetStringUTFRegion(JNIEnv* env, jstring str, jsize start, jsize len, char* buf) {
1867    CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1868    baseEnv(env)->GetStringUTFRegion(env, str, start, len, buf);
1869    CHECK_JNI_EXIT_VOID();
1870}
1871
1872static void* Check_GetPrimitiveArrayCritical(JNIEnv* env, jarray array, jboolean* isCopy) {
1873    CHECK_JNI_ENTRY(kFlag_CritGet, "Eap", env, array, isCopy);
1874    void* result = baseEnv(env)->GetPrimitiveArrayCritical(env, array, isCopy);
1875    if (gDvmJni.forceCopy && result != NULL) {
1876        result = createGuardedPACopy(env, array, isCopy);
1877    }
1878    return CHECK_JNI_EXIT("p", result);
1879}
1880
1881static void Check_ReleasePrimitiveArrayCritical(JNIEnv* env, jarray array, void* carray, jint mode)
1882{
1883    CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Eapr", env, array, carray, mode);
1884    sc.checkNonNull(carray);
1885    if (gDvmJni.forceCopy) {
1886        carray = releaseGuardedPACopy(env, array, carray, mode);
1887    }
1888    baseEnv(env)->ReleasePrimitiveArrayCritical(env, array, carray, mode);
1889    CHECK_JNI_EXIT_VOID();
1890}
1891
1892static const jchar* Check_GetStringCritical(JNIEnv* env, jstring string, jboolean* isCopy) {
1893    CHECK_JNI_ENTRY(kFlag_CritGet, "Esp", env, string, isCopy);
1894    const jchar* result = baseEnv(env)->GetStringCritical(env, string, isCopy);
1895    if (gDvmJni.forceCopy && result != NULL) {
1896        ScopedJniThreadState ts(env);
1897        StringObject* strObj = (StringObject*) dvmDecodeIndirectRef(env, string);
1898        int byteCount = strObj->length() * 2;
1899        result = (const jchar*) GuardedCopy::create(result, byteCount, false);
1900        if (isCopy != NULL) {
1901            *isCopy = JNI_TRUE;
1902        }
1903    }
1904    return CHECK_JNI_EXIT("p", result);
1905}
1906
1907static void Check_ReleaseStringCritical(JNIEnv* env, jstring string, const jchar* carray) {
1908    CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Esp", env, string, carray);
1909    sc.checkNonNull(carray);
1910    if (gDvmJni.forceCopy) {
1911        if (!GuardedCopy::check(carray, false)) {
1912            LOGE("JNI: failed guarded copy check in ReleaseStringCritical");
1913            abortMaybe();
1914            return;
1915        }
1916        carray = (const jchar*) GuardedCopy::destroy((jchar*)carray);
1917    }
1918    baseEnv(env)->ReleaseStringCritical(env, string, carray);
1919    CHECK_JNI_EXIT_VOID();
1920}
1921
1922static jweak Check_NewWeakGlobalRef(JNIEnv* env, jobject obj) {
1923    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1924    return CHECK_JNI_EXIT("L", baseEnv(env)->NewWeakGlobalRef(env, obj));
1925}
1926
1927static void Check_DeleteWeakGlobalRef(JNIEnv* env, jweak obj) {
1928    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
1929    baseEnv(env)->DeleteWeakGlobalRef(env, obj);
1930    CHECK_JNI_EXIT_VOID();
1931}
1932
1933static jboolean Check_ExceptionCheck(JNIEnv* env) {
1934    CHECK_JNI_ENTRY(kFlag_CritOkay | kFlag_ExcepOkay, "E", env);
1935    return CHECK_JNI_EXIT("b", baseEnv(env)->ExceptionCheck(env));
1936}
1937
1938static jobjectRefType Check_GetObjectRefType(JNIEnv* env, jobject obj) {
1939    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1940    // TODO: proper decoding of jobjectRefType!
1941    return CHECK_JNI_EXIT("I", baseEnv(env)->GetObjectRefType(env, obj));
1942}
1943
1944static jobject Check_NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
1945    CHECK_JNI_ENTRY(kFlag_Default, "EpJ", env, address, capacity);
1946    if (address == NULL || capacity < 0) {
1947        LOGW("JNI WARNING: invalid values for address (%p) or capacity (%ld)",
1948            address, (long) capacity);
1949        abortMaybe();
1950        return NULL;
1951    }
1952    return CHECK_JNI_EXIT("L", baseEnv(env)->NewDirectByteBuffer(env, address, capacity));
1953}
1954
1955static void* Check_GetDirectBufferAddress(JNIEnv* env, jobject buf) {
1956    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1957    // TODO: check that 'buf' is a java.nio.Buffer.
1958    return CHECK_JNI_EXIT("p", baseEnv(env)->GetDirectBufferAddress(env, buf));
1959}
1960
1961static jlong Check_GetDirectBufferCapacity(JNIEnv* env, jobject buf) {
1962    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1963    // TODO: check that 'buf' is a java.nio.Buffer.
1964    return CHECK_JNI_EXIT("J", baseEnv(env)->GetDirectBufferCapacity(env, buf));
1965}
1966
1967
1968/*
1969 * ===========================================================================
1970 *      JNI invocation functions
1971 * ===========================================================================
1972 */
1973
1974static jint Check_DestroyJavaVM(JavaVM* vm) {
1975    ScopedCheck sc(false, __FUNCTION__);
1976    sc.check(true, "v", vm);
1977    return CHECK_JNI_EXIT("I", baseVm(vm)->DestroyJavaVM(vm));
1978}
1979
1980static jint Check_AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
1981    ScopedCheck sc(false, __FUNCTION__);
1982    sc.check(true, "vpp", vm, p_env, thr_args);
1983    return CHECK_JNI_EXIT("I", baseVm(vm)->AttachCurrentThread(vm, p_env, thr_args));
1984}
1985
1986static jint Check_AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
1987    ScopedCheck sc(false, __FUNCTION__);
1988    sc.check(true, "vpp", vm, p_env, thr_args);
1989    return CHECK_JNI_EXIT("I", baseVm(vm)->AttachCurrentThreadAsDaemon(vm, p_env, thr_args));
1990}
1991
1992static jint Check_DetachCurrentThread(JavaVM* vm) {
1993    ScopedCheck sc(true, __FUNCTION__);
1994    sc.check(true, "v", vm);
1995    return CHECK_JNI_EXIT("I", baseVm(vm)->DetachCurrentThread(vm));
1996}
1997
1998static jint Check_GetEnv(JavaVM* vm, void** env, jint version) {
1999    ScopedCheck sc(true, __FUNCTION__);
2000    sc.check(true, "v", vm);
2001    return CHECK_JNI_EXIT("I", baseVm(vm)->GetEnv(vm, env, version));
2002}
2003
2004
2005/*
2006 * ===========================================================================
2007 *      Function tables
2008 * ===========================================================================
2009 */
2010
2011static const struct JNINativeInterface gCheckNativeInterface = {
2012    NULL,
2013    NULL,
2014    NULL,
2015    NULL,
2016
2017    Check_GetVersion,
2018
2019    Check_DefineClass,
2020    Check_FindClass,
2021
2022    Check_FromReflectedMethod,
2023    Check_FromReflectedField,
2024    Check_ToReflectedMethod,
2025
2026    Check_GetSuperclass,
2027    Check_IsAssignableFrom,
2028
2029    Check_ToReflectedField,
2030
2031    Check_Throw,
2032    Check_ThrowNew,
2033    Check_ExceptionOccurred,
2034    Check_ExceptionDescribe,
2035    Check_ExceptionClear,
2036    Check_FatalError,
2037
2038    Check_PushLocalFrame,
2039    Check_PopLocalFrame,
2040
2041    Check_NewGlobalRef,
2042    Check_DeleteGlobalRef,
2043    Check_DeleteLocalRef,
2044    Check_IsSameObject,
2045    Check_NewLocalRef,
2046    Check_EnsureLocalCapacity,
2047
2048    Check_AllocObject,
2049    Check_NewObject,
2050    Check_NewObjectV,
2051    Check_NewObjectA,
2052
2053    Check_GetObjectClass,
2054    Check_IsInstanceOf,
2055
2056    Check_GetMethodID,
2057
2058    Check_CallObjectMethod,
2059    Check_CallObjectMethodV,
2060    Check_CallObjectMethodA,
2061    Check_CallBooleanMethod,
2062    Check_CallBooleanMethodV,
2063    Check_CallBooleanMethodA,
2064    Check_CallByteMethod,
2065    Check_CallByteMethodV,
2066    Check_CallByteMethodA,
2067    Check_CallCharMethod,
2068    Check_CallCharMethodV,
2069    Check_CallCharMethodA,
2070    Check_CallShortMethod,
2071    Check_CallShortMethodV,
2072    Check_CallShortMethodA,
2073    Check_CallIntMethod,
2074    Check_CallIntMethodV,
2075    Check_CallIntMethodA,
2076    Check_CallLongMethod,
2077    Check_CallLongMethodV,
2078    Check_CallLongMethodA,
2079    Check_CallFloatMethod,
2080    Check_CallFloatMethodV,
2081    Check_CallFloatMethodA,
2082    Check_CallDoubleMethod,
2083    Check_CallDoubleMethodV,
2084    Check_CallDoubleMethodA,
2085    Check_CallVoidMethod,
2086    Check_CallVoidMethodV,
2087    Check_CallVoidMethodA,
2088
2089    Check_CallNonvirtualObjectMethod,
2090    Check_CallNonvirtualObjectMethodV,
2091    Check_CallNonvirtualObjectMethodA,
2092    Check_CallNonvirtualBooleanMethod,
2093    Check_CallNonvirtualBooleanMethodV,
2094    Check_CallNonvirtualBooleanMethodA,
2095    Check_CallNonvirtualByteMethod,
2096    Check_CallNonvirtualByteMethodV,
2097    Check_CallNonvirtualByteMethodA,
2098    Check_CallNonvirtualCharMethod,
2099    Check_CallNonvirtualCharMethodV,
2100    Check_CallNonvirtualCharMethodA,
2101    Check_CallNonvirtualShortMethod,
2102    Check_CallNonvirtualShortMethodV,
2103    Check_CallNonvirtualShortMethodA,
2104    Check_CallNonvirtualIntMethod,
2105    Check_CallNonvirtualIntMethodV,
2106    Check_CallNonvirtualIntMethodA,
2107    Check_CallNonvirtualLongMethod,
2108    Check_CallNonvirtualLongMethodV,
2109    Check_CallNonvirtualLongMethodA,
2110    Check_CallNonvirtualFloatMethod,
2111    Check_CallNonvirtualFloatMethodV,
2112    Check_CallNonvirtualFloatMethodA,
2113    Check_CallNonvirtualDoubleMethod,
2114    Check_CallNonvirtualDoubleMethodV,
2115    Check_CallNonvirtualDoubleMethodA,
2116    Check_CallNonvirtualVoidMethod,
2117    Check_CallNonvirtualVoidMethodV,
2118    Check_CallNonvirtualVoidMethodA,
2119
2120    Check_GetFieldID,
2121
2122    Check_GetObjectField,
2123    Check_GetBooleanField,
2124    Check_GetByteField,
2125    Check_GetCharField,
2126    Check_GetShortField,
2127    Check_GetIntField,
2128    Check_GetLongField,
2129    Check_GetFloatField,
2130    Check_GetDoubleField,
2131    Check_SetObjectField,
2132    Check_SetBooleanField,
2133    Check_SetByteField,
2134    Check_SetCharField,
2135    Check_SetShortField,
2136    Check_SetIntField,
2137    Check_SetLongField,
2138    Check_SetFloatField,
2139    Check_SetDoubleField,
2140
2141    Check_GetStaticMethodID,
2142
2143    Check_CallStaticObjectMethod,
2144    Check_CallStaticObjectMethodV,
2145    Check_CallStaticObjectMethodA,
2146    Check_CallStaticBooleanMethod,
2147    Check_CallStaticBooleanMethodV,
2148    Check_CallStaticBooleanMethodA,
2149    Check_CallStaticByteMethod,
2150    Check_CallStaticByteMethodV,
2151    Check_CallStaticByteMethodA,
2152    Check_CallStaticCharMethod,
2153    Check_CallStaticCharMethodV,
2154    Check_CallStaticCharMethodA,
2155    Check_CallStaticShortMethod,
2156    Check_CallStaticShortMethodV,
2157    Check_CallStaticShortMethodA,
2158    Check_CallStaticIntMethod,
2159    Check_CallStaticIntMethodV,
2160    Check_CallStaticIntMethodA,
2161    Check_CallStaticLongMethod,
2162    Check_CallStaticLongMethodV,
2163    Check_CallStaticLongMethodA,
2164    Check_CallStaticFloatMethod,
2165    Check_CallStaticFloatMethodV,
2166    Check_CallStaticFloatMethodA,
2167    Check_CallStaticDoubleMethod,
2168    Check_CallStaticDoubleMethodV,
2169    Check_CallStaticDoubleMethodA,
2170    Check_CallStaticVoidMethod,
2171    Check_CallStaticVoidMethodV,
2172    Check_CallStaticVoidMethodA,
2173
2174    Check_GetStaticFieldID,
2175
2176    Check_GetStaticObjectField,
2177    Check_GetStaticBooleanField,
2178    Check_GetStaticByteField,
2179    Check_GetStaticCharField,
2180    Check_GetStaticShortField,
2181    Check_GetStaticIntField,
2182    Check_GetStaticLongField,
2183    Check_GetStaticFloatField,
2184    Check_GetStaticDoubleField,
2185
2186    Check_SetStaticObjectField,
2187    Check_SetStaticBooleanField,
2188    Check_SetStaticByteField,
2189    Check_SetStaticCharField,
2190    Check_SetStaticShortField,
2191    Check_SetStaticIntField,
2192    Check_SetStaticLongField,
2193    Check_SetStaticFloatField,
2194    Check_SetStaticDoubleField,
2195
2196    Check_NewString,
2197
2198    Check_GetStringLength,
2199    Check_GetStringChars,
2200    Check_ReleaseStringChars,
2201
2202    Check_NewStringUTF,
2203    Check_GetStringUTFLength,
2204    Check_GetStringUTFChars,
2205    Check_ReleaseStringUTFChars,
2206
2207    Check_GetArrayLength,
2208    Check_NewObjectArray,
2209    Check_GetObjectArrayElement,
2210    Check_SetObjectArrayElement,
2211
2212    Check_NewBooleanArray,
2213    Check_NewByteArray,
2214    Check_NewCharArray,
2215    Check_NewShortArray,
2216    Check_NewIntArray,
2217    Check_NewLongArray,
2218    Check_NewFloatArray,
2219    Check_NewDoubleArray,
2220
2221    Check_GetBooleanArrayElements,
2222    Check_GetByteArrayElements,
2223    Check_GetCharArrayElements,
2224    Check_GetShortArrayElements,
2225    Check_GetIntArrayElements,
2226    Check_GetLongArrayElements,
2227    Check_GetFloatArrayElements,
2228    Check_GetDoubleArrayElements,
2229
2230    Check_ReleaseBooleanArrayElements,
2231    Check_ReleaseByteArrayElements,
2232    Check_ReleaseCharArrayElements,
2233    Check_ReleaseShortArrayElements,
2234    Check_ReleaseIntArrayElements,
2235    Check_ReleaseLongArrayElements,
2236    Check_ReleaseFloatArrayElements,
2237    Check_ReleaseDoubleArrayElements,
2238
2239    Check_GetBooleanArrayRegion,
2240    Check_GetByteArrayRegion,
2241    Check_GetCharArrayRegion,
2242    Check_GetShortArrayRegion,
2243    Check_GetIntArrayRegion,
2244    Check_GetLongArrayRegion,
2245    Check_GetFloatArrayRegion,
2246    Check_GetDoubleArrayRegion,
2247    Check_SetBooleanArrayRegion,
2248    Check_SetByteArrayRegion,
2249    Check_SetCharArrayRegion,
2250    Check_SetShortArrayRegion,
2251    Check_SetIntArrayRegion,
2252    Check_SetLongArrayRegion,
2253    Check_SetFloatArrayRegion,
2254    Check_SetDoubleArrayRegion,
2255
2256    Check_RegisterNatives,
2257    Check_UnregisterNatives,
2258
2259    Check_MonitorEnter,
2260    Check_MonitorExit,
2261
2262    Check_GetJavaVM,
2263
2264    Check_GetStringRegion,
2265    Check_GetStringUTFRegion,
2266
2267    Check_GetPrimitiveArrayCritical,
2268    Check_ReleasePrimitiveArrayCritical,
2269
2270    Check_GetStringCritical,
2271    Check_ReleaseStringCritical,
2272
2273    Check_NewWeakGlobalRef,
2274    Check_DeleteWeakGlobalRef,
2275
2276    Check_ExceptionCheck,
2277
2278    Check_NewDirectByteBuffer,
2279    Check_GetDirectBufferAddress,
2280    Check_GetDirectBufferCapacity,
2281
2282    Check_GetObjectRefType
2283};
2284
2285static const struct JNIInvokeInterface gCheckInvokeInterface = {
2286    NULL,
2287    NULL,
2288    NULL,
2289
2290    Check_DestroyJavaVM,
2291    Check_AttachCurrentThread,
2292    Check_DetachCurrentThread,
2293
2294    Check_GetEnv,
2295
2296    Check_AttachCurrentThreadAsDaemon,
2297};
2298
2299/*
2300 * Replace the normal table with the checked table.
2301 */
2302void dvmUseCheckedJniEnv(JNIEnvExt* pEnv) {
2303    assert(pEnv->funcTable != &gCheckNativeInterface);
2304    pEnv->baseFuncTable = pEnv->funcTable;
2305    pEnv->funcTable = &gCheckNativeInterface;
2306}
2307
2308/*
2309 * Replace the normal table with the checked table.
2310 */
2311void dvmUseCheckedJniVm(JavaVMExt* pVm) {
2312    assert(pVm->funcTable != &gCheckInvokeInterface);
2313    pVm->baseFuncTable = pVm->funcTable;
2314    pVm->funcTable = &gCheckInvokeInterface;
2315}
2316