class_linker.cc revision ee39a10e45a6a0880e8b829525c40d6055818560
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 <sys/types.h> 23#include <sys/wait.h> 24 25#include <deque> 26#include <string> 27#include <utility> 28#include <vector> 29 30#include "base/casts.h" 31#include "base/logging.h" 32#include "base/stl_util.h" 33#include "base/unix_file/fd_file.h" 34#include "class_linker-inl.h" 35#include "debugger.h" 36#include "dex_file-inl.h" 37#include "gc/accounting/card_table-inl.h" 38#include "gc/accounting/heap_bitmap.h" 39#include "gc/heap.h" 40#include "gc/space/image_space.h" 41#include "intern_table.h" 42#include "interpreter/interpreter.h" 43#include "leb128.h" 44#include "oat.h" 45#include "oat_file.h" 46#include "mirror/art_field-inl.h" 47#include "mirror/art_method-inl.h" 48#include "mirror/class.h" 49#include "mirror/class-inl.h" 50#include "mirror/class_loader.h" 51#include "mirror/dex_cache-inl.h" 52#include "mirror/iftable-inl.h" 53#include "mirror/object-inl.h" 54#include "mirror/object_array-inl.h" 55#include "mirror/proxy.h" 56#include "mirror/stack_trace_element.h" 57#include "object_utils.h" 58#include "os.h" 59#include "runtime.h" 60#include "entrypoints/entrypoint_utils.h" 61#include "ScopedLocalRef.h" 62#include "scoped_thread_state_change.h" 63#include "sirt_ref.h" 64#include "stack_indirect_reference_table.h" 65#include "thread.h" 66#include "UniquePtr.h" 67#include "utils.h" 68#include "verifier/method_verifier.h" 69#include "well_known_classes.h" 70 71namespace art { 72 73static void ThrowNoClassDefFoundError(const char* fmt, ...) 74 __attribute__((__format__(__printf__, 1, 2))) 75 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 76static void ThrowNoClassDefFoundError(const char* fmt, ...) { 77 va_list args; 78 va_start(args, fmt); 79 Thread* self = Thread::Current(); 80 ThrowLocation throw_location = self->GetCurrentLocationForThrow(); 81 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args); 82 va_end(args); 83} 84 85static void ThrowEarlierClassFailure(mirror::Class* c) 86 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 87 // The class failed to initialize on a previous attempt, so we want to throw 88 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we 89 // failed in verification, in which case v2 5.4.1 says we need to re-throw 90 // the previous error. 91 if (!Runtime::Current()->IsCompiler()) { // Give info if this occurs at runtime. 92 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c); 93 } 94 95 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus(); 96 Thread* self = Thread::Current(); 97 ThrowLocation throw_location = self->GetCurrentLocationForThrow(); 98 if (c->GetVerifyErrorClass() != NULL) { 99 // TODO: change the verifier to store an _instance_, with a useful detail message? 100 ClassHelper ve_ch(c->GetVerifyErrorClass()); 101 self->ThrowNewException(throw_location, ve_ch.GetDescriptor(), PrettyDescriptor(c).c_str()); 102 } else { 103 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;", 104 PrettyDescriptor(c).c_str()); 105 } 106} 107 108static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 109 Thread* self = Thread::Current(); 110 JNIEnv* env = self->GetJniEnv(); 111 112 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred()); 113 CHECK(cause.get() != NULL); 114 115 env->ExceptionClear(); 116 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error); 117 env->Throw(cause.get()); 118 119 // We only wrap non-Error exceptions; an Error can just be used as-is. 120 if (!is_error) { 121 ThrowLocation throw_location = self->GetCurrentLocationForThrow(); 122 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;", NULL); 123 } 124} 125 126static size_t Hash(const char* s) { 127 // This is the java.lang.String hashcode for convenience, not interoperability. 128 size_t hash = 0; 129 for (; *s != '\0'; ++s) { 130 hash = hash * 31 + *s; 131 } 132 return hash; 133} 134 135const char* ClassLinker::class_roots_descriptors_[] = { 136 "Ljava/lang/Class;", 137 "Ljava/lang/Object;", 138 "[Ljava/lang/Class;", 139 "[Ljava/lang/Object;", 140 "Ljava/lang/String;", 141 "Ljava/lang/DexCache;", 142 "Ljava/lang/ref/Reference;", 143 "Ljava/lang/reflect/ArtField;", 144 "Ljava/lang/reflect/ArtMethod;", 145 "Ljava/lang/reflect/Proxy;", 146 "[Ljava/lang/String;", 147 "[Ljava/lang/reflect/ArtField;", 148 "[Ljava/lang/reflect/ArtMethod;", 149 "Ljava/lang/ClassLoader;", 150 "Ljava/lang/Throwable;", 151 "Ljava/lang/ClassNotFoundException;", 152 "Ljava/lang/StackTraceElement;", 153 "Z", 154 "B", 155 "C", 156 "D", 157 "F", 158 "I", 159 "J", 160 "S", 161 "V", 162 "[Z", 163 "[B", 164 "[C", 165 "[D", 166 "[F", 167 "[I", 168 "[J", 169 "[S", 170 "[Ljava/lang/StackTraceElement;", 171}; 172 173ClassLinker* ClassLinker::CreateFromCompiler(const std::vector<const DexFile*>& boot_class_path, 174 InternTable* intern_table) { 175 CHECK_NE(boot_class_path.size(), 0U); 176 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table)); 177 class_linker->InitFromCompiler(boot_class_path); 178 return class_linker.release(); 179} 180 181ClassLinker* ClassLinker::CreateFromImage(InternTable* intern_table) { 182 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table)); 183 class_linker->InitFromImage(); 184 return class_linker.release(); 185} 186 187ClassLinker::ClassLinker(InternTable* intern_table) 188 // dex_lock_ is recursive as it may be used in stack dumping. 189 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel), 190 dex_cache_image_class_lookup_required_(false), 191 failed_dex_cache_class_lookups_(0), 192 class_roots_(NULL), 193 array_iftable_(NULL), 194 init_done_(false), 195 dex_caches_dirty_(false), 196 class_table_dirty_(false), 197 intern_table_(intern_table), 198 portable_resolution_trampoline_(NULL), 199 quick_resolution_trampoline_(NULL) { 200 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax)); 201} 202 203void ClassLinker::InitFromCompiler(const std::vector<const DexFile*>& boot_class_path) { 204 VLOG(startup) << "ClassLinker::Init"; 205 CHECK(Runtime::Current()->IsCompiler()); 206 207 CHECK(!init_done_); 208 209 // java_lang_Class comes first, it's needed for AllocClass 210 Thread* self = Thread::Current(); 211 gc::Heap* heap = Runtime::Current()->GetHeap(); 212 SirtRef<mirror::Class> 213 java_lang_Class(self, 214 down_cast<mirror::Class*>(heap->AllocObject(self, NULL, 215 sizeof(mirror::ClassClass)))); 216 CHECK(java_lang_Class.get() != NULL); 217 mirror::Class::SetClassClass(java_lang_Class.get()); 218 java_lang_Class->SetClass(java_lang_Class.get()); 219 java_lang_Class->SetClassSize(sizeof(mirror::ClassClass)); 220 // AllocClass(mirror::Class*) can now be used 221 222 // Class[] is used for reflection support. 223 SirtRef<mirror::Class> class_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class))); 224 class_array_class->SetComponentType(java_lang_Class.get()); 225 226 // java_lang_Object comes next so that object_array_class can be created. 227 SirtRef<mirror::Class> java_lang_Object(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class))); 228 CHECK(java_lang_Object.get() != NULL); 229 // backfill Object as the super class of Class. 230 java_lang_Class->SetSuperClass(java_lang_Object.get()); 231 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self); 232 233 // Object[] next to hold class roots. 234 SirtRef<mirror::Class> object_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class))); 235 object_array_class->SetComponentType(java_lang_Object.get()); 236 237 // Setup the char class to be used for char[]. 238 SirtRef<mirror::Class> char_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class))); 239 240 // Setup the char[] class to be used for String. 241 SirtRef<mirror::Class> char_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class))); 242 char_array_class->SetComponentType(char_class.get()); 243 mirror::CharArray::SetArrayClass(char_array_class.get()); 244 245 // Setup String. 246 SirtRef<mirror::Class> java_lang_String(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::StringClass))); 247 mirror::String::SetClass(java_lang_String.get()); 248 java_lang_String->SetObjectSize(sizeof(mirror::String)); 249 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self); 250 251 // Create storage for root classes, save away our work so far (requires descriptors). 252 class_roots_ = mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.get(), kClassRootsMax); 253 CHECK(class_roots_ != NULL); 254 SetClassRoot(kJavaLangClass, java_lang_Class.get()); 255 SetClassRoot(kJavaLangObject, java_lang_Object.get()); 256 SetClassRoot(kClassArrayClass, class_array_class.get()); 257 SetClassRoot(kObjectArrayClass, object_array_class.get()); 258 SetClassRoot(kCharArrayClass, char_array_class.get()); 259 SetClassRoot(kJavaLangString, java_lang_String.get()); 260 261 // Setup the primitive type classes. 262 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean)); 263 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte)); 264 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort)); 265 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt)); 266 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong)); 267 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat)); 268 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble)); 269 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid)); 270 271 // Create array interface entries to populate once we can load system classes. 272 array_iftable_ = AllocIfTable(self, 2); 273 274 // Create int array type for AllocDexCache (done in AppendToBootClassPath). 275 SirtRef<mirror::Class> int_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class))); 276 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt)); 277 mirror::IntArray::SetArrayClass(int_array_class.get()); 278 SetClassRoot(kIntArrayClass, int_array_class.get()); 279 280 // now that these are registered, we can use AllocClass() and AllocObjectArray 281 282 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache. 283 SirtRef<mirror::Class> 284 java_lang_DexCache(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::DexCacheClass))); 285 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.get()); 286 java_lang_DexCache->SetObjectSize(sizeof(mirror::DexCacheClass)); 287 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self); 288 289 // Constructor, Field, Method, and AbstractMethod are necessary so that FindClass can link members. 290 SirtRef<mirror::Class> java_lang_reflect_ArtField(self, AllocClass(self, java_lang_Class.get(), 291 sizeof(mirror::ArtFieldClass))); 292 CHECK(java_lang_reflect_ArtField.get() != NULL); 293 java_lang_reflect_ArtField->SetObjectSize(sizeof(mirror::ArtField)); 294 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.get()); 295 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self); 296 mirror::ArtField::SetClass(java_lang_reflect_ArtField.get()); 297 298 SirtRef<mirror::Class> java_lang_reflect_ArtMethod(self, AllocClass(self, java_lang_Class.get(), 299 sizeof(mirror::ArtMethodClass))); 300 CHECK(java_lang_reflect_ArtMethod.get() != NULL); 301 java_lang_reflect_ArtMethod->SetObjectSize(sizeof(mirror::ArtMethod)); 302 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.get()); 303 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self); 304 305 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.get()); 306 307 // Set up array classes for string, field, method 308 SirtRef<mirror::Class> object_array_string(self, AllocClass(self, java_lang_Class.get(), 309 sizeof(mirror::Class))); 310 object_array_string->SetComponentType(java_lang_String.get()); 311 SetClassRoot(kJavaLangStringArrayClass, object_array_string.get()); 312 313 SirtRef<mirror::Class> object_array_art_method(self, AllocClass(self, java_lang_Class.get(), 314 sizeof(mirror::Class))); 315 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.get()); 316 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.get()); 317 318 SirtRef<mirror::Class> object_array_art_field(self, AllocClass(self, java_lang_Class.get(), 319 sizeof(mirror::Class))); 320 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.get()); 321 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.get()); 322 323 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create 324 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses 325 // these roots. 326 CHECK_NE(0U, boot_class_path.size()); 327 for (size_t i = 0; i != boot_class_path.size(); ++i) { 328 const DexFile* dex_file = boot_class_path[i]; 329 CHECK(dex_file != NULL); 330 AppendToBootClassPath(*dex_file); 331 } 332 333 // now we can use FindSystemClass 334 335 // run char class through InitializePrimitiveClass to finish init 336 InitializePrimitiveClass(char_class.get(), Primitive::kPrimChar); 337 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor 338 339 // Object, String and DexCache need to be rerun through FindSystemClass to finish init 340 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self); 341 mirror::Class* Object_class = FindSystemClass("Ljava/lang/Object;"); 342 CHECK_EQ(java_lang_Object.get(), Object_class); 343 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(mirror::Object)); 344 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self); 345 mirror::Class* String_class = FindSystemClass("Ljava/lang/String;"); 346 CHECK_EQ(java_lang_String.get(), String_class); 347 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(mirror::String)); 348 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self); 349 mirror::Class* DexCache_class = FindSystemClass("Ljava/lang/DexCache;"); 350 CHECK_EQ(java_lang_String.get(), String_class); 351 CHECK_EQ(java_lang_DexCache.get(), DexCache_class); 352 CHECK_EQ(java_lang_DexCache->GetObjectSize(), sizeof(mirror::DexCache)); 353 354 // Setup the primitive array type classes - can't be done until Object has a vtable. 355 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z")); 356 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass)); 357 358 SetClassRoot(kByteArrayClass, FindSystemClass("[B")); 359 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass)); 360 361 mirror::Class* found_char_array_class = FindSystemClass("[C"); 362 CHECK_EQ(char_array_class.get(), found_char_array_class); 363 364 SetClassRoot(kShortArrayClass, FindSystemClass("[S")); 365 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass)); 366 367 mirror::Class* found_int_array_class = FindSystemClass("[I"); 368 CHECK_EQ(int_array_class.get(), found_int_array_class); 369 370 SetClassRoot(kLongArrayClass, FindSystemClass("[J")); 371 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass)); 372 373 SetClassRoot(kFloatArrayClass, FindSystemClass("[F")); 374 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass)); 375 376 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D")); 377 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass)); 378 379 mirror::Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;"); 380 CHECK_EQ(class_array_class.get(), found_class_array_class); 381 382 mirror::Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;"); 383 CHECK_EQ(object_array_class.get(), found_object_array_class); 384 385 // Setup the single, global copy of "iftable". 386 mirror::Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;"); 387 CHECK(java_lang_Cloneable != NULL); 388 mirror::Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;"); 389 CHECK(java_io_Serializable != NULL); 390 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to 391 // crawl up and explicitly list all of the supers as well. 392 array_iftable_->SetInterface(0, java_lang_Cloneable); 393 array_iftable_->SetInterface(1, java_io_Serializable); 394 395 // Sanity check Class[] and Object[]'s interfaces. 396 ClassHelper kh(class_array_class.get(), this); 397 CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0)); 398 CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1)); 399 kh.ChangeClass(object_array_class.get()); 400 CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0)); 401 CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1)); 402 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their 403 // dex_cache_ fields and register them in class_table_. 404 mirror::Class* Class_class = FindSystemClass("Ljava/lang/Class;"); 405 CHECK_EQ(java_lang_Class.get(), Class_class); 406 407 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self); 408 mirror::Class* Art_method_class = FindSystemClass("Ljava/lang/reflect/ArtMethod;"); 409 CHECK_EQ(java_lang_reflect_ArtMethod.get(), Art_method_class); 410 411 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self); 412 mirror::Class* Art_field_class = FindSystemClass("Ljava/lang/reflect/ArtField;"); 413 CHECK_EQ(java_lang_reflect_ArtField.get(), Art_field_class); 414 415 mirror::Class* String_array_class = FindSystemClass(class_roots_descriptors_[kJavaLangStringArrayClass]); 416 CHECK_EQ(object_array_string.get(), String_array_class); 417 418 mirror::Class* Art_method_array_class = 419 FindSystemClass(class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]); 420 CHECK_EQ(object_array_art_method.get(), Art_method_array_class); 421 422 mirror::Class* Art_field_array_class = 423 FindSystemClass(class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]); 424 CHECK_EQ(object_array_art_field.get(), Art_field_array_class); 425 426 // End of special init trickery, subsequent classes may be loaded via FindSystemClass. 427 428 // Create java.lang.reflect.Proxy root. 429 mirror::Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;"); 430 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy); 431 432 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes 433 mirror::Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;"); 434 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference); 435 mirror::Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;"); 436 java_lang_ref_FinalizerReference->SetAccessFlags( 437 java_lang_ref_FinalizerReference->GetAccessFlags() | 438 kAccClassIsReference | kAccClassIsFinalizerReference); 439 mirror::Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;"); 440 java_lang_ref_PhantomReference->SetAccessFlags( 441 java_lang_ref_PhantomReference->GetAccessFlags() | 442 kAccClassIsReference | kAccClassIsPhantomReference); 443 mirror::Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;"); 444 java_lang_ref_SoftReference->SetAccessFlags( 445 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference); 446 mirror::Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;"); 447 java_lang_ref_WeakReference->SetAccessFlags( 448 java_lang_ref_WeakReference->GetAccessFlags() | 449 kAccClassIsReference | kAccClassIsWeakReference); 450 451 // Setup the ClassLoader, verifying the object_size_. 452 mirror::Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;"); 453 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(mirror::ClassLoader)); 454 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader); 455 456 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and 457 // java.lang.StackTraceElement as a convenience. 458 SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;")); 459 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable)); 460 SetClassRoot(kJavaLangClassNotFoundException, FindSystemClass("Ljava/lang/ClassNotFoundException;")); 461 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;")); 462 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;")); 463 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement)); 464 465 FinishInit(); 466 467 VLOG(startup) << "ClassLinker::InitFromCompiler exiting"; 468} 469 470void ClassLinker::FinishInit() { 471 VLOG(startup) << "ClassLinker::FinishInit entering"; 472 473 // Let the heap know some key offsets into java.lang.ref instances 474 // Note: we hard code the field indexes here rather than using FindInstanceField 475 // as the types of the field can't be resolved prior to the runtime being 476 // fully initialized 477 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference); 478 mirror::Class* java_lang_ref_FinalizerReference = 479 FindSystemClass("Ljava/lang/ref/FinalizerReference;"); 480 481 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0); 482 FieldHelper fh(pendingNext, this); 483 CHECK_STREQ(fh.GetName(), "pendingNext"); 484 CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/ref/Reference;"); 485 486 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1); 487 fh.ChangeField(queue); 488 CHECK_STREQ(fh.GetName(), "queue"); 489 CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;"); 490 491 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2); 492 fh.ChangeField(queueNext); 493 CHECK_STREQ(fh.GetName(), "queueNext"); 494 CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/ref/Reference;"); 495 496 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3); 497 fh.ChangeField(referent); 498 CHECK_STREQ(fh.GetName(), "referent"); 499 CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/Object;"); 500 501 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2); 502 fh.ChangeField(zombie); 503 CHECK_STREQ(fh.GetName(), "zombie"); 504 CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/Object;"); 505 506 gc::Heap* heap = Runtime::Current()->GetHeap(); 507 heap->SetReferenceOffsets(referent->GetOffset(), 508 queue->GetOffset(), 509 queueNext->GetOffset(), 510 pendingNext->GetOffset(), 511 zombie->GetOffset()); 512 513 // ensure all class_roots_ are initialized 514 for (size_t i = 0; i < kClassRootsMax; i++) { 515 ClassRoot class_root = static_cast<ClassRoot>(i); 516 mirror::Class* klass = GetClassRoot(class_root); 517 CHECK(klass != NULL); 518 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL); 519 // note SetClassRoot does additional validation. 520 // if possible add new checks there to catch errors early 521 } 522 523 CHECK(array_iftable_ != NULL); 524 525 // disable the slow paths in FindClass and CreatePrimitiveClass now 526 // that Object, Class, and Object[] are setup 527 init_done_ = true; 528 529 VLOG(startup) << "ClassLinker::FinishInit exiting"; 530} 531 532void ClassLinker::RunRootClinits() { 533 Thread* self = Thread::Current(); 534 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) { 535 mirror::Class* c = GetClassRoot(ClassRoot(i)); 536 if (!c->IsArrayClass() && !c->IsPrimitive()) { 537 EnsureInitialized(GetClassRoot(ClassRoot(i)), true, true); 538 self->AssertNoPendingException(); 539 } 540 } 541} 542 543bool ClassLinker::GenerateOatFile(const std::string& dex_filename, 544 int oat_fd, 545 const std::string& oat_cache_filename) { 546 std::string dex2oat_string(GetAndroidRoot()); 547 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat"); 548 const char* dex2oat = dex2oat_string.c_str(); 549 550 const char* class_path = Runtime::Current()->GetClassPathString().c_str(); 551 552 gc::Heap* heap = Runtime::Current()->GetHeap(); 553 std::string boot_image_option_string("--boot-image="); 554 boot_image_option_string += heap->GetImageSpace()->GetImageFilename(); 555 const char* boot_image_option = boot_image_option_string.c_str(); 556 557 std::string dex_file_option_string("--dex-file="); 558 dex_file_option_string += dex_filename; 559 const char* dex_file_option = dex_file_option_string.c_str(); 560 561 std::string oat_fd_option_string("--oat-fd="); 562 StringAppendF(&oat_fd_option_string, "%d", oat_fd); 563 const char* oat_fd_option = oat_fd_option_string.c_str(); 564 565 std::string oat_location_option_string("--oat-location="); 566 oat_location_option_string += oat_cache_filename; 567 const char* oat_location_option = oat_location_option_string.c_str(); 568 569 std::string oat_compiler_filter_string("-compiler-filter:"); 570 switch (Runtime::Current()->GetCompilerFilter()) { 571 case Runtime::kInterpretOnly: 572 oat_compiler_filter_string += "interpret-only"; 573 break; 574 case Runtime::kSpace: 575 oat_compiler_filter_string += "space"; 576 break; 577 case Runtime::kBalanced: 578 oat_compiler_filter_string += "balanced"; 579 break; 580 case Runtime::kSpeed: 581 oat_compiler_filter_string += "speed"; 582 break; 583 case Runtime::kEverything: 584 oat_compiler_filter_string += "everything"; 585 break; 586 default: 587 LOG(FATAL) << "Unexpected case."; 588 } 589 const char* oat_compiler_filter_option = oat_compiler_filter_string.c_str(); 590 591 // fork and exec dex2oat 592 pid_t pid = fork(); 593 if (pid == 0) { 594 // no allocation allowed between fork and exec 595 596 // change process groups, so we don't get reaped by ProcessManager 597 setpgid(0, 0); 598 599 VLOG(class_linker) << dex2oat 600 << " --runtime-arg -Xms64m" 601 << " --runtime-arg -Xmx64m" 602 << " --runtime-arg -classpath" 603 << " --runtime-arg " << class_path 604 << " --runtime-arg " << oat_compiler_filter_option 605#if !defined(ART_TARGET) 606 << " --host" 607#endif 608 << " " << boot_image_option 609 << " " << dex_file_option 610 << " " << oat_fd_option 611 << " " << oat_location_option; 612 613 execl(dex2oat, dex2oat, 614 "--runtime-arg", "-Xms64m", 615 "--runtime-arg", "-Xmx64m", 616 "--runtime-arg", "-classpath", 617 "--runtime-arg", class_path, 618 "--runtime-arg", oat_compiler_filter_option, 619#if !defined(ART_TARGET) 620 "--host", 621#endif 622 boot_image_option, 623 dex_file_option, 624 oat_fd_option, 625 oat_location_option, 626 NULL); 627 628 PLOG(FATAL) << "execl(" << dex2oat << ") failed"; 629 return false; 630 } else { 631 // wait for dex2oat to finish 632 int status; 633 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0)); 634 if (got_pid != pid) { 635 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid; 636 return false; 637 } 638 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { 639 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename; 640 return false; 641 } 642 } 643 return true; 644} 645 646void ClassLinker::RegisterOatFile(const OatFile& oat_file) { 647 WriterMutexLock mu(Thread::Current(), dex_lock_); 648 RegisterOatFileLocked(oat_file); 649} 650 651void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) { 652 dex_lock_.AssertExclusiveHeld(Thread::Current()); 653 if (kIsDebugBuild) { 654 for (size_t i = 0; i < oat_files_.size(); ++i) { 655 CHECK_NE(&oat_file, oat_files_[i]) << oat_file.GetLocation(); 656 } 657 } 658 VLOG(class_linker) << "Registering " << oat_file.GetLocation(); 659 oat_files_.push_back(&oat_file); 660} 661 662OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) { 663 VLOG(startup) << "ClassLinker::GetImageOatFile entering"; 664 OatFile& oat_file = space->ReleaseOatFile(); 665 WriterMutexLock mu(Thread::Current(), dex_lock_); 666 RegisterOatFileLocked(oat_file); 667 VLOG(startup) << "ClassLinker::GetImageOatFile exiting"; 668 return oat_file; 669} 670 671const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) { 672 ReaderMutexLock mu(Thread::Current(), dex_lock_); 673 return FindOpenedOatFileFromDexLocation(dex_file.GetLocation()); 674} 675 676const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const std::string& dex_location) { 677 for (size_t i = 0; i < oat_files_.size(); i++) { 678 const OatFile* oat_file = oat_files_[i]; 679 DCHECK(oat_file != NULL); 680 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, false); 681 if (oat_dex_file != NULL) { 682 return oat_file; 683 } 684 } 685 return NULL; 686} 687 688const DexFile* ClassLinker::FindDexFileInOatLocation(const std::string& dex_location, 689 uint32_t dex_location_checksum, 690 const std::string& oat_location) { 691 UniquePtr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL, 692 !Runtime::Current()->IsCompiler())); 693 if (oat_file.get() == NULL) { 694 VLOG(class_linker) << "Failed to find existing oat file at " << oat_location; 695 return NULL; 696 } 697 Runtime* runtime = Runtime::Current(); 698 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader(); 699 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum(); 700 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum(); 701 if (expected_image_oat_checksum != actual_image_oat_checksum) { 702 VLOG(class_linker) << "Failed to find oat file at " << oat_location 703 << " with expected image oat checksum of " << expected_image_oat_checksum 704 << ", found " << actual_image_oat_checksum; 705 return NULL; 706 } 707 708 uint32_t expected_image_oat_offset = reinterpret_cast<uint32_t>(image_header.GetOatDataBegin()); 709 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(); 710 if (expected_image_oat_offset != actual_image_oat_offset) { 711 VLOG(class_linker) << "Failed to find oat file at " << oat_location 712 << " with expected image oat offset " << expected_image_oat_offset 713 << ", found " << actual_image_oat_offset; 714 return NULL; 715 } 716 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location); 717 if (oat_dex_file == NULL) { 718 VLOG(class_linker) << "Failed to find oat file at " << oat_location << " containing " << dex_location; 719 return NULL; 720 } 721 uint32_t expected_dex_checksum = dex_location_checksum; 722 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum(); 723 if (expected_dex_checksum != actual_dex_checksum) { 724 VLOG(class_linker) << "Failed to find oat file at " << oat_location 725 << " with expected dex checksum of " << expected_dex_checksum 726 << ", found " << actual_dex_checksum; 727 return NULL; 728 } 729 RegisterOatFileLocked(*oat_file.release()); 730 return oat_dex_file->OpenDexFile(); 731} 732 733const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const std::string& dex_location, 734 const std::string& oat_location) { 735 WriterMutexLock mu(Thread::Current(), dex_lock_); 736 return FindOrCreateOatFileForDexLocationLocked(dex_location, oat_location); 737} 738 739class ScopedFlock { 740 public: 741 ScopedFlock() {} 742 743 bool Init(const std::string& filename) { 744 while (true) { 745 file_.reset(OS::OpenFileWithFlags(filename.c_str(), O_CREAT | O_RDWR)); 746 if (file_.get() == NULL) { 747 LOG(ERROR) << "Failed to open file: " << filename; 748 return false; 749 } 750 int flock_result = TEMP_FAILURE_RETRY(flock(file_->Fd(), LOCK_EX)); 751 if (flock_result != 0) { 752 PLOG(ERROR) << "Failed to lock file: " << filename; 753 return false; 754 } 755 struct stat fstat_stat; 756 int fstat_result = TEMP_FAILURE_RETRY(fstat(file_->Fd(), &fstat_stat)); 757 if (fstat_result != 0) { 758 PLOG(ERROR) << "Failed to fstat: " << filename; 759 return false; 760 } 761 struct stat stat_stat; 762 int stat_result = TEMP_FAILURE_RETRY(stat(filename.c_str(), &stat_stat)); 763 if (stat_result != 0) { 764 PLOG(WARNING) << "Failed to stat, will retry: " << filename; 765 // ENOENT can happen if someone racing with us unlinks the file we created so just retry. 766 continue; 767 } 768 if (fstat_stat.st_dev != stat_stat.st_dev || fstat_stat.st_ino != stat_stat.st_ino) { 769 LOG(WARNING) << "File changed while locking, will retry: " << filename; 770 continue; 771 } 772 return true; 773 } 774 } 775 776 File& GetFile() { 777 return *file_; 778 } 779 780 ~ScopedFlock() { 781 if (file_.get() != NULL) { 782 int flock_result = TEMP_FAILURE_RETRY(flock(file_->Fd(), LOCK_UN)); 783 CHECK_EQ(0, flock_result); 784 } 785 } 786 787 private: 788 UniquePtr<File> file_; 789 790 DISALLOW_COPY_AND_ASSIGN(ScopedFlock); 791}; 792 793const DexFile* ClassLinker::FindOrCreateOatFileForDexLocationLocked(const std::string& dex_location, 794 const std::string& oat_location) { 795 uint32_t dex_location_checksum; 796 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) { 797 LOG(ERROR) << "Failed to compute checksum '" << dex_location << "'"; 798 return NULL; 799 } 800 801 // We play a locking game here so that if two different processes 802 // race to generate (or worse, one tries to open a partial generated 803 // file) we will be okay. This is actually common with apps that use 804 // DexClassLoader to work around the dex method reference limit and 805 // that have a background service running in a separate process. 806 ScopedFlock scoped_flock; 807 if (!scoped_flock.Init(oat_location)) { 808 LOG(ERROR) << "Failed to open locked oat file: " << oat_location; 809 return NULL; 810 } 811 812 // Check if we already have an up-to-date output file 813 const DexFile* dex_file = FindDexFileInOatLocation(dex_location, 814 dex_location_checksum, 815 oat_location); 816 if (dex_file != NULL) { 817 return dex_file; 818 } 819 820 // Generate the output oat file for the dex file 821 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location; 822 if (!GenerateOatFile(dex_location, scoped_flock.GetFile().Fd(), oat_location)) { 823 LOG(ERROR) << "Failed to generate oat file: " << oat_location; 824 return NULL; 825 } 826 const OatFile* oat_file = OatFile::Open(oat_location, oat_location, NULL, 827 !Runtime::Current()->IsCompiler()); 828 if (oat_file == NULL) { 829 LOG(ERROR) << "Failed to open generated oat file: " << oat_location; 830 return NULL; 831 } 832 RegisterOatFileLocked(*oat_file); 833 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location); 834 if (oat_dex_file == NULL) { 835 LOG(ERROR) << "Failed to find dex file in generated oat file: " << oat_location; 836 return NULL; 837 } 838 return oat_dex_file->OpenDexFile(); 839} 840 841bool ClassLinker::VerifyOatFileChecksums(const OatFile* oat_file, 842 const std::string& dex_location, 843 uint32_t dex_location_checksum) { 844 Runtime* runtime = Runtime::Current(); 845 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader(); 846 uint32_t image_oat_checksum = image_header.GetOatChecksum(); 847 uint32_t image_oat_data_begin = reinterpret_cast<uint32_t>(image_header.GetOatDataBegin()); 848 bool image_check = ((oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum) 849 && (oat_file->GetOatHeader().GetImageFileLocationOatDataBegin() == image_oat_data_begin)); 850 851 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location); 852 if (oat_dex_file == NULL) { 853 LOG(ERROR) << "oat file " << oat_file->GetLocation() 854 << " does not contain contents for " << dex_location; 855 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file->GetOatDexFiles(); 856 for (size_t i = 0; i < oat_dex_files.size(); i++) { 857 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i]; 858 LOG(ERROR) << "oat file " << oat_file->GetLocation() 859 << " contains contents for " << oat_dex_file->GetDexFileLocation(); 860 } 861 return false; 862 } 863 bool dex_check = dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum(); 864 865 if (image_check && dex_check) { 866 return true; 867 } 868 869 if (!image_check) { 870 std::string image_file(image_header.GetImageRoot( 871 ImageHeader::kOatLocation)->AsString()->ToModifiedUtf8()); 872 LOG(WARNING) << "oat file " << oat_file->GetLocation() 873 << " mismatch ( " << std::hex << oat_file->GetOatHeader().GetImageFileLocationOatChecksum() 874 << ", " << oat_file->GetOatHeader().GetImageFileLocationOatDataBegin() 875 << ") with " << image_file 876 << " (" << image_oat_checksum << ", " << std::hex << image_oat_data_begin << ")"; 877 } 878 if (!dex_check) { 879 LOG(WARNING) << "oat file " << oat_file->GetLocation() 880 << " mismatch ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum() 881 << ") with " << dex_location 882 << " (" << std::hex << dex_location_checksum << ")"; 883 } 884 return false; 885} 886 887const DexFile* ClassLinker::VerifyAndOpenDexFileFromOatFile(const OatFile* oat_file, 888 const std::string& dex_location, 889 uint32_t dex_location_checksum) { 890 bool verified = VerifyOatFileChecksums(oat_file, dex_location, dex_location_checksum); 891 if (!verified) { 892 return NULL; 893 } 894 RegisterOatFileLocked(*oat_file); 895 return oat_file->GetOatDexFile(dex_location)->OpenDexFile(); 896} 897 898const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const std::string& dex_location) { 899 WriterMutexLock mu(Thread::Current(), dex_lock_); 900 901 const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location); 902 if (open_oat_file != NULL) { 903 return open_oat_file->GetOatDexFile(dex_location)->OpenDexFile(); 904 } 905 906 // Look for an existing file next to dex. for example, for 907 // /foo/bar/baz.jar, look for /foo/bar/baz.odex. 908 std::string odex_filename(OatFile::DexFilenameToOdexFilename(dex_location)); 909 const OatFile* oat_file = FindOatFileFromOatLocationLocked(odex_filename); 910 if (oat_file != NULL) { 911 uint32_t dex_location_checksum; 912 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) { 913 // If no classes.dex found in dex_location, it has been stripped, assume oat is up-to-date. 914 // This is the common case in user builds for jar's and apk's in the /system directory. 915 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location); 916 CHECK(oat_dex_file != NULL) << odex_filename << " " << dex_location; 917 RegisterOatFileLocked(*oat_file); 918 return oat_dex_file->OpenDexFile(); 919 } 920 const DexFile* dex_file = VerifyAndOpenDexFileFromOatFile(oat_file, 921 dex_location, 922 dex_location_checksum); 923 if (dex_file != NULL) { 924 return dex_file; 925 } 926 } 927 // Look for an existing file in the dalvik-cache, validating the result if found 928 // not found in /foo/bar/baz.odex? try /data/dalvik-cache/foo@bar@baz.jar@classes.dex 929 std::string cache_location(GetDalvikCacheFilenameOrDie(dex_location)); 930 oat_file = FindOatFileFromOatLocationLocked(cache_location); 931 if (oat_file != NULL) { 932 uint32_t dex_location_checksum; 933 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) { 934 LOG(WARNING) << "Failed to compute checksum: " << dex_location; 935 return NULL; 936 } 937 const DexFile* dex_file = VerifyAndOpenDexFileFromOatFile(oat_file, 938 dex_location, 939 dex_location_checksum); 940 if (dex_file != NULL) { 941 return dex_file; 942 } 943 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) { 944 PLOG(FATAL) << "Failed to remove obsolete oat file " << oat_file->GetLocation(); 945 } 946 } 947 LOG(INFO) << "Failed to open oat file from " << odex_filename << " or " << cache_location << "."; 948 949 // Try to generate oat file if it wasn't found or was obsolete. 950 std::string oat_cache_filename(GetDalvikCacheFilenameOrDie(dex_location)); 951 return FindOrCreateOatFileForDexLocationLocked(dex_location, oat_cache_filename); 952} 953 954const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) { 955 for (size_t i = 0; i < oat_files_.size(); i++) { 956 const OatFile* oat_file = oat_files_[i]; 957 DCHECK(oat_file != NULL); 958 if (oat_file->GetLocation() == oat_location) { 959 return oat_file; 960 } 961 } 962 return NULL; 963} 964 965const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) { 966 ReaderMutexLock mu(Thread::Current(), dex_lock_); 967 return FindOatFileFromOatLocationLocked(oat_location); 968} 969 970const OatFile* ClassLinker::FindOatFileFromOatLocationLocked(const std::string& oat_location) { 971 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location); 972 if (oat_file != NULL) { 973 return oat_file; 974 } 975 976 oat_file = OatFile::Open(oat_location, oat_location, NULL, !Runtime::Current()->IsCompiler()); 977 if (oat_file == NULL) { 978 return NULL; 979 } 980 return oat_file; 981} 982 983static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) 984 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 985 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg); 986 987 DCHECK(obj != NULL); 988 DCHECK(class_linker != NULL); 989 990 if (obj->IsArtMethod()) { 991 mirror::ArtMethod* method = obj->AsArtMethod(); 992 if (!method->IsNative()) { 993 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge); 994 if (method != Runtime::Current()->GetResolutionMethod()) { 995 method->SetEntryPointFromCompiledCode(GetCompiledCodeToInterpreterBridge()); 996 } 997 } 998 } 999} 1000 1001void ClassLinker::InitFromImage() { 1002 VLOG(startup) << "ClassLinker::InitFromImage entering"; 1003 CHECK(!init_done_); 1004 1005 gc::Heap* heap = Runtime::Current()->GetHeap(); 1006 gc::space::ImageSpace* space = heap->GetImageSpace(); 1007 dex_cache_image_class_lookup_required_ = true; 1008 CHECK(space != NULL); 1009 OatFile& oat_file = GetImageOatFile(space); 1010 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U); 1011 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U); 1012 CHECK(oat_file.GetOatHeader().GetImageFileLocation().empty()); 1013 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline(); 1014 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline(); 1015 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 1016 mirror::ObjectArray<mirror::DexCache>* dex_caches = 1017 dex_caches_object->AsObjectArray<mirror::DexCache>(); 1018 1019 mirror::ObjectArray<mirror::Class>* class_roots = 1020 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>(); 1021 class_roots_ = class_roots; 1022 1023 // Special case of setting up the String class early so that we can test arbitrary objects 1024 // as being Strings or not 1025 mirror::String::SetClass(GetClassRoot(kJavaLangString)); 1026 1027 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(), 1028 static_cast<uint32_t>(dex_caches->GetLength())); 1029 Thread* self = Thread::Current(); 1030 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 1031 SirtRef<mirror::DexCache> dex_cache(self, dex_caches->Get(i)); 1032 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8()); 1033 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location); 1034 CHECK(oat_dex_file != NULL) << oat_file.GetLocation() << " " << dex_file_location; 1035 const DexFile* dex_file = oat_dex_file->OpenDexFile(); 1036 if (dex_file == NULL) { 1037 LOG(FATAL) << "Failed to open dex file " << dex_file_location 1038 << " from within oat file " << oat_file.GetLocation(); 1039 } 1040 1041 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum()); 1042 1043 AppendToBootClassPath(*dex_file, dex_cache); 1044 } 1045 1046 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live 1047 // bitmap walk. 1048 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod)); 1049 1050 // Set entry point to interpreter if in InterpretOnly mode. 1051 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) { 1052 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 1053 heap->FlushAllocStack(); 1054 heap->GetLiveBitmap()->Walk(InitFromImageInterpretOnlyCallback, this); 1055 } 1056 1057 // reinit class_roots_ 1058 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass)); 1059 class_roots_ = class_roots; 1060 1061 // reinit array_iftable_ from any array class instance, they should be == 1062 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable(); 1063 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable()); 1064 // String class root was set above 1065 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField)); 1066 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass)); 1067 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass)); 1068 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass)); 1069 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass)); 1070 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass)); 1071 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass)); 1072 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass)); 1073 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass)); 1074 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable)); 1075 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement)); 1076 1077 FinishInit(); 1078 1079 VLOG(startup) << "ClassLinker::InitFromImage exiting"; 1080} 1081 1082// Keep in sync with InitCallback. Anything we visit, we need to 1083// reinit references to when reinitializing a ClassLinker from a 1084// mapped image. 1085void ClassLinker::VisitRoots(RootVisitor* visitor, void* arg, bool only_dirty, bool clean_dirty) { 1086 visitor(class_roots_, arg); 1087 Thread* self = Thread::Current(); 1088 { 1089 ReaderMutexLock mu(self, dex_lock_); 1090 if (!only_dirty || dex_caches_dirty_) { 1091 for (mirror::DexCache* dex_cache : dex_caches_) { 1092 visitor(dex_cache, arg); 1093 } 1094 if (clean_dirty) { 1095 dex_caches_dirty_ = false; 1096 } 1097 } 1098 } 1099 1100 { 1101 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); 1102 if (!only_dirty || class_table_dirty_) { 1103 for (const std::pair<size_t, mirror::Class*>& it : class_table_) { 1104 visitor(it.second, arg); 1105 } 1106 if (clean_dirty) { 1107 class_table_dirty_ = false; 1108 } 1109 } 1110 1111 // We deliberately ignore the class roots in the image since we 1112 // handle image roots by using the MS/CMS rescanning of dirty cards. 1113 } 1114 1115 visitor(array_iftable_, arg); 1116} 1117 1118void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) { 1119 if (dex_cache_image_class_lookup_required_) { 1120 MoveImageClassesToClassTable(); 1121 } 1122 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1123 for (const std::pair<size_t, mirror::Class*>& it : class_table_) { 1124 if (!visitor(it.second, arg)) { 1125 return; 1126 } 1127 } 1128} 1129 1130static bool GetClassesVisitor(mirror::Class* c, void* arg) { 1131 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg); 1132 classes->insert(c); 1133 return true; 1134} 1135 1136void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) { 1137 std::set<mirror::Class*> classes; 1138 VisitClasses(GetClassesVisitor, &classes); 1139 for (mirror::Class* klass : classes) { 1140 if (!visitor(klass, arg)) { 1141 return; 1142 } 1143 } 1144} 1145 1146 1147ClassLinker::~ClassLinker() { 1148 mirror::Class::ResetClass(); 1149 mirror::String::ResetClass(); 1150 mirror::ArtField::ResetClass(); 1151 mirror::ArtMethod::ResetClass(); 1152 mirror::BooleanArray::ResetArrayClass(); 1153 mirror::ByteArray::ResetArrayClass(); 1154 mirror::CharArray::ResetArrayClass(); 1155 mirror::DoubleArray::ResetArrayClass(); 1156 mirror::FloatArray::ResetArrayClass(); 1157 mirror::IntArray::ResetArrayClass(); 1158 mirror::LongArray::ResetArrayClass(); 1159 mirror::ShortArray::ResetArrayClass(); 1160 mirror::Throwable::ResetClass(); 1161 mirror::StackTraceElement::ResetClass(); 1162 STLDeleteElements(&boot_class_path_); 1163 STLDeleteElements(&oat_files_); 1164} 1165 1166mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) { 1167 gc::Heap* heap = Runtime::Current()->GetHeap(); 1168 mirror::Class* dex_cache_class = GetClassRoot(kJavaLangDexCache); 1169 SirtRef<mirror::DexCache> dex_cache(self, 1170 down_cast<mirror::DexCache*>(heap->AllocObject(self, dex_cache_class, 1171 dex_cache_class->GetObjectSize()))); 1172 if (dex_cache.get() == NULL) { 1173 return NULL; 1174 } 1175 SirtRef<mirror::String> 1176 location(self, intern_table_->InternStrong(dex_file.GetLocation().c_str())); 1177 if (location.get() == NULL) { 1178 return NULL; 1179 } 1180 SirtRef<mirror::ObjectArray<mirror::String> > 1181 strings(self, AllocStringArray(self, dex_file.NumStringIds())); 1182 if (strings.get() == NULL) { 1183 return NULL; 1184 } 1185 SirtRef<mirror::ObjectArray<mirror::Class> > 1186 types(self, AllocClassArray(self, dex_file.NumTypeIds())); 1187 if (types.get() == NULL) { 1188 return NULL; 1189 } 1190 SirtRef<mirror::ObjectArray<mirror::ArtMethod> > 1191 methods(self, AllocArtMethodArray(self, dex_file.NumMethodIds())); 1192 if (methods.get() == NULL) { 1193 return NULL; 1194 } 1195 SirtRef<mirror::ObjectArray<mirror::ArtField> > 1196 fields(self, AllocArtFieldArray(self, dex_file.NumFieldIds())); 1197 if (fields.get() == NULL) { 1198 return NULL; 1199 } 1200 SirtRef<mirror::ObjectArray<mirror::StaticStorageBase> > 1201 initialized_static_storage(self, 1202 AllocObjectArray<mirror::StaticStorageBase>(self, dex_file.NumTypeIds())); 1203 if (initialized_static_storage.get() == NULL) { 1204 return NULL; 1205 } 1206 1207 dex_cache->Init(&dex_file, 1208 location.get(), 1209 strings.get(), 1210 types.get(), 1211 methods.get(), 1212 fields.get(), 1213 initialized_static_storage.get()); 1214 return dex_cache.get(); 1215} 1216 1217mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class, 1218 size_t class_size) { 1219 DCHECK_GE(class_size, sizeof(mirror::Class)); 1220 gc::Heap* heap = Runtime::Current()->GetHeap(); 1221 mirror::Object* k = heap->AllocObject(self, java_lang_Class, class_size); 1222 if (UNLIKELY(k == NULL)) { 1223 CHECK(self->IsExceptionPending()); // OOME. 1224 return NULL; 1225 } 1226 mirror::Class* klass = k->AsClass(); 1227 klass->SetPrimitiveType(Primitive::kPrimNot); // Default to not being primitive. 1228 klass->SetClassSize(class_size); 1229 klass->SetDexClassDefIndex(DexFile::kDexNoIndex16); // Default to no valid class def index. 1230 klass->SetDexTypeIndex(DexFile::kDexNoIndex16); // Default to no valid type index. 1231 return klass; 1232} 1233 1234mirror::Class* ClassLinker::AllocClass(Thread* self, size_t class_size) { 1235 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size); 1236} 1237 1238mirror::ArtField* ClassLinker::AllocArtField(Thread* self) { 1239 return down_cast<mirror::ArtField*>(GetClassRoot(kJavaLangReflectArtField)->AllocObject(self)); 1240} 1241 1242mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) { 1243 return down_cast<mirror::ArtMethod*>(GetClassRoot(kJavaLangReflectArtMethod)->AllocObject(self)); 1244} 1245 1246mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(Thread* self, 1247 size_t length) { 1248 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(self, 1249 GetClassRoot(kJavaLangStackTraceElementArrayClass), 1250 length); 1251} 1252 1253static mirror::Class* EnsureResolved(Thread* self, mirror::Class* klass) 1254 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1255 DCHECK(klass != NULL); 1256 // Wait for the class if it has not already been linked. 1257 if (!klass->IsResolved() && !klass->IsErroneous()) { 1258 ObjectLock lock(self, klass); 1259 // Check for circular dependencies between classes. 1260 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) { 1261 ThrowClassCircularityError(klass); 1262 klass->SetStatus(mirror::Class::kStatusError, self); 1263 return NULL; 1264 } 1265 // Wait for the pending initialization to complete. 1266 while (!klass->IsResolved() && !klass->IsErroneous()) { 1267 lock.WaitIgnoringInterrupts(); 1268 } 1269 } 1270 if (klass->IsErroneous()) { 1271 ThrowEarlierClassFailure(klass); 1272 return NULL; 1273 } 1274 // Return the loaded class. No exceptions should be pending. 1275 CHECK(klass->IsResolved()) << PrettyClass(klass); 1276 self->AssertNoPendingException(); 1277 return klass; 1278} 1279 1280bool ClassLinker::IsInBootClassPath(const char* descriptor) { 1281 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_); 1282 return pair.second != NULL; 1283} 1284 1285mirror::Class* ClassLinker::FindSystemClass(const char* descriptor) { 1286 return FindClass(descriptor, NULL); 1287} 1288 1289mirror::Class* ClassLinker::FindClass(const char* descriptor, mirror::ClassLoader* class_loader) { 1290 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string"; 1291 Thread* self = Thread::Current(); 1292 DCHECK(self != NULL); 1293 self->AssertNoPendingException(); 1294 if (descriptor[1] == '\0') { 1295 // only the descriptors of primitive types should be 1 character long, also avoid class lookup 1296 // for primitive classes that aren't backed by dex files. 1297 return FindPrimitiveClass(descriptor[0]); 1298 } 1299 // Find the class in the loaded classes table. 1300 mirror::Class* klass = LookupClass(descriptor, class_loader); 1301 if (klass != NULL) { 1302 return EnsureResolved(self, klass); 1303 } 1304 // Class is not yet loaded. 1305 if (descriptor[0] == '[') { 1306 return CreateArrayClass(descriptor, class_loader); 1307 1308 } else if (class_loader == NULL) { 1309 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_); 1310 if (pair.second != NULL) { 1311 return DefineClass(descriptor, NULL, *pair.first, *pair.second); 1312 } 1313 1314 } else if (Runtime::Current()->UseCompileTimeClassPath()) { 1315 // First try the boot class path, we check the descriptor first to avoid an unnecessary 1316 // throw of a NoClassDefFoundError. 1317 if (IsInBootClassPath(descriptor)) { 1318 mirror::Class* system_class = FindSystemClass(descriptor); 1319 CHECK(system_class != NULL); 1320 return system_class; 1321 } 1322 // Next try the compile time class path. 1323 const std::vector<const DexFile*>* class_path; 1324 { 1325 ScopedObjectAccessUnchecked soa(self); 1326 ScopedLocalRef<jobject> jclass_loader(soa.Env(), soa.AddLocalReference<jobject>(class_loader)); 1327 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get()); 1328 } 1329 1330 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, *class_path); 1331 if (pair.second != NULL) { 1332 return DefineClass(descriptor, class_loader, *pair.first, *pair.second); 1333 } 1334 1335 } else { 1336 ScopedObjectAccessUnchecked soa(self->GetJniEnv()); 1337 ScopedLocalRef<jobject> class_loader_object(soa.Env(), 1338 soa.AddLocalReference<jobject>(class_loader)); 1339 std::string class_name_string(DescriptorToDot(descriptor)); 1340 ScopedLocalRef<jobject> result(soa.Env(), NULL); 1341 { 1342 ScopedThreadStateChange tsc(self, kNative); 1343 ScopedLocalRef<jobject> class_name_object(soa.Env(), 1344 soa.Env()->NewStringUTF(class_name_string.c_str())); 1345 if (class_name_object.get() == NULL) { 1346 return NULL; 1347 } 1348 CHECK(class_loader_object.get() != NULL); 1349 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(), 1350 WellKnownClasses::java_lang_ClassLoader_loadClass, 1351 class_name_object.get())); 1352 } 1353 if (soa.Self()->IsExceptionPending()) { 1354 // If the ClassLoader threw, pass that exception up. 1355 return NULL; 1356 } else if (result.get() == NULL) { 1357 // broken loader - throw NPE to be compatible with Dalvik 1358 ThrowNullPointerException(NULL, StringPrintf("ClassLoader.loadClass returned null for %s", 1359 class_name_string.c_str()).c_str()); 1360 return NULL; 1361 } else { 1362 // success, return mirror::Class* 1363 return soa.Decode<mirror::Class*>(result.get()); 1364 } 1365 } 1366 1367 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str()); 1368 return NULL; 1369} 1370 1371mirror::Class* ClassLinker::DefineClass(const char* descriptor, 1372 mirror::ClassLoader* class_loader, 1373 const DexFile& dex_file, 1374 const DexFile::ClassDef& dex_class_def) { 1375 Thread* self = Thread::Current(); 1376 SirtRef<mirror::Class> klass(self, NULL); 1377 // Load the class from the dex file. 1378 if (UNLIKELY(!init_done_)) { 1379 // finish up init of hand crafted class_roots_ 1380 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) { 1381 klass.reset(GetClassRoot(kJavaLangObject)); 1382 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) { 1383 klass.reset(GetClassRoot(kJavaLangClass)); 1384 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) { 1385 klass.reset(GetClassRoot(kJavaLangString)); 1386 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) { 1387 klass.reset(GetClassRoot(kJavaLangDexCache)); 1388 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) { 1389 klass.reset(GetClassRoot(kJavaLangReflectArtField)); 1390 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) { 1391 klass.reset(GetClassRoot(kJavaLangReflectArtMethod)); 1392 } else { 1393 klass.reset(AllocClass(self, SizeOfClass(dex_file, dex_class_def))); 1394 } 1395 } else { 1396 klass.reset(AllocClass(self, SizeOfClass(dex_file, dex_class_def))); 1397 } 1398 if (UNLIKELY(klass.get() == NULL)) { 1399 CHECK(self->IsExceptionPending()); // Expect an OOME. 1400 return NULL; 1401 } 1402 klass->SetDexCache(FindDexCache(dex_file)); 1403 LoadClass(dex_file, dex_class_def, klass, class_loader); 1404 // Check for a pending exception during load 1405 if (self->IsExceptionPending()) { 1406 klass->SetStatus(mirror::Class::kStatusError, self); 1407 return NULL; 1408 } 1409 ObjectLock lock(self, klass.get()); 1410 klass->SetClinitThreadId(self->GetTid()); 1411 { 1412 // Add the newly loaded class to the loaded classes table. 1413 mirror::Class* existing = InsertClass(descriptor, klass.get(), Hash(descriptor)); 1414 if (existing != NULL) { 1415 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause 1416 // this thread to block. 1417 return EnsureResolved(self, existing); 1418 } 1419 } 1420 // Finish loading (if necessary) by finding parents 1421 CHECK(!klass->IsLoaded()); 1422 if (!LoadSuperAndInterfaces(klass, dex_file)) { 1423 // Loading failed. 1424 klass->SetStatus(mirror::Class::kStatusError, self); 1425 return NULL; 1426 } 1427 CHECK(klass->IsLoaded()); 1428 // Link the class (if necessary) 1429 CHECK(!klass->IsResolved()); 1430 if (!LinkClass(klass, NULL, self)) { 1431 // Linking failed. 1432 klass->SetStatus(mirror::Class::kStatusError, self); 1433 return NULL; 1434 } 1435 CHECK(klass->IsResolved()); 1436 1437 /* 1438 * We send CLASS_PREPARE events to the debugger from here. The 1439 * definition of "preparation" is creating the static fields for a 1440 * class and initializing them to the standard default values, but not 1441 * executing any code (that comes later, during "initialization"). 1442 * 1443 * We did the static preparation in LinkClass. 1444 * 1445 * The class has been prepared and resolved but possibly not yet verified 1446 * at this point. 1447 */ 1448 Dbg::PostClassPrepare(klass.get()); 1449 1450 return klass.get(); 1451} 1452 1453// Precomputes size that will be needed for Class, matching LinkStaticFields 1454size_t ClassLinker::SizeOfClass(const DexFile& dex_file, 1455 const DexFile::ClassDef& dex_class_def) { 1456 const byte* class_data = dex_file.GetClassData(dex_class_def); 1457 size_t num_ref = 0; 1458 size_t num_32 = 0; 1459 size_t num_64 = 0; 1460 if (class_data != NULL) { 1461 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) { 1462 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex()); 1463 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id); 1464 char c = descriptor[0]; 1465 if (c == 'L' || c == '[') { 1466 num_ref++; 1467 } else if (c == 'J' || c == 'D') { 1468 num_64++; 1469 } else { 1470 num_32++; 1471 } 1472 } 1473 } 1474 // start with generic class data 1475 size_t size = sizeof(mirror::Class); 1476 // follow with reference fields which must be contiguous at start 1477 size += (num_ref * sizeof(uint32_t)); 1478 // if there are 64-bit fields to add, make sure they are aligned 1479 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment 1480 if (num_32 != 0) { 1481 // use an available 32-bit field for padding 1482 num_32--; 1483 } 1484 size += sizeof(uint32_t); // either way, we are adding a word 1485 DCHECK_EQ(size, RoundUp(size, 8)); 1486 } 1487 // tack on any 64-bit fields now that alignment is assured 1488 size += (num_64 * sizeof(uint64_t)); 1489 // tack on any remaining 32-bit fields 1490 size += (num_32 * sizeof(uint32_t)); 1491 return size; 1492} 1493 1494const OatFile::OatClass* ClassLinker::GetOatClass(const DexFile& dex_file, uint16_t class_def_idx) { 1495 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16); 1496 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file); 1497 CHECK(oat_file != NULL) << dex_file.GetLocation(); 1498 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation()); 1499 CHECK(oat_dex_file != NULL) << dex_file.GetLocation(); 1500 const OatFile::OatClass* oat_class = oat_dex_file->GetOatClass(class_def_idx); 1501 CHECK(oat_class != NULL) << dex_file.GetLocation() << " " << class_def_idx; 1502 return oat_class; 1503} 1504 1505static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx, 1506 uint32_t method_idx) { 1507 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx); 1508 const byte* class_data = dex_file.GetClassData(class_def); 1509 CHECK(class_data != NULL); 1510 ClassDataItemIterator it(dex_file, class_data); 1511 // Skip fields 1512 while (it.HasNextStaticField()) { 1513 it.Next(); 1514 } 1515 while (it.HasNextInstanceField()) { 1516 it.Next(); 1517 } 1518 // Process methods 1519 size_t class_def_method_index = 0; 1520 while (it.HasNextDirectMethod()) { 1521 if (it.GetMemberIndex() == method_idx) { 1522 return class_def_method_index; 1523 } 1524 class_def_method_index++; 1525 it.Next(); 1526 } 1527 while (it.HasNextVirtualMethod()) { 1528 if (it.GetMemberIndex() == method_idx) { 1529 return class_def_method_index; 1530 } 1531 class_def_method_index++; 1532 it.Next(); 1533 } 1534 DCHECK(!it.HasNext()); 1535 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation(); 1536 return 0; 1537} 1538 1539const OatFile::OatMethod ClassLinker::GetOatMethodFor(const mirror::ArtMethod* method) { 1540 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution 1541 // method for direct methods (or virtual methods made direct). 1542 mirror::Class* declaring_class = method->GetDeclaringClass(); 1543 size_t oat_method_index; 1544 if (method->IsStatic() || method->IsDirect()) { 1545 // Simple case where the oat method index was stashed at load time. 1546 oat_method_index = method->GetMethodIndex(); 1547 } else { 1548 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index 1549 // by search for its position in the declared virtual methods. 1550 oat_method_index = declaring_class->NumDirectMethods(); 1551 size_t end = declaring_class->NumVirtualMethods(); 1552 bool found = false; 1553 for (size_t i = 0; i < end; i++) { 1554 if (declaring_class->GetVirtualMethod(i) == method) { 1555 found = true; 1556 break; 1557 } 1558 oat_method_index++; 1559 } 1560 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method); 1561 } 1562 UniquePtr<const OatFile::OatClass> 1563 oat_class(GetOatClass(*declaring_class->GetDexCache()->GetDexFile(), 1564 declaring_class->GetDexClassDefIndex())); 1565 CHECK(oat_class.get() != NULL); 1566 DCHECK_EQ(oat_method_index, 1567 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(), 1568 method->GetDeclaringClass()->GetDexClassDefIndex(), 1569 method->GetDexMethodIndex())); 1570 1571 return oat_class->GetOatMethod(oat_method_index); 1572} 1573 1574// Special case to get oat code without overwriting a trampoline. 1575const void* ClassLinker::GetOatCodeFor(const mirror::ArtMethod* method) { 1576 CHECK(!method->IsAbstract()) << PrettyMethod(method); 1577 if (method->IsProxyMethod()) { 1578#if !defined(ART_USE_PORTABLE_COMPILER) 1579 return reinterpret_cast<void*>(art_quick_proxy_invoke_handler); 1580#else 1581 return reinterpret_cast<void*>(art_portable_proxy_invoke_handler); 1582#endif 1583 } 1584 const void* result = GetOatMethodFor(method).GetCode(); 1585 if (result == NULL) { 1586 // No code? You must mean to go into the interpreter. 1587 result = GetCompiledCodeToInterpreterBridge(); 1588 } 1589 return result; 1590} 1591 1592const void* ClassLinker::GetOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx, 1593 uint32_t method_idx) { 1594 UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(dex_file, class_def_idx)); 1595 CHECK(oat_class.get() != nullptr); 1596 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx); 1597 return oat_class->GetOatMethod(oat_method_idx).GetCode(); 1598} 1599 1600// Returns true if the method must run with interpreter, false otherwise. 1601static bool NeedsInterpreter(const mirror::ArtMethod* method, const void* code) { 1602 if (code == NULL) { 1603 // No code: need interpreter. 1604 return true; 1605 } 1606#ifdef ART_SEA_IR_MODE 1607 ScopedObjectAccess soa(Thread::Current()); 1608 if (std::string::npos != PrettyMethod(method).find("fibonacci")) { 1609 LOG(INFO) << "Found " << PrettyMethod(method); 1610 return false; 1611 } 1612#endif 1613 // If interpreter mode is enabled, every method (except native and proxy) must 1614 // be run with interpreter. 1615 return Runtime::Current()->GetInstrumentation()->InterpretOnly() && 1616 !method->IsNative() && !method->IsProxyMethod(); 1617} 1618 1619void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) { 1620 ClassHelper kh(klass); 1621 const DexFile::ClassDef* dex_class_def = kh.GetClassDef(); 1622 CHECK(dex_class_def != NULL); 1623 const DexFile& dex_file = kh.GetDexFile(); 1624 const byte* class_data = dex_file.GetClassData(*dex_class_def); 1625 if (class_data == NULL) { 1626 return; // no fields or methods - for example a marker interface 1627 } 1628 Runtime* runtime = Runtime::Current(); 1629 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) { 1630 // OAT file unavailable 1631 return; 1632 } 1633 UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(dex_file, klass->GetDexClassDefIndex())); 1634 CHECK(oat_class.get() != NULL); 1635 ClassDataItemIterator it(dex_file, class_data); 1636 // Skip fields 1637 while (it.HasNextStaticField()) { 1638 it.Next(); 1639 } 1640 while (it.HasNextInstanceField()) { 1641 it.Next(); 1642 } 1643 // Link the code of methods skipped by LinkCode 1644 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) { 1645 mirror::ArtMethod* method = klass->GetDirectMethod(method_index); 1646 if (!method->IsStatic()) { 1647 // Only update static methods. 1648 continue; 1649 } 1650 const void* code = oat_class->GetOatMethod(method_index).GetCode(); 1651 const bool enter_interpreter = NeedsInterpreter(method, code); 1652 if (enter_interpreter) { 1653 // Use interpreter entry point. 1654 code = GetCompiledCodeToInterpreterBridge(); 1655 } 1656 runtime->GetInstrumentation()->UpdateMethodsCode(method, code); 1657 } 1658 // Ignore virtual methods on the iterator. 1659} 1660 1661static void LinkCode(SirtRef<mirror::ArtMethod>& method, const OatFile::OatClass* oat_class, 1662 uint32_t method_index) 1663 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1664 // Method shouldn't have already been linked. 1665 DCHECK(method->GetEntryPointFromCompiledCode() == NULL); 1666 // Every kind of method should at least get an invoke stub from the oat_method. 1667 // non-abstract methods also get their code pointers. 1668 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index); 1669 oat_method.LinkMethod(method.get()); 1670 1671 // Install entry point from interpreter. 1672 Runtime* runtime = Runtime::Current(); 1673 bool enter_interpreter = NeedsInterpreter(method.get(), method->GetEntryPointFromCompiledCode()); 1674 if (enter_interpreter) { 1675 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge); 1676 } else { 1677 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge); 1678 } 1679 1680 if (method->IsAbstract()) { 1681 method->SetEntryPointFromCompiledCode(GetCompiledCodeToInterpreterBridge()); 1682 return; 1683 } 1684 1685 if (method->IsStatic() && !method->IsConstructor()) { 1686 // For static methods excluding the class initializer, install the trampoline. 1687 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines 1688 // after initializing class (see ClassLinker::InitializeClass method). 1689 method->SetEntryPointFromCompiledCode(GetResolutionTrampoline(runtime->GetClassLinker())); 1690 } else if (enter_interpreter) { 1691 // Set entry point from compiled code if there's no code or in interpreter only mode. 1692 method->SetEntryPointFromCompiledCode(GetCompiledCodeToInterpreterBridge()); 1693 } 1694 1695 if (method->IsNative()) { 1696 // Unregistering restores the dlsym lookup stub. 1697 method->UnregisterNative(Thread::Current()); 1698 } 1699 1700 // Allow instrumentation its chance to hijack code. 1701 runtime->GetInstrumentation()->UpdateMethodsCode(method.get(), 1702 method->GetEntryPointFromCompiledCode()); 1703} 1704 1705void ClassLinker::LoadClass(const DexFile& dex_file, 1706 const DexFile::ClassDef& dex_class_def, 1707 SirtRef<mirror::Class>& klass, 1708 mirror::ClassLoader* class_loader) { 1709 CHECK(klass.get() != NULL); 1710 CHECK(klass->GetDexCache() != NULL); 1711 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus()); 1712 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def); 1713 CHECK(descriptor != NULL); 1714 1715 klass->SetClass(GetClassRoot(kJavaLangClass)); 1716 uint32_t access_flags = dex_class_def.access_flags_; 1717 // Make sure that none of our runtime-only flags are set. 1718 // TODO: JACK CLASS ACCESS (HACK TO BE REMOVED) 1719 CHECK_EQ(access_flags & ~(kAccJavaFlagsMask | kAccClassJack), 0U); 1720 klass->SetAccessFlags(access_flags); 1721 klass->SetClassLoader(class_loader); 1722 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 1723 klass->SetStatus(mirror::Class::kStatusIdx, NULL); 1724 1725 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def)); 1726 klass->SetDexTypeIndex(dex_class_def.class_idx_); 1727 1728 // Load fields fields. 1729 const byte* class_data = dex_file.GetClassData(dex_class_def); 1730 if (class_data == NULL) { 1731 return; // no fields or methods - for example a marker interface 1732 } 1733 ClassDataItemIterator it(dex_file, class_data); 1734 Thread* self = Thread::Current(); 1735 if (it.NumStaticFields() != 0) { 1736 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields()); 1737 if (UNLIKELY(statics == NULL)) { 1738 CHECK(self->IsExceptionPending()); // OOME. 1739 return; 1740 } 1741 klass->SetSFields(statics); 1742 } 1743 if (it.NumInstanceFields() != 0) { 1744 mirror::ObjectArray<mirror::ArtField>* fields = 1745 AllocArtFieldArray(self, it.NumInstanceFields()); 1746 if (UNLIKELY(fields == NULL)) { 1747 CHECK(self->IsExceptionPending()); // OOME. 1748 return; 1749 } 1750 klass->SetIFields(fields); 1751 } 1752 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) { 1753 SirtRef<mirror::ArtField> sfield(self, AllocArtField(self)); 1754 if (UNLIKELY(sfield.get() == NULL)) { 1755 CHECK(self->IsExceptionPending()); // OOME. 1756 return; 1757 } 1758 klass->SetStaticField(i, sfield.get()); 1759 LoadField(dex_file, it, klass, sfield); 1760 } 1761 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) { 1762 SirtRef<mirror::ArtField> ifield(self, AllocArtField(self)); 1763 if (UNLIKELY(ifield.get() == NULL)) { 1764 CHECK(self->IsExceptionPending()); // OOME. 1765 return; 1766 } 1767 klass->SetInstanceField(i, ifield.get()); 1768 LoadField(dex_file, it, klass, ifield); 1769 } 1770 1771 UniquePtr<const OatFile::OatClass> oat_class; 1772 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) { 1773 oat_class.reset(GetOatClass(dex_file, klass->GetDexClassDefIndex())); 1774 } 1775 1776 // Load methods. 1777 if (it.NumDirectMethods() != 0) { 1778 // TODO: append direct methods to class object 1779 mirror::ObjectArray<mirror::ArtMethod>* directs = 1780 AllocArtMethodArray(self, it.NumDirectMethods()); 1781 if (UNLIKELY(directs == NULL)) { 1782 CHECK(self->IsExceptionPending()); // OOME. 1783 return; 1784 } 1785 klass->SetDirectMethods(directs); 1786 } 1787 if (it.NumVirtualMethods() != 0) { 1788 // TODO: append direct methods to class object 1789 mirror::ObjectArray<mirror::ArtMethod>* virtuals = 1790 AllocArtMethodArray(self, it.NumVirtualMethods()); 1791 if (UNLIKELY(virtuals == NULL)) { 1792 CHECK(self->IsExceptionPending()); // OOME. 1793 return; 1794 } 1795 klass->SetVirtualMethods(virtuals); 1796 } 1797 size_t class_def_method_index = 0; 1798 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) { 1799 SirtRef<mirror::ArtMethod> method(self, LoadMethod(self, dex_file, it, klass)); 1800 if (UNLIKELY(method.get() == NULL)) { 1801 CHECK(self->IsExceptionPending()); // OOME. 1802 return; 1803 } 1804 klass->SetDirectMethod(i, method.get()); 1805 if (oat_class.get() != NULL) { 1806 LinkCode(method, oat_class.get(), class_def_method_index); 1807 } 1808 method->SetMethodIndex(class_def_method_index); 1809 class_def_method_index++; 1810 } 1811 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) { 1812 SirtRef<mirror::ArtMethod> method(self, LoadMethod(self, dex_file, it, klass)); 1813 if (UNLIKELY(method.get() == NULL)) { 1814 CHECK(self->IsExceptionPending()); // OOME. 1815 return; 1816 } 1817 klass->SetVirtualMethod(i, method.get()); 1818 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i); 1819 if (oat_class.get() != NULL) { 1820 LinkCode(method, oat_class.get(), class_def_method_index); 1821 } 1822 class_def_method_index++; 1823 } 1824 DCHECK(!it.HasNext()); 1825} 1826 1827void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it, 1828 SirtRef<mirror::Class>& klass, SirtRef<mirror::ArtField>& dst) { 1829 uint32_t field_idx = it.GetMemberIndex(); 1830 dst->SetDexFieldIndex(field_idx); 1831 dst->SetDeclaringClass(klass.get()); 1832 dst->SetAccessFlags(it.GetMemberAccessFlags()); 1833} 1834 1835mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file, 1836 const ClassDataItemIterator& it, 1837 SirtRef<mirror::Class>& klass) { 1838 uint32_t dex_method_idx = it.GetMemberIndex(); 1839 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx); 1840 StringPiece method_name(dex_file.GetMethodName(method_id)); 1841 1842 mirror::ArtMethod* dst = AllocArtMethod(self); 1843 if (UNLIKELY(dst == NULL)) { 1844 CHECK(self->IsExceptionPending()); // OOME. 1845 return NULL; 1846 } 1847 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass()); 1848 1849 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod"); 1850 dst->SetDexMethodIndex(dex_method_idx); 1851 dst->SetDeclaringClass(klass.get()); 1852 1853 if (method_name == "finalize") { 1854 // Create the prototype for a signature of "()V" 1855 const DexFile::StringId* void_string_id = dex_file.FindStringId("V"); 1856 if (void_string_id != NULL) { 1857 const DexFile::TypeId* void_type_id = 1858 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id)); 1859 if (void_type_id != NULL) { 1860 std::vector<uint16_t> no_args; 1861 const DexFile::ProtoId* finalizer_proto = 1862 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args); 1863 if (finalizer_proto != NULL) { 1864 // We have the prototype in the dex file 1865 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged 1866 klass->SetFinalizable(); 1867 } else { 1868 ClassHelper kh(klass.get()); 1869 StringPiece klass_descriptor(kh.GetDescriptor()); 1870 // The Enum class declares a "final" finalize() method to prevent subclasses from 1871 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its 1872 // subclasses, so we exclude it here. 1873 // We also want to avoid setting the flag on Object, where we know that finalize() is 1874 // empty. 1875 if (klass_descriptor != "Ljava/lang/Object;" && 1876 klass_descriptor != "Ljava/lang/Enum;") { 1877 klass->SetFinalizable(); 1878 } 1879 } 1880 } 1881 } 1882 } 1883 } 1884 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset()); 1885 dst->SetAccessFlags(it.GetMemberAccessFlags()); 1886 1887 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings()); 1888 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods()); 1889 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes()); 1890 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage()); 1891 1892 CHECK(dst->IsArtMethod()); 1893 1894 self->EndAssertNoThreadSuspension(old_cause); 1895 return dst; 1896} 1897 1898void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) { 1899 Thread* self = Thread::Current(); 1900 SirtRef<mirror::DexCache> dex_cache(self, AllocDexCache(self, dex_file)); 1901 CHECK(dex_cache.get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation(); 1902 AppendToBootClassPath(dex_file, dex_cache); 1903} 1904 1905void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<mirror::DexCache>& dex_cache) { 1906 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation(); 1907 boot_class_path_.push_back(&dex_file); 1908 RegisterDexFile(dex_file, dex_cache); 1909} 1910 1911bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const { 1912 dex_lock_.AssertSharedHeld(Thread::Current()); 1913 for (size_t i = 0; i != dex_caches_.size(); ++i) { 1914 if (dex_caches_[i]->GetDexFile() == &dex_file) { 1915 return true; 1916 } 1917 } 1918 return false; 1919} 1920 1921bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const { 1922 ReaderMutexLock mu(Thread::Current(), dex_lock_); 1923 return IsDexFileRegisteredLocked(dex_file); 1924} 1925 1926void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<mirror::DexCache>& dex_cache) { 1927 dex_lock_.AssertExclusiveHeld(Thread::Current()); 1928 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation(); 1929 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation())); 1930 dex_caches_.push_back(dex_cache.get()); 1931 dex_cache->SetDexFile(&dex_file); 1932 dex_caches_dirty_ = true; 1933} 1934 1935void ClassLinker::RegisterDexFile(const DexFile& dex_file) { 1936 Thread* self = Thread::Current(); 1937 { 1938 ReaderMutexLock mu(self, dex_lock_); 1939 if (IsDexFileRegisteredLocked(dex_file)) { 1940 return; 1941 } 1942 } 1943 // Don't alloc while holding the lock, since allocation may need to 1944 // suspend all threads and another thread may need the dex_lock_ to 1945 // get to a suspend point. 1946 SirtRef<mirror::DexCache> dex_cache(self, AllocDexCache(self, dex_file)); 1947 CHECK(dex_cache.get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation(); 1948 { 1949 WriterMutexLock mu(self, dex_lock_); 1950 if (IsDexFileRegisteredLocked(dex_file)) { 1951 return; 1952 } 1953 RegisterDexFileLocked(dex_file, dex_cache); 1954 } 1955} 1956 1957void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<mirror::DexCache>& dex_cache) { 1958 WriterMutexLock mu(Thread::Current(), dex_lock_); 1959 RegisterDexFileLocked(dex_file, dex_cache); 1960} 1961 1962mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const { 1963 ReaderMutexLock mu(Thread::Current(), dex_lock_); 1964 // Search assuming unique-ness of dex file. 1965 for (size_t i = 0; i != dex_caches_.size(); ++i) { 1966 mirror::DexCache* dex_cache = dex_caches_[i]; 1967 if (dex_cache->GetDexFile() == &dex_file) { 1968 return dex_cache; 1969 } 1970 } 1971 // Search matching by location name. 1972 std::string location(dex_file.GetLocation()); 1973 for (size_t i = 0; i != dex_caches_.size(); ++i) { 1974 mirror::DexCache* dex_cache = dex_caches_[i]; 1975 if (dex_cache->GetDexFile()->GetLocation() == location) { 1976 return dex_cache; 1977 } 1978 } 1979 // Failure, dump diagnostic and abort. 1980 for (size_t i = 0; i != dex_caches_.size(); ++i) { 1981 mirror::DexCache* dex_cache = dex_caches_[i]; 1982 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation(); 1983 } 1984 LOG(FATAL) << "Failed to find DexCache for DexFile " << location; 1985 return NULL; 1986} 1987 1988void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) const { 1989 ReaderMutexLock mu(Thread::Current(), dex_lock_); 1990 for (size_t i = 0; i != dex_caches_.size(); ++i) { 1991 dex_caches_[i]->Fixup(resolution_method); 1992 } 1993} 1994 1995mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) { 1996 mirror::Class* klass = AllocClass(self, sizeof(mirror::Class)); 1997 if (UNLIKELY(klass == NULL)) { 1998 return NULL; 1999 } 2000 return InitializePrimitiveClass(klass, type); 2001} 2002 2003mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class, Primitive::Type type) { 2004 CHECK(primitive_class != NULL); 2005 // Must hold lock on object when initializing. 2006 Thread* self = Thread::Current(); 2007 ObjectLock lock(self, primitive_class); 2008 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract); 2009 primitive_class->SetPrimitiveType(type); 2010 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self); 2011 const char* descriptor = Primitive::Descriptor(type); 2012 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor)); 2013 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed"; 2014 return primitive_class; 2015} 2016 2017// Create an array class (i.e. the class object for the array, not the 2018// array itself). "descriptor" looks like "[C" or "[[[[B" or 2019// "[Ljava/lang/String;". 2020// 2021// If "descriptor" refers to an array of primitives, look up the 2022// primitive type's internally-generated class object. 2023// 2024// "class_loader" is the class loader of the class that's referring to 2025// us. It's used to ensure that we're looking for the element type in 2026// the right context. It does NOT become the class loader for the 2027// array class; that always comes from the base element class. 2028// 2029// Returns NULL with an exception raised on failure. 2030mirror::Class* ClassLinker::CreateArrayClass(const char* descriptor, 2031 mirror::ClassLoader* class_loader) { 2032 // Identify the underlying component type 2033 CHECK_EQ('[', descriptor[0]); 2034 mirror::Class* component_type = FindClass(descriptor + 1, class_loader); 2035 if (component_type == NULL) { 2036 DCHECK(Thread::Current()->IsExceptionPending()); 2037 return NULL; 2038 } 2039 2040 // See if the component type is already loaded. Array classes are 2041 // always associated with the class loader of their underlying 2042 // element type -- an array of Strings goes with the loader for 2043 // java/lang/String -- so we need to look for it there. (The 2044 // caller should have checked for the existence of the class 2045 // before calling here, but they did so with *their* class loader, 2046 // not the component type's loader.) 2047 // 2048 // If we find it, the caller adds "loader" to the class' initiating 2049 // loader list, which should prevent us from going through this again. 2050 // 2051 // This call is unnecessary if "loader" and "component_type->GetClassLoader()" 2052 // are the same, because our caller (FindClass) just did the 2053 // lookup. (Even if we get this wrong we still have correct behavior, 2054 // because we effectively do this lookup again when we add the new 2055 // class to the hash table --- necessary because of possible races with 2056 // other threads.) 2057 if (class_loader != component_type->GetClassLoader()) { 2058 mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader()); 2059 if (new_class != NULL) { 2060 return new_class; 2061 } 2062 } 2063 2064 // Fill out the fields in the Class. 2065 // 2066 // It is possible to execute some methods against arrays, because 2067 // all arrays are subclasses of java_lang_Object_, so we need to set 2068 // up a vtable. We can just point at the one in java_lang_Object_. 2069 // 2070 // Array classes are simple enough that we don't need to do a full 2071 // link step. 2072 Thread* self = Thread::Current(); 2073 SirtRef<mirror::Class> new_class(self, NULL); 2074 if (UNLIKELY(!init_done_)) { 2075 // Classes that were hand created, ie not by FindSystemClass 2076 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) { 2077 new_class.reset(GetClassRoot(kClassArrayClass)); 2078 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) { 2079 new_class.reset(GetClassRoot(kObjectArrayClass)); 2080 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) { 2081 new_class.reset(GetClassRoot(kJavaLangStringArrayClass)); 2082 } else if (strcmp(descriptor, 2083 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) { 2084 new_class.reset(GetClassRoot(kJavaLangReflectArtMethodArrayClass)); 2085 } else if (strcmp(descriptor, 2086 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) { 2087 new_class.reset(GetClassRoot(kJavaLangReflectArtFieldArrayClass)); 2088 } else if (strcmp(descriptor, "[C") == 0) { 2089 new_class.reset(GetClassRoot(kCharArrayClass)); 2090 } else if (strcmp(descriptor, "[I") == 0) { 2091 new_class.reset(GetClassRoot(kIntArrayClass)); 2092 } 2093 } 2094 if (new_class.get() == NULL) { 2095 new_class.reset(AllocClass(self, sizeof(mirror::Class))); 2096 if (new_class.get() == NULL) { 2097 return NULL; 2098 } 2099 new_class->SetComponentType(component_type); 2100 } 2101 ObjectLock lock(self, new_class.get()); // Must hold lock on object when initializing. 2102 DCHECK(new_class->GetComponentType() != NULL); 2103 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject); 2104 new_class->SetSuperClass(java_lang_Object); 2105 new_class->SetVTable(java_lang_Object->GetVTable()); 2106 new_class->SetPrimitiveType(Primitive::kPrimNot); 2107 new_class->SetClassLoader(component_type->GetClassLoader()); 2108 new_class->SetStatus(mirror::Class::kStatusInitialized, self); 2109 // don't need to set new_class->SetObjectSize(..) 2110 // because Object::SizeOf delegates to Array::SizeOf 2111 2112 2113 // All arrays have java/lang/Cloneable and java/io/Serializable as 2114 // interfaces. We need to set that up here, so that stuff like 2115 // "instanceof" works right. 2116 // 2117 // Note: The GC could run during the call to FindSystemClass, 2118 // so we need to make sure the class object is GC-valid while we're in 2119 // there. Do this by clearing the interface list so the GC will just 2120 // think that the entries are null. 2121 2122 2123 // Use the single, global copies of "interfaces" and "iftable" 2124 // (remember not to free them for arrays). 2125 CHECK(array_iftable_ != NULL); 2126 new_class->SetIfTable(array_iftable_); 2127 2128 // Inherit access flags from the component type. 2129 int access_flags = new_class->GetComponentType()->GetAccessFlags(); 2130 // Lose any implementation detail flags; in particular, arrays aren't finalizable. 2131 access_flags &= kAccJavaFlagsMask; 2132 // Arrays can't be used as a superclass or interface, so we want to add "abstract final" 2133 // and remove "interface". 2134 access_flags |= kAccAbstract | kAccFinal; 2135 access_flags &= ~kAccInterface; 2136 2137 new_class->SetAccessFlags(access_flags); 2138 2139 mirror::Class* existing = InsertClass(descriptor, new_class.get(), Hash(descriptor)); 2140 if (existing == NULL) { 2141 return new_class.get(); 2142 } 2143 // Another thread must have loaded the class after we 2144 // started but before we finished. Abandon what we've 2145 // done. 2146 // 2147 // (Yes, this happens.) 2148 2149 return existing; 2150} 2151 2152mirror::Class* ClassLinker::FindPrimitiveClass(char type) { 2153 switch (Primitive::GetType(type)) { 2154 case Primitive::kPrimByte: 2155 return GetClassRoot(kPrimitiveByte); 2156 case Primitive::kPrimChar: 2157 return GetClassRoot(kPrimitiveChar); 2158 case Primitive::kPrimDouble: 2159 return GetClassRoot(kPrimitiveDouble); 2160 case Primitive::kPrimFloat: 2161 return GetClassRoot(kPrimitiveFloat); 2162 case Primitive::kPrimInt: 2163 return GetClassRoot(kPrimitiveInt); 2164 case Primitive::kPrimLong: 2165 return GetClassRoot(kPrimitiveLong); 2166 case Primitive::kPrimShort: 2167 return GetClassRoot(kPrimitiveShort); 2168 case Primitive::kPrimBoolean: 2169 return GetClassRoot(kPrimitiveBoolean); 2170 case Primitive::kPrimVoid: 2171 return GetClassRoot(kPrimitiveVoid); 2172 case Primitive::kPrimNot: 2173 break; 2174 } 2175 std::string printable_type(PrintableChar(type)); 2176 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str()); 2177 return NULL; 2178} 2179 2180mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, 2181 size_t hash) { 2182 if (VLOG_IS_ON(class_linker)) { 2183 mirror::DexCache* dex_cache = klass->GetDexCache(); 2184 std::string source; 2185 if (dex_cache != NULL) { 2186 source += " from "; 2187 source += dex_cache->GetLocation()->ToModifiedUtf8(); 2188 } 2189 LOG(INFO) << "Loaded class " << descriptor << source; 2190 } 2191 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2192 mirror::Class* existing = 2193 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash); 2194 if (existing != NULL) { 2195 return existing; 2196 } 2197 if (kIsDebugBuild && klass->GetClassLoader() == NULL && dex_cache_image_class_lookup_required_) { 2198 // Check a class loaded with the system class loader matches one in the image if the class 2199 // is in the image. 2200 existing = LookupClassFromImage(descriptor); 2201 if (existing != NULL) { 2202 CHECK(klass == existing); 2203 } 2204 } 2205 Runtime::Current()->GetHeap()->VerifyObject(klass); 2206 class_table_.insert(std::make_pair(hash, klass)); 2207 class_table_dirty_ = true; 2208 return NULL; 2209} 2210 2211bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) { 2212 size_t hash = Hash(descriptor); 2213 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2214 ClassHelper kh; 2215 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash; 2216 ++it) { 2217 mirror::Class* klass = it->second; 2218 kh.ChangeClass(klass); 2219 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) { 2220 class_table_.erase(it); 2221 return true; 2222 } 2223 } 2224 return false; 2225} 2226 2227mirror::Class* ClassLinker::LookupClass(const char* descriptor, 2228 const mirror::ClassLoader* class_loader) { 2229 size_t hash = Hash(descriptor); 2230 { 2231 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2232 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash); 2233 if (result != NULL) { 2234 return result; 2235 } 2236 } 2237 if (class_loader != NULL || !dex_cache_image_class_lookup_required_) { 2238 return NULL; 2239 } else { 2240 // Lookup failed but need to search dex_caches_. 2241 mirror::Class* result = LookupClassFromImage(descriptor); 2242 if (result != NULL) { 2243 InsertClass(descriptor, result, hash); 2244 } else { 2245 // Searching the image dex files/caches failed, we don't want to get into this situation 2246 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image 2247 // classes into the class table. 2248 const int32_t kMaxFailedDexCacheLookups = 1000; 2249 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) { 2250 MoveImageClassesToClassTable(); 2251 } 2252 } 2253 return result; 2254 } 2255} 2256 2257mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor, 2258 const mirror::ClassLoader* class_loader, 2259 size_t hash) { 2260 ClassHelper kh(NULL, this); 2261 auto end = class_table_.end(); 2262 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) { 2263 mirror::Class* klass = it->second; 2264 kh.ChangeClass(klass); 2265 if (klass->GetClassLoader() == class_loader && strcmp(descriptor, kh.GetDescriptor()) == 0) { 2266 if (kIsDebugBuild) { 2267 // Check for duplicates in the table. 2268 for (++it; it != end && it->first == hash; ++it) { 2269 mirror::Class* klass2 = it->second; 2270 kh.ChangeClass(klass2); 2271 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass2->GetClassLoader() == class_loader)) 2272 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " " 2273 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader(); 2274 } 2275 } 2276 return klass; 2277 } 2278 } 2279 return NULL; 2280} 2281 2282static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches() 2283 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2284 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace(); 2285 CHECK(image != NULL); 2286 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 2287 return root->AsObjectArray<mirror::DexCache>(); 2288} 2289 2290void ClassLinker::MoveImageClassesToClassTable() { 2291 Thread* self = Thread::Current(); 2292 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 2293 if (!dex_cache_image_class_lookup_required_) { 2294 return; // All dex cache classes are already in the class table. 2295 } 2296 const char* old_no_suspend_cause = 2297 self->StartAssertNoThreadSuspension("Moving image classes to class table"); 2298 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 2299 ClassHelper kh(NULL, this); 2300 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 2301 mirror::DexCache* dex_cache = dex_caches->Get(i); 2302 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes(); 2303 for (int32_t j = 0; j < types->GetLength(); j++) { 2304 mirror::Class* klass = types->Get(j); 2305 if (klass != NULL) { 2306 kh.ChangeClass(klass); 2307 DCHECK(klass->GetClassLoader() == NULL); 2308 const char* descriptor = kh.GetDescriptor(); 2309 size_t hash = Hash(descriptor); 2310 mirror::Class* existing = LookupClassFromTableLocked(descriptor, NULL, hash); 2311 if (existing != NULL) { 2312 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != " 2313 << PrettyClassAndClassLoader(klass); 2314 } else { 2315 class_table_.insert(std::make_pair(hash, klass)); 2316 } 2317 } 2318 } 2319 } 2320 class_table_dirty_ = true; 2321 dex_cache_image_class_lookup_required_ = false; 2322 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 2323} 2324 2325mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) { 2326 Thread* self = Thread::Current(); 2327 const char* old_no_suspend_cause = 2328 self->StartAssertNoThreadSuspension("Image class lookup"); 2329 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 2330 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) { 2331 mirror::DexCache* dex_cache = dex_caches->Get(i); 2332 const DexFile* dex_file = dex_cache->GetDexFile(); 2333 // First search using the class def map, but don't bother for non-class types. 2334 if (descriptor[0] == 'L') { 2335 const DexFile::StringId* descriptor_string_id = dex_file->FindStringId(descriptor); 2336 if (descriptor_string_id != NULL) { 2337 const DexFile::TypeId* type_id = 2338 dex_file->FindTypeId(dex_file->GetIndexForStringId(*descriptor_string_id)); 2339 if (type_id != NULL) { 2340 mirror::Class* klass = dex_cache->GetResolvedType(dex_file->GetIndexForTypeId(*type_id)); 2341 if (klass != NULL) { 2342 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 2343 return klass; 2344 } 2345 } 2346 } 2347 } 2348 // Now try binary searching the string/type index. 2349 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor); 2350 if (string_id != NULL) { 2351 const DexFile::TypeId* type_id = 2352 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id)); 2353 if (type_id != NULL) { 2354 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id); 2355 mirror::Class* klass = dex_cache->GetResolvedType(type_idx); 2356 if (klass != NULL) { 2357 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 2358 return klass; 2359 } 2360 } 2361 } 2362 } 2363 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 2364 return NULL; 2365} 2366 2367void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) { 2368 result.clear(); 2369 if (dex_cache_image_class_lookup_required_) { 2370 MoveImageClassesToClassTable(); 2371 } 2372 size_t hash = Hash(descriptor); 2373 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2374 ClassHelper kh(NULL, this); 2375 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); 2376 it != end && it->first == hash; ++it) { 2377 mirror::Class* klass = it->second; 2378 kh.ChangeClass(klass); 2379 if (strcmp(descriptor, kh.GetDescriptor()) == 0) { 2380 result.push_back(klass); 2381 } 2382 } 2383} 2384 2385void ClassLinker::VerifyClass(mirror::Class* klass) { 2386 // TODO: assert that the monitor on the Class is held 2387 Thread* self = Thread::Current(); 2388 ObjectLock lock(self, klass); 2389 2390 // Don't attempt to re-verify if already sufficiently verified. 2391 if (klass->IsVerified() || 2392 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) { 2393 return; 2394 } 2395 2396 // The class might already be erroneous, for example at compile time if we attempted to verify 2397 // this class as a parent to another. 2398 if (klass->IsErroneous()) { 2399 ThrowEarlierClassFailure(klass); 2400 return; 2401 } 2402 2403 if (klass->GetStatus() == mirror::Class::kStatusResolved) { 2404 klass->SetStatus(mirror::Class::kStatusVerifying, self); 2405 } else { 2406 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime) 2407 << PrettyClass(klass); 2408 CHECK(!Runtime::Current()->IsCompiler()); 2409 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self); 2410 } 2411 2412 // Verify super class. 2413 SirtRef<mirror::Class> super(self, klass->GetSuperClass()); 2414 if (super.get() != NULL) { 2415 // Acquire lock to prevent races on verifying the super class. 2416 ObjectLock lock(self, super.get()); 2417 2418 if (!super->IsVerified() && !super->IsErroneous()) { 2419 VerifyClass(super.get()); 2420 } 2421 if (!super->IsCompileTimeVerified()) { 2422 std::string error_msg(StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s", 2423 PrettyDescriptor(klass).c_str(), 2424 PrettyDescriptor(super.get()).c_str())); 2425 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 2426 SirtRef<mirror::Throwable> cause(self, self->GetException(NULL)); 2427 if (cause.get() != NULL) { 2428 self->ClearException(); 2429 } 2430 ThrowVerifyError(klass, "%s", error_msg.c_str()); 2431 if (cause.get() != NULL) { 2432 self->GetException(NULL)->SetCause(cause.get()); 2433 } 2434 klass->SetStatus(mirror::Class::kStatusError, self); 2435 return; 2436 } 2437 } 2438 2439 // Try to use verification information from the oat file, otherwise do runtime verification. 2440 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile(); 2441 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady); 2442 bool preverified = VerifyClassUsingOatFile(dex_file, klass, oat_file_class_status); 2443 if (oat_file_class_status == mirror::Class::kStatusError) { 2444 VLOG(class_linker) << "Skipping runtime verification of erroneous class " 2445 << PrettyDescriptor(klass) << " in " 2446 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 2447 ThrowVerifyError(klass, "Rejecting class %s because it failed compile-time verification", 2448 PrettyDescriptor(klass).c_str()); 2449 klass->SetStatus(mirror::Class::kStatusError, self); 2450 return; 2451 } 2452 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure; 2453 std::string error_msg; 2454 if (!preverified) { 2455 verifier_failure = verifier::MethodVerifier::VerifyClass(klass, 2456 Runtime::Current()->IsCompiler(), 2457 &error_msg); 2458 } 2459 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) { 2460 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) { 2461 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass) 2462 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 2463 << " because: " << error_msg; 2464 } 2465 self->AssertNoPendingException(); 2466 // Make sure all classes referenced by catch blocks are resolved. 2467 ResolveClassExceptionHandlerTypes(dex_file, klass); 2468 if (verifier_failure == verifier::MethodVerifier::kNoFailure) { 2469 // Even though there were no verifier failures we need to respect whether the super-class 2470 // was verified or requiring runtime reverification. 2471 if (super.get() == NULL || super->IsVerified()) { 2472 klass->SetStatus(mirror::Class::kStatusVerified, self); 2473 } else { 2474 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 2475 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self); 2476 // Pretend a soft failure occured so that we don't consider the class verified below. 2477 verifier_failure = verifier::MethodVerifier::kSoftFailure; 2478 } 2479 } else { 2480 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure); 2481 // Soft failures at compile time should be retried at runtime. Soft 2482 // failures at runtime will be handled by slow paths in the generated 2483 // code. Set status accordingly. 2484 if (Runtime::Current()->IsCompiler()) { 2485 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self); 2486 } else { 2487 klass->SetStatus(mirror::Class::kStatusVerified, self); 2488 } 2489 } 2490 } else { 2491 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass) 2492 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 2493 << " because: " << error_msg; 2494 self->AssertNoPendingException(); 2495 ThrowVerifyError(klass, "%s", error_msg.c_str()); 2496 klass->SetStatus(mirror::Class::kStatusError, self); 2497 } 2498 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) { 2499 // Class is verified so we don't need to do any access check on its methods. 2500 // Let the interpreter know it by setting the kAccPreverified flag onto each 2501 // method. 2502 // Note: we're going here during compilation and at runtime. When we set the 2503 // kAccPreverified flag when compiling image classes, the flag is recorded 2504 // in the image and is set when loading the image. 2505 klass->SetPreverifiedFlagOnAllMethods(); 2506 } 2507} 2508 2509bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass, 2510 mirror::Class::Status& oat_file_class_status) { 2511 // If we're compiling, we can only verify the class using the oat file if 2512 // we are not compiling the image or if the class we're verifying is not part of 2513 // the app. In other words, we will only check for preverification of bootclasspath 2514 // classes. 2515 if (Runtime::Current()->IsCompiler()) { 2516 // Are we compiling the bootclasspath? 2517 if (!Runtime::Current()->UseCompileTimeClassPath()) { 2518 return false; 2519 } 2520 // We are compiling an app (not the image). 2521 2522 // Is this an app class? (I.e. not a bootclasspath class) 2523 if (klass->GetClassLoader() != NULL) { 2524 return false; 2525 } 2526 } 2527 2528 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file); 2529 // Make this work with gtests, which do not set up the image properly. 2530 // TODO: we should clean up gtests to set up the image path properly. 2531 if (Runtime::Current()->IsCompiler() && (oat_file == NULL)) { 2532 return false; 2533 } 2534 2535 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass); 2536 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation()); 2537 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass); 2538 const char* descriptor = ClassHelper(klass).GetDescriptor(); 2539 uint16_t class_def_index = klass->GetDexClassDefIndex(); 2540 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index)); 2541 CHECK(oat_class.get() != NULL) 2542 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor; 2543 oat_file_class_status = oat_class->GetStatus(); 2544 if (oat_file_class_status == mirror::Class::kStatusVerified || 2545 oat_file_class_status == mirror::Class::kStatusInitialized) { 2546 return true; 2547 } 2548 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) { 2549 // Compile time verification failed with a soft error. Compile time verification can fail 2550 // because we have incomplete type information. Consider the following: 2551 // class ... { 2552 // Foo x; 2553 // .... () { 2554 // if (...) { 2555 // v1 gets assigned a type of resolved class Foo 2556 // } else { 2557 // v1 gets assigned a type of unresolved class Bar 2558 // } 2559 // iput x = v1 2560 // } } 2561 // when we merge v1 following the if-the-else it results in Conflict 2562 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be 2563 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as 2564 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk 2565 // at compile time). 2566 return false; 2567 } 2568 if (oat_file_class_status == mirror::Class::kStatusError) { 2569 // Compile time verification failed with a hard error. This is caused by invalid instructions 2570 // in the class. These errors are unrecoverable. 2571 return false; 2572 } 2573 if (oat_file_class_status == mirror::Class::kStatusNotReady) { 2574 // Status is uninitialized if we couldn't determine the status at compile time, for example, 2575 // not loading the class. 2576 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy 2577 // isn't a problem and this case shouldn't occur 2578 return false; 2579 } 2580 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status 2581 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor; 2582 2583 return false; 2584} 2585 2586void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, mirror::Class* klass) { 2587 for (size_t i = 0; i < klass->NumDirectMethods(); i++) { 2588 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i)); 2589 } 2590 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) { 2591 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i)); 2592 } 2593} 2594 2595void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, 2596 mirror::ArtMethod* method) { 2597 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod. 2598 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset()); 2599 if (code_item == NULL) { 2600 return; // native or abstract method 2601 } 2602 if (code_item->tries_size_ == 0) { 2603 return; // nothing to process 2604 } 2605 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0); 2606 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 2607 ClassLinker* linker = Runtime::Current()->GetClassLinker(); 2608 for (uint32_t idx = 0; idx < handlers_size; idx++) { 2609 CatchHandlerIterator iterator(handlers_ptr); 2610 for (; iterator.HasNext(); iterator.Next()) { 2611 // Ensure exception types are resolved so that they don't need resolution to be delivered, 2612 // unresolved exception types will be ignored by exception delivery 2613 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) { 2614 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method); 2615 if (exception_type == NULL) { 2616 DCHECK(Thread::Current()->IsExceptionPending()); 2617 Thread::Current()->ClearException(); 2618 } 2619 } 2620 } 2621 handlers_ptr = iterator.EndDataPointer(); 2622 } 2623} 2624 2625static void CheckProxyConstructor(mirror::ArtMethod* constructor); 2626static void CheckProxyMethod(mirror::ArtMethod* method, 2627 SirtRef<mirror::ArtMethod>& prototype); 2628 2629mirror::Class* ClassLinker::CreateProxyClass(mirror::String* name, 2630 mirror::ObjectArray<mirror::Class>* interfaces, 2631 mirror::ClassLoader* loader, 2632 mirror::ObjectArray<mirror::ArtMethod>* methods, 2633 mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >* throws) { 2634 Thread* self = Thread::Current(); 2635 SirtRef<mirror::Class> klass(self, AllocClass(self, GetClassRoot(kJavaLangClass), 2636 sizeof(mirror::SynthesizedProxyClass))); 2637 if (klass.get() == NULL) { 2638 CHECK(self->IsExceptionPending()); // OOME. 2639 return NULL; 2640 } 2641 DCHECK(klass->GetClass() != NULL); 2642 klass->SetObjectSize(sizeof(mirror::Proxy)); 2643 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal); 2644 klass->SetClassLoader(loader); 2645 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 2646 klass->SetName(name); 2647 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy); 2648 klass->SetDexCache(proxy_class->GetDexCache()); 2649 2650 klass->SetStatus(mirror::Class::kStatusIdx, self); 2651 2652 // Instance fields are inherited, but we add a couple of static fields... 2653 { 2654 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2); 2655 if (UNLIKELY(sfields == NULL)) { 2656 CHECK(self->IsExceptionPending()); // OOME. 2657 return NULL; 2658 } 2659 klass->SetSFields(sfields); 2660 } 2661 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by 2662 // our proxy, so Class.getInterfaces doesn't return the flattened set. 2663 SirtRef<mirror::ArtField> interfaces_sfield(self, AllocArtField(self)); 2664 if (UNLIKELY(interfaces_sfield.get() == NULL)) { 2665 CHECK(self->IsExceptionPending()); // OOME. 2666 return NULL; 2667 } 2668 klass->SetStaticField(0, interfaces_sfield.get()); 2669 interfaces_sfield->SetDexFieldIndex(0); 2670 interfaces_sfield->SetDeclaringClass(klass.get()); 2671 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 2672 // 2. Create a static field 'throws' that holds exceptions thrown by our methods. 2673 SirtRef<mirror::ArtField> throws_sfield(self, AllocArtField(self)); 2674 if (UNLIKELY(throws_sfield.get() == NULL)) { 2675 CHECK(self->IsExceptionPending()); // OOME. 2676 return NULL; 2677 } 2678 klass->SetStaticField(1, throws_sfield.get()); 2679 throws_sfield->SetDexFieldIndex(1); 2680 throws_sfield->SetDeclaringClass(klass.get()); 2681 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 2682 2683 // Proxies have 1 direct method, the constructor 2684 { 2685 mirror::ObjectArray<mirror::ArtMethod>* directs = 2686 AllocArtMethodArray(self, 1); 2687 if (UNLIKELY(directs == NULL)) { 2688 CHECK(self->IsExceptionPending()); // OOME. 2689 return NULL; 2690 } 2691 klass->SetDirectMethods(directs); 2692 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class); 2693 if (UNLIKELY(constructor == NULL)) { 2694 CHECK(self->IsExceptionPending()); // OOME. 2695 return NULL; 2696 } 2697 klass->SetDirectMethod(0, constructor); 2698 } 2699 2700 // Create virtual method using specified prototypes 2701 size_t num_virtual_methods = methods->GetLength(); 2702 { 2703 mirror::ObjectArray<mirror::ArtMethod>* virtuals = 2704 AllocArtMethodArray(self, num_virtual_methods); 2705 if (UNLIKELY(virtuals == NULL)) { 2706 CHECK(self->IsExceptionPending()); // OOME. 2707 return NULL; 2708 } 2709 klass->SetVirtualMethods(virtuals); 2710 } 2711 for (size_t i = 0; i < num_virtual_methods; ++i) { 2712 SirtRef<mirror::ArtMethod> prototype(self, methods->Get(i)); 2713 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype); 2714 if (UNLIKELY(clone == NULL)) { 2715 CHECK(self->IsExceptionPending()); // OOME. 2716 return NULL; 2717 } 2718 klass->SetVirtualMethod(i, clone); 2719 } 2720 2721 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy 2722 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Class is now effectively in the loaded state 2723 self->AssertNoPendingException(); 2724 2725 { 2726 ObjectLock lock(self, klass.get()); // Must hold lock on object when resolved. 2727 // Link the fields and virtual methods, creating vtable and iftables 2728 if (!LinkClass(klass, interfaces, self)) { 2729 klass->SetStatus(mirror::Class::kStatusError, self); 2730 return NULL; 2731 } 2732 2733 interfaces_sfield->SetObject(klass.get(), interfaces); 2734 throws_sfield->SetObject(klass.get(), throws); 2735 klass->SetStatus(mirror::Class::kStatusInitialized, self); 2736 } 2737 2738 // sanity checks 2739 if (kIsDebugBuild) { 2740 CHECK(klass->GetIFields() == NULL); 2741 CheckProxyConstructor(klass->GetDirectMethod(0)); 2742 for (size_t i = 0; i < num_virtual_methods; ++i) { 2743 SirtRef<mirror::ArtMethod> prototype(self, methods->Get(i)); 2744 CheckProxyMethod(klass->GetVirtualMethod(i), prototype); 2745 } 2746 2747 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces", 2748 name->ToModifiedUtf8().c_str())); 2749 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name); 2750 2751 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws", 2752 name->ToModifiedUtf8().c_str())); 2753 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name); 2754 2755 mirror::SynthesizedProxyClass* synth_proxy_class = 2756 down_cast<mirror::SynthesizedProxyClass*>(klass.get()); 2757 CHECK_EQ(synth_proxy_class->GetInterfaces(), interfaces); 2758 CHECK_EQ(synth_proxy_class->GetThrows(), throws); 2759 } 2760 return klass.get(); 2761} 2762 2763std::string ClassLinker::GetDescriptorForProxy(const mirror::Class* proxy_class) { 2764 DCHECK(proxy_class->IsProxyClass()); 2765 mirror::String* name = proxy_class->GetName(); 2766 DCHECK(name != NULL); 2767 return DotToDescriptor(name->ToModifiedUtf8().c_str()); 2768} 2769 2770mirror::ArtMethod* ClassLinker::FindMethodForProxy(const mirror::Class* proxy_class, 2771 const mirror::ArtMethod* proxy_method) { 2772 DCHECK(proxy_class->IsProxyClass()); 2773 DCHECK(proxy_method->IsProxyMethod()); 2774 // Locate the dex cache of the original interface/Object 2775 mirror::DexCache* dex_cache = NULL; 2776 { 2777 mirror::ObjectArray<mirror::Class>* resolved_types = proxy_method->GetDexCacheResolvedTypes(); 2778 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2779 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2780 if (dex_caches_[i]->GetResolvedTypes() == resolved_types) { 2781 dex_cache = dex_caches_[i]; 2782 break; 2783 } 2784 } 2785 } 2786 CHECK(dex_cache != NULL); 2787 uint32_t method_idx = proxy_method->GetDexMethodIndex(); 2788 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx); 2789 CHECK(resolved_method != NULL); 2790 return resolved_method; 2791} 2792 2793 2794mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self, 2795 SirtRef<mirror::Class>& klass, 2796 mirror::Class* proxy_class) { 2797 // Create constructor for Proxy that must initialize h 2798 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods = 2799 proxy_class->GetDirectMethods(); 2800 CHECK_EQ(proxy_direct_methods->GetLength(), 16); 2801 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2); 2802 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its 2803 // code_ too) 2804 mirror::ArtMethod* constructor = 2805 down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self)); 2806 if (constructor == NULL) { 2807 CHECK(self->IsExceptionPending()); // OOME. 2808 return NULL; 2809 } 2810 // Make this constructor public and fix the class to be our Proxy version 2811 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic); 2812 constructor->SetDeclaringClass(klass.get()); 2813 return constructor; 2814} 2815 2816static void CheckProxyConstructor(mirror::ArtMethod* constructor) 2817 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2818 CHECK(constructor->IsConstructor()); 2819 MethodHelper mh(constructor); 2820 CHECK_STREQ(mh.GetName(), "<init>"); 2821 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V")); 2822 DCHECK(constructor->IsPublic()); 2823} 2824 2825mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self, SirtRef<mirror::Class>& klass, 2826 SirtRef<mirror::ArtMethod>& prototype) { 2827 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden 2828 // prototype method 2829 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(), 2830 prototype.get()); 2831 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize 2832 // as necessary 2833 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self)); 2834 if (UNLIKELY(method == NULL)) { 2835 CHECK(self->IsExceptionPending()); // OOME. 2836 return NULL; 2837 } 2838 2839 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to 2840 // the intersection of throw exceptions as defined in Proxy 2841 method->SetDeclaringClass(klass.get()); 2842 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal); 2843 2844 // At runtime the method looks like a reference and argument saving method, clone the code 2845 // related parameters from this method. 2846 mirror::ArtMethod* refs_and_args = 2847 Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs); 2848 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask()); 2849 method->SetFpSpillMask(refs_and_args->GetFpSpillMask()); 2850 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes()); 2851 method->SetEntryPointFromCompiledCode(GetProxyInvokeHandler()); 2852 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge); 2853 2854 return method; 2855} 2856 2857static void CheckProxyMethod(mirror::ArtMethod* method, 2858 SirtRef<mirror::ArtMethod>& prototype) 2859 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2860 // Basic sanity 2861 CHECK(!prototype->IsFinal()); 2862 CHECK(method->IsFinal()); 2863 CHECK(!method->IsAbstract()); 2864 2865 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its 2866 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself. 2867 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings()); 2868 CHECK_EQ(prototype->GetDexCacheResolvedMethods(), method->GetDexCacheResolvedMethods()); 2869 CHECK_EQ(prototype->GetDexCacheResolvedTypes(), method->GetDexCacheResolvedTypes()); 2870 CHECK_EQ(prototype->GetDexCacheInitializedStaticStorage(), 2871 method->GetDexCacheInitializedStaticStorage()); 2872 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex()); 2873 2874 MethodHelper mh(method); 2875 MethodHelper mh2(prototype.get()); 2876 CHECK_STREQ(mh.GetName(), mh2.GetName()); 2877 CHECK_STREQ(mh.GetShorty(), mh2.GetShorty()); 2878 // More complex sanity - via dex cache 2879 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType()); 2880} 2881 2882static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics, 2883 bool can_init_parents) 2884 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2885 if (can_init_statics && can_init_statics) { 2886 return true; 2887 } 2888 if (!can_init_statics) { 2889 // Check if there's a class initializer. 2890 mirror::ArtMethod* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V"); 2891 if (clinit != NULL) { 2892 return false; 2893 } 2894 // Check if there are encoded static values needing initialization. 2895 if (klass->NumStaticFields() != 0) { 2896 ClassHelper kh(klass); 2897 const DexFile::ClassDef* dex_class_def = kh.GetClassDef(); 2898 DCHECK(dex_class_def != NULL); 2899 if (dex_class_def->static_values_off_ != 0) { 2900 return false; 2901 } 2902 } 2903 } 2904 if (!klass->IsInterface() && klass->HasSuperClass()) { 2905 mirror::Class* super_class = klass->GetSuperClass(); 2906 if (!can_init_parents && !super_class->IsInitialized()) { 2907 return false; 2908 } else { 2909 if (!CanWeInitializeClass(super_class, can_init_statics, true)) { 2910 return false; 2911 } 2912 } 2913 } 2914 return true; 2915} 2916 2917bool ClassLinker::InitializeClass(mirror::Class* klass, bool can_init_statics, 2918 bool can_init_parents) { 2919 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol 2920 2921 // Are we already initialized and therefore done? 2922 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as 2923 // an initialized class will never change its state. 2924 if (klass->IsInitialized()) { 2925 return true; 2926 } 2927 2928 // Fast fail if initialization requires a full runtime. Not part of the JLS. 2929 if (!CanWeInitializeClass(klass, can_init_statics, can_init_parents)) { 2930 return false; 2931 } 2932 2933 Thread* self = Thread::Current(); 2934 uint64_t t0; 2935 { 2936 ObjectLock lock(self, klass); 2937 2938 // Re-check under the lock in case another thread initialized ahead of us. 2939 if (klass->IsInitialized()) { 2940 return true; 2941 } 2942 2943 // Was the class already found to be erroneous? Done under the lock to match the JLS. 2944 if (klass->IsErroneous()) { 2945 ThrowEarlierClassFailure(klass); 2946 return false; 2947 } 2948 2949 CHECK(klass->IsResolved()) << PrettyClass(klass) << ": state=" << klass->GetStatus(); 2950 2951 if (!klass->IsVerified()) { 2952 VerifyClass(klass); 2953 if (!klass->IsVerified()) { 2954 // We failed to verify, expect either the klass to be erroneous or verification failed at 2955 // compile time. 2956 if (klass->IsErroneous()) { 2957 CHECK(self->IsExceptionPending()); 2958 } else { 2959 CHECK(Runtime::Current()->IsCompiler()); 2960 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 2961 } 2962 return false; 2963 } 2964 } 2965 2966 // If the class is kStatusInitializing, either this thread is 2967 // initializing higher up the stack or another thread has beat us 2968 // to initializing and we need to wait. Either way, this 2969 // invocation of InitializeClass will not be responsible for 2970 // running <clinit> and will return. 2971 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 2972 // We caught somebody else in the act; was it us? 2973 if (klass->GetClinitThreadId() == self->GetTid()) { 2974 // Yes. That's fine. Return so we can continue initializing. 2975 return true; 2976 } 2977 // No. That's fine. Wait for another thread to finish initializing. 2978 return WaitForInitializeClass(klass, self, lock); 2979 } 2980 2981 if (!ValidateSuperClassDescriptors(klass)) { 2982 klass->SetStatus(mirror::Class::kStatusError, self); 2983 return false; 2984 } 2985 2986 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass); 2987 2988 // From here out other threads may observe that we're initializing and so changes of state 2989 // require the a notification. 2990 klass->SetClinitThreadId(self->GetTid()); 2991 klass->SetStatus(mirror::Class::kStatusInitializing, self); 2992 2993 t0 = NanoTime(); 2994 } 2995 2996 // Initialize super classes, must be done while initializing for the JLS. 2997 if (!klass->IsInterface() && klass->HasSuperClass()) { 2998 mirror::Class* super_class = klass->GetSuperClass(); 2999 if (!super_class->IsInitialized()) { 3000 CHECK(!super_class->IsInterface()); 3001 CHECK(can_init_parents); 3002 bool super_initialized = InitializeClass(super_class, can_init_statics, true); 3003 if (!super_initialized) { 3004 // The super class was verified ahead of entering initializing, we should only be here if 3005 // the super class became erroneous due to initialization. 3006 CHECK(super_class->IsErroneous() && self->IsExceptionPending()) 3007 << "Super class initialization failed for " << PrettyDescriptor(super_class) 3008 << " that has unexpected status " << super_class->GetStatus() 3009 << "\nPending exception:\n" 3010 << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : ""); 3011 ObjectLock lock(self, klass); 3012 // Initialization failed because the super-class is erroneous. 3013 klass->SetStatus(mirror::Class::kStatusError, self); 3014 return false; 3015 } 3016 } 3017 } 3018 3019 if (klass->NumStaticFields() > 0) { 3020 ClassHelper kh(klass); 3021 const DexFile::ClassDef* dex_class_def = kh.GetClassDef(); 3022 CHECK(dex_class_def != NULL); 3023 const DexFile& dex_file = kh.GetDexFile(); 3024 EncodedStaticFieldValueIterator it(dex_file, kh.GetDexCache(), klass->GetClassLoader(), 3025 this, *dex_class_def); 3026 if (it.HasNext()) { 3027 CHECK(can_init_statics); 3028 // We reordered the fields, so we need to be able to map the field indexes to the right fields. 3029 SafeMap<uint32_t, mirror::ArtField*> field_map; 3030 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map); 3031 for (size_t i = 0; it.HasNext(); i++, it.Next()) { 3032 it.ReadValueToField(field_map.Get(i)); 3033 } 3034 } 3035 } 3036 3037 mirror::ArtMethod* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V"); 3038 if (clinit != NULL) { 3039 CHECK(can_init_statics); 3040 if (LIKELY(Runtime::Current()->IsStarted())) { 3041 JValue result; 3042 clinit->Invoke(self, NULL, 0, &result, 'V'); 3043 } else { 3044 art::interpreter::EnterInterpreterFromInvoke(self, clinit, NULL, NULL, NULL); 3045 } 3046 } 3047 3048 // Opportunistically set static method trampolines to their destination. 3049 FixupStaticTrampolines(klass); 3050 3051 uint64_t t1 = NanoTime(); 3052 3053 bool success = true; 3054 { 3055 ObjectLock lock(self, klass); 3056 3057 if (self->IsExceptionPending()) { 3058 WrapExceptionInInitializer(); 3059 klass->SetStatus(mirror::Class::kStatusError, self); 3060 success = false; 3061 } else { 3062 RuntimeStats* global_stats = Runtime::Current()->GetStats(); 3063 RuntimeStats* thread_stats = self->GetStats(); 3064 ++global_stats->class_init_count; 3065 ++thread_stats->class_init_count; 3066 global_stats->class_init_time_ns += (t1 - t0); 3067 thread_stats->class_init_time_ns += (t1 - t0); 3068 // Set the class as initialized except if failed to initialize static fields. 3069 klass->SetStatus(mirror::Class::kStatusInitialized, self); 3070 if (VLOG_IS_ON(class_linker)) { 3071 ClassHelper kh(klass); 3072 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation(); 3073 } 3074 } 3075 } 3076 return success; 3077} 3078 3079bool ClassLinker::WaitForInitializeClass(mirror::Class* klass, Thread* self, ObjectLock& lock) 3080 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3081 while (true) { 3082 self->AssertNoPendingException(); 3083 CHECK(!klass->IsInitialized()); 3084 lock.WaitIgnoringInterrupts(); 3085 3086 // When we wake up, repeat the test for init-in-progress. If 3087 // there's an exception pending (only possible if 3088 // "interruptShouldThrow" was set), bail out. 3089 if (self->IsExceptionPending()) { 3090 WrapExceptionInInitializer(); 3091 klass->SetStatus(mirror::Class::kStatusError, self); 3092 return false; 3093 } 3094 // Spurious wakeup? Go back to waiting. 3095 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 3096 continue; 3097 } 3098 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) { 3099 // Compile time initialization failed. 3100 return false; 3101 } 3102 if (klass->IsErroneous()) { 3103 // The caller wants an exception, but it was thrown in a 3104 // different thread. Synthesize one here. 3105 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread", 3106 PrettyDescriptor(klass).c_str()); 3107 return false; 3108 } 3109 if (klass->IsInitialized()) { 3110 return true; 3111 } 3112 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus(); 3113 } 3114 LOG(FATAL) << "Not Reached" << PrettyClass(klass); 3115} 3116 3117bool ClassLinker::ValidateSuperClassDescriptors(const mirror::Class* klass) { 3118 if (klass->IsInterface()) { 3119 return true; 3120 } 3121 // begin with the methods local to the superclass 3122 if (klass->HasSuperClass() && 3123 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) { 3124 const mirror::Class* super = klass->GetSuperClass(); 3125 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) { 3126 const mirror::ArtMethod* method = klass->GetVTable()->Get(i); 3127 if (method != super->GetVTable()->Get(i) && 3128 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) { 3129 ThrowLinkageError(klass, "Class %s method %s resolves differently in superclass %s", 3130 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(), 3131 PrettyDescriptor(super).c_str()); 3132 return false; 3133 } 3134 } 3135 } 3136 mirror::IfTable* iftable = klass->GetIfTable(); 3137 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 3138 mirror::Class* interface = iftable->GetInterface(i); 3139 if (klass->GetClassLoader() != interface->GetClassLoader()) { 3140 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) { 3141 const mirror::ArtMethod* method = iftable->GetMethodArray(i)->Get(j); 3142 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface, 3143 method->GetDeclaringClass())) { 3144 ThrowLinkageError(klass, "Class %s method %s resolves differently in interface %s", 3145 PrettyDescriptor(method->GetDeclaringClass()).c_str(), 3146 PrettyMethod(method).c_str(), 3147 PrettyDescriptor(interface).c_str()); 3148 return false; 3149 } 3150 } 3151 } 3152 } 3153 return true; 3154} 3155 3156// Returns true if classes referenced by the signature of the method are the 3157// same classes in klass1 as they are in klass2. 3158bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const mirror::ArtMethod* method, 3159 const mirror::Class* klass1, 3160 const mirror::Class* klass2) { 3161 if (klass1 == klass2) { 3162 return true; 3163 } 3164 const DexFile& dex_file = *method->GetDeclaringClass()->GetDexCache()->GetDexFile(); 3165 const DexFile::ProtoId& proto_id = 3166 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex())); 3167 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) { 3168 const char* descriptor = it.GetDescriptor(); 3169 if (descriptor == NULL) { 3170 break; 3171 } 3172 if (descriptor[0] == 'L' || descriptor[0] == '[') { 3173 // Found a non-primitive type. 3174 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) { 3175 return false; 3176 } 3177 } 3178 } 3179 // Check the return type 3180 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id); 3181 if (descriptor[0] == 'L' || descriptor[0] == '[') { 3182 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) { 3183 return false; 3184 } 3185 } 3186 return true; 3187} 3188 3189// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2. 3190bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor, 3191 const mirror::Class* klass1, 3192 const mirror::Class* klass2) { 3193 CHECK(descriptor != NULL); 3194 CHECK(klass1 != NULL); 3195 CHECK(klass2 != NULL); 3196 if (klass1 == klass2) { 3197 return true; 3198 } 3199 mirror::Class* found1 = FindClass(descriptor, klass1->GetClassLoader()); 3200 if (found1 == NULL) { 3201 Thread::Current()->ClearException(); 3202 } 3203 mirror::Class* found2 = FindClass(descriptor, klass2->GetClassLoader()); 3204 if (found2 == NULL) { 3205 Thread::Current()->ClearException(); 3206 } 3207 return found1 == found2; 3208} 3209 3210bool ClassLinker::EnsureInitialized(mirror::Class* c, bool can_init_fields, bool can_init_parents) { 3211 DCHECK(c != NULL); 3212 if (c->IsInitialized()) { 3213 return true; 3214 } 3215 3216 bool success = InitializeClass(c, can_init_fields, can_init_parents); 3217 if (!success) { 3218 Thread* self = Thread::Current(); 3219 CHECK(self->IsExceptionPending() || !can_init_fields || !can_init_parents) << PrettyClass(c); 3220 } 3221 return success; 3222} 3223 3224void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def, 3225 mirror::Class* c, SafeMap<uint32_t, mirror::ArtField*>& field_map) { 3226 mirror::ClassLoader* cl = c->GetClassLoader(); 3227 const byte* class_data = dex_file.GetClassData(dex_class_def); 3228 ClassDataItemIterator it(dex_file, class_data); 3229 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) { 3230 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true)); 3231 } 3232} 3233 3234bool ClassLinker::LinkClass(SirtRef<mirror::Class>& klass, 3235 mirror::ObjectArray<mirror::Class>* interfaces, Thread* self) { 3236 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 3237 if (!LinkSuperClass(klass)) { 3238 return false; 3239 } 3240 if (!LinkMethods(klass, interfaces)) { 3241 return false; 3242 } 3243 if (!LinkInstanceFields(klass)) { 3244 return false; 3245 } 3246 if (!LinkStaticFields(klass)) { 3247 return false; 3248 } 3249 CreateReferenceInstanceOffsets(klass); 3250 CreateReferenceStaticOffsets(klass); 3251 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 3252 klass->SetStatus(mirror::Class::kStatusResolved, self); 3253 return true; 3254} 3255 3256bool ClassLinker::LoadSuperAndInterfaces(SirtRef<mirror::Class>& klass, const DexFile& dex_file) { 3257 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus()); 3258 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex()); 3259 uint16_t super_class_idx = class_def.superclass_idx_; 3260 if (super_class_idx != DexFile::kDexNoIndex16) { 3261 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.get()); 3262 if (super_class == NULL) { 3263 DCHECK(Thread::Current()->IsExceptionPending()); 3264 return false; 3265 } 3266 // Verify 3267 if (!klass->CanAccess(super_class)) { 3268 ThrowIllegalAccessError(klass.get(), "Class %s extended by class %s is inaccessible", 3269 PrettyDescriptor(super_class).c_str(), 3270 PrettyDescriptor(klass.get()).c_str()); 3271 return false; 3272 } 3273 klass->SetSuperClass(super_class); 3274 } 3275 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def); 3276 if (interfaces != NULL) { 3277 for (size_t i = 0; i < interfaces->Size(); i++) { 3278 uint16_t idx = interfaces->GetTypeItem(i).type_idx_; 3279 mirror::Class* interface = ResolveType(dex_file, idx, klass.get()); 3280 if (interface == NULL) { 3281 DCHECK(Thread::Current()->IsExceptionPending()); 3282 return false; 3283 } 3284 // Verify 3285 if (!klass->CanAccess(interface)) { 3286 // TODO: the RI seemed to ignore this in my testing. 3287 ThrowIllegalAccessError(klass.get(), "Interface %s implemented by class %s is inaccessible", 3288 PrettyDescriptor(interface).c_str(), 3289 PrettyDescriptor(klass.get()).c_str()); 3290 return false; 3291 } 3292 } 3293 } 3294 // Mark the class as loaded. 3295 klass->SetStatus(mirror::Class::kStatusLoaded, NULL); 3296 return true; 3297} 3298 3299bool ClassLinker::LinkSuperClass(SirtRef<mirror::Class>& klass) { 3300 CHECK(!klass->IsPrimitive()); 3301 mirror::Class* super = klass->GetSuperClass(); 3302 if (klass.get() == GetClassRoot(kJavaLangObject)) { 3303 if (super != NULL) { 3304 ThrowClassFormatError(klass.get(), "java.lang.Object must not have a superclass"); 3305 return false; 3306 } 3307 return true; 3308 } 3309 if (super == NULL) { 3310 ThrowLinkageError(klass.get(), "No superclass defined for class %s", 3311 PrettyDescriptor(klass.get()).c_str()); 3312 return false; 3313 } 3314 // Verify 3315 if (super->IsFinal() || super->IsInterface()) { 3316 ThrowIncompatibleClassChangeError(klass.get(), "Superclass %s of %s is %s", 3317 PrettyDescriptor(super).c_str(), 3318 PrettyDescriptor(klass.get()).c_str(), 3319 super->IsFinal() ? "declared final" : "an interface"); 3320 return false; 3321 } 3322 if (!klass->CanAccess(super)) { 3323 ThrowIllegalAccessError(klass.get(), "Superclass %s is inaccessible to class %s", 3324 PrettyDescriptor(super).c_str(), 3325 PrettyDescriptor(klass.get()).c_str()); 3326 return false; 3327 } 3328 3329 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize. 3330 if (super->IsFinalizable()) { 3331 klass->SetFinalizable(); 3332 } 3333 3334 // Inherit reference flags (if any) from the superclass. 3335 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask); 3336 if (reference_flags != 0) { 3337 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags); 3338 } 3339 // Disallow custom direct subclasses of java.lang.ref.Reference. 3340 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) { 3341 ThrowLinkageError(klass.get(), 3342 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed", 3343 PrettyDescriptor(klass.get()).c_str()); 3344 return false; 3345 } 3346 3347 if (kIsDebugBuild) { 3348 // Ensure super classes are fully resolved prior to resolving fields.. 3349 while (super != NULL) { 3350 CHECK(super->IsResolved()); 3351 super = super->GetSuperClass(); 3352 } 3353 } 3354 return true; 3355} 3356 3357// Populate the class vtable and itable. Compute return type indices. 3358bool ClassLinker::LinkMethods(SirtRef<mirror::Class>& klass, 3359 mirror::ObjectArray<mirror::Class>* interfaces) { 3360 if (klass->IsInterface()) { 3361 // No vtable. 3362 size_t count = klass->NumVirtualMethods(); 3363 if (!IsUint(16, count)) { 3364 ThrowClassFormatError(klass.get(), "Too many methods on interface: %zd", count); 3365 return false; 3366 } 3367 for (size_t i = 0; i < count; ++i) { 3368 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i); 3369 } 3370 // Link interface method tables 3371 return LinkInterfaceMethods(klass, interfaces); 3372 } else { 3373 // Link virtual and interface method tables 3374 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces); 3375 } 3376 return true; 3377} 3378 3379bool ClassLinker::LinkVirtualMethods(SirtRef<mirror::Class>& klass) { 3380 Thread* self = Thread::Current(); 3381 if (klass->HasSuperClass()) { 3382 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength(); 3383 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength(); 3384 CHECK_LE(actual_count, max_count); 3385 // TODO: do not assign to the vtable field until it is fully constructed. 3386 SirtRef<mirror::ObjectArray<mirror::ArtMethod> > 3387 vtable(self, klass->GetSuperClass()->GetVTable()->CopyOf(self, max_count)); 3388 if (UNLIKELY(vtable.get() == NULL)) { 3389 CHECK(self->IsExceptionPending()); // OOME. 3390 return false; 3391 } 3392 // See if any of our virtual methods override the superclass. 3393 MethodHelper local_mh(NULL, this); 3394 MethodHelper super_mh(NULL, this); 3395 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) { 3396 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i); 3397 local_mh.ChangeMethod(local_method); 3398 size_t j = 0; 3399 for (; j < actual_count; ++j) { 3400 mirror::ArtMethod* super_method = vtable->Get(j); 3401 super_mh.ChangeMethod(super_method); 3402 if (local_mh.HasSameNameAndSignature(&super_mh)) { 3403 if (klass->CanAccessMember(super_method->GetDeclaringClass(), super_method->GetAccessFlags())) { 3404 if (super_method->IsFinal()) { 3405 ThrowLinkageError(klass.get(), "Method %s overrides final method in class %s", 3406 PrettyMethod(local_method).c_str(), 3407 super_mh.GetDeclaringClassDescriptor()); 3408 return false; 3409 } 3410 vtable->Set(j, local_method); 3411 local_method->SetMethodIndex(j); 3412 break; 3413 } else { 3414 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method) 3415 << " would have incorrectly overridden the package-private method in " 3416 << PrettyDescriptor(super_mh.GetDeclaringClassDescriptor()); 3417 } 3418 } 3419 } 3420 if (j == actual_count) { 3421 // Not overriding, append. 3422 vtable->Set(actual_count, local_method); 3423 local_method->SetMethodIndex(actual_count); 3424 actual_count += 1; 3425 } 3426 } 3427 if (!IsUint(16, actual_count)) { 3428 ThrowClassFormatError(klass.get(), "Too many methods defined on class: %zd", actual_count); 3429 return false; 3430 } 3431 // Shrink vtable if possible 3432 CHECK_LE(actual_count, max_count); 3433 if (actual_count < max_count) { 3434 vtable.reset(vtable->CopyOf(self, actual_count)); 3435 if (UNLIKELY(vtable.get() == NULL)) { 3436 CHECK(self->IsExceptionPending()); // OOME. 3437 return false; 3438 } 3439 } 3440 klass->SetVTable(vtable.get()); 3441 } else { 3442 CHECK(klass.get() == GetClassRoot(kJavaLangObject)); 3443 uint32_t num_virtual_methods = klass->NumVirtualMethods(); 3444 if (!IsUint(16, num_virtual_methods)) { 3445 ThrowClassFormatError(klass.get(), "Too many methods: %d", num_virtual_methods); 3446 return false; 3447 } 3448 SirtRef<mirror::ObjectArray<mirror::ArtMethod> > 3449 vtable(self, AllocArtMethodArray(self, num_virtual_methods)); 3450 if (UNLIKELY(vtable.get() == NULL)) { 3451 CHECK(self->IsExceptionPending()); // OOME. 3452 return false; 3453 } 3454 for (size_t i = 0; i < num_virtual_methods; ++i) { 3455 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i); 3456 vtable->Set(i, virtual_method); 3457 virtual_method->SetMethodIndex(i & 0xFFFF); 3458 } 3459 klass->SetVTable(vtable.get()); 3460 } 3461 return true; 3462} 3463 3464bool ClassLinker::LinkInterfaceMethods(SirtRef<mirror::Class>& klass, 3465 mirror::ObjectArray<mirror::Class>* interfaces) { 3466 size_t super_ifcount; 3467 if (klass->HasSuperClass()) { 3468 super_ifcount = klass->GetSuperClass()->GetIfTableCount(); 3469 } else { 3470 super_ifcount = 0; 3471 } 3472 size_t ifcount = super_ifcount; 3473 ClassHelper kh(klass.get(), this); 3474 uint32_t num_interfaces = interfaces == NULL ? kh.NumDirectInterfaces() : interfaces->GetLength(); 3475 ifcount += num_interfaces; 3476 for (size_t i = 0; i < num_interfaces; i++) { 3477 mirror::Class* interface = interfaces == NULL ? kh.GetDirectInterface(i) : interfaces->Get(i); 3478 ifcount += interface->GetIfTableCount(); 3479 } 3480 if (ifcount == 0) { 3481 // Class implements no interfaces. 3482 DCHECK_EQ(klass->GetIfTableCount(), 0); 3483 DCHECK(klass->GetIfTable() == NULL); 3484 return true; 3485 } 3486 if (ifcount == super_ifcount) { 3487 // Class implements same interfaces as parent, are any of these not marker interfaces? 3488 bool has_non_marker_interface = false; 3489 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 3490 for (size_t i = 0; i < ifcount; ++i) { 3491 if (super_iftable->GetMethodArrayCount(i) > 0) { 3492 has_non_marker_interface = true; 3493 break; 3494 } 3495 } 3496 if (!has_non_marker_interface) { 3497 // Class just inherits marker interfaces from parent so recycle parent's iftable. 3498 klass->SetIfTable(super_iftable); 3499 return true; 3500 } 3501 } 3502 Thread* self = Thread::Current(); 3503 SirtRef<mirror::IfTable> iftable(self, AllocIfTable(self, ifcount)); 3504 if (UNLIKELY(iftable.get() == NULL)) { 3505 CHECK(self->IsExceptionPending()); // OOME. 3506 return false; 3507 } 3508 if (super_ifcount != 0) { 3509 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 3510 for (size_t i = 0; i < super_ifcount; i++) { 3511 mirror::Class* super_interface = super_iftable->GetInterface(i); 3512 iftable->SetInterface(i, super_interface); 3513 } 3514 } 3515 // Flatten the interface inheritance hierarchy. 3516 size_t idx = super_ifcount; 3517 for (size_t i = 0; i < num_interfaces; i++) { 3518 mirror::Class* interface = interfaces == NULL ? kh.GetDirectInterface(i) : interfaces->Get(i); 3519 DCHECK(interface != NULL); 3520 if (!interface->IsInterface()) { 3521 ClassHelper ih(interface); 3522 ThrowIncompatibleClassChangeError(klass.get(), "Class %s implements non-interface class %s", 3523 PrettyDescriptor(klass.get()).c_str(), 3524 PrettyDescriptor(ih.GetDescriptor()).c_str()); 3525 return false; 3526 } 3527 // Check if interface is already in iftable 3528 bool duplicate = false; 3529 for (size_t j = 0; j < idx; j++) { 3530 mirror::Class* existing_interface = iftable->GetInterface(j); 3531 if (existing_interface == interface) { 3532 duplicate = true; 3533 break; 3534 } 3535 } 3536 if (!duplicate) { 3537 // Add this non-duplicate interface. 3538 iftable->SetInterface(idx++, interface); 3539 // Add this interface's non-duplicate super-interfaces. 3540 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) { 3541 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j); 3542 bool super_duplicate = false; 3543 for (size_t k = 0; k < idx; k++) { 3544 mirror::Class* existing_interface = iftable->GetInterface(k); 3545 if (existing_interface == super_interface) { 3546 super_duplicate = true; 3547 break; 3548 } 3549 } 3550 if (!super_duplicate) { 3551 iftable->SetInterface(idx++, super_interface); 3552 } 3553 } 3554 } 3555 } 3556 // Shrink iftable in case duplicates were found 3557 if (idx < ifcount) { 3558 iftable.reset(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax))); 3559 if (UNLIKELY(iftable.get() == NULL)) { 3560 CHECK(self->IsExceptionPending()); // OOME. 3561 return false; 3562 } 3563 ifcount = idx; 3564 } else { 3565 CHECK_EQ(idx, ifcount); 3566 } 3567 klass->SetIfTable(iftable.get()); 3568 3569 // If we're an interface, we don't need the vtable pointers, so we're done. 3570 if (klass->IsInterface()) { 3571 return true; 3572 } 3573 std::vector<mirror::ArtMethod*> miranda_list; 3574 MethodHelper vtable_mh(NULL, this); 3575 MethodHelper interface_mh(NULL, this); 3576 for (size_t i = 0; i < ifcount; ++i) { 3577 mirror::Class* interface = iftable->GetInterface(i); 3578 size_t num_methods = interface->NumVirtualMethods(); 3579 if (num_methods > 0) { 3580 mirror::ObjectArray<mirror::ArtMethod>* method_array = 3581 AllocArtMethodArray(self, num_methods); 3582 if (UNLIKELY(method_array == NULL)) { 3583 CHECK(self->IsExceptionPending()); // OOME. 3584 return false; 3585 } 3586 iftable->SetMethodArray(i, method_array); 3587 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking(); 3588 for (size_t j = 0; j < num_methods; ++j) { 3589 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j); 3590 interface_mh.ChangeMethod(interface_method); 3591 int32_t k; 3592 // For each method listed in the interface's method list, find the 3593 // matching method in our class's method list. We want to favor the 3594 // subclass over the superclass, which just requires walking 3595 // back from the end of the vtable. (This only matters if the 3596 // superclass defines a private method and this class redefines 3597 // it -- otherwise it would use the same vtable slot. In .dex files 3598 // those don't end up in the virtual method table, so it shouldn't 3599 // matter which direction we go. We walk it backward anyway.) 3600 for (k = vtable->GetLength() - 1; k >= 0; --k) { 3601 mirror::ArtMethod* vtable_method = vtable->Get(k); 3602 vtable_mh.ChangeMethod(vtable_method); 3603 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) { 3604 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) { 3605 ThrowIllegalAccessError(klass.get(), 3606 "Method '%s' implementing interface method '%s' is not public", 3607 PrettyMethod(vtable_method).c_str(), 3608 PrettyMethod(interface_method).c_str()); 3609 return false; 3610 } 3611 method_array->Set(j, vtable_method); 3612 break; 3613 } 3614 } 3615 if (k < 0) { 3616 SirtRef<mirror::ArtMethod> miranda_method(self, NULL); 3617 for (size_t mir = 0; mir < miranda_list.size(); mir++) { 3618 mirror::ArtMethod* mir_method = miranda_list[mir]; 3619 vtable_mh.ChangeMethod(mir_method); 3620 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) { 3621 miranda_method.reset(miranda_list[mir]); 3622 break; 3623 } 3624 } 3625 if (miranda_method.get() == NULL) { 3626 // Point the interface table at a phantom slot. 3627 miranda_method.reset(down_cast<mirror::ArtMethod*>(interface_method->Clone(self))); 3628 if (UNLIKELY(miranda_method.get() == NULL)) { 3629 CHECK(self->IsExceptionPending()); // OOME. 3630 return false; 3631 } 3632#ifdef MOVING_GARBAGE_COLLECTOR 3633 // TODO: If a methods move then the miranda_list may hold stale references. 3634 UNIMPLEMENTED(FATAL); 3635#endif 3636 miranda_list.push_back(miranda_method.get()); 3637 } 3638 method_array->Set(j, miranda_method.get()); 3639 } 3640 } 3641 } 3642 } 3643 if (!miranda_list.empty()) { 3644 int old_method_count = klass->NumVirtualMethods(); 3645 int new_method_count = old_method_count + miranda_list.size(); 3646 mirror::ObjectArray<mirror::ArtMethod>* virtuals; 3647 if (old_method_count == 0) { 3648 virtuals = AllocArtMethodArray(self, new_method_count); 3649 } else { 3650 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count); 3651 } 3652 if (UNLIKELY(virtuals == NULL)) { 3653 CHECK(self->IsExceptionPending()); // OOME. 3654 return false; 3655 } 3656 klass->SetVirtualMethods(virtuals); 3657 3658 SirtRef<mirror::ObjectArray<mirror::ArtMethod> > 3659 vtable(self, klass->GetVTableDuringLinking()); 3660 CHECK(vtable.get() != NULL); 3661 int old_vtable_count = vtable->GetLength(); 3662 int new_vtable_count = old_vtable_count + miranda_list.size(); 3663 vtable.reset(vtable->CopyOf(self, new_vtable_count)); 3664 if (UNLIKELY(vtable.get() == NULL)) { 3665 CHECK(self->IsExceptionPending()); // OOME. 3666 return false; 3667 } 3668 for (size_t i = 0; i < miranda_list.size(); ++i) { 3669 mirror::ArtMethod* method = miranda_list[i]; 3670 // Leave the declaring class alone as type indices are relative to it 3671 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda); 3672 method->SetMethodIndex(0xFFFF & (old_vtable_count + i)); 3673 klass->SetVirtualMethod(old_method_count + i, method); 3674 vtable->Set(old_vtable_count + i, method); 3675 } 3676 // TODO: do not assign to the vtable field until it is fully constructed. 3677 klass->SetVTable(vtable.get()); 3678 } 3679 3680 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking(); 3681 for (int i = 0; i < vtable->GetLength(); ++i) { 3682 CHECK(vtable->Get(i) != NULL); 3683 } 3684 3685// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail); 3686 3687 return true; 3688} 3689 3690bool ClassLinker::LinkInstanceFields(SirtRef<mirror::Class>& klass) { 3691 CHECK(klass.get() != NULL); 3692 return LinkFields(klass, false); 3693} 3694 3695bool ClassLinker::LinkStaticFields(SirtRef<mirror::Class>& klass) { 3696 CHECK(klass.get() != NULL); 3697 size_t allocated_class_size = klass->GetClassSize(); 3698 bool success = LinkFields(klass, true); 3699 CHECK_EQ(allocated_class_size, klass->GetClassSize()); 3700 return success; 3701} 3702 3703struct LinkFieldsComparator { 3704 explicit LinkFieldsComparator(FieldHelper* fh) 3705 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 3706 : fh_(fh) {} 3707 // No thread safety analysis as will be called from STL. Checked lock held in constructor. 3708 bool operator()(const mirror::ArtField* field1, const mirror::ArtField* field2) 3709 NO_THREAD_SAFETY_ANALYSIS { 3710 // First come reference fields, then 64-bit, and finally 32-bit 3711 fh_->ChangeField(field1); 3712 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType(); 3713 fh_->ChangeField(field2); 3714 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType(); 3715 bool isPrimitive1 = type1 != Primitive::kPrimNot; 3716 bool isPrimitive2 = type2 != Primitive::kPrimNot; 3717 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble); 3718 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble); 3719 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2)); 3720 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2)); 3721 if (order1 != order2) { 3722 return order1 < order2; 3723 } 3724 3725 // same basic group? then sort by string. 3726 fh_->ChangeField(field1); 3727 StringPiece name1(fh_->GetName()); 3728 fh_->ChangeField(field2); 3729 StringPiece name2(fh_->GetName()); 3730 return name1 < name2; 3731 } 3732 3733 FieldHelper* fh_; 3734}; 3735 3736bool ClassLinker::LinkFields(SirtRef<mirror::Class>& klass, bool is_static) { 3737 size_t num_fields = 3738 is_static ? klass->NumStaticFields() : klass->NumInstanceFields(); 3739 3740 mirror::ObjectArray<mirror::ArtField>* fields = 3741 is_static ? klass->GetSFields() : klass->GetIFields(); 3742 3743 // Initialize size and field_offset 3744 size_t size; 3745 MemberOffset field_offset(0); 3746 if (is_static) { 3747 size = klass->GetClassSize(); 3748 field_offset = mirror::Class::FieldsOffset(); 3749 } else { 3750 mirror::Class* super_class = klass->GetSuperClass(); 3751 if (super_class != NULL) { 3752 CHECK(super_class->IsResolved()); 3753 field_offset = MemberOffset(super_class->GetObjectSize()); 3754 } 3755 size = field_offset.Uint32Value(); 3756 } 3757 3758 CHECK_EQ(num_fields == 0, fields == NULL); 3759 3760 // we want a relatively stable order so that adding new fields 3761 // minimizes disruption of C++ version such as Class and Method. 3762 std::deque<mirror::ArtField*> grouped_and_sorted_fields; 3763 for (size_t i = 0; i < num_fields; i++) { 3764 grouped_and_sorted_fields.push_back(fields->Get(i)); 3765 } 3766 FieldHelper fh(NULL, this); 3767 std::sort(grouped_and_sorted_fields.begin(), 3768 grouped_and_sorted_fields.end(), 3769 LinkFieldsComparator(&fh)); 3770 3771 // References should be at the front. 3772 size_t current_field = 0; 3773 size_t num_reference_fields = 0; 3774 for (; current_field < num_fields; current_field++) { 3775 mirror::ArtField* field = grouped_and_sorted_fields.front(); 3776 fh.ChangeField(field); 3777 Primitive::Type type = fh.GetTypeAsPrimitiveType(); 3778 bool isPrimitive = type != Primitive::kPrimNot; 3779 if (isPrimitive) { 3780 break; // past last reference, move on to the next phase 3781 } 3782 grouped_and_sorted_fields.pop_front(); 3783 num_reference_fields++; 3784 fields->Set(current_field, field); 3785 field->SetOffset(field_offset); 3786 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t)); 3787 } 3788 3789 // Now we want to pack all of the double-wide fields together. If 3790 // we're not aligned, though, we want to shuffle one 32-bit field 3791 // into place. If we can't find one, we'll have to pad it. 3792 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) { 3793 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) { 3794 mirror::ArtField* field = grouped_and_sorted_fields[i]; 3795 fh.ChangeField(field); 3796 Primitive::Type type = fh.GetTypeAsPrimitiveType(); 3797 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types 3798 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) { 3799 continue; 3800 } 3801 fields->Set(current_field++, field); 3802 field->SetOffset(field_offset); 3803 // drop the consumed field 3804 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i); 3805 break; 3806 } 3807 // whether we found a 32-bit field for padding or not, we advance 3808 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t)); 3809 } 3810 3811 // Alignment is good, shuffle any double-wide fields forward, and 3812 // finish assigning field offsets to all fields. 3813 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value())); 3814 while (!grouped_and_sorted_fields.empty()) { 3815 mirror::ArtField* field = grouped_and_sorted_fields.front(); 3816 grouped_and_sorted_fields.pop_front(); 3817 fh.ChangeField(field); 3818 Primitive::Type type = fh.GetTypeAsPrimitiveType(); 3819 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types 3820 fields->Set(current_field, field); 3821 field->SetOffset(field_offset); 3822 field_offset = MemberOffset(field_offset.Uint32Value() + 3823 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble) 3824 ? sizeof(uint64_t) 3825 : sizeof(uint32_t))); 3826 current_field++; 3827 } 3828 3829 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it. 3830 if (!is_static && 3831 StringPiece(ClassHelper(klass.get(), this).GetDescriptor()) == "Ljava/lang/ref/Reference;") { 3832 // We know there are no non-reference fields in the Reference classes, and we know 3833 // that 'referent' is alphabetically last, so this is easy... 3834 CHECK_EQ(num_reference_fields, num_fields); 3835 fh.ChangeField(fields->Get(num_fields - 1)); 3836 CHECK_STREQ(fh.GetName(), "referent"); 3837 --num_reference_fields; 3838 } 3839 3840#ifndef NDEBUG 3841 // Make sure that all reference fields appear before 3842 // non-reference fields, and all double-wide fields are aligned. 3843 bool seen_non_ref = false; 3844 for (size_t i = 0; i < num_fields; i++) { 3845 mirror::ArtField* field = fields->Get(i); 3846 if (false) { // enable to debug field layout 3847 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance") 3848 << " class=" << PrettyClass(klass.get()) 3849 << " field=" << PrettyField(field) 3850 << " offset=" << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()), 3851 false); 3852 } 3853 fh.ChangeField(field); 3854 Primitive::Type type = fh.GetTypeAsPrimitiveType(); 3855 bool is_primitive = type != Primitive::kPrimNot; 3856 if (StringPiece(ClassHelper(klass.get(), this).GetDescriptor()) == "Ljava/lang/ref/Reference;" && 3857 StringPiece(fh.GetName()) == "referent") { 3858 is_primitive = true; // We lied above, so we have to expect a lie here. 3859 } 3860 if (is_primitive) { 3861 if (!seen_non_ref) { 3862 seen_non_ref = true; 3863 DCHECK_EQ(num_reference_fields, i); 3864 } 3865 } else { 3866 DCHECK(!seen_non_ref); 3867 } 3868 } 3869 if (!seen_non_ref) { 3870 DCHECK_EQ(num_fields, num_reference_fields); 3871 } 3872#endif 3873 size = field_offset.Uint32Value(); 3874 // Update klass 3875 if (is_static) { 3876 klass->SetNumReferenceStaticFields(num_reference_fields); 3877 klass->SetClassSize(size); 3878 } else { 3879 klass->SetNumReferenceInstanceFields(num_reference_fields); 3880 if (!klass->IsVariableSize()) { 3881 DCHECK_GE(size, sizeof(mirror::Object)) << ClassHelper(klass.get(), this).GetDescriptor(); 3882 klass->SetObjectSize(size); 3883 } 3884 } 3885 return true; 3886} 3887 3888// Set the bitmap of reference offsets, refOffsets, from the ifields 3889// list. 3890void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<mirror::Class>& klass) { 3891 uint32_t reference_offsets = 0; 3892 mirror::Class* super_class = klass->GetSuperClass(); 3893 if (super_class != NULL) { 3894 reference_offsets = super_class->GetReferenceInstanceOffsets(); 3895 // If our superclass overflowed, we don't stand a chance. 3896 if (reference_offsets == CLASS_WALK_SUPER) { 3897 klass->SetReferenceInstanceOffsets(reference_offsets); 3898 return; 3899 } 3900 } 3901 CreateReferenceOffsets(klass, false, reference_offsets); 3902} 3903 3904void ClassLinker::CreateReferenceStaticOffsets(SirtRef<mirror::Class>& klass) { 3905 CreateReferenceOffsets(klass, true, 0); 3906} 3907 3908void ClassLinker::CreateReferenceOffsets(SirtRef<mirror::Class>& klass, bool is_static, 3909 uint32_t reference_offsets) { 3910 size_t num_reference_fields = 3911 is_static ? klass->NumReferenceStaticFieldsDuringLinking() 3912 : klass->NumReferenceInstanceFieldsDuringLinking(); 3913 const mirror::ObjectArray<mirror::ArtField>* fields = 3914 is_static ? klass->GetSFields() : klass->GetIFields(); 3915 // All of the fields that contain object references are guaranteed 3916 // to be at the beginning of the fields list. 3917 for (size_t i = 0; i < num_reference_fields; ++i) { 3918 // Note that byte_offset is the offset from the beginning of 3919 // object, not the offset into instance data 3920 const mirror::ArtField* field = fields->Get(i); 3921 MemberOffset byte_offset = field->GetOffsetDuringLinking(); 3922 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U); 3923 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) { 3924 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value()); 3925 CHECK_NE(new_bit, 0U); 3926 reference_offsets |= new_bit; 3927 } else { 3928 reference_offsets = CLASS_WALK_SUPER; 3929 break; 3930 } 3931 } 3932 // Update fields in klass 3933 if (is_static) { 3934 klass->SetReferenceStaticOffsets(reference_offsets); 3935 } else { 3936 klass->SetReferenceInstanceOffsets(reference_offsets); 3937 } 3938} 3939 3940mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, 3941 uint32_t string_idx, mirror::DexCache* dex_cache) { 3942 DCHECK(dex_cache != NULL); 3943 mirror::String* resolved = dex_cache->GetResolvedString(string_idx); 3944 if (resolved != NULL) { 3945 return resolved; 3946 } 3947 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx); 3948 int32_t utf16_length = dex_file.GetStringLength(string_id); 3949 const char* utf8_data = dex_file.GetStringData(string_id); 3950 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data); 3951 dex_cache->SetResolvedString(string_idx, string); 3952 return string; 3953} 3954 3955mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, 3956 uint16_t type_idx, 3957 mirror::DexCache* dex_cache, 3958 mirror::ClassLoader* class_loader) { 3959 DCHECK(dex_cache != NULL); 3960 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx); 3961 if (resolved == NULL) { 3962 const char* descriptor = dex_file.StringByTypeIdx(type_idx); 3963 resolved = FindClass(descriptor, class_loader); 3964 if (resolved != NULL) { 3965 // TODO: we used to throw here if resolved's class loader was not the 3966 // boot class loader. This was to permit different classes with the 3967 // same name to be loaded simultaneously by different loaders 3968 dex_cache->SetResolvedType(type_idx, resolved); 3969 } else { 3970 Thread* self = Thread::Current(); 3971 CHECK(self->IsExceptionPending()) 3972 << "Expected pending exception for failed resolution of: " << descriptor; 3973 // Convert a ClassNotFoundException to a NoClassDefFoundError. 3974 SirtRef<mirror::Throwable> cause(self, self->GetException(NULL)); 3975 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) { 3976 Thread::Current()->ClearException(); 3977 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor); 3978 self->GetException(NULL)->SetCause(cause.get()); 3979 } 3980 } 3981 } 3982 return resolved; 3983} 3984 3985mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, 3986 uint32_t method_idx, 3987 mirror::DexCache* dex_cache, 3988 mirror::ClassLoader* class_loader, 3989 const mirror::ArtMethod* referrer, 3990 InvokeType type) { 3991 DCHECK(dex_cache != NULL); 3992 // Check for hit in the dex cache. 3993 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx); 3994 if (resolved != NULL) { 3995 return resolved; 3996 } 3997 // Fail, get the declaring class. 3998 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 3999 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader); 4000 if (klass == NULL) { 4001 DCHECK(Thread::Current()->IsExceptionPending()); 4002 return NULL; 4003 } 4004 // Scan using method_idx, this saves string compares but will only hit for matching dex 4005 // caches/files. 4006 switch (type) { 4007 case kDirect: // Fall-through. 4008 case kStatic: 4009 resolved = klass->FindDirectMethod(dex_cache, method_idx); 4010 break; 4011 case kInterface: 4012 resolved = klass->FindInterfaceMethod(dex_cache, method_idx); 4013 DCHECK(resolved == NULL || resolved->GetDeclaringClass()->IsInterface()); 4014 break; 4015 case kSuper: // Fall-through. 4016 case kVirtual: 4017 resolved = klass->FindVirtualMethod(dex_cache, method_idx); 4018 break; 4019 default: 4020 LOG(FATAL) << "Unreachable - invocation type: " << type; 4021 } 4022 if (resolved == NULL) { 4023 // Search by name, which works across dex files. 4024 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 4025 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL)); 4026 switch (type) { 4027 case kDirect: // Fall-through. 4028 case kStatic: 4029 resolved = klass->FindDirectMethod(name, signature); 4030 break; 4031 case kInterface: 4032 resolved = klass->FindInterfaceMethod(name, signature); 4033 DCHECK(resolved == NULL || resolved->GetDeclaringClass()->IsInterface()); 4034 break; 4035 case kSuper: // Fall-through. 4036 case kVirtual: 4037 resolved = klass->FindVirtualMethod(name, signature); 4038 break; 4039 } 4040 } 4041 if (resolved != NULL) { 4042 // We found a method, check for incompatible class changes. 4043 if (resolved->CheckIncompatibleClassChange(type)) { 4044 resolved = NULL; 4045 } 4046 } 4047 if (resolved != NULL) { 4048 // Be a good citizen and update the dex cache to speed subsequent calls. 4049 dex_cache->SetResolvedMethod(method_idx, resolved); 4050 return resolved; 4051 } else { 4052 // We failed to find the method which means either an access error, an incompatible class 4053 // change, or no such method. First try to find the method among direct and virtual methods. 4054 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 4055 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL)); 4056 switch (type) { 4057 case kDirect: 4058 case kStatic: 4059 resolved = klass->FindVirtualMethod(name, signature); 4060 break; 4061 case kInterface: 4062 case kVirtual: 4063 case kSuper: 4064 resolved = klass->FindDirectMethod(name, signature); 4065 break; 4066 } 4067 4068 // If we found something, check that it can be accessed by the referrer. 4069 if (resolved != NULL && referrer != NULL) { 4070 mirror::Class* methods_class = resolved->GetDeclaringClass(); 4071 mirror::Class* referring_class = referrer->GetDeclaringClass(); 4072 if (!referring_class->CanAccess(methods_class)) { 4073 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class, 4074 referrer, resolved, type); 4075 return NULL; 4076 } else if (!referring_class->CanAccessMember(methods_class, 4077 resolved->GetAccessFlags())) { 4078 ThrowIllegalAccessErrorMethod(referring_class, resolved); 4079 return NULL; 4080 } 4081 } 4082 4083 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface 4084 // methods and throw if we find the method there. If we find nothing, throw a NoSuchMethodError. 4085 switch (type) { 4086 case kDirect: 4087 case kStatic: 4088 if (resolved != NULL) { 4089 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer); 4090 } else { 4091 resolved = klass->FindInterfaceMethod(name, signature); 4092 if (resolved != NULL) { 4093 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer); 4094 } else { 4095 ThrowNoSuchMethodError(type, klass, name, signature); 4096 } 4097 } 4098 break; 4099 case kInterface: 4100 if (resolved != NULL) { 4101 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer); 4102 } else { 4103 resolved = klass->FindVirtualMethod(name, signature); 4104 if (resolved != NULL) { 4105 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer); 4106 } else { 4107 ThrowNoSuchMethodError(type, klass, name, signature); 4108 } 4109 } 4110 break; 4111 case kSuper: 4112 ThrowNoSuchMethodError(type, klass, name, signature); 4113 break; 4114 case kVirtual: 4115 if (resolved != NULL) { 4116 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer); 4117 } else { 4118 resolved = klass->FindInterfaceMethod(name, signature); 4119 if (resolved != NULL) { 4120 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer); 4121 } else { 4122 ThrowNoSuchMethodError(type, klass, name, signature); 4123 } 4124 } 4125 break; 4126 } 4127 DCHECK(Thread::Current()->IsExceptionPending()); 4128 return NULL; 4129 } 4130} 4131 4132mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, 4133 uint32_t field_idx, 4134 mirror::DexCache* dex_cache, 4135 mirror::ClassLoader* class_loader, 4136 bool is_static) { 4137 DCHECK(dex_cache != NULL); 4138 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx); 4139 if (resolved != NULL) { 4140 return resolved; 4141 } 4142 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 4143 mirror::Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader); 4144 if (klass == NULL) { 4145 DCHECK(Thread::Current()->IsExceptionPending()); 4146 return NULL; 4147 } 4148 4149 if (is_static) { 4150 resolved = klass->FindStaticField(dex_cache, field_idx); 4151 } else { 4152 resolved = klass->FindInstanceField(dex_cache, field_idx); 4153 } 4154 4155 if (resolved == NULL) { 4156 const char* name = dex_file.GetFieldName(field_id); 4157 const char* type = dex_file.GetFieldTypeDescriptor(field_id); 4158 if (is_static) { 4159 resolved = klass->FindStaticField(name, type); 4160 } else { 4161 resolved = klass->FindInstanceField(name, type); 4162 } 4163 if (resolved == NULL) { 4164 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name); 4165 return NULL; 4166 } 4167 } 4168 dex_cache->SetResolvedField(field_idx, resolved); 4169 return resolved; 4170} 4171 4172mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, 4173 uint32_t field_idx, 4174 mirror::DexCache* dex_cache, 4175 mirror::ClassLoader* class_loader) { 4176 DCHECK(dex_cache != NULL); 4177 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx); 4178 if (resolved != NULL) { 4179 return resolved; 4180 } 4181 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 4182 mirror::Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader); 4183 if (klass == NULL) { 4184 DCHECK(Thread::Current()->IsExceptionPending()); 4185 return NULL; 4186 } 4187 4188 const char* name = dex_file.GetFieldName(field_id); 4189 const char* type = dex_file.GetFieldTypeDescriptor(field_id); 4190 resolved = klass->FindField(name, type); 4191 if (resolved != NULL) { 4192 dex_cache->SetResolvedField(field_idx, resolved); 4193 } else { 4194 ThrowNoSuchFieldError("", klass, type, name); 4195 } 4196 return resolved; 4197} 4198 4199const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer, 4200 uint32_t* length) { 4201 mirror::Class* declaring_class = referrer->GetDeclaringClass(); 4202 mirror::DexCache* dex_cache = declaring_class->GetDexCache(); 4203 const DexFile& dex_file = *dex_cache->GetDexFile(); 4204 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 4205 return dex_file.GetMethodShorty(method_id, length); 4206} 4207 4208void ClassLinker::DumpAllClasses(int flags) { 4209 if (dex_cache_image_class_lookup_required_) { 4210 MoveImageClassesToClassTable(); 4211 } 4212 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker 4213 // lock held, because it might need to resolve a field's type, which would try to take the lock. 4214 std::vector<mirror::Class*> all_classes; 4215 { 4216 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 4217 for (const std::pair<size_t, mirror::Class*>& it : class_table_) { 4218 all_classes.push_back(it.second); 4219 } 4220 } 4221 4222 for (size_t i = 0; i < all_classes.size(); ++i) { 4223 all_classes[i]->DumpClass(std::cerr, flags); 4224 } 4225} 4226 4227void ClassLinker::DumpForSigQuit(std::ostream& os) { 4228 if (dex_cache_image_class_lookup_required_) { 4229 MoveImageClassesToClassTable(); 4230 } 4231 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 4232 os << "Loaded classes: " << class_table_.size() << " allocated classes\n"; 4233} 4234 4235size_t ClassLinker::NumLoadedClasses() { 4236 if (dex_cache_image_class_lookup_required_) { 4237 MoveImageClassesToClassTable(); 4238 } 4239 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 4240 return class_table_.size(); 4241} 4242 4243pid_t ClassLinker::GetClassesLockOwner() { 4244 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid(); 4245} 4246 4247pid_t ClassLinker::GetDexLockOwner() { 4248 return dex_lock_.GetExclusiveOwnerTid(); 4249} 4250 4251void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) { 4252 DCHECK(!init_done_); 4253 4254 DCHECK(klass != NULL); 4255 DCHECK(klass->GetClassLoader() == NULL); 4256 4257 DCHECK(class_roots_ != NULL); 4258 DCHECK(class_roots_->Get(class_root) == NULL); 4259 class_roots_->Set(class_root, klass); 4260} 4261 4262} // namespace art 4263