class_linker.cc revision 1a12858eb15a14788478c4aca82c052bc84fcafa
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 return nullptr; 2657 } 2658 if (UNLIKELY(component_type->IsPrimitiveVoid())) { 2659 ThrowNoClassDefFoundError("Attempt to create array of void primitive type"); 2660 return nullptr; 2661 } 2662 // See if the component type is already loaded. Array classes are 2663 // always associated with the class loader of their underlying 2664 // element type -- an array of Strings goes with the loader for 2665 // java/lang/String -- so we need to look for it there. (The 2666 // caller should have checked for the existence of the class 2667 // before calling here, but they did so with *their* class loader, 2668 // not the component type's loader.) 2669 // 2670 // If we find it, the caller adds "loader" to the class' initiating 2671 // loader list, which should prevent us from going through this again. 2672 // 2673 // This call is unnecessary if "loader" and "component_type->GetClassLoader()" 2674 // are the same, because our caller (FindClass) just did the 2675 // lookup. (Even if we get this wrong we still have correct behavior, 2676 // because we effectively do this lookup again when we add the new 2677 // class to the hash table --- necessary because of possible races with 2678 // other threads.) 2679 if (class_loader.Get() != component_type->GetClassLoader()) { 2680 mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader()); 2681 if (new_class != NULL) { 2682 return new_class; 2683 } 2684 } 2685 2686 // Fill out the fields in the Class. 2687 // 2688 // It is possible to execute some methods against arrays, because 2689 // all arrays are subclasses of java_lang_Object_, so we need to set 2690 // up a vtable. We can just point at the one in java_lang_Object_. 2691 // 2692 // Array classes are simple enough that we don't need to do a full 2693 // link step. 2694 auto new_class = hs.NewHandle<mirror::Class>(nullptr); 2695 if (UNLIKELY(!init_done_)) { 2696 // Classes that were hand created, ie not by FindSystemClass 2697 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) { 2698 new_class.Assign(GetClassRoot(kClassArrayClass)); 2699 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) { 2700 new_class.Assign(GetClassRoot(kObjectArrayClass)); 2701 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) { 2702 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass)); 2703 } else if (strcmp(descriptor, 2704 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) { 2705 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass)); 2706 } else if (strcmp(descriptor, 2707 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) { 2708 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass)); 2709 } else if (strcmp(descriptor, "[C") == 0) { 2710 new_class.Assign(GetClassRoot(kCharArrayClass)); 2711 } else if (strcmp(descriptor, "[I") == 0) { 2712 new_class.Assign(GetClassRoot(kIntArrayClass)); 2713 } 2714 } 2715 if (new_class.Get() == nullptr) { 2716 new_class.Assign(AllocClass(self, mirror::Array::ClassSize())); 2717 if (new_class.Get() == nullptr) { 2718 return nullptr; 2719 } 2720 new_class->SetComponentType(component_type.Get()); 2721 } 2722 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing. 2723 DCHECK(new_class->GetComponentType() != NULL); 2724 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject); 2725 new_class->SetSuperClass(java_lang_Object); 2726 new_class->SetVTable(java_lang_Object->GetVTable()); 2727 new_class->SetPrimitiveType(Primitive::kPrimNot); 2728 new_class->SetClassLoader(component_type->GetClassLoader()); 2729 new_class->SetStatus(mirror::Class::kStatusLoaded, self); 2730 new_class->PopulateEmbeddedImtAndVTable(); 2731 new_class->SetStatus(mirror::Class::kStatusInitialized, self); 2732 // don't need to set new_class->SetObjectSize(..) 2733 // because Object::SizeOf delegates to Array::SizeOf 2734 2735 2736 // All arrays have java/lang/Cloneable and java/io/Serializable as 2737 // interfaces. We need to set that up here, so that stuff like 2738 // "instanceof" works right. 2739 // 2740 // Note: The GC could run during the call to FindSystemClass, 2741 // so we need to make sure the class object is GC-valid while we're in 2742 // there. Do this by clearing the interface list so the GC will just 2743 // think that the entries are null. 2744 2745 2746 // Use the single, global copies of "interfaces" and "iftable" 2747 // (remember not to free them for arrays). 2748 { 2749 mirror::IfTable* array_iftable = 2750 ReadBarrier::BarrierForRoot<mirror::IfTable, kWithReadBarrier>(&array_iftable_); 2751 CHECK(array_iftable != nullptr); 2752 new_class->SetIfTable(array_iftable); 2753 } 2754 2755 // Inherit access flags from the component type. 2756 int access_flags = new_class->GetComponentType()->GetAccessFlags(); 2757 // Lose any implementation detail flags; in particular, arrays aren't finalizable. 2758 access_flags &= kAccJavaFlagsMask; 2759 // Arrays can't be used as a superclass or interface, so we want to add "abstract final" 2760 // and remove "interface". 2761 access_flags |= kAccAbstract | kAccFinal; 2762 access_flags &= ~kAccInterface; 2763 2764 new_class->SetAccessFlags(access_flags); 2765 2766 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor)); 2767 if (existing == nullptr) { 2768 return new_class.Get(); 2769 } 2770 // Another thread must have loaded the class after we 2771 // started but before we finished. Abandon what we've 2772 // done. 2773 // 2774 // (Yes, this happens.) 2775 2776 return existing; 2777} 2778 2779mirror::Class* ClassLinker::FindPrimitiveClass(char type) { 2780 switch (type) { 2781 case 'B': 2782 return GetClassRoot(kPrimitiveByte); 2783 case 'C': 2784 return GetClassRoot(kPrimitiveChar); 2785 case 'D': 2786 return GetClassRoot(kPrimitiveDouble); 2787 case 'F': 2788 return GetClassRoot(kPrimitiveFloat); 2789 case 'I': 2790 return GetClassRoot(kPrimitiveInt); 2791 case 'J': 2792 return GetClassRoot(kPrimitiveLong); 2793 case 'S': 2794 return GetClassRoot(kPrimitiveShort); 2795 case 'Z': 2796 return GetClassRoot(kPrimitiveBoolean); 2797 case 'V': 2798 return GetClassRoot(kPrimitiveVoid); 2799 default: 2800 break; 2801 } 2802 std::string printable_type(PrintableChar(type)); 2803 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str()); 2804 return NULL; 2805} 2806 2807mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, 2808 size_t hash) { 2809 if (VLOG_IS_ON(class_linker)) { 2810 mirror::DexCache* dex_cache = klass->GetDexCache(); 2811 std::string source; 2812 if (dex_cache != NULL) { 2813 source += " from "; 2814 source += dex_cache->GetLocation()->ToModifiedUtf8(); 2815 } 2816 LOG(INFO) << "Loaded class " << descriptor << source; 2817 } 2818 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2819 mirror::Class* existing = 2820 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash); 2821 if (existing != NULL) { 2822 return existing; 2823 } 2824 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == NULL && 2825 dex_cache_image_class_lookup_required_) { 2826 // Check a class loaded with the system class loader matches one in the image if the class 2827 // is in the image. 2828 existing = LookupClassFromImage(descriptor); 2829 if (existing != NULL) { 2830 CHECK(klass == existing); 2831 } 2832 } 2833 VerifyObject(klass); 2834 class_table_.insert(std::make_pair(hash, klass)); 2835 if (log_new_class_table_roots_) { 2836 new_class_roots_.push_back(std::make_pair(hash, klass)); 2837 } 2838 return NULL; 2839} 2840 2841mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass, 2842 size_t hash) { 2843 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2844 mirror::Class* existing = 2845 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash); 2846 2847 if (existing == nullptr) { 2848 CHECK(klass->IsProxyClass()); 2849 return nullptr; 2850 } 2851 2852 CHECK_NE(existing, klass) << descriptor; 2853 CHECK(!existing->IsResolved()) << descriptor; 2854 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor; 2855 2856 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash; 2857 ++it) { 2858 mirror::Class** root = &it->second; 2859 mirror::Class* klass = ReadBarrier::BarrierForRoot<mirror::Class, kWithReadBarrier>(root); 2860 if (klass == existing) { 2861 class_table_.erase(it); 2862 break; 2863 } 2864 } 2865 2866 CHECK(!klass->IsTemp()) << descriptor; 2867 if (kIsDebugBuild && klass->GetClassLoader() == nullptr && 2868 dex_cache_image_class_lookup_required_) { 2869 // Check a class loaded with the system class loader matches one in the image if the class 2870 // is in the image. 2871 existing = LookupClassFromImage(descriptor); 2872 if (existing != nullptr) { 2873 CHECK(klass == existing) << descriptor; 2874 } 2875 } 2876 VerifyObject(klass); 2877 2878 class_table_.insert(std::make_pair(hash, klass)); 2879 if (log_new_class_table_roots_) { 2880 new_class_roots_.push_back(std::make_pair(hash, klass)); 2881 } 2882 2883 return existing; 2884} 2885 2886bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) { 2887 size_t hash = Hash(descriptor); 2888 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2889 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); 2890 it != end && it->first == hash; 2891 ++it) { 2892 mirror::Class** root = &it->second; 2893 mirror::Class* klass = ReadBarrier::BarrierForRoot<mirror::Class, kWithReadBarrier>(root); 2894 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) { 2895 class_table_.erase(it); 2896 return true; 2897 } 2898 } 2899 return false; 2900} 2901 2902mirror::Class* ClassLinker::LookupClass(const char* descriptor, 2903 const mirror::ClassLoader* class_loader) { 2904 size_t hash = Hash(descriptor); 2905 { 2906 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 2907 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash); 2908 if (result != NULL) { 2909 return result; 2910 } 2911 } 2912 if (class_loader != NULL || !dex_cache_image_class_lookup_required_) { 2913 return NULL; 2914 } else { 2915 // Lookup failed but need to search dex_caches_. 2916 mirror::Class* result = LookupClassFromImage(descriptor); 2917 if (result != NULL) { 2918 InsertClass(descriptor, result, hash); 2919 } else { 2920 // Searching the image dex files/caches failed, we don't want to get into this situation 2921 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image 2922 // classes into the class table. 2923 const int32_t kMaxFailedDexCacheLookups = 1000; 2924 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) { 2925 MoveImageClassesToClassTable(); 2926 } 2927 } 2928 return result; 2929 } 2930} 2931 2932mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor, 2933 const mirror::ClassLoader* class_loader, 2934 size_t hash) { 2935 auto end = class_table_.end(); 2936 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) { 2937 mirror::Class** root = &it->second; 2938 mirror::Class* klass = ReadBarrier::BarrierForRoot<mirror::Class, kWithReadBarrier>(root); 2939 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) { 2940 if (kIsDebugBuild) { 2941 // Check for duplicates in the table. 2942 for (++it; it != end && it->first == hash; ++it) { 2943 mirror::Class** root2 = &it->second; 2944 mirror::Class* klass2 = ReadBarrier::BarrierForRoot<mirror::Class, kWithReadBarrier>(root2); 2945 CHECK(!(klass2->GetClassLoader() == class_loader && 2946 klass2->DescriptorEquals(descriptor))) 2947 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " " 2948 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader(); 2949 } 2950 } 2951 return klass; 2952 } 2953 } 2954 return NULL; 2955} 2956 2957static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches() 2958 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2959 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace(); 2960 CHECK(image != NULL); 2961 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 2962 return root->AsObjectArray<mirror::DexCache>(); 2963} 2964 2965void ClassLinker::MoveImageClassesToClassTable() { 2966 Thread* self = Thread::Current(); 2967 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 2968 if (!dex_cache_image_class_lookup_required_) { 2969 return; // All dex cache classes are already in the class table. 2970 } 2971 const char* old_no_suspend_cause = 2972 self->StartAssertNoThreadSuspension("Moving image classes to class table"); 2973 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 2974 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 2975 mirror::DexCache* dex_cache = dex_caches->Get(i); 2976 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes(); 2977 for (int32_t j = 0; j < types->GetLength(); j++) { 2978 mirror::Class* klass = types->Get(j); 2979 if (klass != NULL) { 2980 DCHECK(klass->GetClassLoader() == NULL); 2981 std::string descriptor = klass->GetDescriptor(); 2982 size_t hash = Hash(descriptor.c_str()); 2983 mirror::Class* existing = LookupClassFromTableLocked(descriptor.c_str(), NULL, hash); 2984 if (existing != NULL) { 2985 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != " 2986 << PrettyClassAndClassLoader(klass); 2987 } else { 2988 class_table_.insert(std::make_pair(hash, klass)); 2989 if (log_new_class_table_roots_) { 2990 new_class_roots_.push_back(std::make_pair(hash, klass)); 2991 } 2992 } 2993 } 2994 } 2995 } 2996 dex_cache_image_class_lookup_required_ = false; 2997 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 2998} 2999 3000mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) { 3001 Thread* self = Thread::Current(); 3002 const char* old_no_suspend_cause = 3003 self->StartAssertNoThreadSuspension("Image class lookup"); 3004 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 3005 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) { 3006 mirror::DexCache* dex_cache = dex_caches->Get(i); 3007 const DexFile* dex_file = dex_cache->GetDexFile(); 3008 // Try binary searching the string/type index. 3009 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor); 3010 if (string_id != NULL) { 3011 const DexFile::TypeId* type_id = 3012 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id)); 3013 if (type_id != NULL) { 3014 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id); 3015 mirror::Class* klass = dex_cache->GetResolvedType(type_idx); 3016 if (klass != NULL) { 3017 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 3018 return klass; 3019 } 3020 } 3021 } 3022 } 3023 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 3024 return NULL; 3025} 3026 3027void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) { 3028 result.clear(); 3029 if (dex_cache_image_class_lookup_required_) { 3030 MoveImageClassesToClassTable(); 3031 } 3032 size_t hash = Hash(descriptor); 3033 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3034 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); 3035 it != end && it->first == hash; ++it) { 3036 mirror::Class** root = &it->second; 3037 mirror::Class* klass = ReadBarrier::BarrierForRoot<mirror::Class, kWithReadBarrier>(root); 3038 if (klass->DescriptorEquals(descriptor)) { 3039 result.push_back(klass); 3040 } 3041 } 3042} 3043 3044void ClassLinker::VerifyClass(Handle<mirror::Class> klass) { 3045 // TODO: assert that the monitor on the Class is held 3046 Thread* self = Thread::Current(); 3047 ObjectLock<mirror::Class> lock(self, klass); 3048 3049 // Don't attempt to re-verify if already sufficiently verified. 3050 if (klass->IsVerified() || 3051 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) { 3052 return; 3053 } 3054 3055 // The class might already be erroneous, for example at compile time if we attempted to verify 3056 // this class as a parent to another. 3057 if (klass->IsErroneous()) { 3058 ThrowEarlierClassFailure(klass.Get()); 3059 return; 3060 } 3061 3062 if (klass->GetStatus() == mirror::Class::kStatusResolved) { 3063 klass->SetStatus(mirror::Class::kStatusVerifying, self); 3064 } else { 3065 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime) 3066 << PrettyClass(klass.Get()); 3067 CHECK(!Runtime::Current()->IsCompiler()); 3068 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self); 3069 } 3070 3071 // Skip verification if disabled. 3072 if (!Runtime::Current()->IsVerificationEnabled()) { 3073 klass->SetStatus(mirror::Class::kStatusVerified, self); 3074 return; 3075 } 3076 3077 // Verify super class. 3078 StackHandleScope<2> hs(self); 3079 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass())); 3080 if (super.Get() != NULL) { 3081 // Acquire lock to prevent races on verifying the super class. 3082 ObjectLock<mirror::Class> lock(self, super); 3083 3084 if (!super->IsVerified() && !super->IsErroneous()) { 3085 VerifyClass(super); 3086 } 3087 if (!super->IsCompileTimeVerified()) { 3088 std::string error_msg( 3089 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s", 3090 PrettyDescriptor(klass.Get()).c_str(), 3091 PrettyDescriptor(super.Get()).c_str())); 3092 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3093 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr))); 3094 if (cause.Get() != nullptr) { 3095 self->ClearException(); 3096 } 3097 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3098 if (cause.Get() != nullptr) { 3099 self->GetException(nullptr)->SetCause(cause.Get()); 3100 } 3101 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex()); 3102 if (Runtime::Current()->IsCompiler()) { 3103 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref); 3104 } 3105 klass->SetStatus(mirror::Class::kStatusError, self); 3106 return; 3107 } 3108 } 3109 3110 // Try to use verification information from the oat file, otherwise do runtime verification. 3111 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile(); 3112 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady); 3113 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status); 3114 if (oat_file_class_status == mirror::Class::kStatusError) { 3115 VLOG(class_linker) << "Skipping runtime verification of erroneous class " 3116 << PrettyDescriptor(klass.Get()) << " in " 3117 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3118 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification", 3119 PrettyDescriptor(klass.Get()).c_str()); 3120 klass->SetStatus(mirror::Class::kStatusError, self); 3121 return; 3122 } 3123 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure; 3124 std::string error_msg; 3125 if (!preverified) { 3126 verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(), 3127 Runtime::Current()->IsCompiler(), 3128 &error_msg); 3129 } 3130 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) { 3131 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) { 3132 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get()) 3133 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3134 << " because: " << error_msg; 3135 } 3136 self->AssertNoPendingException(); 3137 // Make sure all classes referenced by catch blocks are resolved. 3138 ResolveClassExceptionHandlerTypes(dex_file, klass); 3139 if (verifier_failure == verifier::MethodVerifier::kNoFailure) { 3140 // Even though there were no verifier failures we need to respect whether the super-class 3141 // was verified or requiring runtime reverification. 3142 if (super.Get() == NULL || super->IsVerified()) { 3143 klass->SetStatus(mirror::Class::kStatusVerified, self); 3144 } else { 3145 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 3146 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self); 3147 // Pretend a soft failure occured so that we don't consider the class verified below. 3148 verifier_failure = verifier::MethodVerifier::kSoftFailure; 3149 } 3150 } else { 3151 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure); 3152 // Soft failures at compile time should be retried at runtime. Soft 3153 // failures at runtime will be handled by slow paths in the generated 3154 // code. Set status accordingly. 3155 if (Runtime::Current()->IsCompiler()) { 3156 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self); 3157 } else { 3158 klass->SetStatus(mirror::Class::kStatusVerified, self); 3159 } 3160 } 3161 } else { 3162 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get()) 3163 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3164 << " because: " << error_msg; 3165 self->AssertNoPendingException(); 3166 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3167 klass->SetStatus(mirror::Class::kStatusError, self); 3168 } 3169 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) { 3170 // Class is verified so we don't need to do any access check on its methods. 3171 // Let the interpreter know it by setting the kAccPreverified flag onto each 3172 // method. 3173 // Note: we're going here during compilation and at runtime. When we set the 3174 // kAccPreverified flag when compiling image classes, the flag is recorded 3175 // in the image and is set when loading the image. 3176 klass->SetPreverifiedFlagOnAllMethods(); 3177 } 3178} 3179 3180bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass, 3181 mirror::Class::Status& oat_file_class_status) { 3182 // If we're compiling, we can only verify the class using the oat file if 3183 // we are not compiling the image or if the class we're verifying is not part of 3184 // the app. In other words, we will only check for preverification of bootclasspath 3185 // classes. 3186 if (Runtime::Current()->IsCompiler()) { 3187 // Are we compiling the bootclasspath? 3188 if (!Runtime::Current()->UseCompileTimeClassPath()) { 3189 return false; 3190 } 3191 // We are compiling an app (not the image). 3192 3193 // Is this an app class? (I.e. not a bootclasspath class) 3194 if (klass->GetClassLoader() != NULL) { 3195 return false; 3196 } 3197 } 3198 3199 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file); 3200 // Make this work with gtests, which do not set up the image properly. 3201 // TODO: we should clean up gtests to set up the image path properly. 3202 if (Runtime::Current()->IsCompiler() && (oat_file == NULL)) { 3203 return false; 3204 } 3205 3206 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass); 3207 uint dex_location_checksum = dex_file.GetLocationChecksum(); 3208 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(), 3209 &dex_location_checksum); 3210 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass); 3211 uint16_t class_def_index = klass->GetDexClassDefIndex(); 3212 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus(); 3213 if (oat_file_class_status == mirror::Class::kStatusVerified || 3214 oat_file_class_status == mirror::Class::kStatusInitialized) { 3215 return true; 3216 } 3217 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) { 3218 // Compile time verification failed with a soft error. Compile time verification can fail 3219 // because we have incomplete type information. Consider the following: 3220 // class ... { 3221 // Foo x; 3222 // .... () { 3223 // if (...) { 3224 // v1 gets assigned a type of resolved class Foo 3225 // } else { 3226 // v1 gets assigned a type of unresolved class Bar 3227 // } 3228 // iput x = v1 3229 // } } 3230 // when we merge v1 following the if-the-else it results in Conflict 3231 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be 3232 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as 3233 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk 3234 // at compile time). 3235 return false; 3236 } 3237 if (oat_file_class_status == mirror::Class::kStatusError) { 3238 // Compile time verification failed with a hard error. This is caused by invalid instructions 3239 // in the class. These errors are unrecoverable. 3240 return false; 3241 } 3242 if (oat_file_class_status == mirror::Class::kStatusNotReady) { 3243 // Status is uninitialized if we couldn't determine the status at compile time, for example, 3244 // not loading the class. 3245 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy 3246 // isn't a problem and this case shouldn't occur 3247 return false; 3248 } 3249 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status 3250 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " 3251 << klass->GetDescriptor(); 3252 3253 return false; 3254} 3255 3256void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, 3257 Handle<mirror::Class> klass) { 3258 for (size_t i = 0; i < klass->NumDirectMethods(); i++) { 3259 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i)); 3260 } 3261 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) { 3262 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i)); 3263 } 3264} 3265 3266void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, 3267 mirror::ArtMethod* method) { 3268 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod. 3269 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset()); 3270 if (code_item == NULL) { 3271 return; // native or abstract method 3272 } 3273 if (code_item->tries_size_ == 0) { 3274 return; // nothing to process 3275 } 3276 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0); 3277 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 3278 ClassLinker* linker = Runtime::Current()->GetClassLinker(); 3279 for (uint32_t idx = 0; idx < handlers_size; idx++) { 3280 CatchHandlerIterator iterator(handlers_ptr); 3281 for (; iterator.HasNext(); iterator.Next()) { 3282 // Ensure exception types are resolved so that they don't need resolution to be delivered, 3283 // unresolved exception types will be ignored by exception delivery 3284 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) { 3285 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method); 3286 if (exception_type == NULL) { 3287 DCHECK(Thread::Current()->IsExceptionPending()); 3288 Thread::Current()->ClearException(); 3289 } 3290 } 3291 } 3292 handlers_ptr = iterator.EndDataPointer(); 3293 } 3294} 3295 3296static void CheckProxyConstructor(mirror::ArtMethod* constructor); 3297static void CheckProxyMethod(Handle<mirror::ArtMethod> method, 3298 Handle<mirror::ArtMethod> prototype); 3299 3300mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name, 3301 jobjectArray interfaces, jobject loader, 3302 jobjectArray methods, jobjectArray throws) { 3303 Thread* self = soa.Self(); 3304 StackHandleScope<8> hs(self); 3305 Handle<mirror::Class> klass(hs.NewHandle( 3306 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class)))); 3307 if (klass.Get() == NULL) { 3308 CHECK(self->IsExceptionPending()); // OOME. 3309 return NULL; 3310 } 3311 DCHECK(klass->GetClass() != NULL); 3312 klass->SetObjectSize(sizeof(mirror::Proxy)); 3313 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal); 3314 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader)); 3315 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 3316 klass->SetName(soa.Decode<mirror::String*>(name)); 3317 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy); 3318 klass->SetDexCache(proxy_class->GetDexCache()); 3319 klass->SetStatus(mirror::Class::kStatusIdx, self); 3320 3321 // Instance fields are inherited, but we add a couple of static fields... 3322 { 3323 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2); 3324 if (UNLIKELY(sfields == NULL)) { 3325 CHECK(self->IsExceptionPending()); // OOME. 3326 return NULL; 3327 } 3328 klass->SetSFields(sfields); 3329 } 3330 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by 3331 // our proxy, so Class.getInterfaces doesn't return the flattened set. 3332 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self))); 3333 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) { 3334 CHECK(self->IsExceptionPending()); // OOME. 3335 return nullptr; 3336 } 3337 klass->SetStaticField(0, interfaces_sfield.Get()); 3338 interfaces_sfield->SetDexFieldIndex(0); 3339 interfaces_sfield->SetDeclaringClass(klass.Get()); 3340 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 3341 // 2. Create a static field 'throws' that holds exceptions thrown by our methods. 3342 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self))); 3343 if (UNLIKELY(throws_sfield.Get() == nullptr)) { 3344 CHECK(self->IsExceptionPending()); // OOME. 3345 return nullptr; 3346 } 3347 klass->SetStaticField(1, throws_sfield.Get()); 3348 throws_sfield->SetDexFieldIndex(1); 3349 throws_sfield->SetDeclaringClass(klass.Get()); 3350 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 3351 3352 // Proxies have 1 direct method, the constructor 3353 { 3354 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1); 3355 if (UNLIKELY(directs == nullptr)) { 3356 CHECK(self->IsExceptionPending()); // OOME. 3357 return nullptr; 3358 } 3359 klass->SetDirectMethods(directs); 3360 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class); 3361 if (UNLIKELY(constructor == nullptr)) { 3362 CHECK(self->IsExceptionPending()); // OOME. 3363 return nullptr; 3364 } 3365 klass->SetDirectMethod(0, constructor); 3366 } 3367 3368 // Create virtual method using specified prototypes. 3369 size_t num_virtual_methods = 3370 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength(); 3371 { 3372 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self, 3373 num_virtual_methods); 3374 if (UNLIKELY(virtuals == NULL)) { 3375 CHECK(self->IsExceptionPending()); // OOME. 3376 return NULL; 3377 } 3378 klass->SetVirtualMethods(virtuals); 3379 } 3380 for (size_t i = 0; i < num_virtual_methods; ++i) { 3381 StackHandleScope<1> hs(self); 3382 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods = 3383 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods); 3384 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i))); 3385 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype); 3386 if (UNLIKELY(clone == nullptr)) { 3387 CHECK(self->IsExceptionPending()); // OOME. 3388 return nullptr; 3389 } 3390 klass->SetVirtualMethod(i, clone); 3391 } 3392 3393 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy 3394 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state. 3395 self->AssertNoPendingException(); 3396 3397 std::string descriptor(GetDescriptorForProxy(klass.Get())); 3398 mirror::Class* new_class = nullptr; 3399 { 3400 ObjectLock<mirror::Class> resolution_lock(self, klass); // Must hold lock on object when resolved. 3401 // Link the fields and virtual methods, creating vtable and iftables 3402 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces( 3403 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces))); 3404 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) { 3405 klass->SetStatus(mirror::Class::kStatusError, self); 3406 return nullptr; 3407 } 3408 } 3409 3410 CHECK(klass->IsRetired()); 3411 CHECK_NE(klass.Get(), new_class); 3412 klass.Assign(new_class); 3413 3414 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class); 3415 interfaces_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 3416 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class); 3417 throws_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws)); 3418 3419 { 3420 // Lock on klass is released. Lock new class object. 3421 ObjectLock<mirror::Class> initialization_lock(self, klass); 3422 klass->SetStatus(mirror::Class::kStatusInitialized, self); 3423 } 3424 3425 // sanity checks 3426 if (kIsDebugBuild) { 3427 CHECK(klass->GetIFields() == nullptr); 3428 CheckProxyConstructor(klass->GetDirectMethod(0)); 3429 for (size_t i = 0; i < num_virtual_methods; ++i) { 3430 StackHandleScope<2> hs(self); 3431 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods = 3432 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods); 3433 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i))); 3434 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i))); 3435 CheckProxyMethod(virtual_method, prototype); 3436 } 3437 3438 mirror::String* decoded_name = soa.Decode<mirror::String*>(name); 3439 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces", 3440 decoded_name->ToModifiedUtf8().c_str())); 3441 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name); 3442 3443 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws", 3444 decoded_name->ToModifiedUtf8().c_str())); 3445 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name); 3446 3447 CHECK_EQ(klass.Get()->GetInterfaces(), 3448 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 3449 CHECK_EQ(klass.Get()->GetThrows(), 3450 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws)); 3451 } 3452 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str())); 3453 CHECK(existing == nullptr); 3454 return klass.Get(); 3455} 3456 3457std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) { 3458 DCHECK(proxy_class->IsProxyClass()); 3459 mirror::String* name = proxy_class->GetName(); 3460 DCHECK(name != NULL); 3461 return DotToDescriptor(name->ToModifiedUtf8().c_str()); 3462} 3463 3464mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, 3465 mirror::ArtMethod* proxy_method) { 3466 DCHECK(proxy_class->IsProxyClass()); 3467 DCHECK(proxy_method->IsProxyMethod()); 3468 // Locate the dex cache of the original interface/Object 3469 mirror::DexCache* dex_cache = NULL; 3470 { 3471 mirror::ObjectArray<mirror::Class>* resolved_types = proxy_method->GetDexCacheResolvedTypes(); 3472 ReaderMutexLock mu(Thread::Current(), dex_lock_); 3473 for (size_t i = 0; i != dex_caches_.size(); ++i) { 3474 mirror::DexCache* a_dex_cache = GetDexCache(i); 3475 if (a_dex_cache->GetResolvedTypes() == resolved_types) { 3476 dex_cache = a_dex_cache; 3477 break; 3478 } 3479 } 3480 } 3481 CHECK(dex_cache != NULL); 3482 uint32_t method_idx = proxy_method->GetDexMethodIndex(); 3483 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx); 3484 CHECK(resolved_method != NULL); 3485 return resolved_method; 3486} 3487 3488 3489mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self, 3490 Handle<mirror::Class> klass, 3491 mirror::Class* proxy_class) { 3492 // Create constructor for Proxy that must initialize h 3493 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods = 3494 proxy_class->GetDirectMethods(); 3495 CHECK_EQ(proxy_direct_methods->GetLength(), 16); 3496 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2); 3497 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its 3498 // code_ too) 3499 mirror::ArtMethod* constructor = 3500 down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self)); 3501 if (constructor == NULL) { 3502 CHECK(self->IsExceptionPending()); // OOME. 3503 return NULL; 3504 } 3505 // Make this constructor public and fix the class to be our Proxy version 3506 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic); 3507 constructor->SetDeclaringClass(klass.Get()); 3508 return constructor; 3509} 3510 3511static void CheckProxyConstructor(mirror::ArtMethod* constructor) 3512 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3513 CHECK(constructor->IsConstructor()); 3514 CHECK_STREQ(constructor->GetName(), "<init>"); 3515 CHECK_STREQ(constructor->GetSignature().ToString().c_str(), 3516 "(Ljava/lang/reflect/InvocationHandler;)V"); 3517 DCHECK(constructor->IsPublic()); 3518} 3519 3520mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self, 3521 Handle<mirror::Class> klass, 3522 Handle<mirror::ArtMethod> prototype) { 3523 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden 3524 // prototype method 3525 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(), 3526 prototype.Get()); 3527 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize 3528 // as necessary 3529 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self)); 3530 if (UNLIKELY(method == NULL)) { 3531 CHECK(self->IsExceptionPending()); // OOME. 3532 return NULL; 3533 } 3534 3535 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to 3536 // the intersection of throw exceptions as defined in Proxy 3537 method->SetDeclaringClass(klass.Get()); 3538 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal); 3539 3540 // At runtime the method looks like a reference and argument saving method, clone the code 3541 // related parameters from this method. 3542 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler()); 3543 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler()); 3544 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge); 3545 3546 return method; 3547} 3548 3549static void CheckProxyMethod(Handle<mirror::ArtMethod> method, Handle<mirror::ArtMethod> prototype) 3550 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3551 // Basic sanity 3552 CHECK(!prototype->IsFinal()); 3553 CHECK(method->IsFinal()); 3554 CHECK(!method->IsAbstract()); 3555 3556 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its 3557 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself. 3558 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings()); 3559 CHECK_EQ(prototype->GetDexCacheResolvedMethods(), method->GetDexCacheResolvedMethods()); 3560 CHECK_EQ(prototype->GetDexCacheResolvedTypes(), method->GetDexCacheResolvedTypes()); 3561 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex()); 3562 3563 MethodHelper mh(method); 3564 MethodHelper mh2(prototype); 3565 CHECK_STREQ(method->GetName(), prototype->GetName()); 3566 CHECK_STREQ(method->GetShorty(), prototype->GetShorty()); 3567 // More complex sanity - via dex cache 3568 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType()); 3569} 3570 3571static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics, 3572 bool can_init_parents) 3573 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3574 if (can_init_statics && can_init_parents) { 3575 return true; 3576 } 3577 if (!can_init_statics) { 3578 // Check if there's a class initializer. 3579 mirror::ArtMethod* clinit = klass->FindClassInitializer(); 3580 if (clinit != NULL) { 3581 return false; 3582 } 3583 // Check if there are encoded static values needing initialization. 3584 if (klass->NumStaticFields() != 0) { 3585 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 3586 DCHECK(dex_class_def != NULL); 3587 if (dex_class_def->static_values_off_ != 0) { 3588 return false; 3589 } 3590 } 3591 } 3592 if (!klass->IsInterface() && klass->HasSuperClass()) { 3593 mirror::Class* super_class = klass->GetSuperClass(); 3594 if (!can_init_parents && !super_class->IsInitialized()) { 3595 return false; 3596 } else { 3597 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) { 3598 return false; 3599 } 3600 } 3601 } 3602 return true; 3603} 3604 3605bool ClassLinker::IsInitialized() const { 3606 return init_done_; 3607} 3608 3609bool ClassLinker::InitializeClass(Handle<mirror::Class> klass, bool can_init_statics, 3610 bool can_init_parents) { 3611 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol 3612 3613 // Are we already initialized and therefore done? 3614 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as 3615 // an initialized class will never change its state. 3616 if (klass->IsInitialized()) { 3617 return true; 3618 } 3619 3620 // Fast fail if initialization requires a full runtime. Not part of the JLS. 3621 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) { 3622 return false; 3623 } 3624 3625 Thread* self = Thread::Current(); 3626 uint64_t t0; 3627 { 3628 ObjectLock<mirror::Class> lock(self, klass); 3629 3630 // Re-check under the lock in case another thread initialized ahead of us. 3631 if (klass->IsInitialized()) { 3632 return true; 3633 } 3634 3635 // Was the class already found to be erroneous? Done under the lock to match the JLS. 3636 if (klass->IsErroneous()) { 3637 ThrowEarlierClassFailure(klass.Get()); 3638 return false; 3639 } 3640 3641 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus(); 3642 3643 if (!klass->IsVerified()) { 3644 VerifyClass(klass); 3645 if (!klass->IsVerified()) { 3646 // We failed to verify, expect either the klass to be erroneous or verification failed at 3647 // compile time. 3648 if (klass->IsErroneous()) { 3649 CHECK(self->IsExceptionPending()); 3650 } else { 3651 CHECK(Runtime::Current()->IsCompiler()); 3652 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 3653 } 3654 return false; 3655 } 3656 } 3657 3658 // If the class is kStatusInitializing, either this thread is 3659 // initializing higher up the stack or another thread has beat us 3660 // to initializing and we need to wait. Either way, this 3661 // invocation of InitializeClass will not be responsible for 3662 // running <clinit> and will return. 3663 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 3664 // We caught somebody else in the act; was it us? 3665 if (klass->GetClinitThreadId() == self->GetTid()) { 3666 // Yes. That's fine. Return so we can continue initializing. 3667 return true; 3668 } 3669 // No. That's fine. Wait for another thread to finish initializing. 3670 return WaitForInitializeClass(klass, self, lock); 3671 } 3672 3673 if (!ValidateSuperClassDescriptors(klass)) { 3674 klass->SetStatus(mirror::Class::kStatusError, self); 3675 return false; 3676 } 3677 3678 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get()); 3679 3680 // From here out other threads may observe that we're initializing and so changes of state 3681 // require the a notification. 3682 klass->SetClinitThreadId(self->GetTid()); 3683 klass->SetStatus(mirror::Class::kStatusInitializing, self); 3684 3685 t0 = NanoTime(); 3686 } 3687 3688 // Initialize super classes, must be done while initializing for the JLS. 3689 if (!klass->IsInterface() && klass->HasSuperClass()) { 3690 mirror::Class* super_class = klass->GetSuperClass(); 3691 if (!super_class->IsInitialized()) { 3692 CHECK(!super_class->IsInterface()); 3693 CHECK(can_init_parents); 3694 StackHandleScope<1> hs(self); 3695 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class)); 3696 bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true); 3697 if (!super_initialized) { 3698 // The super class was verified ahead of entering initializing, we should only be here if 3699 // the super class became erroneous due to initialization. 3700 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending()) 3701 << "Super class initialization failed for " 3702 << PrettyDescriptor(handle_scope_super.Get()) 3703 << " that has unexpected status " << handle_scope_super->GetStatus() 3704 << "\nPending exception:\n" 3705 << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : ""); 3706 ObjectLock<mirror::Class> lock(self, klass); 3707 // Initialization failed because the super-class is erroneous. 3708 klass->SetStatus(mirror::Class::kStatusError, self); 3709 return false; 3710 } 3711 } 3712 } 3713 3714 if (klass->NumStaticFields() > 0) { 3715 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 3716 CHECK(dex_class_def != NULL); 3717 const DexFile& dex_file = klass->GetDexFile(); 3718 StackHandleScope<2> hs(self); 3719 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader())); 3720 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache())); 3721 EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader, 3722 this, *dex_class_def); 3723 if (it.HasNext()) { 3724 CHECK(can_init_statics); 3725 // We reordered the fields, so we need to be able to map the 3726 // field indexes to the right fields. 3727 SafeMap<uint32_t, mirror::ArtField*> field_map; 3728 ConstructFieldMap(dex_file, *dex_class_def, klass.Get(), field_map); 3729 for (size_t i = 0; it.HasNext(); i++, it.Next()) { 3730 if (Runtime::Current()->IsActiveTransaction()) { 3731 it.ReadValueToField<true>(field_map.Get(i)); 3732 } else { 3733 it.ReadValueToField<false>(field_map.Get(i)); 3734 } 3735 } 3736 } 3737 } 3738 3739 mirror::ArtMethod* clinit = klass->FindClassInitializer(); 3740 if (clinit != NULL) { 3741 CHECK(can_init_statics); 3742 JValue result; 3743 clinit->Invoke(self, NULL, 0, &result, "V"); 3744 } 3745 3746 uint64_t t1 = NanoTime(); 3747 3748 bool success = true; 3749 { 3750 ObjectLock<mirror::Class> lock(self, klass); 3751 3752 if (self->IsExceptionPending()) { 3753 WrapExceptionInInitializer(); 3754 klass->SetStatus(mirror::Class::kStatusError, self); 3755 success = false; 3756 } else { 3757 RuntimeStats* global_stats = Runtime::Current()->GetStats(); 3758 RuntimeStats* thread_stats = self->GetStats(); 3759 ++global_stats->class_init_count; 3760 ++thread_stats->class_init_count; 3761 global_stats->class_init_time_ns += (t1 - t0); 3762 thread_stats->class_init_time_ns += (t1 - t0); 3763 // Set the class as initialized except if failed to initialize static fields. 3764 klass->SetStatus(mirror::Class::kStatusInitialized, self); 3765 if (VLOG_IS_ON(class_linker)) { 3766 LOG(INFO) << "Initialized class " << klass->GetDescriptor() << " from " << 3767 klass->GetLocation(); 3768 } 3769 // Opportunistically set static method trampolines to their destination. 3770 FixupStaticTrampolines(klass.Get()); 3771 } 3772 } 3773 return success; 3774} 3775 3776bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self, 3777 ObjectLock<mirror::Class>& lock) 3778 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3779 while (true) { 3780 self->AssertNoPendingException(); 3781 CHECK(!klass->IsInitialized()); 3782 lock.WaitIgnoringInterrupts(); 3783 3784 // When we wake up, repeat the test for init-in-progress. If 3785 // there's an exception pending (only possible if 3786 // "interruptShouldThrow" was set), bail out. 3787 if (self->IsExceptionPending()) { 3788 WrapExceptionInInitializer(); 3789 klass->SetStatus(mirror::Class::kStatusError, self); 3790 return false; 3791 } 3792 // Spurious wakeup? Go back to waiting. 3793 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 3794 continue; 3795 } 3796 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) { 3797 // Compile time initialization failed. 3798 return false; 3799 } 3800 if (klass->IsErroneous()) { 3801 // The caller wants an exception, but it was thrown in a 3802 // different thread. Synthesize one here. 3803 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread", 3804 PrettyDescriptor(klass.Get()).c_str()); 3805 return false; 3806 } 3807 if (klass->IsInitialized()) { 3808 return true; 3809 } 3810 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is " 3811 << klass->GetStatus(); 3812 } 3813 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get()); 3814} 3815 3816bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) { 3817 if (klass->IsInterface()) { 3818 return true; 3819 } 3820 // Begin with the methods local to the superclass. 3821 StackHandleScope<2> hs(Thread::Current()); 3822 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 3823 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 3824 if (klass->HasSuperClass() && 3825 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) { 3826 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) { 3827 mh.ChangeMethod(klass->GetVTableEntry(i)); 3828 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i)); 3829 if (mh.GetMethod() != super_mh.GetMethod() && 3830 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) { 3831 ThrowLinkageError(klass.Get(), 3832 "Class %s method %s resolves differently in superclass %s", 3833 PrettyDescriptor(klass.Get()).c_str(), 3834 PrettyMethod(mh.GetMethod()).c_str(), 3835 PrettyDescriptor(klass->GetSuperClass()).c_str()); 3836 return false; 3837 } 3838 } 3839 } 3840 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 3841 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) { 3842 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods(); 3843 for (uint32_t j = 0; j < num_methods; ++j) { 3844 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j)); 3845 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j)); 3846 if (mh.GetMethod() != super_mh.GetMethod() && 3847 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) { 3848 ThrowLinkageError(klass.Get(), 3849 "Class %s method %s resolves differently in interface %s", 3850 PrettyDescriptor(klass.Get()).c_str(), 3851 PrettyMethod(mh.GetMethod()).c_str(), 3852 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str()); 3853 return false; 3854 } 3855 } 3856 } 3857 } 3858 return true; 3859} 3860 3861bool ClassLinker::EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields, 3862 bool can_init_parents) { 3863 DCHECK(c.Get() != nullptr); 3864 const bool success = c->IsInitialized() || InitializeClass(c, can_init_fields, can_init_parents); 3865 if (!success && can_init_fields && can_init_parents) { 3866 CHECK(Thread::Current()->IsExceptionPending()) << PrettyClass(c.Get()); 3867 } 3868 return success; 3869} 3870 3871void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def, 3872 mirror::Class* c, 3873 SafeMap<uint32_t, mirror::ArtField*>& field_map) { 3874 const byte* class_data = dex_file.GetClassData(dex_class_def); 3875 ClassDataItemIterator it(dex_file, class_data); 3876 StackHandleScope<2> hs(Thread::Current()); 3877 Handle<mirror::DexCache> dex_cache(hs.NewHandle(c->GetDexCache())); 3878 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader())); 3879 CHECK(!kMovingFields); 3880 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) { 3881 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true)); 3882 } 3883} 3884 3885void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) { 3886 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields(); 3887 if (fields != nullptr) { 3888 for (int index = 0; index < fields->GetLength(); index ++) { 3889 if (fields->Get(index)->GetDeclaringClass() == temp_class) { 3890 fields->Get(index)->SetDeclaringClass(new_class); 3891 } 3892 } 3893 } 3894 3895 fields = new_class->GetSFields(); 3896 if (fields != nullptr) { 3897 for (int index = 0; index < fields->GetLength(); index ++) { 3898 if (fields->Get(index)->GetDeclaringClass() == temp_class) { 3899 fields->Get(index)->SetDeclaringClass(new_class); 3900 } 3901 } 3902 } 3903 3904 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods(); 3905 if (methods != nullptr) { 3906 for (int index = 0; index < methods->GetLength(); index ++) { 3907 if (methods->Get(index)->GetDeclaringClass() == temp_class) { 3908 methods->Get(index)->SetDeclaringClass(new_class); 3909 } 3910 } 3911 } 3912 3913 methods = new_class->GetVirtualMethods(); 3914 if (methods != nullptr) { 3915 for (int index = 0; index < methods->GetLength(); index ++) { 3916 if (methods->Get(index)->GetDeclaringClass() == temp_class) { 3917 methods->Get(index)->SetDeclaringClass(new_class); 3918 } 3919 } 3920 } 3921} 3922 3923bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass, 3924 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 3925 mirror::Class** new_class) { 3926 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 3927 3928 if (!LinkSuperClass(klass)) { 3929 return false; 3930 } 3931 if (!LinkMethods(self, klass, interfaces)) { 3932 return false; 3933 } 3934 if (!LinkInstanceFields(klass)) { 3935 return false; 3936 } 3937 size_t class_size; 3938 if (!LinkStaticFields(klass, &class_size)) { 3939 return false; 3940 } 3941 CreateReferenceInstanceOffsets(klass); 3942 CreateReferenceStaticOffsets(klass); 3943 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 3944 3945 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) { 3946 // We don't need to retire this class as it has no embedded tables or it was created the 3947 // correct size during class linker initialization. 3948 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get()); 3949 3950 if (klass->ShouldHaveEmbeddedImtAndVTable()) { 3951 klass->PopulateEmbeddedImtAndVTable(); 3952 } 3953 3954 // This will notify waiters on klass that saw the not yet resolved 3955 // class in the class_table_ during EnsureResolved. 3956 klass->SetStatus(mirror::Class::kStatusResolved, self); 3957 *new_class = klass.Get(); 3958 } else { 3959 CHECK(!klass->IsResolved()); 3960 // Retire the temporary class and create the correctly sized resolved class. 3961 *new_class = klass->CopyOf(self, class_size); 3962 if (UNLIKELY(*new_class == NULL)) { 3963 CHECK(self->IsExceptionPending()); // Expect an OOME. 3964 klass->SetStatus(mirror::Class::kStatusError, self); 3965 return false; 3966 } 3967 3968 CHECK_EQ((*new_class)->GetClassSize(), class_size); 3969 StackHandleScope<1> hs(self); 3970 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class); 3971 ObjectLock<mirror::Class> lock(self, new_class_h); 3972 3973 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get()); 3974 3975 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor)); 3976 CHECK(existing == NULL || existing == klass.Get()); 3977 3978 // This will notify waiters on temp class that saw the not yet resolved class in the 3979 // class_table_ during EnsureResolved. 3980 klass->SetStatus(mirror::Class::kStatusRetired, self); 3981 3982 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving); 3983 // This will notify waiters on new_class that saw the not yet resolved 3984 // class in the class_table_ during EnsureResolved. 3985 new_class_h->SetStatus(mirror::Class::kStatusResolved, self); 3986 } 3987 return true; 3988} 3989 3990bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) { 3991 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus()); 3992 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex()); 3993 uint16_t super_class_idx = class_def.superclass_idx_; 3994 if (super_class_idx != DexFile::kDexNoIndex16) { 3995 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get()); 3996 if (super_class == NULL) { 3997 DCHECK(Thread::Current()->IsExceptionPending()); 3998 return false; 3999 } 4000 // Verify 4001 if (!klass->CanAccess(super_class)) { 4002 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible", 4003 PrettyDescriptor(super_class).c_str(), 4004 PrettyDescriptor(klass.Get()).c_str()); 4005 return false; 4006 } 4007 CHECK(super_class->IsResolved()); 4008 klass->SetSuperClass(super_class); 4009 } 4010 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def); 4011 if (interfaces != NULL) { 4012 for (size_t i = 0; i < interfaces->Size(); i++) { 4013 uint16_t idx = interfaces->GetTypeItem(i).type_idx_; 4014 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get()); 4015 if (interface == NULL) { 4016 DCHECK(Thread::Current()->IsExceptionPending()); 4017 return false; 4018 } 4019 // Verify 4020 if (!klass->CanAccess(interface)) { 4021 // TODO: the RI seemed to ignore this in my testing. 4022 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible", 4023 PrettyDescriptor(interface).c_str(), 4024 PrettyDescriptor(klass.Get()).c_str()); 4025 return false; 4026 } 4027 } 4028 } 4029 // Mark the class as loaded. 4030 klass->SetStatus(mirror::Class::kStatusLoaded, NULL); 4031 return true; 4032} 4033 4034bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) { 4035 CHECK(!klass->IsPrimitive()); 4036 mirror::Class* super = klass->GetSuperClass(); 4037 if (klass.Get() == GetClassRoot(kJavaLangObject)) { 4038 if (super != NULL) { 4039 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass"); 4040 return false; 4041 } 4042 return true; 4043 } 4044 if (super == NULL) { 4045 ThrowLinkageError(klass.Get(), "No superclass defined for class %s", 4046 PrettyDescriptor(klass.Get()).c_str()); 4047 return false; 4048 } 4049 // Verify 4050 if (super->IsFinal() || super->IsInterface()) { 4051 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s", 4052 PrettyDescriptor(super).c_str(), 4053 PrettyDescriptor(klass.Get()).c_str(), 4054 super->IsFinal() ? "declared final" : "an interface"); 4055 return false; 4056 } 4057 if (!klass->CanAccess(super)) { 4058 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s", 4059 PrettyDescriptor(super).c_str(), 4060 PrettyDescriptor(klass.Get()).c_str()); 4061 return false; 4062 } 4063 4064 // Inherit kAccClassIsFinalizable from the superclass in case this 4065 // class doesn't override finalize. 4066 if (super->IsFinalizable()) { 4067 klass->SetFinalizable(); 4068 } 4069 4070 // Inherit reference flags (if any) from the superclass. 4071 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask); 4072 if (reference_flags != 0) { 4073 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags); 4074 } 4075 // Disallow custom direct subclasses of java.lang.ref.Reference. 4076 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) { 4077 ThrowLinkageError(klass.Get(), 4078 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed", 4079 PrettyDescriptor(klass.Get()).c_str()); 4080 return false; 4081 } 4082 4083 if (kIsDebugBuild) { 4084 // Ensure super classes are fully resolved prior to resolving fields.. 4085 while (super != NULL) { 4086 CHECK(super->IsResolved()); 4087 super = super->GetSuperClass(); 4088 } 4089 } 4090 return true; 4091} 4092 4093// Populate the class vtable and itable. Compute return type indices. 4094bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass, 4095 Handle<mirror::ObjectArray<mirror::Class>> interfaces) { 4096 if (klass->IsInterface()) { 4097 // No vtable. 4098 size_t count = klass->NumVirtualMethods(); 4099 if (!IsUint(16, count)) { 4100 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count); 4101 return false; 4102 } 4103 for (size_t i = 0; i < count; ++i) { 4104 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i); 4105 } 4106 // Link interface method tables 4107 return LinkInterfaceMethods(klass, interfaces); 4108 } else { 4109 // Link virtual and interface method tables 4110 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces); 4111 } 4112 return true; 4113} 4114 4115bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) { 4116 if (klass->HasSuperClass()) { 4117 uint32_t max_count = klass->NumVirtualMethods() + 4118 klass->GetSuperClass()->GetVTableLength(); 4119 size_t actual_count = klass->GetSuperClass()->GetVTableLength(); 4120 CHECK_LE(actual_count, max_count); 4121 StackHandleScope<3> hs(self); 4122 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable; 4123 mirror::Class* super_class = klass->GetSuperClass(); 4124 if (super_class->ShouldHaveEmbeddedImtAndVTable()) { 4125 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count)); 4126 if (UNLIKELY(vtable.Get() == nullptr)) { 4127 CHECK(self->IsExceptionPending()); // OOME. 4128 return false; 4129 } 4130 int len = super_class->GetVTableLength(); 4131 for (int i = 0; i < len; i++) { 4132 vtable->Set<false>(i, super_class->GetVTableEntry(i)); 4133 } 4134 } else { 4135 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class); 4136 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count)); 4137 if (UNLIKELY(vtable.Get() == nullptr)) { 4138 CHECK(self->IsExceptionPending()); // OOME. 4139 return false; 4140 } 4141 } 4142 4143 // See if any of our virtual methods override the superclass. 4144 MethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4145 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4146 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) { 4147 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i); 4148 local_mh.ChangeMethod(local_method); 4149 size_t j = 0; 4150 for (; j < actual_count; ++j) { 4151 mirror::ArtMethod* super_method = vtable->Get(j); 4152 super_mh.ChangeMethod(super_method); 4153 if (local_mh.HasSameNameAndSignature(&super_mh)) { 4154 if (klass->CanAccessMember(super_method->GetDeclaringClass(), 4155 super_method->GetAccessFlags())) { 4156 if (super_method->IsFinal()) { 4157 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s", 4158 PrettyMethod(local_method).c_str(), 4159 super_method->GetDeclaringClassDescriptor()); 4160 return false; 4161 } 4162 vtable->Set<false>(j, local_method); 4163 local_method->SetMethodIndex(j); 4164 break; 4165 } else { 4166 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method) 4167 << " would have incorrectly overridden the package-private method in " 4168 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor()); 4169 } 4170 } 4171 } 4172 if (j == actual_count) { 4173 // Not overriding, append. 4174 vtable->Set<false>(actual_count, local_method); 4175 local_method->SetMethodIndex(actual_count); 4176 actual_count += 1; 4177 } 4178 } 4179 if (!IsUint(16, actual_count)) { 4180 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count); 4181 return false; 4182 } 4183 // Shrink vtable if possible 4184 CHECK_LE(actual_count, max_count); 4185 if (actual_count < max_count) { 4186 vtable.Assign(vtable->CopyOf(self, actual_count)); 4187 if (UNLIKELY(vtable.Get() == NULL)) { 4188 CHECK(self->IsExceptionPending()); // OOME. 4189 return false; 4190 } 4191 } 4192 klass->SetVTable(vtable.Get()); 4193 } else { 4194 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject)); 4195 uint32_t num_virtual_methods = klass->NumVirtualMethods(); 4196 if (!IsUint(16, num_virtual_methods)) { 4197 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods); 4198 return false; 4199 } 4200 StackHandleScope<1> hs(self); 4201 Handle<mirror::ObjectArray<mirror::ArtMethod>> 4202 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods))); 4203 if (UNLIKELY(vtable.Get() == NULL)) { 4204 CHECK(self->IsExceptionPending()); // OOME. 4205 return false; 4206 } 4207 for (size_t i = 0; i < num_virtual_methods; ++i) { 4208 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i); 4209 vtable->Set<false>(i, virtual_method); 4210 virtual_method->SetMethodIndex(i & 0xFFFF); 4211 } 4212 klass->SetVTable(vtable.Get()); 4213 } 4214 return true; 4215} 4216 4217bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass, 4218 Handle<mirror::ObjectArray<mirror::Class>> interfaces) { 4219 Thread* const self = Thread::Current(); 4220 Runtime* const runtime = Runtime::Current(); 4221 // Set the imt table to be all conflicts by default. 4222 klass->SetImTable(runtime->GetDefaultImt()); 4223 size_t super_ifcount; 4224 if (klass->HasSuperClass()) { 4225 super_ifcount = klass->GetSuperClass()->GetIfTableCount(); 4226 } else { 4227 super_ifcount = 0; 4228 } 4229 uint32_t num_interfaces = 4230 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength(); 4231 size_t ifcount = super_ifcount + num_interfaces; 4232 for (size_t i = 0; i < num_interfaces; i++) { 4233 mirror::Class* interface = 4234 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) : 4235 interfaces->Get(i); 4236 ifcount += interface->GetIfTableCount(); 4237 } 4238 if (ifcount == 0) { 4239 // Class implements no interfaces. 4240 DCHECK_EQ(klass->GetIfTableCount(), 0); 4241 DCHECK(klass->GetIfTable() == NULL); 4242 return true; 4243 } 4244 if (ifcount == super_ifcount) { 4245 // Class implements same interfaces as parent, are any of these not marker interfaces? 4246 bool has_non_marker_interface = false; 4247 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 4248 for (size_t i = 0; i < ifcount; ++i) { 4249 if (super_iftable->GetMethodArrayCount(i) > 0) { 4250 has_non_marker_interface = true; 4251 break; 4252 } 4253 } 4254 if (!has_non_marker_interface) { 4255 // Class just inherits marker interfaces from parent so recycle parent's iftable. 4256 klass->SetIfTable(super_iftable); 4257 return true; 4258 } 4259 } 4260 StackHandleScope<4> hs(self); 4261 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount))); 4262 if (UNLIKELY(iftable.Get() == NULL)) { 4263 CHECK(self->IsExceptionPending()); // OOME. 4264 return false; 4265 } 4266 if (super_ifcount != 0) { 4267 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 4268 for (size_t i = 0; i < super_ifcount; i++) { 4269 mirror::Class* super_interface = super_iftable->GetInterface(i); 4270 iftable->SetInterface(i, super_interface); 4271 } 4272 } 4273 // Flatten the interface inheritance hierarchy. 4274 size_t idx = super_ifcount; 4275 for (size_t i = 0; i < num_interfaces; i++) { 4276 mirror::Class* interface = 4277 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) : 4278 interfaces->Get(i); 4279 DCHECK(interface != NULL); 4280 if (!interface->IsInterface()) { 4281 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s", 4282 PrettyDescriptor(klass.Get()).c_str(), 4283 PrettyDescriptor(interface->GetDescriptor()).c_str()); 4284 return false; 4285 } 4286 // Check if interface is already in iftable 4287 bool duplicate = false; 4288 for (size_t j = 0; j < idx; j++) { 4289 mirror::Class* existing_interface = iftable->GetInterface(j); 4290 if (existing_interface == interface) { 4291 duplicate = true; 4292 break; 4293 } 4294 } 4295 if (!duplicate) { 4296 // Add this non-duplicate interface. 4297 iftable->SetInterface(idx++, interface); 4298 // Add this interface's non-duplicate super-interfaces. 4299 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) { 4300 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j); 4301 bool super_duplicate = false; 4302 for (size_t k = 0; k < idx; k++) { 4303 mirror::Class* existing_interface = iftable->GetInterface(k); 4304 if (existing_interface == super_interface) { 4305 super_duplicate = true; 4306 break; 4307 } 4308 } 4309 if (!super_duplicate) { 4310 iftable->SetInterface(idx++, super_interface); 4311 } 4312 } 4313 } 4314 } 4315 // Shrink iftable in case duplicates were found 4316 if (idx < ifcount) { 4317 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax))); 4318 if (UNLIKELY(iftable.Get() == NULL)) { 4319 CHECK(self->IsExceptionPending()); // OOME. 4320 return false; 4321 } 4322 ifcount = idx; 4323 } else { 4324 CHECK_EQ(idx, ifcount); 4325 } 4326 klass->SetIfTable(iftable.Get()); 4327 4328 // If we're an interface, we don't need the vtable pointers, so we're done. 4329 if (klass->IsInterface()) { 4330 return true; 4331 } 4332 // Allocate imtable 4333 bool imtable_changed = false; 4334 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable( 4335 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize))); 4336 if (UNLIKELY(imtable.Get() == NULL)) { 4337 CHECK(self->IsExceptionPending()); // OOME. 4338 return false; 4339 } 4340 MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4341 MethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4342 std::vector<mirror::ArtMethod*> miranda_list; 4343 for (size_t i = 0; i < ifcount; ++i) { 4344 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods(); 4345 if (num_methods > 0) { 4346 StackHandleScope<2> hs(self); 4347 Handle<mirror::ObjectArray<mirror::ArtMethod>> 4348 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods))); 4349 if (UNLIKELY(method_array.Get() == nullptr)) { 4350 CHECK(self->IsExceptionPending()); // OOME. 4351 return false; 4352 } 4353 iftable->SetMethodArray(i, method_array.Get()); 4354 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable( 4355 hs.NewHandle(klass->GetVTableDuringLinking())); 4356 for (size_t j = 0; j < num_methods; ++j) { 4357 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j); 4358 interface_mh.ChangeMethod(interface_method); 4359 int32_t k; 4360 // For each method listed in the interface's method list, find the 4361 // matching method in our class's method list. We want to favor the 4362 // subclass over the superclass, which just requires walking 4363 // back from the end of the vtable. (This only matters if the 4364 // superclass defines a private method and this class redefines 4365 // it -- otherwise it would use the same vtable slot. In .dex files 4366 // those don't end up in the virtual method table, so it shouldn't 4367 // matter which direction we go. We walk it backward anyway.) 4368 for (k = vtable->GetLength() - 1; k >= 0; --k) { 4369 mirror::ArtMethod* vtable_method = vtable->Get(k); 4370 vtable_mh.ChangeMethod(vtable_method); 4371 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) { 4372 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) { 4373 ThrowIllegalAccessError( 4374 klass.Get(), 4375 "Method '%s' implementing interface method '%s' is not public", 4376 PrettyMethod(vtable_method).c_str(), 4377 PrettyMethod(interface_method).c_str()); 4378 return false; 4379 } 4380 method_array->Set<false>(j, vtable_method); 4381 // Place method in imt if entry is empty, place conflict otherwise. 4382 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize; 4383 if (imtable->Get(imt_index) == NULL) { 4384 imtable->Set<false>(imt_index, vtable_method); 4385 imtable_changed = true; 4386 } else { 4387 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod()); 4388 } 4389 break; 4390 } 4391 } 4392 if (k < 0) { 4393 StackHandleScope<1> hs(self); 4394 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr); 4395 for (mirror::ArtMethod* mir_method : miranda_list) { 4396 vtable_mh.ChangeMethod(mir_method); 4397 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) { 4398 miranda_method.Assign(mir_method); 4399 break; 4400 } 4401 } 4402 if (miranda_method.Get() == NULL) { 4403 // Point the interface table at a phantom slot. 4404 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_method->Clone(self))); 4405 if (UNLIKELY(miranda_method.Get() == NULL)) { 4406 CHECK(self->IsExceptionPending()); // OOME. 4407 return false; 4408 } 4409 // TODO: If a methods move then the miranda_list may hold stale references. 4410 miranda_list.push_back(miranda_method.Get()); 4411 } 4412 method_array->Set<false>(j, miranda_method.Get()); 4413 } 4414 } 4415 } 4416 } 4417 if (imtable_changed) { 4418 // Fill in empty entries in interface method table with conflict. 4419 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod(); 4420 for (size_t i = 0; i < mirror::Class::kImtSize; i++) { 4421 if (imtable->Get(i) == NULL) { 4422 imtable->Set<false>(i, imt_conflict_method); 4423 } 4424 } 4425 klass->SetImTable(imtable.Get()); 4426 } 4427 if (!miranda_list.empty()) { 4428 int old_method_count = klass->NumVirtualMethods(); 4429 int new_method_count = old_method_count + miranda_list.size(); 4430 mirror::ObjectArray<mirror::ArtMethod>* virtuals; 4431 if (old_method_count == 0) { 4432 virtuals = AllocArtMethodArray(self, new_method_count); 4433 } else { 4434 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count); 4435 } 4436 if (UNLIKELY(virtuals == NULL)) { 4437 CHECK(self->IsExceptionPending()); // OOME. 4438 return false; 4439 } 4440 klass->SetVirtualMethods(virtuals); 4441 4442 StackHandleScope<1> hs(self); 4443 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable( 4444 hs.NewHandle(klass->GetVTableDuringLinking())); 4445 CHECK(vtable.Get() != NULL); 4446 int old_vtable_count = vtable->GetLength(); 4447 int new_vtable_count = old_vtable_count + miranda_list.size(); 4448 vtable.Assign(vtable->CopyOf(self, new_vtable_count)); 4449 if (UNLIKELY(vtable.Get() == NULL)) { 4450 CHECK(self->IsExceptionPending()); // OOME. 4451 return false; 4452 } 4453 for (size_t i = 0; i < miranda_list.size(); ++i) { 4454 mirror::ArtMethod* method = miranda_list[i]; 4455 // Leave the declaring class alone as type indices are relative to it 4456 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda); 4457 method->SetMethodIndex(0xFFFF & (old_vtable_count + i)); 4458 klass->SetVirtualMethod(old_method_count + i, method); 4459 vtable->Set<false>(old_vtable_count + i, method); 4460 } 4461 // TODO: do not assign to the vtable field until it is fully constructed. 4462 klass->SetVTable(vtable.Get()); 4463 } 4464 4465 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking(); 4466 for (int i = 0; i < vtable->GetLength(); ++i) { 4467 CHECK(vtable->Get(i) != NULL); 4468 } 4469 4470// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail); 4471 4472 return true; 4473} 4474 4475bool ClassLinker::LinkInstanceFields(Handle<mirror::Class> klass) { 4476 CHECK(klass.Get() != NULL); 4477 return LinkFields(klass, false, nullptr); 4478} 4479 4480bool ClassLinker::LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size) { 4481 CHECK(klass.Get() != NULL); 4482 return LinkFields(klass, true, class_size); 4483} 4484 4485struct LinkFieldsComparator { 4486 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4487 } 4488 // No thread safety analysis as will be called from STL. Checked lock held in constructor. 4489 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2) 4490 NO_THREAD_SAFETY_ANALYSIS { 4491 // First come reference fields, then 64-bit, and finally 32-bit 4492 Primitive::Type type1 = field1->GetTypeAsPrimitiveType(); 4493 Primitive::Type type2 = field2->GetTypeAsPrimitiveType(); 4494 if (type1 != type2) { 4495 bool is_primitive1 = type1 != Primitive::kPrimNot; 4496 bool is_primitive2 = type2 != Primitive::kPrimNot; 4497 bool is64bit1 = is_primitive1 && (type1 == Primitive::kPrimLong || 4498 type1 == Primitive::kPrimDouble); 4499 bool is64bit2 = is_primitive2 && (type2 == Primitive::kPrimLong || 4500 type2 == Primitive::kPrimDouble); 4501 int order1 = !is_primitive1 ? 0 : (is64bit1 ? 1 : 2); 4502 int order2 = !is_primitive2 ? 0 : (is64bit2 ? 1 : 2); 4503 if (order1 != order2) { 4504 return order1 < order2; 4505 } 4506 } 4507 // same basic group? then sort by string. 4508 return strcmp(field1->GetName(), field2->GetName()) < 0; 4509 } 4510}; 4511 4512bool ClassLinker::LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size) { 4513 size_t num_fields = 4514 is_static ? klass->NumStaticFields() : klass->NumInstanceFields(); 4515 4516 mirror::ObjectArray<mirror::ArtField>* fields = 4517 is_static ? klass->GetSFields() : klass->GetIFields(); 4518 4519 // Initialize field_offset 4520 MemberOffset field_offset(0); 4521 if (is_static) { 4522 uint32_t base = sizeof(mirror::Class); // Static fields come after the class. 4523 if (klass->ShouldHaveEmbeddedImtAndVTable()) { 4524 // Static fields come after the embedded tables. 4525 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(), 4526 0, 0, 0); 4527 } 4528 field_offset = MemberOffset(base); 4529 } else { 4530 mirror::Class* super_class = klass->GetSuperClass(); 4531 if (super_class != NULL) { 4532 CHECK(super_class->IsResolved()) 4533 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class); 4534 field_offset = MemberOffset(super_class->GetObjectSize()); 4535 } 4536 } 4537 4538 CHECK_EQ(num_fields == 0, fields == NULL) << PrettyClass(klass.Get()); 4539 4540 // we want a relatively stable order so that adding new fields 4541 // minimizes disruption of C++ version such as Class and Method. 4542 std::deque<mirror::ArtField*> grouped_and_sorted_fields; 4543 for (size_t i = 0; i < num_fields; i++) { 4544 mirror::ArtField* f = fields->Get(i); 4545 CHECK(f != NULL) << PrettyClass(klass.Get()); 4546 grouped_and_sorted_fields.push_back(f); 4547 } 4548 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(), 4549 LinkFieldsComparator()); 4550 4551 // References should be at the front. 4552 size_t current_field = 0; 4553 size_t num_reference_fields = 0; 4554 for (; current_field < num_fields; current_field++) { 4555 mirror::ArtField* field = grouped_and_sorted_fields.front(); 4556 Primitive::Type type = field->GetTypeAsPrimitiveType(); 4557 bool isPrimitive = type != Primitive::kPrimNot; 4558 if (isPrimitive) { 4559 break; // past last reference, move on to the next phase 4560 } 4561 grouped_and_sorted_fields.pop_front(); 4562 num_reference_fields++; 4563 fields->Set<false>(current_field, field); 4564 field->SetOffset(field_offset); 4565 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t)); 4566 } 4567 4568 // Now we want to pack all of the double-wide fields together. If 4569 // we're not aligned, though, we want to shuffle one 32-bit field 4570 // into place. If we can't find one, we'll have to pad it. 4571 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) { 4572 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) { 4573 mirror::ArtField* field = grouped_and_sorted_fields[i]; 4574 Primitive::Type type = field->GetTypeAsPrimitiveType(); 4575 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types 4576 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) { 4577 continue; 4578 } 4579 fields->Set<false>(current_field++, field); 4580 field->SetOffset(field_offset); 4581 // drop the consumed field 4582 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i); 4583 break; 4584 } 4585 // whether we found a 32-bit field for padding or not, we advance 4586 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t)); 4587 } 4588 4589 // Alignment is good, shuffle any double-wide fields forward, and 4590 // finish assigning field offsets to all fields. 4591 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value())) 4592 << PrettyClass(klass.Get()); 4593 while (!grouped_and_sorted_fields.empty()) { 4594 mirror::ArtField* field = grouped_and_sorted_fields.front(); 4595 grouped_and_sorted_fields.pop_front(); 4596 Primitive::Type type = field->GetTypeAsPrimitiveType(); 4597 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types 4598 fields->Set<false>(current_field, field); 4599 field->SetOffset(field_offset); 4600 field_offset = MemberOffset(field_offset.Uint32Value() + 4601 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble) 4602 ? sizeof(uint64_t) 4603 : sizeof(uint32_t))); 4604 current_field++; 4605 } 4606 4607 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it. 4608 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) { 4609 // We know there are no non-reference fields in the Reference classes, and we know 4610 // that 'referent' is alphabetically last, so this is easy... 4611 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get()); 4612 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get()); 4613 --num_reference_fields; 4614 } 4615 4616 if (kIsDebugBuild) { 4617 // Make sure that all reference fields appear before 4618 // non-reference fields, and all double-wide fields are aligned. 4619 bool seen_non_ref = false; 4620 for (size_t i = 0; i < num_fields; i++) { 4621 mirror::ArtField* field = fields->Get(i); 4622 if (false) { // enable to debug field layout 4623 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance") 4624 << " class=" << PrettyClass(klass.Get()) 4625 << " field=" << PrettyField(field) 4626 << " offset=" 4627 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset())); 4628 } 4629 Primitive::Type type = field->GetTypeAsPrimitiveType(); 4630 bool is_primitive = type != Primitive::kPrimNot; 4631 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") && 4632 strcmp("referent", field->GetName()) == 0) { 4633 is_primitive = true; // We lied above, so we have to expect a lie here. 4634 } 4635 if (is_primitive) { 4636 if (!seen_non_ref) { 4637 seen_non_ref = true; 4638 DCHECK_EQ(num_reference_fields, i) << PrettyField(field); 4639 } 4640 } else { 4641 DCHECK(!seen_non_ref) << PrettyField(field); 4642 } 4643 } 4644 if (!seen_non_ref) { 4645 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get()); 4646 } 4647 } 4648 4649 size_t size = field_offset.Uint32Value(); 4650 // Update klass 4651 if (is_static) { 4652 klass->SetNumReferenceStaticFields(num_reference_fields); 4653 *class_size = size; 4654 } else { 4655 klass->SetNumReferenceInstanceFields(num_reference_fields); 4656 if (!klass->IsVariableSize()) { 4657 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(); 4658 size_t previous_size = klass->GetObjectSize(); 4659 if (previous_size != 0) { 4660 // Make sure that we didn't originally have an incorrect size. 4661 CHECK_EQ(previous_size, size) << klass->GetDescriptor(); 4662 } 4663 klass->SetObjectSize(size); 4664 } 4665 } 4666 return true; 4667} 4668 4669// Set the bitmap of reference offsets, refOffsets, from the ifields 4670// list. 4671void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) { 4672 uint32_t reference_offsets = 0; 4673 mirror::Class* super_class = klass->GetSuperClass(); 4674 if (super_class != NULL) { 4675 reference_offsets = super_class->GetReferenceInstanceOffsets(); 4676 // If our superclass overflowed, we don't stand a chance. 4677 if (reference_offsets == CLASS_WALK_SUPER) { 4678 klass->SetReferenceInstanceOffsets(reference_offsets); 4679 return; 4680 } 4681 } 4682 CreateReferenceOffsets(klass, false, reference_offsets); 4683} 4684 4685void ClassLinker::CreateReferenceStaticOffsets(Handle<mirror::Class> klass) { 4686 CreateReferenceOffsets(klass, true, 0); 4687} 4688 4689void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static, 4690 uint32_t reference_offsets) { 4691 size_t num_reference_fields = 4692 is_static ? klass->NumReferenceStaticFieldsDuringLinking() 4693 : klass->NumReferenceInstanceFieldsDuringLinking(); 4694 mirror::ObjectArray<mirror::ArtField>* fields = 4695 is_static ? klass->GetSFields() : klass->GetIFields(); 4696 // All of the fields that contain object references are guaranteed 4697 // to be at the beginning of the fields list. 4698 for (size_t i = 0; i < num_reference_fields; ++i) { 4699 // Note that byte_offset is the offset from the beginning of 4700 // object, not the offset into instance data 4701 mirror::ArtField* field = fields->Get(i); 4702 MemberOffset byte_offset = field->GetOffsetDuringLinking(); 4703 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U); 4704 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) { 4705 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value()); 4706 CHECK_NE(new_bit, 0U); 4707 reference_offsets |= new_bit; 4708 } else { 4709 reference_offsets = CLASS_WALK_SUPER; 4710 break; 4711 } 4712 } 4713 // Update fields in klass 4714 if (is_static) { 4715 klass->SetReferenceStaticOffsets(reference_offsets); 4716 } else { 4717 klass->SetReferenceInstanceOffsets(reference_offsets); 4718 } 4719} 4720 4721mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx, 4722 Handle<mirror::DexCache> dex_cache) { 4723 DCHECK(dex_cache.Get() != nullptr); 4724 mirror::String* resolved = dex_cache->GetResolvedString(string_idx); 4725 if (resolved != NULL) { 4726 return resolved; 4727 } 4728 uint32_t utf16_length; 4729 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length); 4730 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data); 4731 dex_cache->SetResolvedString(string_idx, string); 4732 return string; 4733} 4734 4735mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx, 4736 mirror::Class* referrer) { 4737 StackHandleScope<2> hs(Thread::Current()); 4738 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache())); 4739 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader())); 4740 return ResolveType(dex_file, type_idx, dex_cache, class_loader); 4741} 4742 4743mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx, 4744 Handle<mirror::DexCache> dex_cache, 4745 Handle<mirror::ClassLoader> class_loader) { 4746 DCHECK(dex_cache.Get() != NULL); 4747 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx); 4748 if (resolved == NULL) { 4749 Thread* self = Thread::Current(); 4750 const char* descriptor = dex_file.StringByTypeIdx(type_idx); 4751 resolved = FindClass(self, descriptor, class_loader); 4752 if (resolved != NULL) { 4753 // TODO: we used to throw here if resolved's class loader was not the 4754 // boot class loader. This was to permit different classes with the 4755 // same name to be loaded simultaneously by different loaders 4756 dex_cache->SetResolvedType(type_idx, resolved); 4757 } else { 4758 CHECK(self->IsExceptionPending()) 4759 << "Expected pending exception for failed resolution of: " << descriptor; 4760 // Convert a ClassNotFoundException to a NoClassDefFoundError. 4761 StackHandleScope<1> hs(self); 4762 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr))); 4763 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) { 4764 DCHECK(resolved == NULL); // No Handle needed to preserve resolved. 4765 self->ClearException(); 4766 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor); 4767 self->GetException(NULL)->SetCause(cause.Get()); 4768 } 4769 } 4770 } 4771 DCHECK((resolved == NULL) || resolved->IsResolved() || resolved->IsErroneous()) 4772 << PrettyDescriptor(resolved) << " " << resolved->GetStatus(); 4773 return resolved; 4774} 4775 4776mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx, 4777 Handle<mirror::DexCache> dex_cache, 4778 Handle<mirror::ClassLoader> class_loader, 4779 Handle<mirror::ArtMethod> referrer, 4780 InvokeType type) { 4781 DCHECK(dex_cache.Get() != NULL); 4782 // Check for hit in the dex cache. 4783 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx); 4784 if (resolved != nullptr && !resolved->IsRuntimeMethod()) { 4785 return resolved; 4786 } 4787 // Fail, get the declaring class. 4788 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 4789 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader); 4790 if (klass == NULL) { 4791 DCHECK(Thread::Current()->IsExceptionPending()); 4792 return NULL; 4793 } 4794 // Scan using method_idx, this saves string compares but will only hit for matching dex 4795 // caches/files. 4796 switch (type) { 4797 case kDirect: // Fall-through. 4798 case kStatic: 4799 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx); 4800 break; 4801 case kInterface: 4802 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx); 4803 DCHECK(resolved == NULL || resolved->GetDeclaringClass()->IsInterface()); 4804 break; 4805 case kSuper: // Fall-through. 4806 case kVirtual: 4807 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx); 4808 break; 4809 default: 4810 LOG(FATAL) << "Unreachable - invocation type: " << type; 4811 } 4812 if (resolved == NULL) { 4813 // Search by name, which works across dex files. 4814 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 4815 const Signature signature = dex_file.GetMethodSignature(method_id); 4816 switch (type) { 4817 case kDirect: // Fall-through. 4818 case kStatic: 4819 resolved = klass->FindDirectMethod(name, signature); 4820 break; 4821 case kInterface: 4822 resolved = klass->FindInterfaceMethod(name, signature); 4823 DCHECK(resolved == NULL || resolved->GetDeclaringClass()->IsInterface()); 4824 break; 4825 case kSuper: // Fall-through. 4826 case kVirtual: 4827 resolved = klass->FindVirtualMethod(name, signature); 4828 break; 4829 } 4830 } 4831 if (resolved != NULL) { 4832 // We found a method, check for incompatible class changes. 4833 if (resolved->CheckIncompatibleClassChange(type)) { 4834 resolved = NULL; 4835 } 4836 } 4837 if (resolved != NULL) { 4838 // Be a good citizen and update the dex cache to speed subsequent calls. 4839 dex_cache->SetResolvedMethod(method_idx, resolved); 4840 return resolved; 4841 } else { 4842 // We failed to find the method which means either an access error, an incompatible class 4843 // change, or no such method. First try to find the method among direct and virtual methods. 4844 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 4845 const Signature signature = dex_file.GetMethodSignature(method_id); 4846 switch (type) { 4847 case kDirect: 4848 case kStatic: 4849 resolved = klass->FindVirtualMethod(name, signature); 4850 break; 4851 case kInterface: 4852 case kVirtual: 4853 case kSuper: 4854 resolved = klass->FindDirectMethod(name, signature); 4855 break; 4856 } 4857 4858 // If we found something, check that it can be accessed by the referrer. 4859 if (resolved != NULL && referrer.Get() != NULL) { 4860 mirror::Class* methods_class = resolved->GetDeclaringClass(); 4861 mirror::Class* referring_class = referrer->GetDeclaringClass(); 4862 if (!referring_class->CanAccess(methods_class)) { 4863 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class, 4864 resolved, type); 4865 return NULL; 4866 } else if (!referring_class->CanAccessMember(methods_class, 4867 resolved->GetAccessFlags())) { 4868 ThrowIllegalAccessErrorMethod(referring_class, resolved); 4869 return NULL; 4870 } 4871 } 4872 4873 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface 4874 // methods and throw if we find the method there. If we find nothing, throw a NoSuchMethodError. 4875 switch (type) { 4876 case kDirect: 4877 case kStatic: 4878 if (resolved != NULL) { 4879 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get()); 4880 } else { 4881 resolved = klass->FindInterfaceMethod(name, signature); 4882 if (resolved != NULL) { 4883 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get()); 4884 } else { 4885 ThrowNoSuchMethodError(type, klass, name, signature); 4886 } 4887 } 4888 break; 4889 case kInterface: 4890 if (resolved != NULL) { 4891 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get()); 4892 } else { 4893 resolved = klass->FindVirtualMethod(name, signature); 4894 if (resolved != NULL) { 4895 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get()); 4896 } else { 4897 ThrowNoSuchMethodError(type, klass, name, signature); 4898 } 4899 } 4900 break; 4901 case kSuper: 4902 ThrowNoSuchMethodError(type, klass, name, signature); 4903 break; 4904 case kVirtual: 4905 if (resolved != NULL) { 4906 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get()); 4907 } else { 4908 resolved = klass->FindInterfaceMethod(name, signature); 4909 if (resolved != NULL) { 4910 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get()); 4911 } else { 4912 ThrowNoSuchMethodError(type, klass, name, signature); 4913 } 4914 } 4915 break; 4916 } 4917 DCHECK(Thread::Current()->IsExceptionPending()); 4918 return NULL; 4919 } 4920} 4921 4922mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx, 4923 Handle<mirror::DexCache> dex_cache, 4924 Handle<mirror::ClassLoader> class_loader, 4925 bool is_static) { 4926 DCHECK(dex_cache.Get() != nullptr); 4927 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx); 4928 if (resolved != NULL) { 4929 return resolved; 4930 } 4931 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 4932 Thread* const self = Thread::Current(); 4933 StackHandleScope<1> hs(self); 4934 Handle<mirror::Class> klass( 4935 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 4936 if (klass.Get() == NULL) { 4937 DCHECK(Thread::Current()->IsExceptionPending()); 4938 return NULL; 4939 } 4940 4941 if (is_static) { 4942 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx); 4943 } else { 4944 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx); 4945 } 4946 4947 if (resolved == NULL) { 4948 const char* name = dex_file.GetFieldName(field_id); 4949 const char* type = dex_file.GetFieldTypeDescriptor(field_id); 4950 if (is_static) { 4951 resolved = mirror::Class::FindStaticField(self, klass, name, type); 4952 } else { 4953 resolved = klass->FindInstanceField(name, type); 4954 } 4955 if (resolved == NULL) { 4956 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name); 4957 return NULL; 4958 } 4959 } 4960 dex_cache->SetResolvedField(field_idx, resolved); 4961 return resolved; 4962} 4963 4964mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, 4965 uint32_t field_idx, 4966 Handle<mirror::DexCache> dex_cache, 4967 Handle<mirror::ClassLoader> class_loader) { 4968 DCHECK(dex_cache.Get() != nullptr); 4969 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx); 4970 if (resolved != NULL) { 4971 return resolved; 4972 } 4973 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 4974 Thread* self = Thread::Current(); 4975 StackHandleScope<1> hs(self); 4976 Handle<mirror::Class> klass( 4977 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 4978 if (klass.Get() == NULL) { 4979 DCHECK(Thread::Current()->IsExceptionPending()); 4980 return NULL; 4981 } 4982 4983 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_)); 4984 StringPiece type(dex_file.StringDataByIdx( 4985 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_)); 4986 resolved = mirror::Class::FindField(self, klass, name, type); 4987 if (resolved != NULL) { 4988 dex_cache->SetResolvedField(field_idx, resolved); 4989 } else { 4990 ThrowNoSuchFieldError("", klass.Get(), type, name); 4991 } 4992 return resolved; 4993} 4994 4995const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer, 4996 uint32_t* length) { 4997 mirror::Class* declaring_class = referrer->GetDeclaringClass(); 4998 mirror::DexCache* dex_cache = declaring_class->GetDexCache(); 4999 const DexFile& dex_file = *dex_cache->GetDexFile(); 5000 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 5001 return dex_file.GetMethodShorty(method_id, length); 5002} 5003 5004void ClassLinker::DumpAllClasses(int flags) { 5005 if (dex_cache_image_class_lookup_required_) { 5006 MoveImageClassesToClassTable(); 5007 } 5008 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker 5009 // lock held, because it might need to resolve a field's type, which would try to take the lock. 5010 std::vector<mirror::Class*> all_classes; 5011 { 5012 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5013 for (std::pair<const size_t, mirror::Class*>& it : class_table_) { 5014 mirror::Class** root = &it.second; 5015 mirror::Class* klass = ReadBarrier::BarrierForRoot<mirror::Class, kWithReadBarrier>(root); 5016 all_classes.push_back(klass); 5017 } 5018 } 5019 5020 for (size_t i = 0; i < all_classes.size(); ++i) { 5021 all_classes[i]->DumpClass(std::cerr, flags); 5022 } 5023} 5024 5025void ClassLinker::DumpForSigQuit(std::ostream& os) { 5026 if (dex_cache_image_class_lookup_required_) { 5027 MoveImageClassesToClassTable(); 5028 } 5029 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5030 os << "Loaded classes: " << class_table_.size() << " allocated classes\n"; 5031} 5032 5033size_t ClassLinker::NumLoadedClasses() { 5034 if (dex_cache_image_class_lookup_required_) { 5035 MoveImageClassesToClassTable(); 5036 } 5037 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5038 return class_table_.size(); 5039} 5040 5041pid_t ClassLinker::GetClassesLockOwner() { 5042 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid(); 5043} 5044 5045pid_t ClassLinker::GetDexLockOwner() { 5046 return dex_lock_.GetExclusiveOwnerTid(); 5047} 5048 5049void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) { 5050 DCHECK(!init_done_); 5051 5052 DCHECK(klass != NULL); 5053 DCHECK(klass->GetClassLoader() == NULL); 5054 5055 mirror::ObjectArray<mirror::Class>* class_roots = 5056 ReadBarrier::BarrierForRoot<mirror::ObjectArray<mirror::Class>, kWithReadBarrier>( 5057 &class_roots_); 5058 DCHECK(class_roots != NULL); 5059 DCHECK(class_roots->Get(class_root) == NULL); 5060 class_roots->Set<false>(class_root, klass); 5061} 5062 5063} // namespace art 5064