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