CheckJni.cpp revision 8bc8bf71a52e17d483021b4c9dc8e735d9bce3ed
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 && !dvmIsHeapAddress(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 (!dvmIsHeapAddress(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 || !dvmIsHeapAddress(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        if (!dvmIsHeapAddress(obj)) {
706            LOGW("JNI WARNING: jarray is an invalid %s reference (%p)",
707            indirectRefKindName(jarr), jarr);
708            printWarn = true;
709        } else if (obj->clazz->descriptor[0] != '[') {
710            LOGW("JNI WARNING: jarray arg has wrong type (expected array, got %s)",
711            obj->clazz->descriptor);
712            printWarn = true;
713        }
714
715        if (printWarn) {
716            showLocation();
717            abortMaybe();
718        }
719    }
720
721    void checkClass(jclass c) {
722        checkInstance(c, gDvm.classJavaLangClass, "jclass");
723    }
724
725    void checkLengthPositive(jsize length) {
726        if (length < 0) {
727            LOGW("JNI WARNING: negative jsize (%s)", mFunctionName);
728            abortMaybe();
729        }
730    }
731
732    /*
733     * Verify that "jobj" is a valid object, and that it's an object that JNI
734     * is allowed to know about.  We allow NULL references.
735     *
736     * Switches to "running" mode before performing checks.
737     */
738    void checkObject(jobject jobj) {
739        if (jobj == NULL) {
740            return;
741        }
742
743        ScopedJniThreadState ts(mEnv);
744
745        bool printWarn = false;
746        if (dvmGetJNIRefType(mEnv, jobj) == JNIInvalidRefType) {
747            LOGW("JNI WARNING: %p is not a valid JNI reference", jobj);
748            printWarn = true;
749        } else {
750            Object* obj = dvmDecodeIndirectRef(mEnv, jobj);
751            if (obj == kInvalidIndirectRefObject) {
752                LOGW("JNI WARNING: native code passing in invalid reference %p", jobj);
753                printWarn = true;
754            } else if (obj != NULL && !dvmIsHeapAddress(obj)) {
755                // TODO: when we remove workAroundAppJniBugs, this should be impossible.
756                LOGW("JNI WARNING: native code passing in reference to invalid object %p %p",
757                        jobj, obj);
758                printWarn = true;
759            }
760        }
761
762        if (printWarn) {
763            showLocation();
764            abortMaybe();
765        }
766    }
767
768    /*
769     * Verify that the "mode" argument passed to a primitive array Release
770     * function is one of the valid values.
771     */
772    void checkReleaseMode(jint mode) {
773        if (mode != 0 && mode != JNI_COMMIT && mode != JNI_ABORT) {
774            LOGW("JNI WARNING: bad value for mode (%d) (%s)", mode, mFunctionName);
775            abortMaybe();
776        }
777    }
778
779    void checkString(jstring s) {
780        checkInstance(s, gDvm.classJavaLangString, "jstring");
781    }
782
783    void checkThread(int flags) {
784        // Get the *correct* JNIEnv by going through our TLS pointer.
785        JNIEnvExt* threadEnv = dvmGetJNIEnvForThread();
786
787        /*
788         * Verify that the current thread is (a) attached and (b) associated with
789         * this particular instance of JNIEnv.
790         */
791        bool printWarn = false;
792        if (threadEnv == NULL) {
793            LOGE("JNI ERROR: non-VM thread making JNI calls");
794            // don't set printWarn -- it'll try to call showLocation()
795            dvmAbort();
796        } else if ((JNIEnvExt*) mEnv != threadEnv) {
797            if (dvmThreadSelf()->threadId != threadEnv->envThreadId) {
798                LOGE("JNI: threadEnv != thread->env?");
799                dvmAbort();
800            }
801
802            LOGW("JNI WARNING: threadid=%d using env from threadid=%d",
803                    threadEnv->envThreadId, ((JNIEnvExt*) mEnv)->envThreadId);
804            printWarn = true;
805
806            // If we're keeping broken code limping along, we need to suppress the abort...
807            if (gDvmJni.workAroundAppJniBugs) {
808                printWarn = false;
809            }
810
811            /* this is a bad idea -- need to throw as we exit, or abort func */
812            //dvmThrowRuntimeException("invalid use of JNI env ptr");
813        } else if (((JNIEnvExt*) mEnv)->self != dvmThreadSelf()) {
814            /* correct JNIEnv*; make sure the "self" pointer is correct */
815            LOGE("JNI ERROR: env->self != thread-self (%p vs. %p)",
816                    ((JNIEnvExt*) mEnv)->self, dvmThreadSelf());
817            dvmAbort();
818        }
819
820        /*
821         * Verify that, if this thread previously made a critical "get" call, we
822         * do the corresponding "release" call before we try anything else.
823         */
824        switch (flags & kFlag_CritMask) {
825        case kFlag_CritOkay:    // okay to call this method
826            break;
827        case kFlag_CritBad:     // not okay to call
828            if (threadEnv->critical) {
829                LOGW("JNI WARNING: threadid=%d using JNI after critical get",
830                        threadEnv->envThreadId);
831                printWarn = true;
832            }
833            break;
834        case kFlag_CritGet:     // this is a "get" call
835            /* don't check here; we allow nested gets */
836            threadEnv->critical++;
837            break;
838        case kFlag_CritRelease: // this is a "release" call
839            threadEnv->critical--;
840            if (threadEnv->critical < 0) {
841                LOGW("JNI WARNING: threadid=%d called too many crit releases",
842                        threadEnv->envThreadId);
843                printWarn = true;
844            }
845            break;
846        default:
847            assert(false);
848        }
849
850        /*
851         * Verify that, if an exception has been raised, the native code doesn't
852         * make any JNI calls other than the Exception* methods.
853         */
854        bool printException = false;
855        if ((flags & kFlag_ExcepOkay) == 0 && dvmCheckException(dvmThreadSelf())) {
856            LOGW("JNI WARNING: JNI method called with exception pending");
857            printWarn = true;
858            printException = true;
859        }
860
861        if (printWarn) {
862            showLocation();
863        }
864        if (printException) {
865            LOGW("Pending exception is:");
866            dvmLogExceptionStackTrace();
867        }
868        if (printWarn) {
869            abortMaybe();
870        }
871    }
872
873    /*
874     * Verify that "bytes" points to valid "modified UTF-8" data.
875     */
876    void checkUtfString(const char* bytes, bool nullable) {
877        if (bytes == NULL) {
878            if (!nullable) {
879                LOGW("JNI WARNING: non-nullable const char* was NULL");
880                showLocation();
881                abortMaybe();
882            }
883            return;
884        }
885
886        const char* errorKind = NULL;
887        u1 utf8 = checkUtfBytes(bytes, &errorKind);
888        if (errorKind != NULL) {
889            LOGW("JNI WARNING: input is not valid UTF-8: illegal %s byte %#x", errorKind, utf8);
890            LOGW("             string: '%s'", bytes);
891            showLocation();
892            abortMaybe();
893        }
894    }
895
896    /*
897     * Verify that "jobj" is a valid non-NULL object reference, and points to
898     * an instance of expectedClass.
899     *
900     * Because we're looking at an object on the GC heap, we have to switch
901     * to "running" mode before doing the checks.
902     */
903    void checkInstance(jobject jobj, ClassObject* expectedClass, const char* argName) {
904        if (jobj == NULL) {
905            LOGW("JNI WARNING: received null %s", argName);
906            showLocation();
907            abortMaybe();
908            return;
909        }
910
911        ScopedJniThreadState ts(mEnv);
912        bool printWarn = false;
913
914        Object* obj = dvmDecodeIndirectRef(mEnv, jobj);
915        if (!dvmIsHeapAddress(obj)) {
916            LOGW("JNI WARNING: %s is an invalid %s reference (%p)",
917                    argName, indirectRefKindName(jobj), jobj);
918            printWarn = true;
919        } else if (obj->clazz != expectedClass) {
920            LOGW("JNI WARNING: %s arg has wrong type (expected %s, got %s)",
921                    argName, expectedClass->descriptor, obj->clazz->descriptor);
922            printWarn = true;
923        }
924
925        if (printWarn) {
926            showLocation();
927            abortMaybe();
928        }
929    }
930
931    static u1 checkUtfBytes(const char* bytes, const char** errorKind) {
932        while (*bytes != '\0') {
933            u1 utf8 = *(bytes++);
934            // Switch on the high four bits.
935            switch (utf8 >> 4) {
936            case 0x00:
937            case 0x01:
938            case 0x02:
939            case 0x03:
940            case 0x04:
941            case 0x05:
942            case 0x06:
943            case 0x07:
944                // Bit pattern 0xxx. No need for any extra bytes.
945                break;
946            case 0x08:
947            case 0x09:
948            case 0x0a:
949            case 0x0b:
950            case 0x0f:
951                /*
952                 * Bit pattern 10xx or 1111, which are illegal start bytes.
953                 * Note: 1111 is valid for normal UTF-8, but not the
954                 * modified UTF-8 used here.
955                 */
956                *errorKind = "start";
957                return utf8;
958            case 0x0e:
959                // Bit pattern 1110, so there are two additional bytes.
960                utf8 = *(bytes++);
961                if ((utf8 & 0xc0) != 0x80) {
962                    *errorKind = "continuation";
963                    return utf8;
964                }
965                // Fall through to take care of the final byte.
966            case 0x0c:
967            case 0x0d:
968                // Bit pattern 110x, so there is one additional byte.
969                utf8 = *(bytes++);
970                if ((utf8 & 0xc0) != 0x80) {
971                    *errorKind = "continuation";
972                    return utf8;
973                }
974                break;
975            }
976        }
977        return 0;
978    }
979
980    /**
981     * Returns a human-readable name for the given primitive type.
982     */
983    static const char* primitiveTypeToName(PrimitiveType primType) {
984        switch (primType) {
985        case PRIM_VOID:    return "void";
986        case PRIM_BOOLEAN: return "boolean";
987        case PRIM_BYTE:    return "byte";
988        case PRIM_SHORT:   return "short";
989        case PRIM_CHAR:    return "char";
990        case PRIM_INT:     return "int";
991        case PRIM_LONG:    return "long";
992        case PRIM_FLOAT:   return "float";
993        case PRIM_DOUBLE:  return "double";
994        case PRIM_NOT:     return "Object/array";
995        default:           return "???";
996        }
997    }
998
999    void showLocation() {
1000        const Method* method = dvmGetCurrentJNIMethod();
1001        char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
1002        LOGW("             in %s.%s:%s (%s)", method->clazz->descriptor, method->name, desc, mFunctionName);
1003        free(desc);
1004    }
1005
1006    // Disallow copy and assignment.
1007    ScopedCheck(const ScopedCheck&);
1008    void operator=(const ScopedCheck&);
1009};
1010
1011/*
1012 * ===========================================================================
1013 *      Guarded arrays
1014 * ===========================================================================
1015 */
1016
1017#define kGuardLen       512         /* must be multiple of 2 */
1018#define kGuardPattern   0xd5e3      /* uncommon values; d5e3d5e3 invalid addr */
1019#define kGuardMagic     0xffd5aa96
1020
1021/* this gets tucked in at the start of the buffer; struct size must be even */
1022struct GuardedCopy {
1023    u4          magic;
1024    uLong       adler;
1025    size_t      originalLen;
1026    const void* originalPtr;
1027
1028    /* find the GuardedCopy given the pointer into the "live" data */
1029    static inline const GuardedCopy* fromData(const void* dataBuf) {
1030        return reinterpret_cast<const GuardedCopy*>(actualBuffer(dataBuf));
1031    }
1032
1033    /*
1034     * Create an over-sized buffer to hold the contents of "buf".  Copy it in,
1035     * filling in the area around it with guard data.
1036     *
1037     * We use a 16-bit pattern to make a rogue memset less likely to elude us.
1038     */
1039    static void* create(const void* buf, size_t len, bool modOkay) {
1040        size_t newLen = actualLength(len);
1041        u1* newBuf = debugAlloc(newLen);
1042
1043        /* fill it in with a pattern */
1044        u2* pat = (u2*) newBuf;
1045        for (size_t i = 0; i < newLen / 2; i++) {
1046            *pat++ = kGuardPattern;
1047        }
1048
1049        /* copy the data in; note "len" could be zero */
1050        memcpy(newBuf + kGuardLen / 2, buf, len);
1051
1052        /* if modification is not expected, grab a checksum */
1053        uLong adler = 0;
1054        if (!modOkay) {
1055            adler = adler32(0L, Z_NULL, 0);
1056            adler = adler32(adler, (const Bytef*)buf, len);
1057            *(uLong*)newBuf = adler;
1058        }
1059
1060        GuardedCopy* pExtra = reinterpret_cast<GuardedCopy*>(newBuf);
1061        pExtra->magic = kGuardMagic;
1062        pExtra->adler = adler;
1063        pExtra->originalPtr = buf;
1064        pExtra->originalLen = len;
1065
1066        return newBuf + kGuardLen / 2;
1067    }
1068
1069    /*
1070     * Free up the guard buffer, scrub it, and return the original pointer.
1071     */
1072    static void* destroy(void* dataBuf) {
1073        const GuardedCopy* pExtra = GuardedCopy::fromData(dataBuf);
1074        void* originalPtr = (void*) pExtra->originalPtr;
1075        size_t len = pExtra->originalLen;
1076        debugFree(dataBuf, len);
1077        return originalPtr;
1078    }
1079
1080    /*
1081     * Verify the guard area and, if "modOkay" is false, that the data itself
1082     * has not been altered.
1083     *
1084     * The caller has already checked that "dataBuf" is non-NULL.
1085     */
1086    static bool check(const void* dataBuf, bool modOkay) {
1087        static const u4 kMagicCmp = kGuardMagic;
1088        const u1* fullBuf = actualBuffer(dataBuf);
1089        const GuardedCopy* pExtra = GuardedCopy::fromData(dataBuf);
1090
1091        /*
1092         * Before we do anything with "pExtra", check the magic number.  We
1093         * do the check with memcmp rather than "==" in case the pointer is
1094         * unaligned.  If it points to completely bogus memory we're going
1095         * to crash, but there's no easy way around that.
1096         */
1097        if (memcmp(&pExtra->magic, &kMagicCmp, 4) != 0) {
1098            u1 buf[4];
1099            memcpy(buf, &pExtra->magic, 4);
1100            LOGE("JNI: guard magic does not match (found 0x%02x%02x%02x%02x) -- incorrect data pointer %p?",
1101                    buf[3], buf[2], buf[1], buf[0], dataBuf); /* assume little endian */
1102            return false;
1103        }
1104
1105        size_t len = pExtra->originalLen;
1106
1107        /* check bottom half of guard; skip over optional checksum storage */
1108        const u2* pat = (u2*) fullBuf;
1109        for (size_t i = sizeof(GuardedCopy) / 2; i < (kGuardLen / 2 - sizeof(GuardedCopy)) / 2; i++) {
1110            if (pat[i] != kGuardPattern) {
1111                LOGE("JNI: guard pattern(1) disturbed at %p + %d", fullBuf, i*2);
1112                return false;
1113            }
1114        }
1115
1116        int offset = kGuardLen / 2 + len;
1117        if (offset & 0x01) {
1118            /* odd byte; expected value depends on endian-ness of host */
1119            const u2 patSample = kGuardPattern;
1120            if (fullBuf[offset] != ((const u1*) &patSample)[1]) {
1121                LOGE("JNI: guard pattern disturbed in odd byte after %p (+%d) 0x%02x 0x%02x",
1122                        fullBuf, offset, fullBuf[offset], ((const u1*) &patSample)[1]);
1123                return false;
1124            }
1125            offset++;
1126        }
1127
1128        /* check top half of guard */
1129        pat = (u2*) (fullBuf + offset);
1130        for (size_t i = 0; i < kGuardLen / 4; i++) {
1131            if (pat[i] != kGuardPattern) {
1132                LOGE("JNI: guard pattern(2) disturbed at %p + %d", fullBuf, offset + i*2);
1133                return false;
1134            }
1135        }
1136
1137        /*
1138         * If modification is not expected, verify checksum.  Strictly speaking
1139         * this is wrong: if we told the client that we made a copy, there's no
1140         * reason they can't alter the buffer.
1141         */
1142        if (!modOkay) {
1143            uLong adler = adler32(0L, Z_NULL, 0);
1144            adler = adler32(adler, (const Bytef*)dataBuf, len);
1145            if (pExtra->adler != adler) {
1146                LOGE("JNI: buffer modified (0x%08lx vs 0x%08lx) at addr %p",
1147                        pExtra->adler, adler, dataBuf);
1148                return false;
1149            }
1150        }
1151
1152        return true;
1153    }
1154
1155private:
1156    static u1* debugAlloc(size_t len) {
1157        void* result = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
1158        if (result == MAP_FAILED) {
1159            LOGE("GuardedCopy::create mmap(%d) failed: %s", len, strerror(errno));
1160            dvmAbort();
1161        }
1162        return reinterpret_cast<u1*>(result);
1163    }
1164
1165    static void debugFree(void* dataBuf, size_t len) {
1166        u1* fullBuf = actualBuffer(dataBuf);
1167        size_t totalByteCount = actualLength(len);
1168        // TODO: we could mprotect instead, and keep the allocation around for a while.
1169        // This would be even more expensive, but it might catch more errors.
1170        // if (mprotect(fullBuf, totalByteCount, PROT_NONE) != 0) {
1171        //     LOGW("mprotect(PROT_NONE) failed: %s", strerror(errno));
1172        // }
1173        if (munmap(fullBuf, totalByteCount) != 0) {
1174            LOGW("munmap failed: %s", strerror(errno));
1175            dvmAbort();
1176        }
1177    }
1178
1179    static const u1* actualBuffer(const void* dataBuf) {
1180        return reinterpret_cast<const u1*>(dataBuf) - kGuardLen / 2;
1181    }
1182
1183    static u1* actualBuffer(void* dataBuf) {
1184        return reinterpret_cast<u1*>(dataBuf) - kGuardLen / 2;
1185    }
1186
1187    // Underlying length of a user allocation of 'length' bytes.
1188    static size_t actualLength(size_t length) {
1189        return (length + kGuardLen + 1) & ~0x01;
1190    }
1191};
1192
1193/*
1194 * Return the width, in bytes, of a primitive type.
1195 */
1196static int dvmPrimitiveTypeWidth(PrimitiveType primType) {
1197    switch (primType) {
1198        case PRIM_BOOLEAN: return 1;
1199        case PRIM_BYTE:    return 1;
1200        case PRIM_SHORT:   return 2;
1201        case PRIM_CHAR:    return 2;
1202        case PRIM_INT:     return 4;
1203        case PRIM_LONG:    return 8;
1204        case PRIM_FLOAT:   return 4;
1205        case PRIM_DOUBLE:  return 8;
1206        case PRIM_VOID:
1207        default: {
1208            assert(false);
1209            return -1;
1210        }
1211    }
1212}
1213
1214/*
1215 * Create a guarded copy of a primitive array.  Modifications to the copied
1216 * data are allowed.  Returns a pointer to the copied data.
1217 */
1218static void* createGuardedPACopy(JNIEnv* env, const jarray jarr, jboolean* isCopy) {
1219    ScopedJniThreadState ts(env);
1220
1221    ArrayObject* arrObj = (ArrayObject*) dvmDecodeIndirectRef(env, jarr);
1222    PrimitiveType primType = arrObj->clazz->elementClass->primitiveType;
1223    int len = arrObj->length * dvmPrimitiveTypeWidth(primType);
1224    void* result = GuardedCopy::create(arrObj->contents, len, true);
1225    if (isCopy != NULL) {
1226        *isCopy = JNI_TRUE;
1227    }
1228    return result;
1229}
1230
1231/*
1232 * Perform the array "release" operation, which may or may not copy data
1233 * back into the VM, and may or may not release the underlying storage.
1234 */
1235static void* releaseGuardedPACopy(JNIEnv* env, jarray jarr, void* dataBuf, int mode) {
1236    ScopedJniThreadState ts(env);
1237    ArrayObject* arrObj = (ArrayObject*) dvmDecodeIndirectRef(env, jarr);
1238
1239    if (!GuardedCopy::check(dataBuf, true)) {
1240        LOGE("JNI: failed guarded copy check in releaseGuardedPACopy");
1241        abortMaybe();
1242        return NULL;
1243    }
1244
1245    if (mode != JNI_ABORT) {
1246        size_t len = GuardedCopy::fromData(dataBuf)->originalLen;
1247        memcpy(arrObj->contents, dataBuf, len);
1248    }
1249
1250    u1* result = NULL;
1251    if (mode != JNI_COMMIT) {
1252        result = (u1*) GuardedCopy::destroy(dataBuf);
1253    } else {
1254        result = (u1*) (void*) GuardedCopy::fromData(dataBuf)->originalPtr;
1255    }
1256
1257    /* pointer is to the array contents; back up to the array object */
1258    result -= OFFSETOF_MEMBER(ArrayObject, contents);
1259    return result;
1260}
1261
1262
1263/*
1264 * ===========================================================================
1265 *      JNI functions
1266 * ===========================================================================
1267 */
1268
1269#define CHECK_JNI_ENTRY(flags, types, args...) \
1270    ScopedCheck sc(env, flags, __FUNCTION__); \
1271    sc.check(true, types, ##args)
1272
1273#define CHECK_JNI_EXIT(type, exp) ({ \
1274    typeof (exp) _rc = (exp); \
1275    sc.check(false, type, _rc); \
1276    _rc; })
1277#define CHECK_JNI_EXIT_VOID() \
1278    sc.check(false, "V")
1279
1280static jint Check_GetVersion(JNIEnv* env) {
1281    CHECK_JNI_ENTRY(kFlag_Default, "E", env);
1282    return CHECK_JNI_EXIT("I", baseEnv(env)->GetVersion(env));
1283}
1284
1285static jclass Check_DefineClass(JNIEnv* env, const char* name, jobject loader,
1286    const jbyte* buf, jsize bufLen)
1287{
1288    CHECK_JNI_ENTRY(kFlag_Default, "EuLpz", env, name, loader, buf, bufLen);
1289    sc.checkClassName(name);
1290    return CHECK_JNI_EXIT("c", baseEnv(env)->DefineClass(env, name, loader, buf, bufLen));
1291}
1292
1293static jclass Check_FindClass(JNIEnv* env, const char* name) {
1294    CHECK_JNI_ENTRY(kFlag_Default, "Eu", env, name);
1295    sc.checkClassName(name);
1296    return CHECK_JNI_EXIT("c", baseEnv(env)->FindClass(env, name));
1297}
1298
1299static jclass Check_GetSuperclass(JNIEnv* env, jclass clazz) {
1300    CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1301    return CHECK_JNI_EXIT("c", baseEnv(env)->GetSuperclass(env, clazz));
1302}
1303
1304static jboolean Check_IsAssignableFrom(JNIEnv* env, jclass clazz1, jclass clazz2) {
1305    CHECK_JNI_ENTRY(kFlag_Default, "Ecc", env, clazz1, clazz2);
1306    return CHECK_JNI_EXIT("b", baseEnv(env)->IsAssignableFrom(env, clazz1, clazz2));
1307}
1308
1309static jmethodID Check_FromReflectedMethod(JNIEnv* env, jobject method) {
1310    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, method);
1311    // TODO: check that 'field' is a java.lang.reflect.Method.
1312    return CHECK_JNI_EXIT("m", baseEnv(env)->FromReflectedMethod(env, method));
1313}
1314
1315static jfieldID Check_FromReflectedField(JNIEnv* env, jobject field) {
1316    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, field);
1317    // TODO: check that 'field' is a java.lang.reflect.Field.
1318    return CHECK_JNI_EXIT("f", baseEnv(env)->FromReflectedField(env, field));
1319}
1320
1321static jobject Check_ToReflectedMethod(JNIEnv* env, jclass cls,
1322        jmethodID methodID, jboolean isStatic)
1323{
1324    CHECK_JNI_ENTRY(kFlag_Default, "Ecmb", env, cls, methodID, isStatic);
1325    return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedMethod(env, cls, methodID, isStatic));
1326}
1327
1328static jobject Check_ToReflectedField(JNIEnv* env, jclass cls,
1329        jfieldID fieldID, jboolean isStatic)
1330{
1331    CHECK_JNI_ENTRY(kFlag_Default, "Ecfb", env, cls, fieldID, isStatic);
1332    return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedField(env, cls, fieldID, isStatic));
1333}
1334
1335static jint Check_Throw(JNIEnv* env, jthrowable obj) {
1336    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1337    // TODO: check that 'obj' is a java.lang.Throwable.
1338    return CHECK_JNI_EXIT("I", baseEnv(env)->Throw(env, obj));
1339}
1340
1341static jint Check_ThrowNew(JNIEnv* env, jclass clazz, const char* message) {
1342    CHECK_JNI_ENTRY(kFlag_NullableUtf, "Ecu", env, clazz, message);
1343    return CHECK_JNI_EXIT("I", baseEnv(env)->ThrowNew(env, clazz, message));
1344}
1345
1346static jthrowable Check_ExceptionOccurred(JNIEnv* env) {
1347    CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1348    return CHECK_JNI_EXIT("L", baseEnv(env)->ExceptionOccurred(env));
1349}
1350
1351static void Check_ExceptionDescribe(JNIEnv* env) {
1352    CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1353    baseEnv(env)->ExceptionDescribe(env);
1354    CHECK_JNI_EXIT_VOID();
1355}
1356
1357static void Check_ExceptionClear(JNIEnv* env) {
1358    CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
1359    baseEnv(env)->ExceptionClear(env);
1360    CHECK_JNI_EXIT_VOID();
1361}
1362
1363static void Check_FatalError(JNIEnv* env, const char* msg) {
1364    CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, msg);
1365    baseEnv(env)->FatalError(env, msg);
1366    CHECK_JNI_EXIT_VOID();
1367}
1368
1369static jint Check_PushLocalFrame(JNIEnv* env, jint capacity) {
1370    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EI", env, capacity);
1371    return CHECK_JNI_EXIT("I", baseEnv(env)->PushLocalFrame(env, capacity));
1372}
1373
1374static jobject Check_PopLocalFrame(JNIEnv* env, jobject res) {
1375    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, res);
1376    return CHECK_JNI_EXIT("L", baseEnv(env)->PopLocalFrame(env, res));
1377}
1378
1379static jobject Check_NewGlobalRef(JNIEnv* env, jobject obj) {
1380    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1381    return CHECK_JNI_EXIT("L", baseEnv(env)->NewGlobalRef(env, obj));
1382}
1383
1384static void Check_DeleteGlobalRef(JNIEnv* env, jobject globalRef) {
1385    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, globalRef);
1386    if (globalRef != NULL && dvmGetJNIRefType(env, globalRef) != JNIGlobalRefType) {
1387        LOGW("JNI WARNING: DeleteGlobalRef on non-global %p (type=%d)",
1388                globalRef, dvmGetJNIRefType(env, globalRef));
1389        abortMaybe();
1390    } else {
1391        baseEnv(env)->DeleteGlobalRef(env, globalRef);
1392        CHECK_JNI_EXIT_VOID();
1393    }
1394}
1395
1396static jobject Check_NewLocalRef(JNIEnv* env, jobject ref) {
1397    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, ref);
1398    return CHECK_JNI_EXIT("L", baseEnv(env)->NewLocalRef(env, ref));
1399}
1400
1401static void Check_DeleteLocalRef(JNIEnv* env, jobject localRef) {
1402    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, localRef);
1403    if (localRef != NULL && dvmGetJNIRefType(env, localRef) != JNILocalRefType) {
1404        LOGW("JNI WARNING: DeleteLocalRef on non-local %p (type=%d)",
1405                localRef, dvmGetJNIRefType(env, localRef));
1406        abortMaybe();
1407    } else {
1408        baseEnv(env)->DeleteLocalRef(env, localRef);
1409        CHECK_JNI_EXIT_VOID();
1410    }
1411}
1412
1413static jint Check_EnsureLocalCapacity(JNIEnv *env, jint capacity) {
1414    CHECK_JNI_ENTRY(kFlag_Default, "EI", env, capacity);
1415    return CHECK_JNI_EXIT("I", baseEnv(env)->EnsureLocalCapacity(env, capacity));
1416}
1417
1418static jboolean Check_IsSameObject(JNIEnv* env, jobject ref1, jobject ref2) {
1419    CHECK_JNI_ENTRY(kFlag_Default, "ELL", env, ref1, ref2);
1420    return CHECK_JNI_EXIT("b", baseEnv(env)->IsSameObject(env, ref1, ref2));
1421}
1422
1423static jobject Check_AllocObject(JNIEnv* env, jclass clazz) {
1424    CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1425    return CHECK_JNI_EXIT("L", baseEnv(env)->AllocObject(env, clazz));
1426}
1427
1428static jobject Check_NewObject(JNIEnv* env, jclass clazz, jmethodID methodID, ...) {
1429    CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
1430    va_list args;
1431    va_start(args, methodID);
1432    jobject result = baseEnv(env)->NewObjectV(env, clazz, methodID, args);
1433    va_end(args);
1434    return CHECK_JNI_EXIT("L", result);
1435}
1436
1437static jobject Check_NewObjectV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) {
1438    CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
1439    return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectV(env, clazz, methodID, args));
1440}
1441
1442static jobject Check_NewObjectA(JNIEnv* env, jclass clazz, jmethodID methodID, jvalue* args) {
1443    CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
1444    return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectA(env, clazz, methodID, args));
1445}
1446
1447static jclass Check_GetObjectClass(JNIEnv* env, jobject obj) {
1448    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1449    return CHECK_JNI_EXIT("c", baseEnv(env)->GetObjectClass(env, obj));
1450}
1451
1452static jboolean Check_IsInstanceOf(JNIEnv* env, jobject obj, jclass clazz) {
1453    CHECK_JNI_ENTRY(kFlag_Default, "ELc", env, obj, clazz);
1454    return CHECK_JNI_EXIT("b", baseEnv(env)->IsInstanceOf(env, obj, clazz));
1455}
1456
1457static jmethodID Check_GetMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1458    CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1459    return CHECK_JNI_EXIT("m", baseEnv(env)->GetMethodID(env, clazz, name, sig));
1460}
1461
1462static jfieldID Check_GetFieldID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
1463    CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1464    return CHECK_JNI_EXIT("f", baseEnv(env)->GetFieldID(env, clazz, name, sig));
1465}
1466
1467static jmethodID Check_GetStaticMethodID(JNIEnv* env, jclass clazz,
1468        const char* name, const char* sig)
1469{
1470    CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1471    return CHECK_JNI_EXIT("m", baseEnv(env)->GetStaticMethodID(env, clazz, name, sig));
1472}
1473
1474static jfieldID Check_GetStaticFieldID(JNIEnv* env, jclass clazz,
1475        const char* name, const char* sig)
1476{
1477    CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
1478    return CHECK_JNI_EXIT("f", baseEnv(env)->GetStaticFieldID(env, clazz, name, sig));
1479}
1480
1481#define FIELD_ACCESSORS(_ctype, _jname, _ftype, _type) \
1482    static _ctype Check_GetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fieldID) { \
1483        CHECK_JNI_ENTRY(kFlag_Default, "Ecf", env, clazz, fieldID); \
1484        sc.checkStaticFieldID(clazz, fieldID); \
1485        return CHECK_JNI_EXIT(_type, baseEnv(env)->GetStatic##_jname##Field(env, clazz, fieldID)); \
1486    } \
1487    static _ctype Check_Get##_jname##Field(JNIEnv* env, jobject obj, jfieldID fieldID) { \
1488        CHECK_JNI_ENTRY(kFlag_Default, "ELf", env, obj, fieldID); \
1489        sc.checkInstanceFieldID(obj, fieldID); \
1490        return CHECK_JNI_EXIT(_type, baseEnv(env)->Get##_jname##Field(env, obj, fieldID)); \
1491    } \
1492    static void Check_SetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fieldID, _ctype value) { \
1493        CHECK_JNI_ENTRY(kFlag_Default, "Ecf" _type, env, clazz, fieldID, value); \
1494        sc.checkStaticFieldID(clazz, fieldID); \
1495        /* "value" arg only used when type == ref */ \
1496        sc.checkFieldType((jobject)(u4)value, fieldID, _ftype, true); \
1497        baseEnv(env)->SetStatic##_jname##Field(env, clazz, fieldID, value); \
1498        CHECK_JNI_EXIT_VOID(); \
1499    } \
1500    static void Check_Set##_jname##Field(JNIEnv* env, jobject obj, jfieldID fieldID, _ctype value) { \
1501        CHECK_JNI_ENTRY(kFlag_Default, "ELf" _type, env, obj, fieldID, value); \
1502        sc.checkInstanceFieldID(obj, fieldID); \
1503        /* "value" arg only used when type == ref */ \
1504        sc.checkFieldType((jobject)(u4) value, fieldID, _ftype, false); \
1505        baseEnv(env)->Set##_jname##Field(env, obj, fieldID, value); \
1506        CHECK_JNI_EXIT_VOID(); \
1507    }
1508
1509FIELD_ACCESSORS(jobject, Object, PRIM_NOT, "L");
1510FIELD_ACCESSORS(jboolean, Boolean, PRIM_BOOLEAN, "Z");
1511FIELD_ACCESSORS(jbyte, Byte, PRIM_BYTE, "B");
1512FIELD_ACCESSORS(jchar, Char, PRIM_CHAR, "C");
1513FIELD_ACCESSORS(jshort, Short, PRIM_SHORT, "S");
1514FIELD_ACCESSORS(jint, Int, PRIM_INT, "I");
1515FIELD_ACCESSORS(jlong, Long, PRIM_LONG, "J");
1516FIELD_ACCESSORS(jfloat, Float, PRIM_FLOAT, "F");
1517FIELD_ACCESSORS(jdouble, Double, PRIM_DOUBLE, "D");
1518
1519#define CALL(_ctype, _jname, _retdecl, _retasgn, _retok, _retsig) \
1520    /* Virtual... */ \
1521    static _ctype Check_Call##_jname##Method(JNIEnv* env, jobject obj, \
1522        jmethodID methodID, ...) \
1523    { \
1524        CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
1525        sc.checkSig(methodID, _retsig, false); \
1526        sc.checkVirtualMethod(obj, methodID); \
1527        _retdecl; \
1528        va_list args; \
1529        va_start(args, methodID); \
1530        _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, methodID, args); \
1531        va_end(args); \
1532        _retok; \
1533    } \
1534    static _ctype Check_Call##_jname##MethodV(JNIEnv* env, jobject obj, \
1535        jmethodID methodID, va_list args) \
1536    { \
1537        CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
1538        sc.checkSig(methodID, _retsig, false); \
1539        sc.checkVirtualMethod(obj, methodID); \
1540        _retdecl; \
1541        _retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, methodID, args); \
1542        _retok; \
1543    } \
1544    static _ctype Check_Call##_jname##MethodA(JNIEnv* env, jobject obj, \
1545        jmethodID methodID, jvalue* args) \
1546    { \
1547        CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
1548        sc.checkSig(methodID, _retsig, false); \
1549        sc.checkVirtualMethod(obj, methodID); \
1550        _retdecl; \
1551        _retasgn baseEnv(env)->Call##_jname##MethodA(env, obj, methodID, args); \
1552        _retok; \
1553    } \
1554    /* Non-virtual... */ \
1555    static _ctype Check_CallNonvirtual##_jname##Method(JNIEnv* env, \
1556        jobject obj, jclass clazz, jmethodID methodID, ...) \
1557    { \
1558        CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
1559        sc.checkSig(methodID, _retsig, false); \
1560        sc.checkVirtualMethod(obj, methodID); \
1561        _retdecl; \
1562        va_list args; \
1563        va_start(args, methodID); \
1564        _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, methodID, args); \
1565        va_end(args); \
1566        _retok; \
1567    } \
1568    static _ctype Check_CallNonvirtual##_jname##MethodV(JNIEnv* env, \
1569        jobject obj, jclass clazz, jmethodID methodID, va_list args) \
1570    { \
1571        CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
1572        sc.checkSig(methodID, _retsig, false); \
1573        sc.checkVirtualMethod(obj, methodID); \
1574        _retdecl; \
1575        _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, methodID, args); \
1576        _retok; \
1577    } \
1578    static _ctype Check_CallNonvirtual##_jname##MethodA(JNIEnv* env, \
1579        jobject obj, jclass clazz, jmethodID methodID, jvalue* args) \
1580    { \
1581        CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
1582        sc.checkSig(methodID, _retsig, false); \
1583        sc.checkVirtualMethod(obj, methodID); \
1584        _retdecl; \
1585        _retasgn baseEnv(env)->CallNonvirtual##_jname##MethodA(env, obj, clazz, methodID, args); \
1586        _retok; \
1587    } \
1588    /* Static... */ \
1589    static _ctype Check_CallStatic##_jname##Method(JNIEnv* env, \
1590        jclass clazz, jmethodID methodID, ...) \
1591    { \
1592        CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
1593        sc.checkSig(methodID, _retsig, true); \
1594        sc.checkStaticMethod(clazz, methodID); \
1595        _retdecl; \
1596        va_list args; \
1597        va_start(args, methodID); \
1598        _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, methodID, args); \
1599        va_end(args); \
1600        _retok; \
1601    } \
1602    static _ctype Check_CallStatic##_jname##MethodV(JNIEnv* env, \
1603        jclass clazz, jmethodID methodID, va_list args) \
1604    { \
1605        CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
1606        sc.checkSig(methodID, _retsig, true); \
1607        sc.checkStaticMethod(clazz, methodID); \
1608        _retdecl; \
1609        _retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, methodID, args); \
1610        _retok; \
1611    } \
1612    static _ctype Check_CallStatic##_jname##MethodA(JNIEnv* env, \
1613        jclass clazz, jmethodID methodID, jvalue* args) \
1614    { \
1615        CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
1616        sc.checkSig(methodID, _retsig, true); \
1617        sc.checkStaticMethod(clazz, methodID); \
1618        _retdecl; \
1619        _retasgn baseEnv(env)->CallStatic##_jname##MethodA(env, clazz, methodID, args); \
1620        _retok; \
1621    }
1622
1623#define NON_VOID_RETURN(_retsig, _ctype) return CHECK_JNI_EXIT(_retsig, (_ctype) result)
1624#define VOID_RETURN CHECK_JNI_EXIT_VOID()
1625
1626CALL(jobject, Object, Object* result, result=(Object*), NON_VOID_RETURN("L", jobject), "L");
1627CALL(jboolean, Boolean, jboolean result, result=, NON_VOID_RETURN("Z", jboolean), "Z");
1628CALL(jbyte, Byte, jbyte result, result=, NON_VOID_RETURN("B", jbyte), "B");
1629CALL(jchar, Char, jchar result, result=, NON_VOID_RETURN("C", jchar), "C");
1630CALL(jshort, Short, jshort result, result=, NON_VOID_RETURN("S", jshort), "S");
1631CALL(jint, Int, jint result, result=, NON_VOID_RETURN("I", jint), "I");
1632CALL(jlong, Long, jlong result, result=, NON_VOID_RETURN("J", jlong), "J");
1633CALL(jfloat, Float, jfloat result, result=, NON_VOID_RETURN("F", jfloat), "F");
1634CALL(jdouble, Double, jdouble result, result=, NON_VOID_RETURN("D", jdouble), "D");
1635CALL(void, Void, , , VOID_RETURN, "V");
1636
1637static jstring Check_NewString(JNIEnv* env, const jchar* unicodeChars, jsize len) {
1638    CHECK_JNI_ENTRY(kFlag_Default, "Epz", env, unicodeChars, len);
1639    return CHECK_JNI_EXIT("s", baseEnv(env)->NewString(env, unicodeChars, len));
1640}
1641
1642static jsize Check_GetStringLength(JNIEnv* env, jstring string) {
1643    CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1644    return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringLength(env, string));
1645}
1646
1647static const jchar* Check_GetStringChars(JNIEnv* env, jstring string, jboolean* isCopy) {
1648    CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
1649    const jchar* result = baseEnv(env)->GetStringChars(env, string, isCopy);
1650    if (gDvmJni.forceCopy && result != NULL) {
1651        ScopedJniThreadState ts(env);
1652        StringObject* strObj = (StringObject*) dvmDecodeIndirectRef(env, string);
1653        int byteCount = strObj->length() * 2;
1654        result = (const jchar*) GuardedCopy::create(result, byteCount, false);
1655        if (isCopy != NULL) {
1656            *isCopy = JNI_TRUE;
1657        }
1658    }
1659    return CHECK_JNI_EXIT("p", result);
1660}
1661
1662static void Check_ReleaseStringChars(JNIEnv* env, jstring string, const jchar* chars) {
1663    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Esp", env, string, chars);
1664    sc.checkNonNull(chars);
1665    if (gDvmJni.forceCopy) {
1666        if (!GuardedCopy::check(chars, false)) {
1667            LOGE("JNI: failed guarded copy check in ReleaseStringChars");
1668            abortMaybe();
1669            return;
1670        }
1671        chars = (const jchar*) GuardedCopy::destroy((jchar*)chars);
1672    }
1673    baseEnv(env)->ReleaseStringChars(env, string, chars);
1674    CHECK_JNI_EXIT_VOID();
1675}
1676
1677static jstring Check_NewStringUTF(JNIEnv* env, const char* bytes) {
1678    CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, bytes); // TODO: show pointer and truncate string.
1679    return CHECK_JNI_EXIT("s", baseEnv(env)->NewStringUTF(env, bytes));
1680}
1681
1682static jsize Check_GetStringUTFLength(JNIEnv* env, jstring string) {
1683    CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
1684    return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringUTFLength(env, string));
1685}
1686
1687static const char* Check_GetStringUTFChars(JNIEnv* env, jstring string, jboolean* isCopy) {
1688    CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
1689    const char* result = baseEnv(env)->GetStringUTFChars(env, string, isCopy);
1690    if (gDvmJni.forceCopy && result != NULL) {
1691        result = (const char*) GuardedCopy::create(result, strlen(result) + 1, false);
1692        if (isCopy != NULL) {
1693            *isCopy = JNI_TRUE;
1694        }
1695    }
1696    return CHECK_JNI_EXIT("u", result); // TODO: show pointer and truncate string.
1697}
1698
1699static void Check_ReleaseStringUTFChars(JNIEnv* env, jstring string, const char* utf) {
1700    CHECK_JNI_ENTRY(kFlag_ExcepOkay | kFlag_Release, "Esu", env, string, utf); // TODO: show pointer and truncate string.
1701    if (gDvmJni.forceCopy) {
1702        if (!GuardedCopy::check(utf, false)) {
1703            LOGE("JNI: failed guarded copy check in ReleaseStringUTFChars");
1704            abortMaybe();
1705            return;
1706        }
1707        utf = (const char*) GuardedCopy::destroy((char*)utf);
1708    }
1709    baseEnv(env)->ReleaseStringUTFChars(env, string, utf);
1710    CHECK_JNI_EXIT_VOID();
1711}
1712
1713static jsize Check_GetArrayLength(JNIEnv* env, jarray array) {
1714    CHECK_JNI_ENTRY(kFlag_CritOkay, "Ea", env, array);
1715    return CHECK_JNI_EXIT("I", baseEnv(env)->GetArrayLength(env, array));
1716}
1717
1718static jobjectArray Check_NewObjectArray(JNIEnv* env, jsize length,
1719        jclass elementClass, jobject initialElement)
1720{
1721    CHECK_JNI_ENTRY(kFlag_Default, "EzcL", env, length, elementClass, initialElement);
1722    return CHECK_JNI_EXIT("a", baseEnv(env)->NewObjectArray(env, length, elementClass, initialElement));
1723}
1724
1725static jobject Check_GetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index) {
1726    CHECK_JNI_ENTRY(kFlag_Default, "EaI", env, array, index);
1727    return CHECK_JNI_EXIT("L", baseEnv(env)->GetObjectArrayElement(env, array, index));
1728}
1729
1730static void Check_SetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, jobject value)
1731{
1732    CHECK_JNI_ENTRY(kFlag_Default, "EaIL", env, array, index, value);
1733    baseEnv(env)->SetObjectArrayElement(env, array, index, value);
1734    CHECK_JNI_EXIT_VOID();
1735}
1736
1737#define NEW_PRIMITIVE_ARRAY(_artype, _jname) \
1738    static _artype Check_New##_jname##Array(JNIEnv* env, jsize length) { \
1739        CHECK_JNI_ENTRY(kFlag_Default, "Ez", env, length); \
1740        return CHECK_JNI_EXIT("a", baseEnv(env)->New##_jname##Array(env, length)); \
1741    }
1742NEW_PRIMITIVE_ARRAY(jbooleanArray, Boolean);
1743NEW_PRIMITIVE_ARRAY(jbyteArray, Byte);
1744NEW_PRIMITIVE_ARRAY(jcharArray, Char);
1745NEW_PRIMITIVE_ARRAY(jshortArray, Short);
1746NEW_PRIMITIVE_ARRAY(jintArray, Int);
1747NEW_PRIMITIVE_ARRAY(jlongArray, Long);
1748NEW_PRIMITIVE_ARRAY(jfloatArray, Float);
1749NEW_PRIMITIVE_ARRAY(jdoubleArray, Double);
1750
1751
1752/*
1753 * Hack to allow forcecopy to work with jniGetNonMovableArrayElements.
1754 * The code deliberately uses an invalid sequence of operations, so we
1755 * need to pass it through unmodified.  Review that code before making
1756 * any changes here.
1757 */
1758#define kNoCopyMagic    0xd5aab57f
1759
1760#define GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1761    static _ctype* Check_Get##_jname##ArrayElements(JNIEnv* env, \
1762        _ctype##Array array, jboolean* isCopy) \
1763    { \
1764        CHECK_JNI_ENTRY(kFlag_Default, "Eap", env, array, isCopy); \
1765        u4 noCopy = 0; \
1766        if (gDvmJni.forceCopy && isCopy != NULL) { \
1767            /* capture this before the base call tramples on it */ \
1768            noCopy = *(u4*) isCopy; \
1769        } \
1770        _ctype* result = baseEnv(env)->Get##_jname##ArrayElements(env, array, isCopy); \
1771        if (gDvmJni.forceCopy && result != NULL) { \
1772            if (noCopy == kNoCopyMagic) { \
1773                LOGV("FC: not copying %p %x", array, noCopy); \
1774            } else { \
1775                result = (_ctype*) createGuardedPACopy(env, array, isCopy); \
1776            } \
1777        } \
1778        return CHECK_JNI_EXIT("p", result); \
1779    }
1780
1781#define RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
1782    static void Check_Release##_jname##ArrayElements(JNIEnv* env, \
1783        _ctype##Array array, _ctype* elems, jint mode) \
1784    { \
1785        CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Eapr", env, array, elems, mode); \
1786        sc.checkNonNull(elems); \
1787        if (gDvmJni.forceCopy) { \
1788            if ((uintptr_t)elems == kNoCopyMagic) { \
1789                LOGV("FC: not freeing %p", array); \
1790                elems = NULL;   /* base JNI call doesn't currently need */ \
1791            } else { \
1792                elems = (_ctype*) releaseGuardedPACopy(env, array, elems, mode); \
1793            } \
1794        } \
1795        baseEnv(env)->Release##_jname##ArrayElements(env, array, elems, mode); \
1796        CHECK_JNI_EXIT_VOID(); \
1797    }
1798
1799#define GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1800    static void Check_Get##_jname##ArrayRegion(JNIEnv* env, \
1801            _ctype##Array array, jsize start, jsize len, _ctype* buf) { \
1802        CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1803        baseEnv(env)->Get##_jname##ArrayRegion(env, array, start, len, buf); \
1804        CHECK_JNI_EXIT_VOID(); \
1805    }
1806
1807#define SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
1808    static void Check_Set##_jname##ArrayRegion(JNIEnv* env, \
1809            _ctype##Array array, jsize start, jsize len, const _ctype* buf) { \
1810        CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
1811        baseEnv(env)->Set##_jname##ArrayRegion(env, array, start, len, buf); \
1812        CHECK_JNI_EXIT_VOID(); \
1813    }
1814
1815#define PRIMITIVE_ARRAY_FUNCTIONS(_ctype, _jname, _typechar) \
1816    GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1817    RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
1818    GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname); \
1819    SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname);
1820
1821/* TODO: verify primitive array type matches call type */
1822PRIMITIVE_ARRAY_FUNCTIONS(jboolean, Boolean, 'Z');
1823PRIMITIVE_ARRAY_FUNCTIONS(jbyte, Byte, 'B');
1824PRIMITIVE_ARRAY_FUNCTIONS(jchar, Char, 'C');
1825PRIMITIVE_ARRAY_FUNCTIONS(jshort, Short, 'S');
1826PRIMITIVE_ARRAY_FUNCTIONS(jint, Int, 'I');
1827PRIMITIVE_ARRAY_FUNCTIONS(jlong, Long, 'J');
1828PRIMITIVE_ARRAY_FUNCTIONS(jfloat, Float, 'F');
1829PRIMITIVE_ARRAY_FUNCTIONS(jdouble, Double, 'D');
1830
1831static jint Check_RegisterNatives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods,
1832        jint nMethods)
1833{
1834    CHECK_JNI_ENTRY(kFlag_Default, "EcpI", env, clazz, methods, nMethods);
1835    return CHECK_JNI_EXIT("I", baseEnv(env)->RegisterNatives(env, clazz, methods, nMethods));
1836}
1837
1838static jint Check_UnregisterNatives(JNIEnv* env, jclass clazz) {
1839    CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
1840    return CHECK_JNI_EXIT("I", baseEnv(env)->UnregisterNatives(env, clazz));
1841}
1842
1843static jint Check_MonitorEnter(JNIEnv* env, jobject obj) {
1844    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1845    return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorEnter(env, obj));
1846}
1847
1848static jint Check_MonitorExit(JNIEnv* env, jobject obj) {
1849    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
1850    return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorExit(env, obj));
1851}
1852
1853static jint Check_GetJavaVM(JNIEnv *env, JavaVM **vm) {
1854    CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, vm);
1855    return CHECK_JNI_EXIT("I", baseEnv(env)->GetJavaVM(env, vm));
1856}
1857
1858static void Check_GetStringRegion(JNIEnv* env, jstring str, jsize start, jsize len, jchar* buf) {
1859    CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1860    baseEnv(env)->GetStringRegion(env, str, start, len, buf);
1861    CHECK_JNI_EXIT_VOID();
1862}
1863
1864static void Check_GetStringUTFRegion(JNIEnv* env, jstring str, jsize start, jsize len, char* buf) {
1865    CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
1866    baseEnv(env)->GetStringUTFRegion(env, str, start, len, buf);
1867    CHECK_JNI_EXIT_VOID();
1868}
1869
1870static void* Check_GetPrimitiveArrayCritical(JNIEnv* env, jarray array, jboolean* isCopy) {
1871    CHECK_JNI_ENTRY(kFlag_CritGet, "Eap", env, array, isCopy);
1872    void* result = baseEnv(env)->GetPrimitiveArrayCritical(env, array, isCopy);
1873    if (gDvmJni.forceCopy && result != NULL) {
1874        result = createGuardedPACopy(env, array, isCopy);
1875    }
1876    return CHECK_JNI_EXIT("p", result);
1877}
1878
1879static void Check_ReleasePrimitiveArrayCritical(JNIEnv* env, jarray array, void* carray, jint mode)
1880{
1881    CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Eapr", env, array, carray, mode);
1882    sc.checkNonNull(carray);
1883    if (gDvmJni.forceCopy) {
1884        carray = releaseGuardedPACopy(env, array, carray, mode);
1885    }
1886    baseEnv(env)->ReleasePrimitiveArrayCritical(env, array, carray, mode);
1887    CHECK_JNI_EXIT_VOID();
1888}
1889
1890static const jchar* Check_GetStringCritical(JNIEnv* env, jstring string, jboolean* isCopy) {
1891    CHECK_JNI_ENTRY(kFlag_CritGet, "Esp", env, string, isCopy);
1892    const jchar* result = baseEnv(env)->GetStringCritical(env, string, isCopy);
1893    if (gDvmJni.forceCopy && result != NULL) {
1894        ScopedJniThreadState ts(env);
1895        StringObject* strObj = (StringObject*) dvmDecodeIndirectRef(env, string);
1896        int byteCount = strObj->length() * 2;
1897        result = (const jchar*) GuardedCopy::create(result, byteCount, false);
1898        if (isCopy != NULL) {
1899            *isCopy = JNI_TRUE;
1900        }
1901    }
1902    return CHECK_JNI_EXIT("p", result);
1903}
1904
1905static void Check_ReleaseStringCritical(JNIEnv* env, jstring string, const jchar* carray) {
1906    CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Esp", env, string, carray);
1907    sc.checkNonNull(carray);
1908    if (gDvmJni.forceCopy) {
1909        if (!GuardedCopy::check(carray, false)) {
1910            LOGE("JNI: failed guarded copy check in ReleaseStringCritical");
1911            abortMaybe();
1912            return;
1913        }
1914        carray = (const jchar*) GuardedCopy::destroy((jchar*)carray);
1915    }
1916    baseEnv(env)->ReleaseStringCritical(env, string, carray);
1917    CHECK_JNI_EXIT_VOID();
1918}
1919
1920static jweak Check_NewWeakGlobalRef(JNIEnv* env, jobject obj) {
1921    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1922    return CHECK_JNI_EXIT("L", baseEnv(env)->NewWeakGlobalRef(env, obj));
1923}
1924
1925static void Check_DeleteWeakGlobalRef(JNIEnv* env, jweak obj) {
1926    CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
1927    baseEnv(env)->DeleteWeakGlobalRef(env, obj);
1928    CHECK_JNI_EXIT_VOID();
1929}
1930
1931static jboolean Check_ExceptionCheck(JNIEnv* env) {
1932    CHECK_JNI_ENTRY(kFlag_CritOkay | kFlag_ExcepOkay, "E", env);
1933    return CHECK_JNI_EXIT("b", baseEnv(env)->ExceptionCheck(env));
1934}
1935
1936static jobjectRefType Check_GetObjectRefType(JNIEnv* env, jobject obj) {
1937    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
1938    // TODO: proper decoding of jobjectRefType!
1939    return CHECK_JNI_EXIT("I", baseEnv(env)->GetObjectRefType(env, obj));
1940}
1941
1942static jobject Check_NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
1943    CHECK_JNI_ENTRY(kFlag_Default, "EpJ", env, address, capacity);
1944    if (address == NULL || capacity < 0) {
1945        LOGW("JNI WARNING: invalid values for address (%p) or capacity (%ld)",
1946            address, (long) capacity);
1947        abortMaybe();
1948        return NULL;
1949    }
1950    return CHECK_JNI_EXIT("L", baseEnv(env)->NewDirectByteBuffer(env, address, capacity));
1951}
1952
1953static void* Check_GetDirectBufferAddress(JNIEnv* env, jobject buf) {
1954    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1955    // TODO: check that 'buf' is a java.nio.Buffer.
1956    return CHECK_JNI_EXIT("p", baseEnv(env)->GetDirectBufferAddress(env, buf));
1957}
1958
1959static jlong Check_GetDirectBufferCapacity(JNIEnv* env, jobject buf) {
1960    CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
1961    // TODO: check that 'buf' is a java.nio.Buffer.
1962    return CHECK_JNI_EXIT("J", baseEnv(env)->GetDirectBufferCapacity(env, buf));
1963}
1964
1965
1966/*
1967 * ===========================================================================
1968 *      JNI invocation functions
1969 * ===========================================================================
1970 */
1971
1972static jint Check_DestroyJavaVM(JavaVM* vm) {
1973    ScopedCheck sc(false, __FUNCTION__);
1974    sc.check(true, "v", vm);
1975    return CHECK_JNI_EXIT("I", baseVm(vm)->DestroyJavaVM(vm));
1976}
1977
1978static jint Check_AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
1979    ScopedCheck sc(false, __FUNCTION__);
1980    sc.check(true, "vpp", vm, p_env, thr_args);
1981    return CHECK_JNI_EXIT("I", baseVm(vm)->AttachCurrentThread(vm, p_env, thr_args));
1982}
1983
1984static jint Check_AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
1985    ScopedCheck sc(false, __FUNCTION__);
1986    sc.check(true, "vpp", vm, p_env, thr_args);
1987    return CHECK_JNI_EXIT("I", baseVm(vm)->AttachCurrentThreadAsDaemon(vm, p_env, thr_args));
1988}
1989
1990static jint Check_DetachCurrentThread(JavaVM* vm) {
1991    ScopedCheck sc(true, __FUNCTION__);
1992    sc.check(true, "v", vm);
1993    return CHECK_JNI_EXIT("I", baseVm(vm)->DetachCurrentThread(vm));
1994}
1995
1996static jint Check_GetEnv(JavaVM* vm, void** env, jint version) {
1997    ScopedCheck sc(true, __FUNCTION__);
1998    sc.check(true, "v", vm);
1999    return CHECK_JNI_EXIT("I", baseVm(vm)->GetEnv(vm, env, version));
2000}
2001
2002
2003/*
2004 * ===========================================================================
2005 *      Function tables
2006 * ===========================================================================
2007 */
2008
2009static const struct JNINativeInterface gCheckNativeInterface = {
2010    NULL,
2011    NULL,
2012    NULL,
2013    NULL,
2014
2015    Check_GetVersion,
2016
2017    Check_DefineClass,
2018    Check_FindClass,
2019
2020    Check_FromReflectedMethod,
2021    Check_FromReflectedField,
2022    Check_ToReflectedMethod,
2023
2024    Check_GetSuperclass,
2025    Check_IsAssignableFrom,
2026
2027    Check_ToReflectedField,
2028
2029    Check_Throw,
2030    Check_ThrowNew,
2031    Check_ExceptionOccurred,
2032    Check_ExceptionDescribe,
2033    Check_ExceptionClear,
2034    Check_FatalError,
2035
2036    Check_PushLocalFrame,
2037    Check_PopLocalFrame,
2038
2039    Check_NewGlobalRef,
2040    Check_DeleteGlobalRef,
2041    Check_DeleteLocalRef,
2042    Check_IsSameObject,
2043    Check_NewLocalRef,
2044    Check_EnsureLocalCapacity,
2045
2046    Check_AllocObject,
2047    Check_NewObject,
2048    Check_NewObjectV,
2049    Check_NewObjectA,
2050
2051    Check_GetObjectClass,
2052    Check_IsInstanceOf,
2053
2054    Check_GetMethodID,
2055
2056    Check_CallObjectMethod,
2057    Check_CallObjectMethodV,
2058    Check_CallObjectMethodA,
2059    Check_CallBooleanMethod,
2060    Check_CallBooleanMethodV,
2061    Check_CallBooleanMethodA,
2062    Check_CallByteMethod,
2063    Check_CallByteMethodV,
2064    Check_CallByteMethodA,
2065    Check_CallCharMethod,
2066    Check_CallCharMethodV,
2067    Check_CallCharMethodA,
2068    Check_CallShortMethod,
2069    Check_CallShortMethodV,
2070    Check_CallShortMethodA,
2071    Check_CallIntMethod,
2072    Check_CallIntMethodV,
2073    Check_CallIntMethodA,
2074    Check_CallLongMethod,
2075    Check_CallLongMethodV,
2076    Check_CallLongMethodA,
2077    Check_CallFloatMethod,
2078    Check_CallFloatMethodV,
2079    Check_CallFloatMethodA,
2080    Check_CallDoubleMethod,
2081    Check_CallDoubleMethodV,
2082    Check_CallDoubleMethodA,
2083    Check_CallVoidMethod,
2084    Check_CallVoidMethodV,
2085    Check_CallVoidMethodA,
2086
2087    Check_CallNonvirtualObjectMethod,
2088    Check_CallNonvirtualObjectMethodV,
2089    Check_CallNonvirtualObjectMethodA,
2090    Check_CallNonvirtualBooleanMethod,
2091    Check_CallNonvirtualBooleanMethodV,
2092    Check_CallNonvirtualBooleanMethodA,
2093    Check_CallNonvirtualByteMethod,
2094    Check_CallNonvirtualByteMethodV,
2095    Check_CallNonvirtualByteMethodA,
2096    Check_CallNonvirtualCharMethod,
2097    Check_CallNonvirtualCharMethodV,
2098    Check_CallNonvirtualCharMethodA,
2099    Check_CallNonvirtualShortMethod,
2100    Check_CallNonvirtualShortMethodV,
2101    Check_CallNonvirtualShortMethodA,
2102    Check_CallNonvirtualIntMethod,
2103    Check_CallNonvirtualIntMethodV,
2104    Check_CallNonvirtualIntMethodA,
2105    Check_CallNonvirtualLongMethod,
2106    Check_CallNonvirtualLongMethodV,
2107    Check_CallNonvirtualLongMethodA,
2108    Check_CallNonvirtualFloatMethod,
2109    Check_CallNonvirtualFloatMethodV,
2110    Check_CallNonvirtualFloatMethodA,
2111    Check_CallNonvirtualDoubleMethod,
2112    Check_CallNonvirtualDoubleMethodV,
2113    Check_CallNonvirtualDoubleMethodA,
2114    Check_CallNonvirtualVoidMethod,
2115    Check_CallNonvirtualVoidMethodV,
2116    Check_CallNonvirtualVoidMethodA,
2117
2118    Check_GetFieldID,
2119
2120    Check_GetObjectField,
2121    Check_GetBooleanField,
2122    Check_GetByteField,
2123    Check_GetCharField,
2124    Check_GetShortField,
2125    Check_GetIntField,
2126    Check_GetLongField,
2127    Check_GetFloatField,
2128    Check_GetDoubleField,
2129    Check_SetObjectField,
2130    Check_SetBooleanField,
2131    Check_SetByteField,
2132    Check_SetCharField,
2133    Check_SetShortField,
2134    Check_SetIntField,
2135    Check_SetLongField,
2136    Check_SetFloatField,
2137    Check_SetDoubleField,
2138
2139    Check_GetStaticMethodID,
2140
2141    Check_CallStaticObjectMethod,
2142    Check_CallStaticObjectMethodV,
2143    Check_CallStaticObjectMethodA,
2144    Check_CallStaticBooleanMethod,
2145    Check_CallStaticBooleanMethodV,
2146    Check_CallStaticBooleanMethodA,
2147    Check_CallStaticByteMethod,
2148    Check_CallStaticByteMethodV,
2149    Check_CallStaticByteMethodA,
2150    Check_CallStaticCharMethod,
2151    Check_CallStaticCharMethodV,
2152    Check_CallStaticCharMethodA,
2153    Check_CallStaticShortMethod,
2154    Check_CallStaticShortMethodV,
2155    Check_CallStaticShortMethodA,
2156    Check_CallStaticIntMethod,
2157    Check_CallStaticIntMethodV,
2158    Check_CallStaticIntMethodA,
2159    Check_CallStaticLongMethod,
2160    Check_CallStaticLongMethodV,
2161    Check_CallStaticLongMethodA,
2162    Check_CallStaticFloatMethod,
2163    Check_CallStaticFloatMethodV,
2164    Check_CallStaticFloatMethodA,
2165    Check_CallStaticDoubleMethod,
2166    Check_CallStaticDoubleMethodV,
2167    Check_CallStaticDoubleMethodA,
2168    Check_CallStaticVoidMethod,
2169    Check_CallStaticVoidMethodV,
2170    Check_CallStaticVoidMethodA,
2171
2172    Check_GetStaticFieldID,
2173
2174    Check_GetStaticObjectField,
2175    Check_GetStaticBooleanField,
2176    Check_GetStaticByteField,
2177    Check_GetStaticCharField,
2178    Check_GetStaticShortField,
2179    Check_GetStaticIntField,
2180    Check_GetStaticLongField,
2181    Check_GetStaticFloatField,
2182    Check_GetStaticDoubleField,
2183
2184    Check_SetStaticObjectField,
2185    Check_SetStaticBooleanField,
2186    Check_SetStaticByteField,
2187    Check_SetStaticCharField,
2188    Check_SetStaticShortField,
2189    Check_SetStaticIntField,
2190    Check_SetStaticLongField,
2191    Check_SetStaticFloatField,
2192    Check_SetStaticDoubleField,
2193
2194    Check_NewString,
2195
2196    Check_GetStringLength,
2197    Check_GetStringChars,
2198    Check_ReleaseStringChars,
2199
2200    Check_NewStringUTF,
2201    Check_GetStringUTFLength,
2202    Check_GetStringUTFChars,
2203    Check_ReleaseStringUTFChars,
2204
2205    Check_GetArrayLength,
2206    Check_NewObjectArray,
2207    Check_GetObjectArrayElement,
2208    Check_SetObjectArrayElement,
2209
2210    Check_NewBooleanArray,
2211    Check_NewByteArray,
2212    Check_NewCharArray,
2213    Check_NewShortArray,
2214    Check_NewIntArray,
2215    Check_NewLongArray,
2216    Check_NewFloatArray,
2217    Check_NewDoubleArray,
2218
2219    Check_GetBooleanArrayElements,
2220    Check_GetByteArrayElements,
2221    Check_GetCharArrayElements,
2222    Check_GetShortArrayElements,
2223    Check_GetIntArrayElements,
2224    Check_GetLongArrayElements,
2225    Check_GetFloatArrayElements,
2226    Check_GetDoubleArrayElements,
2227
2228    Check_ReleaseBooleanArrayElements,
2229    Check_ReleaseByteArrayElements,
2230    Check_ReleaseCharArrayElements,
2231    Check_ReleaseShortArrayElements,
2232    Check_ReleaseIntArrayElements,
2233    Check_ReleaseLongArrayElements,
2234    Check_ReleaseFloatArrayElements,
2235    Check_ReleaseDoubleArrayElements,
2236
2237    Check_GetBooleanArrayRegion,
2238    Check_GetByteArrayRegion,
2239    Check_GetCharArrayRegion,
2240    Check_GetShortArrayRegion,
2241    Check_GetIntArrayRegion,
2242    Check_GetLongArrayRegion,
2243    Check_GetFloatArrayRegion,
2244    Check_GetDoubleArrayRegion,
2245    Check_SetBooleanArrayRegion,
2246    Check_SetByteArrayRegion,
2247    Check_SetCharArrayRegion,
2248    Check_SetShortArrayRegion,
2249    Check_SetIntArrayRegion,
2250    Check_SetLongArrayRegion,
2251    Check_SetFloatArrayRegion,
2252    Check_SetDoubleArrayRegion,
2253
2254    Check_RegisterNatives,
2255    Check_UnregisterNatives,
2256
2257    Check_MonitorEnter,
2258    Check_MonitorExit,
2259
2260    Check_GetJavaVM,
2261
2262    Check_GetStringRegion,
2263    Check_GetStringUTFRegion,
2264
2265    Check_GetPrimitiveArrayCritical,
2266    Check_ReleasePrimitiveArrayCritical,
2267
2268    Check_GetStringCritical,
2269    Check_ReleaseStringCritical,
2270
2271    Check_NewWeakGlobalRef,
2272    Check_DeleteWeakGlobalRef,
2273
2274    Check_ExceptionCheck,
2275
2276    Check_NewDirectByteBuffer,
2277    Check_GetDirectBufferAddress,
2278    Check_GetDirectBufferCapacity,
2279
2280    Check_GetObjectRefType
2281};
2282
2283static const struct JNIInvokeInterface gCheckInvokeInterface = {
2284    NULL,
2285    NULL,
2286    NULL,
2287
2288    Check_DestroyJavaVM,
2289    Check_AttachCurrentThread,
2290    Check_DetachCurrentThread,
2291
2292    Check_GetEnv,
2293
2294    Check_AttachCurrentThreadAsDaemon,
2295};
2296
2297/*
2298 * Replace the normal table with the checked table.
2299 */
2300void dvmUseCheckedJniEnv(JNIEnvExt* pEnv) {
2301    assert(pEnv->funcTable != &gCheckNativeInterface);
2302    pEnv->baseFuncTable = pEnv->funcTable;
2303    pEnv->funcTable = &gCheckNativeInterface;
2304}
2305
2306/*
2307 * Replace the normal table with the checked table.
2308 */
2309void dvmUseCheckedJniVm(JavaVMExt* pVm) {
2310    assert(pVm->funcTable != &gCheckInvokeInterface);
2311    pVm->baseFuncTable = pVm->funcTable;
2312    pVm->funcTable = &gCheckInvokeInterface;
2313}
2314