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 "class.h" 18 19 #include "art_field-inl.h" 20 #include "art_method-inl.h" 21 #include "class_linker-inl.h" 22 #include "class_loader.h" 23 #include "class-inl.h" 24 #include "dex_cache.h" 25 #include "dex_file-inl.h" 26 #include "gc/accounting/card_table-inl.h" 27 #include "handle_scope-inl.h" 28 #include "method.h" 29 #include "object_array-inl.h" 30 #include "object-inl.h" 31 #include "runtime.h" 32 #include "thread.h" 33 #include "throwable.h" 34 #include "utils.h" 35 #include "well_known_classes.h" 36 37 namespace art { 38 namespace mirror { 39 40 GcRoot<Class> Class::java_lang_Class_; 41 42 void Class::SetClassClass(Class* java_lang_Class) { 43 CHECK(java_lang_Class_.IsNull()) 44 << java_lang_Class_.Read() 45 << " " << java_lang_Class; 46 CHECK(java_lang_Class != nullptr); 47 java_lang_Class_ = GcRoot<Class>(java_lang_Class); 48 } 49 50 void Class::ResetClass() { 51 CHECK(!java_lang_Class_.IsNull()); 52 java_lang_Class_ = GcRoot<Class>(nullptr); 53 } 54 55 void Class::VisitRoots(RootVisitor* visitor) { 56 java_lang_Class_.VisitRootIfNonNull(visitor, RootInfo(kRootStickyClass)); 57 } 58 59 void Class::SetStatus(Handle<Class> h_this, Status new_status, Thread* self) { 60 Status old_status = h_this->GetStatus(); 61 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 62 bool class_linker_initialized = class_linker != nullptr && class_linker->IsInitialized(); 63 if (LIKELY(class_linker_initialized)) { 64 if (UNLIKELY(new_status <= old_status && new_status != kStatusError && 65 new_status != kStatusRetired)) { 66 LOG(FATAL) << "Unexpected change back of class status for " << PrettyClass(h_this.Get()) 67 << " " << old_status << " -> " << new_status; 68 } 69 if (new_status >= kStatusResolved || old_status >= kStatusResolved) { 70 // When classes are being resolved the resolution code should hold the lock. 71 CHECK_EQ(h_this->GetLockOwnerThreadId(), self->GetThreadId()) 72 << "Attempt to change status of class while not holding its lock: " 73 << PrettyClass(h_this.Get()) << " " << old_status << " -> " << new_status; 74 } 75 } 76 if (UNLIKELY(new_status == kStatusError)) { 77 CHECK_NE(h_this->GetStatus(), kStatusError) 78 << "Attempt to set as erroneous an already erroneous class " 79 << PrettyClass(h_this.Get()); 80 81 // Stash current exception. 82 StackHandleScope<1> hs(self); 83 Handle<mirror::Throwable> old_exception(hs.NewHandle(self->GetException())); 84 CHECK(old_exception.Get() != nullptr); 85 Class* eiie_class; 86 // Do't attempt to use FindClass if we have an OOM error since this can try to do more 87 // allocations and may cause infinite loops. 88 bool throw_eiie = (old_exception.Get() == nullptr); 89 if (!throw_eiie) { 90 std::string temp; 91 const char* old_exception_descriptor = old_exception->GetClass()->GetDescriptor(&temp); 92 throw_eiie = (strcmp(old_exception_descriptor, "Ljava/lang/OutOfMemoryError;") != 0); 93 } 94 if (throw_eiie) { 95 // Clear exception to call FindSystemClass. 96 self->ClearException(); 97 eiie_class = Runtime::Current()->GetClassLinker()->FindSystemClass( 98 self, "Ljava/lang/ExceptionInInitializerError;"); 99 CHECK(!self->IsExceptionPending()); 100 // Only verification errors, not initialization problems, should set a verify error. 101 // This is to ensure that ThrowEarlierClassFailure will throw NoClassDefFoundError in that 102 // case. 103 Class* exception_class = old_exception->GetClass(); 104 if (!eiie_class->IsAssignableFrom(exception_class)) { 105 h_this->SetVerifyErrorClass(exception_class); 106 } 107 } 108 109 // Restore exception. 110 self->SetException(old_exception.Get()); 111 } 112 static_assert(sizeof(Status) == sizeof(uint32_t), "Size of status not equal to uint32"); 113 if (Runtime::Current()->IsActiveTransaction()) { 114 h_this->SetField32Volatile<true>(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status); 115 } else { 116 h_this->SetField32Volatile<false>(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status); 117 } 118 119 if (!class_linker_initialized) { 120 // When the class linker is being initialized its single threaded and by definition there can be 121 // no waiters. During initialization classes may appear temporary but won't be retired as their 122 // size was statically computed. 123 } else { 124 // Classes that are being resolved or initialized need to notify waiters that the class status 125 // changed. See ClassLinker::EnsureResolved and ClassLinker::WaitForInitializeClass. 126 if (h_this->IsTemp()) { 127 // Class is a temporary one, ensure that waiters for resolution get notified of retirement 128 // so that they can grab the new version of the class from the class linker's table. 129 CHECK_LT(new_status, kStatusResolved) << PrettyDescriptor(h_this.Get()); 130 if (new_status == kStatusRetired || new_status == kStatusError) { 131 h_this->NotifyAll(self); 132 } 133 } else { 134 CHECK_NE(new_status, kStatusRetired); 135 if (old_status >= kStatusResolved || new_status >= kStatusResolved) { 136 h_this->NotifyAll(self); 137 } 138 } 139 } 140 } 141 142 void Class::SetDexCache(DexCache* new_dex_cache) { 143 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache); 144 SetDexCacheStrings(new_dex_cache != nullptr ? new_dex_cache->GetStrings() : nullptr); 145 } 146 147 void Class::SetClassSize(uint32_t new_class_size) { 148 if (kIsDebugBuild && new_class_size < GetClassSize()) { 149 DumpClass(LOG(INTERNAL_FATAL), kDumpClassFullDetail); 150 LOG(INTERNAL_FATAL) << new_class_size << " vs " << GetClassSize(); 151 LOG(FATAL) << " class=" << PrettyTypeOf(this); 152 } 153 // Not called within a transaction. 154 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size); 155 } 156 157 // Return the class' name. The exact format is bizarre, but it's the specified behavior for 158 // Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int" 159 // but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than 160 // slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness. 161 String* Class::ComputeName(Handle<Class> h_this) { 162 String* name = h_this->GetName(); 163 if (name != nullptr) { 164 return name; 165 } 166 std::string temp; 167 const char* descriptor = h_this->GetDescriptor(&temp); 168 Thread* self = Thread::Current(); 169 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) { 170 // The descriptor indicates that this is the class for 171 // a primitive type; special-case the return value. 172 const char* c_name = nullptr; 173 switch (descriptor[0]) { 174 case 'Z': c_name = "boolean"; break; 175 case 'B': c_name = "byte"; break; 176 case 'C': c_name = "char"; break; 177 case 'S': c_name = "short"; break; 178 case 'I': c_name = "int"; break; 179 case 'J': c_name = "long"; break; 180 case 'F': c_name = "float"; break; 181 case 'D': c_name = "double"; break; 182 case 'V': c_name = "void"; break; 183 default: 184 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]); 185 } 186 name = String::AllocFromModifiedUtf8(self, c_name); 187 } else { 188 // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package 189 // components. 190 name = String::AllocFromModifiedUtf8(self, DescriptorToDot(descriptor).c_str()); 191 } 192 h_this->SetName(name); 193 return name; 194 } 195 196 void Class::DumpClass(std::ostream& os, int flags) { 197 if ((flags & kDumpClassFullDetail) == 0) { 198 os << PrettyClass(this); 199 if ((flags & kDumpClassClassLoader) != 0) { 200 os << ' ' << GetClassLoader(); 201 } 202 if ((flags & kDumpClassInitialized) != 0) { 203 os << ' ' << GetStatus(); 204 } 205 os << "\n"; 206 return; 207 } 208 209 Thread* const self = Thread::Current(); 210 StackHandleScope<2> hs(self); 211 Handle<mirror::Class> h_this(hs.NewHandle(this)); 212 Handle<mirror::Class> h_super(hs.NewHandle(GetSuperClass())); 213 auto image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize(); 214 215 std::string temp; 216 os << "----- " << (IsInterface() ? "interface" : "class") << " " 217 << "'" << GetDescriptor(&temp) << "' cl=" << GetClassLoader() << " -----\n", 218 os << " objectSize=" << SizeOf() << " " 219 << "(" << (h_super.Get() != nullptr ? h_super->SizeOf() : -1) << " from super)\n", 220 os << StringPrintf(" access=0x%04x.%04x\n", 221 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask); 222 if (h_super.Get() != nullptr) { 223 os << " super='" << PrettyClass(h_super.Get()) << "' (cl=" << h_super->GetClassLoader() 224 << ")\n"; 225 } 226 if (IsArrayClass()) { 227 os << " componentType=" << PrettyClass(GetComponentType()) << "\n"; 228 } 229 const size_t num_direct_interfaces = NumDirectInterfaces(); 230 if (num_direct_interfaces > 0) { 231 os << " interfaces (" << num_direct_interfaces << "):\n"; 232 for (size_t i = 0; i < num_direct_interfaces; ++i) { 233 Class* interface = GetDirectInterface(self, h_this, i); 234 if (interface == nullptr) { 235 os << StringPrintf(" %2zd: nullptr!\n", i); 236 } else { 237 const ClassLoader* cl = interface->GetClassLoader(); 238 os << StringPrintf(" %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl); 239 } 240 } 241 } 242 if (!IsLoaded()) { 243 os << " class not yet loaded"; 244 } else { 245 // After this point, this may have moved due to GetDirectInterface. 246 os << " vtable (" << h_this->NumVirtualMethods() << " entries, " 247 << (h_super.Get() != nullptr ? h_super->NumVirtualMethods() : 0) << " in super):\n"; 248 for (size_t i = 0; i < NumVirtualMethods(); ++i) { 249 os << StringPrintf(" %2zd: %s\n", i, PrettyMethod( 250 h_this->GetVirtualMethodDuringLinking(i, image_pointer_size)).c_str()); 251 } 252 os << " direct methods (" << h_this->NumDirectMethods() << " entries):\n"; 253 for (size_t i = 0; i < h_this->NumDirectMethods(); ++i) { 254 os << StringPrintf(" %2zd: %s\n", i, PrettyMethod( 255 h_this->GetDirectMethod(i, image_pointer_size)).c_str()); 256 } 257 if (h_this->NumStaticFields() > 0) { 258 os << " static fields (" << h_this->NumStaticFields() << " entries):\n"; 259 if (h_this->IsResolved() || h_this->IsErroneous()) { 260 for (size_t i = 0; i < h_this->NumStaticFields(); ++i) { 261 os << StringPrintf(" %2zd: %s\n", i, PrettyField(h_this->GetStaticField(i)).c_str()); 262 } 263 } else { 264 os << " <not yet available>"; 265 } 266 } 267 if (h_this->NumInstanceFields() > 0) { 268 os << " instance fields (" << h_this->NumInstanceFields() << " entries):\n"; 269 if (h_this->IsResolved() || h_this->IsErroneous()) { 270 for (size_t i = 0; i < h_this->NumInstanceFields(); ++i) { 271 os << StringPrintf(" %2zd: %s\n", i, PrettyField(h_this->GetInstanceField(i)).c_str()); 272 } 273 } else { 274 os << " <not yet available>"; 275 } 276 } 277 } 278 } 279 280 void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) { 281 if (kIsDebugBuild && new_reference_offsets != kClassWalkSuper) { 282 // Sanity check that the number of bits set in the reference offset bitmap 283 // agrees with the number of references 284 uint32_t count = 0; 285 for (Class* c = this; c != nullptr; c = c->GetSuperClass()) { 286 count += c->NumReferenceInstanceFieldsDuringLinking(); 287 } 288 // +1 for the Class in Object. 289 CHECK_EQ(static_cast<uint32_t>(POPCOUNT(new_reference_offsets)) + 1, count); 290 } 291 // Not called within a transaction. 292 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_), 293 new_reference_offsets); 294 } 295 296 bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) { 297 size_t i = 0; 298 size_t min_length = std::min(descriptor1.size(), descriptor2.size()); 299 while (i < min_length && descriptor1[i] == descriptor2[i]) { 300 ++i; 301 } 302 if (descriptor1.find('/', i) != StringPiece::npos || 303 descriptor2.find('/', i) != StringPiece::npos) { 304 return false; 305 } else { 306 return true; 307 } 308 } 309 310 bool Class::IsInSamePackage(Class* that) { 311 Class* klass1 = this; 312 Class* klass2 = that; 313 if (klass1 == klass2) { 314 return true; 315 } 316 // Class loaders must match. 317 if (klass1->GetClassLoader() != klass2->GetClassLoader()) { 318 return false; 319 } 320 // Arrays are in the same package when their element classes are. 321 while (klass1->IsArrayClass()) { 322 klass1 = klass1->GetComponentType(); 323 } 324 while (klass2->IsArrayClass()) { 325 klass2 = klass2->GetComponentType(); 326 } 327 // trivial check again for array types 328 if (klass1 == klass2) { 329 return true; 330 } 331 // Compare the package part of the descriptor string. 332 std::string temp1, temp2; 333 return IsInSamePackage(klass1->GetDescriptor(&temp1), klass2->GetDescriptor(&temp2)); 334 } 335 336 bool Class::IsThrowableClass() { 337 return WellKnownClasses::ToClass(WellKnownClasses::java_lang_Throwable)->IsAssignableFrom(this); 338 } 339 340 void Class::SetClassLoader(ClassLoader* new_class_loader) { 341 if (Runtime::Current()->IsActiveTransaction()) { 342 SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader); 343 } else { 344 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader); 345 } 346 } 347 348 ArtMethod* Class::FindInterfaceMethod(const StringPiece& name, const StringPiece& signature, 349 size_t pointer_size) { 350 // Check the current class before checking the interfaces. 351 ArtMethod* method = FindDeclaredVirtualMethod(name, signature, pointer_size); 352 if (method != nullptr) { 353 return method; 354 } 355 356 int32_t iftable_count = GetIfTableCount(); 357 IfTable* iftable = GetIfTable(); 358 for (int32_t i = 0; i < iftable_count; ++i) { 359 method = iftable->GetInterface(i)->FindDeclaredVirtualMethod(name, signature, pointer_size); 360 if (method != nullptr) { 361 return method; 362 } 363 } 364 return nullptr; 365 } 366 367 ArtMethod* Class::FindInterfaceMethod(const StringPiece& name, const Signature& signature, 368 size_t pointer_size) { 369 // Check the current class before checking the interfaces. 370 ArtMethod* method = FindDeclaredVirtualMethod(name, signature, pointer_size); 371 if (method != nullptr) { 372 return method; 373 } 374 375 int32_t iftable_count = GetIfTableCount(); 376 IfTable* iftable = GetIfTable(); 377 for (int32_t i = 0; i < iftable_count; ++i) { 378 method = iftable->GetInterface(i)->FindDeclaredVirtualMethod(name, signature, pointer_size); 379 if (method != nullptr) { 380 return method; 381 } 382 } 383 return nullptr; 384 } 385 386 ArtMethod* Class::FindInterfaceMethod(const DexCache* dex_cache, uint32_t dex_method_idx, 387 size_t pointer_size) { 388 // Check the current class before checking the interfaces. 389 ArtMethod* method = FindDeclaredVirtualMethod(dex_cache, dex_method_idx, pointer_size); 390 if (method != nullptr) { 391 return method; 392 } 393 394 int32_t iftable_count = GetIfTableCount(); 395 IfTable* iftable = GetIfTable(); 396 for (int32_t i = 0; i < iftable_count; ++i) { 397 method = iftable->GetInterface(i)->FindDeclaredVirtualMethod( 398 dex_cache, dex_method_idx, pointer_size); 399 if (method != nullptr) { 400 return method; 401 } 402 } 403 return nullptr; 404 } 405 406 ArtMethod* Class::FindDeclaredDirectMethod(const StringPiece& name, const StringPiece& signature, 407 size_t pointer_size) { 408 for (auto& method : GetDirectMethods(pointer_size)) { 409 if (name == method.GetName() && method.GetSignature() == signature) { 410 return &method; 411 } 412 } 413 return nullptr; 414 } 415 416 ArtMethod* Class::FindDeclaredDirectMethod(const StringPiece& name, const Signature& signature, 417 size_t pointer_size) { 418 for (auto& method : GetDirectMethods(pointer_size)) { 419 if (name == method.GetName() && signature == method.GetSignature()) { 420 return &method; 421 } 422 } 423 return nullptr; 424 } 425 426 ArtMethod* Class::FindDeclaredDirectMethod(const DexCache* dex_cache, uint32_t dex_method_idx, 427 size_t pointer_size) { 428 if (GetDexCache() == dex_cache) { 429 for (auto& method : GetDirectMethods(pointer_size)) { 430 if (method.GetDexMethodIndex() == dex_method_idx) { 431 return &method; 432 } 433 } 434 } 435 return nullptr; 436 } 437 438 ArtMethod* Class::FindDirectMethod(const StringPiece& name, const StringPiece& signature, 439 size_t pointer_size) { 440 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) { 441 ArtMethod* method = klass->FindDeclaredDirectMethod(name, signature, pointer_size); 442 if (method != nullptr) { 443 return method; 444 } 445 } 446 return nullptr; 447 } 448 449 ArtMethod* Class::FindDirectMethod(const StringPiece& name, const Signature& signature, 450 size_t pointer_size) { 451 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) { 452 ArtMethod* method = klass->FindDeclaredDirectMethod(name, signature, pointer_size); 453 if (method != nullptr) { 454 return method; 455 } 456 } 457 return nullptr; 458 } 459 460 ArtMethod* Class::FindDirectMethod( 461 const DexCache* dex_cache, uint32_t dex_method_idx, size_t pointer_size) { 462 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) { 463 ArtMethod* method = klass->FindDeclaredDirectMethod(dex_cache, dex_method_idx, pointer_size); 464 if (method != nullptr) { 465 return method; 466 } 467 } 468 return nullptr; 469 } 470 471 ArtMethod* Class::FindDeclaredVirtualMethod(const StringPiece& name, const StringPiece& signature, 472 size_t pointer_size) { 473 for (auto& method : GetVirtualMethods(pointer_size)) { 474 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size); 475 if (name == np_method->GetName() && np_method->GetSignature() == signature) { 476 return &method; 477 } 478 } 479 return nullptr; 480 } 481 482 ArtMethod* Class::FindDeclaredVirtualMethod(const StringPiece& name, const Signature& signature, 483 size_t pointer_size) { 484 for (auto& method : GetVirtualMethods(pointer_size)) { 485 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size); 486 if (name == np_method->GetName() && signature == np_method->GetSignature()) { 487 return &method; 488 } 489 } 490 return nullptr; 491 } 492 493 ArtMethod* Class::FindDeclaredVirtualMethod(const DexCache* dex_cache, uint32_t dex_method_idx, 494 size_t pointer_size) { 495 if (GetDexCache() == dex_cache) { 496 for (auto& method : GetVirtualMethods(pointer_size)) { 497 // A miranda method may have a different DexCache and is always created by linking, 498 // never *declared* in the class. 499 if (method.GetDexMethodIndex() == dex_method_idx && !method.IsMiranda()) { 500 return &method; 501 } 502 } 503 } 504 return nullptr; 505 } 506 507 ArtMethod* Class::FindVirtualMethod( 508 const StringPiece& name, const StringPiece& signature, size_t pointer_size) { 509 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) { 510 ArtMethod* method = klass->FindDeclaredVirtualMethod(name, signature, pointer_size); 511 if (method != nullptr) { 512 return method; 513 } 514 } 515 return nullptr; 516 } 517 518 ArtMethod* Class::FindVirtualMethod( 519 const StringPiece& name, const Signature& signature, size_t pointer_size) { 520 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) { 521 ArtMethod* method = klass->FindDeclaredVirtualMethod(name, signature, pointer_size); 522 if (method != nullptr) { 523 return method; 524 } 525 } 526 return nullptr; 527 } 528 529 ArtMethod* Class::FindVirtualMethod( 530 const DexCache* dex_cache, uint32_t dex_method_idx, size_t pointer_size) { 531 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) { 532 ArtMethod* method = klass->FindDeclaredVirtualMethod(dex_cache, dex_method_idx, pointer_size); 533 if (method != nullptr) { 534 return method; 535 } 536 } 537 return nullptr; 538 } 539 540 ArtMethod* Class::FindClassInitializer(size_t pointer_size) { 541 for (ArtMethod& method : GetDirectMethods(pointer_size)) { 542 if (method.IsClassInitializer()) { 543 DCHECK_STREQ(method.GetName(), "<clinit>"); 544 DCHECK_STREQ(method.GetSignature().ToString().c_str(), "()V"); 545 return &method; 546 } 547 } 548 return nullptr; 549 } 550 551 ArtField* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) { 552 // Is the field in this class? 553 // Interfaces are not relevant because they can't contain instance fields. 554 for (size_t i = 0; i < NumInstanceFields(); ++i) { 555 ArtField* f = GetInstanceField(i); 556 if (name == f->GetName() && type == f->GetTypeDescriptor()) { 557 return f; 558 } 559 } 560 return nullptr; 561 } 562 563 ArtField* Class::FindDeclaredInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) { 564 if (GetDexCache() == dex_cache) { 565 for (size_t i = 0; i < NumInstanceFields(); ++i) { 566 ArtField* f = GetInstanceField(i); 567 if (f->GetDexFieldIndex() == dex_field_idx) { 568 return f; 569 } 570 } 571 } 572 return nullptr; 573 } 574 575 ArtField* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) { 576 // Is the field in this class, or any of its superclasses? 577 // Interfaces are not relevant because they can't contain instance fields. 578 for (Class* c = this; c != nullptr; c = c->GetSuperClass()) { 579 ArtField* f = c->FindDeclaredInstanceField(name, type); 580 if (f != nullptr) { 581 return f; 582 } 583 } 584 return nullptr; 585 } 586 587 ArtField* Class::FindInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) { 588 // Is the field in this class, or any of its superclasses? 589 // Interfaces are not relevant because they can't contain instance fields. 590 for (Class* c = this; c != nullptr; c = c->GetSuperClass()) { 591 ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx); 592 if (f != nullptr) { 593 return f; 594 } 595 } 596 return nullptr; 597 } 598 599 ArtField* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) { 600 DCHECK(type != nullptr); 601 for (size_t i = 0; i < NumStaticFields(); ++i) { 602 ArtField* f = GetStaticField(i); 603 if (name == f->GetName() && type == f->GetTypeDescriptor()) { 604 return f; 605 } 606 } 607 return nullptr; 608 } 609 610 ArtField* Class::FindDeclaredStaticField(const DexCache* dex_cache, uint32_t dex_field_idx) { 611 if (dex_cache == GetDexCache()) { 612 for (size_t i = 0; i < NumStaticFields(); ++i) { 613 ArtField* f = GetStaticField(i); 614 if (f->GetDexFieldIndex() == dex_field_idx) { 615 return f; 616 } 617 } 618 } 619 return nullptr; 620 } 621 622 ArtField* Class::FindStaticField(Thread* self, Handle<Class> klass, const StringPiece& name, 623 const StringPiece& type) { 624 // Is the field in this class (or its interfaces), or any of its 625 // superclasses (or their interfaces)? 626 for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) { 627 // Is the field in this class? 628 ArtField* f = k->FindDeclaredStaticField(name, type); 629 if (f != nullptr) { 630 return f; 631 } 632 // Wrap k incase it moves during GetDirectInterface. 633 StackHandleScope<1> hs(self); 634 HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k)); 635 // Is this field in any of this class' interfaces? 636 for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) { 637 StackHandleScope<1> hs2(self); 638 Handle<mirror::Class> interface(hs2.NewHandle(GetDirectInterface(self, h_k, i))); 639 f = FindStaticField(self, interface, name, type); 640 if (f != nullptr) { 641 return f; 642 } 643 } 644 } 645 return nullptr; 646 } 647 648 ArtField* Class::FindStaticField(Thread* self, Handle<Class> klass, const DexCache* dex_cache, 649 uint32_t dex_field_idx) { 650 for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) { 651 // Is the field in this class? 652 ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx); 653 if (f != nullptr) { 654 return f; 655 } 656 // Wrap k incase it moves during GetDirectInterface. 657 StackHandleScope<1> hs(self); 658 HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k)); 659 // Is this field in any of this class' interfaces? 660 for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) { 661 StackHandleScope<1> hs2(self); 662 Handle<mirror::Class> interface(hs2.NewHandle(GetDirectInterface(self, h_k, i))); 663 f = FindStaticField(self, interface, dex_cache, dex_field_idx); 664 if (f != nullptr) { 665 return f; 666 } 667 } 668 } 669 return nullptr; 670 } 671 672 ArtField* Class::FindField(Thread* self, Handle<Class> klass, const StringPiece& name, 673 const StringPiece& type) { 674 // Find a field using the JLS field resolution order 675 for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) { 676 // Is the field in this class? 677 ArtField* f = k->FindDeclaredInstanceField(name, type); 678 if (f != nullptr) { 679 return f; 680 } 681 f = k->FindDeclaredStaticField(name, type); 682 if (f != nullptr) { 683 return f; 684 } 685 // Is this field in any of this class' interfaces? 686 StackHandleScope<1> hs(self); 687 HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k)); 688 for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) { 689 StackHandleScope<1> hs2(self); 690 Handle<mirror::Class> interface(hs2.NewHandle(GetDirectInterface(self, h_k, i))); 691 f = interface->FindStaticField(self, interface, name, type); 692 if (f != nullptr) { 693 return f; 694 } 695 } 696 } 697 return nullptr; 698 } 699 700 void Class::SetPreverifiedFlagOnAllMethods(size_t pointer_size) { 701 DCHECK(IsVerified()); 702 for (auto& m : GetDirectMethods(pointer_size)) { 703 if (!m.IsNative() && !m.IsAbstract()) { 704 m.SetPreverified(); 705 } 706 } 707 for (auto& m : GetVirtualMethods(pointer_size)) { 708 if (!m.IsNative() && !m.IsAbstract()) { 709 m.SetPreverified(); 710 } 711 } 712 } 713 714 const char* Class::GetDescriptor(std::string* storage) { 715 if (IsPrimitive()) { 716 return Primitive::Descriptor(GetPrimitiveType()); 717 } else if (IsArrayClass()) { 718 return GetArrayDescriptor(storage); 719 } else if (IsProxyClass()) { 720 *storage = Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this); 721 return storage->c_str(); 722 } else { 723 const DexFile& dex_file = GetDexFile(); 724 const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_); 725 return dex_file.GetTypeDescriptor(type_id); 726 } 727 } 728 729 const char* Class::GetArrayDescriptor(std::string* storage) { 730 std::string temp; 731 const char* elem_desc = GetComponentType()->GetDescriptor(&temp); 732 *storage = "["; 733 *storage += elem_desc; 734 return storage->c_str(); 735 } 736 737 const DexFile::ClassDef* Class::GetClassDef() { 738 uint16_t class_def_idx = GetDexClassDefIndex(); 739 if (class_def_idx == DexFile::kDexNoIndex16) { 740 return nullptr; 741 } 742 return &GetDexFile().GetClassDef(class_def_idx); 743 } 744 745 uint16_t Class::GetDirectInterfaceTypeIdx(uint32_t idx) { 746 DCHECK(!IsPrimitive()); 747 DCHECK(!IsArrayClass()); 748 return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_; 749 } 750 751 mirror::Class* Class::GetDirectInterface(Thread* self, Handle<mirror::Class> klass, 752 uint32_t idx) { 753 DCHECK(klass.Get() != nullptr); 754 DCHECK(!klass->IsPrimitive()); 755 if (klass->IsArrayClass()) { 756 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 757 if (idx == 0) { 758 return class_linker->FindSystemClass(self, "Ljava/lang/Cloneable;"); 759 } else { 760 DCHECK_EQ(1U, idx); 761 return class_linker->FindSystemClass(self, "Ljava/io/Serializable;"); 762 } 763 } else if (klass->IsProxyClass()) { 764 mirror::ObjectArray<mirror::Class>* interfaces = klass.Get()->GetInterfaces(); 765 DCHECK(interfaces != nullptr); 766 return interfaces->Get(idx); 767 } else { 768 uint16_t type_idx = klass->GetDirectInterfaceTypeIdx(idx); 769 mirror::Class* interface = klass->GetDexCache()->GetResolvedType(type_idx); 770 if (interface == nullptr) { 771 interface = Runtime::Current()->GetClassLinker()->ResolveType(klass->GetDexFile(), type_idx, 772 klass.Get()); 773 CHECK(interface != nullptr || self->IsExceptionPending()); 774 } 775 return interface; 776 } 777 } 778 779 const char* Class::GetSourceFile() { 780 const DexFile& dex_file = GetDexFile(); 781 const DexFile::ClassDef* dex_class_def = GetClassDef(); 782 if (dex_class_def == nullptr) { 783 // Generated classes have no class def. 784 return nullptr; 785 } 786 return dex_file.GetSourceFile(*dex_class_def); 787 } 788 789 std::string Class::GetLocation() { 790 mirror::DexCache* dex_cache = GetDexCache(); 791 if (dex_cache != nullptr && !IsProxyClass()) { 792 return dex_cache->GetLocation()->ToModifiedUtf8(); 793 } 794 // Arrays and proxies are generated and have no corresponding dex file location. 795 return "generated class"; 796 } 797 798 const DexFile::TypeList* Class::GetInterfaceTypeList() { 799 const DexFile::ClassDef* class_def = GetClassDef(); 800 if (class_def == nullptr) { 801 return nullptr; 802 } 803 return GetDexFile().GetInterfacesList(*class_def); 804 } 805 806 void Class::PopulateEmbeddedImtAndVTable(ArtMethod* const (&methods)[kImtSize], 807 size_t pointer_size) { 808 for (size_t i = 0; i < kImtSize; i++) { 809 auto method = methods[i]; 810 DCHECK(method != nullptr); 811 SetEmbeddedImTableEntry(i, method, pointer_size); 812 } 813 PointerArray* table = GetVTableDuringLinking(); 814 CHECK(table != nullptr) << PrettyClass(this); 815 const size_t table_length = table->GetLength(); 816 SetEmbeddedVTableLength(table_length); 817 for (size_t i = 0; i < table_length; i++) { 818 SetEmbeddedVTableEntry(i, table->GetElementPtrSize<ArtMethod*>(i, pointer_size), pointer_size); 819 } 820 // Keep java.lang.Object class's vtable around for since it's easier 821 // to be reused by array classes during their linking. 822 if (!IsObjectClass()) { 823 SetVTable(nullptr); 824 } 825 } 826 827 // The pre-fence visitor for Class::CopyOf(). 828 class CopyClassVisitor { 829 public: 830 explicit CopyClassVisitor(Thread* self, Handle<mirror::Class>* orig, size_t new_length, 831 size_t copy_bytes, ArtMethod* const (&imt)[mirror::Class::kImtSize], 832 size_t pointer_size) 833 : self_(self), orig_(orig), new_length_(new_length), 834 copy_bytes_(copy_bytes), imt_(imt), pointer_size_(pointer_size) { 835 } 836 837 void operator()(mirror::Object* obj, size_t usable_size ATTRIBUTE_UNUSED) const 838 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 839 StackHandleScope<1> hs(self_); 840 Handle<mirror::Class> h_new_class_obj(hs.NewHandle(obj->AsClass())); 841 mirror::Object::CopyObject(self_, h_new_class_obj.Get(), orig_->Get(), copy_bytes_); 842 mirror::Class::SetStatus(h_new_class_obj, Class::kStatusResolving, self_); 843 h_new_class_obj->PopulateEmbeddedImtAndVTable(imt_, pointer_size_); 844 h_new_class_obj->SetClassSize(new_length_); 845 } 846 847 private: 848 Thread* const self_; 849 Handle<mirror::Class>* const orig_; 850 const size_t new_length_; 851 const size_t copy_bytes_; 852 ArtMethod* const (&imt_)[mirror::Class::kImtSize]; 853 const size_t pointer_size_; 854 DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor); 855 }; 856 857 Class* Class::CopyOf(Thread* self, int32_t new_length, 858 ArtMethod* const (&imt)[mirror::Class::kImtSize], size_t pointer_size) { 859 DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class))); 860 // We may get copied by a compacting GC. 861 StackHandleScope<1> hs(self); 862 Handle<mirror::Class> h_this(hs.NewHandle(this)); 863 gc::Heap* heap = Runtime::Current()->GetHeap(); 864 // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf() 865 // to skip copying the tail part that we will overwrite here. 866 CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class), imt, pointer_size); 867 mirror::Object* new_class = kMovingClasses ? 868 heap->AllocObject<true>(self, java_lang_Class_.Read(), new_length, visitor) : 869 heap->AllocNonMovableObject<true>(self, java_lang_Class_.Read(), new_length, visitor); 870 if (UNLIKELY(new_class == nullptr)) { 871 self->AssertPendingOOMException(); 872 return nullptr; 873 } 874 return new_class->AsClass(); 875 } 876 877 bool Class::ProxyDescriptorEquals(const char* match) { 878 DCHECK(IsProxyClass()); 879 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this) == match; 880 } 881 882 // TODO: Move this to java_lang_Class.cc? 883 ArtMethod* Class::GetDeclaredConstructor( 884 Thread* self, Handle<mirror::ObjectArray<mirror::Class>> args) { 885 for (auto& m : GetDirectMethods(sizeof(void*))) { 886 // Skip <clinit> which is a static constructor, as well as non constructors. 887 if (m.IsStatic() || !m.IsConstructor()) { 888 continue; 889 } 890 // May cause thread suspension and exceptions. 891 if (m.GetInterfaceMethodIfProxy(sizeof(void*))->EqualParameters(args)) { 892 return &m; 893 } 894 if (UNLIKELY(self->IsExceptionPending())) { 895 return nullptr; 896 } 897 } 898 return nullptr; 899 } 900 901 uint32_t Class::Depth() { 902 uint32_t depth = 0; 903 for (Class* klass = this; klass->GetSuperClass() != nullptr; klass = klass->GetSuperClass()) { 904 depth++; 905 } 906 return depth; 907 } 908 909 } // namespace mirror 910 } // namespace art 911