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