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