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