class_linker.cc revision c0fe56a4ee672bb346b124438941e753887e7416
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 <deque> 20#include <iostream> 21#include <memory> 22#include <queue> 23#include <string> 24#include <unistd.h> 25#include <utility> 26#include <vector> 27 28#include "art_field-inl.h" 29#include "art_method-inl.h" 30#include "base/arena_allocator.h" 31#include "base/casts.h" 32#include "base/logging.h" 33#include "base/scoped_arena_containers.h" 34#include "base/scoped_flock.h" 35#include "base/stl_util.h" 36#include "base/time_utils.h" 37#include "base/unix_file/fd_file.h" 38#include "base/value_object.h" 39#include "class_linker-inl.h" 40#include "compiler_callbacks.h" 41#include "debugger.h" 42#include "dex_file-inl.h" 43#include "entrypoints/runtime_asm_entrypoints.h" 44#include "gc_root-inl.h" 45#include "gc/accounting/card_table-inl.h" 46#include "gc/accounting/heap_bitmap.h" 47#include "gc/heap.h" 48#include "gc/space/image_space.h" 49#include "handle_scope.h" 50#include "intern_table.h" 51#include "interpreter/interpreter.h" 52#include "jit/jit.h" 53#include "jit/jit_code_cache.h" 54#include "leb128.h" 55#include "linear_alloc.h" 56#include "oat.h" 57#include "oat_file.h" 58#include "oat_file-inl.h" 59#include "oat_file_assistant.h" 60#include "object_lock.h" 61#include "mirror/class.h" 62#include "mirror/class-inl.h" 63#include "mirror/class_loader.h" 64#include "mirror/dex_cache-inl.h" 65#include "mirror/field.h" 66#include "mirror/iftable-inl.h" 67#include "mirror/method.h" 68#include "mirror/object-inl.h" 69#include "mirror/object_array-inl.h" 70#include "mirror/proxy.h" 71#include "mirror/reference-inl.h" 72#include "mirror/stack_trace_element.h" 73#include "mirror/string-inl.h" 74#include "os.h" 75#include "runtime.h" 76#include "entrypoints/entrypoint_utils.h" 77#include "ScopedLocalRef.h" 78#include "scoped_thread_state_change.h" 79#include "handle_scope-inl.h" 80#include "thread-inl.h" 81#include "utils.h" 82#include "verifier/method_verifier.h" 83#include "well_known_classes.h" 84 85namespace art { 86 87static constexpr bool kSanityCheckObjects = kIsDebugBuild; 88 89// For b/21333911. 90static constexpr bool kDuplicateClassesCheck = false; 91 92static void ThrowNoClassDefFoundError(const char* fmt, ...) 93 __attribute__((__format__(__printf__, 1, 2))) 94 SHARED_REQUIRES(Locks::mutator_lock_); 95static void ThrowNoClassDefFoundError(const char* fmt, ...) { 96 va_list args; 97 va_start(args, fmt); 98 Thread* self = Thread::Current(); 99 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args); 100 va_end(args); 101} 102 103bool ClassLinker::HasInitWithString(Thread* self, const char* descriptor) { 104 ArtMethod* method = self->GetCurrentMethod(nullptr); 105 StackHandleScope<1> hs(self); 106 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ? 107 method->GetDeclaringClass()->GetClassLoader() : nullptr)); 108 mirror::Class* exception_class = FindClass(self, descriptor, class_loader); 109 110 if (exception_class == nullptr) { 111 // No exc class ~ no <init>-with-string. 112 CHECK(self->IsExceptionPending()); 113 self->ClearException(); 114 return false; 115 } 116 117 ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod( 118 "<init>", "(Ljava/lang/String;)V", image_pointer_size_); 119 return exception_init_method != nullptr; 120} 121 122void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c) { 123 // The class failed to initialize on a previous attempt, so we want to throw 124 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we 125 // failed in verification, in which case v2 5.4.1 says we need to re-throw 126 // the previous error. 127 Runtime* const runtime = Runtime::Current(); 128 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime. 129 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c); 130 } 131 132 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus(); 133 Thread* self = Thread::Current(); 134 if (runtime->IsAotCompiler()) { 135 // At compile time, accurate errors and NCDFE are disabled to speed compilation. 136 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError(); 137 self->SetException(pre_allocated); 138 } else { 139 if (c->GetVerifyErrorClass() != nullptr) { 140 // TODO: change the verifier to store an _instance_, with a useful detail message? 141 // It's possible the exception doesn't have a <init>(String). 142 std::string temp; 143 const char* descriptor = c->GetVerifyErrorClass()->GetDescriptor(&temp); 144 145 if (HasInitWithString(self, descriptor)) { 146 self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str()); 147 } else { 148 self->ThrowNewException(descriptor, nullptr); 149 } 150 } else { 151 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;", 152 PrettyDescriptor(c).c_str()); 153 } 154 } 155} 156 157static void VlogClassInitializationFailure(Handle<mirror::Class> klass) 158 SHARED_REQUIRES(Locks::mutator_lock_) { 159 if (VLOG_IS_ON(class_linker)) { 160 std::string temp; 161 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from " 162 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump(); 163 } 164} 165 166static void WrapExceptionInInitializer(Handle<mirror::Class> klass) 167 SHARED_REQUIRES(Locks::mutator_lock_) { 168 Thread* self = Thread::Current(); 169 JNIEnv* env = self->GetJniEnv(); 170 171 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred()); 172 CHECK(cause.get() != nullptr); 173 174 env->ExceptionClear(); 175 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error); 176 env->Throw(cause.get()); 177 178 // We only wrap non-Error exceptions; an Error can just be used as-is. 179 if (!is_error) { 180 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr); 181 } 182 VlogClassInitializationFailure(klass); 183} 184 185// Gap between two fields in object layout. 186struct FieldGap { 187 uint32_t start_offset; // The offset from the start of the object. 188 uint32_t size; // The gap size of 1, 2, or 4 bytes. 189}; 190struct FieldGapsComparator { 191 explicit FieldGapsComparator() { 192 } 193 bool operator() (const FieldGap& lhs, const FieldGap& rhs) 194 NO_THREAD_SAFETY_ANALYSIS { 195 // Sort by gap size, largest first. Secondary sort by starting offset. 196 // Note that the priority queue returns the largest element, so operator() 197 // should return true if lhs is less than rhs. 198 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset); 199 } 200}; 201typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps; 202 203// Adds largest aligned gaps to queue of gaps. 204static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) { 205 DCHECK(gaps != nullptr); 206 207 uint32_t current_offset = gap_start; 208 while (current_offset != gap_end) { 209 size_t remaining = gap_end - current_offset; 210 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) { 211 gaps->push(FieldGap {current_offset, sizeof(uint32_t)}); 212 current_offset += sizeof(uint32_t); 213 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) { 214 gaps->push(FieldGap {current_offset, sizeof(uint16_t)}); 215 current_offset += sizeof(uint16_t); 216 } else { 217 gaps->push(FieldGap {current_offset, sizeof(uint8_t)}); 218 current_offset += sizeof(uint8_t); 219 } 220 DCHECK_LE(current_offset, gap_end) << "Overran gap"; 221 } 222} 223// Shuffle fields forward, making use of gaps whenever possible. 224template<int n> 225static void ShuffleForward(size_t* current_field_idx, 226 MemberOffset* field_offset, 227 std::deque<ArtField*>* grouped_and_sorted_fields, 228 FieldGaps* gaps) 229 SHARED_REQUIRES(Locks::mutator_lock_) { 230 DCHECK(current_field_idx != nullptr); 231 DCHECK(grouped_and_sorted_fields != nullptr); 232 DCHECK(gaps != nullptr); 233 DCHECK(field_offset != nullptr); 234 235 DCHECK(IsPowerOfTwo(n)); 236 while (!grouped_and_sorted_fields->empty()) { 237 ArtField* field = grouped_and_sorted_fields->front(); 238 Primitive::Type type = field->GetTypeAsPrimitiveType(); 239 if (Primitive::ComponentSize(type) < n) { 240 break; 241 } 242 if (!IsAligned<n>(field_offset->Uint32Value())) { 243 MemberOffset old_offset = *field_offset; 244 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n)); 245 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps); 246 } 247 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types 248 grouped_and_sorted_fields->pop_front(); 249 if (!gaps->empty() && gaps->top().size >= n) { 250 FieldGap gap = gaps->top(); 251 gaps->pop(); 252 DCHECK_ALIGNED(gap.start_offset, n); 253 field->SetOffset(MemberOffset(gap.start_offset)); 254 if (gap.size > n) { 255 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps); 256 } 257 } else { 258 DCHECK_ALIGNED(field_offset->Uint32Value(), n); 259 field->SetOffset(*field_offset); 260 *field_offset = MemberOffset(field_offset->Uint32Value() + n); 261 } 262 ++(*current_field_idx); 263 } 264} 265 266ClassLinker::ClassLinker(InternTable* intern_table) 267 // dex_lock_ is recursive as it may be used in stack dumping. 268 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel), 269 dex_cache_image_class_lookup_required_(false), 270 failed_dex_cache_class_lookups_(0), 271 class_roots_(nullptr), 272 array_iftable_(nullptr), 273 find_array_class_cache_next_victim_(0), 274 init_done_(false), 275 log_new_dex_caches_roots_(false), 276 log_new_class_table_roots_(false), 277 intern_table_(intern_table), 278 quick_resolution_trampoline_(nullptr), 279 quick_imt_conflict_trampoline_(nullptr), 280 quick_generic_jni_trampoline_(nullptr), 281 quick_to_interpreter_bridge_trampoline_(nullptr), 282 image_pointer_size_(sizeof(void*)) { 283 CHECK(intern_table_ != nullptr); 284 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_), 285 "Array cache size wrong."); 286 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr)); 287} 288 289void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) { 290 VLOG(startup) << "ClassLinker::Init"; 291 292 Thread* const self = Thread::Current(); 293 Runtime* const runtime = Runtime::Current(); 294 gc::Heap* const heap = runtime->GetHeap(); 295 296 CHECK(!heap->HasImageSpace()) << "Runtime has image. We should use it."; 297 CHECK(!init_done_); 298 299 // Use the pointer size from the runtime since we are probably creating the image. 300 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet()); 301 302 // java_lang_Class comes first, it's needed for AllocClass 303 // The GC can't handle an object with a null class since we can't get the size of this object. 304 heap->IncrementDisableMovingGC(self); 305 StackHandleScope<64> hs(self); // 64 is picked arbitrarily. 306 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_); 307 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>( 308 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor())))); 309 CHECK(java_lang_Class.Get() != nullptr); 310 mirror::Class::SetClassClass(java_lang_Class.Get()); 311 java_lang_Class->SetClass(java_lang_Class.Get()); 312 if (kUseBakerOrBrooksReadBarrier) { 313 java_lang_Class->AssertReadBarrierPointer(); 314 } 315 java_lang_Class->SetClassSize(class_class_size); 316 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot); 317 heap->DecrementDisableMovingGC(self); 318 // AllocClass(mirror::Class*) can now be used 319 320 // Class[] is used for reflection support. 321 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_); 322 Handle<mirror::Class> class_array_class(hs.NewHandle( 323 AllocClass(self, java_lang_Class.Get(), class_array_class_size))); 324 class_array_class->SetComponentType(java_lang_Class.Get()); 325 326 // java_lang_Object comes next so that object_array_class can be created. 327 Handle<mirror::Class> java_lang_Object(hs.NewHandle( 328 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_)))); 329 CHECK(java_lang_Object.Get() != nullptr); 330 // backfill Object as the super class of Class. 331 java_lang_Class->SetSuperClass(java_lang_Object.Get()); 332 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self); 333 334 // Object[] next to hold class roots. 335 Handle<mirror::Class> object_array_class(hs.NewHandle( 336 AllocClass(self, java_lang_Class.Get(), 337 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_)))); 338 object_array_class->SetComponentType(java_lang_Object.Get()); 339 340 // Setup the char (primitive) class to be used for char[]. 341 Handle<mirror::Class> char_class(hs.NewHandle( 342 AllocClass(self, java_lang_Class.Get(), 343 mirror::Class::PrimitiveClassSize(image_pointer_size_)))); 344 // The primitive char class won't be initialized by 345 // InitializePrimitiveClass until line 459, but strings (and 346 // internal char arrays) will be allocated before that and the 347 // component size, which is computed from the primitive type, needs 348 // to be set here. 349 char_class->SetPrimitiveType(Primitive::kPrimChar); 350 351 // Setup the char[] class to be used for String. 352 Handle<mirror::Class> char_array_class(hs.NewHandle( 353 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_)))); 354 char_array_class->SetComponentType(char_class.Get()); 355 mirror::CharArray::SetArrayClass(char_array_class.Get()); 356 357 // Setup String. 358 Handle<mirror::Class> java_lang_String(hs.NewHandle( 359 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_)))); 360 mirror::String::SetClass(java_lang_String.Get()); 361 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self); 362 java_lang_String->SetStringClass(); 363 364 // Setup java.lang.ref.Reference. 365 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle( 366 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_)))); 367 mirror::Reference::SetClass(java_lang_ref_Reference.Get()); 368 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize()); 369 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self); 370 371 // Create storage for root classes, save away our work so far (requires descriptors). 372 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>( 373 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(), 374 kClassRootsMax)); 375 CHECK(!class_roots_.IsNull()); 376 SetClassRoot(kJavaLangClass, java_lang_Class.Get()); 377 SetClassRoot(kJavaLangObject, java_lang_Object.Get()); 378 SetClassRoot(kClassArrayClass, class_array_class.Get()); 379 SetClassRoot(kObjectArrayClass, object_array_class.Get()); 380 SetClassRoot(kCharArrayClass, char_array_class.Get()); 381 SetClassRoot(kJavaLangString, java_lang_String.Get()); 382 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get()); 383 384 // Setup the primitive type classes. 385 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean)); 386 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte)); 387 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort)); 388 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt)); 389 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong)); 390 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat)); 391 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble)); 392 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid)); 393 394 // Create array interface entries to populate once we can load system classes. 395 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2)); 396 397 // Create int array type for AllocDexCache (done in AppendToBootClassPath). 398 Handle<mirror::Class> int_array_class(hs.NewHandle( 399 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_)))); 400 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt)); 401 mirror::IntArray::SetArrayClass(int_array_class.Get()); 402 SetClassRoot(kIntArrayClass, int_array_class.Get()); 403 404 // Create long array type for AllocDexCache (done in AppendToBootClassPath). 405 Handle<mirror::Class> long_array_class(hs.NewHandle( 406 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_)))); 407 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong)); 408 mirror::LongArray::SetArrayClass(long_array_class.Get()); 409 SetClassRoot(kLongArrayClass, long_array_class.Get()); 410 411 // now that these are registered, we can use AllocClass() and AllocObjectArray 412 413 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache. 414 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle( 415 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_)))); 416 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get()); 417 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize()); 418 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self); 419 420 // Set up array classes for string, field, method 421 Handle<mirror::Class> object_array_string(hs.NewHandle( 422 AllocClass(self, java_lang_Class.Get(), 423 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_)))); 424 object_array_string->SetComponentType(java_lang_String.Get()); 425 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get()); 426 427 // Create runtime resolution and imt conflict methods. 428 runtime->SetResolutionMethod(runtime->CreateResolutionMethod()); 429 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod()); 430 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod()); 431 432 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create 433 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses 434 // these roots. 435 CHECK_NE(0U, boot_class_path.size()); 436 for (auto& dex_file : boot_class_path) { 437 CHECK(dex_file.get() != nullptr); 438 AppendToBootClassPath(self, *dex_file); 439 opened_dex_files_.push_back(std::move(dex_file)); 440 } 441 442 // now we can use FindSystemClass 443 444 // run char class through InitializePrimitiveClass to finish init 445 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar); 446 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor 447 448 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that 449 // we do not need friend classes or a publicly exposed setter. 450 quick_generic_jni_trampoline_ = GetQuickGenericJniStub(); 451 if (!runtime->IsAotCompiler()) { 452 // We need to set up the generic trampolines since we don't have an image. 453 quick_resolution_trampoline_ = GetQuickResolutionStub(); 454 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub(); 455 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge(); 456 } 457 458 // Object, String and DexCache need to be rerun through FindSystemClass to finish init 459 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self); 460 CHECK_EQ(java_lang_Object.Get(), FindSystemClass(self, "Ljava/lang/Object;")); 461 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize()); 462 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self); 463 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;"); 464 if (java_lang_String.Get() != String_class) { 465 std::ostringstream os1, os2; 466 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail); 467 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail); 468 LOG(FATAL) << os1.str() << "\n\n" << os2.str(); 469 } 470 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self); 471 CHECK_EQ(java_lang_DexCache.Get(), FindSystemClass(self, "Ljava/lang/DexCache;")); 472 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize()); 473 474 // Setup the primitive array type classes - can't be done until Object has a vtable. 475 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z")); 476 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass)); 477 478 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B")); 479 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass)); 480 481 CHECK_EQ(char_array_class.Get(), FindSystemClass(self, "[C")); 482 483 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S")); 484 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass)); 485 486 CHECK_EQ(int_array_class.Get(), FindSystemClass(self, "[I")); 487 488 CHECK_EQ(long_array_class.Get(), FindSystemClass(self, "[J")); 489 490 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F")); 491 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass)); 492 493 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D")); 494 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass)); 495 496 CHECK_EQ(class_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Class;")); 497 498 CHECK_EQ(object_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Object;")); 499 500 // Setup the single, global copy of "iftable". 501 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;")); 502 CHECK(java_lang_Cloneable.Get() != nullptr); 503 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;")); 504 CHECK(java_io_Serializable.Get() != nullptr); 505 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to 506 // crawl up and explicitly list all of the supers as well. 507 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get()); 508 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get()); 509 510 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread 511 // suspension. 512 CHECK_EQ(java_lang_Cloneable.Get(), 513 mirror::Class::GetDirectInterface(self, class_array_class, 0)); 514 CHECK_EQ(java_io_Serializable.Get(), 515 mirror::Class::GetDirectInterface(self, class_array_class, 1)); 516 CHECK_EQ(java_lang_Cloneable.Get(), 517 mirror::Class::GetDirectInterface(self, object_array_class, 0)); 518 CHECK_EQ(java_io_Serializable.Get(), 519 mirror::Class::GetDirectInterface(self, object_array_class, 1)); 520 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their 521 // dex_cache_ fields and register them in class_table_. 522 CHECK_EQ(java_lang_Class.Get(), FindSystemClass(self, "Ljava/lang/Class;")); 523 524 CHECK_EQ(object_array_string.Get(), 525 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass))); 526 527 // End of special init trickery, subsequent classes may be loaded via FindSystemClass. 528 529 // Create java.lang.reflect.Proxy root. 530 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;")); 531 532 // Create java.lang.reflect.Field.class root. 533 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;"); 534 CHECK(class_root != nullptr); 535 SetClassRoot(kJavaLangReflectField, class_root); 536 mirror::Field::SetClass(class_root); 537 538 // Create java.lang.reflect.Field array root. 539 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;"); 540 CHECK(class_root != nullptr); 541 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root); 542 mirror::Field::SetArrayClass(class_root); 543 544 // Create java.lang.reflect.Constructor.class root and array root. 545 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;"); 546 CHECK(class_root != nullptr); 547 SetClassRoot(kJavaLangReflectConstructor, class_root); 548 mirror::Constructor::SetClass(class_root); 549 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;"); 550 CHECK(class_root != nullptr); 551 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root); 552 mirror::Constructor::SetArrayClass(class_root); 553 554 // Create java.lang.reflect.Method.class root and array root. 555 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;"); 556 CHECK(class_root != nullptr); 557 SetClassRoot(kJavaLangReflectMethod, class_root); 558 mirror::Method::SetClass(class_root); 559 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;"); 560 CHECK(class_root != nullptr); 561 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root); 562 mirror::Method::SetArrayClass(class_root); 563 564 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes 565 // finish initializing Reference class 566 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self); 567 CHECK_EQ(java_lang_ref_Reference.Get(), FindSystemClass(self, "Ljava/lang/ref/Reference;")); 568 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize()); 569 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), 570 mirror::Reference::ClassSize(image_pointer_size_)); 571 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"); 572 class_root->SetAccessFlags(class_root->GetAccessFlags() | 573 kAccClassIsReference | kAccClassIsFinalizerReference); 574 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;"); 575 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference | 576 kAccClassIsPhantomReference); 577 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;"); 578 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference); 579 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;"); 580 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference | 581 kAccClassIsWeakReference); 582 583 // Setup the ClassLoader, verifying the object_size_. 584 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;"); 585 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize()); 586 SetClassRoot(kJavaLangClassLoader, class_root); 587 588 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and 589 // java.lang.StackTraceElement as a convenience. 590 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;")); 591 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable)); 592 SetClassRoot(kJavaLangClassNotFoundException, 593 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;")); 594 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;")); 595 SetClassRoot(kJavaLangStackTraceElementArrayClass, 596 FindSystemClass(self, "[Ljava/lang/StackTraceElement;")); 597 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement)); 598 599 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly 600 // initialized. 601 { 602 const DexFile& dex_file = java_lang_Object->GetDexFile(); 603 const DexFile::StringId* void_string_id = dex_file.FindStringId("V"); 604 CHECK(void_string_id != nullptr); 605 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id); 606 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index); 607 CHECK(void_type_id != nullptr); 608 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id); 609 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class 610 // as referrer so the used dex cache is core's one. 611 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get()); 612 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid)); 613 self->AssertNoPendingException(); 614 } 615 616 FinishInit(self); 617 618 VLOG(startup) << "ClassLinker::InitFromCompiler exiting"; 619} 620 621void ClassLinker::FinishInit(Thread* self) { 622 VLOG(startup) << "ClassLinker::FinishInit entering"; 623 624 // Let the heap know some key offsets into java.lang.ref instances 625 // Note: we hard code the field indexes here rather than using FindInstanceField 626 // as the types of the field can't be resolved prior to the runtime being 627 // fully initialized 628 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference); 629 mirror::Class* java_lang_ref_FinalizerReference = 630 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"); 631 632 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0); 633 CHECK_STREQ(pendingNext->GetName(), "pendingNext"); 634 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;"); 635 636 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1); 637 CHECK_STREQ(queue->GetName(), "queue"); 638 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;"); 639 640 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2); 641 CHECK_STREQ(queueNext->GetName(), "queueNext"); 642 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;"); 643 644 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3); 645 CHECK_STREQ(referent->GetName(), "referent"); 646 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;"); 647 648 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2); 649 CHECK_STREQ(zombie->GetName(), "zombie"); 650 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;"); 651 652 // ensure all class_roots_ are initialized 653 for (size_t i = 0; i < kClassRootsMax; i++) { 654 ClassRoot class_root = static_cast<ClassRoot>(i); 655 mirror::Class* klass = GetClassRoot(class_root); 656 CHECK(klass != nullptr); 657 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr); 658 // note SetClassRoot does additional validation. 659 // if possible add new checks there to catch errors early 660 } 661 662 CHECK(!array_iftable_.IsNull()); 663 664 // disable the slow paths in FindClass and CreatePrimitiveClass now 665 // that Object, Class, and Object[] are setup 666 init_done_ = true; 667 668 VLOG(startup) << "ClassLinker::FinishInit exiting"; 669} 670 671void ClassLinker::RunRootClinits() { 672 Thread* self = Thread::Current(); 673 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) { 674 mirror::Class* c = GetClassRoot(ClassRoot(i)); 675 if (!c->IsArrayClass() && !c->IsPrimitive()) { 676 StackHandleScope<1> hs(self); 677 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i)))); 678 EnsureInitialized(self, h_class, true, true); 679 self->AssertNoPendingException(); 680 } 681 } 682} 683 684const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) { 685 WriterMutexLock mu(Thread::Current(), dex_lock_); 686 if (kIsDebugBuild) { 687 for (size_t i = 0; i < oat_files_.size(); ++i) { 688 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation(); 689 } 690 } 691 VLOG(class_linker) << "Registering " << oat_file->GetLocation(); 692 oat_files_.push_back(oat_file); 693 return oat_file; 694} 695 696OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) { 697 VLOG(startup) << "ClassLinker::GetImageOatFile entering"; 698 OatFile* oat_file = space->ReleaseOatFile(); 699 CHECK_EQ(RegisterOatFile(oat_file), oat_file); 700 VLOG(startup) << "ClassLinker::GetImageOatFile exiting"; 701 return *oat_file; 702} 703 704class DexFileAndClassPair : ValueObject { 705 public: 706 DexFileAndClassPair(const DexFile* dex_file, size_t current_class_index, bool from_loaded_oat) 707 : cached_descriptor_(GetClassDescriptor(dex_file, current_class_index)), 708 dex_file_(dex_file), 709 current_class_index_(current_class_index), 710 from_loaded_oat_(from_loaded_oat) {} 711 712 DexFileAndClassPair(const DexFileAndClassPair&) = default; 713 714 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) { 715 cached_descriptor_ = rhs.cached_descriptor_; 716 dex_file_ = rhs.dex_file_; 717 current_class_index_ = rhs.current_class_index_; 718 from_loaded_oat_ = rhs.from_loaded_oat_; 719 return *this; 720 } 721 722 const char* GetCachedDescriptor() const { 723 return cached_descriptor_; 724 } 725 726 bool operator<(const DexFileAndClassPair& rhs) const { 727 const char* lhsDescriptor = cached_descriptor_; 728 const char* rhsDescriptor = rhs.cached_descriptor_; 729 int cmp = strcmp(lhsDescriptor, rhsDescriptor); 730 if (cmp != 0) { 731 // Note that the order must be reversed. We want to iterate over the classes in dex files. 732 // They are sorted lexicographically. Thus, the priority-queue must be a min-queue. 733 return cmp > 0; 734 } 735 return dex_file_ < rhs.dex_file_; 736 } 737 738 bool DexFileHasMoreClasses() const { 739 return current_class_index_ + 1 < dex_file_->NumClassDefs(); 740 } 741 742 DexFileAndClassPair GetNext() const { 743 return DexFileAndClassPair(dex_file_, current_class_index_ + 1, from_loaded_oat_); 744 } 745 746 size_t GetCurrentClassIndex() const { 747 return current_class_index_; 748 } 749 750 bool FromLoadedOat() const { 751 return from_loaded_oat_; 752 } 753 754 const DexFile* GetDexFile() const { 755 return dex_file_; 756 } 757 758 void DeleteDexFile() { 759 delete dex_file_; 760 dex_file_ = nullptr; 761 } 762 763 private: 764 static const char* GetClassDescriptor(const DexFile* dex_file, size_t index) { 765 const DexFile::ClassDef& class_def = dex_file->GetClassDef(static_cast<uint16_t>(index)); 766 return dex_file->StringByTypeIdx(class_def.class_idx_); 767 } 768 769 const char* cached_descriptor_; 770 const DexFile* dex_file_; 771 size_t current_class_index_; 772 bool from_loaded_oat_; // We only need to compare mismatches between what we load now 773 // and what was loaded before. Any old duplicates must have been 774 // OK, and any new "internal" duplicates are as well (they must 775 // be from multidex, which resolves correctly). 776}; 777 778static void AddDexFilesFromOat(const OatFile* oat_file, bool already_loaded, 779 std::priority_queue<DexFileAndClassPair>* heap) { 780 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles(); 781 for (const OatDexFile* oat_dex_file : oat_dex_files) { 782 std::string error; 783 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error); 784 if (dex_file.get() == nullptr) { 785 LOG(WARNING) << "Could not create dex file from oat file: " << error; 786 } else { 787 if (dex_file->NumClassDefs() > 0U) { 788 heap->emplace(dex_file.release(), 0U, already_loaded); 789 } 790 } 791 } 792} 793 794static void AddNext(DexFileAndClassPair* original, 795 std::priority_queue<DexFileAndClassPair>* heap) { 796 if (original->DexFileHasMoreClasses()) { 797 heap->push(original->GetNext()); 798 } else { 799 // Need to delete the dex file. 800 original->DeleteDexFile(); 801 } 802} 803 804static void FreeDexFilesInHeap(std::priority_queue<DexFileAndClassPair>* heap) { 805 while (!heap->empty()) { 806 delete heap->top().GetDexFile(); 807 heap->pop(); 808 } 809} 810 811const OatFile* ClassLinker::GetBootOatFile() { 812 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace(); 813 if (image_space == nullptr) { 814 return nullptr; 815 } 816 return image_space->GetOatFile(); 817} 818 819const OatFile* ClassLinker::GetPrimaryOatFile() { 820 ReaderMutexLock mu(Thread::Current(), dex_lock_); 821 const OatFile* boot_oat_file = GetBootOatFile(); 822 if (boot_oat_file != nullptr) { 823 for (const OatFile* oat_file : oat_files_) { 824 if (oat_file != boot_oat_file) { 825 return oat_file; 826 } 827 } 828 } 829 return nullptr; 830} 831 832// Check for class-def collisions in dex files. 833// 834// This works by maintaining a heap with one class from each dex file, sorted by the class 835// descriptor. Then a dex-file/class pair is continually removed from the heap and compared 836// against the following top element. If the descriptor is the same, it is now checked whether 837// the two elements agree on whether their dex file was from an already-loaded oat-file or the 838// new oat file. Any disagreement indicates a collision. 839bool ClassLinker::HasCollisions(const OatFile* oat_file, std::string* error_msg) { 840 if (!kDuplicateClassesCheck) { 841 return false; 842 } 843 844 // Dex files are registered late - once a class is actually being loaded. We have to compare 845 // against the open oat files. Take the dex_lock_ that protects oat_files_ accesses. 846 ReaderMutexLock mu(Thread::Current(), dex_lock_); 847 848 std::priority_queue<DexFileAndClassPair> queue; 849 850 // Add dex files from already loaded oat files, but skip boot. 851 { 852 const OatFile* boot_oat = GetBootOatFile(); 853 for (const OatFile* loaded_oat_file : oat_files_) { 854 if (loaded_oat_file == boot_oat) { 855 continue; 856 } 857 AddDexFilesFromOat(loaded_oat_file, true, &queue); 858 } 859 } 860 861 if (queue.empty()) { 862 // No other oat files, return early. 863 return false; 864 } 865 866 // Add dex files from the oat file to check. 867 AddDexFilesFromOat(oat_file, false, &queue); 868 869 // Now drain the queue. 870 while (!queue.empty()) { 871 DexFileAndClassPair compare_pop = queue.top(); 872 queue.pop(); 873 874 // Compare against the following elements. 875 while (!queue.empty()) { 876 DexFileAndClassPair top = queue.top(); 877 878 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) { 879 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files. 880 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) { 881 *error_msg = 882 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s", 883 compare_pop.GetCachedDescriptor(), 884 compare_pop.GetDexFile()->GetLocation().c_str(), 885 top.GetDexFile()->GetLocation().c_str()); 886 FreeDexFilesInHeap(&queue); 887 return true; 888 } 889 // Pop it. 890 queue.pop(); 891 AddNext(&top, &queue); 892 } else { 893 // Something else. Done here. 894 break; 895 } 896 } 897 AddNext(&compare_pop, &queue); 898 } 899 900 return false; 901} 902 903std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat( 904 const char* dex_location, const char* oat_location, 905 std::vector<std::string>* error_msgs) { 906 CHECK(error_msgs != nullptr); 907 908 // Verify we aren't holding the mutator lock, which could starve GC if we 909 // have to generate or relocate an oat file. 910 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); 911 912 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA, 913 !Runtime::Current()->IsAotCompiler()); 914 915 // Lock the target oat location to avoid races generating and loading the 916 // oat file. 917 std::string error_msg; 918 if (!oat_file_assistant.Lock(&error_msg)) { 919 // Don't worry too much if this fails. If it does fail, it's unlikely we 920 // can generate an oat file anyway. 921 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg; 922 } 923 924 // Check if we already have an up-to-date oat file open. 925 const OatFile* source_oat_file = nullptr; 926 { 927 ReaderMutexLock mu(Thread::Current(), dex_lock_); 928 for (const OatFile* oat_file : oat_files_) { 929 CHECK(oat_file != nullptr); 930 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) { 931 source_oat_file = oat_file; 932 break; 933 } 934 } 935 } 936 937 // If we didn't have an up-to-date oat file open, try to load one from disk. 938 if (source_oat_file == nullptr) { 939 // Update the oat file on disk if we can. This may fail, but that's okay. 940 // Best effort is all that matters here. 941 if (!oat_file_assistant.MakeUpToDate(&error_msg)) { 942 LOG(WARNING) << error_msg; 943 } 944 945 // Get the oat file on disk. 946 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile(); 947 if (oat_file.get() != nullptr) { 948 // Take the file only if it has no collisions, or we must take it because of preopting. 949 bool accept_oat_file = !HasCollisions(oat_file.get(), &error_msg); 950 if (!accept_oat_file) { 951 // Failed the collision check. Print warning. 952 if (Runtime::Current()->IsDexFileFallbackEnabled()) { 953 LOG(WARNING) << "Found duplicate classes, falling back to interpreter mode for " 954 << dex_location; 955 } else { 956 LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to " 957 " load classes for " << dex_location; 958 } 959 LOG(WARNING) << error_msg; 960 961 // However, if the app was part of /system and preopted, there is no original dex file 962 // available. In that case grudgingly accept the oat file. 963 if (!DexFile::MaybeDex(dex_location)) { 964 accept_oat_file = true; 965 LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. " 966 << "Allow oat file use. This is potentially dangerous."; 967 } 968 } 969 970 if (accept_oat_file) { 971 source_oat_file = oat_file.release(); 972 RegisterOatFile(source_oat_file); 973 } 974 } 975 } 976 977 std::vector<std::unique_ptr<const DexFile>> dex_files; 978 979 // Load the dex files from the oat file. 980 if (source_oat_file != nullptr) { 981 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location); 982 if (dex_files.empty()) { 983 error_msgs->push_back("Failed to open dex files from " 984 + source_oat_file->GetLocation()); 985 } 986 } 987 988 // Fall back to running out of the original dex file if we couldn't load any 989 // dex_files from the oat file. 990 if (dex_files.empty()) { 991 if (oat_file_assistant.HasOriginalDexFiles()) { 992 if (Runtime::Current()->IsDexFileFallbackEnabled()) { 993 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) { 994 LOG(WARNING) << error_msg; 995 error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)); 996 } 997 } else { 998 error_msgs->push_back("Fallback mode disabled, skipping dex files."); 999 } 1000 } else { 1001 error_msgs->push_back("No original dex files found for dex location " 1002 + std::string(dex_location)); 1003 } 1004 } 1005 return dex_files; 1006} 1007 1008const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) { 1009 ReaderMutexLock mu(Thread::Current(), dex_lock_); 1010 for (size_t i = 0; i < oat_files_.size(); i++) { 1011 const OatFile* oat_file = oat_files_[i]; 1012 DCHECK(oat_file != nullptr); 1013 if (oat_file->GetLocation() == oat_location) { 1014 return oat_file; 1015 } 1016 } 1017 return nullptr; 1018} 1019 1020static void SanityCheckArtMethod(ArtMethod* m, mirror::Class* expected_class, 1021 gc::space::ImageSpace* space) 1022 SHARED_REQUIRES(Locks::mutator_lock_) { 1023 if (m->IsRuntimeMethod()) { 1024 CHECK(m->GetDeclaringClass() == nullptr) << PrettyMethod(m); 1025 } else if (m->IsMiranda()) { 1026 CHECK(m->GetDeclaringClass() != nullptr) << PrettyMethod(m); 1027 } else if (expected_class != nullptr) { 1028 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << PrettyMethod(m); 1029 } 1030 if (space != nullptr) { 1031 auto& header = space->GetImageHeader(); 1032 auto& methods = header.GetMethodsSection(); 1033 auto offset = reinterpret_cast<uint8_t*>(m) - space->Begin(); 1034 CHECK(methods.Contains(offset)) << m << " not in " << methods; 1035 } 1036} 1037 1038static void SanityCheckArtMethodPointerArray( 1039 mirror::PointerArray* arr, mirror::Class* expected_class, size_t pointer_size, 1040 gc::space::ImageSpace* space) SHARED_REQUIRES(Locks::mutator_lock_) { 1041 CHECK(arr != nullptr); 1042 for (int32_t j = 0; j < arr->GetLength(); ++j) { 1043 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size); 1044 // expected_class == null means we are a dex cache. 1045 if (expected_class != nullptr) { 1046 CHECK(method != nullptr); 1047 } 1048 if (method != nullptr) { 1049 SanityCheckArtMethod(method, expected_class, space); 1050 } 1051 } 1052} 1053 1054static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) 1055 SHARED_REQUIRES(Locks::mutator_lock_) { 1056 DCHECK(obj != nullptr); 1057 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj; 1058 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj; 1059 if (obj->IsClass()) { 1060 auto klass = obj->AsClass(); 1061 for (ArtField& field : klass->GetIFields()) { 1062 CHECK_EQ(field.GetDeclaringClass(), klass); 1063 } 1064 for (ArtField& field : klass->GetSFields()) { 1065 CHECK_EQ(field.GetDeclaringClass(), klass); 1066 } 1067 auto* runtime = Runtime::Current(); 1068 auto* image_space = runtime->GetHeap()->GetImageSpace(); 1069 auto pointer_size = runtime->GetClassLinker()->GetImagePointerSize(); 1070 for (auto& m : klass->GetDirectMethods(pointer_size)) { 1071 SanityCheckArtMethod(&m, klass, image_space); 1072 } 1073 for (auto& m : klass->GetVirtualMethods(pointer_size)) { 1074 SanityCheckArtMethod(&m, klass, image_space); 1075 } 1076 auto* vtable = klass->GetVTable(); 1077 if (vtable != nullptr) { 1078 SanityCheckArtMethodPointerArray(vtable, nullptr, pointer_size, image_space); 1079 } 1080 if (klass->ShouldHaveEmbeddedImtAndVTable()) { 1081 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) { 1082 SanityCheckArtMethod(klass->GetEmbeddedImTableEntry(i, pointer_size), nullptr, image_space); 1083 } 1084 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) { 1085 SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr, image_space); 1086 } 1087 } 1088 auto* iftable = klass->GetIfTable(); 1089 if (iftable != nullptr) { 1090 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 1091 if (iftable->GetMethodArrayCount(i) > 0) { 1092 SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr, pointer_size, 1093 image_space); 1094 } 1095 } 1096 } 1097 } 1098} 1099 1100// Set image methods' entry point to interpreter. 1101class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor { 1102 public: 1103 explicit SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size) 1104 : image_pointer_size_(image_pointer_size) {} 1105 1106 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 1107 if (kIsDebugBuild && !method->IsRuntimeMethod()) { 1108 CHECK(method->GetDeclaringClass() != nullptr); 1109 } 1110 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) { 1111 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(), 1112 image_pointer_size_); 1113 } 1114 } 1115 1116 private: 1117 const size_t image_pointer_size_; 1118 1119 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor); 1120}; 1121 1122void ClassLinker::InitFromImage() { 1123 VLOG(startup) << "ClassLinker::InitFromImage entering"; 1124 CHECK(!init_done_); 1125 1126 Runtime* const runtime = Runtime::Current(); 1127 Thread* const self = Thread::Current(); 1128 gc::Heap* const heap = runtime->GetHeap(); 1129 gc::space::ImageSpace* const space = heap->GetImageSpace(); 1130 CHECK(space != nullptr); 1131 image_pointer_size_ = space->GetImageHeader().GetPointerSize(); 1132 dex_cache_image_class_lookup_required_ = true; 1133 OatFile& oat_file = GetImageOatFile(space); 1134 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U); 1135 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U); 1136 const char* image_file_location = oat_file.GetOatHeader(). 1137 GetStoreValueByKey(OatHeader::kImageLocationKey); 1138 CHECK(image_file_location == nullptr || *image_file_location == 0); 1139 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline(); 1140 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline(); 1141 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline(); 1142 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge(); 1143 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 1144 mirror::ObjectArray<mirror::DexCache>* dex_caches = 1145 dex_caches_object->AsObjectArray<mirror::DexCache>(); 1146 1147 StackHandleScope<1> hs(self); 1148 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle( 1149 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)-> 1150 AsObjectArray<mirror::Class>())); 1151 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get()); 1152 1153 // Special case of setting up the String class early so that we can test arbitrary objects 1154 // as being Strings or not 1155 mirror::String::SetClass(GetClassRoot(kJavaLangString)); 1156 1157 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(), 1158 static_cast<uint32_t>(dex_caches->GetLength())); 1159 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 1160 StackHandleScope<1> hs2(self); 1161 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i))); 1162 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8()); 1163 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(), 1164 nullptr); 1165 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location; 1166 std::string error_msg; 1167 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg); 1168 if (dex_file.get() == nullptr) { 1169 LOG(FATAL) << "Failed to open dex file " << dex_file_location 1170 << " from within oat file " << oat_file.GetLocation() 1171 << " error '" << error_msg << "'"; 1172 UNREACHABLE(); 1173 } 1174 1175 if (kSanityCheckObjects) { 1176 SanityCheckArtMethodPointerArray(dex_cache->GetResolvedMethods(), nullptr, 1177 image_pointer_size_, space); 1178 } 1179 1180 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum()); 1181 1182 AppendToBootClassPath(*dex_file.get(), dex_cache); 1183 opened_dex_files_.push_back(std::move(dex_file)); 1184 } 1185 1186 CHECK(ValidPointerSize(image_pointer_size_)) << image_pointer_size_; 1187 1188 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live 1189 // bitmap walk. 1190 if (!runtime->IsAotCompiler()) { 1191 // Only the Aot compiler supports having an image with a different pointer size than the 1192 // runtime. This happens on the host for compile 32 bit tests since we use a 64 bit libart 1193 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps. 1194 CHECK_EQ(image_pointer_size_, sizeof(void*)); 1195 } 1196 1197 if (kSanityCheckObjects) { 1198 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 1199 auto* dex_cache = dex_caches->Get(i); 1200 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) { 1201 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_); 1202 if (field != nullptr) { 1203 CHECK(field->GetDeclaringClass()->GetClass() != nullptr); 1204 } 1205 } 1206 } 1207 heap->VisitObjects(SanityCheckObjectsCallback, nullptr); 1208 } 1209 1210 // Set entry point to interpreter if in InterpretOnly mode. 1211 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) { 1212 const ImageHeader& header = space->GetImageHeader(); 1213 const ImageSection& methods = header.GetMethodsSection(); 1214 const size_t art_method_size = ArtMethod::ObjectSize(image_pointer_size_); 1215 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_); 1216 methods.VisitPackedArtMethods(&visitor, space->Begin(), art_method_size); 1217 } 1218 1219 // reinit class_roots_ 1220 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass)); 1221 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get()); 1222 1223 // reinit array_iftable_ from any array class instance, they should be == 1224 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable()); 1225 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable()); 1226 // String class root was set above 1227 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField)); 1228 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass)); 1229 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor)); 1230 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass)); 1231 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod)); 1232 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass)); 1233 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference)); 1234 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass)); 1235 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass)); 1236 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass)); 1237 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass)); 1238 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass)); 1239 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass)); 1240 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass)); 1241 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass)); 1242 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable)); 1243 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement)); 1244 1245 FinishInit(self); 1246 1247 VLOG(startup) << "ClassLinker::InitFromImage exiting"; 1248} 1249 1250bool ClassLinker::ClassInClassTable(mirror::Class* klass) { 1251 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1252 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader()); 1253 return class_table != nullptr && class_table->Contains(klass); 1254} 1255 1256void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) { 1257 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1258 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor( 1259 visitor, RootInfo(kRootStickyClass)); 1260 if ((flags & kVisitRootFlagAllRoots) != 0) { 1261 // Argument for how root visiting deals with ArtField and ArtMethod roots. 1262 // There is 3 GC cases to handle: 1263 // Non moving concurrent: 1264 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held 1265 // live by the class and class roots. 1266 // 1267 // Moving non-concurrent: 1268 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move. 1269 // To prevent missing roots, this case needs to ensure that there is no 1270 // suspend points between the point which we allocate ArtMethod arrays and place them in a 1271 // class which is in the class table. 1272 // 1273 // Moving concurrent: 1274 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are 1275 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy. 1276 boot_class_table_.VisitRoots(visitor, flags); 1277 for (GcRoot<mirror::ClassLoader>& root : class_loaders_) { 1278 // May be null for boot ClassLoader. 1279 root.VisitRoot(visitor, RootInfo(kRootVMInternal)); 1280 ClassTable* const class_table = root.Read()->GetClassTable(); 1281 if (class_table != nullptr) { 1282 // May be null if we have no classes. 1283 class_table->VisitRoots(visitor, flags); 1284 } 1285 } 1286 } else if ((flags & kVisitRootFlagNewRoots) != 0) { 1287 for (auto& root : new_class_roots_) { 1288 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>(); 1289 root.VisitRoot(visitor, RootInfo(kRootStickyClass)); 1290 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>(); 1291 // Concurrent moving GC marked new roots through the to-space invariant. 1292 CHECK_EQ(new_ref, old_ref); 1293 } 1294 } 1295 buffered_visitor.Flush(); // Flush before clearing new_class_roots_. 1296 if ((flags & kVisitRootFlagClearRootLog) != 0) { 1297 new_class_roots_.clear(); 1298 } 1299 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) { 1300 log_new_class_table_roots_ = true; 1301 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) { 1302 log_new_class_table_roots_ = false; 1303 } 1304 // We deliberately ignore the class roots in the image since we 1305 // handle image roots by using the MS/CMS rescanning of dirty cards. 1306} 1307 1308// Keep in sync with InitCallback. Anything we visit, we need to 1309// reinit references to when reinitializing a ClassLinker from a 1310// mapped image. 1311void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) { 1312 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal)); 1313 Thread* const self = Thread::Current(); 1314 { 1315 ReaderMutexLock mu(self, dex_lock_); 1316 if ((flags & kVisitRootFlagAllRoots) != 0) { 1317 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) { 1318 dex_cache.VisitRoot(visitor, RootInfo(kRootVMInternal)); 1319 } 1320 } else if ((flags & kVisitRootFlagNewRoots) != 0) { 1321 for (size_t index : new_dex_cache_roots_) { 1322 dex_caches_[index].VisitRoot(visitor, RootInfo(kRootVMInternal)); 1323 } 1324 } 1325 if ((flags & kVisitRootFlagClearRootLog) != 0) { 1326 new_dex_cache_roots_.clear(); 1327 } 1328 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) { 1329 log_new_dex_caches_roots_ = true; 1330 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) { 1331 log_new_dex_caches_roots_ = false; 1332 } 1333 } 1334 VisitClassRoots(visitor, flags); 1335 array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal)); 1336 for (GcRoot<mirror::Class>& root : find_array_class_cache_) { 1337 root.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal)); 1338 } 1339} 1340 1341void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) { 1342 if (boot_class_table_.Visit(visitor)) { 1343 for (GcRoot<mirror::ClassLoader>& root : class_loaders_) { 1344 ClassTable* const class_table = root.Read()->GetClassTable(); 1345 if (class_table != nullptr && !class_table->Visit(visitor)) { 1346 return; 1347 } 1348 } 1349 } 1350} 1351 1352void ClassLinker::VisitClasses(ClassVisitor* visitor) { 1353 if (dex_cache_image_class_lookup_required_) { 1354 MoveImageClassesToClassTable(); 1355 } 1356 Thread* const self = Thread::Current(); 1357 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 1358 // Not safe to have thread suspension when we are holding a lock. 1359 if (self != nullptr) { 1360 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__); 1361 VisitClassesInternal(visitor); 1362 } else { 1363 VisitClassesInternal(visitor); 1364 } 1365} 1366 1367class GetClassesInToVector : public ClassVisitor { 1368 public: 1369 bool Visit(mirror::Class* klass) OVERRIDE { 1370 classes_.push_back(klass); 1371 return true; 1372 } 1373 std::vector<mirror::Class*> classes_; 1374}; 1375 1376class GetClassInToObjectArray : public ClassVisitor { 1377 public: 1378 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr) 1379 : arr_(arr), index_(0) {} 1380 1381 bool Visit(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 1382 ++index_; 1383 if (index_ <= arr_->GetLength()) { 1384 arr_->Set(index_ - 1, klass); 1385 return true; 1386 } 1387 return false; 1388 } 1389 1390 bool Succeeded() const SHARED_REQUIRES(Locks::mutator_lock_) { 1391 return index_ <= arr_->GetLength(); 1392 } 1393 1394 private: 1395 mirror::ObjectArray<mirror::Class>* const arr_; 1396 int32_t index_; 1397}; 1398 1399void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) { 1400 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem 1401 // is avoiding duplicates. 1402 if (!kMovingClasses) { 1403 GetClassesInToVector accumulator; 1404 VisitClasses(&accumulator); 1405 for (mirror::Class* klass : accumulator.classes_) { 1406 if (!visitor->Visit(klass)) { 1407 return; 1408 } 1409 } 1410 } else { 1411 Thread* const self = Thread::Current(); 1412 StackHandleScope<1> hs(self); 1413 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr); 1414 // We size the array assuming classes won't be added to the class table during the visit. 1415 // If this assumption fails we iterate again. 1416 while (true) { 1417 size_t class_table_size; 1418 { 1419 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 1420 // Add 100 in case new classes get loaded when we are filling in the object array. 1421 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100; 1422 } 1423 mirror::Class* class_type = mirror::Class::GetJavaLangClass(); 1424 mirror::Class* array_of_class = FindArrayClass(self, &class_type); 1425 classes.Assign( 1426 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size)); 1427 CHECK(classes.Get() != nullptr); // OOME. 1428 GetClassInToObjectArray accumulator(classes.Get()); 1429 VisitClasses(&accumulator); 1430 if (accumulator.Succeeded()) { 1431 break; 1432 } 1433 } 1434 for (int32_t i = 0; i < classes->GetLength(); ++i) { 1435 // If the class table shrank during creation of the clases array we expect null elements. If 1436 // the class table grew then the loop repeats. If classes are created after the loop has 1437 // finished then we don't visit. 1438 mirror::Class* klass = classes->Get(i); 1439 if (klass != nullptr && !visitor->Visit(klass)) { 1440 return; 1441 } 1442 } 1443 } 1444} 1445 1446ClassLinker::~ClassLinker() { 1447 mirror::Class::ResetClass(); 1448 mirror::Constructor::ResetClass(); 1449 mirror::Field::ResetClass(); 1450 mirror::Method::ResetClass(); 1451 mirror::Reference::ResetClass(); 1452 mirror::StackTraceElement::ResetClass(); 1453 mirror::String::ResetClass(); 1454 mirror::Throwable::ResetClass(); 1455 mirror::BooleanArray::ResetArrayClass(); 1456 mirror::ByteArray::ResetArrayClass(); 1457 mirror::CharArray::ResetArrayClass(); 1458 mirror::Constructor::ResetArrayClass(); 1459 mirror::DoubleArray::ResetArrayClass(); 1460 mirror::Field::ResetArrayClass(); 1461 mirror::FloatArray::ResetArrayClass(); 1462 mirror::Method::ResetArrayClass(); 1463 mirror::IntArray::ResetArrayClass(); 1464 mirror::LongArray::ResetArrayClass(); 1465 mirror::ShortArray::ResetArrayClass(); 1466 STLDeleteElements(&oat_files_); 1467 for (GcRoot<mirror::ClassLoader>& root : class_loaders_) { 1468 ClassTable* const class_table = root.Read()->GetClassTable(); 1469 delete class_table; 1470 } 1471} 1472 1473mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) { 1474 return down_cast<mirror::PointerArray*>(image_pointer_size_ == 8u ? 1475 static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length)) : 1476 static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length))); 1477} 1478 1479mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) { 1480 StackHandleScope<6> hs(self); 1481 auto dex_cache(hs.NewHandle(down_cast<mirror::DexCache*>( 1482 GetClassRoot(kJavaLangDexCache)->AllocObject(self)))); 1483 if (dex_cache.Get() == nullptr) { 1484 self->AssertPendingOOMException(); 1485 return nullptr; 1486 } 1487 auto location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str()))); 1488 if (location.Get() == nullptr) { 1489 self->AssertPendingOOMException(); 1490 return nullptr; 1491 } 1492 auto strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds()))); 1493 if (strings.Get() == nullptr) { 1494 self->AssertPendingOOMException(); 1495 return nullptr; 1496 } 1497 auto types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds()))); 1498 if (types.Get() == nullptr) { 1499 self->AssertPendingOOMException(); 1500 return nullptr; 1501 } 1502 auto methods(hs.NewHandle(AllocPointerArray(self, dex_file.NumMethodIds()))); 1503 if (methods.Get() == nullptr) { 1504 self->AssertPendingOOMException(); 1505 return nullptr; 1506 } 1507 auto fields(hs.NewHandle(AllocPointerArray(self, dex_file.NumFieldIds()))); 1508 if (fields.Get() == nullptr) { 1509 self->AssertPendingOOMException(); 1510 return nullptr; 1511 } 1512 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(), 1513 fields.Get(), image_pointer_size_); 1514 return dex_cache.Get(); 1515} 1516 1517mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class, 1518 uint32_t class_size) { 1519 DCHECK_GE(class_size, sizeof(mirror::Class)); 1520 gc::Heap* heap = Runtime::Current()->GetHeap(); 1521 mirror::Class::InitializeClassVisitor visitor(class_size); 1522 mirror::Object* k = kMovingClasses ? 1523 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) : 1524 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor); 1525 if (UNLIKELY(k == nullptr)) { 1526 self->AssertPendingOOMException(); 1527 return nullptr; 1528 } 1529 return k->AsClass(); 1530} 1531 1532mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) { 1533 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size); 1534} 1535 1536mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray( 1537 Thread* self, size_t length) { 1538 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc( 1539 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length); 1540} 1541 1542mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor, 1543 mirror::Class* klass) { 1544 DCHECK(klass != nullptr); 1545 1546 // For temporary classes we must wait for them to be retired. 1547 if (init_done_ && klass->IsTemp()) { 1548 CHECK(!klass->IsResolved()); 1549 if (klass->IsErroneous()) { 1550 ThrowEarlierClassFailure(klass); 1551 return nullptr; 1552 } 1553 StackHandleScope<1> hs(self); 1554 Handle<mirror::Class> h_class(hs.NewHandle(klass)); 1555 ObjectLock<mirror::Class> lock(self, h_class); 1556 // Loop and wait for the resolving thread to retire this class. 1557 while (!h_class->IsRetired() && !h_class->IsErroneous()) { 1558 lock.WaitIgnoringInterrupts(); 1559 } 1560 if (h_class->IsErroneous()) { 1561 ThrowEarlierClassFailure(h_class.Get()); 1562 return nullptr; 1563 } 1564 CHECK(h_class->IsRetired()); 1565 // Get the updated class from class table. 1566 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), 1567 h_class.Get()->GetClassLoader()); 1568 } 1569 1570 // Wait for the class if it has not already been linked. 1571 if (!klass->IsResolved() && !klass->IsErroneous()) { 1572 StackHandleScope<1> hs(self); 1573 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass)); 1574 ObjectLock<mirror::Class> lock(self, h_class); 1575 // Check for circular dependencies between classes. 1576 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) { 1577 ThrowClassCircularityError(h_class.Get()); 1578 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self); 1579 return nullptr; 1580 } 1581 // Wait for the pending initialization to complete. 1582 while (!h_class->IsResolved() && !h_class->IsErroneous()) { 1583 lock.WaitIgnoringInterrupts(); 1584 } 1585 } 1586 1587 if (klass->IsErroneous()) { 1588 ThrowEarlierClassFailure(klass); 1589 return nullptr; 1590 } 1591 // Return the loaded class. No exceptions should be pending. 1592 CHECK(klass->IsResolved()) << PrettyClass(klass); 1593 self->AssertNoPendingException(); 1594 return klass; 1595} 1596 1597typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry; 1598 1599// Search a collection of DexFiles for a descriptor 1600ClassPathEntry FindInClassPath(const char* descriptor, 1601 size_t hash, const std::vector<const DexFile*>& class_path) { 1602 for (const DexFile* dex_file : class_path) { 1603 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash); 1604 if (dex_class_def != nullptr) { 1605 return ClassPathEntry(dex_file, dex_class_def); 1606 } 1607 } 1608 return ClassPathEntry(nullptr, nullptr); 1609} 1610 1611static bool IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa, 1612 mirror::ClassLoader* class_loader) 1613 SHARED_REQUIRES(Locks::mutator_lock_) { 1614 return class_loader == nullptr || 1615 class_loader->GetClass() == 1616 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader); 1617} 1618 1619bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa, 1620 Thread* self, const char* descriptor, 1621 size_t hash, 1622 Handle<mirror::ClassLoader> class_loader, 1623 mirror::Class** result) { 1624 // Termination case: boot class-loader. 1625 if (IsBootClassLoader(soa, class_loader.Get())) { 1626 // The boot class loader, search the boot class path. 1627 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_); 1628 if (pair.second != nullptr) { 1629 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr); 1630 if (klass != nullptr) { 1631 *result = EnsureResolved(self, descriptor, klass); 1632 } else { 1633 *result = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), 1634 *pair.first, *pair.second); 1635 } 1636 if (*result == nullptr) { 1637 CHECK(self->IsExceptionPending()) << descriptor; 1638 self->ClearException(); 1639 } 1640 } else { 1641 *result = nullptr; 1642 } 1643 return true; 1644 } 1645 1646 // Unsupported class-loader? 1647 if (class_loader->GetClass() != 1648 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) { 1649 *result = nullptr; 1650 return false; 1651 } 1652 1653 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension). 1654 StackHandleScope<4> hs(self); 1655 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent())); 1656 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result); 1657 1658 if (!recursive_result) { 1659 // Something wrong up the chain. 1660 return false; 1661 } 1662 1663 if (*result != nullptr) { 1664 // Found the class up the chain. 1665 return true; 1666 } 1667 1668 // Handle this step. 1669 // Handle as if this is the child PathClassLoader. 1670 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader. 1671 // We need to get the DexPathList and loop through it. 1672 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie); 1673 ArtField* const dex_file_field = 1674 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile); 1675 mirror::Object* dex_path_list = 1676 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)-> 1677 GetObject(class_loader.Get()); 1678 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) { 1679 // DexPathList has an array dexElements of Elements[] which each contain a dex file. 1680 mirror::Object* dex_elements_obj = 1681 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)-> 1682 GetObject(dex_path_list); 1683 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look 1684 // at the mCookie which is a DexFile vector. 1685 if (dex_elements_obj != nullptr) { 1686 Handle<mirror::ObjectArray<mirror::Object>> dex_elements = 1687 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()); 1688 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) { 1689 mirror::Object* element = dex_elements->GetWithoutChecks(i); 1690 if (element == nullptr) { 1691 // Should never happen, fall back to java code to throw a NPE. 1692 break; 1693 } 1694 mirror::Object* dex_file = dex_file_field->GetObject(element); 1695 if (dex_file != nullptr) { 1696 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray(); 1697 if (long_array == nullptr) { 1698 // This should never happen so log a warning. 1699 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor; 1700 break; 1701 } 1702 int32_t long_array_size = long_array->GetLength(); 1703 for (int32_t j = 0; j < long_array_size; ++j) { 1704 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>( 1705 long_array->GetWithoutChecks(j))); 1706 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash); 1707 if (dex_class_def != nullptr) { 1708 RegisterDexFile(*cp_dex_file); 1709 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader, 1710 *cp_dex_file, *dex_class_def); 1711 if (klass == nullptr) { 1712 CHECK(self->IsExceptionPending()) << descriptor; 1713 self->ClearException(); 1714 // TODO: Is it really right to break here, and not check the other dex files? 1715 return true; 1716 } 1717 *result = klass; 1718 return true; 1719 } 1720 } 1721 } 1722 } 1723 } 1724 self->AssertNoPendingException(); 1725 } 1726 1727 // Result is still null from the parent call, no need to set it again... 1728 return true; 1729} 1730 1731mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor, 1732 Handle<mirror::ClassLoader> class_loader) { 1733 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string"; 1734 DCHECK(self != nullptr); 1735 self->AssertNoPendingException(); 1736 if (descriptor[1] == '\0') { 1737 // only the descriptors of primitive types should be 1 character long, also avoid class lookup 1738 // for primitive classes that aren't backed by dex files. 1739 return FindPrimitiveClass(descriptor[0]); 1740 } 1741 const size_t hash = ComputeModifiedUtf8Hash(descriptor); 1742 // Find the class in the loaded classes table. 1743 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get()); 1744 if (klass != nullptr) { 1745 return EnsureResolved(self, descriptor, klass); 1746 } 1747 // Class is not yet loaded. 1748 if (descriptor[0] == '[') { 1749 return CreateArrayClass(self, descriptor, hash, class_loader); 1750 } else if (class_loader.Get() == nullptr) { 1751 // The boot class loader, search the boot class path. 1752 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_); 1753 if (pair.second != nullptr) { 1754 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first, 1755 *pair.second); 1756 } else { 1757 // The boot class loader is searched ahead of the application class loader, failures are 1758 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to 1759 // trigger the chaining with a proper stack trace. 1760 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError(); 1761 self->SetException(pre_allocated); 1762 return nullptr; 1763 } 1764 } else { 1765 ScopedObjectAccessUnchecked soa(self); 1766 mirror::Class* cp_klass; 1767 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) { 1768 // The chain was understood. So the value in cp_klass is either the class we were looking 1769 // for, or not found. 1770 if (cp_klass != nullptr) { 1771 return cp_klass; 1772 } 1773 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this 1774 // and the branch above. TODO: throw the right exception here. 1775 1776 // We'll let the Java-side rediscover all this and throw the exception with the right stack 1777 // trace. 1778 } 1779 1780 if (Runtime::Current()->IsAotCompiler()) { 1781 // Oops, compile-time, can't run actual class-loader code. 1782 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError(); 1783 self->SetException(pre_allocated); 1784 return nullptr; 1785 } 1786 1787 ScopedLocalRef<jobject> class_loader_object(soa.Env(), 1788 soa.AddLocalReference<jobject>(class_loader.Get())); 1789 std::string class_name_string(DescriptorToDot(descriptor)); 1790 ScopedLocalRef<jobject> result(soa.Env(), nullptr); 1791 { 1792 ScopedThreadStateChange tsc(self, kNative); 1793 ScopedLocalRef<jobject> class_name_object(soa.Env(), 1794 soa.Env()->NewStringUTF(class_name_string.c_str())); 1795 if (class_name_object.get() == nullptr) { 1796 DCHECK(self->IsExceptionPending()); // OOME. 1797 return nullptr; 1798 } 1799 CHECK(class_loader_object.get() != nullptr); 1800 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(), 1801 WellKnownClasses::java_lang_ClassLoader_loadClass, 1802 class_name_object.get())); 1803 } 1804 if (self->IsExceptionPending()) { 1805 // If the ClassLoader threw, pass that exception up. 1806 return nullptr; 1807 } else if (result.get() == nullptr) { 1808 // broken loader - throw NPE to be compatible with Dalvik 1809 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s", 1810 class_name_string.c_str()).c_str()); 1811 return nullptr; 1812 } else { 1813 // success, return mirror::Class* 1814 return soa.Decode<mirror::Class*>(result.get()); 1815 } 1816 } 1817 UNREACHABLE(); 1818} 1819 1820mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash, 1821 Handle<mirror::ClassLoader> class_loader, 1822 const DexFile& dex_file, 1823 const DexFile::ClassDef& dex_class_def) { 1824 StackHandleScope<3> hs(self); 1825 auto klass = hs.NewHandle<mirror::Class>(nullptr); 1826 1827 // Load the class from the dex file. 1828 if (UNLIKELY(!init_done_)) { 1829 // finish up init of hand crafted class_roots_ 1830 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) { 1831 klass.Assign(GetClassRoot(kJavaLangObject)); 1832 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) { 1833 klass.Assign(GetClassRoot(kJavaLangClass)); 1834 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) { 1835 klass.Assign(GetClassRoot(kJavaLangString)); 1836 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) { 1837 klass.Assign(GetClassRoot(kJavaLangRefReference)); 1838 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) { 1839 klass.Assign(GetClassRoot(kJavaLangDexCache)); 1840 } 1841 } 1842 1843 if (klass.Get() == nullptr) { 1844 // Allocate a class with the status of not ready. 1845 // Interface object should get the right size here. Regular class will 1846 // figure out the right size later and be replaced with one of the right 1847 // size when the class becomes resolved. 1848 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def))); 1849 } 1850 if (UNLIKELY(klass.Get() == nullptr)) { 1851 CHECK(self->IsExceptionPending()); // Expect an OOME. 1852 return nullptr; 1853 } 1854 klass->SetDexCache(FindDexCache(dex_file)); 1855 1856 SetupClass(dex_file, dex_class_def, klass, class_loader.Get()); 1857 1858 // Mark the string class by setting its access flag. 1859 if (UNLIKELY(!init_done_)) { 1860 if (strcmp(descriptor, "Ljava/lang/String;") == 0) { 1861 klass->SetStringClass(); 1862 } 1863 } 1864 1865 ObjectLock<mirror::Class> lock(self, klass); 1866 klass->SetClinitThreadId(self->GetTid()); 1867 1868 // Add the newly loaded class to the loaded classes table. 1869 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash); 1870 if (existing != nullptr) { 1871 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause 1872 // this thread to block. 1873 return EnsureResolved(self, descriptor, existing); 1874 } 1875 1876 // Load the fields and other things after we are inserted in the table. This is so that we don't 1877 // end up allocating unfree-able linear alloc resources and then lose the race condition. The 1878 // other reason is that the field roots are only visited from the class table. So we need to be 1879 // inserted before we allocate / fill in these fields. 1880 LoadClass(self, dex_file, dex_class_def, klass); 1881 if (self->IsExceptionPending()) { 1882 // An exception occured during load, set status to erroneous while holding klass' lock in case 1883 // notification is necessary. 1884 if (!klass->IsErroneous()) { 1885 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 1886 } 1887 return nullptr; 1888 } 1889 1890 // Finish loading (if necessary) by finding parents 1891 CHECK(!klass->IsLoaded()); 1892 if (!LoadSuperAndInterfaces(klass, dex_file)) { 1893 // Loading failed. 1894 if (!klass->IsErroneous()) { 1895 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 1896 } 1897 return nullptr; 1898 } 1899 CHECK(klass->IsLoaded()); 1900 // Link the class (if necessary) 1901 CHECK(!klass->IsResolved()); 1902 // TODO: Use fast jobjects? 1903 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr); 1904 1905 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr); 1906 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) { 1907 // Linking failed. 1908 if (!klass->IsErroneous()) { 1909 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 1910 } 1911 return nullptr; 1912 } 1913 self->AssertNoPendingException(); 1914 CHECK(h_new_class.Get() != nullptr) << descriptor; 1915 CHECK(h_new_class->IsResolved()) << descriptor; 1916 1917 // Instrumentation may have updated entrypoints for all methods of all 1918 // classes. However it could not update methods of this class while we 1919 // were loading it. Now the class is resolved, we can update entrypoints 1920 // as required by instrumentation. 1921 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) { 1922 // We must be in the kRunnable state to prevent instrumentation from 1923 // suspending all threads to update entrypoints while we are doing it 1924 // for this class. 1925 DCHECK_EQ(self->GetState(), kRunnable); 1926 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get()); 1927 } 1928 1929 /* 1930 * We send CLASS_PREPARE events to the debugger from here. The 1931 * definition of "preparation" is creating the static fields for a 1932 * class and initializing them to the standard default values, but not 1933 * executing any code (that comes later, during "initialization"). 1934 * 1935 * We did the static preparation in LinkClass. 1936 * 1937 * The class has been prepared and resolved but possibly not yet verified 1938 * at this point. 1939 */ 1940 Dbg::PostClassPrepare(h_new_class.Get()); 1941 1942 return h_new_class.Get(); 1943} 1944 1945uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file, 1946 const DexFile::ClassDef& dex_class_def) { 1947 const uint8_t* class_data = dex_file.GetClassData(dex_class_def); 1948 size_t num_ref = 0; 1949 size_t num_8 = 0; 1950 size_t num_16 = 0; 1951 size_t num_32 = 0; 1952 size_t num_64 = 0; 1953 if (class_data != nullptr) { 1954 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) { 1955 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex()); 1956 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id); 1957 char c = descriptor[0]; 1958 switch (c) { 1959 case 'L': 1960 case '[': 1961 num_ref++; 1962 break; 1963 case 'J': 1964 case 'D': 1965 num_64++; 1966 break; 1967 case 'I': 1968 case 'F': 1969 num_32++; 1970 break; 1971 case 'S': 1972 case 'C': 1973 num_16++; 1974 break; 1975 case 'B': 1976 case 'Z': 1977 num_8++; 1978 break; 1979 default: 1980 LOG(FATAL) << "Unknown descriptor: " << c; 1981 UNREACHABLE(); 1982 } 1983 } 1984 } 1985 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref, 1986 image_pointer_size_); 1987} 1988 1989OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx, 1990 bool* found) { 1991 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16); 1992 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile(); 1993 if (oat_dex_file == nullptr) { 1994 *found = false; 1995 return OatFile::OatClass::Invalid(); 1996 } 1997 *found = true; 1998 return oat_dex_file->GetOatClass(class_def_idx); 1999} 2000 2001static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx, 2002 uint32_t method_idx) { 2003 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx); 2004 const uint8_t* class_data = dex_file.GetClassData(class_def); 2005 CHECK(class_data != nullptr); 2006 ClassDataItemIterator it(dex_file, class_data); 2007 // Skip fields 2008 while (it.HasNextStaticField()) { 2009 it.Next(); 2010 } 2011 while (it.HasNextInstanceField()) { 2012 it.Next(); 2013 } 2014 // Process methods 2015 size_t class_def_method_index = 0; 2016 while (it.HasNextDirectMethod()) { 2017 if (it.GetMemberIndex() == method_idx) { 2018 return class_def_method_index; 2019 } 2020 class_def_method_index++; 2021 it.Next(); 2022 } 2023 while (it.HasNextVirtualMethod()) { 2024 if (it.GetMemberIndex() == method_idx) { 2025 return class_def_method_index; 2026 } 2027 class_def_method_index++; 2028 it.Next(); 2029 } 2030 DCHECK(!it.HasNext()); 2031 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation(); 2032 UNREACHABLE(); 2033} 2034 2035const OatFile::OatMethod ClassLinker::FindOatMethodFor(ArtMethod* method, bool* found) { 2036 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution 2037 // method for direct methods (or virtual methods made direct). 2038 mirror::Class* declaring_class = method->GetDeclaringClass(); 2039 size_t oat_method_index; 2040 if (method->IsStatic() || method->IsDirect()) { 2041 // Simple case where the oat method index was stashed at load time. 2042 oat_method_index = method->GetMethodIndex(); 2043 } else { 2044 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index 2045 // by search for its position in the declared virtual methods. 2046 oat_method_index = declaring_class->NumDirectMethods(); 2047 size_t end = declaring_class->NumVirtualMethods(); 2048 bool found_virtual = false; 2049 for (size_t i = 0; i < end; i++) { 2050 // Check method index instead of identity in case of duplicate method definitions. 2051 if (method->GetDexMethodIndex() == 2052 declaring_class->GetVirtualMethod(i, image_pointer_size_)->GetDexMethodIndex()) { 2053 found_virtual = true; 2054 break; 2055 } 2056 oat_method_index++; 2057 } 2058 CHECK(found_virtual) << "Didn't find oat method index for virtual method: " 2059 << PrettyMethod(method); 2060 } 2061 DCHECK_EQ(oat_method_index, 2062 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(), 2063 method->GetDeclaringClass()->GetDexClassDefIndex(), 2064 method->GetDexMethodIndex())); 2065 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(), 2066 declaring_class->GetDexClassDefIndex(), 2067 found); 2068 if (!(*found)) { 2069 return OatFile::OatMethod::Invalid(); 2070 } 2071 return oat_class.GetOatMethod(oat_method_index); 2072} 2073 2074// Special case to get oat code without overwriting a trampoline. 2075const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) { 2076 CHECK(!method->IsAbstract()) << PrettyMethod(method); 2077 if (method->IsProxyMethod()) { 2078 return GetQuickProxyInvokeHandler(); 2079 } 2080 bool found; 2081 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found); 2082 if (found) { 2083 auto* code = oat_method.GetQuickCode(); 2084 if (code != nullptr) { 2085 return code; 2086 } 2087 } 2088 jit::Jit* const jit = Runtime::Current()->GetJit(); 2089 if (jit != nullptr) { 2090 auto* code = jit->GetCodeCache()->GetCodeFor(method); 2091 if (code != nullptr) { 2092 return code; 2093 } 2094 } 2095 if (method->IsNative()) { 2096 // No code and native? Use generic trampoline. 2097 return GetQuickGenericJniStub(); 2098 } 2099 return GetQuickToInterpreterBridge(); 2100} 2101 2102const void* ClassLinker::GetOatMethodQuickCodeFor(ArtMethod* method) { 2103 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) { 2104 return nullptr; 2105 } 2106 bool found; 2107 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found); 2108 if (found) { 2109 return oat_method.GetQuickCode(); 2110 } 2111 jit::Jit* jit = Runtime::Current()->GetJit(); 2112 if (jit != nullptr) { 2113 auto* code = jit->GetCodeCache()->GetCodeFor(method); 2114 if (code != nullptr) { 2115 return code; 2116 } 2117 } 2118 return nullptr; 2119} 2120 2121const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx, 2122 uint32_t method_idx) { 2123 bool found; 2124 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found); 2125 if (!found) { 2126 return nullptr; 2127 } 2128 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx); 2129 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode(); 2130} 2131 2132// Returns true if the method must run with interpreter, false otherwise. 2133static bool NeedsInterpreter(ArtMethod* method, const void* quick_code) 2134 SHARED_REQUIRES(Locks::mutator_lock_) { 2135 if (quick_code == nullptr) { 2136 // No code: need interpreter. 2137 // May return true for native code, in the case of generic JNI 2138 // DCHECK(!method->IsNative()); 2139 return true; 2140 } 2141 // If interpreter mode is enabled, every method (except native and proxy) must 2142 // be run with interpreter. 2143 return Runtime::Current()->GetInstrumentation()->InterpretOnly() && 2144 !method->IsNative() && !method->IsProxyMethod(); 2145} 2146 2147void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) { 2148 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass); 2149 if (klass->NumDirectMethods() == 0) { 2150 return; // No direct methods => no static methods. 2151 } 2152 Runtime* runtime = Runtime::Current(); 2153 if (!runtime->IsStarted()) { 2154 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) { 2155 return; // OAT file unavailable. 2156 } 2157 } 2158 2159 const DexFile& dex_file = klass->GetDexFile(); 2160 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 2161 CHECK(dex_class_def != nullptr); 2162 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def); 2163 // There should always be class data if there were direct methods. 2164 CHECK(class_data != nullptr) << PrettyDescriptor(klass); 2165 ClassDataItemIterator it(dex_file, class_data); 2166 // Skip fields 2167 while (it.HasNextStaticField()) { 2168 it.Next(); 2169 } 2170 while (it.HasNextInstanceField()) { 2171 it.Next(); 2172 } 2173 bool has_oat_class; 2174 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), 2175 &has_oat_class); 2176 // Link the code of methods skipped by LinkCode. 2177 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) { 2178 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_); 2179 if (!method->IsStatic()) { 2180 // Only update static methods. 2181 continue; 2182 } 2183 const void* quick_code = nullptr; 2184 if (has_oat_class) { 2185 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index); 2186 quick_code = oat_method.GetQuickCode(); 2187 } 2188 const bool enter_interpreter = NeedsInterpreter(method, quick_code); 2189 if (enter_interpreter) { 2190 // Use interpreter entry point. 2191 // Check whether the method is native, in which case it's generic JNI. 2192 if (quick_code == nullptr && method->IsNative()) { 2193 quick_code = GetQuickGenericJniStub(); 2194 } else { 2195 quick_code = GetQuickToInterpreterBridge(); 2196 } 2197 } 2198 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code); 2199 } 2200 // Ignore virtual methods on the iterator. 2201} 2202 2203void ClassLinker::LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class, 2204 uint32_t class_def_method_index) { 2205 Runtime* const runtime = Runtime::Current(); 2206 if (runtime->IsAotCompiler()) { 2207 // The following code only applies to a non-compiler runtime. 2208 return; 2209 } 2210 // Method shouldn't have already been linked. 2211 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr); 2212 if (oat_class != nullptr) { 2213 // Every kind of method should at least get an invoke stub from the oat_method. 2214 // non-abstract methods also get their code pointers. 2215 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index); 2216 oat_method.LinkMethod(method); 2217 } 2218 2219 // Install entry point from interpreter. 2220 bool enter_interpreter = NeedsInterpreter(method, method->GetEntryPointFromQuickCompiledCode()); 2221 2222 if (method->IsAbstract()) { 2223 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 2224 return; 2225 } 2226 2227 if (method->IsStatic() && !method->IsConstructor()) { 2228 // For static methods excluding the class initializer, install the trampoline. 2229 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines 2230 // after initializing class (see ClassLinker::InitializeClass method). 2231 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub()); 2232 } else if (enter_interpreter) { 2233 if (!method->IsNative()) { 2234 // Set entry point from compiled code if there's no code or in interpreter only mode. 2235 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 2236 } else { 2237 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub()); 2238 } 2239 } 2240 2241 if (method->IsNative()) { 2242 // Unregistering restores the dlsym lookup stub. 2243 method->UnregisterNative(); 2244 2245 if (enter_interpreter) { 2246 // We have a native method here without code. Then it should have either the generic JNI 2247 // trampoline as entrypoint (non-static), or the resolution trampoline (static). 2248 // TODO: this doesn't handle all the cases where trampolines may be installed. 2249 const void* entry_point = method->GetEntryPointFromQuickCompiledCode(); 2250 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point)); 2251 } 2252 } 2253} 2254 2255void ClassLinker::SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def, 2256 Handle<mirror::Class> klass, mirror::ClassLoader* class_loader) { 2257 CHECK(klass.Get() != nullptr); 2258 CHECK(klass->GetDexCache() != nullptr); 2259 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus()); 2260 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def); 2261 CHECK(descriptor != nullptr); 2262 2263 klass->SetClass(GetClassRoot(kJavaLangClass)); 2264 uint32_t access_flags = dex_class_def.GetJavaAccessFlags(); 2265 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U); 2266 klass->SetAccessFlags(access_flags); 2267 klass->SetClassLoader(class_loader); 2268 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 2269 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr); 2270 2271 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def)); 2272 klass->SetDexTypeIndex(dex_class_def.class_idx_); 2273 CHECK(klass->GetDexCacheStrings() != nullptr); 2274} 2275 2276void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file, 2277 const DexFile::ClassDef& dex_class_def, 2278 Handle<mirror::Class> klass) { 2279 const uint8_t* class_data = dex_file.GetClassData(dex_class_def); 2280 if (class_data == nullptr) { 2281 return; // no fields or methods - for example a marker interface 2282 } 2283 bool has_oat_class = false; 2284 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) { 2285 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), 2286 &has_oat_class); 2287 if (has_oat_class) { 2288 LoadClassMembers(self, dex_file, class_data, klass, &oat_class); 2289 } 2290 } 2291 if (!has_oat_class) { 2292 LoadClassMembers(self, dex_file, class_data, klass, nullptr); 2293 } 2294} 2295 2296LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self, size_t length) { 2297 if (length == 0) { 2298 return nullptr; 2299 } 2300 auto* ret = new(Runtime::Current()->GetLinearAlloc()->Alloc( 2301 self, LengthPrefixedArray<ArtField>::ComputeSize(length))) LengthPrefixedArray<ArtField>( 2302 length); 2303 CHECK(ret != nullptr); 2304 std::uninitialized_fill_n(&ret->At(0), length, ArtField()); 2305 return ret; 2306} 2307 2308LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self, size_t length) { 2309 if (length == 0) { 2310 return nullptr; 2311 } 2312 const size_t method_size = ArtMethod::ObjectSize(image_pointer_size_); 2313 auto* ret = new (Runtime::Current()->GetLinearAlloc()->Alloc( 2314 self, LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size))) 2315 LengthPrefixedArray<ArtMethod>(length); 2316 CHECK(ret != nullptr); 2317 for (size_t i = 0; i < length; ++i) { 2318 new(reinterpret_cast<void*>(&ret->At(i, method_size))) ArtMethod; 2319 } 2320 return ret; 2321} 2322 2323void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file, 2324 const uint8_t* class_data, 2325 Handle<mirror::Class> klass, 2326 const OatFile::OatClass* oat_class) { 2327 { 2328 // Note: We cannot have thread suspension until the field and method arrays are setup or else 2329 // Class::VisitFieldRoots may miss some fields or methods. 2330 ScopedAssertNoThreadSuspension nts(self, __FUNCTION__); 2331 // Load static fields. 2332 // We allow duplicate definitions of the same field in a class_data_item 2333 // but ignore the repeated indexes here, b/21868015. 2334 ClassDataItemIterator it(dex_file, class_data); 2335 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, it.NumStaticFields()); 2336 size_t num_sfields = 0; 2337 uint32_t last_field_idx = 0u; 2338 for (; it.HasNextStaticField(); it.Next()) { 2339 uint32_t field_idx = it.GetMemberIndex(); 2340 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier. 2341 if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) { 2342 DCHECK_LT(num_sfields, it.NumStaticFields()); 2343 LoadField(it, klass, &sfields->At(num_sfields)); 2344 ++num_sfields; 2345 last_field_idx = field_idx; 2346 } 2347 } 2348 klass->SetSFieldsPtr(sfields); 2349 DCHECK_EQ(klass->NumStaticFields(), num_sfields); 2350 // Load instance fields. 2351 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self, it.NumInstanceFields()); 2352 size_t num_ifields = 0u; 2353 last_field_idx = 0u; 2354 for (; it.HasNextInstanceField(); it.Next()) { 2355 uint32_t field_idx = it.GetMemberIndex(); 2356 DCHECK_GE(field_idx, last_field_idx); // Ordering enforced by DexFileVerifier. 2357 if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) { 2358 DCHECK_LT(num_ifields, it.NumInstanceFields()); 2359 LoadField(it, klass, &ifields->At(num_ifields)); 2360 ++num_ifields; 2361 last_field_idx = field_idx; 2362 } 2363 } 2364 if (UNLIKELY(num_sfields != it.NumStaticFields()) || 2365 UNLIKELY(num_ifields != it.NumInstanceFields())) { 2366 LOG(WARNING) << "Duplicate fields in class " << PrettyDescriptor(klass.Get()) 2367 << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields() 2368 << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")"; 2369 // NOTE: Not shrinking the over-allocated sfields/ifields. 2370 } 2371 klass->SetIFieldsPtr(ifields); 2372 DCHECK_EQ(klass->NumInstanceFields(), num_ifields); 2373 // Load methods. 2374 klass->SetDirectMethodsPtr(AllocArtMethodArray(self, it.NumDirectMethods())); 2375 klass->SetVirtualMethodsPtr(AllocArtMethodArray(self, it.NumVirtualMethods())); 2376 size_t class_def_method_index = 0; 2377 uint32_t last_dex_method_index = DexFile::kDexNoIndex; 2378 size_t last_class_def_method_index = 0; 2379 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) { 2380 ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_); 2381 LoadMethod(self, dex_file, it, klass, method); 2382 LinkCode(method, oat_class, class_def_method_index); 2383 uint32_t it_method_index = it.GetMemberIndex(); 2384 if (last_dex_method_index == it_method_index) { 2385 // duplicate case 2386 method->SetMethodIndex(last_class_def_method_index); 2387 } else { 2388 method->SetMethodIndex(class_def_method_index); 2389 last_dex_method_index = it_method_index; 2390 last_class_def_method_index = class_def_method_index; 2391 } 2392 class_def_method_index++; 2393 } 2394 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) { 2395 ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_); 2396 LoadMethod(self, dex_file, it, klass, method); 2397 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i); 2398 LinkCode(method, oat_class, class_def_method_index); 2399 class_def_method_index++; 2400 } 2401 DCHECK(!it.HasNext()); 2402 } 2403 // Ensure that the card is marked so that remembered sets pick up native roots. 2404 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get()); 2405 self->AllowThreadSuspension(); 2406} 2407 2408void ClassLinker::LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass, 2409 ArtField* dst) { 2410 const uint32_t field_idx = it.GetMemberIndex(); 2411 dst->SetDexFieldIndex(field_idx); 2412 dst->SetDeclaringClass(klass.Get()); 2413 dst->SetAccessFlags(it.GetFieldAccessFlags()); 2414} 2415 2416void ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file, const ClassDataItemIterator& it, 2417 Handle<mirror::Class> klass, ArtMethod* dst) { 2418 uint32_t dex_method_idx = it.GetMemberIndex(); 2419 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx); 2420 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_); 2421 2422 ScopedAssertNoThreadSuspension ants(self, "LoadMethod"); 2423 dst->SetDexMethodIndex(dex_method_idx); 2424 dst->SetDeclaringClass(klass.Get()); 2425 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset()); 2426 2427 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods()); 2428 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes()); 2429 2430 uint32_t access_flags = it.GetMethodAccessFlags(); 2431 2432 if (UNLIKELY(strcmp("finalize", method_name) == 0)) { 2433 // Set finalizable flag on declaring class. 2434 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) { 2435 // Void return type. 2436 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged. 2437 klass->SetFinalizable(); 2438 } else { 2439 std::string temp; 2440 const char* klass_descriptor = klass->GetDescriptor(&temp); 2441 // The Enum class declares a "final" finalize() method to prevent subclasses from 2442 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its 2443 // subclasses, so we exclude it here. 2444 // We also want to avoid setting the flag on Object, where we know that finalize() is 2445 // empty. 2446 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 && 2447 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) { 2448 klass->SetFinalizable(); 2449 } 2450 } 2451 } 2452 } else if (method_name[0] == '<') { 2453 // Fix broken access flags for initializers. Bug 11157540. 2454 bool is_init = (strcmp("<init>", method_name) == 0); 2455 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0); 2456 if (UNLIKELY(!is_init && !is_clinit)) { 2457 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name; 2458 } else { 2459 if (UNLIKELY((access_flags & kAccConstructor) == 0)) { 2460 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class " 2461 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation(); 2462 access_flags |= kAccConstructor; 2463 } 2464 } 2465 } 2466 dst->SetAccessFlags(access_flags); 2467} 2468 2469void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) { 2470 StackHandleScope<1> hs(self); 2471 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file))); 2472 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for " 2473 << dex_file.GetLocation(); 2474 AppendToBootClassPath(dex_file, dex_cache); 2475} 2476 2477void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, 2478 Handle<mirror::DexCache> dex_cache) { 2479 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation(); 2480 boot_class_path_.push_back(&dex_file); 2481 RegisterDexFile(dex_file, dex_cache); 2482} 2483 2484bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) { 2485 dex_lock_.AssertSharedHeld(Thread::Current()); 2486 for (GcRoot<mirror::DexCache>& root : dex_caches_) { 2487 mirror::DexCache* dex_cache = root.Read(); 2488 if (dex_cache->GetDexFile() == &dex_file) { 2489 return true; 2490 } 2491 } 2492 return false; 2493} 2494 2495bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) { 2496 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2497 return IsDexFileRegisteredLocked(dex_file); 2498} 2499 2500void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, 2501 Handle<mirror::DexCache> dex_cache) { 2502 dex_lock_.AssertExclusiveHeld(Thread::Current()); 2503 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation(); 2504 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation())) 2505 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation(); 2506 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get())); 2507 dex_cache->SetDexFile(&dex_file); 2508 if (log_new_dex_caches_roots_) { 2509 // TODO: This is not safe if we can remove dex caches. 2510 new_dex_cache_roots_.push_back(dex_caches_.size() - 1); 2511 } 2512} 2513 2514void ClassLinker::RegisterDexFile(const DexFile& dex_file) { 2515 Thread* self = Thread::Current(); 2516 { 2517 ReaderMutexLock mu(self, dex_lock_); 2518 if (IsDexFileRegisteredLocked(dex_file)) { 2519 return; 2520 } 2521 } 2522 // Don't alloc while holding the lock, since allocation may need to 2523 // suspend all threads and another thread may need the dex_lock_ to 2524 // get to a suspend point. 2525 StackHandleScope<1> hs(self); 2526 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file))); 2527 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for " 2528 << dex_file.GetLocation(); 2529 { 2530 WriterMutexLock mu(self, dex_lock_); 2531 if (IsDexFileRegisteredLocked(dex_file)) { 2532 return; 2533 } 2534 RegisterDexFileLocked(dex_file, dex_cache); 2535 } 2536} 2537 2538void ClassLinker::RegisterDexFile(const DexFile& dex_file, 2539 Handle<mirror::DexCache> dex_cache) { 2540 WriterMutexLock mu(Thread::Current(), dex_lock_); 2541 RegisterDexFileLocked(dex_file, dex_cache); 2542} 2543 2544mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) { 2545 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2546 // Search assuming unique-ness of dex file. 2547 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2548 mirror::DexCache* dex_cache = GetDexCache(i); 2549 if (dex_cache->GetDexFile() == &dex_file) { 2550 return dex_cache; 2551 } 2552 } 2553 // Search matching by location name. 2554 std::string location(dex_file.GetLocation()); 2555 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2556 mirror::DexCache* dex_cache = GetDexCache(i); 2557 if (dex_cache->GetDexFile()->GetLocation() == location) { 2558 return dex_cache; 2559 } 2560 } 2561 // Failure, dump diagnostic and abort. 2562 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2563 mirror::DexCache* dex_cache = GetDexCache(i); 2564 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation(); 2565 } 2566 LOG(FATAL) << "Failed to find DexCache for DexFile " << location; 2567 UNREACHABLE(); 2568} 2569 2570void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) { 2571 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2572 for (auto& dex_cache : dex_caches_) { 2573 dex_cache.Read()->Fixup(resolution_method, image_pointer_size_); 2574 } 2575} 2576 2577mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) { 2578 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_)); 2579 if (UNLIKELY(klass == nullptr)) { 2580 self->AssertPendingOOMException(); 2581 return nullptr; 2582 } 2583 return InitializePrimitiveClass(klass, type); 2584} 2585 2586mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class, 2587 Primitive::Type type) { 2588 CHECK(primitive_class != nullptr); 2589 // Must hold lock on object when initializing. 2590 Thread* self = Thread::Current(); 2591 StackHandleScope<1> hs(self); 2592 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class)); 2593 ObjectLock<mirror::Class> lock(self, h_class); 2594 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract); 2595 h_class->SetPrimitiveType(type); 2596 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self); 2597 const char* descriptor = Primitive::Descriptor(type); 2598 mirror::Class* existing = InsertClass(descriptor, h_class.Get(), 2599 ComputeModifiedUtf8Hash(descriptor)); 2600 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed"; 2601 return h_class.Get(); 2602} 2603 2604// Create an array class (i.e. the class object for the array, not the 2605// array itself). "descriptor" looks like "[C" or "[[[[B" or 2606// "[Ljava/lang/String;". 2607// 2608// If "descriptor" refers to an array of primitives, look up the 2609// primitive type's internally-generated class object. 2610// 2611// "class_loader" is the class loader of the class that's referring to 2612// us. It's used to ensure that we're looking for the element type in 2613// the right context. It does NOT become the class loader for the 2614// array class; that always comes from the base element class. 2615// 2616// Returns null with an exception raised on failure. 2617mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash, 2618 Handle<mirror::ClassLoader> class_loader) { 2619 // Identify the underlying component type 2620 CHECK_EQ('[', descriptor[0]); 2621 StackHandleScope<2> hs(self); 2622 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, 2623 class_loader))); 2624 if (component_type.Get() == nullptr) { 2625 DCHECK(self->IsExceptionPending()); 2626 // We need to accept erroneous classes as component types. 2627 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1); 2628 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get())); 2629 if (component_type.Get() == nullptr) { 2630 DCHECK(self->IsExceptionPending()); 2631 return nullptr; 2632 } else { 2633 self->ClearException(); 2634 } 2635 } 2636 if (UNLIKELY(component_type->IsPrimitiveVoid())) { 2637 ThrowNoClassDefFoundError("Attempt to create array of void primitive type"); 2638 return nullptr; 2639 } 2640 // See if the component type is already loaded. Array classes are 2641 // always associated with the class loader of their underlying 2642 // element type -- an array of Strings goes with the loader for 2643 // java/lang/String -- so we need to look for it there. (The 2644 // caller should have checked for the existence of the class 2645 // before calling here, but they did so with *their* class loader, 2646 // not the component type's loader.) 2647 // 2648 // If we find it, the caller adds "loader" to the class' initiating 2649 // loader list, which should prevent us from going through this again. 2650 // 2651 // This call is unnecessary if "loader" and "component_type->GetClassLoader()" 2652 // are the same, because our caller (FindClass) just did the 2653 // lookup. (Even if we get this wrong we still have correct behavior, 2654 // because we effectively do this lookup again when we add the new 2655 // class to the hash table --- necessary because of possible races with 2656 // other threads.) 2657 if (class_loader.Get() != component_type->GetClassLoader()) { 2658 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader()); 2659 if (new_class != nullptr) { 2660 return new_class; 2661 } 2662 } 2663 2664 // Fill out the fields in the Class. 2665 // 2666 // It is possible to execute some methods against arrays, because 2667 // all arrays are subclasses of java_lang_Object_, so we need to set 2668 // up a vtable. We can just point at the one in java_lang_Object_. 2669 // 2670 // Array classes are simple enough that we don't need to do a full 2671 // link step. 2672 auto new_class = hs.NewHandle<mirror::Class>(nullptr); 2673 if (UNLIKELY(!init_done_)) { 2674 // Classes that were hand created, ie not by FindSystemClass 2675 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) { 2676 new_class.Assign(GetClassRoot(kClassArrayClass)); 2677 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) { 2678 new_class.Assign(GetClassRoot(kObjectArrayClass)); 2679 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) { 2680 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass)); 2681 } else if (strcmp(descriptor, "[C") == 0) { 2682 new_class.Assign(GetClassRoot(kCharArrayClass)); 2683 } else if (strcmp(descriptor, "[I") == 0) { 2684 new_class.Assign(GetClassRoot(kIntArrayClass)); 2685 } else if (strcmp(descriptor, "[J") == 0) { 2686 new_class.Assign(GetClassRoot(kLongArrayClass)); 2687 } 2688 } 2689 if (new_class.Get() == nullptr) { 2690 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_))); 2691 if (new_class.Get() == nullptr) { 2692 self->AssertPendingOOMException(); 2693 return nullptr; 2694 } 2695 new_class->SetComponentType(component_type.Get()); 2696 } 2697 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing. 2698 DCHECK(new_class->GetComponentType() != nullptr); 2699 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject); 2700 new_class->SetSuperClass(java_lang_Object); 2701 new_class->SetVTable(java_lang_Object->GetVTable()); 2702 new_class->SetPrimitiveType(Primitive::kPrimNot); 2703 new_class->SetClassLoader(component_type->GetClassLoader()); 2704 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self); 2705 { 2706 ArtMethod* imt[mirror::Class::kImtSize]; 2707 std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod()); 2708 new_class->PopulateEmbeddedImtAndVTable(imt, image_pointer_size_); 2709 } 2710 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self); 2711 // don't need to set new_class->SetObjectSize(..) 2712 // because Object::SizeOf delegates to Array::SizeOf 2713 2714 2715 // All arrays have java/lang/Cloneable and java/io/Serializable as 2716 // interfaces. We need to set that up here, so that stuff like 2717 // "instanceof" works right. 2718 // 2719 // Note: The GC could run during the call to FindSystemClass, 2720 // so we need to make sure the class object is GC-valid while we're in 2721 // there. Do this by clearing the interface list so the GC will just 2722 // think that the entries are null. 2723 2724 2725 // Use the single, global copies of "interfaces" and "iftable" 2726 // (remember not to free them for arrays). 2727 { 2728 mirror::IfTable* array_iftable = array_iftable_.Read(); 2729 CHECK(array_iftable != nullptr); 2730 new_class->SetIfTable(array_iftable); 2731 } 2732 2733 // Inherit access flags from the component type. 2734 int access_flags = new_class->GetComponentType()->GetAccessFlags(); 2735 // Lose any implementation detail flags; in particular, arrays aren't finalizable. 2736 access_flags &= kAccJavaFlagsMask; 2737 // Arrays can't be used as a superclass or interface, so we want to add "abstract final" 2738 // and remove "interface". 2739 access_flags |= kAccAbstract | kAccFinal; 2740 access_flags &= ~kAccInterface; 2741 2742 new_class->SetAccessFlags(access_flags); 2743 2744 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash); 2745 if (existing == nullptr) { 2746 return new_class.Get(); 2747 } 2748 // Another thread must have loaded the class after we 2749 // started but before we finished. Abandon what we've 2750 // done. 2751 // 2752 // (Yes, this happens.) 2753 2754 return existing; 2755} 2756 2757mirror::Class* ClassLinker::FindPrimitiveClass(char type) { 2758 switch (type) { 2759 case 'B': 2760 return GetClassRoot(kPrimitiveByte); 2761 case 'C': 2762 return GetClassRoot(kPrimitiveChar); 2763 case 'D': 2764 return GetClassRoot(kPrimitiveDouble); 2765 case 'F': 2766 return GetClassRoot(kPrimitiveFloat); 2767 case 'I': 2768 return GetClassRoot(kPrimitiveInt); 2769 case 'J': 2770 return GetClassRoot(kPrimitiveLong); 2771 case 'S': 2772 return GetClassRoot(kPrimitiveShort); 2773 case 'Z': 2774 return GetClassRoot(kPrimitiveBoolean); 2775 case 'V': 2776 return GetClassRoot(kPrimitiveVoid); 2777 default: 2778 break; 2779 } 2780 std::string printable_type(PrintableChar(type)); 2781 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str()); 2782 return nullptr; 2783} 2784 2785mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, size_t hash) { 2786 if (VLOG_IS_ON(class_linker)) { 2787 mirror::DexCache* dex_cache = klass->GetDexCache(); 2788 std::string source; 2789 if (dex_cache != nullptr) { 2790 source += " from "; 2791 source += dex_cache->GetLocation()->ToModifiedUtf8(); 2792 } 2793 LOG(INFO) << "Loaded class " << descriptor << source; 2794 } 2795 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2796 mirror::ClassLoader* const class_loader = klass->GetClassLoader(); 2797 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader); 2798 mirror::Class* existing = class_table->Lookup(descriptor, hash); 2799 if (existing != nullptr) { 2800 return existing; 2801 } 2802 if (kIsDebugBuild && !klass->IsTemp() && class_loader == nullptr && 2803 dex_cache_image_class_lookup_required_) { 2804 // Check a class loaded with the system class loader matches one in the image if the class 2805 // is in the image. 2806 existing = LookupClassFromImage(descriptor); 2807 if (existing != nullptr) { 2808 CHECK_EQ(klass, existing); 2809 } 2810 } 2811 VerifyObject(klass); 2812 class_table->InsertWithHash(klass, hash); 2813 if (log_new_class_table_roots_) { 2814 new_class_roots_.push_back(GcRoot<mirror::Class>(klass)); 2815 } 2816 return nullptr; 2817} 2818 2819void ClassLinker::UpdateClassVirtualMethods(mirror::Class* klass, 2820 LengthPrefixedArray<ArtMethod>* new_methods) { 2821 klass->SetVirtualMethodsPtr(new_methods); 2822 // Need to mark the card so that the remembered sets and mod union tables get updated. 2823 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass); 2824} 2825 2826bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) { 2827 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2828 ClassTable* const class_table = ClassTableForClassLoader(class_loader); 2829 return class_table != nullptr && class_table->Remove(descriptor); 2830} 2831 2832mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash, 2833 mirror::ClassLoader* class_loader) { 2834 { 2835 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 2836 ClassTable* const class_table = ClassTableForClassLoader(class_loader); 2837 if (class_table != nullptr) { 2838 mirror::Class* result = class_table->Lookup(descriptor, hash); 2839 if (result != nullptr) { 2840 return result; 2841 } 2842 } 2843 } 2844 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) { 2845 return nullptr; 2846 } 2847 // Lookup failed but need to search dex_caches_. 2848 mirror::Class* result = LookupClassFromImage(descriptor); 2849 if (result != nullptr) { 2850 result = InsertClass(descriptor, result, hash); 2851 } else { 2852 // Searching the image dex files/caches failed, we don't want to get into this situation 2853 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image 2854 // classes into the class table. 2855 constexpr uint32_t kMaxFailedDexCacheLookups = 1000; 2856 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) { 2857 MoveImageClassesToClassTable(); 2858 } 2859 } 2860 return result; 2861} 2862 2863static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches() 2864 SHARED_REQUIRES(Locks::mutator_lock_) { 2865 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace(); 2866 CHECK(image != nullptr); 2867 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 2868 return root->AsObjectArray<mirror::DexCache>(); 2869} 2870 2871void ClassLinker::MoveImageClassesToClassTable() { 2872 Thread* self = Thread::Current(); 2873 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 2874 if (!dex_cache_image_class_lookup_required_) { 2875 return; // All dex cache classes are already in the class table. 2876 } 2877 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table"); 2878 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 2879 std::string temp; 2880 ClassTable* const class_table = InsertClassTableForClassLoader(nullptr); 2881 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 2882 mirror::DexCache* dex_cache = dex_caches->Get(i); 2883 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes(); 2884 for (int32_t j = 0; j < types->GetLength(); j++) { 2885 mirror::Class* klass = types->Get(j); 2886 if (klass != nullptr) { 2887 DCHECK(klass->GetClassLoader() == nullptr); 2888 const char* descriptor = klass->GetDescriptor(&temp); 2889 size_t hash = ComputeModifiedUtf8Hash(descriptor); 2890 mirror::Class* existing = class_table->Lookup(descriptor, hash); 2891 if (existing != nullptr) { 2892 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != " 2893 << PrettyClassAndClassLoader(klass); 2894 } else { 2895 class_table->Insert(klass); 2896 if (log_new_class_table_roots_) { 2897 new_class_roots_.push_back(GcRoot<mirror::Class>(klass)); 2898 } 2899 } 2900 } 2901 } 2902 } 2903 dex_cache_image_class_lookup_required_ = false; 2904} 2905 2906void ClassLinker::MoveClassTableToPreZygote() { 2907 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2908 boot_class_table_.FreezeSnapshot(); 2909 for (GcRoot<mirror::ClassLoader>& root : class_loaders_) { 2910 ClassTable* const class_table = root.Read()->GetClassTable(); 2911 if (class_table != nullptr) { 2912 class_table->FreezeSnapshot(); 2913 } 2914 } 2915} 2916 2917mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) { 2918 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup"); 2919 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 2920 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) { 2921 mirror::DexCache* dex_cache = dex_caches->Get(i); 2922 const DexFile* dex_file = dex_cache->GetDexFile(); 2923 // Try binary searching the string/type index. 2924 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor); 2925 if (string_id != nullptr) { 2926 const DexFile::TypeId* type_id = 2927 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id)); 2928 if (type_id != nullptr) { 2929 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id); 2930 mirror::Class* klass = dex_cache->GetResolvedType(type_idx); 2931 if (klass != nullptr) { 2932 return klass; 2933 } 2934 } 2935 } 2936 } 2937 return nullptr; 2938} 2939 2940void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) { 2941 result.clear(); 2942 if (dex_cache_image_class_lookup_required_) { 2943 MoveImageClassesToClassTable(); 2944 } 2945 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2946 const size_t hash = ComputeModifiedUtf8Hash(descriptor); 2947 mirror::Class* klass = boot_class_table_.Lookup(descriptor, hash); 2948 if (klass != nullptr) { 2949 result.push_back(klass); 2950 } 2951 for (GcRoot<mirror::ClassLoader>& root : class_loaders_) { 2952 // There can only be one class with the same descriptor per class loader. 2953 ClassTable* const class_table = root.Read()->GetClassTable(); 2954 klass = class_table->Lookup(descriptor, hash); 2955 if (klass != nullptr) { 2956 result.push_back(klass); 2957 } 2958 } 2959} 2960 2961void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) { 2962 // TODO: assert that the monitor on the Class is held 2963 ObjectLock<mirror::Class> lock(self, klass); 2964 2965 // Don't attempt to re-verify if already sufficiently verified. 2966 if (klass->IsVerified()) { 2967 EnsurePreverifiedMethods(klass); 2968 return; 2969 } 2970 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) { 2971 return; 2972 } 2973 2974 // The class might already be erroneous, for example at compile time if we attempted to verify 2975 // this class as a parent to another. 2976 if (klass->IsErroneous()) { 2977 ThrowEarlierClassFailure(klass.Get()); 2978 return; 2979 } 2980 2981 if (klass->GetStatus() == mirror::Class::kStatusResolved) { 2982 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self); 2983 } else { 2984 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime) 2985 << PrettyClass(klass.Get()); 2986 CHECK(!Runtime::Current()->IsAotCompiler()); 2987 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self); 2988 } 2989 2990 // Skip verification if we are forcing a soft fail. 2991 // This has to be before the normal verification enabled check, 2992 // since technically verification is disabled in this mode. 2993 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) { 2994 // Force verification to be a 'soft failure'. 2995 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self); 2996 // As this is a fake verified status, make sure the methods are _not_ marked preverified 2997 // later. 2998 klass->SetPreverified(); 2999 return; 3000 } 3001 3002 // Skip verification if disabled. 3003 if (!Runtime::Current()->IsVerificationEnabled()) { 3004 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self); 3005 EnsurePreverifiedMethods(klass); 3006 return; 3007 } 3008 3009 // Verify super class. 3010 StackHandleScope<2> hs(self); 3011 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass())); 3012 if (super.Get() != nullptr) { 3013 // Acquire lock to prevent races on verifying the super class. 3014 ObjectLock<mirror::Class> super_lock(self, super); 3015 3016 if (!super->IsVerified() && !super->IsErroneous()) { 3017 VerifyClass(self, super); 3018 } 3019 if (!super->IsCompileTimeVerified()) { 3020 std::string error_msg( 3021 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s", 3022 PrettyDescriptor(klass.Get()).c_str(), 3023 PrettyDescriptor(super.Get()).c_str())); 3024 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3025 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException())); 3026 if (cause.Get() != nullptr) { 3027 self->ClearException(); 3028 } 3029 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3030 if (cause.Get() != nullptr) { 3031 self->GetException()->SetCause(cause.Get()); 3032 } 3033 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex()); 3034 if (Runtime::Current()->IsAotCompiler()) { 3035 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref); 3036 } 3037 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3038 return; 3039 } 3040 } 3041 3042 // Try to use verification information from the oat file, otherwise do runtime verification. 3043 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile(); 3044 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady); 3045 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status); 3046 if (oat_file_class_status == mirror::Class::kStatusError) { 3047 VLOG(class_linker) << "Skipping runtime verification of erroneous class " 3048 << PrettyDescriptor(klass.Get()) << " in " 3049 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3050 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification", 3051 PrettyDescriptor(klass.Get()).c_str()); 3052 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3053 return; 3054 } 3055 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure; 3056 std::string error_msg; 3057 if (!preverified) { 3058 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(), 3059 Runtime::Current()->IsAotCompiler(), 3060 &error_msg); 3061 } 3062 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) { 3063 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) { 3064 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get()) 3065 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3066 << " because: " << error_msg; 3067 } 3068 self->AssertNoPendingException(); 3069 // Make sure all classes referenced by catch blocks are resolved. 3070 ResolveClassExceptionHandlerTypes(dex_file, klass); 3071 if (verifier_failure == verifier::MethodVerifier::kNoFailure) { 3072 // Even though there were no verifier failures we need to respect whether the super-class 3073 // was verified or requiring runtime reverification. 3074 if (super.Get() == nullptr || super->IsVerified()) { 3075 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self); 3076 } else { 3077 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 3078 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self); 3079 // Pretend a soft failure occured so that we don't consider the class verified below. 3080 verifier_failure = verifier::MethodVerifier::kSoftFailure; 3081 } 3082 } else { 3083 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure); 3084 // Soft failures at compile time should be retried at runtime. Soft 3085 // failures at runtime will be handled by slow paths in the generated 3086 // code. Set status accordingly. 3087 if (Runtime::Current()->IsAotCompiler()) { 3088 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self); 3089 } else { 3090 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self); 3091 // As this is a fake verified status, make sure the methods are _not_ marked preverified 3092 // later. 3093 klass->SetPreverified(); 3094 } 3095 } 3096 } else { 3097 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get()) 3098 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3099 << " because: " << error_msg; 3100 self->AssertNoPendingException(); 3101 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3102 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3103 } 3104 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) { 3105 // Class is verified so we don't need to do any access check on its methods. 3106 // Let the interpreter know it by setting the kAccPreverified flag onto each 3107 // method. 3108 // Note: we're going here during compilation and at runtime. When we set the 3109 // kAccPreverified flag when compiling image classes, the flag is recorded 3110 // in the image and is set when loading the image. 3111 EnsurePreverifiedMethods(klass); 3112 } 3113} 3114 3115void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) { 3116 if (!klass->IsPreverified()) { 3117 klass->SetPreverifiedFlagOnAllMethods(image_pointer_size_); 3118 klass->SetPreverified(); 3119 } 3120} 3121 3122bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass, 3123 mirror::Class::Status& oat_file_class_status) { 3124 // If we're compiling, we can only verify the class using the oat file if 3125 // we are not compiling the image or if the class we're verifying is not part of 3126 // the app. In other words, we will only check for preverification of bootclasspath 3127 // classes. 3128 if (Runtime::Current()->IsAotCompiler()) { 3129 // Are we compiling the bootclasspath? 3130 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) { 3131 return false; 3132 } 3133 // We are compiling an app (not the image). 3134 3135 // Is this an app class? (I.e. not a bootclasspath class) 3136 if (klass->GetClassLoader() != nullptr) { 3137 return false; 3138 } 3139 } 3140 3141 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile(); 3142 // In case we run without an image there won't be a backing oat file. 3143 if (oat_dex_file == nullptr) { 3144 return false; 3145 } 3146 3147 // We may be running with a preopted oat file but without image. In this case, 3148 // we don't skip verification of preverified classes to ensure we initialize 3149 // dex caches with all types resolved during verification. 3150 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot 3151 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when 3152 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are 3153 // already pre-opted, as then the runtime is started. 3154 if (!Runtime::Current()->IsAotCompiler() && 3155 !Runtime::Current()->GetHeap()->HasImageSpace() && 3156 klass->GetClassLoader() != nullptr) { 3157 return false; 3158 } 3159 3160 uint16_t class_def_index = klass->GetDexClassDefIndex(); 3161 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus(); 3162 if (oat_file_class_status == mirror::Class::kStatusVerified || 3163 oat_file_class_status == mirror::Class::kStatusInitialized) { 3164 return true; 3165 } 3166 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) { 3167 // Compile time verification failed with a soft error. Compile time verification can fail 3168 // because we have incomplete type information. Consider the following: 3169 // class ... { 3170 // Foo x; 3171 // .... () { 3172 // if (...) { 3173 // v1 gets assigned a type of resolved class Foo 3174 // } else { 3175 // v1 gets assigned a type of unresolved class Bar 3176 // } 3177 // iput x = v1 3178 // } } 3179 // when we merge v1 following the if-the-else it results in Conflict 3180 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be 3181 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as 3182 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk 3183 // at compile time). 3184 return false; 3185 } 3186 if (oat_file_class_status == mirror::Class::kStatusError) { 3187 // Compile time verification failed with a hard error. This is caused by invalid instructions 3188 // in the class. These errors are unrecoverable. 3189 return false; 3190 } 3191 if (oat_file_class_status == mirror::Class::kStatusNotReady) { 3192 // Status is uninitialized if we couldn't determine the status at compile time, for example, 3193 // not loading the class. 3194 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy 3195 // isn't a problem and this case shouldn't occur 3196 return false; 3197 } 3198 std::string temp; 3199 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status 3200 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " 3201 << klass->GetDescriptor(&temp); 3202 UNREACHABLE(); 3203} 3204 3205void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, 3206 Handle<mirror::Class> klass) { 3207 for (size_t i = 0; i < klass->NumDirectMethods(); i++) { 3208 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i, image_pointer_size_)); 3209 } 3210 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) { 3211 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i, image_pointer_size_)); 3212 } 3213} 3214 3215void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, 3216 ArtMethod* method) { 3217 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod. 3218 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset()); 3219 if (code_item == nullptr) { 3220 return; // native or abstract method 3221 } 3222 if (code_item->tries_size_ == 0) { 3223 return; // nothing to process 3224 } 3225 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0); 3226 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 3227 for (uint32_t idx = 0; idx < handlers_size; idx++) { 3228 CatchHandlerIterator iterator(handlers_ptr); 3229 for (; iterator.HasNext(); iterator.Next()) { 3230 // Ensure exception types are resolved so that they don't need resolution to be delivered, 3231 // unresolved exception types will be ignored by exception delivery 3232 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) { 3233 mirror::Class* exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method); 3234 if (exception_type == nullptr) { 3235 DCHECK(Thread::Current()->IsExceptionPending()); 3236 Thread::Current()->ClearException(); 3237 } 3238 } 3239 } 3240 handlers_ptr = iterator.EndDataPointer(); 3241 } 3242} 3243 3244mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name, 3245 jobjectArray interfaces, jobject loader, 3246 jobjectArray methods, jobjectArray throws) { 3247 Thread* self = soa.Self(); 3248 StackHandleScope<10> hs(self); 3249 MutableHandle<mirror::Class> klass(hs.NewHandle( 3250 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class)))); 3251 if (klass.Get() == nullptr) { 3252 CHECK(self->IsExceptionPending()); // OOME. 3253 return nullptr; 3254 } 3255 DCHECK(klass->GetClass() != nullptr); 3256 klass->SetObjectSize(sizeof(mirror::Proxy)); 3257 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods. 3258 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified); 3259 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader)); 3260 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 3261 klass->SetName(soa.Decode<mirror::String*>(name)); 3262 klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache()); 3263 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self); 3264 std::string descriptor(GetDescriptorForProxy(klass.Get())); 3265 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str()); 3266 3267 // Insert the class before loading the fields as the field roots 3268 // (ArtField::declaring_class_) are only visited from the class 3269 // table. There can't be any suspend points between inserting the 3270 // class and setting the field arrays below. 3271 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), hash); 3272 CHECK(existing == nullptr); 3273 3274 // Instance fields are inherited, but we add a couple of static fields... 3275 const size_t num_fields = 2; 3276 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, num_fields); 3277 klass->SetSFieldsPtr(sfields); 3278 3279 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by 3280 // our proxy, so Class.getInterfaces doesn't return the flattened set. 3281 ArtField& interfaces_sfield = sfields->At(0); 3282 interfaces_sfield.SetDexFieldIndex(0); 3283 interfaces_sfield.SetDeclaringClass(klass.Get()); 3284 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 3285 3286 // 2. Create a static field 'throws' that holds exceptions thrown by our methods. 3287 ArtField& throws_sfield = sfields->At(1); 3288 throws_sfield.SetDexFieldIndex(1); 3289 throws_sfield.SetDeclaringClass(klass.Get()); 3290 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 3291 3292 // Proxies have 1 direct method, the constructor 3293 LengthPrefixedArray<ArtMethod>* directs = AllocArtMethodArray(self, 1); 3294 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we 3295 // want to throw OOM in the future. 3296 if (UNLIKELY(directs == nullptr)) { 3297 self->AssertPendingOOMException(); 3298 return nullptr; 3299 } 3300 klass->SetDirectMethodsPtr(directs); 3301 CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_)); 3302 3303 // Create virtual method using specified prototypes. 3304 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods)); 3305 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass()) 3306 << PrettyClass(h_methods->GetClass()); 3307 const size_t num_virtual_methods = h_methods->GetLength(); 3308 auto* virtuals = AllocArtMethodArray(self, num_virtual_methods); 3309 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we 3310 // want to throw OOM in the future. 3311 if (UNLIKELY(virtuals == nullptr)) { 3312 self->AssertPendingOOMException(); 3313 return nullptr; 3314 } 3315 klass->SetVirtualMethodsPtr(virtuals); 3316 for (size_t i = 0; i < num_virtual_methods; ++i) { 3317 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_); 3318 auto* prototype = h_methods->Get(i)->GetArtMethod(); 3319 CreateProxyMethod(klass, prototype, virtual_method); 3320 DCHECK(virtual_method->GetDeclaringClass() != nullptr); 3321 DCHECK(prototype->GetDeclaringClass() != nullptr); 3322 } 3323 3324 // The super class is java.lang.reflect.Proxy 3325 klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy)); 3326 // Now effectively in the loaded state. 3327 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); 3328 self->AssertNoPendingException(); 3329 3330 MutableHandle<mirror::Class> new_class = hs.NewHandle<mirror::Class>(nullptr); 3331 { 3332 // Must hold lock on object when resolved. 3333 ObjectLock<mirror::Class> resolution_lock(self, klass); 3334 // Link the fields and virtual methods, creating vtable and iftables. 3335 // The new class will replace the old one in the class table. 3336 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces( 3337 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces))); 3338 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) { 3339 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3340 return nullptr; 3341 } 3342 } 3343 CHECK(klass->IsRetired()); 3344 CHECK_NE(klass.Get(), new_class.Get()); 3345 klass.Assign(new_class.Get()); 3346 3347 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get()); 3348 interfaces_sfield.SetObject<false>(klass.Get(), 3349 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 3350 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get()); 3351 throws_sfield.SetObject<false>( 3352 klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws)); 3353 3354 { 3355 // Lock on klass is released. Lock new class object. 3356 ObjectLock<mirror::Class> initialization_lock(self, klass); 3357 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self); 3358 } 3359 3360 // sanity checks 3361 if (kIsDebugBuild) { 3362 CHECK(klass->GetIFieldsPtr() == nullptr); 3363 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_)); 3364 3365 for (size_t i = 0; i < num_virtual_methods; ++i) { 3366 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_); 3367 auto* prototype = h_methods->Get(i++)->GetArtMethod(); 3368 CheckProxyMethod(virtual_method, prototype); 3369 } 3370 3371 StackHandleScope<1> hs2(self); 3372 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String*>(name)); 3373 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces", 3374 decoded_name->ToModifiedUtf8().c_str())); 3375 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name); 3376 3377 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws", 3378 decoded_name->ToModifiedUtf8().c_str())); 3379 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name); 3380 3381 CHECK_EQ(klass.Get()->GetInterfaces(), 3382 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 3383 CHECK_EQ(klass.Get()->GetThrows(), 3384 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws)); 3385 } 3386 return klass.Get(); 3387} 3388 3389std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) { 3390 DCHECK(proxy_class->IsProxyClass()); 3391 mirror::String* name = proxy_class->GetName(); 3392 DCHECK(name != nullptr); 3393 return DotToDescriptor(name->ToModifiedUtf8().c_str()); 3394} 3395 3396ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, ArtMethod* proxy_method) { 3397 DCHECK(proxy_class->IsProxyClass()); 3398 DCHECK(proxy_method->IsProxyMethod()); 3399 { 3400 ReaderMutexLock mu(Thread::Current(), dex_lock_); 3401 // Locate the dex cache of the original interface/Object 3402 for (const GcRoot<mirror::DexCache>& root : dex_caches_) { 3403 auto* dex_cache = root.Read(); 3404 if (proxy_method->HasSameDexCacheResolvedTypes(dex_cache->GetResolvedTypes())) { 3405 ArtMethod* resolved_method = dex_cache->GetResolvedMethod( 3406 proxy_method->GetDexMethodIndex(), image_pointer_size_); 3407 CHECK(resolved_method != nullptr); 3408 return resolved_method; 3409 } 3410 } 3411 } 3412 LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " " 3413 << PrettyMethod(proxy_method); 3414 UNREACHABLE(); 3415} 3416 3417void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) { 3418 // Create constructor for Proxy that must initialize the method. 3419 CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 16u); 3420 ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->GetDirectMethodUnchecked( 3421 2, image_pointer_size_); 3422 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden 3423 // constructor method. 3424 GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod( 3425 proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_); 3426 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its 3427 // code_ too) 3428 DCHECK(out != nullptr); 3429 out->CopyFrom(proxy_constructor, image_pointer_size_); 3430 // Make this constructor public and fix the class to be our Proxy version 3431 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic); 3432 out->SetDeclaringClass(klass.Get()); 3433} 3434 3435void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const { 3436 CHECK(constructor->IsConstructor()); 3437 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_); 3438 CHECK_STREQ(np->GetName(), "<init>"); 3439 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V"); 3440 DCHECK(constructor->IsPublic()); 3441} 3442 3443void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype, 3444 ArtMethod* out) { 3445 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden 3446 // prototype method 3447 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache(); 3448 // Avoid dirtying the dex cache unless we need to. 3449 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) != 3450 prototype) { 3451 dex_cache->SetResolvedMethod( 3452 prototype->GetDexMethodIndex(), prototype, image_pointer_size_); 3453 } 3454 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize 3455 // as necessary 3456 DCHECK(out != nullptr); 3457 out->CopyFrom(prototype, image_pointer_size_); 3458 3459 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to 3460 // the intersection of throw exceptions as defined in Proxy 3461 out->SetDeclaringClass(klass.Get()); 3462 out->SetAccessFlags((out->GetAccessFlags() & ~kAccAbstract) | kAccFinal); 3463 3464 // At runtime the method looks like a reference and argument saving method, clone the code 3465 // related parameters from this method. 3466 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler()); 3467} 3468 3469void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const { 3470 // Basic sanity 3471 CHECK(!prototype->IsFinal()); 3472 CHECK(method->IsFinal()); 3473 CHECK(!method->IsAbstract()); 3474 3475 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its 3476 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself. 3477 CHECK(prototype->HasSameDexCacheResolvedMethods(method)); 3478 CHECK(prototype->HasSameDexCacheResolvedTypes(method)); 3479 auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_); 3480 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache()); 3481 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex()); 3482 3483 CHECK_STREQ(np->GetName(), prototype->GetName()); 3484 CHECK_STREQ(np->GetShorty(), prototype->GetShorty()); 3485 // More complex sanity - via dex cache 3486 CHECK_EQ(np->GetReturnType(), prototype->GetReturnType()); 3487} 3488 3489bool ClassLinker::CanWeInitializeClass(mirror::Class* klass, bool can_init_statics, 3490 bool can_init_parents) { 3491 if (can_init_statics && can_init_parents) { 3492 return true; 3493 } 3494 if (!can_init_statics) { 3495 // Check if there's a class initializer. 3496 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_); 3497 if (clinit != nullptr) { 3498 return false; 3499 } 3500 // Check if there are encoded static values needing initialization. 3501 if (klass->NumStaticFields() != 0) { 3502 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 3503 DCHECK(dex_class_def != nullptr); 3504 if (dex_class_def->static_values_off_ != 0) { 3505 return false; 3506 } 3507 } 3508 } 3509 if (klass->IsInterface() || !klass->HasSuperClass()) { 3510 return true; 3511 } 3512 mirror::Class* super_class = klass->GetSuperClass(); 3513 if (!can_init_parents && !super_class->IsInitialized()) { 3514 return false; 3515 } 3516 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents); 3517} 3518 3519bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass, 3520 bool can_init_statics, bool can_init_parents) { 3521 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol 3522 3523 // Are we already initialized and therefore done? 3524 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as 3525 // an initialized class will never change its state. 3526 if (klass->IsInitialized()) { 3527 return true; 3528 } 3529 3530 // Fast fail if initialization requires a full runtime. Not part of the JLS. 3531 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) { 3532 return false; 3533 } 3534 3535 self->AllowThreadSuspension(); 3536 uint64_t t0; 3537 { 3538 ObjectLock<mirror::Class> lock(self, klass); 3539 3540 // Re-check under the lock in case another thread initialized ahead of us. 3541 if (klass->IsInitialized()) { 3542 return true; 3543 } 3544 3545 // Was the class already found to be erroneous? Done under the lock to match the JLS. 3546 if (klass->IsErroneous()) { 3547 ThrowEarlierClassFailure(klass.Get()); 3548 VlogClassInitializationFailure(klass); 3549 return false; 3550 } 3551 3552 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus(); 3553 3554 if (!klass->IsVerified()) { 3555 VerifyClass(self, klass); 3556 if (!klass->IsVerified()) { 3557 // We failed to verify, expect either the klass to be erroneous or verification failed at 3558 // compile time. 3559 if (klass->IsErroneous()) { 3560 CHECK(self->IsExceptionPending()); 3561 VlogClassInitializationFailure(klass); 3562 } else { 3563 CHECK(Runtime::Current()->IsAotCompiler()); 3564 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 3565 } 3566 return false; 3567 } else { 3568 self->AssertNoPendingException(); 3569 } 3570 } 3571 3572 // If the class is kStatusInitializing, either this thread is 3573 // initializing higher up the stack or another thread has beat us 3574 // to initializing and we need to wait. Either way, this 3575 // invocation of InitializeClass will not be responsible for 3576 // running <clinit> and will return. 3577 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 3578 // Could have got an exception during verification. 3579 if (self->IsExceptionPending()) { 3580 VlogClassInitializationFailure(klass); 3581 return false; 3582 } 3583 // We caught somebody else in the act; was it us? 3584 if (klass->GetClinitThreadId() == self->GetTid()) { 3585 // Yes. That's fine. Return so we can continue initializing. 3586 return true; 3587 } 3588 // No. That's fine. Wait for another thread to finish initializing. 3589 return WaitForInitializeClass(klass, self, lock); 3590 } 3591 3592 if (!ValidateSuperClassDescriptors(klass)) { 3593 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3594 return false; 3595 } 3596 self->AllowThreadSuspension(); 3597 3598 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get()); 3599 3600 // From here out other threads may observe that we're initializing and so changes of state 3601 // require the a notification. 3602 klass->SetClinitThreadId(self->GetTid()); 3603 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self); 3604 3605 t0 = NanoTime(); 3606 } 3607 3608 // Initialize super classes, must be done while initializing for the JLS. 3609 if (!klass->IsInterface() && klass->HasSuperClass()) { 3610 mirror::Class* super_class = klass->GetSuperClass(); 3611 if (!super_class->IsInitialized()) { 3612 CHECK(!super_class->IsInterface()); 3613 CHECK(can_init_parents); 3614 StackHandleScope<1> hs(self); 3615 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class)); 3616 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true); 3617 if (!super_initialized) { 3618 // The super class was verified ahead of entering initializing, we should only be here if 3619 // the super class became erroneous due to initialization. 3620 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending()) 3621 << "Super class initialization failed for " 3622 << PrettyDescriptor(handle_scope_super.Get()) 3623 << " that has unexpected status " << handle_scope_super->GetStatus() 3624 << "\nPending exception:\n" 3625 << (self->GetException() != nullptr ? self->GetException()->Dump() : ""); 3626 ObjectLock<mirror::Class> lock(self, klass); 3627 // Initialization failed because the super-class is erroneous. 3628 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3629 return false; 3630 } 3631 } 3632 } 3633 3634 const size_t num_static_fields = klass->NumStaticFields(); 3635 if (num_static_fields > 0) { 3636 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 3637 CHECK(dex_class_def != nullptr); 3638 const DexFile& dex_file = klass->GetDexFile(); 3639 StackHandleScope<3> hs(self); 3640 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader())); 3641 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache())); 3642 3643 // Eagerly fill in static fields so that the we don't have to do as many expensive 3644 // Class::FindStaticField in ResolveField. 3645 for (size_t i = 0; i < num_static_fields; ++i) { 3646 ArtField* field = klass->GetStaticField(i); 3647 const uint32_t field_idx = field->GetDexFieldIndex(); 3648 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_); 3649 if (resolved_field == nullptr) { 3650 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_); 3651 } else { 3652 DCHECK_EQ(field, resolved_field); 3653 } 3654 } 3655 3656 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader, 3657 this, *dex_class_def); 3658 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def); 3659 ClassDataItemIterator field_it(dex_file, class_data); 3660 if (value_it.HasNext()) { 3661 DCHECK(field_it.HasNextStaticField()); 3662 CHECK(can_init_statics); 3663 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) { 3664 ArtField* field = ResolveField( 3665 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true); 3666 if (Runtime::Current()->IsActiveTransaction()) { 3667 value_it.ReadValueToField<true>(field); 3668 } else { 3669 value_it.ReadValueToField<false>(field); 3670 } 3671 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField()); 3672 } 3673 } 3674 } 3675 3676 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_); 3677 if (clinit != nullptr) { 3678 CHECK(can_init_statics); 3679 JValue result; 3680 clinit->Invoke(self, nullptr, 0, &result, "V"); 3681 } 3682 3683 self->AllowThreadSuspension(); 3684 uint64_t t1 = NanoTime(); 3685 3686 bool success = true; 3687 { 3688 ObjectLock<mirror::Class> lock(self, klass); 3689 3690 if (self->IsExceptionPending()) { 3691 WrapExceptionInInitializer(klass); 3692 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3693 success = false; 3694 } else if (Runtime::Current()->IsTransactionAborted()) { 3695 // The exception thrown when the transaction aborted has been caught and cleared 3696 // so we need to throw it again now. 3697 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get()) 3698 << " without exception while transaction was aborted: re-throw it now."; 3699 Runtime::Current()->ThrowTransactionAbortError(self); 3700 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3701 success = false; 3702 } else { 3703 RuntimeStats* global_stats = Runtime::Current()->GetStats(); 3704 RuntimeStats* thread_stats = self->GetStats(); 3705 ++global_stats->class_init_count; 3706 ++thread_stats->class_init_count; 3707 global_stats->class_init_time_ns += (t1 - t0); 3708 thread_stats->class_init_time_ns += (t1 - t0); 3709 // Set the class as initialized except if failed to initialize static fields. 3710 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self); 3711 if (VLOG_IS_ON(class_linker)) { 3712 std::string temp; 3713 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " << 3714 klass->GetLocation(); 3715 } 3716 // Opportunistically set static method trampolines to their destination. 3717 FixupStaticTrampolines(klass.Get()); 3718 } 3719 } 3720 return success; 3721} 3722 3723bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self, 3724 ObjectLock<mirror::Class>& lock) 3725 SHARED_REQUIRES(Locks::mutator_lock_) { 3726 while (true) { 3727 self->AssertNoPendingException(); 3728 CHECK(!klass->IsInitialized()); 3729 lock.WaitIgnoringInterrupts(); 3730 3731 // When we wake up, repeat the test for init-in-progress. If 3732 // there's an exception pending (only possible if 3733 // we were not using WaitIgnoringInterrupts), bail out. 3734 if (self->IsExceptionPending()) { 3735 WrapExceptionInInitializer(klass); 3736 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 3737 return false; 3738 } 3739 // Spurious wakeup? Go back to waiting. 3740 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 3741 continue; 3742 } 3743 if (klass->GetStatus() == mirror::Class::kStatusVerified && 3744 Runtime::Current()->IsAotCompiler()) { 3745 // Compile time initialization failed. 3746 return false; 3747 } 3748 if (klass->IsErroneous()) { 3749 // The caller wants an exception, but it was thrown in a 3750 // different thread. Synthesize one here. 3751 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread", 3752 PrettyDescriptor(klass.Get()).c_str()); 3753 VlogClassInitializationFailure(klass); 3754 return false; 3755 } 3756 if (klass->IsInitialized()) { 3757 return true; 3758 } 3759 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is " 3760 << klass->GetStatus(); 3761 } 3762 UNREACHABLE(); 3763} 3764 3765static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass, 3766 Handle<mirror::Class> super_klass, 3767 ArtMethod* method, 3768 ArtMethod* m) 3769 SHARED_REQUIRES(Locks::mutator_lock_) { 3770 DCHECK(Thread::Current()->IsExceptionPending()); 3771 DCHECK(!m->IsProxyMethod()); 3772 const DexFile* dex_file = m->GetDexFile(); 3773 const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex()); 3774 const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id); 3775 uint16_t return_type_idx = proto_id.return_type_idx_; 3776 std::string return_type = PrettyType(return_type_idx, *dex_file); 3777 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader()); 3778 ThrowWrappedLinkageError(klass.Get(), 3779 "While checking class %s method %s signature against %s %s: " 3780 "Failed to resolve return type %s with %s", 3781 PrettyDescriptor(klass.Get()).c_str(), 3782 PrettyMethod(method).c_str(), 3783 super_klass->IsInterface() ? "interface" : "superclass", 3784 PrettyDescriptor(super_klass.Get()).c_str(), 3785 return_type.c_str(), class_loader.c_str()); 3786} 3787 3788static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass, 3789 Handle<mirror::Class> super_klass, 3790 ArtMethod* method, 3791 ArtMethod* m, 3792 uint32_t index, uint32_t arg_type_idx) 3793 SHARED_REQUIRES(Locks::mutator_lock_) { 3794 DCHECK(Thread::Current()->IsExceptionPending()); 3795 DCHECK(!m->IsProxyMethod()); 3796 const DexFile* dex_file = m->GetDexFile(); 3797 std::string arg_type = PrettyType(arg_type_idx, *dex_file); 3798 std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader()); 3799 ThrowWrappedLinkageError(klass.Get(), 3800 "While checking class %s method %s signature against %s %s: " 3801 "Failed to resolve arg %u type %s with %s", 3802 PrettyDescriptor(klass.Get()).c_str(), 3803 PrettyMethod(method).c_str(), 3804 super_klass->IsInterface() ? "interface" : "superclass", 3805 PrettyDescriptor(super_klass.Get()).c_str(), 3806 index, arg_type.c_str(), class_loader.c_str()); 3807} 3808 3809static void ThrowSignatureMismatch(Handle<mirror::Class> klass, 3810 Handle<mirror::Class> super_klass, 3811 ArtMethod* method, 3812 const std::string& error_msg) 3813 SHARED_REQUIRES(Locks::mutator_lock_) { 3814 ThrowLinkageError(klass.Get(), 3815 "Class %s method %s resolves differently in %s %s: %s", 3816 PrettyDescriptor(klass.Get()).c_str(), 3817 PrettyMethod(method).c_str(), 3818 super_klass->IsInterface() ? "interface" : "superclass", 3819 PrettyDescriptor(super_klass.Get()).c_str(), 3820 error_msg.c_str()); 3821} 3822 3823static bool HasSameSignatureWithDifferentClassLoaders(Thread* self, 3824 Handle<mirror::Class> klass, 3825 Handle<mirror::Class> super_klass, 3826 ArtMethod* method1, 3827 ArtMethod* method2) 3828 SHARED_REQUIRES(Locks::mutator_lock_) { 3829 { 3830 StackHandleScope<1> hs(self); 3831 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType())); 3832 if (UNLIKELY(return_type.Get() == nullptr)) { 3833 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1); 3834 return false; 3835 } 3836 mirror::Class* other_return_type = method2->GetReturnType(); 3837 if (UNLIKELY(other_return_type == nullptr)) { 3838 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2); 3839 return false; 3840 } 3841 if (UNLIKELY(other_return_type != return_type.Get())) { 3842 ThrowSignatureMismatch(klass, super_klass, method1, 3843 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)", 3844 PrettyClassAndClassLoader(return_type.Get()).c_str(), 3845 return_type.Get(), 3846 PrettyClassAndClassLoader(other_return_type).c_str(), 3847 other_return_type)); 3848 return false; 3849 } 3850 } 3851 const DexFile::TypeList* types1 = method1->GetParameterTypeList(); 3852 const DexFile::TypeList* types2 = method2->GetParameterTypeList(); 3853 if (types1 == nullptr) { 3854 if (types2 != nullptr && types2->Size() != 0) { 3855 ThrowSignatureMismatch(klass, super_klass, method1, 3856 StringPrintf("Type list mismatch with %s", 3857 PrettyMethod(method2, true).c_str())); 3858 return false; 3859 } 3860 return true; 3861 } else if (UNLIKELY(types2 == nullptr)) { 3862 if (types1->Size() != 0) { 3863 ThrowSignatureMismatch(klass, super_klass, method1, 3864 StringPrintf("Type list mismatch with %s", 3865 PrettyMethod(method2, true).c_str())); 3866 return false; 3867 } 3868 return true; 3869 } 3870 uint32_t num_types = types1->Size(); 3871 if (UNLIKELY(num_types != types2->Size())) { 3872 ThrowSignatureMismatch(klass, super_klass, method1, 3873 StringPrintf("Type list mismatch with %s", 3874 PrettyMethod(method2, true).c_str())); 3875 return false; 3876 } 3877 for (uint32_t i = 0; i < num_types; ++i) { 3878 StackHandleScope<1> hs(self); 3879 uint32_t param_type_idx = types1->GetTypeItem(i).type_idx_; 3880 Handle<mirror::Class> param_type(hs.NewHandle( 3881 method1->GetClassFromTypeIndex(param_type_idx, true))); 3882 if (UNLIKELY(param_type.Get() == nullptr)) { 3883 ThrowSignatureCheckResolveArgException(klass, super_klass, method1, 3884 method1, i, param_type_idx); 3885 return false; 3886 } 3887 uint32_t other_param_type_idx = types2->GetTypeItem(i).type_idx_; 3888 mirror::Class* other_param_type = 3889 method2->GetClassFromTypeIndex(other_param_type_idx, true); 3890 if (UNLIKELY(other_param_type == nullptr)) { 3891 ThrowSignatureCheckResolveArgException(klass, super_klass, method1, 3892 method2, i, other_param_type_idx); 3893 return false; 3894 } 3895 if (UNLIKELY(param_type.Get() != other_param_type)) { 3896 ThrowSignatureMismatch(klass, super_klass, method1, 3897 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)", 3898 i, 3899 PrettyClassAndClassLoader(param_type.Get()).c_str(), 3900 param_type.Get(), 3901 PrettyClassAndClassLoader(other_param_type).c_str(), 3902 other_param_type)); 3903 return false; 3904 } 3905 } 3906 return true; 3907} 3908 3909 3910bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) { 3911 if (klass->IsInterface()) { 3912 return true; 3913 } 3914 // Begin with the methods local to the superclass. 3915 Thread* self = Thread::Current(); 3916 StackHandleScope<1> hs(self); 3917 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr)); 3918 if (klass->HasSuperClass() && 3919 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) { 3920 super_klass.Assign(klass->GetSuperClass()); 3921 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) { 3922 auto* m = klass->GetVTableEntry(i, image_pointer_size_); 3923 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_); 3924 if (m != super_m) { 3925 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, klass, super_klass, 3926 m, super_m))) { 3927 self->AssertPendingException(); 3928 return false; 3929 } 3930 } 3931 } 3932 } 3933 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 3934 super_klass.Assign(klass->GetIfTable()->GetInterface(i)); 3935 if (klass->GetClassLoader() != super_klass->GetClassLoader()) { 3936 uint32_t num_methods = super_klass->NumVirtualMethods(); 3937 for (uint32_t j = 0; j < num_methods; ++j) { 3938 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>( 3939 j, image_pointer_size_); 3940 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_); 3941 if (m != super_m) { 3942 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, klass, super_klass, 3943 m, super_m))) { 3944 self->AssertPendingException(); 3945 return false; 3946 } 3947 } 3948 } 3949 } 3950 } 3951 return true; 3952} 3953 3954bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields, 3955 bool can_init_parents) { 3956 DCHECK(c.Get() != nullptr); 3957 if (c->IsInitialized()) { 3958 EnsurePreverifiedMethods(c); 3959 return true; 3960 } 3961 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents); 3962 if (!success) { 3963 if (can_init_fields && can_init_parents) { 3964 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get()); 3965 } 3966 } else { 3967 self->AssertNoPendingException(); 3968 } 3969 return success; 3970} 3971 3972void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, 3973 mirror::Class* new_class) { 3974 DCHECK_EQ(temp_class->NumInstanceFields(), 0u); 3975 for (ArtField& field : new_class->GetIFields()) { 3976 if (field.GetDeclaringClass() == temp_class) { 3977 field.SetDeclaringClass(new_class); 3978 } 3979 } 3980 3981 DCHECK_EQ(temp_class->NumStaticFields(), 0u); 3982 for (ArtField& field : new_class->GetSFields()) { 3983 if (field.GetDeclaringClass() == temp_class) { 3984 field.SetDeclaringClass(new_class); 3985 } 3986 } 3987 3988 DCHECK_EQ(temp_class->NumDirectMethods(), 0u); 3989 for (auto& method : new_class->GetDirectMethods(image_pointer_size_)) { 3990 if (method.GetDeclaringClass() == temp_class) { 3991 method.SetDeclaringClass(new_class); 3992 } 3993 } 3994 3995 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u); 3996 for (auto& method : new_class->GetVirtualMethods(image_pointer_size_)) { 3997 if (method.GetDeclaringClass() == temp_class) { 3998 method.SetDeclaringClass(new_class); 3999 } 4000 } 4001 4002 // Make sure the remembered set and mod-union tables know that we updated some of the native 4003 // roots. 4004 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class); 4005} 4006 4007ClassTable* ClassLinker::InsertClassTableForClassLoader(mirror::ClassLoader* class_loader) { 4008 if (class_loader == nullptr) { 4009 return &boot_class_table_; 4010 } 4011 ClassTable* class_table = class_loader->GetClassTable(); 4012 if (class_table == nullptr) { 4013 class_table = new ClassTable; 4014 class_loaders_.push_back(class_loader); 4015 // Don't already have a class table, add it to the class loader. 4016 class_loader->SetClassTable(class_table); 4017 } 4018 return class_table; 4019} 4020 4021ClassTable* ClassLinker::ClassTableForClassLoader(mirror::ClassLoader* class_loader) { 4022 return class_loader == nullptr ? &boot_class_table_ : class_loader->GetClassTable(); 4023} 4024 4025bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass, 4026 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 4027 MutableHandle<mirror::Class>* h_new_class_out) { 4028 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 4029 4030 if (!LinkSuperClass(klass)) { 4031 return false; 4032 } 4033 ArtMethod* imt[mirror::Class::kImtSize]; 4034 std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod()); 4035 if (!LinkMethods(self, klass, interfaces, imt)) { 4036 return false; 4037 } 4038 if (!LinkInstanceFields(self, klass)) { 4039 return false; 4040 } 4041 size_t class_size; 4042 if (!LinkStaticFields(self, klass, &class_size)) { 4043 return false; 4044 } 4045 CreateReferenceInstanceOffsets(klass); 4046 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 4047 4048 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) { 4049 // We don't need to retire this class as it has no embedded tables or it was created the 4050 // correct size during class linker initialization. 4051 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get()); 4052 4053 if (klass->ShouldHaveEmbeddedImtAndVTable()) { 4054 klass->PopulateEmbeddedImtAndVTable(imt, image_pointer_size_); 4055 } 4056 4057 // This will notify waiters on klass that saw the not yet resolved 4058 // class in the class_table_ during EnsureResolved. 4059 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self); 4060 h_new_class_out->Assign(klass.Get()); 4061 } else { 4062 CHECK(!klass->IsResolved()); 4063 // Retire the temporary class and create the correctly sized resolved class. 4064 StackHandleScope<1> hs(self); 4065 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_)); 4066 // Set arrays to null since we don't want to have multiple classes with the same ArtField or 4067 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC 4068 // may not see any references to the target space and clean the card for a class if another 4069 // class had the same array pointer. 4070 klass->SetDirectMethodsPtrUnchecked(nullptr); 4071 klass->SetVirtualMethodsPtr(nullptr); 4072 klass->SetSFieldsPtrUnchecked(nullptr); 4073 klass->SetIFieldsPtrUnchecked(nullptr); 4074 if (UNLIKELY(h_new_class.Get() == nullptr)) { 4075 self->AssertPendingOOMException(); 4076 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self); 4077 return false; 4078 } 4079 4080 CHECK_EQ(h_new_class->GetClassSize(), class_size); 4081 ObjectLock<mirror::Class> lock(self, h_new_class); 4082 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get()); 4083 4084 { 4085 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 4086 mirror::ClassLoader* const class_loader = h_new_class.Get()->GetClassLoader(); 4087 ClassTable* const table = InsertClassTableForClassLoader(class_loader); 4088 mirror::Class* existing = table->UpdateClass(descriptor, h_new_class.Get(), 4089 ComputeModifiedUtf8Hash(descriptor)); 4090 CHECK_EQ(existing, klass.Get()); 4091 if (kIsDebugBuild && class_loader == nullptr && dex_cache_image_class_lookup_required_) { 4092 // Check a class loaded with the system class loader matches one in the image if the class 4093 // is in the image. 4094 mirror::Class* const image_class = LookupClassFromImage(descriptor); 4095 if (image_class != nullptr) { 4096 CHECK_EQ(klass.Get(), existing) << descriptor; 4097 } 4098 } 4099 if (log_new_class_table_roots_) { 4100 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get())); 4101 } 4102 } 4103 4104 // This will notify waiters on temp class that saw the not yet resolved class in the 4105 // class_table_ during EnsureResolved. 4106 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self); 4107 4108 CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving); 4109 // This will notify waiters on new_class that saw the not yet resolved 4110 // class in the class_table_ during EnsureResolved. 4111 mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self); 4112 // Return the new class. 4113 h_new_class_out->Assign(h_new_class.Get()); 4114 } 4115 return true; 4116} 4117 4118static void CountMethodsAndFields(ClassDataItemIterator& dex_data, 4119 size_t* virtual_methods, 4120 size_t* direct_methods, 4121 size_t* static_fields, 4122 size_t* instance_fields) { 4123 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0; 4124 4125 while (dex_data.HasNextStaticField()) { 4126 dex_data.Next(); 4127 (*static_fields)++; 4128 } 4129 while (dex_data.HasNextInstanceField()) { 4130 dex_data.Next(); 4131 (*instance_fields)++; 4132 } 4133 while (dex_data.HasNextDirectMethod()) { 4134 (*direct_methods)++; 4135 dex_data.Next(); 4136 } 4137 while (dex_data.HasNextVirtualMethod()) { 4138 (*virtual_methods)++; 4139 dex_data.Next(); 4140 } 4141 DCHECK(!dex_data.HasNext()); 4142} 4143 4144static void DumpClass(std::ostream& os, 4145 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def, 4146 const char* suffix) { 4147 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def)); 4148 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n"; 4149 os << " Static fields:\n"; 4150 while (dex_data.HasNextStaticField()) { 4151 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex()); 4152 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n"; 4153 dex_data.Next(); 4154 } 4155 os << " Instance fields:\n"; 4156 while (dex_data.HasNextInstanceField()) { 4157 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex()); 4158 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n"; 4159 dex_data.Next(); 4160 } 4161 os << " Direct methods:\n"; 4162 while (dex_data.HasNextDirectMethod()) { 4163 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex()); 4164 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n"; 4165 dex_data.Next(); 4166 } 4167 os << " Virtual methods:\n"; 4168 while (dex_data.HasNextVirtualMethod()) { 4169 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex()); 4170 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n"; 4171 dex_data.Next(); 4172 } 4173} 4174 4175static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1, 4176 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) { 4177 std::ostringstream os; 4178 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)"); 4179 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)"); 4180 return os.str(); 4181} 4182 4183 4184// Very simple structural check on whether the classes match. Only compares the number of 4185// methods and fields. 4186static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1, 4187 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2, 4188 std::string* error_msg) { 4189 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1)); 4190 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2)); 4191 4192 // Counters for current dex file. 4193 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1; 4194 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1, 4195 &dex_instance_fields1); 4196 // Counters for compile-time dex file. 4197 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2; 4198 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2, 4199 &dex_instance_fields2); 4200 4201 if (dex_virtual_methods1 != dex_virtual_methods2) { 4202 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2); 4203 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1, 4204 dex_virtual_methods2, class_dump.c_str()); 4205 return false; 4206 } 4207 if (dex_direct_methods1 != dex_direct_methods2) { 4208 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2); 4209 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1, 4210 dex_direct_methods2, class_dump.c_str()); 4211 return false; 4212 } 4213 if (dex_static_fields1 != dex_static_fields2) { 4214 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2); 4215 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1, 4216 dex_static_fields2, class_dump.c_str()); 4217 return false; 4218 } 4219 if (dex_instance_fields1 != dex_instance_fields2) { 4220 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2); 4221 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1, 4222 dex_instance_fields2, class_dump.c_str()); 4223 return false; 4224 } 4225 4226 return true; 4227} 4228 4229// Checks whether a the super-class changed from what we had at compile-time. This would 4230// invalidate quickening. 4231static bool CheckSuperClassChange(Handle<mirror::Class> klass, 4232 const DexFile& dex_file, 4233 const DexFile::ClassDef& class_def, 4234 mirror::Class* super_class) 4235 SHARED_REQUIRES(Locks::mutator_lock_) { 4236 // Check for unexpected changes in the superclass. 4237 // Quick check 1) is the super_class class-loader the boot class loader? This always has 4238 // precedence. 4239 if (super_class->GetClassLoader() != nullptr && 4240 // Quick check 2) different dex cache? Breaks can only occur for different dex files, 4241 // which is implied by different dex cache. 4242 klass->GetDexCache() != super_class->GetDexCache()) { 4243 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a 4244 // definition for the super-class, and (b) the files are in separate oat files. The oat files 4245 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files. 4246 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile(); 4247 const OatFile* class_oat_file = nullptr; 4248 if (class_oat_dex_file != nullptr) { 4249 class_oat_file = class_oat_dex_file->GetOatFile(); 4250 } 4251 4252 if (class_oat_file != nullptr) { 4253 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile(); 4254 const OatFile* loaded_super_oat_file = nullptr; 4255 if (loaded_super_oat_dex_file != nullptr) { 4256 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile(); 4257 } 4258 4259 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) { 4260 // Now check (a). 4261 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_); 4262 if (super_class_def != nullptr) { 4263 // Uh-oh, we found something. Do our check. 4264 std::string error_msg; 4265 if (!SimpleStructuralCheck(dex_file, *super_class_def, 4266 super_class->GetDexFile(), *super_class->GetClassDef(), 4267 &error_msg)) { 4268 // Print a warning to the log. This exception might be caught, e.g., as common in test 4269 // drivers. When the class is later tried to be used, we re-throw a new instance, as we 4270 // only save the type of the exception. 4271 LOG(WARNING) << "Incompatible structural change detected: " << 4272 StringPrintf( 4273 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s", 4274 PrettyType(super_class_def->class_idx_, dex_file).c_str(), 4275 class_oat_file->GetLocation().c_str(), 4276 loaded_super_oat_file->GetLocation().c_str(), 4277 error_msg.c_str()); 4278 ThrowIncompatibleClassChangeError(klass.Get(), 4279 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s", 4280 PrettyType(super_class_def->class_idx_, dex_file).c_str(), 4281 class_oat_file->GetLocation().c_str(), 4282 loaded_super_oat_file->GetLocation().c_str(), 4283 error_msg.c_str()); 4284 return false; 4285 } 4286 } 4287 } 4288 } 4289 } 4290 return true; 4291} 4292 4293bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) { 4294 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus()); 4295 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex()); 4296 uint16_t super_class_idx = class_def.superclass_idx_; 4297 if (super_class_idx != DexFile::kDexNoIndex16) { 4298 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get()); 4299 if (super_class == nullptr) { 4300 DCHECK(Thread::Current()->IsExceptionPending()); 4301 return false; 4302 } 4303 // Verify 4304 if (!klass->CanAccess(super_class)) { 4305 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible", 4306 PrettyDescriptor(super_class).c_str(), 4307 PrettyDescriptor(klass.Get()).c_str()); 4308 return false; 4309 } 4310 CHECK(super_class->IsResolved()); 4311 klass->SetSuperClass(super_class); 4312 4313 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) { 4314 DCHECK(Thread::Current()->IsExceptionPending()); 4315 return false; 4316 } 4317 } 4318 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def); 4319 if (interfaces != nullptr) { 4320 for (size_t i = 0; i < interfaces->Size(); i++) { 4321 uint16_t idx = interfaces->GetTypeItem(i).type_idx_; 4322 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get()); 4323 if (interface == nullptr) { 4324 DCHECK(Thread::Current()->IsExceptionPending()); 4325 return false; 4326 } 4327 // Verify 4328 if (!klass->CanAccess(interface)) { 4329 // TODO: the RI seemed to ignore this in my testing. 4330 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible", 4331 PrettyDescriptor(interface).c_str(), 4332 PrettyDescriptor(klass.Get()).c_str()); 4333 return false; 4334 } 4335 } 4336 } 4337 // Mark the class as loaded. 4338 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr); 4339 return true; 4340} 4341 4342bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) { 4343 CHECK(!klass->IsPrimitive()); 4344 mirror::Class* super = klass->GetSuperClass(); 4345 if (klass.Get() == GetClassRoot(kJavaLangObject)) { 4346 if (super != nullptr) { 4347 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass"); 4348 return false; 4349 } 4350 return true; 4351 } 4352 if (super == nullptr) { 4353 ThrowLinkageError(klass.Get(), "No superclass defined for class %s", 4354 PrettyDescriptor(klass.Get()).c_str()); 4355 return false; 4356 } 4357 // Verify 4358 if (super->IsFinal() || super->IsInterface()) { 4359 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s", 4360 PrettyDescriptor(super).c_str(), 4361 PrettyDescriptor(klass.Get()).c_str(), 4362 super->IsFinal() ? "declared final" : "an interface"); 4363 return false; 4364 } 4365 if (!klass->CanAccess(super)) { 4366 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s", 4367 PrettyDescriptor(super).c_str(), 4368 PrettyDescriptor(klass.Get()).c_str()); 4369 return false; 4370 } 4371 4372 // Inherit kAccClassIsFinalizable from the superclass in case this 4373 // class doesn't override finalize. 4374 if (super->IsFinalizable()) { 4375 klass->SetFinalizable(); 4376 } 4377 4378 // Inherit reference flags (if any) from the superclass. 4379 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask); 4380 if (reference_flags != 0) { 4381 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags); 4382 } 4383 // Disallow custom direct subclasses of java.lang.ref.Reference. 4384 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) { 4385 ThrowLinkageError(klass.Get(), 4386 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed", 4387 PrettyDescriptor(klass.Get()).c_str()); 4388 return false; 4389 } 4390 4391 if (kIsDebugBuild) { 4392 // Ensure super classes are fully resolved prior to resolving fields.. 4393 while (super != nullptr) { 4394 CHECK(super->IsResolved()); 4395 super = super->GetSuperClass(); 4396 } 4397 } 4398 return true; 4399} 4400 4401// Populate the class vtable and itable. Compute return type indices. 4402bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass, 4403 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 4404 ArtMethod** out_imt) { 4405 self->AllowThreadSuspension(); 4406 if (klass->IsInterface()) { 4407 // No vtable. 4408 size_t count = klass->NumVirtualMethods(); 4409 if (!IsUint<16>(count)) { 4410 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count); 4411 return false; 4412 } 4413 for (size_t i = 0; i < count; ++i) { 4414 klass->GetVirtualMethodDuringLinking(i, image_pointer_size_)->SetMethodIndex(i); 4415 } 4416 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first. 4417 return false; 4418 } 4419 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last. 4420} 4421 4422// Comparator for name and signature of a method, used in finding overriding methods. Implementation 4423// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex 4424// caches in the implementation below. 4425class MethodNameAndSignatureComparator FINAL : public ValueObject { 4426 public: 4427 explicit MethodNameAndSignatureComparator(ArtMethod* method) 4428 SHARED_REQUIRES(Locks::mutator_lock_) : 4429 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())), 4430 name_(nullptr), name_len_(0) { 4431 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method); 4432 } 4433 4434 const char* GetName() { 4435 if (name_ == nullptr) { 4436 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_); 4437 } 4438 return name_; 4439 } 4440 4441 bool HasSameNameAndSignature(ArtMethod* other) 4442 SHARED_REQUIRES(Locks::mutator_lock_) { 4443 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other); 4444 const DexFile* other_dex_file = other->GetDexFile(); 4445 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex()); 4446 if (dex_file_ == other_dex_file) { 4447 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_; 4448 } 4449 GetName(); // Only used to make sure its calculated. 4450 uint32_t other_name_len; 4451 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_, 4452 &other_name_len); 4453 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) { 4454 return false; 4455 } 4456 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid); 4457 } 4458 4459 private: 4460 // Dex file for the method to compare against. 4461 const DexFile* const dex_file_; 4462 // MethodId for the method to compare against. 4463 const DexFile::MethodId* const mid_; 4464 // Lazily computed name from the dex file's strings. 4465 const char* name_; 4466 // Lazily computed name length. 4467 uint32_t name_len_; 4468}; 4469 4470class LinkVirtualHashTable { 4471 public: 4472 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table, 4473 size_t image_pointer_size) 4474 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table), 4475 image_pointer_size_(image_pointer_size) { 4476 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_); 4477 } 4478 void Add(uint32_t virtual_method_index) SHARED_REQUIRES(Locks::mutator_lock_) { 4479 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking( 4480 virtual_method_index, image_pointer_size_); 4481 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName(); 4482 uint32_t hash = ComputeModifiedUtf8Hash(name); 4483 uint32_t index = hash % hash_size_; 4484 // Linear probe until we have an empty slot. 4485 while (hash_table_[index] != invalid_index_) { 4486 if (++index == hash_size_) { 4487 index = 0; 4488 } 4489 } 4490 hash_table_[index] = virtual_method_index; 4491 } 4492 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator) 4493 SHARED_REQUIRES(Locks::mutator_lock_) { 4494 const char* name = comparator->GetName(); 4495 uint32_t hash = ComputeModifiedUtf8Hash(name); 4496 size_t index = hash % hash_size_; 4497 while (true) { 4498 const uint32_t value = hash_table_[index]; 4499 // Since linear probe makes continuous blocks, hitting an invalid index means we are done 4500 // the block and can safely assume not found. 4501 if (value == invalid_index_) { 4502 break; 4503 } 4504 if (value != removed_index_) { // This signifies not already overriden. 4505 ArtMethod* virtual_method = 4506 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_); 4507 if (comparator->HasSameNameAndSignature( 4508 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) { 4509 hash_table_[index] = removed_index_; 4510 return value; 4511 } 4512 } 4513 if (++index == hash_size_) { 4514 index = 0; 4515 } 4516 } 4517 return GetNotFoundIndex(); 4518 } 4519 static uint32_t GetNotFoundIndex() { 4520 return invalid_index_; 4521 } 4522 4523 private: 4524 static const uint32_t invalid_index_; 4525 static const uint32_t removed_index_; 4526 4527 Handle<mirror::Class> klass_; 4528 const size_t hash_size_; 4529 uint32_t* const hash_table_; 4530 const size_t image_pointer_size_; 4531}; 4532 4533const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max(); 4534const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1; 4535 4536bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) { 4537 const size_t num_virtual_methods = klass->NumVirtualMethods(); 4538 if (klass->HasSuperClass()) { 4539 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength(); 4540 const size_t max_count = num_virtual_methods + super_vtable_length; 4541 StackHandleScope<2> hs(self); 4542 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass())); 4543 MutableHandle<mirror::PointerArray> vtable; 4544 if (super_class->ShouldHaveEmbeddedImtAndVTable()) { 4545 vtable = hs.NewHandle(AllocPointerArray(self, max_count)); 4546 if (UNLIKELY(vtable.Get() == nullptr)) { 4547 self->AssertPendingOOMException(); 4548 return false; 4549 } 4550 for (size_t i = 0; i < super_vtable_length; i++) { 4551 vtable->SetElementPtrSize( 4552 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_); 4553 } 4554 if (num_virtual_methods == 0) { 4555 klass->SetVTable(vtable.Get()); 4556 return true; 4557 } 4558 } else { 4559 auto* super_vtable = super_class->GetVTable(); 4560 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get()); 4561 if (num_virtual_methods == 0) { 4562 klass->SetVTable(super_vtable); 4563 return true; 4564 } 4565 vtable = hs.NewHandle(down_cast<mirror::PointerArray*>( 4566 super_vtable->CopyOf(self, max_count))); 4567 if (UNLIKELY(vtable.Get() == nullptr)) { 4568 self->AssertPendingOOMException(); 4569 return false; 4570 } 4571 } 4572 // How the algorithm works: 4573 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash 4574 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual 4575 // method which has not been matched to a vtable method, and j if the virtual method at the 4576 // index overrode the super virtual method at index j. 4577 // 2. Loop through super virtual methods, if they overwrite, update hash table to j 4578 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing 4579 // the need for the initial vtable which we later shrink back down). 4580 // 3. Add non overridden methods to the end of the vtable. 4581 static constexpr size_t kMaxStackHash = 250; 4582 const size_t hash_table_size = num_virtual_methods * 3; 4583 uint32_t* hash_table_ptr; 4584 std::unique_ptr<uint32_t[]> hash_heap_storage; 4585 if (hash_table_size <= kMaxStackHash) { 4586 hash_table_ptr = reinterpret_cast<uint32_t*>( 4587 alloca(hash_table_size * sizeof(*hash_table_ptr))); 4588 } else { 4589 hash_heap_storage.reset(new uint32_t[hash_table_size]); 4590 hash_table_ptr = hash_heap_storage.get(); 4591 } 4592 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_); 4593 // Add virtual methods to the hash table. 4594 for (size_t i = 0; i < num_virtual_methods; ++i) { 4595 DCHECK(klass->GetVirtualMethodDuringLinking( 4596 i, image_pointer_size_)->GetDeclaringClass() != nullptr); 4597 hash_table.Add(i); 4598 } 4599 // Loop through each super vtable method and see if they are overriden by a method we added to 4600 // the hash table. 4601 for (size_t j = 0; j < super_vtable_length; ++j) { 4602 // Search the hash table to see if we are overidden by any method. 4603 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_); 4604 MethodNameAndSignatureComparator super_method_name_comparator( 4605 super_method->GetInterfaceMethodIfProxy(image_pointer_size_)); 4606 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator); 4607 if (hash_index != hash_table.GetNotFoundIndex()) { 4608 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking( 4609 hash_index, image_pointer_size_); 4610 if (klass->CanAccessMember(super_method->GetDeclaringClass(), 4611 super_method->GetAccessFlags())) { 4612 if (super_method->IsFinal()) { 4613 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s", 4614 PrettyMethod(virtual_method).c_str(), 4615 super_method->GetDeclaringClassDescriptor()); 4616 return false; 4617 } 4618 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_); 4619 virtual_method->SetMethodIndex(j); 4620 } else { 4621 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method) 4622 << " would have incorrectly overridden the package-private method in " 4623 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor()); 4624 } 4625 } 4626 } 4627 // Add the non overridden methods at the end. 4628 size_t actual_count = super_vtable_length; 4629 for (size_t i = 0; i < num_virtual_methods; ++i) { 4630 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_); 4631 size_t method_idx = local_method->GetMethodIndexDuringLinking(); 4632 if (method_idx < super_vtable_length && 4633 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) { 4634 continue; 4635 } 4636 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_); 4637 local_method->SetMethodIndex(actual_count); 4638 ++actual_count; 4639 } 4640 if (!IsUint<16>(actual_count)) { 4641 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count); 4642 return false; 4643 } 4644 // Shrink vtable if possible 4645 CHECK_LE(actual_count, max_count); 4646 if (actual_count < max_count) { 4647 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count))); 4648 if (UNLIKELY(vtable.Get() == nullptr)) { 4649 self->AssertPendingOOMException(); 4650 return false; 4651 } 4652 } 4653 klass->SetVTable(vtable.Get()); 4654 } else { 4655 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject)); 4656 if (!IsUint<16>(num_virtual_methods)) { 4657 ThrowClassFormatError(klass.Get(), "Too many methods: %d", 4658 static_cast<int>(num_virtual_methods)); 4659 return false; 4660 } 4661 auto* vtable = AllocPointerArray(self, num_virtual_methods); 4662 if (UNLIKELY(vtable == nullptr)) { 4663 self->AssertPendingOOMException(); 4664 return false; 4665 } 4666 for (size_t i = 0; i < num_virtual_methods; ++i) { 4667 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_); 4668 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_); 4669 virtual_method->SetMethodIndex(i & 0xFFFF); 4670 } 4671 klass->SetVTable(vtable); 4672 } 4673 return true; 4674} 4675 4676bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass, 4677 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 4678 ArtMethod** out_imt) { 4679 StackHandleScope<3> hs(self); 4680 Runtime* const runtime = Runtime::Current(); 4681 const bool has_superclass = klass->HasSuperClass(); 4682 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U; 4683 const bool have_interfaces = interfaces.Get() != nullptr; 4684 const size_t num_interfaces = 4685 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces(); 4686 const size_t method_size = ArtMethod::ObjectSize(image_pointer_size_); 4687 if (num_interfaces == 0) { 4688 if (super_ifcount == 0) { 4689 // Class implements no interfaces. 4690 DCHECK_EQ(klass->GetIfTableCount(), 0); 4691 DCHECK(klass->GetIfTable() == nullptr); 4692 return true; 4693 } 4694 // Class implements same interfaces as parent, are any of these not marker interfaces? 4695 bool has_non_marker_interface = false; 4696 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 4697 for (size_t i = 0; i < super_ifcount; ++i) { 4698 if (super_iftable->GetMethodArrayCount(i) > 0) { 4699 has_non_marker_interface = true; 4700 break; 4701 } 4702 } 4703 // Class just inherits marker interfaces from parent so recycle parent's iftable. 4704 if (!has_non_marker_interface) { 4705 klass->SetIfTable(super_iftable); 4706 return true; 4707 } 4708 } 4709 size_t ifcount = super_ifcount + num_interfaces; 4710 for (size_t i = 0; i < num_interfaces; i++) { 4711 mirror::Class* interface = have_interfaces ? 4712 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i); 4713 DCHECK(interface != nullptr); 4714 if (UNLIKELY(!interface->IsInterface())) { 4715 std::string temp; 4716 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s", 4717 PrettyDescriptor(klass.Get()).c_str(), 4718 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str()); 4719 return false; 4720 } 4721 ifcount += interface->GetIfTableCount(); 4722 } 4723 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount))); 4724 if (UNLIKELY(iftable.Get() == nullptr)) { 4725 self->AssertPendingOOMException(); 4726 return false; 4727 } 4728 if (super_ifcount != 0) { 4729 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 4730 for (size_t i = 0; i < super_ifcount; i++) { 4731 mirror::Class* super_interface = super_iftable->GetInterface(i); 4732 iftable->SetInterface(i, super_interface); 4733 } 4734 } 4735 self->AllowThreadSuspension(); 4736 // Flatten the interface inheritance hierarchy. 4737 size_t idx = super_ifcount; 4738 for (size_t i = 0; i < num_interfaces; i++) { 4739 mirror::Class* interface = have_interfaces ? interfaces->Get(i) : 4740 mirror::Class::GetDirectInterface(self, klass, i); 4741 // Check if interface is already in iftable 4742 bool duplicate = false; 4743 for (size_t j = 0; j < idx; j++) { 4744 mirror::Class* existing_interface = iftable->GetInterface(j); 4745 if (existing_interface == interface) { 4746 duplicate = true; 4747 break; 4748 } 4749 } 4750 if (!duplicate) { 4751 // Add this non-duplicate interface. 4752 iftable->SetInterface(idx++, interface); 4753 // Add this interface's non-duplicate super-interfaces. 4754 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) { 4755 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j); 4756 bool super_duplicate = false; 4757 for (size_t k = 0; k < idx; k++) { 4758 mirror::Class* existing_interface = iftable->GetInterface(k); 4759 if (existing_interface == super_interface) { 4760 super_duplicate = true; 4761 break; 4762 } 4763 } 4764 if (!super_duplicate) { 4765 iftable->SetInterface(idx++, super_interface); 4766 } 4767 } 4768 } 4769 } 4770 self->AllowThreadSuspension(); 4771 // Shrink iftable in case duplicates were found 4772 if (idx < ifcount) { 4773 DCHECK_NE(num_interfaces, 0U); 4774 iftable.Assign(down_cast<mirror::IfTable*>( 4775 iftable->CopyOf(self, idx * mirror::IfTable::kMax))); 4776 if (UNLIKELY(iftable.Get() == nullptr)) { 4777 self->AssertPendingOOMException(); 4778 return false; 4779 } 4780 ifcount = idx; 4781 } else { 4782 DCHECK_EQ(idx, ifcount); 4783 } 4784 klass->SetIfTable(iftable.Get()); 4785 // If we're an interface, we don't need the vtable pointers, so we're done. 4786 if (klass->IsInterface()) { 4787 return true; 4788 } 4789 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create 4790 // the virtual methods array. 4791 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array 4792 // during cross compilation. 4793 // Use the linear alloc pool since this one is in the low 4gb for the compiler. 4794 ArenaStack stack(runtime->GetLinearAlloc()->GetArenaPool()); 4795 ScopedArenaAllocator allocator(&stack); 4796 ScopedArenaVector<ArtMethod*> miranda_methods(allocator.Adapter()); 4797 4798 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking())); 4799 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod(); 4800 ArtMethod* const conflict_method = runtime->GetImtConflictMethod(); 4801 // Copy the IMT from the super class if possible. 4802 bool extend_super_iftable = false; 4803 if (has_superclass) { 4804 mirror::Class* super_class = klass->GetSuperClass(); 4805 extend_super_iftable = true; 4806 if (super_class->ShouldHaveEmbeddedImtAndVTable()) { 4807 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) { 4808 out_imt[i] = super_class->GetEmbeddedImTableEntry(i, image_pointer_size_); 4809 } 4810 } else { 4811 // No imt in the super class, need to reconstruct from the iftable. 4812 mirror::IfTable* if_table = super_class->GetIfTable(); 4813 const size_t length = super_class->GetIfTableCount(); 4814 for (size_t i = 0; i < length; ++i) { 4815 mirror::Class* interface = iftable->GetInterface(i); 4816 const size_t num_virtuals = interface->NumVirtualMethods(); 4817 const size_t method_array_count = if_table->GetMethodArrayCount(i); 4818 DCHECK_EQ(num_virtuals, method_array_count); 4819 if (method_array_count == 0) { 4820 continue; 4821 } 4822 auto* method_array = if_table->GetMethodArray(i); 4823 for (size_t j = 0; j < num_virtuals; ++j) { 4824 auto method = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_); 4825 DCHECK(method != nullptr) << PrettyClass(super_class); 4826 if (method->IsMiranda()) { 4827 continue; 4828 } 4829 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_); 4830 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize; 4831 auto** imt_ref = &out_imt[imt_index]; 4832 if (*imt_ref == unimplemented_method) { 4833 *imt_ref = method; 4834 } else if (*imt_ref != conflict_method) { 4835 *imt_ref = conflict_method; 4836 } 4837 } 4838 } 4839 } 4840 } 4841 // Allocate method arrays before since we don't want miss visiting miranda method roots due to 4842 // thread suspension. 4843 for (size_t i = 0; i < ifcount; ++i) { 4844 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods(); 4845 if (num_methods > 0) { 4846 const bool is_super = i < super_ifcount; 4847 const bool super_interface = is_super && extend_super_iftable; 4848 mirror::PointerArray* method_array; 4849 if (super_interface) { 4850 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable(); 4851 DCHECK(if_table != nullptr); 4852 DCHECK(if_table->GetMethodArray(i) != nullptr); 4853 // If we are working on a super interface, try extending the existing method array. 4854 method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self)); 4855 } else { 4856 method_array = AllocPointerArray(self, num_methods); 4857 } 4858 if (UNLIKELY(method_array == nullptr)) { 4859 self->AssertPendingOOMException(); 4860 return false; 4861 } 4862 iftable->SetMethodArray(i, method_array); 4863 } 4864 } 4865 4866 auto* old_cause = self->StartAssertNoThreadSuspension( 4867 "Copying ArtMethods for LinkInterfaceMethods"); 4868 for (size_t i = 0; i < ifcount; ++i) { 4869 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods(); 4870 if (num_methods > 0) { 4871 StackHandleScope<2> hs2(self); 4872 const bool is_super = i < super_ifcount; 4873 const bool super_interface = is_super && extend_super_iftable; 4874 auto method_array(hs2.NewHandle(iftable->GetMethodArray(i))); 4875 4876 LengthPrefixedArray<ArtMethod>* input_virtual_methods = nullptr; 4877 Handle<mirror::PointerArray> input_vtable_array = NullHandle<mirror::PointerArray>(); 4878 int32_t input_array_length = 0; 4879 if (super_interface) { 4880 // We are overwriting a super class interface, try to only virtual methods instead of the 4881 // whole vtable. 4882 input_virtual_methods = klass->GetVirtualMethodsPtr(); 4883 input_array_length = klass->NumVirtualMethods(); 4884 } else { 4885 // A new interface, we need the whole vtable in case a new interface method is implemented 4886 // in the whole superclass. 4887 input_vtable_array = vtable; 4888 input_array_length = input_vtable_array->GetLength(); 4889 } 4890 if (input_array_length == 0) { 4891 // If the added virtual methods is empty, do nothing. 4892 DCHECK(super_interface); 4893 continue; 4894 } 4895 for (size_t j = 0; j < num_methods; ++j) { 4896 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod( 4897 j, image_pointer_size_); 4898 MethodNameAndSignatureComparator interface_name_comparator( 4899 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_)); 4900 int32_t k; 4901 // For each method listed in the interface's method list, find the 4902 // matching method in our class's method list. We want to favor the 4903 // subclass over the superclass, which just requires walking 4904 // back from the end of the vtable. (This only matters if the 4905 // superclass defines a private method and this class redefines 4906 // it -- otherwise it would use the same vtable slot. In .dex files 4907 // those don't end up in the virtual method table, so it shouldn't 4908 // matter which direction we go. We walk it backward anyway.) 4909 for (k = input_array_length - 1; k >= 0; --k) { 4910 ArtMethod* vtable_method = input_virtual_methods != nullptr ? 4911 &input_virtual_methods->At(k, method_size) : 4912 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_); 4913 ArtMethod* vtable_method_for_name_comparison = 4914 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_); 4915 if (interface_name_comparator.HasSameNameAndSignature( 4916 vtable_method_for_name_comparison)) { 4917 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) { 4918 // Must do EndAssertNoThreadSuspension before throw since the throw can cause 4919 // allocations. 4920 self->EndAssertNoThreadSuspension(old_cause); 4921 ThrowIllegalAccessError(klass.Get(), 4922 "Method '%s' implementing interface method '%s' is not public", 4923 PrettyMethod(vtable_method).c_str(), PrettyMethod(interface_method).c_str()); 4924 return false; 4925 } 4926 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_); 4927 // Place method in imt if entry is empty, place conflict otherwise. 4928 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize; 4929 auto** imt_ref = &out_imt[imt_index]; 4930 if (*imt_ref == unimplemented_method) { 4931 *imt_ref = vtable_method; 4932 } else if (*imt_ref != conflict_method) { 4933 // If we are not a conflict and we have the same signature and name as the imt entry, 4934 // it must be that we overwrote a superclass vtable entry. 4935 MethodNameAndSignatureComparator imt_comparator( 4936 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_)); 4937 *imt_ref = imt_comparator.HasSameNameAndSignature(vtable_method_for_name_comparison) ? 4938 vtable_method : conflict_method; 4939 } 4940 break; 4941 } 4942 } 4943 if (k < 0 && !super_interface) { 4944 ArtMethod* miranda_method = nullptr; 4945 for (auto& mir_method : miranda_methods) { 4946 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) { 4947 miranda_method = mir_method; 4948 break; 4949 } 4950 } 4951 if (miranda_method == nullptr) { 4952 miranda_method = reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size)); 4953 CHECK(miranda_method != nullptr); 4954 // Point the interface table at a phantom slot. 4955 new(miranda_method) ArtMethod(*interface_method, image_pointer_size_); 4956 miranda_methods.push_back(miranda_method); 4957 } 4958 method_array->SetElementPtrSize(j, miranda_method, image_pointer_size_); 4959 } 4960 } 4961 } 4962 } 4963 if (!miranda_methods.empty()) { 4964 const size_t old_method_count = klass->NumVirtualMethods(); 4965 const size_t new_method_count = old_method_count + miranda_methods.size(); 4966 // Attempt to realloc to save RAM if possible. 4967 LengthPrefixedArray<ArtMethod>* old_virtuals = klass->GetVirtualMethodsPtr(); 4968 // The Realloced virtual methods aren't visiblef from the class roots, so there is no issue 4969 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the 4970 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since 4971 // CopyFrom has internal read barriers. 4972 const size_t old_size = old_virtuals != nullptr ? 4973 LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count, method_size) : 0u; 4974 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count, 4975 method_size); 4976 auto* virtuals = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>( 4977 runtime->GetLinearAlloc()->Realloc(self, old_virtuals, old_size, new_size)); 4978 if (UNLIKELY(virtuals == nullptr)) { 4979 self->AssertPendingOOMException(); 4980 self->EndAssertNoThreadSuspension(old_cause); 4981 return false; 4982 } 4983 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table(allocator.Adapter()); 4984 if (virtuals != old_virtuals) { 4985 // Maps from heap allocated miranda method to linear alloc miranda method. 4986 StrideIterator<ArtMethod> out = virtuals->Begin(method_size); 4987 // Copy over the old methods + miranda methods. 4988 for (auto& m : klass->GetVirtualMethods(image_pointer_size_)) { 4989 move_table.emplace(&m, &*out); 4990 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read 4991 // barriers when it copies. 4992 out->CopyFrom(&m, image_pointer_size_); 4993 ++out; 4994 } 4995 } 4996 StrideIterator<ArtMethod> out(virtuals->Begin(method_size) + old_method_count); 4997 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and 4998 // we want the roots of the miranda methods to get visited. 4999 for (ArtMethod* mir_method : miranda_methods) { 5000 out->CopyFrom(mir_method, image_pointer_size_); 5001 out->SetAccessFlags(out->GetAccessFlags() | kAccMiranda); 5002 move_table.emplace(mir_method, &*out); 5003 ++out; 5004 } 5005 virtuals->SetLength(new_method_count); 5006 UpdateClassVirtualMethods(klass.Get(), virtuals); 5007 // Done copying methods, they are all roots in the class now, so we can end the no thread 5008 // suspension assert. 5009 self->EndAssertNoThreadSuspension(old_cause); 5010 5011 const size_t old_vtable_count = vtable->GetLength(); 5012 const size_t new_vtable_count = old_vtable_count + miranda_methods.size(); 5013 miranda_methods.clear(); 5014 vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, new_vtable_count))); 5015 if (UNLIKELY(vtable.Get() == nullptr)) { 5016 self->AssertPendingOOMException(); 5017 return false; 5018 } 5019 out = StrideIterator<ArtMethod>(virtuals->Begin(method_size) + old_method_count); 5020 size_t vtable_pos = old_vtable_count; 5021 for (size_t i = old_method_count; i < new_method_count; ++i) { 5022 // Leave the declaring class alone as type indices are relative to it 5023 out->SetMethodIndex(0xFFFF & vtable_pos); 5024 vtable->SetElementPtrSize(vtable_pos, &*out, image_pointer_size_); 5025 ++out; 5026 ++vtable_pos; 5027 } 5028 CHECK_EQ(vtable_pos, new_vtable_count); 5029 // Update old vtable methods. 5030 for (size_t i = 0; i < old_vtable_count; ++i) { 5031 auto* m = vtable->GetElementPtrSize<ArtMethod*>(i, image_pointer_size_); 5032 DCHECK(m != nullptr) << PrettyClass(klass.Get()); 5033 auto it = move_table.find(m); 5034 if (it != move_table.end()) { 5035 auto* new_m = it->second; 5036 DCHECK(new_m != nullptr) << PrettyClass(klass.Get()); 5037 vtable->SetElementPtrSize(i, new_m, image_pointer_size_); 5038 } 5039 } 5040 5041 klass->SetVTable(vtable.Get()); 5042 // Go fix up all the stale miranda pointers. 5043 for (size_t i = 0; i < ifcount; ++i) { 5044 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) { 5045 auto* method_array = iftable->GetMethodArray(i); 5046 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_); 5047 DCHECK(m != nullptr) << PrettyClass(klass.Get()); 5048 auto it = move_table.find(m); 5049 if (it != move_table.end()) { 5050 auto* new_m = it->second; 5051 DCHECK(new_m != nullptr) << PrettyClass(klass.Get()); 5052 method_array->SetElementPtrSize(j, new_m, image_pointer_size_); 5053 } 5054 } 5055 } 5056 // Fix up IMT in case it has any miranda methods in it. 5057 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) { 5058 auto it = move_table.find(out_imt[i]); 5059 if (it != move_table.end()) { 5060 out_imt[i] = it->second; 5061 } 5062 } 5063 // Check that there are no stale methods are in the dex cache array. 5064 if (kIsDebugBuild) { 5065 auto* resolved_methods = klass->GetDexCache()->GetResolvedMethods(); 5066 for (size_t i = 0, count = resolved_methods->GetLength(); i < count; ++i) { 5067 auto* m = resolved_methods->GetElementPtrSize<ArtMethod*>(i, image_pointer_size_); 5068 CHECK(move_table.find(m) == move_table.end()) << PrettyMethod(m); 5069 } 5070 } 5071 // Put some random garbage in old virtuals to help find stale pointers. 5072 if (virtuals != old_virtuals) { 5073 memset(old_virtuals, 0xFEu, old_size); 5074 } 5075 } else { 5076 self->EndAssertNoThreadSuspension(old_cause); 5077 } 5078 if (kIsDebugBuild) { 5079 auto* check_vtable = klass->GetVTableDuringLinking(); 5080 for (int i = 0; i < check_vtable->GetLength(); ++i) { 5081 CHECK(check_vtable->GetElementPtrSize<ArtMethod*>(i, image_pointer_size_) != nullptr); 5082 } 5083 } 5084 return true; 5085} 5086 5087bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) { 5088 CHECK(klass.Get() != nullptr); 5089 return LinkFields(self, klass, false, nullptr); 5090} 5091 5092bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) { 5093 CHECK(klass.Get() != nullptr); 5094 return LinkFields(self, klass, true, class_size); 5095} 5096 5097struct LinkFieldsComparator { 5098 explicit LinkFieldsComparator() SHARED_REQUIRES(Locks::mutator_lock_) { 5099 } 5100 // No thread safety analysis as will be called from STL. Checked lock held in constructor. 5101 bool operator()(ArtField* field1, ArtField* field2) 5102 NO_THREAD_SAFETY_ANALYSIS { 5103 // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit. 5104 Primitive::Type type1 = field1->GetTypeAsPrimitiveType(); 5105 Primitive::Type type2 = field2->GetTypeAsPrimitiveType(); 5106 if (type1 != type2) { 5107 if (type1 == Primitive::kPrimNot) { 5108 // Reference always goes first. 5109 return true; 5110 } 5111 if (type2 == Primitive::kPrimNot) { 5112 // Reference always goes first. 5113 return false; 5114 } 5115 size_t size1 = Primitive::ComponentSize(type1); 5116 size_t size2 = Primitive::ComponentSize(type2); 5117 if (size1 != size2) { 5118 // Larger primitive types go first. 5119 return size1 > size2; 5120 } 5121 // Primitive types differ but sizes match. Arbitrarily order by primitive type. 5122 return type1 < type2; 5123 } 5124 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted 5125 // by name and for equal names by type id index. 5126 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes. 5127 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex(); 5128 } 5129}; 5130 5131bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static, 5132 size_t* class_size) { 5133 self->AllowThreadSuspension(); 5134 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields(); 5135 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() : 5136 klass->GetIFieldsPtr(); 5137 5138 // Initialize field_offset 5139 MemberOffset field_offset(0); 5140 if (is_static) { 5141 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_); 5142 } else { 5143 mirror::Class* super_class = klass->GetSuperClass(); 5144 if (super_class != nullptr) { 5145 CHECK(super_class->IsResolved()) 5146 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class); 5147 field_offset = MemberOffset(super_class->GetObjectSize()); 5148 } 5149 } 5150 5151 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get()); 5152 5153 // we want a relatively stable order so that adding new fields 5154 // minimizes disruption of C++ version such as Class and Method. 5155 std::deque<ArtField*> grouped_and_sorted_fields; 5156 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension( 5157 "Naked ArtField references in deque"); 5158 for (size_t i = 0; i < num_fields; i++) { 5159 grouped_and_sorted_fields.push_back(&fields->At(i)); 5160 } 5161 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(), 5162 LinkFieldsComparator()); 5163 5164 // References should be at the front. 5165 size_t current_field = 0; 5166 size_t num_reference_fields = 0; 5167 FieldGaps gaps; 5168 5169 for (; current_field < num_fields; current_field++) { 5170 ArtField* field = grouped_and_sorted_fields.front(); 5171 Primitive::Type type = field->GetTypeAsPrimitiveType(); 5172 bool isPrimitive = type != Primitive::kPrimNot; 5173 if (isPrimitive) { 5174 break; // past last reference, move on to the next phase 5175 } 5176 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>( 5177 field_offset.Uint32Value()))) { 5178 MemberOffset old_offset = field_offset; 5179 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4)); 5180 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps); 5181 } 5182 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>)); 5183 grouped_and_sorted_fields.pop_front(); 5184 num_reference_fields++; 5185 field->SetOffset(field_offset); 5186 field_offset = MemberOffset(field_offset.Uint32Value() + 5187 sizeof(mirror::HeapReference<mirror::Object>)); 5188 } 5189 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest 5190 // otherwise we could end up with suboptimal gap fills. 5191 ShuffleForward<8>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps); 5192 ShuffleForward<4>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps); 5193 ShuffleForward<2>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps); 5194 ShuffleForward<1>(¤t_field, &field_offset, &grouped_and_sorted_fields, &gaps); 5195 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() << 5196 " fields."; 5197 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 5198 5199 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it. 5200 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) { 5201 // We know there are no non-reference fields in the Reference classes, and we know 5202 // that 'referent' is alphabetically last, so this is easy... 5203 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get()); 5204 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent") 5205 << PrettyClass(klass.Get()); 5206 --num_reference_fields; 5207 } 5208 5209 size_t size = field_offset.Uint32Value(); 5210 // Update klass 5211 if (is_static) { 5212 klass->SetNumReferenceStaticFields(num_reference_fields); 5213 *class_size = size; 5214 } else { 5215 klass->SetNumReferenceInstanceFields(num_reference_fields); 5216 if (!klass->IsVariableSize()) { 5217 std::string temp; 5218 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp); 5219 size_t previous_size = klass->GetObjectSize(); 5220 if (previous_size != 0) { 5221 // Make sure that we didn't originally have an incorrect size. 5222 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp); 5223 } 5224 klass->SetObjectSize(size); 5225 } 5226 } 5227 5228 if (kIsDebugBuild) { 5229 // Make sure that the fields array is ordered by name but all reference 5230 // offsets are at the beginning as far as alignment allows. 5231 MemberOffset start_ref_offset = is_static 5232 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_) 5233 : klass->GetFirstReferenceInstanceFieldOffset(); 5234 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() + 5235 num_reference_fields * 5236 sizeof(mirror::HeapReference<mirror::Object>)); 5237 MemberOffset current_ref_offset = start_ref_offset; 5238 for (size_t i = 0; i < num_fields; i++) { 5239 ArtField* field = &fields->At(i); 5240 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance") 5241 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset=" 5242 << field->GetOffsetDuringLinking(); 5243 if (i != 0) { 5244 ArtField* const prev_field = &fields->At(i - 1); 5245 // NOTE: The field names can be the same. This is not possible in the Java language 5246 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode. 5247 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0); 5248 } 5249 Primitive::Type type = field->GetTypeAsPrimitiveType(); 5250 bool is_primitive = type != Primitive::kPrimNot; 5251 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") && 5252 strcmp("referent", field->GetName()) == 0) { 5253 is_primitive = true; // We lied above, so we have to expect a lie here. 5254 } 5255 MemberOffset offset = field->GetOffsetDuringLinking(); 5256 if (is_primitive) { 5257 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) { 5258 // Shuffled before references. 5259 size_t type_size = Primitive::ComponentSize(type); 5260 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>)); 5261 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value()); 5262 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value()); 5263 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value())); 5264 } 5265 } else { 5266 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value()); 5267 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() + 5268 sizeof(mirror::HeapReference<mirror::Object>)); 5269 } 5270 } 5271 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value()); 5272 } 5273 return true; 5274} 5275 5276// Set the bitmap of reference instance field offsets. 5277void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) { 5278 uint32_t reference_offsets = 0; 5279 mirror::Class* super_class = klass->GetSuperClass(); 5280 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially). 5281 if (super_class != nullptr) { 5282 reference_offsets = super_class->GetReferenceInstanceOffsets(); 5283 // Compute reference offsets unless our superclass overflowed. 5284 if (reference_offsets != mirror::Class::kClassWalkSuper) { 5285 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking(); 5286 if (num_reference_fields != 0u) { 5287 // All of the fields that contain object references are guaranteed be grouped in memory 5288 // starting at an appropriately aligned address after super class object data. 5289 uint32_t start_offset = RoundUp(super_class->GetObjectSize(), 5290 sizeof(mirror::HeapReference<mirror::Object>)); 5291 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) / 5292 sizeof(mirror::HeapReference<mirror::Object>); 5293 if (start_bit + num_reference_fields > 32) { 5294 reference_offsets = mirror::Class::kClassWalkSuper; 5295 } else { 5296 reference_offsets |= (0xffffffffu << start_bit) & 5297 (0xffffffffu >> (32 - (start_bit + num_reference_fields))); 5298 } 5299 } 5300 } 5301 } 5302 klass->SetReferenceInstanceOffsets(reference_offsets); 5303} 5304 5305mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx, 5306 Handle<mirror::DexCache> dex_cache) { 5307 DCHECK(dex_cache.Get() != nullptr); 5308 mirror::String* resolved = dex_cache->GetResolvedString(string_idx); 5309 if (resolved != nullptr) { 5310 return resolved; 5311 } 5312 uint32_t utf16_length; 5313 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length); 5314 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data); 5315 dex_cache->SetResolvedString(string_idx, string); 5316 return string; 5317} 5318 5319mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx, 5320 mirror::Class* referrer) { 5321 StackHandleScope<2> hs(Thread::Current()); 5322 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache())); 5323 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader())); 5324 return ResolveType(dex_file, type_idx, dex_cache, class_loader); 5325} 5326 5327mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx, 5328 Handle<mirror::DexCache> dex_cache, 5329 Handle<mirror::ClassLoader> class_loader) { 5330 DCHECK(dex_cache.Get() != nullptr); 5331 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx); 5332 if (resolved == nullptr) { 5333 Thread* self = Thread::Current(); 5334 const char* descriptor = dex_file.StringByTypeIdx(type_idx); 5335 resolved = FindClass(self, descriptor, class_loader); 5336 if (resolved != nullptr) { 5337 // TODO: we used to throw here if resolved's class loader was not the 5338 // boot class loader. This was to permit different classes with the 5339 // same name to be loaded simultaneously by different loaders 5340 dex_cache->SetResolvedType(type_idx, resolved); 5341 } else { 5342 CHECK(self->IsExceptionPending()) 5343 << "Expected pending exception for failed resolution of: " << descriptor; 5344 // Convert a ClassNotFoundException to a NoClassDefFoundError. 5345 StackHandleScope<1> hs(self); 5346 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException())); 5347 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) { 5348 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved. 5349 self->ClearException(); 5350 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor); 5351 self->GetException()->SetCause(cause.Get()); 5352 } 5353 } 5354 } 5355 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous()) 5356 << PrettyDescriptor(resolved) << " " << resolved->GetStatus(); 5357 return resolved; 5358} 5359 5360ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx, 5361 Handle<mirror::DexCache> dex_cache, 5362 Handle<mirror::ClassLoader> class_loader, 5363 ArtMethod* referrer, InvokeType type) { 5364 DCHECK(dex_cache.Get() != nullptr); 5365 // Check for hit in the dex cache. 5366 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_); 5367 if (resolved != nullptr && !resolved->IsRuntimeMethod()) { 5368 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex(); 5369 return resolved; 5370 } 5371 // Fail, get the declaring class. 5372 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 5373 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader); 5374 if (klass == nullptr) { 5375 DCHECK(Thread::Current()->IsExceptionPending()); 5376 return nullptr; 5377 } 5378 // Scan using method_idx, this saves string compares but will only hit for matching dex 5379 // caches/files. 5380 switch (type) { 5381 case kDirect: // Fall-through. 5382 case kStatic: 5383 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_); 5384 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr); 5385 break; 5386 case kInterface: 5387 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_); 5388 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface()); 5389 break; 5390 case kSuper: // Fall-through. 5391 case kVirtual: 5392 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_); 5393 break; 5394 default: 5395 LOG(FATAL) << "Unreachable - invocation type: " << type; 5396 UNREACHABLE(); 5397 } 5398 if (resolved == nullptr) { 5399 // Search by name, which works across dex files. 5400 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 5401 const Signature signature = dex_file.GetMethodSignature(method_id); 5402 switch (type) { 5403 case kDirect: // Fall-through. 5404 case kStatic: 5405 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_); 5406 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr); 5407 break; 5408 case kInterface: 5409 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_); 5410 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface()); 5411 break; 5412 case kSuper: // Fall-through. 5413 case kVirtual: 5414 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_); 5415 break; 5416 } 5417 } 5418 // If we found a method, check for incompatible class changes. 5419 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) { 5420 // Be a good citizen and update the dex cache to speed subsequent calls. 5421 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_); 5422 return resolved; 5423 } else { 5424 // If we had a method, it's an incompatible-class-change error. 5425 if (resolved != nullptr) { 5426 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer); 5427 } else { 5428 // We failed to find the method which means either an access error, an incompatible class 5429 // change, or no such method. First try to find the method among direct and virtual methods. 5430 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 5431 const Signature signature = dex_file.GetMethodSignature(method_id); 5432 switch (type) { 5433 case kDirect: 5434 case kStatic: 5435 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_); 5436 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would 5437 // have had a resolved method before, which triggers the "true" branch above. 5438 break; 5439 case kInterface: 5440 case kVirtual: 5441 case kSuper: 5442 resolved = klass->FindDirectMethod(name, signature, image_pointer_size_); 5443 break; 5444 } 5445 5446 // If we found something, check that it can be accessed by the referrer. 5447 bool exception_generated = false; 5448 if (resolved != nullptr && referrer != nullptr) { 5449 mirror::Class* methods_class = resolved->GetDeclaringClass(); 5450 mirror::Class* referring_class = referrer->GetDeclaringClass(); 5451 if (!referring_class->CanAccess(methods_class)) { 5452 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class, resolved, 5453 type); 5454 exception_generated = true; 5455 } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) { 5456 ThrowIllegalAccessErrorMethod(referring_class, resolved); 5457 exception_generated = true; 5458 } 5459 } 5460 if (!exception_generated) { 5461 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check 5462 // interface methods and throw if we find the method there. If we find nothing, throw a 5463 // NoSuchMethodError. 5464 switch (type) { 5465 case kDirect: 5466 case kStatic: 5467 if (resolved != nullptr) { 5468 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer); 5469 } else { 5470 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_); 5471 if (resolved != nullptr) { 5472 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer); 5473 } else { 5474 ThrowNoSuchMethodError(type, klass, name, signature); 5475 } 5476 } 5477 break; 5478 case kInterface: 5479 if (resolved != nullptr) { 5480 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer); 5481 } else { 5482 resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_); 5483 if (resolved != nullptr) { 5484 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer); 5485 } else { 5486 ThrowNoSuchMethodError(type, klass, name, signature); 5487 } 5488 } 5489 break; 5490 case kSuper: 5491 if (resolved != nullptr) { 5492 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer); 5493 } else { 5494 ThrowNoSuchMethodError(type, klass, name, signature); 5495 } 5496 break; 5497 case kVirtual: 5498 if (resolved != nullptr) { 5499 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer); 5500 } else { 5501 resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_); 5502 if (resolved != nullptr) { 5503 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer); 5504 } else { 5505 ThrowNoSuchMethodError(type, klass, name, signature); 5506 } 5507 } 5508 break; 5509 } 5510 } 5511 } 5512 Thread::Current()->AssertPendingException(); 5513 return nullptr; 5514 } 5515} 5516 5517ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx, 5518 Handle<mirror::DexCache> dex_cache, 5519 Handle<mirror::ClassLoader> class_loader, bool is_static) { 5520 DCHECK(dex_cache.Get() != nullptr); 5521 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_); 5522 if (resolved != nullptr) { 5523 return resolved; 5524 } 5525 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 5526 Thread* const self = Thread::Current(); 5527 StackHandleScope<1> hs(self); 5528 Handle<mirror::Class> klass( 5529 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 5530 if (klass.Get() == nullptr) { 5531 DCHECK(Thread::Current()->IsExceptionPending()); 5532 return nullptr; 5533 } 5534 5535 if (is_static) { 5536 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx); 5537 } else { 5538 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx); 5539 } 5540 5541 if (resolved == nullptr) { 5542 const char* name = dex_file.GetFieldName(field_id); 5543 const char* type = dex_file.GetFieldTypeDescriptor(field_id); 5544 if (is_static) { 5545 resolved = mirror::Class::FindStaticField(self, klass, name, type); 5546 } else { 5547 resolved = klass->FindInstanceField(name, type); 5548 } 5549 if (resolved == nullptr) { 5550 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name); 5551 return nullptr; 5552 } 5553 } 5554 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_); 5555 return resolved; 5556} 5557 5558ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx, 5559 Handle<mirror::DexCache> dex_cache, 5560 Handle<mirror::ClassLoader> class_loader) { 5561 DCHECK(dex_cache.Get() != nullptr); 5562 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_); 5563 if (resolved != nullptr) { 5564 return resolved; 5565 } 5566 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 5567 Thread* self = Thread::Current(); 5568 StackHandleScope<1> hs(self); 5569 Handle<mirror::Class> klass( 5570 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 5571 if (klass.Get() == nullptr) { 5572 DCHECK(Thread::Current()->IsExceptionPending()); 5573 return nullptr; 5574 } 5575 5576 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_)); 5577 StringPiece type(dex_file.StringDataByIdx( 5578 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_)); 5579 resolved = mirror::Class::FindField(self, klass, name, type); 5580 if (resolved != nullptr) { 5581 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_); 5582 } else { 5583 ThrowNoSuchFieldError("", klass.Get(), type, name); 5584 } 5585 return resolved; 5586} 5587 5588const char* ClassLinker::MethodShorty(uint32_t method_idx, ArtMethod* referrer, 5589 uint32_t* length) { 5590 mirror::Class* declaring_class = referrer->GetDeclaringClass(); 5591 mirror::DexCache* dex_cache = declaring_class->GetDexCache(); 5592 const DexFile& dex_file = *dex_cache->GetDexFile(); 5593 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 5594 return dex_file.GetMethodShorty(method_id, length); 5595} 5596 5597class DumpClassVisitor : public ClassVisitor { 5598 public: 5599 explicit DumpClassVisitor(int flags) : flags_(flags) {} 5600 5601 bool Visit(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 5602 klass->DumpClass(LOG(ERROR), flags_); 5603 return true; 5604 } 5605 5606 private: 5607 const int flags_; 5608}; 5609 5610void ClassLinker::DumpAllClasses(int flags) { 5611 DumpClassVisitor visitor(flags); 5612 VisitClasses(&visitor); 5613} 5614 5615static OatFile::OatMethod CreateOatMethod(const void* code) { 5616 CHECK(code != nullptr); 5617 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code. 5618 base -= sizeof(void*); // Move backward so that code_offset != 0. 5619 const uint32_t code_offset = sizeof(void*); 5620 return OatFile::OatMethod(base, code_offset); 5621} 5622 5623bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const { 5624 return (entry_point == GetQuickResolutionStub()) || 5625 (quick_resolution_trampoline_ == entry_point); 5626} 5627 5628bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const { 5629 return (entry_point == GetQuickToInterpreterBridge()) || 5630 (quick_to_interpreter_bridge_trampoline_ == entry_point); 5631} 5632 5633bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const { 5634 return (entry_point == GetQuickGenericJniStub()) || 5635 (quick_generic_jni_trampoline_ == entry_point); 5636} 5637 5638const void* ClassLinker::GetRuntimeQuickGenericJniStub() const { 5639 return GetQuickGenericJniStub(); 5640} 5641 5642void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method, 5643 const void* method_code) const { 5644 OatFile::OatMethod oat_method = CreateOatMethod(method_code); 5645 oat_method.LinkMethod(method); 5646} 5647 5648void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const { 5649 if (!method->IsNative()) { 5650 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 5651 } else { 5652 const void* quick_method_code = GetQuickGenericJniStub(); 5653 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code); 5654 oat_method.LinkMethod(method); 5655 } 5656} 5657 5658void ClassLinker::DumpForSigQuit(std::ostream& os) { 5659 ScopedObjectAccess soa(Thread::Current()); 5660 if (dex_cache_image_class_lookup_required_) { 5661 MoveImageClassesToClassTable(); 5662 } 5663 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_); 5664 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes=" 5665 << NumNonZygoteClasses() << "\n"; 5666} 5667 5668size_t ClassLinker::NumZygoteClasses() const { 5669 size_t sum = boot_class_table_.NumZygoteClasses(); 5670 for (const GcRoot<mirror::ClassLoader>& root : class_loaders_) { 5671 ClassTable* const class_table = root.Read()->GetClassTable(); 5672 if (class_table != nullptr) { 5673 sum += class_table->NumZygoteClasses(); 5674 } 5675 } 5676 return sum; 5677} 5678 5679size_t ClassLinker::NumNonZygoteClasses() const { 5680 size_t sum = boot_class_table_.NumNonZygoteClasses(); 5681 for (const GcRoot<mirror::ClassLoader>& root : class_loaders_) { 5682 ClassTable* const class_table = root.Read()->GetClassTable(); 5683 if (class_table != nullptr) { 5684 sum += class_table->NumNonZygoteClasses(); 5685 } 5686 } 5687 return sum; 5688} 5689 5690size_t ClassLinker::NumLoadedClasses() { 5691 if (dex_cache_image_class_lookup_required_) { 5692 MoveImageClassesToClassTable(); 5693 } 5694 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5695 // Only return non zygote classes since these are the ones which apps which care about. 5696 return NumNonZygoteClasses(); 5697} 5698 5699pid_t ClassLinker::GetClassesLockOwner() { 5700 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid(); 5701} 5702 5703pid_t ClassLinker::GetDexLockOwner() { 5704 return dex_lock_.GetExclusiveOwnerTid(); 5705} 5706 5707void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) { 5708 DCHECK(!init_done_); 5709 5710 DCHECK(klass != nullptr); 5711 DCHECK(klass->GetClassLoader() == nullptr); 5712 5713 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read(); 5714 DCHECK(class_roots != nullptr); 5715 DCHECK(class_roots->Get(class_root) == nullptr); 5716 class_roots->Set<false>(class_root, klass); 5717} 5718 5719const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) { 5720 static const char* class_roots_descriptors[] = { 5721 "Ljava/lang/Class;", 5722 "Ljava/lang/Object;", 5723 "[Ljava/lang/Class;", 5724 "[Ljava/lang/Object;", 5725 "Ljava/lang/String;", 5726 "Ljava/lang/DexCache;", 5727 "Ljava/lang/ref/Reference;", 5728 "Ljava/lang/reflect/Constructor;", 5729 "Ljava/lang/reflect/Field;", 5730 "Ljava/lang/reflect/Method;", 5731 "Ljava/lang/reflect/Proxy;", 5732 "[Ljava/lang/String;", 5733 "[Ljava/lang/reflect/Constructor;", 5734 "[Ljava/lang/reflect/Field;", 5735 "[Ljava/lang/reflect/Method;", 5736 "Ljava/lang/ClassLoader;", 5737 "Ljava/lang/Throwable;", 5738 "Ljava/lang/ClassNotFoundException;", 5739 "Ljava/lang/StackTraceElement;", 5740 "Z", 5741 "B", 5742 "C", 5743 "D", 5744 "F", 5745 "I", 5746 "J", 5747 "S", 5748 "V", 5749 "[Z", 5750 "[B", 5751 "[C", 5752 "[D", 5753 "[F", 5754 "[I", 5755 "[J", 5756 "[S", 5757 "[Ljava/lang/StackTraceElement;", 5758 }; 5759 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax), 5760 "Mismatch between class descriptors and class-root enum"); 5761 5762 const char* descriptor = class_roots_descriptors[class_root]; 5763 CHECK(descriptor != nullptr); 5764 return descriptor; 5765} 5766 5767bool ClassLinker::MayBeCalledWithDirectCodePointer(ArtMethod* m) { 5768 if (Runtime::Current()->UseJit()) { 5769 // JIT can have direct code pointers from any method to any other method. 5770 return true; 5771 } 5772 // Non-image methods don't use direct code pointer. 5773 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) { 5774 return false; 5775 } 5776 if (m->IsPrivate()) { 5777 // The method can only be called inside its own oat file. Therefore it won't be called using 5778 // its direct code if the oat file has been compiled in PIC mode. 5779 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile(); 5780 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile(); 5781 if (oat_dex_file == nullptr) { 5782 // No oat file: the method has not been compiled. 5783 return false; 5784 } 5785 const OatFile* oat_file = oat_dex_file->GetOatFile(); 5786 return oat_file != nullptr && !oat_file->IsPic(); 5787 } else { 5788 // The method can be called outside its own oat file. Therefore it won't be called using its 5789 // direct code pointer only if all loaded oat files have been compiled in PIC mode. 5790 ReaderMutexLock mu(Thread::Current(), dex_lock_); 5791 for (const OatFile* oat_file : oat_files_) { 5792 if (!oat_file->IsPic()) { 5793 return true; 5794 } 5795 } 5796 return false; 5797 } 5798} 5799 5800jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) { 5801 // SOAAlreadyRunnable is protected, and we need something to add a global reference. 5802 // We could move the jobject to the callers, but all call-sites do this... 5803 ScopedObjectAccessUnchecked soa(self); 5804 5805 // Register the dex files. 5806 for (const DexFile* dex_file : dex_files) { 5807 RegisterDexFile(*dex_file); 5808 } 5809 5810 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex. 5811 StackHandleScope<10> hs(self); 5812 5813 ArtField* dex_elements_field = 5814 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements); 5815 5816 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>(); 5817 DCHECK(dex_elements_class != nullptr); 5818 DCHECK(dex_elements_class->IsArrayClass()); 5819 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle( 5820 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size()))); 5821 Handle<mirror::Class> h_dex_element_class = 5822 hs.NewHandle(dex_elements_class->GetComponentType()); 5823 5824 ArtField* element_file_field = 5825 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile); 5826 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass()); 5827 5828 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie); 5829 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>()); 5830 5831 // Fill the elements array. 5832 int32_t index = 0; 5833 for (const DexFile* dex_file : dex_files) { 5834 StackHandleScope<3> hs2(self); 5835 5836 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1)); 5837 DCHECK(h_long_array.Get() != nullptr); 5838 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file)); 5839 5840 Handle<mirror::Object> h_dex_file = hs2.NewHandle( 5841 cookie_field->GetDeclaringClass()->AllocObject(self)); 5842 DCHECK(h_dex_file.Get() != nullptr); 5843 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get()); 5844 5845 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self)); 5846 DCHECK(h_element.Get() != nullptr); 5847 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get()); 5848 5849 h_dex_elements->Set(index, h_element.Get()); 5850 index++; 5851 } 5852 DCHECK_EQ(index, h_dex_elements->GetLength()); 5853 5854 // Create DexPathList. 5855 Handle<mirror::Object> h_dex_path_list = hs.NewHandle( 5856 dex_elements_field->GetDeclaringClass()->AllocObject(self)); 5857 DCHECK(h_dex_path_list.Get() != nullptr); 5858 // Set elements. 5859 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get()); 5860 5861 // Create PathClassLoader. 5862 Handle<mirror::Class> h_path_class_class = hs.NewHandle( 5863 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)); 5864 Handle<mirror::Object> h_path_class_loader = hs.NewHandle( 5865 h_path_class_class->AllocObject(self)); 5866 DCHECK(h_path_class_loader.Get() != nullptr); 5867 // Set DexPathList. 5868 ArtField* path_list_field = 5869 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList); 5870 DCHECK(path_list_field != nullptr); 5871 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get()); 5872 5873 // Make a pretend boot-classpath. 5874 // TODO: Should we scan the image? 5875 ArtField* const parent_field = 5876 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent", 5877 "Ljava/lang/ClassLoader;"); 5878 DCHECK(parent_field != nullptr); 5879 mirror::Object* boot_cl = 5880 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self); 5881 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl); 5882 5883 // Make it a global ref and return. 5884 ScopedLocalRef<jobject> local_ref( 5885 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get())); 5886 return soa.Env()->NewGlobalRef(local_ref.get()); 5887} 5888 5889ArtMethod* ClassLinker::CreateRuntimeMethod() { 5890 const size_t method_size = ArtMethod::ObjectSize(image_pointer_size_); 5891 ArtMethod* method = &AllocArtMethodArray(Thread::Current(), 1)->At(0, method_size); 5892 CHECK(method != nullptr); 5893 method->SetDexMethodIndex(DexFile::kDexNoIndex); 5894 CHECK(method->IsRuntimeMethod()); 5895 return method; 5896} 5897 5898void ClassLinker::DropFindArrayClassCache() { 5899 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr)); 5900 find_array_class_cache_next_victim_ = 0; 5901} 5902 5903} // namespace art 5904