• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "check_jni.h"
18 
19 #include <sys/mman.h>
20 #include <zlib.h>
21 
22 #include <iomanip>
23 
24 #include <android-base/logging.h>
25 #include <android-base/stringprintf.h>
26 
27 #include "art_field-inl.h"
28 #include "art_method-inl.h"
29 #include "base/macros.h"
30 #include "base/to_str.h"
31 #include "base/time_utils.h"
32 #include "class_linker-inl.h"
33 #include "class_linker.h"
34 #include "class_root-inl.h"
35 #include "dex/descriptors_names.h"
36 #include "dex/dex_file-inl.h"
37 #include "gc/space/space.h"
38 #include "indirect_reference_table-inl.h"
39 #include "java_vm_ext.h"
40 #include "jni_internal.h"
41 #include "local_reference_table-inl.h"
42 #include "mirror/class-inl.h"
43 #include "mirror/field.h"
44 #include "mirror/method.h"
45 #include "mirror/object-inl.h"
46 #include "mirror/object_array-inl.h"
47 #include "mirror/string-inl.h"
48 #include "mirror/throwable.h"
49 #include "runtime.h"
50 #include "scoped_thread_state_change-inl.h"
51 #include "thread.h"
52 #include "well_known_classes.h"
53 
54 namespace art HIDDEN {
55 
56 // This helper cannot be in the anonymous namespace because it needs to be
57 // declared as a friend by JniVmExt and JniEnvExt.
GetIndirectReferenceTable(ScopedObjectAccess & soa,IndirectRefKind kind)58 inline IndirectReferenceTable* GetIndirectReferenceTable(ScopedObjectAccess& soa,
59                                                          IndirectRefKind kind) {
60   DCHECK_NE(kind, kJniTransition);
61   DCHECK_NE(kind, kLocal);
62   JavaVMExt* vm = soa.Env()->GetVm();
63   IndirectReferenceTable* irt = (kind == kGlobal) ? &vm->globals_ : &vm->weak_globals_;
64   DCHECK_EQ(irt->GetKind(), kind);
65   return irt;
66 }
67 
68 // This helper cannot be in the anonymous namespace because it needs to be
69 // declared as a friend by JniEnvExt.
GetLocalReferenceTable(ScopedObjectAccess & soa)70 inline jni::LocalReferenceTable* GetLocalReferenceTable(ScopedObjectAccess& soa) {
71   return &soa.Env()->locals_;
72 }
73 
74 namespace {
75 
76 using android::base::StringAppendF;
77 using android::base::StringPrintf;
78 
79 /*
80  * ===========================================================================
81  *      JNI function helpers
82  * ===========================================================================
83  */
84 
85 // Warn if a JNI critical is held for longer than 16ms.
86 static constexpr uint64_t kCriticalWarnTimeUs = MsToUs(16);
87 static_assert(kCriticalWarnTimeUs > 0, "No JNI critical warn time set");
88 
89 // True if primitives within specific ranges cause a fatal error,
90 // otherwise just warn.
91 static constexpr bool kBrokenPrimitivesAreFatal = kIsDebugBuild;
92 
93 // Flags passed into ScopedCheck.
94 static constexpr uint16_t kFlag_Default = 0x0000;
95 
96 // Calling while in critical is not allowed.
97 static constexpr uint16_t kFlag_CritBad = 0x0000;
98 // Calling while in critical is allowed.
99 static constexpr uint16_t kFlag_CritOkay = 0x0001;
100 // This is a critical "get".
101 static constexpr uint16_t kFlag_CritGet = 0x0002;
102 // This is a critical "release".
103 static constexpr uint16_t kFlag_CritRelease = 0x0003;
104 // Bit mask to get "crit" value.
105 static constexpr uint16_t kFlag_CritMask = 0x0003;
106 
107 // Raised exceptions are allowed.
108 static constexpr uint16_t kFlag_ExcepOkay = 0x0004;
109 
110 // Are we in a non-critical release function?
111 static constexpr uint16_t kFlag_Release = 0x0010;
112 // Are our UTF parameters nullable?
113 static constexpr uint16_t kFlag_NullableUtf = 0x0020;
114 
115 // Part of the invocation interface (JavaVM*).
116 static constexpr uint16_t kFlag_Invocation = 0x0100;
117 
118 // Add this to a JNI function's flags if you want to trace every call.
119 static constexpr uint16_t kFlag_ForceTrace = 0x8000;
120 
121 class VarArgs;
122 /*
123  * Java primitive types:
124  * B - jbyte
125  * C - jchar
126  * D - jdouble
127  * F - jfloat
128  * I - jint
129  * J - jlong
130  * S - jshort
131  * Z - jboolean (shown as true and false)
132  * V - void
133  *
134  * Java reference types:
135  * L - jobject
136  * a - jarray
137  * c - jclass
138  * s - jstring
139  * t - jthrowable
140  *
141  * JNI types:
142  * b - jboolean (shown as JNI_TRUE and JNI_FALSE)
143  * f - jfieldID
144  * i - JNI error value (JNI_OK, JNI_ERR, JNI_EDETACHED, JNI_EVERSION)
145  * m - jmethodID
146  * p - void*
147  * r - jint (for release mode arguments)
148  * u - const char* (Modified UTF-8)
149  * z - jsize (for lengths; use i if negative values are okay)
150  * v - JavaVM*
151  * w - jobjectRefType
152  * E - JNIEnv*
153  * . - no argument; just print "..." (used for varargs JNI calls)
154  *
155  */
156 union JniValueType {
157   jarray a;
158   jboolean b;
159   jclass c;
160   jfieldID f;
161   jint i;
162   jmethodID m;
163   const void* p;  // Pointer.
164   jint r;  // Release mode.
165   jstring s;
166   jthrowable t;
167   const char* u;  // Modified UTF-8.
168   JavaVM* v;
169   jobjectRefType w;
170   jsize z;
171   jbyte B;
172   jchar C;
173   jdouble D;
174   JNIEnv* E;
175   jfloat F;
176   jint I;
177   jlong J;
178   jobject L;
179   jshort S;
180   const void* V;  // void
181   jboolean Z;
182   const VarArgs* va;
183 };
184 
185 /*
186  * A structure containing all the information needed to validate varargs arguments.
187  *
188  * Note that actually getting the arguments from this structure mutates it so should only be done on
189  * owned copies.
190  */
191 class VarArgs {
192  public:
VarArgs(jmethodID m,va_list var)193   VarArgs(jmethodID m, va_list var) : m_(m), type_(kTypeVaList), cnt_(0) {
194     va_copy(vargs_, var);
195   }
196 
VarArgs(jmethodID m,const jvalue * vals)197   VarArgs(jmethodID m, const jvalue* vals) : m_(m), type_(kTypePtr), cnt_(0), ptr_(vals) {}
198 
~VarArgs()199   ~VarArgs() {
200     if (type_ == kTypeVaList) {
201       va_end(vargs_);
202     }
203   }
204 
VarArgs(VarArgs && other)205   VarArgs(VarArgs&& other) noexcept {
206     m_ = other.m_;
207     cnt_ = other.cnt_;
208     type_ = other.type_;
209     if (other.type_ == kTypeVaList) {
210       va_copy(vargs_, other.vargs_);
211     } else {
212       ptr_ = other.ptr_;
213     }
214   }
215 
216   // This method is const because we need to ensure that one only uses the GetValue method on an
217   // owned copy of the VarArgs. This is because getting the next argument from a va_list is a
218   // mutating operation. Therefore we pass around these VarArgs with the 'const' qualifier and when
219   // we want to use one we need to Clone() it.
Clone() const220   VarArgs Clone() const {
221     if (type_ == kTypeVaList) {
222       // const_cast needed to make sure the compiler is okay with va_copy, which (being a macro) is
223       // messed up if the source argument is not the exact type 'va_list'.
224       return VarArgs(m_, cnt_, const_cast<VarArgs*>(this)->vargs_);
225     } else {
226       return VarArgs(m_, cnt_, ptr_);
227     }
228   }
229 
GetMethodID() const230   jmethodID GetMethodID() const {
231     return m_;
232   }
233 
GetValue(char fmt)234   JniValueType GetValue(char fmt) {
235     JniValueType o;
236     if (type_ == kTypeVaList) {
237       switch (fmt) {
238         // Assign a full int for va_list values as this is what is done in reflection.cc.
239         // TODO(b/73656264): avoid undefined behavior.
240         case 'Z': FALLTHROUGH_INTENDED;
241         case 'B': FALLTHROUGH_INTENDED;
242         case 'C': FALLTHROUGH_INTENDED;
243         case 'S': FALLTHROUGH_INTENDED;
244         case 'I': o.I = va_arg(vargs_, jint); break;
245         case 'J': o.J = va_arg(vargs_, jlong); break;
246         case 'F': o.F = static_cast<jfloat>(va_arg(vargs_, jdouble)); break;
247         case 'D': o.D = va_arg(vargs_, jdouble); break;
248         case 'L': o.L = va_arg(vargs_, jobject); break;
249         default:
250           LOG(FATAL) << "Illegal type format char " << fmt;
251           UNREACHABLE();
252       }
253     } else {
254       CHECK(type_ == kTypePtr);
255       jvalue v = ptr_[cnt_];
256       cnt_++;
257       switch (fmt) {
258         // Copy just the amount of the jvalue necessary, as done in
259         // reflection.cc, but extend to an int to be consistent with
260         // var args in CheckNonHeapValue.
261         // TODO(b/73656264): avoid undefined behavior.
262         case 'Z': o.I = v.z; break;
263         case 'B': o.I = v.b; break;
264         case 'C': o.I = v.c; break;
265         case 'S': o.I = v.s; break;
266         case 'I': o.I = v.i; break;
267         case 'J': o.J = v.j; break;
268         case 'F': o.F = v.f; break;
269         case 'D': o.D = v.d; break;
270         case 'L': o.L = v.l; break;
271         default:
272           LOG(FATAL) << "Illegal type format char " << fmt;
273           UNREACHABLE();
274       }
275     }
276     return o;
277   }
278 
279  private:
VarArgs(jmethodID m,uint32_t cnt,va_list var)280   VarArgs(jmethodID m, uint32_t cnt, va_list var) : m_(m), type_(kTypeVaList), cnt_(cnt) {
281     va_copy(vargs_, var);
282   }
283 
VarArgs(jmethodID m,uint32_t cnt,const jvalue * vals)284   VarArgs(jmethodID m, uint32_t cnt, const jvalue* vals) : m_(m), type_(kTypePtr), cnt_(cnt), ptr_(vals) {}
285 
286   enum VarArgsType {
287     kTypeVaList,
288     kTypePtr,
289   };
290 
291   jmethodID m_;
292   VarArgsType type_;
293   uint32_t cnt_;
294   union {
295     va_list vargs_;
296     const jvalue* ptr_;
297   };
298 };
299 
300 // Check whether the current thread is attached. This is usually required
301 // to be the first check, as ScopedCheck needs a ScopedObjectAccess for
302 // checking heap values (and that will fail with unattached threads).
CheckAttachedThread(const char * function_name)303 bool CheckAttachedThread(const char* function_name) {
304   Thread* self = Thread::Current();
305   if (UNLIKELY(self == nullptr)) {
306     // Need to attach this thread for a proper abort to work. We prefer this
307     // to get reasonable stacks and environment, rather than relying on
308     // tombstoned.
309     JNIEnv* env;
310     Runtime::Current()->GetJavaVM()->AttachCurrentThread(&env, /* thr_args= */ nullptr);
311 
312     std::string tmp = android::base::StringPrintf(
313         "a thread (tid %" PRId64 " is making JNI calls without being attached",
314         static_cast<int64_t>(GetTid()));
315     Runtime::Current()->GetJavaVM()->JniAbort(function_name, tmp.c_str());
316 
317     CHECK_NE(Runtime::Current()->GetJavaVM()->DetachCurrentThread(), JNI_ERR);
318     return false;
319   }
320   return true;
321 }
322 
323 // Macro helpers for the above.
324 #define CHECK_ATTACHED_THREAD(function_name, fail_val)  \
325   do {                                                  \
326     if (!CheckAttachedThread((function_name))) {        \
327       return fail_val;                                  \
328     }                                                   \
329   } while (false)
330 #define CHECK_ATTACHED_THREAD_VOID(function_name)       \
331   do {                                                  \
332     if (!CheckAttachedThread((function_name))) {        \
333       return;                                           \
334     }                                                   \
335   } while (false)
336 
337 class ScopedCheck {
338  public:
ScopedCheck(uint16_t flags,const char * functionName,bool has_method=true)339   ScopedCheck(uint16_t flags, const char* functionName, bool has_method = true)
340       : function_name_(functionName), indent_(0), flags_(flags), has_method_(has_method) {
341   }
342 
~ScopedCheck()343   ~ScopedCheck() {}
344 
345   // Checks that 'class_name' is a valid "fully-qualified" JNI class name, like "java/lang/Thread"
346   // or "[Ljava/lang/Object;". A ClassLoader can actually normalize class names a couple of
347   // times, so using "java.lang.Thread" instead of "java/lang/Thread" might work in some
348   // circumstances, but this is incorrect.
CheckClassName(const char * class_name)349   bool CheckClassName(const char* class_name) {
350     if ((class_name == nullptr) || !IsValidJniClassName(class_name)) {
351       AbortF("illegal class name '%s'\n"
352              "    (should be of the form 'package/Class', [Lpackage/Class;' or '[[B')",
353              class_name);
354       return false;
355     }
356     return true;
357   }
358 
359   /*
360    * Verify that this instance field ID is valid for this object.
361    *
362    * Assumes "jobj" has already been validated.
363    */
CheckInstanceFieldID(ScopedObjectAccess & soa,jobject java_object,jfieldID fid)364   bool CheckInstanceFieldID(ScopedObjectAccess& soa, jobject java_object, jfieldID fid)
365       REQUIRES_SHARED(Locks::mutator_lock_) {
366     ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(java_object);
367     if (o == nullptr) {
368       AbortF("field operation on NULL object: %p", java_object);
369       return false;
370     }
371     if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(o.Ptr())) {
372       Runtime::Current()->GetHeap()->DumpSpaces(LOG_STREAM(ERROR));
373       AbortF("field operation on invalid %s: %p",
374              GetIndirectRefKindString(IndirectReferenceTable::GetIndirectRefKind(java_object)),
375              java_object);
376       return false;
377     }
378 
379     ArtField* f = CheckFieldID(fid);
380     if (f == nullptr) {
381       return false;
382     }
383     ObjPtr<mirror::Class> c = o->GetClass();
384     if (c->FindInstanceField(f->GetName(), f->GetTypeDescriptor()) == nullptr) {
385       AbortF("jfieldID %s not valid for an object of class %s",
386              f->PrettyField().c_str(), o->PrettyTypeOf().c_str());
387       return false;
388     }
389     return true;
390   }
391 
392   /*
393    * Verify that the pointer value is non-null.
394    */
CheckNonNull(const void * ptr)395   bool CheckNonNull(const void* ptr) {
396     if (UNLIKELY(ptr == nullptr)) {
397       AbortF("non-nullable argument was NULL");
398       return false;
399     }
400     return true;
401   }
402 
403   /*
404    * Verify that the method's return type matches the type of call.
405    * 'expectedType' will be "L" for all objects, including arrays.
406    */
CheckMethodAndSig(ScopedObjectAccess & soa,jobject jobj,jclass jc,jmethodID mid,Primitive::Type type,InvokeType invoke)407   bool CheckMethodAndSig(ScopedObjectAccess& soa, jobject jobj, jclass jc,
408                          jmethodID mid, Primitive::Type type, InvokeType invoke)
409       REQUIRES_SHARED(Locks::mutator_lock_) {
410     ArtMethod* m = CheckMethodID(mid);
411     if (m == nullptr) {
412       return false;
413     }
414     if (type != Primitive::GetType(m->GetShorty()[0])) {
415       AbortF("the return type of %s does not match %s", function_name_, m->PrettyMethod().c_str());
416       return false;
417     }
418     bool is_static = (invoke == kStatic);
419     if (is_static != m->IsStatic()) {
420       if (is_static) {
421         AbortF("calling non-static method %s with %s",
422                m->PrettyMethod().c_str(), function_name_);
423       } else {
424         AbortF("calling static method %s with %s",
425                m->PrettyMethod().c_str(), function_name_);
426       }
427       return false;
428     }
429     if (invoke != kVirtual) {
430       ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(jc);
431       if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
432         AbortF("can't call %s %s with class %s", invoke == kStatic ? "static" : "nonvirtual",
433             m->PrettyMethod().c_str(), mirror::Class::PrettyClass(c).c_str());
434         return false;
435       }
436     }
437     if (invoke != kStatic) {
438       ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(jobj);
439       if (o == nullptr) {
440         AbortF("can't call %s on null object", m->PrettyMethod().c_str());
441         return false;
442       } else if (!o->InstanceOf(m->GetDeclaringClass())) {
443         AbortF("can't call %s on instance of %s", m->PrettyMethod().c_str(),
444                o->PrettyTypeOf().c_str());
445         return false;
446       }
447     }
448     return true;
449   }
450 
451   /*
452    * Verify that this static field ID is valid for this class.
453    *
454    * Assumes "java_class" has already been validated.
455    */
CheckStaticFieldID(ScopedObjectAccess & soa,jclass java_class,jfieldID fid)456   bool CheckStaticFieldID(ScopedObjectAccess& soa, jclass java_class, jfieldID fid)
457       REQUIRES_SHARED(Locks::mutator_lock_) {
458     ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(java_class);
459     ArtField* f = CheckFieldID(fid);
460     if (f == nullptr) {
461       return false;
462     }
463     if (!f->GetDeclaringClass()->IsAssignableFrom(c)) {
464       AbortF("static jfieldID %p not valid for class %s", fid,
465              mirror::Class::PrettyClass(c).c_str());
466       return false;
467     }
468     return true;
469   }
470 
471   /*
472    * Verify that "mid" is appropriate for "java_class".
473    *
474    * A mismatch isn't dangerous, because the jmethodID defines the class.  In
475    * fact, java_class is unused in the implementation.  It's best if we don't
476    * allow bad code in the system though.
477    *
478    * Instances of "java_class" must be instances of the method's declaring class.
479    */
CheckStaticMethod(ScopedObjectAccess & soa,jclass java_class,jmethodID mid)480   bool CheckStaticMethod(ScopedObjectAccess& soa, jclass java_class, jmethodID mid)
481       REQUIRES_SHARED(Locks::mutator_lock_) {
482     ArtMethod* m = CheckMethodID(mid);
483     if (m == nullptr) {
484       return false;
485     }
486     ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(java_class);
487     if (!m->GetDeclaringClass()->IsAssignableFrom(c)) {
488       AbortF("can't call static %s on class %s", m->PrettyMethod().c_str(),
489              mirror::Class::PrettyClass(c).c_str());
490       return false;
491     }
492     return true;
493   }
494 
495   /*
496    * Verify that "mid" is appropriate for "jobj".
497    *
498    * Make sure the object is an instance of the method's declaring class.
499    * (Note the mid might point to a declaration in an interface; this
500    * will be handled automatically by the instanceof check.)
501    */
CheckVirtualMethod(ScopedObjectAccess & soa,jobject java_object,jmethodID mid)502   bool CheckVirtualMethod(ScopedObjectAccess& soa, jobject java_object, jmethodID mid)
503       REQUIRES_SHARED(Locks::mutator_lock_) {
504     ArtMethod* m = CheckMethodID(mid);
505     if (m == nullptr) {
506       return false;
507     }
508     ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(java_object);
509     if (o == nullptr) {
510       AbortF("can't call %s on null object", m->PrettyMethod().c_str());
511       return false;
512     } else if (!o->InstanceOf(m->GetDeclaringClass())) {
513       AbortF("can't call %s on instance of %s", m->PrettyMethod().c_str(),
514              o->PrettyTypeOf().c_str());
515       return false;
516     }
517     return true;
518   }
519 
520   /**
521    * The format string is a sequence of the following characters,
522    * and must be followed by arguments of the corresponding types
523    * in the same order.
524    *
525    * Java primitive types:
526    * B - jbyte
527    * C - jchar
528    * D - jdouble
529    * F - jfloat
530    * I - jint
531    * J - jlong
532    * S - jshort
533    * Z - jboolean (shown as true and false)
534    * V - void
535    *
536    * Java reference types:
537    * L - jobject
538    * a - jarray
539    * c - jclass
540    * s - jstring
541    *
542    * JNI types:
543    * b - jboolean (shown as JNI_TRUE and JNI_FALSE)
544    * f - jfieldID
545    * m - jmethodID
546    * p - void*
547    * r - jint (for release mode arguments)
548    * u - const char* (Modified UTF-8)
549    * z - jsize (for lengths; use i if negative values are okay)
550    * v - JavaVM*
551    * E - JNIEnv*
552    * . - VarArgs* for Jni calls with variable length arguments
553    *
554    * Use the kFlag_NullableUtf flag where 'u' field(s) are nullable.
555    */
Check(ScopedObjectAccess & soa,bool entry,const char * fmt,JniValueType * args)556   bool Check(ScopedObjectAccess& soa, bool entry, const char* fmt, JniValueType* args)
557       REQUIRES_SHARED(Locks::mutator_lock_) {
558     ArtMethod* traceMethod = nullptr;
559     if (has_method_ && soa.Vm()->IsTracingEnabled()) {
560       // We need to guard some of the invocation interface's calls: a bad caller might
561       // use DetachCurrentThread or GetEnv on a thread that's not yet attached.
562       Thread* self = Thread::Current();
563       if ((flags_ & kFlag_Invocation) == 0 || self != nullptr) {
564         traceMethod = self->GetCurrentMethod(nullptr);
565       }
566     }
567 
568     if (((flags_ & kFlag_ForceTrace) != 0) ||
569         (traceMethod != nullptr && soa.Vm()->ShouldTrace(traceMethod))) {
570       std::string msg;
571       for (size_t i = 0; fmt[i] != '\0'; ++i) {
572         TracePossibleHeapValue(soa, entry, fmt[i], args[i], &msg);
573         if (fmt[i + 1] != '\0') {
574           StringAppendF(&msg, ", ");
575         }
576       }
577 
578       if ((flags_ & kFlag_ForceTrace) != 0) {
579         LOG(INFO) << "JNI: call to " << function_name_ << "(" << msg << ")";
580       } else if (entry) {
581         if (has_method_) {
582           std::string methodName(ArtMethod::PrettyMethod(traceMethod, false));
583           LOG(INFO) << "JNI: " << methodName << " -> " << function_name_ << "(" << msg << ")";
584           indent_ = methodName.size() + 1;
585         } else {
586           LOG(INFO) << "JNI: -> " << function_name_ << "(" << msg << ")";
587           indent_ = 0;
588         }
589       } else {
590         LOG(INFO) << StringPrintf("JNI: %*s<- %s returned %s", indent_, "", function_name_, msg.c_str());
591       }
592     }
593 
594     // We always do the thorough checks on entry, and never on exit...
595     if (entry) {
596       for (size_t i = 0; fmt[i] != '\0'; ++i) {
597         if (!CheckPossibleHeapValue(soa, fmt[i], args[i])) {
598           return false;
599         }
600       }
601     }
602     return true;
603   }
604 
CheckNonHeap(JavaVMExt * vm,bool entry,const char * fmt,JniValueType * args)605   bool CheckNonHeap(JavaVMExt* vm, bool entry, const char* fmt, JniValueType* args) {
606     bool should_trace = (flags_ & kFlag_ForceTrace) != 0;
607     if (!should_trace && vm != nullptr && vm->IsTracingEnabled()) {
608       // We need to guard some of the invocation interface's calls: a bad caller might
609       // use DetachCurrentThread or GetEnv on a thread that's not yet attached.
610       Thread* self = Thread::Current();
611       if ((flags_ & kFlag_Invocation) == 0 || self != nullptr) {
612         ScopedObjectAccess soa(self);
613         ArtMethod* traceMethod = self->GetCurrentMethod(nullptr);
614         should_trace = (traceMethod != nullptr && vm->ShouldTrace(traceMethod));
615       }
616     }
617     if (should_trace) {
618       std::string msg;
619       for (size_t i = 0; fmt[i] != '\0'; ++i) {
620         TraceNonHeapValue(fmt[i], args[i], &msg);
621         if (fmt[i + 1] != '\0') {
622           StringAppendF(&msg, ", ");
623         }
624       }
625 
626       if ((flags_ & kFlag_ForceTrace) != 0) {
627         LOG(INFO) << "JNI: call to " << function_name_ << "(" << msg << ")";
628       } else if (entry) {
629         if (has_method_) {
630           Thread* self = Thread::Current();
631           ScopedObjectAccess soa(self);
632           ArtMethod* traceMethod = self->GetCurrentMethod(nullptr);
633           std::string methodName(ArtMethod::PrettyMethod(traceMethod, false));
634           LOG(INFO) << "JNI: " << methodName << " -> " << function_name_ << "(" << msg << ")";
635           indent_ = methodName.size() + 1;
636         } else {
637           LOG(INFO) << "JNI: -> " << function_name_ << "(" << msg << ")";
638           indent_ = 0;
639         }
640       } else {
641         LOG(INFO) << StringPrintf("JNI: %*s<- %s returned %s", indent_, "", function_name_, msg.c_str());
642       }
643     }
644 
645     // We always do the thorough checks on entry, and never on exit...
646     if (entry) {
647       for (size_t i = 0; fmt[i] != '\0'; ++i) {
648         if (!CheckNonHeapValue(fmt[i], args[i])) {
649           return false;
650         }
651       }
652     }
653     return true;
654   }
655 
CheckReflectedMethod(ScopedObjectAccess & soa,jobject jmethod)656   bool CheckReflectedMethod(ScopedObjectAccess& soa, jobject jmethod)
657       REQUIRES_SHARED(Locks::mutator_lock_) {
658     ObjPtr<mirror::Object> method = soa.Decode<mirror::Object>(jmethod);
659     if (method == nullptr) {
660       AbortF("expected non-null method");
661       return false;
662     }
663     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
664         Runtime::Current()->GetClassLinker()->GetClassRoots();
665     ObjPtr<mirror::Class> c = method->GetClass();
666     if (c != GetClassRoot<mirror::Method>(class_roots) &&
667         c != GetClassRoot<mirror::Constructor>(class_roots)) {
668       AbortF("expected java.lang.reflect.Method or "
669           "java.lang.reflect.Constructor but got object of type %s: %p",
670           method->PrettyTypeOf().c_str(), jmethod);
671       return false;
672     }
673     return true;
674   }
675 
CheckConstructor(jmethodID mid)676   bool CheckConstructor(jmethodID mid) REQUIRES_SHARED(Locks::mutator_lock_) {
677     ArtMethod* method = jni::DecodeArtMethod(mid);
678     if (method == nullptr) {
679       AbortF("expected non-null constructor");
680       return false;
681     }
682     if (!method->IsConstructor() || method->IsStatic()) {
683       AbortF("expected a constructor but %s: %p", method->PrettyMethod().c_str(), mid);
684       return false;
685     }
686     return true;
687   }
688 
CheckReflectedField(ScopedObjectAccess & soa,jobject jfield)689   bool CheckReflectedField(ScopedObjectAccess& soa, jobject jfield)
690       REQUIRES_SHARED(Locks::mutator_lock_) {
691     ObjPtr<mirror::Object> field = soa.Decode<mirror::Object>(jfield);
692     if (field == nullptr) {
693       AbortF("expected non-null java.lang.reflect.Field");
694       return false;
695     }
696     ObjPtr<mirror::Class> c = field->GetClass();
697     if (GetClassRoot<mirror::Field>() != c) {
698       AbortF("expected java.lang.reflect.Field but got object of type %s: %p",
699              field->PrettyTypeOf().c_str(), jfield);
700       return false;
701     }
702     return true;
703   }
704 
CheckThrowable(ScopedObjectAccess & soa,jthrowable jobj)705   bool CheckThrowable(ScopedObjectAccess& soa, jthrowable jobj)
706       REQUIRES_SHARED(Locks::mutator_lock_) {
707     ObjPtr<mirror::Object> obj = soa.Decode<mirror::Object>(jobj);
708     if (!obj->GetClass()->IsThrowableClass()) {
709       AbortF("expected java.lang.Throwable but got object of type "
710              "%s: %p", obj->PrettyTypeOf().c_str(), obj.Ptr());
711       return false;
712     }
713     return true;
714   }
715 
CheckThrowableClass(ScopedObjectAccess & soa,jclass jc)716   bool CheckThrowableClass(ScopedObjectAccess& soa, jclass jc)
717       REQUIRES_SHARED(Locks::mutator_lock_) {
718     ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(jc);
719     if (!c->IsThrowableClass()) {
720       AbortF("expected java.lang.Throwable class but got object of "
721              "type %s: %p", c->PrettyDescriptor().c_str(), c.Ptr());
722       return false;
723     }
724     return true;
725   }
726 
CheckReferenceKind(IndirectRefKind expected_kind,Thread * self,jobject obj)727   bool CheckReferenceKind(IndirectRefKind expected_kind, Thread* self, jobject obj)
728       REQUIRES_SHARED(Locks::mutator_lock_) {
729     IndirectRefKind found_kind;
730     if (expected_kind == kLocal) {
731       found_kind = IndirectReferenceTable::GetIndirectRefKind(obj);
732       if (found_kind == kJniTransition &&
733           obj != nullptr &&
734           self->IsJniTransitionReference(obj)) {
735         found_kind = kLocal;
736       }
737     } else {
738       found_kind = IndirectReferenceTable::GetIndirectRefKind(obj);
739     }
740     if (obj != nullptr && found_kind != expected_kind) {
741       AbortF("expected reference of kind %s but found %s: %p",
742              GetIndirectRefKindString(expected_kind),
743              GetIndirectRefKindString(IndirectReferenceTable::GetIndirectRefKind(obj)),
744              obj);
745       return false;
746     }
747     return true;
748   }
749 
CheckInstantiableNonArray(ScopedObjectAccess & soa,jclass jc)750   bool CheckInstantiableNonArray(ScopedObjectAccess& soa, jclass jc)
751       REQUIRES_SHARED(Locks::mutator_lock_) {
752     ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(jc);
753     if (!c->IsInstantiableNonArray()) {
754       AbortF("can't make objects of type %s: %p", c->PrettyDescriptor().c_str(), c.Ptr());
755       return false;
756     }
757     return true;
758   }
759 
CheckPrimitiveArrayType(ScopedObjectAccess & soa,jarray array,Primitive::Type type)760   bool CheckPrimitiveArrayType(ScopedObjectAccess& soa, jarray array, Primitive::Type type)
761       REQUIRES_SHARED(Locks::mutator_lock_) {
762     if (!CheckArray(soa, array)) {
763       return false;
764     }
765     ObjPtr<mirror::Array> a = soa.Decode<mirror::Array>(array);
766     if (a->GetClass()->GetComponentType()->GetPrimitiveType() != type) {
767       AbortF("incompatible array type %s expected %s[]: %p",
768              a->GetClass()->PrettyDescriptor().c_str(), PrettyDescriptor(type).c_str(), array);
769       return false;
770     }
771     return true;
772   }
773 
CheckFieldAccess(ScopedObjectAccess & soa,jobject obj,jfieldID fid,bool is_static,Primitive::Type type)774   bool CheckFieldAccess(ScopedObjectAccess& soa, jobject obj, jfieldID fid, bool is_static,
775                         Primitive::Type type)
776       REQUIRES_SHARED(Locks::mutator_lock_) {
777     if (is_static && !CheckStaticFieldID(soa, down_cast<jclass>(obj), fid)) {
778       return false;
779     }
780     if (!is_static && !CheckInstanceFieldID(soa, obj, fid)) {
781       return false;
782     }
783     ArtField* field = jni::DecodeArtField(fid);
784     DCHECK(field != nullptr);  // Already checked by Check.
785     if (is_static != field->IsStatic()) {
786       AbortF("attempt to access %s field %s: %p",
787              field->IsStatic() ? "static" : "non-static", field->PrettyField().c_str(), fid);
788       return false;
789     }
790     if (type != field->GetTypeAsPrimitiveType()) {
791       AbortF("attempt to access field %s of type %s with the wrong type %s: %p",
792              field->PrettyField().c_str(),
793              PrettyDescriptor(field->GetTypeDescriptor()).c_str(),
794              PrettyDescriptor(type).c_str(), fid);
795       return false;
796     }
797     if (is_static) {
798       ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(obj);
799       if (o == nullptr || !o->IsClass()) {
800         AbortF("attempt to access static field %s with a class argument of type %s: %p",
801                field->PrettyField().c_str(), o->PrettyTypeOf().c_str(), fid);
802         return false;
803       }
804       ObjPtr<mirror::Class> c = o->AsClass();
805       if (!field->GetDeclaringClass()->IsAssignableFrom(c)) {
806         AbortF("attempt to access static field %s with an incompatible class argument of %s: %p",
807                field->PrettyField().c_str(), mirror::Class::PrettyDescriptor(c).c_str(), fid);
808         return false;
809       }
810     } else {
811       ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(obj);
812       if (o == nullptr || !field->GetDeclaringClass()->IsAssignableFrom(o->GetClass())) {
813         AbortF("attempt to access field %s from an object argument of type %s: %p",
814                field->PrettyField().c_str(), o->PrettyTypeOf().c_str(), fid);
815         return false;
816       }
817     }
818     return true;
819   }
820 
821  private:
822   enum InstanceKind {
823     kClass,
824     kDirectByteBuffer,
825     kObject,
826     kString,
827     kThrowable,
828   };
829 
830   /*
831    * Verify that "jobj" is a valid non-null object reference, and points to
832    * an instance of expectedClass.
833    *
834    * Because we're looking at an object on the GC heap, we have to switch
835    * to "running" mode before doing the checks.
836    */
CheckInstance(ScopedObjectAccess & soa,InstanceKind kind,jobject java_object,bool null_ok)837   bool CheckInstance(ScopedObjectAccess& soa, InstanceKind kind, jobject java_object, bool null_ok)
838       REQUIRES_SHARED(Locks::mutator_lock_) {
839     const char* what = nullptr;
840     switch (kind) {
841     case kClass:
842       what = "jclass";
843       break;
844     case kDirectByteBuffer:
845       what = "direct ByteBuffer";
846       break;
847     case kObject:
848       what = "jobject";
849       break;
850     case kString:
851       what = "jstring";
852       break;
853     case kThrowable:
854       what = "jthrowable";
855       break;
856     }
857 
858     if (java_object == nullptr) {
859       if (null_ok) {
860         return true;
861       } else {
862         AbortF("%s received NULL %s", function_name_, what);
863         return false;
864       }
865     }
866 
867     ObjPtr<mirror::Object> obj = nullptr;
868     IndirectRef ref = reinterpret_cast<IndirectRef>(java_object);
869     IndirectRefKind ref_kind = IndirectReferenceTable::GetIndirectRefKind(ref);
870     bool expect_null = false;
871     bool okay = true;
872     std::string error_msg;
873     if (ref_kind == kJniTransition) {
874       if (!soa.Self()->IsJniTransitionReference(java_object)) {
875         okay = false;
876         error_msg = "use of invalid jobject";
877       } else {
878         obj = soa.Decode<mirror::Object>(java_object);
879       }
880     } else if (ref_kind == kLocal) {
881       jni::LocalReferenceTable* lrt = GetLocalReferenceTable(soa);
882       okay = lrt->IsValidReference(java_object, &error_msg);
883       if (okay) {
884         obj = lrt->Get(ref);
885       }
886     } else {
887       IndirectReferenceTable* irt = GetIndirectReferenceTable(soa, ref_kind);
888       okay = irt->IsValidReference(java_object, &error_msg);
889       DCHECK_EQ(okay, error_msg.empty());
890       if (okay) {
891         // Note: The `IsValidReference()` checks for null but we do not prevent races,
892         // so the null check below can still fail. Even if it succeeds, another thread
893         // could delete the global or weak global before it's used by JNI.
894         if (ref_kind == kGlobal) {
895           obj = soa.Env()->GetVm()->DecodeGlobal(ref);
896         } else {
897           obj = soa.Env()->GetVm()->DecodeWeakGlobal(soa.Self(), ref);
898           if (Runtime::Current()->IsClearedJniWeakGlobal(obj)) {
899             obj = nullptr;
900             expect_null = true;
901           }
902         }
903       }
904     }
905     if (okay) {
906       if (!expect_null && obj == nullptr) {
907         okay = false;
908         error_msg = "deleted reference";
909       }
910       if (expect_null && !null_ok) {
911         okay = false;
912         error_msg = "cleared weak reference";
913       }
914     }
915     if (!okay) {
916       AbortF("JNI ERROR (app bug): %s is an invalid %s: %p (%s)",
917              what,
918              ToStr<IndirectRefKind>(ref_kind).c_str(),
919              java_object,
920              error_msg.c_str());
921       return false;
922     }
923 
924     if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(obj.Ptr())) {
925       Runtime::Current()->GetHeap()->DumpSpaces(LOG_STREAM(ERROR));
926       AbortF("%s is an invalid %s: %p (%p)",
927              what,
928              GetIndirectRefKindString(IndirectReferenceTable::GetIndirectRefKind(java_object)),
929              java_object,
930              obj.Ptr());
931       return false;
932     }
933 
934     switch (kind) {
935     case kClass:
936       okay = obj->IsClass();
937       break;
938     case kDirectByteBuffer:
939       UNIMPLEMENTED(FATAL);
940       UNREACHABLE();
941     case kString:
942       okay = obj->GetClass()->IsStringClass();
943       break;
944     case kThrowable:
945       okay = obj->GetClass()->IsThrowableClass();
946       break;
947     case kObject:
948       break;
949     }
950     if (!okay) {
951       AbortF("%s has wrong type: %s", what, mirror::Object::PrettyTypeOf(obj).c_str());
952       return false;
953     }
954 
955     return true;
956   }
957 
958   /*
959    * Verify that the "mode" argument passed to a primitive array Release
960    * function is one of the valid values.
961    */
CheckReleaseMode(jint mode)962   bool CheckReleaseMode(jint mode) {
963     if (mode != 0 && mode != JNI_COMMIT && mode != JNI_ABORT) {
964       AbortF("unknown value for release mode: %d", mode);
965       return false;
966     }
967     return true;
968   }
969 
CheckPossibleHeapValue(ScopedObjectAccess & soa,char fmt,JniValueType arg)970   bool CheckPossibleHeapValue(ScopedObjectAccess& soa, char fmt, JniValueType arg)
971       REQUIRES_SHARED(Locks::mutator_lock_) {
972     switch (fmt) {
973       case 'a':  // jarray
974         return CheckArray(soa, arg.a);
975       case 'c':  // jclass
976         return CheckInstance(soa, kClass, arg.c, false);
977       case 'f':  // jfieldID
978         return CheckFieldID(arg.f) != nullptr;
979       case 'm':  // jmethodID
980         return CheckMethodID(arg.m) != nullptr;
981       case 'r':  // release int
982         return CheckReleaseMode(arg.r);
983       case 's':  // jstring
984         return CheckInstance(soa, kString, arg.s, false);
985       case 't':  // jthrowable
986         return CheckInstance(soa, kThrowable, arg.t, false);
987       case 'E':  // JNIEnv*
988         return CheckThread(arg.E);
989       case 'L':  // jobject
990         return CheckInstance(soa, kObject, arg.L, true);
991       case '.':  // A VarArgs list
992         return CheckVarArgs(soa, arg.va);
993       default:
994         return CheckNonHeapValue(fmt, arg);
995     }
996   }
997 
CheckVarArgs(ScopedObjectAccess & soa,const VarArgs * args_p)998   bool CheckVarArgs(ScopedObjectAccess& soa, const VarArgs* args_p)
999       REQUIRES_SHARED(Locks::mutator_lock_) {
1000     CHECK(args_p != nullptr);
1001     VarArgs args(args_p->Clone());
1002     ArtMethod* m = CheckMethodID(args.GetMethodID());
1003     if (m == nullptr) {
1004       return false;
1005     }
1006     uint32_t len = 0;
1007     const char* shorty = m->GetShorty(&len);
1008     // Skip the return type
1009     CHECK_GE(len, 1u);
1010     len--;
1011     shorty++;
1012     for (uint32_t i = 0; i < len; i++) {
1013       if (!CheckPossibleHeapValue(soa, shorty[i], args.GetValue(shorty[i]))) {
1014         return false;
1015       }
1016     }
1017     return true;
1018   }
1019 
CheckNonHeapValue(char fmt,JniValueType arg)1020   bool CheckNonHeapValue(char fmt, JniValueType arg) {
1021     switch (fmt) {
1022       case 'p':  // TODO: pointer - null or readable?
1023       case 'v':  // JavaVM*
1024       case 'D':  // jdouble
1025       case 'F':  // jfloat
1026       case 'J':  // jlong
1027       case 'I':  // jint
1028         break;  // Ignored.
1029       case 'b':  // jboolean, why two? Fall-through.
1030       case 'Z':
1031         return CheckBoolean(arg.I);
1032       case 'B':  // jbyte
1033         return CheckByte(arg.I);
1034       case 'C':  // jchar
1035         return CheckChar(arg.I);
1036       case 'S':  // jshort
1037         return CheckShort(arg.I);
1038       case 'u':  // utf8
1039         if ((flags_ & kFlag_Release) != 0) {
1040           return CheckNonNull(arg.u);
1041         } else {
1042           bool nullable = ((flags_ & kFlag_NullableUtf) != 0);
1043           return CheckUtfString(arg.u, nullable);
1044         }
1045       case 'w':  // jobjectRefType
1046         switch (arg.w) {
1047           case JNIInvalidRefType:
1048           case JNILocalRefType:
1049           case JNIGlobalRefType:
1050           case JNIWeakGlobalRefType:
1051             break;
1052           default:
1053             AbortF("Unknown reference type");
1054             return false;
1055         }
1056         break;
1057       case 'z':  // jsize
1058         return CheckLengthPositive(arg.z);
1059       default:
1060         AbortF("unknown format specifier: '%c'", fmt);
1061         return false;
1062     }
1063     return true;
1064   }
1065 
TracePossibleHeapValue(ScopedObjectAccess & soa,bool entry,char fmt,JniValueType arg,std::string * msg)1066   void TracePossibleHeapValue(ScopedObjectAccess& soa, bool entry, char fmt, JniValueType arg,
1067                               std::string* msg)
1068       REQUIRES_SHARED(Locks::mutator_lock_) {
1069     switch (fmt) {
1070       case 'L':  // jobject fall-through.
1071       case 'a':  // jarray fall-through.
1072       case 's':  // jstring fall-through.
1073       case 't':  // jthrowable fall-through.
1074         if (arg.L == nullptr) {
1075           *msg += "NULL";
1076         } else {
1077           StringAppendF(msg, "%p", arg.L);
1078         }
1079         break;
1080       case 'c': {  // jclass
1081         jclass jc = arg.c;
1082         ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(jc);
1083         if (c == nullptr) {
1084           *msg += "NULL";
1085         } else if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(c.Ptr())) {
1086           StringAppendF(msg, "INVALID POINTER:%p", jc);
1087         } else if (!c->IsClass()) {
1088           *msg += "INVALID NON-CLASS OBJECT OF TYPE:" + c->PrettyTypeOf();
1089         } else {
1090           *msg += c->PrettyClass();
1091           if (!entry) {
1092             StringAppendF(msg, " (%p)", jc);
1093           }
1094         }
1095         break;
1096       }
1097       case 'f': {  // jfieldID
1098         jfieldID fid = arg.f;
1099         ArtField* f = jni::DecodeArtField(fid);
1100         *msg += ArtField::PrettyField(f);
1101         if (!entry) {
1102           StringAppendF(msg, " (%p)", fid);
1103         }
1104         break;
1105       }
1106       case 'm': {  // jmethodID
1107         jmethodID mid = arg.m;
1108         ArtMethod* m = jni::DecodeArtMethod(mid);
1109         *msg += ArtMethod::PrettyMethod(m);
1110         if (!entry) {
1111           StringAppendF(msg, " (%p)", mid);
1112         }
1113         break;
1114       }
1115       case '.': {
1116         const VarArgs* va = arg.va;
1117         VarArgs args(va->Clone());
1118         ArtMethod* m = jni::DecodeArtMethod(args.GetMethodID());
1119         uint32_t len;
1120         const char* shorty = m->GetShorty(&len);
1121         CHECK_GE(len, 1u);
1122         // Skip past return value.
1123         len--;
1124         shorty++;
1125         // Remove the previous ', ' from the message.
1126         msg->erase(msg->length() - 2);
1127         for (uint32_t i = 0; i < len; i++) {
1128           *msg += ", ";
1129           TracePossibleHeapValue(soa, entry, shorty[i], args.GetValue(shorty[i]), msg);
1130         }
1131         break;
1132       }
1133       default:
1134         TraceNonHeapValue(fmt, arg, msg);
1135         break;
1136     }
1137   }
1138 
TraceNonHeapValue(char fmt,JniValueType arg,std::string * msg)1139   void TraceNonHeapValue(char fmt, JniValueType arg, std::string* msg) {
1140     switch (fmt) {
1141       case 'B':  // jbyte
1142         if (arg.B >= 0 && arg.B < 10) {
1143           StringAppendF(msg, "%d", arg.B);
1144         } else {
1145           StringAppendF(msg, "%#x (%d)", arg.B, arg.B);
1146         }
1147         break;
1148       case 'C':  // jchar
1149         if (arg.C < 0x7f && arg.C >= ' ') {
1150           StringAppendF(msg, "U+%x ('%c')", arg.C, arg.C);
1151         } else {
1152           StringAppendF(msg, "U+%x", arg.C);
1153         }
1154         break;
1155       case 'F':  // jfloat
1156         StringAppendF(msg, "%g", arg.F);
1157         break;
1158       case 'D':  // jdouble
1159         StringAppendF(msg, "%g", arg.D);
1160         break;
1161       case 'S':  // jshort
1162         StringAppendF(msg, "%d", arg.S);
1163         break;
1164       case 'i':  // jint - fall-through.
1165       case 'I':  // jint
1166         StringAppendF(msg, "%d", arg.I);
1167         break;
1168       case 'J':  // jlong
1169         StringAppendF(msg, "%" PRId64, arg.J);
1170         break;
1171       case 'Z':  // jboolean
1172       case 'b':  // jboolean (JNI-style)
1173         *msg += arg.b == JNI_TRUE ? "true" : "false";
1174         break;
1175       case 'V':  // void
1176         DCHECK(arg.V == nullptr);
1177         *msg += "void";
1178         break;
1179       case 'v':  // JavaVM*
1180         StringAppendF(msg, "(JavaVM*)%p", arg.v);
1181         break;
1182       case 'E':
1183         StringAppendF(msg, "(JNIEnv*)%p", arg.E);
1184         break;
1185       case 'z':  // non-negative jsize
1186         // You might expect jsize to be size_t, but it's not; it's the same as jint.
1187         // We only treat this specially so we can do the non-negative check.
1188         // TODO: maybe this wasn't worth it?
1189         StringAppendF(msg, "%d", arg.z);
1190         break;
1191       case 'p':  // void* ("pointer")
1192         if (arg.p == nullptr) {
1193           *msg += "NULL";
1194         } else {
1195           StringAppendF(msg, "(void*) %p", arg.p);
1196         }
1197         break;
1198       case 'r': {  // jint (release mode)
1199         jint releaseMode = arg.r;
1200         if (releaseMode == 0) {
1201           *msg += "0";
1202         } else if (releaseMode == JNI_ABORT) {
1203           *msg += "JNI_ABORT";
1204         } else if (releaseMode == JNI_COMMIT) {
1205           *msg += "JNI_COMMIT";
1206         } else {
1207           StringAppendF(msg, "invalid release mode %d", releaseMode);
1208         }
1209         break;
1210       }
1211       case 'u':  // const char* (Modified UTF-8)
1212         if (arg.u == nullptr) {
1213           *msg += "NULL";
1214         } else {
1215           StringAppendF(msg, "\"%s\"", arg.u);
1216         }
1217         break;
1218       case 'w':  // jobjectRefType
1219         switch (arg.w) {
1220           case JNIInvalidRefType:
1221             *msg += "invalid reference type";
1222             break;
1223           case JNILocalRefType:
1224             *msg += "local ref type";
1225             break;
1226           case JNIGlobalRefType:
1227             *msg += "global ref type";
1228             break;
1229           case JNIWeakGlobalRefType:
1230             *msg += "weak global ref type";
1231             break;
1232           default:
1233             *msg += "unknown ref type";
1234             break;
1235         }
1236         break;
1237       default:
1238         LOG(FATAL) << function_name_ << ": unknown trace format specifier: '" << fmt << "'";
1239     }
1240   }
1241   /*
1242    * Verify that "array" is non-null and points to an Array object.
1243    *
1244    * Since we're dealing with objects, switch to "running" mode.
1245    */
CheckArray(ScopedObjectAccess & soa,jarray java_array)1246   bool CheckArray(ScopedObjectAccess& soa, jarray java_array)
1247       REQUIRES_SHARED(Locks::mutator_lock_) {
1248     if (UNLIKELY(java_array == nullptr)) {
1249       AbortF("jarray was NULL");
1250       return false;
1251     }
1252 
1253     ObjPtr<mirror::Array> a = soa.Decode<mirror::Array>(java_array);
1254     if (UNLIKELY(!Runtime::Current()->GetHeap()->IsValidObjectAddress(a.Ptr()))) {
1255       Runtime::Current()->GetHeap()->DumpSpaces(LOG_STREAM(ERROR));
1256       AbortF("jarray is an invalid %s: %p (%p)",
1257              GetIndirectRefKindString(IndirectReferenceTable::GetIndirectRefKind(java_array)),
1258              java_array,
1259              a.Ptr());
1260       return false;
1261     } else if (!a->IsArrayInstance()) {
1262       AbortF("jarray argument has non-array type: %s", a->PrettyTypeOf().c_str());
1263       return false;
1264     }
1265     return true;
1266   }
1267 
CheckBoolean(jint z)1268   bool CheckBoolean(jint z) {
1269     if (z != JNI_TRUE && z != JNI_FALSE) {
1270       // Note, broken booleans are always fatal.
1271       AbortF("unexpected jboolean value: %d", z);
1272       return false;
1273     }
1274     return true;
1275   }
1276 
CheckByte(jint b)1277   bool CheckByte(jint b) {
1278     if (b < std::numeric_limits<jbyte>::min() ||
1279         b > std::numeric_limits<jbyte>::max()) {
1280       if (kBrokenPrimitivesAreFatal) {
1281         AbortF("unexpected jbyte value: %d", b);
1282         return false;
1283       } else {
1284         LOG(WARNING) << "Unexpected jbyte value: " << b;
1285       }
1286     }
1287     return true;
1288   }
1289 
CheckShort(jint s)1290   bool CheckShort(jint s) {
1291     if (s < std::numeric_limits<jshort>::min() ||
1292         s > std::numeric_limits<jshort>::max()) {
1293       if (kBrokenPrimitivesAreFatal) {
1294         AbortF("unexpected jshort value: %d", s);
1295         return false;
1296       } else {
1297         LOG(WARNING) << "Unexpected jshort value: " << s;
1298       }
1299     }
1300     return true;
1301   }
1302 
CheckChar(jint c)1303   bool CheckChar(jint c) {
1304     if (c < std::numeric_limits<jchar>::min() ||
1305         c > std::numeric_limits<jchar>::max()) {
1306       if (kBrokenPrimitivesAreFatal) {
1307         AbortF("unexpected jchar value: %d", c);
1308         return false;
1309       } else {
1310         LOG(WARNING) << "Unexpected jchar value: " << c;
1311       }
1312     }
1313     return true;
1314   }
1315 
CheckLengthPositive(jsize length)1316   bool CheckLengthPositive(jsize length) {
1317     if (length < 0) {
1318       AbortF("negative jsize: %d", length);
1319       return false;
1320     }
1321     return true;
1322   }
1323 
CheckFieldID(jfieldID fid)1324   ArtField* CheckFieldID(jfieldID fid) REQUIRES_SHARED(Locks::mutator_lock_) {
1325     if (fid == nullptr) {
1326       AbortF("jfieldID was NULL");
1327       return nullptr;
1328     }
1329     ArtField* f = jni::DecodeArtField(fid);
1330     // TODO: Better check here.
1331     if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(f->GetDeclaringClass().Ptr())) {
1332       Runtime::Current()->GetHeap()->DumpSpaces(LOG_STREAM(ERROR));
1333       AbortF("invalid jfieldID: %p", fid);
1334       return nullptr;
1335     }
1336     return f;
1337   }
1338 
CheckMethodID(jmethodID mid)1339   ArtMethod* CheckMethodID(jmethodID mid) REQUIRES_SHARED(Locks::mutator_lock_) {
1340     if (mid == nullptr) {
1341       AbortF("jmethodID was NULL");
1342       return nullptr;
1343     }
1344     ArtMethod* m = jni::DecodeArtMethod(mid);
1345     // TODO: Better check here.
1346     if (!Runtime::Current()->GetHeap()->IsValidObjectAddress(m->GetDeclaringClass().Ptr())) {
1347       Runtime::Current()->GetHeap()->DumpSpaces(LOG_STREAM(ERROR));
1348       AbortF("invalid jmethodID: %p", mid);
1349       return nullptr;
1350     }
1351     return m;
1352   }
1353 
CheckThread(JNIEnv * env)1354   bool CheckThread(JNIEnv* env) REQUIRES_SHARED(Locks::mutator_lock_) {
1355     Thread* self = Thread::Current();
1356     CHECK(self != nullptr);
1357 
1358     // Get the current thread's JNIEnv by going through our TLS pointer.
1359     JNIEnvExt* threadEnv = self->GetJniEnv();
1360 
1361     // Verify that the current thread is (a) attached and (b) associated with
1362     // this particular instance of JNIEnv.
1363     if (env != threadEnv) {
1364       // Get the thread owning the JNIEnv that's being used.
1365       Thread* envThread = reinterpret_cast<JNIEnvExt*>(env)->GetSelf();
1366       AbortF("thread %s using JNIEnv* from thread %s",
1367              ToStr<Thread>(*self).c_str(), ToStr<Thread>(*envThread).c_str());
1368       return false;
1369     }
1370 
1371     // Verify that, if this thread previously made a critical "get" call, we
1372     // do the corresponding "release" call before we try anything else.
1373     switch (flags_ & kFlag_CritMask) {
1374     case kFlag_CritOkay:    // okay to call this method
1375       break;
1376     case kFlag_CritBad:     // not okay to call
1377       if (threadEnv->GetCritical() > 0) {
1378         AbortF("thread %s using JNI after critical get",
1379                ToStr<Thread>(*self).c_str());
1380         return false;
1381       }
1382       break;
1383     case kFlag_CritGet:     // this is a "get" call
1384       // Don't check here; we allow nested gets.
1385       if (threadEnv->GetCritical() == 0) {
1386         threadEnv->SetCriticalStartUs(self->GetCpuMicroTime());
1387       }
1388       threadEnv->SetCritical(threadEnv->GetCritical() + 1);
1389       break;
1390     case kFlag_CritRelease:  // this is a "release" call
1391       if (threadEnv->GetCritical() == 0) {
1392         AbortF("thread %s called too many critical releases",
1393                ToStr<Thread>(*self).c_str());
1394         return false;
1395       } else if (threadEnv->GetCritical() == 1) {
1396         // Leaving the critical region, possibly warn about long critical regions.
1397         uint64_t critical_duration_us = self->GetCpuMicroTime() - threadEnv->GetCriticalStartUs();
1398         if (critical_duration_us > kCriticalWarnTimeUs) {
1399           LOG(WARNING) << "JNI critical lock held for "
1400                        << PrettyDuration(UsToNs(critical_duration_us)) << " on " << *self;
1401         }
1402       }
1403       threadEnv->SetCritical(threadEnv->GetCritical() - 1);
1404       break;
1405     default:
1406       LOG(FATAL) << "Bad flags (internal error): " << flags_;
1407     }
1408 
1409     // Verify that, if an exception has been raised, the native code doesn't
1410     // make any JNI calls other than the Exception* methods.
1411     if ((flags_ & kFlag_ExcepOkay) == 0 && self->IsExceptionPending()) {
1412       mirror::Throwable* exception = self->GetException();
1413       AbortF("JNI %s called with pending exception %s",
1414              function_name_,
1415              exception->Dump().c_str());
1416       return false;
1417     }
1418     return true;
1419   }
1420 
1421   // Verifies that "bytes" points to valid Modified UTF-8 data.
CheckUtfString(const char * bytes,bool nullable)1422   bool CheckUtfString(const char* bytes, bool nullable) {
1423     if (bytes == nullptr) {
1424       if (!nullable) {
1425         AbortF("non-nullable const char* was NULL");
1426         return false;
1427       }
1428       return true;
1429     }
1430 
1431     const char* errorKind = nullptr;
1432     const uint8_t* utf8 = CheckUtfBytes(bytes, &errorKind);
1433     if (errorKind != nullptr) {
1434       // This is an expensive loop that will resize often, but this isn't supposed to hit in
1435       // practice anyways.
1436       std::ostringstream oss;
1437       oss << std::hex;
1438       const uint8_t* tmp = reinterpret_cast<const uint8_t*>(bytes);
1439       while (*tmp != 0) {
1440         if (tmp == utf8) {
1441           oss << "<";
1442         }
1443         oss << "0x" << std::setfill('0') << std::setw(2) << static_cast<uint32_t>(*tmp);
1444         if (tmp == utf8) {
1445           oss << '>';
1446         }
1447         tmp++;
1448         if (*tmp != 0) {
1449           oss << ' ';
1450         }
1451       }
1452 
1453       AbortF("input is not valid Modified UTF-8: illegal %s byte %#x\n"
1454           "    string: '%s'\n    input: '%s'", errorKind, *utf8, bytes, oss.str().c_str());
1455       return false;
1456     }
1457     return true;
1458   }
1459 
1460   // Checks whether |bytes| is valid modified UTF-8. We also accept 4 byte UTF
1461   // sequences in place of encoded surrogate pairs.
CheckUtfBytes(const char * bytes,const char ** errorKind)1462   static const uint8_t* CheckUtfBytes(const char* bytes, const char** errorKind) {
1463     while (*bytes != '\0') {
1464       const uint8_t* utf8 = reinterpret_cast<const uint8_t*>(bytes++);
1465       // Switch on the high four bits.
1466       switch (*utf8 >> 4) {
1467       case 0x00:
1468       case 0x01:
1469       case 0x02:
1470       case 0x03:
1471       case 0x04:
1472       case 0x05:
1473       case 0x06:
1474       case 0x07:
1475         // Bit pattern 0xxx. No need for any extra bytes.
1476         break;
1477       case 0x08:
1478       case 0x09:
1479       case 0x0a:
1480       case 0x0b:
1481          // Bit patterns 10xx, which are illegal start bytes.
1482         *errorKind = "start";
1483         return utf8;
1484       case 0x0f:
1485         // Bit pattern 1111, which might be the start of a 4 byte sequence.
1486         if ((*utf8 & 0x08) == 0) {
1487           // Bit pattern 1111 0xxx, which is the start of a 4 byte sequence.
1488           // We consume one continuation byte here, and fall through to consume two more.
1489           utf8 = reinterpret_cast<const uint8_t*>(bytes++);
1490           if ((*utf8 & 0xc0) != 0x80) {
1491             *errorKind = "continuation";
1492             return utf8;
1493           }
1494         } else {
1495           *errorKind = "start";
1496           return utf8;
1497         }
1498 
1499         // Fall through to the cases below to consume two more continuation bytes.
1500         FALLTHROUGH_INTENDED;
1501       case 0x0e:
1502         // Bit pattern 1110, so there are two additional bytes.
1503         utf8 = reinterpret_cast<const uint8_t*>(bytes++);
1504         if ((*utf8 & 0xc0) != 0x80) {
1505           *errorKind = "continuation";
1506           return utf8;
1507         }
1508 
1509         // Fall through to consume one more continuation byte.
1510         FALLTHROUGH_INTENDED;
1511       case 0x0c:
1512       case 0x0d:
1513         // Bit pattern 110x, so there is one additional byte.
1514         utf8 = reinterpret_cast<const uint8_t*>(bytes++);
1515         if ((*utf8 & 0xc0) != 0x80) {
1516           *errorKind = "continuation";
1517           return utf8;
1518         }
1519         break;
1520       }
1521     }
1522     return nullptr;
1523   }
1524 
AbortF(const char * fmt,...)1525   void AbortF(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))) {
1526     va_list args;
1527     va_start(args, fmt);
1528     Runtime::Current()->GetJavaVM()->JniAbortV(function_name_, fmt, args);
1529     va_end(args);
1530   }
1531 
1532   // The name of the JNI function being checked.
1533   const char* const function_name_;
1534 
1535   int indent_;
1536 
1537   const uint16_t flags_;
1538 
1539   const bool has_method_;
1540 
1541   DISALLOW_COPY_AND_ASSIGN(ScopedCheck);
1542 };
1543 
1544 /*
1545  * ===========================================================================
1546  *      Guarded arrays
1547  * ===========================================================================
1548  */
1549 
1550 /* this gets tucked in at the start of the buffer; struct size must be even */
1551 class GuardedCopy {
1552  public:
1553   /*
1554    * Create an over-sized buffer to hold the contents of "buf".  Copy it in,
1555    * filling in the area around it with guard data.
1556    */
Create(void * original_buf,size_t len,bool mod_okay)1557   static void* Create(void* original_buf, size_t len, bool mod_okay) {
1558     const size_t new_len = LengthIncludingRedZones(len);
1559     uint8_t* const new_buf = DebugAlloc(new_len);
1560 
1561     // If modification is not expected, grab a checksum.
1562     uLong adler = 0;
1563     if (!mod_okay) {
1564       adler = adler32(adler32(0L, Z_NULL, 0), reinterpret_cast<const Bytef*>(original_buf), len);
1565     }
1566 
1567     GuardedCopy* copy = new (new_buf) GuardedCopy(original_buf, len, adler);
1568 
1569     // Fill begin region with canary pattern.
1570     const size_t kStartCanaryLength = (GuardedCopy::kRedZoneSize / 2) - sizeof(GuardedCopy);
1571     for (size_t i = 0, j = 0; i < kStartCanaryLength; ++i) {
1572       const_cast<char*>(copy->StartRedZone())[i] = kCanary[j];
1573       if (kCanary[j] == '\0') {
1574         j = 0;
1575       } else {
1576         j++;
1577       }
1578     }
1579 
1580     // Copy the data in; note "len" could be zero.
1581     memcpy(const_cast<uint8_t*>(copy->BufferWithinRedZones()), original_buf, len);
1582 
1583     // Fill end region with canary pattern.
1584     for (size_t i = 0, j = 0; i < kEndCanaryLength; ++i) {
1585       const_cast<char*>(copy->EndRedZone())[i] = kCanary[j];
1586       if (kCanary[j] == '\0') {
1587         j = 0;
1588       } else {
1589         j++;
1590       }
1591     }
1592 
1593     return const_cast<uint8_t*>(copy->BufferWithinRedZones());
1594   }
1595 
1596   /*
1597    * Create a guarded copy of a primitive array.  Modifications to the copied
1598    * data are allowed.  Returns a pointer to the copied data.
1599    */
CreateGuardedPACopy(JNIEnv * env,const jarray java_array,jboolean * is_copy,void * original_ptr)1600   static void* CreateGuardedPACopy(JNIEnv* env, const jarray java_array, jboolean* is_copy,
1601                                    void* original_ptr) {
1602     ScopedObjectAccess soa(env);
1603 
1604     ObjPtr<mirror::Array> a = soa.Decode<mirror::Array>(java_array);
1605     size_t component_size = a->GetClass()->GetComponentSize();
1606     size_t byte_count = a->GetLength() * component_size;
1607     void* result = Create(original_ptr, byte_count, true);
1608     if (is_copy != nullptr) {
1609       *is_copy = JNI_TRUE;
1610     }
1611     return result;
1612   }
1613 
1614   /*
1615    * Perform the array "release" operation, which may or may not copy data
1616    * back into the managed heap, and may or may not release the underlying storage.
1617    */
ReleaseGuardedPACopy(const char * function_name,JNIEnv * env,jarray java_array,void * embedded_buf,int mode)1618   static void* ReleaseGuardedPACopy(const char* function_name,
1619                                     JNIEnv* env,
1620                                     [[maybe_unused]] jarray java_array,
1621                                     void* embedded_buf,
1622                                     int mode) {
1623     ScopedObjectAccess soa(env);
1624     if (!GuardedCopy::Check(function_name, embedded_buf, true)) {
1625       return nullptr;
1626     }
1627     GuardedCopy* const copy = FromEmbedded(embedded_buf);
1628     void* original_ptr = copy->original_ptr_;
1629     if (mode != JNI_ABORT) {
1630       memcpy(original_ptr, embedded_buf, copy->original_length_);
1631     }
1632     if (mode != JNI_COMMIT) {
1633       Destroy(embedded_buf);
1634     }
1635     return original_ptr;
1636   }
1637 
1638   /*
1639    * Free up the guard buffer, scrub it, and return the original pointer.
1640    */
Destroy(void * embedded_buf)1641   static void* Destroy(void* embedded_buf) {
1642     GuardedCopy* copy = FromEmbedded(embedded_buf);
1643     void* original_ptr = const_cast<void*>(copy->original_ptr_);
1644     size_t len = LengthIncludingRedZones(copy->original_length_);
1645     DebugFree(copy, len);
1646     return original_ptr;
1647   }
1648 
1649   /*
1650    * Verify the guard area and, if "modOkay" is false, that the data itself
1651    * has not been altered.
1652    *
1653    * The caller has already checked that "dataBuf" is non-null.
1654    */
Check(const char * function_name,const void * embedded_buf,bool mod_okay)1655   static bool Check(const char* function_name, const void* embedded_buf, bool mod_okay) {
1656     const GuardedCopy* copy = FromEmbedded(embedded_buf);
1657     return copy->CheckHeader(function_name, mod_okay) && copy->CheckRedZones(function_name);
1658   }
1659 
1660  private:
GuardedCopy(void * original_buf,size_t len,uLong adler)1661   GuardedCopy(void* original_buf, size_t len, uLong adler) :
1662     magic_(kGuardMagic), adler_(adler), original_ptr_(original_buf), original_length_(len) {
1663   }
1664 
DebugAlloc(size_t len)1665   static uint8_t* DebugAlloc(size_t len) {
1666     void* result = mmap(nullptr, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
1667     if (result == MAP_FAILED) {
1668       PLOG(FATAL) << "GuardedCopy::create mmap(" << len << ") failed";
1669     }
1670     return reinterpret_cast<uint8_t*>(result);
1671   }
1672 
DebugFree(void * buf,size_t len)1673   static void DebugFree(void* buf, size_t len) {
1674     if (munmap(buf, len) != 0) {
1675       PLOG(FATAL) << "munmap(" << buf << ", " << len << ") failed";
1676     }
1677   }
1678 
LengthIncludingRedZones(size_t len)1679   static size_t LengthIncludingRedZones(size_t len) {
1680     return len + kRedZoneSize;
1681   }
1682 
1683   // Get the GuardedCopy from the interior pointer.
FromEmbedded(void * embedded_buf)1684   static GuardedCopy* FromEmbedded(void* embedded_buf) {
1685     return reinterpret_cast<GuardedCopy*>(
1686         reinterpret_cast<uint8_t*>(embedded_buf) - (kRedZoneSize / 2));
1687   }
1688 
FromEmbedded(const void * embedded_buf)1689   static const GuardedCopy* FromEmbedded(const void* embedded_buf) {
1690     return reinterpret_cast<const GuardedCopy*>(
1691         reinterpret_cast<const uint8_t*>(embedded_buf) - (kRedZoneSize / 2));
1692   }
1693 
AbortF(const char * jni_function_name,const char * fmt,...)1694   static void AbortF(const char* jni_function_name, const char* fmt, ...) {
1695     va_list args;
1696     va_start(args, fmt);
1697     Runtime::Current()->GetJavaVM()->JniAbortV(jni_function_name, fmt, args);
1698     va_end(args);
1699   }
1700 
CheckHeader(const char * function_name,bool mod_okay) const1701   bool CheckHeader(const char* function_name, bool mod_okay) const {
1702     static const uint32_t kMagicCmp = kGuardMagic;
1703 
1704     // Before we do anything with "pExtra", check the magic number.  We
1705     // do the check with memcmp rather than "==" in case the pointer is
1706     // unaligned.  If it points to completely bogus memory we're going
1707     // to crash, but there's no easy way around that.
1708     if (UNLIKELY(memcmp(&magic_, &kMagicCmp, 4) != 0)) {
1709       uint8_t buf[4];
1710       memcpy(buf, &magic_, 4);
1711       AbortF(function_name,
1712              "guard magic does not match (found 0x%02x%02x%02x%02x) -- incorrect data pointer %p?",
1713              buf[3], buf[2], buf[1], buf[0], this);  // Assumes little-endian.
1714       return false;
1715     }
1716 
1717     // If modification is not expected, verify checksum. Strictly speaking this is wrong: if we
1718     // told the client that we made a copy, there's no reason they can't alter the buffer.
1719     if (!mod_okay) {
1720       uLong computed_adler =
1721           adler32(adler32(0L, Z_NULL, 0), BufferWithinRedZones(), original_length_);
1722       if (computed_adler != adler_) {
1723         AbortF(function_name, "buffer modified (0x%08lx vs 0x%08lx) at address %p",
1724                computed_adler, adler_, this);
1725         return false;
1726       }
1727     }
1728     return true;
1729   }
1730 
CheckRedZones(const char * function_name) const1731   bool CheckRedZones(const char* function_name) const {
1732     // Check the begin red zone.
1733     const size_t kStartCanaryLength = (GuardedCopy::kRedZoneSize / 2) - sizeof(GuardedCopy);
1734     for (size_t i = 0, j = 0; i < kStartCanaryLength; ++i) {
1735       if (UNLIKELY(StartRedZone()[i] != kCanary[j])) {
1736         AbortF(function_name, "guard pattern before buffer disturbed at %p +%zd", this, i);
1737         return false;
1738       }
1739       if (kCanary[j] == '\0') {
1740         j = 0;
1741       } else {
1742         j++;
1743       }
1744     }
1745 
1746     // Check end region.
1747     for (size_t i = 0, j = 0; i < kEndCanaryLength; ++i) {
1748       if (UNLIKELY(EndRedZone()[i] != kCanary[j])) {
1749         size_t offset_from_buffer_start =
1750             &(EndRedZone()[i]) - &(StartRedZone()[kStartCanaryLength]);
1751         AbortF(function_name, "guard pattern after buffer disturbed at %p +%zd", this,
1752                offset_from_buffer_start);
1753         return false;
1754       }
1755       if (kCanary[j] == '\0') {
1756         j = 0;
1757       } else {
1758         j++;
1759       }
1760     }
1761     return true;
1762   }
1763 
1764   // Location that canary value will be written before the guarded region.
StartRedZone() const1765   const char* StartRedZone() const {
1766     const uint8_t* buf = reinterpret_cast<const uint8_t*>(this);
1767     return reinterpret_cast<const char*>(buf + sizeof(GuardedCopy));
1768   }
1769 
1770   // Return the interior embedded buffer.
BufferWithinRedZones() const1771   const uint8_t* BufferWithinRedZones() const {
1772     const uint8_t* embedded_buf = reinterpret_cast<const uint8_t*>(this) + (kRedZoneSize / 2);
1773     return embedded_buf;
1774   }
1775 
1776   // Location that canary value will be written after the guarded region.
EndRedZone() const1777   const char* EndRedZone() const {
1778     const uint8_t* buf = reinterpret_cast<const uint8_t*>(this);
1779     size_t buf_len = LengthIncludingRedZones(original_length_);
1780     return reinterpret_cast<const char*>(buf + (buf_len - (kRedZoneSize / 2)));
1781   }
1782 
1783   static constexpr size_t kRedZoneSize = 512;
1784   static constexpr size_t kEndCanaryLength = kRedZoneSize / 2;
1785 
1786   // Value written before and after the guarded array.
1787   static const char* const kCanary;
1788 
1789   static constexpr uint32_t kGuardMagic = 0xffd5aa96;
1790 
1791   const uint32_t magic_;
1792   const uLong adler_;
1793   void* const original_ptr_;
1794   const size_t original_length_;
1795 };
1796 const char* const GuardedCopy::kCanary = "JNI BUFFER RED ZONE";
1797 
1798 /*
1799  * ===========================================================================
1800  *      JNI functions
1801  * ===========================================================================
1802  */
1803 
1804 class CheckJNI {
1805  public:
GetVersion(JNIEnv * env)1806   static jint GetVersion(JNIEnv* env) {
1807     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
1808     ScopedObjectAccess soa(env);
1809     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1810     JniValueType args[1] = {{.E = env }};
1811     if (sc.Check(soa, true, "E", args)) {
1812       JniValueType result;
1813       result.I = baseEnv(env)->GetVersion(env);
1814       if (sc.Check(soa, false, "I", &result)) {
1815         return result.I;
1816       }
1817     }
1818     return JNI_ERR;
1819   }
1820 
GetJavaVM(JNIEnv * env,JavaVM ** vm)1821   static jint GetJavaVM(JNIEnv *env, JavaVM **vm) {
1822     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
1823     ScopedObjectAccess soa(env);
1824     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1825     JniValueType args[2] = {{.E = env }, {.p = vm}};
1826     if (sc.Check(soa, true, "Ep", args)) {
1827       JniValueType result;
1828       result.i = baseEnv(env)->GetJavaVM(env, vm);
1829       if (sc.Check(soa, false, "i", &result)) {
1830         return result.i;
1831       }
1832     }
1833     return JNI_ERR;
1834   }
1835 
RegisterNatives(JNIEnv * env,jclass c,const JNINativeMethod * methods,jint nMethods)1836   static jint RegisterNatives(JNIEnv* env, jclass c, const JNINativeMethod* methods, jint nMethods) {
1837     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
1838     ScopedObjectAccess soa(env);
1839     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1840     JniValueType args[4] = {{.E = env }, {.c = c}, {.p = methods}, {.I = nMethods}};
1841     if (sc.Check(soa, true, "EcpI", args)) {
1842       JniValueType result;
1843       result.i = baseEnv(env)->RegisterNatives(env, c, methods, nMethods);
1844       if (sc.Check(soa, false, "i", &result)) {
1845         return result.i;
1846       }
1847     }
1848     return JNI_ERR;
1849   }
1850 
UnregisterNatives(JNIEnv * env,jclass c)1851   static jint UnregisterNatives(JNIEnv* env, jclass c) {
1852     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
1853     ScopedObjectAccess soa(env);
1854     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1855     JniValueType args[2] = {{.E = env }, {.c = c}};
1856     if (sc.Check(soa, true, "Ec", args)) {
1857       JniValueType result;
1858       result.i = baseEnv(env)->UnregisterNatives(env, c);
1859       if (sc.Check(soa, false, "i", &result)) {
1860         return result.i;
1861       }
1862     }
1863     return JNI_ERR;
1864   }
1865 
GetObjectRefType(JNIEnv * env,jobject obj)1866   static jobjectRefType GetObjectRefType(JNIEnv* env, jobject obj) {
1867     CHECK_ATTACHED_THREAD(__FUNCTION__, JNIInvalidRefType);
1868     // Note: we use "EL" here but "Ep" has been used in the past on the basis that we'd like to
1869     // know the object is invalid. The spec says that passing invalid objects or even ones that
1870     // are deleted isn't supported.
1871     ScopedObjectAccess soa(env);
1872     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1873     JniValueType args[2] = {{.E = env }, {.L = obj}};
1874     if (sc.Check(soa, true, "EL", args)) {
1875       JniValueType result;
1876       result.w = baseEnv(env)->GetObjectRefType(env, obj);
1877       if (sc.Check(soa, false, "w", &result)) {
1878         return result.w;
1879       }
1880     }
1881     return JNIInvalidRefType;
1882   }
1883 
DefineClass(JNIEnv * env,const char * name,jobject loader,const jbyte * buf,jsize bufLen)1884   static jclass DefineClass(JNIEnv* env, const char* name, jobject loader, const jbyte* buf,
1885                             jsize bufLen) {
1886     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
1887     ScopedObjectAccess soa(env);
1888     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1889     JniValueType args[5] = {{.E = env}, {.u = name}, {.L = loader}, {.p = buf}, {.z = bufLen}};
1890     if (sc.Check(soa, true, "EuLpz", args) && sc.CheckClassName(name)) {
1891       JniValueType result;
1892       result.c = baseEnv(env)->DefineClass(env, name, loader, buf, bufLen);
1893       if (sc.Check(soa, false, "c", &result)) {
1894         return result.c;
1895       }
1896     }
1897     return nullptr;
1898   }
1899 
FindClass(JNIEnv * env,const char * name)1900   static jclass FindClass(JNIEnv* env, const char* name) {
1901     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
1902     ScopedObjectAccess soa(env);
1903     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1904     JniValueType args[2] = {{.E = env}, {.u = name}};
1905     if (sc.Check(soa, true, "Eu", args) && sc.CheckClassName(name)) {
1906       JniValueType result;
1907       result.c = baseEnv(env)->FindClass(env, name);
1908       if (sc.Check(soa, false, "c", &result)) {
1909         return result.c;
1910       }
1911     }
1912     return nullptr;
1913   }
1914 
GetSuperclass(JNIEnv * env,jclass c)1915   static jclass GetSuperclass(JNIEnv* env, jclass c) {
1916     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
1917     ScopedObjectAccess soa(env);
1918     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1919     JniValueType args[2] = {{.E = env}, {.c = c}};
1920     if (sc.Check(soa, true, "Ec", args)) {
1921       JniValueType result;
1922       result.c = baseEnv(env)->GetSuperclass(env, c);
1923       if (sc.Check(soa, false, "c", &result)) {
1924         return result.c;
1925       }
1926     }
1927     return nullptr;
1928   }
1929 
IsAssignableFrom(JNIEnv * env,jclass c1,jclass c2)1930   static jboolean IsAssignableFrom(JNIEnv* env, jclass c1, jclass c2) {
1931     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_FALSE);
1932     ScopedObjectAccess soa(env);
1933     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1934     JniValueType args[3] = {{.E = env}, {.c = c1}, {.c = c2}};
1935     if (sc.Check(soa, true, "Ecc", args)) {
1936       JniValueType result;
1937       result.b = baseEnv(env)->IsAssignableFrom(env, c1, c2);
1938       if (sc.Check(soa, false, "b", &result)) {
1939         return result.b;
1940       }
1941     }
1942     return JNI_FALSE;
1943   }
1944 
FromReflectedMethod(JNIEnv * env,jobject method)1945   static jmethodID FromReflectedMethod(JNIEnv* env, jobject method) {
1946     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
1947     ScopedObjectAccess soa(env);
1948     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1949     JniValueType args[2] = {{.E = env}, {.L = method}};
1950     if (sc.Check(soa, true, "EL", args) && sc.CheckReflectedMethod(soa, method)) {
1951       JniValueType result;
1952       result.m = baseEnv(env)->FromReflectedMethod(env, method);
1953       if (sc.Check(soa, false, "m", &result)) {
1954         return result.m;
1955       }
1956     }
1957     return nullptr;
1958   }
1959 
FromReflectedField(JNIEnv * env,jobject field)1960   static jfieldID FromReflectedField(JNIEnv* env, jobject field) {
1961     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
1962     ScopedObjectAccess soa(env);
1963     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1964     JniValueType args[2] = {{.E = env}, {.L = field}};
1965     if (sc.Check(soa, true, "EL", args) && sc.CheckReflectedField(soa, field)) {
1966       JniValueType result;
1967       result.f = baseEnv(env)->FromReflectedField(env, field);
1968       if (sc.Check(soa, false, "f", &result)) {
1969         return result.f;
1970       }
1971     }
1972     return nullptr;
1973   }
1974 
ToReflectedMethod(JNIEnv * env,jclass cls,jmethodID mid,jboolean isStatic)1975   static jobject ToReflectedMethod(JNIEnv* env, jclass cls, jmethodID mid, jboolean isStatic) {
1976     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
1977     ScopedObjectAccess soa(env);
1978     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1979     JniValueType args[4] = {{.E = env}, {.c = cls}, {.m = mid}, {.I = isStatic}};
1980     if (sc.Check(soa, true, "Ecmb", args)) {
1981       JniValueType result;
1982       result.L = baseEnv(env)->ToReflectedMethod(env, cls, mid, isStatic);
1983       if (sc.Check(soa, false, "L", &result) && (result.L != nullptr)) {
1984         DCHECK(sc.CheckReflectedMethod(soa, result.L));
1985         return result.L;
1986       }
1987     }
1988     return nullptr;
1989   }
1990 
ToReflectedField(JNIEnv * env,jclass cls,jfieldID fid,jboolean isStatic)1991   static jobject ToReflectedField(JNIEnv* env, jclass cls, jfieldID fid, jboolean isStatic) {
1992     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
1993     ScopedObjectAccess soa(env);
1994     ScopedCheck sc(kFlag_Default, __FUNCTION__);
1995     JniValueType args[4] = {{.E = env}, {.c = cls}, {.f = fid}, {.I = isStatic}};
1996     if (sc.Check(soa, true, "Ecfb", args)) {
1997       JniValueType result;
1998       result.L = baseEnv(env)->ToReflectedField(env, cls, fid, isStatic);
1999       if (sc.Check(soa, false, "L", &result) && (result.L != nullptr)) {
2000         DCHECK(sc.CheckReflectedField(soa, result.L));
2001         return result.L;
2002       }
2003     }
2004     return nullptr;
2005   }
2006 
Throw(JNIEnv * env,jthrowable obj)2007   static jint Throw(JNIEnv* env, jthrowable obj) {
2008     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2009     ScopedObjectAccess soa(env);
2010     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2011     JniValueType args[2] = {{.E = env}, {.t = obj}};
2012     if (sc.Check(soa, true, "Et", args) && sc.CheckThrowable(soa, obj)) {
2013       JniValueType result;
2014       result.i = baseEnv(env)->Throw(env, obj);
2015       if (sc.Check(soa, false, "i", &result)) {
2016         return result.i;
2017       }
2018     }
2019     return JNI_ERR;
2020   }
2021 
ThrowNew(JNIEnv * env,jclass c,const char * message)2022   static jint ThrowNew(JNIEnv* env, jclass c, const char* message) {
2023     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2024     ScopedObjectAccess soa(env);
2025     ScopedCheck sc(kFlag_NullableUtf, __FUNCTION__);
2026     JniValueType args[3] = {{.E = env}, {.c = c}, {.u = message}};
2027     if (sc.Check(soa, true, "Ecu", args) && sc.CheckThrowableClass(soa, c)) {
2028       JniValueType result;
2029       result.i = baseEnv(env)->ThrowNew(env, c, message);
2030       if (sc.Check(soa, false, "i", &result)) {
2031         return result.i;
2032       }
2033     }
2034     return JNI_ERR;
2035   }
2036 
ExceptionOccurred(JNIEnv * env)2037   static jthrowable ExceptionOccurred(JNIEnv* env) {
2038     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2039     ScopedObjectAccess soa(env);
2040     ScopedCheck sc(kFlag_ExcepOkay, __FUNCTION__);
2041     JniValueType args[1] = {{.E = env}};
2042     if (sc.Check(soa, true, "E", args)) {
2043       JniValueType result;
2044       result.t = baseEnv(env)->ExceptionOccurred(env);
2045       if (sc.Check(soa, false, "t", &result)) {
2046         return result.t;
2047       }
2048     }
2049     return nullptr;
2050   }
2051 
ExceptionDescribe(JNIEnv * env)2052   static void ExceptionDescribe(JNIEnv* env) {
2053     CHECK_ATTACHED_THREAD_VOID(__FUNCTION__);
2054     ScopedObjectAccess soa(env);
2055     ScopedCheck sc(kFlag_ExcepOkay, __FUNCTION__);
2056     JniValueType args[1] = {{.E = env}};
2057     if (sc.Check(soa, true, "E", args)) {
2058       JniValueType result;
2059       baseEnv(env)->ExceptionDescribe(env);
2060       result.V = nullptr;
2061       sc.Check(soa, false, "V", &result);
2062     }
2063   }
2064 
ExceptionClear(JNIEnv * env)2065   static void ExceptionClear(JNIEnv* env) {
2066     CHECK_ATTACHED_THREAD_VOID(__FUNCTION__);
2067     ScopedObjectAccess soa(env);
2068     ScopedCheck sc(kFlag_ExcepOkay, __FUNCTION__);
2069     JniValueType args[1] = {{.E = env}};
2070     if (sc.Check(soa, true, "E", args)) {
2071       JniValueType result;
2072       baseEnv(env)->ExceptionClear(env);
2073       result.V = nullptr;
2074       sc.Check(soa, false, "V", &result);
2075     }
2076   }
2077 
ExceptionCheck(JNIEnv * env)2078   static jboolean ExceptionCheck(JNIEnv* env) {
2079     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_FALSE);
2080     ScopedObjectAccess soa(env);
2081     ScopedCheck sc(kFlag_CritOkay | kFlag_ExcepOkay, __FUNCTION__);
2082     JniValueType args[1] = {{.E = env}};
2083     if (sc.Check(soa, true, "E", args)) {
2084       JniValueType result;
2085       result.b = baseEnv(env)->ExceptionCheck(env);
2086       if (sc.Check(soa, false, "b", &result)) {
2087         return result.b;
2088       }
2089     }
2090     return JNI_FALSE;
2091   }
2092 
FatalError(JNIEnv * env,const char * msg)2093   static void FatalError(JNIEnv* env, const char* msg) {
2094     CHECK_ATTACHED_THREAD_VOID(__FUNCTION__);
2095     // The JNI specification doesn't say it's okay to call FatalError with a pending exception,
2096     // but you're about to abort anyway, and it's quite likely that you have a pending exception,
2097     // and it's not unimaginable that you don't know that you do. So we allow it.
2098     ScopedObjectAccess soa(env);
2099     ScopedCheck sc(kFlag_ExcepOkay | kFlag_NullableUtf, __FUNCTION__);
2100     JniValueType args[2] = {{.E = env}, {.u = msg}};
2101     if (sc.Check(soa, true, "Eu", args)) {
2102       JniValueType result;
2103       baseEnv(env)->FatalError(env, msg);
2104       // Unreachable.
2105       result.V = nullptr;
2106       sc.Check(soa, false, "V", &result);
2107     }
2108   }
2109 
PushLocalFrame(JNIEnv * env,jint capacity)2110   static jint PushLocalFrame(JNIEnv* env, jint capacity) {
2111     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2112     ScopedObjectAccess soa(env);
2113     ScopedCheck sc(kFlag_ExcepOkay, __FUNCTION__);
2114     JniValueType args[2] = {{.E = env}, {.I = capacity}};
2115     if (sc.Check(soa, true, "EI", args)) {
2116       JniValueType result;
2117       result.i = baseEnv(env)->PushLocalFrame(env, capacity);
2118       if (sc.Check(soa, false, "i", &result)) {
2119         return result.i;
2120       }
2121     }
2122     return JNI_ERR;
2123   }
2124 
PopLocalFrame(JNIEnv * env,jobject res)2125   static jobject PopLocalFrame(JNIEnv* env, jobject res) {
2126     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2127     ScopedObjectAccess soa(env);
2128     ScopedCheck sc(kFlag_ExcepOkay, __FUNCTION__);
2129     JniValueType args[2] = {{.E = env}, {.L = res}};
2130     if (sc.Check(soa, true, "EL", args)) {
2131       JniValueType result;
2132       result.L = baseEnv(env)->PopLocalFrame(env, res);
2133       sc.Check(soa, false, "L", &result);
2134       return result.L;
2135     }
2136     return nullptr;
2137   }
2138 
NewGlobalRef(JNIEnv * env,jobject obj)2139   static jobject NewGlobalRef(JNIEnv* env, jobject obj) {
2140     return NewRef(__FUNCTION__, env, obj, kGlobal);
2141   }
2142 
NewLocalRef(JNIEnv * env,jobject obj)2143   static jobject NewLocalRef(JNIEnv* env, jobject obj) {
2144     return NewRef(__FUNCTION__, env, obj, kLocal);
2145   }
2146 
NewWeakGlobalRef(JNIEnv * env,jobject obj)2147   static jweak NewWeakGlobalRef(JNIEnv* env, jobject obj) {
2148     return NewRef(__FUNCTION__, env, obj, kWeakGlobal);
2149   }
2150 
DeleteGlobalRef(JNIEnv * env,jobject obj)2151   static void DeleteGlobalRef(JNIEnv* env, jobject obj) {
2152     DeleteRef(__FUNCTION__, env, obj, kGlobal);
2153   }
2154 
DeleteWeakGlobalRef(JNIEnv * env,jweak obj)2155   static void DeleteWeakGlobalRef(JNIEnv* env, jweak obj) {
2156     DeleteRef(__FUNCTION__, env, obj, kWeakGlobal);
2157   }
2158 
DeleteLocalRef(JNIEnv * env,jobject obj)2159   static void DeleteLocalRef(JNIEnv* env, jobject obj) {
2160     DeleteRef(__FUNCTION__, env, obj, kLocal);
2161   }
2162 
EnsureLocalCapacity(JNIEnv * env,jint capacity)2163   static jint EnsureLocalCapacity(JNIEnv *env, jint capacity) {
2164     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2165     ScopedObjectAccess soa(env);
2166     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2167     JniValueType args[2] = {{.E = env}, {.I = capacity}};
2168     if (sc.Check(soa, true, "EI", args)) {
2169       JniValueType result;
2170       result.i = baseEnv(env)->EnsureLocalCapacity(env, capacity);
2171       if (sc.Check(soa, false, "i", &result)) {
2172         return result.i;
2173       }
2174     }
2175     return JNI_ERR;
2176   }
2177 
IsSameObject(JNIEnv * env,jobject ref1,jobject ref2)2178   static jboolean IsSameObject(JNIEnv* env, jobject ref1, jobject ref2) {
2179     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_FALSE);
2180     ScopedObjectAccess soa(env);
2181     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2182     JniValueType args[3] = {{.E = env}, {.L = ref1}, {.L = ref2}};
2183     if (sc.Check(soa, true, "ELL", args)) {
2184       JniValueType result;
2185       result.b = baseEnv(env)->IsSameObject(env, ref1, ref2);
2186       if (sc.Check(soa, false, "b", &result)) {
2187         return result.b;
2188       }
2189     }
2190     return JNI_FALSE;
2191   }
2192 
AllocObject(JNIEnv * env,jclass c)2193   static jobject AllocObject(JNIEnv* env, jclass c) {
2194     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2195     ScopedObjectAccess soa(env);
2196     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2197     JniValueType args[2] = {{.E = env}, {.c = c}};
2198     if (sc.Check(soa, true, "Ec", args) && sc.CheckInstantiableNonArray(soa, c)) {
2199       JniValueType result;
2200       result.L = baseEnv(env)->AllocObject(env, c);
2201       if (sc.Check(soa, false, "L", &result)) {
2202         return result.L;
2203       }
2204     }
2205     return nullptr;
2206   }
2207 
NewObjectV(JNIEnv * env,jclass c,jmethodID mid,va_list vargs)2208   static jobject NewObjectV(JNIEnv* env, jclass c, jmethodID mid, va_list vargs) {
2209     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2210     ScopedObjectAccess soa(env);
2211     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2212     VarArgs rest(mid, vargs);
2213     JniValueType args[4] = {{.E = env}, {.c = c}, {.m = mid}, {.va = &rest}};
2214     if (sc.Check(soa, true, "Ecm.", args) && sc.CheckInstantiableNonArray(soa, c) &&
2215         sc.CheckConstructor(mid)) {
2216       JniValueType result;
2217       result.L = baseEnv(env)->NewObjectV(env, c, mid, vargs);
2218       if (sc.Check(soa, false, "L", &result)) {
2219         return result.L;
2220       }
2221     }
2222     return nullptr;
2223   }
2224 
NewObject(JNIEnv * env,jclass c,jmethodID mid,...)2225   static jobject NewObject(JNIEnv* env, jclass c, jmethodID mid, ...) {
2226     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2227     va_list args;
2228     va_start(args, mid);
2229     jobject result = NewObjectV(env, c, mid, args);
2230     va_end(args);
2231     return result;
2232   }
2233 
NewObjectA(JNIEnv * env,jclass c,jmethodID mid,const jvalue * vargs)2234   static jobject NewObjectA(JNIEnv* env, jclass c, jmethodID mid, const jvalue* vargs) {
2235     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2236     ScopedObjectAccess soa(env);
2237     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2238     VarArgs rest(mid, vargs);
2239     JniValueType args[4] = {{.E = env}, {.c = c}, {.m = mid}, {.va = &rest}};
2240     if (sc.Check(soa, true, "Ecm.", args) && sc.CheckInstantiableNonArray(soa, c) &&
2241         sc.CheckConstructor(mid)) {
2242       JniValueType result;
2243       result.L = baseEnv(env)->NewObjectA(env, c, mid, vargs);
2244       if (sc.Check(soa, false, "L", &result)) {
2245         return result.L;
2246       }
2247     }
2248     return nullptr;
2249   }
2250 
GetObjectClass(JNIEnv * env,jobject obj)2251   static jclass GetObjectClass(JNIEnv* env, jobject obj) {
2252     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2253     ScopedObjectAccess soa(env);
2254     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2255     JniValueType args[2] = {{.E = env}, {.L = obj}};
2256     if (sc.Check(soa, true, "EL", args)) {
2257       JniValueType result;
2258       result.c = baseEnv(env)->GetObjectClass(env, obj);
2259       if (sc.Check(soa, false, "c", &result)) {
2260         return result.c;
2261       }
2262     }
2263     return nullptr;
2264   }
2265 
IsInstanceOf(JNIEnv * env,jobject obj,jclass c)2266   static jboolean IsInstanceOf(JNIEnv* env, jobject obj, jclass c) {
2267     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_FALSE);
2268     ScopedObjectAccess soa(env);
2269     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2270     JniValueType args[3] = {{.E = env}, {.L = obj}, {.c = c}};
2271     if (sc.Check(soa, true, "ELc", args)) {
2272       JniValueType result;
2273       result.b = baseEnv(env)->IsInstanceOf(env, obj, c);
2274       if (sc.Check(soa, false, "b", &result)) {
2275         return result.b;
2276       }
2277     }
2278     return JNI_FALSE;
2279   }
2280 
GetMethodID(JNIEnv * env,jclass c,const char * name,const char * sig)2281   static jmethodID GetMethodID(JNIEnv* env, jclass c, const char* name, const char* sig) {
2282     return GetMethodIDInternal(__FUNCTION__, env, c, name, sig, false);
2283   }
2284 
GetStaticMethodID(JNIEnv * env,jclass c,const char * name,const char * sig)2285   static jmethodID GetStaticMethodID(JNIEnv* env, jclass c, const char* name, const char* sig) {
2286     return GetMethodIDInternal(__FUNCTION__, env, c, name, sig, true);
2287   }
2288 
GetFieldID(JNIEnv * env,jclass c,const char * name,const char * sig)2289   static jfieldID GetFieldID(JNIEnv* env, jclass c, const char* name, const char* sig) {
2290     return GetFieldIDInternal(__FUNCTION__, env, c, name, sig, false);
2291   }
2292 
GetStaticFieldID(JNIEnv * env,jclass c,const char * name,const char * sig)2293   static jfieldID GetStaticFieldID(JNIEnv* env, jclass c, const char* name, const char* sig) {
2294     return GetFieldIDInternal(__FUNCTION__, env, c, name, sig, true);
2295   }
2296 
2297 #define FIELD_ACCESSORS(jtype, name, ptype, shorty, slot_sized_shorty)  \
2298   static jtype GetStatic##name##Field(JNIEnv* env, jclass c, jfieldID fid) { \
2299     return GetField(__FUNCTION__, env, c, fid, true, ptype).shorty; \
2300   } \
2301   \
2302   static jtype Get##name##Field(JNIEnv* env, jobject obj, jfieldID fid) { \
2303     return GetField(__FUNCTION__, env, obj, fid, false, ptype).shorty; \
2304   } \
2305   \
2306   static void SetStatic##name##Field(JNIEnv* env, jclass c, jfieldID fid, jtype v) { \
2307     JniValueType value; \
2308     value.slot_sized_shorty = v; \
2309     SetField(__FUNCTION__, env, c, fid, true, ptype, value); \
2310   } \
2311   \
2312   static void Set##name##Field(JNIEnv* env, jobject obj, jfieldID fid, jtype v) { \
2313     JniValueType value; \
2314     value.slot_sized_shorty = v; \
2315     SetField(__FUNCTION__, env, obj, fid, false, ptype, value); \
2316   }
2317 
FIELD_ACCESSORS(jobject,Object,Primitive::kPrimNot,L,L)2318   FIELD_ACCESSORS(jobject, Object, Primitive::kPrimNot, L, L)
2319   FIELD_ACCESSORS(jboolean, Boolean, Primitive::kPrimBoolean, Z, I)
2320   FIELD_ACCESSORS(jbyte, Byte, Primitive::kPrimByte, B, I)
2321   FIELD_ACCESSORS(jchar, Char, Primitive::kPrimChar, C, I)
2322   FIELD_ACCESSORS(jshort, Short, Primitive::kPrimShort, S, I)
2323   FIELD_ACCESSORS(jint, Int, Primitive::kPrimInt, I, I)
2324   FIELD_ACCESSORS(jlong, Long, Primitive::kPrimLong, J, J)
2325   FIELD_ACCESSORS(jfloat, Float, Primitive::kPrimFloat, F, F)
2326   FIELD_ACCESSORS(jdouble, Double, Primitive::kPrimDouble, D, D)
2327 #undef FIELD_ACCESSORS
2328 
2329   static void CallVoidMethodA(JNIEnv* env, jobject obj, jmethodID mid, const jvalue* vargs) {
2330     CallMethodA(__FUNCTION__, env, obj, nullptr, mid, vargs, Primitive::kPrimVoid, kVirtual);
2331   }
2332 
CallNonvirtualVoidMethodA(JNIEnv * env,jobject obj,jclass c,jmethodID mid,const jvalue * vargs)2333   static void CallNonvirtualVoidMethodA(JNIEnv* env, jobject obj, jclass c, jmethodID mid,
2334                                         const jvalue* vargs) {
2335     CallMethodA(__FUNCTION__, env, obj, c, mid, vargs, Primitive::kPrimVoid, kDirect);
2336   }
2337 
CallStaticVoidMethodA(JNIEnv * env,jclass c,jmethodID mid,const jvalue * vargs)2338   static void CallStaticVoidMethodA(JNIEnv* env, jclass c, jmethodID mid, const jvalue* vargs) {
2339     CallMethodA(__FUNCTION__, env, nullptr, c, mid, vargs, Primitive::kPrimVoid, kStatic);
2340   }
2341 
CallVoidMethodV(JNIEnv * env,jobject obj,jmethodID mid,va_list vargs)2342   static void CallVoidMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list vargs) {
2343     CallMethodV(__FUNCTION__, env, obj, nullptr, mid, vargs, Primitive::kPrimVoid, kVirtual);
2344   }
2345 
CallNonvirtualVoidMethodV(JNIEnv * env,jobject obj,jclass c,jmethodID mid,va_list vargs)2346   static void CallNonvirtualVoidMethodV(JNIEnv* env, jobject obj, jclass c, jmethodID mid,
2347                                         va_list vargs) {
2348     CallMethodV(__FUNCTION__, env, obj, c, mid, vargs, Primitive::kPrimVoid, kDirect);
2349   }
2350 
2351   NO_STACK_PROTECTOR
CallStaticVoidMethodV(JNIEnv * env,jclass c,jmethodID mid,va_list vargs)2352   static void CallStaticVoidMethodV(JNIEnv* env, jclass c, jmethodID mid, va_list vargs) {
2353     CallMethodV(__FUNCTION__, env, nullptr, c, mid, vargs, Primitive::kPrimVoid, kStatic);
2354   }
2355 
CallVoidMethod(JNIEnv * env,jobject obj,jmethodID mid,...)2356   static void CallVoidMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
2357     va_list vargs;
2358     va_start(vargs, mid);
2359     CallMethodV(__FUNCTION__, env, obj, nullptr, mid, vargs, Primitive::kPrimVoid, kVirtual);
2360     va_end(vargs);
2361   }
2362 
CallNonvirtualVoidMethod(JNIEnv * env,jobject obj,jclass c,jmethodID mid,...)2363   static void CallNonvirtualVoidMethod(JNIEnv* env, jobject obj, jclass c, jmethodID mid, ...) {
2364     va_list vargs;
2365     va_start(vargs, mid);
2366     CallMethodV(__FUNCTION__, env, obj, c, mid, vargs, Primitive::kPrimVoid, kDirect);
2367     va_end(vargs);
2368   }
2369 
CallStaticVoidMethod(JNIEnv * env,jclass c,jmethodID mid,...)2370   static void CallStaticVoidMethod(JNIEnv* env, jclass c, jmethodID mid, ...) {
2371     va_list vargs;
2372     va_start(vargs, mid);
2373     CallMethodV(__FUNCTION__, env, nullptr, c, mid, vargs, Primitive::kPrimVoid, kStatic);
2374     va_end(vargs);
2375   }
2376 
2377 #define CALL(rtype, name, ptype, shorty) \
2378   static rtype Call##name##MethodA(JNIEnv* env, jobject obj, jmethodID mid, const jvalue* vargs) { \
2379     return CallMethodA(__FUNCTION__, env, obj, nullptr, mid, vargs, ptype, kVirtual).shorty; \
2380   } \
2381   \
2382   static rtype CallNonvirtual##name##MethodA(JNIEnv* env, jobject obj, jclass c, jmethodID mid, \
2383                                              const jvalue* vargs) { \
2384     return CallMethodA(__FUNCTION__, env, obj, c, mid, vargs, ptype, kDirect).shorty; \
2385   } \
2386   \
2387   static rtype CallStatic##name##MethodA(JNIEnv* env, jclass c, jmethodID mid, const jvalue* vargs) { \
2388     return CallMethodA(__FUNCTION__, env, nullptr, c, mid, vargs, ptype, kStatic).shorty; \
2389   } \
2390   \
2391   static rtype Call##name##MethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list vargs) { \
2392     return CallMethodV(__FUNCTION__, env, obj, nullptr, mid, vargs, ptype, kVirtual).shorty; \
2393   } \
2394   \
2395   static rtype CallNonvirtual##name##MethodV(JNIEnv* env, jobject obj, jclass c, jmethodID mid, \
2396                                              va_list vargs) { \
2397     return CallMethodV(__FUNCTION__, env, obj, c, mid, vargs, ptype, kDirect).shorty; \
2398   } \
2399   \
2400   static rtype CallStatic##name##MethodV(JNIEnv* env, jclass c, jmethodID mid, va_list vargs) { \
2401     return CallMethodV(__FUNCTION__, env, nullptr, c, mid, vargs, ptype, kStatic).shorty; \
2402   } \
2403   \
2404   static rtype Call##name##Method(JNIEnv* env, jobject obj, jmethodID mid, ...) { \
2405     va_list vargs; \
2406     va_start(vargs, mid); \
2407     rtype result = \
2408         CallMethodV(__FUNCTION__, env, obj, nullptr, mid, vargs, ptype, kVirtual).shorty; \
2409     va_end(vargs); \
2410     return result; \
2411   } \
2412   \
2413   static rtype CallNonvirtual##name##Method(JNIEnv* env, jobject obj, jclass c, jmethodID mid, \
2414                                             ...) { \
2415     va_list vargs; \
2416     va_start(vargs, mid); \
2417     rtype result = \
2418         CallMethodV(__FUNCTION__, env, obj, c, mid, vargs, ptype, kDirect).shorty; \
2419     va_end(vargs); \
2420     return result; \
2421   } \
2422   \
2423   static rtype CallStatic##name##Method(JNIEnv* env, jclass c, jmethodID mid, ...) { \
2424     va_list vargs; \
2425     va_start(vargs, mid); \
2426     rtype result = \
2427         CallMethodV(__FUNCTION__, env, nullptr, c, mid, vargs, ptype, kStatic).shorty; \
2428     va_end(vargs); \
2429     return result; \
2430   }
2431 
CALL(jobject,Object,Primitive::kPrimNot,L)2432   CALL(jobject, Object, Primitive::kPrimNot, L)
2433   CALL(jboolean, Boolean, Primitive::kPrimBoolean, Z)
2434   CALL(jbyte, Byte, Primitive::kPrimByte, B)
2435   CALL(jchar, Char, Primitive::kPrimChar, C)
2436   CALL(jshort, Short, Primitive::kPrimShort, S)
2437   CALL(jint, Int, Primitive::kPrimInt, I)
2438   CALL(jlong, Long, Primitive::kPrimLong, J)
2439   CALL(jfloat, Float, Primitive::kPrimFloat, F)
2440   CALL(jdouble, Double, Primitive::kPrimDouble, D)
2441 #undef CALL
2442 
2443   static jstring NewString(JNIEnv* env, const jchar* unicode_chars, jsize len) {
2444     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2445     ScopedObjectAccess soa(env);
2446     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2447     JniValueType args[3] = {{.E = env}, {.p = unicode_chars}, {.z = len}};
2448     if (sc.Check(soa, true, "Epz", args)) {
2449       JniValueType result;
2450       result.s = baseEnv(env)->NewString(env, unicode_chars, len);
2451       if (sc.Check(soa, false, "s", &result)) {
2452         return result.s;
2453       }
2454     }
2455     return nullptr;
2456   }
2457 
NewStringUTF(JNIEnv * env,const char * chars)2458   static jstring NewStringUTF(JNIEnv* env, const char* chars) {
2459     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2460     ScopedObjectAccess soa(env);
2461     ScopedCheck sc(kFlag_NullableUtf, __FUNCTION__);
2462     JniValueType args[2] = {{.E = env}, {.u = chars}};
2463     if (sc.Check(soa, true, "Eu", args)) {
2464       JniValueType result;
2465       // TODO: stale? show pointer and truncate string.
2466       result.s = baseEnv(env)->NewStringUTF(env, chars);
2467       if (sc.Check(soa, false, "s", &result)) {
2468         return result.s;
2469       }
2470     }
2471     return nullptr;
2472   }
2473 
GetStringLength(JNIEnv * env,jstring string)2474   static jsize GetStringLength(JNIEnv* env, jstring string) {
2475     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2476     ScopedObjectAccess soa(env);
2477     ScopedCheck sc(kFlag_CritOkay, __FUNCTION__);
2478     JniValueType args[2] = {{.E = env}, {.s = string}};
2479     if (sc.Check(soa, true, "Es", args)) {
2480       JniValueType result;
2481       result.z = baseEnv(env)->GetStringLength(env, string);
2482       if (sc.Check(soa, false, "z", &result)) {
2483         return result.z;
2484       }
2485     }
2486     return JNI_ERR;
2487   }
2488 
GetStringUTFLength(JNIEnv * env,jstring string)2489   static jsize GetStringUTFLength(JNIEnv* env, jstring string) {
2490     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2491     ScopedObjectAccess soa(env);
2492     ScopedCheck sc(kFlag_CritOkay, __FUNCTION__);
2493     JniValueType args[2] = {{.E = env}, {.s = string}};
2494     if (sc.Check(soa, true, "Es", args)) {
2495       JniValueType result;
2496       result.z = baseEnv(env)->GetStringUTFLength(env, string);
2497       if (sc.Check(soa, false, "z", &result)) {
2498         return result.z;
2499       }
2500     }
2501     return JNI_ERR;
2502   }
2503 
GetStringChars(JNIEnv * env,jstring string,jboolean * is_copy)2504   static const jchar* GetStringChars(JNIEnv* env, jstring string, jboolean* is_copy) {
2505     return reinterpret_cast<const jchar*>(GetStringCharsInternal(__FUNCTION__, env, string,
2506                                                                  is_copy, false, false));
2507   }
2508 
GetStringUTFChars(JNIEnv * env,jstring string,jboolean * is_copy)2509   static const char* GetStringUTFChars(JNIEnv* env, jstring string, jboolean* is_copy) {
2510     return reinterpret_cast<const char*>(GetStringCharsInternal(__FUNCTION__, env, string,
2511                                                                 is_copy, true, false));
2512   }
2513 
GetStringCritical(JNIEnv * env,jstring string,jboolean * is_copy)2514   static const jchar* GetStringCritical(JNIEnv* env, jstring string, jboolean* is_copy) {
2515     return reinterpret_cast<const jchar*>(GetStringCharsInternal(__FUNCTION__, env, string,
2516                                                                  is_copy, false, true));
2517   }
2518 
ReleaseStringChars(JNIEnv * env,jstring string,const jchar * chars)2519   static void ReleaseStringChars(JNIEnv* env, jstring string, const jchar* chars) {
2520     ReleaseStringCharsInternal(__FUNCTION__, env, string, chars, false, false);
2521   }
2522 
ReleaseStringUTFChars(JNIEnv * env,jstring string,const char * utf)2523   static void ReleaseStringUTFChars(JNIEnv* env, jstring string, const char* utf) {
2524     ReleaseStringCharsInternal(__FUNCTION__, env, string, utf, true, false);
2525   }
2526 
ReleaseStringCritical(JNIEnv * env,jstring string,const jchar * chars)2527   static void ReleaseStringCritical(JNIEnv* env, jstring string, const jchar* chars) {
2528     ReleaseStringCharsInternal(__FUNCTION__, env, string, chars, false, true);
2529   }
2530 
GetStringRegion(JNIEnv * env,jstring string,jsize start,jsize len,jchar * buf)2531   static void GetStringRegion(JNIEnv* env, jstring string, jsize start, jsize len, jchar* buf) {
2532     CHECK_ATTACHED_THREAD_VOID(__FUNCTION__);
2533     ScopedObjectAccess soa(env);
2534     ScopedCheck sc(kFlag_CritOkay, __FUNCTION__);
2535     JniValueType args[5] = {{.E = env}, {.s = string}, {.z = start}, {.z = len}, {.p = buf}};
2536     // Note: the start and len arguments are checked as 'I' rather than 'z' as invalid indices
2537     // result in ArrayIndexOutOfBoundsExceptions in the base implementation.
2538     if (sc.Check(soa, true, "EsIIp", args)) {
2539       baseEnv(env)->GetStringRegion(env, string, start, len, buf);
2540       JniValueType result;
2541       result.V = nullptr;
2542       sc.Check(soa, false, "V", &result);
2543     }
2544   }
2545 
GetStringUTFRegion(JNIEnv * env,jstring string,jsize start,jsize len,char * buf)2546   static void GetStringUTFRegion(JNIEnv* env, jstring string, jsize start, jsize len, char* buf) {
2547     CHECK_ATTACHED_THREAD_VOID(__FUNCTION__);
2548     ScopedObjectAccess soa(env);
2549     ScopedCheck sc(kFlag_CritOkay, __FUNCTION__);
2550     JniValueType args[5] = {{.E = env}, {.s = string}, {.z = start}, {.z = len}, {.p = buf}};
2551     // Note: the start and len arguments are checked as 'I' rather than 'z' as invalid indices
2552     // result in ArrayIndexOutOfBoundsExceptions in the base implementation.
2553     if (sc.Check(soa, true, "EsIIp", args)) {
2554       baseEnv(env)->GetStringUTFRegion(env, string, start, len, buf);
2555       JniValueType result;
2556       result.V = nullptr;
2557       sc.Check(soa, false, "V", &result);
2558     }
2559   }
2560 
GetArrayLength(JNIEnv * env,jarray array)2561   static jsize GetArrayLength(JNIEnv* env, jarray array) {
2562     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2563     ScopedObjectAccess soa(env);
2564     ScopedCheck sc(kFlag_CritOkay, __FUNCTION__);
2565     JniValueType args[2] = {{.E = env}, {.a = array}};
2566     if (sc.Check(soa, true, "Ea", args)) {
2567       JniValueType result;
2568       result.z = baseEnv(env)->GetArrayLength(env, array);
2569       if (sc.Check(soa, false, "z", &result)) {
2570         return result.z;
2571       }
2572     }
2573     return JNI_ERR;
2574   }
2575 
NewObjectArray(JNIEnv * env,jsize length,jclass element_class,jobject initial_element)2576   static jobjectArray NewObjectArray(JNIEnv* env, jsize length, jclass element_class,
2577                                      jobject initial_element) {
2578     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2579     ScopedObjectAccess soa(env);
2580     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2581     JniValueType args[4] =
2582         {{.E = env}, {.z = length}, {.c = element_class}, {.L = initial_element}};
2583     if (sc.Check(soa, true, "EzcL", args)) {
2584       JniValueType result;
2585       // Note: assignability tests of initial_element are done in the base implementation.
2586       result.a = baseEnv(env)->NewObjectArray(env, length, element_class, initial_element);
2587       if (sc.Check(soa, false, "a", &result)) {
2588         return down_cast<jobjectArray>(result.a);
2589       }
2590     }
2591     return nullptr;
2592   }
2593 
GetObjectArrayElement(JNIEnv * env,jobjectArray array,jsize index)2594   static jobject GetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index) {
2595     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2596     ScopedObjectAccess soa(env);
2597     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2598     JniValueType args[3] = {{.E = env}, {.a = array}, {.z = index}};
2599     if (sc.Check(soa, true, "Eaz", args)) {
2600       JniValueType result;
2601       result.L = baseEnv(env)->GetObjectArrayElement(env, array, index);
2602       if (sc.Check(soa, false, "L", &result)) {
2603         return result.L;
2604       }
2605     }
2606     return nullptr;
2607   }
2608 
SetObjectArrayElement(JNIEnv * env,jobjectArray array,jsize index,jobject value)2609   static void SetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, jobject value) {
2610     CHECK_ATTACHED_THREAD_VOID(__FUNCTION__);
2611     ScopedObjectAccess soa(env);
2612     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2613     JniValueType args[4] = {{.E = env}, {.a = array}, {.z = index}, {.L = value}};
2614     // Note: the index arguments is checked as 'I' rather than 'z' as invalid indices result in
2615     // ArrayIndexOutOfBoundsExceptions in the base implementation. Similarly invalid stores result
2616     // in ArrayStoreExceptions.
2617     if (sc.Check(soa, true, "EaIL", args)) {
2618       baseEnv(env)->SetObjectArrayElement(env, array, index, value);
2619       JniValueType result;
2620       result.V = nullptr;
2621       sc.Check(soa, false, "V", &result);
2622     }
2623   }
2624 
NewBooleanArray(JNIEnv * env,jsize length)2625   static jbooleanArray NewBooleanArray(JNIEnv* env, jsize length) {
2626     return down_cast<jbooleanArray>(NewPrimitiveArray(__FUNCTION__, env, length,
2627                                                       Primitive::kPrimBoolean));
2628   }
2629 
NewByteArray(JNIEnv * env,jsize length)2630   static jbyteArray NewByteArray(JNIEnv* env, jsize length) {
2631     return down_cast<jbyteArray>(NewPrimitiveArray(__FUNCTION__, env, length,
2632                                                    Primitive::kPrimByte));
2633   }
2634 
NewCharArray(JNIEnv * env,jsize length)2635   static jcharArray NewCharArray(JNIEnv* env, jsize length) {
2636     return down_cast<jcharArray>(NewPrimitiveArray(__FUNCTION__, env, length,
2637                                                    Primitive::kPrimChar));
2638   }
2639 
NewShortArray(JNIEnv * env,jsize length)2640   static jshortArray NewShortArray(JNIEnv* env, jsize length) {
2641     return down_cast<jshortArray>(NewPrimitiveArray(__FUNCTION__, env, length,
2642                                                     Primitive::kPrimShort));
2643   }
2644 
NewIntArray(JNIEnv * env,jsize length)2645   static jintArray NewIntArray(JNIEnv* env, jsize length) {
2646     return down_cast<jintArray>(NewPrimitiveArray(__FUNCTION__, env, length, Primitive::kPrimInt));
2647   }
2648 
NewLongArray(JNIEnv * env,jsize length)2649   static jlongArray NewLongArray(JNIEnv* env, jsize length) {
2650     return down_cast<jlongArray>(NewPrimitiveArray(__FUNCTION__, env, length,
2651                                                    Primitive::kPrimLong));
2652   }
2653 
NewFloatArray(JNIEnv * env,jsize length)2654   static jfloatArray NewFloatArray(JNIEnv* env, jsize length) {
2655     return down_cast<jfloatArray>(NewPrimitiveArray(__FUNCTION__, env, length,
2656                                                     Primitive::kPrimFloat));
2657   }
2658 
NewDoubleArray(JNIEnv * env,jsize length)2659   static jdoubleArray NewDoubleArray(JNIEnv* env, jsize length) {
2660     return down_cast<jdoubleArray>(NewPrimitiveArray(__FUNCTION__, env, length,
2661                                                      Primitive::kPrimDouble));
2662   }
2663 
2664 // NOLINT added to avoid wrong warning/fix from clang-tidy.
2665 #define PRIMITIVE_ARRAY_FUNCTIONS(ctype, name, ptype) \
2666   static ctype* Get##name##ArrayElements(JNIEnv* env, ctype##Array array, jboolean* is_copy) { /* NOLINT */ \
2667     return reinterpret_cast<ctype*>( /* NOLINT */ \
2668         GetPrimitiveArrayElements(__FUNCTION__, ptype, env, array, is_copy)); \
2669   } \
2670   \
2671   static void Release##name##ArrayElements(JNIEnv* env, ctype##Array array, ctype* elems, /* NOLINT */ \
2672                                            jint mode) { \
2673     ReleasePrimitiveArrayElements(__FUNCTION__, ptype, env, array, elems, mode); \
2674   } \
2675   \
2676   static void Get##name##ArrayRegion(JNIEnv* env, ctype##Array array, jsize start, jsize len, \
2677                                      ctype* buf) { /* NOLINT */ \
2678     GetPrimitiveArrayRegion(__FUNCTION__, ptype, env, array, start, len, buf); \
2679   } \
2680   \
2681   static void Set##name##ArrayRegion(JNIEnv* env, ctype##Array array, jsize start, jsize len, \
2682                                      const ctype* buf) { \
2683     SetPrimitiveArrayRegion(__FUNCTION__, ptype, env, array, start, len, buf); \
2684   }
2685 
PRIMITIVE_ARRAY_FUNCTIONS(jboolean,Boolean,Primitive::kPrimBoolean)2686   PRIMITIVE_ARRAY_FUNCTIONS(jboolean, Boolean, Primitive::kPrimBoolean)
2687   PRIMITIVE_ARRAY_FUNCTIONS(jbyte, Byte, Primitive::kPrimByte)
2688   PRIMITIVE_ARRAY_FUNCTIONS(jchar, Char, Primitive::kPrimChar)
2689   PRIMITIVE_ARRAY_FUNCTIONS(jshort, Short, Primitive::kPrimShort)
2690   PRIMITIVE_ARRAY_FUNCTIONS(jint, Int, Primitive::kPrimInt)
2691   PRIMITIVE_ARRAY_FUNCTIONS(jlong, Long, Primitive::kPrimLong)
2692   PRIMITIVE_ARRAY_FUNCTIONS(jfloat, Float, Primitive::kPrimFloat)
2693   PRIMITIVE_ARRAY_FUNCTIONS(jdouble, Double, Primitive::kPrimDouble)
2694 #undef PRIMITIVE_ARRAY_FUNCTIONS
2695 
2696   static jint MonitorEnter(JNIEnv* env, jobject obj) {
2697     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2698     ScopedObjectAccess soa(env);
2699     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2700     JniValueType args[2] = {{.E = env}, {.L = obj}};
2701     if (sc.Check(soa, true, "EL", args)) {
2702       if (obj != nullptr) {
2703         down_cast<JNIEnvExt*>(env)->RecordMonitorEnter(obj);
2704       }
2705       JniValueType result;
2706       result.i = baseEnv(env)->MonitorEnter(env, obj);
2707       if (sc.Check(soa, false, "i", &result)) {
2708         return result.i;
2709       }
2710     }
2711     return JNI_ERR;
2712   }
2713 
MonitorExit(JNIEnv * env,jobject obj)2714   static jint MonitorExit(JNIEnv* env, jobject obj) {
2715     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2716     ScopedObjectAccess soa(env);
2717     ScopedCheck sc(kFlag_ExcepOkay, __FUNCTION__);
2718     JniValueType args[2] = {{.E = env}, {.L = obj}};
2719     if (sc.Check(soa, true, "EL", args)) {
2720       if (obj != nullptr) {
2721         down_cast<JNIEnvExt*>(env)->CheckMonitorRelease(obj);
2722       }
2723       JniValueType result;
2724       result.i = baseEnv(env)->MonitorExit(env, obj);
2725       if (sc.Check(soa, false, "i", &result)) {
2726         return result.i;
2727       }
2728     }
2729     return JNI_ERR;
2730   }
2731 
GetPrimitiveArrayCritical(JNIEnv * env,jarray array,jboolean * is_copy)2732   static void* GetPrimitiveArrayCritical(JNIEnv* env, jarray array, jboolean* is_copy) {
2733     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2734     ScopedObjectAccess soa(env);
2735     ScopedCheck sc(kFlag_CritGet, __FUNCTION__);
2736     JniValueType args[3] = {{.E = env}, {.a = array}, {.p = is_copy}};
2737     if (sc.Check(soa, true, "Eap", args)) {
2738       JniValueType result;
2739       void* ptr = baseEnv(env)->GetPrimitiveArrayCritical(env, array, is_copy);
2740       if (ptr != nullptr && soa.ForceCopy()) {
2741         ptr = GuardedCopy::CreateGuardedPACopy(env, array, is_copy, ptr);
2742       }
2743       result.p = ptr;
2744       if (sc.Check(soa, false, "p", &result)) {
2745         return const_cast<void*>(result.p);
2746       }
2747     }
2748     return nullptr;
2749   }
2750 
ReleasePrimitiveArrayCritical(JNIEnv * env,jarray array,void * carray,jint mode)2751   static void ReleasePrimitiveArrayCritical(JNIEnv* env, jarray array, void* carray, jint mode) {
2752     CHECK_ATTACHED_THREAD_VOID(__FUNCTION__);
2753     ScopedObjectAccess soa(env);
2754     ScopedCheck sc(kFlag_CritRelease | kFlag_ExcepOkay, __FUNCTION__);
2755     sc.CheckNonNull(carray);
2756     JniValueType args[4] = {{.E = env}, {.a = array}, {.p = carray}, {.r = mode}};
2757     if (sc.Check(soa, true, "Eapr", args)) {
2758       if (soa.ForceCopy()) {
2759         carray = GuardedCopy::ReleaseGuardedPACopy(__FUNCTION__, env, array, carray, mode);
2760       }
2761       baseEnv(env)->ReleasePrimitiveArrayCritical(env, array, carray, mode);
2762       JniValueType result;
2763       result.V = nullptr;
2764       sc.Check(soa, false, "V", &result);
2765     }
2766   }
2767 
NewDirectByteBuffer(JNIEnv * env,void * address,jlong capacity)2768   static jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
2769     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2770     ScopedObjectAccess soa(env);
2771     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2772     JniValueType args[3] = {{.E = env}, {.p = address}, {.J = capacity}};
2773     if (sc.Check(soa, true, "EpJ", args)) {
2774       JniValueType result;
2775       // Note: the validity of address and capacity are checked in the base implementation.
2776       result.L = baseEnv(env)->NewDirectByteBuffer(env, address, capacity);
2777       if (sc.Check(soa, false, "L", &result)) {
2778         return result.L;
2779       }
2780     }
2781     return nullptr;
2782   }
2783 
GetDirectBufferAddress(JNIEnv * env,jobject buf)2784   static void* GetDirectBufferAddress(JNIEnv* env, jobject buf) {
2785     CHECK_ATTACHED_THREAD(__FUNCTION__, nullptr);
2786     ScopedObjectAccess soa(env);
2787     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2788     JniValueType args[2] = {{.E = env}, {.L = buf}};
2789     if (sc.Check(soa, true, "EL", args)) {
2790       JniValueType result;
2791       // Note: this is implemented in the base environment by a GetLongField which will check the
2792       // type of buf in GetLongField above.
2793       result.p = baseEnv(env)->GetDirectBufferAddress(env, buf);
2794       if (sc.Check(soa, false, "p", &result)) {
2795         return const_cast<void*>(result.p);
2796       }
2797     }
2798     return nullptr;
2799   }
2800 
GetDirectBufferCapacity(JNIEnv * env,jobject buf)2801   static jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf) {
2802     CHECK_ATTACHED_THREAD(__FUNCTION__, JNI_ERR);
2803     ScopedObjectAccess soa(env);
2804     ScopedCheck sc(kFlag_Default, __FUNCTION__);
2805     JniValueType args[2] = {{.E = env}, {.L = buf}};
2806     if (sc.Check(soa, true, "EL", args)) {
2807       JniValueType result;
2808       // Note: this is implemented in the base environment by a GetIntField which will check the
2809       // type of buf in GetIntField above.
2810       result.J = baseEnv(env)->GetDirectBufferCapacity(env, buf);
2811       if (sc.Check(soa, false, "J", &result)) {
2812         return result.J;
2813       }
2814     }
2815     return JNI_ERR;
2816   }
2817 
2818  private:
GetJavaVMExt(JNIEnv * env)2819   static JavaVMExt* GetJavaVMExt(JNIEnv* env) {
2820     return reinterpret_cast<JNIEnvExt*>(env)->GetVm();
2821   }
2822 
baseEnv(JNIEnv * env)2823   static const JNINativeInterface* baseEnv(JNIEnv* env) {
2824     return reinterpret_cast<JNIEnvExt*>(env)->GetUncheckedFunctions();
2825   }
2826 
NewRef(const char * function_name,JNIEnv * env,jobject obj,IndirectRefKind kind)2827   static jobject NewRef(const char* function_name, JNIEnv* env, jobject obj, IndirectRefKind kind) {
2828     CHECK_ATTACHED_THREAD(function_name, nullptr);
2829     ScopedObjectAccess soa(env);
2830     ScopedCheck sc(kFlag_Default, function_name);
2831     JniValueType args[2] = {{.E = env}, {.L = obj}};
2832     if (sc.Check(soa, true, "EL", args)) {
2833       JniValueType result;
2834       switch (kind) {
2835         case kGlobal:
2836           result.L = baseEnv(env)->NewGlobalRef(env, obj);
2837           break;
2838         case kLocal:
2839           result.L = baseEnv(env)->NewLocalRef(env, obj);
2840           break;
2841         case kWeakGlobal:
2842           result.L = baseEnv(env)->NewWeakGlobalRef(env, obj);
2843           break;
2844         default:
2845           LOG(FATAL) << "Unexpected reference kind: " << kind;
2846       }
2847       if (sc.Check(soa, false, "L", &result)) {
2848         DCHECK_EQ(IsSameObject(env, obj, result.L), JNI_TRUE);
2849         DCHECK(sc.CheckReferenceKind(kind, soa.Self(), result.L));
2850         return result.L;
2851       }
2852     }
2853     return nullptr;
2854   }
2855 
DeleteRef(const char * function_name,JNIEnv * env,jobject obj,IndirectRefKind kind)2856   static void DeleteRef(const char* function_name, JNIEnv* env, jobject obj, IndirectRefKind kind) {
2857     CHECK_ATTACHED_THREAD_VOID(function_name);
2858     ScopedObjectAccess soa(env);
2859     ScopedCheck sc(kFlag_ExcepOkay, function_name);
2860     JniValueType args[2] = {{.E = env}, {.L = obj}};
2861     sc.Check(soa, true, "EL", args);
2862     if (sc.CheckReferenceKind(kind, soa.Self(), obj)) {
2863       JniValueType result;
2864       switch (kind) {
2865         case kGlobal:
2866           baseEnv(env)->DeleteGlobalRef(env, obj);
2867           break;
2868         case kLocal:
2869           baseEnv(env)->DeleteLocalRef(env, obj);
2870           break;
2871         case kWeakGlobal:
2872           baseEnv(env)->DeleteWeakGlobalRef(env, obj);
2873           break;
2874         default:
2875           LOG(FATAL) << "Unexpected reference kind: " << kind;
2876       }
2877       result.V = nullptr;
2878       sc.Check(soa, false, "V", &result);
2879     }
2880   }
2881 
GetMethodIDInternal(const char * function_name,JNIEnv * env,jclass c,const char * name,const char * sig,bool is_static)2882   static jmethodID GetMethodIDInternal(const char* function_name, JNIEnv* env, jclass c,
2883                                        const char* name, const char* sig, bool is_static) {
2884     CHECK_ATTACHED_THREAD(function_name, nullptr);
2885     ScopedObjectAccess soa(env);
2886     ScopedCheck sc(kFlag_Default, function_name);
2887     JniValueType args[4] = {{.E = env}, {.c = c}, {.u = name}, {.u = sig}};
2888     if (sc.Check(soa, true, "Ecuu", args)) {
2889       JniValueType result;
2890       if (is_static) {
2891         result.m = baseEnv(env)->GetStaticMethodID(env, c, name, sig);
2892       } else {
2893         result.m = baseEnv(env)->GetMethodID(env, c, name, sig);
2894       }
2895       if (sc.Check(soa, false, "m", &result)) {
2896         return result.m;
2897       }
2898     }
2899     return nullptr;
2900   }
2901 
GetFieldIDInternal(const char * function_name,JNIEnv * env,jclass c,const char * name,const char * sig,bool is_static)2902   static jfieldID GetFieldIDInternal(const char* function_name, JNIEnv* env, jclass c,
2903                                      const char* name, const char* sig, bool is_static) {
2904     CHECK_ATTACHED_THREAD(function_name, nullptr);
2905     ScopedObjectAccess soa(env);
2906     ScopedCheck sc(kFlag_Default, function_name);
2907     JniValueType args[4] = {{.E = env}, {.c = c}, {.u = name}, {.u = sig}};
2908     if (sc.Check(soa, true, "Ecuu", args)) {
2909       JniValueType result;
2910       if (is_static) {
2911         result.f = baseEnv(env)->GetStaticFieldID(env, c, name, sig);
2912       } else {
2913         result.f = baseEnv(env)->GetFieldID(env, c, name, sig);
2914       }
2915       if (sc.Check(soa, false, "f", &result)) {
2916         return result.f;
2917       }
2918     }
2919     return nullptr;
2920   }
2921 
GetField(const char * function_name,JNIEnv * env,jobject obj,jfieldID fid,bool is_static,Primitive::Type type)2922   static JniValueType GetField(const char* function_name, JNIEnv* env, jobject obj, jfieldID fid,
2923                                bool is_static, Primitive::Type type) {
2924     CHECK_ATTACHED_THREAD(function_name, JniValueType());
2925     ScopedObjectAccess soa(env);
2926     ScopedCheck sc(kFlag_Default, function_name);
2927     JniValueType args[3] = {{.E = env}, {.L = obj}, {.f = fid}};
2928     JniValueType result;
2929     if (sc.Check(soa, true, is_static ? "Ecf" : "ELf", args) &&
2930         sc.CheckFieldAccess(soa, obj, fid, is_static, type)) {
2931       const char* result_check = nullptr;
2932       switch (type) {
2933         case Primitive::kPrimNot:
2934           if (is_static) {
2935             result.L = baseEnv(env)->GetStaticObjectField(env, down_cast<jclass>(obj), fid);
2936           } else {
2937             result.L = baseEnv(env)->GetObjectField(env, obj, fid);
2938           }
2939           result_check = "L";
2940           break;
2941         case Primitive::kPrimBoolean:
2942           if (is_static) {
2943             result.Z = baseEnv(env)->GetStaticBooleanField(env, down_cast<jclass>(obj), fid);
2944           } else {
2945             result.Z = baseEnv(env)->GetBooleanField(env, obj, fid);
2946           }
2947           result_check = "Z";
2948           break;
2949         case Primitive::kPrimByte:
2950           if (is_static) {
2951             result.B = baseEnv(env)->GetStaticByteField(env, down_cast<jclass>(obj), fid);
2952           } else {
2953             result.B = baseEnv(env)->GetByteField(env, obj, fid);
2954           }
2955           result_check = "B";
2956           break;
2957         case Primitive::kPrimChar:
2958           if (is_static) {
2959             result.C = baseEnv(env)->GetStaticCharField(env, down_cast<jclass>(obj), fid);
2960           } else {
2961             result.C = baseEnv(env)->GetCharField(env, obj, fid);
2962           }
2963           result_check = "C";
2964           break;
2965         case Primitive::kPrimShort:
2966           if (is_static) {
2967             result.S = baseEnv(env)->GetStaticShortField(env, down_cast<jclass>(obj), fid);
2968           } else {
2969             result.S = baseEnv(env)->GetShortField(env, obj, fid);
2970           }
2971           result_check = "S";
2972           break;
2973         case Primitive::kPrimInt:
2974           if (is_static) {
2975             result.I = baseEnv(env)->GetStaticIntField(env, down_cast<jclass>(obj), fid);
2976           } else {
2977             result.I = baseEnv(env)->GetIntField(env, obj, fid);
2978           }
2979           result_check = "I";
2980           break;
2981         case Primitive::kPrimLong:
2982           if (is_static) {
2983             result.J = baseEnv(env)->GetStaticLongField(env, down_cast<jclass>(obj), fid);
2984           } else {
2985             result.J = baseEnv(env)->GetLongField(env, obj, fid);
2986           }
2987           result_check = "J";
2988           break;
2989         case Primitive::kPrimFloat:
2990           if (is_static) {
2991             result.F = baseEnv(env)->GetStaticFloatField(env, down_cast<jclass>(obj), fid);
2992           } else {
2993             result.F = baseEnv(env)->GetFloatField(env, obj, fid);
2994           }
2995           result_check = "F";
2996           break;
2997         case Primitive::kPrimDouble:
2998           if (is_static) {
2999             result.D = baseEnv(env)->GetStaticDoubleField(env, down_cast<jclass>(obj), fid);
3000           } else {
3001             result.D = baseEnv(env)->GetDoubleField(env, obj, fid);
3002           }
3003           result_check = "D";
3004           break;
3005         case Primitive::kPrimVoid:
3006           LOG(FATAL) << "Unexpected type: " << type;
3007           UNREACHABLE();
3008       }
3009       if (sc.Check(soa, false, result_check, &result)) {
3010         return result;
3011       }
3012     }
3013     result.J = 0;
3014     return result;
3015   }
3016 
SetField(const char * function_name,JNIEnv * env,jobject obj,jfieldID fid,bool is_static,Primitive::Type type,JniValueType value)3017   static void SetField(const char* function_name, JNIEnv* env, jobject obj, jfieldID fid,
3018                        bool is_static, Primitive::Type type, JniValueType value) {
3019     CHECK_ATTACHED_THREAD_VOID(function_name);
3020     ScopedObjectAccess soa(env);
3021     ScopedCheck sc(kFlag_Default, function_name);
3022     JniValueType args[4] = {{.E = env}, {.L = obj}, {.f = fid}, value};
3023     char sig[5] = { 'E', is_static ? 'c' : 'L', 'f',
3024         type == Primitive::kPrimNot ? 'L' : Primitive::Descriptor(type)[0], '\0'};
3025     if (sc.Check(soa, true, sig, args) &&
3026         sc.CheckFieldAccess(soa, obj, fid, is_static, type)) {
3027       switch (type) {
3028         case Primitive::kPrimNot:
3029           if (is_static) {
3030             baseEnv(env)->SetStaticObjectField(env, down_cast<jclass>(obj), fid, value.L);
3031           } else {
3032             baseEnv(env)->SetObjectField(env, obj, fid, value.L);
3033           }
3034           break;
3035         case Primitive::kPrimBoolean:
3036           if (is_static) {
3037             baseEnv(env)->SetStaticBooleanField(env, down_cast<jclass>(obj), fid, value.Z);
3038           } else {
3039             baseEnv(env)->SetBooleanField(env, obj, fid, value.Z);
3040           }
3041           break;
3042         case Primitive::kPrimByte:
3043           if (is_static) {
3044             baseEnv(env)->SetStaticByteField(env, down_cast<jclass>(obj), fid, value.B);
3045           } else {
3046             baseEnv(env)->SetByteField(env, obj, fid, value.B);
3047           }
3048           break;
3049         case Primitive::kPrimChar:
3050           if (is_static) {
3051             baseEnv(env)->SetStaticCharField(env, down_cast<jclass>(obj), fid, value.C);
3052           } else {
3053             baseEnv(env)->SetCharField(env, obj, fid, value.C);
3054           }
3055           break;
3056         case Primitive::kPrimShort:
3057           if (is_static) {
3058             baseEnv(env)->SetStaticShortField(env, down_cast<jclass>(obj), fid, value.S);
3059           } else {
3060             baseEnv(env)->SetShortField(env, obj, fid, value.S);
3061           }
3062           break;
3063         case Primitive::kPrimInt:
3064           if (is_static) {
3065             baseEnv(env)->SetStaticIntField(env, down_cast<jclass>(obj), fid, value.I);
3066           } else {
3067             baseEnv(env)->SetIntField(env, obj, fid, value.I);
3068           }
3069           break;
3070         case Primitive::kPrimLong:
3071           if (is_static) {
3072             baseEnv(env)->SetStaticLongField(env, down_cast<jclass>(obj), fid, value.J);
3073           } else {
3074             baseEnv(env)->SetLongField(env, obj, fid, value.J);
3075           }
3076           break;
3077         case Primitive::kPrimFloat:
3078           if (is_static) {
3079             baseEnv(env)->SetStaticFloatField(env, down_cast<jclass>(obj), fid, value.F);
3080           } else {
3081             baseEnv(env)->SetFloatField(env, obj, fid, value.F);
3082           }
3083           break;
3084         case Primitive::kPrimDouble:
3085           if (is_static) {
3086             baseEnv(env)->SetStaticDoubleField(env, down_cast<jclass>(obj), fid, value.D);
3087           } else {
3088             baseEnv(env)->SetDoubleField(env, obj, fid, value.D);
3089           }
3090           break;
3091         case Primitive::kPrimVoid:
3092           LOG(FATAL) << "Unexpected type: " << type;
3093           UNREACHABLE();
3094       }
3095       JniValueType result;
3096       result.V = nullptr;
3097       sc.Check(soa, false, "V", &result);
3098     }
3099   }
3100 
CheckCallArgs(ScopedObjectAccess & soa,ScopedCheck & sc,JNIEnv * env,jobject obj,jclass c,jmethodID mid,InvokeType invoke,const VarArgs * vargs)3101   static bool CheckCallArgs(ScopedObjectAccess& soa, ScopedCheck& sc, JNIEnv* env, jobject obj,
3102                             jclass c, jmethodID mid, InvokeType invoke, const VarArgs* vargs)
3103       REQUIRES_SHARED(Locks::mutator_lock_) {
3104     bool checked;
3105     switch (invoke) {
3106       case kVirtual: {
3107         DCHECK(c == nullptr);
3108         JniValueType args[4] = {{.E = env}, {.L = obj}, {.m = mid}, {.va = vargs}};
3109         checked = sc.Check(soa, true, "ELm.", args);
3110         break;
3111       }
3112       case kDirect: {
3113         JniValueType args[5] = {{.E = env}, {.L = obj}, {.c = c}, {.m = mid}, {.va = vargs}};
3114         checked = sc.Check(soa, true, "ELcm.", args);
3115         break;
3116       }
3117       case kStatic: {
3118         DCHECK(obj == nullptr);
3119         JniValueType args[4] = {{.E = env}, {.c = c}, {.m = mid}, {.va = vargs}};
3120         checked = sc.Check(soa, true, "Ecm.", args);
3121         break;
3122       }
3123       default:
3124         LOG(FATAL) << "Unexpected invoke: " << invoke;
3125         checked = false;
3126         break;
3127     }
3128     return checked;
3129   }
3130 
CallMethodA(const char * function_name,JNIEnv * env,jobject obj,jclass c,jmethodID mid,const jvalue * vargs,Primitive::Type type,InvokeType invoke)3131   static JniValueType CallMethodA(const char* function_name, JNIEnv* env, jobject obj, jclass c,
3132                                   jmethodID mid, const jvalue* vargs, Primitive::Type type,
3133                                   InvokeType invoke) {
3134     CHECK_ATTACHED_THREAD(function_name, JniValueType());
3135     ScopedObjectAccess soa(env);
3136     ScopedCheck sc(kFlag_Default, function_name);
3137     JniValueType result;
3138     VarArgs rest(mid, vargs);
3139     if (CheckCallArgs(soa, sc, env, obj, c, mid, invoke, &rest) &&
3140         sc.CheckMethodAndSig(soa, obj, c, mid, type, invoke)) {
3141       const char* result_check;
3142       switch (type) {
3143         case Primitive::kPrimNot:
3144           result_check = "L";
3145           switch (invoke) {
3146             case kVirtual:
3147               result.L = baseEnv(env)->CallObjectMethodA(env, obj, mid, vargs);
3148               break;
3149             case kDirect:
3150               result.L = baseEnv(env)->CallNonvirtualObjectMethodA(env, obj, c, mid, vargs);
3151               break;
3152             case kStatic:
3153               result.L = baseEnv(env)->CallStaticObjectMethodA(env, c, mid, vargs);
3154               break;
3155             default:
3156               break;
3157           }
3158           break;
3159         case Primitive::kPrimBoolean:
3160           result_check = "Z";
3161           switch (invoke) {
3162             case kVirtual:
3163               result.Z = baseEnv(env)->CallBooleanMethodA(env, obj, mid, vargs);
3164               break;
3165             case kDirect:
3166               result.Z = baseEnv(env)->CallNonvirtualBooleanMethodA(env, obj, c, mid, vargs);
3167               break;
3168             case kStatic:
3169               result.Z = baseEnv(env)->CallStaticBooleanMethodA(env, c, mid, vargs);
3170               break;
3171             default:
3172               break;
3173           }
3174           break;
3175         case Primitive::kPrimByte:
3176           result_check = "B";
3177           switch (invoke) {
3178             case kVirtual:
3179               result.B = baseEnv(env)->CallByteMethodA(env, obj, mid, vargs);
3180               break;
3181             case kDirect:
3182               result.B = baseEnv(env)->CallNonvirtualByteMethodA(env, obj, c, mid, vargs);
3183               break;
3184             case kStatic:
3185               result.B = baseEnv(env)->CallStaticByteMethodA(env, c, mid, vargs);
3186               break;
3187             default:
3188               break;
3189           }
3190           break;
3191         case Primitive::kPrimChar:
3192           result_check = "C";
3193           switch (invoke) {
3194             case kVirtual:
3195               result.C = baseEnv(env)->CallCharMethodA(env, obj, mid, vargs);
3196               break;
3197             case kDirect:
3198               result.C = baseEnv(env)->CallNonvirtualCharMethodA(env, obj, c, mid, vargs);
3199               break;
3200             case kStatic:
3201               result.C = baseEnv(env)->CallStaticCharMethodA(env, c, mid, vargs);
3202               break;
3203             default:
3204               break;
3205           }
3206           break;
3207         case Primitive::kPrimShort:
3208           result_check = "S";
3209           switch (invoke) {
3210             case kVirtual:
3211               result.S = baseEnv(env)->CallShortMethodA(env, obj, mid, vargs);
3212               break;
3213             case kDirect:
3214               result.S = baseEnv(env)->CallNonvirtualShortMethodA(env, obj, c, mid, vargs);
3215               break;
3216             case kStatic:
3217               result.S = baseEnv(env)->CallStaticShortMethodA(env, c, mid, vargs);
3218               break;
3219             default:
3220               break;
3221           }
3222           break;
3223         case Primitive::kPrimInt:
3224           result_check = "I";
3225           switch (invoke) {
3226             case kVirtual:
3227               result.I = baseEnv(env)->CallIntMethodA(env, obj, mid, vargs);
3228               break;
3229             case kDirect:
3230               result.I = baseEnv(env)->CallNonvirtualIntMethodA(env, obj, c, mid, vargs);
3231               break;
3232             case kStatic:
3233               result.I = baseEnv(env)->CallStaticIntMethodA(env, c, mid, vargs);
3234               break;
3235             default:
3236               break;
3237           }
3238           break;
3239         case Primitive::kPrimLong:
3240           result_check = "J";
3241           switch (invoke) {
3242             case kVirtual:
3243               result.J = baseEnv(env)->CallLongMethodA(env, obj, mid, vargs);
3244               break;
3245             case kDirect:
3246               result.J = baseEnv(env)->CallNonvirtualLongMethodA(env, obj, c, mid, vargs);
3247               break;
3248             case kStatic:
3249               result.J = baseEnv(env)->CallStaticLongMethodA(env, c, mid, vargs);
3250               break;
3251             default:
3252               break;
3253           }
3254           break;
3255         case Primitive::kPrimFloat:
3256           result_check = "F";
3257           switch (invoke) {
3258             case kVirtual:
3259               result.F = baseEnv(env)->CallFloatMethodA(env, obj, mid, vargs);
3260               break;
3261             case kDirect:
3262               result.F = baseEnv(env)->CallNonvirtualFloatMethodA(env, obj, c, mid, vargs);
3263               break;
3264             case kStatic:
3265               result.F = baseEnv(env)->CallStaticFloatMethodA(env, c, mid, vargs);
3266               break;
3267             default:
3268               break;
3269           }
3270           break;
3271         case Primitive::kPrimDouble:
3272           result_check = "D";
3273           switch (invoke) {
3274             case kVirtual:
3275               result.D = baseEnv(env)->CallDoubleMethodA(env, obj, mid, vargs);
3276               break;
3277             case kDirect:
3278               result.D = baseEnv(env)->CallNonvirtualDoubleMethodA(env, obj, c, mid, vargs);
3279               break;
3280             case kStatic:
3281               result.D = baseEnv(env)->CallStaticDoubleMethodA(env, c, mid, vargs);
3282               break;
3283             default:
3284               break;
3285           }
3286           break;
3287         case Primitive::kPrimVoid:
3288           result_check = "V";
3289           result.V = nullptr;
3290           switch (invoke) {
3291             case kVirtual:
3292               baseEnv(env)->CallVoidMethodA(env, obj, mid, vargs);
3293               break;
3294             case kDirect:
3295               baseEnv(env)->CallNonvirtualVoidMethodA(env, obj, c, mid, vargs);
3296               break;
3297             case kStatic:
3298               baseEnv(env)->CallStaticVoidMethodA(env, c, mid, vargs);
3299               break;
3300             default:
3301               LOG(FATAL) << "Unexpected invoke: " << invoke;
3302           }
3303           break;
3304       }
3305       if (sc.Check(soa, false, result_check, &result)) {
3306         return result;
3307       }
3308     }
3309     result.J = 0;
3310     return result;
3311   }
3312 
3313   NO_STACK_PROTECTOR
CallMethodV(const char * function_name,JNIEnv * env,jobject obj,jclass c,jmethodID mid,va_list vargs,Primitive::Type type,InvokeType invoke)3314   static JniValueType CallMethodV(const char* function_name, JNIEnv* env, jobject obj, jclass c,
3315                                   jmethodID mid, va_list vargs, Primitive::Type type,
3316                                   InvokeType invoke) {
3317     CHECK_ATTACHED_THREAD(function_name, JniValueType());
3318     ScopedObjectAccess soa(env);
3319     ScopedCheck sc(kFlag_Default, function_name);
3320     JniValueType result;
3321     VarArgs rest(mid, vargs);
3322     if (CheckCallArgs(soa, sc, env, obj, c, mid, invoke, &rest) &&
3323         sc.CheckMethodAndSig(soa, obj, c, mid, type, invoke)) {
3324       const char* result_check;
3325       switch (type) {
3326         case Primitive::kPrimNot:
3327           result_check = "L";
3328           switch (invoke) {
3329             case kVirtual:
3330               result.L = baseEnv(env)->CallObjectMethodV(env, obj, mid, vargs);
3331               break;
3332             case kDirect:
3333               result.L = baseEnv(env)->CallNonvirtualObjectMethodV(env, obj, c, mid, vargs);
3334               break;
3335             case kStatic:
3336               result.L = baseEnv(env)->CallStaticObjectMethodV(env, c, mid, vargs);
3337               break;
3338             default:
3339               LOG(FATAL) << "Unexpected invoke: " << invoke;
3340           }
3341           break;
3342         case Primitive::kPrimBoolean:
3343           result_check = "Z";
3344           switch (invoke) {
3345             case kVirtual:
3346               result.Z = baseEnv(env)->CallBooleanMethodV(env, obj, mid, vargs);
3347               break;
3348             case kDirect:
3349               result.Z = baseEnv(env)->CallNonvirtualBooleanMethodV(env, obj, c, mid, vargs);
3350               break;
3351             case kStatic:
3352               result.Z = baseEnv(env)->CallStaticBooleanMethodV(env, c, mid, vargs);
3353               break;
3354             default:
3355               LOG(FATAL) << "Unexpected invoke: " << invoke;
3356           }
3357           break;
3358         case Primitive::kPrimByte:
3359           result_check = "B";
3360           switch (invoke) {
3361             case kVirtual:
3362               result.B = baseEnv(env)->CallByteMethodV(env, obj, mid, vargs);
3363               break;
3364             case kDirect:
3365               result.B = baseEnv(env)->CallNonvirtualByteMethodV(env, obj, c, mid, vargs);
3366               break;
3367             case kStatic:
3368               result.B = baseEnv(env)->CallStaticByteMethodV(env, c, mid, vargs);
3369               break;
3370             default:
3371               LOG(FATAL) << "Unexpected invoke: " << invoke;
3372           }
3373           break;
3374         case Primitive::kPrimChar:
3375           result_check = "C";
3376           switch (invoke) {
3377             case kVirtual:
3378               result.C = baseEnv(env)->CallCharMethodV(env, obj, mid, vargs);
3379               break;
3380             case kDirect:
3381               result.C = baseEnv(env)->CallNonvirtualCharMethodV(env, obj, c, mid, vargs);
3382               break;
3383             case kStatic:
3384               result.C = baseEnv(env)->CallStaticCharMethodV(env, c, mid, vargs);
3385               break;
3386             default:
3387               LOG(FATAL) << "Unexpected invoke: " << invoke;
3388           }
3389           break;
3390         case Primitive::kPrimShort:
3391           result_check = "S";
3392           switch (invoke) {
3393             case kVirtual:
3394               result.S = baseEnv(env)->CallShortMethodV(env, obj, mid, vargs);
3395               break;
3396             case kDirect:
3397               result.S = baseEnv(env)->CallNonvirtualShortMethodV(env, obj, c, mid, vargs);
3398               break;
3399             case kStatic:
3400               result.S = baseEnv(env)->CallStaticShortMethodV(env, c, mid, vargs);
3401               break;
3402             default:
3403               LOG(FATAL) << "Unexpected invoke: " << invoke;
3404           }
3405           break;
3406         case Primitive::kPrimInt:
3407           result_check = "I";
3408           switch (invoke) {
3409             case kVirtual:
3410               result.I = baseEnv(env)->CallIntMethodV(env, obj, mid, vargs);
3411               break;
3412             case kDirect:
3413               result.I = baseEnv(env)->CallNonvirtualIntMethodV(env, obj, c, mid, vargs);
3414               break;
3415             case kStatic:
3416               result.I = baseEnv(env)->CallStaticIntMethodV(env, c, mid, vargs);
3417               break;
3418             default:
3419               LOG(FATAL) << "Unexpected invoke: " << invoke;
3420           }
3421           break;
3422         case Primitive::kPrimLong:
3423           result_check = "J";
3424           switch (invoke) {
3425             case kVirtual:
3426               result.J = baseEnv(env)->CallLongMethodV(env, obj, mid, vargs);
3427               break;
3428             case kDirect:
3429               result.J = baseEnv(env)->CallNonvirtualLongMethodV(env, obj, c, mid, vargs);
3430               break;
3431             case kStatic:
3432               result.J = baseEnv(env)->CallStaticLongMethodV(env, c, mid, vargs);
3433               break;
3434             default:
3435               LOG(FATAL) << "Unexpected invoke: " << invoke;
3436           }
3437           break;
3438         case Primitive::kPrimFloat:
3439           result_check = "F";
3440           switch (invoke) {
3441             case kVirtual:
3442               result.F = baseEnv(env)->CallFloatMethodV(env, obj, mid, vargs);
3443               break;
3444             case kDirect:
3445               result.F = baseEnv(env)->CallNonvirtualFloatMethodV(env, obj, c, mid, vargs);
3446               break;
3447             case kStatic:
3448               result.F = baseEnv(env)->CallStaticFloatMethodV(env, c, mid, vargs);
3449               break;
3450             default:
3451               LOG(FATAL) << "Unexpected invoke: " << invoke;
3452           }
3453           break;
3454         case Primitive::kPrimDouble:
3455           result_check = "D";
3456           switch (invoke) {
3457             case kVirtual:
3458               result.D = baseEnv(env)->CallDoubleMethodV(env, obj, mid, vargs);
3459               break;
3460             case kDirect:
3461               result.D = baseEnv(env)->CallNonvirtualDoubleMethodV(env, obj, c, mid, vargs);
3462               break;
3463             case kStatic:
3464               result.D = baseEnv(env)->CallStaticDoubleMethodV(env, c, mid, vargs);
3465               break;
3466             default:
3467               LOG(FATAL) << "Unexpected invoke: " << invoke;
3468           }
3469           break;
3470         case Primitive::kPrimVoid:
3471           result_check = "V";
3472           result.V = nullptr;
3473           switch (invoke) {
3474             case kVirtual:
3475               baseEnv(env)->CallVoidMethodV(env, obj, mid, vargs);
3476               break;
3477             case kDirect:
3478               baseEnv(env)->CallNonvirtualVoidMethodV(env, obj, c, mid, vargs);
3479               break;
3480             case kStatic:
3481               baseEnv(env)->CallStaticVoidMethodV(env, c, mid, vargs);
3482               break;
3483             default:
3484               LOG(FATAL) << "Unexpected invoke: " << invoke;
3485           }
3486           break;
3487       }
3488       if (sc.Check(soa, false, result_check, &result)) {
3489         return result;
3490       }
3491     }
3492     result.J = 0;
3493     return result;
3494   }
3495 
GetStringCharsInternal(const char * function_name,JNIEnv * env,jstring string,jboolean * is_copy,bool utf,bool critical)3496   static const void* GetStringCharsInternal(const char* function_name, JNIEnv* env, jstring string,
3497                                             jboolean* is_copy, bool utf, bool critical) {
3498     CHECK_ATTACHED_THREAD(function_name, nullptr);
3499     ScopedObjectAccess soa(env);
3500     int flags = critical ? kFlag_CritGet : kFlag_CritOkay;
3501     ScopedCheck sc(flags, function_name);
3502     JniValueType args[3] = {{.E = env}, {.s = string}, {.p = is_copy}};
3503     if (sc.Check(soa, true, "Esp", args)) {
3504       JniValueType result;
3505       void* ptr;
3506       if (utf) {
3507         CHECK(!critical);
3508         ptr = const_cast<char*>(baseEnv(env)->GetStringUTFChars(env, string, is_copy));
3509         result.u = reinterpret_cast<char*>(ptr);
3510       } else {
3511         ptr = const_cast<jchar*>(critical ? baseEnv(env)->GetStringCritical(env, string, is_copy) :
3512             baseEnv(env)->GetStringChars(env, string, is_copy));
3513         result.p = ptr;
3514       }
3515       // TODO: could we be smarter about not copying when local_is_copy?
3516       if (ptr != nullptr && soa.ForceCopy()) {
3517         if (utf) {
3518           size_t length_in_bytes = strlen(result.u) + 1;
3519           result.u =
3520               reinterpret_cast<const char*>(GuardedCopy::Create(ptr, length_in_bytes, false));
3521         } else {
3522           size_t length_in_bytes = baseEnv(env)->GetStringLength(env, string) * 2;
3523           result.p =
3524               reinterpret_cast<const jchar*>(GuardedCopy::Create(ptr, length_in_bytes, false));
3525         }
3526         if (is_copy != nullptr) {
3527           *is_copy = JNI_TRUE;
3528         }
3529       }
3530       if (sc.Check(soa, false, utf ? "u" : "p", &result)) {
3531         return utf ? result.u : result.p;
3532       }
3533     }
3534     return nullptr;
3535   }
3536 
ReleaseStringCharsInternal(const char * function_name,JNIEnv * env,jstring string,const void * chars,bool utf,bool critical)3537   static void ReleaseStringCharsInternal(const char* function_name, JNIEnv* env, jstring string,
3538                                          const void* chars, bool utf, bool critical) {
3539     CHECK_ATTACHED_THREAD_VOID(function_name);
3540     ScopedObjectAccess soa(env);
3541     int flags = kFlag_ExcepOkay | kFlag_Release;
3542     if (critical) {
3543       flags |= kFlag_CritRelease;
3544     }
3545     ScopedCheck sc(flags, function_name);
3546     sc.CheckNonNull(chars);
3547     bool force_copy_ok = !soa.ForceCopy() || GuardedCopy::Check(function_name, chars, false);
3548     if (force_copy_ok && soa.ForceCopy()) {
3549       chars = reinterpret_cast<const jchar*>(GuardedCopy::Destroy(const_cast<void*>(chars)));
3550     }
3551     if (force_copy_ok) {
3552       JniValueType args[3] = {{.E = env}, {.s = string}, {.p = chars}};
3553       if (sc.Check(soa, true, utf ? "Esu" : "Esp", args)) {
3554         if (utf) {
3555           CHECK(!critical);
3556           baseEnv(env)->ReleaseStringUTFChars(env, string, reinterpret_cast<const char*>(chars));
3557         } else {
3558           if (critical) {
3559             baseEnv(env)->ReleaseStringCritical(env, string, reinterpret_cast<const jchar*>(chars));
3560           } else {
3561             baseEnv(env)->ReleaseStringChars(env, string, reinterpret_cast<const jchar*>(chars));
3562           }
3563         }
3564         JniValueType result;
3565         sc.Check(soa, false, "V", &result);
3566       }
3567     }
3568   }
3569 
NewPrimitiveArray(const char * function_name,JNIEnv * env,jsize length,Primitive::Type type)3570   static jarray NewPrimitiveArray(const char* function_name, JNIEnv* env, jsize length,
3571                                   Primitive::Type type) {
3572     CHECK_ATTACHED_THREAD(function_name, nullptr);
3573     ScopedObjectAccess soa(env);
3574     ScopedCheck sc(kFlag_Default, function_name);
3575     JniValueType args[2] = {{.E = env}, {.z = length}};
3576     if (sc.Check(soa, true, "Ez", args)) {
3577       JniValueType result;
3578       switch (type) {
3579         case Primitive::kPrimBoolean:
3580           result.a = baseEnv(env)->NewBooleanArray(env, length);
3581           break;
3582         case Primitive::kPrimByte:
3583           result.a = baseEnv(env)->NewByteArray(env, length);
3584           break;
3585         case Primitive::kPrimChar:
3586           result.a = baseEnv(env)->NewCharArray(env, length);
3587           break;
3588         case Primitive::kPrimShort:
3589           result.a = baseEnv(env)->NewShortArray(env, length);
3590           break;
3591         case Primitive::kPrimInt:
3592           result.a = baseEnv(env)->NewIntArray(env, length);
3593           break;
3594         case Primitive::kPrimLong:
3595           result.a = baseEnv(env)->NewLongArray(env, length);
3596           break;
3597         case Primitive::kPrimFloat:
3598           result.a = baseEnv(env)->NewFloatArray(env, length);
3599           break;
3600         case Primitive::kPrimDouble:
3601           result.a = baseEnv(env)->NewDoubleArray(env, length);
3602           break;
3603         default:
3604           LOG(FATAL) << "Unexpected primitive type: " << type;
3605       }
3606       if (sc.Check(soa, false, "a", &result)) {
3607         return result.a;
3608       }
3609     }
3610     return nullptr;
3611   }
3612 
GetPrimitiveArrayElements(const char * function_name,Primitive::Type type,JNIEnv * env,jarray array,jboolean * is_copy)3613   static void* GetPrimitiveArrayElements(const char* function_name, Primitive::Type type,
3614                                          JNIEnv* env, jarray array, jboolean* is_copy) {
3615     CHECK_ATTACHED_THREAD(function_name, nullptr);
3616     ScopedObjectAccess soa(env);
3617     ScopedCheck sc(kFlag_Default, function_name);
3618     JniValueType args[3] = {{.E = env}, {.a = array}, {.p = is_copy}};
3619     if (sc.Check(soa, true, "Eap", args) && sc.CheckPrimitiveArrayType(soa, array, type)) {
3620       JniValueType result;
3621       void* ptr = nullptr;
3622       switch (type) {
3623         case Primitive::kPrimBoolean:
3624           ptr = baseEnv(env)->GetBooleanArrayElements(env, down_cast<jbooleanArray>(array),
3625                                                       is_copy);
3626           break;
3627         case Primitive::kPrimByte:
3628           ptr = baseEnv(env)->GetByteArrayElements(env, down_cast<jbyteArray>(array), is_copy);
3629           break;
3630         case Primitive::kPrimChar:
3631           ptr = baseEnv(env)->GetCharArrayElements(env, down_cast<jcharArray>(array), is_copy);
3632           break;
3633         case Primitive::kPrimShort:
3634           ptr = baseEnv(env)->GetShortArrayElements(env, down_cast<jshortArray>(array), is_copy);
3635           break;
3636         case Primitive::kPrimInt:
3637           ptr = baseEnv(env)->GetIntArrayElements(env, down_cast<jintArray>(array), is_copy);
3638           break;
3639         case Primitive::kPrimLong:
3640           ptr = baseEnv(env)->GetLongArrayElements(env, down_cast<jlongArray>(array), is_copy);
3641           break;
3642         case Primitive::kPrimFloat:
3643           ptr = baseEnv(env)->GetFloatArrayElements(env, down_cast<jfloatArray>(array), is_copy);
3644           break;
3645         case Primitive::kPrimDouble:
3646           ptr = baseEnv(env)->GetDoubleArrayElements(env, down_cast<jdoubleArray>(array), is_copy);
3647           break;
3648         default:
3649           LOG(FATAL) << "Unexpected primitive type: " << type;
3650       }
3651       if (ptr != nullptr && soa.ForceCopy()) {
3652         ptr = GuardedCopy::CreateGuardedPACopy(env, array, is_copy, ptr);
3653         if (is_copy != nullptr) {
3654           *is_copy = JNI_TRUE;
3655         }
3656       }
3657       result.p = ptr;
3658       if (sc.Check(soa, false, "p", &result)) {
3659         return const_cast<void*>(result.p);
3660       }
3661     }
3662     return nullptr;
3663   }
3664 
ReleasePrimitiveArrayElements(const char * function_name,Primitive::Type type,JNIEnv * env,jarray array,void * elems,jint mode)3665   static void ReleasePrimitiveArrayElements(const char* function_name, Primitive::Type type,
3666                                             JNIEnv* env, jarray array, void* elems, jint mode) {
3667     CHECK_ATTACHED_THREAD_VOID(function_name);
3668     ScopedObjectAccess soa(env);
3669     ScopedCheck sc(kFlag_ExcepOkay, function_name);
3670     if (sc.CheckNonNull(elems) && sc.CheckPrimitiveArrayType(soa, array, type)) {
3671       if (soa.ForceCopy()) {
3672         elems = GuardedCopy::ReleaseGuardedPACopy(function_name, env, array, elems, mode);
3673       }
3674       if (!soa.ForceCopy() || elems != nullptr) {
3675         JniValueType args[4] = {{.E = env}, {.a = array}, {.p = elems}, {.r = mode}};
3676         if (sc.Check(soa, true, "Eapr", args)) {
3677           switch (type) {
3678             case Primitive::kPrimBoolean:
3679               baseEnv(env)->ReleaseBooleanArrayElements(env, down_cast<jbooleanArray>(array),
3680                                                         reinterpret_cast<jboolean*>(elems), mode);
3681               break;
3682             case Primitive::kPrimByte:
3683               baseEnv(env)->ReleaseByteArrayElements(env, down_cast<jbyteArray>(array),
3684                                                      reinterpret_cast<jbyte*>(elems), mode);
3685               break;
3686             case Primitive::kPrimChar:
3687               baseEnv(env)->ReleaseCharArrayElements(env, down_cast<jcharArray>(array),
3688                                                      reinterpret_cast<jchar*>(elems), mode);
3689               break;
3690             case Primitive::kPrimShort:
3691               baseEnv(env)->ReleaseShortArrayElements(env, down_cast<jshortArray>(array),
3692                                                       reinterpret_cast<jshort*>(elems), mode);
3693               break;
3694             case Primitive::kPrimInt:
3695               baseEnv(env)->ReleaseIntArrayElements(env, down_cast<jintArray>(array),
3696                                                     reinterpret_cast<jint*>(elems), mode);
3697               break;
3698             case Primitive::kPrimLong:
3699               baseEnv(env)->ReleaseLongArrayElements(env, down_cast<jlongArray>(array),
3700                                                      reinterpret_cast<jlong*>(elems), mode);
3701               break;
3702             case Primitive::kPrimFloat:
3703               baseEnv(env)->ReleaseFloatArrayElements(env, down_cast<jfloatArray>(array),
3704                                                       reinterpret_cast<jfloat*>(elems), mode);
3705               break;
3706             case Primitive::kPrimDouble:
3707               baseEnv(env)->ReleaseDoubleArrayElements(env, down_cast<jdoubleArray>(array),
3708                                                        reinterpret_cast<jdouble*>(elems), mode);
3709               break;
3710             default:
3711               LOG(FATAL) << "Unexpected primitive type: " << type;
3712           }
3713           JniValueType result;
3714           result.V = nullptr;
3715           sc.Check(soa, false, "V", &result);
3716         }
3717       }
3718     }
3719   }
3720 
GetPrimitiveArrayRegion(const char * function_name,Primitive::Type type,JNIEnv * env,jarray array,jsize start,jsize len,void * buf)3721   static void GetPrimitiveArrayRegion(const char* function_name, Primitive::Type type, JNIEnv* env,
3722                                       jarray array, jsize start, jsize len, void* buf) {
3723     CHECK_ATTACHED_THREAD_VOID(function_name);
3724     ScopedObjectAccess soa(env);
3725     ScopedCheck sc(kFlag_Default, function_name);
3726     JniValueType args[5] = {{.E = env}, {.a = array}, {.z = start}, {.z = len}, {.p = buf}};
3727     // Note: the start and len arguments are checked as 'I' rather than 'z' as invalid indices
3728     // result in ArrayIndexOutOfBoundsExceptions in the base implementation.
3729     if (sc.Check(soa, true, "EaIIp", args) && sc.CheckPrimitiveArrayType(soa, array, type)) {
3730       switch (type) {
3731         case Primitive::kPrimBoolean:
3732           baseEnv(env)->GetBooleanArrayRegion(env, down_cast<jbooleanArray>(array), start, len,
3733                                               reinterpret_cast<jboolean*>(buf));
3734           break;
3735         case Primitive::kPrimByte:
3736           baseEnv(env)->GetByteArrayRegion(env, down_cast<jbyteArray>(array), start, len,
3737                                            reinterpret_cast<jbyte*>(buf));
3738           break;
3739         case Primitive::kPrimChar:
3740           baseEnv(env)->GetCharArrayRegion(env, down_cast<jcharArray>(array), start, len,
3741                                            reinterpret_cast<jchar*>(buf));
3742           break;
3743         case Primitive::kPrimShort:
3744           baseEnv(env)->GetShortArrayRegion(env, down_cast<jshortArray>(array), start, len,
3745                                             reinterpret_cast<jshort*>(buf));
3746           break;
3747         case Primitive::kPrimInt:
3748           baseEnv(env)->GetIntArrayRegion(env, down_cast<jintArray>(array), start, len,
3749                                           reinterpret_cast<jint*>(buf));
3750           break;
3751         case Primitive::kPrimLong:
3752           baseEnv(env)->GetLongArrayRegion(env, down_cast<jlongArray>(array), start, len,
3753                                            reinterpret_cast<jlong*>(buf));
3754           break;
3755         case Primitive::kPrimFloat:
3756           baseEnv(env)->GetFloatArrayRegion(env, down_cast<jfloatArray>(array), start, len,
3757                                             reinterpret_cast<jfloat*>(buf));
3758           break;
3759         case Primitive::kPrimDouble:
3760           baseEnv(env)->GetDoubleArrayRegion(env, down_cast<jdoubleArray>(array), start, len,
3761                                              reinterpret_cast<jdouble*>(buf));
3762           break;
3763         default:
3764           LOG(FATAL) << "Unexpected primitive type: " << type;
3765       }
3766       JniValueType result;
3767       result.V = nullptr;
3768       sc.Check(soa, false, "V", &result);
3769     }
3770   }
3771 
SetPrimitiveArrayRegion(const char * function_name,Primitive::Type type,JNIEnv * env,jarray array,jsize start,jsize len,const void * buf)3772   static void SetPrimitiveArrayRegion(const char* function_name, Primitive::Type type, JNIEnv* env,
3773                                       jarray array, jsize start, jsize len, const void* buf) {
3774     CHECK_ATTACHED_THREAD_VOID(function_name);
3775     ScopedObjectAccess soa(env);
3776     ScopedCheck sc(kFlag_Default, function_name);
3777     JniValueType args[5] = {{.E = env}, {.a = array}, {.z = start}, {.z = len}, {.p = buf}};
3778     // Note: the start and len arguments are checked as 'I' rather than 'z' as invalid indices
3779     // result in ArrayIndexOutOfBoundsExceptions in the base implementation.
3780     if (sc.Check(soa, true, "EaIIp", args) && sc.CheckPrimitiveArrayType(soa, array, type)) {
3781       switch (type) {
3782         case Primitive::kPrimBoolean:
3783           baseEnv(env)->SetBooleanArrayRegion(env, down_cast<jbooleanArray>(array), start, len,
3784                                               reinterpret_cast<const jboolean*>(buf));
3785           break;
3786         case Primitive::kPrimByte:
3787           baseEnv(env)->SetByteArrayRegion(env, down_cast<jbyteArray>(array), start, len,
3788                                            reinterpret_cast<const jbyte*>(buf));
3789           break;
3790         case Primitive::kPrimChar:
3791           baseEnv(env)->SetCharArrayRegion(env, down_cast<jcharArray>(array), start, len,
3792                                            reinterpret_cast<const jchar*>(buf));
3793           break;
3794         case Primitive::kPrimShort:
3795           baseEnv(env)->SetShortArrayRegion(env, down_cast<jshortArray>(array), start, len,
3796                                               reinterpret_cast<const jshort*>(buf));
3797           break;
3798         case Primitive::kPrimInt:
3799           baseEnv(env)->SetIntArrayRegion(env, down_cast<jintArray>(array), start, len,
3800                                           reinterpret_cast<const jint*>(buf));
3801           break;
3802         case Primitive::kPrimLong:
3803           baseEnv(env)->SetLongArrayRegion(env, down_cast<jlongArray>(array), start, len,
3804                                               reinterpret_cast<const jlong*>(buf));
3805           break;
3806         case Primitive::kPrimFloat:
3807           baseEnv(env)->SetFloatArrayRegion(env, down_cast<jfloatArray>(array), start, len,
3808                                             reinterpret_cast<const jfloat*>(buf));
3809           break;
3810         case Primitive::kPrimDouble:
3811           baseEnv(env)->SetDoubleArrayRegion(env, down_cast<jdoubleArray>(array), start, len,
3812                                              reinterpret_cast<const jdouble*>(buf));
3813           break;
3814         default:
3815           LOG(FATAL) << "Unexpected primitive type: " << type;
3816       }
3817       JniValueType result;
3818       result.V = nullptr;
3819       sc.Check(soa, false, "V", &result);
3820     }
3821   }
3822 };
3823 
3824 const JNINativeInterface gCheckNativeInterface = {
3825   nullptr,  // reserved0.
3826   nullptr,  // reserved1.
3827   nullptr,  // reserved2.
3828   nullptr,  // reserved3.
3829   CheckJNI::GetVersion,
3830   CheckJNI::DefineClass,
3831   CheckJNI::FindClass,
3832   CheckJNI::FromReflectedMethod,
3833   CheckJNI::FromReflectedField,
3834   CheckJNI::ToReflectedMethod,
3835   CheckJNI::GetSuperclass,
3836   CheckJNI::IsAssignableFrom,
3837   CheckJNI::ToReflectedField,
3838   CheckJNI::Throw,
3839   CheckJNI::ThrowNew,
3840   CheckJNI::ExceptionOccurred,
3841   CheckJNI::ExceptionDescribe,
3842   CheckJNI::ExceptionClear,
3843   CheckJNI::FatalError,
3844   CheckJNI::PushLocalFrame,
3845   CheckJNI::PopLocalFrame,
3846   CheckJNI::NewGlobalRef,
3847   CheckJNI::DeleteGlobalRef,
3848   CheckJNI::DeleteLocalRef,
3849   CheckJNI::IsSameObject,
3850   CheckJNI::NewLocalRef,
3851   CheckJNI::EnsureLocalCapacity,
3852   CheckJNI::AllocObject,
3853   CheckJNI::NewObject,
3854   CheckJNI::NewObjectV,
3855   CheckJNI::NewObjectA,
3856   CheckJNI::GetObjectClass,
3857   CheckJNI::IsInstanceOf,
3858   CheckJNI::GetMethodID,
3859   CheckJNI::CallObjectMethod,
3860   CheckJNI::CallObjectMethodV,
3861   CheckJNI::CallObjectMethodA,
3862   CheckJNI::CallBooleanMethod,
3863   CheckJNI::CallBooleanMethodV,
3864   CheckJNI::CallBooleanMethodA,
3865   CheckJNI::CallByteMethod,
3866   CheckJNI::CallByteMethodV,
3867   CheckJNI::CallByteMethodA,
3868   CheckJNI::CallCharMethod,
3869   CheckJNI::CallCharMethodV,
3870   CheckJNI::CallCharMethodA,
3871   CheckJNI::CallShortMethod,
3872   CheckJNI::CallShortMethodV,
3873   CheckJNI::CallShortMethodA,
3874   CheckJNI::CallIntMethod,
3875   CheckJNI::CallIntMethodV,
3876   CheckJNI::CallIntMethodA,
3877   CheckJNI::CallLongMethod,
3878   CheckJNI::CallLongMethodV,
3879   CheckJNI::CallLongMethodA,
3880   CheckJNI::CallFloatMethod,
3881   CheckJNI::CallFloatMethodV,
3882   CheckJNI::CallFloatMethodA,
3883   CheckJNI::CallDoubleMethod,
3884   CheckJNI::CallDoubleMethodV,
3885   CheckJNI::CallDoubleMethodA,
3886   CheckJNI::CallVoidMethod,
3887   CheckJNI::CallVoidMethodV,
3888   CheckJNI::CallVoidMethodA,
3889   CheckJNI::CallNonvirtualObjectMethod,
3890   CheckJNI::CallNonvirtualObjectMethodV,
3891   CheckJNI::CallNonvirtualObjectMethodA,
3892   CheckJNI::CallNonvirtualBooleanMethod,
3893   CheckJNI::CallNonvirtualBooleanMethodV,
3894   CheckJNI::CallNonvirtualBooleanMethodA,
3895   CheckJNI::CallNonvirtualByteMethod,
3896   CheckJNI::CallNonvirtualByteMethodV,
3897   CheckJNI::CallNonvirtualByteMethodA,
3898   CheckJNI::CallNonvirtualCharMethod,
3899   CheckJNI::CallNonvirtualCharMethodV,
3900   CheckJNI::CallNonvirtualCharMethodA,
3901   CheckJNI::CallNonvirtualShortMethod,
3902   CheckJNI::CallNonvirtualShortMethodV,
3903   CheckJNI::CallNonvirtualShortMethodA,
3904   CheckJNI::CallNonvirtualIntMethod,
3905   CheckJNI::CallNonvirtualIntMethodV,
3906   CheckJNI::CallNonvirtualIntMethodA,
3907   CheckJNI::CallNonvirtualLongMethod,
3908   CheckJNI::CallNonvirtualLongMethodV,
3909   CheckJNI::CallNonvirtualLongMethodA,
3910   CheckJNI::CallNonvirtualFloatMethod,
3911   CheckJNI::CallNonvirtualFloatMethodV,
3912   CheckJNI::CallNonvirtualFloatMethodA,
3913   CheckJNI::CallNonvirtualDoubleMethod,
3914   CheckJNI::CallNonvirtualDoubleMethodV,
3915   CheckJNI::CallNonvirtualDoubleMethodA,
3916   CheckJNI::CallNonvirtualVoidMethod,
3917   CheckJNI::CallNonvirtualVoidMethodV,
3918   CheckJNI::CallNonvirtualVoidMethodA,
3919   CheckJNI::GetFieldID,
3920   CheckJNI::GetObjectField,
3921   CheckJNI::GetBooleanField,
3922   CheckJNI::GetByteField,
3923   CheckJNI::GetCharField,
3924   CheckJNI::GetShortField,
3925   CheckJNI::GetIntField,
3926   CheckJNI::GetLongField,
3927   CheckJNI::GetFloatField,
3928   CheckJNI::GetDoubleField,
3929   CheckJNI::SetObjectField,
3930   CheckJNI::SetBooleanField,
3931   CheckJNI::SetByteField,
3932   CheckJNI::SetCharField,
3933   CheckJNI::SetShortField,
3934   CheckJNI::SetIntField,
3935   CheckJNI::SetLongField,
3936   CheckJNI::SetFloatField,
3937   CheckJNI::SetDoubleField,
3938   CheckJNI::GetStaticMethodID,
3939   CheckJNI::CallStaticObjectMethod,
3940   CheckJNI::CallStaticObjectMethodV,
3941   CheckJNI::CallStaticObjectMethodA,
3942   CheckJNI::CallStaticBooleanMethod,
3943   CheckJNI::CallStaticBooleanMethodV,
3944   CheckJNI::CallStaticBooleanMethodA,
3945   CheckJNI::CallStaticByteMethod,
3946   CheckJNI::CallStaticByteMethodV,
3947   CheckJNI::CallStaticByteMethodA,
3948   CheckJNI::CallStaticCharMethod,
3949   CheckJNI::CallStaticCharMethodV,
3950   CheckJNI::CallStaticCharMethodA,
3951   CheckJNI::CallStaticShortMethod,
3952   CheckJNI::CallStaticShortMethodV,
3953   CheckJNI::CallStaticShortMethodA,
3954   CheckJNI::CallStaticIntMethod,
3955   CheckJNI::CallStaticIntMethodV,
3956   CheckJNI::CallStaticIntMethodA,
3957   CheckJNI::CallStaticLongMethod,
3958   CheckJNI::CallStaticLongMethodV,
3959   CheckJNI::CallStaticLongMethodA,
3960   CheckJNI::CallStaticFloatMethod,
3961   CheckJNI::CallStaticFloatMethodV,
3962   CheckJNI::CallStaticFloatMethodA,
3963   CheckJNI::CallStaticDoubleMethod,
3964   CheckJNI::CallStaticDoubleMethodV,
3965   CheckJNI::CallStaticDoubleMethodA,
3966   CheckJNI::CallStaticVoidMethod,
3967   CheckJNI::CallStaticVoidMethodV,
3968   CheckJNI::CallStaticVoidMethodA,
3969   CheckJNI::GetStaticFieldID,
3970   CheckJNI::GetStaticObjectField,
3971   CheckJNI::GetStaticBooleanField,
3972   CheckJNI::GetStaticByteField,
3973   CheckJNI::GetStaticCharField,
3974   CheckJNI::GetStaticShortField,
3975   CheckJNI::GetStaticIntField,
3976   CheckJNI::GetStaticLongField,
3977   CheckJNI::GetStaticFloatField,
3978   CheckJNI::GetStaticDoubleField,
3979   CheckJNI::SetStaticObjectField,
3980   CheckJNI::SetStaticBooleanField,
3981   CheckJNI::SetStaticByteField,
3982   CheckJNI::SetStaticCharField,
3983   CheckJNI::SetStaticShortField,
3984   CheckJNI::SetStaticIntField,
3985   CheckJNI::SetStaticLongField,
3986   CheckJNI::SetStaticFloatField,
3987   CheckJNI::SetStaticDoubleField,
3988   CheckJNI::NewString,
3989   CheckJNI::GetStringLength,
3990   CheckJNI::GetStringChars,
3991   CheckJNI::ReleaseStringChars,
3992   CheckJNI::NewStringUTF,
3993   CheckJNI::GetStringUTFLength,
3994   CheckJNI::GetStringUTFChars,
3995   CheckJNI::ReleaseStringUTFChars,
3996   CheckJNI::GetArrayLength,
3997   CheckJNI::NewObjectArray,
3998   CheckJNI::GetObjectArrayElement,
3999   CheckJNI::SetObjectArrayElement,
4000   CheckJNI::NewBooleanArray,
4001   CheckJNI::NewByteArray,
4002   CheckJNI::NewCharArray,
4003   CheckJNI::NewShortArray,
4004   CheckJNI::NewIntArray,
4005   CheckJNI::NewLongArray,
4006   CheckJNI::NewFloatArray,
4007   CheckJNI::NewDoubleArray,
4008   CheckJNI::GetBooleanArrayElements,
4009   CheckJNI::GetByteArrayElements,
4010   CheckJNI::GetCharArrayElements,
4011   CheckJNI::GetShortArrayElements,
4012   CheckJNI::GetIntArrayElements,
4013   CheckJNI::GetLongArrayElements,
4014   CheckJNI::GetFloatArrayElements,
4015   CheckJNI::GetDoubleArrayElements,
4016   CheckJNI::ReleaseBooleanArrayElements,
4017   CheckJNI::ReleaseByteArrayElements,
4018   CheckJNI::ReleaseCharArrayElements,
4019   CheckJNI::ReleaseShortArrayElements,
4020   CheckJNI::ReleaseIntArrayElements,
4021   CheckJNI::ReleaseLongArrayElements,
4022   CheckJNI::ReleaseFloatArrayElements,
4023   CheckJNI::ReleaseDoubleArrayElements,
4024   CheckJNI::GetBooleanArrayRegion,
4025   CheckJNI::GetByteArrayRegion,
4026   CheckJNI::GetCharArrayRegion,
4027   CheckJNI::GetShortArrayRegion,
4028   CheckJNI::GetIntArrayRegion,
4029   CheckJNI::GetLongArrayRegion,
4030   CheckJNI::GetFloatArrayRegion,
4031   CheckJNI::GetDoubleArrayRegion,
4032   CheckJNI::SetBooleanArrayRegion,
4033   CheckJNI::SetByteArrayRegion,
4034   CheckJNI::SetCharArrayRegion,
4035   CheckJNI::SetShortArrayRegion,
4036   CheckJNI::SetIntArrayRegion,
4037   CheckJNI::SetLongArrayRegion,
4038   CheckJNI::SetFloatArrayRegion,
4039   CheckJNI::SetDoubleArrayRegion,
4040   CheckJNI::RegisterNatives,
4041   CheckJNI::UnregisterNatives,
4042   CheckJNI::MonitorEnter,
4043   CheckJNI::MonitorExit,
4044   CheckJNI::GetJavaVM,
4045   CheckJNI::GetStringRegion,
4046   CheckJNI::GetStringUTFRegion,
4047   CheckJNI::GetPrimitiveArrayCritical,
4048   CheckJNI::ReleasePrimitiveArrayCritical,
4049   CheckJNI::GetStringCritical,
4050   CheckJNI::ReleaseStringCritical,
4051   CheckJNI::NewWeakGlobalRef,
4052   CheckJNI::DeleteWeakGlobalRef,
4053   CheckJNI::ExceptionCheck,
4054   CheckJNI::NewDirectByteBuffer,
4055   CheckJNI::GetDirectBufferAddress,
4056   CheckJNI::GetDirectBufferCapacity,
4057   CheckJNI::GetObjectRefType,
4058 };
4059 
4060 class CheckJII {
4061  public:
DestroyJavaVM(JavaVM * vm)4062   static jint DestroyJavaVM(JavaVM* vm) {
4063     ScopedCheck sc(kFlag_Invocation, __FUNCTION__, false);
4064     JniValueType args[1] = {{.v = vm}};
4065     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), true, "v", args);
4066     JniValueType result;
4067     result.i = BaseVm(vm)->DestroyJavaVM(vm);
4068     // Use null to signal that the JavaVM isn't valid anymore. DestroyJavaVM deletes the runtime,
4069     // which will delete the JavaVMExt.
4070     sc.CheckNonHeap(nullptr, false, "i", &result);
4071     return result.i;
4072   }
4073 
AttachCurrentThread(JavaVM * vm,JNIEnv ** p_env,void * thr_args)4074   static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
4075     ScopedCheck sc(kFlag_Invocation, __FUNCTION__);
4076     JniValueType args[3] = {{.v = vm}, {.p = p_env}, {.p = thr_args}};
4077     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), true, "vpp", args);
4078     JniValueType result;
4079     result.i = BaseVm(vm)->AttachCurrentThread(vm, p_env, thr_args);
4080     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), false, "i", &result);
4081     return result.i;
4082   }
4083 
AttachCurrentThreadAsDaemon(JavaVM * vm,JNIEnv ** p_env,void * thr_args)4084   static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
4085     ScopedCheck sc(kFlag_Invocation, __FUNCTION__);
4086     JniValueType args[3] = {{.v = vm}, {.p = p_env}, {.p = thr_args}};
4087     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), true, "vpp", args);
4088     JniValueType result;
4089     result.i = BaseVm(vm)->AttachCurrentThreadAsDaemon(vm, p_env, thr_args);
4090     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), false, "i", &result);
4091     return result.i;
4092   }
4093 
DetachCurrentThread(JavaVM * vm)4094   static jint DetachCurrentThread(JavaVM* vm) {
4095     ScopedCheck sc(kFlag_Invocation, __FUNCTION__);
4096     JniValueType args[1] = {{.v = vm}};
4097     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), true, "v", args);
4098     JniValueType result;
4099     result.i = BaseVm(vm)->DetachCurrentThread(vm);
4100     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), false, "i", &result);
4101     return result.i;
4102   }
4103 
GetEnv(JavaVM * vm,void ** p_env,jint version)4104   static jint GetEnv(JavaVM* vm, void** p_env, jint version) {
4105     ScopedCheck sc(kFlag_Invocation, __FUNCTION__);
4106     JniValueType args[3] = {{.v = vm}, {.p = p_env}, {.I = version}};
4107     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), true, "vpI", args);
4108     JniValueType result;
4109     result.i = BaseVm(vm)->GetEnv(vm, p_env, version);
4110     sc.CheckNonHeap(reinterpret_cast<JavaVMExt*>(vm), false, "i", &result);
4111     return result.i;
4112   }
4113 
4114  private:
BaseVm(JavaVM * vm)4115   static const JNIInvokeInterface* BaseVm(JavaVM* vm) {
4116     return reinterpret_cast<JavaVMExt*>(vm)->GetUncheckedFunctions();
4117   }
4118 };
4119 
4120 const JNIInvokeInterface gCheckInvokeInterface = {
4121   nullptr,  // reserved0
4122   nullptr,  // reserved1
4123   nullptr,  // reserved2
4124   CheckJII::DestroyJavaVM,
4125   CheckJII::AttachCurrentThread,
4126   CheckJII::DetachCurrentThread,
4127   CheckJII::GetEnv,
4128   CheckJII::AttachCurrentThreadAsDaemon
4129 };
4130 
4131 }  // anonymous namespace
4132 
GetCheckJniNativeInterface()4133 const JNINativeInterface* GetCheckJniNativeInterface() {
4134   return &gCheckNativeInterface;
4135 }
4136 
GetCheckJniInvokeInterface()4137 const JNIInvokeInterface* GetCheckJniInvokeInterface() {
4138   return &gCheckInvokeInterface;
4139 }
4140 
4141 }  // namespace art
4142