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