reflection.cc revision ab9a0dbf3b63d517da5278b8298e6cd316e09f68
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.h" 18 19#include "class_linker.h" 20#include "common_throws.h" 21#include "dex_file-inl.h" 22#include "jni_internal.h" 23#include "method_helper-inl.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(const ScopedObjectAccessAlreadyRunnable& soa, 222 mirror::Object* receiver, 223 mirror::ObjectArray<mirror::Object>* args, MethodHelper& mh) 224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 225 const DexFile::TypeList* classes = mh.GetMethod()->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 mh.GetClassFromTypeIdx(classes->GetTypeItem(args_offset).type_idx_); 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(mh.GetMethod(), 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(mh.GetMethod(), 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#endif 333 } 334#undef DO_FIRST_ARG 335#undef DO_ARG 336#undef DO_FAIL 337 } 338 return true; 339 } 340 341 private: 342 enum { kSmallArgArraySize = 16 }; 343 const char* const shorty_; 344 const uint32_t shorty_len_; 345 uint32_t num_bytes_; 346 uint32_t* arg_array_; 347 uint32_t small_arg_array_[kSmallArgArraySize]; 348 std::unique_ptr<uint32_t[]> large_arg_array_; 349}; 350 351static void CheckMethodArguments(mirror::ArtMethod* m, uint32_t* args) 352 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 353 const DexFile::TypeList* params = m->GetParameterTypeList(); 354 if (params == nullptr) { 355 return; // No arguments so nothing to check. 356 } 357 uint32_t offset = 0; 358 uint32_t num_params = params->Size(); 359 size_t error_count = 0; 360 if (!m->IsStatic()) { 361 offset = 1; 362 } 363 // TODO: If args contain object references, it may cause problems 364 Thread* self = Thread::Current(); 365 StackHandleScope<1> hs(self); 366 Handle<mirror::ArtMethod> h_m(hs.NewHandle(m)); 367 MethodHelper mh(h_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 = mh.GetClassFromTypeIdx(type_idx); 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: check primitives are in range. 380 // TODO: There is a compaction bug here since GetClassFromTypeIdx can cause thread suspension, 381 // this is a hard to fix problem since the args can contain Object*, we need to save and 382 // restore them by using a visitor similar to the ones used in the trampoline entrypoints. 383 mirror::Object* argument = reinterpret_cast<mirror::Object*>(args[i + offset]); 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 } 393 } 394 if (error_count > 0) { 395 // TODO: pass the JNI function name (such as "CallVoidMethodV") through so we can call JniAbort 396 // with an argument. 397 JniAbortF(nullptr, "bad arguments passed to %s (see above for details)", 398 PrettyMethod(h_m.Get()).c_str()); 399 } 400} 401 402static mirror::ArtMethod* FindVirtualMethod(mirror::Object* receiver, 403 mirror::ArtMethod* method) 404 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 405 return receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(method); 406} 407 408 409static void InvokeWithArgArray(const ScopedObjectAccessAlreadyRunnable& soa, 410 mirror::ArtMethod* method, ArgArray* arg_array, JValue* result, 411 const char* shorty) 412 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 413 uint32_t* args = arg_array->GetArray(); 414 if (UNLIKELY(soa.Env()->check_jni)) { 415 CheckMethodArguments(method, args); 416 } 417 method->Invoke(soa.Self(), args, arg_array->GetNumBytes(), result, shorty); 418} 419 420JValue InvokeWithVarArgs(const ScopedObjectAccessAlreadyRunnable& soa, jobject obj, jmethodID mid, 421 va_list args) 422 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 423 mirror::ArtMethod* method = soa.DecodeMethod(mid); 424 mirror::Object* receiver = method->IsStatic() ? nullptr : soa.Decode<mirror::Object*>(obj); 425 uint32_t shorty_len = 0; 426 const char* shorty = method->GetShorty(&shorty_len); 427 JValue result; 428 ArgArray arg_array(shorty, shorty_len); 429 arg_array.BuildArgArrayFromVarArgs(soa, receiver, args); 430 InvokeWithArgArray(soa, method, &arg_array, &result, shorty); 431 return result; 432} 433 434JValue InvokeWithJValues(const ScopedObjectAccessAlreadyRunnable& soa, mirror::Object* receiver, 435 jmethodID mid, jvalue* args) { 436 mirror::ArtMethod* method = soa.DecodeMethod(mid); 437 uint32_t shorty_len = 0; 438 const char* shorty = method->GetShorty(&shorty_len); 439 JValue result; 440 ArgArray arg_array(shorty, shorty_len); 441 arg_array.BuildArgArrayFromJValues(soa, receiver, args); 442 InvokeWithArgArray(soa, method, &arg_array, &result, shorty); 443 return result; 444} 445 446JValue InvokeVirtualOrInterfaceWithJValues(const ScopedObjectAccessAlreadyRunnable& soa, 447 mirror::Object* receiver, jmethodID mid, jvalue* args) { 448 mirror::ArtMethod* method = FindVirtualMethod(receiver, soa.DecodeMethod(mid)); 449 uint32_t shorty_len = 0; 450 const char* shorty = method->GetShorty(&shorty_len); 451 JValue result; 452 ArgArray arg_array(shorty, shorty_len); 453 arg_array.BuildArgArrayFromJValues(soa, receiver, args); 454 InvokeWithArgArray(soa, method, &arg_array, &result, shorty); 455 return result; 456} 457 458JValue InvokeVirtualOrInterfaceWithVarArgs(const ScopedObjectAccessAlreadyRunnable& soa, 459 jobject obj, jmethodID mid, va_list args) { 460 mirror::Object* receiver = soa.Decode<mirror::Object*>(obj); 461 mirror::ArtMethod* method = FindVirtualMethod(receiver, soa.DecodeMethod(mid)); 462 uint32_t shorty_len = 0; 463 const char* shorty = method->GetShorty(&shorty_len); 464 JValue result; 465 ArgArray arg_array(shorty, shorty_len); 466 arg_array.BuildArgArrayFromVarArgs(soa, receiver, args); 467 InvokeWithArgArray(soa, method, &arg_array, &result, shorty); 468 return result; 469} 470 471void InvokeWithShadowFrame(Thread* self, ShadowFrame* shadow_frame, uint16_t arg_offset, 472 MethodHelper& mh, JValue* result) { 473 ArgArray arg_array(mh.GetShorty(), mh.GetShortyLength()); 474 arg_array.BuildArgArrayFromFrame(shadow_frame, arg_offset); 475 shadow_frame->GetMethod()->Invoke(self, arg_array.GetArray(), arg_array.GetNumBytes(), result, 476 mh.GetShorty()); 477} 478 479jobject InvokeMethod(const ScopedObjectAccessAlreadyRunnable& soa, jobject javaMethod, 480 jobject javaReceiver, jobject javaArgs, bool accessible) { 481 mirror::ArtMethod* m = mirror::ArtMethod::FromReflectedMethod(soa, javaMethod); 482 483 mirror::Class* declaring_class = m->GetDeclaringClass(); 484 if (UNLIKELY(!declaring_class->IsInitialized())) { 485 StackHandleScope<1> hs(soa.Self()); 486 Handle<mirror::Class> h_class(hs.NewHandle(declaring_class)); 487 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(h_class, true, true)) { 488 return nullptr; 489 } 490 declaring_class = h_class.Get(); 491 } 492 493 mirror::Object* receiver = nullptr; 494 if (!m->IsStatic()) { 495 // Check that the receiver is non-null and an instance of the field's declaring class. 496 receiver = soa.Decode<mirror::Object*>(javaReceiver); 497 if (!VerifyObjectIsClass(receiver, declaring_class)) { 498 return NULL; 499 } 500 501 // Find the actual implementation of the virtual method. 502 m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(m); 503 } 504 505 // Get our arrays of arguments and their types, and check they're the same size. 506 mirror::ObjectArray<mirror::Object>* objects = 507 soa.Decode<mirror::ObjectArray<mirror::Object>*>(javaArgs); 508 const DexFile::TypeList* classes = m->GetParameterTypeList(); 509 uint32_t classes_size = (classes == nullptr) ? 0 : classes->Size(); 510 uint32_t arg_count = (objects != nullptr) ? objects->GetLength() : 0; 511 if (arg_count != classes_size) { 512 ThrowIllegalArgumentException(NULL, 513 StringPrintf("Wrong number of arguments; expected %d, got %d", 514 classes_size, arg_count).c_str()); 515 return NULL; 516 } 517 518 // If method is not set to be accessible, verify it can be accessed by the caller. 519 if (!accessible && !VerifyAccess(receiver, declaring_class, m->GetAccessFlags())) { 520 ThrowIllegalAccessException(nullptr, StringPrintf("Cannot access method: %s", 521 PrettyMethod(m).c_str()).c_str()); 522 return nullptr; 523 } 524 525 // Invoke the method. 526 JValue result; 527 uint32_t shorty_len = 0; 528 const char* shorty = m->GetShorty(&shorty_len); 529 ArgArray arg_array(shorty, shorty_len); 530 StackHandleScope<1> hs(soa.Self()); 531 MethodHelper mh(hs.NewHandle(m)); 532 if (!arg_array.BuildArgArrayFromObjectArray(soa, receiver, objects, mh)) { 533 CHECK(soa.Self()->IsExceptionPending()); 534 return nullptr; 535 } 536 537 InvokeWithArgArray(soa, m, &arg_array, &result, shorty); 538 539 // Wrap any exception with "Ljava/lang/reflect/InvocationTargetException;" and return early. 540 if (soa.Self()->IsExceptionPending()) { 541 jthrowable th = soa.Env()->ExceptionOccurred(); 542 soa.Env()->ExceptionClear(); 543 jclass exception_class = soa.Env()->FindClass("java/lang/reflect/InvocationTargetException"); 544 jmethodID mid = soa.Env()->GetMethodID(exception_class, "<init>", "(Ljava/lang/Throwable;)V"); 545 jobject exception_instance = soa.Env()->NewObject(exception_class, mid, th); 546 soa.Env()->Throw(reinterpret_cast<jthrowable>(exception_instance)); 547 return NULL; 548 } 549 550 // Box if necessary and return. 551 return soa.AddLocalReference<jobject>(BoxPrimitive(mh.GetReturnType()->GetPrimitiveType(), 552 result)); 553} 554 555bool VerifyObjectIsClass(mirror::Object* o, mirror::Class* c) { 556 if (o == NULL) { 557 ThrowNullPointerException(NULL, "null receiver"); 558 return false; 559 } else if (!o->InstanceOf(c)) { 560 std::string expected_class_name(PrettyDescriptor(c)); 561 std::string actual_class_name(PrettyTypeOf(o)); 562 ThrowIllegalArgumentException(NULL, 563 StringPrintf("Expected receiver of type %s, but got %s", 564 expected_class_name.c_str(), 565 actual_class_name.c_str()).c_str()); 566 return false; 567 } 568 return true; 569} 570 571static std::string PrettyDescriptor(Primitive::Type type) { 572 return PrettyDescriptor(Primitive::Descriptor(type)); 573} 574 575bool ConvertPrimitiveValue(const ThrowLocation* throw_location, bool unbox_for_result, 576 Primitive::Type srcType, Primitive::Type dstType, 577 const JValue& src, JValue* dst) { 578 DCHECK(srcType != Primitive::kPrimNot && dstType != Primitive::kPrimNot); 579 if (LIKELY(srcType == dstType)) { 580 dst->SetJ(src.GetJ()); 581 return true; 582 } 583 switch (dstType) { 584 case Primitive::kPrimBoolean: // Fall-through. 585 case Primitive::kPrimChar: // Fall-through. 586 case Primitive::kPrimByte: 587 // Only expect assignment with source and destination of identical type. 588 break; 589 case Primitive::kPrimShort: 590 if (srcType == Primitive::kPrimByte) { 591 dst->SetS(src.GetI()); 592 return true; 593 } 594 break; 595 case Primitive::kPrimInt: 596 if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || 597 srcType == Primitive::kPrimShort) { 598 dst->SetI(src.GetI()); 599 return true; 600 } 601 break; 602 case Primitive::kPrimLong: 603 if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || 604 srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { 605 dst->SetJ(src.GetI()); 606 return true; 607 } 608 break; 609 case Primitive::kPrimFloat: 610 if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || 611 srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { 612 dst->SetF(src.GetI()); 613 return true; 614 } else if (srcType == Primitive::kPrimLong) { 615 dst->SetF(src.GetJ()); 616 return true; 617 } 618 break; 619 case Primitive::kPrimDouble: 620 if (srcType == Primitive::kPrimByte || srcType == Primitive::kPrimChar || 621 srcType == Primitive::kPrimShort || srcType == Primitive::kPrimInt) { 622 dst->SetD(src.GetI()); 623 return true; 624 } else if (srcType == Primitive::kPrimLong) { 625 dst->SetD(src.GetJ()); 626 return true; 627 } else if (srcType == Primitive::kPrimFloat) { 628 dst->SetD(src.GetF()); 629 return true; 630 } 631 break; 632 default: 633 break; 634 } 635 if (!unbox_for_result) { 636 ThrowIllegalArgumentException(throw_location, 637 StringPrintf("Invalid primitive conversion from %s to %s", 638 PrettyDescriptor(srcType).c_str(), 639 PrettyDescriptor(dstType).c_str()).c_str()); 640 } else { 641 ThrowClassCastException(throw_location, 642 StringPrintf("Couldn't convert result of type %s to %s", 643 PrettyDescriptor(srcType).c_str(), 644 PrettyDescriptor(dstType).c_str()).c_str()); 645 } 646 return false; 647} 648 649mirror::Object* BoxPrimitive(Primitive::Type src_class, const JValue& value) { 650 if (src_class == Primitive::kPrimNot) { 651 return value.GetL(); 652 } 653 if (src_class == Primitive::kPrimVoid) { 654 // There's no such thing as a void field, and void methods invoked via reflection return null. 655 return nullptr; 656 } 657 658 jmethodID m = nullptr; 659 const char* shorty; 660 switch (src_class) { 661 case Primitive::kPrimBoolean: 662 m = WellKnownClasses::java_lang_Boolean_valueOf; 663 shorty = "LZ"; 664 break; 665 case Primitive::kPrimByte: 666 m = WellKnownClasses::java_lang_Byte_valueOf; 667 shorty = "LB"; 668 break; 669 case Primitive::kPrimChar: 670 m = WellKnownClasses::java_lang_Character_valueOf; 671 shorty = "LC"; 672 break; 673 case Primitive::kPrimDouble: 674 m = WellKnownClasses::java_lang_Double_valueOf; 675 shorty = "LD"; 676 break; 677 case Primitive::kPrimFloat: 678 m = WellKnownClasses::java_lang_Float_valueOf; 679 shorty = "LF"; 680 break; 681 case Primitive::kPrimInt: 682 m = WellKnownClasses::java_lang_Integer_valueOf; 683 shorty = "LI"; 684 break; 685 case Primitive::kPrimLong: 686 m = WellKnownClasses::java_lang_Long_valueOf; 687 shorty = "LJ"; 688 break; 689 case Primitive::kPrimShort: 690 m = WellKnownClasses::java_lang_Short_valueOf; 691 shorty = "LS"; 692 break; 693 default: 694 LOG(FATAL) << static_cast<int>(src_class); 695 shorty = nullptr; 696 } 697 698 ScopedObjectAccessUnchecked soa(Thread::Current()); 699 DCHECK_EQ(soa.Self()->GetState(), kRunnable); 700 701 ArgArray arg_array(shorty, 2); 702 JValue result; 703 if (src_class == Primitive::kPrimDouble || src_class == Primitive::kPrimLong) { 704 arg_array.AppendWide(value.GetJ()); 705 } else { 706 arg_array.Append(value.GetI()); 707 } 708 709 soa.DecodeMethod(m)->Invoke(soa.Self(), arg_array.GetArray(), arg_array.GetNumBytes(), 710 &result, shorty); 711 return result.GetL(); 712} 713 714static std::string UnboxingFailureKind(mirror::ArtField* f) 715 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 716 if (f != nullptr) { 717 return "field " + PrettyField(f, false); 718 } 719 return "result"; 720} 721 722static bool UnboxPrimitive(const ThrowLocation* throw_location, mirror::Object* o, 723 mirror::Class* dst_class, mirror::ArtField* f, 724 JValue* unboxed_value) 725 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 726 bool unbox_for_result = (f == nullptr); 727 if (!dst_class->IsPrimitive()) { 728 if (UNLIKELY(o != nullptr && !o->InstanceOf(dst_class))) { 729 if (!unbox_for_result) { 730 ThrowIllegalArgumentException(throw_location, 731 StringPrintf("%s has type %s, got %s", 732 UnboxingFailureKind(f).c_str(), 733 PrettyDescriptor(dst_class).c_str(), 734 PrettyTypeOf(o).c_str()).c_str()); 735 } else { 736 ThrowClassCastException(throw_location, 737 StringPrintf("Couldn't convert result of type %s to %s", 738 PrettyTypeOf(o).c_str(), 739 PrettyDescriptor(dst_class).c_str()).c_str()); 740 } 741 return false; 742 } 743 unboxed_value->SetL(o); 744 return true; 745 } 746 if (UNLIKELY(dst_class->GetPrimitiveType() == Primitive::kPrimVoid)) { 747 ThrowIllegalArgumentException(throw_location, 748 StringPrintf("Can't unbox %s to void", 749 UnboxingFailureKind(f).c_str()).c_str()); 750 return false; 751 } 752 if (UNLIKELY(o == nullptr)) { 753 if (!unbox_for_result) { 754 ThrowIllegalArgumentException(throw_location, 755 StringPrintf("%s has type %s, got null", 756 UnboxingFailureKind(f).c_str(), 757 PrettyDescriptor(dst_class).c_str()).c_str()); 758 } else { 759 ThrowNullPointerException(throw_location, 760 StringPrintf("Expected to unbox a '%s' primitive type but was returned null", 761 PrettyDescriptor(dst_class).c_str()).c_str()); 762 } 763 return false; 764 } 765 766 JValue boxed_value; 767 mirror::Class* klass = o->GetClass(); 768 mirror::Class* src_class = nullptr; 769 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 770 mirror::ArtField* primitive_field = o->GetClass()->GetIFields()->Get(0); 771 if (klass->DescriptorEquals("Ljava/lang/Boolean;")) { 772 src_class = class_linker->FindPrimitiveClass('Z'); 773 boxed_value.SetZ(primitive_field->GetBoolean(o)); 774 } else if (klass->DescriptorEquals("Ljava/lang/Byte;")) { 775 src_class = class_linker->FindPrimitiveClass('B'); 776 boxed_value.SetB(primitive_field->GetByte(o)); 777 } else if (klass->DescriptorEquals("Ljava/lang/Character;")) { 778 src_class = class_linker->FindPrimitiveClass('C'); 779 boxed_value.SetC(primitive_field->GetChar(o)); 780 } else if (klass->DescriptorEquals("Ljava/lang/Float;")) { 781 src_class = class_linker->FindPrimitiveClass('F'); 782 boxed_value.SetF(primitive_field->GetFloat(o)); 783 } else if (klass->DescriptorEquals("Ljava/lang/Double;")) { 784 src_class = class_linker->FindPrimitiveClass('D'); 785 boxed_value.SetD(primitive_field->GetDouble(o)); 786 } else if (klass->DescriptorEquals("Ljava/lang/Integer;")) { 787 src_class = class_linker->FindPrimitiveClass('I'); 788 boxed_value.SetI(primitive_field->GetInt(o)); 789 } else if (klass->DescriptorEquals("Ljava/lang/Long;")) { 790 src_class = class_linker->FindPrimitiveClass('J'); 791 boxed_value.SetJ(primitive_field->GetLong(o)); 792 } else if (klass->DescriptorEquals("Ljava/lang/Short;")) { 793 src_class = class_linker->FindPrimitiveClass('S'); 794 boxed_value.SetS(primitive_field->GetShort(o)); 795 } else { 796 std::string temp; 797 ThrowIllegalArgumentException(throw_location, 798 StringPrintf("%s has type %s, got %s", UnboxingFailureKind(f).c_str(), 799 PrettyDescriptor(dst_class).c_str(), 800 PrettyDescriptor(o->GetClass()->GetDescriptor(&temp)).c_str()).c_str()); 801 return false; 802 } 803 804 return ConvertPrimitiveValue(throw_location, unbox_for_result, 805 src_class->GetPrimitiveType(), dst_class->GetPrimitiveType(), 806 boxed_value, unboxed_value); 807} 808 809bool UnboxPrimitiveForField(mirror::Object* o, mirror::Class* dst_class, mirror::ArtField* f, 810 JValue* unboxed_value) { 811 DCHECK(f != nullptr); 812 return UnboxPrimitive(nullptr, o, dst_class, f, unboxed_value); 813} 814 815bool UnboxPrimitiveForResult(const ThrowLocation& throw_location, mirror::Object* o, 816 mirror::Class* dst_class, JValue* unboxed_value) { 817 return UnboxPrimitive(&throw_location, o, dst_class, nullptr, unboxed_value); 818} 819 820bool VerifyAccess(mirror::Object* obj, mirror::Class* declaring_class, uint32_t access_flags) { 821 NthCallerVisitor visitor(Thread::Current(), 2); 822 visitor.WalkStack(); 823 if (UNLIKELY(visitor.caller == nullptr)) { 824 // The caller is an attached native thread. 825 return (access_flags & kAccPublic) != 0; 826 } 827 mirror::Class* caller_class = visitor.caller->GetDeclaringClass(); 828 829 if (((access_flags & kAccPublic) != 0) || (caller_class == declaring_class)) { 830 return true; 831 } 832 if ((access_flags & kAccPrivate) != 0) { 833 return false; 834 } 835 if ((access_flags & kAccProtected) != 0) { 836 if (obj != nullptr && !obj->InstanceOf(caller_class) && 837 !declaring_class->IsInSamePackage(caller_class)) { 838 return false; 839 } else if (declaring_class->IsAssignableFrom(caller_class)) { 840 return true; 841 } 842 } 843 if (!declaring_class->IsInSamePackage(caller_class)) { 844 return false; 845 } 846 return true; 847} 848 849} // namespace art 850