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