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