blob: e3b4eea65e29c8183b0c02717b3fc12cd2c7dc1a [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
Brian Carlstromdbc05252011-09-09 01:59:59 -07005#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070011#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070012#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070013#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "dex_verifier.h"
15#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070016#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070018#include "monitor.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070019#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include "runtime.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070021#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070022#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070023#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070024#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025
26namespace art {
27
Brian Carlstroma663ea52011-08-19 23:33:41 -070028const char* ClassLinker::class_roots_descriptors_[kClassRootsMax] = {
29 "Ljava/lang/Class;",
30 "Ljava/lang/Object;",
31 "[Ljava/lang/Object;",
32 "Ljava/lang/String;",
33 "Ljava/lang/reflect/Field;",
34 "Ljava/lang/reflect/Method;",
35 "Ljava/lang/ClassLoader;",
36 "Ldalvik/system/BaseDexClassLoader;",
37 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070038 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070039 "Z",
40 "B",
41 "C",
42 "D",
43 "F",
44 "I",
45 "J",
46 "S",
47 "V",
48 "[Z",
49 "[B",
50 "[C",
51 "[D",
52 "[F",
53 "[I",
54 "[J",
55 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070056 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070057};
58
Elliott Hughes5f791332011-09-15 17:45:30 -070059class ObjectLock {
60 public:
61 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
62 CHECK(object != NULL);
63 obj_->MonitorEnter(self_);
64 }
65
66 ~ObjectLock() {
67 obj_->MonitorExit(self_);
68 }
69
70 void Wait() {
71 return Monitor::Wait(self_, obj_, 0, 0, false);
72 }
73
74 void Notify() {
75 obj_->Notify();
76 }
77
78 void NotifyAll() {
79 obj_->NotifyAll();
80 }
81
82 private:
83 Thread* self_;
84 Object* obj_;
85 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
86};
87
Elliott Hughescf4c6c42011-09-01 15:16:42 -070088ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path,
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070089 const std::vector<const DexFile*>& class_path,
Brian Carlstromc74255f2011-09-11 22:47:39 -070090 InternTable* intern_table, bool image) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070091 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -070092 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstromc74255f2011-09-11 22:47:39 -070093 if (image) {
94 class_linker->InitFromImage(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -070095 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -070096 class_linker->Init(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -070097 }
Carl Shapiro61e019d2011-07-14 16:53:09 -070098 // TODO: check for failure during initialization
99 return class_linker.release();
100}
101
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700102ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700103 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700104 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700105 array_interfaces_(NULL),
106 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700107 init_done_(false),
108 intern_table_(intern_table) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700109}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700110
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700111void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
112 const std::vector<const DexFile*>& class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700113 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700114
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700115 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700116 Class* java_lang_Class = down_cast<Class*>(
117 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700118 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700119 java_lang_Class->SetClass(java_lang_Class);
120 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700121 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700122
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700123 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700124 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700125 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700126 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700127 java_lang_Class->SetSuperClass(java_lang_Object);
128 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700129
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700130 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700131 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700132 object_array_class->SetArrayRank(1);
133 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700134
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700135 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700136 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700137 char_array_class->SetArrayRank(1);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700138 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700139
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700140 // Setup String
141 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
142 String::SetClass(java_lang_String);
143 java_lang_String->SetObjectSize(sizeof(String));
144 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400145
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700146 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700147 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
148 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
149 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
150 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
151 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700152
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700153 // Create storage for root classes, save away our work so far (requires
154 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700155 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700156 SetClassRoot(kJavaLangClass, java_lang_Class);
157 SetClassRoot(kJavaLangObject, java_lang_Object);
158 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700159 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700160 SetClassRoot(kJavaLangString, java_lang_String);
161
162 // Setup the primitive type classes.
163 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
164 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
165 SetClassRoot(kPrimitiveChar, CreatePrimitiveClass("C", Class::kPrimChar));
166 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
167 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
168 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
169 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
170 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
171 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
172
173 // Backfill component type of char[]
174 char_array_class->SetComponentType(GetClassRoot(kPrimitiveChar));
175
176 // Create array interface entries to populate once we can load system classes
177 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700178 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700179
180 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
181 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
182 int_array_class->SetArrayRank(1);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700183 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700184 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
185 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700186 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700187
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700188 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700189
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700190 // setup boot_class_path_ and register class_path now that we can
191 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700192 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700193 const DexFile* dex_file = boot_class_path[i];
194 CHECK(dex_file != NULL);
195 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700196 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700197 for (size_t i = 0; i != class_path.size(); ++i) {
198 const DexFile* dex_file = class_path[i];
199 CHECK(dex_file != NULL);
200 RegisterDexFile(*dex_file);
201 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700202
203 // Field and Method are necessary so that FindClass can link members
204 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
205 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700206 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700207 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
208 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
209 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
210 Field::SetClass(java_lang_reflect_Field);
211
212 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700213 java_lang_reflect_Method->SetDescriptor(
214 intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700215 CHECK(java_lang_reflect_Method != NULL);
216 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
217 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
218 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
219 Method::SetClass(java_lang_reflect_Method);
220
221 // now we can use FindSystemClass
222
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700223 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700224 java_lang_Object->SetStatus(Class::kStatusNotReady);
225 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
226 CHECK_EQ(java_lang_Object, Object_class);
227 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
228 java_lang_String->SetStatus(Class::kStatusNotReady);
229 Class* String_class = FindSystemClass("Ljava/lang/String;");
230 CHECK_EQ(java_lang_String, String_class);
231 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
232
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700233 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700234 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
235 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
236
237 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
238 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
239
240 Class* found_char_array_class = FindSystemClass("[C");
241 CHECK_EQ(char_array_class, found_char_array_class);
242
243 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
244 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
245
246 Class* found_int_array_class = FindSystemClass("[I");
247 CHECK_EQ(int_array_class, found_int_array_class);
248
249 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
250 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
251
252 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
253 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
254
255 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
256 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
257
258 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
259 CHECK_EQ(object_array_class, found_object_array_class);
260
261 // Setup the single, global copies of "interfaces" and "iftable"
262 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
263 CHECK(java_lang_Cloneable != NULL);
264 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
265 CHECK(java_io_Serializable != NULL);
266 CHECK(array_interfaces_ != NULL);
267 array_interfaces_->Set(0, java_lang_Cloneable);
268 array_interfaces_->Set(1, java_io_Serializable);
269 // We assume that Cloneable/Serializable don't have superinterfaces --
270 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700271 // supers as well.
272 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
273 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700274
275 // Sanity check Object[]'s interfaces
276 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
277 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700278
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700279 // run Class, Field, and Method through FindSystemClass.
280 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700281 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700282 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283
284 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700285 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700286 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700287
288 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700289 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700290 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700291
292 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
293 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294 java_lang_ref_FinalizerReference->SetAccessFlags(
295 java_lang_ref_FinalizerReference->GetAccessFlags() |
296 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700297 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298 java_lang_ref_PhantomReference->SetAccessFlags(
299 java_lang_ref_PhantomReference->GetAccessFlags() |
300 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700301 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302 java_lang_ref_SoftReference->SetAccessFlags(
303 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700304 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305 java_lang_ref_WeakReference->SetAccessFlags(
306 java_lang_ref_WeakReference->GetAccessFlags() |
307 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700308
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700309 // Setup the ClassLoaders, adjusting the object_size_ as necessary
310 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
311 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
312 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
313 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
314
315 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
316 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
317 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
318
319 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
320 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
321 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
322 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
323
324 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700325 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
326 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700327 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700328
Brian Carlstroma663ea52011-08-19 23:33:41 -0700329 FinishInit();
330}
331
332void ClassLinker::FinishInit() {
Brian Carlstrom16192862011-09-12 17:50:06 -0700333
334 // Let the heap know some key offsets into java.lang.ref instances
335 // NB we hard code the field indexes here rather than using FindInstanceField
336 // as the types of the field can't be resolved prior to the runtime being
337 // fully initialized
338 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
339 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
340
341 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
342 CHECK(pendingNext->GetName()->Equals("pendingNext"));
343 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
344
345 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
346 CHECK(queue->GetName()->Equals("queue"));
347 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
348 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
349
350 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
351 CHECK(queueNext->GetName()->Equals("queueNext"));
352 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
353
354 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
355 CHECK(referent->GetName()->Equals("referent"));
356 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
357
358 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
359 CHECK(zombie->GetName()->Equals("zombie"));
360 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
361
362 Heap::SetReferenceOffsets(referent->GetOffset(),
363 queue->GetOffset(),
364 queueNext->GetOffset(),
365 pendingNext->GetOffset(),
366 zombie->GetOffset());
367
Brian Carlstroma663ea52011-08-19 23:33:41 -0700368 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700369 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700370 ClassRoot class_root = static_cast<ClassRoot>(i);
371 Class* klass = GetClassRoot(class_root);
372 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700373 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700374 // note SetClassRoot does additional validation.
375 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700376 }
377
378 // disable the slow paths in FindClass and CreatePrimitiveClass now
379 // that Object, Class, and Object[] are setup
380 init_done_ = true;
381}
382
Brian Carlstromc74255f2011-09-11 22:47:39 -0700383struct ClassLinker::InitFromImageCallbackState {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700384 ClassLinker* class_linker;
385
386 Class* class_roots[kClassRootsMax];
387
388 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
389 Table descriptor_to_class_root;
390
Brian Carlstroma663ea52011-08-19 23:33:41 -0700391 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
392 Set dex_caches;
393};
394
Brian Carlstromc74255f2011-09-11 22:47:39 -0700395void ClassLinker::InitFromImage(const std::vector<const DexFile*>& boot_class_path,
396 const std::vector<const DexFile*>& class_path) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700397 CHECK(!init_done_);
398
399 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
400 DCHECK(heap_bitmap != NULL);
401
Brian Carlstromc74255f2011-09-11 22:47:39 -0700402 InitFromImageCallbackState state;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700403 state.class_linker = this;
404 for (size_t i = 0; i < kClassRootsMax; i++) {
405 ClassRoot class_root = static_cast<ClassRoot>(i);
406 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
407 }
408
409 // reinit clases_ table
Brian Carlstromc74255f2011-09-11 22:47:39 -0700410 heap_bitmap->Walk(InitFromImageCallback, &state);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700411
412 // reinit class_roots_
413 Class* object_array_class = state.class_roots[kObjectArrayClass];
414 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
415 for (size_t i = 0; i < kClassRootsMax; i++) {
416 ClassRoot class_root = static_cast<ClassRoot>(i);
417 SetClassRoot(class_root, state.class_roots[class_root]);
418 }
419
Brian Carlstroma663ea52011-08-19 23:33:41 -0700420 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700421 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
422 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700423
424 // build a map from location to DexCache to match up with DexFile::GetLocation
425 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Brian Carlstromc74255f2011-09-11 22:47:39 -0700426 typedef InitFromImageCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700427 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
428 DexCache* dex_cache = *it;
429 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
430 location_to_dex_cache[location] = dex_cache;
431 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700432 CHECK_EQ(boot_class_path.size() + class_path.size(),
433 location_to_dex_cache.size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700434
435 // reinit boot_class_path with DexFile arguments and found DexCaches
436 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700437 const DexFile* dex_file = boot_class_path[i];
438 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700439 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700440 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700441 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700442 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700443
444 // register class_path with DexFile arguments and found DexCaches
445 for (size_t i = 0; i != class_path.size(); ++i) {
446 const DexFile* dex_file = class_path[i];
447 CHECK(dex_file != NULL);
448 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
449 CHECK(dex_cache != NULL) << dex_file->GetLocation();
450 RegisterDexFile(*dex_file, dex_cache);
451 }
452
Brian Carlstroma663ea52011-08-19 23:33:41 -0700453 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454 Field::SetClass(GetClassRoot(kJavaLangReflectField));
455 Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700456 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
457 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
458 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
459 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
460 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
461 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
462 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
463 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700464 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700465 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700466
467 FinishInit();
468}
469
Brian Carlstrom78128a62011-09-15 17:21:19 -0700470void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700471 DCHECK(obj != NULL);
472 DCHECK(arg != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700473 InitFromImageCallbackState* state = reinterpret_cast<InitFromImageCallbackState*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700474
Brian Carlstromc74255f2011-09-11 22:47:39 -0700475 if (obj->IsString()) {
476 state->class_linker->intern_table_->RegisterStrong(obj->AsString());
477 return;
478 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700479 if (!obj->IsClass()) {
480 return;
481 }
482 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700483 // TODO: restore ClassLoader's list of DexFiles after image load
484 // CHECK(klass->GetClassLoader() == NULL);
485 const ClassLoader* class_loader = klass->GetClassLoader();
486 if (class_loader != NULL) {
487 // TODO: replace this hack with something based on command line arguments
488 Thread::Current()->SetClassLoaderOverride(class_loader);
489 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700490
491 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700492 // restore class to ClassLinker::classes_ table
493 state->class_linker->InsertClass(descriptor, klass);
494
495 // note DexCache to match with DexFile later
496 DexCache* dex_cache = klass->GetDexCache();
497 if (dex_cache != NULL) {
498 state->dex_caches.insert(dex_cache);
499 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700500 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700501 }
502
503 // check if this is a root, if so, register it
Brian Carlstromc74255f2011-09-11 22:47:39 -0700504 typedef InitFromImageCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700505 It it = state->descriptor_to_class_root.find(descriptor);
506 if (it != state->descriptor_to_class_root.end()) {
507 ClassRoot class_root = it->second;
508 state->class_roots[class_root] = klass;
509 }
510}
511
512// Keep in sync with InitCallback. Anything we visit, we need to
513// reinit references to when reinitializing a ClassLinker from a
514// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700515void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
516 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700517
518 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700519 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700520 }
521
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700522 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700523 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700524 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700525 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700526 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700527 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700528 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700529
Elliott Hughes410c0c82011-09-01 17:58:25 -0700530 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700531}
532
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700533ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700534 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535 Field::ResetClass();
536 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700537 BooleanArray::ResetArrayClass();
538 ByteArray::ResetArrayClass();
539 CharArray::ResetArrayClass();
540 DoubleArray::ResetArrayClass();
541 FloatArray::ResetArrayClass();
542 IntArray::ResetArrayClass();
543 LongArray::ResetArrayClass();
544 ShortArray::ResetArrayClass();
545 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700546 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700547}
548
549DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700550 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700551 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700552 AllocObjectArray<String>(dex_file.NumStringIds()),
553 AllocObjectArray<Class>(dex_file.NumTypeIds()),
554 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700555 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700556 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
557 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700558 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700559}
560
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700561CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
562 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700563}
564
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700565InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
566 DCHECK(interface->IsInterface());
567 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
568 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
569 interface_entry->SetInterface(interface);
570 return interface_entry;
571}
572
Brian Carlstrom4873d462011-08-21 15:23:39 -0700573Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
574 DCHECK_GE(class_size, sizeof(Class));
575 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700576 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
577 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700578 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700579}
580
Brian Carlstrom4873d462011-08-21 15:23:39 -0700581Class* ClassLinker::AllocClass(size_t class_size) {
582 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700583}
584
Jesse Wilson35baaab2011-08-10 16:18:03 -0400585Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700586 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700587}
588
589Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700590 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700591}
592
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700593ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
594 return ObjectArray<StackTraceElement>::Alloc(
595 GetClassRoot(kJavaLangStackTraceElementArrayClass),
596 length);
597}
598
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700599Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700600 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700601 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700602 if (class_loader != NULL) {
603 Class* klass = FindClass(descriptor, NULL);
604 if (klass != NULL) {
605 return klass;
606 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700607 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700608 }
609
Carl Shapirob5573532011-07-12 18:22:59 -0700610 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700611 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700612 CHECK(!self->IsExceptionPending());
613 // Find the class in the loaded classes table.
614 Class* klass = LookupClass(descriptor, class_loader);
615 if (klass == NULL) {
616 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700617 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700618 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700619 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700620 const DexFile::ClassPath& class_path = ((class_loader != NULL)
621 ? ClassLoader::GetClassPath(class_loader)
622 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700623 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700624 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700625 std::string name(PrintableString(descriptor));
626 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
627 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700628 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700629 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700630 const DexFile& dex_file = *pair.first;
631 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700632 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700633 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700634 if (!init_done_) {
635 // finish up init of hand crafted class_roots_
636 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700637 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700638 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700639 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400640 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700641 klass = GetClassRoot(kJavaLangString);
642 } else if (descriptor == "Ljava/lang/reflect/Field;") {
643 klass = GetClassRoot(kJavaLangReflectField);
644 } else if (descriptor == "Ljava/lang/reflect/Method;") {
645 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700646 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700647 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700648 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700649 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700650 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700651 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700652 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700653 klass->SetDexCache(dex_cache);
654 LoadClass(dex_file, dex_class_def, klass, class_loader);
655 // Check for a pending exception during load
656 if (self->IsExceptionPending()) {
657 // TODO: free native allocations in klass
658 return NULL;
659 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700660 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700661 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700662 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700663 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700664 if (!success) {
665 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700666 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700667 // TODO: free native allocations in klass
668 klass = LookupClass(descriptor, class_loader);
669 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700670 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700671 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700672 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700673 CHECK(!klass->IsLoaded());
674 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700675 // Loading failed.
676 // TODO: CHECK(self->IsExceptionPending());
677 lock.NotifyAll();
678 return NULL;
679 }
680 CHECK(klass->IsLoaded());
681 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700682 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700683 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700684 // Linking failed.
685 // TODO: CHECK(self->IsExceptionPending());
686 lock.NotifyAll();
687 return NULL;
688 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700689 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700690 }
691 }
692 }
693 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700694 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700695 ObjectLock lock(klass);
696 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700697 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700698 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700699 return NULL;
700 }
701 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700702 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700703 lock.Wait();
704 }
705 }
706 if (klass->IsErroneous()) {
707 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
708 return NULL;
709 }
710 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700711 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700712 CHECK(!self->IsExceptionPending());
713 return klass;
714}
715
Brian Carlstrom4873d462011-08-21 15:23:39 -0700716// Precomputes size that will be needed for Class, matching LinkStaticFields
717size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
718 const DexFile::ClassDef& dex_class_def) {
719 const byte* class_data = dex_file.GetClassData(dex_class_def);
720 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
721 size_t num_static_fields = header.static_fields_size_;
722 size_t num_ref = 0;
723 size_t num_32 = 0;
724 size_t num_64 = 0;
725 if (num_static_fields != 0) {
726 uint32_t last_idx = 0;
727 for (size_t i = 0; i < num_static_fields; ++i) {
728 DexFile::Field dex_field;
729 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
730 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
731 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
732 char c = descriptor[0];
733 if (c == 'L' || c == '[') {
734 num_ref++;
735 } else if (c == 'J' || c == 'D') {
736 num_64++;
737 } else {
738 num_32++;
739 }
740 }
741 }
742
743 // start with generic class data
744 size_t size = sizeof(Class);
745 // follow with reference fields which must be contiguous at start
746 size += (num_ref * sizeof(uint32_t));
747 // if there are 64-bit fields to add, make sure they are aligned
748 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
749 if (num_32 != 0) {
750 // use an available 32-bit field for padding
751 num_32--;
752 }
753 size += sizeof(uint32_t); // either way, we are adding a word
754 DCHECK_EQ(size, RoundUp(size, 8));
755 }
756 // tack on any 64-bit fields now that alignment is assured
757 size += (num_64 * sizeof(uint64_t));
758 // tack on any remaining 32-bit fields
759 size += (num_32 * sizeof(uint32_t));
760 return size;
761}
762
Brian Carlstromf615a612011-07-23 12:50:34 -0700763void ClassLinker::LoadClass(const DexFile& dex_file,
764 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700765 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700766 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700767 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700768 CHECK(klass->GetDexCache() != NULL);
769 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700770 const byte* class_data = dex_file.GetClassData(dex_class_def);
771 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700772
Brian Carlstromf615a612011-07-23 12:50:34 -0700773 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700774 CHECK(descriptor != NULL);
775
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700776 klass->SetClass(GetClassRoot(kJavaLangClass));
777 if (klass->GetDescriptor() != NULL) {
778 DCHECK(klass->GetDescriptor()->Equals(descriptor));
779 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700780 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700781 }
782 uint32_t access_flags = dex_class_def.access_flags_;
783 // Make sure there aren't any "bonus" flags set, since we use them for runtime
784 // state.
785 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
786 klass->SetAccessFlags(access_flags);
787 klass->SetClassLoader(class_loader);
788 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
789 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700790
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700791 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700792
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700793 size_t num_static_fields = header.static_fields_size_;
794 size_t num_instance_fields = header.instance_fields_size_;
795 size_t num_direct_methods = header.direct_methods_size_;
796 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700797
Brian Carlstromc74255f2011-09-11 22:47:39 -0700798 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700799
800 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700801 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700802
803 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700804 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700805 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700806 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700807 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700808 DexFile::Field dex_field;
809 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400810 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700811 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700812 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700813 }
814 }
815
816 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700817 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700818 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700819 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700820 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700821 DexFile::Field dex_field;
822 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400823 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700824 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700825 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700826 }
827 }
828
829 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700830 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700831 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700832 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700833 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700834 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700835 DexFile::Method dex_method;
836 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700837 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700838 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700839 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700840 // TODO: register maps
841 }
842 }
843
844 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700845 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700846 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700847 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700848 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700849 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700850 DexFile::Method dex_method;
851 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700852 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700853 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700854 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700855 // TODO: register maps
856 }
857 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700858}
859
Brian Carlstromf615a612011-07-23 12:50:34 -0700860void ClassLinker::LoadInterfaces(const DexFile& dex_file,
861 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700862 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700863 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700864 if (list != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700865 klass->SetInterfaces(AllocObjectArray<Class>(list->Size()));
866 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
867 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700868 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700869 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700870 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700871 }
872 }
873}
874
Brian Carlstromf615a612011-07-23 12:50:34 -0700875void ClassLinker::LoadField(const DexFile& dex_file,
876 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700877 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700878 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700879 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700880 dst->SetDeclaringClass(klass);
881 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
882 dst->SetTypeIdx(field_id.type_idx_);
883 dst->SetAccessFlags(src.access_flags_);
884
885 // In order to access primitive types using GetTypeDuringLinking we need to
886 // ensure they are resolved into the dex cache
887 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
888 if (descriptor[1] == '\0') {
889 // only the descriptors of primitive types should be 1 character long
890 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
891 DCHECK(resolved->IsPrimitive());
892 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700893}
894
Brian Carlstromf615a612011-07-23 12:50:34 -0700895void ClassLinker::LoadMethod(const DexFile& dex_file,
896 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700897 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700898 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700899 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700900 dst->SetDeclaringClass(klass);
901 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700902 {
903 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700904 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700905 dst->SetSignature(intern_table_->InternStrong(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700906 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700907 dst->SetProtoIdx(method_id.proto_idx_);
908 dst->SetCodeItemOffset(src.code_off_);
909 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700910 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700911 dst->SetAccessFlags(src.access_flags_);
912 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700913
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700914 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
915 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
916 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
917 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
918 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
919 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700920
Brian Carlstrom934486c2011-07-12 23:42:50 -0700921 // TODO: check for finalize method
922
Brian Carlstromf615a612011-07-23 12:50:34 -0700923 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700924 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700925 dst->SetNumRegisters(code_item->registers_size_);
926 dst->SetNumIns(code_item->ins_size_);
927 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700928 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700929 uint16_t num_args = Method::NumArgRegisters(shorty);
930 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700931 ++num_args;
932 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700933 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700934 // TODO: native methods
935 }
936}
937
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700938void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700939 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
940}
941
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700942void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700943 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700944 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700945 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700946}
947
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700948void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700949 RegisterDexFile(dex_file, AllocDexCache(dex_file));
950}
951
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700952void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700953 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700954 CHECK(dex_cache != NULL) << dex_file.GetLocation();
955 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700956 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700957 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700958}
959
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700960const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700961 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700962 for (size_t i = 0; i != dex_caches_.size(); ++i) {
963 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700964 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700965 }
966 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700967 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700968 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700969}
970
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700971DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700972 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -0700973 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700974 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700975 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700976 }
977 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700978 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700979 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700980}
981
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700982Class* ClassLinker::CreatePrimitiveClass(const char* descriptor,
983 Class::PrimitiveType type) {
984 // TODO: deduce one argument from the other
Brian Carlstrom4873d462011-08-21 15:23:39 -0700985 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700986 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700987 klass->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700988 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700989 klass->SetPrimitiveType(type);
990 klass->SetStatus(Class::kStatusInitialized);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700991 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700992 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700993 return klass;
994}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700995
Brian Carlstrombe977852011-07-19 14:54:54 -0700996// Create an array class (i.e. the class object for the array, not the
997// array itself). "descriptor" looks like "[C" or "[[[[B" or
998// "[Ljava/lang/String;".
999//
1000// If "descriptor" refers to an array of primitives, look up the
1001// primitive type's internally-generated class object.
1002//
1003// "loader" is the class loader of the class that's referring to us. It's
1004// used to ensure that we're looking for the element type in the right
1005// context. It does NOT become the class loader for the array class; that
1006// always comes from the base element class.
1007//
1008// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001009Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001010 const ClassLoader* class_loader) {
1011 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001012
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001013 // Identify the underlying element class and the array dimension depth.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001014 Class* component_type = NULL;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001015 int array_rank;
1016 if (descriptor[1] == '[') {
1017 // array of arrays; keep descriptor and grab stuff from parent
1018 Class* outer = FindClass(descriptor.substr(1), class_loader);
1019 if (outer != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001020 // want the base class, not "outer", in our component_type
1021 component_type = outer->GetComponentType();
1022 array_rank = outer->GetArrayRank() + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001023 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001024 DCHECK(component_type == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001025 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001026 } else {
1027 array_rank = 1;
1028 if (descriptor[1] == 'L') {
1029 // array of objects; strip off "[" and look up descriptor.
1030 const StringPiece subDescriptor = descriptor.substr(1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001031 component_type = FindClass(subDescriptor, class_loader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001032 } else {
1033 // array of a primitive type
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001034 component_type = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001035 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001036 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001037
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001038 if (component_type == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001039 // failed
1040 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
1041 return NULL;
1042 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001043
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001044 // See if the component type is already loaded. Array classes are
1045 // always associated with the class loader of their underlying
1046 // element type -- an array of Strings goes with the loader for
1047 // java/lang/String -- so we need to look for it there. (The
1048 // caller should have checked for the existence of the class
1049 // before calling here, but they did so with *their* class loader,
1050 // not the component type's loader.)
1051 //
1052 // If we find it, the caller adds "loader" to the class' initiating
1053 // loader list, which should prevent us from going through this again.
1054 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001055 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001056 // are the same, because our caller (FindClass) just did the
1057 // lookup. (Even if we get this wrong we still have correct behavior,
1058 // because we effectively do this lookup again when we add the new
1059 // class to the hash table --- necessary because of possible races with
1060 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001061 if (class_loader != component_type->GetClassLoader()) {
1062 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001063 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001064 return new_class;
1065 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001066 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001067
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001068 // Fill out the fields in the Class.
1069 //
1070 // It is possible to execute some methods against arrays, because
1071 // all arrays are subclasses of java_lang_Object_, so we need to set
1072 // up a vtable. We can just point at the one in java_lang_Object_.
1073 //
1074 // Array classes are simple enough that we don't need to do a full
1075 // link step.
1076
1077 Class* new_class = NULL;
1078 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001079 // Classes that were hand created, ie not by FindSystemClass
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001080 if (descriptor == "[Ljava/lang/Object;") {
1081 new_class = GetClassRoot(kObjectArrayClass);
1082 } else if (descriptor == "[C") {
1083 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001084 } else if (descriptor == "[I") {
1085 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001086 }
1087 }
1088 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001089 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001090 if (new_class == NULL) {
1091 return NULL;
1092 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001093 new_class->SetArrayRank(array_rank);
1094 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001095 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001096 DCHECK_LE(1, new_class->GetArrayRank());
1097 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001098 if (new_class->GetDescriptor() != NULL) {
1099 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1100 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001101 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001102 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001103 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001104 new_class->SetSuperClass(java_lang_Object);
1105 new_class->SetVTable(java_lang_Object->GetVTable());
1106 new_class->SetPrimitiveType(Class::kPrimNot);
1107 new_class->SetClassLoader(component_type->GetClassLoader());
1108 new_class->SetStatus(Class::kStatusInitialized);
1109 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001110 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001111
1112
1113 // All arrays have java/lang/Cloneable and java/io/Serializable as
1114 // interfaces. We need to set that up here, so that stuff like
1115 // "instanceof" works right.
1116 //
1117 // Note: The GC could run during the call to FindSystemClass,
1118 // so we need to make sure the class object is GC-valid while we're in
1119 // there. Do this by clearing the interface list so the GC will just
1120 // think that the entries are null.
1121
1122
1123 // Use the single, global copies of "interfaces" and "iftable"
1124 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001125 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001126 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001127
1128 // Inherit access flags from the component type. Arrays can't be
1129 // used as a superclass or interface, so we want to add "final"
1130 // and remove "interface".
1131 //
1132 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001133 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001134 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001135 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1136 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001137
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001138 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001139 return new_class;
1140 }
1141 // Another thread must have loaded the class after we
1142 // started but before we finished. Abandon what we've
1143 // done.
1144 //
1145 // (Yes, this happens.)
1146
1147 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001148 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001149 DCHECK(other_class != NULL);
1150 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001151}
1152
1153Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001154 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001155 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001156 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001157 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001158 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001159 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001160 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001161 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001162 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001163 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001164 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001165 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001166 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001167 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001168 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001169 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001170 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001171 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001172 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001173 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001174 std::string printable_type(PrintableChar(type));
1175 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1176 "Not a primitive type: %s", printable_type.c_str());
1177 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001178}
1179
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001180bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1181 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001182 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001183 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001184 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001185}
1186
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001187Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001188 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001189 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001190 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001191 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001192 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001193 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001194 return klass;
1195 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001196 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001197 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001198}
1199
jeffhao98eacac2011-09-14 16:11:53 -07001200void ClassLinker::VerifyClass(Class* klass) {
1201 if (klass->IsVerified()) {
1202 return;
1203 }
1204
1205 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
1206
1207 klass->SetStatus(Class::kStatusVerifying);
1208 if (!DexVerifier::VerifyClass(klass)) {
1209 LOG(ERROR) << "Verification failed on class "
1210 << klass->GetDescriptor()->ToModifiedUtf8();
1211 Object* exception = Thread::Current()->GetException();
1212 klass->SetVerifyErrorClass(exception->GetClass());
1213 klass->SetStatus(Class::kStatusError);
1214 return;
1215 }
1216
1217 klass->SetStatus(Class::kStatusVerified);
1218}
1219
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001220bool ClassLinker::InitializeClass(Class* klass) {
1221 CHECK(klass->GetStatus() == Class::kStatusResolved ||
jeffhao98eacac2011-09-14 16:11:53 -07001222 klass->GetStatus() == Class::kStatusVerified ||
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001223 klass->GetStatus() == Class::kStatusInitializing ||
1224 klass->GetStatus() == Class::kStatusError)
Elliott Hughes54e7df12011-09-16 11:47:04 -07001225 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001226
Carl Shapirob5573532011-07-12 18:22:59 -07001227 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001228
1229 {
1230 ObjectLock lock(klass);
1231
1232 if (klass->GetStatus() < Class::kStatusVerified) {
1233 if (klass->IsErroneous()) {
1234 LG << "re-initializing failed class"; // TODO: throw
1235 return false;
1236 }
1237
jeffhao98eacac2011-09-14 16:11:53 -07001238 VerifyClass(klass);
1239 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001240 return false;
1241 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001242 }
1243
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001244 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001245 return true;
1246 }
1247
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001248 while (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001249 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001250 if (klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001251 // Yes. That's fine.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001252 return true;
1253 }
1254
1255 CHECK(!self->IsExceptionPending());
1256
1257 lock.Wait(); // TODO: check for interruption
1258
1259 // When we wake up, repeat the test for init-in-progress. If
1260 // there's an exception pending (only possible if
1261 // "interruptShouldThrow" was set), bail out.
1262 if (self->IsExceptionPending()) {
1263 CHECK(false);
1264 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1265 klass->SetStatus(Class::kStatusError);
1266 return false;
1267 }
1268 if (klass->GetStatus() == Class::kStatusInitializing) {
1269 continue;
1270 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001271 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001272 klass->GetStatus() == Class::kStatusError);
1273 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001274 // The caller wants an exception, but it was thrown in a
1275 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001276 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1277 return false;
1278 }
1279 return true; // otherwise, initialized
1280 }
1281
1282 // see if we failed previously
1283 if (klass->IsErroneous()) {
1284 // might be wise to unlock before throwing; depends on which class
1285 // it is that we have locked
1286
1287 // TODO: throwEarlierClassFailure(klass);
1288 return false;
1289 }
1290
1291 if (!ValidateSuperClassDescriptors(klass)) {
1292 klass->SetStatus(Class::kStatusError);
1293 return false;
1294 }
1295
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001296 DCHECK(klass->GetStatus() < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001297
Elliott Hughesdcc24742011-09-07 14:02:44 -07001298 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001299 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001300 }
1301
1302 if (!InitializeSuperClass(klass)) {
1303 return false;
1304 }
1305
1306 InitializeStaticFields(klass);
1307
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001308 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001309 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001310 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001311 }
1312
1313 {
1314 ObjectLock lock(klass);
1315
1316 if (self->IsExceptionPending()) {
1317 klass->SetStatus(Class::kStatusError);
1318 } else {
1319 klass->SetStatus(Class::kStatusInitialized);
1320 }
1321 lock.NotifyAll();
1322 }
1323
1324 return true;
1325}
1326
1327bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1328 if (klass->IsInterface()) {
1329 return true;
1330 }
1331 // begin with the methods local to the superclass
1332 if (klass->HasSuperClass() &&
1333 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1334 const Class* super = klass->GetSuperClass();
1335 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001336 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001337 if (method != super->GetVirtualMethod(i) &&
1338 !HasSameMethodDescriptorClasses(method, super, klass)) {
1339 LG << "Classes resolve differently in superclass";
1340 return false;
1341 }
1342 }
1343 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001344 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1345 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1346 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001347 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1348 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001349 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001350 if (!HasSameMethodDescriptorClasses(method, interface,
1351 method->GetClass())) {
1352 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1353 return false;
1354 }
1355 }
1356 }
1357 }
1358 return true;
1359}
1360
1361bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001362 const Class* klass1,
1363 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001364 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001365 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001366 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001367 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001368 const char* descriptor = it->GetDescriptor();
1369 if (descriptor == NULL) {
1370 break;
1371 }
1372 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1373 // Found a non-primitive type.
1374 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1375 return false;
1376 }
1377 }
1378 }
1379 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001380 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001381 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1382 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1383 return false;
1384 }
1385 }
1386 return true;
1387}
1388
1389// Returns true if classes referenced by the descriptor are the
1390// same classes in klass1 as they are in klass2.
1391bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001392 const Class* klass1,
1393 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001394 CHECK(descriptor != NULL);
1395 CHECK(klass1 != NULL);
1396 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001397 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001398 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001399 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001400 // TODO: found2 == NULL
1401 // TODO: lookup found1 in initiating loader list
1402 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001403 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001404 if (found1 == found2) {
1405 return true;
1406 } else {
1407 return false;
1408 }
1409 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001410 return true;
1411}
1412
1413bool ClassLinker::InitializeSuperClass(Class* klass) {
1414 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001415 if (!klass->IsInterface() && klass->HasSuperClass()) {
1416 Class* super_class = klass->GetSuperClass();
1417 if (super_class->GetStatus() != Class::kStatusInitialized) {
1418 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001419 Thread* self = Thread::Current();
1420 klass->MonitorEnter(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001421 bool super_initialized = InitializeClass(super_class);
Elliott Hughes5f791332011-09-15 17:45:30 -07001422 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001423 // TODO: check for a pending exception
1424 if (!super_initialized) {
1425 klass->SetStatus(Class::kStatusError);
1426 klass->NotifyAll();
1427 return false;
1428 }
1429 }
1430 }
1431 return true;
1432}
1433
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001434bool ClassLinker::EnsureInitialized(Class* c) {
1435 CHECK(c != NULL);
1436 if (c->IsInitialized()) {
1437 return true;
1438 }
1439
Elliott Hughes5f791332011-09-15 17:45:30 -07001440 Thread* self = Thread::Current();
1441 c->MonitorEnter(self);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001442 InitializeClass(c);
Elliott Hughes5f791332011-09-15 17:45:30 -07001443 c->MonitorExit(self);
1444 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001445}
1446
Brian Carlstromb9edb842011-08-28 16:31:06 -07001447StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1448 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001449 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1450 Class* klass = class_linker->ResolveType(type_idx, referrer);
1451 if (klass == NULL) {
1452 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1453 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001454 // If we are the <clinit> of this class, just return our storage.
1455 //
1456 // Do not set the DexCache InitializedStaticStorage, since that
1457 // implies <clinit> has finished running.
1458 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1459 return klass;
1460 }
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001461 if (!class_linker->EnsureInitialized(klass)) {
1462 CHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001463 UNIMPLEMENTED(FATAL) << "throw exception due to class initialization problem";
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001464 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001465 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001466 return klass;
1467}
1468
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001469void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1470 Class* c, std::map<int, Field*>& field_map) {
1471 const ClassLoader* cl = c->GetClassLoader();
1472 const byte* class_data = dex_file.GetClassData(dex_class_def);
1473 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1474 uint32_t last_idx = 0;
1475 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1476 DexFile::Field dex_field;
1477 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1478 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1479 }
1480}
1481
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001482void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001483 size_t num_static_fields = klass->NumStaticFields();
1484 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001485 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001486 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001487 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001488 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001489 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001490 return;
1491 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001492 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001493 const DexFile& dex_file = FindDexFile(dex_cache);
1494 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001495 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001496
1497 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1498 std::map<int, Field*> field_map;
1499 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1500
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001501 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001502 if (addr == NULL) {
1503 // All this class' static fields have default values.
1504 return;
1505 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001506 size_t array_size = DecodeUnsignedLeb128(&addr);
1507 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001508 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001509 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001510 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001511 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001512 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001513 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001514 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001515 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001516 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001517 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001518 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001519 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001520 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001521 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001522 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001523 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001524 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001525 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001526 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001527 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001528 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001529 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001530 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001531 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001532 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001533 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001534 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001535 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001536 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001537 break;
1538 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001539 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001540 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001541 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001542 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001543 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001544 break;
1545 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001546 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001547 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001548 }
1549}
1550
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001551bool ClassLinker::LinkClass(Class* klass) {
1552 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001553 if (!LinkSuperClass(klass)) {
1554 return false;
1555 }
1556 if (!LinkMethods(klass)) {
1557 return false;
1558 }
1559 if (!LinkInstanceFields(klass)) {
1560 return false;
1561 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001562 if (!LinkStaticFields(klass)) {
1563 return false;
1564 }
1565 CreateReferenceInstanceOffsets(klass);
1566 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001567 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1568 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001569 return true;
1570}
1571
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001572bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001573 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1574 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1575 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001576 if (super_class == NULL) {
1577 LG << "Failed to resolve superclass";
1578 return false;
1579 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001580 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001581 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001582 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1583 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1584 Class *interface = ResolveType(dex_file, idx, klass);
1585 klass->SetInterface(i, interface);
1586 if (interface == NULL) {
1587 LG << "Failed to resolve interface";
1588 return false;
1589 }
1590 // Verify
1591 if (!klass->CanAccess(interface)) {
1592 LG << "Inaccessible interface";
1593 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001594 }
1595 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001596 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001597 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001598 return true;
1599}
1600
1601bool ClassLinker::LinkSuperClass(Class* klass) {
1602 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001603 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001604 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001605 if (super != NULL) {
1606 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1607 return false;
1608 }
1609 // TODO: clear finalize attribute
1610 return true;
1611 }
1612 if (super == NULL) {
1613 LG << "No superclass defined"; // TODO: LinkageError
1614 return false;
1615 }
1616 // Verify
1617 if (super->IsFinal()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001618 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001619 return false;
1620 }
1621 if (super->IsInterface()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001622 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001623 return false;
1624 }
1625 if (!klass->CanAccess(super)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001626 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001627 return false;
1628 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001629#ifndef NDEBUG
1630 // Ensure super classes are fully resolved prior to resolving fields..
1631 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001632 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001633 super = super->GetSuperClass();
1634 }
1635#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001636 return true;
1637}
1638
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001639// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640bool ClassLinker::LinkMethods(Class* klass) {
1641 if (klass->IsInterface()) {
1642 // No vtable.
1643 size_t count = klass->NumVirtualMethods();
1644 if (!IsUint(16, count)) {
1645 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1646 return false;
1647 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001648 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001649 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001650 }
jeffhaobdb76512011-09-07 11:43:16 -07001651 // Link interface method tables
1652 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001653 } else {
1654 // Link virtual method tables
1655 LinkVirtualMethods(klass);
1656
1657 // Link interface method tables
1658 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001659 }
1660 return true;
1661}
1662
1663bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001664 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001665 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1666 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001667 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001668 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001669 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001670 // See if any of our virtual methods override the superclass.
1671 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001672 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001673 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001674 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001675 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001676 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001677 // Verify
1678 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001679 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001680 return false;
1681 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001682 vtable->Set(j, local_method);
1683 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001684 break;
1685 }
1686 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001687 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001688 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001689 vtable->Set(actual_count, local_method);
1690 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001691 actual_count += 1;
1692 }
1693 }
1694 if (!IsUint(16, actual_count)) {
1695 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1696 return false;
1697 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001698 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001699 CHECK_LE(actual_count, max_count);
1700 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001701 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001702 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001703 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001704 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001705 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001706 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001707 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001708 LG << "Too many methods"; // TODO: VirtualMachineError
1709 return false;
1710 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001711 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001712 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001713 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1714 vtable->Set(i, virtual_method);
1715 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001716 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001717 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001718 }
1719 return true;
1720}
1721
1722bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001723 int miranda_count = 0;
1724 int miranda_alloc = 0;
1725 size_t super_ifcount;
1726 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001727 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001728 } else {
1729 super_ifcount = 0;
1730 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001731 size_t ifcount = super_ifcount;
1732 ifcount += klass->NumInterfaces();
1733 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001734 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001735 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001736 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001737 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001738 // DCHECK(klass->GetIfTableCount() == 0);
1739 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001740 return true;
1741 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001742 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001743 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001744 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1745 for (size_t i = 0; i < super_ifcount; i++) {
1746 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1747 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001748 }
1749 // Flatten the interface inheritance hierarchy.
1750 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001751 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001752 Class* interface = klass->GetInterface(i);
1753 DCHECK(interface != NULL);
1754 if (!interface->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001755 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1756 return false;
1757 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001758 iftable->Set(idx++, AllocInterfaceEntry(interface));
1759 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1760 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001761 }
1762 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001763 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001764 CHECK_EQ(idx, ifcount);
Brian Carlstrom86927212011-09-15 11:31:11 -07001765 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001766 return true;
1767 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001768 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001769 for (size_t i = 0; i < ifcount; ++i) {
1770 InterfaceEntry* interface_entry = iftable->Get(i);
1771 Class* interface = interface_entry->GetInterface();
1772 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1773 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001774 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001775 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1776 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001777 int32_t k;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001778 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1779 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001780 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1781 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001782 LG << "Implementation not public";
1783 return false;
1784 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001785 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001786 break;
1787 }
1788 }
1789 if (k < 0) {
1790 if (miranda_count == miranda_alloc) {
1791 miranda_alloc += 8;
1792 if (miranda_list.empty()) {
1793 miranda_list.resize(miranda_alloc);
1794 } else {
1795 miranda_list.resize(miranda_alloc);
1796 }
1797 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001798 Method* miranda_method = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001799 int mir;
1800 for (mir = 0; mir < miranda_count; mir++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001801 miranda_method = miranda_list[mir];
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001802 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001803 break;
1804 }
1805 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001806 // point the interface table at a phantom slot
1807 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001808 if (mir == miranda_count) {
1809 miranda_list[miranda_count++] = interface_method;
1810 }
1811 }
1812 }
1813 }
1814 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001815 int old_method_count = klass->NumVirtualMethods();
1816 int new_method_count = old_method_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001817 klass->SetVirtualMethods(
1818 klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001819
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001820 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1821 CHECK(vtable != NULL);
1822 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001823 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001824 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001825 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001826 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001827 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001828 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001829 meth->SetDeclaringClass(klass);
1830 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1831 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001832 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001833 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001834 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001835 // TODO: do not assign to the vtable field until it is fully constructed.
1836 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001837 }
1838 return true;
1839}
1840
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001841bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001842 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001843 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001844}
1845
1846bool ClassLinker::LinkStaticFields(Class* klass) {
1847 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001848 size_t allocated_class_size = klass->GetClassSize();
1849 bool success = LinkFields(klass, false);
1850 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001851 return success;
1852}
1853
Brian Carlstromdbc05252011-09-09 01:59:59 -07001854struct LinkFieldsComparator {
1855 bool operator()(const Field* field1, const Field* field2){
1856
1857 // First come reference fields, then 64-bit, and finally 32-bit
1858 const Class* type1 = field1->GetTypeDuringLinking();
1859 const Class* type2 = field2->GetTypeDuringLinking();
1860 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
1861 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
1862 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
1863 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
1864 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
1865 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
1866 if (order1 != order2) {
1867 return order1 < order2;
1868 }
1869
1870 // same basic group? then sort by string.
1871 std::string name1 = field1->GetName()->ToModifiedUtf8();
1872 std::string name2 = field2->GetName()->ToModifiedUtf8();
1873 return name1 < name2;
1874 }
1875};
1876
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001877bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001878 size_t num_fields =
1879 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1880
1881 ObjectArray<Field>* fields =
1882 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001883
1884 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07001885 size_t size;
1886 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001887 if (instance) {
1888 Class* super_class = klass->GetSuperClass();
1889 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001890 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001891 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001892 }
1893 size = field_offset.Uint32Value();
1894 } else {
1895 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07001896 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001897 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001898
Brian Carlstromdbc05252011-09-09 01:59:59 -07001899 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001900
Brian Carlstromdbc05252011-09-09 01:59:59 -07001901 // we want a relatively stable order so that adding new fields
1902 // minimizes distruption of C++ version such as Class and Method.
1903 std::deque<Field*> grouped_and_sorted_fields;
1904 for (size_t i = 0; i < num_fields; i++) {
1905 grouped_and_sorted_fields.push_back(fields->Get(i));
1906 }
1907 std::sort(grouped_and_sorted_fields.begin(),
1908 grouped_and_sorted_fields.end(),
1909 LinkFieldsComparator());
1910
1911 // References should be at the front.
1912 size_t current_field = 0;
1913 size_t num_reference_fields = 0;
1914 for (; current_field < num_fields; current_field++) {
1915 Field* field = grouped_and_sorted_fields.front();
1916 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001917 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07001918 bool isPrimitive = type != NULL && type->IsPrimitive();
1919 if (isPrimitive) {
1920 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001921 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001922 grouped_and_sorted_fields.pop_front();
1923 num_reference_fields++;
1924 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001925 field->SetOffset(field_offset);
1926 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001927 }
1928
1929 // Now we want to pack all of the double-wide fields together. If
1930 // we're not aligned, though, we want to shuffle one 32-bit field
1931 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001932 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
1933 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
1934 Field* field = grouped_and_sorted_fields[i];
1935 const Class* type = field->GetTypeDuringLinking();
1936 CHECK(type != NULL); // should only be working on primitive types
1937 DCHECK(type->IsPrimitive());
1938 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
1939 continue;
1940 }
1941 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001942 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001943 // drop the consumed field
1944 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
1945 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001946 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001947 // whether we found a 32-bit field for padding or not, we advance
1948 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001949 }
1950
1951 // Alignment is good, shuffle any double-wide fields forward, and
1952 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001953 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
1954 while (!grouped_and_sorted_fields.empty()) {
1955 Field* field = grouped_and_sorted_fields.front();
1956 grouped_and_sorted_fields.pop_front();
1957 const Class* type = field->GetTypeDuringLinking();
1958 CHECK(type != NULL); // should only be working on primitive types
1959 DCHECK(type->IsPrimitive());
1960 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001961 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001962 field_offset = MemberOffset(field_offset.Uint32Value() +
1963 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
1964 ? sizeof(uint64_t)
1965 : sizeof(uint32_t)));
1966 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967 }
1968
1969#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001970 // Make sure that all reference fields appear before
1971 // non-reference fields, and all double-wide fields are aligned.
1972 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07001973 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001974 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001975 if (false) { // enable to debug field layout
1976 LOG(INFO) << "LinkFields:"
1977 << " class=" << klass->GetDescriptor()->ToModifiedUtf8()
1978 << " field=" << field->GetName()->ToModifiedUtf8()
1979 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
1980 }
1981 const Class* type = field->GetTypeDuringLinking();
1982 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001983 if (!seen_non_ref) {
1984 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001985 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001986 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001987 } else {
1988 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001989 }
1990 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001991 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001992 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001993 }
1994#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001995 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001996 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07001997 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001998 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001999 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002000 klass->SetObjectSize(size);
2001 }
2002 } else {
2003 klass->SetNumReferenceStaticFields(num_reference_fields);
2004 klass->SetClassSize(size);
2005 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002006 return true;
2007}
2008
2009// Set the bitmap of reference offsets, refOffsets, from the ifields
2010// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002011void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002012 uint32_t reference_offsets = 0;
2013 Class* super_class = klass->GetSuperClass();
2014 if (super_class != NULL) {
2015 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002016 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002017 if (reference_offsets == CLASS_WALK_SUPER) {
2018 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002019 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002021 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002022 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002023}
2024
2025void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002026 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002027}
2028
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002029void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2030 uint32_t reference_offsets) {
2031 size_t num_reference_fields =
2032 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2033 : klass->NumReferenceStaticFieldsDuringLinking();
2034 const ObjectArray<Field>* fields =
2035 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002036 // All of the fields that contain object references are guaranteed
2037 // to be at the beginning of the fields list.
2038 for (size_t i = 0; i < num_reference_fields; ++i) {
2039 // Note that byte_offset is the offset from the beginning of
2040 // object, not the offset into instance data
2041 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002042 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002043 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2044 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2045 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002046 CHECK_NE(new_bit, 0U);
2047 reference_offsets |= new_bit;
2048 } else {
2049 reference_offsets = CLASS_WALK_SUPER;
2050 break;
2051 }
2052 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002053 // Update fields in klass
2054 if (instance) {
2055 klass->SetReferenceInstanceOffsets(reference_offsets);
2056 } else {
2057 klass->SetReferenceStaticOffsets(reference_offsets);
2058 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002059}
2060
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002061String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002062 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002063 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002064 if (resolved != NULL) {
2065 return resolved;
2066 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002067 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2068 int32_t utf16_length = dex_file.GetStringLength(string_id);
2069 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002070 // TODO: remote the const_cast below
2071 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002072 dex_cache->SetResolvedString(string_idx, string);
2073 return string;
2074}
2075
2076Class* ClassLinker::ResolveType(const DexFile& dex_file,
2077 uint32_t type_idx,
2078 DexCache* dex_cache,
2079 const ClassLoader* class_loader) {
2080 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002081 if (resolved == NULL) {
2082 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2083 if (descriptor[1] == '\0') {
2084 // only the descriptors of primitive types should be 1 character long
2085 resolved = FindPrimitiveClass(descriptor[0]);
2086 } else {
2087 resolved = FindClass(descriptor, class_loader);
2088 }
2089 if (resolved != NULL) {
2090 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2091 if (dex_cache != check->GetDexCache()) {
2092 if (check->GetClassLoader() != NULL) {
2093 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
2094 resolved = NULL;
2095 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002096 }
2097 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002098 if (resolved != NULL) {
2099 dex_cache->SetResolvedType(type_idx, resolved);
2100 } else {
2101 DCHECK(Thread::Current()->IsExceptionPending());
2102 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002103 }
2104 return resolved;
2105}
2106
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002107Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2108 uint32_t method_idx,
2109 DexCache* dex_cache,
2110 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002111 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002112 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2113 if (resolved != NULL) {
2114 return resolved;
2115 }
2116 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2117 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2118 if (klass == NULL) {
2119 return NULL;
2120 }
2121
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002122 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002123 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002124 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002125 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002126 } else if (klass->IsInterface()) {
2127 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002128 } else {
2129 resolved = klass->FindVirtualMethod(name, signature);
2130 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002131 if (resolved != NULL) {
2132 dex_cache->SetResolvedMethod(method_idx, resolved);
2133 } else {
2134 // DCHECK(Thread::Current()->IsExceptionPending());
2135 }
2136 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002137}
2138
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002139Field* ClassLinker::ResolveField(const DexFile& dex_file,
2140 uint32_t field_idx,
2141 DexCache* dex_cache,
2142 const ClassLoader* class_loader,
2143 bool is_static) {
2144 Field* resolved = dex_cache->GetResolvedField(field_idx);
2145 if (resolved != NULL) {
2146 return resolved;
2147 }
2148 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2149 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2150 if (klass == NULL) {
2151 return NULL;
2152 }
2153
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002154 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002155 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2156 // TODO: LinkageError?
2157 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002158 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002159 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002160 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002161 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002162 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002163 if (resolved != NULL) {
2164 dex_cache->SetResolvedfield(field_idx, resolved);
2165 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002166 // TODO: DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002167 }
2168 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002169}
2170
Elliott Hughese27955c2011-08-26 15:21:24 -07002171size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002172 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002173 return classes_.size();
2174}
2175
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002176} // namespace art