blob: 0f02d09fd891de3d3cbb3473319cf9d1dd4f99d5 [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->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700133
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700134 // Setup the char class to be used for char[]
135 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
136
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700137 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700138 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700139 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700140 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700141
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700142 // Setup String
143 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
144 String::SetClass(java_lang_String);
145 java_lang_String->SetObjectSize(sizeof(String));
146 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400147
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700148 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700149 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
150 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
151 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
152 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
153 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700154
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700155 // Create storage for root classes, save away our work so far (requires
156 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700157 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700158 SetClassRoot(kJavaLangClass, java_lang_Class);
159 SetClassRoot(kJavaLangObject, java_lang_Object);
160 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700161 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700162 SetClassRoot(kJavaLangString, java_lang_String);
163
164 // Setup the primitive type classes.
165 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
166 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700167 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
168 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
169 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
170 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
171 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
172 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
173
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700174 // Create array interface entries to populate once we can load system classes
175 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700176 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700177
178 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
179 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700180 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700181 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
182 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700183 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700184
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700185 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700186
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700187 // setup boot_class_path_ and register class_path now that we can
188 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700189 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700190 const DexFile* dex_file = boot_class_path[i];
191 CHECK(dex_file != NULL);
192 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700193 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700194 for (size_t i = 0; i != class_path.size(); ++i) {
195 const DexFile* dex_file = class_path[i];
196 CHECK(dex_file != NULL);
197 RegisterDexFile(*dex_file);
198 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199
200 // Field and Method are necessary so that FindClass can link members
201 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
202 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700203 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700204 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
205 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
206 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
207 Field::SetClass(java_lang_reflect_Field);
208
209 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700210 java_lang_reflect_Method->SetDescriptor(
211 intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700212 CHECK(java_lang_reflect_Method != NULL);
213 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
214 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
215 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
216 Method::SetClass(java_lang_reflect_Method);
217
218 // now we can use FindSystemClass
219
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700220 // run char class through InitializePrimitiveClass to finish init
221 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
222 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
223
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700224 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700225 java_lang_Object->SetStatus(Class::kStatusNotReady);
226 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
227 CHECK_EQ(java_lang_Object, Object_class);
228 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
229 java_lang_String->SetStatus(Class::kStatusNotReady);
230 Class* String_class = FindSystemClass("Ljava/lang/String;");
231 CHECK_EQ(java_lang_String, String_class);
232 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
233
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700234 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700235 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
236 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
237
238 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
239 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
240
241 Class* found_char_array_class = FindSystemClass("[C");
242 CHECK_EQ(char_array_class, found_char_array_class);
243
244 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
245 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
246
247 Class* found_int_array_class = FindSystemClass("[I");
248 CHECK_EQ(int_array_class, found_int_array_class);
249
250 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
251 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
252
253 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
254 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
255
256 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
257 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
258
259 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
260 CHECK_EQ(object_array_class, found_object_array_class);
261
262 // Setup the single, global copies of "interfaces" and "iftable"
263 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
264 CHECK(java_lang_Cloneable != NULL);
265 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
266 CHECK(java_io_Serializable != NULL);
267 CHECK(array_interfaces_ != NULL);
268 array_interfaces_->Set(0, java_lang_Cloneable);
269 array_interfaces_->Set(1, java_io_Serializable);
270 // We assume that Cloneable/Serializable don't have superinterfaces --
271 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700272 // supers as well.
273 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
274 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275
276 // Sanity check Object[]'s interfaces
277 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
278 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700279
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700280 // run Class, Field, and Method through FindSystemClass.
281 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700282 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700283 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284
285 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700286 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700287 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288
289 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700290 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700291 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700292
293 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
294 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295 java_lang_ref_FinalizerReference->SetAccessFlags(
296 java_lang_ref_FinalizerReference->GetAccessFlags() |
297 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700298 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299 java_lang_ref_PhantomReference->SetAccessFlags(
300 java_lang_ref_PhantomReference->GetAccessFlags() |
301 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700302 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303 java_lang_ref_SoftReference->SetAccessFlags(
304 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700305 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306 java_lang_ref_WeakReference->SetAccessFlags(
307 java_lang_ref_WeakReference->GetAccessFlags() |
308 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700309
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700310 // Setup the ClassLoaders, adjusting the object_size_ as necessary
311 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
312 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
313 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
314 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
315
316 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
317 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
318 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
319
320 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
321 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
322 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
323 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
324
325 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700326 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
327 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700328 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700329
Brian Carlstroma663ea52011-08-19 23:33:41 -0700330 FinishInit();
331}
332
333void ClassLinker::FinishInit() {
Brian Carlstrom16192862011-09-12 17:50:06 -0700334
335 // Let the heap know some key offsets into java.lang.ref instances
336 // NB we hard code the field indexes here rather than using FindInstanceField
337 // as the types of the field can't be resolved prior to the runtime being
338 // fully initialized
339 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
340 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
341
342 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
343 CHECK(pendingNext->GetName()->Equals("pendingNext"));
344 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
345
346 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
347 CHECK(queue->GetName()->Equals("queue"));
348 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
349 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
350
351 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
352 CHECK(queueNext->GetName()->Equals("queueNext"));
353 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
354
355 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
356 CHECK(referent->GetName()->Equals("referent"));
357 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
358
359 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
360 CHECK(zombie->GetName()->Equals("zombie"));
361 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
362
363 Heap::SetReferenceOffsets(referent->GetOffset(),
364 queue->GetOffset(),
365 queueNext->GetOffset(),
366 pendingNext->GetOffset(),
367 zombie->GetOffset());
368
Brian Carlstroma663ea52011-08-19 23:33:41 -0700369 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700370 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700371 ClassRoot class_root = static_cast<ClassRoot>(i);
372 Class* klass = GetClassRoot(class_root);
373 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700375 // note SetClassRoot does additional validation.
376 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700377 }
378
379 // disable the slow paths in FindClass and CreatePrimitiveClass now
380 // that Object, Class, and Object[] are setup
381 init_done_ = true;
382}
383
Brian Carlstromc74255f2011-09-11 22:47:39 -0700384struct ClassLinker::InitFromImageCallbackState {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700385 ClassLinker* class_linker;
386
387 Class* class_roots[kClassRootsMax];
388
389 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
390 Table descriptor_to_class_root;
391
Brian Carlstroma663ea52011-08-19 23:33:41 -0700392 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
393 Set dex_caches;
394};
395
Brian Carlstromc74255f2011-09-11 22:47:39 -0700396void ClassLinker::InitFromImage(const std::vector<const DexFile*>& boot_class_path,
397 const std::vector<const DexFile*>& class_path) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700398 CHECK(!init_done_);
399
400 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
401 DCHECK(heap_bitmap != NULL);
402
Brian Carlstromc74255f2011-09-11 22:47:39 -0700403 InitFromImageCallbackState state;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700404 state.class_linker = this;
405 for (size_t i = 0; i < kClassRootsMax; i++) {
406 ClassRoot class_root = static_cast<ClassRoot>(i);
407 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
408 }
409
410 // reinit clases_ table
Brian Carlstromc74255f2011-09-11 22:47:39 -0700411 heap_bitmap->Walk(InitFromImageCallback, &state);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700412
413 // reinit class_roots_
414 Class* object_array_class = state.class_roots[kObjectArrayClass];
415 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
416 for (size_t i = 0; i < kClassRootsMax; i++) {
417 ClassRoot class_root = static_cast<ClassRoot>(i);
418 SetClassRoot(class_root, state.class_roots[class_root]);
419 }
420
Brian Carlstroma663ea52011-08-19 23:33:41 -0700421 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
423 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700424
425 // build a map from location to DexCache to match up with DexFile::GetLocation
426 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Brian Carlstromc74255f2011-09-11 22:47:39 -0700427 typedef InitFromImageCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700428 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
429 DexCache* dex_cache = *it;
430 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
431 location_to_dex_cache[location] = dex_cache;
432 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700433 CHECK_EQ(boot_class_path.size() + class_path.size(),
434 location_to_dex_cache.size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700435
436 // reinit boot_class_path with DexFile arguments and found DexCaches
437 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700438 const DexFile* dex_file = boot_class_path[i];
439 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700440 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700441 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700442 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700443 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700444
445 // register class_path with DexFile arguments and found DexCaches
446 for (size_t i = 0; i != class_path.size(); ++i) {
447 const DexFile* dex_file = class_path[i];
448 CHECK(dex_file != NULL);
449 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
450 CHECK(dex_cache != NULL) << dex_file->GetLocation();
451 RegisterDexFile(*dex_file, dex_cache);
452 }
453
Brian Carlstroma663ea52011-08-19 23:33:41 -0700454 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455 Field::SetClass(GetClassRoot(kJavaLangReflectField));
456 Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700457 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
458 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
459 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
460 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
461 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
462 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
463 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
464 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700465 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700466 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700467
468 FinishInit();
469}
470
Brian Carlstrom78128a62011-09-15 17:21:19 -0700471void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700472 DCHECK(obj != NULL);
473 DCHECK(arg != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700474 InitFromImageCallbackState* state = reinterpret_cast<InitFromImageCallbackState*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700475
Brian Carlstromc74255f2011-09-11 22:47:39 -0700476 if (obj->IsString()) {
477 state->class_linker->intern_table_->RegisterStrong(obj->AsString());
478 return;
479 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700480 if (!obj->IsClass()) {
481 return;
482 }
483 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700484 // TODO: restore ClassLoader's list of DexFiles after image load
485 // CHECK(klass->GetClassLoader() == NULL);
486 const ClassLoader* class_loader = klass->GetClassLoader();
487 if (class_loader != NULL) {
488 // TODO: replace this hack with something based on command line arguments
489 Thread::Current()->SetClassLoaderOverride(class_loader);
490 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700491
492 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700493 // restore class to ClassLinker::classes_ table
494 state->class_linker->InsertClass(descriptor, klass);
495
496 // note DexCache to match with DexFile later
497 DexCache* dex_cache = klass->GetDexCache();
498 if (dex_cache != NULL) {
499 state->dex_caches.insert(dex_cache);
500 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700501 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700502 }
503
504 // check if this is a root, if so, register it
Brian Carlstromc74255f2011-09-11 22:47:39 -0700505 typedef InitFromImageCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700506 It it = state->descriptor_to_class_root.find(descriptor);
507 if (it != state->descriptor_to_class_root.end()) {
508 ClassRoot class_root = it->second;
509 state->class_roots[class_root] = klass;
510 }
511}
512
513// Keep in sync with InitCallback. Anything we visit, we need to
514// reinit references to when reinitializing a ClassLinker from a
515// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700516void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
517 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700518
519 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700520 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700521 }
522
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700523 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700524 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700526 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700527 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700528 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700529 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700530
Elliott Hughes410c0c82011-09-01 17:58:25 -0700531 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700532}
533
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700534ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700535 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700536 Field::ResetClass();
537 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700538 BooleanArray::ResetArrayClass();
539 ByteArray::ResetArrayClass();
540 CharArray::ResetArrayClass();
541 DoubleArray::ResetArrayClass();
542 FloatArray::ResetArrayClass();
543 IntArray::ResetArrayClass();
544 LongArray::ResetArrayClass();
545 ShortArray::ResetArrayClass();
546 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700547 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700548}
549
550DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700551 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700552 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700553 AllocObjectArray<String>(dex_file.NumStringIds()),
554 AllocObjectArray<Class>(dex_file.NumTypeIds()),
555 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700556 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700557 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
558 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700559 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700560}
561
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700562CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
563 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700564}
565
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700566InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
567 DCHECK(interface->IsInterface());
568 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
569 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
570 interface_entry->SetInterface(interface);
571 return interface_entry;
572}
573
Brian Carlstrom4873d462011-08-21 15:23:39 -0700574Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
575 DCHECK_GE(class_size, sizeof(Class));
576 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700577 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
578 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700579 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700580}
581
Brian Carlstrom4873d462011-08-21 15:23:39 -0700582Class* ClassLinker::AllocClass(size_t class_size) {
583 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700584}
585
Jesse Wilson35baaab2011-08-10 16:18:03 -0400586Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700587 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700588}
589
590Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700591 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700592}
593
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700594ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
595 return ObjectArray<StackTraceElement>::Alloc(
596 GetClassRoot(kJavaLangStackTraceElementArrayClass),
597 length);
598}
599
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700600Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700601 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700602 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700603 if (class_loader != NULL) {
604 Class* klass = FindClass(descriptor, NULL);
605 if (klass != NULL) {
606 return klass;
607 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700608 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700609 }
610
Carl Shapirob5573532011-07-12 18:22:59 -0700611 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700612 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700613 CHECK(!self->IsExceptionPending());
614 // Find the class in the loaded classes table.
615 Class* klass = LookupClass(descriptor, class_loader);
616 if (klass == NULL) {
617 // Class is not yet loaded.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700618 if (descriptor[0] == '[' && descriptor[1] != '\0') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700619 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700620 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700621 const DexFile::ClassPath& class_path = ((class_loader != NULL)
622 ? ClassLoader::GetClassPath(class_loader)
623 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700624 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700625 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700626 std::string name(PrintableString(descriptor));
627 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
628 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700629 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700630 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700631 const DexFile& dex_file = *pair.first;
632 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700633 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700634 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700635 if (!init_done_) {
636 // finish up init of hand crafted class_roots_
637 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700638 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700639 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700640 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400641 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700642 klass = GetClassRoot(kJavaLangString);
643 } else if (descriptor == "Ljava/lang/reflect/Field;") {
644 klass = GetClassRoot(kJavaLangReflectField);
645 } else if (descriptor == "Ljava/lang/reflect/Method;") {
646 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700647 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700648 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700649 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700650 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700651 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700652 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700653 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700654 klass->SetDexCache(dex_cache);
655 LoadClass(dex_file, dex_class_def, klass, class_loader);
656 // Check for a pending exception during load
657 if (self->IsExceptionPending()) {
658 // TODO: free native allocations in klass
659 return NULL;
660 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700661 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700662 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700663 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700664 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700665 if (!success) {
666 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700667 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700668 // TODO: free native allocations in klass
669 klass = LookupClass(descriptor, class_loader);
670 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700671 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700672 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700673 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700674 CHECK(!klass->IsLoaded());
675 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700676 // Loading failed.
677 // TODO: CHECK(self->IsExceptionPending());
678 lock.NotifyAll();
679 return NULL;
680 }
681 CHECK(klass->IsLoaded());
682 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700683 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700684 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700685 // Linking failed.
686 // TODO: CHECK(self->IsExceptionPending());
687 lock.NotifyAll();
688 return NULL;
689 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700690 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700691 }
692 }
693 }
694 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700695 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700696 ObjectLock lock(klass);
697 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700698 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700699 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700700 return NULL;
701 }
702 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700703 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700704 lock.Wait();
705 }
706 }
707 if (klass->IsErroneous()) {
708 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
709 return NULL;
710 }
711 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700712 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700713 CHECK(!self->IsExceptionPending());
714 return klass;
715}
716
Brian Carlstrom4873d462011-08-21 15:23:39 -0700717// Precomputes size that will be needed for Class, matching LinkStaticFields
718size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
719 const DexFile::ClassDef& dex_class_def) {
720 const byte* class_data = dex_file.GetClassData(dex_class_def);
721 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
722 size_t num_static_fields = header.static_fields_size_;
723 size_t num_ref = 0;
724 size_t num_32 = 0;
725 size_t num_64 = 0;
726 if (num_static_fields != 0) {
727 uint32_t last_idx = 0;
728 for (size_t i = 0; i < num_static_fields; ++i) {
729 DexFile::Field dex_field;
730 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
731 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
732 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
733 char c = descriptor[0];
734 if (c == 'L' || c == '[') {
735 num_ref++;
736 } else if (c == 'J' || c == 'D') {
737 num_64++;
738 } else {
739 num_32++;
740 }
741 }
742 }
743
744 // start with generic class data
745 size_t size = sizeof(Class);
746 // follow with reference fields which must be contiguous at start
747 size += (num_ref * sizeof(uint32_t));
748 // if there are 64-bit fields to add, make sure they are aligned
749 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
750 if (num_32 != 0) {
751 // use an available 32-bit field for padding
752 num_32--;
753 }
754 size += sizeof(uint32_t); // either way, we are adding a word
755 DCHECK_EQ(size, RoundUp(size, 8));
756 }
757 // tack on any 64-bit fields now that alignment is assured
758 size += (num_64 * sizeof(uint64_t));
759 // tack on any remaining 32-bit fields
760 size += (num_32 * sizeof(uint32_t));
761 return size;
762}
763
Brian Carlstromf615a612011-07-23 12:50:34 -0700764void ClassLinker::LoadClass(const DexFile& dex_file,
765 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700766 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700767 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700768 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700769 CHECK(klass->GetDexCache() != NULL);
770 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700771 const byte* class_data = dex_file.GetClassData(dex_class_def);
772 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700773
Brian Carlstromf615a612011-07-23 12:50:34 -0700774 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700775 CHECK(descriptor != NULL);
776
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700777 klass->SetClass(GetClassRoot(kJavaLangClass));
778 if (klass->GetDescriptor() != NULL) {
779 DCHECK(klass->GetDescriptor()->Equals(descriptor));
780 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700781 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700782 }
783 uint32_t access_flags = dex_class_def.access_flags_;
784 // Make sure there aren't any "bonus" flags set, since we use them for runtime
785 // state.
786 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
787 klass->SetAccessFlags(access_flags);
788 klass->SetClassLoader(class_loader);
789 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
790 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700791
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700792 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700793
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700794 size_t num_static_fields = header.static_fields_size_;
795 size_t num_instance_fields = header.instance_fields_size_;
796 size_t num_direct_methods = header.direct_methods_size_;
797 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700798
Brian Carlstromc74255f2011-09-11 22:47:39 -0700799 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700800
801 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700802 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700803
804 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700805 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700806 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700807 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700808 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700809 DexFile::Field dex_field;
810 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400811 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700812 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700813 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700814 }
815 }
816
817 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700818 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700819 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700820 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700821 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700822 DexFile::Field dex_field;
823 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400824 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700825 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700826 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700827 }
828 }
829
830 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700831 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700832 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700833 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700834 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700835 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700836 DexFile::Method dex_method;
837 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700838 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700839 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700840 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700841 // TODO: register maps
842 }
843 }
844
845 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700846 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700847 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700848 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700849 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700850 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700851 DexFile::Method dex_method;
852 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700853 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700854 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700855 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700856 // TODO: register maps
857 }
858 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700859}
860
Brian Carlstromf615a612011-07-23 12:50:34 -0700861void ClassLinker::LoadInterfaces(const DexFile& dex_file,
862 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700863 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700864 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700865 if (list != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700866 klass->SetInterfaces(AllocObjectArray<Class>(list->Size()));
867 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
868 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700869 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700870 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700871 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700872 }
873 }
874}
875
Brian Carlstromf615a612011-07-23 12:50:34 -0700876void ClassLinker::LoadField(const DexFile& dex_file,
877 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700878 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700879 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700880 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700881 dst->SetDeclaringClass(klass);
882 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
883 dst->SetTypeIdx(field_id.type_idx_);
884 dst->SetAccessFlags(src.access_flags_);
885
886 // In order to access primitive types using GetTypeDuringLinking we need to
887 // ensure they are resolved into the dex cache
888 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
889 if (descriptor[1] == '\0') {
890 // only the descriptors of primitive types should be 1 character long
891 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
892 DCHECK(resolved->IsPrimitive());
893 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700894}
895
Brian Carlstromf615a612011-07-23 12:50:34 -0700896void ClassLinker::LoadMethod(const DexFile& dex_file,
897 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700898 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700899 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700900 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700901 dst->SetDeclaringClass(klass);
902 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700903 {
904 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700905 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700906 dst->SetSignature(intern_table_->InternStrong(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700907 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700908 dst->SetProtoIdx(method_id.proto_idx_);
909 dst->SetCodeItemOffset(src.code_off_);
910 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700911 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700912 dst->SetAccessFlags(src.access_flags_);
913 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700914
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700915 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
916 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
917 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
918 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
919 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
920 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700921
Brian Carlstrom934486c2011-07-12 23:42:50 -0700922 // TODO: check for finalize method
923
Brian Carlstromf615a612011-07-23 12:50:34 -0700924 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700925 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700926 dst->SetNumRegisters(code_item->registers_size_);
927 dst->SetNumIns(code_item->ins_size_);
928 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700929 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700930 uint16_t num_args = Method::NumArgRegisters(shorty);
931 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700932 ++num_args;
933 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700934 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700935 // TODO: native methods
936 }
937}
938
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700939void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700940 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
941}
942
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700943void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700944 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700945 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700946 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700947}
948
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700949void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700950 RegisterDexFile(dex_file, AllocDexCache(dex_file));
951}
952
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700953void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700954 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700955 CHECK(dex_cache != NULL) << dex_file.GetLocation();
956 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700957 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700958 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700959}
960
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700961const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700962 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700963 for (size_t i = 0; i != dex_caches_.size(); ++i) {
964 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700965 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700966 }
967 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700968 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700969 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700970}
971
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700972DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700973 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -0700974 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700975 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700976 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700977 }
978 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700979 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700980 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700981}
982
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700983Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
984 const char* descriptor,
985 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700986 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700987 CHECK(primitive_class != NULL);
988 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
989 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
990 primitive_class->SetPrimitiveType(type);
991 primitive_class->SetStatus(Class::kStatusInitialized);
992 bool success = InsertClass(descriptor, primitive_class);
993 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
994 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -0700995}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700996
Brian Carlstrombe977852011-07-19 14:54:54 -0700997// Create an array class (i.e. the class object for the array, not the
998// array itself). "descriptor" looks like "[C" or "[[[[B" or
999// "[Ljava/lang/String;".
1000//
1001// If "descriptor" refers to an array of primitives, look up the
1002// primitive type's internally-generated class object.
1003//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001004// "class_loader" is the class loader of the class that's referring to
1005// us. It's used to ensure that we're looking for the element type in
1006// the right context. It does NOT become the class loader for the
1007// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001008//
1009// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001010Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001011 const ClassLoader* class_loader) {
1012 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001013
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001014 // Identify the underlying component type
1015 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001016 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001017 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001018 return NULL;
1019 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001020
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001021 // See if the component type is already loaded. Array classes are
1022 // always associated with the class loader of their underlying
1023 // element type -- an array of Strings goes with the loader for
1024 // java/lang/String -- so we need to look for it there. (The
1025 // caller should have checked for the existence of the class
1026 // before calling here, but they did so with *their* class loader,
1027 // not the component type's loader.)
1028 //
1029 // If we find it, the caller adds "loader" to the class' initiating
1030 // loader list, which should prevent us from going through this again.
1031 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001032 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001033 // are the same, because our caller (FindClass) just did the
1034 // lookup. (Even if we get this wrong we still have correct behavior,
1035 // because we effectively do this lookup again when we add the new
1036 // class to the hash table --- necessary because of possible races with
1037 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001038 if (class_loader != component_type->GetClassLoader()) {
1039 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001040 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001041 return new_class;
1042 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001043 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001044
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001045 // Fill out the fields in the Class.
1046 //
1047 // It is possible to execute some methods against arrays, because
1048 // all arrays are subclasses of java_lang_Object_, so we need to set
1049 // up a vtable. We can just point at the one in java_lang_Object_.
1050 //
1051 // Array classes are simple enough that we don't need to do a full
1052 // link step.
1053
1054 Class* new_class = NULL;
1055 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001056 // Classes that were hand created, ie not by FindSystemClass
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001057 if (descriptor == "[Ljava/lang/Object;") {
1058 new_class = GetClassRoot(kObjectArrayClass);
1059 } else if (descriptor == "[C") {
1060 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001061 } else if (descriptor == "[I") {
1062 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001063 }
1064 }
1065 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001066 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001067 if (new_class == NULL) {
1068 return NULL;
1069 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001070 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001071 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001072 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001073 if (new_class->GetDescriptor() != NULL) {
1074 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1075 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001076 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001077 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001078 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001079 new_class->SetSuperClass(java_lang_Object);
1080 new_class->SetVTable(java_lang_Object->GetVTable());
1081 new_class->SetPrimitiveType(Class::kPrimNot);
1082 new_class->SetClassLoader(component_type->GetClassLoader());
1083 new_class->SetStatus(Class::kStatusInitialized);
1084 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001085 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001086
1087
1088 // All arrays have java/lang/Cloneable and java/io/Serializable as
1089 // interfaces. We need to set that up here, so that stuff like
1090 // "instanceof" works right.
1091 //
1092 // Note: The GC could run during the call to FindSystemClass,
1093 // so we need to make sure the class object is GC-valid while we're in
1094 // there. Do this by clearing the interface list so the GC will just
1095 // think that the entries are null.
1096
1097
1098 // Use the single, global copies of "interfaces" and "iftable"
1099 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001100 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001101 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001102
1103 // Inherit access flags from the component type. Arrays can't be
1104 // used as a superclass or interface, so we want to add "final"
1105 // and remove "interface".
1106 //
1107 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001108 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001109 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001110 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1111 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001112
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001113 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001114 return new_class;
1115 }
1116 // Another thread must have loaded the class after we
1117 // started but before we finished. Abandon what we've
1118 // done.
1119 //
1120 // (Yes, this happens.)
1121
1122 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001123 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001124 DCHECK(other_class != NULL);
1125 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001126}
1127
1128Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001129 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001130 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001131 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001132 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001133 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001134 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001135 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001136 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001137 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001138 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001139 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001140 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001141 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001142 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001143 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001144 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001145 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001146 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001147 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001148 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001149 std::string printable_type(PrintableChar(type));
1150 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1151 "Not a primitive type: %s", printable_type.c_str());
1152 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001153}
1154
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001155bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1156 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001157 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001158 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001159 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001160}
1161
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001162Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001163 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001164 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001165 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001166 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001167 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001168 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001169 return klass;
1170 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001171 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001172 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001173}
1174
jeffhao98eacac2011-09-14 16:11:53 -07001175void ClassLinker::VerifyClass(Class* klass) {
1176 if (klass->IsVerified()) {
1177 return;
1178 }
1179
1180 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
1181
1182 klass->SetStatus(Class::kStatusVerifying);
1183 if (!DexVerifier::VerifyClass(klass)) {
1184 LOG(ERROR) << "Verification failed on class "
1185 << klass->GetDescriptor()->ToModifiedUtf8();
1186 Object* exception = Thread::Current()->GetException();
1187 klass->SetVerifyErrorClass(exception->GetClass());
1188 klass->SetStatus(Class::kStatusError);
1189 return;
1190 }
1191
1192 klass->SetStatus(Class::kStatusVerified);
1193}
1194
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001195bool ClassLinker::InitializeClass(Class* klass) {
1196 CHECK(klass->GetStatus() == Class::kStatusResolved ||
jeffhao98eacac2011-09-14 16:11:53 -07001197 klass->GetStatus() == Class::kStatusVerified ||
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001198 klass->GetStatus() == Class::kStatusInitializing ||
1199 klass->GetStatus() == Class::kStatusError)
Elliott Hughes54e7df12011-09-16 11:47:04 -07001200 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001201
Carl Shapirob5573532011-07-12 18:22:59 -07001202 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001203
1204 {
1205 ObjectLock lock(klass);
1206
1207 if (klass->GetStatus() < Class::kStatusVerified) {
1208 if (klass->IsErroneous()) {
1209 LG << "re-initializing failed class"; // TODO: throw
1210 return false;
1211 }
1212
jeffhao98eacac2011-09-14 16:11:53 -07001213 VerifyClass(klass);
1214 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001215 return false;
1216 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001217 }
1218
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001219 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001220 return true;
1221 }
1222
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001223 while (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001224 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001225 if (klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001226 // Yes. That's fine.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001227 return true;
1228 }
1229
1230 CHECK(!self->IsExceptionPending());
1231
1232 lock.Wait(); // TODO: check for interruption
1233
1234 // When we wake up, repeat the test for init-in-progress. If
1235 // there's an exception pending (only possible if
1236 // "interruptShouldThrow" was set), bail out.
1237 if (self->IsExceptionPending()) {
1238 CHECK(false);
1239 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1240 klass->SetStatus(Class::kStatusError);
1241 return false;
1242 }
1243 if (klass->GetStatus() == Class::kStatusInitializing) {
1244 continue;
1245 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001246 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001247 klass->GetStatus() == Class::kStatusError);
1248 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001249 // The caller wants an exception, but it was thrown in a
1250 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001251 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1252 return false;
1253 }
1254 return true; // otherwise, initialized
1255 }
1256
1257 // see if we failed previously
1258 if (klass->IsErroneous()) {
1259 // might be wise to unlock before throwing; depends on which class
1260 // it is that we have locked
1261
1262 // TODO: throwEarlierClassFailure(klass);
1263 return false;
1264 }
1265
1266 if (!ValidateSuperClassDescriptors(klass)) {
1267 klass->SetStatus(Class::kStatusError);
1268 return false;
1269 }
1270
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001271 DCHECK(klass->GetStatus() < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001272
Elliott Hughesdcc24742011-09-07 14:02:44 -07001273 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001274 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001275 }
1276
1277 if (!InitializeSuperClass(klass)) {
1278 return false;
1279 }
1280
1281 InitializeStaticFields(klass);
1282
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001283 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001284 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001285 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001286 }
1287
1288 {
1289 ObjectLock lock(klass);
1290
1291 if (self->IsExceptionPending()) {
1292 klass->SetStatus(Class::kStatusError);
1293 } else {
1294 klass->SetStatus(Class::kStatusInitialized);
1295 }
1296 lock.NotifyAll();
1297 }
1298
1299 return true;
1300}
1301
1302bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1303 if (klass->IsInterface()) {
1304 return true;
1305 }
1306 // begin with the methods local to the superclass
1307 if (klass->HasSuperClass() &&
1308 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1309 const Class* super = klass->GetSuperClass();
1310 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001311 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001312 if (method != super->GetVirtualMethod(i) &&
1313 !HasSameMethodDescriptorClasses(method, super, klass)) {
1314 LG << "Classes resolve differently in superclass";
1315 return false;
1316 }
1317 }
1318 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001319 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1320 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1321 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001322 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1323 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001324 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001325 if (!HasSameMethodDescriptorClasses(method, interface,
1326 method->GetClass())) {
1327 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1328 return false;
1329 }
1330 }
1331 }
1332 }
1333 return true;
1334}
1335
1336bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001337 const Class* klass1,
1338 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001339 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001340 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001341 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001342 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001343 const char* descriptor = it->GetDescriptor();
1344 if (descriptor == NULL) {
1345 break;
1346 }
1347 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1348 // Found a non-primitive type.
1349 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1350 return false;
1351 }
1352 }
1353 }
1354 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001355 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001356 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1357 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1358 return false;
1359 }
1360 }
1361 return true;
1362}
1363
1364// Returns true if classes referenced by the descriptor are the
1365// same classes in klass1 as they are in klass2.
1366bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001367 const Class* klass1,
1368 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001369 CHECK(descriptor != NULL);
1370 CHECK(klass1 != NULL);
1371 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001372 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001373 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001374 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001375 // TODO: found2 == NULL
1376 // TODO: lookup found1 in initiating loader list
1377 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001378 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001379 if (found1 == found2) {
1380 return true;
1381 } else {
1382 return false;
1383 }
1384 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001385 return true;
1386}
1387
1388bool ClassLinker::InitializeSuperClass(Class* klass) {
1389 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001390 if (!klass->IsInterface() && klass->HasSuperClass()) {
1391 Class* super_class = klass->GetSuperClass();
1392 if (super_class->GetStatus() != Class::kStatusInitialized) {
1393 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001394 Thread* self = Thread::Current();
1395 klass->MonitorEnter(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001396 bool super_initialized = InitializeClass(super_class);
Elliott Hughes5f791332011-09-15 17:45:30 -07001397 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001398 // TODO: check for a pending exception
1399 if (!super_initialized) {
1400 klass->SetStatus(Class::kStatusError);
1401 klass->NotifyAll();
1402 return false;
1403 }
1404 }
1405 }
1406 return true;
1407}
1408
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001409bool ClassLinker::EnsureInitialized(Class* c) {
1410 CHECK(c != NULL);
1411 if (c->IsInitialized()) {
1412 return true;
1413 }
1414
Elliott Hughes5f791332011-09-15 17:45:30 -07001415 Thread* self = Thread::Current();
1416 c->MonitorEnter(self);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001417 InitializeClass(c);
Elliott Hughes5f791332011-09-15 17:45:30 -07001418 c->MonitorExit(self);
1419 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001420}
1421
Brian Carlstromb9edb842011-08-28 16:31:06 -07001422StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1423 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001424 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1425 Class* klass = class_linker->ResolveType(type_idx, referrer);
1426 if (klass == NULL) {
1427 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1428 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001429 // If we are the <clinit> of this class, just return our storage.
1430 //
1431 // Do not set the DexCache InitializedStaticStorage, since that
1432 // implies <clinit> has finished running.
1433 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1434 return klass;
1435 }
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001436 if (!class_linker->EnsureInitialized(klass)) {
1437 CHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001438 UNIMPLEMENTED(FATAL) << "throw exception due to class initialization problem";
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001439 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001440 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001441 return klass;
1442}
1443
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001444void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1445 Class* c, std::map<int, Field*>& field_map) {
1446 const ClassLoader* cl = c->GetClassLoader();
1447 const byte* class_data = dex_file.GetClassData(dex_class_def);
1448 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1449 uint32_t last_idx = 0;
1450 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1451 DexFile::Field dex_field;
1452 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1453 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1454 }
1455}
1456
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001457void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001458 size_t num_static_fields = klass->NumStaticFields();
1459 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001460 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001461 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001462 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001463 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001464 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001465 return;
1466 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001467 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001468 const DexFile& dex_file = FindDexFile(dex_cache);
1469 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001470 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001471
1472 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1473 std::map<int, Field*> field_map;
1474 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1475
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001476 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001477 if (addr == NULL) {
1478 // All this class' static fields have default values.
1479 return;
1480 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001481 size_t array_size = DecodeUnsignedLeb128(&addr);
1482 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001483 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001484 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001485 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001486 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001487 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001488 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001489 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001490 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001491 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001492 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001493 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001494 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001495 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001496 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001497 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001498 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001499 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001500 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001501 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001502 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001503 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001504 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001505 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001506 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001507 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001508 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001509 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001510 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001511 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001512 break;
1513 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001514 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001515 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001516 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001517 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001518 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001519 break;
1520 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001521 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001522 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001523 }
1524}
1525
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001526bool ClassLinker::LinkClass(Class* klass) {
1527 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001528 if (!LinkSuperClass(klass)) {
1529 return false;
1530 }
1531 if (!LinkMethods(klass)) {
1532 return false;
1533 }
1534 if (!LinkInstanceFields(klass)) {
1535 return false;
1536 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001537 if (!LinkStaticFields(klass)) {
1538 return false;
1539 }
1540 CreateReferenceInstanceOffsets(klass);
1541 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001542 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1543 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001544 return true;
1545}
1546
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001547bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001548 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1549 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1550 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001551 if (super_class == NULL) {
1552 LG << "Failed to resolve superclass";
1553 return false;
1554 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001555 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001556 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001557 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1558 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1559 Class *interface = ResolveType(dex_file, idx, klass);
1560 klass->SetInterface(i, interface);
1561 if (interface == NULL) {
1562 LG << "Failed to resolve interface";
1563 return false;
1564 }
1565 // Verify
1566 if (!klass->CanAccess(interface)) {
1567 LG << "Inaccessible interface";
1568 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001569 }
1570 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001571 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001572 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001573 return true;
1574}
1575
1576bool ClassLinker::LinkSuperClass(Class* klass) {
1577 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001578 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001579 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001580 if (super != NULL) {
1581 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1582 return false;
1583 }
1584 // TODO: clear finalize attribute
1585 return true;
1586 }
1587 if (super == NULL) {
1588 LG << "No superclass defined"; // TODO: LinkageError
1589 return false;
1590 }
1591 // Verify
1592 if (super->IsFinal()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001593 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001594 return false;
1595 }
1596 if (super->IsInterface()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001597 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001598 return false;
1599 }
1600 if (!klass->CanAccess(super)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001601 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001602 return false;
1603 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001604#ifndef NDEBUG
1605 // Ensure super classes are fully resolved prior to resolving fields..
1606 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001607 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001608 super = super->GetSuperClass();
1609 }
1610#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001611 return true;
1612}
1613
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001614// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001615bool ClassLinker::LinkMethods(Class* klass) {
1616 if (klass->IsInterface()) {
1617 // No vtable.
1618 size_t count = klass->NumVirtualMethods();
1619 if (!IsUint(16, count)) {
1620 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1621 return false;
1622 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001623 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001624 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001625 }
jeffhaobdb76512011-09-07 11:43:16 -07001626 // Link interface method tables
1627 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001628 } else {
1629 // Link virtual method tables
1630 LinkVirtualMethods(klass);
1631
1632 // Link interface method tables
1633 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001634 }
1635 return true;
1636}
1637
1638bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001639 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001640 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1641 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001642 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001643 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001644 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001645 // See if any of our virtual methods override the superclass.
1646 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001647 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001648 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001649 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001650 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001651 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001652 // Verify
1653 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001654 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001655 return false;
1656 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001657 vtable->Set(j, local_method);
1658 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001659 break;
1660 }
1661 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001662 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001663 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001664 vtable->Set(actual_count, local_method);
1665 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001666 actual_count += 1;
1667 }
1668 }
1669 if (!IsUint(16, actual_count)) {
1670 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1671 return false;
1672 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001673 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001674 CHECK_LE(actual_count, max_count);
1675 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001676 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001677 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001678 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001679 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001680 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001681 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001682 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001683 LG << "Too many methods"; // TODO: VirtualMachineError
1684 return false;
1685 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001686 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001687 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001688 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1689 vtable->Set(i, virtual_method);
1690 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001691 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001692 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001693 }
1694 return true;
1695}
1696
1697bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001698 int miranda_count = 0;
1699 int miranda_alloc = 0;
1700 size_t super_ifcount;
1701 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001702 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001703 } else {
1704 super_ifcount = 0;
1705 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001706 size_t ifcount = super_ifcount;
1707 ifcount += klass->NumInterfaces();
1708 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001709 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001711 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001712 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001713 // DCHECK(klass->GetIfTableCount() == 0);
1714 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001715 return true;
1716 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001717 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001718 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001719 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1720 for (size_t i = 0; i < super_ifcount; i++) {
1721 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1722 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001723 }
1724 // Flatten the interface inheritance hierarchy.
1725 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001726 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001727 Class* interface = klass->GetInterface(i);
1728 DCHECK(interface != NULL);
1729 if (!interface->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001730 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1731 return false;
1732 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001733 iftable->Set(idx++, AllocInterfaceEntry(interface));
1734 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1735 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001736 }
1737 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001738 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001739 CHECK_EQ(idx, ifcount);
Brian Carlstrom86927212011-09-15 11:31:11 -07001740 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001741 return true;
1742 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001743 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001744 for (size_t i = 0; i < ifcount; ++i) {
1745 InterfaceEntry* interface_entry = iftable->Get(i);
1746 Class* interface = interface_entry->GetInterface();
1747 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1748 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001749 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001750 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1751 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001752 int32_t k;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001753 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1754 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001755 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1756 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001757 LG << "Implementation not public";
1758 return false;
1759 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001760 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001761 break;
1762 }
1763 }
1764 if (k < 0) {
1765 if (miranda_count == miranda_alloc) {
1766 miranda_alloc += 8;
1767 if (miranda_list.empty()) {
1768 miranda_list.resize(miranda_alloc);
1769 } else {
1770 miranda_list.resize(miranda_alloc);
1771 }
1772 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001773 Method* miranda_method = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001774 int mir;
1775 for (mir = 0; mir < miranda_count; mir++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001776 miranda_method = miranda_list[mir];
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001777 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001778 break;
1779 }
1780 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001781 // point the interface table at a phantom slot
1782 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001783 if (mir == miranda_count) {
1784 miranda_list[miranda_count++] = interface_method;
1785 }
1786 }
1787 }
1788 }
1789 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001790 int old_method_count = klass->NumVirtualMethods();
1791 int new_method_count = old_method_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001792 klass->SetVirtualMethods(
1793 klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001794
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001795 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1796 CHECK(vtable != NULL);
1797 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001798 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001799 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001800 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001801 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001802 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001803 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001804 meth->SetDeclaringClass(klass);
1805 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1806 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001807 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001808 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001809 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001810 // TODO: do not assign to the vtable field until it is fully constructed.
1811 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001812 }
1813 return true;
1814}
1815
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001816bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001817 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001818 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001819}
1820
1821bool ClassLinker::LinkStaticFields(Class* klass) {
1822 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001823 size_t allocated_class_size = klass->GetClassSize();
1824 bool success = LinkFields(klass, false);
1825 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001826 return success;
1827}
1828
Brian Carlstromdbc05252011-09-09 01:59:59 -07001829struct LinkFieldsComparator {
1830 bool operator()(const Field* field1, const Field* field2){
1831
1832 // First come reference fields, then 64-bit, and finally 32-bit
1833 const Class* type1 = field1->GetTypeDuringLinking();
1834 const Class* type2 = field2->GetTypeDuringLinking();
1835 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
1836 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
1837 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
1838 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
1839 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
1840 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
1841 if (order1 != order2) {
1842 return order1 < order2;
1843 }
1844
1845 // same basic group? then sort by string.
1846 std::string name1 = field1->GetName()->ToModifiedUtf8();
1847 std::string name2 = field2->GetName()->ToModifiedUtf8();
1848 return name1 < name2;
1849 }
1850};
1851
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001852bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001853 size_t num_fields =
1854 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1855
1856 ObjectArray<Field>* fields =
1857 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001858
1859 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07001860 size_t size;
1861 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001862 if (instance) {
1863 Class* super_class = klass->GetSuperClass();
1864 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001865 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001866 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001867 }
1868 size = field_offset.Uint32Value();
1869 } else {
1870 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07001871 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001872 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001873
Brian Carlstromdbc05252011-09-09 01:59:59 -07001874 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001875
Brian Carlstromdbc05252011-09-09 01:59:59 -07001876 // we want a relatively stable order so that adding new fields
1877 // minimizes distruption of C++ version such as Class and Method.
1878 std::deque<Field*> grouped_and_sorted_fields;
1879 for (size_t i = 0; i < num_fields; i++) {
1880 grouped_and_sorted_fields.push_back(fields->Get(i));
1881 }
1882 std::sort(grouped_and_sorted_fields.begin(),
1883 grouped_and_sorted_fields.end(),
1884 LinkFieldsComparator());
1885
1886 // References should be at the front.
1887 size_t current_field = 0;
1888 size_t num_reference_fields = 0;
1889 for (; current_field < num_fields; current_field++) {
1890 Field* field = grouped_and_sorted_fields.front();
1891 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001892 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07001893 bool isPrimitive = type != NULL && type->IsPrimitive();
1894 if (isPrimitive) {
1895 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001896 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001897 grouped_and_sorted_fields.pop_front();
1898 num_reference_fields++;
1899 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001900 field->SetOffset(field_offset);
1901 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001902 }
1903
1904 // Now we want to pack all of the double-wide fields together. If
1905 // we're not aligned, though, we want to shuffle one 32-bit field
1906 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001907 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
1908 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
1909 Field* field = grouped_and_sorted_fields[i];
1910 const Class* type = field->GetTypeDuringLinking();
1911 CHECK(type != NULL); // should only be working on primitive types
1912 DCHECK(type->IsPrimitive());
1913 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
1914 continue;
1915 }
1916 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001917 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001918 // drop the consumed field
1919 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
1920 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001921 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001922 // whether we found a 32-bit field for padding or not, we advance
1923 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001924 }
1925
1926 // Alignment is good, shuffle any double-wide fields forward, and
1927 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001928 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
1929 while (!grouped_and_sorted_fields.empty()) {
1930 Field* field = grouped_and_sorted_fields.front();
1931 grouped_and_sorted_fields.pop_front();
1932 const Class* type = field->GetTypeDuringLinking();
1933 CHECK(type != NULL); // should only be working on primitive types
1934 DCHECK(type->IsPrimitive());
1935 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001936 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001937 field_offset = MemberOffset(field_offset.Uint32Value() +
1938 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
1939 ? sizeof(uint64_t)
1940 : sizeof(uint32_t)));
1941 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001942 }
1943
1944#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001945 // Make sure that all reference fields appear before
1946 // non-reference fields, and all double-wide fields are aligned.
1947 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07001948 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001949 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001950 if (false) { // enable to debug field layout
1951 LOG(INFO) << "LinkFields:"
1952 << " class=" << klass->GetDescriptor()->ToModifiedUtf8()
1953 << " field=" << field->GetName()->ToModifiedUtf8()
1954 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
1955 }
1956 const Class* type = field->GetTypeDuringLinking();
1957 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001958 if (!seen_non_ref) {
1959 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001960 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001961 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001962 } else {
1963 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001964 }
1965 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001966 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001967 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001968 }
1969#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001970 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001971 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07001972 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001973 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001974 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001975 klass->SetObjectSize(size);
1976 }
1977 } else {
1978 klass->SetNumReferenceStaticFields(num_reference_fields);
1979 klass->SetClassSize(size);
1980 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001981 return true;
1982}
1983
1984// Set the bitmap of reference offsets, refOffsets, from the ifields
1985// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001986void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001987 uint32_t reference_offsets = 0;
1988 Class* super_class = klass->GetSuperClass();
1989 if (super_class != NULL) {
1990 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001991 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001992 if (reference_offsets == CLASS_WALK_SUPER) {
1993 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001994 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001995 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001996 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001997 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001998}
1999
2000void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002001 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002002}
2003
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002004void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2005 uint32_t reference_offsets) {
2006 size_t num_reference_fields =
2007 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2008 : klass->NumReferenceStaticFieldsDuringLinking();
2009 const ObjectArray<Field>* fields =
2010 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002011 // All of the fields that contain object references are guaranteed
2012 // to be at the beginning of the fields list.
2013 for (size_t i = 0; i < num_reference_fields; ++i) {
2014 // Note that byte_offset is the offset from the beginning of
2015 // object, not the offset into instance data
2016 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002017 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002018 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2019 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2020 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002021 CHECK_NE(new_bit, 0U);
2022 reference_offsets |= new_bit;
2023 } else {
2024 reference_offsets = CLASS_WALK_SUPER;
2025 break;
2026 }
2027 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002028 // Update fields in klass
2029 if (instance) {
2030 klass->SetReferenceInstanceOffsets(reference_offsets);
2031 } else {
2032 klass->SetReferenceStaticOffsets(reference_offsets);
2033 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002034}
2035
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002036String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002037 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002038 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002039 if (resolved != NULL) {
2040 return resolved;
2041 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002042 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2043 int32_t utf16_length = dex_file.GetStringLength(string_id);
2044 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002045 // TODO: remote the const_cast below
2046 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002047 dex_cache->SetResolvedString(string_idx, string);
2048 return string;
2049}
2050
2051Class* ClassLinker::ResolveType(const DexFile& dex_file,
2052 uint32_t type_idx,
2053 DexCache* dex_cache,
2054 const ClassLoader* class_loader) {
2055 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002056 if (resolved == NULL) {
2057 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2058 if (descriptor[1] == '\0') {
2059 // only the descriptors of primitive types should be 1 character long
2060 resolved = FindPrimitiveClass(descriptor[0]);
2061 } else {
2062 resolved = FindClass(descriptor, class_loader);
2063 }
2064 if (resolved != NULL) {
2065 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2066 if (dex_cache != check->GetDexCache()) {
2067 if (check->GetClassLoader() != NULL) {
2068 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
2069 resolved = NULL;
2070 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002071 }
2072 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002073 if (resolved != NULL) {
2074 dex_cache->SetResolvedType(type_idx, resolved);
2075 } else {
2076 DCHECK(Thread::Current()->IsExceptionPending());
2077 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002078 }
2079 return resolved;
2080}
2081
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002082Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2083 uint32_t method_idx,
2084 DexCache* dex_cache,
2085 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002086 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002087 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2088 if (resolved != NULL) {
2089 return resolved;
2090 }
2091 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2092 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2093 if (klass == NULL) {
2094 return NULL;
2095 }
2096
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002097 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002098 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002099 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002100 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002101 } else if (klass->IsInterface()) {
2102 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002103 } else {
2104 resolved = klass->FindVirtualMethod(name, signature);
2105 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002106 if (resolved != NULL) {
2107 dex_cache->SetResolvedMethod(method_idx, resolved);
2108 } else {
2109 // DCHECK(Thread::Current()->IsExceptionPending());
2110 }
2111 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002112}
2113
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002114Field* ClassLinker::ResolveField(const DexFile& dex_file,
2115 uint32_t field_idx,
2116 DexCache* dex_cache,
2117 const ClassLoader* class_loader,
2118 bool is_static) {
2119 Field* resolved = dex_cache->GetResolvedField(field_idx);
2120 if (resolved != NULL) {
2121 return resolved;
2122 }
2123 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2124 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2125 if (klass == NULL) {
2126 return NULL;
2127 }
2128
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002129 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002130 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2131 // TODO: LinkageError?
2132 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002133 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002134 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002135 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002136 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002137 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002138 if (resolved != NULL) {
2139 dex_cache->SetResolvedfield(field_idx, resolved);
2140 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002141 // TODO: DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002142 }
2143 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002144}
2145
Elliott Hughese27955c2011-08-26 15:21:24 -07002146size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002147 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002148 return classes_.size();
2149}
2150
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002151} // namespace art