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