1 /*
2  * Copyright (C) 2011 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 "reflection-inl.h"
18 
19 #include "art_field-inl.h"
20 #include "art_method-alloc-inl.h"
21 #include "base/pointer_size.h"
22 #include "class_linker.h"
23 #include "common_throws.h"
24 #include "dex/dex_file-inl.h"
25 #include "indirect_reference_table-inl.h"
26 #include "jni/java_vm_ext.h"
27 #include "jni/jni_internal.h"
28 #include "jvalue-inl.h"
29 #include "mirror/class-inl.h"
30 #include "mirror/executable.h"
31 #include "mirror/object_array-inl.h"
32 #include "nativehelper/scoped_local_ref.h"
33 #include "nth_caller_visitor.h"
34 #include "scoped_thread_state_change-inl.h"
35 #include "stack_reference.h"
36 #include "thread-inl.h"
37 #include "well_known_classes-inl.h"
38 
39 namespace art HIDDEN {
40 namespace {
41 
42 using android::base::StringPrintf;
43 
44 class ArgArray {
45  public:
ArgArray(const char * shorty,uint32_t shorty_len)46   ArgArray(const char* shorty, uint32_t shorty_len)
47       : shorty_(shorty), shorty_len_(shorty_len), num_bytes_(0) {
48     size_t num_slots = shorty_len + 1;  // +1 in case of receiver.
49     if (LIKELY((num_slots * 2) < kSmallArgArraySize)) {
50       // We can trivially use the small arg array.
51       arg_array_ = small_arg_array_;
52     } else {
53       // Analyze shorty to see if we need the large arg array.
54       for (size_t i = 1; i < shorty_len; ++i) {
55         char c = shorty[i];
56         if (c == 'J' || c == 'D') {
57           num_slots++;
58         }
59       }
60       if (num_slots <= kSmallArgArraySize) {
61         arg_array_ = small_arg_array_;
62       } else {
63         large_arg_array_.reset(new uint32_t[num_slots]);
64         arg_array_ = large_arg_array_.get();
65       }
66     }
67   }
68 
GetArray()69   uint32_t* GetArray() {
70     return arg_array_;
71   }
72 
GetNumBytes()73   uint32_t GetNumBytes() {
74     return num_bytes_;
75   }
76 
Append(uint32_t value)77   void Append(uint32_t value) {
78     arg_array_[num_bytes_ / 4] = value;
79     num_bytes_ += 4;
80   }
81 
Append(ObjPtr<mirror::Object> obj)82   void Append(ObjPtr<mirror::Object> obj) REQUIRES_SHARED(Locks::mutator_lock_) {
83     Append(StackReference<mirror::Object>::FromMirrorPtr(obj.Ptr()).AsVRegValue());
84   }
85 
AppendWide(uint64_t value)86   void AppendWide(uint64_t value) {
87     arg_array_[num_bytes_ / 4] = value;
88     arg_array_[(num_bytes_ / 4) + 1] = value >> 32;
89     num_bytes_ += 8;
90   }
91 
AppendFloat(float value)92   void AppendFloat(float value) {
93     jvalue jv;
94     jv.f = value;
95     Append(jv.i);
96   }
97 
AppendDouble(double value)98   void AppendDouble(double value) {
99     jvalue jv;
100     jv.d = value;
101     AppendWide(jv.j);
102   }
103 
BuildArgArrayFromVarArgs(const ScopedObjectAccessAlreadyRunnable & soa,ObjPtr<mirror::Object> receiver,va_list ap)104   void BuildArgArrayFromVarArgs(const ScopedObjectAccessAlreadyRunnable& soa,
105                                 ObjPtr<mirror::Object> receiver,
106                                 va_list ap)
107       REQUIRES_SHARED(Locks::mutator_lock_) {
108     // Set receiver if non-null (method is not static)
109     if (receiver != nullptr) {
110       Append(receiver);
111     }
112     for (size_t i = 1; i < shorty_len_; ++i) {
113       switch (shorty_[i]) {
114         case 'Z':
115         case 'B':
116         case 'C':
117         case 'S':
118         case 'I':
119           Append(va_arg(ap, jint));
120           break;
121         case 'F':
122           AppendFloat(va_arg(ap, jdouble));
123           break;
124         case 'L':
125           Append(soa.Decode<mirror::Object>(va_arg(ap, jobject)));
126           break;
127         case 'D':
128           AppendDouble(va_arg(ap, jdouble));
129           break;
130         case 'J':
131           AppendWide(va_arg(ap, jlong));
132           break;
133 #ifndef NDEBUG
134         default:
135           LOG(FATAL) << "Unexpected shorty character: " << shorty_[i];
136 #endif
137       }
138     }
139   }
140 
BuildArgArrayFromJValues(const ScopedObjectAccessAlreadyRunnable & soa,ObjPtr<mirror::Object> receiver,const jvalue * args)141   void BuildArgArrayFromJValues(const ScopedObjectAccessAlreadyRunnable& soa,
142                                 ObjPtr<mirror::Object> receiver, const jvalue* args)
143       REQUIRES_SHARED(Locks::mutator_lock_) {
144     // Set receiver if non-null (method is not static)
145     if (receiver != nullptr) {
146       Append(receiver);
147     }
148     for (size_t i = 1, args_offset = 0; i < shorty_len_; ++i, ++args_offset) {
149       switch (shorty_[i]) {
150         case 'Z':
151           Append(args[args_offset].z);
152           break;
153         case 'B':
154           Append(args[args_offset].b);
155           break;
156         case 'C':
157           Append(args[args_offset].c);
158           break;
159         case 'S':
160           Append(args[args_offset].s);
161           break;
162         case 'I':
163           FALLTHROUGH_INTENDED;
164         case 'F':
165           Append(args[args_offset].i);
166           break;
167         case 'L':
168           Append(soa.Decode<mirror::Object>(args[args_offset].l));
169           break;
170         case 'D':
171           FALLTHROUGH_INTENDED;
172         case 'J':
173           AppendWide(args[args_offset].j);
174           break;
175 #ifndef NDEBUG
176         default:
177           LOG(FATAL) << "Unexpected shorty character: " << shorty_[i];
178 #endif
179       }
180     }
181   }
182 
BuildArgArrayFromFrame(ShadowFrame * shadow_frame,uint32_t arg_offset)183   void BuildArgArrayFromFrame(ShadowFrame* shadow_frame, uint32_t arg_offset)
184       REQUIRES_SHARED(Locks::mutator_lock_) {
185     // Set receiver if non-null (method is not static)
186     size_t cur_arg = arg_offset;
187     if (!shadow_frame->GetMethod()->IsStatic()) {
188       Append(shadow_frame->GetVReg(cur_arg));
189       cur_arg++;
190     }
191     for (size_t i = 1; i < shorty_len_; ++i) {
192       switch (shorty_[i]) {
193         case 'Z':
194         case 'B':
195         case 'C':
196         case 'S':
197         case 'I':
198         case 'F':
199         case 'L':
200           Append(shadow_frame->GetVReg(cur_arg));
201           cur_arg++;
202           break;
203         case 'D':
204         case 'J':
205           AppendWide(shadow_frame->GetVRegLong(cur_arg));
206           cur_arg++;
207           cur_arg++;
208           break;
209 #ifndef NDEBUG
210         default:
211           LOG(FATAL) << "Unexpected shorty character: " << shorty_[i];
212 #endif
213       }
214     }
215   }
216 
ThrowIllegalPrimitiveArgumentException(const char * expected,const char * found_descriptor)217   static void ThrowIllegalPrimitiveArgumentException(const char* expected,
218                                                      const char* found_descriptor)
219       REQUIRES_SHARED(Locks::mutator_lock_) {
220     ThrowIllegalArgumentException(
221         StringPrintf("Invalid primitive conversion from %s to %s", expected,
222                      PrettyDescriptor(found_descriptor).c_str()).c_str());
223   }
224 
BuildArgArrayFromObjectArray(ObjPtr<mirror::Object> receiver,ObjPtr<mirror::ObjectArray<mirror::Object>> raw_args,ArtMethod * m,Thread * self)225   bool BuildArgArrayFromObjectArray(ObjPtr<mirror::Object> receiver,
226                                     ObjPtr<mirror::ObjectArray<mirror::Object>> raw_args,
227                                     ArtMethod* m,
228                                     Thread* self)
229       REQUIRES_SHARED(Locks::mutator_lock_) {
230     const dex::TypeList* classes = m->GetParameterTypeList();
231     // Set receiver if non-null (method is not static)
232     if (receiver != nullptr) {
233       Append(receiver);
234     }
235     StackHandleScope<2> hs(self);
236     MutableHandle<mirror::Object> arg(hs.NewHandle<mirror::Object>(nullptr));
237     Handle<mirror::ObjectArray<mirror::Object>> args(
238         hs.NewHandle<mirror::ObjectArray<mirror::Object>>(raw_args));
239     for (size_t i = 1, args_offset = 0; i < shorty_len_; ++i, ++args_offset) {
240       arg.Assign(args->Get(args_offset));
241       if (((shorty_[i] == 'L') && (arg != nullptr)) ||
242           ((arg == nullptr && shorty_[i] != 'L'))) {
243         // TODO: The method's parameter's type must have been previously resolved, yet
244         // we've seen cases where it's not b/34440020.
245         ObjPtr<mirror::Class> dst_class(
246             m->ResolveClassFromTypeIndex(classes->GetTypeItem(args_offset).type_idx_));
247         if (dst_class == nullptr) {
248           CHECK(self->IsExceptionPending());
249           return false;
250         }
251         if (UNLIKELY(arg == nullptr || !arg->InstanceOf(dst_class))) {
252           ThrowIllegalArgumentException(
253               StringPrintf("method %s argument %zd has type %s, got %s",
254                   m->PrettyMethod(false).c_str(),
255                   args_offset + 1,  // Humans don't count from 0.
256                   mirror::Class::PrettyDescriptor(dst_class).c_str(),
257                   mirror::Object::PrettyTypeOf(arg.Get()).c_str()).c_str());
258           return false;
259         }
260       }
261 
262 #define DO_FIRST_ARG(boxed, get_fn, append) { \
263           if (LIKELY(arg != nullptr && \
264                      arg->GetClass() == WellKnownClasses::java_lang_##boxed)) { \
265             ArtField* primitive_field = arg->GetClass()->GetInstanceField(0); \
266             append(primitive_field-> get_fn(arg.Get()));
267 
268 #define DO_ARG(boxed, get_fn, append) \
269           } else if (LIKELY(arg != nullptr && \
270                             arg->GetClass() == WellKnownClasses::java_lang_##boxed)) { \
271             ArtField* primitive_field = arg->GetClass()->GetInstanceField(0); \
272             append(primitive_field-> get_fn(arg.Get()));
273 
274 #define DO_FAIL(expected) \
275           } else { \
276             if (arg->GetClass<>()->IsPrimitive()) { \
277               std::string temp; \
278               ThrowIllegalPrimitiveArgumentException(expected, \
279                                                      arg->GetClass<>()->GetDescriptor(&temp)); \
280             } else { \
281               ThrowIllegalArgumentException(\
282                   StringPrintf("method %s argument %zd has type %s, got %s", \
283                       ArtMethod::PrettyMethod(m, false).c_str(), \
284                       args_offset + 1, \
285                       expected, \
286                       mirror::Object::PrettyTypeOf(arg.Get()).c_str()).c_str()); \
287             } \
288             return false; \
289           } }
290 
291       switch (shorty_[i]) {
292         case 'L':
293           Append(arg.Get());
294           break;
295         case 'Z':
296           DO_FIRST_ARG(Boolean, GetBoolean, Append)
297           DO_FAIL("boolean")
298           break;
299         case 'B':
300           DO_FIRST_ARG(Byte, GetByte, Append)
301           DO_FAIL("byte")
302           break;
303         case 'C':
304           DO_FIRST_ARG(Character, GetChar, Append)
305           DO_FAIL("char")
306           break;
307         case 'S':
308           DO_FIRST_ARG(Short, GetShort, Append)
309           DO_ARG(Byte, GetByte, Append)
310           DO_FAIL("short")
311           break;
312         case 'I':
313           DO_FIRST_ARG(Integer, GetInt, Append)
314           DO_ARG(Character, GetChar, Append)
315           DO_ARG(Short, GetShort, Append)
316           DO_ARG(Byte, GetByte, Append)
317           DO_FAIL("int")
318           break;
319         case 'J':
320           DO_FIRST_ARG(Long, GetLong, AppendWide)
321           DO_ARG(Integer, GetInt, AppendWide)
322           DO_ARG(Character, GetChar, AppendWide)
323           DO_ARG(Short, GetShort, AppendWide)
324           DO_ARG(Byte, GetByte, AppendWide)
325           DO_FAIL("long")
326           break;
327         case 'F':
328           DO_FIRST_ARG(Float, GetFloat, AppendFloat)
329           DO_ARG(Long, GetLong, AppendFloat)
330           DO_ARG(Integer, GetInt, AppendFloat)
331           DO_ARG(Character, GetChar, AppendFloat)
332           DO_ARG(Short, GetShort, AppendFloat)
333           DO_ARG(Byte, GetByte, AppendFloat)
334           DO_FAIL("float")
335           break;
336         case 'D':
337           DO_FIRST_ARG(Double, GetDouble, AppendDouble)
338           DO_ARG(Float, GetFloat, AppendDouble)
339           DO_ARG(Long, GetLong, AppendDouble)
340           DO_ARG(Integer, GetInt, AppendDouble)
341           DO_ARG(Character, GetChar, AppendDouble)
342           DO_ARG(Short, GetShort, AppendDouble)
343           DO_ARG(Byte, GetByte, AppendDouble)
344           DO_FAIL("double")
345           break;
346 #ifndef NDEBUG
347         default:
348           LOG(FATAL) << "Unexpected shorty character: " << shorty_[i];
349           UNREACHABLE();
350 #endif
351       }
352 #undef DO_FIRST_ARG
353 #undef DO_ARG
354 #undef DO_FAIL
355     }
356     return true;
357   }
358 
359  private:
360   enum { kSmallArgArraySize = 16 };
361   const char* const shorty_;
362   const uint32_t shorty_len_;
363   uint32_t num_bytes_;
364   uint32_t* arg_array_;
365   uint32_t small_arg_array_[kSmallArgArraySize];
366   std::unique_ptr<uint32_t[]> large_arg_array_;
367 };
368 
CheckMethodArguments(JavaVMExt * vm,ArtMethod * m,uint32_t * args)369 void CheckMethodArguments(JavaVMExt* vm, ArtMethod* m, uint32_t* args)
370     REQUIRES_SHARED(Locks::mutator_lock_) {
371   const dex::TypeList* params = m->GetParameterTypeList();
372   if (params == nullptr) {
373     return;  // No arguments so nothing to check.
374   }
375   uint32_t offset = 0;
376   uint32_t num_params = params->Size();
377   size_t error_count = 0;
378   if (!m->IsStatic()) {
379     offset = 1;
380   }
381   // TODO: If args contain object references, it may cause problems.
382   Thread* const self = Thread::Current();
383   for (uint32_t i = 0; i < num_params; i++) {
384     dex::TypeIndex type_idx = params->GetTypeItem(i).type_idx_;
385     ObjPtr<mirror::Class> param_type(m->ResolveClassFromTypeIndex(type_idx));
386     if (param_type == nullptr) {
387       CHECK(self->IsExceptionPending());
388       LOG(ERROR) << "Internal error: unresolvable type for argument type in JNI invoke: "
389           << m->GetTypeDescriptorFromTypeIdx(type_idx) << "\n"
390           << self->GetException()->Dump();
391       self->ClearException();
392       ++error_count;
393     } else if (!param_type->IsPrimitive()) {
394       // TODO: There is a compaction bug here since GetClassFromTypeIdx can cause thread suspension,
395       // this is a hard to fix problem since the args can contain Object*, we need to save and
396       // restore them by using a visitor similar to the ones used in the trampoline entrypoints.
397       ObjPtr<mirror::Object> argument =
398           (reinterpret_cast<StackReference<mirror::Object>*>(&args[i + offset]))->AsMirrorPtr();
399       if (argument != nullptr && !argument->InstanceOf(param_type)) {
400         LOG(ERROR) << "JNI ERROR (app bug): attempt to pass an instance of "
401                    << argument->PrettyTypeOf() << " as argument " << (i + 1)
402                    << " to " << m->PrettyMethod();
403         ++error_count;
404       }
405     } else if (param_type->IsPrimitiveLong() || param_type->IsPrimitiveDouble()) {
406       offset++;
407     } else {
408       int32_t arg = static_cast<int32_t>(args[i + offset]);
409       if (param_type->IsPrimitiveBoolean()) {
410         if (arg != JNI_TRUE && arg != JNI_FALSE) {
411           LOG(ERROR) << "JNI ERROR (app bug): expected jboolean (0/1) but got value of "
412               << arg << " as argument " << (i + 1) << " to " << m->PrettyMethod();
413           ++error_count;
414         }
415       } else if (param_type->IsPrimitiveByte()) {
416         if (arg < -128 || arg > 127) {
417           LOG(ERROR) << "JNI ERROR (app bug): expected jbyte but got value of "
418               << arg << " as argument " << (i + 1) << " to " << m->PrettyMethod();
419           ++error_count;
420         }
421       } else if (param_type->IsPrimitiveChar()) {
422         if (args[i + offset] > 0xFFFF) {
423           LOG(ERROR) << "JNI ERROR (app bug): expected jchar but got value of "
424               << arg << " as argument " << (i + 1) << " to " << m->PrettyMethod();
425           ++error_count;
426         }
427       } else if (param_type->IsPrimitiveShort()) {
428         if (arg < -32768 || arg > 0x7FFF) {
429           LOG(ERROR) << "JNI ERROR (app bug): expected jshort but got value of "
430               << arg << " as argument " << (i + 1) << " to " << m->PrettyMethod();
431           ++error_count;
432         }
433       }
434     }
435   }
436   if (UNLIKELY(error_count > 0)) {
437     // TODO: pass the JNI function name (such as "CallVoidMethodV") through so we can call JniAbort
438     // with an argument.
439     vm->JniAbortF(nullptr, "bad arguments passed to %s (see above for details)",
440                   m->PrettyMethod().c_str());
441   }
442 }
443 
FindVirtualMethod(ObjPtr<mirror::Object> receiver,ArtMethod * method)444 ArtMethod* FindVirtualMethod(ObjPtr<mirror::Object> receiver, ArtMethod* method)
445     REQUIRES_SHARED(Locks::mutator_lock_) {
446   return receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(method, kRuntimePointerSize);
447 }
448 
449 
InvokeWithArgArray(const ScopedObjectAccessAlreadyRunnable & soa,ArtMethod * method,ArgArray * arg_array,JValue * result,const char * shorty)450 void InvokeWithArgArray(const ScopedObjectAccessAlreadyRunnable& soa,
451                                ArtMethod* method, ArgArray* arg_array, JValue* result,
452                                const char* shorty)
453     REQUIRES_SHARED(Locks::mutator_lock_) {
454   uint32_t* args = arg_array->GetArray();
455   if (UNLIKELY(soa.Env()->IsCheckJniEnabled())) {
456     CheckMethodArguments(soa.Vm(), method->GetInterfaceMethodIfProxy(kRuntimePointerSize), args);
457   }
458   method->Invoke(soa.Self(), args, arg_array->GetNumBytes(), result, shorty);
459 }
460 
461 ALWAYS_INLINE
CheckArgsForInvokeMethod(ArtMethod * np_method,ObjPtr<mirror::ObjectArray<mirror::Object>> objects)462 bool CheckArgsForInvokeMethod(ArtMethod* np_method,
463                               ObjPtr<mirror::ObjectArray<mirror::Object>> objects)
464     REQUIRES_SHARED(Locks::mutator_lock_) {
465   const dex::TypeList* classes = np_method->GetParameterTypeList();
466   uint32_t classes_size = (classes == nullptr) ? 0 : classes->Size();
467   uint32_t arg_count = (objects == nullptr) ? 0 : objects->GetLength();
468   if (UNLIKELY(arg_count != classes_size)) {
469     ThrowIllegalArgumentException(StringPrintf("Wrong number of arguments; expected %d, got %d",
470                                                classes_size, arg_count).c_str());
471     return false;
472   }
473   return true;
474 }
475 
476 ALWAYS_INLINE
InvokeMethodImpl(const ScopedObjectAccessAlreadyRunnable & soa,ArtMethod * m,ArtMethod * np_method,ObjPtr<mirror::Object> receiver,ObjPtr<mirror::ObjectArray<mirror::Object>> objects,const char ** shorty,JValue * result)477 bool InvokeMethodImpl(const ScopedObjectAccessAlreadyRunnable& soa,
478                       ArtMethod* m,
479                       ArtMethod* np_method,
480                       ObjPtr<mirror::Object> receiver,
481                       ObjPtr<mirror::ObjectArray<mirror::Object>> objects,
482                       const char** shorty,
483                       JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
484   // Invoke the method.
485   uint32_t shorty_len = 0;
486   *shorty = np_method->GetShorty(&shorty_len);
487   ArgArray arg_array(*shorty, shorty_len);
488   if (!arg_array.BuildArgArrayFromObjectArray(receiver, objects, np_method, soa.Self())) {
489     CHECK(soa.Self()->IsExceptionPending());
490     return false;
491   }
492 
493   InvokeWithArgArray(soa, m, &arg_array, result, *shorty);
494 
495   // Wrap any exception with "Ljava/lang/reflect/InvocationTargetException;" and return early.
496   if (soa.Self()->IsExceptionPending()) {
497     // To abort a transaction we use a fake exception that should never be caught by the bytecode
498     // and therefore it makes no sense to wrap it.
499     if (Runtime::Current()->IsActiveTransaction() &&
500         Runtime::Current()->GetClassLinker()->IsTransactionAborted()) {
501       DCHECK(soa.Self()->GetException()->GetClass()->DescriptorEquals(
502                   "Ldalvik/system/TransactionAbortError;"))
503           << soa.Self()->GetException()->GetClass()->PrettyDescriptor();
504     } else {
505       // If we get another exception when we are trying to wrap, then just use that instead.
506       StackHandleScope<2u> hs(soa.Self());
507       Handle<mirror::Throwable> cause = hs.NewHandle(soa.Self()->GetException());
508       soa.Self()->ClearException();
509       Handle<mirror::Object> exception_instance =
510           WellKnownClasses::java_lang_reflect_InvocationTargetException_init->NewObject<'L'>(
511               hs, soa.Self(), cause);
512       if (exception_instance == nullptr) {
513         soa.Self()->AssertPendingException();
514         return false;
515       }
516       soa.Self()->SetException(exception_instance->AsThrowable());
517     }
518     return false;
519   }
520 
521   return true;
522 }
523 
524 }  // anonymous namespace
525 
526 template <>
527 NO_STACK_PROTECTOR
InvokeWithVarArgs(const ScopedObjectAccessAlreadyRunnable & soa,jobject obj,ArtMethod * method,va_list args)528 JValue InvokeWithVarArgs(const ScopedObjectAccessAlreadyRunnable& soa,
529                          jobject obj,
530                          ArtMethod* method,
531                          va_list args) REQUIRES_SHARED(Locks::mutator_lock_) {
532   // We want to make sure that the stack is not within a small distance from the
533   // protected region in case we are calling into a leaf function whose stack
534   // check has been elided.
535   if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEnd())) {
536     ThrowStackOverflowError(soa.Self());
537     return JValue();
538   }
539   bool is_string_init = method->IsStringConstructor();
540   if (is_string_init) {
541     // Replace calls to String.<init> with equivalent StringFactory call.
542     method = WellKnownClasses::StringInitToStringFactory(method);
543   }
544   ObjPtr<mirror::Object> receiver = method->IsStatic() ? nullptr : soa.Decode<mirror::Object>(obj);
545   uint32_t shorty_len = 0;
546   const char* shorty =
547       method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(&shorty_len);
548   JValue result;
549   ArgArray arg_array(shorty, shorty_len);
550   arg_array.BuildArgArrayFromVarArgs(soa, receiver, args);
551   InvokeWithArgArray(soa, method, &arg_array, &result, shorty);
552   if (is_string_init) {
553     // For string init, remap original receiver to StringFactory result.
554     UpdateReference(soa.Self(), obj, result.GetL());
555   }
556   return result;
557 }
558 
559 template <>
560 NO_STACK_PROTECTOR
InvokeWithVarArgs(const ScopedObjectAccessAlreadyRunnable & soa,jobject obj,jmethodID mid,va_list args)561 JValue InvokeWithVarArgs(const ScopedObjectAccessAlreadyRunnable& soa,
562                          jobject obj,
563                          jmethodID mid,
564                          va_list args) REQUIRES_SHARED(Locks::mutator_lock_) {
565   DCHECK(mid != nullptr) << "Called with null jmethodID";
566   return InvokeWithVarArgs(soa, obj, jni::DecodeArtMethod(mid), args);
567 }
568 
569 template <>
InvokeWithJValues(const ScopedObjectAccessAlreadyRunnable & soa,jobject obj,ArtMethod * method,const jvalue * args)570 JValue InvokeWithJValues(const ScopedObjectAccessAlreadyRunnable& soa,
571                          jobject obj,
572                          ArtMethod* method,
573                          const jvalue* args) {
574   // We want to make sure that the stack is not within a small distance from the
575   // protected region in case we are calling into a leaf function whose stack
576   // check has been elided.
577   if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEnd())) {
578     ThrowStackOverflowError(soa.Self());
579     return JValue();
580   }
581   bool is_string_init = method->IsStringConstructor();
582   if (is_string_init) {
583     // Replace calls to String.<init> with equivalent StringFactory call.
584     method = WellKnownClasses::StringInitToStringFactory(method);
585   }
586   ObjPtr<mirror::Object> receiver = method->IsStatic() ? nullptr : soa.Decode<mirror::Object>(obj);
587   uint32_t shorty_len = 0;
588   const char* shorty =
589       method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(&shorty_len);
590   JValue result;
591   ArgArray arg_array(shorty, shorty_len);
592   arg_array.BuildArgArrayFromJValues(soa, receiver, args);
593   InvokeWithArgArray(soa, method, &arg_array, &result, shorty);
594   if (is_string_init) {
595     // For string init, remap original receiver to StringFactory result.
596     UpdateReference(soa.Self(), obj, result.GetL());
597   }
598   return result;
599 }
600 
601 template <>
InvokeWithJValues(const ScopedObjectAccessAlreadyRunnable & soa,jobject obj,jmethodID mid,const jvalue * args)602 JValue InvokeWithJValues(const ScopedObjectAccessAlreadyRunnable& soa,
603                          jobject obj,
604                          jmethodID mid,
605                          const jvalue* args) {
606   DCHECK(mid != nullptr) << "Called with null jmethodID";
607   return InvokeWithJValues(soa, obj, jni::DecodeArtMethod(mid), args);
608 }
609 
610 template <>
InvokeVirtualOrInterfaceWithJValues(const ScopedObjectAccessAlreadyRunnable & soa,jobject obj,ArtMethod * interface_method,const jvalue * args)611 JValue InvokeVirtualOrInterfaceWithJValues(const ScopedObjectAccessAlreadyRunnable& soa,
612                                            jobject obj,
613                                            ArtMethod* interface_method,
614                                            const jvalue* args) {
615   // We want to make sure that the stack is not within a small distance from the
616   // protected region in case we are calling into a leaf function whose stack
617   // check has been elided.
618   if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEnd())) {
619     ThrowStackOverflowError(soa.Self());
620     return JValue();
621   }
622   ObjPtr<mirror::Object> receiver = soa.Decode<mirror::Object>(obj);
623   ArtMethod* method = FindVirtualMethod(receiver, interface_method);
624   bool is_string_init = method->IsStringConstructor();
625   if (is_string_init) {
626     // Replace calls to String.<init> with equivalent StringFactory call.
627     method = WellKnownClasses::StringInitToStringFactory(method);
628     receiver = nullptr;
629   }
630   uint32_t shorty_len = 0;
631   const char* shorty =
632       method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(&shorty_len);
633   JValue result;
634   ArgArray arg_array(shorty, shorty_len);
635   arg_array.BuildArgArrayFromJValues(soa, receiver, args);
636   InvokeWithArgArray(soa, method, &arg_array, &result, shorty);
637   if (is_string_init) {
638     // For string init, remap original receiver to StringFactory result.
639     UpdateReference(soa.Self(), obj, result.GetL());
640   }
641   return result;
642 }
643 
644 template <>
InvokeVirtualOrInterfaceWithJValues(const ScopedObjectAccessAlreadyRunnable & soa,jobject obj,jmethodID mid,const jvalue * args)645 JValue InvokeVirtualOrInterfaceWithJValues(const ScopedObjectAccessAlreadyRunnable& soa,
646                                            jobject obj,
647                                            jmethodID mid,
648                                            const jvalue* args) {
649   DCHECK(mid != nullptr) << "Called with null jmethodID";
650   return InvokeVirtualOrInterfaceWithJValues(soa, obj, jni::DecodeArtMethod(mid), args);
651 }
652 
653 template <>
InvokeVirtualOrInterfaceWithVarArgs(const ScopedObjectAccessAlreadyRunnable & soa,jobject obj,ArtMethod * interface_method,va_list args)654 JValue InvokeVirtualOrInterfaceWithVarArgs(const ScopedObjectAccessAlreadyRunnable& soa,
655                                            jobject obj,
656                                            ArtMethod* interface_method,
657                                            va_list args) {
658   // We want to make sure that the stack is not within a small distance from the
659   // protected region in case we are calling into a leaf function whose stack
660   // check has been elided.
661   if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEnd())) {
662     ThrowStackOverflowError(soa.Self());
663     return JValue();
664   }
665 
666   ObjPtr<mirror::Object> receiver = soa.Decode<mirror::Object>(obj);
667   ArtMethod* method = FindVirtualMethod(receiver, interface_method);
668   bool is_string_init = method->IsStringConstructor();
669   if (is_string_init) {
670     // Replace calls to String.<init> with equivalent StringFactory call.
671     method = WellKnownClasses::StringInitToStringFactory(method);
672     receiver = nullptr;
673   }
674   uint32_t shorty_len = 0;
675   const char* shorty =
676       method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(&shorty_len);
677   JValue result;
678   ArgArray arg_array(shorty, shorty_len);
679   arg_array.BuildArgArrayFromVarArgs(soa, receiver, args);
680   InvokeWithArgArray(soa, method, &arg_array, &result, shorty);
681   if (is_string_init) {
682     // For string init, remap original receiver to StringFactory result.
683     UpdateReference(soa.Self(), obj, result.GetL());
684   }
685   return result;
686 }
687 
688 template <>
InvokeVirtualOrInterfaceWithVarArgs(const ScopedObjectAccessAlreadyRunnable & soa,jobject obj,jmethodID mid,va_list args)689 JValue InvokeVirtualOrInterfaceWithVarArgs(const ScopedObjectAccessAlreadyRunnable& soa,
690                                            jobject obj,
691                                            jmethodID mid,
692                                            va_list args) {
693   DCHECK(mid != nullptr) << "Called with null jmethodID";
694   return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, jni::DecodeArtMethod(mid), args);
695 }
696 
697 template <PointerSize kPointerSize>
InvokeMethod(const ScopedObjectAccessAlreadyRunnable & soa,jobject javaMethod,jobject javaReceiver,jobject javaArgs,size_t num_frames)698 jobject InvokeMethod(const ScopedObjectAccessAlreadyRunnable& soa, jobject javaMethod,
699                      jobject javaReceiver, jobject javaArgs, size_t num_frames) {
700   // We want to make sure that the stack is not within a small distance from the
701   // protected region in case we are calling into a leaf function whose stack
702   // check has been elided.
703   if (UNLIKELY(__builtin_frame_address(0) <
704                soa.Self()->GetStackEndForInterpreter(true))) {
705     ThrowStackOverflowError(soa.Self());
706     return nullptr;
707   }
708 
709   ObjPtr<mirror::Executable> executable = soa.Decode<mirror::Executable>(javaMethod);
710   const bool accessible = executable->IsAccessible();
711   ArtMethod* m = executable->GetArtMethod();
712 
713   ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClass();
714   if (UNLIKELY(!declaring_class->IsVisiblyInitialized())) {
715     Thread* self = soa.Self();
716     StackHandleScope<1> hs(self);
717     HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&declaring_class));
718     if (UNLIKELY(!Runtime::Current()->GetClassLinker()->EnsureInitialized(
719                       self, h_class, /*can_init_fields=*/ true, /*can_init_parents=*/ true))) {
720       DCHECK(self->IsExceptionPending());
721       return nullptr;
722     }
723     DCHECK(h_class->IsInitializing());
724   }
725 
726   ObjPtr<mirror::Object> receiver;
727   if (!m->IsStatic()) {
728     // Replace calls to String.<init> with equivalent StringFactory call.
729     if (declaring_class->IsStringClass() && m->IsConstructor()) {
730       m = WellKnownClasses::StringInitToStringFactory(m);
731       CHECK(javaReceiver == nullptr);
732     } else {
733       // Check that the receiver is non-null and an instance of the field's declaring class.
734       receiver = soa.Decode<mirror::Object>(javaReceiver);
735       if (!VerifyObjectIsClass(receiver, declaring_class)) {
736         return nullptr;
737       }
738 
739       // Find the actual implementation of the virtual method.
740       m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(m, kPointerSize);
741     }
742   }
743 
744   // Get our arrays of arguments and their types, and check they're the same size.
745   ObjPtr<mirror::ObjectArray<mirror::Object>> objects =
746       soa.Decode<mirror::ObjectArray<mirror::Object>>(javaArgs);
747   auto* np_method = m->GetInterfaceMethodIfProxy(kPointerSize);
748   if (!CheckArgsForInvokeMethod(np_method, objects)) {
749     return nullptr;
750   }
751 
752   // If method is not set to be accessible, verify it can be accessed by the caller.
753   ObjPtr<mirror::Class> calling_class;
754   if (!accessible && !VerifyAccess(soa.Self(),
755                                    receiver,
756                                    declaring_class,
757                                    m->GetAccessFlags(),
758                                    &calling_class,
759                                    num_frames)) {
760     ThrowIllegalAccessException(
761         StringPrintf("Class %s cannot access %s method %s of class %s",
762             calling_class == nullptr ? "null" : calling_class->PrettyClass().c_str(),
763             PrettyJavaAccessFlags(m->GetAccessFlags()).c_str(),
764             m->PrettyMethod().c_str(),
765             m->GetDeclaringClass() == nullptr ? "null" :
766                 m->GetDeclaringClass()->PrettyClass().c_str()).c_str());
767     return nullptr;
768   }
769 
770   // Invoke the method.
771   JValue result;
772   const char* shorty;
773   if (!InvokeMethodImpl(soa, m, np_method, receiver, objects, &shorty, &result)) {
774     return nullptr;
775   }
776   return soa.AddLocalReference<jobject>(BoxPrimitive(Primitive::GetType(shorty[0]), result));
777 }
778 
779 template
780 jobject InvokeMethod<PointerSize::k32>(const ScopedObjectAccessAlreadyRunnable& soa,
781                                        jobject javaMethod,
782                                        jobject javaReceiver,
783                                        jobject javaArgs,
784                                        size_t num_frames);
785 template
786 jobject InvokeMethod<PointerSize::k64>(const ScopedObjectAccessAlreadyRunnable& soa,
787                                        jobject javaMethod,
788                                        jobject javaReceiver,
789                                        jobject javaArgs,
790                                        size_t num_frames);
791 
InvokeConstructor(const ScopedObjectAccessAlreadyRunnable & soa,ArtMethod * constructor,ObjPtr<mirror::Object> receiver,jobject javaArgs)792 void InvokeConstructor(const ScopedObjectAccessAlreadyRunnable& soa,
793                        ArtMethod* constructor,
794                        ObjPtr<mirror::Object> receiver,
795                        jobject javaArgs) {
796   // We want to make sure that the stack is not within a small distance from the
797   // protected region in case we are calling into a leaf function whose stack
798   // check has been elided.
799   if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEndForInterpreter(true))) {
800     ThrowStackOverflowError(soa.Self());
801     return;
802   }
803 
804   if (kIsDebugBuild) {
805     CHECK(constructor->IsConstructor());
806 
807     ObjPtr<mirror::Class> declaring_class = constructor->GetDeclaringClass();
808     CHECK(declaring_class->IsInitializing());
809 
810     // Calls to String.<init> should have been repplaced with with equivalent StringFactory calls.
811     CHECK(!declaring_class->IsStringClass());
812 
813     // Check that the receiver is non-null and an instance of the field's declaring class.
814     CHECK(receiver != nullptr);
815     CHECK(VerifyObjectIsClass(receiver, declaring_class));
816     CHECK_EQ(constructor,
817              receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(constructor,
818                                                                           kRuntimePointerSize));
819   }
820 
821   // Get our arrays of arguments and their types, and check they're the same size.
822   ObjPtr<mirror::ObjectArray<mirror::Object>> objects =
823       soa.Decode<mirror::ObjectArray<mirror::Object>>(javaArgs);
824   ArtMethod* np_method = constructor->GetInterfaceMethodIfProxy(kRuntimePointerSize);
825   if (!CheckArgsForInvokeMethod(np_method, objects)) {
826     return;
827   }
828 
829   // Invoke the constructor.
830   JValue result;
831   const char* shorty;
832   InvokeMethodImpl(soa, constructor, np_method, receiver, objects, &shorty, &result);
833 }
834 
BoxPrimitive(Primitive::Type src_class,const JValue & value)835 ObjPtr<mirror::Object> BoxPrimitive(Primitive::Type src_class, const JValue& value) {
836   if (src_class == Primitive::kPrimNot) {
837     return value.GetL();
838   }
839   if (src_class == Primitive::kPrimVoid) {
840     // There's no such thing as a void field, and void methods invoked via reflection return null.
841     return nullptr;
842   }
843 
844   ArtMethod* m = nullptr;
845   const char* shorty;
846   switch (src_class) {
847   case Primitive::kPrimBoolean:
848     m = WellKnownClasses::java_lang_Boolean_valueOf;
849     shorty = "LZ";
850     break;
851   case Primitive::kPrimByte:
852     m = WellKnownClasses::java_lang_Byte_valueOf;
853     shorty = "LB";
854     break;
855   case Primitive::kPrimChar:
856     m = WellKnownClasses::java_lang_Character_valueOf;
857     shorty = "LC";
858     break;
859   case Primitive::kPrimDouble:
860     m = WellKnownClasses::java_lang_Double_valueOf;
861     shorty = "LD";
862     break;
863   case Primitive::kPrimFloat:
864     m = WellKnownClasses::java_lang_Float_valueOf;
865     shorty = "LF";
866     break;
867   case Primitive::kPrimInt:
868     m = WellKnownClasses::java_lang_Integer_valueOf;
869     shorty = "LI";
870     break;
871   case Primitive::kPrimLong:
872     m = WellKnownClasses::java_lang_Long_valueOf;
873     shorty = "LJ";
874     break;
875   case Primitive::kPrimShort:
876     m = WellKnownClasses::java_lang_Short_valueOf;
877     shorty = "LS";
878     break;
879   default:
880     LOG(FATAL) << static_cast<int>(src_class);
881     shorty = nullptr;
882   }
883 
884   ScopedObjectAccessUnchecked soa(Thread::Current());
885   DCHECK_EQ(soa.Self()->GetState(), ThreadState::kRunnable);
886 
887   ArgArray arg_array(shorty, 2);
888   JValue result;
889   if (src_class == Primitive::kPrimDouble || src_class == Primitive::kPrimLong) {
890     arg_array.AppendWide(value.GetJ());
891   } else {
892     arg_array.Append(value.GetI());
893   }
894 
895   DCHECK(m->GetDeclaringClass()->IsInitialized());  // By `ClassLinker::RunRootClinits()`.
896   m->Invoke(soa.Self(), arg_array.GetArray(), arg_array.GetNumBytes(), &result, shorty);
897   return result.GetL();
898 }
899 
UnboxingFailureKind(ArtField * f)900 static std::string UnboxingFailureKind(ArtField* f)
901     REQUIRES_SHARED(Locks::mutator_lock_) {
902   if (f != nullptr) {
903     return "field " + f->PrettyField(false);
904   }
905   return "result";
906 }
907 
UnboxPrimitive(ObjPtr<mirror::Object> o,ObjPtr<mirror::Class> dst_class,ArtField * f,JValue * unboxed_value)908 static bool UnboxPrimitive(ObjPtr<mirror::Object> o,
909                            ObjPtr<mirror::Class> dst_class,
910                            ArtField* f,
911                            JValue* unboxed_value)
912     REQUIRES_SHARED(Locks::mutator_lock_) {
913   bool unbox_for_result = (f == nullptr);
914   if (!dst_class->IsPrimitive()) {
915     if (UNLIKELY(o != nullptr && !o->InstanceOf(dst_class))) {
916       if (!unbox_for_result) {
917         ThrowIllegalArgumentException(
918             StringPrintf("%s has type %s, got %s",
919                          UnboxingFailureKind(f).c_str(),
920                          dst_class->PrettyDescriptor().c_str(),
921                          o->PrettyTypeOf().c_str()).c_str());
922       } else {
923         ThrowClassCastException(
924             StringPrintf("Couldn't convert result of type %s to %s",
925                          o->PrettyTypeOf().c_str(),
926                          dst_class->PrettyDescriptor().c_str()).c_str());
927       }
928       return false;
929     }
930     unboxed_value->SetL(o);
931     return true;
932   }
933   if (UNLIKELY(dst_class->GetPrimitiveType() == Primitive::kPrimVoid)) {
934     ThrowIllegalArgumentException(StringPrintf("Can't unbox %s to void",
935                                                UnboxingFailureKind(f).c_str()).c_str());
936     return false;
937   }
938   if (UNLIKELY(o == nullptr)) {
939     if (!unbox_for_result) {
940       ThrowIllegalArgumentException(
941           StringPrintf("%s has type %s, got null",
942                        UnboxingFailureKind(f).c_str(),
943                        dst_class->PrettyDescriptor().c_str()).c_str());
944     } else {
945       ThrowNullPointerException(
946           StringPrintf("Expected to unbox a '%s' primitive type but was returned null",
947                        dst_class->PrettyDescriptor().c_str()).c_str());
948     }
949     return false;
950   }
951 
952   JValue boxed_value;
953   ObjPtr<mirror::Class> klass = o->GetClass();
954   Primitive::Type primitive_type;
955   ArtField* primitive_field = &klass->GetIFieldsPtr()->At(0);
956   if (klass == WellKnownClasses::java_lang_Boolean) {
957     primitive_type = Primitive::kPrimBoolean;
958     boxed_value.SetZ(primitive_field->GetBoolean(o));
959   } else if (klass == WellKnownClasses::java_lang_Byte) {
960     primitive_type = Primitive::kPrimByte;
961     boxed_value.SetB(primitive_field->GetByte(o));
962   } else if (klass == WellKnownClasses::java_lang_Character) {
963     primitive_type = Primitive::kPrimChar;
964     boxed_value.SetC(primitive_field->GetChar(o));
965   } else if (klass == WellKnownClasses::java_lang_Float) {
966     primitive_type = Primitive::kPrimFloat;
967     boxed_value.SetF(primitive_field->GetFloat(o));
968   } else if (klass == WellKnownClasses::java_lang_Double) {
969     primitive_type = Primitive::kPrimDouble;
970     boxed_value.SetD(primitive_field->GetDouble(o));
971   } else if (klass == WellKnownClasses::java_lang_Integer) {
972     primitive_type = Primitive::kPrimInt;
973     boxed_value.SetI(primitive_field->GetInt(o));
974   } else if (klass == WellKnownClasses::java_lang_Long) {
975     primitive_type = Primitive::kPrimLong;
976     boxed_value.SetJ(primitive_field->GetLong(o));
977   } else if (klass == WellKnownClasses::java_lang_Short) {
978     primitive_type = Primitive::kPrimShort;
979     boxed_value.SetS(primitive_field->GetShort(o));
980   } else {
981     std::string temp;
982     ThrowIllegalArgumentException(
983         StringPrintf("%s has type %s, got %s", UnboxingFailureKind(f).c_str(),
984             dst_class->PrettyDescriptor().c_str(),
985             PrettyDescriptor(o->GetClass()->GetDescriptor(&temp)).c_str()).c_str());
986     return false;
987   }
988 
989   return ConvertPrimitiveValue(unbox_for_result,
990                                primitive_type,
991                                dst_class->GetPrimitiveType(),
992                                boxed_value, unboxed_value);
993 }
994 
UnboxPrimitiveForField(ObjPtr<mirror::Object> o,ObjPtr<mirror::Class> dst_class,ArtField * f,JValue * unboxed_value)995 bool UnboxPrimitiveForField(ObjPtr<mirror::Object> o,
996                             ObjPtr<mirror::Class> dst_class,
997                             ArtField* f,
998                             JValue* unboxed_value) {
999   DCHECK(f != nullptr);
1000   return UnboxPrimitive(o, dst_class, f, unboxed_value);
1001 }
1002 
UnboxPrimitiveForResult(ObjPtr<mirror::Object> o,ObjPtr<mirror::Class> dst_class,JValue * unboxed_value)1003 bool UnboxPrimitiveForResult(ObjPtr<mirror::Object> o,
1004                              ObjPtr<mirror::Class> dst_class,
1005                              JValue* unboxed_value) {
1006   return UnboxPrimitive(o, dst_class, nullptr, unboxed_value);
1007 }
1008 
GetCallingClass(Thread * self,size_t num_frames)1009 ObjPtr<mirror::Class> GetCallingClass(Thread* self, size_t num_frames) {
1010   NthCallerVisitor visitor(self, num_frames);
1011   visitor.WalkStack();
1012   return visitor.caller != nullptr ? visitor.caller->GetDeclaringClass() : nullptr;
1013 }
1014 
VerifyAccess(Thread * self,ObjPtr<mirror::Object> obj,ObjPtr<mirror::Class> declaring_class,uint32_t access_flags,ObjPtr<mirror::Class> * calling_class,size_t num_frames)1015 bool VerifyAccess(Thread* self,
1016                   ObjPtr<mirror::Object> obj,
1017                   ObjPtr<mirror::Class> declaring_class,
1018                   uint32_t access_flags,
1019                   ObjPtr<mirror::Class>* calling_class,
1020                   size_t num_frames) {
1021   if ((access_flags & kAccPublic) != 0) {
1022     return true;
1023   }
1024   ObjPtr<mirror::Class> klass = GetCallingClass(self, num_frames);
1025   if (UNLIKELY(klass == nullptr)) {
1026     // The caller is an attached native thread.
1027     return false;
1028   }
1029   *calling_class = klass;
1030   return VerifyAccess(obj, declaring_class, access_flags, klass);
1031 }
1032 
VerifyAccess(ObjPtr<mirror::Object> obj,ObjPtr<mirror::Class> declaring_class,uint32_t access_flags,ObjPtr<mirror::Class> calling_class)1033 bool VerifyAccess(ObjPtr<mirror::Object> obj,
1034                   ObjPtr<mirror::Class> declaring_class,
1035                   uint32_t access_flags,
1036                   ObjPtr<mirror::Class> calling_class) {
1037   if (calling_class == declaring_class) {
1038     return true;
1039   }
1040   ScopedAssertNoThreadSuspension sants("verify-access");
1041   if ((access_flags & kAccPrivate) != 0) {
1042     return false;
1043   }
1044   if ((access_flags & kAccProtected) != 0) {
1045     if (obj != nullptr && !obj->InstanceOf(calling_class) &&
1046         !declaring_class->IsInSamePackage(calling_class)) {
1047       return false;
1048     } else if (declaring_class->IsAssignableFrom(calling_class)) {
1049       return true;
1050     }
1051   }
1052   return declaring_class->IsInSamePackage(calling_class);
1053 }
1054 
InvalidReceiverError(ObjPtr<mirror::Object> o,ObjPtr<mirror::Class> c)1055 void InvalidReceiverError(ObjPtr<mirror::Object> o, ObjPtr<mirror::Class> c) {
1056   std::string expected_class_name(mirror::Class::PrettyDescriptor(c));
1057   std::string actual_class_name(mirror::Object::PrettyTypeOf(o));
1058   ThrowIllegalArgumentException(StringPrintf("Expected receiver of type %s, but got %s",
1059                                              expected_class_name.c_str(),
1060                                              actual_class_name.c_str()).c_str());
1061 }
1062 
1063 // This only works if there's one reference which points to the object in obj.
1064 // Will need to be fixed if there's cases where it's not.
UpdateReference(Thread * self,jobject obj,ObjPtr<mirror::Object> result)1065 void UpdateReference(Thread* self, jobject obj, ObjPtr<mirror::Object> result) {
1066   IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1067   IndirectRefKind kind = IndirectReferenceTable::GetIndirectRefKind(ref);
1068   if (kind == kLocal) {
1069     self->GetJniEnv()->UpdateLocal(obj, result);
1070   } else if (kind == kJniTransition) {
1071     LOG(FATAL) << "Unsupported UpdateReference for kind kJniTransition";
1072   } else if (kind == kGlobal) {
1073     self->GetJniEnv()->GetVm()->UpdateGlobal(self, ref, result);
1074   } else {
1075     DCHECK_EQ(kind, kWeakGlobal);
1076     self->GetJniEnv()->GetVm()->UpdateWeakGlobal(self, ref, result);
1077   }
1078 }
1079 
1080 }  // namespace art
1081