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