reflection.cc revision ca239af73e512df5eeb80fe6c09c2ca614649e06
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 "class_linker.h" 20#include "common_throws.h" 21#include "dex_file-inl.h" 22#include "entrypoints/entrypoint_utils.h" 23#include "jni_internal.h" 24#include "mirror/art_field-inl.h" 25#include "mirror/art_method-inl.h" 26#include "mirror/class-inl.h" 27#include "mirror/object_array-inl.h" 28#include "mirror/object_array.h" 29#include "nth_caller_visitor.h" 30#include "scoped_thread_state_change.h" 31#include "stack.h" 32#include "well_known_classes.h" 33 34namespace art { 35 36class ArgArray { 37 public: 38 explicit ArgArray(const char* shorty, uint32_t shorty_len) 39 : shorty_(shorty), shorty_len_(shorty_len), num_bytes_(0) { 40 size_t num_slots = shorty_len + 1; // +1 in case of receiver. 41 if (LIKELY((num_slots * 2) < kSmallArgArraySize)) { 42 // We can trivially use the small arg array. 43 arg_array_ = small_arg_array_; 44 } else { 45 // Analyze shorty to see if we need the large arg array. 46 for (size_t i = 1; i < shorty_len; ++i) { 47 char c = shorty[i]; 48 if (c == 'J' || c == 'D') { 49 num_slots++; 50 } 51 } 52 if (num_slots <= kSmallArgArraySize) { 53 arg_array_ = small_arg_array_; 54 } else { 55 large_arg_array_.reset(new uint32_t[num_slots]); 56 arg_array_ = large_arg_array_.get(); 57 } 58 } 59 } 60 61 uint32_t* GetArray() { 62 return arg_array_; 63 } 64 65 uint32_t GetNumBytes() { 66 return num_bytes_; 67 } 68 69 void Append(uint32_t value) { 70 arg_array_[num_bytes_ / 4] = value; 71 num_bytes_ += 4; 72 } 73 74 void Append(mirror::Object* obj) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 75 Append(StackReference<mirror::Object>::FromMirrorPtr(obj).AsVRegValue()); 76 } 77 78 void AppendWide(uint64_t value) { 79 arg_array_[num_bytes_ / 4] = value; 80 arg_array_[(num_bytes_ / 4) + 1] = value >> 32; 81 num_bytes_ += 8; 82 } 83 84 void AppendFloat(float value) { 85 jvalue jv; 86 jv.f = value; 87 Append(jv.i); 88 } 89 90 void AppendDouble(double value) { 91 jvalue jv; 92 jv.d = value; 93 AppendWide(jv.j); 94 } 95 96 void BuildArgArrayFromVarArgs(const ScopedObjectAccessAlreadyRunnable& soa, 97 mirror::Object* receiver, va_list ap) 98 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 99 // Set receiver if non-null (method is not static) 100 if (receiver != nullptr) { 101 Append(receiver); 102 } 103 for (size_t i = 1; i < shorty_len_; ++i) { 104 switch (shorty_[i]) { 105 case 'Z': 106 case 'B': 107 case 'C': 108 case 'S': 109 case 'I': 110 Append(va_arg(ap, jint)); 111 break; 112 case 'F': 113 AppendFloat(va_arg(ap, jdouble)); 114 break; 115 case 'L': 116 Append(soa.Decode<mirror::Object*>(va_arg(ap, jobject))); 117 break; 118 case 'D': 119 AppendDouble(va_arg(ap, jdouble)); 120 break; 121 case 'J': 122 AppendWide(va_arg(ap, jlong)); 123 break; 124#ifndef NDEBUG 125 default: 126 LOG(FATAL) << "Unexpected shorty character: " << shorty_[i]; 127#endif 128 } 129 } 130 } 131 132 void BuildArgArrayFromJValues(const ScopedObjectAccessAlreadyRunnable& soa, 133 mirror::Object* receiver, jvalue* args) 134 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 135 // Set receiver if non-null (method is not static) 136 if (receiver != nullptr) { 137 Append(receiver); 138 } 139 for (size_t i = 1, args_offset = 0; i < shorty_len_; ++i, ++args_offset) { 140 switch (shorty_[i]) { 141 case 'Z': 142 Append(args[args_offset].z); 143 break; 144 case 'B': 145 Append(args[args_offset].b); 146 break; 147 case 'C': 148 Append(args[args_offset].c); 149 break; 150 case 'S': 151 Append(args[args_offset].s); 152 break; 153 case 'I': 154 case 'F': 155 Append(args[args_offset].i); 156 break; 157 case 'L': 158 Append(soa.Decode<mirror::Object*>(args[args_offset].l)); 159 break; 160 case 'D': 161 case 'J': 162 AppendWide(args[args_offset].j); 163 break; 164#ifndef NDEBUG 165 default: 166 LOG(FATAL) << "Unexpected shorty character: " << shorty_[i]; 167#endif 168 } 169 } 170 } 171 172 void BuildArgArrayFromFrame(ShadowFrame* shadow_frame, uint32_t arg_offset) 173 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 174 // Set receiver if non-null (method is not static) 175 size_t cur_arg = arg_offset; 176 if (!shadow_frame->GetMethod()->IsStatic()) { 177 Append(shadow_frame->GetVReg(cur_arg)); 178 cur_arg++; 179 } 180 for (size_t i = 1; i < shorty_len_; ++i) { 181 switch (shorty_[i]) { 182 case 'Z': 183 case 'B': 184 case 'C': 185 case 'S': 186 case 'I': 187 case 'F': 188 case 'L': 189 Append(shadow_frame->GetVReg(cur_arg)); 190 cur_arg++; 191 break; 192 case 'D': 193 case 'J': 194 AppendWide(shadow_frame->GetVRegLong(cur_arg)); 195 cur_arg++; 196 cur_arg++; 197 break; 198#ifndef NDEBUG 199 default: 200 LOG(FATAL) << "Unexpected shorty character: " << shorty_[i]; 201#endif 202 } 203 } 204 } 205 206 static void ThrowIllegalPrimitiveArgumentException(const char* expected, 207 const char* found_descriptor) 208 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 209 ThrowIllegalArgumentException( 210 StringPrintf("Invalid primitive conversion from %s to %s", expected, 211 PrettyDescriptor(found_descriptor).c_str()).c_str()); 212 } 213 214 bool BuildArgArrayFromObjectArray(mirror::Object* receiver, 215 mirror::ObjectArray<mirror::Object>* args, 216 Handle<mirror::ArtMethod> h_m) 217 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 218 const DexFile::TypeList* classes = h_m->GetParameterTypeList(); 219 // Set receiver if non-null (method is not static) 220 if (receiver != nullptr) { 221 Append(receiver); 222 } 223 for (size_t i = 1, args_offset = 0; i < shorty_len_; ++i, ++args_offset) { 224 mirror::Object* arg = args->Get(args_offset); 225 if (((shorty_[i] == 'L') && (arg != nullptr)) || ((arg == nullptr && shorty_[i] != 'L'))) { 226 mirror::Class* dst_class = 227 h_m->GetClassFromTypeIndex(classes->GetTypeItem(args_offset).type_idx_, true); 228 if (UNLIKELY(arg == nullptr || !arg->InstanceOf(dst_class))) { 229 ThrowIllegalArgumentException( 230 StringPrintf("method %s argument %zd has type %s, got %s", 231 PrettyMethod(h_m.Get(), false).c_str(), 232 args_offset + 1, // Humans don't count from 0. 233 PrettyDescriptor(dst_class).c_str(), 234 PrettyTypeOf(arg).c_str()).c_str()); 235 return false; 236 } 237 } 238 239#define DO_FIRST_ARG(match_descriptor, get_fn, append) { \ 240 if (LIKELY(arg != nullptr && arg->GetClass<>()->DescriptorEquals(match_descriptor))) { \ 241 mirror::ArtField* primitive_field = arg->GetClass()->GetIFields()->Get(0); \ 242 append(primitive_field-> get_fn(arg)); 243 244#define DO_ARG(match_descriptor, get_fn, append) \ 245 } else if (LIKELY(arg != nullptr && \ 246 arg->GetClass<>()->DescriptorEquals(match_descriptor))) { \ 247 mirror::ArtField* primitive_field = arg->GetClass()->GetIFields()->Get(0); \ 248 append(primitive_field-> get_fn(arg)); 249 250#define DO_FAIL(expected) \ 251 } else { \ 252 if (arg->GetClass<>()->IsPrimitive()) { \ 253 std::string temp; \ 254 ThrowIllegalPrimitiveArgumentException(expected, \ 255 arg->GetClass<>()->GetDescriptor(&temp)); \ 256 } else { \ 257 ThrowIllegalArgumentException(\ 258 StringPrintf("method %s argument %zd has type %s, got %s", \ 259 PrettyMethod(h_m.Get(), false).c_str(), \ 260 args_offset + 1, \ 261 expected, \ 262 PrettyTypeOf(arg).c_str()).c_str()); \ 263 } \ 264 return false; \ 265 } } 266 267 switch (shorty_[i]) { 268 case 'L': 269 Append(arg); 270 break; 271 case 'Z': 272 DO_FIRST_ARG("Ljava/lang/Boolean;", GetBoolean, Append) 273 DO_FAIL("boolean") 274 break; 275 case 'B': 276 DO_FIRST_ARG("Ljava/lang/Byte;", GetByte, Append) 277 DO_FAIL("byte") 278 break; 279 case 'C': 280 DO_FIRST_ARG("Ljava/lang/Character;", GetChar, Append) 281 DO_FAIL("char") 282 break; 283 case 'S': 284 DO_FIRST_ARG("Ljava/lang/Short;", GetShort, Append) 285 DO_ARG("Ljava/lang/Byte;", GetByte, Append) 286 DO_FAIL("short") 287 break; 288 case 'I': 289 DO_FIRST_ARG("Ljava/lang/Integer;", GetInt, Append) 290 DO_ARG("Ljava/lang/Character;", GetChar, Append) 291 DO_ARG("Ljava/lang/Short;", GetShort, Append) 292 DO_ARG("Ljava/lang/Byte;", GetByte, Append) 293 DO_FAIL("int") 294 break; 295 case 'J': 296 DO_FIRST_ARG("Ljava/lang/Long;", GetLong, AppendWide) 297 DO_ARG("Ljava/lang/Integer;", GetInt, AppendWide) 298 DO_ARG("Ljava/lang/Character;", GetChar, AppendWide) 299 DO_ARG("Ljava/lang/Short;", GetShort, AppendWide) 300 DO_ARG("Ljava/lang/Byte;", GetByte, AppendWide) 301 DO_FAIL("long") 302 break; 303 case 'F': 304 DO_FIRST_ARG("Ljava/lang/Float;", GetFloat, AppendFloat) 305 DO_ARG("Ljava/lang/Long;", GetLong, AppendFloat) 306 DO_ARG("Ljava/lang/Integer;", GetInt, AppendFloat) 307 DO_ARG("Ljava/lang/Character;", GetChar, AppendFloat) 308 DO_ARG("Ljava/lang/Short;", GetShort, AppendFloat) 309 DO_ARG("Ljava/lang/Byte;", GetByte, AppendFloat) 310 DO_FAIL("float") 311 break; 312 case 'D': 313 DO_FIRST_ARG("Ljava/lang/Double;", GetDouble, AppendDouble) 314 DO_ARG("Ljava/lang/Float;", GetFloat, AppendDouble) 315 DO_ARG("Ljava/lang/Long;", GetLong, AppendDouble) 316 DO_ARG("Ljava/lang/Integer;", GetInt, AppendDouble) 317 DO_ARG("Ljava/lang/Character;", GetChar, AppendDouble) 318 DO_ARG("Ljava/lang/Short;", GetShort, AppendDouble) 319 DO_ARG("Ljava/lang/Byte;", GetByte, AppendDouble) 320 DO_FAIL("double") 321 break; 322#ifndef NDEBUG 323 default: 324 LOG(FATAL) << "Unexpected shorty character: " << shorty_[i]; 325 UNREACHABLE(); 326#endif 327 } 328#undef DO_FIRST_ARG 329#undef DO_ARG 330#undef DO_FAIL 331 } 332 return true; 333 } 334 335 private: 336 enum { kSmallArgArraySize = 16 }; 337 const char* const shorty_; 338 const uint32_t shorty_len_; 339 uint32_t num_bytes_; 340 uint32_t* arg_array_; 341 uint32_t small_arg_array_[kSmallArgArraySize]; 342 std::unique_ptr<uint32_t[]> large_arg_array_; 343}; 344 345static void CheckMethodArguments(JavaVMExt* vm, mirror::ArtMethod* m, uint32_t* args) 346 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 347 const DexFile::TypeList* params = m->GetParameterTypeList(); 348 if (params == nullptr) { 349 return; // No arguments so nothing to check. 350 } 351 uint32_t offset = 0; 352 uint32_t num_params = params->Size(); 353 size_t error_count = 0; 354 if (!m->IsStatic()) { 355 offset = 1; 356 } 357 // TODO: If args contain object references, it may cause problems. 358 Thread* self = Thread::Current(); 359 StackHandleScope<1> hs(self); 360 Handle<mirror::ArtMethod> h_m(hs.NewHandle(m)); 361 for (uint32_t i = 0; i < num_params; i++) { 362 uint16_t type_idx = params->GetTypeItem(i).type_idx_; 363 mirror::Class* param_type = h_m->GetClassFromTypeIndex(type_idx, true); 364 if (param_type == nullptr) { 365 CHECK(self->IsExceptionPending()); 366 LOG(ERROR) << "Internal error: unresolvable type for argument type in JNI invoke: " 367 << h_m->GetTypeDescriptorFromTypeIdx(type_idx) << "\n" 368 << self->GetException()->Dump(); 369 self->ClearException(); 370 ++error_count; 371 } else if (!param_type->IsPrimitive()) { 372 // TODO: There is a compaction bug here since GetClassFromTypeIdx can cause thread suspension, 373 // this is a hard to fix problem since the args can contain Object*, we need to save and 374 // restore them by using a visitor similar to the ones used in the trampoline entrypoints. 375 mirror::Object* argument = 376 (reinterpret_cast<StackReference<mirror::Object>*>(&args[i + offset]))->AsMirrorPtr(); 377 if (argument != nullptr && !argument->InstanceOf(param_type)) { 378 LOG(ERROR) << "JNI ERROR (app bug): attempt to pass an instance of " 379 << PrettyTypeOf(argument) << " as argument " << (i + 1) 380 << " to " << PrettyMethod(h_m.Get()); 381 ++error_count; 382 } 383 } else if (param_type->IsPrimitiveLong() || param_type->IsPrimitiveDouble()) { 384 offset++; 385 } else { 386 int32_t arg = static_cast<int32_t>(args[i + offset]); 387 if (param_type->IsPrimitiveBoolean()) { 388 if (arg != JNI_TRUE && arg != JNI_FALSE) { 389 LOG(ERROR) << "JNI ERROR (app bug): expected jboolean (0/1) but got value of " 390 << arg << " as argument " << (i + 1) << " to " << PrettyMethod(h_m.Get()); 391 ++error_count; 392 } 393 } else if (param_type->IsPrimitiveByte()) { 394 if (arg < -128 || arg > 127) { 395 LOG(ERROR) << "JNI ERROR (app bug): expected jbyte but got value of " 396 << arg << " as argument " << (i + 1) << " to " << PrettyMethod(h_m.Get()); 397 ++error_count; 398 } 399 } else if (param_type->IsPrimitiveChar()) { 400 if (args[i + offset] > 0xFFFF) { 401 LOG(ERROR) << "JNI ERROR (app bug): expected jchar but got value of " 402 << arg << " as argument " << (i + 1) << " to " << PrettyMethod(h_m.Get()); 403 ++error_count; 404 } 405 } else if (param_type->IsPrimitiveShort()) { 406 if (arg < -32768 || arg > 0x7FFF) { 407 LOG(ERROR) << "JNI ERROR (app bug): expected jshort but got value of " 408 << arg << " as argument " << (i + 1) << " to " << PrettyMethod(h_m.Get()); 409 ++error_count; 410 } 411 } 412 } 413 } 414 if (UNLIKELY(error_count > 0)) { 415 // TODO: pass the JNI function name (such as "CallVoidMethodV") through so we can call JniAbort 416 // with an argument. 417 vm->JniAbortF(nullptr, "bad arguments passed to %s (see above for details)", 418 PrettyMethod(h_m.Get()).c_str()); 419 } 420} 421 422static mirror::ArtMethod* FindVirtualMethod(mirror::Object* receiver, 423 mirror::ArtMethod* method) 424 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 425 return receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(method); 426} 427 428 429static void InvokeWithArgArray(const ScopedObjectAccessAlreadyRunnable& soa, 430 mirror::ArtMethod* method, ArgArray* arg_array, JValue* result, 431 const char* shorty) 432 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 433 uint32_t* args = arg_array->GetArray(); 434 if (UNLIKELY(soa.Env()->check_jni)) { 435 CheckMethodArguments(soa.Vm(), method, args); 436 } 437 method->Invoke(soa.Self(), args, arg_array->GetNumBytes(), result, shorty); 438} 439 440JValue InvokeWithVarArgs(const ScopedObjectAccessAlreadyRunnable& soa, jobject obj, jmethodID mid, 441 va_list args) 442 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 443 // We want to make sure that the stack is not within a small distance from the 444 // protected region in case we are calling into a leaf function whose stack 445 // check has been elided. 446 if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEnd())) { 447 ThrowStackOverflowError(soa.Self()); 448 return JValue(); 449 } 450 451 mirror::ArtMethod* method = soa.DecodeMethod(mid); 452 mirror::Object* receiver = method->IsStatic() ? nullptr : soa.Decode<mirror::Object*>(obj); 453 uint32_t shorty_len = 0; 454 const char* shorty = method->GetShorty(&shorty_len); 455 JValue result; 456 ArgArray arg_array(shorty, shorty_len); 457 arg_array.BuildArgArrayFromVarArgs(soa, receiver, args); 458 InvokeWithArgArray(soa, method, &arg_array, &result, shorty); 459 return result; 460} 461 462JValue InvokeWithJValues(const ScopedObjectAccessAlreadyRunnable& soa, mirror::Object* receiver, 463 jmethodID mid, jvalue* args) { 464 // We want to make sure that the stack is not within a small distance from the 465 // protected region in case we are calling into a leaf function whose stack 466 // check has been elided. 467 if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEnd())) { 468 ThrowStackOverflowError(soa.Self()); 469 return JValue(); 470 } 471 472 mirror::ArtMethod* method = soa.DecodeMethod(mid); 473 uint32_t shorty_len = 0; 474 const char* shorty = method->GetShorty(&shorty_len); 475 JValue result; 476 ArgArray arg_array(shorty, shorty_len); 477 arg_array.BuildArgArrayFromJValues(soa, receiver, args); 478 InvokeWithArgArray(soa, method, &arg_array, &result, shorty); 479 return result; 480} 481 482JValue InvokeVirtualOrInterfaceWithJValues(const ScopedObjectAccessAlreadyRunnable& soa, 483 mirror::Object* receiver, jmethodID mid, jvalue* args) { 484 // We want to make sure that the stack is not within a small distance from the 485 // protected region in case we are calling into a leaf function whose stack 486 // check has been elided. 487 if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEnd())) { 488 ThrowStackOverflowError(soa.Self()); 489 return JValue(); 490 } 491 492 mirror::ArtMethod* method = FindVirtualMethod(receiver, soa.DecodeMethod(mid)); 493 uint32_t shorty_len = 0; 494 const char* shorty = method->GetShorty(&shorty_len); 495 JValue result; 496 ArgArray arg_array(shorty, shorty_len); 497 arg_array.BuildArgArrayFromJValues(soa, receiver, args); 498 InvokeWithArgArray(soa, method, &arg_array, &result, shorty); 499 return result; 500} 501 502JValue InvokeVirtualOrInterfaceWithVarArgs(const ScopedObjectAccessAlreadyRunnable& soa, 503 jobject obj, jmethodID mid, va_list args) { 504 // We want to make sure that the stack is not within a small distance from the 505 // protected region in case we are calling into a leaf function whose stack 506 // check has been elided. 507 if (UNLIKELY(__builtin_frame_address(0) < soa.Self()->GetStackEnd())) { 508 ThrowStackOverflowError(soa.Self()); 509 return JValue(); 510 } 511 512 mirror::Object* receiver = soa.Decode<mirror::Object*>(obj); 513 mirror::ArtMethod* method = FindVirtualMethod(receiver, soa.DecodeMethod(mid)); 514 uint32_t shorty_len = 0; 515 const char* shorty = method->GetShorty(&shorty_len); 516 JValue result; 517 ArgArray arg_array(shorty, shorty_len); 518 arg_array.BuildArgArrayFromVarArgs(soa, receiver, args); 519 InvokeWithArgArray(soa, method, &arg_array, &result, shorty); 520 return result; 521} 522 523void InvokeWithShadowFrame(Thread* self, ShadowFrame* shadow_frame, uint16_t arg_offset, 524 JValue* result) { 525 // We want to make sure that the stack is not within a small distance from the 526 // protected region in case we are calling into a leaf function whose stack 527 // check has been elided. 528 if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEnd())) { 529 ThrowStackOverflowError(self); 530 return; 531 } 532 uint32_t shorty_len; 533 const char* shorty = shadow_frame->GetMethod()->GetShorty(&shorty_len); 534 ArgArray arg_array(shorty, shorty_len); 535 arg_array.BuildArgArrayFromFrame(shadow_frame, arg_offset); 536 shadow_frame->GetMethod()->Invoke(self, arg_array.GetArray(), arg_array.GetNumBytes(), result, 537 shorty); 538} 539 540jobject InvokeMethod(const ScopedObjectAccessAlreadyRunnable& soa, jobject javaMethod, 541 jobject javaReceiver, jobject javaArgs, bool accessible) { 542 // We want to make sure that the stack is not within a small distance from the 543 // protected region in case we are calling into a leaf function whose stack 544 // check has been elided. 545 if (UNLIKELY(__builtin_frame_address(0) < 546 soa.Self()->GetStackEndForInterpreter(true))) { 547 ThrowStackOverflowError(soa.Self()); 548 return nullptr; 549 } 550 551 mirror::ArtMethod* m = mirror::ArtMethod::FromReflectedMethod(soa, javaMethod); 552 553 mirror::Class* declaring_class = m->GetDeclaringClass(); 554 if (UNLIKELY(!declaring_class->IsInitialized())) { 555 StackHandleScope<1> hs(soa.Self()); 556 Handle<mirror::Class> h_class(hs.NewHandle(declaring_class)); 557 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(soa.Self(), h_class, true, true)) { 558 return nullptr; 559 } 560 declaring_class = h_class.Get(); 561 } 562 563 mirror::Object* receiver = nullptr; 564 if (!m->IsStatic()) { 565 // Check that the receiver is non-null and an instance of the field's declaring class. 566 receiver = soa.Decode<mirror::Object*>(javaReceiver); 567 if (!VerifyObjectIsClass(receiver, declaring_class)) { 568 return nullptr; 569 } 570 571 // Find the actual implementation of the virtual method. 572 m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(m); 573 } 574 575 // Get our arrays of arguments and their types, and check they're the same size. 576 mirror::ObjectArray<mirror::Object>* objects = 577 soa.Decode<mirror::ObjectArray<mirror::Object>*>(javaArgs); 578 const DexFile::TypeList* classes = m->GetParameterTypeList(); 579 uint32_t classes_size = (classes == nullptr) ? 0 : classes->Size(); 580 uint32_t arg_count = (objects != nullptr) ? objects->GetLength() : 0; 581 if (arg_count != classes_size) { 582 ThrowIllegalArgumentException(StringPrintf("Wrong number of arguments; expected %d, got %d", 583 classes_size, arg_count).c_str()); 584 return nullptr; 585 } 586 587 // If method is not set to be accessible, verify it can be accessed by the caller. 588 mirror::Class* calling_class = nullptr; 589 if (!accessible && !VerifyAccess(soa.Self(), receiver, declaring_class, m->GetAccessFlags(), 590 &calling_class, 2)) { 591 ThrowIllegalAccessException( 592 StringPrintf("Class %s cannot access %s method %s of class %s", 593 calling_class == nullptr ? "null" : PrettyClass(calling_class).c_str(), 594 PrettyJavaAccessFlags(m->GetAccessFlags()).c_str(), 595 PrettyMethod(m).c_str(), 596 m->GetDeclaringClass() == nullptr ? "null" : 597 PrettyClass(m->GetDeclaringClass()).c_str()).c_str()); 598 return nullptr; 599 } 600 601 // Invoke the method. 602 JValue result; 603 uint32_t shorty_len = 0; 604 const char* shorty = m->GetShorty(&shorty_len); 605 ArgArray arg_array(shorty, shorty_len); 606 StackHandleScope<1> hs(soa.Self()); 607 Handle<mirror::ArtMethod> h_m(hs.NewHandle(m)); 608 if (!arg_array.BuildArgArrayFromObjectArray(receiver, objects, h_m)) { 609 CHECK(soa.Self()->IsExceptionPending()); 610 return nullptr; 611 } 612 613 InvokeWithArgArray(soa, m, &arg_array, &result, shorty); 614 615 // Wrap any exception with "Ljava/lang/reflect/InvocationTargetException;" and return early. 616 if (soa.Self()->IsExceptionPending()) { 617 jthrowable th = soa.Env()->ExceptionOccurred(); 618 soa.Env()->ExceptionClear(); 619 jclass exception_class = soa.Env()->FindClass("java/lang/reflect/InvocationTargetException"); 620 jmethodID mid = soa.Env()->GetMethodID(exception_class, "<init>", "(Ljava/lang/Throwable;)V"); 621 jobject exception_instance = soa.Env()->NewObject(exception_class, mid, th); 622 soa.Env()->Throw(reinterpret_cast<jthrowable>(exception_instance)); 623 return nullptr; 624 } 625 626 // Box if necessary and return. 627 return soa.AddLocalReference<jobject>(BoxPrimitive(Primitive::GetType(shorty[0]), result)); 628} 629 630mirror::Object* BoxPrimitive(Primitive::Type src_class, const JValue& value) { 631 if (src_class == Primitive::kPrimNot) { 632 return value.GetL(); 633 } 634 if (src_class == Primitive::kPrimVoid) { 635 // There's no such thing as a void field, and void methods invoked via reflection return null. 636 return nullptr; 637 } 638 639 jmethodID m = nullptr; 640 const char* shorty; 641 switch (src_class) { 642 case Primitive::kPrimBoolean: 643 m = WellKnownClasses::java_lang_Boolean_valueOf; 644 shorty = "LZ"; 645 break; 646 case Primitive::kPrimByte: 647 m = WellKnownClasses::java_lang_Byte_valueOf; 648 shorty = "LB"; 649 break; 650 case Primitive::kPrimChar: 651 m = WellKnownClasses::java_lang_Character_valueOf; 652 shorty = "LC"; 653 break; 654 case Primitive::kPrimDouble: 655 m = WellKnownClasses::java_lang_Double_valueOf; 656 shorty = "LD"; 657 break; 658 case Primitive::kPrimFloat: 659 m = WellKnownClasses::java_lang_Float_valueOf; 660 shorty = "LF"; 661 break; 662 case Primitive::kPrimInt: 663 m = WellKnownClasses::java_lang_Integer_valueOf; 664 shorty = "LI"; 665 break; 666 case Primitive::kPrimLong: 667 m = WellKnownClasses::java_lang_Long_valueOf; 668 shorty = "LJ"; 669 break; 670 case Primitive::kPrimShort: 671 m = WellKnownClasses::java_lang_Short_valueOf; 672 shorty = "LS"; 673 break; 674 default: 675 LOG(FATAL) << static_cast<int>(src_class); 676 shorty = nullptr; 677 } 678 679 ScopedObjectAccessUnchecked soa(Thread::Current()); 680 DCHECK_EQ(soa.Self()->GetState(), kRunnable); 681 682 ArgArray arg_array(shorty, 2); 683 JValue result; 684 if (src_class == Primitive::kPrimDouble || src_class == Primitive::kPrimLong) { 685 arg_array.AppendWide(value.GetJ()); 686 } else { 687 arg_array.Append(value.GetI()); 688 } 689 690 soa.DecodeMethod(m)->Invoke(soa.Self(), arg_array.GetArray(), arg_array.GetNumBytes(), 691 &result, shorty); 692 return result.GetL(); 693} 694 695static std::string UnboxingFailureKind(mirror::ArtField* f) 696 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 697 if (f != nullptr) { 698 return "field " + PrettyField(f, false); 699 } 700 return "result"; 701} 702 703static bool UnboxPrimitive(mirror::Object* o, 704 mirror::Class* dst_class, mirror::ArtField* f, 705 JValue* unboxed_value) 706 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 707 bool unbox_for_result = (f == nullptr); 708 if (!dst_class->IsPrimitive()) { 709 if (UNLIKELY(o != nullptr && !o->InstanceOf(dst_class))) { 710 if (!unbox_for_result) { 711 ThrowIllegalArgumentException(StringPrintf("%s has type %s, got %s", 712 UnboxingFailureKind(f).c_str(), 713 PrettyDescriptor(dst_class).c_str(), 714 PrettyTypeOf(o).c_str()).c_str()); 715 } else { 716 ThrowClassCastException(StringPrintf("Couldn't convert result of type %s to %s", 717 PrettyTypeOf(o).c_str(), 718 PrettyDescriptor(dst_class).c_str()).c_str()); 719 } 720 return false; 721 } 722 unboxed_value->SetL(o); 723 return true; 724 } 725 if (UNLIKELY(dst_class->GetPrimitiveType() == Primitive::kPrimVoid)) { 726 ThrowIllegalArgumentException(StringPrintf("Can't unbox %s to void", 727 UnboxingFailureKind(f).c_str()).c_str()); 728 return false; 729 } 730 if (UNLIKELY(o == nullptr)) { 731 if (!unbox_for_result) { 732 ThrowIllegalArgumentException(StringPrintf("%s has type %s, got null", 733 UnboxingFailureKind(f).c_str(), 734 PrettyDescriptor(dst_class).c_str()).c_str()); 735 } else { 736 ThrowNullPointerException(StringPrintf("Expected to unbox a '%s' primitive type but was returned null", 737 PrettyDescriptor(dst_class).c_str()).c_str()); 738 } 739 return false; 740 } 741 742 JValue boxed_value; 743 mirror::Class* klass = o->GetClass(); 744 mirror::Class* src_class = nullptr; 745 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 746 mirror::ArtField* primitive_field = o->GetClass()->GetIFields()->Get(0); 747 if (klass->DescriptorEquals("Ljava/lang/Boolean;")) { 748 src_class = class_linker->FindPrimitiveClass('Z'); 749 boxed_value.SetZ(primitive_field->GetBoolean(o)); 750 } else if (klass->DescriptorEquals("Ljava/lang/Byte;")) { 751 src_class = class_linker->FindPrimitiveClass('B'); 752 boxed_value.SetB(primitive_field->GetByte(o)); 753 } else if (klass->DescriptorEquals("Ljava/lang/Character;")) { 754 src_class = class_linker->FindPrimitiveClass('C'); 755 boxed_value.SetC(primitive_field->GetChar(o)); 756 } else if (klass->DescriptorEquals("Ljava/lang/Float;")) { 757 src_class = class_linker->FindPrimitiveClass('F'); 758 boxed_value.SetF(primitive_field->GetFloat(o)); 759 } else if (klass->DescriptorEquals("Ljava/lang/Double;")) { 760 src_class = class_linker->FindPrimitiveClass('D'); 761 boxed_value.SetD(primitive_field->GetDouble(o)); 762 } else if (klass->DescriptorEquals("Ljava/lang/Integer;")) { 763 src_class = class_linker->FindPrimitiveClass('I'); 764 boxed_value.SetI(primitive_field->GetInt(o)); 765 } else if (klass->DescriptorEquals("Ljava/lang/Long;")) { 766 src_class = class_linker->FindPrimitiveClass('J'); 767 boxed_value.SetJ(primitive_field->GetLong(o)); 768 } else if (klass->DescriptorEquals("Ljava/lang/Short;")) { 769 src_class = class_linker->FindPrimitiveClass('S'); 770 boxed_value.SetS(primitive_field->GetShort(o)); 771 } else { 772 std::string temp; 773 ThrowIllegalArgumentException( 774 StringPrintf("%s has type %s, got %s", UnboxingFailureKind(f).c_str(), 775 PrettyDescriptor(dst_class).c_str(), 776 PrettyDescriptor(o->GetClass()->GetDescriptor(&temp)).c_str()).c_str()); 777 return false; 778 } 779 780 return ConvertPrimitiveValue(unbox_for_result, 781 src_class->GetPrimitiveType(), dst_class->GetPrimitiveType(), 782 boxed_value, unboxed_value); 783} 784 785bool UnboxPrimitiveForField(mirror::Object* o, mirror::Class* dst_class, mirror::ArtField* f, 786 JValue* unboxed_value) { 787 DCHECK(f != nullptr); 788 return UnboxPrimitive(o, dst_class, f, unboxed_value); 789} 790 791bool UnboxPrimitiveForResult(mirror::Object* o, 792 mirror::Class* dst_class, JValue* unboxed_value) { 793 return UnboxPrimitive(o, dst_class, nullptr, unboxed_value); 794} 795 796bool VerifyAccess(Thread* self, mirror::Object* obj, mirror::Class* declaring_class, 797 uint32_t access_flags, mirror::Class** calling_class, size_t num_frames) { 798 if ((access_flags & kAccPublic) != 0) { 799 return true; 800 } 801 NthCallerVisitor visitor(self, num_frames); 802 visitor.WalkStack(); 803 if (UNLIKELY(visitor.caller == nullptr)) { 804 // The caller is an attached native thread. 805 return false; 806 } 807 mirror::Class* caller_class = visitor.caller->GetDeclaringClass(); 808 if (caller_class == declaring_class) { 809 return true; 810 } 811 ScopedAssertNoThreadSuspension sants(self, "verify-access"); 812 *calling_class = caller_class; 813 if ((access_flags & kAccPrivate) != 0) { 814 return false; 815 } 816 if ((access_flags & kAccProtected) != 0) { 817 if (obj != nullptr && !obj->InstanceOf(caller_class) && 818 !declaring_class->IsInSamePackage(caller_class)) { 819 return false; 820 } else if (declaring_class->IsAssignableFrom(caller_class)) { 821 return true; 822 } 823 } 824 return declaring_class->IsInSamePackage(caller_class); 825} 826 827void InvalidReceiverError(mirror::Object* o, mirror::Class* c) { 828 std::string expected_class_name(PrettyDescriptor(c)); 829 std::string actual_class_name(PrettyTypeOf(o)); 830 ThrowIllegalArgumentException(StringPrintf("Expected receiver of type %s, but got %s", 831 expected_class_name.c_str(), 832 actual_class_name.c_str()).c_str()); 833} 834 835} // namespace art 836