blob: 89b425fee85ecc4696cb5722c462f8e651d24e88 [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07006#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07009#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070010#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070011#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070012#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070013#include "dex_verifier.h"
14#include "heap.h"
15#include "logging.h"
16#include "monitor.h"
17#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070018#include "runtime.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070019#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070020#include "thread.h"
21#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070022
23namespace art {
24
Brian Carlstroma663ea52011-08-19 23:33:41 -070025const char* ClassLinker::class_roots_descriptors_[kClassRootsMax] = {
26 "Ljava/lang/Class;",
27 "Ljava/lang/Object;",
28 "[Ljava/lang/Object;",
29 "Ljava/lang/String;",
30 "Ljava/lang/reflect/Field;",
31 "Ljava/lang/reflect/Method;",
32 "Ljava/lang/ClassLoader;",
33 "Ldalvik/system/BaseDexClassLoader;",
34 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070035 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070036 "Z",
37 "B",
38 "C",
39 "D",
40 "F",
41 "I",
42 "J",
43 "S",
44 "V",
45 "[Z",
46 "[B",
47 "[C",
48 "[D",
49 "[F",
50 "[I",
51 "[J",
52 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070053 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070054};
55
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070056ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path, Space* space) {
Elliott Hughes90a33692011-08-30 13:27:07 -070057 UniquePtr<ClassLinker> class_linker(new ClassLinker);
Brian Carlstroma663ea52011-08-19 23:33:41 -070058 if (space == NULL) {
59 class_linker->Init(boot_class_path);
60 } else {
61 class_linker->Init(boot_class_path, space);
62 }
Carl Shapiro61e019d2011-07-14 16:53:09 -070063 // TODO: check for failure during initialization
64 return class_linker.release();
65}
66
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070067ClassLinker::ClassLinker()
68 : classes_lock_(Mutex::Create("ClassLinker::Lock")),
69 class_roots_(NULL),
70 init_done_(false) {
71}
Brian Carlstroma663ea52011-08-19 23:33:41 -070072
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070073void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070074 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070075
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070076 // java_lang_Class comes first, its needed for AllocClass
Brian Carlstrom4873d462011-08-21 15:23:39 -070077 Class* java_lang_Class = down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070078 CHECK(java_lang_Class != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -070079 java_lang_Class->class_size_ = sizeof(ClassClass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070080 java_lang_Class->klass_ = java_lang_Class;
81 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -070082
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070083 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -070084 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070085 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070086 // backfill Object as the super class of Class
87 java_lang_Class->super_class_ = java_lang_Object;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070088 // mark as non-primitive for object_array_class
89 java_lang_Object->primitive_type_ = Class::kPrimNot;
Brian Carlstroma0808032011-07-18 00:39:23 -070090
Elliott Hughesc1674ed2011-08-25 18:09:09 -070091 // Object[] is for DexCache and int[] is for various Class members.
Brian Carlstrom4873d462011-08-21 15:23:39 -070092 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070093 CHECK(object_array_class != NULL);
Brian Carlstromb63ec392011-08-27 17:38:27 -070094 object_array_class->array_rank_ = 1;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070095 object_array_class->component_type_ = java_lang_Object;
Elliott Hughesc1674ed2011-08-25 18:09:09 -070096 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
97 CHECK(int_array_class != NULL);
Brian Carlstromb63ec392011-08-27 17:38:27 -070098 int_array_class->array_rank_ = 1;
Elliott Hughesc1674ed2011-08-25 18:09:09 -070099 IntArray::SetArrayClass(int_array_class);
Brian Carlstroma0808032011-07-18 00:39:23 -0700100
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700101 // String and char[] are necessary so that FindClass can assign names to members
Brian Carlstrom4873d462011-08-21 15:23:39 -0700102 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
Jesse Wilson14150742011-07-29 19:04:44 -0400103 CHECK(java_lang_String != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700104 CHECK_LT(java_lang_String->object_size_, sizeof(String));
Jesse Wilson14150742011-07-29 19:04:44 -0400105 java_lang_String->object_size_ = sizeof(String);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700106 String::SetClass(java_lang_String);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700107 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Jesse Wilson8989d992011-08-02 13:39:42 -0700108 CHECK(char_array_class != NULL);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700109 char_array_class->array_rank_ = 1;
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700110 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700111 // Now String::Alloc* can be used
112
113 // backfill Class descriptors missing until this point
114 java_lang_Class->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/Class;");
115 java_lang_Object->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/Object;");
116 object_array_class->descriptor_ = String::AllocFromModifiedUtf8("[Ljava/lang/Object;");
117 java_lang_String->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/String;");
118 char_array_class->descriptor_ = String::AllocFromModifiedUtf8("[C");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700119 int_array_class->descriptor_ = String::AllocFromModifiedUtf8("[I");
Jesse Wilson14150742011-07-29 19:04:44 -0400120
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700121 // Field and Method are necessary so that FindClass can link members
Brian Carlstrom4873d462011-08-21 15:23:39 -0700122 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700123 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700124 java_lang_reflect_Field->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/reflect/Field;");
Jesse Wilson35baaab2011-08-10 16:18:03 -0400125 CHECK_LT(java_lang_reflect_Field->object_size_, sizeof(Field));
126 java_lang_reflect_Field->object_size_ = sizeof(Field);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700127 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700128 java_lang_reflect_Method->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700129 CHECK(java_lang_reflect_Method != NULL);
130 CHECK_LT(java_lang_reflect_Method->object_size_, sizeof(Method));
131 java_lang_reflect_Method->object_size_ = sizeof(Method);
132
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700133 // create storage for root classes, save away our work so far
134 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700135 SetClassRoot(kJavaLangClass, java_lang_Class);
136 SetClassRoot(kJavaLangObject, java_lang_Object);
137 SetClassRoot(kObjectArrayClass, object_array_class);
138 SetClassRoot(kJavaLangString, java_lang_String);
139 SetClassRoot(kCharArrayClass, char_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700140 SetClassRoot(kIntArrayClass, int_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700141 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
142 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700143 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700144
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700145 // setup boot_class_path_ now that we can use AllocObjectArray to
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700146 // create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700147 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700148 const DexFile* dex_file = boot_class_path[i];
149 CHECK(dex_file != NULL);
150 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700151 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700152 // now we can use FindSystemClass, at least for non-arrays classes.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700153
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700154 // run Class, Field, and Method through FindSystemClass.
155 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700156 // we also override their object_size_ values to accommodate the extra C++ fields.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700157 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700158 CHECK_EQ(java_lang_Class, Class_class);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700159 CHECK_LT(java_lang_Class->object_size_, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700160 java_lang_Class->object_size_ = sizeof(Class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700161 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700162 CHECK_EQ(java_lang_reflect_Field, Field_class);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400163 CHECK_LT(java_lang_reflect_Field->object_size_, sizeof(Field));
164 java_lang_reflect_Field->object_size_ = sizeof(Field);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700165 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700166 CHECK_EQ(java_lang_reflect_Method, Method_class);
167 CHECK_LT(java_lang_reflect_Method->object_size_, sizeof(Method));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700168 java_lang_reflect_Method->object_size_ = sizeof(Method);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700169
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700170 // Object and String just need more minimal setup, since they do not have extra C++ fields.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700171 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700172 CHECK_EQ(java_lang_Object, Object_class);
173 CHECK_EQ(java_lang_Object->object_size_, sizeof(Object));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700174 Class* String_class = FindSystemClass("Ljava/lang/String;");
Jesse Wilsonf7e85a52011-08-01 18:45:58 -0700175 CHECK_EQ(java_lang_String, String_class);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700176 CHECK_EQ(java_lang_String->object_size_, sizeof(String));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700177
178 // Setup the ClassLoaders, adjusting the object_size_ as necessary
179 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
180 CHECK(java_lang_ClassLoader != NULL);
181 CHECK_LT(java_lang_ClassLoader->object_size_, sizeof(ClassLoader));
182 java_lang_ClassLoader->object_size_ = sizeof(ClassLoader);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700183 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700184 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
185 CHECK(dalvik_system_BaseDexClassLoader != NULL);
186 CHECK_EQ(dalvik_system_BaseDexClassLoader->object_size_, sizeof(BaseDexClassLoader));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700187 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700188 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
189 CHECK(dalvik_system_PathClassLoader != NULL);
190 CHECK_EQ(dalvik_system_PathClassLoader->object_size_, sizeof(PathClassLoader));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700191 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700192 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700193
194 // Setup a single, global copy of "interfaces" and "iftable" for
195 // reuse across array classes
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700196 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700197 CHECK(java_lang_Cloneable != NULL);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700198 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700199 CHECK(java_io_Serializable != NULL);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700200
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700201 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700202 CHECK(array_interfaces_ != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700203 array_interfaces_->Set(0, java_lang_Cloneable);
204 array_interfaces_->Set(1, java_io_Serializable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700205
206 // We assume that Cloneable/Serializable don't have superinterfaces --
207 // normally we'd have to crawl up and explicitly list all of the
208 // supers as well. These interfaces don't have any methods, so we
209 // don't have to worry about the ifviPool either.
210 array_iftable_ = new InterfaceEntry[2];
Brian Carlstrom30b94452011-08-25 21:35:26 -0700211 array_iftable_[0].SetInterface(array_interfaces_->Get(0));
212 array_iftable_[1].SetInterface(array_interfaces_->Get(1));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700213 // now FindClass can be used for non-primitive array classes
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700214
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700215 // run Object[] through FindClass to complete initialization
Jesse Wilson8989d992011-08-02 13:39:42 -0700216 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
217 CHECK_EQ(object_array_class, found_object_array_class);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700218 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
219 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700220
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700221 // Setup the primitive type classes.
Brian Carlstroma663ea52011-08-19 23:33:41 -0700222 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z"));
223 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B"));
224 SetClassRoot(kPrimitiveChar, CreatePrimitiveClass("C"));
225 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D"));
226 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F"));
227 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I"));
228 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J"));
229 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S"));
230 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V"));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700231 // now we can use FindSystemClass for anything, including for "[C"
232
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700233 // run char[] and int[] through FindClass to complete initialization
Jesse Wilson8989d992011-08-02 13:39:42 -0700234 Class* found_char_array_class = FindSystemClass("[C");
235 CHECK_EQ(char_array_class, found_char_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700236 Class* found_int_array_class = FindSystemClass("[I");
237 CHECK_EQ(int_array_class, found_int_array_class);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700238
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700239 // Initialize all the other primitive array types for PrimitiveArray::Alloc.
240 // These are easy because everything we need has already been set up.
Brian Carlstroma663ea52011-08-19 23:33:41 -0700241 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
242 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
243 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
244 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
Brian Carlstrom4873d462011-08-21 15:23:39 -0700245 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700246 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700247 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
248 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
249 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
250 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Brian Carlstrom4873d462011-08-21 15:23:39 -0700251 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700252 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700253
254 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
255 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
256 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
257 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
258 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
259 java_lang_ref_FinalizerReference->access_flags_ |= kAccClassIsReference | kAccClassIsFinalizerReference;
260 java_lang_ref_PhantomReference->access_flags_ |= kAccClassIsReference | kAccClassIsPhantomReference;
261 java_lang_ref_SoftReference->access_flags_ |= kAccClassIsReference;
262 java_lang_ref_WeakReference->access_flags_ |= kAccClassIsReference | kAccClassIsWeakReference;
263
264 // Let the heap know some key offsets into java.lang.ref instances
265 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
266 Field* referent = java_lang_ref_Reference->FindDeclaredInstanceField(
267 "referent", "Ljava/lang/Object;");
268 Field* queue = java_lang_ref_Reference->FindDeclaredInstanceField(
269 "queue", "Ljava/lang/ref/ReferenceQueue;");
270 Field* queueNext = java_lang_ref_Reference->FindDeclaredInstanceField(
271 "queueNext", "Ljava/lang/ref/Reference;");
272 Field* pendingNext = java_lang_ref_Reference->FindDeclaredInstanceField(
273 "pendingNext", "Ljava/lang/ref/Reference;");
274 Field* zombie = java_lang_ref_FinalizerReference->FindDeclaredInstanceField(
275 "zombie", "Ljava/lang/Object;");
276 Heap::SetReferenceOffsets(referent->GetOffset(),
277 queue->GetOffset(),
278 queueNext->GetOffset(),
279 pendingNext->GetOffset(),
280 zombie->GetOffset());
281
282 // Optimization for quick stack trace allocation
283 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
284 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700285 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700286
Brian Carlstroma663ea52011-08-19 23:33:41 -0700287 FinishInit();
288}
289
290void ClassLinker::FinishInit() {
291 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700292 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700293 ClassRoot class_root = static_cast<ClassRoot>(i);
294 Class* klass = GetClassRoot(class_root);
295 CHECK(klass != NULL);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700296 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->dex_cache_ != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700297 // note SetClassRoot does additional validation.
298 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700299 }
300
301 // disable the slow paths in FindClass and CreatePrimitiveClass now
302 // that Object, Class, and Object[] are setup
303 init_done_ = true;
304}
305
Brian Carlstroma663ea52011-08-19 23:33:41 -0700306struct ClassLinker::InitCallbackState {
307 ClassLinker* class_linker;
308
309 Class* class_roots[kClassRootsMax];
310
311 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
312 Table descriptor_to_class_root;
313
314 struct DexCacheHash {
315 size_t operator()(art::DexCache* const& obj) const {
316 return reinterpret_cast<size_t>(&obj);
317 }
318 };
319 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
320 Set dex_caches;
321};
322
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700323void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path, Space* space) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700324 CHECK(!init_done_);
325
326 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
327 DCHECK(heap_bitmap != NULL);
328
329 InitCallbackState state;
330 state.class_linker = this;
331 for (size_t i = 0; i < kClassRootsMax; i++) {
332 ClassRoot class_root = static_cast<ClassRoot>(i);
333 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
334 }
335
336 // reinit clases_ table
337 heap_bitmap->Walk(InitCallback, &state);
338
339 // reinit class_roots_
340 Class* object_array_class = state.class_roots[kObjectArrayClass];
341 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
342 for (size_t i = 0; i < kClassRootsMax; i++) {
343 ClassRoot class_root = static_cast<ClassRoot>(i);
344 SetClassRoot(class_root, state.class_roots[class_root]);
345 }
346
347 // reinit intern_table_
348 ObjectArray<Object>* interned_array = space->GetImageHeader().GetInternedArray();
349 for (int32_t i = 0; i < interned_array->GetLength(); i++) {
350 String* string = interned_array->Get(i)->AsString();
351 intern_table_.Register(string);
352 }
353
354 // reinit array_interfaces_ from any array class instance, they should all be ==
355 array_interfaces_ = GetClassRoot(kObjectArrayClass)->interfaces_;
356 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->interfaces_);
357
358 // build a map from location to DexCache to match up with DexFile::GetLocation
359 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
360 typedef InitCallbackState::Set::const_iterator It; // TODO: C++0x auto
361 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
362 DexCache* dex_cache = *it;
363 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
364 location_to_dex_cache[location] = dex_cache;
365 }
366
367 // reinit boot_class_path with DexFile arguments and found DexCaches
368 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700369 const DexFile* dex_file = boot_class_path[i];
370 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700371 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700372 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700373 }
374
375 String::SetClass(GetClassRoot(kJavaLangString));
376 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
377 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
378 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
379 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
380 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
381 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
382 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
383 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700384 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700385 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700386
387 FinishInit();
388}
389
Brian Carlstrom4873d462011-08-21 15:23:39 -0700390void ClassLinker::InitCallback(Object* obj, void *arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700391 DCHECK(obj != NULL);
392 DCHECK(arg != NULL);
393 InitCallbackState* state = reinterpret_cast<InitCallbackState*>(arg);
394
395 if (!obj->IsClass()) {
396 return;
397 }
398 Class* klass = obj->AsClass();
399 CHECK(klass->class_loader_ == NULL);
400
401 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
402
403 // restore class to ClassLinker::classes_ table
404 state->class_linker->InsertClass(descriptor, klass);
405
406 // note DexCache to match with DexFile later
407 DexCache* dex_cache = klass->GetDexCache();
408 if (dex_cache != NULL) {
409 state->dex_caches.insert(dex_cache);
410 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700411 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700412 }
413
414 // check if this is a root, if so, register it
415 typedef InitCallbackState::Table::const_iterator It; // TODO: C++0x auto
416 It it = state->descriptor_to_class_root.find(descriptor);
417 if (it != state->descriptor_to_class_root.end()) {
418 ClassRoot class_root = it->second;
419 state->class_roots[class_root] = klass;
420 }
421}
422
423// Keep in sync with InitCallback. Anything we visit, we need to
424// reinit references to when reinitializing a ClassLinker from a
425// mapped image.
426void ClassLinker::VisitRoots(Heap::RootVistor* root_visitor, void* arg) const {
427
Brian Carlstromb88e9442011-07-28 15:15:51 -0700428 root_visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700429
430 for (size_t i = 0; i < dex_caches_.size(); i++) {
Brian Carlstromb88e9442011-07-28 15:15:51 -0700431 root_visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700432 }
433
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700434 {
435 MutexLock mu(classes_lock_);
436 typedef Table::const_iterator It; // TODO: C++0x auto
437 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
438 root_visitor(it->second, arg);
439 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700440 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700441
442 intern_table_.VisitRoots(root_visitor, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700443
Brian Carlstromb88e9442011-07-28 15:15:51 -0700444 root_visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700445}
446
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700447ClassLinker::~ClassLinker() {
448 delete classes_lock_;
449 String::ResetClass();
450 BooleanArray::ResetArrayClass();
451 ByteArray::ResetArrayClass();
452 CharArray::ResetArrayClass();
453 DoubleArray::ResetArrayClass();
454 FloatArray::ResetArrayClass();
455 IntArray::ResetArrayClass();
456 LongArray::ResetArrayClass();
457 ShortArray::ResetArrayClass();
458 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700459 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700460}
461
462DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700463 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700464 dex_cache->Init(String::AllocFromModifiedUtf8(dex_file.GetLocation().c_str()),
465 AllocObjectArray<String>(dex_file.NumStringIds()),
466 AllocObjectArray<Class>(dex_file.NumTypeIds()),
467 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700468 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700469 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
470 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700471 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700472}
473
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700474CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
475 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700476}
477
Brian Carlstrom4873d462011-08-21 15:23:39 -0700478Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
479 DCHECK_GE(class_size, sizeof(Class));
480 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
481 klass->class_size_ = class_size;
482 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700483}
484
Brian Carlstrom4873d462011-08-21 15:23:39 -0700485Class* ClassLinker::AllocClass(size_t class_size) {
486 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700487}
488
Jesse Wilson35baaab2011-08-10 16:18:03 -0400489Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700490 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700491}
492
493Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700494 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700495}
496
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700497ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
498 return ObjectArray<StackTraceElement>::Alloc(
499 GetClassRoot(kJavaLangStackTraceElementArrayClass),
500 length);
501}
502
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700503Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700504 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700505 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700506 if (class_loader != NULL) {
507 Class* klass = FindClass(descriptor, NULL);
508 if (klass != NULL) {
509 return klass;
510 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700511 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700512 }
513
Carl Shapirob5573532011-07-12 18:22:59 -0700514 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700515 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700516 CHECK(!self->IsExceptionPending());
517 // Find the class in the loaded classes table.
518 Class* klass = LookupClass(descriptor, class_loader);
519 if (klass == NULL) {
520 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700521 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700522 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700523 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700524 const DexFile::ClassPath& class_path = ((class_loader != NULL)
525 ? ClassLoader::GetClassPath(class_loader)
526 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700527 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700528 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700529 std::string name(PrintableString(descriptor));
530 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
531 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700532 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700533 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700534 const DexFile& dex_file = *pair.first;
535 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700536 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700537 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700538 if (!init_done_) {
539 // finish up init of hand crafted class_roots_
540 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700541 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700542 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700543 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400544 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700545 klass = GetClassRoot(kJavaLangString);
546 } else if (descriptor == "Ljava/lang/reflect/Field;") {
547 klass = GetClassRoot(kJavaLangReflectField);
548 } else if (descriptor == "Ljava/lang/reflect/Method;") {
549 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700551 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700552 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700553 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700554 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700555 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700556 klass->dex_cache_ = dex_cache;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700557 LoadClass(dex_file, dex_class_def, klass, class_loader);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700558 // Check for a pending exception during load
559 if (self->IsExceptionPending()) {
560 // TODO: free native allocations in klass
561 return NULL;
562 }
563 {
564 ObjectLock lock(klass);
Carl Shapirob5573532011-07-12 18:22:59 -0700565 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700566 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700567 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700568 if (!success) {
569 // We may fail to insert if we raced with another thread.
570 klass->clinit_thread_id_ = 0;
571 // TODO: free native allocations in klass
572 klass = LookupClass(descriptor, class_loader);
573 CHECK(klass != NULL);
574 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700575 // Finish loading (if necessary) by finding parents
576 if (!klass->IsLoaded() && !LoadSuperAndInterfaces(klass, dex_file)) {
577 // Loading failed.
578 // TODO: CHECK(self->IsExceptionPending());
579 lock.NotifyAll();
580 return NULL;
581 }
582 CHECK(klass->IsLoaded());
583 // Link the class (if necessary)
584 if (!klass->IsLinked() && !LinkClass(klass, dex_file)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700585 // Linking failed.
586 // TODO: CHECK(self->IsExceptionPending());
587 lock.NotifyAll();
588 return NULL;
589 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700590 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700591 }
592 }
593 }
594 // Link the class if it has not already been linked.
595 if (!klass->IsLinked() && !klass->IsErroneous()) {
596 ObjectLock lock(klass);
597 // Check for circular dependencies between classes.
Carl Shapirob5573532011-07-12 18:22:59 -0700598 if (!klass->IsLinked() && klass->clinit_thread_id_ == self->GetId()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700599 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700600 return NULL;
601 }
602 // Wait for the pending initialization to complete.
603 while (!klass->IsLinked() && !klass->IsErroneous()) {
604 lock.Wait();
605 }
606 }
607 if (klass->IsErroneous()) {
608 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
609 return NULL;
610 }
611 // Return the loaded class. No exceptions should be pending.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700612 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700613 CHECK(!self->IsExceptionPending());
614 return klass;
615}
616
Brian Carlstrom4873d462011-08-21 15:23:39 -0700617// Precomputes size that will be needed for Class, matching LinkStaticFields
618size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
619 const DexFile::ClassDef& dex_class_def) {
620 const byte* class_data = dex_file.GetClassData(dex_class_def);
621 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
622 size_t num_static_fields = header.static_fields_size_;
623 size_t num_ref = 0;
624 size_t num_32 = 0;
625 size_t num_64 = 0;
626 if (num_static_fields != 0) {
627 uint32_t last_idx = 0;
628 for (size_t i = 0; i < num_static_fields; ++i) {
629 DexFile::Field dex_field;
630 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
631 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
632 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
633 char c = descriptor[0];
634 if (c == 'L' || c == '[') {
635 num_ref++;
636 } else if (c == 'J' || c == 'D') {
637 num_64++;
638 } else {
639 num_32++;
640 }
641 }
642 }
643
644 // start with generic class data
645 size_t size = sizeof(Class);
646 // follow with reference fields which must be contiguous at start
647 size += (num_ref * sizeof(uint32_t));
648 // if there are 64-bit fields to add, make sure they are aligned
649 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
650 if (num_32 != 0) {
651 // use an available 32-bit field for padding
652 num_32--;
653 }
654 size += sizeof(uint32_t); // either way, we are adding a word
655 DCHECK_EQ(size, RoundUp(size, 8));
656 }
657 // tack on any 64-bit fields now that alignment is assured
658 size += (num_64 * sizeof(uint64_t));
659 // tack on any remaining 32-bit fields
660 size += (num_32 * sizeof(uint32_t));
661 return size;
662}
663
Brian Carlstromf615a612011-07-23 12:50:34 -0700664void ClassLinker::LoadClass(const DexFile& dex_file,
665 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700666 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700667 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700668 CHECK(klass != NULL);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700669 CHECK(klass->dex_cache_ != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700670 CHECK_EQ(Class::kStatusNotReady, klass->status_);
Brian Carlstromf615a612011-07-23 12:50:34 -0700671 const byte* class_data = dex_file.GetClassData(dex_class_def);
672 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700673
Brian Carlstromf615a612011-07-23 12:50:34 -0700674 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700675 CHECK(descriptor != NULL);
676
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700677 klass->klass_ = GetClassRoot(kJavaLangClass);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700678 klass->descriptor_ = String::AllocFromModifiedUtf8(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -0700679 klass->access_flags_ = dex_class_def.access_flags_;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700680 klass->class_loader_ = class_loader;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700681 klass->primitive_type_ = Class::kPrimNot;
682 klass->status_ = Class::kStatusIdx;
683
Brian Carlstrom1f870082011-08-23 16:02:11 -0700684 // Make sure the aren't any "bonus" flags set, since we use them for runtime state.
685 CHECK_EQ(klass->access_flags_ & ~kAccClassFlagsMask, 0U);
686
Brian Carlstrom934486c2011-07-12 23:42:50 -0700687 klass->super_class_ = NULL;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700688 klass->super_class_type_idx_ = dex_class_def.superclass_idx_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700689
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700690 size_t num_static_fields = header.static_fields_size_;
691 size_t num_instance_fields = header.instance_fields_size_;
692 size_t num_direct_methods = header.direct_methods_size_;
693 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700694
Brian Carlstromf615a612011-07-23 12:50:34 -0700695 klass->source_file_ = dex_file.dexGetSourceFile(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700696
697 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700698 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700699
700 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700701 DCHECK(klass->sfields_ == NULL);
702 if (num_static_fields != 0) {
Jesse Wilson35baaab2011-08-10 16:18:03 -0400703 klass->sfields_ = AllocObjectArray<Field>(num_static_fields);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700704 uint32_t last_idx = 0;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700705 for (size_t i = 0; i < klass->NumStaticFields(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700706 DexFile::Field dex_field;
707 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400708 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700709 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700710 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700711 }
712 }
713
714 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700715 DCHECK(klass->ifields_ == NULL);
716 if (num_instance_fields != 0) {
Jesse Wilson35baaab2011-08-10 16:18:03 -0400717 klass->ifields_ = AllocObjectArray<Field>(num_instance_fields);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700718 uint32_t last_idx = 0;
719 for (size_t i = 0; i < klass->NumInstanceFields(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700720 DexFile::Field dex_field;
721 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400722 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700723 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700724 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700725 }
726 }
727
728 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700729 DCHECK(klass->direct_methods_ == NULL);
730 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700731 // TODO: append direct methods to class object
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700732 klass->direct_methods_ = AllocObjectArray<Method>(num_direct_methods);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700733 uint32_t last_idx = 0;
734 for (size_t i = 0; i < klass->NumDirectMethods(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700735 DexFile::Method dex_method;
736 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700737 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700738 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700739 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700740 // TODO: register maps
741 }
742 }
743
744 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700745 DCHECK(klass->virtual_methods_ == NULL);
746 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700747 // TODO: append virtual methods to class object
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700748 klass->virtual_methods_ = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700749 uint32_t last_idx = 0;
750 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700751 DexFile::Method dex_method;
752 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700753 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700754 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700755 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700756 // TODO: register maps
757 }
758 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700759}
760
Brian Carlstromf615a612011-07-23 12:50:34 -0700761void ClassLinker::LoadInterfaces(const DexFile& dex_file,
762 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700763 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700764 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700765 if (list != NULL) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700766 DCHECK(klass->interfaces_ == NULL);
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700767 klass->interfaces_ = AllocObjectArray<Class>(list->Size());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700768 DCHECK(klass->interfaces_type_idx_ == NULL);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700769 klass->interfaces_type_idx_ = IntArray::Alloc(list->Size());
Brian Carlstrom934486c2011-07-12 23:42:50 -0700770 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700771 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700772 klass->interfaces_type_idx_->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700773 }
774 }
775}
776
Brian Carlstromf615a612011-07-23 12:50:34 -0700777void ClassLinker::LoadField(const DexFile& dex_file,
778 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700779 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700780 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700781 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400782 dst->declaring_class_ = klass;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700783 dst->name_ = ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache());
Brian Carlstromae3ac012011-07-27 01:30:28 -0700784 dst->descriptor_.set(dex_file.dexStringByTypeIdx(field_id.type_idx_));
Jesse Wilson35baaab2011-08-10 16:18:03 -0400785 // TODO: Assign dst->type_.
Brian Carlstrom934486c2011-07-12 23:42:50 -0700786 dst->access_flags_ = src.access_flags_;
787}
788
Brian Carlstromf615a612011-07-23 12:50:34 -0700789void ClassLinker::LoadMethod(const DexFile& dex_file,
790 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700791 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700792 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700793 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400794 dst->declaring_class_ = klass;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700795 dst->name_ = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700796 {
797 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700798 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
799 dst->signature_ = String::AllocFromModifiedUtf8(utf16_length, utf8.c_str());
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700800 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700801 dst->proto_idx_ = method_id.proto_idx_;
Shih-wei Liao2fb97532011-08-11 16:17:23 -0700802 dst->code_off_ = src.code_off_;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700803 dst->shorty_ = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700804 dst->access_flags_ = src.access_flags_;
805
Brian Carlstromc4fa2c02011-08-21 03:00:12 -0700806 dst->dex_cache_strings_ = klass->dex_cache_->GetStrings();
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700807 dst->dex_cache_resolved_types_ = klass->dex_cache_->GetResolvedTypes();
808 dst->dex_cache_resolved_methods_ = klass->dex_cache_->GetResolvedMethods();
809 dst->dex_cache_resolved_fields_ = klass->dex_cache_->GetResolvedFields();
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700810 dst->dex_cache_code_and_direct_methods_ = klass->dex_cache_->GetCodeAndDirectMethods();
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700811 dst->dex_cache_initialized_static_storage_ = klass->dex_cache_->GetInitializedStaticStorage();
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700812
Brian Carlstrom934486c2011-07-12 23:42:50 -0700813 // TODO: check for finalize method
814
Brian Carlstromf615a612011-07-23 12:50:34 -0700815 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700816 if (code_item != NULL) {
817 dst->num_registers_ = code_item->registers_size_;
818 dst->num_ins_ = code_item->ins_size_;
819 dst->num_outs_ = code_item->outs_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700820 } else {
821 uint16_t num_args = dst->NumArgRegisters();
822 if (!dst->IsStatic()) {
823 ++num_args;
824 }
825 dst->num_registers_ = dst->num_ins_ + num_args;
826 // TODO: native methods
827 }
828}
829
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700830void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700831 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
832}
833
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700834void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700835 CHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700836 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700837 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700838}
839
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700840void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700841 RegisterDexFile(dex_file, AllocDexCache(dex_file));
842}
843
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700844void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700845 CHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700846 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700847 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700848}
849
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700850const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700851 for (size_t i = 0; i != dex_caches_.size(); ++i) {
852 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700853 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700854 }
855 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700856 CHECK(false) << "Could not find DexFile";
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700857 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700858}
859
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700860DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstromf615a612011-07-23 12:50:34 -0700861 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700862 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700863 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700864 }
865 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700866 CHECK(false) << "Could not find DexCache";
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700867 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700868}
869
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700870Class* ClassLinker::CreatePrimitiveClass(const char* descriptor) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700871 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700872 CHECK(klass != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -0700873 klass->super_class_ = NULL;
Carl Shapiro565f5072011-07-10 13:39:43 -0700874 klass->access_flags_ = kAccPublic | kAccFinal | kAccAbstract;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700875 klass->descriptor_ = String::AllocFromModifiedUtf8(descriptor);
Carl Shapiro565f5072011-07-10 13:39:43 -0700876 klass->status_ = Class::kStatusInitialized;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700877 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700878 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700879 return klass;
880}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700881
Brian Carlstrombe977852011-07-19 14:54:54 -0700882// Create an array class (i.e. the class object for the array, not the
883// array itself). "descriptor" looks like "[C" or "[[[[B" or
884// "[Ljava/lang/String;".
885//
886// If "descriptor" refers to an array of primitives, look up the
887// primitive type's internally-generated class object.
888//
889// "loader" is the class loader of the class that's referring to us. It's
890// used to ensure that we're looking for the element type in the right
891// context. It does NOT become the class loader for the array class; that
892// always comes from the base element class.
893//
894// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700895Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700896 const ClassLoader* class_loader)
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700897{
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700898 CHECK(descriptor[0] == '[');
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700899
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700900 // Identify the underlying element class and the array dimension depth.
901 Class* component_type_ = NULL;
902 int array_rank;
903 if (descriptor[1] == '[') {
904 // array of arrays; keep descriptor and grab stuff from parent
905 Class* outer = FindClass(descriptor.substr(1), class_loader);
906 if (outer != NULL) {
907 // want the base class, not "outer", in our component_type_
908 component_type_ = outer->component_type_;
909 array_rank = outer->array_rank_ + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700910 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700911 DCHECK(component_type_ == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700912 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700913 } else {
914 array_rank = 1;
915 if (descriptor[1] == 'L') {
916 // array of objects; strip off "[" and look up descriptor.
917 const StringPiece subDescriptor = descriptor.substr(1);
918 component_type_ = FindClass(subDescriptor, class_loader);
919 } else {
920 // array of a primitive type
921 component_type_ = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700922 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700923 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700924
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700925 if (component_type_ == NULL) {
926 // failed
927 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
928 return NULL;
929 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700930
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700931 // See if the component type is already loaded. Array classes are
932 // always associated with the class loader of their underlying
933 // element type -- an array of Strings goes with the loader for
934 // java/lang/String -- so we need to look for it there. (The
935 // caller should have checked for the existence of the class
936 // before calling here, but they did so with *their* class loader,
937 // not the component type's loader.)
938 //
939 // If we find it, the caller adds "loader" to the class' initiating
940 // loader list, which should prevent us from going through this again.
941 //
942 // This call is unnecessary if "loader" and "component_type_->class_loader_"
943 // are the same, because our caller (FindClass) just did the
944 // lookup. (Even if we get this wrong we still have correct behavior,
945 // because we effectively do this lookup again when we add the new
946 // class to the hash table --- necessary because of possible races with
947 // other threads.)
948 if (class_loader != component_type_->class_loader_) {
949 Class* new_class = LookupClass(descriptor, component_type_->class_loader_);
950 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700951 return new_class;
952 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700953 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700954
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700955 // Fill out the fields in the Class.
956 //
957 // It is possible to execute some methods against arrays, because
958 // all arrays are subclasses of java_lang_Object_, so we need to set
959 // up a vtable. We can just point at the one in java_lang_Object_.
960 //
961 // Array classes are simple enough that we don't need to do a full
962 // link step.
963
964 Class* new_class = NULL;
965 if (!init_done_) {
966 if (descriptor == "[Ljava/lang/Object;") {
967 new_class = GetClassRoot(kObjectArrayClass);
968 } else if (descriptor == "[C") {
969 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700970 } else if (descriptor == "[I") {
971 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700972 }
973 }
974 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700975 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700976 if (new_class == NULL) {
977 return NULL;
978 }
979 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700980 new_class->descriptor_ = String::AllocFromModifiedUtf8(descriptor.ToString().c_str());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700981 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
982 new_class->super_class_ = java_lang_Object;
983 new_class->vtable_ = java_lang_Object->vtable_;
984 new_class->primitive_type_ = Class::kPrimNot;
985 new_class->component_type_ = component_type_;
986 new_class->class_loader_ = component_type_->class_loader_;
987 new_class->array_rank_ = array_rank;
988 new_class->status_ = Class::kStatusInitialized;
989 // don't need to set new_class->object_size_
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700990 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700991
992
993 // All arrays have java/lang/Cloneable and java/io/Serializable as
994 // interfaces. We need to set that up here, so that stuff like
995 // "instanceof" works right.
996 //
997 // Note: The GC could run during the call to FindSystemClass,
998 // so we need to make sure the class object is GC-valid while we're in
999 // there. Do this by clearing the interface list so the GC will just
1000 // think that the entries are null.
1001
1002
1003 // Use the single, global copies of "interfaces" and "iftable"
1004 // (remember not to free them for arrays).
1005 DCHECK(array_interfaces_ != NULL);
1006 new_class->interfaces_ = array_interfaces_;
1007 new_class->iftable_count_ = 2;
1008 DCHECK(array_iftable_ != NULL);
1009 new_class->iftable_ = array_iftable_;
1010
1011 // Inherit access flags from the component type. Arrays can't be
1012 // used as a superclass or interface, so we want to add "final"
1013 // and remove "interface".
1014 //
1015 // Don't inherit any non-standard flags (e.g., kAccFinal)
1016 // from component_type_. We assume that the array class does not
1017 // override finalize().
1018 new_class->access_flags_ = ((new_class->component_type_->access_flags_ &
1019 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask;
1020
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001021 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001022 return new_class;
1023 }
1024 // Another thread must have loaded the class after we
1025 // started but before we finished. Abandon what we've
1026 // done.
1027 //
1028 // (Yes, this happens.)
1029
1030 // Grab the winning class.
1031 Class* other_class = LookupClass(descriptor, component_type_->class_loader_);
1032 DCHECK(other_class != NULL);
1033 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001034}
1035
1036Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001037 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001038 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001039 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001040 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001041 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001042 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001043 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001044 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001045 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001046 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001047 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001048 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001049 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001050 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001051 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001052 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001053 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001054 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001055 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001056 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001057 std::string printable_type(PrintableChar(type));
1058 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1059 "Not a primitive type: %s", printable_type.c_str());
1060 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001061}
1062
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001063bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1064 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001065 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001066 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001067 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001068}
1069
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001070Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001071 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001072 MutexLock mu(classes_lock_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001073 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001074 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001075 Class* klass = it->second;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001076 if (klass->descriptor_->Equals(descriptor) && klass->class_loader_ == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001077 return klass;
1078 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001079 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001080 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001081}
1082
1083bool ClassLinker::InitializeClass(Class* klass) {
1084 CHECK(klass->GetStatus() == Class::kStatusResolved ||
1085 klass->GetStatus() == Class::kStatusError);
1086
Carl Shapirob5573532011-07-12 18:22:59 -07001087 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001088
1089 {
1090 ObjectLock lock(klass);
1091
1092 if (klass->GetStatus() < Class::kStatusVerified) {
1093 if (klass->IsErroneous()) {
1094 LG << "re-initializing failed class"; // TODO: throw
1095 return false;
1096 }
1097
1098 CHECK(klass->GetStatus() == Class::kStatusResolved);
1099
1100 klass->status_ = Class::kStatusVerifying;
1101 if (!DexVerify::VerifyClass(klass)) {
1102 LG << "Verification failed"; // TODO: ThrowVerifyError
1103 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001104 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001105 klass->SetStatus(Class::kStatusError);
1106 return false;
1107 }
1108
1109 klass->SetStatus(Class::kStatusVerified);
1110 }
1111
1112 if (klass->status_ == Class::kStatusInitialized) {
1113 return true;
1114 }
1115
1116 while (klass->status_ == Class::kStatusInitializing) {
1117 // we caught somebody else in the act; was it us?
Carl Shapirob5573532011-07-12 18:22:59 -07001118 if (klass->clinit_thread_id_ == self->GetId()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001119 LG << "recursive <clinit>";
1120 return true;
1121 }
1122
1123 CHECK(!self->IsExceptionPending());
1124
1125 lock.Wait(); // TODO: check for interruption
1126
1127 // When we wake up, repeat the test for init-in-progress. If
1128 // there's an exception pending (only possible if
1129 // "interruptShouldThrow" was set), bail out.
1130 if (self->IsExceptionPending()) {
1131 CHECK(false);
1132 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1133 klass->SetStatus(Class::kStatusError);
1134 return false;
1135 }
1136 if (klass->GetStatus() == Class::kStatusInitializing) {
1137 continue;
1138 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001139 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001140 klass->GetStatus() == Class::kStatusError);
1141 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001142 // The caller wants an exception, but it was thrown in a
1143 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001144 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1145 return false;
1146 }
1147 return true; // otherwise, initialized
1148 }
1149
1150 // see if we failed previously
1151 if (klass->IsErroneous()) {
1152 // might be wise to unlock before throwing; depends on which class
1153 // it is that we have locked
1154
1155 // TODO: throwEarlierClassFailure(klass);
1156 return false;
1157 }
1158
1159 if (!ValidateSuperClassDescriptors(klass)) {
1160 klass->SetStatus(Class::kStatusError);
1161 return false;
1162 }
1163
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001164 DCHECK(klass->status_ < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001165
Carl Shapirob5573532011-07-12 18:22:59 -07001166 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001167 klass->status_ = Class::kStatusInitializing;
1168 }
1169
1170 if (!InitializeSuperClass(klass)) {
1171 return false;
1172 }
1173
1174 InitializeStaticFields(klass);
1175
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001176 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001177 if (clinit != NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001178 // JValue unused;
1179 // TODO: dvmCallMethod(self, method, NULL, &unused);
Elliott Hughes53b61312011-08-12 18:28:20 -07001180 // UNIMPLEMENTED(FATAL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001181 }
1182
1183 {
1184 ObjectLock lock(klass);
1185
1186 if (self->IsExceptionPending()) {
1187 klass->SetStatus(Class::kStatusError);
1188 } else {
1189 klass->SetStatus(Class::kStatusInitialized);
1190 }
1191 lock.NotifyAll();
1192 }
1193
1194 return true;
1195}
1196
1197bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1198 if (klass->IsInterface()) {
1199 return true;
1200 }
1201 // begin with the methods local to the superclass
1202 if (klass->HasSuperClass() &&
1203 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1204 const Class* super = klass->GetSuperClass();
1205 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001206 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001207 if (method != super->GetVirtualMethod(i) &&
1208 !HasSameMethodDescriptorClasses(method, super, klass)) {
1209 LG << "Classes resolve differently in superclass";
1210 return false;
1211 }
1212 }
1213 }
1214 for (size_t i = 0; i < klass->iftable_count_; ++i) {
1215 const InterfaceEntry* iftable = &klass->iftable_[i];
Brian Carlstrom30b94452011-08-25 21:35:26 -07001216 Class* interface = iftable->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001217 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1218 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1219 uint32_t vtable_index = iftable->method_index_array_[j];
1220 const Method* method = klass->GetVirtualMethod(vtable_index);
1221 if (!HasSameMethodDescriptorClasses(method, interface,
1222 method->GetClass())) {
1223 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1224 return false;
1225 }
1226 }
1227 }
1228 }
1229 return true;
1230}
1231
1232bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001233 const Class* klass1,
1234 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001235 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
1236 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->proto_idx_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001237 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001238 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001239 const char* descriptor = it->GetDescriptor();
1240 if (descriptor == NULL) {
1241 break;
1242 }
1243 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1244 // Found a non-primitive type.
1245 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1246 return false;
1247 }
1248 }
1249 }
1250 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001251 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001252 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1253 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1254 return false;
1255 }
1256 }
1257 return true;
1258}
1259
1260// Returns true if classes referenced by the descriptor are the
1261// same classes in klass1 as they are in klass2.
1262bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001263 const Class* klass1,
1264 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001265 CHECK(descriptor != NULL);
1266 CHECK(klass1 != NULL);
1267 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001268 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001269 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001270 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001271 // TODO: found2 == NULL
1272 // TODO: lookup found1 in initiating loader list
1273 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001274 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001275 if (found1 == found2) {
1276 return true;
1277 } else {
1278 return false;
1279 }
1280 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001281 return true;
1282}
1283
1284bool ClassLinker::InitializeSuperClass(Class* klass) {
1285 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001286 if (!klass->IsInterface() && klass->HasSuperClass()) {
1287 Class* super_class = klass->GetSuperClass();
1288 if (super_class->GetStatus() != Class::kStatusInitialized) {
1289 CHECK(!super_class->IsInterface());
1290 klass->MonitorExit();
1291 bool super_initialized = InitializeClass(super_class);
1292 klass->MonitorEnter();
1293 // TODO: check for a pending exception
1294 if (!super_initialized) {
1295 klass->SetStatus(Class::kStatusError);
1296 klass->NotifyAll();
1297 return false;
1298 }
1299 }
1300 }
1301 return true;
1302}
1303
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001304bool ClassLinker::EnsureInitialized(Class* c) {
1305 CHECK(c != NULL);
1306 if (c->IsInitialized()) {
1307 return true;
1308 }
1309
1310 c->MonitorExit();
1311 InitializeClass(c);
1312 c->MonitorEnter();
1313 return !Thread::Current()->IsExceptionPending();
1314}
1315
Brian Carlstromb9edb842011-08-28 16:31:06 -07001316StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1317 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001318 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1319 Class* klass = class_linker->ResolveType(type_idx, referrer);
1320 if (klass == NULL) {
1321 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1322 }
1323 if (!class_linker->EnsureInitialized(klass)) {
1324 CHECK(Thread::Current()->IsExceptionPending());
1325 UNIMPLEMENTED(FATAL) << "throw exception due to class initializtion problem";
1326 }
1327 return klass;
1328}
1329
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001330void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001331 size_t num_static_fields = klass->NumStaticFields();
1332 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001333 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001334 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001335 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001336 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001337 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001338 return;
1339 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001340 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001341 const DexFile& dex_file = FindDexFile(dex_cache);
1342 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001343 CHECK(dex_class_def != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001344 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001345 if (addr == NULL) {
1346 // All this class' static fields have default values.
1347 return;
1348 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001349 size_t array_size = DecodeUnsignedLeb128(&addr);
1350 for (size_t i = 0; i < array_size; ++i) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001351 Field* field = klass->GetStaticField(i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001352 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001353 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001354 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001355 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001356 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001357 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001358 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001359 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001360 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001361 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001362 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001363 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001364 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001365 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001366 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001367 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001368 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001369 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001370 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001371 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001372 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001373 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001374 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001375 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001376 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001377 uint32_t string_idx = value.i;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001378 String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001379 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001380 break;
1381 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001382 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001383 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001384 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001385 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001386 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001387 break;
1388 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001389 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001390 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001391 }
1392}
1393
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001394bool ClassLinker::LinkClass(Class* klass, const DexFile& dex_file) {
1395 CHECK_EQ(Class::kStatusLoaded, klass->status_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001396 if (!LinkSuperClass(klass)) {
1397 return false;
1398 }
1399 if (!LinkMethods(klass)) {
1400 return false;
1401 }
1402 if (!LinkInstanceFields(klass)) {
1403 return false;
1404 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001405 if (!LinkStaticFields(klass)) {
1406 return false;
1407 }
1408 CreateReferenceInstanceOffsets(klass);
1409 CreateReferenceStaticOffsets(klass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001410 CHECK_EQ(Class::kStatusLoaded, klass->status_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001411 klass->status_ = Class::kStatusResolved;
1412 return true;
1413}
1414
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001415bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
1416 CHECK_EQ(Class::kStatusIdx, klass->status_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001417 if (klass->super_class_type_idx_ != DexFile::kDexNoIndex) {
1418 Class* super_class = ResolveType(dex_file, klass->super_class_type_idx_, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001419 if (super_class == NULL) {
1420 LG << "Failed to resolve superclass";
1421 return false;
1422 }
1423 klass->super_class_ = super_class; // TODO: write barrier
1424 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001425 if (klass->NumInterfaces() > 0) {
1426 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001427 uint32_t type_idx = klass->interfaces_type_idx_->Get(i);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001428 klass->SetInterface(i, ResolveType(dex_file, type_idx, klass));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001429 if (klass->GetInterface(i) == NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001430 LG << "Failed to resolve interface";
1431 return false;
1432 }
1433 // Verify
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001434 if (!klass->CanAccess(klass->GetInterface(i))) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001435 LG << "Inaccessible interface";
1436 return false;
1437 }
1438 }
1439 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001440 // Mark the class as loaded.
1441 klass->status_ = Class::kStatusLoaded;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001442 return true;
1443}
1444
1445bool ClassLinker::LinkSuperClass(Class* klass) {
1446 CHECK(!klass->IsPrimitive());
1447 const Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001448 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001449 if (super != NULL) {
1450 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1451 return false;
1452 }
1453 // TODO: clear finalize attribute
1454 return true;
1455 }
1456 if (super == NULL) {
1457 LG << "No superclass defined"; // TODO: LinkageError
1458 return false;
1459 }
1460 // Verify
1461 if (super->IsFinal()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001462 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001463 return false;
1464 }
1465 if (super->IsInterface()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001466 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001467 return false;
1468 }
1469 if (!klass->CanAccess(super)) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001470 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001471 return false;
1472 }
1473 return true;
1474}
1475
1476// Populate the class vtable and itable.
1477bool ClassLinker::LinkMethods(Class* klass) {
1478 if (klass->IsInterface()) {
1479 // No vtable.
1480 size_t count = klass->NumVirtualMethods();
1481 if (!IsUint(16, count)) {
1482 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1483 return false;
1484 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001485 for (size_t i = 0; i < count; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001486 klass->GetVirtualMethod(i)->method_index_ = i;
1487 }
1488 } else {
1489 // Link virtual method tables
1490 LinkVirtualMethods(klass);
1491
1492 // Link interface method tables
1493 LinkInterfaceMethods(klass);
1494
1495 // Insert stubs.
1496 LinkAbstractMethods(klass);
1497 }
1498 return true;
1499}
1500
1501bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001502 if (klass->HasSuperClass()) {
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001503 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->vtable_->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001504 size_t actual_count = klass->GetSuperClass()->vtable_->GetLength();
1505 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001506 // TODO: do not assign to the vtable field until it is fully constructed.
1507 klass->vtable_ = klass->GetSuperClass()->vtable_->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001508 // See if any of our virtual methods override the superclass.
1509 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1510 Method* local_method = klass->GetVirtualMethod(i);
1511 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001512 for (; j < actual_count; ++j) {
1513 Method* super_method = klass->vtable_->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001514 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001515 // Verify
1516 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001517 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001518 return false;
1519 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001520 klass->vtable_->Set(j, local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001521 local_method->method_index_ = j;
1522 break;
1523 }
1524 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001525 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001526 // Not overriding, append.
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001527 klass->vtable_->Set(actual_count, local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001528 local_method->method_index_ = actual_count;
1529 actual_count += 1;
1530 }
1531 }
1532 if (!IsUint(16, actual_count)) {
1533 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1534 return false;
1535 }
1536 CHECK_LE(actual_count, max_count);
1537 if (actual_count < max_count) {
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001538 // TODO: do not assign to the vtable field until it is fully constructed.
1539 klass->vtable_ = klass->vtable_->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001540 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001541 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001542 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001543 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001544 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001545 LG << "Too many methods"; // TODO: VirtualMachineError
1546 return false;
1547 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001548 // TODO: do not assign to the vtable field until it is fully constructed.
1549 klass->vtable_ = AllocObjectArray<Method>(num_virtual_methods);
1550 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001551 klass->vtable_->Set(i, klass->GetVirtualMethod(i));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001552 klass->GetVirtualMethod(i)->method_index_ = i & 0xFFFF;
1553 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001554 }
1555 return true;
1556}
1557
1558bool ClassLinker::LinkInterfaceMethods(Class* klass) {
1559 int pool_offset = 0;
1560 int pool_size = 0;
1561 int miranda_count = 0;
1562 int miranda_alloc = 0;
1563 size_t super_ifcount;
1564 if (klass->HasSuperClass()) {
1565 super_ifcount = klass->GetSuperClass()->iftable_count_;
1566 } else {
1567 super_ifcount = 0;
1568 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001569 size_t ifcount = super_ifcount;
1570 ifcount += klass->NumInterfaces();
1571 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1572 ifcount += klass->GetInterface(i)->iftable_count_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001573 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001574 if (ifcount == 0) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001575 DCHECK(klass->iftable_count_ == 0);
1576 DCHECK(klass->iftable_ == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001577 return true;
1578 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001579 klass->iftable_ = new InterfaceEntry[ifcount * sizeof(InterfaceEntry)];
1580 memset(klass->iftable_, 0x00, sizeof(InterfaceEntry) * ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001581 if (super_ifcount != 0) {
1582 memcpy(klass->iftable_, klass->GetSuperClass()->iftable_,
1583 sizeof(InterfaceEntry) * super_ifcount);
1584 }
1585 // Flatten the interface inheritance hierarchy.
1586 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001587 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1588 Class* interf = klass->GetInterface(i);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001589 DCHECK(interf != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001590 if (!interf->IsInterface()) {
1591 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1592 return false;
1593 }
Brian Carlstrom30b94452011-08-25 21:35:26 -07001594 klass->iftable_[idx++].SetInterface(interf);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001595 for (size_t j = 0; j < interf->iftable_count_; j++) {
Brian Carlstrom30b94452011-08-25 21:35:26 -07001596 klass->iftable_[idx++].SetInterface(interf->iftable_[j].GetInterface());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001597 }
1598 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001599 CHECK_EQ(idx, ifcount);
1600 klass->iftable_count_ = ifcount;
1601 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001602 return true;
1603 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001604 for (size_t i = super_ifcount; i < ifcount; i++) {
Brian Carlstrom30b94452011-08-25 21:35:26 -07001605 pool_size += klass->iftable_[i].GetInterface()->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001606 }
1607 if (pool_size == 0) {
1608 return true;
1609 }
1610 klass->ifvi_pool_count_ = pool_size;
1611 klass->ifvi_pool_ = new uint32_t[pool_size];
1612 std::vector<Method*> miranda_list;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001613 for (size_t i = super_ifcount; i < ifcount; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001614 klass->iftable_[i].method_index_array_ = klass->ifvi_pool_ + pool_offset;
Brian Carlstrom30b94452011-08-25 21:35:26 -07001615 Class* interface = klass->iftable_[i].GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001616 pool_offset += interface->NumVirtualMethods(); // end here
1617 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1618 Method* interface_method = interface->GetVirtualMethod(j);
1619 int k; // must be signed
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001620 for (k = klass->vtable_->GetLength() - 1; k >= 0; --k) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001621 Method* vtable_method = klass->vtable_->Get(k);
1622 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1623 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001624 LG << "Implementation not public";
1625 return false;
1626 }
1627 klass->iftable_[i].method_index_array_[j] = k;
1628 break;
1629 }
1630 }
1631 if (k < 0) {
1632 if (miranda_count == miranda_alloc) {
1633 miranda_alloc += 8;
1634 if (miranda_list.empty()) {
1635 miranda_list.resize(miranda_alloc);
1636 } else {
1637 miranda_list.resize(miranda_alloc);
1638 }
1639 }
1640 int mir;
1641 for (mir = 0; mir < miranda_count; mir++) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001642 Method* miranda_method = miranda_list[mir];
1643 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001644 break;
1645 }
1646 }
1647 // point the interface table at a phantom slot index
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001648 klass->iftable_[i].method_index_array_[j] = klass->vtable_->GetLength() + mir;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001649 if (mir == miranda_count) {
1650 miranda_list[miranda_count++] = interface_method;
1651 }
1652 }
1653 }
1654 }
1655 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001656 int old_method_count = klass->NumVirtualMethods();
1657 int new_method_count = old_method_count + miranda_count;
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001658 klass->virtual_methods_ = klass->virtual_methods_->CopyOf(new_method_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001659
1660 CHECK(klass->vtable_ != NULL);
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001661 int old_vtable_count = klass->vtable_->GetLength();
1662 int new_vtable_count = old_vtable_count + miranda_count;
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001663 // TODO: do not assign to the vtable field until it is fully constructed.
1664 klass->vtable_ = klass->vtable_->CopyOf(new_vtable_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001665
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001666 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001667 Method* meth = AllocMethod();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001668 memcpy(meth, miranda_list[i], sizeof(Method));
1669 meth->klass_ = klass;
1670 meth->access_flags_ |= kAccMiranda;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001671 meth->method_index_ = 0xFFFF & (old_vtable_count + i);
1672 klass->SetVirtualMethod(old_method_count + i, meth);
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001673 klass->vtable_->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001674 }
1675 }
1676 return true;
1677}
1678
1679void ClassLinker::LinkAbstractMethods(Class* klass) {
1680 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1681 Method* method = klass->GetVirtualMethod(i);
1682 if (method->IsAbstract()) {
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001683 LG << "AbstractMethodError";
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001684 // TODO: throw AbstractMethodError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001685 }
1686 }
1687}
1688
1689bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001690 CHECK(klass != NULL);
1691 size_t field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001692 if (klass->GetSuperClass() != NULL) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001693 field_offset = klass->GetSuperClass()->object_size_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001694 } else {
Brian Carlstroma0808032011-07-18 00:39:23 -07001695 field_offset = OFFSETOF_MEMBER(DataObject, fields_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001696 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001697 return LinkFields(field_offset,
1698 klass->num_reference_instance_fields_,
1699 klass->NumInstanceFields(),
1700 klass->ifields_,
1701 klass->object_size_);
1702}
1703
1704bool ClassLinker::LinkStaticFields(Class* klass) {
1705 CHECK(klass != NULL);
1706 size_t allocated_class_size = klass->class_size_;
1707 size_t field_offset = OFFSETOF_MEMBER(Class, fields_);
1708 bool success = LinkFields(field_offset,
1709 klass->num_reference_static_fields_,
1710 klass->NumStaticFields(),
1711 klass->sfields_,
1712 klass->class_size_);
1713 CHECK_EQ(allocated_class_size, klass->class_size_);
1714 return success;
1715}
1716
1717bool ClassLinker::LinkFields(size_t field_offset,
1718 size_t& num_reference_fields,
1719 size_t num_fields,
1720 ObjectArray<Field>* fields,
1721 size_t& size) {
1722 CHECK((num_fields == 0) == (fields == NULL));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001723 // Move references to the front.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001724 num_reference_fields = 0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001725 size_t i = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001726 for ( ; i < num_fields; i++) {
1727 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001728 char c = pField->GetType();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001729 if (c != '[' && c != 'L') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001730 for (size_t j = num_fields - 1; j > i; j--) {
1731 Field* refField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001732 char rc = refField->GetType();
1733 if (rc == '[' || rc == 'L') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001734 fields->Set(i, refField);
1735 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001736 pField = refField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001737 c = rc;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001738 num_reference_fields++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001739 break;
1740 }
1741 }
1742 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001743 num_reference_fields++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001744 }
1745 if (c != '[' && c != 'L') {
1746 break;
1747 }
Brian Carlstroma0808032011-07-18 00:39:23 -07001748 pField->SetOffset(field_offset);
1749 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001750 }
1751
1752 // Now we want to pack all of the double-wide fields together. If
1753 // we're not aligned, though, we want to shuffle one 32-bit field
1754 // into place. If we can't find one, we'll have to pad it.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001755 if (i != num_fields && (field_offset & 0x04) != 0) {
1756 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001757 char c = pField->GetType();
1758
1759 if (c != 'J' && c != 'D') {
1760 // The field that comes next is 32-bit, so just advance past it.
Brian Carlstrombe977852011-07-19 14:54:54 -07001761 DCHECK(c != '[');
1762 DCHECK(c != 'L');
Brian Carlstroma0808032011-07-18 00:39:23 -07001763 pField->SetOffset(field_offset);
1764 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001765 i++;
1766 } else {
1767 // Next field is 64-bit, so search for a 32-bit field we can
1768 // swap into it.
1769 bool found = false;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001770 for (size_t j = num_fields - 1; j > i; j--) {
1771 Field* singleField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001772 char rc = singleField->GetType();
1773 if (rc != 'J' && rc != 'D') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001774 fields->Set(i, singleField);
1775 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001776 pField = singleField;
Brian Carlstroma0808032011-07-18 00:39:23 -07001777 pField->SetOffset(field_offset);
1778 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001779 found = true;
1780 i++;
1781 break;
1782 }
1783 }
1784 if (!found) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001785 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001786 }
1787 }
1788 }
1789
1790 // Alignment is good, shuffle any double-wide fields forward, and
1791 // finish assigning field offsets to all fields.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001792 DCHECK(i == num_fields || (field_offset & 0x04) == 0);
1793 for ( ; i < num_fields; i++) {
1794 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795 char c = pField->GetType();
1796 if (c != 'D' && c != 'J') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001797 for (size_t j = num_fields - 1; j > i; j--) {
1798 Field* doubleField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001799 char rc = doubleField->GetType();
1800 if (rc == 'D' || rc == 'J') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001801 fields->Set(i, doubleField);
1802 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001803 pField = doubleField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001804 c = rc;
1805 break;
1806 }
1807 }
1808 } else {
1809 // This is a double-wide field, leave it be.
1810 }
1811
Brian Carlstroma0808032011-07-18 00:39:23 -07001812 pField->SetOffset(field_offset);
1813 field_offset += sizeof(uint32_t);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001814 if (c == 'J' || c == 'D') {
Brian Carlstroma0808032011-07-18 00:39:23 -07001815 field_offset += sizeof(uint32_t);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001816 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001817 }
1818
1819#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001820 // Make sure that all reference fields appear before
1821 // non-reference fields, and all double-wide fields are aligned.
1822 bool seen_non_ref = false;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001823 for (i = 0; i < num_fields; i++) {
1824 Field *pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001825 char c = pField->GetType();
1826
1827 if (c == 'D' || c == 'J') {
Brian Carlstrombe977852011-07-19 14:54:54 -07001828 DCHECK_EQ(0U, pField->GetOffset() & 0x07);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001829 }
1830
1831 if (c != '[' && c != 'L') {
Brian Carlstrombe977852011-07-19 14:54:54 -07001832 if (!seen_non_ref) {
1833 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001834 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001835 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001836 } else {
1837 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001838 }
1839 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001840 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001841 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001842 }
1843#endif
Brian Carlstrom4873d462011-08-21 15:23:39 -07001844 size = field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001845 return true;
1846}
1847
1848// Set the bitmap of reference offsets, refOffsets, from the ifields
1849// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001850void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
1851 klass->reference_instance_offsets_ = 0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001852 if (klass->HasSuperClass()) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001853 klass->reference_instance_offsets_ = klass->GetSuperClass()->GetReferenceInstanceOffsets();
1854 // If our superclass overflowed, we don't stand a chance.
1855 if (klass->reference_instance_offsets_ == CLASS_WALK_SUPER) {
1856 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001857 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001858 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001859 CreateReferenceOffsets(klass->reference_instance_offsets_,
1860 klass->NumReferenceInstanceFields(),
1861 klass->ifields_);
1862}
1863
1864void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
1865 klass->reference_static_offsets_ = 0;
1866 CreateReferenceOffsets(klass->reference_static_offsets_,
1867 klass->NumReferenceStaticFields(),
1868 klass->sfields_);
1869}
1870
1871void ClassLinker::CreateReferenceOffsets(uint32_t& reference_offsets,
1872 size_t num_reference_fields,
1873 const ObjectArray<Field>* fields) {
1874 // All of the fields that contain object references are guaranteed
1875 // to be at the beginning of the fields list.
1876 for (size_t i = 0; i < num_reference_fields; ++i) {
1877 // Note that byte_offset is the offset from the beginning of
1878 // object, not the offset into instance data
1879 const Field* field = fields->Get(i);
1880 size_t byte_offset = field->GetOffset();
1881 CHECK_GE(byte_offset, CLASS_SMALLEST_OFFSET);
1882 CHECK_EQ(byte_offset & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
1883 if (CLASS_CAN_ENCODE_OFFSET(byte_offset)) {
1884 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset);
1885 CHECK_NE(new_bit, 0U);
1886 reference_offsets |= new_bit;
1887 } else {
1888 reference_offsets = CLASS_WALK_SUPER;
1889 break;
1890 }
1891 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001892}
1893
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001894String* ClassLinker::ResolveString(const DexFile& dex_file,
1895 uint32_t string_idx,
1896 DexCache* dex_cache) {
1897 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001898 if (resolved != NULL) {
1899 return resolved;
1900 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001901 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
1902 int32_t utf16_length = dex_file.GetStringLength(string_id);
1903 const char* utf8_data = dex_file.GetStringData(string_id);
1904 String* string = intern_table_.Intern(utf16_length, utf8_data);
1905 dex_cache->SetResolvedString(string_idx, string);
1906 return string;
1907}
1908
1909Class* ClassLinker::ResolveType(const DexFile& dex_file,
1910 uint32_t type_idx,
1911 DexCache* dex_cache,
1912 const ClassLoader* class_loader) {
1913 Class* resolved = dex_cache->GetResolvedType(type_idx);
1914 if (resolved != NULL) {
1915 return resolved;
1916 }
1917 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001918 if (descriptor[0] != '\0' && descriptor[1] == '\0') {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001919 resolved = FindPrimitiveClass(descriptor[0]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001920 } else {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001921 resolved = FindClass(descriptor, class_loader);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001922 }
1923 if (resolved != NULL) {
Brian Carlstromb63ec392011-08-27 17:38:27 -07001924 Class* check = resolved->IsArrayClass() ? resolved->component_type_ : resolved;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001925 if (dex_cache != check->GetDexCache()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001926 if (check->GetClassLoader() != NULL) {
1927 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
1928 return NULL;
1929 }
1930 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001931 dex_cache->SetResolvedType(type_idx, resolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001932 } else {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001933 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001934 }
1935 return resolved;
1936}
1937
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001938Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
1939 uint32_t method_idx,
1940 DexCache* dex_cache,
1941 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001942 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001943 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
1944 if (resolved != NULL) {
1945 return resolved;
1946 }
1947 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
1948 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
1949 if (klass == NULL) {
1950 return NULL;
1951 }
1952
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001953 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07001954 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001955 if (is_direct) {
1956 resolved = klass->FindDirectMethod(name, signature);
1957 } else {
1958 resolved = klass->FindVirtualMethod(name, signature);
1959 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001960 if (resolved != NULL) {
1961 dex_cache->SetResolvedMethod(method_idx, resolved);
1962 } else {
1963 // DCHECK(Thread::Current()->IsExceptionPending());
1964 }
1965 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001966}
1967
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001968Field* ClassLinker::ResolveField(const DexFile& dex_file,
1969 uint32_t field_idx,
1970 DexCache* dex_cache,
1971 const ClassLoader* class_loader,
1972 bool is_static) {
1973 Field* resolved = dex_cache->GetResolvedField(field_idx);
1974 if (resolved != NULL) {
1975 return resolved;
1976 }
1977 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
1978 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
1979 if (klass == NULL) {
1980 return NULL;
1981 }
1982
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001983 const char* name = dex_file.dexStringById(field_id.name_idx_);
1984 const char* type = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1985 if (is_static) {
1986 resolved = klass->FindStaticField(name, type);
1987 } else {
1988 resolved = klass->FindInstanceField(name, type);
1989 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001990 if (resolved != NULL) {
1991 dex_cache->SetResolvedfield(field_idx, resolved);
1992 } else {
1993 // DCHECK(Thread::Current()->IsExceptionPending());
1994 }
1995 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001996}
1997
Elliott Hughese27955c2011-08-26 15:21:24 -07001998size_t ClassLinker::NumLoadedClasses() const {
1999 MutexLock mu(classes_lock_);
2000 return classes_.size();
2001}
2002
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002003} // namespace art