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