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