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