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_linker.h" 18 19 #include <algorithm> 20 #include <deque> 21 #include <iostream> 22 #include <memory> 23 #include <queue> 24 #include <string> 25 #include <tuple> 26 #include <unistd.h> 27 #include <unordered_map> 28 #include <utility> 29 #include <vector> 30 31 #include "art_field-inl.h" 32 #include "art_method-inl.h" 33 #include "base/arena_allocator.h" 34 #include "base/casts.h" 35 #include "base/logging.h" 36 #include "base/scoped_arena_containers.h" 37 #include "base/scoped_flock.h" 38 #include "base/stl_util.h" 39 #include "base/systrace.h" 40 #include "base/time_utils.h" 41 #include "base/unix_file/fd_file.h" 42 #include "base/value_object.h" 43 #include "class_linker-inl.h" 44 #include "class_table-inl.h" 45 #include "compiler_callbacks.h" 46 #include "debugger.h" 47 #include "dex_file-inl.h" 48 #include "entrypoints/entrypoint_utils.h" 49 #include "entrypoints/runtime_asm_entrypoints.h" 50 #include "experimental_flags.h" 51 #include "gc_root-inl.h" 52 #include "gc/accounting/card_table-inl.h" 53 #include "gc/accounting/heap_bitmap-inl.h" 54 #include "gc/heap.h" 55 #include "gc/scoped_gc_critical_section.h" 56 #include "gc/space/image_space.h" 57 #include "handle_scope-inl.h" 58 #include "image-inl.h" 59 #include "intern_table.h" 60 #include "interpreter/interpreter.h" 61 #include "jit/jit.h" 62 #include "jit/jit_code_cache.h" 63 #include "jit/offline_profiling_info.h" 64 #include "leb128.h" 65 #include "linear_alloc.h" 66 #include "mirror/class.h" 67 #include "mirror/class-inl.h" 68 #include "mirror/class_loader.h" 69 #include "mirror/dex_cache-inl.h" 70 #include "mirror/field.h" 71 #include "mirror/iftable-inl.h" 72 #include "mirror/method.h" 73 #include "mirror/object-inl.h" 74 #include "mirror/object_array-inl.h" 75 #include "mirror/proxy.h" 76 #include "mirror/reference-inl.h" 77 #include "mirror/stack_trace_element.h" 78 #include "mirror/string-inl.h" 79 #include "native/dalvik_system_DexFile.h" 80 #include "oat.h" 81 #include "oat_file.h" 82 #include "oat_file-inl.h" 83 #include "oat_file_assistant.h" 84 #include "oat_file_manager.h" 85 #include "object_lock.h" 86 #include "os.h" 87 #include "runtime.h" 88 #include "ScopedLocalRef.h" 89 #include "scoped_thread_state_change.h" 90 #include "thread-inl.h" 91 #include "trace.h" 92 #include "utils.h" 93 #include "utils/dex_cache_arrays_layout-inl.h" 94 #include "verifier/method_verifier.h" 95 #include "well_known_classes.h" 96 97 namespace art { 98 99 static constexpr bool kSanityCheckObjects = kIsDebugBuild; 100 static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild; 101 102 static void ThrowNoClassDefFoundError(const char* fmt, ...) 103 __attribute__((__format__(__printf__, 1, 2))) 104 SHARED_REQUIRES(Locks::mutator_lock_); 105 static void ThrowNoClassDefFoundError(const char* fmt, ...) { 106 va_list args; 107 va_start(args, fmt); 108 Thread* self = Thread::Current(); 109 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args); 110 va_end(args); 111 } 112 113 static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor) 114 SHARED_REQUIRES(Locks::mutator_lock_) { 115 ArtMethod* method = self->GetCurrentMethod(nullptr); 116 StackHandleScope<1> hs(self); 117 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ? 118 method->GetDeclaringClass()->GetClassLoader() : nullptr)); 119 mirror::Class* exception_class = class_linker->FindClass(self, descriptor, class_loader); 120 121 if (exception_class == nullptr) { 122 // No exc class ~ no <init>-with-string. 123 CHECK(self->IsExceptionPending()); 124 self->ClearException(); 125 return false; 126 } 127 128 ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod( 129 "<init>", "(Ljava/lang/String;)V", class_linker->GetImagePointerSize()); 130 return exception_init_method != nullptr; 131 } 132 133 // Helper for ThrowEarlierClassFailure. Throws the stored error. 134 static void HandleEarlierVerifyError(Thread* self, ClassLinker* class_linker, mirror::Class* c) 135 SHARED_REQUIRES(Locks::mutator_lock_) { 136 mirror::Object* obj = c->GetVerifyError(); 137 DCHECK(obj != nullptr); 138 self->AssertNoPendingException(); 139 if (obj->IsClass()) { 140 // Previous error has been stored as class. Create a new exception of that type. 141 142 // It's possible the exception doesn't have a <init>(String). 143 std::string temp; 144 const char* descriptor = obj->AsClass()->GetDescriptor(&temp); 145 146 if (HasInitWithString(self, class_linker, descriptor)) { 147 self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str()); 148 } else { 149 self->ThrowNewException(descriptor, nullptr); 150 } 151 } else { 152 // Previous error has been stored as an instance. Just rethrow. 153 mirror::Class* throwable_class = 154 self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass(); 155 mirror::Class* error_class = obj->GetClass(); 156 CHECK(throwable_class->IsAssignableFrom(error_class)); 157 self->SetException(obj->AsThrowable()); 158 } 159 self->AssertPendingException(); 160 } 161 162 void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c, bool wrap_in_no_class_def) { 163 // The class failed to initialize on a previous attempt, so we want to throw 164 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we 165 // failed in verification, in which case v2 5.4.1 says we need to re-throw 166 // the previous error. 167 Runtime* const runtime = Runtime::Current(); 168 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime. 169 std::string extra; 170 if (c->GetVerifyError() != nullptr) { 171 mirror::Object* verify_error = c->GetVerifyError(); 172 if (verify_error->IsClass()) { 173 extra = PrettyDescriptor(verify_error->AsClass()); 174 } else { 175 extra = verify_error->AsThrowable()->Dump(); 176 } 177 } 178 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c) << ": " << extra; 179 } 180 181 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus(); 182 Thread* self = Thread::Current(); 183 if (runtime->IsAotCompiler()) { 184 // At compile time, accurate errors and NCDFE are disabled to speed compilation. 185 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError(); 186 self->SetException(pre_allocated); 187 } else { 188 if (c->GetVerifyError() != nullptr) { 189 // Rethrow stored error. 190 HandleEarlierVerifyError(self, this, c); 191 } 192 if (c->GetVerifyError() == nullptr || wrap_in_no_class_def) { 193 // If there isn't a recorded earlier error, or this is a repeat throw from initialization, 194 // the top-level exception must be a NoClassDefFoundError. The potentially already pending 195 // exception will be a cause. 196 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;", 197 PrettyDescriptor(c).c_str()); 198 } 199 } 200 } 201 202 static void VlogClassInitializationFailure(Handle<mirror::Class> klass) 203 SHARED_REQUIRES(Locks::mutator_lock_) { 204 if (VLOG_IS_ON(class_linker)) { 205 std::string temp; 206 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from " 207 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump(); 208 } 209 } 210 211 static void WrapExceptionInInitializer(Handle<mirror::Class> klass) 212 SHARED_REQUIRES(Locks::mutator_lock_) { 213 Thread* self = Thread::Current(); 214 JNIEnv* env = self->GetJniEnv(); 215 216 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred()); 217 CHECK(cause.get() != nullptr); 218 219 env->ExceptionClear(); 220 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error); 221 env->Throw(cause.get()); 222 223 // We only wrap non-Error exceptions; an Error can just be used as-is. 224 if (!is_error) { 225 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr); 226 } 227 VlogClassInitializationFailure(klass); 228 } 229 230 // Gap between two fields in object layout. 231 struct FieldGap { 232 uint32_t start_offset; // The offset from the start of the object. 233 uint32_t size; // The gap size of 1, 2, or 4 bytes. 234 }; 235 struct FieldGapsComparator { 236 explicit FieldGapsComparator() { 237 } 238 bool operator() (const FieldGap& lhs, const FieldGap& rhs) 239 NO_THREAD_SAFETY_ANALYSIS { 240 // Sort by gap size, largest first. Secondary sort by starting offset. 241 // Note that the priority queue returns the largest element, so operator() 242 // should return true if lhs is less than rhs. 243 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset); 244 } 245 }; 246 typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps; 247 248 // Adds largest aligned gaps to queue of gaps. 249 static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) { 250 DCHECK(gaps != nullptr); 251 252 uint32_t current_offset = gap_start; 253 while (current_offset != gap_end) { 254 size_t remaining = gap_end - current_offset; 255 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) { 256 gaps->push(FieldGap {current_offset, sizeof(uint32_t)}); 257 current_offset += sizeof(uint32_t); 258 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) { 259 gaps->push(FieldGap {current_offset, sizeof(uint16_t)}); 260 current_offset += sizeof(uint16_t); 261 } else { 262 gaps->push(FieldGap {current_offset, sizeof(uint8_t)}); 263 current_offset += sizeof(uint8_t); 264 } 265 DCHECK_LE(current_offset, gap_end) << "Overran gap"; 266 } 267 } 268 // Shuffle fields forward, making use of gaps whenever possible. 269 template<int n> 270 static void ShuffleForward(size_t* current_field_idx, 271 MemberOffset* field_offset, 272 std::deque<ArtField*>* grouped_and_sorted_fields, 273 FieldGaps* gaps) 274 SHARED_REQUIRES(Locks::mutator_lock_) { 275 DCHECK(current_field_idx != nullptr); 276 DCHECK(grouped_and_sorted_fields != nullptr); 277 DCHECK(gaps != nullptr); 278 DCHECK(field_offset != nullptr); 279 280 DCHECK(IsPowerOfTwo(n)); 281 while (!grouped_and_sorted_fields->empty()) { 282 ArtField* field = grouped_and_sorted_fields->front(); 283 Primitive::Type type = field->GetTypeAsPrimitiveType(); 284 if (Primitive::ComponentSize(type) < n) { 285 break; 286 } 287 if (!IsAligned<n>(field_offset->Uint32Value())) { 288 MemberOffset old_offset = *field_offset; 289 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n)); 290 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps); 291 } 292 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types 293 grouped_and_sorted_fields->pop_front(); 294 if (!gaps->empty() && gaps->top().size >= n) { 295 FieldGap gap = gaps->top(); 296 gaps->pop(); 297 DCHECK_ALIGNED(gap.start_offset, n); 298 field->SetOffset(MemberOffset(gap.start_offset)); 299 if (gap.size > n) { 300 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps); 301 } 302 } else { 303 DCHECK_ALIGNED(field_offset->Uint32Value(), n); 304 field->SetOffset(*field_offset); 305 *field_offset = MemberOffset(field_offset->Uint32Value() + n); 306 } 307 ++(*current_field_idx); 308 } 309 } 310 311 ClassLinker::ClassLinker(InternTable* intern_table) 312 // dex_lock_ is recursive as it may be used in stack dumping. 313 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel), 314 dex_cache_boot_image_class_lookup_required_(false), 315 failed_dex_cache_class_lookups_(0), 316 class_roots_(nullptr), 317 array_iftable_(nullptr), 318 find_array_class_cache_next_victim_(0), 319 init_done_(false), 320 log_new_class_table_roots_(false), 321 intern_table_(intern_table), 322 quick_resolution_trampoline_(nullptr), 323 quick_imt_conflict_trampoline_(nullptr), 324 quick_generic_jni_trampoline_(nullptr), 325 quick_to_interpreter_bridge_trampoline_(nullptr), 326 image_pointer_size_(sizeof(void*)) { 327 CHECK(intern_table_ != nullptr); 328 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_), 329 "Array cache size wrong."); 330 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr)); 331 } 332 333 void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) { 334 mirror::Class* c2 = FindSystemClass(self, descriptor); 335 if (c2 == nullptr) { 336 LOG(FATAL) << "Could not find class " << descriptor; 337 UNREACHABLE(); 338 } 339 if (c1.Get() != c2) { 340 std::ostringstream os1, os2; 341 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail); 342 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail); 343 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor 344 << ". This is most likely the result of a broken build. Make sure that " 345 << "libcore and art projects match.\n\n" 346 << os1.str() << "\n\n" << os2.str(); 347 UNREACHABLE(); 348 } 349 } 350 351 bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path, 352 std::string* error_msg) { 353 VLOG(startup) << "ClassLinker::Init"; 354 355 Thread* const self = Thread::Current(); 356 Runtime* const runtime = Runtime::Current(); 357 gc::Heap* const heap = runtime->GetHeap(); 358 359 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it."; 360 CHECK(!init_done_); 361 362 // Use the pointer size from the runtime since we are probably creating the image. 363 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet()); 364 if (!ValidPointerSize(image_pointer_size_)) { 365 *error_msg = StringPrintf("Invalid image pointer size: %zu", image_pointer_size_); 366 return false; 367 } 368 369 // java_lang_Class comes first, it's needed for AllocClass 370 // The GC can't handle an object with a null class since we can't get the size of this object. 371 heap->IncrementDisableMovingGC(self); 372 StackHandleScope<64> hs(self); // 64 is picked arbitrarily. 373 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_); 374 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>( 375 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor())))); 376 CHECK(java_lang_Class.Get() != nullptr); 377 mirror::Class::SetClassClass(java_lang_Class.Get()); 378 java_lang_Class->SetClass(java_lang_Class.Get()); 379 if (kUseBakerOrBrooksReadBarrier) { 380 java_lang_Class->AssertReadBarrierPointer(); 381 } 382 java_lang_Class->SetClassSize(class_class_size); 383 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot); 384 heap->DecrementDisableMovingGC(self); 385 // AllocClass(mirror::Class*) can now be used 386 387 // Class[] is used for reflection support. 388 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_); 389 Handle<mirror::Class> class_array_class(hs.NewHandle( 390 AllocClass(self, java_lang_Class.Get(), class_array_class_size))); 391 class_array_class->SetComponentType(java_lang_Class.Get()); 392 393 // java_lang_Object comes next so that object_array_class can be created. 394 Handle<mirror::Class> java_lang_Object(hs.NewHandle( 395 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_)))); 396 CHECK(java_lang_Object.Get() != nullptr); 397 // backfill Object as the super class of Class. 398 java_lang_Class->SetSuperClass(java_lang_Object.Get()); 399 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self); 400 401 java_lang_Object->SetObjectSize(sizeof(mirror::Object)); 402 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been 403 // cleared without triggering the read barrier and unintentionally mark the sentinel alive. 404 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self, 405 java_lang_Object.Get(), 406 java_lang_Object->GetObjectSize(), 407 VoidFunctor())); 408 409 // Object[] next to hold class roots. 410 Handle<mirror::Class> object_array_class(hs.NewHandle( 411 AllocClass(self, java_lang_Class.Get(), 412 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_)))); 413 object_array_class->SetComponentType(java_lang_Object.Get()); 414 415 // Setup the char (primitive) class to be used for char[]. 416 Handle<mirror::Class> char_class(hs.NewHandle( 417 AllocClass(self, java_lang_Class.Get(), 418 mirror::Class::PrimitiveClassSize(image_pointer_size_)))); 419 // The primitive char class won't be initialized by 420 // InitializePrimitiveClass until line 459, but strings (and 421 // internal char arrays) will be allocated before that and the 422 // component size, which is computed from the primitive type, needs 423 // to be set here. 424 char_class->SetPrimitiveType(Primitive::kPrimChar); 425 426 // Setup the char[] class to be used for String. 427 Handle<mirror::Class> char_array_class(hs.NewHandle( 428 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_)))); 429 char_array_class->SetComponentType(char_class.Get()); 430 mirror::CharArray::SetArrayClass(char_array_class.Get()); 431 432 // Setup String. 433 Handle<mirror::Class> java_lang_String(hs.NewHandle( 434 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_)))); 435 java_lang_String->SetStringClass(); 436 mirror::String::SetClass(java_lang_String.Get()); 437 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self); 438 439 // Setup java.lang.ref.Reference. 440 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle( 441 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_)))); 442 mirror::Reference::SetClass(java_lang_ref_Reference.Get()); 443 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize()); 444 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self); 445 446 // Create storage for root classes, save away our work so far (requires descriptors). 447 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>( 448 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(), 449 kClassRootsMax)); 450 CHECK(!class_roots_.IsNull()); 451 SetClassRoot(kJavaLangClass, java_lang_Class.Get()); 452 SetClassRoot(kJavaLangObject, java_lang_Object.Get()); 453 SetClassRoot(kClassArrayClass, class_array_class.Get()); 454 SetClassRoot(kObjectArrayClass, object_array_class.Get()); 455 SetClassRoot(kCharArrayClass, char_array_class.Get()); 456 SetClassRoot(kJavaLangString, java_lang_String.Get()); 457 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get()); 458 459 // Setup the primitive type classes. 460 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean)); 461 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte)); 462 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort)); 463 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt)); 464 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong)); 465 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat)); 466 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble)); 467 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid)); 468 469 // Create array interface entries to populate once we can load system classes. 470 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2)); 471 472 // Create int array type for AllocDexCache (done in AppendToBootClassPath). 473 Handle<mirror::Class> int_array_class(hs.NewHandle( 474 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_)))); 475 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt)); 476 mirror::IntArray::SetArrayClass(int_array_class.Get()); 477 SetClassRoot(kIntArrayClass, int_array_class.Get()); 478 479 // Create long array type for AllocDexCache (done in AppendToBootClassPath). 480 Handle<mirror::Class> long_array_class(hs.NewHandle( 481 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_)))); 482 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong)); 483 mirror::LongArray::SetArrayClass(long_array_class.Get()); 484 SetClassRoot(kLongArrayClass, long_array_class.Get()); 485 486 // now that these are registered, we can use AllocClass() and AllocObjectArray 487 488 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache. 489 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle( 490 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_)))); 491 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get()); 492 java_lang_DexCache->SetDexCacheClass(); 493 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize()); 494 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self); 495 496 // Set up array classes for string, field, method 497 Handle<mirror::Class> object_array_string(hs.NewHandle( 498 AllocClass(self, java_lang_Class.Get(), 499 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_)))); 500 object_array_string->SetComponentType(java_lang_String.Get()); 501 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get()); 502 503 LinearAlloc* linear_alloc = runtime->GetLinearAlloc(); 504 // Create runtime resolution and imt conflict methods. 505 runtime->SetResolutionMethod(runtime->CreateResolutionMethod()); 506 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc)); 507 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc)); 508 509 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create 510 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses 511 // these roots. 512 if (boot_class_path.empty()) { 513 *error_msg = "Boot classpath is empty."; 514 return false; 515 } 516 for (auto& dex_file : boot_class_path) { 517 if (dex_file.get() == nullptr) { 518 *error_msg = "Null dex file."; 519 return false; 520 } 521 AppendToBootClassPath(self, *dex_file); 522 boot_dex_files_.push_back(std::move(dex_file)); 523 } 524 525 // now we can use FindSystemClass 526 527 // run char class through InitializePrimitiveClass to finish init 528 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar); 529 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor 530 531 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that 532 // we do not need friend classes or a publicly exposed setter. 533 quick_generic_jni_trampoline_ = GetQuickGenericJniStub(); 534 if (!runtime->IsAotCompiler()) { 535 // We need to set up the generic trampolines since we don't have an image. 536 quick_resolution_trampoline_ = GetQuickResolutionStub(); 537 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub(); 538 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge(); 539 } 540 541 // Object, String and DexCache need to be rerun through FindSystemClass to finish init 542 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self); 543 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;"); 544 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize()); 545 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self); 546 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;"); 547 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self); 548 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;"); 549 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize()); 550 551 // Setup the primitive array type classes - can't be done until Object has a vtable. 552 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z")); 553 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass)); 554 555 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B")); 556 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass)); 557 558 CheckSystemClass(self, char_array_class, "[C"); 559 560 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S")); 561 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass)); 562 563 CheckSystemClass(self, int_array_class, "[I"); 564 CheckSystemClass(self, long_array_class, "[J"); 565 566 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F")); 567 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass)); 568 569 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D")); 570 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass)); 571 572 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it 573 // in class_table_. 574 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;"); 575 576 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;"); 577 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;"); 578 579 // Setup the single, global copy of "iftable". 580 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;")); 581 CHECK(java_lang_Cloneable.Get() != nullptr); 582 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;")); 583 CHECK(java_io_Serializable.Get() != nullptr); 584 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to 585 // crawl up and explicitly list all of the supers as well. 586 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get()); 587 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get()); 588 589 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread 590 // suspension. 591 CHECK_EQ(java_lang_Cloneable.Get(), 592 mirror::Class::GetDirectInterface(self, class_array_class, 0)); 593 CHECK_EQ(java_io_Serializable.Get(), 594 mirror::Class::GetDirectInterface(self, class_array_class, 1)); 595 CHECK_EQ(java_lang_Cloneable.Get(), 596 mirror::Class::GetDirectInterface(self, object_array_class, 0)); 597 CHECK_EQ(java_io_Serializable.Get(), 598 mirror::Class::GetDirectInterface(self, object_array_class, 1)); 599 600 CHECK_EQ(object_array_string.Get(), 601 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass))); 602 603 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass. 604 605 // Create java.lang.reflect.Proxy root. 606 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;")); 607 608 // Create java.lang.reflect.Field.class root. 609 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;"); 610 CHECK(class_root != nullptr); 611 SetClassRoot(kJavaLangReflectField, class_root); 612 mirror::Field::SetClass(class_root); 613 614 // Create java.lang.reflect.Field array root. 615 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;"); 616 CHECK(class_root != nullptr); 617 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root); 618 mirror::Field::SetArrayClass(class_root); 619 620 // Create java.lang.reflect.Constructor.class root and array root. 621 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;"); 622 CHECK(class_root != nullptr); 623 SetClassRoot(kJavaLangReflectConstructor, class_root); 624 mirror::Constructor::SetClass(class_root); 625 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;"); 626 CHECK(class_root != nullptr); 627 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root); 628 mirror::Constructor::SetArrayClass(class_root); 629 630 // Create java.lang.reflect.Method.class root and array root. 631 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;"); 632 CHECK(class_root != nullptr); 633 SetClassRoot(kJavaLangReflectMethod, class_root); 634 mirror::Method::SetClass(class_root); 635 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;"); 636 CHECK(class_root != nullptr); 637 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root); 638 mirror::Method::SetArrayClass(class_root); 639 640 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes 641 // finish initializing Reference class 642 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self); 643 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;"); 644 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize()); 645 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), 646 mirror::Reference::ClassSize(image_pointer_size_)); 647 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"); 648 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal); 649 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference); 650 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;"); 651 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal); 652 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference); 653 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;"); 654 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal); 655 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference); 656 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;"); 657 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal); 658 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference); 659 660 // Setup the ClassLoader, verifying the object_size_. 661 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;"); 662 class_root->SetClassLoaderClass(); 663 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize()); 664 SetClassRoot(kJavaLangClassLoader, class_root); 665 666 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and 667 // java.lang.StackTraceElement as a convenience. 668 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;")); 669 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable)); 670 SetClassRoot(kJavaLangClassNotFoundException, 671 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;")); 672 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;")); 673 SetClassRoot(kJavaLangStackTraceElementArrayClass, 674 FindSystemClass(self, "[Ljava/lang/StackTraceElement;")); 675 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement)); 676 677 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly 678 // initialized. 679 { 680 const DexFile& dex_file = java_lang_Object->GetDexFile(); 681 const DexFile::TypeId* void_type_id = dex_file.FindTypeId("V"); 682 CHECK(void_type_id != nullptr); 683 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id); 684 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class 685 // as referrer so the used dex cache is core's one. 686 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get()); 687 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid)); 688 self->AssertNoPendingException(); 689 } 690 691 // Create conflict tables that depend on the class linker. 692 runtime->FixupConflictTables(); 693 694 FinishInit(self); 695 696 VLOG(startup) << "ClassLinker::InitFromCompiler exiting"; 697 698 return true; 699 } 700 701 void ClassLinker::FinishInit(Thread* self) { 702 VLOG(startup) << "ClassLinker::FinishInit entering"; 703 704 // Let the heap know some key offsets into java.lang.ref instances 705 // Note: we hard code the field indexes here rather than using FindInstanceField 706 // as the types of the field can't be resolved prior to the runtime being 707 // fully initialized 708 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference); 709 mirror::Class* java_lang_ref_FinalizerReference = 710 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"); 711 712 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0); 713 CHECK_STREQ(pendingNext->GetName(), "pendingNext"); 714 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;"); 715 716 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1); 717 CHECK_STREQ(queue->GetName(), "queue"); 718 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;"); 719 720 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2); 721 CHECK_STREQ(queueNext->GetName(), "queueNext"); 722 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;"); 723 724 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3); 725 CHECK_STREQ(referent->GetName(), "referent"); 726 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;"); 727 728 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2); 729 CHECK_STREQ(zombie->GetName(), "zombie"); 730 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;"); 731 732 // ensure all class_roots_ are initialized 733 for (size_t i = 0; i < kClassRootsMax; i++) { 734 ClassRoot class_root = static_cast<ClassRoot>(i); 735 mirror::Class* klass = GetClassRoot(class_root); 736 CHECK(klass != nullptr); 737 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr); 738 // note SetClassRoot does additional validation. 739 // if possible add new checks there to catch errors early 740 } 741 742 CHECK(!array_iftable_.IsNull()); 743 744 // disable the slow paths in FindClass and CreatePrimitiveClass now 745 // that Object, Class, and Object[] are setup 746 init_done_ = true; 747 748 VLOG(startup) << "ClassLinker::FinishInit exiting"; 749 } 750 751 void ClassLinker::RunRootClinits() { 752 Thread* self = Thread::Current(); 753 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) { 754 mirror::Class* c = GetClassRoot(ClassRoot(i)); 755 if (!c->IsArrayClass() && !c->IsPrimitive()) { 756 StackHandleScope<1> hs(self); 757 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i)))); 758 EnsureInitialized(self, h_class, true, true); 759 self->AssertNoPendingException(); 760 } 761 } 762 } 763 764 static void SanityCheckArtMethod(ArtMethod* m, 765 mirror::Class* expected_class, 766 const std::vector<gc::space::ImageSpace*>& spaces) 767 SHARED_REQUIRES(Locks::mutator_lock_) { 768 if (m->IsRuntimeMethod()) { 769 mirror::Class* declaring_class = m->GetDeclaringClassUnchecked(); 770 CHECK(declaring_class == nullptr) << declaring_class << " " << PrettyMethod(m); 771 } else if (m->IsCopied()) { 772 CHECK(m->GetDeclaringClass() != nullptr) << PrettyMethod(m); 773 } else if (expected_class != nullptr) { 774 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << PrettyMethod(m); 775 } 776 if (!spaces.empty()) { 777 bool contains = false; 778 for (gc::space::ImageSpace* space : spaces) { 779 auto& header = space->GetImageHeader(); 780 size_t offset = reinterpret_cast<uint8_t*>(m) - space->Begin(); 781 782 const ImageSection& methods = header.GetMethodsSection(); 783 contains = contains || methods.Contains(offset); 784 785 const ImageSection& runtime_methods = header.GetRuntimeMethodsSection(); 786 contains = contains || runtime_methods.Contains(offset); 787 } 788 CHECK(contains) << m << " not found"; 789 } 790 } 791 792 static void SanityCheckArtMethodPointerArray(mirror::PointerArray* arr, 793 mirror::Class* expected_class, 794 size_t pointer_size, 795 const std::vector<gc::space::ImageSpace*>& spaces) 796 SHARED_REQUIRES(Locks::mutator_lock_) { 797 CHECK(arr != nullptr); 798 for (int32_t j = 0; j < arr->GetLength(); ++j) { 799 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size); 800 // expected_class == null means we are a dex cache. 801 if (expected_class != nullptr) { 802 CHECK(method != nullptr); 803 } 804 if (method != nullptr) { 805 SanityCheckArtMethod(method, expected_class, spaces); 806 } 807 } 808 } 809 810 static void SanityCheckArtMethodPointerArray(ArtMethod** arr, 811 size_t size, 812 size_t pointer_size, 813 const std::vector<gc::space::ImageSpace*>& spaces) 814 SHARED_REQUIRES(Locks::mutator_lock_) { 815 CHECK_EQ(arr != nullptr, size != 0u); 816 if (arr != nullptr) { 817 bool contains = false; 818 for (auto space : spaces) { 819 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin(); 820 if (space->GetImageHeader().GetImageSection( 821 ImageHeader::kSectionDexCacheArrays).Contains(offset)) { 822 contains = true; 823 break; 824 } 825 } 826 CHECK(contains); 827 } 828 for (size_t j = 0; j < size; ++j) { 829 ArtMethod* method = mirror::DexCache::GetElementPtrSize(arr, j, pointer_size); 830 // expected_class == null means we are a dex cache. 831 if (method != nullptr) { 832 SanityCheckArtMethod(method, nullptr, spaces); 833 } 834 } 835 } 836 837 static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) 838 SHARED_REQUIRES(Locks::mutator_lock_) { 839 DCHECK(obj != nullptr); 840 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj; 841 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj; 842 if (obj->IsClass()) { 843 auto klass = obj->AsClass(); 844 for (ArtField& field : klass->GetIFields()) { 845 CHECK_EQ(field.GetDeclaringClass(), klass); 846 } 847 for (ArtField& field : klass->GetSFields()) { 848 CHECK_EQ(field.GetDeclaringClass(), klass); 849 } 850 auto* runtime = Runtime::Current(); 851 auto image_spaces = runtime->GetHeap()->GetBootImageSpaces(); 852 auto pointer_size = runtime->GetClassLinker()->GetImagePointerSize(); 853 for (auto& m : klass->GetMethods(pointer_size)) { 854 SanityCheckArtMethod(&m, klass, image_spaces); 855 } 856 auto* vtable = klass->GetVTable(); 857 if (vtable != nullptr) { 858 SanityCheckArtMethodPointerArray(vtable, nullptr, pointer_size, image_spaces); 859 } 860 if (klass->ShouldHaveImt()) { 861 ImTable* imt = klass->GetImt(pointer_size); 862 for (size_t i = 0; i < ImTable::kSize; ++i) { 863 SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr, image_spaces); 864 } 865 } 866 if (klass->ShouldHaveEmbeddedVTable()) { 867 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) { 868 SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr, image_spaces); 869 } 870 } 871 auto* iftable = klass->GetIfTable(); 872 if (iftable != nullptr) { 873 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 874 if (iftable->GetMethodArrayCount(i) > 0) { 875 SanityCheckArtMethodPointerArray( 876 iftable->GetMethodArray(i), nullptr, pointer_size, image_spaces); 877 } 878 } 879 } 880 } 881 } 882 883 // Set image methods' entry point to interpreter. 884 class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor { 885 public: 886 explicit SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size) 887 : image_pointer_size_(image_pointer_size) {} 888 889 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 890 if (kIsDebugBuild && !method->IsRuntimeMethod()) { 891 CHECK(method->GetDeclaringClass() != nullptr); 892 } 893 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) { 894 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(), 895 image_pointer_size_); 896 } 897 } 898 899 private: 900 const size_t image_pointer_size_; 901 902 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor); 903 }; 904 905 struct TrampolineCheckData { 906 const void* quick_resolution_trampoline; 907 const void* quick_imt_conflict_trampoline; 908 const void* quick_generic_jni_trampoline; 909 const void* quick_to_interpreter_bridge_trampoline; 910 size_t pointer_size; 911 ArtMethod* m; 912 bool error; 913 }; 914 915 static void CheckTrampolines(mirror::Object* obj, void* arg) NO_THREAD_SAFETY_ANALYSIS { 916 if (obj->IsClass()) { 917 mirror::Class* klass = obj->AsClass(); 918 TrampolineCheckData* d = reinterpret_cast<TrampolineCheckData*>(arg); 919 for (ArtMethod& m : klass->GetMethods(d->pointer_size)) { 920 const void* entrypoint = m.GetEntryPointFromQuickCompiledCodePtrSize(d->pointer_size); 921 if (entrypoint == d->quick_resolution_trampoline || 922 entrypoint == d->quick_imt_conflict_trampoline || 923 entrypoint == d->quick_generic_jni_trampoline || 924 entrypoint == d->quick_to_interpreter_bridge_trampoline) { 925 d->m = &m; 926 d->error = true; 927 return; 928 } 929 } 930 } 931 } 932 933 bool ClassLinker::InitFromBootImage(std::string* error_msg) { 934 VLOG(startup) << __FUNCTION__ << " entering"; 935 CHECK(!init_done_); 936 937 Runtime* const runtime = Runtime::Current(); 938 Thread* const self = Thread::Current(); 939 gc::Heap* const heap = runtime->GetHeap(); 940 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces(); 941 CHECK(!spaces.empty()); 942 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize(); 943 if (!ValidPointerSize(image_pointer_size_)) { 944 *error_msg = StringPrintf("Invalid image pointer size: %zu", image_pointer_size_); 945 return false; 946 } 947 if (!runtime->IsAotCompiler()) { 948 // Only the Aot compiler supports having an image with a different pointer size than the 949 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart 950 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps. 951 if (image_pointer_size_ != sizeof(void*)) { 952 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu", 953 image_pointer_size_, 954 sizeof(void*)); 955 return false; 956 } 957 } 958 dex_cache_boot_image_class_lookup_required_ = true; 959 std::vector<const OatFile*> oat_files = 960 runtime->GetOatFileManager().RegisterImageOatFiles(spaces); 961 DCHECK(!oat_files.empty()); 962 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader(); 963 CHECK_EQ(default_oat_header.GetImageFileLocationOatChecksum(), 0U); 964 CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U); 965 const char* image_file_location = oat_files[0]->GetOatHeader(). 966 GetStoreValueByKey(OatHeader::kImageLocationKey); 967 CHECK(image_file_location == nullptr || *image_file_location == 0); 968 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline(); 969 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline(); 970 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline(); 971 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge(); 972 if (kIsDebugBuild) { 973 // Check that the other images use the same trampoline. 974 for (size_t i = 1; i < oat_files.size(); ++i) { 975 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader(); 976 const void* ith_quick_resolution_trampoline = 977 ith_oat_header.GetQuickResolutionTrampoline(); 978 const void* ith_quick_imt_conflict_trampoline = 979 ith_oat_header.GetQuickImtConflictTrampoline(); 980 const void* ith_quick_generic_jni_trampoline = 981 ith_oat_header.GetQuickGenericJniTrampoline(); 982 const void* ith_quick_to_interpreter_bridge_trampoline = 983 ith_oat_header.GetQuickToInterpreterBridge(); 984 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ || 985 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ || 986 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ || 987 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) { 988 // Make sure that all methods in this image do not contain those trampolines as 989 // entrypoints. Otherwise the class-linker won't be able to work with a single set. 990 TrampolineCheckData data; 991 data.error = false; 992 data.pointer_size = GetImagePointerSize(); 993 data.quick_resolution_trampoline = ith_quick_resolution_trampoline; 994 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline; 995 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline; 996 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline; 997 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 998 spaces[i]->GetLiveBitmap()->Walk(CheckTrampolines, &data); 999 if (data.error) { 1000 ArtMethod* m = data.m; 1001 LOG(ERROR) << "Found a broken ArtMethod: " << PrettyMethod(m); 1002 *error_msg = "Found an ArtMethod with a bad entrypoint"; 1003 return false; 1004 } 1005 } 1006 } 1007 } 1008 1009 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>( 1010 down_cast<mirror::ObjectArray<mirror::Class>*>( 1011 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots))); 1012 mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass)); 1013 1014 // Special case of setting up the String class early so that we can test arbitrary objects 1015 // as being Strings or not 1016 mirror::String::SetClass(GetClassRoot(kJavaLangString)); 1017 1018 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject); 1019 java_lang_Object->SetObjectSize(sizeof(mirror::Object)); 1020 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been 1021 // cleared without triggering the read barrier and unintentionally mark the sentinel alive. 1022 runtime->SetSentinel(heap->AllocNonMovableObject<true>( 1023 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor())); 1024 1025 // reinit array_iftable_ from any array class instance, they should be == 1026 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable()); 1027 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable()); 1028 // String class root was set above 1029 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField)); 1030 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass)); 1031 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor)); 1032 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass)); 1033 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod)); 1034 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass)); 1035 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference)); 1036 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass)); 1037 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass)); 1038 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass)); 1039 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass)); 1040 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass)); 1041 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass)); 1042 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass)); 1043 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass)); 1044 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable)); 1045 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement)); 1046 1047 for (gc::space::ImageSpace* image_space : spaces) { 1048 // Boot class loader, use a null handle. 1049 std::vector<std::unique_ptr<const DexFile>> dex_files; 1050 if (!AddImageSpace(image_space, 1051 ScopedNullHandle<mirror::ClassLoader>(), 1052 /*dex_elements*/nullptr, 1053 /*dex_location*/nullptr, 1054 /*out*/&dex_files, 1055 error_msg)) { 1056 return false; 1057 } 1058 // Append opened dex files at the end. 1059 boot_dex_files_.insert(boot_dex_files_.end(), 1060 std::make_move_iterator(dex_files.begin()), 1061 std::make_move_iterator(dex_files.end())); 1062 } 1063 FinishInit(self); 1064 1065 VLOG(startup) << __FUNCTION__ << " exiting"; 1066 return true; 1067 } 1068 1069 bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa, 1070 mirror::ClassLoader* class_loader) { 1071 return class_loader == nullptr || 1072 class_loader->GetClass() == 1073 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader); 1074 } 1075 1076 static mirror::String* GetDexPathListElementName(ScopedObjectAccessUnchecked& soa, 1077 mirror::Object* element) 1078 SHARED_REQUIRES(Locks::mutator_lock_) { 1079 ArtField* const dex_file_field = 1080 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile); 1081 ArtField* const dex_file_name_field = 1082 soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_fileName); 1083 DCHECK(dex_file_field != nullptr); 1084 DCHECK(dex_file_name_field != nullptr); 1085 DCHECK(element != nullptr); 1086 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << PrettyTypeOf(element); 1087 mirror::Object* dex_file = dex_file_field->GetObject(element); 1088 if (dex_file == nullptr) { 1089 return nullptr; 1090 } 1091 mirror::Object* const name_object = dex_file_name_field->GetObject(dex_file); 1092 if (name_object != nullptr) { 1093 return name_object->AsString(); 1094 } 1095 return nullptr; 1096 } 1097 1098 static bool FlattenPathClassLoader(mirror::ClassLoader* class_loader, 1099 std::list<mirror::String*>* out_dex_file_names, 1100 std::string* error_msg) 1101 SHARED_REQUIRES(Locks::mutator_lock_) { 1102 DCHECK(out_dex_file_names != nullptr); 1103 DCHECK(error_msg != nullptr); 1104 ScopedObjectAccessUnchecked soa(Thread::Current()); 1105 ArtField* const dex_path_list_field = 1106 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList); 1107 ArtField* const dex_elements_field = 1108 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements); 1109 CHECK(dex_path_list_field != nullptr); 1110 CHECK(dex_elements_field != nullptr); 1111 while (!ClassLinker::IsBootClassLoader(soa, class_loader)) { 1112 if (class_loader->GetClass() != 1113 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) { 1114 *error_msg = StringPrintf("Unknown class loader type %s", PrettyTypeOf(class_loader).c_str()); 1115 // Unsupported class loader. 1116 return false; 1117 } 1118 mirror::Object* dex_path_list = dex_path_list_field->GetObject(class_loader); 1119 if (dex_path_list != nullptr) { 1120 // DexPathList has an array dexElements of Elements[] which each contain a dex file. 1121 mirror::Object* dex_elements_obj = dex_elements_field->GetObject(dex_path_list); 1122 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look 1123 // at the mCookie which is a DexFile vector. 1124 if (dex_elements_obj != nullptr) { 1125 mirror::ObjectArray<mirror::Object>* dex_elements = 1126 dex_elements_obj->AsObjectArray<mirror::Object>(); 1127 // Reverse order since we insert the parent at the front. 1128 for (int32_t i = dex_elements->GetLength() - 1; i >= 0; --i) { 1129 mirror::Object* const element = dex_elements->GetWithoutChecks(i); 1130 if (element == nullptr) { 1131 *error_msg = StringPrintf("Null dex element at index %d", i); 1132 return false; 1133 } 1134 mirror::String* const name = GetDexPathListElementName(soa, element); 1135 if (name == nullptr) { 1136 *error_msg = StringPrintf("Null name for dex element at index %d", i); 1137 return false; 1138 } 1139 out_dex_file_names->push_front(name); 1140 } 1141 } 1142 } 1143 class_loader = class_loader->GetParent(); 1144 } 1145 return true; 1146 } 1147 1148 class FixupArtMethodArrayVisitor : public ArtMethodVisitor { 1149 public: 1150 explicit FixupArtMethodArrayVisitor(const ImageHeader& header) : header_(header) {} 1151 1152 virtual void Visit(ArtMethod* method) SHARED_REQUIRES(Locks::mutator_lock_) { 1153 GcRoot<mirror::Class>* resolved_types = method->GetDexCacheResolvedTypes(sizeof(void*)); 1154 const bool is_copied = method->IsCopied(); 1155 if (resolved_types != nullptr) { 1156 bool in_image_space = false; 1157 if (kIsDebugBuild || is_copied) { 1158 in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains( 1159 reinterpret_cast<const uint8_t*>(resolved_types) - header_.GetImageBegin()); 1160 } 1161 // Must be in image space for non-miranda method. 1162 DCHECK(is_copied || in_image_space) 1163 << resolved_types << " is not in image starting at " 1164 << reinterpret_cast<void*>(header_.GetImageBegin()); 1165 if (!is_copied || in_image_space) { 1166 // Go through the array so that we don't need to do a slow map lookup. 1167 method->SetDexCacheResolvedTypes(*reinterpret_cast<GcRoot<mirror::Class>**>(resolved_types), 1168 sizeof(void*)); 1169 } 1170 } 1171 ArtMethod** resolved_methods = method->GetDexCacheResolvedMethods(sizeof(void*)); 1172 if (resolved_methods != nullptr) { 1173 bool in_image_space = false; 1174 if (kIsDebugBuild || is_copied) { 1175 in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains( 1176 reinterpret_cast<const uint8_t*>(resolved_methods) - header_.GetImageBegin()); 1177 } 1178 // Must be in image space for non-miranda method. 1179 DCHECK(is_copied || in_image_space) 1180 << resolved_methods << " is not in image starting at " 1181 << reinterpret_cast<void*>(header_.GetImageBegin()); 1182 if (!is_copied || in_image_space) { 1183 // Go through the array so that we don't need to do a slow map lookup. 1184 method->SetDexCacheResolvedMethods(*reinterpret_cast<ArtMethod***>(resolved_methods), 1185 sizeof(void*)); 1186 } 1187 } 1188 } 1189 1190 private: 1191 const ImageHeader& header_; 1192 }; 1193 1194 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor { 1195 public: 1196 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {} 1197 1198 virtual void Visit(ArtMethod* method) 1199 SHARED_REQUIRES(Locks::mutator_lock_, Locks::classlinker_classes_lock_) { 1200 mirror::Class* klass = method->GetDeclaringClass(); 1201 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) { 1202 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << PrettyClass(klass); 1203 } 1204 } 1205 1206 private: 1207 ClassTable* const table_; 1208 }; 1209 1210 class VerifyDeclaringClassVisitor : public ArtMethodVisitor { 1211 public: 1212 VerifyDeclaringClassVisitor() SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) 1213 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {} 1214 1215 virtual void Visit(ArtMethod* method) 1216 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) { 1217 mirror::Class* klass = method->GetDeclaringClassUnchecked(); 1218 if (klass != nullptr) { 1219 CHECK(live_bitmap_->Test(klass)) << "Image method has unmarked declaring class"; 1220 } 1221 } 1222 1223 private: 1224 gc::accounting::HeapBitmap* const live_bitmap_; 1225 }; 1226 1227 bool ClassLinker::UpdateAppImageClassLoadersAndDexCaches( 1228 gc::space::ImageSpace* space, 1229 Handle<mirror::ClassLoader> class_loader, 1230 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches, 1231 ClassTable::ClassSet* new_class_set, 1232 bool* out_forward_dex_cache_array, 1233 std::string* out_error_msg) { 1234 DCHECK(out_forward_dex_cache_array != nullptr); 1235 DCHECK(out_error_msg != nullptr); 1236 Thread* const self = Thread::Current(); 1237 gc::Heap* const heap = Runtime::Current()->GetHeap(); 1238 const ImageHeader& header = space->GetImageHeader(); 1239 { 1240 // Add image classes into the class table for the class loader, and fixup the dex caches and 1241 // class loader fields. 1242 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 1243 ClassTable* table = InsertClassTableForClassLoader(class_loader.Get()); 1244 // Dex cache array fixup is all or nothing, we must reject app images that have mixed since we 1245 // rely on clobering the dex cache arrays in the image to forward to bss. 1246 size_t num_dex_caches_with_bss_arrays = 0; 1247 const size_t num_dex_caches = dex_caches->GetLength(); 1248 for (size_t i = 0; i < num_dex_caches; i++) { 1249 mirror::DexCache* const dex_cache = dex_caches->Get(i); 1250 const DexFile* const dex_file = dex_cache->GetDexFile(); 1251 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile(); 1252 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) { 1253 ++num_dex_caches_with_bss_arrays; 1254 } 1255 } 1256 *out_forward_dex_cache_array = num_dex_caches_with_bss_arrays != 0; 1257 if (*out_forward_dex_cache_array) { 1258 if (num_dex_caches_with_bss_arrays != num_dex_caches) { 1259 // Reject application image since we cannot forward only some of the dex cache arrays. 1260 // TODO: We could get around this by having a dedicated forwarding slot. It should be an 1261 // uncommon case. 1262 *out_error_msg = StringPrintf("Dex caches in bss does not match total: %zu vs %zu", 1263 num_dex_caches_with_bss_arrays, 1264 num_dex_caches); 1265 return false; 1266 } 1267 } 1268 // Only add the classes to the class loader after the points where we can return false. 1269 for (size_t i = 0; i < num_dex_caches; i++) { 1270 mirror::DexCache* const dex_cache = dex_caches->Get(i); 1271 const DexFile* const dex_file = dex_cache->GetDexFile(); 1272 const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile(); 1273 if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) { 1274 // If the oat file expects the dex cache arrays to be in the BSS, then allocate there and 1275 // copy over the arrays. 1276 DCHECK(dex_file != nullptr); 1277 const size_t num_strings = dex_file->NumStringIds(); 1278 const size_t num_types = dex_file->NumTypeIds(); 1279 const size_t num_methods = dex_file->NumMethodIds(); 1280 const size_t num_fields = dex_file->NumFieldIds(); 1281 CHECK_EQ(num_strings, dex_cache->NumStrings()); 1282 CHECK_EQ(num_types, dex_cache->NumResolvedTypes()); 1283 CHECK_EQ(num_methods, dex_cache->NumResolvedMethods()); 1284 CHECK_EQ(num_fields, dex_cache->NumResolvedFields()); 1285 DexCacheArraysLayout layout(image_pointer_size_, dex_file); 1286 uint8_t* const raw_arrays = oat_dex_file->GetDexCacheArrays(); 1287 // The space is not yet visible to the GC, we can avoid the read barriers and use 1288 // std::copy_n. 1289 if (num_strings != 0u) { 1290 GcRoot<mirror::String>* const image_resolved_strings = dex_cache->GetStrings(); 1291 GcRoot<mirror::String>* const strings = 1292 reinterpret_cast<GcRoot<mirror::String>*>(raw_arrays + layout.StringsOffset()); 1293 for (size_t j = 0; kIsDebugBuild && j < num_strings; ++j) { 1294 DCHECK(strings[j].IsNull()); 1295 } 1296 std::copy_n(image_resolved_strings, num_strings, strings); 1297 dex_cache->SetStrings(strings); 1298 } 1299 if (num_types != 0u) { 1300 GcRoot<mirror::Class>* const image_resolved_types = dex_cache->GetResolvedTypes(); 1301 GcRoot<mirror::Class>* const types = 1302 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset()); 1303 for (size_t j = 0; kIsDebugBuild && j < num_types; ++j) { 1304 DCHECK(types[j].IsNull()); 1305 } 1306 std::copy_n(image_resolved_types, num_types, types); 1307 // Store a pointer to the new location for fast ArtMethod patching without requiring map. 1308 // This leaves random garbage at the start of the dex cache array, but nobody should ever 1309 // read from it again. 1310 *reinterpret_cast<GcRoot<mirror::Class>**>(image_resolved_types) = types; 1311 dex_cache->SetResolvedTypes(types); 1312 } 1313 if (num_methods != 0u) { 1314 ArtMethod** const methods = reinterpret_cast<ArtMethod**>( 1315 raw_arrays + layout.MethodsOffset()); 1316 ArtMethod** const image_resolved_methods = dex_cache->GetResolvedMethods(); 1317 for (size_t j = 0; kIsDebugBuild && j < num_methods; ++j) { 1318 DCHECK(methods[j] == nullptr); 1319 } 1320 std::copy_n(image_resolved_methods, num_methods, methods); 1321 // Store a pointer to the new location for fast ArtMethod patching without requiring map. 1322 *reinterpret_cast<ArtMethod***>(image_resolved_methods) = methods; 1323 dex_cache->SetResolvedMethods(methods); 1324 } 1325 if (num_fields != 0u) { 1326 ArtField** const fields = 1327 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset()); 1328 for (size_t j = 0; kIsDebugBuild && j < num_fields; ++j) { 1329 DCHECK(fields[j] == nullptr); 1330 } 1331 std::copy_n(dex_cache->GetResolvedFields(), num_fields, fields); 1332 dex_cache->SetResolvedFields(fields); 1333 } 1334 } 1335 { 1336 WriterMutexLock mu2(self, dex_lock_); 1337 // Make sure to do this after we update the arrays since we store the resolved types array 1338 // in DexCacheData in RegisterDexFileLocked. We need the array pointer to be the one in the 1339 // BSS. 1340 mirror::DexCache* existing_dex_cache = FindDexCacheLocked(self, 1341 *dex_file, 1342 /*allow_failure*/true); 1343 CHECK(existing_dex_cache == nullptr); 1344 StackHandleScope<1> hs3(self); 1345 RegisterDexFileLocked(*dex_file, hs3.NewHandle(dex_cache)); 1346 } 1347 GcRoot<mirror::Class>* const types = dex_cache->GetResolvedTypes(); 1348 const size_t num_types = dex_cache->NumResolvedTypes(); 1349 if (new_class_set == nullptr) { 1350 for (int32_t j = 0; j < static_cast<int32_t>(num_types); j++) { 1351 // The image space is not yet added to the heap, avoid read barriers. 1352 mirror::Class* klass = types[j].Read(); 1353 // There may also be boot image classes, 1354 if (space->HasAddress(klass)) { 1355 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError); 1356 // Update the class loader from the one in the image class loader to the one that loaded 1357 // the app image. 1358 klass->SetClassLoader(class_loader.Get()); 1359 // The resolved type could be from another dex cache, go through the dex cache just in 1360 // case. May be null for array classes. 1361 if (klass->GetDexCacheStrings() != nullptr) { 1362 DCHECK(!klass->IsArrayClass()); 1363 klass->SetDexCacheStrings(klass->GetDexCache()->GetStrings()); 1364 } 1365 // If there are multiple dex caches, there may be the same class multiple times 1366 // in different dex caches. Check for this since inserting will add duplicates 1367 // otherwise. 1368 if (num_dex_caches > 1) { 1369 mirror::Class* existing = table->LookupByDescriptor(klass); 1370 if (existing != nullptr) { 1371 DCHECK_EQ(existing, klass) << PrettyClass(klass); 1372 } else { 1373 table->Insert(klass); 1374 } 1375 } else { 1376 table->Insert(klass); 1377 } 1378 // Double checked VLOG to avoid overhead. 1379 if (VLOG_IS_ON(image)) { 1380 VLOG(image) << PrettyClass(klass) << " " << klass->GetStatus(); 1381 if (!klass->IsArrayClass()) { 1382 VLOG(image) << "From " << klass->GetDexCache()->GetDexFile()->GetBaseLocation(); 1383 } 1384 VLOG(image) << "Direct methods"; 1385 for (ArtMethod& m : klass->GetDirectMethods(sizeof(void*))) { 1386 VLOG(image) << PrettyMethod(&m); 1387 } 1388 VLOG(image) << "Virtual methods"; 1389 for (ArtMethod& m : klass->GetVirtualMethods(sizeof(void*))) { 1390 VLOG(image) << PrettyMethod(&m); 1391 } 1392 } 1393 } else { 1394 DCHECK(klass == nullptr || heap->ObjectIsInBootImageSpace(klass)) 1395 << klass << " " << PrettyClass(klass); 1396 } 1397 } 1398 } 1399 if (kIsDebugBuild) { 1400 for (int32_t j = 0; j < static_cast<int32_t>(num_types); j++) { 1401 // The image space is not yet added to the heap, avoid read barriers. 1402 mirror::Class* klass = types[j].Read(); 1403 if (space->HasAddress(klass)) { 1404 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError); 1405 if (kIsDebugBuild) { 1406 if (new_class_set != nullptr) { 1407 auto it = new_class_set->Find(GcRoot<mirror::Class>(klass)); 1408 DCHECK(it != new_class_set->end()); 1409 DCHECK_EQ(it->Read(), klass); 1410 mirror::Class* super_class = klass->GetSuperClass(); 1411 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) { 1412 auto it2 = new_class_set->Find(GcRoot<mirror::Class>(super_class)); 1413 DCHECK(it2 != new_class_set->end()); 1414 DCHECK_EQ(it2->Read(), super_class); 1415 } 1416 } else { 1417 DCHECK_EQ(table->LookupByDescriptor(klass), klass); 1418 mirror::Class* super_class = klass->GetSuperClass(); 1419 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) { 1420 CHECK_EQ(table->LookupByDescriptor(super_class), super_class); 1421 } 1422 } 1423 } 1424 if (kIsDebugBuild) { 1425 for (ArtMethod& m : klass->GetDirectMethods(sizeof(void*))) { 1426 const void* code = m.GetEntryPointFromQuickCompiledCode(); 1427 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code; 1428 if (!IsQuickResolutionStub(code) && 1429 !IsQuickGenericJniStub(code) && 1430 !IsQuickToInterpreterBridge(code) && 1431 !m.IsNative()) { 1432 DCHECK_EQ(code, oat_code) << PrettyMethod(&m); 1433 } 1434 } 1435 for (ArtMethod& m : klass->GetVirtualMethods(sizeof(void*))) { 1436 const void* code = m.GetEntryPointFromQuickCompiledCode(); 1437 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code; 1438 if (!IsQuickResolutionStub(code) && 1439 !IsQuickGenericJniStub(code) && 1440 !IsQuickToInterpreterBridge(code) && 1441 !m.IsNative()) { 1442 DCHECK_EQ(code, oat_code) << PrettyMethod(&m); 1443 } 1444 } 1445 } 1446 } 1447 } 1448 } 1449 } 1450 } 1451 if (*out_forward_dex_cache_array) { 1452 ScopedTrace timing("Fixup ArtMethod dex cache arrays"); 1453 FixupArtMethodArrayVisitor visitor(header); 1454 header.VisitPackedArtMethods(&visitor, space->Begin(), sizeof(void*)); 1455 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get()); 1456 } 1457 if (kVerifyArtMethodDeclaringClasses) { 1458 ScopedTrace timing("Verify declaring classes"); 1459 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_); 1460 VerifyDeclaringClassVisitor visitor; 1461 header.VisitPackedArtMethods(&visitor, space->Begin(), sizeof(void*)); 1462 } 1463 return true; 1464 } 1465 1466 // Update the class loader and resolved string dex cache array of classes. Should only be used on 1467 // classes in the image space. 1468 class UpdateClassLoaderAndResolvedStringsVisitor { 1469 public: 1470 UpdateClassLoaderAndResolvedStringsVisitor(gc::space::ImageSpace* space, 1471 mirror::ClassLoader* class_loader, 1472 bool forward_strings) 1473 : space_(space), 1474 class_loader_(class_loader), 1475 forward_strings_(forward_strings) {} 1476 1477 bool operator()(mirror::Class* klass) const SHARED_REQUIRES(Locks::mutator_lock_) { 1478 if (forward_strings_) { 1479 GcRoot<mirror::String>* strings = klass->GetDexCacheStrings(); 1480 if (strings != nullptr) { 1481 DCHECK( 1482 space_->GetImageHeader().GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains( 1483 reinterpret_cast<uint8_t*>(strings) - space_->Begin())) 1484 << "String dex cache array for " << PrettyClass(klass) << " is not in app image"; 1485 // Dex caches have already been updated, so take the strings pointer from there. 1486 GcRoot<mirror::String>* new_strings = klass->GetDexCache()->GetStrings(); 1487 DCHECK_NE(strings, new_strings); 1488 klass->SetDexCacheStrings(new_strings); 1489 } 1490 } 1491 // Finally, update class loader. 1492 klass->SetClassLoader(class_loader_); 1493 return true; 1494 } 1495 1496 gc::space::ImageSpace* const space_; 1497 mirror::ClassLoader* const class_loader_; 1498 const bool forward_strings_; 1499 }; 1500 1501 static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file, 1502 const char* location, 1503 std::string* error_msg) 1504 SHARED_REQUIRES(Locks::mutator_lock_) { 1505 DCHECK(error_msg != nullptr); 1506 std::unique_ptr<const DexFile> dex_file; 1507 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr); 1508 if (oat_dex_file == nullptr) { 1509 *error_msg = StringPrintf("Failed finding oat dex file for %s %s", 1510 oat_file->GetLocation().c_str(), 1511 location); 1512 return std::unique_ptr<const DexFile>(); 1513 } 1514 std::string inner_error_msg; 1515 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg); 1516 if (dex_file == nullptr) { 1517 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'", 1518 location, 1519 oat_file->GetLocation().c_str(), 1520 inner_error_msg.c_str()); 1521 return std::unique_ptr<const DexFile>(); 1522 } 1523 1524 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) { 1525 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x", 1526 location, 1527 dex_file->GetLocationChecksum(), 1528 oat_dex_file->GetDexFileLocationChecksum()); 1529 return std::unique_ptr<const DexFile>(); 1530 } 1531 return dex_file; 1532 } 1533 1534 bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space, 1535 std::vector<std::unique_ptr<const DexFile>>* out_dex_files, 1536 std::string* error_msg) { 1537 ScopedAssertNoThreadSuspension nts(Thread::Current(), __FUNCTION__); 1538 const ImageHeader& header = space->GetImageHeader(); 1539 mirror::Object* dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches); 1540 DCHECK(dex_caches_object != nullptr); 1541 mirror::ObjectArray<mirror::DexCache>* dex_caches = 1542 dex_caches_object->AsObjectArray<mirror::DexCache>(); 1543 const OatFile* oat_file = space->GetOatFile(); 1544 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 1545 mirror::DexCache* dex_cache = dex_caches->Get(i); 1546 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8()); 1547 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file, 1548 dex_file_location.c_str(), 1549 error_msg); 1550 if (dex_file == nullptr) { 1551 return false; 1552 } 1553 dex_cache->SetDexFile(dex_file.get()); 1554 out_dex_files->push_back(std::move(dex_file)); 1555 } 1556 return true; 1557 } 1558 1559 bool ClassLinker::AddImageSpace( 1560 gc::space::ImageSpace* space, 1561 Handle<mirror::ClassLoader> class_loader, 1562 jobjectArray dex_elements, 1563 const char* dex_location, 1564 std::vector<std::unique_ptr<const DexFile>>* out_dex_files, 1565 std::string* error_msg) { 1566 DCHECK(out_dex_files != nullptr); 1567 DCHECK(error_msg != nullptr); 1568 const uint64_t start_time = NanoTime(); 1569 const bool app_image = class_loader.Get() != nullptr; 1570 const ImageHeader& header = space->GetImageHeader(); 1571 mirror::Object* dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches); 1572 DCHECK(dex_caches_object != nullptr); 1573 Runtime* const runtime = Runtime::Current(); 1574 gc::Heap* const heap = runtime->GetHeap(); 1575 Thread* const self = Thread::Current(); 1576 StackHandleScope<2> hs(self); 1577 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches( 1578 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>())); 1579 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle( 1580 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>())); 1581 const OatFile* oat_file = space->GetOatFile(); 1582 std::unordered_set<mirror::ClassLoader*> image_class_loaders; 1583 // Check that the image is what we are expecting. 1584 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) { 1585 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu", 1586 static_cast<size_t>(space->GetImageHeader().GetPointerSize()), 1587 image_pointer_size_); 1588 return false; 1589 } 1590 DCHECK(class_roots.Get() != nullptr); 1591 if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) { 1592 *error_msg = StringPrintf("Expected %d class roots but got %d", 1593 class_roots->GetLength(), 1594 static_cast<int32_t>(kClassRootsMax)); 1595 return false; 1596 } 1597 // Check against existing class roots to make sure they match the ones in the boot image. 1598 for (size_t i = 0; i < kClassRootsMax; i++) { 1599 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) { 1600 *error_msg = "App image class roots must have pointer equality with runtime ones."; 1601 return false; 1602 } 1603 } 1604 if (oat_file->GetOatHeader().GetDexFileCount() != 1605 static_cast<uint32_t>(dex_caches->GetLength())) { 1606 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from " 1607 "image"; 1608 return false; 1609 } 1610 1611 StackHandleScope<1> hs2(self); 1612 MutableHandle<mirror::DexCache> h_dex_cache(hs2.NewHandle<mirror::DexCache>(nullptr)); 1613 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 1614 h_dex_cache.Assign(dex_caches->Get(i)); 1615 std::string dex_file_location(h_dex_cache->GetLocation()->ToModifiedUtf8()); 1616 // TODO: Only store qualified paths. 1617 // If non qualified, qualify it. 1618 if (dex_file_location.find('/') == std::string::npos) { 1619 std::string dex_location_path = dex_location; 1620 const size_t pos = dex_location_path.find_last_of('/'); 1621 CHECK_NE(pos, std::string::npos); 1622 dex_location_path = dex_location_path.substr(0, pos + 1); // Keep trailing '/' 1623 dex_file_location = dex_location_path + dex_file_location; 1624 } 1625 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file, 1626 dex_file_location.c_str(), 1627 error_msg); 1628 if (dex_file == nullptr) { 1629 return false; 1630 } 1631 1632 if (app_image) { 1633 // The current dex file field is bogus, overwrite it so that we can get the dex file in the 1634 // loop below. 1635 h_dex_cache->SetDexFile(dex_file.get()); 1636 // Check that each class loader resolved the same way. 1637 // TODO: Store image class loaders as image roots. 1638 GcRoot<mirror::Class>* const types = h_dex_cache->GetResolvedTypes(); 1639 for (int32_t j = 0, num_types = h_dex_cache->NumResolvedTypes(); j < num_types; j++) { 1640 mirror::Class* klass = types[j].Read(); 1641 if (klass != nullptr) { 1642 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError); 1643 mirror::ClassLoader* image_class_loader = klass->GetClassLoader(); 1644 image_class_loaders.insert(image_class_loader); 1645 } 1646 } 1647 } else { 1648 if (kSanityCheckObjects) { 1649 SanityCheckArtMethodPointerArray(h_dex_cache->GetResolvedMethods(), 1650 h_dex_cache->NumResolvedMethods(), 1651 image_pointer_size_, 1652 heap->GetBootImageSpaces()); 1653 } 1654 // Register dex files, keep track of existing ones that are conflicts. 1655 AppendToBootClassPath(*dex_file.get(), h_dex_cache); 1656 } 1657 out_dex_files->push_back(std::move(dex_file)); 1658 } 1659 1660 if (app_image) { 1661 ScopedObjectAccessUnchecked soa(Thread::Current()); 1662 // Check that the class loader resolves the same way as the ones in the image. 1663 // Image class loader [A][B][C][image dex files] 1664 // Class loader = [???][dex_elements][image dex files] 1665 // Need to ensure that [???][dex_elements] == [A][B][C]. 1666 // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic 1667 // for PathClassLoader does this by looping through the array of dex files. To ensure they 1668 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be, 1669 // and check that the dex file names are the same. 1670 for (mirror::ClassLoader* image_class_loader : image_class_loaders) { 1671 if (IsBootClassLoader(soa, image_class_loader)) { 1672 // The dex cache can reference types from the boot class loader. 1673 continue; 1674 } 1675 std::list<mirror::String*> image_dex_file_names; 1676 std::string temp_error_msg; 1677 if (!FlattenPathClassLoader(image_class_loader, &image_dex_file_names, &temp_error_msg)) { 1678 *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'", 1679 temp_error_msg.c_str()); 1680 return false; 1681 } 1682 std::list<mirror::String*> loader_dex_file_names; 1683 if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) { 1684 *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'", 1685 temp_error_msg.c_str()); 1686 return false; 1687 } 1688 // Add the temporary dex path list elements at the end. 1689 auto* elements = soa.Decode<mirror::ObjectArray<mirror::Object>*>(dex_elements); 1690 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) { 1691 mirror::Object* element = elements->GetWithoutChecks(i); 1692 if (element != nullptr) { 1693 // If we are somewhere in the middle of the array, there may be nulls at the end. 1694 loader_dex_file_names.push_back(GetDexPathListElementName(soa, element)); 1695 } 1696 } 1697 // Ignore the number of image dex files since we are adding those to the class loader anyways. 1698 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()), 1699 static_cast<size_t>(dex_caches->GetLength())); 1700 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength(); 1701 // Check that the dex file names match. 1702 bool equal = image_count == loader_dex_file_names.size(); 1703 if (equal) { 1704 auto it1 = image_dex_file_names.begin(); 1705 auto it2 = loader_dex_file_names.begin(); 1706 for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) { 1707 equal = equal && (*it1)->Equals(*it2); 1708 } 1709 } 1710 if (!equal) { 1711 VLOG(image) << "Image dex files " << image_dex_file_names.size(); 1712 for (mirror::String* name : image_dex_file_names) { 1713 VLOG(image) << name->ToModifiedUtf8(); 1714 } 1715 VLOG(image) << "Loader dex files " << loader_dex_file_names.size(); 1716 for (mirror::String* name : loader_dex_file_names) { 1717 VLOG(image) << name->ToModifiedUtf8(); 1718 } 1719 *error_msg = "Rejecting application image due to class loader mismatch"; 1720 // Ignore class loader mismatch for now since these would just use possibly incorrect 1721 // oat code anyways. The structural class check should be done in the parent. 1722 } 1723 } 1724 } 1725 1726 if (kSanityCheckObjects) { 1727 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 1728 auto* dex_cache = dex_caches->Get(i); 1729 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) { 1730 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_); 1731 if (field != nullptr) { 1732 CHECK(field->GetDeclaringClass()->GetClass() != nullptr); 1733 } 1734 } 1735 } 1736 if (!app_image) { 1737 heap->VisitObjects(SanityCheckObjectsCallback, nullptr); 1738 } 1739 } 1740 1741 // Set entry point to interpreter if in InterpretOnly mode. 1742 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) { 1743 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_); 1744 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_); 1745 } 1746 1747 ClassTable* class_table = nullptr; 1748 { 1749 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 1750 class_table = InsertClassTableForClassLoader(class_loader.Get()); 1751 } 1752 // If we have a class table section, read it and use it for verification in 1753 // UpdateAppImageClassLoadersAndDexCaches. 1754 ClassTable::ClassSet temp_set; 1755 const ImageSection& class_table_section = header.GetImageSection(ImageHeader::kSectionClassTable); 1756 const bool added_class_table = class_table_section.Size() > 0u; 1757 if (added_class_table) { 1758 const uint64_t start_time2 = NanoTime(); 1759 size_t read_count = 0; 1760 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(), 1761 /*make copy*/false, 1762 &read_count); 1763 if (!app_image) { 1764 dex_cache_boot_image_class_lookup_required_ = false; 1765 } 1766 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2); 1767 } 1768 if (app_image) { 1769 bool forward_dex_cache_arrays = false; 1770 if (!UpdateAppImageClassLoadersAndDexCaches(space, 1771 class_loader, 1772 dex_caches, 1773 added_class_table ? &temp_set : nullptr, 1774 /*out*/&forward_dex_cache_arrays, 1775 /*out*/error_msg)) { 1776 return false; 1777 } 1778 // Update class loader and resolved strings. If added_class_table is false, the resolved 1779 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches. 1780 UpdateClassLoaderAndResolvedStringsVisitor visitor(space, 1781 class_loader.Get(), 1782 forward_dex_cache_arrays); 1783 if (added_class_table) { 1784 for (GcRoot<mirror::Class>& root : temp_set) { 1785 visitor(root.Read()); 1786 } 1787 } 1788 // forward_dex_cache_arrays is true iff we copied all of the dex cache arrays into the .bss. 1789 // In this case, madvise away the dex cache arrays section of the image to reduce RAM usage and 1790 // mark as PROT_NONE to catch any invalid accesses. 1791 if (forward_dex_cache_arrays) { 1792 const ImageSection& dex_cache_section = header.GetImageSection( 1793 ImageHeader::kSectionDexCacheArrays); 1794 uint8_t* section_begin = AlignUp(space->Begin() + dex_cache_section.Offset(), kPageSize); 1795 uint8_t* section_end = AlignDown(space->Begin() + dex_cache_section.End(), kPageSize); 1796 if (section_begin < section_end) { 1797 madvise(section_begin, section_end - section_begin, MADV_DONTNEED); 1798 mprotect(section_begin, section_end - section_begin, PROT_NONE); 1799 VLOG(image) << "Released and protected dex cache array image section from " 1800 << reinterpret_cast<const void*>(section_begin) << "-" 1801 << reinterpret_cast<const void*>(section_end); 1802 } 1803 } 1804 } 1805 if (added_class_table) { 1806 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 1807 class_table->AddClassSet(std::move(temp_set)); 1808 } 1809 if (kIsDebugBuild && app_image) { 1810 // This verification needs to happen after the classes have been added to the class loader. 1811 // Since it ensures classes are in the class table. 1812 VerifyClassInTableArtMethodVisitor visitor2(class_table); 1813 header.VisitPackedArtMethods(&visitor2, space->Begin(), sizeof(void*)); 1814 } 1815 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time); 1816 return true; 1817 } 1818 1819 bool ClassLinker::ClassInClassTable(mirror::Class* klass) { 1820 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader()); 1821 return class_table != nullptr && class_table->Contains(klass); 1822 } 1823 1824 void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) { 1825 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since 1826 // enabling tracing requires the mutator lock, there are no race conditions here. 1827 const bool tracing_enabled = Trace::IsTracingEnabled(); 1828 Thread* const self = Thread::Current(); 1829 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 1830 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor( 1831 visitor, RootInfo(kRootStickyClass)); 1832 if ((flags & kVisitRootFlagAllRoots) != 0) { 1833 // Argument for how root visiting deals with ArtField and ArtMethod roots. 1834 // There is 3 GC cases to handle: 1835 // Non moving concurrent: 1836 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held 1837 // live by the class and class roots. 1838 // 1839 // Moving non-concurrent: 1840 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move. 1841 // To prevent missing roots, this case needs to ensure that there is no 1842 // suspend points between the point which we allocate ArtMethod arrays and place them in a 1843 // class which is in the class table. 1844 // 1845 // Moving concurrent: 1846 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are 1847 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy. 1848 boot_class_table_.VisitRoots(buffered_visitor); 1849 1850 // If tracing is enabled, then mark all the class loaders to prevent unloading. 1851 if (tracing_enabled) { 1852 for (const ClassLoaderData& data : class_loaders_) { 1853 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root))); 1854 root.VisitRoot(visitor, RootInfo(kRootVMInternal)); 1855 } 1856 } 1857 } else if ((flags & kVisitRootFlagNewRoots) != 0) { 1858 for (auto& root : new_class_roots_) { 1859 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>(); 1860 root.VisitRoot(visitor, RootInfo(kRootStickyClass)); 1861 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>(); 1862 // Concurrent moving GC marked new roots through the to-space invariant. 1863 CHECK_EQ(new_ref, old_ref); 1864 } 1865 } 1866 buffered_visitor.Flush(); // Flush before clearing new_class_roots_. 1867 if ((flags & kVisitRootFlagClearRootLog) != 0) { 1868 new_class_roots_.clear(); 1869 } 1870 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) { 1871 log_new_class_table_roots_ = true; 1872 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) { 1873 log_new_class_table_roots_ = false; 1874 } 1875 // We deliberately ignore the class roots in the image since we 1876 // handle image roots by using the MS/CMS rescanning of dirty cards. 1877 } 1878 1879 // Keep in sync with InitCallback. Anything we visit, we need to 1880 // reinit references to when reinitializing a ClassLinker from a 1881 // mapped image. 1882 void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) { 1883 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal)); 1884 VisitClassRoots(visitor, flags); 1885 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal)); 1886 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class 1887 // unloading if we are marking roots. 1888 DropFindArrayClassCache(); 1889 } 1890 1891 class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor { 1892 public: 1893 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor) 1894 : visitor_(visitor), 1895 done_(false) {} 1896 1897 void Visit(mirror::ClassLoader* class_loader) 1898 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE { 1899 ClassTable* const class_table = class_loader->GetClassTable(); 1900 if (!done_ && class_table != nullptr && !class_table->Visit(*visitor_)) { 1901 // If the visitor ClassTable returns false it means that we don't need to continue. 1902 done_ = true; 1903 } 1904 } 1905 1906 private: 1907 ClassVisitor* const visitor_; 1908 // If done is true then we don't need to do any more visiting. 1909 bool done_; 1910 }; 1911 1912 void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) { 1913 if (boot_class_table_.Visit(*visitor)) { 1914 VisitClassLoaderClassesVisitor loader_visitor(visitor); 1915 VisitClassLoaders(&loader_visitor); 1916 } 1917 } 1918 1919 void ClassLinker::VisitClasses(ClassVisitor* visitor) { 1920 if (dex_cache_boot_image_class_lookup_required_) { 1921 AddBootImageClassesToClassTable(); 1922 } 1923 Thread* const self = Thread::Current(); 1924 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 1925 // Not safe to have thread suspension when we are holding a lock. 1926 if (self != nullptr) { 1927 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__); 1928 VisitClassesInternal(visitor); 1929 } else { 1930 VisitClassesInternal(visitor); 1931 } 1932 } 1933 1934 class GetClassesInToVector : public ClassVisitor { 1935 public: 1936 bool operator()(mirror::Class* klass) OVERRIDE { 1937 classes_.push_back(klass); 1938 return true; 1939 } 1940 std::vector<mirror::Class*> classes_; 1941 }; 1942 1943 class GetClassInToObjectArray : public ClassVisitor { 1944 public: 1945 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr) 1946 : arr_(arr), index_(0) {} 1947 1948 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 1949 ++index_; 1950 if (index_ <= arr_->GetLength()) { 1951 arr_->Set(index_ - 1, klass); 1952 return true; 1953 } 1954 return false; 1955 } 1956 1957 bool Succeeded() const SHARED_REQUIRES(Locks::mutator_lock_) { 1958 return index_ <= arr_->GetLength(); 1959 } 1960 1961 private: 1962 mirror::ObjectArray<mirror::Class>* const arr_; 1963 int32_t index_; 1964 }; 1965 1966 void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) { 1967 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem 1968 // is avoiding duplicates. 1969 Thread* const self = Thread::Current(); 1970 if (!kMovingClasses) { 1971 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__); 1972 GetClassesInToVector accumulator; 1973 VisitClasses(&accumulator); 1974 for (mirror::Class* klass : accumulator.classes_) { 1975 if (!visitor->operator()(klass)) { 1976 return; 1977 } 1978 } 1979 } else { 1980 StackHandleScope<1> hs(self); 1981 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr); 1982 // We size the array assuming classes won't be added to the class table during the visit. 1983 // If this assumption fails we iterate again. 1984 while (true) { 1985 size_t class_table_size; 1986 { 1987 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 1988 // Add 100 in case new classes get loaded when we are filling in the object array. 1989 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100; 1990 } 1991 mirror::Class* class_type = mirror::Class::GetJavaLangClass(); 1992 mirror::Class* array_of_class = FindArrayClass(self, &class_type); 1993 classes.Assign( 1994 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size)); 1995 CHECK(classes.Get() != nullptr); // OOME. 1996 GetClassInToObjectArray accumulator(classes.Get()); 1997 VisitClasses(&accumulator); 1998 if (accumulator.Succeeded()) { 1999 break; 2000 } 2001 } 2002 for (int32_t i = 0; i < classes->GetLength(); ++i) { 2003 // If the class table shrank during creation of the clases array we expect null elements. If 2004 // the class table grew then the loop repeats. If classes are created after the loop has 2005 // finished then we don't visit. 2006 mirror::Class* klass = classes->Get(i); 2007 if (klass != nullptr && !visitor->operator()(klass)) { 2008 return; 2009 } 2010 } 2011 } 2012 } 2013 2014 ClassLinker::~ClassLinker() { 2015 mirror::Class::ResetClass(); 2016 mirror::Constructor::ResetClass(); 2017 mirror::Field::ResetClass(); 2018 mirror::Method::ResetClass(); 2019 mirror::Reference::ResetClass(); 2020 mirror::StackTraceElement::ResetClass(); 2021 mirror::String::ResetClass(); 2022 mirror::Throwable::ResetClass(); 2023 mirror::BooleanArray::ResetArrayClass(); 2024 mirror::ByteArray::ResetArrayClass(); 2025 mirror::CharArray::ResetArrayClass(); 2026 mirror::Constructor::ResetArrayClass(); 2027 mirror::DoubleArray::ResetArrayClass(); 2028 mirror::Field::ResetArrayClass(); 2029 mirror::FloatArray::ResetArrayClass(); 2030 mirror::Method::ResetArrayClass(); 2031 mirror::IntArray::ResetArrayClass(); 2032 mirror::LongArray::ResetArrayClass(); 2033 mirror::ShortArray::ResetArrayClass(); 2034 Thread* const self = Thread::Current(); 2035 for (const ClassLoaderData& data : class_loaders_) { 2036 DeleteClassLoader(self, data); 2037 } 2038 class_loaders_.clear(); 2039 } 2040 2041 void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) { 2042 Runtime* const runtime = Runtime::Current(); 2043 JavaVMExt* const vm = runtime->GetJavaVM(); 2044 vm->DeleteWeakGlobalRef(self, data.weak_root); 2045 // Notify the JIT that we need to remove the methods and/or profiling info. 2046 if (runtime->GetJit() != nullptr) { 2047 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache(); 2048 if (code_cache != nullptr) { 2049 code_cache->RemoveMethodsIn(self, *data.allocator); 2050 } 2051 } 2052 delete data.allocator; 2053 delete data.class_table; 2054 } 2055 2056 mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) { 2057 return down_cast<mirror::PointerArray*>(image_pointer_size_ == 8u ? 2058 static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length)) : 2059 static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length))); 2060 } 2061 2062 mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, 2063 const DexFile& dex_file, 2064 LinearAlloc* linear_alloc) { 2065 StackHandleScope<6> hs(self); 2066 auto dex_cache(hs.NewHandle(down_cast<mirror::DexCache*>( 2067 GetClassRoot(kJavaLangDexCache)->AllocObject(self)))); 2068 if (dex_cache.Get() == nullptr) { 2069 self->AssertPendingOOMException(); 2070 return nullptr; 2071 } 2072 auto location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str()))); 2073 if (location.Get() == nullptr) { 2074 self->AssertPendingOOMException(); 2075 return nullptr; 2076 } 2077 DexCacheArraysLayout layout(image_pointer_size_, &dex_file); 2078 uint8_t* raw_arrays = nullptr; 2079 if (dex_file.GetOatDexFile() != nullptr && 2080 dex_file.GetOatDexFile()->GetDexCacheArrays() != nullptr) { 2081 raw_arrays = dex_file.GetOatDexFile()->GetDexCacheArrays(); 2082 } else if (dex_file.NumStringIds() != 0u || dex_file.NumTypeIds() != 0u || 2083 dex_file.NumMethodIds() != 0u || dex_file.NumFieldIds() != 0u) { 2084 // NOTE: We "leak" the raw_arrays because we never destroy the dex cache. 2085 DCHECK(image_pointer_size_ == 4u || image_pointer_size_ == 8u); 2086 // Zero-initialized. 2087 raw_arrays = reinterpret_cast<uint8_t*>(linear_alloc->Alloc(self, layout.Size())); 2088 } 2089 GcRoot<mirror::String>* strings = (dex_file.NumStringIds() == 0u) ? nullptr : 2090 reinterpret_cast<GcRoot<mirror::String>*>(raw_arrays + layout.StringsOffset()); 2091 GcRoot<mirror::Class>* types = (dex_file.NumTypeIds() == 0u) ? nullptr : 2092 reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset()); 2093 ArtMethod** methods = (dex_file.NumMethodIds() == 0u) ? nullptr : 2094 reinterpret_cast<ArtMethod**>(raw_arrays + layout.MethodsOffset()); 2095 ArtField** fields = (dex_file.NumFieldIds() == 0u) ? nullptr : 2096 reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset()); 2097 if (kIsDebugBuild) { 2098 // Sanity check to make sure all the dex cache arrays are empty. b/28992179 2099 for (size_t i = 0; i < dex_file.NumStringIds(); ++i) { 2100 CHECK(strings[i].Read<kWithoutReadBarrier>() == nullptr); 2101 } 2102 for (size_t i = 0; i < dex_file.NumTypeIds(); ++i) { 2103 CHECK(types[i].Read<kWithoutReadBarrier>() == nullptr); 2104 } 2105 for (size_t i = 0; i < dex_file.NumMethodIds(); ++i) { 2106 CHECK(mirror::DexCache::GetElementPtrSize(methods, i, image_pointer_size_) == nullptr); 2107 } 2108 for (size_t i = 0; i < dex_file.NumFieldIds(); ++i) { 2109 CHECK(mirror::DexCache::GetElementPtrSize(fields, i, image_pointer_size_) == nullptr); 2110 } 2111 } 2112 dex_cache->Init(&dex_file, 2113 location.Get(), 2114 strings, 2115 dex_file.NumStringIds(), 2116 types, 2117 dex_file.NumTypeIds(), 2118 methods, 2119 dex_file.NumMethodIds(), 2120 fields, 2121 dex_file.NumFieldIds(), 2122 image_pointer_size_); 2123 return dex_cache.Get(); 2124 } 2125 2126 mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class, 2127 uint32_t class_size) { 2128 DCHECK_GE(class_size, sizeof(mirror::Class)); 2129 gc::Heap* heap = Runtime::Current()->GetHeap(); 2130 mirror::Class::InitializeClassVisitor visitor(class_size); 2131 mirror::Object* k = kMovingClasses ? 2132 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) : 2133 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor); 2134 if (UNLIKELY(k == nullptr)) { 2135 self->AssertPendingOOMException(); 2136 return nullptr; 2137 } 2138 return k->AsClass(); 2139 } 2140 2141 mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) { 2142 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size); 2143 } 2144 2145 mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray( 2146 Thread* self, 2147 size_t length) { 2148 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc( 2149 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length); 2150 } 2151 2152 mirror::Class* ClassLinker::EnsureResolved(Thread* self, 2153 const char* descriptor, 2154 mirror::Class* klass) { 2155 DCHECK(klass != nullptr); 2156 2157 // For temporary classes we must wait for them to be retired. 2158 if (init_done_ && klass->IsTemp()) { 2159 CHECK(!klass->IsResolved()); 2160 if (klass->IsErroneous()) { 2161 ThrowEarlierClassFailure(klass); 2162 return nullptr; 2163 } 2164 StackHandleScope<1> hs(self); 2165 Handle<mirror::Class> h_class(hs.NewHandle(klass)); 2166 ObjectLock<mirror::Class> lock(self, h_class); 2167 // Loop and wait for the resolving thread to retire this class. 2168 while (!h_class->IsRetired() && !h_class->IsErroneous()) { 2169 lock.WaitIgnoringInterrupts(); 2170 } 2171 if (h_class->IsErroneous()) { 2172 ThrowEarlierClassFailure(h_class.Get()); 2173 return nullptr; 2174 } 2175 CHECK(h_class->IsRetired()); 2176 // Get the updated class from class table. 2177 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), 2178 h_class.Get()->GetClassLoader()); 2179 } 2180 2181 // Wait for the class if it has not already been linked. 2182 size_t index = 0; 2183 // Maximum number of yield iterations until we start sleeping. 2184 static const size_t kNumYieldIterations = 1000; 2185 // How long each sleep is in us. 2186 static const size_t kSleepDurationUS = 1000; // 1 ms. 2187 while (!klass->IsResolved() && !klass->IsErroneous()) { 2188 StackHandleScope<1> hs(self); 2189 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass)); 2190 { 2191 ObjectTryLock<mirror::Class> lock(self, h_class); 2192 // Can not use a monitor wait here since it may block when returning and deadlock if another 2193 // thread has locked klass. 2194 if (lock.Acquired()) { 2195 // Check for circular dependencies between classes, the lock is required for SetStatus. 2196 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) { 2197 ThrowClassCircularityError(h_class.Get()); 2198 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self); 2199 return nullptr; 2200 } 2201 } 2202 } 2203 { 2204 // Handle wrapper deals with klass moving. 2205 ScopedThreadSuspension sts(self, kSuspended); 2206 if (index < kNumYieldIterations) { 2207 sched_yield(); 2208 } else { 2209 usleep(kSleepDurationUS); 2210 } 2211 } 2212 ++index; 2213 } 2214 2215 if (klass->IsErroneous()) { 2216 ThrowEarlierClassFailure(klass); 2217 return nullptr; 2218 } 2219 // Return the loaded class. No exceptions should be pending. 2220 CHECK(klass->IsResolved()) << PrettyClass(klass); 2221 self->AssertNoPendingException(); 2222 return klass; 2223 } 2224 2225 typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry; 2226 2227 // Search a collection of DexFiles for a descriptor 2228 ClassPathEntry FindInClassPath(const char* descriptor, 2229 size_t hash, const std::vector<const DexFile*>& class_path) { 2230 for (const DexFile* dex_file : class_path) { 2231 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash); 2232 if (dex_class_def != nullptr) { 2233 return ClassPathEntry(dex_file, dex_class_def); 2234 } 2235 } 2236 return ClassPathEntry(nullptr, nullptr); 2237 } 2238 2239 bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa, 2240 Thread* self, 2241 const char* descriptor, 2242 size_t hash, 2243 Handle<mirror::ClassLoader> class_loader, 2244 mirror::Class** result) { 2245 // Termination case: boot class-loader. 2246 if (IsBootClassLoader(soa, class_loader.Get())) { 2247 // The boot class loader, search the boot class path. 2248 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_); 2249 if (pair.second != nullptr) { 2250 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr); 2251 if (klass != nullptr) { 2252 *result = EnsureResolved(self, descriptor, klass); 2253 } else { 2254 *result = DefineClass(self, 2255 descriptor, 2256 hash, 2257 ScopedNullHandle<mirror::ClassLoader>(), 2258 *pair.first, 2259 *pair.second); 2260 } 2261 if (*result == nullptr) { 2262 CHECK(self->IsExceptionPending()) << descriptor; 2263 self->ClearException(); 2264 } 2265 } else { 2266 *result = nullptr; 2267 } 2268 return true; 2269 } 2270 2271 // Unsupported class-loader? 2272 if (class_loader->GetClass() != 2273 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) { 2274 *result = nullptr; 2275 return false; 2276 } 2277 2278 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension). 2279 StackHandleScope<4> hs(self); 2280 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent())); 2281 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result); 2282 2283 if (!recursive_result) { 2284 // Something wrong up the chain. 2285 return false; 2286 } 2287 2288 if (*result != nullptr) { 2289 // Found the class up the chain. 2290 return true; 2291 } 2292 2293 // Handle this step. 2294 // Handle as if this is the child PathClassLoader. 2295 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader. 2296 // We need to get the DexPathList and loop through it. 2297 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie); 2298 ArtField* const dex_file_field = 2299 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile); 2300 mirror::Object* dex_path_list = 2301 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)-> 2302 GetObject(class_loader.Get()); 2303 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) { 2304 // DexPathList has an array dexElements of Elements[] which each contain a dex file. 2305 mirror::Object* dex_elements_obj = 2306 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)-> 2307 GetObject(dex_path_list); 2308 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look 2309 // at the mCookie which is a DexFile vector. 2310 if (dex_elements_obj != nullptr) { 2311 Handle<mirror::ObjectArray<mirror::Object>> dex_elements = 2312 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()); 2313 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) { 2314 mirror::Object* element = dex_elements->GetWithoutChecks(i); 2315 if (element == nullptr) { 2316 // Should never happen, fall back to java code to throw a NPE. 2317 break; 2318 } 2319 mirror::Object* dex_file = dex_file_field->GetObject(element); 2320 if (dex_file != nullptr) { 2321 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray(); 2322 if (long_array == nullptr) { 2323 // This should never happen so log a warning. 2324 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor; 2325 break; 2326 } 2327 int32_t long_array_size = long_array->GetLength(); 2328 // First element is the oat file. 2329 for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) { 2330 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>( 2331 long_array->GetWithoutChecks(j))); 2332 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash); 2333 if (dex_class_def != nullptr) { 2334 mirror::Class* klass = DefineClass(self, 2335 descriptor, 2336 hash, 2337 class_loader, 2338 *cp_dex_file, 2339 *dex_class_def); 2340 if (klass == nullptr) { 2341 CHECK(self->IsExceptionPending()) << descriptor; 2342 self->ClearException(); 2343 // TODO: Is it really right to break here, and not check the other dex files? 2344 return true; 2345 } 2346 *result = klass; 2347 return true; 2348 } 2349 } 2350 } 2351 } 2352 } 2353 self->AssertNoPendingException(); 2354 } 2355 2356 // Result is still null from the parent call, no need to set it again... 2357 return true; 2358 } 2359 2360 mirror::Class* ClassLinker::FindClass(Thread* self, 2361 const char* descriptor, 2362 Handle<mirror::ClassLoader> class_loader) { 2363 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string"; 2364 DCHECK(self != nullptr); 2365 self->AssertNoPendingException(); 2366 if (descriptor[1] == '\0') { 2367 // only the descriptors of primitive types should be 1 character long, also avoid class lookup 2368 // for primitive classes that aren't backed by dex files. 2369 return FindPrimitiveClass(descriptor[0]); 2370 } 2371 const size_t hash = ComputeModifiedUtf8Hash(descriptor); 2372 // Find the class in the loaded classes table. 2373 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get()); 2374 if (klass != nullptr) { 2375 return EnsureResolved(self, descriptor, klass); 2376 } 2377 // Class is not yet loaded. 2378 if (descriptor[0] == '[') { 2379 return CreateArrayClass(self, descriptor, hash, class_loader); 2380 } else if (class_loader.Get() == nullptr) { 2381 // The boot class loader, search the boot class path. 2382 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_); 2383 if (pair.second != nullptr) { 2384 return DefineClass(self, 2385 descriptor, 2386 hash, 2387 ScopedNullHandle<mirror::ClassLoader>(), 2388 *pair.first, 2389 *pair.second); 2390 } else { 2391 // The boot class loader is searched ahead of the application class loader, failures are 2392 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to 2393 // trigger the chaining with a proper stack trace. 2394 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError(); 2395 self->SetException(pre_allocated); 2396 return nullptr; 2397 } 2398 } else { 2399 ScopedObjectAccessUnchecked soa(self); 2400 mirror::Class* cp_klass; 2401 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) { 2402 // The chain was understood. So the value in cp_klass is either the class we were looking 2403 // for, or not found. 2404 if (cp_klass != nullptr) { 2405 return cp_klass; 2406 } 2407 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this 2408 // and the branch above. TODO: throw the right exception here. 2409 2410 // We'll let the Java-side rediscover all this and throw the exception with the right stack 2411 // trace. 2412 } 2413 2414 if (Runtime::Current()->IsAotCompiler()) { 2415 // Oops, compile-time, can't run actual class-loader code. 2416 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError(); 2417 self->SetException(pre_allocated); 2418 return nullptr; 2419 } 2420 2421 ScopedLocalRef<jobject> class_loader_object(soa.Env(), 2422 soa.AddLocalReference<jobject>(class_loader.Get())); 2423 std::string class_name_string(DescriptorToDot(descriptor)); 2424 ScopedLocalRef<jobject> result(soa.Env(), nullptr); 2425 { 2426 ScopedThreadStateChange tsc(self, kNative); 2427 ScopedLocalRef<jobject> class_name_object(soa.Env(), 2428 soa.Env()->NewStringUTF(class_name_string.c_str())); 2429 if (class_name_object.get() == nullptr) { 2430 DCHECK(self->IsExceptionPending()); // OOME. 2431 return nullptr; 2432 } 2433 CHECK(class_loader_object.get() != nullptr); 2434 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(), 2435 WellKnownClasses::java_lang_ClassLoader_loadClass, 2436 class_name_object.get())); 2437 } 2438 if (self->IsExceptionPending()) { 2439 // If the ClassLoader threw, pass that exception up. 2440 return nullptr; 2441 } else if (result.get() == nullptr) { 2442 // broken loader - throw NPE to be compatible with Dalvik 2443 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s", 2444 class_name_string.c_str()).c_str()); 2445 return nullptr; 2446 } else { 2447 // success, return mirror::Class* 2448 return soa.Decode<mirror::Class*>(result.get()); 2449 } 2450 } 2451 UNREACHABLE(); 2452 } 2453 2454 mirror::Class* ClassLinker::DefineClass(Thread* self, 2455 const char* descriptor, 2456 size_t hash, 2457 Handle<mirror::ClassLoader> class_loader, 2458 const DexFile& dex_file, 2459 const DexFile::ClassDef& dex_class_def) { 2460 StackHandleScope<3> hs(self); 2461 auto klass = hs.NewHandle<mirror::Class>(nullptr); 2462 2463 // Load the class from the dex file. 2464 if (UNLIKELY(!init_done_)) { 2465 // finish up init of hand crafted class_roots_ 2466 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) { 2467 klass.Assign(GetClassRoot(kJavaLangObject)); 2468 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) { 2469 klass.Assign(GetClassRoot(kJavaLangClass)); 2470 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) { 2471 klass.Assign(GetClassRoot(kJavaLangString)); 2472 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) { 2473 klass.Assign(GetClassRoot(kJavaLangRefReference)); 2474 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) { 2475 klass.Assign(GetClassRoot(kJavaLangDexCache)); 2476 } 2477 } 2478 2479 if (klass.Get() == nullptr) { 2480 // Allocate a class with the status of not ready. 2481 // Interface object should get the right size here. Regular class will 2482 // figure out the right size later and be replaced with one of the right 2483 // size when the class becomes resolved. 2484 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def))); 2485 } 2486 if (UNLIKELY(klass.Get() == nullptr)) { 2487 self->AssertPendingOOMException(); 2488 return nullptr; 2489 } 2490 mirror::DexCache* dex_cache = RegisterDexFile(dex_file, class_loader.Get()); 2491 if (dex_cache == nullptr) { 2492 self->AssertPendingOOMException(); 2493 return nullptr; 2494 } 2495 klass->SetDexCache(dex_cache); 2496 SetupClass(dex_file, dex_class_def, klass, class_loader.Get()); 2497 2498 // Mark the string class by setting its access flag. 2499 if (UNLIKELY(!init_done_)) { 2500 if (strcmp(descriptor, "Ljava/lang/String;") == 0) { 2501 klass->SetStringClass(); 2502 } 2503 } 2504 2505 ObjectLock<mirror::Class> lock(self, klass); 2506 klass->SetClinitThreadId(self->GetTid()); 2507 2508 // Add the newly loaded class to the loaded classes table. 2509 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash); 2510 if (existing != nullptr) { 2511 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause 2512 // this thread to block. 2513 return EnsureResolved(self, descriptor, existing); 2514 } 2515 2516 // Load the fields and other things after we are inserted in the table. This is so that we don't 2517 // end up allocating unfree-able linear alloc resources and then lose the race condition. The 2518 // other reason is that the field roots are only visited from the class table. So we need to be 2519 // inserted before we allocate / fill in these fields. 2520 LoadClass(self, dex_file, dex_class_def, klass); 2521 if (self->IsExceptionPending()) { 2522 VLOG(class_linker) << self->GetException()->Dump(); 2523 // An exception occured during load, set status to erroneous while holding klass' lock in case 2524 // notification is necessary. 2525 if (!klass->IsErroneous()) { 2526 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 2527 } 2528 return nullptr; 2529 } 2530 2531 // Finish loading (if necessary) by finding parents 2532 CHECK(!klass->IsLoaded()); 2533 if (!LoadSuperAndInterfaces(klass, dex_file)) { 2534 // Loading failed. 2535 if (!klass->IsErroneous()) { 2536 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 2537 } 2538 return nullptr; 2539 } 2540 CHECK(klass->IsLoaded()); 2541 // Link the class (if necessary) 2542 CHECK(!klass->IsResolved()); 2543 // TODO: Use fast jobjects? 2544 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr); 2545 2546 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr); 2547 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) { 2548 // Linking failed. 2549 if (!klass->IsErroneous()) { 2550 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 2551 } 2552 return nullptr; 2553 } 2554 self->AssertNoPendingException(); 2555 CHECK(h_new_class.Get() != nullptr) << descriptor; 2556 CHECK(h_new_class->IsResolved()) << descriptor; 2557 2558 // Instrumentation may have updated entrypoints for all methods of all 2559 // classes. However it could not update methods of this class while we 2560 // were loading it. Now the class is resolved, we can update entrypoints 2561 // as required by instrumentation. 2562 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) { 2563 // We must be in the kRunnable state to prevent instrumentation from 2564 // suspending all threads to update entrypoints while we are doing it 2565 // for this class. 2566 DCHECK_EQ(self->GetState(), kRunnable); 2567 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get()); 2568 } 2569 2570 /* 2571 * We send CLASS_PREPARE events to the debugger from here. The 2572 * definition of "preparation" is creating the static fields for a 2573 * class and initializing them to the standard default values, but not 2574 * executing any code (that comes later, during "initialization"). 2575 * 2576 * We did the static preparation in LinkClass. 2577 * 2578 * The class has been prepared and resolved but possibly not yet verified 2579 * at this point. 2580 */ 2581 Dbg::PostClassPrepare(h_new_class.Get()); 2582 2583 // Notify native debugger of the new class and its layout. 2584 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get()); 2585 2586 return h_new_class.Get(); 2587 } 2588 2589 uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file, 2590 const DexFile::ClassDef& dex_class_def) { 2591 const uint8_t* class_data = dex_file.GetClassData(dex_class_def); 2592 size_t num_ref = 0; 2593 size_t num_8 = 0; 2594 size_t num_16 = 0; 2595 size_t num_32 = 0; 2596 size_t num_64 = 0; 2597 if (class_data != nullptr) { 2598 // We allow duplicate definitions of the same field in a class_data_item 2599 // but ignore the repeated indexes here, b/21868015. 2600 uint32_t last_field_idx = DexFile::kDexNoIndex; 2601 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) { 2602 uint32_t field_idx = it.GetMemberIndex(); 2603 // Ordering enforced by DexFileVerifier. 2604 DCHECK(last_field_idx == DexFile::kDexNoIndex || last_field_idx <= field_idx); 2605 if (UNLIKELY(field_idx == last_field_idx)) { 2606 continue; 2607 } 2608 last_field_idx = field_idx; 2609 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 2610 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id); 2611 char c = descriptor[0]; 2612 switch (c) { 2613 case 'L': 2614 case '[': 2615 num_ref++; 2616 break; 2617 case 'J': 2618 case 'D': 2619 num_64++; 2620 break; 2621 case 'I': 2622 case 'F': 2623 num_32++; 2624 break; 2625 case 'S': 2626 case 'C': 2627 num_16++; 2628 break; 2629 case 'B': 2630 case 'Z': 2631 num_8++; 2632 break; 2633 default: 2634 LOG(FATAL) << "Unknown descriptor: " << c; 2635 UNREACHABLE(); 2636 } 2637 } 2638 } 2639 return mirror::Class::ComputeClassSize(false, 2640 0, 2641 num_8, 2642 num_16, 2643 num_32, 2644 num_64, 2645 num_ref, 2646 image_pointer_size_); 2647 } 2648 2649 OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, 2650 uint16_t class_def_idx, 2651 bool* found) { 2652 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16); 2653 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile(); 2654 if (oat_dex_file == nullptr) { 2655 *found = false; 2656 return OatFile::OatClass::Invalid(); 2657 } 2658 *found = true; 2659 return oat_dex_file->GetOatClass(class_def_idx); 2660 } 2661 2662 static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, 2663 uint16_t class_def_idx, 2664 uint32_t method_idx) { 2665 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx); 2666 const uint8_t* class_data = dex_file.GetClassData(class_def); 2667 CHECK(class_data != nullptr); 2668 ClassDataItemIterator it(dex_file, class_data); 2669 // Skip fields 2670 while (it.HasNextStaticField()) { 2671 it.Next(); 2672 } 2673 while (it.HasNextInstanceField()) { 2674 it.Next(); 2675 } 2676 // Process methods 2677 size_t class_def_method_index = 0; 2678 while (it.HasNextDirectMethod()) { 2679 if (it.GetMemberIndex() == method_idx) { 2680 return class_def_method_index; 2681 } 2682 class_def_method_index++; 2683 it.Next(); 2684 } 2685 while (it.HasNextVirtualMethod()) { 2686 if (it.GetMemberIndex() == method_idx) { 2687 return class_def_method_index; 2688 } 2689 class_def_method_index++; 2690 it.Next(); 2691 } 2692 DCHECK(!it.HasNext()); 2693 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation(); 2694 UNREACHABLE(); 2695 } 2696 2697 const OatFile::OatMethod ClassLinker::FindOatMethodFor(ArtMethod* method, bool* found) { 2698 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution 2699 // method for direct methods (or virtual methods made direct). 2700 mirror::Class* declaring_class = method->GetDeclaringClass(); 2701 size_t oat_method_index; 2702 if (method->IsStatic() || method->IsDirect()) { 2703 // Simple case where the oat method index was stashed at load time. 2704 oat_method_index = method->GetMethodIndex(); 2705 } else { 2706 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index 2707 // by search for its position in the declared virtual methods. 2708 oat_method_index = declaring_class->NumDirectMethods(); 2709 bool found_virtual = false; 2710 for (ArtMethod& art_method : declaring_class->GetVirtualMethods(image_pointer_size_)) { 2711 // Check method index instead of identity in case of duplicate method definitions. 2712 if (method->GetDexMethodIndex() == art_method.GetDexMethodIndex()) { 2713 found_virtual = true; 2714 break; 2715 } 2716 oat_method_index++; 2717 } 2718 CHECK(found_virtual) << "Didn't find oat method index for virtual method: " 2719 << PrettyMethod(method); 2720 } 2721 DCHECK_EQ(oat_method_index, 2722 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(), 2723 method->GetDeclaringClass()->GetDexClassDefIndex(), 2724 method->GetDexMethodIndex())); 2725 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(), 2726 declaring_class->GetDexClassDefIndex(), 2727 found); 2728 if (!(*found)) { 2729 return OatFile::OatMethod::Invalid(); 2730 } 2731 return oat_class.GetOatMethod(oat_method_index); 2732 } 2733 2734 // Special case to get oat code without overwriting a trampoline. 2735 const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) { 2736 CHECK(method->IsInvokable()) << PrettyMethod(method); 2737 if (method->IsProxyMethod()) { 2738 return GetQuickProxyInvokeHandler(); 2739 } 2740 bool found; 2741 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found); 2742 if (found) { 2743 auto* code = oat_method.GetQuickCode(); 2744 if (code != nullptr) { 2745 return code; 2746 } 2747 } 2748 if (method->IsNative()) { 2749 // No code and native? Use generic trampoline. 2750 return GetQuickGenericJniStub(); 2751 } 2752 return GetQuickToInterpreterBridge(); 2753 } 2754 2755 const void* ClassLinker::GetOatMethodQuickCodeFor(ArtMethod* method) { 2756 if (method->IsNative() || !method->IsInvokable() || method->IsProxyMethod()) { 2757 return nullptr; 2758 } 2759 bool found; 2760 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found); 2761 if (found) { 2762 return oat_method.GetQuickCode(); 2763 } 2764 return nullptr; 2765 } 2766 2767 bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) { 2768 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) { 2769 return false; 2770 } 2771 2772 if (quick_code == nullptr) { 2773 return true; 2774 } 2775 2776 Runtime* runtime = Runtime::Current(); 2777 instrumentation::Instrumentation* instr = runtime->GetInstrumentation(); 2778 if (instr->InterpretOnly()) { 2779 return true; 2780 } 2781 2782 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) { 2783 // Doing this check avoids doing compiled/interpreter transitions. 2784 return true; 2785 } 2786 2787 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) { 2788 // Force the use of interpreter when it is required by the debugger. 2789 return true; 2790 } 2791 2792 if (runtime->IsNativeDebuggable()) { 2793 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse()); 2794 // If we are doing native debugging, ignore application's AOT code, 2795 // since we want to JIT it with extra stackmaps for native debugging. 2796 // On the other hand, keep all AOT code from the boot image, since the 2797 // blocking JIT would results in non-negligible performance impact. 2798 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code); 2799 } 2800 2801 if (Dbg::IsDebuggerActive()) { 2802 // Boot image classes may be AOT-compiled as non-debuggable. 2803 // This is not suitable for the Java debugger, so ignore the AOT code. 2804 return runtime->GetHeap()->IsInBootImageOatFile(quick_code); 2805 } 2806 2807 return false; 2808 } 2809 2810 void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) { 2811 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass); 2812 if (klass->NumDirectMethods() == 0) { 2813 return; // No direct methods => no static methods. 2814 } 2815 Runtime* runtime = Runtime::Current(); 2816 if (!runtime->IsStarted()) { 2817 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) { 2818 return; // OAT file unavailable. 2819 } 2820 } 2821 2822 const DexFile& dex_file = klass->GetDexFile(); 2823 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 2824 CHECK(dex_class_def != nullptr); 2825 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def); 2826 // There should always be class data if there were direct methods. 2827 CHECK(class_data != nullptr) << PrettyDescriptor(klass); 2828 ClassDataItemIterator it(dex_file, class_data); 2829 // Skip fields 2830 while (it.HasNextStaticField()) { 2831 it.Next(); 2832 } 2833 while (it.HasNextInstanceField()) { 2834 it.Next(); 2835 } 2836 bool has_oat_class; 2837 OatFile::OatClass oat_class = FindOatClass(dex_file, 2838 klass->GetDexClassDefIndex(), 2839 &has_oat_class); 2840 // Link the code of methods skipped by LinkCode. 2841 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) { 2842 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_); 2843 if (!method->IsStatic()) { 2844 // Only update static methods. 2845 continue; 2846 } 2847 const void* quick_code = nullptr; 2848 if (has_oat_class) { 2849 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index); 2850 quick_code = oat_method.GetQuickCode(); 2851 } 2852 // Check whether the method is native, in which case it's generic JNI. 2853 if (quick_code == nullptr && method->IsNative()) { 2854 quick_code = GetQuickGenericJniStub(); 2855 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) { 2856 // Use interpreter entry point. 2857 quick_code = GetQuickToInterpreterBridge(); 2858 } 2859 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code); 2860 } 2861 // Ignore virtual methods on the iterator. 2862 } 2863 2864 void ClassLinker::EnsureThrowsInvocationError(ArtMethod* method) { 2865 DCHECK(method != nullptr); 2866 DCHECK(!method->IsInvokable()); 2867 method->SetEntryPointFromQuickCompiledCodePtrSize(quick_to_interpreter_bridge_trampoline_, 2868 image_pointer_size_); 2869 } 2870 2871 void ClassLinker::LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class, 2872 uint32_t class_def_method_index) { 2873 Runtime* const runtime = Runtime::Current(); 2874 if (runtime->IsAotCompiler()) { 2875 // The following code only applies to a non-compiler runtime. 2876 return; 2877 } 2878 // Method shouldn't have already been linked. 2879 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr); 2880 if (oat_class != nullptr) { 2881 // Every kind of method should at least get an invoke stub from the oat_method. 2882 // non-abstract methods also get their code pointers. 2883 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index); 2884 oat_method.LinkMethod(method); 2885 } 2886 2887 // Install entry point from interpreter. 2888 const void* quick_code = method->GetEntryPointFromQuickCompiledCode(); 2889 bool enter_interpreter = ShouldUseInterpreterEntrypoint(method, quick_code); 2890 2891 if (!method->IsInvokable()) { 2892 EnsureThrowsInvocationError(method); 2893 return; 2894 } 2895 2896 if (method->IsStatic() && !method->IsConstructor()) { 2897 // For static methods excluding the class initializer, install the trampoline. 2898 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines 2899 // after initializing class (see ClassLinker::InitializeClass method). 2900 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub()); 2901 } else if (quick_code == nullptr && method->IsNative()) { 2902 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub()); 2903 } else if (enter_interpreter) { 2904 // Set entry point from compiled code if there's no code or in interpreter only mode. 2905 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 2906 } 2907 2908 if (method->IsNative()) { 2909 // Unregistering restores the dlsym lookup stub. 2910 method->UnregisterNative(); 2911 2912 if (enter_interpreter || quick_code == nullptr) { 2913 // We have a native method here without code. Then it should have either the generic JNI 2914 // trampoline as entrypoint (non-static), or the resolution trampoline (static). 2915 // TODO: this doesn't handle all the cases where trampolines may be installed. 2916 const void* entry_point = method->GetEntryPointFromQuickCompiledCode(); 2917 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point)); 2918 } 2919 } 2920 } 2921 2922 void ClassLinker::SetupClass(const DexFile& dex_file, 2923 const DexFile::ClassDef& dex_class_def, 2924 Handle<mirror::Class> klass, 2925 mirror::ClassLoader* class_loader) { 2926 CHECK(klass.Get() != nullptr); 2927 CHECK(klass->GetDexCache() != nullptr); 2928 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus()); 2929 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def); 2930 CHECK(descriptor != nullptr); 2931 2932 klass->SetClass(GetClassRoot(kJavaLangClass)); 2933 uint32_t access_flags = dex_class_def.GetJavaAccessFlags(); 2934 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U); 2935 klass->SetAccessFlags(access_flags); 2936 klass->SetClassLoader(class_loader); 2937 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 2938 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr); 2939 2940 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def)); 2941 klass->SetDexTypeIndex(dex_class_def.class_idx_); 2942 CHECK(klass->GetDexCacheStrings() != nullptr); 2943 } 2944 2945 void ClassLinker::LoadClass(Thread* self, 2946 const DexFile& dex_file, 2947 const DexFile::ClassDef& dex_class_def, 2948 Handle<mirror::Class> klass) { 2949 const uint8_t* class_data = dex_file.GetClassData(dex_class_def); 2950 if (class_data == nullptr) { 2951 return; // no fields or methods - for example a marker interface 2952 } 2953 bool has_oat_class = false; 2954 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) { 2955 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), 2956 &has_oat_class); 2957 if (has_oat_class) { 2958 LoadClassMembers(self, dex_file, class_data, klass, &oat_class); 2959 } 2960 } 2961 if (!has_oat_class) { 2962 LoadClassMembers(self, dex_file, class_data, klass, nullptr); 2963 } 2964 } 2965 2966 LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self, 2967 LinearAlloc* allocator, 2968 size_t length) { 2969 if (length == 0) { 2970 return nullptr; 2971 } 2972 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>. 2973 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4."); 2974 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length); 2975 void* array_storage = allocator->Alloc(self, storage_size); 2976 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length); 2977 CHECK(ret != nullptr); 2978 std::uninitialized_fill_n(&ret->At(0), length, ArtField()); 2979 return ret; 2980 } 2981 2982 LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self, 2983 LinearAlloc* allocator, 2984 size_t length) { 2985 if (length == 0) { 2986 return nullptr; 2987 } 2988 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_); 2989 const size_t method_size = ArtMethod::Size(image_pointer_size_); 2990 const size_t storage_size = 2991 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment); 2992 void* array_storage = allocator->Alloc(self, storage_size); 2993 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length); 2994 CHECK(ret != nullptr); 2995 for (size_t i = 0; i < length; ++i) { 2996 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod; 2997 } 2998 return ret; 2999 } 3000 3001 LinearAlloc* ClassLinker::GetAllocatorForClassLoader(mirror::ClassLoader* class_loader) { 3002 if (class_loader == nullptr) { 3003 return Runtime::Current()->GetLinearAlloc(); 3004 } 3005 LinearAlloc* allocator = class_loader->GetAllocator(); 3006 DCHECK(allocator != nullptr); 3007 return allocator; 3008 } 3009 3010 LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(mirror::ClassLoader* class_loader) { 3011 if (class_loader == nullptr) { 3012 return Runtime::Current()->GetLinearAlloc(); 3013 } 3014 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3015 LinearAlloc* allocator = class_loader->GetAllocator(); 3016 if (allocator == nullptr) { 3017 RegisterClassLoader(class_loader); 3018 allocator = class_loader->GetAllocator(); 3019 CHECK(allocator != nullptr); 3020 } 3021 return allocator; 3022 } 3023 3024 void ClassLinker::LoadClassMembers(Thread* self, 3025 const DexFile& dex_file, 3026 const uint8_t* class_data, 3027 Handle<mirror::Class> klass, 3028 const OatFile::OatClass* oat_class) { 3029 { 3030 // Note: We cannot have thread suspension until the field and method arrays are setup or else 3031 // Class::VisitFieldRoots may miss some fields or methods. 3032 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__); 3033 // Load static fields. 3034 // We allow duplicate definitions of the same field in a class_data_item 3035 // but ignore the repeated indexes here, b/21868015. 3036 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader()); 3037 ClassDataItemIterator it(dex_file, class_data); 3038 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, 3039 allocator, 3040 it.NumStaticFields()); 3041 size_t num_sfields = 0; 3042 uint32_t last_field_idx = 0u; 3043 for (; it.HasNextStaticField(); it.Next()) { 3044 uint32_t field_idx = it.GetMemberIndex(); 3045 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier. 3046 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) { 3047 DCHECK_LT(num_sfields, it.NumStaticFields()); 3048 LoadField(it, klass, &sfields->At(num_sfields)); 3049 ++num_sfields; 3050 last_field_idx = field_idx; 3051 } 3052 } 3053 // Load instance fields. 3054 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self, 3055 allocator, 3056 it.NumInstanceFields()); 3057 size_t num_ifields = 0u; 3058 last_field_idx = 0u; 3059 for (; it.HasNextInstanceField(); it.Next()) { 3060 uint32_t field_idx = it.GetMemberIndex(); 3061 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier. 3062 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) { 3063 DCHECK_LT(num_ifields, it.NumInstanceFields()); 3064 LoadField(it, klass, &ifields->At(num_ifields)); 3065 ++num_ifields; 3066 last_field_idx = field_idx; 3067 } 3068 } 3069 if (UNLIKELY(num_sfields != it.NumStaticFields()) || 3070 UNLIKELY(num_ifields != it.NumInstanceFields())) { 3071 LOG(WARNING) << "Duplicate fields in class " << PrettyDescriptor(klass.Get()) 3072 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields() 3073 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")"; 3074 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size. 3075 if (sfields != nullptr) { 3076 sfields->SetSize(num_sfields); 3077 } 3078 if (ifields != nullptr) { 3079 ifields->SetSize(num_ifields); 3080 } 3081 } 3082 // Set the field arrays. 3083 klass->SetSFieldsPtr(sfields); 3084 DCHECK_EQ(klass->NumStaticFields(), num_sfields); 3085 klass->SetIFieldsPtr(ifields); 3086 DCHECK_EQ(klass->NumInstanceFields(), num_ifields); 3087 // Load methods. 3088 klass->SetMethodsPtr( 3089 AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()), 3090 it.NumDirectMethods(), 3091 it.NumVirtualMethods()); 3092 size_t class_def_method_index = 0; 3093 uint32_t last_dex_method_index = DexFile::kDexNoIndex; 3094 size_t last_class_def_method_index = 0; 3095 // TODO These should really use the iterators. 3096 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) { 3097 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_); 3098 LoadMethod(self, dex_file, it, klass, method); 3099 LinkCode(method, oat_class, class_def_method_index); 3100 uint32_t it_method_index = it.GetMemberIndex(); 3101 if (last_dex_method_index == it_method_index) { 3102 // duplicate case 3103 method->SetMethodIndex(last_class_def_method_index); 3104 } else { 3105 method->SetMethodIndex(class_def_method_index); 3106 last_dex_method_index = it_method_index; 3107 last_class_def_method_index = class_def_method_index; 3108 } 3109 class_def_method_index++; 3110 } 3111 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) { 3112 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_); 3113 LoadMethod(self, dex_file, it, klass, method); 3114 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i); 3115 LinkCode(method, oat_class, class_def_method_index); 3116 class_def_method_index++; 3117 } 3118 DCHECK(!it.HasNext()); 3119 } 3120 // Ensure that the card is marked so that remembered sets pick up native roots. 3121 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get()); 3122 self->AllowThreadSuspension(); 3123 } 3124 3125 void ClassLinker::LoadField(const ClassDataItemIterator& it, 3126 Handle<mirror::Class> klass, 3127 ArtField* dst) { 3128 const uint32_t field_idx = it.GetMemberIndex(); 3129 dst->SetDexFieldIndex(field_idx); 3130 dst->SetDeclaringClass(klass.Get()); 3131 dst->SetAccessFlags(it.GetFieldAccessFlags()); 3132 } 3133 3134 void ClassLinker::LoadMethod(Thread* self, 3135 const DexFile& dex_file, 3136 const ClassDataItemIterator& it, 3137 Handle<mirror::Class> klass, 3138 ArtMethod* dst) { 3139 uint32_t dex_method_idx = it.GetMemberIndex(); 3140 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx); 3141 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_); 3142 3143 ScopedAssertNoThreadSuspension ants(self, "LoadMethod"); 3144 dst->SetDexMethodIndex(dex_method_idx); 3145 dst->SetDeclaringClass(klass.Get()); 3146 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset()); 3147 3148 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods(), image_pointer_size_); 3149 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes(), image_pointer_size_); 3150 3151 uint32_t access_flags = it.GetMethodAccessFlags(); 3152 3153 if (UNLIKELY(strcmp("finalize", method_name) == 0)) { 3154 // Set finalizable flag on declaring class. 3155 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) { 3156 // Void return type. 3157 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged. 3158 klass->SetFinalizable(); 3159 } else { 3160 std::string temp; 3161 const char* klass_descriptor = klass->GetDescriptor(&temp); 3162 // The Enum class declares a "final" finalize() method to prevent subclasses from 3163 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its 3164 // subclasses, so we exclude it here. 3165 // We also want to avoid setting the flag on Object, where we know that finalize() is 3166 // empty. 3167 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 && 3168 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) { 3169 klass->SetFinalizable(); 3170 } 3171 } 3172 } 3173 } else if (method_name[0] == '<') { 3174 // Fix broken access flags for initializers. Bug 11157540. 3175 bool is_init = (strcmp("<init>", method_name) == 0); 3176 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0); 3177 if (UNLIKELY(!is_init && !is_clinit)) { 3178 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name; 3179 } else { 3180 if (UNLIKELY((access_flags & kAccConstructor) == 0)) { 3181 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class " 3182 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation(); 3183 access_flags |= kAccConstructor; 3184 } 3185 } 3186 } 3187 dst->SetAccessFlags(access_flags); 3188 } 3189 3190 void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) { 3191 StackHandleScope<1> hs(self); 3192 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache( 3193 self, 3194 dex_file, 3195 Runtime::Current()->GetLinearAlloc()))); 3196 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for " 3197 << dex_file.GetLocation(); 3198 AppendToBootClassPath(dex_file, dex_cache); 3199 } 3200 3201 void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, 3202 Handle<mirror::DexCache> dex_cache) { 3203 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation(); 3204 boot_class_path_.push_back(&dex_file); 3205 RegisterDexFile(dex_file, dex_cache); 3206 } 3207 3208 void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, 3209 Handle<mirror::DexCache> dex_cache) { 3210 Thread* const self = Thread::Current(); 3211 dex_lock_.AssertExclusiveHeld(self); 3212 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation(); 3213 // For app images, the dex cache location may be a suffix of the dex file location since the 3214 // dex file location is an absolute path. 3215 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8(); 3216 const size_t dex_cache_length = dex_cache_location.length(); 3217 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation(); 3218 std::string dex_file_location = dex_file.GetLocation(); 3219 CHECK_GE(dex_file_location.length(), dex_cache_length) 3220 << dex_cache_location << " " << dex_file.GetLocation(); 3221 // Take suffix. 3222 const std::string dex_file_suffix = dex_file_location.substr( 3223 dex_file_location.length() - dex_cache_length, 3224 dex_cache_length); 3225 // Example dex_cache location is SettingsProvider.apk and 3226 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk 3227 CHECK_EQ(dex_cache_location, dex_file_suffix); 3228 // Clean up pass to remove null dex caches. 3229 // Null dex caches can occur due to class unloading and we are lazily removing null entries. 3230 JavaVMExt* const vm = self->GetJniEnv()->vm; 3231 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) { 3232 DexCacheData data = *it; 3233 if (self->IsJWeakCleared(data.weak_root)) { 3234 vm->DeleteWeakGlobalRef(self, data.weak_root); 3235 it = dex_caches_.erase(it); 3236 } else { 3237 ++it; 3238 } 3239 } 3240 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache.Get()); 3241 dex_cache->SetDexFile(&dex_file); 3242 DexCacheData data; 3243 data.weak_root = dex_cache_jweak; 3244 data.dex_file = dex_cache->GetDexFile(); 3245 data.resolved_types = dex_cache->GetResolvedTypes(); 3246 dex_caches_.push_back(data); 3247 } 3248 3249 mirror::DexCache* ClassLinker::RegisterDexFile(const DexFile& dex_file, 3250 mirror::ClassLoader* class_loader) { 3251 Thread* self = Thread::Current(); 3252 { 3253 ReaderMutexLock mu(self, dex_lock_); 3254 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true); 3255 if (dex_cache != nullptr) { 3256 return dex_cache; 3257 } 3258 } 3259 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader); 3260 DCHECK(linear_alloc != nullptr); 3261 ClassTable* table; 3262 { 3263 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 3264 table = InsertClassTableForClassLoader(class_loader); 3265 } 3266 // Don't alloc while holding the lock, since allocation may need to 3267 // suspend all threads and another thread may need the dex_lock_ to 3268 // get to a suspend point. 3269 StackHandleScope<1> hs(self); 3270 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file, linear_alloc))); 3271 { 3272 WriterMutexLock mu(self, dex_lock_); 3273 mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true); 3274 if (dex_cache != nullptr) { 3275 return dex_cache; 3276 } 3277 if (h_dex_cache.Get() == nullptr) { 3278 self->AssertPendingOOMException(); 3279 return nullptr; 3280 } 3281 RegisterDexFileLocked(dex_file, h_dex_cache); 3282 } 3283 table->InsertStrongRoot(h_dex_cache.Get()); 3284 return h_dex_cache.Get(); 3285 } 3286 3287 void ClassLinker::RegisterDexFile(const DexFile& dex_file, 3288 Handle<mirror::DexCache> dex_cache) { 3289 WriterMutexLock mu(Thread::Current(), dex_lock_); 3290 RegisterDexFileLocked(dex_file, dex_cache); 3291 } 3292 3293 mirror::DexCache* ClassLinker::FindDexCache(Thread* self, 3294 const DexFile& dex_file, 3295 bool allow_failure) { 3296 ReaderMutexLock mu(self, dex_lock_); 3297 return FindDexCacheLocked(self, dex_file, allow_failure); 3298 } 3299 3300 mirror::DexCache* ClassLinker::FindDexCacheLocked(Thread* self, 3301 const DexFile& dex_file, 3302 bool allow_failure) { 3303 // Search assuming unique-ness of dex file. 3304 for (const DexCacheData& data : dex_caches_) { 3305 // Avoid decoding (and read barriers) other unrelated dex caches. 3306 if (data.dex_file == &dex_file) { 3307 mirror::DexCache* dex_cache = 3308 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root)); 3309 if (dex_cache != nullptr) { 3310 return dex_cache; 3311 } else { 3312 break; 3313 } 3314 } 3315 } 3316 if (allow_failure) { 3317 return nullptr; 3318 } 3319 std::string location(dex_file.GetLocation()); 3320 // Failure, dump diagnostic and abort. 3321 for (const DexCacheData& data : dex_caches_) { 3322 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root)); 3323 if (dex_cache != nullptr) { 3324 LOG(ERROR) << "Registered dex file " << dex_cache->GetDexFile()->GetLocation(); 3325 } 3326 } 3327 LOG(FATAL) << "Failed to find DexCache for DexFile " << location; 3328 UNREACHABLE(); 3329 } 3330 3331 void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) { 3332 Thread* const self = Thread::Current(); 3333 ReaderMutexLock mu(self, dex_lock_); 3334 for (const DexCacheData& data : dex_caches_) { 3335 if (!self->IsJWeakCleared(data.weak_root)) { 3336 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>( 3337 self->DecodeJObject(data.weak_root)); 3338 if (dex_cache != nullptr) { 3339 dex_cache->Fixup(resolution_method, image_pointer_size_); 3340 } 3341 } 3342 } 3343 } 3344 3345 mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) { 3346 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_)); 3347 if (UNLIKELY(klass == nullptr)) { 3348 self->AssertPendingOOMException(); 3349 return nullptr; 3350 } 3351 return InitializePrimitiveClass(klass, type); 3352 } 3353 3354 mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class, 3355 Primitive::Type type) { 3356 CHECK(primitive_class != nullptr); 3357 // Must hold lock on object when initializing. 3358 Thread* self = Thread::Current(); 3359 StackHandleScope<1> hs(self); 3360 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class)); 3361 ObjectLock<mirror::Class> lock(self, h_class); 3362 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract); 3363 h_class->SetPrimitiveType(type); 3364 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self); 3365 const char* descriptor = Primitive::Descriptor(type); 3366 mirror::Class* existing = InsertClass(descriptor, h_class.Get(), 3367 ComputeModifiedUtf8Hash(descriptor)); 3368 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed"; 3369 return h_class.Get(); 3370 } 3371 3372 // Create an array class (i.e. the class object for the array, not the 3373 // array itself). "descriptor" looks like "[C" or "[[[[B" or 3374 // "[Ljava/lang/String;". 3375 // 3376 // If "descriptor" refers to an array of primitives, look up the 3377 // primitive type's internally-generated class object. 3378 // 3379 // "class_loader" is the class loader of the class that's referring to 3380 // us. It's used to ensure that we're looking for the element type in 3381 // the right context. It does NOT become the class loader for the 3382 // array class; that always comes from the base element class. 3383 // 3384 // Returns null with an exception raised on failure. 3385 mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash, 3386 Handle<mirror::ClassLoader> class_loader) { 3387 // Identify the underlying component type 3388 CHECK_EQ('[', descriptor[0]); 3389 StackHandleScope<2> hs(self); 3390 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, 3391 class_loader))); 3392 if (component_type.Get() == nullptr) { 3393 DCHECK(self->IsExceptionPending()); 3394 // We need to accept erroneous classes as component types. 3395 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1); 3396 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get())); 3397 if (component_type.Get() == nullptr) { 3398 DCHECK(self->IsExceptionPending()); 3399 return nullptr; 3400 } else { 3401 self->ClearException(); 3402 } 3403 } 3404 if (UNLIKELY(component_type->IsPrimitiveVoid())) { 3405 ThrowNoClassDefFoundError("Attempt to create array of void primitive type"); 3406 return nullptr; 3407 } 3408 // See if the component type is already loaded. Array classes are 3409 // always associated with the class loader of their underlying 3410 // element type -- an array of Strings goes with the loader for 3411 // java/lang/String -- so we need to look for it there. (The 3412 // caller should have checked for the existence of the class 3413 // before calling here, but they did so with *their* class loader, 3414 // not the component type's loader.) 3415 // 3416 // If we find it, the caller adds "loader" to the class' initiating 3417 // loader list, which should prevent us from going through this again. 3418 // 3419 // This call is unnecessary if "loader" and "component_type->GetClassLoader()" 3420 // are the same, because our caller (FindClass) just did the 3421 // lookup. (Even if we get this wrong we still have correct behavior, 3422 // because we effectively do this lookup again when we add the new 3423 // class to the hash table --- necessary because of possible races with 3424 // other threads.) 3425 if (class_loader.Get() != component_type->GetClassLoader()) { 3426 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader()); 3427 if (new_class != nullptr) { 3428 return new_class; 3429 } 3430 } 3431 3432 // Fill out the fields in the Class. 3433 // 3434 // It is possible to execute some methods against arrays, because 3435 // all arrays are subclasses of java_lang_Object_, so we need to set 3436 // up a vtable. We can just point at the one in java_lang_Object_. 3437 // 3438 // Array classes are simple enough that we don't need to do a full 3439 // link step. 3440 auto new_class = hs.NewHandle<mirror::Class>(nullptr); 3441 if (UNLIKELY(!init_done_)) { 3442 // Classes that were hand created, ie not by FindSystemClass 3443 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) { 3444 new_class.Assign(GetClassRoot(kClassArrayClass)); 3445 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) { 3446 new_class.Assign(GetClassRoot(kObjectArrayClass)); 3447 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) { 3448 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass)); 3449 } else if (strcmp(descriptor, "[C") == 0) { 3450 new_class.Assign(GetClassRoot(kCharArrayClass)); 3451 } else if (strcmp(descriptor, "[I") == 0) { 3452 new_class.Assign(GetClassRoot(kIntArrayClass)); 3453 } else if (strcmp(descriptor, "[J") == 0) { 3454 new_class.Assign(GetClassRoot(kLongArrayClass)); 3455 } 3456 } 3457 if (new_class.Get() == nullptr) { 3458 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_))); 3459 if (new_class.Get() == nullptr) { 3460 self->AssertPendingOOMException(); 3461 return nullptr; 3462 } 3463 new_class->SetComponentType(component_type.Get()); 3464 } 3465 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing. 3466 DCHECK(new_class->GetComponentType() != nullptr); 3467 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject); 3468 new_class->SetSuperClass(java_lang_Object); 3469 new_class->SetVTable(java_lang_Object->GetVTable()); 3470 new_class->SetPrimitiveType(Primitive::kPrimNot); 3471 new_class->SetClassLoader(component_type->GetClassLoader()); 3472 if (component_type->IsPrimitive()) { 3473 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields); 3474 } else { 3475 new_class->SetClassFlags(mirror::kClassFlagObjectArray); 3476 } 3477 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self); 3478 new_class->PopulateEmbeddedVTable(image_pointer_size_); 3479 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_); 3480 new_class->SetImt(object_imt, image_pointer_size_); 3481 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self); 3482 // don't need to set new_class->SetObjectSize(..) 3483 // because Object::SizeOf delegates to Array::SizeOf 3484 3485 // All arrays have java/lang/Cloneable and java/io/Serializable as 3486 // interfaces. We need to set that up here, so that stuff like 3487 // "instanceof" works right. 3488 // 3489 // Note: The GC could run during the call to FindSystemClass, 3490 // so we need to make sure the class object is GC-valid while we're in 3491 // there. Do this by clearing the interface list so the GC will just 3492 // think that the entries are null. 3493 3494 3495 // Use the single, global copies of "interfaces" and "iftable" 3496 // (remember not to free them for arrays). 3497 { 3498 mirror::IfTable* array_iftable = array_iftable_.Read(); 3499 CHECK(array_iftable != nullptr); 3500 new_class->SetIfTable(array_iftable); 3501 } 3502 3503 // Inherit access flags from the component type. 3504 int access_flags = new_class->GetComponentType()->GetAccessFlags(); 3505 // Lose any implementation detail flags; in particular, arrays aren't finalizable. 3506 access_flags &= kAccJavaFlagsMask; 3507 // Arrays can't be used as a superclass or interface, so we want to add "abstract final" 3508 // and remove "interface". 3509 access_flags |= kAccAbstract | kAccFinal; 3510 access_flags &= ~kAccInterface; 3511 3512 new_class->SetAccessFlags(access_flags); 3513 3514 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash); 3515 if (existing == nullptr) { 3516 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get()); 3517 return new_class.Get(); 3518 } 3519 // Another thread must have loaded the class after we 3520 // started but before we finished. Abandon what we've 3521 // done. 3522 // 3523 // (Yes, this happens.) 3524 3525 return existing; 3526 } 3527 3528 mirror::Class* ClassLinker::FindPrimitiveClass(char type) { 3529 switch (type) { 3530 case 'B': 3531 return GetClassRoot(kPrimitiveByte); 3532 case 'C': 3533 return GetClassRoot(kPrimitiveChar); 3534 case 'D': 3535 return GetClassRoot(kPrimitiveDouble); 3536 case 'F': 3537 return GetClassRoot(kPrimitiveFloat); 3538 case 'I': 3539 return GetClassRoot(kPrimitiveInt); 3540 case 'J': 3541 return GetClassRoot(kPrimitiveLong); 3542 case 'S': 3543 return GetClassRoot(kPrimitiveShort); 3544 case 'Z': 3545 return GetClassRoot(kPrimitiveBoolean); 3546 case 'V': 3547 return GetClassRoot(kPrimitiveVoid); 3548 default: 3549 break; 3550 } 3551 std::string printable_type(PrintableChar(type)); 3552 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str()); 3553 return nullptr; 3554 } 3555 3556 mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, size_t hash) { 3557 if (VLOG_IS_ON(class_linker)) { 3558 mirror::DexCache* dex_cache = klass->GetDexCache(); 3559 std::string source; 3560 if (dex_cache != nullptr) { 3561 source += " from "; 3562 source += dex_cache->GetLocation()->ToModifiedUtf8(); 3563 } 3564 LOG(INFO) << "Loaded class " << descriptor << source; 3565 } 3566 { 3567 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3568 mirror::ClassLoader* const class_loader = klass->GetClassLoader(); 3569 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader); 3570 mirror::Class* existing = class_table->Lookup(descriptor, hash); 3571 if (existing != nullptr) { 3572 return existing; 3573 } 3574 if (kIsDebugBuild && 3575 !klass->IsTemp() && 3576 class_loader == nullptr && 3577 dex_cache_boot_image_class_lookup_required_) { 3578 // Check a class loaded with the system class loader matches one in the image if the class 3579 // is in the image. 3580 existing = LookupClassFromBootImage(descriptor); 3581 if (existing != nullptr) { 3582 CHECK_EQ(klass, existing); 3583 } 3584 } 3585 VerifyObject(klass); 3586 class_table->InsertWithHash(klass, hash); 3587 if (class_loader != nullptr) { 3588 // This is necessary because we need to have the card dirtied for remembered sets. 3589 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader); 3590 } 3591 if (log_new_class_table_roots_) { 3592 new_class_roots_.push_back(GcRoot<mirror::Class>(klass)); 3593 } 3594 } 3595 if (kIsDebugBuild) { 3596 // Test that copied methods correctly can find their holder. 3597 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) { 3598 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass); 3599 } 3600 } 3601 return nullptr; 3602 } 3603 3604 // TODO This should really be in mirror::Class. 3605 void ClassLinker::UpdateClassMethods(mirror::Class* klass, 3606 LengthPrefixedArray<ArtMethod>* new_methods) { 3607 klass->SetMethodsPtrUnchecked(new_methods, 3608 klass->NumDirectMethods(), 3609 klass->NumDeclaredVirtualMethods()); 3610 // Need to mark the card so that the remembered sets and mod union tables get updated. 3611 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass); 3612 } 3613 3614 bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) { 3615 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3616 ClassTable* const class_table = ClassTableForClassLoader(class_loader); 3617 return class_table != nullptr && class_table->Remove(descriptor); 3618 } 3619 3620 mirror::Class* ClassLinker::LookupClass(Thread* self, 3621 const char* descriptor, 3622 size_t hash, 3623 mirror::ClassLoader* class_loader) { 3624 { 3625 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 3626 ClassTable* const class_table = ClassTableForClassLoader(class_loader); 3627 if (class_table != nullptr) { 3628 mirror::Class* result = class_table->Lookup(descriptor, hash); 3629 if (result != nullptr) { 3630 return result; 3631 } 3632 } 3633 } 3634 if (class_loader != nullptr || !dex_cache_boot_image_class_lookup_required_) { 3635 return nullptr; 3636 } 3637 // Lookup failed but need to search dex_caches_. 3638 mirror::Class* result = LookupClassFromBootImage(descriptor); 3639 if (result != nullptr) { 3640 result = InsertClass(descriptor, result, hash); 3641 } else { 3642 // Searching the image dex files/caches failed, we don't want to get into this situation 3643 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image 3644 // classes into the class table. 3645 constexpr uint32_t kMaxFailedDexCacheLookups = 1000; 3646 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) { 3647 AddBootImageClassesToClassTable(); 3648 } 3649 } 3650 return result; 3651 } 3652 3653 static std::vector<mirror::ObjectArray<mirror::DexCache>*> GetImageDexCaches( 3654 std::vector<gc::space::ImageSpace*> image_spaces) SHARED_REQUIRES(Locks::mutator_lock_) { 3655 CHECK(!image_spaces.empty()); 3656 std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector; 3657 for (gc::space::ImageSpace* image_space : image_spaces) { 3658 mirror::Object* root = image_space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 3659 DCHECK(root != nullptr); 3660 dex_caches_vector.push_back(root->AsObjectArray<mirror::DexCache>()); 3661 } 3662 return dex_caches_vector; 3663 } 3664 3665 void ClassLinker::AddBootImageClassesToClassTable() { 3666 if (dex_cache_boot_image_class_lookup_required_) { 3667 AddImageClassesToClassTable(Runtime::Current()->GetHeap()->GetBootImageSpaces(), 3668 /*class_loader*/nullptr); 3669 dex_cache_boot_image_class_lookup_required_ = false; 3670 } 3671 } 3672 3673 void ClassLinker::AddImageClassesToClassTable(std::vector<gc::space::ImageSpace*> image_spaces, 3674 mirror::ClassLoader* class_loader) { 3675 Thread* self = Thread::Current(); 3676 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 3677 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table"); 3678 3679 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader); 3680 3681 std::string temp; 3682 std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector = 3683 GetImageDexCaches(image_spaces); 3684 for (mirror::ObjectArray<mirror::DexCache>* dex_caches : dex_caches_vector) { 3685 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 3686 mirror::DexCache* dex_cache = dex_caches->Get(i); 3687 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes(); 3688 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) { 3689 mirror::Class* klass = types[j].Read(); 3690 if (klass != nullptr) { 3691 DCHECK_EQ(klass->GetClassLoader(), class_loader); 3692 const char* descriptor = klass->GetDescriptor(&temp); 3693 size_t hash = ComputeModifiedUtf8Hash(descriptor); 3694 mirror::Class* existing = class_table->Lookup(descriptor, hash); 3695 if (existing != nullptr) { 3696 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != " 3697 << PrettyClassAndClassLoader(klass); 3698 } else { 3699 class_table->Insert(klass); 3700 if (log_new_class_table_roots_) { 3701 new_class_roots_.push_back(GcRoot<mirror::Class>(klass)); 3702 } 3703 } 3704 } 3705 } 3706 } 3707 } 3708 } 3709 3710 class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor { 3711 public: 3712 explicit MoveClassTableToPreZygoteVisitor() {} 3713 3714 void Visit(mirror::ClassLoader* class_loader) 3715 REQUIRES(Locks::classlinker_classes_lock_) 3716 SHARED_REQUIRES(Locks::mutator_lock_) OVERRIDE { 3717 ClassTable* const class_table = class_loader->GetClassTable(); 3718 if (class_table != nullptr) { 3719 class_table->FreezeSnapshot(); 3720 } 3721 } 3722 }; 3723 3724 void ClassLinker::MoveClassTableToPreZygote() { 3725 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3726 boot_class_table_.FreezeSnapshot(); 3727 MoveClassTableToPreZygoteVisitor visitor; 3728 VisitClassLoaders(&visitor); 3729 } 3730 3731 mirror::Class* ClassLinker::LookupClassFromBootImage(const char* descriptor) { 3732 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup"); 3733 std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector = 3734 GetImageDexCaches(Runtime::Current()->GetHeap()->GetBootImageSpaces()); 3735 for (mirror::ObjectArray<mirror::DexCache>* dex_caches : dex_caches_vector) { 3736 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) { 3737 mirror::DexCache* dex_cache = dex_caches->Get(i); 3738 const DexFile* dex_file = dex_cache->GetDexFile(); 3739 // Try binary searching the type index by descriptor. 3740 const DexFile::TypeId* type_id = dex_file->FindTypeId(descriptor); 3741 if (type_id != nullptr) { 3742 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id); 3743 mirror::Class* klass = dex_cache->GetResolvedType(type_idx); 3744 if (klass != nullptr) { 3745 return klass; 3746 } 3747 } 3748 } 3749 } 3750 return nullptr; 3751 } 3752 3753 // Look up classes by hash and descriptor and put all matching ones in the result array. 3754 class LookupClassesVisitor : public ClassLoaderVisitor { 3755 public: 3756 LookupClassesVisitor(const char* descriptor, size_t hash, std::vector<mirror::Class*>* result) 3757 : descriptor_(descriptor), 3758 hash_(hash), 3759 result_(result) {} 3760 3761 void Visit(mirror::ClassLoader* class_loader) 3762 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE { 3763 ClassTable* const class_table = class_loader->GetClassTable(); 3764 mirror::Class* klass = class_table->Lookup(descriptor_, hash_); 3765 if (klass != nullptr) { 3766 result_->push_back(klass); 3767 } 3768 } 3769 3770 private: 3771 const char* const descriptor_; 3772 const size_t hash_; 3773 std::vector<mirror::Class*>* const result_; 3774 }; 3775 3776 void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) { 3777 result.clear(); 3778 if (dex_cache_boot_image_class_lookup_required_) { 3779 AddBootImageClassesToClassTable(); 3780 } 3781 Thread* const self = Thread::Current(); 3782 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 3783 const size_t hash = ComputeModifiedUtf8Hash(descriptor); 3784 mirror::Class* klass = boot_class_table_.Lookup(descriptor, hash); 3785 if (klass != nullptr) { 3786 result.push_back(klass); 3787 } 3788 LookupClassesVisitor visitor(descriptor, hash, &result); 3789 VisitClassLoaders(&visitor); 3790 } 3791 3792 bool ClassLinker::AttemptSupertypeVerification(Thread* self, 3793 Handle<mirror::Class> klass, 3794 Handle<mirror::Class> supertype) { 3795 DCHECK(self != nullptr); 3796 DCHECK(klass.Get() != nullptr); 3797 DCHECK(supertype.Get() != nullptr); 3798 3799 if (!supertype->IsVerified() && !supertype->IsErroneous()) { 3800 VerifyClass(self, supertype); 3801 } 3802 if (supertype->IsCompileTimeVerified()) { 3803 // Either we are verified or we soft failed and need to retry at runtime. 3804 return true; 3805 } 3806 // If we got this far then we have a hard failure. 3807 std::string error_msg = 3808 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s", 3809 PrettyDescriptor(klass.Get()).c_str(), 3810 PrettyDescriptor(supertype.Get()).c_str()); 3811 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3812 StackHandleScope<1> hs(self); 3813 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException())); 3814 if (cause.Get() != nullptr) { 3815 // Set during VerifyClass call (if at all). 3816 self->ClearException(); 3817 } 3818 // Change into a verify error. 3819 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3820 if (cause.Get() != nullptr) { 3821 self->GetException()->SetCause(cause.Get()); 3822 } 3823 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex()); 3824 if (Runtime::Current()->IsAotCompiler()) { 3825 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref); 3826 } 3827 // Need to grab the lock to change status. 3828 ObjectLock<mirror::Class> super_lock(self, klass); 3829 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3830 return false; 3831 } 3832 3833 void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass, LogSeverity log_level) { 3834 { 3835 // TODO: assert that the monitor on the Class is held 3836 ObjectLock<mirror::Class> lock(self, klass); 3837 3838 // Is somebody verifying this now? 3839 mirror::Class::Status old_status = klass->GetStatus(); 3840 while (old_status == mirror::Class::kStatusVerifying || 3841 old_status == mirror::Class::kStatusVerifyingAtRuntime) { 3842 lock.WaitIgnoringInterrupts(); 3843 CHECK(klass->IsErroneous() || (klass->GetStatus() > old_status)) 3844 << "Class '" << PrettyClass(klass.Get()) << "' performed an illegal verification state " 3845 << "transition from " << old_status << " to " << klass->GetStatus(); 3846 old_status = klass->GetStatus(); 3847 } 3848 3849 // The class might already be erroneous, for example at compile time if we attempted to verify 3850 // this class as a parent to another. 3851 if (klass->IsErroneous()) { 3852 ThrowEarlierClassFailure(klass.Get()); 3853 return; 3854 } 3855 3856 // Don't attempt to re-verify if already sufficiently verified. 3857 if (klass->IsVerified()) { 3858 EnsureSkipAccessChecksMethods(klass); 3859 return; 3860 } 3861 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) { 3862 return; 3863 } 3864 3865 if (klass->GetStatus() == mirror::Class::kStatusResolved) { 3866 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self); 3867 } else { 3868 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime) 3869 << PrettyClass(klass.Get()); 3870 CHECK(!Runtime::Current()->IsAotCompiler()); 3871 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self); 3872 } 3873 3874 // Skip verification if disabled. 3875 if (!Runtime::Current()->IsVerificationEnabled()) { 3876 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self); 3877 EnsureSkipAccessChecksMethods(klass); 3878 return; 3879 } 3880 } 3881 3882 // Verify super class. 3883 StackHandleScope<2> hs(self); 3884 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass())); 3885 // If we have a superclass and we get a hard verification failure we can return immediately. 3886 if (supertype.Get() != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) { 3887 CHECK(self->IsExceptionPending()) << "Verification error should be pending."; 3888 return; 3889 } 3890 3891 // Verify all default super-interfaces. 3892 // 3893 // (1) Don't bother if the superclass has already had a soft verification failure. 3894 // 3895 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause 3896 // recursive initialization by themselves. This is because when an interface is initialized 3897 // directly it must not initialize its superinterfaces. We are allowed to verify regardless 3898 // but choose not to for an optimization. If the interfaces is being verified due to a class 3899 // initialization (which would need all the default interfaces to be verified) the class code 3900 // will trigger the recursive verification anyway. 3901 if ((supertype.Get() == nullptr || supertype->IsVerified()) // See (1) 3902 && !klass->IsInterface()) { // See (2) 3903 int32_t iftable_count = klass->GetIfTableCount(); 3904 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr)); 3905 // Loop through all interfaces this class has defined. It doesn't matter the order. 3906 for (int32_t i = 0; i < iftable_count; i++) { 3907 iface.Assign(klass->GetIfTable()->GetInterface(i)); 3908 DCHECK(iface.Get() != nullptr); 3909 // We only care if we have default interfaces and can skip if we are already verified... 3910 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) { 3911 continue; 3912 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) { 3913 // We had a hard failure while verifying this interface. Just return immediately. 3914 CHECK(self->IsExceptionPending()) << "Verification error should be pending."; 3915 return; 3916 } else if (UNLIKELY(!iface->IsVerified())) { 3917 // We softly failed to verify the iface. Stop checking and clean up. 3918 // Put the iface into the supertype handle so we know what caused us to fail. 3919 supertype.Assign(iface.Get()); 3920 break; 3921 } 3922 } 3923 } 3924 3925 // At this point if verification failed, then supertype is the "first" supertype that failed 3926 // verification (without a specific order). If verification succeeded, then supertype is either 3927 // null or the original superclass of klass and is verified. 3928 DCHECK(supertype.Get() == nullptr || 3929 supertype.Get() == klass->GetSuperClass() || 3930 !supertype->IsVerified()); 3931 3932 // Try to use verification information from the oat file, otherwise do runtime verification. 3933 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile(); 3934 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady); 3935 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status); 3936 // If the oat file says the class had an error, re-run the verifier. That way we will get a 3937 // precise error message. To ensure a rerun, test: 3938 // oat_file_class_status == mirror::Class::kStatusError => !preverified 3939 DCHECK(!(oat_file_class_status == mirror::Class::kStatusError) || !preverified); 3940 3941 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure; 3942 std::string error_msg; 3943 if (!preverified) { 3944 Runtime* runtime = Runtime::Current(); 3945 verifier_failure = verifier::MethodVerifier::VerifyClass(self, 3946 klass.Get(), 3947 runtime->GetCompilerCallbacks(), 3948 runtime->IsAotCompiler(), 3949 log_level, 3950 &error_msg); 3951 } 3952 3953 // Verification is done, grab the lock again. 3954 ObjectLock<mirror::Class> lock(self, klass); 3955 3956 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) { 3957 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) { 3958 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get()) 3959 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3960 << " because: " << error_msg; 3961 } 3962 self->AssertNoPendingException(); 3963 // Make sure all classes referenced by catch blocks are resolved. 3964 ResolveClassExceptionHandlerTypes(klass); 3965 if (verifier_failure == verifier::MethodVerifier::kNoFailure) { 3966 // Even though there were no verifier failures we need to respect whether the super-class and 3967 // super-default-interfaces were verified or requiring runtime reverification. 3968 if (supertype.Get() == nullptr || supertype->IsVerified()) { 3969 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self); 3970 } else { 3971 CHECK_EQ(supertype->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 3972 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self); 3973 // Pretend a soft failure occurred so that we don't consider the class verified below. 3974 verifier_failure = verifier::MethodVerifier::kSoftFailure; 3975 } 3976 } else { 3977 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure); 3978 // Soft failures at compile time should be retried at runtime. Soft 3979 // failures at runtime will be handled by slow paths in the generated 3980 // code. Set status accordingly. 3981 if (Runtime::Current()->IsAotCompiler()) { 3982 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self); 3983 } else { 3984 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self); 3985 // As this is a fake verified status, make sure the methods are _not_ marked 3986 // kAccSkipAccessChecks later. 3987 klass->SetVerificationAttempted(); 3988 } 3989 } 3990 } else { 3991 VLOG(verifier) << "Verification failed on class " << PrettyDescriptor(klass.Get()) 3992 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3993 << " because: " << error_msg; 3994 self->AssertNoPendingException(); 3995 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3996 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3997 } 3998 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) { 3999 // Class is verified so we don't need to do any access check on its methods. 4000 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each 4001 // method. 4002 // Note: we're going here during compilation and at runtime. When we set the 4003 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded 4004 // in the image and is set when loading the image. 4005 4006 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) { 4007 // Never skip access checks if the verification soft fail is forced. 4008 // Mark the class as having a verification attempt to avoid re-running the verifier. 4009 klass->SetVerificationAttempted(); 4010 } else { 4011 EnsureSkipAccessChecksMethods(klass); 4012 } 4013 } 4014 } 4015 4016 void ClassLinker::EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass) { 4017 if (!klass->WasVerificationAttempted()) { 4018 klass->SetSkipAccessChecksFlagOnAllMethods(image_pointer_size_); 4019 klass->SetVerificationAttempted(); 4020 } 4021 } 4022 4023 bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, 4024 mirror::Class* klass, 4025 mirror::Class::Status& oat_file_class_status) { 4026 // If we're compiling, we can only verify the class using the oat file if 4027 // we are not compiling the image or if the class we're verifying is not part of 4028 // the app. In other words, we will only check for preverification of bootclasspath 4029 // classes. 4030 if (Runtime::Current()->IsAotCompiler()) { 4031 // Are we compiling the bootclasspath? 4032 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) { 4033 return false; 4034 } 4035 // We are compiling an app (not the image). 4036 4037 // Is this an app class? (I.e. not a bootclasspath class) 4038 if (klass->GetClassLoader() != nullptr) { 4039 return false; 4040 } 4041 } 4042 4043 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile(); 4044 // In case we run without an image there won't be a backing oat file. 4045 if (oat_dex_file == nullptr) { 4046 return false; 4047 } 4048 4049 // We may be running with a preopted oat file but without image. In this case, 4050 // we don't skip verification of skip_access_checks classes to ensure we initialize 4051 // dex caches with all types resolved during verification. 4052 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot 4053 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when 4054 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are 4055 // already pre-opted, as then the runtime is started. 4056 if (!Runtime::Current()->IsAotCompiler() && 4057 !Runtime::Current()->GetHeap()->HasBootImageSpace() && 4058 klass->GetClassLoader() != nullptr) { 4059 return false; 4060 } 4061 4062 uint16_t class_def_index = klass->GetDexClassDefIndex(); 4063 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus(); 4064 if (oat_file_class_status == mirror::Class::kStatusVerified || 4065 oat_file_class_status == mirror::Class::kStatusInitialized) { 4066 return true; 4067 } 4068 // If we only verified a subset of the classes at compile time, we can end up with classes that 4069 // were resolved by the verifier. 4070 if (oat_file_class_status == mirror::Class::kStatusResolved) { 4071 return false; 4072 } 4073 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) { 4074 // Compile time verification failed with a soft error. Compile time verification can fail 4075 // because we have incomplete type information. Consider the following: 4076 // class ... { 4077 // Foo x; 4078 // .... () { 4079 // if (...) { 4080 // v1 gets assigned a type of resolved class Foo 4081 // } else { 4082 // v1 gets assigned a type of unresolved class Bar 4083 // } 4084 // iput x = v1 4085 // } } 4086 // when we merge v1 following the if-the-else it results in Conflict 4087 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be 4088 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as 4089 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk 4090 // at compile time). 4091 return false; 4092 } 4093 if (oat_file_class_status == mirror::Class::kStatusError) { 4094 // Compile time verification failed with a hard error. This is caused by invalid instructions 4095 // in the class. These errors are unrecoverable. 4096 return false; 4097 } 4098 if (oat_file_class_status == mirror::Class::kStatusNotReady) { 4099 // Status is uninitialized if we couldn't determine the status at compile time, for example, 4100 // not loading the class. 4101 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy 4102 // isn't a problem and this case shouldn't occur 4103 return false; 4104 } 4105 std::string temp; 4106 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status 4107 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " 4108 << klass->GetDescriptor(&temp); 4109 UNREACHABLE(); 4110 } 4111 4112 void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) { 4113 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) { 4114 ResolveMethodExceptionHandlerTypes(&method); 4115 } 4116 } 4117 4118 void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) { 4119 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod. 4120 const DexFile::CodeItem* code_item = 4121 method->GetDexFile()->GetCodeItem(method->GetCodeItemOffset()); 4122 if (code_item == nullptr) { 4123 return; // native or abstract method 4124 } 4125 if (code_item->tries_size_ == 0) { 4126 return; // nothing to process 4127 } 4128 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0); 4129 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 4130 for (uint32_t idx = 0; idx < handlers_size; idx++) { 4131 CatchHandlerIterator iterator(handlers_ptr); 4132 for (; iterator.HasNext(); iterator.Next()) { 4133 // Ensure exception types are resolved so that they don't need resolution to be delivered, 4134 // unresolved exception types will be ignored by exception delivery 4135 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) { 4136 mirror::Class* exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method); 4137 if (exception_type == nullptr) { 4138 DCHECK(Thread::Current()->IsExceptionPending()); 4139 Thread::Current()->ClearException(); 4140 } 4141 } 4142 } 4143 handlers_ptr = iterator.EndDataPointer(); 4144 } 4145 } 4146 4147 mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, 4148 jstring name, 4149 jobjectArray interfaces, 4150 jobject loader, 4151 jobjectArray methods, 4152 jobjectArray throws) { 4153 Thread* self = soa.Self(); 4154 StackHandleScope<10> hs(self); 4155 MutableHandle<mirror::Class> klass(hs.NewHandle( 4156 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class)))); 4157 if (klass.Get() == nullptr) { 4158 CHECK(self->IsExceptionPending()); // OOME. 4159 return nullptr; 4160 } 4161 DCHECK(klass->GetClass() != nullptr); 4162 klass->SetObjectSize(sizeof(mirror::Proxy)); 4163 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on 4164 // the methods. 4165 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted); 4166 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader)); 4167 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 4168 klass->SetName(soa.Decode<mirror::String*>(name)); 4169 klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache()); 4170 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self); 4171 std::string descriptor(GetDescriptorForProxy(klass.Get())); 4172 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str()); 4173 4174 // Needs to be before we insert the class so that the allocator field is set. 4175 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(klass->GetClassLoader()); 4176 4177 // Insert the class before loading the fields as the field roots 4178 // (ArtField::declaring_class_) are only visited from the class 4179 // table. There can't be any suspend points between inserting the 4180 // class and setting the field arrays below. 4181 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), hash); 4182 CHECK(existing == nullptr); 4183 4184 // Instance fields are inherited, but we add a couple of static fields... 4185 const size_t num_fields = 2; 4186 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields); 4187 klass->SetSFieldsPtr(sfields); 4188 4189 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by 4190 // our proxy, so Class.getInterfaces doesn't return the flattened set. 4191 ArtField& interfaces_sfield = sfields->At(0); 4192 interfaces_sfield.SetDexFieldIndex(0); 4193 interfaces_sfield.SetDeclaringClass(klass.Get()); 4194 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 4195 4196 // 2. Create a static field 'throws' that holds exceptions thrown by our methods. 4197 ArtField& throws_sfield = sfields->At(1); 4198 throws_sfield.SetDexFieldIndex(1); 4199 throws_sfield.SetDeclaringClass(klass.Get()); 4200 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 4201 4202 // Proxies have 1 direct method, the constructor 4203 const size_t num_direct_methods = 1; 4204 4205 // They have as many virtual methods as the array 4206 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods)); 4207 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass()) 4208 << PrettyClass(h_methods->GetClass()); 4209 const size_t num_virtual_methods = h_methods->GetLength(); 4210 4211 // Create the methods array. 4212 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray( 4213 self, allocator, num_direct_methods + num_virtual_methods); 4214 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we 4215 // want to throw OOM in the future. 4216 if (UNLIKELY(proxy_class_methods == nullptr)) { 4217 self->AssertPendingOOMException(); 4218 return nullptr; 4219 } 4220 klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods); 4221 4222 // Create the single direct method. 4223 CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_)); 4224 4225 // Create virtual method using specified prototypes. 4226 // TODO These should really use the iterators. 4227 for (size_t i = 0; i < num_virtual_methods; ++i) { 4228 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_); 4229 auto* prototype = h_methods->Get(i)->GetArtMethod(); 4230 CreateProxyMethod(klass, prototype, virtual_method); 4231 DCHECK(virtual_method->GetDeclaringClass() != nullptr); 4232 DCHECK(prototype->GetDeclaringClass() != nullptr); 4233 } 4234 4235 // The super class is java.lang.reflect.Proxy 4236 klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy)); 4237 // Now effectively in the loaded state. 4238 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); 4239 self->AssertNoPendingException(); 4240 4241 MutableHandle<mirror::Class> new_class = hs.NewHandle<mirror::Class>(nullptr); 4242 { 4243 // Must hold lock on object when resolved. 4244 ObjectLock<mirror::Class> resolution_lock(self, klass); 4245 // Link the fields and virtual methods, creating vtable and iftables. 4246 // The new class will replace the old one in the class table. 4247 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces( 4248 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces))); 4249 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) { 4250 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 4251 return nullptr; 4252 } 4253 } 4254 CHECK(klass->IsRetired()); 4255 CHECK_NE(klass.Get(), new_class.Get()); 4256 klass.Assign(new_class.Get()); 4257 4258 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get()); 4259 interfaces_sfield.SetObject<false>(klass.Get(), 4260 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 4261 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get()); 4262 throws_sfield.SetObject<false>( 4263 klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws)); 4264 4265 { 4266 // Lock on klass is released. Lock new class object. 4267 ObjectLock<mirror::Class> initialization_lock(self, klass); 4268 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self); 4269 } 4270 4271 // sanity checks 4272 if (kIsDebugBuild) { 4273 CHECK(klass->GetIFieldsPtr() == nullptr); 4274 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_)); 4275 4276 for (size_t i = 0; i < num_virtual_methods; ++i) { 4277 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_); 4278 auto* prototype = h_methods->Get(i++)->GetArtMethod(); 4279 CheckProxyMethod(virtual_method, prototype); 4280 } 4281 4282 StackHandleScope<1> hs2(self); 4283 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String*>(name)); 4284 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces", 4285 decoded_name->ToModifiedUtf8().c_str())); 4286 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name); 4287 4288 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws", 4289 decoded_name->ToModifiedUtf8().c_str())); 4290 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name); 4291 4292 CHECK_EQ(klass.Get()->GetInterfaces(), 4293 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 4294 CHECK_EQ(klass.Get()->GetThrows(), 4295 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws)); 4296 } 4297 return klass.Get(); 4298 } 4299 4300 std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) { 4301 DCHECK(proxy_class->IsProxyClass()); 4302 mirror::String* name = proxy_class->GetName(); 4303 DCHECK(name != nullptr); 4304 return DotToDescriptor(name->ToModifiedUtf8().c_str()); 4305 } 4306 4307 ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, ArtMethod* proxy_method) { 4308 DCHECK(proxy_class->IsProxyClass()); 4309 DCHECK(proxy_method->IsProxyMethod()); 4310 { 4311 Thread* const self = Thread::Current(); 4312 ReaderMutexLock mu(self, dex_lock_); 4313 // Locate the dex cache of the original interface/Object 4314 for (const DexCacheData& data : dex_caches_) { 4315 if (!self->IsJWeakCleared(data.weak_root) && 4316 proxy_method->HasSameDexCacheResolvedTypes(data.resolved_types, 4317 image_pointer_size_)) { 4318 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>( 4319 self->DecodeJObject(data.weak_root)); 4320 if (dex_cache != nullptr) { 4321 ArtMethod* resolved_method = dex_cache->GetResolvedMethod( 4322 proxy_method->GetDexMethodIndex(), image_pointer_size_); 4323 CHECK(resolved_method != nullptr); 4324 return resolved_method; 4325 } 4326 } 4327 } 4328 } 4329 LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " " 4330 << PrettyMethod(proxy_method); 4331 UNREACHABLE(); 4332 } 4333 4334 void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) { 4335 // Create constructor for Proxy that must initialize the method. 4336 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 18u); 4337 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->GetDirectMethodUnchecked( 4338 2, image_pointer_size_); 4339 DCHECK_EQ(std::string(proxy_constructor->GetName()), "<init>"); 4340 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden 4341 // constructor method. 4342 GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod( 4343 proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_); 4344 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its 4345 // code_ too) 4346 DCHECK(out != nullptr); 4347 out->CopyFrom(proxy_constructor, image_pointer_size_); 4348 // Make this constructor public and fix the class to be our Proxy version 4349 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic); 4350 out->SetDeclaringClass(klass.Get()); 4351 } 4352 4353 void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const { 4354 CHECK(constructor->IsConstructor()); 4355 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_); 4356 CHECK_STREQ(np->GetName(), "<init>"); 4357 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V"); 4358 DCHECK(constructor->IsPublic()); 4359 } 4360 4361 void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype, 4362 ArtMethod* out) { 4363 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden 4364 // prototype method 4365 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache(); 4366 // Avoid dirtying the dex cache unless we need to. 4367 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) != 4368 prototype) { 4369 dex_cache->SetResolvedMethod( 4370 prototype->GetDexMethodIndex(), prototype, image_pointer_size_); 4371 } 4372 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize 4373 // as necessary 4374 DCHECK(out != nullptr); 4375 out->CopyFrom(prototype, image_pointer_size_); 4376 4377 // Set class to be the concrete proxy class. 4378 out->SetDeclaringClass(klass.Get()); 4379 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in 4380 // preference to the invocation handler. 4381 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict; 4382 // Make the method final. 4383 const uint32_t kAddFlags = kAccFinal; 4384 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags); 4385 4386 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the 4387 // method they copy might (if it's a default method). 4388 out->SetCodeItemOffset(0); 4389 4390 // At runtime the method looks like a reference and argument saving method, clone the code 4391 // related parameters from this method. 4392 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler()); 4393 } 4394 4395 void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const { 4396 // Basic sanity 4397 CHECK(!prototype->IsFinal()); 4398 CHECK(method->IsFinal()); 4399 CHECK(method->IsInvokable()); 4400 4401 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its 4402 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself. 4403 CHECK(prototype->HasSameDexCacheResolvedMethods(method, image_pointer_size_)); 4404 CHECK(prototype->HasSameDexCacheResolvedTypes(method, image_pointer_size_)); 4405 auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_); 4406 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache()); 4407 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex()); 4408 4409 CHECK_STREQ(np->GetName(), prototype->GetName()); 4410 CHECK_STREQ(np->GetShorty(), prototype->GetShorty()); 4411 // More complex sanity - via dex cache 4412 CHECK_EQ(np->GetReturnType(true /* resolve */, image_pointer_size_), 4413 prototype->GetReturnType(true /* resolve */, image_pointer_size_)); 4414 } 4415 4416 bool ClassLinker::CanWeInitializeClass(mirror::Class* klass, bool can_init_statics, 4417 bool can_init_parents) { 4418 if (can_init_statics && can_init_parents) { 4419 return true; 4420 } 4421 if (!can_init_statics) { 4422 // Check if there's a class initializer. 4423 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_); 4424 if (clinit != nullptr) { 4425 return false; 4426 } 4427 // Check if there are encoded static values needing initialization. 4428 if (klass->NumStaticFields() != 0) { 4429 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 4430 DCHECK(dex_class_def != nullptr); 4431 if (dex_class_def->static_values_off_ != 0) { 4432 return false; 4433 } 4434 } 4435 // If we are a class we need to initialize all interfaces with default methods when we are 4436 // initialized. Check all of them. 4437 if (!klass->IsInterface()) { 4438 size_t num_interfaces = klass->GetIfTableCount(); 4439 for (size_t i = 0; i < num_interfaces; i++) { 4440 mirror::Class* iface = klass->GetIfTable()->GetInterface(i); 4441 if (iface->HasDefaultMethods() && 4442 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) { 4443 return false; 4444 } 4445 } 4446 } 4447 } 4448 if (klass->IsInterface() || !klass->HasSuperClass()) { 4449 return true; 4450 } 4451 mirror::Class* super_class = klass->GetSuperClass(); 4452 if (!can_init_parents && !super_class->IsInitialized()) { 4453 return false; 4454 } 4455 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents); 4456 } 4457 4458 bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass, 4459 bool can_init_statics, bool can_init_parents) { 4460 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol 4461 4462 // Are we already initialized and therefore done? 4463 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as 4464 // an initialized class will never change its state. 4465 if (klass->IsInitialized()) { 4466 return true; 4467 } 4468 4469 // Fast fail if initialization requires a full runtime. Not part of the JLS. 4470 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) { 4471 return false; 4472 } 4473 4474 self->AllowThreadSuspension(); 4475 uint64_t t0; 4476 { 4477 ObjectLock<mirror::Class> lock(self, klass); 4478 4479 // Re-check under the lock in case another thread initialized ahead of us. 4480 if (klass->IsInitialized()) { 4481 return true; 4482 } 4483 4484 // Was the class already found to be erroneous? Done under the lock to match the JLS. 4485 if (klass->IsErroneous()) { 4486 ThrowEarlierClassFailure(klass.Get(), true); 4487 VlogClassInitializationFailure(klass); 4488 return false; 4489 } 4490 4491 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus(); 4492 4493 if (!klass->IsVerified()) { 4494 VerifyClass(self, klass); 4495 if (!klass->IsVerified()) { 4496 // We failed to verify, expect either the klass to be erroneous or verification failed at 4497 // compile time. 4498 if (klass->IsErroneous()) { 4499 // The class is erroneous. This may be a verifier error, or another thread attempted 4500 // verification and/or initialization and failed. We can distinguish those cases by 4501 // whether an exception is already pending. 4502 if (self->IsExceptionPending()) { 4503 // Check that it's a VerifyError. 4504 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>", 4505 PrettyClass(self->GetException()->GetClass())); 4506 } else { 4507 // Check that another thread attempted initialization. 4508 DCHECK_NE(0, klass->GetClinitThreadId()); 4509 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId()); 4510 // Need to rethrow the previous failure now. 4511 ThrowEarlierClassFailure(klass.Get(), true); 4512 } 4513 VlogClassInitializationFailure(klass); 4514 } else { 4515 CHECK(Runtime::Current()->IsAotCompiler()); 4516 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 4517 } 4518 return false; 4519 } else { 4520 self->AssertNoPendingException(); 4521 } 4522 4523 // A separate thread could have moved us all the way to initialized. A "simple" example 4524 // involves a subclass of the current class being initialized at the same time (which 4525 // will implicitly initialize the superclass, if scheduled that way). b/28254258 4526 DCHECK_NE(mirror::Class::kStatusError, klass->GetStatus()); 4527 if (klass->IsInitialized()) { 4528 return true; 4529 } 4530 } 4531 4532 // If the class is kStatusInitializing, either this thread is 4533 // initializing higher up the stack or another thread has beat us 4534 // to initializing and we need to wait. Either way, this 4535 // invocation of InitializeClass will not be responsible for 4536 // running <clinit> and will return. 4537 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 4538 // Could have got an exception during verification. 4539 if (self->IsExceptionPending()) { 4540 VlogClassInitializationFailure(klass); 4541 return false; 4542 } 4543 // We caught somebody else in the act; was it us? 4544 if (klass->GetClinitThreadId() == self->GetTid()) { 4545 // Yes. That's fine. Return so we can continue initializing. 4546 return true; 4547 } 4548 // No. That's fine. Wait for another thread to finish initializing. 4549 return WaitForInitializeClass(klass, self, lock); 4550 } 4551 4552 if (!ValidateSuperClassDescriptors(klass)) { 4553 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 4554 return false; 4555 } 4556 self->AllowThreadSuspension(); 4557 4558 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get()) 4559 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId(); 4560 4561 // From here out other threads may observe that we're initializing and so changes of state 4562 // require the a notification. 4563 klass->SetClinitThreadId(self->GetTid()); 4564 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self); 4565 4566 t0 = NanoTime(); 4567 } 4568 4569 // Initialize super classes, must be done while initializing for the JLS. 4570 if (!klass->IsInterface() && klass->HasSuperClass()) { 4571 mirror::Class* super_class = klass->GetSuperClass(); 4572 if (!super_class->IsInitialized()) { 4573 CHECK(!super_class->IsInterface()); 4574 CHECK(can_init_parents); 4575 StackHandleScope<1> hs(self); 4576 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class)); 4577 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true); 4578 if (!super_initialized) { 4579 // The super class was verified ahead of entering initializing, we should only be here if 4580 // the super class became erroneous due to initialization. 4581 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending()) 4582 << "Super class initialization failed for " 4583 << PrettyDescriptor(handle_scope_super.Get()) 4584 << " that has unexpected status " << handle_scope_super->GetStatus() 4585 << "\nPending exception:\n" 4586 << (self->GetException() != nullptr ? self->GetException()->Dump() : ""); 4587 ObjectLock<mirror::Class> lock(self, klass); 4588 // Initialization failed because the super-class is erroneous. 4589 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 4590 return false; 4591 } 4592 } 4593 } 4594 4595 if (!klass->IsInterface()) { 4596 // Initialize interfaces with default methods for the JLS. 4597 size_t num_direct_interfaces = klass->NumDirectInterfaces(); 4598 // Only setup the (expensive) handle scope if we actually need to. 4599 if (UNLIKELY(num_direct_interfaces > 0)) { 4600 StackHandleScope<1> hs_iface(self); 4601 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr)); 4602 for (size_t i = 0; i < num_direct_interfaces; i++) { 4603 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass, i)); 4604 CHECK(handle_scope_iface.Get() != nullptr); 4605 CHECK(handle_scope_iface->IsInterface()); 4606 if (handle_scope_iface->HasBeenRecursivelyInitialized()) { 4607 // We have already done this for this interface. Skip it. 4608 continue; 4609 } 4610 // We cannot just call initialize class directly because we need to ensure that ALL 4611 // interfaces with default methods are initialized. Non-default interface initialization 4612 // will not affect other non-default super-interfaces. 4613 bool iface_initialized = InitializeDefaultInterfaceRecursive(self, 4614 handle_scope_iface, 4615 can_init_statics, 4616 can_init_parents); 4617 if (!iface_initialized) { 4618 ObjectLock<mirror::Class> lock(self, klass); 4619 // Initialization failed because one of our interfaces with default methods is erroneous. 4620 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 4621 return false; 4622 } 4623 } 4624 } 4625 } 4626 4627 const size_t num_static_fields = klass->NumStaticFields(); 4628 if (num_static_fields > 0) { 4629 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 4630 CHECK(dex_class_def != nullptr); 4631 const DexFile& dex_file = klass->GetDexFile(); 4632 StackHandleScope<3> hs(self); 4633 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader())); 4634 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache())); 4635 4636 // Eagerly fill in static fields so that the we don't have to do as many expensive 4637 // Class::FindStaticField in ResolveField. 4638 for (size_t i = 0; i < num_static_fields; ++i) { 4639 ArtField* field = klass->GetStaticField(i); 4640 const uint32_t field_idx = field->GetDexFieldIndex(); 4641 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_); 4642 if (resolved_field == nullptr) { 4643 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_); 4644 } else { 4645 DCHECK_EQ(field, resolved_field); 4646 } 4647 } 4648 4649 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader, 4650 this, *dex_class_def); 4651 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def); 4652 ClassDataItemIterator field_it(dex_file, class_data); 4653 if (value_it.HasNext()) { 4654 DCHECK(field_it.HasNextStaticField()); 4655 CHECK(can_init_statics); 4656 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) { 4657 ArtField* field = ResolveField( 4658 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true); 4659 if (Runtime::Current()->IsActiveTransaction()) { 4660 value_it.ReadValueToField<true>(field); 4661 } else { 4662 value_it.ReadValueToField<false>(field); 4663 } 4664 if (self->IsExceptionPending()) { 4665 break; 4666 } 4667 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField()); 4668 } 4669 } 4670 } 4671 4672 4673 if (!self->IsExceptionPending()) { 4674 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_); 4675 if (clinit != nullptr) { 4676 CHECK(can_init_statics); 4677 JValue result; 4678 clinit->Invoke(self, nullptr, 0, &result, "V"); 4679 } 4680 } 4681 self->AllowThreadSuspension(); 4682 uint64_t t1 = NanoTime(); 4683 4684 bool success = true; 4685 { 4686 ObjectLock<mirror::Class> lock(self, klass); 4687 4688 if (self->IsExceptionPending()) { 4689 WrapExceptionInInitializer(klass); 4690 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 4691 success = false; 4692 } else if (Runtime::Current()->IsTransactionAborted()) { 4693 // The exception thrown when the transaction aborted has been caught and cleared 4694 // so we need to throw it again now. 4695 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get()) 4696 << " without exception while transaction was aborted: re-throw it now."; 4697 Runtime::Current()->ThrowTransactionAbortError(self); 4698 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 4699 success = false; 4700 } else { 4701 RuntimeStats* global_stats = Runtime::Current()->GetStats(); 4702 RuntimeStats* thread_stats = self->GetStats(); 4703 ++global_stats->class_init_count; 4704 ++thread_stats->class_init_count; 4705 global_stats->class_init_time_ns += (t1 - t0); 4706 thread_stats->class_init_time_ns += (t1 - t0); 4707 // Set the class as initialized except if failed to initialize static fields. 4708 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self); 4709 if (VLOG_IS_ON(class_linker)) { 4710 std::string temp; 4711 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " << 4712 klass->GetLocation(); 4713 } 4714 // Opportunistically set static method trampolines to their destination. 4715 FixupStaticTrampolines(klass.Get()); 4716 } 4717 } 4718 return success; 4719 } 4720 4721 // We recursively run down the tree of interfaces. We need to do this in the order they are declared 4722 // and perform the initialization only on those interfaces that contain default methods. 4723 bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self, 4724 Handle<mirror::Class> iface, 4725 bool can_init_statics, 4726 bool can_init_parents) { 4727 CHECK(iface->IsInterface()); 4728 size_t num_direct_ifaces = iface->NumDirectInterfaces(); 4729 // Only create the (expensive) handle scope if we need it. 4730 if (UNLIKELY(num_direct_ifaces > 0)) { 4731 StackHandleScope<1> hs(self); 4732 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr)); 4733 // First we initialize all of iface's super-interfaces recursively. 4734 for (size_t i = 0; i < num_direct_ifaces; i++) { 4735 mirror::Class* super_iface = mirror::Class::GetDirectInterface(self, iface, i); 4736 if (!super_iface->HasBeenRecursivelyInitialized()) { 4737 // Recursive step 4738 handle_super_iface.Assign(super_iface); 4739 if (!InitializeDefaultInterfaceRecursive(self, 4740 handle_super_iface, 4741 can_init_statics, 4742 can_init_parents)) { 4743 return false; 4744 } 4745 } 4746 } 4747 } 4748 4749 bool result = true; 4750 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not) 4751 // initialize if we don't have default methods. 4752 if (iface->HasDefaultMethods()) { 4753 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents); 4754 } 4755 4756 // Mark that this interface has undergone recursive default interface initialization so we know we 4757 // can skip it on any later class initializations. We do this even if we are not a default 4758 // interface since we can still avoid the traversal. This is purely a performance optimization. 4759 if (result) { 4760 // TODO This should be done in a better way 4761 ObjectLock<mirror::Class> lock(self, iface); 4762 iface->SetRecursivelyInitialized(); 4763 } 4764 return result; 4765 } 4766 4767 bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, 4768 Thread* self, 4769 ObjectLock<mirror::Class>& lock) 4770 SHARED_REQUIRES(Locks::mutator_lock_) { 4771 while (true) { 4772 self->AssertNoPendingException(); 4773 CHECK(!klass->IsInitialized()); 4774 lock.WaitIgnoringInterrupts(); 4775 4776 // When we wake up, repeat the test for init-in-progress. If 4777 // there's an exception pending (only possible if 4778 // we were not using WaitIgnoringInterrupts), bail out. 4779 if (self->IsExceptionPending()) { 4780 WrapExceptionInInitializer(klass); 4781 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 4782 return false; 4783 } 4784 // Spurious wakeup? Go back to waiting. 4785 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 4786 continue; 4787 } 4788 if (klass->GetStatus() == mirror::Class::kStatusVerified && 4789 Runtime::Current()->IsAotCompiler()) { 4790 // Compile time initialization failed. 4791 return false; 4792 } 4793 if (klass->IsErroneous()) { 4794 // The caller wants an exception, but it was thrown in a 4795 // different thread. Synthesize one here. 4796 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread", 4797 PrettyDescriptor(klass.Get()).c_str()); 4798 VlogClassInitializationFailure(klass); 4799 return false; 4800 } 4801 if (klass->IsInitialized()) { 4802 return true; 4803 } 4804 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is " 4805 << klass->GetStatus(); 4806 } 4807 UNREACHABLE(); 4808 } 4809 4810 static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass, 4811 Handle<mirror::Class> super_klass, 4812 ArtMethod* method, 4813 ArtMethod* m) 4814 SHARED_REQUIRES(Locks::mutator_lock_) { 4815 DCHECK(Thread::Current()->IsExceptionPending()); 4816 DCHECK(!m->IsProxyMethod()); 4817 const DexFile* dex_file = m->GetDexFile(); 4818 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex()); 4819 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id); 4820 uint16_t return_type_idx = proto_id.return_type_idx_; 4821 std::string return_type = PrettyType(return_type_idx, *dex_file); 4822 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader()); 4823 ThrowWrappedLinkageError(klass.Get(), 4824 "While checking class %s method %s signature against %s %s: " 4825 "Failed to resolve return type %s with %s", 4826 PrettyDescriptor(klass.Get()).c_str(), 4827 PrettyMethod(method).c_str(), 4828 super_klass->IsInterface() ? "interface" : "superclass", 4829 PrettyDescriptor(super_klass.Get()).c_str(), 4830 return_type.c_str(), class_loader.c_str()); 4831 } 4832 4833 static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass, 4834 Handle<mirror::Class> super_klass, 4835 ArtMethod* method, 4836 ArtMethod* m, 4837 uint32_t index, 4838 uint32_t arg_type_idx) 4839 SHARED_REQUIRES(Locks::mutator_lock_) { 4840 DCHECK(Thread::Current()->IsExceptionPending()); 4841 DCHECK(!m->IsProxyMethod()); 4842 const DexFile* dex_file = m->GetDexFile(); 4843 std::string arg_type = PrettyType(arg_type_idx, *dex_file); 4844 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader()); 4845 ThrowWrappedLinkageError(klass.Get(), 4846 "While checking class %s method %s signature against %s %s: " 4847 "Failed to resolve arg %u type %s with %s", 4848 PrettyDescriptor(klass.Get()).c_str(), 4849 PrettyMethod(method).c_str(), 4850 super_klass->IsInterface() ? "interface" : "superclass", 4851 PrettyDescriptor(super_klass.Get()).c_str(), 4852 index, arg_type.c_str(), class_loader.c_str()); 4853 } 4854 4855 static void ThrowSignatureMismatch(Handle<mirror::Class> klass, 4856 Handle<mirror::Class> super_klass, 4857 ArtMethod* method, 4858 const std::string& error_msg) 4859 SHARED_REQUIRES(Locks::mutator_lock_) { 4860 ThrowLinkageError(klass.Get(), 4861 "Class %s method %s resolves differently in %s %s: %s", 4862 PrettyDescriptor(klass.Get()).c_str(), 4863 PrettyMethod(method).c_str(), 4864 super_klass->IsInterface() ? "interface" : "superclass", 4865 PrettyDescriptor(super_klass.Get()).c_str(), 4866 error_msg.c_str()); 4867 } 4868 4869 static bool HasSameSignatureWithDifferentClassLoaders(Thread* self, 4870 size_t pointer_size, 4871 Handle<mirror::Class> klass, 4872 Handle<mirror::Class> super_klass, 4873 ArtMethod* method1, 4874 ArtMethod* method2) 4875 SHARED_REQUIRES(Locks::mutator_lock_) { 4876 { 4877 StackHandleScope<1> hs(self); 4878 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType(true /* resolve */, 4879 pointer_size))); 4880 if (UNLIKELY(return_type.Get() == nullptr)) { 4881 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1); 4882 return false; 4883 } 4884 mirror::Class* other_return_type = method2->GetReturnType(true /* resolve */, 4885 pointer_size); 4886 if (UNLIKELY(other_return_type == nullptr)) { 4887 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2); 4888 return false; 4889 } 4890 if (UNLIKELY(other_return_type != return_type.Get())) { 4891 ThrowSignatureMismatch(klass, super_klass, method1, 4892 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)", 4893 PrettyClassAndClassLoader(return_type.Get()).c_str(), 4894 return_type.Get(), 4895 PrettyClassAndClassLoader(other_return_type).c_str(), 4896 other_return_type)); 4897 return false; 4898 } 4899 } 4900 const DexFile::TypeList* types1 = method1->GetParameterTypeList(); 4901 const DexFile::TypeList* types2 = method2->GetParameterTypeList(); 4902 if (types1 == nullptr) { 4903 if (types2 != nullptr && types2->Size() != 0) { 4904 ThrowSignatureMismatch(klass, super_klass, method1, 4905 StringPrintf("Type list mismatch with %s", 4906 PrettyMethod(method2, true).c_str())); 4907 return false; 4908 } 4909 return true; 4910 } else if (UNLIKELY(types2 == nullptr)) { 4911 if (types1->Size() != 0) { 4912 ThrowSignatureMismatch(klass, super_klass, method1, 4913 StringPrintf("Type list mismatch with %s", 4914 PrettyMethod(method2, true).c_str())); 4915 return false; 4916 } 4917 return true; 4918 } 4919 uint32_t num_types = types1->Size(); 4920 if (UNLIKELY(num_types != types2->Size())) { 4921 ThrowSignatureMismatch(klass, super_klass, method1, 4922 StringPrintf("Type list mismatch with %s", 4923 PrettyMethod(method2, true).c_str())); 4924 return false; 4925 } 4926 for (uint32_t i = 0; i < num_types; ++i) { 4927 StackHandleScope<1> hs(self); 4928 uint32_t param_type_idx = types1->GetTypeItem(i).type_idx_; 4929 Handle<mirror::Class> param_type(hs.NewHandle( 4930 method1->GetClassFromTypeIndex(param_type_idx, true /* resolve */, pointer_size))); 4931 if (UNLIKELY(param_type.Get() == nullptr)) { 4932 ThrowSignatureCheckResolveArgException(klass, super_klass, method1, 4933 method1, i, param_type_idx); 4934 return false; 4935 } 4936 uint32_t other_param_type_idx = types2->GetTypeItem(i).type_idx_; 4937 mirror::Class* other_param_type = 4938 method2->GetClassFromTypeIndex(other_param_type_idx, true /* resolve */, pointer_size); 4939 if (UNLIKELY(other_param_type == nullptr)) { 4940 ThrowSignatureCheckResolveArgException(klass, super_klass, method1, 4941 method2, i, other_param_type_idx); 4942 return false; 4943 } 4944 if (UNLIKELY(param_type.Get() != other_param_type)) { 4945 ThrowSignatureMismatch(klass, super_klass, method1, 4946 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)", 4947 i, 4948 PrettyClassAndClassLoader(param_type.Get()).c_str(), 4949 param_type.Get(), 4950 PrettyClassAndClassLoader(other_param_type).c_str(), 4951 other_param_type)); 4952 return false; 4953 } 4954 } 4955 return true; 4956 } 4957 4958 4959 bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) { 4960 if (klass->IsInterface()) { 4961 return true; 4962 } 4963 // Begin with the methods local to the superclass. 4964 Thread* self = Thread::Current(); 4965 StackHandleScope<1> hs(self); 4966 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr)); 4967 if (klass->HasSuperClass() && 4968 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) { 4969 super_klass.Assign(klass->GetSuperClass()); 4970 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) { 4971 auto* m = klass->GetVTableEntry(i, image_pointer_size_); 4972 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_); 4973 if (m != super_m) { 4974 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_, 4975 klass, super_klass, 4976 m, super_m))) { 4977 self->AssertPendingException(); 4978 return false; 4979 } 4980 } 4981 } 4982 } 4983 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 4984 super_klass.Assign(klass->GetIfTable()->GetInterface(i)); 4985 if (klass->GetClassLoader() != super_klass->GetClassLoader()) { 4986 uint32_t num_methods = super_klass->NumVirtualMethods(); 4987 for (uint32_t j = 0; j < num_methods; ++j) { 4988 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>( 4989 j, image_pointer_size_); 4990 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_); 4991 if (m != super_m) { 4992 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_, 4993 klass, super_klass, 4994 m, super_m))) { 4995 self->AssertPendingException(); 4996 return false; 4997 } 4998 } 4999 } 5000 } 5001 } 5002 return true; 5003 } 5004 5005 bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields, 5006 bool can_init_parents) { 5007 DCHECK(c.Get() != nullptr); 5008 if (c->IsInitialized()) { 5009 EnsureSkipAccessChecksMethods(c); 5010 return true; 5011 } 5012 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents); 5013 if (!success) { 5014 if (can_init_fields && can_init_parents) { 5015 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get()); 5016 } 5017 } else { 5018 self->AssertNoPendingException(); 5019 } 5020 return success; 5021 } 5022 5023 void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, 5024 mirror::Class* new_class) { 5025 DCHECK_EQ(temp_class->NumInstanceFields(), 0u); 5026 for (ArtField& field : new_class->GetIFields()) { 5027 if (field.GetDeclaringClass() == temp_class) { 5028 field.SetDeclaringClass(new_class); 5029 } 5030 } 5031 5032 DCHECK_EQ(temp_class->NumStaticFields(), 0u); 5033 for (ArtField& field : new_class->GetSFields()) { 5034 if (field.GetDeclaringClass() == temp_class) { 5035 field.SetDeclaringClass(new_class); 5036 } 5037 } 5038 5039 DCHECK_EQ(temp_class->NumDirectMethods(), 0u); 5040 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u); 5041 for (auto& method : new_class->GetMethods(image_pointer_size_)) { 5042 if (method.GetDeclaringClass() == temp_class) { 5043 method.SetDeclaringClass(new_class); 5044 } 5045 } 5046 5047 // Make sure the remembered set and mod-union tables know that we updated some of the native 5048 // roots. 5049 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class); 5050 } 5051 5052 void ClassLinker::RegisterClassLoader(mirror::ClassLoader* class_loader) { 5053 CHECK(class_loader->GetAllocator() == nullptr); 5054 CHECK(class_loader->GetClassTable() == nullptr); 5055 Thread* const self = Thread::Current(); 5056 ClassLoaderData data; 5057 data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader); 5058 // Create and set the class table. 5059 data.class_table = new ClassTable; 5060 class_loader->SetClassTable(data.class_table); 5061 // Create and set the linear allocator. 5062 data.allocator = Runtime::Current()->CreateLinearAlloc(); 5063 class_loader->SetAllocator(data.allocator); 5064 // Add to the list so that we know to free the data later. 5065 class_loaders_.push_back(data); 5066 } 5067 5068 ClassTable* ClassLinker::InsertClassTableForClassLoader(mirror::ClassLoader* class_loader) { 5069 if (class_loader == nullptr) { 5070 return &boot_class_table_; 5071 } 5072 ClassTable* class_table = class_loader->GetClassTable(); 5073 if (class_table == nullptr) { 5074 RegisterClassLoader(class_loader); 5075 class_table = class_loader->GetClassTable(); 5076 DCHECK(class_table != nullptr); 5077 } 5078 return class_table; 5079 } 5080 5081 ClassTable* ClassLinker::ClassTableForClassLoader(mirror::ClassLoader* class_loader) { 5082 return class_loader == nullptr ? &boot_class_table_ : class_loader->GetClassTable(); 5083 } 5084 5085 static ImTable* FindSuperImt(mirror::Class* klass, size_t pointer_size) 5086 SHARED_REQUIRES(Locks::mutator_lock_) { 5087 while (klass->HasSuperClass()) { 5088 klass = klass->GetSuperClass(); 5089 if (klass->ShouldHaveImt()) { 5090 return klass->GetImt(pointer_size); 5091 } 5092 } 5093 return nullptr; 5094 } 5095 5096 bool ClassLinker::LinkClass(Thread* self, 5097 const char* descriptor, 5098 Handle<mirror::Class> klass, 5099 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 5100 MutableHandle<mirror::Class>* h_new_class_out) { 5101 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 5102 5103 if (!LinkSuperClass(klass)) { 5104 return false; 5105 } 5106 ArtMethod* imt_data[ImTable::kSize]; 5107 // If there are any new conflicts compared to super class. 5108 bool new_conflict = false; 5109 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod()); 5110 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) { 5111 return false; 5112 } 5113 if (!LinkInstanceFields(self, klass)) { 5114 return false; 5115 } 5116 size_t class_size; 5117 if (!LinkStaticFields(self, klass, &class_size)) { 5118 return false; 5119 } 5120 CreateReferenceInstanceOffsets(klass); 5121 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 5122 5123 ImTable* imt = nullptr; 5124 if (klass->ShouldHaveImt()) { 5125 // If there are any new conflicts compared to the super class we can not make a copy. There 5126 // can be cases where both will have a conflict method at the same slot without having the same 5127 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path 5128 // will possibly create a table that is incorrect for either of the classes. 5129 // Same IMT with new_conflict does not happen very often. 5130 if (!new_conflict) { 5131 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_); 5132 if (super_imt != nullptr) { 5133 bool imt_equals = true; 5134 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) { 5135 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]); 5136 } 5137 if (imt_equals) { 5138 imt = super_imt; 5139 } 5140 } 5141 } 5142 if (imt == nullptr) { 5143 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader()); 5144 imt = reinterpret_cast<ImTable*>( 5145 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_))); 5146 if (imt == nullptr) { 5147 return false; 5148 } 5149 imt->Populate(imt_data, image_pointer_size_); 5150 } 5151 } 5152 5153 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) { 5154 // We don't need to retire this class as it has no embedded tables or it was created the 5155 // correct size during class linker initialization. 5156 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get()); 5157 5158 if (klass->ShouldHaveEmbeddedVTable()) { 5159 klass->PopulateEmbeddedVTable(image_pointer_size_); 5160 } 5161 if (klass->ShouldHaveImt()) { 5162 klass->SetImt(imt, image_pointer_size_); 5163 } 5164 // This will notify waiters on klass that saw the not yet resolved 5165 // class in the class_table_ during EnsureResolved. 5166 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self); 5167 h_new_class_out->Assign(klass.Get()); 5168 } else { 5169 CHECK(!klass->IsResolved()); 5170 // Retire the temporary class and create the correctly sized resolved class. 5171 StackHandleScope<1> hs(self); 5172 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_)); 5173 // Set arrays to null since we don't want to have multiple classes with the same ArtField or 5174 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC 5175 // may not see any references to the target space and clean the card for a class if another 5176 // class had the same array pointer. 5177 klass->SetMethodsPtrUnchecked(nullptr, 0, 0); 5178 klass->SetSFieldsPtrUnchecked(nullptr); 5179 klass->SetIFieldsPtrUnchecked(nullptr); 5180 if (UNLIKELY(h_new_class.Get() == nullptr)) { 5181 self->AssertPendingOOMException(); 5182 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 5183 return false; 5184 } 5185 5186 CHECK_EQ(h_new_class->GetClassSize(), class_size); 5187 ObjectLock<mirror::Class> lock(self, h_new_class); 5188 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get()); 5189 5190 { 5191 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 5192 mirror::ClassLoader* const class_loader = h_new_class.Get()->GetClassLoader(); 5193 ClassTable* const table = InsertClassTableForClassLoader(class_loader); 5194 mirror::Class* existing = table->UpdateClass(descriptor, h_new_class.Get(), 5195 ComputeModifiedUtf8Hash(descriptor)); 5196 if (class_loader != nullptr) { 5197 // We updated the class in the class table, perform the write barrier so that the GC knows 5198 // about the change. 5199 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader); 5200 } 5201 CHECK_EQ(existing, klass.Get()); 5202 if (kIsDebugBuild && class_loader == nullptr && dex_cache_boot_image_class_lookup_required_) { 5203 // Check a class loaded with the system class loader matches one in the image if the class 5204 // is in the image. 5205 mirror::Class* const image_class = LookupClassFromBootImage(descriptor); 5206 if (image_class != nullptr) { 5207 CHECK_EQ(klass.Get(), existing) << descriptor; 5208 } 5209 } 5210 if (log_new_class_table_roots_) { 5211 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get())); 5212 } 5213 } 5214 5215 // This will notify waiters on temp class that saw the not yet resolved class in the 5216 // class_table_ during EnsureResolved. 5217 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self); 5218 5219 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving); 5220 // This will notify waiters on new_class that saw the not yet resolved 5221 // class in the class_table_ during EnsureResolved. 5222 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self); 5223 // Return the new class. 5224 h_new_class_out->Assign(h_new_class.Get()); 5225 } 5226 return true; 5227 } 5228 5229 static void CountMethodsAndFields(ClassDataItemIterator& dex_data, 5230 size_t* virtual_methods, 5231 size_t* direct_methods, 5232 size_t* static_fields, 5233 size_t* instance_fields) { 5234 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0; 5235 5236 while (dex_data.HasNextStaticField()) { 5237 dex_data.Next(); 5238 (*static_fields)++; 5239 } 5240 while (dex_data.HasNextInstanceField()) { 5241 dex_data.Next(); 5242 (*instance_fields)++; 5243 } 5244 while (dex_data.HasNextDirectMethod()) { 5245 (*direct_methods)++; 5246 dex_data.Next(); 5247 } 5248 while (dex_data.HasNextVirtualMethod()) { 5249 (*virtual_methods)++; 5250 dex_data.Next(); 5251 } 5252 DCHECK(!dex_data.HasNext()); 5253 } 5254 5255 static void DumpClass(std::ostream& os, 5256 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def, 5257 const char* suffix) { 5258 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def)); 5259 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n"; 5260 os << " Static fields:\n"; 5261 while (dex_data.HasNextStaticField()) { 5262 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex()); 5263 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n"; 5264 dex_data.Next(); 5265 } 5266 os << " Instance fields:\n"; 5267 while (dex_data.HasNextInstanceField()) { 5268 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex()); 5269 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n"; 5270 dex_data.Next(); 5271 } 5272 os << " Direct methods:\n"; 5273 while (dex_data.HasNextDirectMethod()) { 5274 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex()); 5275 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n"; 5276 dex_data.Next(); 5277 } 5278 os << " Virtual methods:\n"; 5279 while (dex_data.HasNextVirtualMethod()) { 5280 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex()); 5281 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n"; 5282 dex_data.Next(); 5283 } 5284 } 5285 5286 static std::string DumpClasses(const DexFile& dex_file1, 5287 const DexFile::ClassDef& dex_class_def1, 5288 const DexFile& dex_file2, 5289 const DexFile::ClassDef& dex_class_def2) { 5290 std::ostringstream os; 5291 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)"); 5292 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)"); 5293 return os.str(); 5294 } 5295 5296 5297 // Very simple structural check on whether the classes match. Only compares the number of 5298 // methods and fields. 5299 static bool SimpleStructuralCheck(const DexFile& dex_file1, 5300 const DexFile::ClassDef& dex_class_def1, 5301 const DexFile& dex_file2, 5302 const DexFile::ClassDef& dex_class_def2, 5303 std::string* error_msg) { 5304 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1)); 5305 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2)); 5306 5307 // Counters for current dex file. 5308 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1; 5309 CountMethodsAndFields(dex_data1, 5310 &dex_virtual_methods1, 5311 &dex_direct_methods1, 5312 &dex_static_fields1, 5313 &dex_instance_fields1); 5314 // Counters for compile-time dex file. 5315 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2; 5316 CountMethodsAndFields(dex_data2, 5317 &dex_virtual_methods2, 5318 &dex_direct_methods2, 5319 &dex_static_fields2, 5320 &dex_instance_fields2); 5321 5322 if (dex_virtual_methods1 != dex_virtual_methods2) { 5323 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2); 5324 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", 5325 dex_virtual_methods1, 5326 dex_virtual_methods2, 5327 class_dump.c_str()); 5328 return false; 5329 } 5330 if (dex_direct_methods1 != dex_direct_methods2) { 5331 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2); 5332 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", 5333 dex_direct_methods1, 5334 dex_direct_methods2, 5335 class_dump.c_str()); 5336 return false; 5337 } 5338 if (dex_static_fields1 != dex_static_fields2) { 5339 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2); 5340 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", 5341 dex_static_fields1, 5342 dex_static_fields2, 5343 class_dump.c_str()); 5344 return false; 5345 } 5346 if (dex_instance_fields1 != dex_instance_fields2) { 5347 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2); 5348 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", 5349 dex_instance_fields1, 5350 dex_instance_fields2, 5351 class_dump.c_str()); 5352 return false; 5353 } 5354 5355 return true; 5356 } 5357 5358 // Checks whether a the super-class changed from what we had at compile-time. This would 5359 // invalidate quickening. 5360 static bool CheckSuperClassChange(Handle<mirror::Class> klass, 5361 const DexFile& dex_file, 5362 const DexFile::ClassDef& class_def, 5363 mirror::Class* super_class) 5364 SHARED_REQUIRES(Locks::mutator_lock_) { 5365 // Check for unexpected changes in the superclass. 5366 // Quick check 1) is the super_class class-loader the boot class loader? This always has 5367 // precedence. 5368 if (super_class->GetClassLoader() != nullptr && 5369 // Quick check 2) different dex cache? Breaks can only occur for different dex files, 5370 // which is implied by different dex cache. 5371 klass->GetDexCache() != super_class->GetDexCache()) { 5372 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a 5373 // definition for the super-class, and (b) the files are in separate oat files. The oat files 5374 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files. 5375 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile(); 5376 const OatFile* class_oat_file = nullptr; 5377 if (class_oat_dex_file != nullptr) { 5378 class_oat_file = class_oat_dex_file->GetOatFile(); 5379 } 5380 5381 if (class_oat_file != nullptr) { 5382 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile(); 5383 const OatFile* loaded_super_oat_file = nullptr; 5384 if (loaded_super_oat_dex_file != nullptr) { 5385 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile(); 5386 } 5387 5388 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) { 5389 // Now check (a). 5390 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_); 5391 if (super_class_def != nullptr) { 5392 // Uh-oh, we found something. Do our check. 5393 std::string error_msg; 5394 if (!SimpleStructuralCheck(dex_file, *super_class_def, 5395 super_class->GetDexFile(), *super_class->GetClassDef(), 5396 &error_msg)) { 5397 // Print a warning to the log. This exception might be caught, e.g., as common in test 5398 // drivers. When the class is later tried to be used, we re-throw a new instance, as we 5399 // only save the type of the exception. 5400 LOG(WARNING) << "Incompatible structural change detected: " << 5401 StringPrintf( 5402 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s", 5403 PrettyType(super_class_def->class_idx_, dex_file).c_str(), 5404 class_oat_file->GetLocation().c_str(), 5405 loaded_super_oat_file->GetLocation().c_str(), 5406 error_msg.c_str()); 5407 ThrowIncompatibleClassChangeError(klass.Get(), 5408 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s", 5409 PrettyType(super_class_def->class_idx_, dex_file).c_str(), 5410 class_oat_file->GetLocation().c_str(), 5411 loaded_super_oat_file->GetLocation().c_str(), 5412 error_msg.c_str()); 5413 return false; 5414 } 5415 } 5416 } 5417 } 5418 } 5419 return true; 5420 } 5421 5422 bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) { 5423 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus()); 5424 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex()); 5425 uint16_t super_class_idx = class_def.superclass_idx_; 5426 if (super_class_idx != DexFile::kDexNoIndex16) { 5427 // Check that a class does not inherit from itself directly. 5428 // 5429 // TODO: This is a cheap check to detect the straightforward case 5430 // of a class extending itself (b/28685551), but we should do a 5431 // proper cycle detection on loaded classes, to detect all cases 5432 // of class circularity errors (b/28830038). 5433 if (super_class_idx == class_def.class_idx_) { 5434 ThrowClassCircularityError(klass.Get(), 5435 "Class %s extends itself", 5436 PrettyDescriptor(klass.Get()).c_str()); 5437 return false; 5438 } 5439 5440 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get()); 5441 if (super_class == nullptr) { 5442 DCHECK(Thread::Current()->IsExceptionPending()); 5443 return false; 5444 } 5445 // Verify 5446 if (!klass->CanAccess(super_class)) { 5447 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible", 5448 PrettyDescriptor(super_class).c_str(), 5449 PrettyDescriptor(klass.Get()).c_str()); 5450 return false; 5451 } 5452 CHECK(super_class->IsResolved()); 5453 klass->SetSuperClass(super_class); 5454 5455 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) { 5456 DCHECK(Thread::Current()->IsExceptionPending()); 5457 return false; 5458 } 5459 } 5460 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def); 5461 if (interfaces != nullptr) { 5462 for (size_t i = 0; i < interfaces->Size(); i++) { 5463 uint16_t idx = interfaces->GetTypeItem(i).type_idx_; 5464 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get()); 5465 if (interface == nullptr) { 5466 DCHECK(Thread::Current()->IsExceptionPending()); 5467 return false; 5468 } 5469 // Verify 5470 if (!klass->CanAccess(interface)) { 5471 // TODO: the RI seemed to ignore this in my testing. 5472 ThrowIllegalAccessError(klass.Get(), 5473 "Interface %s implemented by class %s is inaccessible", 5474 PrettyDescriptor(interface).c_str(), 5475 PrettyDescriptor(klass.Get()).c_str()); 5476 return false; 5477 } 5478 } 5479 } 5480 // Mark the class as loaded. 5481 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr); 5482 return true; 5483 } 5484 5485 bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) { 5486 CHECK(!klass->IsPrimitive()); 5487 mirror::Class* super = klass->GetSuperClass(); 5488 if (klass.Get() == GetClassRoot(kJavaLangObject)) { 5489 if (super != nullptr) { 5490 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass"); 5491 return false; 5492 } 5493 return true; 5494 } 5495 if (super == nullptr) { 5496 ThrowLinkageError(klass.Get(), "No superclass defined for class %s", 5497 PrettyDescriptor(klass.Get()).c_str()); 5498 return false; 5499 } 5500 // Verify 5501 if (super->IsFinal() || super->IsInterface()) { 5502 ThrowIncompatibleClassChangeError(klass.Get(), 5503 "Superclass %s of %s is %s", 5504 PrettyDescriptor(super).c_str(), 5505 PrettyDescriptor(klass.Get()).c_str(), 5506 super->IsFinal() ? "declared final" : "an interface"); 5507 return false; 5508 } 5509 if (!klass->CanAccess(super)) { 5510 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s", 5511 PrettyDescriptor(super).c_str(), 5512 PrettyDescriptor(klass.Get()).c_str()); 5513 return false; 5514 } 5515 5516 // Inherit kAccClassIsFinalizable from the superclass in case this 5517 // class doesn't override finalize. 5518 if (super->IsFinalizable()) { 5519 klass->SetFinalizable(); 5520 } 5521 5522 // Inherit class loader flag form super class. 5523 if (super->IsClassLoaderClass()) { 5524 klass->SetClassLoaderClass(); 5525 } 5526 5527 // Inherit reference flags (if any) from the superclass. 5528 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference); 5529 if (reference_flags != 0) { 5530 CHECK_EQ(klass->GetClassFlags(), 0u); 5531 klass->SetClassFlags(klass->GetClassFlags() | reference_flags); 5532 } 5533 // Disallow custom direct subclasses of java.lang.ref.Reference. 5534 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) { 5535 ThrowLinkageError(klass.Get(), 5536 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed", 5537 PrettyDescriptor(klass.Get()).c_str()); 5538 return false; 5539 } 5540 5541 if (kIsDebugBuild) { 5542 // Ensure super classes are fully resolved prior to resolving fields.. 5543 while (super != nullptr) { 5544 CHECK(super->IsResolved()); 5545 super = super->GetSuperClass(); 5546 } 5547 } 5548 return true; 5549 } 5550 5551 // Populate the class vtable and itable. Compute return type indices. 5552 bool ClassLinker::LinkMethods(Thread* self, 5553 Handle<mirror::Class> klass, 5554 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 5555 bool* out_new_conflict, 5556 ArtMethod** out_imt) { 5557 self->AllowThreadSuspension(); 5558 // A map from vtable indexes to the method they need to be updated to point to. Used because we 5559 // need to have default methods be in the virtuals array of each class but we don't set that up 5560 // until LinkInterfaceMethods. 5561 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations; 5562 // Link virtual methods then interface methods. 5563 // We set up the interface lookup table first because we need it to determine if we need to update 5564 // any vtable entries with new default method implementations. 5565 return SetupInterfaceLookupTable(self, klass, interfaces) 5566 && LinkVirtualMethods(self, klass, /*out*/ &default_translations) 5567 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt); 5568 } 5569 5570 // Comparator for name and signature of a method, used in finding overriding methods. Implementation 5571 // avoids the use of handles, if it didn't then rather than compare dex files we could compare dex 5572 // caches in the implementation below. 5573 class MethodNameAndSignatureComparator FINAL : public ValueObject { 5574 public: 5575 explicit MethodNameAndSignatureComparator(ArtMethod* method) 5576 SHARED_REQUIRES(Locks::mutator_lock_) : 5577 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())), 5578 name_(nullptr), name_len_(0) { 5579 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method); 5580 } 5581 5582 const char* GetName() { 5583 if (name_ == nullptr) { 5584 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_); 5585 } 5586 return name_; 5587 } 5588 5589 bool HasSameNameAndSignature(ArtMethod* other) 5590 SHARED_REQUIRES(Locks::mutator_lock_) { 5591 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other); 5592 const DexFile* other_dex_file = other->GetDexFile(); 5593 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex()); 5594 if (dex_file_ == other_dex_file) { 5595 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_; 5596 } 5597 GetName(); // Only used to make sure its calculated. 5598 uint32_t other_name_len; 5599 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_, 5600 &other_name_len); 5601 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) { 5602 return false; 5603 } 5604 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid); 5605 } 5606 5607 private: 5608 // Dex file for the method to compare against. 5609 const DexFile* const dex_file_; 5610 // MethodId for the method to compare against. 5611 const DexFile::MethodId* const mid_; 5612 // Lazily computed name from the dex file's strings. 5613 const char* name_; 5614 // Lazily computed name length. 5615 uint32_t name_len_; 5616 }; 5617 5618 class LinkVirtualHashTable { 5619 public: 5620 LinkVirtualHashTable(Handle<mirror::Class> klass, 5621 size_t hash_size, 5622 uint32_t* hash_table, 5623 size_t image_pointer_size) 5624 : klass_(klass), 5625 hash_size_(hash_size), 5626 hash_table_(hash_table), 5627 image_pointer_size_(image_pointer_size) { 5628 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_); 5629 } 5630 5631 void Add(uint32_t virtual_method_index) SHARED_REQUIRES(Locks::mutator_lock_) { 5632 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking( 5633 virtual_method_index, image_pointer_size_); 5634 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName(); 5635 uint32_t hash = ComputeModifiedUtf8Hash(name); 5636 uint32_t index = hash % hash_size_; 5637 // Linear probe until we have an empty slot. 5638 while (hash_table_[index] != invalid_index_) { 5639 if (++index == hash_size_) { 5640 index = 0; 5641 } 5642 } 5643 hash_table_[index] = virtual_method_index; 5644 } 5645 5646 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator) 5647 SHARED_REQUIRES(Locks::mutator_lock_) { 5648 const char* name = comparator->GetName(); 5649 uint32_t hash = ComputeModifiedUtf8Hash(name); 5650 size_t index = hash % hash_size_; 5651 while (true) { 5652 const uint32_t value = hash_table_[index]; 5653 // Since linear probe makes continuous blocks, hitting an invalid index means we are done 5654 // the block and can safely assume not found. 5655 if (value == invalid_index_) { 5656 break; 5657 } 5658 if (value != removed_index_) { // This signifies not already overriden. 5659 ArtMethod* virtual_method = 5660 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_); 5661 if (comparator->HasSameNameAndSignature( 5662 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) { 5663 hash_table_[index] = removed_index_; 5664 return value; 5665 } 5666 } 5667 if (++index == hash_size_) { 5668 index = 0; 5669 } 5670 } 5671 return GetNotFoundIndex(); 5672 } 5673 5674 static uint32_t GetNotFoundIndex() { 5675 return invalid_index_; 5676 } 5677 5678 private: 5679 static const uint32_t invalid_index_; 5680 static const uint32_t removed_index_; 5681 5682 Handle<mirror::Class> klass_; 5683 const size_t hash_size_; 5684 uint32_t* const hash_table_; 5685 const size_t image_pointer_size_; 5686 }; 5687 5688 const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max(); 5689 const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1; 5690 5691 bool ClassLinker::LinkVirtualMethods( 5692 Thread* self, 5693 Handle<mirror::Class> klass, 5694 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) { 5695 const size_t num_virtual_methods = klass->NumVirtualMethods(); 5696 if (klass->IsInterface()) { 5697 // No vtable. 5698 if (!IsUint<16>(num_virtual_methods)) { 5699 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods); 5700 return false; 5701 } 5702 bool has_defaults = false; 5703 // Assign each method an IMT index and set the default flag. 5704 for (size_t i = 0; i < num_virtual_methods; ++i) { 5705 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_); 5706 m->SetMethodIndex(i); 5707 if (!m->IsAbstract()) { 5708 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault); 5709 has_defaults = true; 5710 } 5711 } 5712 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array 5713 // during initialization. This is a performance optimization. We could simply traverse the 5714 // virtual_methods_ array again during initialization. 5715 if (has_defaults) { 5716 klass->SetHasDefaultMethods(); 5717 } 5718 return true; 5719 } else if (klass->HasSuperClass()) { 5720 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength(); 5721 const size_t max_count = num_virtual_methods + super_vtable_length; 5722 StackHandleScope<2> hs(self); 5723 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass())); 5724 MutableHandle<mirror::PointerArray> vtable; 5725 if (super_class->ShouldHaveEmbeddedVTable()) { 5726 vtable = hs.NewHandle(AllocPointerArray(self, max_count)); 5727 if (UNLIKELY(vtable.Get() == nullptr)) { 5728 self->AssertPendingOOMException(); 5729 return false; 5730 } 5731 for (size_t i = 0; i < super_vtable_length; i++) { 5732 vtable->SetElementPtrSize( 5733 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_); 5734 } 5735 // We might need to change vtable if we have new virtual methods or new interfaces (since that 5736 // might give us new default methods). If no new interfaces then we can skip the rest since 5737 // the class cannot override any of the super-class's methods. This is required for 5738 // correctness since without it we might not update overridden default method vtable entries 5739 // correctly. 5740 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) { 5741 klass->SetVTable(vtable.Get()); 5742 return true; 5743 } 5744 } else { 5745 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass()); 5746 auto* super_vtable = super_class->GetVTable(); 5747 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get()); 5748 // We might need to change vtable if we have new virtual methods or new interfaces (since that 5749 // might give us new default methods). See comment above. 5750 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) { 5751 klass->SetVTable(super_vtable); 5752 return true; 5753 } 5754 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>( 5755 super_vtable->CopyOf(self, max_count))); 5756 if (UNLIKELY(vtable.Get() == nullptr)) { 5757 self->AssertPendingOOMException(); 5758 return false; 5759 } 5760 } 5761 // How the algorithm works: 5762 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash 5763 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual 5764 // method which has not been matched to a vtable method, and j if the virtual method at the 5765 // index overrode the super virtual method at index j. 5766 // 2. Loop through super virtual methods, if they overwrite, update hash table to j 5767 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing 5768 // the need for the initial vtable which we later shrink back down). 5769 // 3. Add non overridden methods to the end of the vtable. 5770 static constexpr size_t kMaxStackHash = 250; 5771 // + 1 so that even if we only have new default methods we will still be able to use this hash 5772 // table (i.e. it will never have 0 size). 5773 const size_t hash_table_size = num_virtual_methods * 3 + 1; 5774 uint32_t* hash_table_ptr; 5775 std::unique_ptr<uint32_t[]> hash_heap_storage; 5776 if (hash_table_size <= kMaxStackHash) { 5777 hash_table_ptr = reinterpret_cast<uint32_t*>( 5778 alloca(hash_table_size * sizeof(*hash_table_ptr))); 5779 } else { 5780 hash_heap_storage.reset(new uint32_t[hash_table_size]); 5781 hash_table_ptr = hash_heap_storage.get(); 5782 } 5783 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_); 5784 // Add virtual methods to the hash table. 5785 for (size_t i = 0; i < num_virtual_methods; ++i) { 5786 DCHECK(klass->GetVirtualMethodDuringLinking( 5787 i, image_pointer_size_)->GetDeclaringClass() != nullptr); 5788 hash_table.Add(i); 5789 } 5790 // Loop through each super vtable method and see if they are overridden by a method we added to 5791 // the hash table. 5792 for (size_t j = 0; j < super_vtable_length; ++j) { 5793 // Search the hash table to see if we are overridden by any method. 5794 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_); 5795 MethodNameAndSignatureComparator super_method_name_comparator( 5796 super_method->GetInterfaceMethodIfProxy(image_pointer_size_)); 5797 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator); 5798 if (hash_index != hash_table.GetNotFoundIndex()) { 5799 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking( 5800 hash_index, image_pointer_size_); 5801 if (klass->CanAccessMember(super_method->GetDeclaringClass(), 5802 super_method->GetAccessFlags())) { 5803 if (super_method->IsFinal()) { 5804 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s", 5805 PrettyMethod(virtual_method).c_str(), 5806 super_method->GetDeclaringClassDescriptor()); 5807 return false; 5808 } 5809 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_); 5810 virtual_method->SetMethodIndex(j); 5811 } else { 5812 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method) 5813 << " would have incorrectly overridden the package-private method in " 5814 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor()); 5815 } 5816 } else if (super_method->IsOverridableByDefaultMethod()) { 5817 // We didn't directly override this method but we might through default methods... 5818 // Check for default method update. 5819 ArtMethod* default_method = nullptr; 5820 switch (FindDefaultMethodImplementation(self, 5821 super_method, 5822 klass, 5823 /*out*/&default_method)) { 5824 case DefaultMethodSearchResult::kDefaultConflict: { 5825 // A conflict was found looking for default methods. Note this (assuming it wasn't 5826 // pre-existing) in the translations map. 5827 if (UNLIKELY(!super_method->IsDefaultConflicting())) { 5828 // Don't generate another conflict method to reduce memory use as an optimization. 5829 default_translations->insert( 5830 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()}); 5831 } 5832 break; 5833 } 5834 case DefaultMethodSearchResult::kAbstractFound: { 5835 // No conflict but method is abstract. 5836 // We note that this vtable entry must be made abstract. 5837 if (UNLIKELY(!super_method->IsAbstract())) { 5838 default_translations->insert( 5839 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()}); 5840 } 5841 break; 5842 } 5843 case DefaultMethodSearchResult::kDefaultFound: { 5844 if (UNLIKELY(super_method->IsDefaultConflicting() || 5845 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) { 5846 // Found a default method implementation that is new. 5847 // TODO Refactor this add default methods to virtuals here and not in 5848 // LinkInterfaceMethods maybe. 5849 // The problem is default methods might override previously present 5850 // default-method or miranda-method vtable entries from the superclass. 5851 // Unfortunately we need these to be entries in this class's virtuals. We do not 5852 // give these entries there until LinkInterfaceMethods so we pass this map around 5853 // to let it know which vtable entries need to be updated. 5854 // Make a note that vtable entry j must be updated, store what it needs to be updated 5855 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up 5856 // then. 5857 default_translations->insert( 5858 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)}); 5859 VLOG(class_linker) << "Method " << PrettyMethod(super_method) 5860 << " overridden by default " << PrettyMethod(default_method) 5861 << " in " << PrettyClass(klass.Get()); 5862 } 5863 break; 5864 } 5865 } 5866 } 5867 } 5868 size_t actual_count = super_vtable_length; 5869 // Add the non-overridden methods at the end. 5870 for (size_t i = 0; i < num_virtual_methods; ++i) { 5871 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_); 5872 size_t method_idx = local_method->GetMethodIndexDuringLinking(); 5873 if (method_idx < super_vtable_length && 5874 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) { 5875 continue; 5876 } 5877 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_); 5878 local_method->SetMethodIndex(actual_count); 5879 ++actual_count; 5880 } 5881 if (!IsUint<16>(actual_count)) { 5882 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count); 5883 return false; 5884 } 5885 // Shrink vtable if possible 5886 CHECK_LE(actual_count, max_count); 5887 if (actual_count < max_count) { 5888 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count))); 5889 if (UNLIKELY(vtable.Get() == nullptr)) { 5890 self->AssertPendingOOMException(); 5891 return false; 5892 } 5893 } 5894 klass->SetVTable(vtable.Get()); 5895 } else { 5896 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject)); 5897 if (!IsUint<16>(num_virtual_methods)) { 5898 ThrowClassFormatError(klass.Get(), "Too many methods: %d", 5899 static_cast<int>(num_virtual_methods)); 5900 return false; 5901 } 5902 auto* vtable = AllocPointerArray(self, num_virtual_methods); 5903 if (UNLIKELY(vtable == nullptr)) { 5904 self->AssertPendingOOMException(); 5905 return false; 5906 } 5907 for (size_t i = 0; i < num_virtual_methods; ++i) { 5908 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_); 5909 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_); 5910 virtual_method->SetMethodIndex(i & 0xFFFF); 5911 } 5912 klass->SetVTable(vtable); 5913 } 5914 return true; 5915 } 5916 5917 // Determine if the given iface has any subinterface in the given list that declares the method 5918 // specified by 'target'. 5919 // 5920 // Arguments 5921 // - self: The thread we are running on 5922 // - target: A comparator that will match any method that overrides the method we are checking for 5923 // - iftable: The iftable we are searching for an overriding method on. 5924 // - ifstart: The index of the interface we are checking to see if anything overrides 5925 // - iface: The interface we are checking to see if anything overrides. 5926 // - image_pointer_size: 5927 // The image pointer size. 5928 // 5929 // Returns 5930 // - True: There is some method that matches the target comparator defined in an interface that 5931 // is a subtype of iface. 5932 // - False: There is no method that matches the target comparator in any interface that is a subtype 5933 // of iface. 5934 static bool ContainsOverridingMethodOf(Thread* self, 5935 MethodNameAndSignatureComparator& target, 5936 Handle<mirror::IfTable> iftable, 5937 size_t ifstart, 5938 Handle<mirror::Class> iface, 5939 size_t image_pointer_size) 5940 SHARED_REQUIRES(Locks::mutator_lock_) { 5941 DCHECK(self != nullptr); 5942 DCHECK(iface.Get() != nullptr); 5943 DCHECK(iftable.Get() != nullptr); 5944 DCHECK_GE(ifstart, 0u); 5945 DCHECK_LT(ifstart, iftable->Count()); 5946 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart)); 5947 DCHECK(iface->IsInterface()); 5948 5949 size_t iftable_count = iftable->Count(); 5950 StackHandleScope<1> hs(self); 5951 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr)); 5952 for (size_t k = ifstart + 1; k < iftable_count; k++) { 5953 // Skip ifstart since our current interface obviously cannot override itself. 5954 current_iface.Assign(iftable->GetInterface(k)); 5955 // Iterate through every method on this interface. The order does not matter. 5956 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) { 5957 if (UNLIKELY(target.HasSameNameAndSignature( 5958 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) { 5959 // Check if the i'th interface is a subtype of this one. 5960 if (iface->IsAssignableFrom(current_iface.Get())) { 5961 return true; 5962 } 5963 break; 5964 } 5965 } 5966 } 5967 return false; 5968 } 5969 5970 // Find the default method implementation for 'interface_method' in 'klass'. Stores it into 5971 // out_default_method and returns kDefaultFound on success. If no default method was found return 5972 // kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a 5973 // default_method conflict) it will return kDefaultConflict. 5974 ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation( 5975 Thread* self, 5976 ArtMethod* target_method, 5977 Handle<mirror::Class> klass, 5978 /*out*/ArtMethod** out_default_method) const { 5979 DCHECK(self != nullptr); 5980 DCHECK(target_method != nullptr); 5981 DCHECK(out_default_method != nullptr); 5982 5983 *out_default_method = nullptr; 5984 5985 // We organize the interface table so that, for interface I any subinterfaces J follow it in the 5986 // table. This lets us walk the table backwards when searching for default methods. The first one 5987 // we encounter is the best candidate since it is the most specific. Once we have found it we keep 5988 // track of it and then continue checking all other interfaces, since we need to throw an error if 5989 // we encounter conflicting default method implementations (one is not a subtype of the other). 5990 // 5991 // The order of unrelated interfaces does not matter and is not defined. 5992 size_t iftable_count = klass->GetIfTableCount(); 5993 if (iftable_count == 0) { 5994 // No interfaces. We have already reset out to null so just return kAbstractFound. 5995 return DefaultMethodSearchResult::kAbstractFound; 5996 } 5997 5998 StackHandleScope<3> hs(self); 5999 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr)); 6000 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable())); 6001 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr)); 6002 MethodNameAndSignatureComparator target_name_comparator( 6003 target_method->GetInterfaceMethodIfProxy(image_pointer_size_)); 6004 // Iterates over the klass's iftable in reverse 6005 for (size_t k = iftable_count; k != 0; ) { 6006 --k; 6007 6008 DCHECK_LT(k, iftable->Count()); 6009 6010 iface.Assign(iftable->GetInterface(k)); 6011 // Iterate through every declared method on this interface. The order does not matter. 6012 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) { 6013 ArtMethod* current_method = &method_iter; 6014 // Skip abstract methods and methods with different names. 6015 if (current_method->IsAbstract() || 6016 !target_name_comparator.HasSameNameAndSignature( 6017 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) { 6018 continue; 6019 } else if (!current_method->IsPublic()) { 6020 // The verifier should have caught the non-public method for dex version 37. Just warn and 6021 // skip it since this is from before default-methods so we don't really need to care that it 6022 // has code. 6023 LOG(WARNING) << "Interface method " << PrettyMethod(current_method) << " is not public! " 6024 << "This will be a fatal error in subsequent versions of android. " 6025 << "Continuing anyway."; 6026 } 6027 if (UNLIKELY(chosen_iface.Get() != nullptr)) { 6028 // We have multiple default impls of the same method. This is a potential default conflict. 6029 // We need to check if this possibly conflicting method is either a superclass of the chosen 6030 // default implementation or is overridden by a non-default interface method. In either case 6031 // there is no conflict. 6032 if (!iface->IsAssignableFrom(chosen_iface.Get()) && 6033 !ContainsOverridingMethodOf(self, 6034 target_name_comparator, 6035 iftable, 6036 k, 6037 iface, 6038 image_pointer_size_)) { 6039 VLOG(class_linker) << "Conflicting default method implementations found: " 6040 << PrettyMethod(current_method) << " and " 6041 << PrettyMethod(*out_default_method) << " in class " 6042 << PrettyClass(klass.Get()) << " conflict."; 6043 *out_default_method = nullptr; 6044 return DefaultMethodSearchResult::kDefaultConflict; 6045 } else { 6046 break; // Continue checking at the next interface. 6047 } 6048 } else { 6049 // chosen_iface == null 6050 if (!ContainsOverridingMethodOf(self, 6051 target_name_comparator, 6052 iftable, 6053 k, 6054 iface, 6055 image_pointer_size_)) { 6056 // Don't set this as the chosen interface if something else is overriding it (because that 6057 // other interface would be potentially chosen instead if it was default). If the other 6058 // interface was abstract then we wouldn't select this interface as chosen anyway since 6059 // the abstract method masks it. 6060 *out_default_method = current_method; 6061 chosen_iface.Assign(iface.Get()); 6062 // We should now finish traversing the graph to find if we have default methods that 6063 // conflict. 6064 } else { 6065 VLOG(class_linker) << "A default method '" << PrettyMethod(current_method) << "' was " 6066 << "skipped because it was overridden by an abstract method in a " 6067 << "subinterface on class '" << PrettyClass(klass.Get()) << "'"; 6068 } 6069 } 6070 break; 6071 } 6072 } 6073 if (*out_default_method != nullptr) { 6074 VLOG(class_linker) << "Default method '" << PrettyMethod(*out_default_method) << "' selected " 6075 << "as the implementation for '" << PrettyMethod(target_method) << "' " 6076 << "in '" << PrettyClass(klass.Get()) << "'"; 6077 return DefaultMethodSearchResult::kDefaultFound; 6078 } else { 6079 return DefaultMethodSearchResult::kAbstractFound; 6080 } 6081 } 6082 6083 ArtMethod* ClassLinker::AddMethodToConflictTable(mirror::Class* klass, 6084 ArtMethod* conflict_method, 6085 ArtMethod* interface_method, 6086 ArtMethod* method, 6087 bool force_new_conflict_method) { 6088 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(sizeof(void*)); 6089 Runtime* const runtime = Runtime::Current(); 6090 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader()); 6091 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method; 6092 6093 // Create a new entry if the existing one is the shared conflict method. 6094 ArtMethod* new_conflict_method = new_entry 6095 ? runtime->CreateImtConflictMethod(linear_alloc) 6096 : conflict_method; 6097 6098 // Allocate a new table. Note that we will leak this table at the next conflict, 6099 // but that's a tradeoff compared to making the table fixed size. 6100 void* data = linear_alloc->Alloc( 6101 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table, 6102 image_pointer_size_)); 6103 if (data == nullptr) { 6104 LOG(ERROR) << "Failed to allocate conflict table"; 6105 return conflict_method; 6106 } 6107 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table, 6108 interface_method, 6109 method, 6110 image_pointer_size_); 6111 6112 // Do a fence to ensure threads see the data in the table before it is assigned 6113 // to the conflict method. 6114 // Note that there is a race in the presence of multiple threads and we may leak 6115 // memory from the LinearAlloc, but that's a tradeoff compared to using 6116 // atomic operations. 6117 QuasiAtomic::ThreadFenceRelease(); 6118 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_); 6119 return new_conflict_method; 6120 } 6121 6122 void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method, 6123 ArtMethod* imt_conflict_method, 6124 ArtMethod* current_method, 6125 /*out*/bool* new_conflict, 6126 /*out*/ArtMethod** imt_ref) { 6127 // Place method in imt if entry is empty, place conflict otherwise. 6128 if (*imt_ref == unimplemented_method) { 6129 *imt_ref = current_method; 6130 } else if (!(*imt_ref)->IsRuntimeMethod()) { 6131 // If we are not a conflict and we have the same signature and name as the imt 6132 // entry, it must be that we overwrote a superclass vtable entry. 6133 // Note that we have checked IsRuntimeMethod, as there may be multiple different 6134 // conflict methods. 6135 MethodNameAndSignatureComparator imt_comparator( 6136 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_)); 6137 if (imt_comparator.HasSameNameAndSignature( 6138 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) { 6139 *imt_ref = current_method; 6140 } else { 6141 *imt_ref = imt_conflict_method; 6142 *new_conflict = true; 6143 } 6144 } else { 6145 // Place the default conflict method. Note that there may be an existing conflict 6146 // method in the IMT, but it could be one tailored to the super class, with a 6147 // specific ImtConflictTable. 6148 *imt_ref = imt_conflict_method; 6149 *new_conflict = true; 6150 } 6151 } 6152 6153 void ClassLinker::FillIMTAndConflictTables(mirror::Class* klass) { 6154 DCHECK(klass->ShouldHaveImt()) << PrettyClass(klass); 6155 DCHECK(!klass->IsTemp()) << PrettyClass(klass); 6156 ArtMethod* imt_data[ImTable::kSize]; 6157 Runtime* const runtime = Runtime::Current(); 6158 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod(); 6159 ArtMethod* const conflict_method = runtime->GetImtConflictMethod(); 6160 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method); 6161 if (klass->GetIfTable() != nullptr) { 6162 bool new_conflict = false; 6163 FillIMTFromIfTable(klass->GetIfTable(), 6164 unimplemented_method, 6165 conflict_method, 6166 klass, 6167 /*create_conflict_tables*/true, 6168 /*ignore_copied_methods*/false, 6169 &new_conflict, 6170 &imt_data[0]); 6171 } 6172 if (!klass->ShouldHaveImt()) { 6173 return; 6174 } 6175 // Compare the IMT with the super class including the conflict methods. If they are equivalent, 6176 // we can just use the same pointer. 6177 ImTable* imt = nullptr; 6178 mirror::Class* super_class = klass->GetSuperClass(); 6179 if (super_class != nullptr && super_class->ShouldHaveImt()) { 6180 ImTable* super_imt = super_class->GetImt(image_pointer_size_); 6181 bool same = true; 6182 for (size_t i = 0; same && i < ImTable::kSize; ++i) { 6183 ArtMethod* method = imt_data[i]; 6184 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_); 6185 if (method != super_method) { 6186 bool is_conflict_table = method->IsRuntimeMethod() && 6187 method != unimplemented_method && 6188 method != conflict_method; 6189 // Verify conflict contents. 6190 bool super_conflict_table = super_method->IsRuntimeMethod() && 6191 super_method != unimplemented_method && 6192 super_method != conflict_method; 6193 if (!is_conflict_table || !super_conflict_table) { 6194 same = false; 6195 } else { 6196 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_); 6197 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_); 6198 same = same && table1->Equals(table2, image_pointer_size_); 6199 } 6200 } 6201 } 6202 if (same) { 6203 imt = super_imt; 6204 } 6205 } 6206 if (imt == nullptr) { 6207 imt = klass->GetImt(image_pointer_size_); 6208 DCHECK(imt != nullptr); 6209 imt->Populate(imt_data, image_pointer_size_); 6210 } else { 6211 klass->SetImt(imt, image_pointer_size_); 6212 } 6213 } 6214 6215 static inline uint32_t GetIMTIndex(ArtMethod* interface_method) 6216 SHARED_REQUIRES(Locks::mutator_lock_) { 6217 return interface_method->GetDexMethodIndex() % ImTable::kSize; 6218 } 6219 6220 ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, 6221 LinearAlloc* linear_alloc, 6222 size_t image_pointer_size) { 6223 void* data = linear_alloc->Alloc(Thread::Current(), 6224 ImtConflictTable::ComputeSize(count, 6225 image_pointer_size)); 6226 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr; 6227 } 6228 6229 ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) { 6230 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_); 6231 } 6232 6233 void ClassLinker::FillIMTFromIfTable(mirror::IfTable* if_table, 6234 ArtMethod* unimplemented_method, 6235 ArtMethod* imt_conflict_method, 6236 mirror::Class* klass, 6237 bool create_conflict_tables, 6238 bool ignore_copied_methods, 6239 /*out*/bool* new_conflict, 6240 /*out*/ArtMethod** imt) { 6241 uint32_t conflict_counts[ImTable::kSize] = {}; 6242 for (size_t i = 0, length = if_table->Count(); i < length; ++i) { 6243 mirror::Class* interface = if_table->GetInterface(i); 6244 const size_t num_virtuals = interface->NumVirtualMethods(); 6245 const size_t method_array_count = if_table->GetMethodArrayCount(i); 6246 // Virtual methods can be larger than the if table methods if there are default methods. 6247 DCHECK_GE(num_virtuals, method_array_count); 6248 if (kIsDebugBuild) { 6249 if (klass->IsInterface()) { 6250 DCHECK_EQ(method_array_count, 0u); 6251 } else { 6252 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count); 6253 } 6254 } 6255 if (method_array_count == 0) { 6256 continue; 6257 } 6258 auto* method_array = if_table->GetMethodArray(i); 6259 for (size_t j = 0; j < method_array_count; ++j) { 6260 ArtMethod* implementation_method = 6261 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_); 6262 if (ignore_copied_methods && implementation_method->IsCopied()) { 6263 continue; 6264 } 6265 DCHECK(implementation_method != nullptr); 6266 // Miranda methods cannot be used to implement an interface method, but they are safe to put 6267 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods 6268 // or interface methods in the IMT here they will not create extra conflicts since we compare 6269 // names and signatures in SetIMTRef. 6270 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_); 6271 const uint32_t imt_index = GetIMTIndex(interface_method); 6272 6273 // There is only any conflicts if all of the interface methods for an IMT slot don't have 6274 // the same implementation method, keep track of this to avoid creating a conflict table in 6275 // this case. 6276 6277 // Conflict table size for each IMT slot. 6278 ++conflict_counts[imt_index]; 6279 6280 SetIMTRef(unimplemented_method, 6281 imt_conflict_method, 6282 implementation_method, 6283 /*out*/new_conflict, 6284 /*out*/&imt[imt_index]); 6285 } 6286 } 6287 6288 if (create_conflict_tables) { 6289 // Create the conflict tables. 6290 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader()); 6291 for (size_t i = 0; i < ImTable::kSize; ++i) { 6292 size_t conflicts = conflict_counts[i]; 6293 if (imt[i] == imt_conflict_method) { 6294 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc); 6295 if (new_table != nullptr) { 6296 ArtMethod* new_conflict_method = 6297 Runtime::Current()->CreateImtConflictMethod(linear_alloc); 6298 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_); 6299 imt[i] = new_conflict_method; 6300 } else { 6301 LOG(ERROR) << "Failed to allocate conflict table"; 6302 imt[i] = imt_conflict_method; 6303 } 6304 } else { 6305 DCHECK_NE(imt[i], imt_conflict_method); 6306 } 6307 } 6308 6309 for (size_t i = 0, length = if_table->Count(); i < length; ++i) { 6310 mirror::Class* interface = if_table->GetInterface(i); 6311 const size_t method_array_count = if_table->GetMethodArrayCount(i); 6312 // Virtual methods can be larger than the if table methods if there are default methods. 6313 if (method_array_count == 0) { 6314 continue; 6315 } 6316 auto* method_array = if_table->GetMethodArray(i); 6317 for (size_t j = 0; j < method_array_count; ++j) { 6318 ArtMethod* implementation_method = 6319 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_); 6320 if (ignore_copied_methods && implementation_method->IsCopied()) { 6321 continue; 6322 } 6323 DCHECK(implementation_method != nullptr); 6324 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_); 6325 const uint32_t imt_index = GetIMTIndex(interface_method); 6326 if (!imt[imt_index]->IsRuntimeMethod() || 6327 imt[imt_index] == unimplemented_method || 6328 imt[imt_index] == imt_conflict_method) { 6329 continue; 6330 } 6331 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_); 6332 const size_t num_entries = table->NumEntries(image_pointer_size_); 6333 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method); 6334 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method); 6335 } 6336 } 6337 } 6338 } 6339 6340 // Simple helper function that checks that no subtypes of 'val' are contained within the 'classes' 6341 // set. 6342 static bool NotSubinterfaceOfAny(const std::unordered_set<mirror::Class*>& classes, 6343 mirror::Class* val) 6344 REQUIRES(Roles::uninterruptible_) 6345 SHARED_REQUIRES(Locks::mutator_lock_) { 6346 DCHECK(val != nullptr); 6347 for (auto c : classes) { 6348 if (val->IsAssignableFrom(&*c)) { 6349 return false; 6350 } 6351 } 6352 return true; 6353 } 6354 6355 // Fills in and flattens the interface inheritance hierarchy. 6356 // 6357 // By the end of this function all interfaces in the transitive closure of to_process are added to 6358 // the iftable and every interface precedes all of its sub-interfaces in this list. 6359 // 6360 // all I, J: Interface | I <: J implies J precedes I 6361 // 6362 // (note A <: B means that A is a subtype of B) 6363 // 6364 // This returns the total number of items in the iftable. The iftable might be resized down after 6365 // this call. 6366 // 6367 // We order this backwards so that we do not need to reorder superclass interfaces when new 6368 // interfaces are added in subclass's interface tables. 6369 // 6370 // Upon entry into this function iftable is a copy of the superclass's iftable with the first 6371 // super_ifcount entries filled in with the transitive closure of the interfaces of the superclass. 6372 // The other entries are uninitialized. We will fill in the remaining entries in this function. The 6373 // iftable must be large enough to hold all interfaces without changing its size. 6374 static size_t FillIfTable(mirror::IfTable* iftable, 6375 size_t super_ifcount, 6376 std::vector<mirror::Class*> to_process) 6377 REQUIRES(Roles::uninterruptible_) 6378 SHARED_REQUIRES(Locks::mutator_lock_) { 6379 // This is the set of all class's already in the iftable. Used to make checking if a class has 6380 // already been added quicker. 6381 std::unordered_set<mirror::Class*> classes_in_iftable; 6382 // The first super_ifcount elements are from the superclass. We note that they are already added. 6383 for (size_t i = 0; i < super_ifcount; i++) { 6384 mirror::Class* iface = iftable->GetInterface(i); 6385 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering."; 6386 classes_in_iftable.insert(iface); 6387 } 6388 size_t filled_ifcount = super_ifcount; 6389 for (mirror::Class* interface : to_process) { 6390 // Let us call the first filled_ifcount elements of iftable the current-iface-list. 6391 // At this point in the loop current-iface-list has the invariant that: 6392 // for every pair of interfaces I,J within it: 6393 // if index_of(I) < index_of(J) then I is not a subtype of J 6394 6395 // If we have already seen this element then all of its super-interfaces must already be in the 6396 // current-iface-list so we can skip adding it. 6397 if (!ContainsElement(classes_in_iftable, interface)) { 6398 // We haven't seen this interface so add all of its super-interfaces onto the 6399 // current-iface-list, skipping those already on it. 6400 int32_t ifcount = interface->GetIfTableCount(); 6401 for (int32_t j = 0; j < ifcount; j++) { 6402 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j); 6403 if (!ContainsElement(classes_in_iftable, super_interface)) { 6404 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering."; 6405 classes_in_iftable.insert(super_interface); 6406 iftable->SetInterface(filled_ifcount, super_interface); 6407 filled_ifcount++; 6408 } 6409 } 6410 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering"; 6411 // Place this interface onto the current-iface-list after all of its super-interfaces. 6412 classes_in_iftable.insert(interface); 6413 iftable->SetInterface(filled_ifcount, interface); 6414 filled_ifcount++; 6415 } else if (kIsDebugBuild) { 6416 // Check all super-interfaces are already in the list. 6417 int32_t ifcount = interface->GetIfTableCount(); 6418 for (int32_t j = 0; j < ifcount; j++) { 6419 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j); 6420 DCHECK(ContainsElement(classes_in_iftable, super_interface)) 6421 << "Iftable does not contain " << PrettyClass(super_interface) 6422 << ", a superinterface of " << PrettyClass(interface); 6423 } 6424 } 6425 } 6426 if (kIsDebugBuild) { 6427 // Check that the iftable is ordered correctly. 6428 for (size_t i = 0; i < filled_ifcount; i++) { 6429 mirror::Class* if_a = iftable->GetInterface(i); 6430 for (size_t j = i + 1; j < filled_ifcount; j++) { 6431 mirror::Class* if_b = iftable->GetInterface(j); 6432 // !(if_a <: if_b) 6433 CHECK(!if_b->IsAssignableFrom(if_a)) 6434 << "Bad interface order: " << PrettyClass(if_a) << " (index " << i << ") extends " 6435 << PrettyClass(if_b) << " (index " << j << ") and so should be after it in the " 6436 << "interface list."; 6437 } 6438 } 6439 } 6440 return filled_ifcount; 6441 } 6442 6443 bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass, 6444 Handle<mirror::ObjectArray<mirror::Class>> interfaces) { 6445 StackHandleScope<1> hs(self); 6446 const size_t super_ifcount = 6447 klass->HasSuperClass() ? klass->GetSuperClass()->GetIfTableCount() : 0U; 6448 const bool have_interfaces = interfaces.Get() != nullptr; 6449 const size_t num_interfaces = 6450 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces(); 6451 if (num_interfaces == 0) { 6452 if (super_ifcount == 0) { 6453 // Class implements no interfaces. 6454 DCHECK_EQ(klass->GetIfTableCount(), 0); 6455 DCHECK(klass->GetIfTable() == nullptr); 6456 return true; 6457 } 6458 // Class implements same interfaces as parent, are any of these not marker interfaces? 6459 bool has_non_marker_interface = false; 6460 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 6461 for (size_t i = 0; i < super_ifcount; ++i) { 6462 if (super_iftable->GetMethodArrayCount(i) > 0) { 6463 has_non_marker_interface = true; 6464 break; 6465 } 6466 } 6467 // Class just inherits marker interfaces from parent so recycle parent's iftable. 6468 if (!has_non_marker_interface) { 6469 klass->SetIfTable(super_iftable); 6470 return true; 6471 } 6472 } 6473 size_t ifcount = super_ifcount + num_interfaces; 6474 // Check that every class being implemented is an interface. 6475 for (size_t i = 0; i < num_interfaces; i++) { 6476 mirror::Class* interface = have_interfaces 6477 ? interfaces->GetWithoutChecks(i) 6478 : mirror::Class::GetDirectInterface(self, klass, i); 6479 DCHECK(interface != nullptr); 6480 if (UNLIKELY(!interface->IsInterface())) { 6481 std::string temp; 6482 ThrowIncompatibleClassChangeError(klass.Get(), 6483 "Class %s implements non-interface class %s", 6484 PrettyDescriptor(klass.Get()).c_str(), 6485 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str()); 6486 return false; 6487 } 6488 ifcount += interface->GetIfTableCount(); 6489 } 6490 // Create the interface function table. 6491 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount))); 6492 if (UNLIKELY(iftable.Get() == nullptr)) { 6493 self->AssertPendingOOMException(); 6494 return false; 6495 } 6496 // Fill in table with superclass's iftable. 6497 if (super_ifcount != 0) { 6498 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 6499 for (size_t i = 0; i < super_ifcount; i++) { 6500 mirror::Class* super_interface = super_iftable->GetInterface(i); 6501 iftable->SetInterface(i, super_interface); 6502 } 6503 } 6504 6505 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread 6506 // cancellation. That is it will suspend if one has a pending suspend request but otherwise 6507 // doesn't really do anything. 6508 self->AllowThreadSuspension(); 6509 6510 size_t new_ifcount; 6511 { 6512 ScopedAssertNoThreadSuspension nts(self, "Copying mirror::Class*'s for FillIfTable"); 6513 std::vector<mirror::Class*> to_add; 6514 for (size_t i = 0; i < num_interfaces; i++) { 6515 mirror::Class* interface = have_interfaces ? interfaces->Get(i) : 6516 mirror::Class::GetDirectInterface(self, klass, i); 6517 to_add.push_back(interface); 6518 } 6519 6520 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add)); 6521 } 6522 6523 self->AllowThreadSuspension(); 6524 6525 // Shrink iftable in case duplicates were found 6526 if (new_ifcount < ifcount) { 6527 DCHECK_NE(num_interfaces, 0U); 6528 iftable.Assign(down_cast<mirror::IfTable*>( 6529 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax))); 6530 if (UNLIKELY(iftable.Get() == nullptr)) { 6531 self->AssertPendingOOMException(); 6532 return false; 6533 } 6534 ifcount = new_ifcount; 6535 } else { 6536 DCHECK_EQ(new_ifcount, ifcount); 6537 } 6538 klass->SetIfTable(iftable.Get()); 6539 return true; 6540 } 6541 6542 // Finds the method with a name/signature that matches cmp in the given lists of methods. The list 6543 // of methods must be unique. 6544 static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) { 6545 return nullptr; 6546 } 6547 6548 template <typename ... Types> 6549 static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp, 6550 const ScopedArenaVector<ArtMethod*>& list, 6551 const Types& ... rest) 6552 SHARED_REQUIRES(Locks::mutator_lock_) { 6553 for (ArtMethod* method : list) { 6554 if (cmp.HasSameNameAndSignature(method)) { 6555 return method; 6556 } 6557 } 6558 return FindSameNameAndSignature(cmp, rest...); 6559 } 6560 6561 // Check that all vtable entries are present in this class's virtuals or are the same as a 6562 // superclasses vtable entry. 6563 static void CheckClassOwnsVTableEntries(Thread* self, 6564 Handle<mirror::Class> klass, 6565 size_t pointer_size) 6566 SHARED_REQUIRES(Locks::mutator_lock_) { 6567 StackHandleScope<2> hs(self); 6568 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking())); 6569 mirror::Class* super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr; 6570 Handle<mirror::Class> superclass(hs.NewHandle(super_temp)); 6571 int32_t super_vtable_length = (superclass.Get() != nullptr) ? superclass->GetVTableLength() : 0; 6572 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) { 6573 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size); 6574 CHECK(m != nullptr); 6575 6576 CHECK_EQ(m->GetMethodIndexDuringLinking(), i) 6577 << PrettyMethod(m) << " has an unexpected method index for its spot in the vtable for class" 6578 << PrettyClass(klass.Get()); 6579 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size); 6580 auto is_same_method = [m] (const ArtMethod& meth) { 6581 return &meth == m; 6582 }; 6583 CHECK((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) || 6584 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end()) 6585 << PrettyMethod(m) << " does not seem to be owned by current class " 6586 << PrettyClass(klass.Get()) << " or any of its superclasses!"; 6587 } 6588 } 6589 6590 // Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a 6591 // method is overridden in a subclass. 6592 static void CheckVTableHasNoDuplicates(Thread* self, 6593 Handle<mirror::Class> klass, 6594 size_t pointer_size) 6595 SHARED_REQUIRES(Locks::mutator_lock_) { 6596 StackHandleScope<1> hs(self); 6597 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking())); 6598 int32_t num_entries = vtable->GetLength(); 6599 for (int32_t i = 0; i < num_entries; i++) { 6600 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size); 6601 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member maybe). 6602 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(), 6603 vtable_entry->GetAccessFlags())) { 6604 continue; 6605 } 6606 MethodNameAndSignatureComparator name_comparator( 6607 vtable_entry->GetInterfaceMethodIfProxy(pointer_size)); 6608 for (int32_t j = i+1; j < num_entries; j++) { 6609 ArtMethod* other_entry = vtable->GetElementPtrSize<ArtMethod*>(j, pointer_size); 6610 CHECK(vtable_entry != other_entry && 6611 !name_comparator.HasSameNameAndSignature( 6612 other_entry->GetInterfaceMethodIfProxy(pointer_size))) 6613 << "vtable entries " << i << " and " << j << " are identical for " 6614 << PrettyClass(klass.Get()) << " in method " << PrettyMethod(vtable_entry) << " and " 6615 << PrettyMethod(other_entry); 6616 } 6617 } 6618 } 6619 6620 static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, size_t pointer_size) 6621 SHARED_REQUIRES(Locks::mutator_lock_) { 6622 CheckClassOwnsVTableEntries(self, klass, pointer_size); 6623 CheckVTableHasNoDuplicates(self, klass, pointer_size); 6624 } 6625 6626 void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass, 6627 ArtMethod* unimplemented_method, 6628 ArtMethod* imt_conflict_method, 6629 bool* new_conflict, 6630 ArtMethod** imt) { 6631 DCHECK(klass->HasSuperClass()); 6632 mirror::Class* super_class = klass->GetSuperClass(); 6633 if (super_class->ShouldHaveImt()) { 6634 ImTable* super_imt = super_class->GetImt(image_pointer_size_); 6635 for (size_t i = 0; i < ImTable::kSize; ++i) { 6636 imt[i] = super_imt->Get(i, image_pointer_size_); 6637 } 6638 } else { 6639 // No imt in the super class, need to reconstruct from the iftable. 6640 mirror::IfTable* if_table = super_class->GetIfTable(); 6641 if (if_table != nullptr) { 6642 // Ignore copied methods since we will handle these in LinkInterfaceMethods. 6643 FillIMTFromIfTable(if_table, 6644 unimplemented_method, 6645 imt_conflict_method, 6646 klass.Get(), 6647 /*create_conflict_table*/false, 6648 /*ignore_copied_methods*/true, 6649 /*out*/new_conflict, 6650 /*out*/imt); 6651 } 6652 } 6653 } 6654 6655 // TODO This method needs to be split up into several smaller methods. 6656 bool ClassLinker::LinkInterfaceMethods( 6657 Thread* self, 6658 Handle<mirror::Class> klass, 6659 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations, 6660 bool* out_new_conflict, 6661 ArtMethod** out_imt) { 6662 StackHandleScope<3> hs(self); 6663 Runtime* const runtime = Runtime::Current(); 6664 6665 const bool is_interface = klass->IsInterface(); 6666 const bool has_superclass = klass->HasSuperClass(); 6667 const bool fill_tables = !is_interface; 6668 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U; 6669 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_); 6670 const size_t method_size = ArtMethod::Size(image_pointer_size_); 6671 const size_t ifcount = klass->GetIfTableCount(); 6672 6673 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable())); 6674 6675 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create 6676 // the virtual methods array. 6677 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array 6678 // during cross compilation. 6679 // Use the linear alloc pool since this one is in the low 4gb for the compiler. 6680 ArenaStack stack(runtime->GetLinearAlloc()->GetArenaPool()); 6681 ScopedArenaAllocator allocator(&stack); 6682 6683 ScopedArenaVector<ArtMethod*> default_conflict_methods(allocator.Adapter()); 6684 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods(allocator.Adapter()); 6685 ScopedArenaVector<ArtMethod*> miranda_methods(allocator.Adapter()); 6686 ScopedArenaVector<ArtMethod*> default_methods(allocator.Adapter()); 6687 ScopedArenaVector<ArtMethod*> overriding_default_methods(allocator.Adapter()); 6688 6689 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking())); 6690 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod(); 6691 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod(); 6692 // Copy the IMT from the super class if possible. 6693 const bool extend_super_iftable = has_superclass; 6694 if (has_superclass && fill_tables) { 6695 FillImtFromSuperClass(klass, 6696 unimplemented_method, 6697 imt_conflict_method, 6698 out_new_conflict, 6699 out_imt); 6700 } 6701 // Allocate method arrays before since we don't want miss visiting miranda method roots due to 6702 // thread suspension. 6703 if (fill_tables) { 6704 for (size_t i = 0; i < ifcount; ++i) { 6705 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods(); 6706 if (num_methods > 0) { 6707 const bool is_super = i < super_ifcount; 6708 // This is an interface implemented by a super-class. Therefore we can just copy the method 6709 // array from the superclass. 6710 const bool super_interface = is_super && extend_super_iftable; 6711 mirror::PointerArray* method_array; 6712 if (super_interface) { 6713 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable(); 6714 DCHECK(if_table != nullptr); 6715 DCHECK(if_table->GetMethodArray(i) != nullptr); 6716 // If we are working on a super interface, try extending the existing method array. 6717 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self)); 6718 } else { 6719 method_array = AllocPointerArray(self, num_methods); 6720 } 6721 if (UNLIKELY(method_array == nullptr)) { 6722 self->AssertPendingOOMException(); 6723 return false; 6724 } 6725 iftable->SetMethodArray(i, method_array); 6726 } 6727 } 6728 } 6729 6730 auto* old_cause = self->StartAssertNoThreadSuspension( 6731 "Copying ArtMethods for LinkInterfaceMethods"); 6732 // Going in reverse to ensure that we will hit abstract methods that override defaults before the 6733 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since 6734 // they will already be null. This has the additional benefit that the declarer of a miranda 6735 // method will actually declare an abstract method. 6736 for (size_t i = ifcount; i != 0; ) { 6737 --i; 6738 6739 DCHECK_GE(i, 0u); 6740 DCHECK_LT(i, ifcount); 6741 6742 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods(); 6743 if (num_methods > 0) { 6744 StackHandleScope<2> hs2(self); 6745 const bool is_super = i < super_ifcount; 6746 const bool super_interface = is_super && extend_super_iftable; 6747 // We don't actually create or fill these tables for interfaces, we just copy some methods for 6748 // conflict methods. Just set this as nullptr in those cases. 6749 Handle<mirror::PointerArray> method_array(fill_tables 6750 ? hs2.NewHandle(iftable->GetMethodArray(i)) 6751 : hs2.NewHandle<mirror::PointerArray>(nullptr)); 6752 6753 ArraySlice<ArtMethod> input_virtual_methods; 6754 ScopedNullHandle<mirror::PointerArray> null_handle; 6755 Handle<mirror::PointerArray> input_vtable_array(null_handle); 6756 int32_t input_array_length = 0; 6757 6758 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty 6759 // and confusing. Default methods should always look through all the superclasses 6760 // because they are the last choice of an implementation. We get around this by looking 6761 // at the super-classes iftable methods (copied into method_array previously) when we are 6762 // looking for the implementation of a super-interface method but that is rather dirty. 6763 bool using_virtuals; 6764 if (super_interface || is_interface) { 6765 // If we are overwriting a super class interface, try to only virtual methods instead of the 6766 // whole vtable. 6767 using_virtuals = true; 6768 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_); 6769 input_array_length = input_virtual_methods.size(); 6770 } else { 6771 // For a new interface, however, we need the whole vtable in case a new 6772 // interface method is implemented in the whole superclass. 6773 using_virtuals = false; 6774 DCHECK(vtable.Get() != nullptr); 6775 input_vtable_array = vtable; 6776 input_array_length = input_vtable_array->GetLength(); 6777 } 6778 6779 // For each method in interface 6780 for (size_t j = 0; j < num_methods; ++j) { 6781 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_); 6782 MethodNameAndSignatureComparator interface_name_comparator( 6783 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_)); 6784 uint32_t imt_index = GetIMTIndex(interface_method); 6785 ArtMethod** imt_ptr = &out_imt[imt_index]; 6786 // For each method listed in the interface's method list, find the 6787 // matching method in our class's method list. We want to favor the 6788 // subclass over the superclass, which just requires walking 6789 // back from the end of the vtable. (This only matters if the 6790 // superclass defines a private method and this class redefines 6791 // it -- otherwise it would use the same vtable slot. In .dex files 6792 // those don't end up in the virtual method table, so it shouldn't 6793 // matter which direction we go. We walk it backward anyway.) 6794 // 6795 // To find defaults we need to do the same but also go over interfaces. 6796 bool found_impl = false; 6797 ArtMethod* vtable_impl = nullptr; 6798 for (int32_t k = input_array_length - 1; k >= 0; --k) { 6799 ArtMethod* vtable_method = using_virtuals ? 6800 &input_virtual_methods[k] : 6801 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_); 6802 ArtMethod* vtable_method_for_name_comparison = 6803 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_); 6804 if (interface_name_comparator.HasSameNameAndSignature( 6805 vtable_method_for_name_comparison)) { 6806 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) { 6807 // Must do EndAssertNoThreadSuspension before throw since the throw can cause 6808 // allocations. 6809 self->EndAssertNoThreadSuspension(old_cause); 6810 ThrowIllegalAccessError(klass.Get(), 6811 "Method '%s' implementing interface method '%s' is not public", 6812 PrettyMethod(vtable_method).c_str(), PrettyMethod(interface_method).c_str()); 6813 return false; 6814 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) { 6815 // We might have a newer, better, default method for this, so we just skip it. If we 6816 // are still using this we will select it again when scanning for default methods. To 6817 // obviate the need to copy the method again we will make a note that we already found 6818 // a default here. 6819 // TODO This should be much cleaner. 6820 vtable_impl = vtable_method; 6821 break; 6822 } else { 6823 found_impl = true; 6824 if (LIKELY(fill_tables)) { 6825 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_); 6826 // Place method in imt if entry is empty, place conflict otherwise. 6827 SetIMTRef(unimplemented_method, 6828 imt_conflict_method, 6829 vtable_method, 6830 /*out*/out_new_conflict, 6831 /*out*/imt_ptr); 6832 } 6833 break; 6834 } 6835 } 6836 } 6837 // Continue on to the next method if we are done. 6838 if (LIKELY(found_impl)) { 6839 continue; 6840 } else if (LIKELY(super_interface)) { 6841 // Don't look for a default implementation when the super-method is implemented directly 6842 // by the class. 6843 // 6844 // See if we can use the superclasses method and skip searching everything else. 6845 // Note: !found_impl && super_interface 6846 CHECK(extend_super_iftable); 6847 // If this is a super_interface method it is possible we shouldn't override it because a 6848 // superclass could have implemented it directly. We get the method the superclass used 6849 // to implement this to know if we can override it with a default method. Doing this is 6850 // safe since we know that the super_iftable is filled in so we can simply pull it from 6851 // there. We don't bother if this is not a super-classes interface since in that case we 6852 // have scanned the entire vtable anyway and would have found it. 6853 // TODO This is rather dirty but it is faster than searching through the entire vtable 6854 // every time. 6855 ArtMethod* supers_method = 6856 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_); 6857 DCHECK(supers_method != nullptr); 6858 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method)); 6859 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) { 6860 // The method is not overridable by a default method (i.e. it is directly implemented 6861 // in some class). Therefore move onto the next interface method. 6862 continue; 6863 } else { 6864 // If the super-classes method is override-able by a default method we need to keep 6865 // track of it since though it is override-able it is not guaranteed to be 'overridden'. 6866 // If it turns out not to be overridden and we did not keep track of it we might add it 6867 // to the vtable twice, causing corruption in this class and possibly any subclasses. 6868 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method) 6869 << "vtable_impl was " << PrettyMethod(vtable_impl) << " and not 'nullptr' or " 6870 << PrettyMethod(supers_method) << " as expected. IFTable appears to be corrupt!"; 6871 vtable_impl = supers_method; 6872 } 6873 } 6874 // If we haven't found it yet we should search through the interfaces for default methods. 6875 ArtMethod* current_method = nullptr; 6876 switch (FindDefaultMethodImplementation(self, 6877 interface_method, 6878 klass, 6879 /*out*/¤t_method)) { 6880 case DefaultMethodSearchResult::kDefaultConflict: { 6881 // Default method conflict. 6882 DCHECK(current_method == nullptr); 6883 ArtMethod* default_conflict_method = nullptr; 6884 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) { 6885 // We can reuse the method from the superclass, don't bother adding it to virtuals. 6886 default_conflict_method = vtable_impl; 6887 } else { 6888 // See if we already have a conflict method for this method. 6889 ArtMethod* preexisting_conflict = FindSameNameAndSignature( 6890 interface_name_comparator, 6891 default_conflict_methods, 6892 overriding_default_conflict_methods); 6893 if (LIKELY(preexisting_conflict != nullptr)) { 6894 // We already have another conflict we can reuse. 6895 default_conflict_method = preexisting_conflict; 6896 } else { 6897 // Note that we do this even if we are an interface since we need to create this and 6898 // cannot reuse another classes. 6899 // Create a new conflict method for this to use. 6900 default_conflict_method = 6901 reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size)); 6902 new(default_conflict_method) ArtMethod(interface_method, image_pointer_size_); 6903 if (vtable_impl == nullptr) { 6904 // Save the conflict method. We need to add it to the vtable. 6905 default_conflict_methods.push_back(default_conflict_method); 6906 } else { 6907 // Save the conflict method but it is already in the vtable. 6908 overriding_default_conflict_methods.push_back(default_conflict_method); 6909 } 6910 } 6911 } 6912 current_method = default_conflict_method; 6913 break; 6914 } // case kDefaultConflict 6915 case DefaultMethodSearchResult::kDefaultFound: { 6916 DCHECK(current_method != nullptr); 6917 // Found a default method. 6918 if (vtable_impl != nullptr && 6919 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) { 6920 // We found a default method but it was the same one we already have from our 6921 // superclass. Don't bother adding it to our vtable again. 6922 current_method = vtable_impl; 6923 } else if (LIKELY(fill_tables)) { 6924 // Interfaces don't need to copy default methods since they don't have vtables. 6925 // Only record this default method if it is new to save space. 6926 // TODO It might be worthwhile to copy default methods on interfaces anyway since it 6927 // would make lookup for interface super much faster. (We would only need to scan 6928 // the iftable to find if there is a NSME or AME.) 6929 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator, 6930 default_methods, 6931 overriding_default_methods); 6932 if (old == nullptr) { 6933 // We found a default method implementation and there were no conflicts. 6934 if (vtable_impl == nullptr) { 6935 // Save the default method. We need to add it to the vtable. 6936 default_methods.push_back(current_method); 6937 } else { 6938 // Save the default method but it is already in the vtable. 6939 overriding_default_methods.push_back(current_method); 6940 } 6941 } else { 6942 CHECK(old == current_method) << "Multiple default implementations selected!"; 6943 } 6944 } 6945 break; 6946 } // case kDefaultFound 6947 case DefaultMethodSearchResult::kAbstractFound: { 6948 DCHECK(current_method == nullptr); 6949 // Abstract method masks all defaults. 6950 if (vtable_impl != nullptr && 6951 vtable_impl->IsAbstract() && 6952 !vtable_impl->IsDefaultConflicting()) { 6953 // We need to make this an abstract method but the version in the vtable already is so 6954 // don't do anything. 6955 current_method = vtable_impl; 6956 } 6957 break; 6958 } // case kAbstractFound 6959 } 6960 if (LIKELY(fill_tables)) { 6961 if (current_method == nullptr && !super_interface) { 6962 // We could not find an implementation for this method and since it is a brand new 6963 // interface we searched the entire vtable (and all default methods) for an 6964 // implementation but couldn't find one. We therefore need to make a miranda method. 6965 // 6966 // Find out if there is already a miranda method we can use. 6967 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator, 6968 miranda_methods); 6969 if (miranda_method == nullptr) { 6970 DCHECK(interface_method->IsAbstract()) << PrettyMethod(interface_method); 6971 miranda_method = reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size)); 6972 CHECK(miranda_method != nullptr); 6973 // Point the interface table at a phantom slot. 6974 new(miranda_method) ArtMethod(interface_method, image_pointer_size_); 6975 miranda_methods.push_back(miranda_method); 6976 } 6977 current_method = miranda_method; 6978 } 6979 6980 if (current_method != nullptr) { 6981 // We found a default method implementation. Record it in the iftable and IMT. 6982 method_array->SetElementPtrSize(j, current_method, image_pointer_size_); 6983 SetIMTRef(unimplemented_method, 6984 imt_conflict_method, 6985 current_method, 6986 /*out*/out_new_conflict, 6987 /*out*/imt_ptr); 6988 } 6989 } 6990 } // For each method in interface end. 6991 } // if (num_methods > 0) 6992 } // For each interface. 6993 const bool has_new_virtuals = !(miranda_methods.empty() && 6994 default_methods.empty() && 6995 overriding_default_methods.empty() && 6996 overriding_default_conflict_methods.empty() && 6997 default_conflict_methods.empty()); 6998 // TODO don't extend virtuals of interface unless necessary (when is it?). 6999 if (has_new_virtuals) { 7000 DCHECK(!is_interface || (default_methods.empty() && miranda_methods.empty())) 7001 << "Interfaces should only have default-conflict methods appended to them."; 7002 VLOG(class_linker) << PrettyClass(klass.Get()) << ": miranda_methods=" << miranda_methods.size() 7003 << " default_methods=" << default_methods.size() 7004 << " overriding_default_methods=" << overriding_default_methods.size() 7005 << " default_conflict_methods=" << default_conflict_methods.size() 7006 << " overriding_default_conflict_methods=" 7007 << overriding_default_conflict_methods.size(); 7008 const size_t old_method_count = klass->NumMethods(); 7009 const size_t new_method_count = old_method_count + 7010 miranda_methods.size() + 7011 default_methods.size() + 7012 overriding_default_conflict_methods.size() + 7013 overriding_default_methods.size() + 7014 default_conflict_methods.size(); 7015 // Attempt to realloc to save RAM if possible. 7016 LengthPrefixedArray<ArtMethod>* old_methods = klass->GetMethodsPtr(); 7017 // The Realloced virtual methods aren't visible from the class roots, so there is no issue 7018 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the 7019 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since 7020 // CopyFrom has internal read barriers. 7021 // 7022 // TODO We should maybe move some of this into mirror::Class or at least into another method. 7023 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count, 7024 method_size, 7025 method_alignment); 7026 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count, 7027 method_size, 7028 method_alignment); 7029 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0; 7030 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>( 7031 runtime->GetLinearAlloc()->Realloc(self, old_methods, old_methods_ptr_size, new_size)); 7032 if (UNLIKELY(methods == nullptr)) { 7033 self->AssertPendingOOMException(); 7034 self->EndAssertNoThreadSuspension(old_cause); 7035 return false; 7036 } 7037 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table(allocator.Adapter()); 7038 if (methods != old_methods) { 7039 // Maps from heap allocated miranda method to linear alloc miranda method. 7040 StrideIterator<ArtMethod> out = methods->begin(method_size, method_alignment); 7041 // Copy over the old methods. 7042 for (auto& m : klass->GetMethods(image_pointer_size_)) { 7043 move_table.emplace(&m, &*out); 7044 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read 7045 // barriers when it copies. 7046 out->CopyFrom(&m, image_pointer_size_); 7047 ++out; 7048 } 7049 } 7050 StrideIterator<ArtMethod> out(methods->begin(method_size, method_alignment) + old_method_count); 7051 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and 7052 // we want the roots of the miranda methods to get visited. 7053 for (ArtMethod* mir_method : miranda_methods) { 7054 ArtMethod& new_method = *out; 7055 new_method.CopyFrom(mir_method, image_pointer_size_); 7056 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied); 7057 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u) 7058 << "Miranda method should be abstract!"; 7059 move_table.emplace(mir_method, &new_method); 7060 ++out; 7061 } 7062 // We need to copy the default methods into our own method table since the runtime requires that 7063 // every method on a class's vtable be in that respective class's virtual method table. 7064 // NOTE This means that two classes might have the same implementation of a method from the same 7065 // interface but will have different ArtMethod*s for them. This also means we cannot compare a 7066 // default method found on a class with one found on the declaring interface directly and must 7067 // look at the declaring class to determine if they are the same. 7068 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods, 7069 overriding_default_methods}) { 7070 for (ArtMethod* def_method : methods_vec) { 7071 ArtMethod& new_method = *out; 7072 new_method.CopyFrom(def_method, image_pointer_size_); 7073 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been 7074 // verified yet it shouldn't have methods that are skipping access checks. 7075 // TODO This is rather arbitrary. We should maybe support classes where only some of its 7076 // methods are skip_access_checks. 7077 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied; 7078 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks; 7079 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags); 7080 move_table.emplace(def_method, &new_method); 7081 ++out; 7082 } 7083 } 7084 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_conflict_methods, 7085 overriding_default_conflict_methods}) { 7086 for (ArtMethod* conf_method : methods_vec) { 7087 ArtMethod& new_method = *out; 7088 new_method.CopyFrom(conf_method, image_pointer_size_); 7089 // This is a type of default method (there are default method impls, just a conflict) so 7090 // mark this as a default, non-abstract method, since thats what it is. Also clear the 7091 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have 7092 // methods that are skipping access checks. 7093 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied; 7094 constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks); 7095 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags); 7096 DCHECK(new_method.IsDefaultConflicting()); 7097 // The actual method might or might not be marked abstract since we just copied it from a 7098 // (possibly default) interface method. We need to set it entry point to be the bridge so 7099 // that the compiler will not invoke the implementation of whatever method we copied from. 7100 EnsureThrowsInvocationError(&new_method); 7101 move_table.emplace(conf_method, &new_method); 7102 ++out; 7103 } 7104 } 7105 methods->SetSize(new_method_count); 7106 UpdateClassMethods(klass.Get(), methods); 7107 // Done copying methods, they are all roots in the class now, so we can end the no thread 7108 // suspension assert. 7109 self->EndAssertNoThreadSuspension(old_cause); 7110 7111 if (fill_tables) { 7112 // Update the vtable to the new method structures. We can skip this for interfaces since they 7113 // do not have vtables. 7114 const size_t old_vtable_count = vtable->GetLength(); 7115 const size_t new_vtable_count = old_vtable_count + 7116 miranda_methods.size() + 7117 default_methods.size() + 7118 default_conflict_methods.size(); 7119 7120 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, new_vtable_count))); 7121 if (UNLIKELY(vtable.Get() == nullptr)) { 7122 self->AssertPendingOOMException(); 7123 return false; 7124 } 7125 size_t vtable_pos = old_vtable_count; 7126 // Update all the newly copied method's indexes so they denote their placement in the vtable. 7127 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods, 7128 default_conflict_methods, 7129 miranda_methods}) { 7130 // These are the functions that are not already in the vtable! 7131 for (ArtMethod* new_method : methods_vec) { 7132 auto translated_method_it = move_table.find(new_method); 7133 CHECK(translated_method_it != move_table.end()) 7134 << "We must have a translation for methods added to the classes methods_ array! We " 7135 << "could not find the ArtMethod added for " << PrettyMethod(new_method); 7136 ArtMethod* new_vtable_method = translated_method_it->second; 7137 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_ 7138 // fields are references into the dex file the method was defined in. Since the ArtMethod 7139 // does not store that information it uses declaring_class_->dex_cache_. 7140 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos); 7141 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, image_pointer_size_); 7142 ++vtable_pos; 7143 } 7144 } 7145 CHECK_EQ(vtable_pos, new_vtable_count); 7146 // Update old vtable methods. We use the default_translations map to figure out what each 7147 // vtable entry should be updated to, if they need to be at all. 7148 for (size_t i = 0; i < old_vtable_count; ++i) { 7149 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>( 7150 i, image_pointer_size_); 7151 // Try and find what we need to change this method to. 7152 auto translation_it = default_translations.find(i); 7153 bool found_translation = false; 7154 if (translation_it != default_translations.end()) { 7155 if (translation_it->second.IsInConflict()) { 7156 // Find which conflict method we are to use for this method. 7157 MethodNameAndSignatureComparator old_method_comparator( 7158 translated_method->GetInterfaceMethodIfProxy(image_pointer_size_)); 7159 // We only need to look through overriding_default_conflict_methods since this is an 7160 // overridden method we are fixing up here. 7161 ArtMethod* new_conflict_method = FindSameNameAndSignature( 7162 old_method_comparator, overriding_default_conflict_methods); 7163 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!"; 7164 translated_method = new_conflict_method; 7165 } else if (translation_it->second.IsAbstract()) { 7166 // Find which miranda method we are to use for this method. 7167 MethodNameAndSignatureComparator old_method_comparator( 7168 translated_method->GetInterfaceMethodIfProxy(image_pointer_size_)); 7169 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator, 7170 miranda_methods); 7171 DCHECK(miranda_method != nullptr); 7172 translated_method = miranda_method; 7173 } else { 7174 // Normal default method (changed from an older default or abstract interface method). 7175 DCHECK(translation_it->second.IsTranslation()); 7176 translated_method = translation_it->second.GetTranslation(); 7177 } 7178 found_translation = true; 7179 } 7180 DCHECK(translated_method != nullptr); 7181 auto it = move_table.find(translated_method); 7182 if (it != move_table.end()) { 7183 auto* new_method = it->second; 7184 DCHECK(new_method != nullptr); 7185 // Make sure the new_methods index is set. 7186 if (new_method->GetMethodIndexDuringLinking() != i) { 7187 DCHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size, method_alignment)), 7188 reinterpret_cast<uintptr_t>(new_method)); 7189 DCHECK_LT(reinterpret_cast<uintptr_t>(new_method), 7190 reinterpret_cast<uintptr_t>(&*methods->end(method_size, method_alignment))); 7191 new_method->SetMethodIndex(0xFFFF & i); 7192 } 7193 vtable->SetElementPtrSize(i, new_method, image_pointer_size_); 7194 } else { 7195 // If it was not going to be updated we wouldn't have put it into the default_translations 7196 // map. 7197 CHECK(!found_translation) << "We were asked to update this vtable entry. Must not fail."; 7198 } 7199 } 7200 klass->SetVTable(vtable.Get()); 7201 7202 // Go fix up all the stale iftable pointers. 7203 for (size_t i = 0; i < ifcount; ++i) { 7204 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) { 7205 auto* method_array = iftable->GetMethodArray(i); 7206 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_); 7207 DCHECK(m != nullptr) << PrettyClass(klass.Get()); 7208 auto it = move_table.find(m); 7209 if (it != move_table.end()) { 7210 auto* new_m = it->second; 7211 DCHECK(new_m != nullptr) << PrettyClass(klass.Get()); 7212 method_array->SetElementPtrSize(j, new_m, image_pointer_size_); 7213 } 7214 } 7215 } 7216 7217 // Fix up IMT next 7218 for (size_t i = 0; i < ImTable::kSize; ++i) { 7219 auto it = move_table.find(out_imt[i]); 7220 if (it != move_table.end()) { 7221 out_imt[i] = it->second; 7222 } 7223 } 7224 } 7225 7226 // Check that there are no stale methods are in the dex cache array. 7227 if (kIsDebugBuild) { 7228 auto* resolved_methods = klass->GetDexCache()->GetResolvedMethods(); 7229 for (size_t i = 0, count = klass->GetDexCache()->NumResolvedMethods(); i < count; ++i) { 7230 auto* m = mirror::DexCache::GetElementPtrSize(resolved_methods, i, image_pointer_size_); 7231 CHECK(move_table.find(m) == move_table.end() || 7232 // The original versions of copied methods will still be present so allow those too. 7233 // Note that if the first check passes this might fail to GetDeclaringClass(). 7234 std::find_if(m->GetDeclaringClass()->GetMethods(image_pointer_size_).begin(), 7235 m->GetDeclaringClass()->GetMethods(image_pointer_size_).end(), 7236 [m] (ArtMethod& meth) { 7237 return &meth == m; 7238 }) != m->GetDeclaringClass()->GetMethods(image_pointer_size_).end()) 7239 << "Obsolete methods " << PrettyMethod(m) << " is in dex cache!"; 7240 } 7241 } 7242 // Put some random garbage in old methods to help find stale pointers. 7243 if (methods != old_methods && old_methods != nullptr && kIsDebugBuild) { 7244 // Need to make sure the GC is not running since it could be scanning the methods we are 7245 // about to overwrite. 7246 ScopedThreadStateChange tsc(self, kSuspended); 7247 gc::ScopedGCCriticalSection gcs(self, 7248 gc::kGcCauseClassLinker, 7249 gc::kCollectorTypeClassLinker); 7250 memset(old_methods, 0xFEu, old_size); 7251 } 7252 } else { 7253 self->EndAssertNoThreadSuspension(old_cause); 7254 } 7255 if (kIsDebugBuild && !is_interface) { 7256 SanityCheckVTable(self, klass, image_pointer_size_); 7257 } 7258 return true; 7259 } 7260 7261 bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) { 7262 CHECK(klass.Get() != nullptr); 7263 return LinkFields(self, klass, false, nullptr); 7264 } 7265 7266 bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) { 7267 CHECK(klass.Get() != nullptr); 7268 return LinkFields(self, klass, true, class_size); 7269 } 7270 7271 struct LinkFieldsComparator { 7272 explicit LinkFieldsComparator() SHARED_REQUIRES(Locks::mutator_lock_) { 7273 } 7274 // No thread safety analysis as will be called from STL. Checked lock held in constructor. 7275 bool operator()(ArtField* field1, ArtField* field2) 7276 NO_THREAD_SAFETY_ANALYSIS { 7277 // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit. 7278 Primitive::Type type1 = field1->GetTypeAsPrimitiveType(); 7279 Primitive::Type type2 = field2->GetTypeAsPrimitiveType(); 7280 if (type1 != type2) { 7281 if (type1 == Primitive::kPrimNot) { 7282 // Reference always goes first. 7283 return true; 7284 } 7285 if (type2 == Primitive::kPrimNot) { 7286 // Reference always goes first. 7287 return false; 7288 } 7289 size_t size1 = Primitive::ComponentSize(type1); 7290 size_t size2 = Primitive::ComponentSize(type2); 7291 if (size1 != size2) { 7292 // Larger primitive types go first. 7293 return size1 > size2; 7294 } 7295 // Primitive types differ but sizes match. Arbitrarily order by primitive type. 7296 return type1 < type2; 7297 } 7298 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted 7299 // by name and for equal names by type id index. 7300 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes. 7301 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex(); 7302 } 7303 }; 7304 7305 bool ClassLinker::LinkFields(Thread* self, 7306 Handle<mirror::Class> klass, 7307 bool is_static, 7308 size_t* class_size) { 7309 self->AllowThreadSuspension(); 7310 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields(); 7311 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() : 7312 klass->GetIFieldsPtr(); 7313 7314 // Initialize field_offset 7315 MemberOffset field_offset(0); 7316 if (is_static) { 7317 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_); 7318 } else { 7319 mirror::Class* super_class = klass->GetSuperClass(); 7320 if (super_class != nullptr) { 7321 CHECK(super_class->IsResolved()) 7322 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class); 7323 field_offset = MemberOffset(super_class->GetObjectSize()); 7324 } 7325 } 7326 7327 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get()); 7328 7329 // we want a relatively stable order so that adding new fields 7330 // minimizes disruption of C++ version such as Class and Method. 7331 // 7332 // The overall sort order order is: 7333 // 1) All object reference fields, sorted alphabetically. 7334 // 2) All java long (64-bit) integer fields, sorted alphabetically. 7335 // 3) All java double (64-bit) floating point fields, sorted alphabetically. 7336 // 4) All java int (32-bit) integer fields, sorted alphabetically. 7337 // 5) All java float (32-bit) floating point fields, sorted alphabetically. 7338 // 6) All java char (16-bit) integer fields, sorted alphabetically. 7339 // 7) All java short (16-bit) integer fields, sorted alphabetically. 7340 // 8) All java boolean (8-bit) integer fields, sorted alphabetically. 7341 // 9) All java byte (8-bit) integer fields, sorted alphabetically. 7342 // 7343 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present 7344 // in the memory layout of the structure. See ShuffleForward for how this is done. 7345 std::deque<ArtField*> grouped_and_sorted_fields; 7346 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension( 7347 "Naked ArtField references in deque"); 7348 for (size_t i = 0; i < num_fields; i++) { 7349 grouped_and_sorted_fields.push_back(&fields->At(i)); 7350 } 7351 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(), 7352 LinkFieldsComparator()); 7353 7354 // References should be at the front. 7355 size_t current_field = 0; 7356 size_t num_reference_fields = 0; 7357 FieldGaps gaps; 7358 7359 for (; current_field < num_fields; current_field++) { 7360 ArtField* field = grouped_and_sorted_fields.front(); 7361 Primitive::Type type = field->GetTypeAsPrimitiveType(); 7362 bool isPrimitive = type != Primitive::kPrimNot; 7363 if (isPrimitive) { 7364 break; // past last reference, move on to the next phase 7365 } 7366 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>( 7367 field_offset.Uint32Value()))) { 7368 MemberOffset old_offset = field_offset; 7369 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4)); 7370 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps); 7371 } 7372 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>)); 7373 grouped_and_sorted_fields.pop_front(); 7374 num_reference_fields++; 7375 field->SetOffset(field_offset); 7376 field_offset = MemberOffset(field_offset.Uint32Value() + 7377 sizeof(mirror::HeapReference<mirror::Object>)); 7378 } 7379 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest 7380 // otherwise we could end up with suboptimal gap fills. 7381 ShuffleForward<8>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps); 7382 ShuffleForward<4>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps); 7383 ShuffleForward<2>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps); 7384 ShuffleForward<1>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps); 7385 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() << 7386 " fields."; 7387 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 7388 7389 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it. 7390 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) { 7391 // We know there are no non-reference fields in the Reference classes, and we know 7392 // that 'referent' is alphabetically last, so this is easy... 7393 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get()); 7394 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent") 7395 << PrettyClass(klass.Get()); 7396 --num_reference_fields; 7397 } 7398 7399 size_t size = field_offset.Uint32Value(); 7400 // Update klass 7401 if (is_static) { 7402 klass->SetNumReferenceStaticFields(num_reference_fields); 7403 *class_size = size; 7404 } else { 7405 klass->SetNumReferenceInstanceFields(num_reference_fields); 7406 mirror::Class* super_class = klass->GetSuperClass(); 7407 if (num_reference_fields == 0 || super_class == nullptr) { 7408 // object has one reference field, klass, but we ignore it since we always visit the class. 7409 // super_class is null iff the class is java.lang.Object. 7410 if (super_class == nullptr || 7411 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) { 7412 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields); 7413 } 7414 } 7415 if (kIsDebugBuild) { 7416 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;")); 7417 size_t total_reference_instance_fields = 0; 7418 mirror::Class* cur_super = klass.Get(); 7419 while (cur_super != nullptr) { 7420 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking(); 7421 cur_super = cur_super->GetSuperClass(); 7422 } 7423 if (super_class == nullptr) { 7424 CHECK_EQ(total_reference_instance_fields, 1u) << PrettyDescriptor(klass.Get()); 7425 } else { 7426 // Check that there is at least num_reference_fields other than Object.class. 7427 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields) 7428 << PrettyClass(klass.Get()); 7429 } 7430 } 7431 if (!klass->IsVariableSize()) { 7432 std::string temp; 7433 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp); 7434 size_t previous_size = klass->GetObjectSize(); 7435 if (previous_size != 0) { 7436 // Make sure that we didn't originally have an incorrect size. 7437 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp); 7438 } 7439 klass->SetObjectSize(size); 7440 } 7441 } 7442 7443 if (kIsDebugBuild) { 7444 // Make sure that the fields array is ordered by name but all reference 7445 // offsets are at the beginning as far as alignment allows. 7446 MemberOffset start_ref_offset = is_static 7447 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_) 7448 : klass->GetFirstReferenceInstanceFieldOffset(); 7449 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() + 7450 num_reference_fields * 7451 sizeof(mirror::HeapReference<mirror::Object>)); 7452 MemberOffset current_ref_offset = start_ref_offset; 7453 for (size_t i = 0; i < num_fields; i++) { 7454 ArtField* field = &fields->At(i); 7455 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance") 7456 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset=" 7457 << field->GetOffsetDuringLinking(); 7458 if (i != 0) { 7459 ArtField* const prev_field = &fields->At(i - 1); 7460 // NOTE: The field names can be the same. This is not possible in the Java language 7461 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode. 7462 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0); 7463 } 7464 Primitive::Type type = field->GetTypeAsPrimitiveType(); 7465 bool is_primitive = type != Primitive::kPrimNot; 7466 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") && 7467 strcmp("referent", field->GetName()) == 0) { 7468 is_primitive = true; // We lied above, so we have to expect a lie here. 7469 } 7470 MemberOffset offset = field->GetOffsetDuringLinking(); 7471 if (is_primitive) { 7472 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) { 7473 // Shuffled before references. 7474 size_t type_size = Primitive::ComponentSize(type); 7475 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>)); 7476 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value()); 7477 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value()); 7478 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value())); 7479 } 7480 } else { 7481 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value()); 7482 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() + 7483 sizeof(mirror::HeapReference<mirror::Object>)); 7484 } 7485 } 7486 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value()); 7487 } 7488 return true; 7489 } 7490 7491 // Set the bitmap of reference instance field offsets. 7492 void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) { 7493 uint32_t reference_offsets = 0; 7494 mirror::Class* super_class = klass->GetSuperClass(); 7495 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially). 7496 if (super_class != nullptr) { 7497 reference_offsets = super_class->GetReferenceInstanceOffsets(); 7498 // Compute reference offsets unless our superclass overflowed. 7499 if (reference_offsets != mirror::Class::kClassWalkSuper) { 7500 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking(); 7501 if (num_reference_fields != 0u) { 7502 // All of the fields that contain object references are guaranteed be grouped in memory 7503 // starting at an appropriately aligned address after super class object data. 7504 uint32_t start_offset = RoundUp(super_class->GetObjectSize(), 7505 sizeof(mirror::HeapReference<mirror::Object>)); 7506 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) / 7507 sizeof(mirror::HeapReference<mirror::Object>); 7508 if (start_bit + num_reference_fields > 32) { 7509 reference_offsets = mirror::Class::kClassWalkSuper; 7510 } else { 7511 reference_offsets |= (0xffffffffu << start_bit) & 7512 (0xffffffffu >> (32 - (start_bit + num_reference_fields))); 7513 } 7514 } 7515 } 7516 } 7517 klass->SetReferenceInstanceOffsets(reference_offsets); 7518 } 7519 7520 mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, 7521 uint32_t string_idx, 7522 Handle<mirror::DexCache> dex_cache) { 7523 DCHECK(dex_cache.Get() != nullptr); 7524 mirror::String* resolved = dex_cache->GetResolvedString(string_idx); 7525 if (resolved != nullptr) { 7526 return resolved; 7527 } 7528 uint32_t utf16_length; 7529 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length); 7530 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data); 7531 dex_cache->SetResolvedString(string_idx, string); 7532 return string; 7533 } 7534 7535 mirror::String* ClassLinker::LookupString(const DexFile& dex_file, 7536 uint32_t string_idx, 7537 Handle<mirror::DexCache> dex_cache) { 7538 DCHECK(dex_cache.Get() != nullptr); 7539 mirror::String* resolved = dex_cache->GetResolvedString(string_idx); 7540 if (resolved != nullptr) { 7541 return resolved; 7542 } 7543 uint32_t utf16_length; 7544 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length); 7545 mirror::String* string = intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data); 7546 if (string != nullptr) { 7547 dex_cache->SetResolvedString(string_idx, string); 7548 } 7549 return string; 7550 } 7551 7552 mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, 7553 uint16_t type_idx, 7554 mirror::Class* referrer) { 7555 StackHandleScope<2> hs(Thread::Current()); 7556 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache())); 7557 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader())); 7558 return ResolveType(dex_file, type_idx, dex_cache, class_loader); 7559 } 7560 7561 mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, 7562 uint16_t type_idx, 7563 Handle<mirror::DexCache> dex_cache, 7564 Handle<mirror::ClassLoader> class_loader) { 7565 DCHECK(dex_cache.Get() != nullptr); 7566 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx); 7567 if (resolved == nullptr) { 7568 Thread* self = Thread::Current(); 7569 const char* descriptor = dex_file.StringByTypeIdx(type_idx); 7570 resolved = FindClass(self, descriptor, class_loader); 7571 if (resolved != nullptr) { 7572 // TODO: we used to throw here if resolved's class loader was not the 7573 // boot class loader. This was to permit different classes with the 7574 // same name to be loaded simultaneously by different loaders 7575 dex_cache->SetResolvedType(type_idx, resolved); 7576 } else { 7577 CHECK(self->IsExceptionPending()) 7578 << "Expected pending exception for failed resolution of: " << descriptor; 7579 // Convert a ClassNotFoundException to a NoClassDefFoundError. 7580 StackHandleScope<1> hs(self); 7581 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException())); 7582 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) { 7583 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved. 7584 self->ClearException(); 7585 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor); 7586 self->GetException()->SetCause(cause.Get()); 7587 } 7588 } 7589 } 7590 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous()) 7591 << PrettyDescriptor(resolved) << " " << resolved->GetStatus(); 7592 return resolved; 7593 } 7594 7595 template <ClassLinker::ResolveMode kResolveMode> 7596 ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, 7597 uint32_t method_idx, 7598 Handle<mirror::DexCache> dex_cache, 7599 Handle<mirror::ClassLoader> class_loader, 7600 ArtMethod* referrer, 7601 InvokeType type) { 7602 DCHECK(dex_cache.Get() != nullptr); 7603 // Check for hit in the dex cache. 7604 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_); 7605 if (resolved != nullptr && !resolved->IsRuntimeMethod()) { 7606 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex(); 7607 if (kResolveMode == ClassLinker::kForceICCECheck) { 7608 if (resolved->CheckIncompatibleClassChange(type)) { 7609 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer); 7610 return nullptr; 7611 } 7612 } 7613 return resolved; 7614 } 7615 // Fail, get the declaring class. 7616 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 7617 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader); 7618 if (klass == nullptr) { 7619 DCHECK(Thread::Current()->IsExceptionPending()); 7620 return nullptr; 7621 } 7622 // Scan using method_idx, this saves string compares but will only hit for matching dex 7623 // caches/files. 7624 switch (type) { 7625 case kDirect: // Fall-through. 7626 case kStatic: 7627 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_); 7628 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr); 7629 break; 7630 case kInterface: 7631 // We have to check whether the method id really belongs to an interface (dex static bytecode 7632 // constraint A15). Otherwise you must not invoke-interface on it. 7633 // 7634 // This is not symmetric to A12-A14 (direct, static, virtual), as using FindInterfaceMethod 7635 // assumes that the given type is an interface, and will check the interface table if the 7636 // method isn't declared in the class. So it may find an interface method (usually by name 7637 // in the handling below, but we do the constraint check early). In that case, 7638 // CheckIncompatibleClassChange will succeed (as it is called on an interface method) 7639 // unexpectedly. 7640 // Example: 7641 // interface I { 7642 // foo() 7643 // } 7644 // class A implements I { 7645 // ... 7646 // } 7647 // class B extends A { 7648 // ... 7649 // } 7650 // invoke-interface B.foo 7651 // -> FindInterfaceMethod finds I.foo (interface method), not A.foo (miranda method) 7652 if (UNLIKELY(!klass->IsInterface())) { 7653 ThrowIncompatibleClassChangeError(klass, 7654 "Found class %s, but interface was expected", 7655 PrettyDescriptor(klass).c_str()); 7656 return nullptr; 7657 } else { 7658 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_); 7659 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface()); 7660 } 7661 break; 7662 case kSuper: 7663 if (klass->IsInterface()) { 7664 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_); 7665 } else { 7666 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_); 7667 } 7668 break; 7669 case kVirtual: 7670 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_); 7671 break; 7672 default: 7673 LOG(FATAL) << "Unreachable - invocation type: " << type; 7674 UNREACHABLE(); 7675 } 7676 if (resolved == nullptr) { 7677 // Search by name, which works across dex files. 7678 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 7679 const Signature signature = dex_file.GetMethodSignature(method_id); 7680 switch (type) { 7681 case kDirect: // Fall-through. 7682 case kStatic: 7683 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_); 7684 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr); 7685 break; 7686 case kInterface: 7687 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_); 7688 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface()); 7689 break; 7690 case kSuper: 7691 if (klass->IsInterface()) { 7692 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_); 7693 } else { 7694 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_); 7695 } 7696 break; 7697 case kVirtual: 7698 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_); 7699 break; 7700 } 7701 } 7702 // If we found a method, check for incompatible class changes. 7703 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) { 7704 // Be a good citizen and update the dex cache to speed subsequent calls. 7705 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_); 7706 return resolved; 7707 } else { 7708 // If we had a method, it's an incompatible-class-change error. 7709 if (resolved != nullptr) { 7710 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer); 7711 } else { 7712 // We failed to find the method which means either an access error, an incompatible class 7713 // change, or no such method. First try to find the method among direct and virtual methods. 7714 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 7715 const Signature signature = dex_file.GetMethodSignature(method_id); 7716 switch (type) { 7717 case kDirect: 7718 case kStatic: 7719 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_); 7720 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would 7721 // have had a resolved method before, which triggers the "true" branch above. 7722 break; 7723 case kInterface: 7724 case kVirtual: 7725 case kSuper: 7726 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_); 7727 break; 7728 } 7729 7730 // If we found something, check that it can be accessed by the referrer. 7731 bool exception_generated = false; 7732 if (resolved != nullptr && referrer != nullptr) { 7733 mirror::Class* methods_class = resolved->GetDeclaringClass(); 7734 mirror::Class* referring_class = referrer->GetDeclaringClass(); 7735 if (!referring_class->CanAccess(methods_class)) { 7736 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, 7737 methods_class, 7738 resolved, 7739 type); 7740 exception_generated = true; 7741 } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) { 7742 ThrowIllegalAccessErrorMethod(referring_class, resolved); 7743 exception_generated = true; 7744 } 7745 } 7746 if (!exception_generated) { 7747 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check 7748 // interface methods and throw if we find the method there. If we find nothing, throw a 7749 // NoSuchMethodError. 7750 switch (type) { 7751 case kDirect: 7752 case kStatic: 7753 if (resolved != nullptr) { 7754 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer); 7755 } else { 7756 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_); 7757 if (resolved != nullptr) { 7758 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer); 7759 } else { 7760 ThrowNoSuchMethodError(type, klass, name, signature); 7761 } 7762 } 7763 break; 7764 case kInterface: 7765 if (resolved != nullptr) { 7766 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer); 7767 } else { 7768 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_); 7769 if (resolved != nullptr) { 7770 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer); 7771 } else { 7772 ThrowNoSuchMethodError(type, klass, name, signature); 7773 } 7774 } 7775 break; 7776 case kSuper: 7777 if (resolved != nullptr) { 7778 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer); 7779 } else { 7780 ThrowNoSuchMethodError(type, klass, name, signature); 7781 } 7782 break; 7783 case kVirtual: 7784 if (resolved != nullptr) { 7785 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer); 7786 } else { 7787 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_); 7788 if (resolved != nullptr) { 7789 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer); 7790 } else { 7791 ThrowNoSuchMethodError(type, klass, name, signature); 7792 } 7793 } 7794 break; 7795 } 7796 } 7797 } 7798 Thread::Current()->AssertPendingException(); 7799 return nullptr; 7800 } 7801 } 7802 7803 ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file, 7804 uint32_t method_idx, 7805 Handle<mirror::DexCache> dex_cache, 7806 Handle<mirror::ClassLoader> class_loader) { 7807 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_); 7808 if (resolved != nullptr && !resolved->IsRuntimeMethod()) { 7809 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex(); 7810 return resolved; 7811 } 7812 // Fail, get the declaring class. 7813 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 7814 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader); 7815 if (klass == nullptr) { 7816 Thread::Current()->AssertPendingException(); 7817 return nullptr; 7818 } 7819 if (klass->IsInterface()) { 7820 LOG(FATAL) << "ResolveAmbiguousMethod: unexpected method in interface: " << PrettyClass(klass); 7821 return nullptr; 7822 } 7823 7824 // Search both direct and virtual methods 7825 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_); 7826 if (resolved == nullptr) { 7827 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_); 7828 } 7829 7830 return resolved; 7831 } 7832 7833 ArtField* ClassLinker::ResolveField(const DexFile& dex_file, 7834 uint32_t field_idx, 7835 Handle<mirror::DexCache> dex_cache, 7836 Handle<mirror::ClassLoader> class_loader, 7837 bool is_static) { 7838 DCHECK(dex_cache.Get() != nullptr); 7839 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_); 7840 if (resolved != nullptr) { 7841 return resolved; 7842 } 7843 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 7844 Thread* const self = Thread::Current(); 7845 StackHandleScope<1> hs(self); 7846 Handle<mirror::Class> klass( 7847 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 7848 if (klass.Get() == nullptr) { 7849 DCHECK(Thread::Current()->IsExceptionPending()); 7850 return nullptr; 7851 } 7852 7853 if (is_static) { 7854 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx); 7855 } else { 7856 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx); 7857 } 7858 7859 if (resolved == nullptr) { 7860 const char* name = dex_file.GetFieldName(field_id); 7861 const char* type = dex_file.GetFieldTypeDescriptor(field_id); 7862 if (is_static) { 7863 resolved = mirror::Class::FindStaticField(self, klass, name, type); 7864 } else { 7865 resolved = klass->FindInstanceField(name, type); 7866 } 7867 if (resolved == nullptr) { 7868 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name); 7869 return nullptr; 7870 } 7871 } 7872 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_); 7873 return resolved; 7874 } 7875 7876 ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, 7877 uint32_t field_idx, 7878 Handle<mirror::DexCache> dex_cache, 7879 Handle<mirror::ClassLoader> class_loader) { 7880 DCHECK(dex_cache.Get() != nullptr); 7881 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_); 7882 if (resolved != nullptr) { 7883 return resolved; 7884 } 7885 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 7886 Thread* self = Thread::Current(); 7887 StackHandleScope<1> hs(self); 7888 Handle<mirror::Class> klass( 7889 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 7890 if (klass.Get() == nullptr) { 7891 DCHECK(Thread::Current()->IsExceptionPending()); 7892 return nullptr; 7893 } 7894 7895 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_)); 7896 StringPiece type(dex_file.StringDataByIdx( 7897 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_)); 7898 resolved = mirror::Class::FindField(self, klass, name, type); 7899 if (resolved != nullptr) { 7900 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_); 7901 } else { 7902 ThrowNoSuchFieldError("", klass.Get(), type, name); 7903 } 7904 return resolved; 7905 } 7906 7907 const char* ClassLinker::MethodShorty(uint32_t method_idx, 7908 ArtMethod* referrer, 7909 uint32_t* length) { 7910 mirror::Class* declaring_class = referrer->GetDeclaringClass(); 7911 mirror::DexCache* dex_cache = declaring_class->GetDexCache(); 7912 const DexFile& dex_file = *dex_cache->GetDexFile(); 7913 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 7914 return dex_file.GetMethodShorty(method_id, length); 7915 } 7916 7917 class DumpClassVisitor : public ClassVisitor { 7918 public: 7919 explicit DumpClassVisitor(int flags) : flags_(flags) {} 7920 7921 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 7922 klass->DumpClass(LOG(ERROR), flags_); 7923 return true; 7924 } 7925 7926 private: 7927 const int flags_; 7928 }; 7929 7930 void ClassLinker::DumpAllClasses(int flags) { 7931 DumpClassVisitor visitor(flags); 7932 VisitClasses(&visitor); 7933 } 7934 7935 static OatFile::OatMethod CreateOatMethod(const void* code) { 7936 CHECK(code != nullptr); 7937 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code. 7938 base -= sizeof(void*); // Move backward so that code_offset != 0. 7939 const uint32_t code_offset = sizeof(void*); 7940 return OatFile::OatMethod(base, code_offset); 7941 } 7942 7943 bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const { 7944 return (entry_point == GetQuickResolutionStub()) || 7945 (quick_resolution_trampoline_ == entry_point); 7946 } 7947 7948 bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const { 7949 return (entry_point == GetQuickToInterpreterBridge()) || 7950 (quick_to_interpreter_bridge_trampoline_ == entry_point); 7951 } 7952 7953 bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const { 7954 return (entry_point == GetQuickGenericJniStub()) || 7955 (quick_generic_jni_trampoline_ == entry_point); 7956 } 7957 7958 const void* ClassLinker::GetRuntimeQuickGenericJniStub() const { 7959 return GetQuickGenericJniStub(); 7960 } 7961 7962 void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method, 7963 const void* method_code) const { 7964 OatFile::OatMethod oat_method = CreateOatMethod(method_code); 7965 oat_method.LinkMethod(method); 7966 } 7967 7968 void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const { 7969 if (!method->IsNative()) { 7970 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 7971 } else { 7972 const void* quick_method_code = GetQuickGenericJniStub(); 7973 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code); 7974 oat_method.LinkMethod(method); 7975 } 7976 } 7977 7978 void ClassLinker::DumpForSigQuit(std::ostream& os) { 7979 ScopedObjectAccess soa(Thread::Current()); 7980 if (dex_cache_boot_image_class_lookup_required_) { 7981 AddBootImageClassesToClassTable(); 7982 } 7983 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_); 7984 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes=" 7985 << NumNonZygoteClasses() << "\n"; 7986 } 7987 7988 class CountClassesVisitor : public ClassLoaderVisitor { 7989 public: 7990 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {} 7991 7992 void Visit(mirror::ClassLoader* class_loader) 7993 SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE { 7994 ClassTable* const class_table = class_loader->GetClassTable(); 7995 if (class_table != nullptr) { 7996 num_zygote_classes += class_table->NumZygoteClasses(); 7997 num_non_zygote_classes += class_table->NumNonZygoteClasses(); 7998 } 7999 } 8000 8001 size_t num_zygote_classes; 8002 size_t num_non_zygote_classes; 8003 }; 8004 8005 size_t ClassLinker::NumZygoteClasses() const { 8006 CountClassesVisitor visitor; 8007 VisitClassLoaders(&visitor); 8008 return visitor.num_zygote_classes + boot_class_table_.NumZygoteClasses(); 8009 } 8010 8011 size_t ClassLinker::NumNonZygoteClasses() const { 8012 CountClassesVisitor visitor; 8013 VisitClassLoaders(&visitor); 8014 return visitor.num_non_zygote_classes + boot_class_table_.NumNonZygoteClasses(); 8015 } 8016 8017 size_t ClassLinker::NumLoadedClasses() { 8018 if (dex_cache_boot_image_class_lookup_required_) { 8019 AddBootImageClassesToClassTable(); 8020 } 8021 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 8022 // Only return non zygote classes since these are the ones which apps which care about. 8023 return NumNonZygoteClasses(); 8024 } 8025 8026 pid_t ClassLinker::GetClassesLockOwner() { 8027 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid(); 8028 } 8029 8030 pid_t ClassLinker::GetDexLockOwner() { 8031 return dex_lock_.GetExclusiveOwnerTid(); 8032 } 8033 8034 void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) { 8035 DCHECK(!init_done_); 8036 8037 DCHECK(klass != nullptr); 8038 DCHECK(klass->GetClassLoader() == nullptr); 8039 8040 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read(); 8041 DCHECK(class_roots != nullptr); 8042 DCHECK(class_roots->Get(class_root) == nullptr); 8043 class_roots->Set<false>(class_root, klass); 8044 } 8045 8046 const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) { 8047 static const char* class_roots_descriptors[] = { 8048 "Ljava/lang/Class;", 8049 "Ljava/lang/Object;", 8050 "[Ljava/lang/Class;", 8051 "[Ljava/lang/Object;", 8052 "Ljava/lang/String;", 8053 "Ljava/lang/DexCache;", 8054 "Ljava/lang/ref/Reference;", 8055 "Ljava/lang/reflect/Constructor;", 8056 "Ljava/lang/reflect/Field;", 8057 "Ljava/lang/reflect/Method;", 8058 "Ljava/lang/reflect/Proxy;", 8059 "[Ljava/lang/String;", 8060 "[Ljava/lang/reflect/Constructor;", 8061 "[Ljava/lang/reflect/Field;", 8062 "[Ljava/lang/reflect/Method;", 8063 "Ljava/lang/ClassLoader;", 8064 "Ljava/lang/Throwable;", 8065 "Ljava/lang/ClassNotFoundException;", 8066 "Ljava/lang/StackTraceElement;", 8067 "Z", 8068 "B", 8069 "C", 8070 "D", 8071 "F", 8072 "I", 8073 "J", 8074 "S", 8075 "V", 8076 "[Z", 8077 "[B", 8078 "[C", 8079 "[D", 8080 "[F", 8081 "[I", 8082 "[J", 8083 "[S", 8084 "[Ljava/lang/StackTraceElement;", 8085 }; 8086 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax), 8087 "Mismatch between class descriptors and class-root enum"); 8088 8089 const char* descriptor = class_roots_descriptors[class_root]; 8090 CHECK(descriptor != nullptr); 8091 return descriptor; 8092 } 8093 8094 jobject ClassLinker::CreatePathClassLoader(Thread* self, 8095 const std::vector<const DexFile*>& dex_files) { 8096 // SOAAlreadyRunnable is protected, and we need something to add a global reference. 8097 // We could move the jobject to the callers, but all call-sites do this... 8098 ScopedObjectAccessUnchecked soa(self); 8099 8100 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex. 8101 StackHandleScope<10> hs(self); 8102 8103 ArtField* dex_elements_field = 8104 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements); 8105 8106 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>(); 8107 DCHECK(dex_elements_class != nullptr); 8108 DCHECK(dex_elements_class->IsArrayClass()); 8109 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle( 8110 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size()))); 8111 Handle<mirror::Class> h_dex_element_class = 8112 hs.NewHandle(dex_elements_class->GetComponentType()); 8113 8114 ArtField* element_file_field = 8115 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile); 8116 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass()); 8117 8118 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie); 8119 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>()); 8120 8121 ArtField* file_name_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_fileName); 8122 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->GetType<false>()); 8123 8124 // Fill the elements array. 8125 int32_t index = 0; 8126 for (const DexFile* dex_file : dex_files) { 8127 StackHandleScope<4> hs2(self); 8128 8129 // CreatePathClassLoader is only used by gtests. Index 0 of h_long_array is supposed to be the 8130 // oat file but we can leave it null. 8131 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc( 8132 self, 8133 kDexFileIndexStart + 1)); 8134 DCHECK(h_long_array.Get() != nullptr); 8135 h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file)); 8136 8137 Handle<mirror::Object> h_dex_file = hs2.NewHandle( 8138 cookie_field->GetDeclaringClass()->AllocObject(self)); 8139 DCHECK(h_dex_file.Get() != nullptr); 8140 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get()); 8141 8142 Handle<mirror::String> h_file_name = hs2.NewHandle( 8143 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str())); 8144 DCHECK(h_file_name.Get() != nullptr); 8145 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get()); 8146 8147 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self)); 8148 DCHECK(h_element.Get() != nullptr); 8149 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get()); 8150 8151 h_dex_elements->Set(index, h_element.Get()); 8152 index++; 8153 } 8154 DCHECK_EQ(index, h_dex_elements->GetLength()); 8155 8156 // Create DexPathList. 8157 Handle<mirror::Object> h_dex_path_list = hs.NewHandle( 8158 dex_elements_field->GetDeclaringClass()->AllocObject(self)); 8159 DCHECK(h_dex_path_list.Get() != nullptr); 8160 // Set elements. 8161 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get()); 8162 8163 // Create PathClassLoader. 8164 Handle<mirror::Class> h_path_class_class = hs.NewHandle( 8165 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)); 8166 Handle<mirror::Object> h_path_class_loader = hs.NewHandle( 8167 h_path_class_class->AllocObject(self)); 8168 DCHECK(h_path_class_loader.Get() != nullptr); 8169 // Set DexPathList. 8170 ArtField* path_list_field = 8171 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList); 8172 DCHECK(path_list_field != nullptr); 8173 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get()); 8174 8175 // Make a pretend boot-classpath. 8176 // TODO: Should we scan the image? 8177 ArtField* const parent_field = 8178 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent", 8179 "Ljava/lang/ClassLoader;"); 8180 DCHECK(parent_field != nullptr); 8181 mirror::Object* boot_cl = 8182 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self); 8183 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl); 8184 8185 // Make it a global ref and return. 8186 ScopedLocalRef<jobject> local_ref( 8187 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get())); 8188 return soa.Env()->NewGlobalRef(local_ref.get()); 8189 } 8190 8191 ArtMethod* ClassLinker::CreateRuntimeMethod(LinearAlloc* linear_alloc) { 8192 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_); 8193 const size_t method_size = ArtMethod::Size(image_pointer_size_); 8194 LengthPrefixedArray<ArtMethod>* method_array = AllocArtMethodArray( 8195 Thread::Current(), 8196 linear_alloc, 8197 1); 8198 ArtMethod* method = &method_array->At(0, method_size, method_alignment); 8199 CHECK(method != nullptr); 8200 method->SetDexMethodIndex(DexFile::kDexNoIndex); 8201 CHECK(method->IsRuntimeMethod()); 8202 return method; 8203 } 8204 8205 void ClassLinker::DropFindArrayClassCache() { 8206 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr)); 8207 find_array_class_cache_next_victim_ = 0; 8208 } 8209 8210 void ClassLinker::ClearClassTableStrongRoots() const { 8211 Thread* const self = Thread::Current(); 8212 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 8213 for (const ClassLoaderData& data : class_loaders_) { 8214 if (data.class_table != nullptr) { 8215 data.class_table->ClearStrongRoots(); 8216 } 8217 } 8218 } 8219 8220 void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const { 8221 Thread* const self = Thread::Current(); 8222 for (const ClassLoaderData& data : class_loaders_) { 8223 // Need to use DecodeJObject so that we get null for cleared JNI weak globals. 8224 auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root)); 8225 if (class_loader != nullptr) { 8226 visitor->Visit(class_loader); 8227 } 8228 } 8229 } 8230 8231 void ClassLinker::InsertDexFileInToClassLoader(mirror::Object* dex_file, 8232 mirror::ClassLoader* class_loader) { 8233 DCHECK(dex_file != nullptr); 8234 Thread* const self = Thread::Current(); 8235 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 8236 ClassTable* const table = ClassTableForClassLoader(class_loader); 8237 DCHECK(table != nullptr); 8238 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) { 8239 // It was not already inserted, perform the write barrier to let the GC know the class loader's 8240 // class table was modified. 8241 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader); 8242 } 8243 } 8244 8245 void ClassLinker::CleanupClassLoaders() { 8246 Thread* const self = Thread::Current(); 8247 std::vector<ClassLoaderData> to_delete; 8248 // Do the delete outside the lock to avoid lock violation in jit code cache. 8249 { 8250 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 8251 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) { 8252 const ClassLoaderData& data = *it; 8253 // Need to use DecodeJObject so that we get null for cleared JNI weak globals. 8254 auto* const class_loader = 8255 down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root)); 8256 if (class_loader != nullptr) { 8257 ++it; 8258 } else { 8259 VLOG(class_linker) << "Freeing class loader"; 8260 to_delete.push_back(data); 8261 it = class_loaders_.erase(it); 8262 } 8263 } 8264 } 8265 for (ClassLoaderData& data : to_delete) { 8266 DeleteClassLoader(self, data); 8267 } 8268 } 8269 8270 std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) { 8271 ScopedTrace trace(__PRETTY_FUNCTION__); 8272 ScopedObjectAccess soa(Thread::Current()); 8273 ScopedAssertNoThreadSuspension ants(soa.Self(), __FUNCTION__); 8274 std::set<DexCacheResolvedClasses> ret; 8275 VLOG(class_linker) << "Collecting resolved classes"; 8276 const uint64_t start_time = NanoTime(); 8277 ReaderMutexLock mu(soa.Self(), *DexLock()); 8278 // Loop through all the dex caches and inspect resolved classes. 8279 for (const ClassLinker::DexCacheData& data : GetDexCachesData()) { 8280 if (soa.Self()->IsJWeakCleared(data.weak_root)) { 8281 continue; 8282 } 8283 mirror::DexCache* dex_cache = 8284 down_cast<mirror::DexCache*>(soa.Self()->DecodeJObject(data.weak_root)); 8285 if (dex_cache == nullptr) { 8286 continue; 8287 } 8288 const DexFile* dex_file = dex_cache->GetDexFile(); 8289 const std::string& location = dex_file->GetLocation(); 8290 const size_t num_class_defs = dex_file->NumClassDefs(); 8291 // Use the resolved types, this will miss array classes. 8292 const size_t num_types = dex_file->NumTypeIds(); 8293 VLOG(class_linker) << "Collecting class profile for dex file " << location 8294 << " types=" << num_types << " class_defs=" << num_class_defs; 8295 DexCacheResolvedClasses resolved_classes(dex_file->GetLocation(), 8296 dex_file->GetBaseLocation(), 8297 dex_file->GetLocationChecksum()); 8298 size_t num_resolved = 0; 8299 std::unordered_set<uint16_t> class_set; 8300 CHECK_EQ(num_types, dex_cache->NumResolvedTypes()); 8301 for (size_t i = 0; i < num_types; ++i) { 8302 mirror::Class* klass = dex_cache->GetResolvedType(i); 8303 // Filter out null class loader since that is the boot class loader. 8304 if (klass == nullptr || (ignore_boot_classes && klass->GetClassLoader() == nullptr)) { 8305 continue; 8306 } 8307 ++num_resolved; 8308 DCHECK(!klass->IsProxyClass()); 8309 if (!klass->IsResolved()) { 8310 DCHECK(klass->IsErroneous()); 8311 continue; 8312 } 8313 mirror::DexCache* klass_dex_cache = klass->GetDexCache(); 8314 if (klass_dex_cache == dex_cache) { 8315 const size_t class_def_idx = klass->GetDexClassDefIndex(); 8316 DCHECK(klass->IsResolved()); 8317 CHECK_LT(class_def_idx, num_class_defs); 8318 class_set.insert(class_def_idx); 8319 } 8320 } 8321 8322 if (!class_set.empty()) { 8323 auto it = ret.find(resolved_classes); 8324 if (it != ret.end()) { 8325 // Already have the key, union the class def idxs. 8326 it->AddClasses(class_set.begin(), class_set.end()); 8327 } else { 8328 resolved_classes.AddClasses(class_set.begin(), class_set.end()); 8329 ret.insert(resolved_classes); 8330 } 8331 } 8332 8333 VLOG(class_linker) << "Dex location " << location << " has " << num_resolved << " / " 8334 << num_class_defs << " resolved classes"; 8335 } 8336 VLOG(class_linker) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time); 8337 return ret; 8338 } 8339 8340 std::unordered_set<std::string> ClassLinker::GetClassDescriptorsForProfileKeys( 8341 const std::set<DexCacheResolvedClasses>& classes) { 8342 ScopedTrace trace(__PRETTY_FUNCTION__); 8343 std::unordered_set<std::string> ret; 8344 Thread* const self = Thread::Current(); 8345 std::unordered_map<std::string, const DexFile*> location_to_dex_file; 8346 ScopedObjectAccess soa(self); 8347 ScopedAssertNoThreadSuspension ants(soa.Self(), __FUNCTION__); 8348 ReaderMutexLock mu(self, *DexLock()); 8349 for (const ClassLinker::DexCacheData& data : GetDexCachesData()) { 8350 if (!self->IsJWeakCleared(data.weak_root)) { 8351 mirror::DexCache* dex_cache = 8352 down_cast<mirror::DexCache*>(soa.Self()->DecodeJObject(data.weak_root)); 8353 if (dex_cache != nullptr) { 8354 const DexFile* dex_file = dex_cache->GetDexFile(); 8355 // There could be duplicates if two dex files with the same location are mapped. 8356 location_to_dex_file.emplace( 8357 ProfileCompilationInfo::GetProfileDexFileKey(dex_file->GetLocation()), dex_file); 8358 } 8359 } 8360 } 8361 for (const DexCacheResolvedClasses& info : classes) { 8362 const std::string& profile_key = info.GetDexLocation(); 8363 auto found = location_to_dex_file.find(profile_key); 8364 if (found != location_to_dex_file.end()) { 8365 const DexFile* dex_file = found->second; 8366 VLOG(profiler) << "Found opened dex file for " << dex_file->GetLocation() << " with " 8367 << info.GetClasses().size() << " classes"; 8368 DCHECK_EQ(dex_file->GetLocationChecksum(), info.GetLocationChecksum()); 8369 for (uint16_t class_def_idx : info.GetClasses()) { 8370 if (class_def_idx >= dex_file->NumClassDefs()) { 8371 LOG(WARNING) << "Class def index " << class_def_idx << " >= " << dex_file->NumClassDefs(); 8372 continue; 8373 } 8374 const DexFile::TypeId& type_id = dex_file->GetTypeId( 8375 dex_file->GetClassDef(class_def_idx).class_idx_); 8376 const char* descriptor = dex_file->GetTypeDescriptor(type_id); 8377 ret.insert(descriptor); 8378 } 8379 } else { 8380 VLOG(class_linker) << "Failed to find opened dex file for profile key " << profile_key; 8381 } 8382 } 8383 return ret; 8384 } 8385 8386 class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor { 8387 public: 8388 FindVirtualMethodHolderVisitor(const ArtMethod* method, size_t pointer_size) 8389 : method_(method), 8390 pointer_size_(pointer_size) {} 8391 8392 bool operator()(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) OVERRIDE { 8393 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) { 8394 holder_ = klass; 8395 } 8396 // Return false to stop searching if holder_ is not null. 8397 return holder_ == nullptr; 8398 } 8399 8400 mirror::Class* holder_ = nullptr; 8401 const ArtMethod* const method_; 8402 const size_t pointer_size_; 8403 }; 8404 8405 mirror::Class* ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) { 8406 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people. 8407 CHECK(method->IsCopied()); 8408 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_); 8409 VisitClasses(&visitor); 8410 return visitor.holder_; 8411 } 8412 8413 // Instantiate ResolveMethod. 8414 template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kForceICCECheck>( 8415 const DexFile& dex_file, 8416 uint32_t method_idx, 8417 Handle<mirror::DexCache> dex_cache, 8418 Handle<mirror::ClassLoader> class_loader, 8419 ArtMethod* referrer, 8420 InvokeType type); 8421 template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kNoICCECheckForCache>( 8422 const DexFile& dex_file, 8423 uint32_t method_idx, 8424 Handle<mirror::DexCache> dex_cache, 8425 Handle<mirror::ClassLoader> class_loader, 8426 ArtMethod* referrer, 8427 InvokeType type); 8428 8429 } // namespace art 8430