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