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