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