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