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