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