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