class_linker.cc revision dbf3be0f133c0bdf454f637fee2452dbb5f7c027
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 // TODO: why isn't this a ReaderMutexLock? 1808 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1809 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) { 1810 mirror::Class* c = it.second.Read(); 1811 if (!visitor(c, arg)) { 1812 return; 1813 } 1814 } 1815} 1816 1817static bool GetClassesVisitorSet(mirror::Class* c, void* arg) { 1818 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg); 1819 classes->insert(c); 1820 return true; 1821} 1822 1823struct GetClassesVisitorArrayArg { 1824 Handle<mirror::ObjectArray<mirror::Class>>* classes; 1825 int32_t index; 1826 bool success; 1827}; 1828 1829static bool GetClassesVisitorArray(mirror::Class* c, void* varg) 1830 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1831 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg); 1832 if (arg->index < (*arg->classes)->GetLength()) { 1833 (*arg->classes)->Set(arg->index, c); 1834 arg->index++; 1835 return true; 1836 } else { 1837 arg->success = false; 1838 return false; 1839 } 1840} 1841 1842void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) { 1843 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem 1844 // is avoiding duplicates. 1845 if (!kMovingClasses) { 1846 std::set<mirror::Class*> classes; 1847 VisitClasses(GetClassesVisitorSet, &classes); 1848 for (mirror::Class* klass : classes) { 1849 if (!visitor(klass, arg)) { 1850 return; 1851 } 1852 } 1853 } else { 1854 Thread* self = Thread::Current(); 1855 StackHandleScope<1> hs(self); 1856 Handle<mirror::ObjectArray<mirror::Class>> classes = 1857 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr); 1858 GetClassesVisitorArrayArg local_arg; 1859 local_arg.classes = &classes; 1860 local_arg.success = false; 1861 // We size the array assuming classes won't be added to the class table during the visit. 1862 // If this assumption fails we iterate again. 1863 while (!local_arg.success) { 1864 size_t class_table_size; 1865 { 1866 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1867 class_table_size = class_table_.size(); 1868 } 1869 mirror::Class* class_type = mirror::Class::GetJavaLangClass(); 1870 mirror::Class* array_of_class = FindArrayClass(self, &class_type); 1871 classes.Assign( 1872 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size)); 1873 CHECK(classes.Get() != nullptr); // OOME. 1874 local_arg.index = 0; 1875 local_arg.success = true; 1876 VisitClasses(GetClassesVisitorArray, &local_arg); 1877 } 1878 for (int32_t i = 0; i < classes->GetLength(); ++i) { 1879 // If the class table shrank during creation of the clases array we expect null elements. If 1880 // the class table grew then the loop repeats. If classes are created after the loop has 1881 // finished then we don't visit. 1882 mirror::Class* klass = classes->Get(i); 1883 if (klass != nullptr && !visitor(klass, arg)) { 1884 return; 1885 } 1886 } 1887 } 1888} 1889 1890ClassLinker::~ClassLinker() { 1891 mirror::Class::ResetClass(); 1892 mirror::String::ResetClass(); 1893 mirror::Reference::ResetClass(); 1894 mirror::ArtField::ResetClass(); 1895 mirror::ArtMethod::ResetClass(); 1896 mirror::BooleanArray::ResetArrayClass(); 1897 mirror::ByteArray::ResetArrayClass(); 1898 mirror::CharArray::ResetArrayClass(); 1899 mirror::DoubleArray::ResetArrayClass(); 1900 mirror::FloatArray::ResetArrayClass(); 1901 mirror::IntArray::ResetArrayClass(); 1902 mirror::LongArray::ResetArrayClass(); 1903 mirror::ShortArray::ResetArrayClass(); 1904 mirror::Throwable::ResetClass(); 1905 mirror::StackTraceElement::ResetClass(); 1906 STLDeleteElements(&boot_class_path_); 1907 STLDeleteElements(&oat_files_); 1908} 1909 1910mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) { 1911 gc::Heap* heap = Runtime::Current()->GetHeap(); 1912 StackHandleScope<16> hs(self); 1913 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache))); 1914 Handle<mirror::DexCache> dex_cache( 1915 hs.NewHandle(down_cast<mirror::DexCache*>( 1916 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(), 1917 VoidFunctor())))); 1918 if (dex_cache.Get() == NULL) { 1919 return NULL; 1920 } 1921 Handle<mirror::String> 1922 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str()))); 1923 if (location.Get() == NULL) { 1924 return NULL; 1925 } 1926 Handle<mirror::ObjectArray<mirror::String>> 1927 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds()))); 1928 if (strings.Get() == NULL) { 1929 return NULL; 1930 } 1931 Handle<mirror::ObjectArray<mirror::Class>> 1932 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds()))); 1933 if (types.Get() == NULL) { 1934 return NULL; 1935 } 1936 Handle<mirror::ObjectArray<mirror::ArtMethod>> 1937 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds()))); 1938 if (methods.Get() == NULL) { 1939 return NULL; 1940 } 1941 Handle<mirror::ObjectArray<mirror::ArtField>> 1942 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds()))); 1943 if (fields.Get() == NULL) { 1944 return NULL; 1945 } 1946 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(), 1947 fields.Get()); 1948 return dex_cache.Get(); 1949} 1950 1951mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class, 1952 uint32_t class_size) { 1953 DCHECK_GE(class_size, sizeof(mirror::Class)); 1954 gc::Heap* heap = Runtime::Current()->GetHeap(); 1955 mirror::Class::InitializeClassVisitor visitor(class_size); 1956 mirror::Object* k = kMovingClasses ? 1957 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) : 1958 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor); 1959 if (UNLIKELY(k == nullptr)) { 1960 CHECK(self->IsExceptionPending()); // OOME. 1961 return nullptr; 1962 } 1963 return k->AsClass(); 1964} 1965 1966mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) { 1967 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size); 1968} 1969 1970mirror::ArtField* ClassLinker::AllocArtField(Thread* self) { 1971 return down_cast<mirror::ArtField*>( 1972 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self)); 1973} 1974 1975mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) { 1976 return down_cast<mirror::ArtMethod*>( 1977 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self)); 1978} 1979 1980mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray( 1981 Thread* self, size_t length) { 1982 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc( 1983 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length); 1984} 1985 1986mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor, 1987 mirror::Class* klass) { 1988 DCHECK(klass != NULL); 1989 1990 // For temporary classes we must wait for them to be retired. 1991 if (init_done_ && klass->IsTemp()) { 1992 CHECK(!klass->IsResolved()); 1993 if (klass->IsErroneous()) { 1994 ThrowEarlierClassFailure(klass); 1995 return nullptr; 1996 } 1997 StackHandleScope<1> hs(self); 1998 Handle<mirror::Class> h_class(hs.NewHandle(klass)); 1999 ObjectLock<mirror::Class> lock(self, h_class); 2000 // Loop and wait for the resolving thread to retire this class. 2001 while (!h_class->IsRetired() && !h_class->IsErroneous()) { 2002 lock.WaitIgnoringInterrupts(); 2003 } 2004 if (h_class->IsErroneous()) { 2005 ThrowEarlierClassFailure(h_class.Get()); 2006 return nullptr; 2007 } 2008 CHECK(h_class->IsRetired()); 2009 // Get the updated class from class table. 2010 klass = LookupClass(descriptor, h_class.Get()->GetClassLoader()); 2011 } 2012 2013 // Wait for the class if it has not already been linked. 2014 if (!klass->IsResolved() && !klass->IsErroneous()) { 2015 StackHandleScope<1> hs(self); 2016 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass)); 2017 ObjectLock<mirror::Class> lock(self, h_class); 2018 // Check for circular dependencies between classes. 2019 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) { 2020 ThrowClassCircularityError(h_class.Get()); 2021 h_class->SetStatus(mirror::Class::kStatusError, self); 2022 return nullptr; 2023 } 2024 // Wait for the pending initialization to complete. 2025 while (!h_class->IsResolved() && !h_class->IsErroneous()) { 2026 lock.WaitIgnoringInterrupts(); 2027 } 2028 } 2029 2030 if (klass->IsErroneous()) { 2031 ThrowEarlierClassFailure(klass); 2032 return nullptr; 2033 } 2034 // Return the loaded class. No exceptions should be pending. 2035 CHECK(klass->IsResolved()) << PrettyClass(klass); 2036 self->AssertNoPendingException(); 2037 return klass; 2038} 2039 2040typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry; 2041 2042// Search a collection of DexFiles for a descriptor 2043ClassPathEntry FindInClassPath(const char* descriptor, 2044 const std::vector<const DexFile*>& class_path) { 2045 for (size_t i = 0; i != class_path.size(); ++i) { 2046 const DexFile* dex_file = class_path[i]; 2047 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor); 2048 if (dex_class_def != NULL) { 2049 return ClassPathEntry(dex_file, dex_class_def); 2050 } 2051 } 2052 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved 2053 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL), 2054 reinterpret_cast<const DexFile::ClassDef*>(NULL)); 2055} 2056 2057mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor, 2058 ConstHandle<mirror::ClassLoader> class_loader) { 2059 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string"; 2060 DCHECK(self != nullptr); 2061 self->AssertNoPendingException(); 2062 if (descriptor[1] == '\0') { 2063 // only the descriptors of primitive types should be 1 character long, also avoid class lookup 2064 // for primitive classes that aren't backed by dex files. 2065 return FindPrimitiveClass(descriptor[0]); 2066 } 2067 // Find the class in the loaded classes table. 2068 mirror::Class* klass = LookupClass(descriptor, class_loader.Get()); 2069 if (klass != nullptr) { 2070 return EnsureResolved(self, descriptor, klass); 2071 } 2072 // Class is not yet loaded. 2073 if (descriptor[0] == '[') { 2074 return CreateArrayClass(self, descriptor, class_loader); 2075 } else if (class_loader.Get() == nullptr) { 2076 // The boot class loader, search the boot class path. 2077 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_); 2078 if (pair.second != nullptr) { 2079 StackHandleScope<1> hs(self); 2080 return DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first, *pair.second); 2081 } else { 2082 // The boot class loader is searched ahead of the application class loader, failures are 2083 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to 2084 // trigger the chaining with a proper stack trace. 2085 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError(); 2086 self->SetException(ThrowLocation(), pre_allocated); 2087 return nullptr; 2088 } 2089 } else if (Runtime::Current()->UseCompileTimeClassPath()) { 2090 // First try with the bootstrap class loader. 2091 if (class_loader.Get() != nullptr) { 2092 klass = LookupClass(descriptor, nullptr); 2093 if (klass != nullptr) { 2094 return EnsureResolved(self, descriptor, klass); 2095 } 2096 } 2097 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid 2098 // a NoClassDefFoundError being allocated. 2099 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_); 2100 if (pair.second != nullptr) { 2101 StackHandleScope<1> hs(self); 2102 return DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first, *pair.second); 2103 } 2104 // Next try the compile time class path. 2105 const std::vector<const DexFile*>* class_path; 2106 { 2107 ScopedObjectAccessUnchecked soa(self); 2108 ScopedLocalRef<jobject> jclass_loader(soa.Env(), 2109 soa.AddLocalReference<jobject>(class_loader.Get())); 2110 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get()); 2111 } 2112 pair = FindInClassPath(descriptor, *class_path); 2113 if (pair.second != nullptr) { 2114 return DefineClass(descriptor, class_loader, *pair.first, *pair.second); 2115 } 2116 } else { 2117 ScopedObjectAccessUnchecked soa(self); 2118 ScopedLocalRef<jobject> class_loader_object(soa.Env(), 2119 soa.AddLocalReference<jobject>(class_loader.Get())); 2120 std::string class_name_string(DescriptorToDot(descriptor)); 2121 ScopedLocalRef<jobject> result(soa.Env(), nullptr); 2122 { 2123 ScopedThreadStateChange tsc(self, kNative); 2124 ScopedLocalRef<jobject> class_name_object(soa.Env(), 2125 soa.Env()->NewStringUTF(class_name_string.c_str())); 2126 if (class_name_object.get() == nullptr) { 2127 DCHECK(self->IsExceptionPending()); // OOME. 2128 return nullptr; 2129 } 2130 CHECK(class_loader_object.get() != nullptr); 2131 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(), 2132 WellKnownClasses::java_lang_ClassLoader_loadClass, 2133 class_name_object.get())); 2134 } 2135 if (self->IsExceptionPending()) { 2136 // If the ClassLoader threw, pass that exception up. 2137 return nullptr; 2138 } else if (result.get() == nullptr) { 2139 // broken loader - throw NPE to be compatible with Dalvik 2140 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s", 2141 class_name_string.c_str()).c_str()); 2142 return nullptr; 2143 } else { 2144 // success, return mirror::Class* 2145 return soa.Decode<mirror::Class*>(result.get()); 2146 } 2147 } 2148 2149 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str()); 2150 return nullptr; 2151} 2152 2153mirror::Class* ClassLinker::DefineClass(const char* descriptor, 2154 ConstHandle<mirror::ClassLoader> class_loader, 2155 const DexFile& dex_file, 2156 const DexFile::ClassDef& dex_class_def) { 2157 Thread* self = Thread::Current(); 2158 StackHandleScope<3> hs(self); 2159 auto klass = hs.NewHandle<mirror::Class>(nullptr); 2160 bool should_allocate = false; 2161 2162 // Load the class from the dex file. 2163 if (UNLIKELY(!init_done_)) { 2164 // finish up init of hand crafted class_roots_ 2165 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) { 2166 klass.Assign(GetClassRoot(kJavaLangObject)); 2167 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) { 2168 klass.Assign(GetClassRoot(kJavaLangClass)); 2169 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) { 2170 klass.Assign(GetClassRoot(kJavaLangString)); 2171 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) { 2172 klass.Assign(GetClassRoot(kJavaLangRefReference)); 2173 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) { 2174 klass.Assign(GetClassRoot(kJavaLangDexCache)); 2175 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) { 2176 klass.Assign(GetClassRoot(kJavaLangReflectArtField)); 2177 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) { 2178 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod)); 2179 } else { 2180 should_allocate = true; 2181 } 2182 } else { 2183 should_allocate = true; 2184 } 2185 2186 if (should_allocate) { 2187 // Allocate a class with the status of not ready. 2188 // Interface object should get the right size here. Regular class will 2189 // figure out the right size later and be replaced with one of the right 2190 // size when the class becomes resolved. 2191 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def))); 2192 } 2193 if (UNLIKELY(klass.Get() == nullptr)) { 2194 CHECK(self->IsExceptionPending()); // Expect an OOME. 2195 return nullptr; 2196 } 2197 klass->SetDexCache(FindDexCache(dex_file)); 2198 LoadClass(dex_file, dex_class_def, klass, class_loader.Get()); 2199 ObjectLock<mirror::Class> lock(self, klass); 2200 if (self->IsExceptionPending()) { 2201 // An exception occured during load, set status to erroneous while holding klass' lock in case 2202 // notification is necessary. 2203 if (!klass->IsErroneous()) { 2204 klass->SetStatus(mirror::Class::kStatusError, self); 2205 } 2206 return nullptr; 2207 } 2208 klass->SetClinitThreadId(self->GetTid()); 2209 2210 // Add the newly loaded class to the loaded classes table. 2211 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor)); 2212 if (existing != nullptr) { 2213 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause 2214 // this thread to block. 2215 return EnsureResolved(self, descriptor, existing); 2216 } 2217 2218 // Finish loading (if necessary) by finding parents 2219 CHECK(!klass->IsLoaded()); 2220 if (!LoadSuperAndInterfaces(klass, dex_file)) { 2221 // Loading failed. 2222 if (!klass->IsErroneous()) { 2223 klass->SetStatus(mirror::Class::kStatusError, self); 2224 } 2225 return nullptr; 2226 } 2227 CHECK(klass->IsLoaded()); 2228 // Link the class (if necessary) 2229 CHECK(!klass->IsResolved()); 2230 // TODO: Use fast jobjects? 2231 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr); 2232 2233 mirror::Class* new_class = nullptr; 2234 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) { 2235 // Linking failed. 2236 if (!klass->IsErroneous()) { 2237 klass->SetStatus(mirror::Class::kStatusError, self); 2238 } 2239 return nullptr; 2240 } 2241 self->AssertNoPendingException(); 2242 CHECK(new_class != nullptr) << descriptor; 2243 CHECK(new_class->IsResolved()) << descriptor; 2244 2245 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class)); 2246 2247 /* 2248 * We send CLASS_PREPARE events to the debugger from here. The 2249 * definition of "preparation" is creating the static fields for a 2250 * class and initializing them to the standard default values, but not 2251 * executing any code (that comes later, during "initialization"). 2252 * 2253 * We did the static preparation in LinkClass. 2254 * 2255 * The class has been prepared and resolved but possibly not yet verified 2256 * at this point. 2257 */ 2258 Dbg::PostClassPrepare(new_class_h.Get()); 2259 2260 return new_class_h.Get(); 2261} 2262 2263uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file, 2264 const DexFile::ClassDef& dex_class_def) { 2265 const byte* class_data = dex_file.GetClassData(dex_class_def); 2266 size_t num_ref = 0; 2267 size_t num_8 = 0; 2268 size_t num_16 = 0; 2269 size_t num_32 = 0; 2270 size_t num_64 = 0; 2271 if (class_data != NULL) { 2272 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) { 2273 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex()); 2274 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id); 2275 char c = descriptor[0]; 2276 switch (c) { 2277 case 'L': 2278 case '[': 2279 num_ref++; 2280 break; 2281 case 'J': 2282 case 'D': 2283 num_64++; 2284 break; 2285 case 'I': 2286 case 'F': 2287 num_32++; 2288 break; 2289 case 'S': 2290 case 'C': 2291 num_16++; 2292 break; 2293 case 'B': 2294 case 'Z': 2295 num_8++; 2296 break; 2297 default: 2298 LOG(FATAL) << "Unknown descriptor: " << c; 2299 } 2300 } 2301 } 2302 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref); 2303} 2304 2305OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx, 2306 bool* found) { 2307 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16); 2308 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file); 2309 if (oat_file == nullptr) { 2310 *found = false; 2311 return OatFile::OatClass::Invalid(); 2312 } 2313 uint dex_location_checksum = dex_file.GetLocationChecksum(); 2314 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(), 2315 &dex_location_checksum); 2316 CHECK(oat_dex_file != NULL) << dex_file.GetLocation(); 2317 *found = true; 2318 return oat_dex_file->GetOatClass(class_def_idx); 2319} 2320 2321static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx, 2322 uint32_t method_idx) { 2323 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx); 2324 const byte* class_data = dex_file.GetClassData(class_def); 2325 CHECK(class_data != NULL); 2326 ClassDataItemIterator it(dex_file, class_data); 2327 // Skip fields 2328 while (it.HasNextStaticField()) { 2329 it.Next(); 2330 } 2331 while (it.HasNextInstanceField()) { 2332 it.Next(); 2333 } 2334 // Process methods 2335 size_t class_def_method_index = 0; 2336 while (it.HasNextDirectMethod()) { 2337 if (it.GetMemberIndex() == method_idx) { 2338 return class_def_method_index; 2339 } 2340 class_def_method_index++; 2341 it.Next(); 2342 } 2343 while (it.HasNextVirtualMethod()) { 2344 if (it.GetMemberIndex() == method_idx) { 2345 return class_def_method_index; 2346 } 2347 class_def_method_index++; 2348 it.Next(); 2349 } 2350 DCHECK(!it.HasNext()); 2351 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation(); 2352 return 0; 2353} 2354 2355const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) { 2356 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution 2357 // method for direct methods (or virtual methods made direct). 2358 mirror::Class* declaring_class = method->GetDeclaringClass(); 2359 size_t oat_method_index; 2360 if (method->IsStatic() || method->IsDirect()) { 2361 // Simple case where the oat method index was stashed at load time. 2362 oat_method_index = method->GetMethodIndex(); 2363 } else { 2364 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index 2365 // by search for its position in the declared virtual methods. 2366 oat_method_index = declaring_class->NumDirectMethods(); 2367 size_t end = declaring_class->NumVirtualMethods(); 2368 bool found = false; 2369 for (size_t i = 0; i < end; i++) { 2370 if (declaring_class->GetVirtualMethod(i) == method) { 2371 found = true; 2372 break; 2373 } 2374 oat_method_index++; 2375 } 2376 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method); 2377 } 2378 DCHECK_EQ(oat_method_index, 2379 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(), 2380 method->GetDeclaringClass()->GetDexClassDefIndex(), 2381 method->GetDexMethodIndex())); 2382 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(), 2383 declaring_class->GetDexClassDefIndex(), 2384 found); 2385 if (!found) { 2386 return OatFile::OatMethod::Invalid(); 2387 } 2388 *found = true; 2389 return oat_class.GetOatMethod(oat_method_index); 2390} 2391 2392// Special case to get oat code without overwriting a trampoline. 2393const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) { 2394 CHECK(!method->IsAbstract()) << PrettyMethod(method); 2395 if (method->IsProxyMethod()) { 2396 return GetQuickProxyInvokeHandler(); 2397 } 2398 bool found; 2399 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found); 2400 const void* result = nullptr; 2401 if (found) { 2402 result = oat_method.GetQuickCode(); 2403 } 2404 2405 if (result == nullptr) { 2406 if (method->IsNative()) { 2407 // No code and native? Use generic trampoline. 2408 result = GetQuickGenericJniTrampoline(); 2409 } else if (method->IsPortableCompiled()) { 2410 // No code? Do we expect portable code? 2411 result = GetQuickToPortableBridge(); 2412 } else { 2413 // No code? You must mean to go into the interpreter. 2414 result = GetQuickToInterpreterBridge(); 2415 } 2416 } 2417 return result; 2418} 2419 2420const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method, 2421 bool* have_portable_code) { 2422 CHECK(!method->IsAbstract()) << PrettyMethod(method); 2423 *have_portable_code = false; 2424 if (method->IsProxyMethod()) { 2425 return GetPortableProxyInvokeHandler(); 2426 } 2427 bool found; 2428 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found); 2429 const void* result = nullptr; 2430 const void* quick_code = nullptr; 2431 if (found) { 2432 result = oat_method.GetPortableCode(); 2433 quick_code = oat_method.GetQuickCode(); 2434 } 2435 2436 if (result == nullptr) { 2437 if (quick_code == nullptr) { 2438 // No code? You must mean to go into the interpreter. 2439 result = GetPortableToInterpreterBridge(); 2440 } else { 2441 // No code? But there's quick code, so use a bridge. 2442 result = GetPortableToQuickBridge(); 2443 } 2444 } else { 2445 *have_portable_code = true; 2446 } 2447 return result; 2448} 2449 2450const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) { 2451 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) { 2452 return nullptr; 2453 } 2454 bool found; 2455 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found); 2456 return found ? oat_method.GetQuickCode() : nullptr; 2457} 2458 2459const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) { 2460 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) { 2461 return nullptr; 2462 } 2463 bool found; 2464 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found); 2465 return found ? oat_method.GetPortableCode() : nullptr; 2466} 2467 2468const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx, 2469 uint32_t method_idx) { 2470 bool found; 2471 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found); 2472 if (!found) { 2473 return nullptr; 2474 } 2475 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx); 2476 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode(); 2477} 2478 2479const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx, 2480 uint32_t method_idx) { 2481 bool found; 2482 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found); 2483 if (!found) { 2484 return nullptr; 2485 } 2486 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx); 2487 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode(); 2488} 2489 2490// Returns true if the method must run with interpreter, false otherwise. 2491static bool NeedsInterpreter( 2492 mirror::ArtMethod* method, const void* quick_code, const void* portable_code) 2493 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2494 if ((quick_code == nullptr) && (portable_code == nullptr)) { 2495 // No code: need interpreter. 2496 // May return true for native code, in the case of generic JNI 2497 // DCHECK(!method->IsNative()); 2498 return true; 2499 } 2500#ifdef ART_SEA_IR_MODE 2501 ScopedObjectAccess soa(Thread::Current()); 2502 if (std::string::npos != PrettyMethod(method).find("fibonacci")) { 2503 LOG(INFO) << "Found " << PrettyMethod(method); 2504 return false; 2505 } 2506#endif 2507 // If interpreter mode is enabled, every method (except native and proxy) must 2508 // be run with interpreter. 2509 return Runtime::Current()->GetInstrumentation()->InterpretOnly() && 2510 !method->IsNative() && !method->IsProxyMethod(); 2511} 2512 2513void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) { 2514 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass); 2515 if (klass->NumDirectMethods() == 0) { 2516 return; // No direct methods => no static methods. 2517 } 2518 Runtime* runtime = Runtime::Current(); 2519 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) { 2520 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) { 2521 return; // OAT file unavailable. 2522 } 2523 } 2524 2525 const DexFile& dex_file = klass->GetDexFile(); 2526 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 2527 CHECK(dex_class_def != nullptr); 2528 const byte* class_data = dex_file.GetClassData(*dex_class_def); 2529 // There should always be class data if there were direct methods. 2530 CHECK(class_data != nullptr) << PrettyDescriptor(klass); 2531 ClassDataItemIterator it(dex_file, class_data); 2532 // Skip fields 2533 while (it.HasNextStaticField()) { 2534 it.Next(); 2535 } 2536 while (it.HasNextInstanceField()) { 2537 it.Next(); 2538 } 2539 bool has_oat_class; 2540 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), 2541 &has_oat_class); 2542 // Link the code of methods skipped by LinkCode. 2543 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) { 2544 mirror::ArtMethod* method = klass->GetDirectMethod(method_index); 2545 if (!method->IsStatic()) { 2546 // Only update static methods. 2547 continue; 2548 } 2549 const void* portable_code = nullptr; 2550 const void* quick_code = nullptr; 2551 if (has_oat_class) { 2552 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index); 2553 portable_code = oat_method.GetPortableCode(); 2554 quick_code = oat_method.GetQuickCode(); 2555 } 2556 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code); 2557 bool have_portable_code = false; 2558 if (enter_interpreter) { 2559 // Use interpreter entry point. 2560 // Check whether the method is native, in which case it's generic JNI. 2561 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) { 2562 quick_code = GetQuickGenericJniTrampoline(); 2563 portable_code = GetPortableToQuickBridge(); 2564 } else { 2565 portable_code = GetPortableToInterpreterBridge(); 2566 quick_code = GetQuickToInterpreterBridge(); 2567 } 2568 } else { 2569 if (portable_code == nullptr) { 2570 portable_code = GetPortableToQuickBridge(); 2571 } else { 2572 have_portable_code = true; 2573 } 2574 if (quick_code == nullptr) { 2575 quick_code = GetQuickToPortableBridge(); 2576 } 2577 } 2578 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code, 2579 have_portable_code); 2580 } 2581 // Ignore virtual methods on the iterator. 2582} 2583 2584void ClassLinker::LinkCode(ConstHandle<mirror::ArtMethod> method, 2585 const OatFile::OatClass* oat_class, 2586 const DexFile& dex_file, uint32_t dex_method_index, 2587 uint32_t method_index) { 2588 if (Runtime::Current()->IsCompiler()) { 2589 // The following code only applies to a non-compiler runtime. 2590 return; 2591 } 2592 // Method shouldn't have already been linked. 2593 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr); 2594 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr); 2595 if (oat_class != nullptr) { 2596 // Every kind of method should at least get an invoke stub from the oat_method. 2597 // non-abstract methods also get their code pointers. 2598 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index); 2599 oat_method.LinkMethod(method.Get()); 2600 } 2601 2602 // Install entry point from interpreter. 2603 bool enter_interpreter = NeedsInterpreter(method.Get(), 2604 method->GetEntryPointFromQuickCompiledCode(), 2605 method->GetEntryPointFromPortableCompiledCode()); 2606 if (enter_interpreter && !method->IsNative()) { 2607 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge); 2608 } else { 2609 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge); 2610 } 2611 2612 if (method->IsAbstract()) { 2613 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 2614 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge()); 2615 return; 2616 } 2617 2618 bool have_portable_code = false; 2619 if (method->IsStatic() && !method->IsConstructor()) { 2620 // For static methods excluding the class initializer, install the trampoline. 2621 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines 2622 // after initializing class (see ClassLinker::InitializeClass method). 2623 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline()); 2624 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline()); 2625 } else if (enter_interpreter) { 2626 if (!method->IsNative()) { 2627 // Set entry point from compiled code if there's no code or in interpreter only mode. 2628 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 2629 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge()); 2630 } else { 2631 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline()); 2632 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge()); 2633 } 2634 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) { 2635 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr); 2636 have_portable_code = true; 2637 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge()); 2638 } else { 2639 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr); 2640 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge()); 2641 } 2642 2643 if (method->IsNative()) { 2644 // Unregistering restores the dlsym lookup stub. 2645 method->UnregisterNative(Thread::Current()); 2646 2647 if (enter_interpreter) { 2648 // We have a native method here without code. Then it should have either the GenericJni 2649 // trampoline as entrypoint (non-static), or the Resolution trampoline (static). 2650 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline() 2651 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline()); 2652 } 2653 } 2654 2655 // Allow instrumentation its chance to hijack code. 2656 Runtime* runtime = Runtime::Current(); 2657 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(), 2658 method->GetEntryPointFromQuickCompiledCode(), 2659 method->GetEntryPointFromPortableCompiledCode(), 2660 have_portable_code); 2661} 2662 2663 2664 2665void ClassLinker::LoadClass(const DexFile& dex_file, 2666 const DexFile::ClassDef& dex_class_def, 2667 ConstHandle<mirror::Class> klass, 2668 mirror::ClassLoader* class_loader) { 2669 CHECK(klass.Get() != NULL); 2670 CHECK(klass->GetDexCache() != NULL); 2671 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus()); 2672 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def); 2673 CHECK(descriptor != NULL); 2674 2675 klass->SetClass(GetClassRoot(kJavaLangClass)); 2676 if (kUseBakerOrBrooksReadBarrier) { 2677 klass->AssertReadBarrierPointer(); 2678 } 2679 uint32_t access_flags = dex_class_def.access_flags_; 2680 // Make sure that none of our runtime-only flags are set. 2681 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U); 2682 klass->SetAccessFlags(access_flags); 2683 klass->SetClassLoader(class_loader); 2684 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 2685 klass->SetStatus(mirror::Class::kStatusIdx, NULL); 2686 2687 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def)); 2688 klass->SetDexTypeIndex(dex_class_def.class_idx_); 2689 2690 const byte* class_data = dex_file.GetClassData(dex_class_def); 2691 if (class_data == NULL) { 2692 return; // no fields or methods - for example a marker interface 2693 } 2694 2695 2696 bool has_oat_class = false; 2697 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) { 2698 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), 2699 &has_oat_class); 2700 if (has_oat_class) { 2701 LoadClassMembers(dex_file, class_data, klass, class_loader, &oat_class); 2702 } 2703 } 2704 if (!has_oat_class) { 2705 LoadClassMembers(dex_file, class_data, klass, class_loader, nullptr); 2706 } 2707} 2708 2709void ClassLinker::LoadClassMembers(const DexFile& dex_file, 2710 const byte* class_data, 2711 ConstHandle<mirror::Class> klass, 2712 mirror::ClassLoader* class_loader, 2713 const OatFile::OatClass* oat_class) { 2714 // Load fields. 2715 ClassDataItemIterator it(dex_file, class_data); 2716 Thread* self = Thread::Current(); 2717 if (it.NumStaticFields() != 0) { 2718 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields()); 2719 if (UNLIKELY(statics == NULL)) { 2720 CHECK(self->IsExceptionPending()); // OOME. 2721 return; 2722 } 2723 klass->SetSFields(statics); 2724 } 2725 if (it.NumInstanceFields() != 0) { 2726 mirror::ObjectArray<mirror::ArtField>* fields = 2727 AllocArtFieldArray(self, it.NumInstanceFields()); 2728 if (UNLIKELY(fields == NULL)) { 2729 CHECK(self->IsExceptionPending()); // OOME. 2730 return; 2731 } 2732 klass->SetIFields(fields); 2733 } 2734 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) { 2735 StackHandleScope<1> hs(self); 2736 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self))); 2737 if (UNLIKELY(sfield.Get() == NULL)) { 2738 CHECK(self->IsExceptionPending()); // OOME. 2739 return; 2740 } 2741 klass->SetStaticField(i, sfield.Get()); 2742 LoadField(dex_file, it, klass, sfield); 2743 } 2744 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) { 2745 StackHandleScope<1> hs(self); 2746 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self))); 2747 if (UNLIKELY(ifield.Get() == NULL)) { 2748 CHECK(self->IsExceptionPending()); // OOME. 2749 return; 2750 } 2751 klass->SetInstanceField(i, ifield.Get()); 2752 LoadField(dex_file, it, klass, ifield); 2753 } 2754 2755 // Load methods. 2756 if (it.NumDirectMethods() != 0) { 2757 // TODO: append direct methods to class object 2758 mirror::ObjectArray<mirror::ArtMethod>* directs = 2759 AllocArtMethodArray(self, it.NumDirectMethods()); 2760 if (UNLIKELY(directs == NULL)) { 2761 CHECK(self->IsExceptionPending()); // OOME. 2762 return; 2763 } 2764 klass->SetDirectMethods(directs); 2765 } 2766 if (it.NumVirtualMethods() != 0) { 2767 // TODO: append direct methods to class object 2768 mirror::ObjectArray<mirror::ArtMethod>* virtuals = 2769 AllocArtMethodArray(self, it.NumVirtualMethods()); 2770 if (UNLIKELY(virtuals == NULL)) { 2771 CHECK(self->IsExceptionPending()); // OOME. 2772 return; 2773 } 2774 klass->SetVirtualMethods(virtuals); 2775 } 2776 size_t class_def_method_index = 0; 2777 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) { 2778 StackHandleScope<1> hs(self); 2779 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass))); 2780 if (UNLIKELY(method.Get() == NULL)) { 2781 CHECK(self->IsExceptionPending()); // OOME. 2782 return; 2783 } 2784 klass->SetDirectMethod(i, method.Get()); 2785 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index); 2786 method->SetMethodIndex(class_def_method_index); 2787 class_def_method_index++; 2788 } 2789 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) { 2790 StackHandleScope<1> hs(self); 2791 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass))); 2792 if (UNLIKELY(method.Get() == NULL)) { 2793 CHECK(self->IsExceptionPending()); // OOME. 2794 return; 2795 } 2796 klass->SetVirtualMethod(i, method.Get()); 2797 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i); 2798 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index); 2799 class_def_method_index++; 2800 } 2801 DCHECK(!it.HasNext()); 2802} 2803 2804void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it, 2805 ConstHandle<mirror::Class> klass, 2806 ConstHandle<mirror::ArtField> dst) { 2807 uint32_t field_idx = it.GetMemberIndex(); 2808 dst->SetDexFieldIndex(field_idx); 2809 dst->SetDeclaringClass(klass.Get()); 2810 dst->SetAccessFlags(it.GetMemberAccessFlags()); 2811} 2812 2813mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file, 2814 const ClassDataItemIterator& it, 2815 ConstHandle<mirror::Class> klass) { 2816 uint32_t dex_method_idx = it.GetMemberIndex(); 2817 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx); 2818 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_); 2819 2820 mirror::ArtMethod* dst = AllocArtMethod(self); 2821 if (UNLIKELY(dst == NULL)) { 2822 CHECK(self->IsExceptionPending()); // OOME. 2823 return NULL; 2824 } 2825 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass()); 2826 2827 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod"); 2828 dst->SetDexMethodIndex(dex_method_idx); 2829 dst->SetDeclaringClass(klass.Get()); 2830 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset()); 2831 2832 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings()); 2833 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods()); 2834 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes()); 2835 2836 uint32_t access_flags = it.GetMemberAccessFlags(); 2837 2838 if (UNLIKELY(strcmp("finalize", method_name) == 0)) { 2839 // Set finalizable flag on declaring class. 2840 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) { 2841 // Void return type. 2842 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged. 2843 klass->SetFinalizable(); 2844 } else { 2845 std::string temp; 2846 const char* klass_descriptor = klass->GetDescriptor(&temp); 2847 // The Enum class declares a "final" finalize() method to prevent subclasses from 2848 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its 2849 // subclasses, so we exclude it here. 2850 // We also want to avoid setting the flag on Object, where we know that finalize() is 2851 // empty. 2852 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 && 2853 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) { 2854 klass->SetFinalizable(); 2855 } 2856 } 2857 } 2858 } else if (method_name[0] == '<') { 2859 // Fix broken access flags for initializers. Bug 11157540. 2860 bool is_init = (strcmp("<init>", method_name) == 0); 2861 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0); 2862 if (UNLIKELY(!is_init && !is_clinit)) { 2863 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name; 2864 } else { 2865 if (UNLIKELY((access_flags & kAccConstructor) == 0)) { 2866 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class " 2867 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation(); 2868 access_flags |= kAccConstructor; 2869 } 2870 } 2871 } 2872 dst->SetAccessFlags(access_flags); 2873 2874 self->EndAssertNoThreadSuspension(old_cause); 2875 return dst; 2876} 2877 2878void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) { 2879 Thread* self = Thread::Current(); 2880 StackHandleScope<1> hs(self); 2881 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file))); 2882 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation(); 2883 AppendToBootClassPath(dex_file, dex_cache); 2884} 2885 2886void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, 2887 ConstHandle<mirror::DexCache> dex_cache) { 2888 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation(); 2889 boot_class_path_.push_back(&dex_file); 2890 RegisterDexFile(dex_file, dex_cache); 2891} 2892 2893bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) { 2894 dex_lock_.AssertSharedHeld(Thread::Current()); 2895 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2896 mirror::DexCache* dex_cache = GetDexCache(i); 2897 if (dex_cache->GetDexFile() == &dex_file) { 2898 return true; 2899 } 2900 } 2901 return false; 2902} 2903 2904bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) { 2905 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2906 return IsDexFileRegisteredLocked(dex_file); 2907} 2908 2909void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, 2910 ConstHandle<mirror::DexCache> dex_cache) { 2911 dex_lock_.AssertExclusiveHeld(Thread::Current()); 2912 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation(); 2913 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation())) 2914 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation(); 2915 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get())); 2916 dex_cache->SetDexFile(&dex_file); 2917 if (log_new_dex_caches_roots_) { 2918 // TODO: This is not safe if we can remove dex caches. 2919 new_dex_cache_roots_.push_back(dex_caches_.size() - 1); 2920 } 2921} 2922 2923void ClassLinker::RegisterDexFile(const DexFile& dex_file) { 2924 Thread* self = Thread::Current(); 2925 { 2926 ReaderMutexLock mu(self, dex_lock_); 2927 if (IsDexFileRegisteredLocked(dex_file)) { 2928 return; 2929 } 2930 } 2931 // Don't alloc while holding the lock, since allocation may need to 2932 // suspend all threads and another thread may need the dex_lock_ to 2933 // get to a suspend point. 2934 StackHandleScope<1> hs(self); 2935 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file))); 2936 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation(); 2937 { 2938 WriterMutexLock mu(self, dex_lock_); 2939 if (IsDexFileRegisteredLocked(dex_file)) { 2940 return; 2941 } 2942 RegisterDexFileLocked(dex_file, dex_cache); 2943 } 2944} 2945 2946void ClassLinker::RegisterDexFile(const DexFile& dex_file, 2947 ConstHandle<mirror::DexCache> dex_cache) { 2948 WriterMutexLock mu(Thread::Current(), dex_lock_); 2949 RegisterDexFileLocked(dex_file, dex_cache); 2950} 2951 2952mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) { 2953 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2954 // Search assuming unique-ness of dex file. 2955 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2956 mirror::DexCache* dex_cache = GetDexCache(i); 2957 if (dex_cache->GetDexFile() == &dex_file) { 2958 return dex_cache; 2959 } 2960 } 2961 // Search matching by location name. 2962 std::string location(dex_file.GetLocation()); 2963 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2964 mirror::DexCache* dex_cache = GetDexCache(i); 2965 if (dex_cache->GetDexFile()->GetLocation() == location) { 2966 return dex_cache; 2967 } 2968 } 2969 // Failure, dump diagnostic and abort. 2970 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2971 mirror::DexCache* dex_cache = GetDexCache(i); 2972 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation(); 2973 } 2974 LOG(FATAL) << "Failed to find DexCache for DexFile " << location; 2975 return NULL; 2976} 2977 2978void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) { 2979 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2980 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2981 mirror::DexCache* dex_cache = GetDexCache(i); 2982 dex_cache->Fixup(resolution_method); 2983 } 2984} 2985 2986mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) { 2987 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize()); 2988 if (UNLIKELY(klass == NULL)) { 2989 return NULL; 2990 } 2991 return InitializePrimitiveClass(klass, type); 2992} 2993 2994mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class, 2995 Primitive::Type type) { 2996 CHECK(primitive_class != NULL); 2997 // Must hold lock on object when initializing. 2998 Thread* self = Thread::Current(); 2999 StackHandleScope<1> hs(self); 3000 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class)); 3001 ObjectLock<mirror::Class> lock(self, h_class); 3002 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract); 3003 primitive_class->SetPrimitiveType(type); 3004 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self); 3005 const char* descriptor = Primitive::Descriptor(type); 3006 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor)); 3007 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed"; 3008 return primitive_class; 3009} 3010 3011// Create an array class (i.e. the class object for the array, not the 3012// array itself). "descriptor" looks like "[C" or "[[[[B" or 3013// "[Ljava/lang/String;". 3014// 3015// If "descriptor" refers to an array of primitives, look up the 3016// primitive type's internally-generated class object. 3017// 3018// "class_loader" is the class loader of the class that's referring to 3019// us. It's used to ensure that we're looking for the element type in 3020// the right context. It does NOT become the class loader for the 3021// array class; that always comes from the base element class. 3022// 3023// Returns NULL with an exception raised on failure. 3024mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, 3025 ConstHandle<mirror::ClassLoader> class_loader) { 3026 // Identify the underlying component type 3027 CHECK_EQ('[', descriptor[0]); 3028 StackHandleScope<2> hs(self); 3029 Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader))); 3030 if (component_type.Get() == nullptr) { 3031 DCHECK(self->IsExceptionPending()); 3032 // We need to accept erroneous classes as component types. 3033 component_type.Assign(LookupClass(descriptor + 1, class_loader.Get())); 3034 if (component_type.Get() == nullptr) { 3035 DCHECK(self->IsExceptionPending()); 3036 return nullptr; 3037 } else { 3038 self->ClearException(); 3039 } 3040 } 3041 if (UNLIKELY(component_type->IsPrimitiveVoid())) { 3042 ThrowNoClassDefFoundError("Attempt to create array of void primitive type"); 3043 return nullptr; 3044 } 3045 // See if the component type is already loaded. Array classes are 3046 // always associated with the class loader of their underlying 3047 // element type -- an array of Strings goes with the loader for 3048 // java/lang/String -- so we need to look for it there. (The 3049 // caller should have checked for the existence of the class 3050 // before calling here, but they did so with *their* class loader, 3051 // not the component type's loader.) 3052 // 3053 // If we find it, the caller adds "loader" to the class' initiating 3054 // loader list, which should prevent us from going through this again. 3055 // 3056 // This call is unnecessary if "loader" and "component_type->GetClassLoader()" 3057 // are the same, because our caller (FindClass) just did the 3058 // lookup. (Even if we get this wrong we still have correct behavior, 3059 // because we effectively do this lookup again when we add the new 3060 // class to the hash table --- necessary because of possible races with 3061 // other threads.) 3062 if (class_loader.Get() != component_type->GetClassLoader()) { 3063 mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader()); 3064 if (new_class != NULL) { 3065 return new_class; 3066 } 3067 } 3068 3069 // Fill out the fields in the Class. 3070 // 3071 // It is possible to execute some methods against arrays, because 3072 // all arrays are subclasses of java_lang_Object_, so we need to set 3073 // up a vtable. We can just point at the one in java_lang_Object_. 3074 // 3075 // Array classes are simple enough that we don't need to do a full 3076 // link step. 3077 auto new_class = hs.NewHandle<mirror::Class>(nullptr); 3078 if (UNLIKELY(!init_done_)) { 3079 // Classes that were hand created, ie not by FindSystemClass 3080 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) { 3081 new_class.Assign(GetClassRoot(kClassArrayClass)); 3082 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) { 3083 new_class.Assign(GetClassRoot(kObjectArrayClass)); 3084 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) { 3085 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass)); 3086 } else if (strcmp(descriptor, 3087 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) { 3088 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass)); 3089 } else if (strcmp(descriptor, 3090 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) { 3091 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass)); 3092 } else if (strcmp(descriptor, "[C") == 0) { 3093 new_class.Assign(GetClassRoot(kCharArrayClass)); 3094 } else if (strcmp(descriptor, "[I") == 0) { 3095 new_class.Assign(GetClassRoot(kIntArrayClass)); 3096 } 3097 } 3098 if (new_class.Get() == nullptr) { 3099 new_class.Assign(AllocClass(self, mirror::Array::ClassSize())); 3100 if (new_class.Get() == nullptr) { 3101 return nullptr; 3102 } 3103 new_class->SetComponentType(component_type.Get()); 3104 } 3105 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing. 3106 DCHECK(new_class->GetComponentType() != NULL); 3107 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject); 3108 new_class->SetSuperClass(java_lang_Object); 3109 new_class->SetVTable(java_lang_Object->GetVTable()); 3110 new_class->SetPrimitiveType(Primitive::kPrimNot); 3111 new_class->SetClassLoader(component_type->GetClassLoader()); 3112 new_class->SetStatus(mirror::Class::kStatusLoaded, self); 3113 new_class->PopulateEmbeddedImtAndVTable(); 3114 new_class->SetStatus(mirror::Class::kStatusInitialized, self); 3115 // don't need to set new_class->SetObjectSize(..) 3116 // because Object::SizeOf delegates to Array::SizeOf 3117 3118 3119 // All arrays have java/lang/Cloneable and java/io/Serializable as 3120 // interfaces. We need to set that up here, so that stuff like 3121 // "instanceof" works right. 3122 // 3123 // Note: The GC could run during the call to FindSystemClass, 3124 // so we need to make sure the class object is GC-valid while we're in 3125 // there. Do this by clearing the interface list so the GC will just 3126 // think that the entries are null. 3127 3128 3129 // Use the single, global copies of "interfaces" and "iftable" 3130 // (remember not to free them for arrays). 3131 { 3132 mirror::IfTable* array_iftable = array_iftable_.Read(); 3133 CHECK(array_iftable != nullptr); 3134 new_class->SetIfTable(array_iftable); 3135 } 3136 3137 // Inherit access flags from the component type. 3138 int access_flags = new_class->GetComponentType()->GetAccessFlags(); 3139 // Lose any implementation detail flags; in particular, arrays aren't finalizable. 3140 access_flags &= kAccJavaFlagsMask; 3141 // Arrays can't be used as a superclass or interface, so we want to add "abstract final" 3142 // and remove "interface". 3143 access_flags |= kAccAbstract | kAccFinal; 3144 access_flags &= ~kAccInterface; 3145 3146 new_class->SetAccessFlags(access_flags); 3147 3148 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor)); 3149 if (existing == nullptr) { 3150 return new_class.Get(); 3151 } 3152 // Another thread must have loaded the class after we 3153 // started but before we finished. Abandon what we've 3154 // done. 3155 // 3156 // (Yes, this happens.) 3157 3158 return existing; 3159} 3160 3161mirror::Class* ClassLinker::FindPrimitiveClass(char type) { 3162 switch (type) { 3163 case 'B': 3164 return GetClassRoot(kPrimitiveByte); 3165 case 'C': 3166 return GetClassRoot(kPrimitiveChar); 3167 case 'D': 3168 return GetClassRoot(kPrimitiveDouble); 3169 case 'F': 3170 return GetClassRoot(kPrimitiveFloat); 3171 case 'I': 3172 return GetClassRoot(kPrimitiveInt); 3173 case 'J': 3174 return GetClassRoot(kPrimitiveLong); 3175 case 'S': 3176 return GetClassRoot(kPrimitiveShort); 3177 case 'Z': 3178 return GetClassRoot(kPrimitiveBoolean); 3179 case 'V': 3180 return GetClassRoot(kPrimitiveVoid); 3181 default: 3182 break; 3183 } 3184 std::string printable_type(PrintableChar(type)); 3185 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str()); 3186 return NULL; 3187} 3188 3189mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, 3190 size_t hash) { 3191 if (VLOG_IS_ON(class_linker)) { 3192 mirror::DexCache* dex_cache = klass->GetDexCache(); 3193 std::string source; 3194 if (dex_cache != NULL) { 3195 source += " from "; 3196 source += dex_cache->GetLocation()->ToModifiedUtf8(); 3197 } 3198 LOG(INFO) << "Loaded class " << descriptor << source; 3199 } 3200 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3201 mirror::Class* existing = 3202 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash); 3203 if (existing != NULL) { 3204 return existing; 3205 } 3206 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == NULL && 3207 dex_cache_image_class_lookup_required_) { 3208 // Check a class loaded with the system class loader matches one in the image if the class 3209 // is in the image. 3210 existing = LookupClassFromImage(descriptor); 3211 if (existing != NULL) { 3212 CHECK(klass == existing); 3213 } 3214 } 3215 VerifyObject(klass); 3216 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass))); 3217 if (log_new_class_table_roots_) { 3218 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass))); 3219 } 3220 return NULL; 3221} 3222 3223mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass, 3224 size_t hash) { 3225 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3226 mirror::Class* existing = 3227 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash); 3228 3229 if (existing == nullptr) { 3230 CHECK(klass->IsProxyClass()); 3231 return nullptr; 3232 } 3233 3234 CHECK_NE(existing, klass) << descriptor; 3235 CHECK(!existing->IsResolved()) << descriptor; 3236 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor; 3237 3238 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash; 3239 ++it) { 3240 mirror::Class* klass = it->second.Read(); 3241 if (klass == existing) { 3242 class_table_.erase(it); 3243 break; 3244 } 3245 } 3246 3247 CHECK(!klass->IsTemp()) << descriptor; 3248 if (kIsDebugBuild && klass->GetClassLoader() == nullptr && 3249 dex_cache_image_class_lookup_required_) { 3250 // Check a class loaded with the system class loader matches one in the image if the class 3251 // is in the image. 3252 existing = LookupClassFromImage(descriptor); 3253 if (existing != nullptr) { 3254 CHECK(klass == existing) << descriptor; 3255 } 3256 } 3257 VerifyObject(klass); 3258 3259 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass))); 3260 if (log_new_class_table_roots_) { 3261 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass))); 3262 } 3263 3264 return existing; 3265} 3266 3267bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) { 3268 size_t hash = Hash(descriptor); 3269 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3270 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); 3271 it != end && it->first == hash; 3272 ++it) { 3273 mirror::Class* klass = it->second.Read(); 3274 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) { 3275 class_table_.erase(it); 3276 return true; 3277 } 3278 } 3279 return false; 3280} 3281 3282mirror::Class* ClassLinker::LookupClass(const char* descriptor, 3283 const mirror::ClassLoader* class_loader) { 3284 size_t hash = Hash(descriptor); 3285 { 3286 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3287 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash); 3288 if (result != NULL) { 3289 return result; 3290 } 3291 } 3292 if (class_loader != NULL || !dex_cache_image_class_lookup_required_) { 3293 return NULL; 3294 } else { 3295 // Lookup failed but need to search dex_caches_. 3296 mirror::Class* result = LookupClassFromImage(descriptor); 3297 if (result != NULL) { 3298 InsertClass(descriptor, result, hash); 3299 } else { 3300 // Searching the image dex files/caches failed, we don't want to get into this situation 3301 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image 3302 // classes into the class table. 3303 constexpr uint32_t kMaxFailedDexCacheLookups = 1000; 3304 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) { 3305 MoveImageClassesToClassTable(); 3306 } 3307 } 3308 return result; 3309 } 3310} 3311 3312mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor, 3313 const mirror::ClassLoader* class_loader, 3314 size_t hash) { 3315 auto end = class_table_.end(); 3316 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) { 3317 mirror::Class* klass = it->second.Read(); 3318 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) { 3319 if (kIsDebugBuild) { 3320 // Check for duplicates in the table. 3321 for (++it; it != end && it->first == hash; ++it) { 3322 mirror::Class* klass2 = it->second.Read(); 3323 CHECK(!(klass2->GetClassLoader() == class_loader && 3324 klass2->DescriptorEquals(descriptor))) 3325 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " " 3326 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader(); 3327 } 3328 } 3329 return klass; 3330 } 3331 } 3332 return NULL; 3333} 3334 3335static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches() 3336 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3337 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace(); 3338 CHECK(image != NULL); 3339 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 3340 return root->AsObjectArray<mirror::DexCache>(); 3341} 3342 3343void ClassLinker::MoveImageClassesToClassTable() { 3344 Thread* self = Thread::Current(); 3345 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 3346 if (!dex_cache_image_class_lookup_required_) { 3347 return; // All dex cache classes are already in the class table. 3348 } 3349 const char* old_no_suspend_cause = 3350 self->StartAssertNoThreadSuspension("Moving image classes to class table"); 3351 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 3352 std::string temp; 3353 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 3354 mirror::DexCache* dex_cache = dex_caches->Get(i); 3355 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes(); 3356 for (int32_t j = 0; j < types->GetLength(); j++) { 3357 mirror::Class* klass = types->Get(j); 3358 if (klass != NULL) { 3359 DCHECK(klass->GetClassLoader() == NULL); 3360 const char* descriptor = klass->GetDescriptor(&temp); 3361 size_t hash = Hash(descriptor); 3362 mirror::Class* existing = LookupClassFromTableLocked(descriptor, NULL, hash); 3363 if (existing != NULL) { 3364 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != " 3365 << PrettyClassAndClassLoader(klass); 3366 } else { 3367 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass))); 3368 if (log_new_class_table_roots_) { 3369 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass))); 3370 } 3371 } 3372 } 3373 } 3374 } 3375 dex_cache_image_class_lookup_required_ = false; 3376 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 3377} 3378 3379mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) { 3380 Thread* self = Thread::Current(); 3381 const char* old_no_suspend_cause = 3382 self->StartAssertNoThreadSuspension("Image class lookup"); 3383 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 3384 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) { 3385 mirror::DexCache* dex_cache = dex_caches->Get(i); 3386 const DexFile* dex_file = dex_cache->GetDexFile(); 3387 // Try binary searching the string/type index. 3388 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor); 3389 if (string_id != NULL) { 3390 const DexFile::TypeId* type_id = 3391 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id)); 3392 if (type_id != NULL) { 3393 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id); 3394 mirror::Class* klass = dex_cache->GetResolvedType(type_idx); 3395 if (klass != NULL) { 3396 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 3397 return klass; 3398 } 3399 } 3400 } 3401 } 3402 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 3403 return NULL; 3404} 3405 3406void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) { 3407 result.clear(); 3408 if (dex_cache_image_class_lookup_required_) { 3409 MoveImageClassesToClassTable(); 3410 } 3411 size_t hash = Hash(descriptor); 3412 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3413 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); 3414 it != end && it->first == hash; ++it) { 3415 mirror::Class* klass = it->second.Read(); 3416 if (klass->DescriptorEquals(descriptor)) { 3417 result.push_back(klass); 3418 } 3419 } 3420} 3421 3422void ClassLinker::VerifyClass(ConstHandle<mirror::Class> klass) { 3423 // TODO: assert that the monitor on the Class is held 3424 Thread* self = Thread::Current(); 3425 ObjectLock<mirror::Class> lock(self, klass); 3426 3427 // Don't attempt to re-verify if already sufficiently verified. 3428 if (klass->IsVerified() || 3429 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) { 3430 return; 3431 } 3432 3433 // The class might already be erroneous, for example at compile time if we attempted to verify 3434 // this class as a parent to another. 3435 if (klass->IsErroneous()) { 3436 ThrowEarlierClassFailure(klass.Get()); 3437 return; 3438 } 3439 3440 if (klass->GetStatus() == mirror::Class::kStatusResolved) { 3441 klass->SetStatus(mirror::Class::kStatusVerifying, self); 3442 } else { 3443 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime) 3444 << PrettyClass(klass.Get()); 3445 CHECK(!Runtime::Current()->IsCompiler()); 3446 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self); 3447 } 3448 3449 // Skip verification if disabled. 3450 if (!Runtime::Current()->IsVerificationEnabled()) { 3451 klass->SetStatus(mirror::Class::kStatusVerified, self); 3452 return; 3453 } 3454 3455 // Verify super class. 3456 StackHandleScope<2> hs(self); 3457 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass())); 3458 if (super.Get() != NULL) { 3459 // Acquire lock to prevent races on verifying the super class. 3460 ObjectLock<mirror::Class> lock(self, super); 3461 3462 if (!super->IsVerified() && !super->IsErroneous()) { 3463 VerifyClass(super); 3464 } 3465 if (!super->IsCompileTimeVerified()) { 3466 std::string error_msg( 3467 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s", 3468 PrettyDescriptor(klass.Get()).c_str(), 3469 PrettyDescriptor(super.Get()).c_str())); 3470 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3471 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr))); 3472 if (cause.Get() != nullptr) { 3473 self->ClearException(); 3474 } 3475 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3476 if (cause.Get() != nullptr) { 3477 self->GetException(nullptr)->SetCause(cause.Get()); 3478 } 3479 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex()); 3480 if (Runtime::Current()->IsCompiler()) { 3481 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref); 3482 } 3483 klass->SetStatus(mirror::Class::kStatusError, self); 3484 return; 3485 } 3486 } 3487 3488 // Try to use verification information from the oat file, otherwise do runtime verification. 3489 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile(); 3490 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady); 3491 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status); 3492 if (oat_file_class_status == mirror::Class::kStatusError) { 3493 VLOG(class_linker) << "Skipping runtime verification of erroneous class " 3494 << PrettyDescriptor(klass.Get()) << " in " 3495 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3496 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification", 3497 PrettyDescriptor(klass.Get()).c_str()); 3498 klass->SetStatus(mirror::Class::kStatusError, self); 3499 return; 3500 } 3501 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure; 3502 std::string error_msg; 3503 if (!preverified) { 3504 verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(), 3505 Runtime::Current()->IsCompiler(), 3506 &error_msg); 3507 } 3508 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) { 3509 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) { 3510 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get()) 3511 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3512 << " because: " << error_msg; 3513 } 3514 self->AssertNoPendingException(); 3515 // Make sure all classes referenced by catch blocks are resolved. 3516 ResolveClassExceptionHandlerTypes(dex_file, klass); 3517 if (verifier_failure == verifier::MethodVerifier::kNoFailure) { 3518 // Even though there were no verifier failures we need to respect whether the super-class 3519 // was verified or requiring runtime reverification. 3520 if (super.Get() == NULL || super->IsVerified()) { 3521 klass->SetStatus(mirror::Class::kStatusVerified, self); 3522 } else { 3523 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 3524 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self); 3525 // Pretend a soft failure occured so that we don't consider the class verified below. 3526 verifier_failure = verifier::MethodVerifier::kSoftFailure; 3527 } 3528 } else { 3529 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure); 3530 // Soft failures at compile time should be retried at runtime. Soft 3531 // failures at runtime will be handled by slow paths in the generated 3532 // code. Set status accordingly. 3533 if (Runtime::Current()->IsCompiler()) { 3534 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self); 3535 } else { 3536 klass->SetStatus(mirror::Class::kStatusVerified, self); 3537 } 3538 } 3539 } else { 3540 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get()) 3541 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3542 << " because: " << error_msg; 3543 self->AssertNoPendingException(); 3544 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3545 klass->SetStatus(mirror::Class::kStatusError, self); 3546 } 3547 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) { 3548 // Class is verified so we don't need to do any access check on its methods. 3549 // Let the interpreter know it by setting the kAccPreverified flag onto each 3550 // method. 3551 // Note: we're going here during compilation and at runtime. When we set the 3552 // kAccPreverified flag when compiling image classes, the flag is recorded 3553 // in the image and is set when loading the image. 3554 klass->SetPreverifiedFlagOnAllMethods(); 3555 } 3556} 3557 3558bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass, 3559 mirror::Class::Status& oat_file_class_status) { 3560 // If we're compiling, we can only verify the class using the oat file if 3561 // we are not compiling the image or if the class we're verifying is not part of 3562 // the app. In other words, we will only check for preverification of bootclasspath 3563 // classes. 3564 if (Runtime::Current()->IsCompiler()) { 3565 // Are we compiling the bootclasspath? 3566 if (!Runtime::Current()->UseCompileTimeClassPath()) { 3567 return false; 3568 } 3569 // We are compiling an app (not the image). 3570 3571 // Is this an app class? (I.e. not a bootclasspath class) 3572 if (klass->GetClassLoader() != NULL) { 3573 return false; 3574 } 3575 } 3576 3577 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file); 3578 // Make this work with gtests, which do not set up the image properly. 3579 // TODO: we should clean up gtests to set up the image path properly. 3580 if (Runtime::Current()->IsCompiler() || (oat_file == NULL)) { 3581 return false; 3582 } 3583 3584 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass); 3585 uint dex_location_checksum = dex_file.GetLocationChecksum(); 3586 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(), 3587 &dex_location_checksum); 3588 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass); 3589 uint16_t class_def_index = klass->GetDexClassDefIndex(); 3590 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus(); 3591 if (oat_file_class_status == mirror::Class::kStatusVerified || 3592 oat_file_class_status == mirror::Class::kStatusInitialized) { 3593 return true; 3594 } 3595 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) { 3596 // Compile time verification failed with a soft error. Compile time verification can fail 3597 // because we have incomplete type information. Consider the following: 3598 // class ... { 3599 // Foo x; 3600 // .... () { 3601 // if (...) { 3602 // v1 gets assigned a type of resolved class Foo 3603 // } else { 3604 // v1 gets assigned a type of unresolved class Bar 3605 // } 3606 // iput x = v1 3607 // } } 3608 // when we merge v1 following the if-the-else it results in Conflict 3609 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be 3610 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as 3611 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk 3612 // at compile time). 3613 return false; 3614 } 3615 if (oat_file_class_status == mirror::Class::kStatusError) { 3616 // Compile time verification failed with a hard error. This is caused by invalid instructions 3617 // in the class. These errors are unrecoverable. 3618 return false; 3619 } 3620 if (oat_file_class_status == mirror::Class::kStatusNotReady) { 3621 // Status is uninitialized if we couldn't determine the status at compile time, for example, 3622 // not loading the class. 3623 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy 3624 // isn't a problem and this case shouldn't occur 3625 return false; 3626 } 3627 std::string temp; 3628 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status 3629 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " 3630 << klass->GetDescriptor(&temp); 3631 3632 return false; 3633} 3634 3635void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, 3636 ConstHandle<mirror::Class> klass) { 3637 for (size_t i = 0; i < klass->NumDirectMethods(); i++) { 3638 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i)); 3639 } 3640 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) { 3641 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i)); 3642 } 3643} 3644 3645void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, 3646 mirror::ArtMethod* method) { 3647 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod. 3648 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset()); 3649 if (code_item == NULL) { 3650 return; // native or abstract method 3651 } 3652 if (code_item->tries_size_ == 0) { 3653 return; // nothing to process 3654 } 3655 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0); 3656 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 3657 ClassLinker* linker = Runtime::Current()->GetClassLinker(); 3658 for (uint32_t idx = 0; idx < handlers_size; idx++) { 3659 CatchHandlerIterator iterator(handlers_ptr); 3660 for (; iterator.HasNext(); iterator.Next()) { 3661 // Ensure exception types are resolved so that they don't need resolution to be delivered, 3662 // unresolved exception types will be ignored by exception delivery 3663 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) { 3664 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method); 3665 if (exception_type == NULL) { 3666 DCHECK(Thread::Current()->IsExceptionPending()); 3667 Thread::Current()->ClearException(); 3668 } 3669 } 3670 } 3671 handlers_ptr = iterator.EndDataPointer(); 3672 } 3673} 3674 3675static void CheckProxyConstructor(mirror::ArtMethod* constructor); 3676static void CheckProxyMethod(ConstHandle<mirror::ArtMethod> method, 3677 ConstHandle<mirror::ArtMethod> prototype); 3678 3679mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name, 3680 jobjectArray interfaces, jobject loader, 3681 jobjectArray methods, jobjectArray throws) { 3682 Thread* self = soa.Self(); 3683 StackHandleScope<8> hs(self); 3684 Handle<mirror::Class> klass(hs.NewHandle( 3685 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class)))); 3686 if (klass.Get() == NULL) { 3687 CHECK(self->IsExceptionPending()); // OOME. 3688 return NULL; 3689 } 3690 DCHECK(klass->GetClass() != NULL); 3691 klass->SetObjectSize(sizeof(mirror::Proxy)); 3692 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal); 3693 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader)); 3694 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 3695 klass->SetName(soa.Decode<mirror::String*>(name)); 3696 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy); 3697 klass->SetDexCache(proxy_class->GetDexCache()); 3698 klass->SetStatus(mirror::Class::kStatusIdx, self); 3699 3700 // Instance fields are inherited, but we add a couple of static fields... 3701 { 3702 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2); 3703 if (UNLIKELY(sfields == NULL)) { 3704 CHECK(self->IsExceptionPending()); // OOME. 3705 return NULL; 3706 } 3707 klass->SetSFields(sfields); 3708 } 3709 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by 3710 // our proxy, so Class.getInterfaces doesn't return the flattened set. 3711 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self))); 3712 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) { 3713 CHECK(self->IsExceptionPending()); // OOME. 3714 return nullptr; 3715 } 3716 klass->SetStaticField(0, interfaces_sfield.Get()); 3717 interfaces_sfield->SetDexFieldIndex(0); 3718 interfaces_sfield->SetDeclaringClass(klass.Get()); 3719 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 3720 // 2. Create a static field 'throws' that holds exceptions thrown by our methods. 3721 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self))); 3722 if (UNLIKELY(throws_sfield.Get() == nullptr)) { 3723 CHECK(self->IsExceptionPending()); // OOME. 3724 return nullptr; 3725 } 3726 klass->SetStaticField(1, throws_sfield.Get()); 3727 throws_sfield->SetDexFieldIndex(1); 3728 throws_sfield->SetDeclaringClass(klass.Get()); 3729 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 3730 3731 // Proxies have 1 direct method, the constructor 3732 { 3733 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1); 3734 if (UNLIKELY(directs == nullptr)) { 3735 CHECK(self->IsExceptionPending()); // OOME. 3736 return nullptr; 3737 } 3738 klass->SetDirectMethods(directs); 3739 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class); 3740 if (UNLIKELY(constructor == nullptr)) { 3741 CHECK(self->IsExceptionPending()); // OOME. 3742 return nullptr; 3743 } 3744 klass->SetDirectMethod(0, constructor); 3745 } 3746 3747 // Create virtual method using specified prototypes. 3748 size_t num_virtual_methods = 3749 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength(); 3750 { 3751 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self, 3752 num_virtual_methods); 3753 if (UNLIKELY(virtuals == NULL)) { 3754 CHECK(self->IsExceptionPending()); // OOME. 3755 return NULL; 3756 } 3757 klass->SetVirtualMethods(virtuals); 3758 } 3759 for (size_t i = 0; i < num_virtual_methods; ++i) { 3760 StackHandleScope<1> hs(self); 3761 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods = 3762 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods); 3763 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i))); 3764 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype); 3765 if (UNLIKELY(clone == nullptr)) { 3766 CHECK(self->IsExceptionPending()); // OOME. 3767 return nullptr; 3768 } 3769 klass->SetVirtualMethod(i, clone); 3770 } 3771 3772 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy 3773 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state. 3774 self->AssertNoPendingException(); 3775 3776 std::string descriptor(GetDescriptorForProxy(klass.Get())); 3777 mirror::Class* new_class = nullptr; 3778 { 3779 ObjectLock<mirror::Class> resolution_lock(self, klass); // Must hold lock on object when resolved. 3780 // Link the fields and virtual methods, creating vtable and iftables 3781 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces( 3782 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces))); 3783 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) { 3784 klass->SetStatus(mirror::Class::kStatusError, self); 3785 return nullptr; 3786 } 3787 } 3788 3789 CHECK(klass->IsRetired()); 3790 CHECK_NE(klass.Get(), new_class); 3791 klass.Assign(new_class); 3792 3793 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class); 3794 interfaces_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 3795 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class); 3796 throws_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws)); 3797 3798 { 3799 // Lock on klass is released. Lock new class object. 3800 ObjectLock<mirror::Class> initialization_lock(self, klass); 3801 klass->SetStatus(mirror::Class::kStatusInitialized, self); 3802 } 3803 3804 // sanity checks 3805 if (kIsDebugBuild) { 3806 CHECK(klass->GetIFields() == nullptr); 3807 CheckProxyConstructor(klass->GetDirectMethod(0)); 3808 for (size_t i = 0; i < num_virtual_methods; ++i) { 3809 StackHandleScope<2> hs(self); 3810 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods = 3811 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods); 3812 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i))); 3813 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i))); 3814 CheckProxyMethod(virtual_method, prototype); 3815 } 3816 3817 mirror::String* decoded_name = soa.Decode<mirror::String*>(name); 3818 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces", 3819 decoded_name->ToModifiedUtf8().c_str())); 3820 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name); 3821 3822 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws", 3823 decoded_name->ToModifiedUtf8().c_str())); 3824 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name); 3825 3826 CHECK_EQ(klass.Get()->GetInterfaces(), 3827 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 3828 CHECK_EQ(klass.Get()->GetThrows(), 3829 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws)); 3830 } 3831 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str())); 3832 CHECK(existing == nullptr); 3833 return klass.Get(); 3834} 3835 3836std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) { 3837 DCHECK(proxy_class->IsProxyClass()); 3838 mirror::String* name = proxy_class->GetName(); 3839 DCHECK(name != NULL); 3840 return DotToDescriptor(name->ToModifiedUtf8().c_str()); 3841} 3842 3843mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, 3844 mirror::ArtMethod* proxy_method) { 3845 DCHECK(proxy_class->IsProxyClass()); 3846 DCHECK(proxy_method->IsProxyMethod()); 3847 // Locate the dex cache of the original interface/Object 3848 mirror::DexCache* dex_cache = nullptr; 3849 { 3850 ReaderMutexLock mu(Thread::Current(), dex_lock_); 3851 for (size_t i = 0; i != dex_caches_.size(); ++i) { 3852 mirror::DexCache* a_dex_cache = GetDexCache(i); 3853 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) { 3854 dex_cache = a_dex_cache; 3855 break; 3856 } 3857 } 3858 } 3859 CHECK(dex_cache != nullptr); 3860 uint32_t method_idx = proxy_method->GetDexMethodIndex(); 3861 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx); 3862 CHECK(resolved_method != nullptr); 3863 return resolved_method; 3864} 3865 3866 3867mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self, 3868 ConstHandle<mirror::Class> klass, 3869 mirror::Class* proxy_class) { 3870 // Create constructor for Proxy that must initialize h 3871 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods = 3872 proxy_class->GetDirectMethods(); 3873 CHECK_EQ(proxy_direct_methods->GetLength(), 16); 3874 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2); 3875 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden 3876 // constructor method. 3877 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(), 3878 proxy_constructor); 3879 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its 3880 // code_ too) 3881 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self)); 3882 if (constructor == nullptr) { 3883 CHECK(self->IsExceptionPending()); // OOME. 3884 return nullptr; 3885 } 3886 // Make this constructor public and fix the class to be our Proxy version 3887 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic); 3888 constructor->SetDeclaringClass(klass.Get()); 3889 return constructor; 3890} 3891 3892static void CheckProxyConstructor(mirror::ArtMethod* constructor) 3893 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3894 CHECK(constructor->IsConstructor()); 3895 CHECK_STREQ(constructor->GetName(), "<init>"); 3896 CHECK_STREQ(constructor->GetSignature().ToString().c_str(), 3897 "(Ljava/lang/reflect/InvocationHandler;)V"); 3898 DCHECK(constructor->IsPublic()); 3899} 3900 3901mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self, 3902 ConstHandle<mirror::Class> klass, 3903 ConstHandle<mirror::ArtMethod> prototype) { 3904 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden 3905 // prototype method 3906 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(), 3907 prototype.Get()); 3908 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize 3909 // as necessary 3910 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self)); 3911 if (UNLIKELY(method == NULL)) { 3912 CHECK(self->IsExceptionPending()); // OOME. 3913 return NULL; 3914 } 3915 3916 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to 3917 // the intersection of throw exceptions as defined in Proxy 3918 method->SetDeclaringClass(klass.Get()); 3919 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal); 3920 3921 // At runtime the method looks like a reference and argument saving method, clone the code 3922 // related parameters from this method. 3923 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler()); 3924 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler()); 3925 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge); 3926 3927 return method; 3928} 3929 3930static void CheckProxyMethod(ConstHandle<mirror::ArtMethod> method, 3931 ConstHandle<mirror::ArtMethod> prototype) 3932 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3933 // Basic sanity 3934 CHECK(!prototype->IsFinal()); 3935 CHECK(method->IsFinal()); 3936 CHECK(!method->IsAbstract()); 3937 3938 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its 3939 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself. 3940 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings()); 3941 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get())); 3942 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get())); 3943 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex()); 3944 3945 StackHandleScope<2> hs(Thread::Current()); 3946 MethodHelper mh(hs.NewHandle(method.Get())); 3947 MethodHelper mh2(hs.NewHandle(prototype.Get())); 3948 CHECK_STREQ(method->GetName(), prototype->GetName()); 3949 CHECK_STREQ(method->GetShorty(), prototype->GetShorty()); 3950 // More complex sanity - via dex cache 3951 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType()); 3952} 3953 3954static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics, 3955 bool can_init_parents) 3956 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3957 if (can_init_statics && can_init_parents) { 3958 return true; 3959 } 3960 if (!can_init_statics) { 3961 // Check if there's a class initializer. 3962 mirror::ArtMethod* clinit = klass->FindClassInitializer(); 3963 if (clinit != NULL) { 3964 return false; 3965 } 3966 // Check if there are encoded static values needing initialization. 3967 if (klass->NumStaticFields() != 0) { 3968 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 3969 DCHECK(dex_class_def != NULL); 3970 if (dex_class_def->static_values_off_ != 0) { 3971 return false; 3972 } 3973 } 3974 } 3975 if (!klass->IsInterface() && klass->HasSuperClass()) { 3976 mirror::Class* super_class = klass->GetSuperClass(); 3977 if (!can_init_parents && !super_class->IsInitialized()) { 3978 return false; 3979 } else { 3980 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) { 3981 return false; 3982 } 3983 } 3984 } 3985 return true; 3986} 3987 3988bool ClassLinker::IsInitialized() const { 3989 return init_done_; 3990} 3991 3992bool ClassLinker::InitializeClass(ConstHandle<mirror::Class> klass, bool can_init_statics, 3993 bool can_init_parents) { 3994 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol 3995 3996 // Are we already initialized and therefore done? 3997 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as 3998 // an initialized class will never change its state. 3999 if (klass->IsInitialized()) { 4000 return true; 4001 } 4002 4003 // Fast fail if initialization requires a full runtime. Not part of the JLS. 4004 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) { 4005 return false; 4006 } 4007 4008 Thread* self = Thread::Current(); 4009 uint64_t t0; 4010 { 4011 ObjectLock<mirror::Class> lock(self, klass); 4012 4013 // Re-check under the lock in case another thread initialized ahead of us. 4014 if (klass->IsInitialized()) { 4015 return true; 4016 } 4017 4018 // Was the class already found to be erroneous? Done under the lock to match the JLS. 4019 if (klass->IsErroneous()) { 4020 ThrowEarlierClassFailure(klass.Get()); 4021 return false; 4022 } 4023 4024 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus(); 4025 4026 if (!klass->IsVerified()) { 4027 VerifyClass(klass); 4028 if (!klass->IsVerified()) { 4029 // We failed to verify, expect either the klass to be erroneous or verification failed at 4030 // compile time. 4031 if (klass->IsErroneous()) { 4032 CHECK(self->IsExceptionPending()); 4033 } else { 4034 CHECK(Runtime::Current()->IsCompiler()); 4035 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 4036 } 4037 return false; 4038 } else { 4039 self->AssertNoPendingException(); 4040 } 4041 } 4042 4043 // If the class is kStatusInitializing, either this thread is 4044 // initializing higher up the stack or another thread has beat us 4045 // to initializing and we need to wait. Either way, this 4046 // invocation of InitializeClass will not be responsible for 4047 // running <clinit> and will return. 4048 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 4049 // Could have got an exception during verification. 4050 if (self->IsExceptionPending()) { 4051 return false; 4052 } 4053 // We caught somebody else in the act; was it us? 4054 if (klass->GetClinitThreadId() == self->GetTid()) { 4055 // Yes. That's fine. Return so we can continue initializing. 4056 return true; 4057 } 4058 // No. That's fine. Wait for another thread to finish initializing. 4059 return WaitForInitializeClass(klass, self, lock); 4060 } 4061 4062 if (!ValidateSuperClassDescriptors(klass)) { 4063 klass->SetStatus(mirror::Class::kStatusError, self); 4064 return false; 4065 } 4066 4067 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get()); 4068 4069 // From here out other threads may observe that we're initializing and so changes of state 4070 // require the a notification. 4071 klass->SetClinitThreadId(self->GetTid()); 4072 klass->SetStatus(mirror::Class::kStatusInitializing, self); 4073 4074 t0 = NanoTime(); 4075 } 4076 4077 // Initialize super classes, must be done while initializing for the JLS. 4078 if (!klass->IsInterface() && klass->HasSuperClass()) { 4079 mirror::Class* super_class = klass->GetSuperClass(); 4080 if (!super_class->IsInitialized()) { 4081 CHECK(!super_class->IsInterface()); 4082 CHECK(can_init_parents); 4083 StackHandleScope<1> hs(self); 4084 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class)); 4085 bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true); 4086 if (!super_initialized) { 4087 // The super class was verified ahead of entering initializing, we should only be here if 4088 // the super class became erroneous due to initialization. 4089 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending()) 4090 << "Super class initialization failed for " 4091 << PrettyDescriptor(handle_scope_super.Get()) 4092 << " that has unexpected status " << handle_scope_super->GetStatus() 4093 << "\nPending exception:\n" 4094 << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : ""); 4095 ObjectLock<mirror::Class> lock(self, klass); 4096 // Initialization failed because the super-class is erroneous. 4097 klass->SetStatus(mirror::Class::kStatusError, self); 4098 return false; 4099 } 4100 } 4101 } 4102 4103 if (klass->NumStaticFields() > 0) { 4104 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 4105 CHECK(dex_class_def != NULL); 4106 const DexFile& dex_file = klass->GetDexFile(); 4107 StackHandleScope<3> hs(self); 4108 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader())); 4109 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache())); 4110 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader, 4111 this, *dex_class_def); 4112 const byte* class_data = dex_file.GetClassData(*dex_class_def); 4113 ClassDataItemIterator field_it(dex_file, class_data); 4114 if (value_it.HasNext()) { 4115 DCHECK(field_it.HasNextStaticField()); 4116 CHECK(can_init_statics); 4117 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) { 4118 StackHandleScope<1> hs(self); 4119 Handle<mirror::ArtField> field(hs.NewHandle( 4120 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true))); 4121 if (Runtime::Current()->IsActiveTransaction()) { 4122 value_it.ReadValueToField<true>(field); 4123 } else { 4124 value_it.ReadValueToField<false>(field); 4125 } 4126 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField()); 4127 } 4128 } 4129 } 4130 4131 mirror::ArtMethod* clinit = klass->FindClassInitializer(); 4132 if (clinit != NULL) { 4133 CHECK(can_init_statics); 4134 JValue result; 4135 clinit->Invoke(self, NULL, 0, &result, "V"); 4136 } 4137 4138 uint64_t t1 = NanoTime(); 4139 4140 bool success = true; 4141 { 4142 ObjectLock<mirror::Class> lock(self, klass); 4143 4144 if (self->IsExceptionPending()) { 4145 WrapExceptionInInitializer(); 4146 klass->SetStatus(mirror::Class::kStatusError, self); 4147 success = false; 4148 } else { 4149 RuntimeStats* global_stats = Runtime::Current()->GetStats(); 4150 RuntimeStats* thread_stats = self->GetStats(); 4151 ++global_stats->class_init_count; 4152 ++thread_stats->class_init_count; 4153 global_stats->class_init_time_ns += (t1 - t0); 4154 thread_stats->class_init_time_ns += (t1 - t0); 4155 // Set the class as initialized except if failed to initialize static fields. 4156 klass->SetStatus(mirror::Class::kStatusInitialized, self); 4157 if (VLOG_IS_ON(class_linker)) { 4158 std::string temp; 4159 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " << 4160 klass->GetLocation(); 4161 } 4162 // Opportunistically set static method trampolines to their destination. 4163 FixupStaticTrampolines(klass.Get()); 4164 } 4165 } 4166 return success; 4167} 4168 4169bool ClassLinker::WaitForInitializeClass(ConstHandle<mirror::Class> klass, Thread* self, 4170 ObjectLock<mirror::Class>& lock) 4171 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4172 while (true) { 4173 self->AssertNoPendingException(); 4174 CHECK(!klass->IsInitialized()); 4175 lock.WaitIgnoringInterrupts(); 4176 4177 // When we wake up, repeat the test for init-in-progress. If 4178 // there's an exception pending (only possible if 4179 // "interruptShouldThrow" was set), bail out. 4180 if (self->IsExceptionPending()) { 4181 WrapExceptionInInitializer(); 4182 klass->SetStatus(mirror::Class::kStatusError, self); 4183 return false; 4184 } 4185 // Spurious wakeup? Go back to waiting. 4186 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 4187 continue; 4188 } 4189 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) { 4190 // Compile time initialization failed. 4191 return false; 4192 } 4193 if (klass->IsErroneous()) { 4194 // The caller wants an exception, but it was thrown in a 4195 // different thread. Synthesize one here. 4196 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread", 4197 PrettyDescriptor(klass.Get()).c_str()); 4198 return false; 4199 } 4200 if (klass->IsInitialized()) { 4201 return true; 4202 } 4203 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is " 4204 << klass->GetStatus(); 4205 } 4206 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get()); 4207} 4208 4209bool ClassLinker::ValidateSuperClassDescriptors(ConstHandle<mirror::Class> klass) { 4210 if (klass->IsInterface()) { 4211 return true; 4212 } 4213 // Begin with the methods local to the superclass. 4214 StackHandleScope<2> hs(Thread::Current()); 4215 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4216 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4217 if (klass->HasSuperClass() && 4218 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) { 4219 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) { 4220 mh.ChangeMethod(klass->GetVTableEntry(i)); 4221 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i)); 4222 if (mh.GetMethod() != super_mh.GetMethod() && 4223 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) { 4224 ThrowLinkageError(klass.Get(), 4225 "Class %s method %s resolves differently in superclass %s", 4226 PrettyDescriptor(klass.Get()).c_str(), 4227 PrettyMethod(mh.GetMethod()).c_str(), 4228 PrettyDescriptor(klass->GetSuperClass()).c_str()); 4229 return false; 4230 } 4231 } 4232 } 4233 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 4234 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) { 4235 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods(); 4236 for (uint32_t j = 0; j < num_methods; ++j) { 4237 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j)); 4238 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j)); 4239 if (mh.GetMethod() != super_mh.GetMethod() && 4240 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) { 4241 ThrowLinkageError(klass.Get(), 4242 "Class %s method %s resolves differently in interface %s", 4243 PrettyDescriptor(klass.Get()).c_str(), 4244 PrettyMethod(mh.GetMethod()).c_str(), 4245 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str()); 4246 return false; 4247 } 4248 } 4249 } 4250 } 4251 return true; 4252} 4253 4254bool ClassLinker::EnsureInitialized(ConstHandle<mirror::Class> c, bool can_init_fields, 4255 bool can_init_parents) { 4256 DCHECK(c.Get() != nullptr); 4257 if (c->IsInitialized()) { 4258 return true; 4259 } 4260 const bool success = InitializeClass(c, can_init_fields, can_init_parents); 4261 Thread* self = Thread::Current(); 4262 if (!success) { 4263 if (can_init_fields && can_init_parents) { 4264 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get()); 4265 } 4266 } else { 4267 self->AssertNoPendingException(); 4268 } 4269 return success; 4270} 4271 4272void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) { 4273 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields(); 4274 if (fields != nullptr) { 4275 for (int index = 0; index < fields->GetLength(); index ++) { 4276 if (fields->Get(index)->GetDeclaringClass() == temp_class) { 4277 fields->Get(index)->SetDeclaringClass(new_class); 4278 } 4279 } 4280 } 4281 4282 fields = new_class->GetSFields(); 4283 if (fields != nullptr) { 4284 for (int index = 0; index < fields->GetLength(); index ++) { 4285 if (fields->Get(index)->GetDeclaringClass() == temp_class) { 4286 fields->Get(index)->SetDeclaringClass(new_class); 4287 } 4288 } 4289 } 4290 4291 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods(); 4292 if (methods != nullptr) { 4293 for (int index = 0; index < methods->GetLength(); index ++) { 4294 if (methods->Get(index)->GetDeclaringClass() == temp_class) { 4295 methods->Get(index)->SetDeclaringClass(new_class); 4296 } 4297 } 4298 } 4299 4300 methods = new_class->GetVirtualMethods(); 4301 if (methods != nullptr) { 4302 for (int index = 0; index < methods->GetLength(); index ++) { 4303 if (methods->Get(index)->GetDeclaringClass() == temp_class) { 4304 methods->Get(index)->SetDeclaringClass(new_class); 4305 } 4306 } 4307 } 4308} 4309 4310bool ClassLinker::LinkClass(Thread* self, const char* descriptor, ConstHandle<mirror::Class> klass, 4311 ConstHandle<mirror::ObjectArray<mirror::Class>> interfaces, 4312 mirror::Class** new_class) { 4313 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 4314 4315 if (!LinkSuperClass(klass)) { 4316 return false; 4317 } 4318 if (!LinkMethods(self, klass, interfaces)) { 4319 return false; 4320 } 4321 if (!LinkInstanceFields(klass)) { 4322 return false; 4323 } 4324 size_t class_size; 4325 if (!LinkStaticFields(klass, &class_size)) { 4326 return false; 4327 } 4328 CreateReferenceInstanceOffsets(klass); 4329 CreateReferenceStaticOffsets(klass); 4330 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 4331 4332 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) { 4333 // We don't need to retire this class as it has no embedded tables or it was created the 4334 // correct size during class linker initialization. 4335 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get()); 4336 4337 if (klass->ShouldHaveEmbeddedImtAndVTable()) { 4338 klass->PopulateEmbeddedImtAndVTable(); 4339 } 4340 4341 // This will notify waiters on klass that saw the not yet resolved 4342 // class in the class_table_ during EnsureResolved. 4343 klass->SetStatus(mirror::Class::kStatusResolved, self); 4344 *new_class = klass.Get(); 4345 } else { 4346 CHECK(!klass->IsResolved()); 4347 // Retire the temporary class and create the correctly sized resolved class. 4348 *new_class = klass->CopyOf(self, class_size); 4349 if (UNLIKELY(*new_class == NULL)) { 4350 CHECK(self->IsExceptionPending()); // Expect an OOME. 4351 klass->SetStatus(mirror::Class::kStatusError, self); 4352 return false; 4353 } 4354 4355 CHECK_EQ((*new_class)->GetClassSize(), class_size); 4356 StackHandleScope<1> hs(self); 4357 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class); 4358 ObjectLock<mirror::Class> lock(self, new_class_h); 4359 4360 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get()); 4361 4362 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor)); 4363 CHECK(existing == NULL || existing == klass.Get()); 4364 4365 // This will notify waiters on temp class that saw the not yet resolved class in the 4366 // class_table_ during EnsureResolved. 4367 klass->SetStatus(mirror::Class::kStatusRetired, self); 4368 4369 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving); 4370 // This will notify waiters on new_class that saw the not yet resolved 4371 // class in the class_table_ during EnsureResolved. 4372 new_class_h->SetStatus(mirror::Class::kStatusResolved, self); 4373 } 4374 return true; 4375} 4376 4377bool ClassLinker::LoadSuperAndInterfaces(ConstHandle<mirror::Class> klass, const DexFile& dex_file) { 4378 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus()); 4379 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex()); 4380 uint16_t super_class_idx = class_def.superclass_idx_; 4381 if (super_class_idx != DexFile::kDexNoIndex16) { 4382 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get()); 4383 if (super_class == NULL) { 4384 DCHECK(Thread::Current()->IsExceptionPending()); 4385 return false; 4386 } 4387 // Verify 4388 if (!klass->CanAccess(super_class)) { 4389 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible", 4390 PrettyDescriptor(super_class).c_str(), 4391 PrettyDescriptor(klass.Get()).c_str()); 4392 return false; 4393 } 4394 CHECK(super_class->IsResolved()); 4395 klass->SetSuperClass(super_class); 4396 } 4397 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def); 4398 if (interfaces != NULL) { 4399 for (size_t i = 0; i < interfaces->Size(); i++) { 4400 uint16_t idx = interfaces->GetTypeItem(i).type_idx_; 4401 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get()); 4402 if (interface == NULL) { 4403 DCHECK(Thread::Current()->IsExceptionPending()); 4404 return false; 4405 } 4406 // Verify 4407 if (!klass->CanAccess(interface)) { 4408 // TODO: the RI seemed to ignore this in my testing. 4409 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible", 4410 PrettyDescriptor(interface).c_str(), 4411 PrettyDescriptor(klass.Get()).c_str()); 4412 return false; 4413 } 4414 } 4415 } 4416 // Mark the class as loaded. 4417 klass->SetStatus(mirror::Class::kStatusLoaded, NULL); 4418 return true; 4419} 4420 4421bool ClassLinker::LinkSuperClass(ConstHandle<mirror::Class> klass) { 4422 CHECK(!klass->IsPrimitive()); 4423 mirror::Class* super = klass->GetSuperClass(); 4424 if (klass.Get() == GetClassRoot(kJavaLangObject)) { 4425 if (super != NULL) { 4426 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass"); 4427 return false; 4428 } 4429 return true; 4430 } 4431 if (super == NULL) { 4432 ThrowLinkageError(klass.Get(), "No superclass defined for class %s", 4433 PrettyDescriptor(klass.Get()).c_str()); 4434 return false; 4435 } 4436 // Verify 4437 if (super->IsFinal() || super->IsInterface()) { 4438 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s", 4439 PrettyDescriptor(super).c_str(), 4440 PrettyDescriptor(klass.Get()).c_str(), 4441 super->IsFinal() ? "declared final" : "an interface"); 4442 return false; 4443 } 4444 if (!klass->CanAccess(super)) { 4445 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s", 4446 PrettyDescriptor(super).c_str(), 4447 PrettyDescriptor(klass.Get()).c_str()); 4448 return false; 4449 } 4450 4451 // Inherit kAccClassIsFinalizable from the superclass in case this 4452 // class doesn't override finalize. 4453 if (super->IsFinalizable()) { 4454 klass->SetFinalizable(); 4455 } 4456 4457 // Inherit reference flags (if any) from the superclass. 4458 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask); 4459 if (reference_flags != 0) { 4460 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags); 4461 } 4462 // Disallow custom direct subclasses of java.lang.ref.Reference. 4463 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) { 4464 ThrowLinkageError(klass.Get(), 4465 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed", 4466 PrettyDescriptor(klass.Get()).c_str()); 4467 return false; 4468 } 4469 4470 if (kIsDebugBuild) { 4471 // Ensure super classes are fully resolved prior to resolving fields.. 4472 while (super != NULL) { 4473 CHECK(super->IsResolved()); 4474 super = super->GetSuperClass(); 4475 } 4476 } 4477 return true; 4478} 4479 4480// Populate the class vtable and itable. Compute return type indices. 4481bool ClassLinker::LinkMethods(Thread* self, ConstHandle<mirror::Class> klass, 4482 ConstHandle<mirror::ObjectArray<mirror::Class>> interfaces) { 4483 if (klass->IsInterface()) { 4484 // No vtable. 4485 size_t count = klass->NumVirtualMethods(); 4486 if (!IsUint(16, count)) { 4487 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count); 4488 return false; 4489 } 4490 for (size_t i = 0; i < count; ++i) { 4491 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i); 4492 } 4493 // Link interface method tables 4494 return LinkInterfaceMethods(klass, interfaces); 4495 } else { 4496 // Link virtual and interface method tables 4497 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces); 4498 } 4499 return true; 4500} 4501 4502bool ClassLinker::LinkVirtualMethods(Thread* self, ConstHandle<mirror::Class> klass) { 4503 if (klass->HasSuperClass()) { 4504 uint32_t max_count = klass->NumVirtualMethods() + 4505 klass->GetSuperClass()->GetVTableLength(); 4506 size_t actual_count = klass->GetSuperClass()->GetVTableLength(); 4507 CHECK_LE(actual_count, max_count); 4508 StackHandleScope<4> hs(self); 4509 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass())); 4510 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable; 4511 if (super_class->ShouldHaveEmbeddedImtAndVTable()) { 4512 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count)); 4513 if (UNLIKELY(vtable.Get() == nullptr)) { 4514 CHECK(self->IsExceptionPending()); // OOME. 4515 return false; 4516 } 4517 int len = super_class->GetVTableLength(); 4518 for (int i = 0; i < len; i++) { 4519 vtable->Set<false>(i, super_class->GetVTableEntry(i)); 4520 } 4521 } else { 4522 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get()); 4523 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count)); 4524 if (UNLIKELY(vtable.Get() == nullptr)) { 4525 CHECK(self->IsExceptionPending()); // OOME. 4526 return false; 4527 } 4528 } 4529 4530 // See if any of our virtual methods override the superclass. 4531 MethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4532 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4533 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) { 4534 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i); 4535 local_mh.ChangeMethod(local_method); 4536 size_t j = 0; 4537 for (; j < actual_count; ++j) { 4538 mirror::ArtMethod* super_method = vtable->Get(j); 4539 super_mh.ChangeMethod(super_method); 4540 if (local_mh.HasSameNameAndSignature(&super_mh)) { 4541 if (klass->CanAccessMember(super_method->GetDeclaringClass(), 4542 super_method->GetAccessFlags())) { 4543 if (super_method->IsFinal()) { 4544 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s", 4545 PrettyMethod(local_method).c_str(), 4546 super_method->GetDeclaringClassDescriptor()); 4547 return false; 4548 } 4549 vtable->Set<false>(j, local_method); 4550 local_method->SetMethodIndex(j); 4551 break; 4552 } else { 4553 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method) 4554 << " would have incorrectly overridden the package-private method in " 4555 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor()); 4556 } 4557 } 4558 } 4559 if (j == actual_count) { 4560 // Not overriding, append. 4561 vtable->Set<false>(actual_count, local_method); 4562 local_method->SetMethodIndex(actual_count); 4563 actual_count += 1; 4564 } 4565 } 4566 if (!IsUint(16, actual_count)) { 4567 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count); 4568 return false; 4569 } 4570 // Shrink vtable if possible 4571 CHECK_LE(actual_count, max_count); 4572 if (actual_count < max_count) { 4573 vtable.Assign(vtable->CopyOf(self, actual_count)); 4574 if (UNLIKELY(vtable.Get() == NULL)) { 4575 CHECK(self->IsExceptionPending()); // OOME. 4576 return false; 4577 } 4578 } 4579 klass->SetVTable(vtable.Get()); 4580 } else { 4581 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject)); 4582 uint32_t num_virtual_methods = klass->NumVirtualMethods(); 4583 if (!IsUint(16, num_virtual_methods)) { 4584 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods); 4585 return false; 4586 } 4587 StackHandleScope<1> hs(self); 4588 Handle<mirror::ObjectArray<mirror::ArtMethod>> 4589 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods))); 4590 if (UNLIKELY(vtable.Get() == NULL)) { 4591 CHECK(self->IsExceptionPending()); // OOME. 4592 return false; 4593 } 4594 for (size_t i = 0; i < num_virtual_methods; ++i) { 4595 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i); 4596 vtable->Set<false>(i, virtual_method); 4597 virtual_method->SetMethodIndex(i & 0xFFFF); 4598 } 4599 klass->SetVTable(vtable.Get()); 4600 } 4601 return true; 4602} 4603 4604bool ClassLinker::LinkInterfaceMethods(ConstHandle<mirror::Class> klass, 4605 ConstHandle<mirror::ObjectArray<mirror::Class>> interfaces) { 4606 Thread* const self = Thread::Current(); 4607 Runtime* const runtime = Runtime::Current(); 4608 // Set the imt table to be all conflicts by default. 4609 klass->SetImTable(runtime->GetDefaultImt()); 4610 size_t super_ifcount; 4611 if (klass->HasSuperClass()) { 4612 super_ifcount = klass->GetSuperClass()->GetIfTableCount(); 4613 } else { 4614 super_ifcount = 0; 4615 } 4616 uint32_t num_interfaces = 4617 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength(); 4618 size_t ifcount = super_ifcount + num_interfaces; 4619 for (size_t i = 0; i < num_interfaces; i++) { 4620 mirror::Class* interface = 4621 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) : 4622 interfaces->Get(i); 4623 ifcount += interface->GetIfTableCount(); 4624 } 4625 if (ifcount == 0) { 4626 // Class implements no interfaces. 4627 DCHECK_EQ(klass->GetIfTableCount(), 0); 4628 DCHECK(klass->GetIfTable() == NULL); 4629 return true; 4630 } 4631 if (ifcount == super_ifcount) { 4632 // Class implements same interfaces as parent, are any of these not marker interfaces? 4633 bool has_non_marker_interface = false; 4634 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 4635 for (size_t i = 0; i < ifcount; ++i) { 4636 if (super_iftable->GetMethodArrayCount(i) > 0) { 4637 has_non_marker_interface = true; 4638 break; 4639 } 4640 } 4641 if (!has_non_marker_interface) { 4642 // Class just inherits marker interfaces from parent so recycle parent's iftable. 4643 klass->SetIfTable(super_iftable); 4644 return true; 4645 } 4646 } 4647 StackHandleScope<5> hs(self); 4648 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount))); 4649 if (UNLIKELY(iftable.Get() == NULL)) { 4650 CHECK(self->IsExceptionPending()); // OOME. 4651 return false; 4652 } 4653 if (super_ifcount != 0) { 4654 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 4655 for (size_t i = 0; i < super_ifcount; i++) { 4656 mirror::Class* super_interface = super_iftable->GetInterface(i); 4657 iftable->SetInterface(i, super_interface); 4658 } 4659 } 4660 // Flatten the interface inheritance hierarchy. 4661 size_t idx = super_ifcount; 4662 for (size_t i = 0; i < num_interfaces; i++) { 4663 mirror::Class* interface = 4664 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) : 4665 interfaces->Get(i); 4666 DCHECK(interface != NULL); 4667 if (!interface->IsInterface()) { 4668 std::string temp; 4669 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s", 4670 PrettyDescriptor(klass.Get()).c_str(), 4671 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str()); 4672 return false; 4673 } 4674 // Check if interface is already in iftable 4675 bool duplicate = false; 4676 for (size_t j = 0; j < idx; j++) { 4677 mirror::Class* existing_interface = iftable->GetInterface(j); 4678 if (existing_interface == interface) { 4679 duplicate = true; 4680 break; 4681 } 4682 } 4683 if (!duplicate) { 4684 // Add this non-duplicate interface. 4685 iftable->SetInterface(idx++, interface); 4686 // Add this interface's non-duplicate super-interfaces. 4687 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) { 4688 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j); 4689 bool super_duplicate = false; 4690 for (size_t k = 0; k < idx; k++) { 4691 mirror::Class* existing_interface = iftable->GetInterface(k); 4692 if (existing_interface == super_interface) { 4693 super_duplicate = true; 4694 break; 4695 } 4696 } 4697 if (!super_duplicate) { 4698 iftable->SetInterface(idx++, super_interface); 4699 } 4700 } 4701 } 4702 } 4703 // Shrink iftable in case duplicates were found 4704 if (idx < ifcount) { 4705 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax))); 4706 if (UNLIKELY(iftable.Get() == NULL)) { 4707 CHECK(self->IsExceptionPending()); // OOME. 4708 return false; 4709 } 4710 ifcount = idx; 4711 } else { 4712 CHECK_EQ(idx, ifcount); 4713 } 4714 klass->SetIfTable(iftable.Get()); 4715 4716 // If we're an interface, we don't need the vtable pointers, so we're done. 4717 if (klass->IsInterface()) { 4718 return true; 4719 } 4720 // Allocate imtable 4721 bool imtable_changed = false; 4722 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable( 4723 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize))); 4724 if (UNLIKELY(imtable.Get() == NULL)) { 4725 CHECK(self->IsExceptionPending()); // OOME. 4726 return false; 4727 } 4728 MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4729 MethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4730 size_t max_miranda_methods = 0; // The max size of miranda_list. 4731 for (size_t i = 0; i < ifcount; ++i) { 4732 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods(); 4733 } 4734 Handle<mirror::ObjectArray<mirror::ArtMethod>> 4735 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods))); 4736 size_t miranda_list_size = 0; // The current size of miranda_list. 4737 for (size_t i = 0; i < ifcount; ++i) { 4738 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods(); 4739 if (num_methods > 0) { 4740 StackHandleScope<2> hs(self); 4741 Handle<mirror::ObjectArray<mirror::ArtMethod>> 4742 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods))); 4743 if (UNLIKELY(method_array.Get() == nullptr)) { 4744 CHECK(self->IsExceptionPending()); // OOME. 4745 return false; 4746 } 4747 iftable->SetMethodArray(i, method_array.Get()); 4748 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable( 4749 hs.NewHandle(klass->GetVTableDuringLinking())); 4750 for (size_t j = 0; j < num_methods; ++j) { 4751 interface_mh.ChangeMethod(iftable->GetInterface(i)->GetVirtualMethod(j)); 4752 int32_t k; 4753 // For each method listed in the interface's method list, find the 4754 // matching method in our class's method list. We want to favor the 4755 // subclass over the superclass, which just requires walking 4756 // back from the end of the vtable. (This only matters if the 4757 // superclass defines a private method and this class redefines 4758 // it -- otherwise it would use the same vtable slot. In .dex files 4759 // those don't end up in the virtual method table, so it shouldn't 4760 // matter which direction we go. We walk it backward anyway.) 4761 for (k = vtable->GetLength() - 1; k >= 0; --k) { 4762 vtable_mh.ChangeMethod(vtable->Get(k)); 4763 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) { 4764 if (!vtable_mh.Get()->IsAbstract() && !vtable_mh.Get()->IsPublic()) { 4765 ThrowIllegalAccessError( 4766 klass.Get(), 4767 "Method '%s' implementing interface method '%s' is not public", 4768 PrettyMethod(vtable_mh.Get()).c_str(), 4769 PrettyMethod(interface_mh.Get()).c_str()); 4770 return false; 4771 } 4772 method_array->Set<false>(j, vtable_mh.Get()); 4773 // Place method in imt if entry is empty, place conflict otherwise. 4774 uint32_t imt_index = interface_mh.Get()->GetDexMethodIndex() % mirror::Class::kImtSize; 4775 if (imtable->Get(imt_index) == NULL) { 4776 imtable->Set<false>(imt_index, vtable_mh.Get()); 4777 imtable_changed = true; 4778 } else { 4779 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod()); 4780 } 4781 break; 4782 } 4783 } 4784 if (k < 0) { 4785 StackHandleScope<1> hs(self); 4786 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr); 4787 for (size_t l = 0; l < miranda_list_size; ++l) { 4788 mirror::ArtMethod* mir_method = miranda_list->Get(l); 4789 DCHECK(mir_method != nullptr); 4790 vtable_mh.ChangeMethod(mir_method); 4791 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) { 4792 miranda_method.Assign(mir_method); 4793 break; 4794 } 4795 } 4796 if (miranda_method.Get() == NULL) { 4797 // Point the interface table at a phantom slot. 4798 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_mh.Get()->Clone(self))); 4799 if (UNLIKELY(miranda_method.Get() == NULL)) { 4800 CHECK(self->IsExceptionPending()); // OOME. 4801 return false; 4802 } 4803 DCHECK_LT(miranda_list_size, max_miranda_methods); 4804 miranda_list->Set<false>(miranda_list_size++, miranda_method.Get()); 4805 } 4806 method_array->Set<false>(j, miranda_method.Get()); 4807 } 4808 } 4809 } 4810 } 4811 if (imtable_changed) { 4812 // Fill in empty entries in interface method table with conflict. 4813 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod(); 4814 for (size_t i = 0; i < mirror::Class::kImtSize; i++) { 4815 if (imtable->Get(i) == NULL) { 4816 imtable->Set<false>(i, imt_conflict_method); 4817 } 4818 } 4819 klass->SetImTable(imtable.Get()); 4820 } 4821 if (miranda_list_size > 0) { 4822 int old_method_count = klass->NumVirtualMethods(); 4823 int new_method_count = old_method_count + miranda_list_size; 4824 mirror::ObjectArray<mirror::ArtMethod>* virtuals; 4825 if (old_method_count == 0) { 4826 virtuals = AllocArtMethodArray(self, new_method_count); 4827 } else { 4828 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count); 4829 } 4830 if (UNLIKELY(virtuals == NULL)) { 4831 CHECK(self->IsExceptionPending()); // OOME. 4832 return false; 4833 } 4834 klass->SetVirtualMethods(virtuals); 4835 4836 StackHandleScope<1> hs(self); 4837 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable( 4838 hs.NewHandle(klass->GetVTableDuringLinking())); 4839 CHECK(vtable.Get() != NULL); 4840 int old_vtable_count = vtable->GetLength(); 4841 int new_vtable_count = old_vtable_count + miranda_list_size; 4842 vtable.Assign(vtable->CopyOf(self, new_vtable_count)); 4843 if (UNLIKELY(vtable.Get() == NULL)) { 4844 CHECK(self->IsExceptionPending()); // OOME. 4845 return false; 4846 } 4847 for (size_t i = 0; i < miranda_list_size; ++i) { 4848 mirror::ArtMethod* method = miranda_list->Get(i); 4849 // Leave the declaring class alone as type indices are relative to it 4850 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda); 4851 method->SetMethodIndex(0xFFFF & (old_vtable_count + i)); 4852 klass->SetVirtualMethod(old_method_count + i, method); 4853 vtable->Set<false>(old_vtable_count + i, method); 4854 } 4855 // TODO: do not assign to the vtable field until it is fully constructed. 4856 klass->SetVTable(vtable.Get()); 4857 } 4858 4859 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking(); 4860 for (int i = 0; i < vtable->GetLength(); ++i) { 4861 CHECK(vtable->Get(i) != NULL); 4862 } 4863 4864// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail); 4865 4866 return true; 4867} 4868 4869bool ClassLinker::LinkInstanceFields(ConstHandle<mirror::Class> klass) { 4870 CHECK(klass.Get() != NULL); 4871 return LinkFields(klass, false, nullptr); 4872} 4873 4874bool ClassLinker::LinkStaticFields(ConstHandle<mirror::Class> klass, size_t* class_size) { 4875 CHECK(klass.Get() != NULL); 4876 return LinkFields(klass, true, class_size); 4877} 4878 4879struct LinkFieldsComparator { 4880 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4881 } 4882 // No thread safety analysis as will be called from STL. Checked lock held in constructor. 4883 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2) 4884 NO_THREAD_SAFETY_ANALYSIS { 4885 // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit. 4886 Primitive::Type type1 = field1->GetTypeAsPrimitiveType(); 4887 Primitive::Type type2 = field2->GetTypeAsPrimitiveType(); 4888 if (type1 != type2) { 4889 bool is_primitive1 = type1 != Primitive::kPrimNot; 4890 bool is_primitive2 = type2 != Primitive::kPrimNot; 4891 if (type1 != type2) { 4892 if (is_primitive1 && is_primitive2) { 4893 // Larger primitive types go first. 4894 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2); 4895 } else { 4896 // Reference always goes first. 4897 return !is_primitive1; 4898 } 4899 } 4900 } 4901 // same basic group? then sort by string. 4902 return strcmp(field1->GetName(), field2->GetName()) < 0; 4903 } 4904}; 4905 4906bool ClassLinker::LinkFields(ConstHandle<mirror::Class> klass, bool is_static, size_t* class_size) { 4907 size_t num_fields = 4908 is_static ? klass->NumStaticFields() : klass->NumInstanceFields(); 4909 4910 mirror::ObjectArray<mirror::ArtField>* fields = 4911 is_static ? klass->GetSFields() : klass->GetIFields(); 4912 4913 // Initialize field_offset 4914 MemberOffset field_offset(0); 4915 if (is_static) { 4916 uint32_t base = sizeof(mirror::Class); // Static fields come after the class. 4917 if (klass->ShouldHaveEmbeddedImtAndVTable()) { 4918 // Static fields come after the embedded tables. 4919 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(), 4920 0, 0, 0, 0, 0); 4921 } 4922 field_offset = MemberOffset(base); 4923 } else { 4924 mirror::Class* super_class = klass->GetSuperClass(); 4925 if (super_class != NULL) { 4926 CHECK(super_class->IsResolved()) 4927 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class); 4928 field_offset = MemberOffset(super_class->GetObjectSize()); 4929 } 4930 } 4931 4932 CHECK_EQ(num_fields == 0, fields == NULL) << PrettyClass(klass.Get()); 4933 4934 // we want a relatively stable order so that adding new fields 4935 // minimizes disruption of C++ version such as Class and Method. 4936 std::deque<mirror::ArtField*> grouped_and_sorted_fields; 4937 const char* old_no_suspend_cause = Thread::Current()->StartAssertNoThreadSuspension( 4938 "Naked ArtField references in deque"); 4939 for (size_t i = 0; i < num_fields; i++) { 4940 mirror::ArtField* f = fields->Get(i); 4941 CHECK(f != NULL) << PrettyClass(klass.Get()); 4942 grouped_and_sorted_fields.push_back(f); 4943 } 4944 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(), 4945 LinkFieldsComparator()); 4946 4947 // References should be at the front. 4948 size_t current_field = 0; 4949 size_t num_reference_fields = 0; 4950 FieldGaps gaps; 4951 4952 for (; current_field < num_fields; current_field++) { 4953 mirror::ArtField* field = grouped_and_sorted_fields.front(); 4954 Primitive::Type type = field->GetTypeAsPrimitiveType(); 4955 bool isPrimitive = type != Primitive::kPrimNot; 4956 if (isPrimitive) { 4957 break; // past last reference, move on to the next phase 4958 } 4959 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) { 4960 MemberOffset old_offset = field_offset; 4961 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4)); 4962 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps); 4963 } 4964 DCHECK(IsAligned<4>(field_offset.Uint32Value())); 4965 grouped_and_sorted_fields.pop_front(); 4966 num_reference_fields++; 4967 fields->Set<false>(current_field, field); 4968 field->SetOffset(field_offset); 4969 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t)); 4970 } 4971 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest 4972 // otherwise we could end up with suboptimal gap fills. 4973 ShuffleForward<8>(num_fields, ¤t_field, &field_offset, 4974 fields, &grouped_and_sorted_fields, &gaps); 4975 ShuffleForward<4>(num_fields, ¤t_field, &field_offset, 4976 fields, &grouped_and_sorted_fields, &gaps); 4977 ShuffleForward<2>(num_fields, ¤t_field, &field_offset, 4978 fields, &grouped_and_sorted_fields, &gaps); 4979 ShuffleForward<1>(num_fields, ¤t_field, &field_offset, 4980 fields, &grouped_and_sorted_fields, &gaps); 4981 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() << 4982 " fields."; 4983 4984 Thread::Current()->EndAssertNoThreadSuspension(old_no_suspend_cause); 4985 4986 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it. 4987 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) { 4988 // We know there are no non-reference fields in the Reference classes, and we know 4989 // that 'referent' is alphabetically last, so this is easy... 4990 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get()); 4991 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get()); 4992 --num_reference_fields; 4993 } 4994 4995 if (kIsDebugBuild) { 4996 // Make sure that all reference fields appear before 4997 // non-reference fields, and all double-wide fields are aligned. 4998 bool seen_non_ref = false; 4999 for (size_t i = 0; i < num_fields; i++) { 5000 mirror::ArtField* field = fields->Get(i); 5001 if (false) { // enable to debug field layout 5002 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance") 5003 << " class=" << PrettyClass(klass.Get()) 5004 << " field=" << PrettyField(field) 5005 << " offset=" 5006 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset())); 5007 } 5008 Primitive::Type type = field->GetTypeAsPrimitiveType(); 5009 bool is_primitive = type != Primitive::kPrimNot; 5010 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") && 5011 strcmp("referent", field->GetName()) == 0) { 5012 is_primitive = true; // We lied above, so we have to expect a lie here. 5013 } 5014 if (is_primitive) { 5015 if (!seen_non_ref) { 5016 seen_non_ref = true; 5017 DCHECK_EQ(num_reference_fields, i) << PrettyField(field); 5018 } 5019 } else { 5020 DCHECK(!seen_non_ref) << PrettyField(field); 5021 } 5022 } 5023 if (!seen_non_ref) { 5024 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get()); 5025 } 5026 } 5027 5028 size_t size = field_offset.Uint32Value(); 5029 // Update klass 5030 if (is_static) { 5031 klass->SetNumReferenceStaticFields(num_reference_fields); 5032 *class_size = size; 5033 } else { 5034 klass->SetNumReferenceInstanceFields(num_reference_fields); 5035 if (!klass->IsVariableSize()) { 5036 std::string temp; 5037 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp); 5038 size_t previous_size = klass->GetObjectSize(); 5039 if (previous_size != 0) { 5040 // Make sure that we didn't originally have an incorrect size. 5041 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp); 5042 } 5043 klass->SetObjectSize(size); 5044 } 5045 } 5046 return true; 5047} 5048 5049// Set the bitmap of reference offsets, refOffsets, from the ifields 5050// list. 5051void ClassLinker::CreateReferenceInstanceOffsets(ConstHandle<mirror::Class> klass) { 5052 uint32_t reference_offsets = 0; 5053 mirror::Class* super_class = klass->GetSuperClass(); 5054 if (super_class != NULL) { 5055 reference_offsets = super_class->GetReferenceInstanceOffsets(); 5056 // If our superclass overflowed, we don't stand a chance. 5057 if (reference_offsets == CLASS_WALK_SUPER) { 5058 klass->SetReferenceInstanceOffsets(reference_offsets); 5059 return; 5060 } 5061 } 5062 CreateReferenceOffsets(klass, false, reference_offsets); 5063} 5064 5065void ClassLinker::CreateReferenceStaticOffsets(ConstHandle<mirror::Class> klass) { 5066 CreateReferenceOffsets(klass, true, 0); 5067} 5068 5069void ClassLinker::CreateReferenceOffsets(ConstHandle<mirror::Class> klass, bool is_static, 5070 uint32_t reference_offsets) { 5071 size_t num_reference_fields = 5072 is_static ? klass->NumReferenceStaticFieldsDuringLinking() 5073 : klass->NumReferenceInstanceFieldsDuringLinking(); 5074 mirror::ObjectArray<mirror::ArtField>* fields = 5075 is_static ? klass->GetSFields() : klass->GetIFields(); 5076 // All of the fields that contain object references are guaranteed 5077 // to be at the beginning of the fields list. 5078 for (size_t i = 0; i < num_reference_fields; ++i) { 5079 // Note that byte_offset is the offset from the beginning of 5080 // object, not the offset into instance data 5081 mirror::ArtField* field = fields->Get(i); 5082 MemberOffset byte_offset = field->GetOffsetDuringLinking(); 5083 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U); 5084 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) { 5085 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value()); 5086 CHECK_NE(new_bit, 0U); 5087 reference_offsets |= new_bit; 5088 } else { 5089 reference_offsets = CLASS_WALK_SUPER; 5090 break; 5091 } 5092 } 5093 // Update fields in klass 5094 if (is_static) { 5095 klass->SetReferenceStaticOffsets(reference_offsets); 5096 } else { 5097 klass->SetReferenceInstanceOffsets(reference_offsets); 5098 } 5099} 5100 5101mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx, 5102 ConstHandle<mirror::DexCache> dex_cache) { 5103 DCHECK(dex_cache.Get() != nullptr); 5104 mirror::String* resolved = dex_cache->GetResolvedString(string_idx); 5105 if (resolved != NULL) { 5106 return resolved; 5107 } 5108 uint32_t utf16_length; 5109 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length); 5110 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data); 5111 dex_cache->SetResolvedString(string_idx, string); 5112 return string; 5113} 5114 5115mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx, 5116 mirror::Class* referrer) { 5117 StackHandleScope<2> hs(Thread::Current()); 5118 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache())); 5119 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader())); 5120 return ResolveType(dex_file, type_idx, dex_cache, class_loader); 5121} 5122 5123mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx, 5124 ConstHandle<mirror::DexCache> dex_cache, 5125 ConstHandle<mirror::ClassLoader> class_loader) { 5126 DCHECK(dex_cache.Get() != NULL); 5127 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx); 5128 if (resolved == NULL) { 5129 Thread* self = Thread::Current(); 5130 const char* descriptor = dex_file.StringByTypeIdx(type_idx); 5131 resolved = FindClass(self, descriptor, class_loader); 5132 if (resolved != NULL) { 5133 // TODO: we used to throw here if resolved's class loader was not the 5134 // boot class loader. This was to permit different classes with the 5135 // same name to be loaded simultaneously by different loaders 5136 dex_cache->SetResolvedType(type_idx, resolved); 5137 } else { 5138 CHECK(self->IsExceptionPending()) 5139 << "Expected pending exception for failed resolution of: " << descriptor; 5140 // Convert a ClassNotFoundException to a NoClassDefFoundError. 5141 StackHandleScope<1> hs(self); 5142 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr))); 5143 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) { 5144 DCHECK(resolved == NULL); // No Handle needed to preserve resolved. 5145 self->ClearException(); 5146 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor); 5147 self->GetException(NULL)->SetCause(cause.Get()); 5148 } 5149 } 5150 } 5151 DCHECK((resolved == NULL) || resolved->IsResolved() || resolved->IsErroneous()) 5152 << PrettyDescriptor(resolved) << " " << resolved->GetStatus(); 5153 return resolved; 5154} 5155 5156mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx, 5157 ConstHandle<mirror::DexCache> dex_cache, 5158 ConstHandle<mirror::ClassLoader> class_loader, 5159 ConstHandle<mirror::ArtMethod> referrer, 5160 InvokeType type) { 5161 DCHECK(dex_cache.Get() != nullptr); 5162 // Check for hit in the dex cache. 5163 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx); 5164 if (resolved != nullptr && !resolved->IsRuntimeMethod()) { 5165 return resolved; 5166 } 5167 // Fail, get the declaring class. 5168 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 5169 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader); 5170 if (klass == nullptr) { 5171 DCHECK(Thread::Current()->IsExceptionPending()); 5172 return nullptr; 5173 } 5174 // Scan using method_idx, this saves string compares but will only hit for matching dex 5175 // caches/files. 5176 switch (type) { 5177 case kDirect: // Fall-through. 5178 case kStatic: 5179 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx); 5180 break; 5181 case kInterface: 5182 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx); 5183 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface()); 5184 break; 5185 case kSuper: // Fall-through. 5186 case kVirtual: 5187 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx); 5188 break; 5189 default: 5190 LOG(FATAL) << "Unreachable - invocation type: " << type; 5191 } 5192 if (resolved == nullptr) { 5193 // Search by name, which works across dex files. 5194 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 5195 const Signature signature = dex_file.GetMethodSignature(method_id); 5196 switch (type) { 5197 case kDirect: // Fall-through. 5198 case kStatic: 5199 resolved = klass->FindDirectMethod(name, signature); 5200 break; 5201 case kInterface: 5202 resolved = klass->FindInterfaceMethod(name, signature); 5203 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface()); 5204 break; 5205 case kSuper: // Fall-through. 5206 case kVirtual: 5207 resolved = klass->FindVirtualMethod(name, signature); 5208 break; 5209 } 5210 } 5211 // If we found a method, check for incompatible class changes. 5212 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) { 5213 // Be a good citizen and update the dex cache to speed subsequent calls. 5214 dex_cache->SetResolvedMethod(method_idx, resolved); 5215 return resolved; 5216 } else { 5217 // If we had a method, it's an incompatible-class-change error. 5218 if (resolved != nullptr) { 5219 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get()); 5220 } else { 5221 // We failed to find the method which means either an access error, an incompatible class 5222 // change, or no such method. First try to find the method among direct and virtual methods. 5223 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 5224 const Signature signature = dex_file.GetMethodSignature(method_id); 5225 switch (type) { 5226 case kDirect: 5227 case kStatic: 5228 resolved = klass->FindVirtualMethod(name, signature); 5229 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would 5230 // have had a resolved method before, which triggers the "true" branch above. 5231 break; 5232 case kInterface: 5233 case kVirtual: 5234 case kSuper: 5235 resolved = klass->FindDirectMethod(name, signature); 5236 break; 5237 } 5238 5239 // If we found something, check that it can be accessed by the referrer. 5240 if (resolved != nullptr && referrer.Get() != nullptr) { 5241 mirror::Class* methods_class = resolved->GetDeclaringClass(); 5242 mirror::Class* referring_class = referrer->GetDeclaringClass(); 5243 if (!referring_class->CanAccess(methods_class)) { 5244 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class, 5245 resolved, type); 5246 return nullptr; 5247 } else if (!referring_class->CanAccessMember(methods_class, 5248 resolved->GetAccessFlags())) { 5249 ThrowIllegalAccessErrorMethod(referring_class, resolved); 5250 return nullptr; 5251 } 5252 } 5253 5254 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface 5255 // methods and throw if we find the method there. If we find nothing, throw a 5256 // NoSuchMethodError. 5257 switch (type) { 5258 case kDirect: 5259 case kStatic: 5260 if (resolved != nullptr) { 5261 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get()); 5262 } else { 5263 resolved = klass->FindInterfaceMethod(name, signature); 5264 if (resolved != nullptr) { 5265 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get()); 5266 } else { 5267 ThrowNoSuchMethodError(type, klass, name, signature); 5268 } 5269 } 5270 break; 5271 case kInterface: 5272 if (resolved != nullptr) { 5273 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get()); 5274 } else { 5275 resolved = klass->FindVirtualMethod(name, signature); 5276 if (resolved != nullptr) { 5277 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get()); 5278 } else { 5279 ThrowNoSuchMethodError(type, klass, name, signature); 5280 } 5281 } 5282 break; 5283 case kSuper: 5284 if (resolved != nullptr) { 5285 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get()); 5286 } else { 5287 ThrowNoSuchMethodError(type, klass, name, signature); 5288 } 5289 break; 5290 case kVirtual: 5291 if (resolved != nullptr) { 5292 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get()); 5293 } else { 5294 resolved = klass->FindInterfaceMethod(name, signature); 5295 if (resolved != nullptr) { 5296 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get()); 5297 } else { 5298 ThrowNoSuchMethodError(type, klass, name, signature); 5299 } 5300 } 5301 break; 5302 } 5303 } 5304 DCHECK(Thread::Current()->IsExceptionPending()); 5305 return nullptr; 5306 } 5307} 5308 5309mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx, 5310 ConstHandle<mirror::DexCache> dex_cache, 5311 ConstHandle<mirror::ClassLoader> class_loader, 5312 bool is_static) { 5313 DCHECK(dex_cache.Get() != nullptr); 5314 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx); 5315 if (resolved != nullptr) { 5316 return resolved; 5317 } 5318 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 5319 Thread* const self = Thread::Current(); 5320 StackHandleScope<1> hs(self); 5321 Handle<mirror::Class> klass( 5322 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 5323 if (klass.Get() == nullptr) { 5324 DCHECK(Thread::Current()->IsExceptionPending()); 5325 return nullptr; 5326 } 5327 5328 if (is_static) { 5329 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx); 5330 } else { 5331 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx); 5332 } 5333 5334 if (resolved == nullptr) { 5335 const char* name = dex_file.GetFieldName(field_id); 5336 const char* type = dex_file.GetFieldTypeDescriptor(field_id); 5337 if (is_static) { 5338 resolved = mirror::Class::FindStaticField(self, klass, name, type); 5339 } else { 5340 resolved = klass->FindInstanceField(name, type); 5341 } 5342 if (resolved == nullptr) { 5343 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name); 5344 return NULL; 5345 } 5346 } 5347 dex_cache->SetResolvedField(field_idx, resolved); 5348 return resolved; 5349} 5350 5351mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, 5352 uint32_t field_idx, 5353 ConstHandle<mirror::DexCache> dex_cache, 5354 ConstHandle<mirror::ClassLoader> class_loader) { 5355 DCHECK(dex_cache.Get() != nullptr); 5356 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx); 5357 if (resolved != nullptr) { 5358 return resolved; 5359 } 5360 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 5361 Thread* self = Thread::Current(); 5362 StackHandleScope<1> hs(self); 5363 Handle<mirror::Class> klass( 5364 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 5365 if (klass.Get() == NULL) { 5366 DCHECK(Thread::Current()->IsExceptionPending()); 5367 return NULL; 5368 } 5369 5370 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_)); 5371 StringPiece type(dex_file.StringDataByIdx( 5372 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_)); 5373 resolved = mirror::Class::FindField(self, klass, name, type); 5374 if (resolved != NULL) { 5375 dex_cache->SetResolvedField(field_idx, resolved); 5376 } else { 5377 ThrowNoSuchFieldError("", klass.Get(), type, name); 5378 } 5379 return resolved; 5380} 5381 5382const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer, 5383 uint32_t* length) { 5384 mirror::Class* declaring_class = referrer->GetDeclaringClass(); 5385 mirror::DexCache* dex_cache = declaring_class->GetDexCache(); 5386 const DexFile& dex_file = *dex_cache->GetDexFile(); 5387 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 5388 return dex_file.GetMethodShorty(method_id, length); 5389} 5390 5391void ClassLinker::DumpAllClasses(int flags) { 5392 if (dex_cache_image_class_lookup_required_) { 5393 MoveImageClassesToClassTable(); 5394 } 5395 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker 5396 // lock held, because it might need to resolve a field's type, which would try to take the lock. 5397 std::vector<mirror::Class*> all_classes; 5398 { 5399 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5400 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) { 5401 mirror::Class* klass = it.second.Read(); 5402 all_classes.push_back(klass); 5403 } 5404 } 5405 5406 for (size_t i = 0; i < all_classes.size(); ++i) { 5407 all_classes[i]->DumpClass(std::cerr, flags); 5408 } 5409} 5410 5411void ClassLinker::DumpForSigQuit(std::ostream& os) { 5412 if (dex_cache_image_class_lookup_required_) { 5413 MoveImageClassesToClassTable(); 5414 } 5415 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5416 os << "Loaded classes: " << class_table_.size() << " allocated classes\n"; 5417} 5418 5419size_t ClassLinker::NumLoadedClasses() { 5420 if (dex_cache_image_class_lookup_required_) { 5421 MoveImageClassesToClassTable(); 5422 } 5423 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5424 return class_table_.size(); 5425} 5426 5427pid_t ClassLinker::GetClassesLockOwner() { 5428 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid(); 5429} 5430 5431pid_t ClassLinker::GetDexLockOwner() { 5432 return dex_lock_.GetExclusiveOwnerTid(); 5433} 5434 5435void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) { 5436 DCHECK(!init_done_); 5437 5438 DCHECK(klass != NULL); 5439 DCHECK(klass->GetClassLoader() == NULL); 5440 5441 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read(); 5442 DCHECK(class_roots != NULL); 5443 DCHECK(class_roots->Get(class_root) == NULL); 5444 class_roots->Set<false>(class_root, klass); 5445} 5446 5447} // namespace art 5448