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