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