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