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