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