blob: 2e4aa9ed420bcf030945871587c3a8013a47c605 [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
5#include <vector>
6#include <utility>
7
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07008#include "casts.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07009#include "dex_cache.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010#include "dex_verifier.h"
11#include "heap.h"
12#include "logging.h"
13#include "monitor.h"
14#include "object.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070015#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070016#include "scoped_ptr.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070017#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "thread.h"
19#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070020
21namespace art {
22
Brian Carlstroma663ea52011-08-19 23:33:41 -070023const char* ClassLinker::class_roots_descriptors_[kClassRootsMax] = {
24 "Ljava/lang/Class;",
25 "Ljava/lang/Object;",
26 "[Ljava/lang/Object;",
27 "Ljava/lang/String;",
28 "Ljava/lang/reflect/Field;",
29 "Ljava/lang/reflect/Method;",
30 "Ljava/lang/ClassLoader;",
31 "Ldalvik/system/BaseDexClassLoader;",
32 "Ldalvik/system/PathClassLoader;",
33 "Z",
34 "B",
35 "C",
36 "D",
37 "F",
38 "I",
39 "J",
40 "S",
41 "V",
42 "[Z",
43 "[B",
44 "[C",
45 "[D",
46 "[F",
47 "[I",
48 "[J",
49 "[S",
50};
51
52ClassLinker* ClassLinker::Create(const std::vector<DexFile*>& boot_class_path, Space* space) {
Carl Shapiro61e019d2011-07-14 16:53:09 -070053 scoped_ptr<ClassLinker> class_linker(new ClassLinker);
Brian Carlstroma663ea52011-08-19 23:33:41 -070054 if (space == NULL) {
55 class_linker->Init(boot_class_path);
56 } else {
57 class_linker->Init(boot_class_path, space);
58 }
Carl Shapiro61e019d2011-07-14 16:53:09 -070059 // TODO: check for failure during initialization
60 return class_linker.release();
61}
62
Brian Carlstroma663ea52011-08-19 23:33:41 -070063
Carl Shapiro2ed144c2011-07-26 16:52:08 -070064void ClassLinker::Init(const std::vector<DexFile*>& boot_class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070065 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070066
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070067 // java_lang_Class comes first, its needed for AllocClass
68 Class* java_lang_Class = down_cast<Class*>(Heap::AllocObject(NULL, sizeof(Class)));
69 CHECK(java_lang_Class != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070070 java_lang_Class->object_size_ = sizeof(Class);
71 java_lang_Class->klass_ = java_lang_Class;
72 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -070073
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070074 // java_lang_Object comes next so that object_array_class can be created
75 Class* java_lang_Object = AllocClass(java_lang_Class);
76 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070077 // backfill Object as the super class of Class
78 java_lang_Class->super_class_ = java_lang_Object;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070079 // mark as non-primitive for object_array_class
80 java_lang_Object->primitive_type_ = Class::kPrimNot;
Brian Carlstroma0808032011-07-18 00:39:23 -070081
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070082 // object_array_class is for root_classes to provide the storage for these classes
83 Class* object_array_class = AllocClass(java_lang_Class);
84 CHECK(object_array_class != NULL);
Brian Carlstromdb4d5402011-08-09 12:18:28 -070085 object_array_class->component_type_ = java_lang_Object;
Brian Carlstroma0808032011-07-18 00:39:23 -070086
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070087 // String and char[] are necessary so that FindClass can assign names to members
Jesse Wilson14150742011-07-29 19:04:44 -040088 Class* java_lang_String = AllocClass(java_lang_Class);
89 CHECK(java_lang_String != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070090 CHECK_LT(java_lang_String->object_size_, sizeof(String));
Jesse Wilson14150742011-07-29 19:04:44 -040091 java_lang_String->object_size_ = sizeof(String);
Brian Carlstroma663ea52011-08-19 23:33:41 -070092 String::SetClass(java_lang_String);
Jesse Wilson8989d992011-08-02 13:39:42 -070093 Class* char_array_class = AllocClass(java_lang_Class);
94 CHECK(char_array_class != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070095 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070096 // Now String::Alloc* can be used
97
98 // backfill Class descriptors missing until this point
99 java_lang_Class->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/Class;");
100 java_lang_Object->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/Object;");
101 object_array_class->descriptor_ = String::AllocFromModifiedUtf8("[Ljava/lang/Object;");
102 java_lang_String->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/String;");
103 char_array_class->descriptor_ = String::AllocFromModifiedUtf8("[C");
Jesse Wilson14150742011-07-29 19:04:44 -0400104
Jesse Wilson7833bd22011-08-09 18:31:44 -0400105 // int[] and long[] are used for static field storage
106 Class* int_array_class = AllocClass(java_lang_Class);
107 CHECK(int_array_class != NULL);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700108 int_array_class->descriptor_ = String::AllocFromModifiedUtf8("[I");
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700109 IntArray::SetArrayClass(int_array_class);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400110 Class* long_array_class = AllocClass(java_lang_Class);
111 CHECK(long_array_class != NULL);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700112 long_array_class->descriptor_ = String::AllocFromModifiedUtf8("[J");
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700113 LongArray::SetArrayClass(long_array_class);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400114
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700115 // Field and Method are necessary so that FindClass can link members
116 Class* java_lang_reflect_Field = AllocClass(java_lang_Class);
117 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700118 java_lang_reflect_Field->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/reflect/Field;");
Jesse Wilson35baaab2011-08-10 16:18:03 -0400119 CHECK_LT(java_lang_reflect_Field->object_size_, sizeof(Field));
120 java_lang_reflect_Field->object_size_ = sizeof(Field);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700121 Class* java_lang_reflect_Method = AllocClass(java_lang_Class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700122 java_lang_reflect_Method->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700123 CHECK(java_lang_reflect_Method != NULL);
124 CHECK_LT(java_lang_reflect_Method->object_size_, sizeof(Method));
125 java_lang_reflect_Method->object_size_ = sizeof(Method);
126
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700127 // create storage for root classes, save away our work so far
128 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700129 SetClassRoot(kJavaLangClass, java_lang_Class);
130 SetClassRoot(kJavaLangObject, java_lang_Object);
131 SetClassRoot(kObjectArrayClass, object_array_class);
132 SetClassRoot(kJavaLangString, java_lang_String);
133 SetClassRoot(kCharArrayClass, char_array_class);
134 SetClassRoot(kIntArrayClass, int_array_class);
135 SetClassRoot(kLongArrayClass, long_array_class);
136 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
137 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700138 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700139
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700140 // setup boot_class_path_ now that we can use AllocObjectArray to
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700141 // create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700142 for (size_t i = 0; i != boot_class_path.size(); ++i) {
143 AppendToBootClassPath(boot_class_path[i]);
144 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700145 // now we can use FindSystemClass, at least for non-arrays classes.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700146
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700147 // run Class, Field, and Method through FindSystemClass.
148 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700149 // we also override their object_size_ values to accommodate the extra C++ fields.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700150 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700151 CHECK_EQ(java_lang_Class, Class_class);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700152 CHECK_LT(java_lang_Class->object_size_, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700153 java_lang_Class->object_size_ = sizeof(Class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700154 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700155 CHECK_EQ(java_lang_reflect_Field, Field_class);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400156 CHECK_LT(java_lang_reflect_Field->object_size_, sizeof(Field));
157 java_lang_reflect_Field->object_size_ = sizeof(Field);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700158 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700159 CHECK_EQ(java_lang_reflect_Method, Method_class);
160 CHECK_LT(java_lang_reflect_Method->object_size_, sizeof(Method));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700161 java_lang_reflect_Method->object_size_ = sizeof(Method);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700162
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700163 // Object and String just need more minimal setup, since they do not have extra C++ fields.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700164 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700165 CHECK_EQ(java_lang_Object, Object_class);
166 CHECK_EQ(java_lang_Object->object_size_, sizeof(Object));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700167 Class* String_class = FindSystemClass("Ljava/lang/String;");
Jesse Wilsonf7e85a52011-08-01 18:45:58 -0700168 CHECK_EQ(java_lang_String, String_class);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700169 CHECK_EQ(java_lang_String->object_size_, sizeof(String));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700170
171 // Setup the ClassLoaders, adjusting the object_size_ as necessary
172 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
173 CHECK(java_lang_ClassLoader != NULL);
174 CHECK_LT(java_lang_ClassLoader->object_size_, sizeof(ClassLoader));
175 java_lang_ClassLoader->object_size_ = sizeof(ClassLoader);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700176 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700177 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
178 CHECK(dalvik_system_BaseDexClassLoader != NULL);
179 CHECK_EQ(dalvik_system_BaseDexClassLoader->object_size_, sizeof(BaseDexClassLoader));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700180 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700181 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
182 CHECK(dalvik_system_PathClassLoader != NULL);
183 CHECK_EQ(dalvik_system_PathClassLoader->object_size_, sizeof(PathClassLoader));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700184 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700185
186 // Setup a single, global copy of "interfaces" and "iftable" for
187 // reuse across array classes
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700188 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700189 CHECK(java_lang_Cloneable != NULL);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700190 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700191 CHECK(java_io_Serializable != NULL);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700192
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700193 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700194 CHECK(array_interfaces_ != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700195 array_interfaces_->Set(0, java_lang_Cloneable);
196 array_interfaces_->Set(1, java_io_Serializable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700197
198 // We assume that Cloneable/Serializable don't have superinterfaces --
199 // normally we'd have to crawl up and explicitly list all of the
200 // supers as well. These interfaces don't have any methods, so we
201 // don't have to worry about the ifviPool either.
202 array_iftable_ = new InterfaceEntry[2];
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700203 array_iftable_[0].SetClass(array_interfaces_->Get(0));
204 array_iftable_[1].SetClass(array_interfaces_->Get(1));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700205 // now FindClass can be used for non-primitive array classes
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700206
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700207 // run Object[] through FindClass to complete initialization
Jesse Wilson8989d992011-08-02 13:39:42 -0700208 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
209 CHECK_EQ(object_array_class, found_object_array_class);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700210 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
211 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700212
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700213 // Setup the primitive type classes.
Brian Carlstroma663ea52011-08-19 23:33:41 -0700214 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z"));
215 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B"));
216 SetClassRoot(kPrimitiveChar, CreatePrimitiveClass("C"));
217 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D"));
218 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F"));
219 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I"));
220 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J"));
221 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S"));
222 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V"));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700223 // now we can use FindSystemClass for anything, including for "[C"
224
Jesse Wilson7833bd22011-08-09 18:31:44 -0400225 // run char[], int[] and long[] through FindClass to complete initialization
Jesse Wilson8989d992011-08-02 13:39:42 -0700226 Class* found_char_array_class = FindSystemClass("[C");
227 CHECK_EQ(char_array_class, found_char_array_class);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400228 Class* found_int_array_class = FindSystemClass("[I");
229 CHECK_EQ(int_array_class, found_int_array_class);
230 Class* found_long_array_class = FindSystemClass("[J");
231 CHECK_EQ(long_array_class, found_long_array_class);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700232
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700233 // Initialize all the other primitive array types for PrimitiveArray::Alloc.
234 // These are easy because everything we need has already been set up.
Brian Carlstroma663ea52011-08-19 23:33:41 -0700235 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
236 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
237 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
238 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
239 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700240 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
241 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
242 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
243 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
244 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
245
Brian Carlstroma663ea52011-08-19 23:33:41 -0700246 FinishInit();
247}
248
249void ClassLinker::FinishInit() {
250 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700251 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700252 ClassRoot class_root = static_cast<ClassRoot>(i);
253 Class* klass = GetClassRoot(class_root);
254 CHECK(klass != NULL);
255 DCHECK(klass->IsArray() || klass->IsPrimitive() || klass->dex_cache_ != NULL);
256 // note SetClassRoot does additional validation.
257 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700258 }
259
260 // disable the slow paths in FindClass and CreatePrimitiveClass now
261 // that Object, Class, and Object[] are setup
262 init_done_ = true;
263}
264
Brian Carlstroma663ea52011-08-19 23:33:41 -0700265struct ClassLinker::InitCallbackState {
266 ClassLinker* class_linker;
267
268 Class* class_roots[kClassRootsMax];
269
270 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
271 Table descriptor_to_class_root;
272
273 struct DexCacheHash {
274 size_t operator()(art::DexCache* const& obj) const {
275 return reinterpret_cast<size_t>(&obj);
276 }
277 };
278 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
279 Set dex_caches;
280};
281
282void ClassLinker::Init(const std::vector<DexFile*>& boot_class_path, Space* space) {
283 CHECK(!init_done_);
284
285 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
286 DCHECK(heap_bitmap != NULL);
287
288 InitCallbackState state;
289 state.class_linker = this;
290 for (size_t i = 0; i < kClassRootsMax; i++) {
291 ClassRoot class_root = static_cast<ClassRoot>(i);
292 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
293 }
294
295 // reinit clases_ table
296 heap_bitmap->Walk(InitCallback, &state);
297
298 // reinit class_roots_
299 Class* object_array_class = state.class_roots[kObjectArrayClass];
300 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
301 for (size_t i = 0; i < kClassRootsMax; i++) {
302 ClassRoot class_root = static_cast<ClassRoot>(i);
303 SetClassRoot(class_root, state.class_roots[class_root]);
304 }
305
306 // reinit intern_table_
307 ObjectArray<Object>* interned_array = space->GetImageHeader().GetInternedArray();
308 for (int32_t i = 0; i < interned_array->GetLength(); i++) {
309 String* string = interned_array->Get(i)->AsString();
310 intern_table_.Register(string);
311 }
312
313 // reinit array_interfaces_ from any array class instance, they should all be ==
314 array_interfaces_ = GetClassRoot(kObjectArrayClass)->interfaces_;
315 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->interfaces_);
316
317 // build a map from location to DexCache to match up with DexFile::GetLocation
318 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
319 typedef InitCallbackState::Set::const_iterator It; // TODO: C++0x auto
320 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
321 DexCache* dex_cache = *it;
322 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
323 location_to_dex_cache[location] = dex_cache;
324 }
325
326 // reinit boot_class_path with DexFile arguments and found DexCaches
327 for (size_t i = 0; i != boot_class_path.size(); ++i) {
328 DexFile* dex_file = boot_class_path[i];
329 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
330 AppendToBootClassPath(dex_file, dex_cache);
331 }
332
333 String::SetClass(GetClassRoot(kJavaLangString));
334 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
335 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
336 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
337 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
338 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
339 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
340 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
341 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
342
343 FinishInit();
344}
345
346void ClassLinker::InitCallback(Object *obj, void *arg) {
347 DCHECK(obj != NULL);
348 DCHECK(arg != NULL);
349 InitCallbackState* state = reinterpret_cast<InitCallbackState*>(arg);
350
351 if (!obj->IsClass()) {
352 return;
353 }
354 Class* klass = obj->AsClass();
355 CHECK(klass->class_loader_ == NULL);
356
357 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
358
359 // restore class to ClassLinker::classes_ table
360 state->class_linker->InsertClass(descriptor, klass);
361
362 // note DexCache to match with DexFile later
363 DexCache* dex_cache = klass->GetDexCache();
364 if (dex_cache != NULL) {
365 state->dex_caches.insert(dex_cache);
366 } else {
367 DCHECK(klass->IsArray() || klass->IsPrimitive());
368 }
369
370 // check if this is a root, if so, register it
371 typedef InitCallbackState::Table::const_iterator It; // TODO: C++0x auto
372 It it = state->descriptor_to_class_root.find(descriptor);
373 if (it != state->descriptor_to_class_root.end()) {
374 ClassRoot class_root = it->second;
375 state->class_roots[class_root] = klass;
376 }
377}
378
379// Keep in sync with InitCallback. Anything we visit, we need to
380// reinit references to when reinitializing a ClassLinker from a
381// mapped image.
382void ClassLinker::VisitRoots(Heap::RootVistor* root_visitor, void* arg) const {
383
Brian Carlstromb88e9442011-07-28 15:15:51 -0700384 root_visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700385
386 for (size_t i = 0; i < dex_caches_.size(); i++) {
Brian Carlstromb88e9442011-07-28 15:15:51 -0700387 root_visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700388 }
389
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700390 {
391 MutexLock mu(classes_lock_);
392 typedef Table::const_iterator It; // TODO: C++0x auto
393 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
394 root_visitor(it->second, arg);
395 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700396 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700397
398 intern_table_.VisitRoots(root_visitor, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700399
Brian Carlstromb88e9442011-07-28 15:15:51 -0700400 root_visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700401}
402
Brian Carlstroma663ea52011-08-19 23:33:41 -0700403DexCache* ClassLinker::AllocDexCache(const DexFile* dex_file) {
404 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::kMax));
405 dex_cache->Init(String::AllocFromModifiedUtf8(dex_file->GetLocation().c_str()),
406 AllocObjectArray<String>(dex_file->NumStringIds()),
407 AllocObjectArray<Class>(dex_file->NumTypeIds()),
408 AllocObjectArray<Method>(dex_file->NumMethodIds()),
409 AllocObjectArray<Field>(dex_file->NumFieldIds()));
410 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700411}
412
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700413Class* ClassLinker::AllocClass(Class* java_lang_Class) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700414 return java_lang_Class->NewInstance()->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700415}
416
417Class* ClassLinker::AllocClass() {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700418 return AllocClass(GetClassRoot(kJavaLangClass));
Brian Carlstroma0808032011-07-18 00:39:23 -0700419}
420
Jesse Wilson35baaab2011-08-10 16:18:03 -0400421Field* ClassLinker::AllocField() {
422 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->NewInstance());
Brian Carlstroma0808032011-07-18 00:39:23 -0700423}
424
425Method* ClassLinker::AllocMethod() {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700426 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->NewInstance());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700427}
428
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700429// TODO: remove once we can use java.lang.Class.getSystemClassLoader
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700430PathClassLoader* ClassLinker::AllocPathClassLoader(std::vector<const DexFile*> dex_files) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700431 PathClassLoader* cl = down_cast<PathClassLoader*>(GetClassRoot(kDalvikSystemPathClassLoader)->NewInstance());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700432 cl->SetClassPath(dex_files);
433 return cl;
Carl Shapiro565f5072011-07-10 13:39:43 -0700434}
435
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700436Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700437 ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700438 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700439 if (class_loader != NULL) {
440 Class* klass = FindClass(descriptor, NULL);
441 if (klass != NULL) {
442 return klass;
443 }
444 }
445
Carl Shapirob5573532011-07-12 18:22:59 -0700446 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700447 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700448 CHECK(!self->IsExceptionPending());
449 // Find the class in the loaded classes table.
450 Class* klass = LookupClass(descriptor, class_loader);
451 if (klass == NULL) {
452 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700453 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700454 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700455 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700456 DexFile::ClassPath& class_path = ((class_loader != NULL) ? class_loader->GetClassPath() : boot_class_path_);
457 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700458 if (pair.second == NULL) {
Elliott Hughesc7ac37f2011-08-12 12:21:58 -0700459 LG << "Class " << PrintableString(descriptor) << " not found in class loader " << class_loader; // TODO: NoClassDefFoundError
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700460 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700461 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700462 const DexFile& dex_file = *pair.first;
463 const DexFile::ClassDef& dex_class_def = *pair.second;
464 DexCache* dex_cache = FindDexCache(pair.first);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700465 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700466 if (!init_done_) {
467 // finish up init of hand crafted class_roots_
468 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700469 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700470 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700471 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400472 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700473 klass = GetClassRoot(kJavaLangString);
474 } else if (descriptor == "Ljava/lang/reflect/Field;") {
475 klass = GetClassRoot(kJavaLangReflectField);
476 } else if (descriptor == "Ljava/lang/reflect/Method;") {
477 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700478 } else {
479 klass = AllocClass();
480 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700481 } else {
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700482 klass = AllocClass();
Carl Shapiro565f5072011-07-10 13:39:43 -0700483 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700484 klass->dex_cache_ = dex_cache;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700485 LoadClass(dex_file, dex_class_def, klass, class_loader);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700486 // Check for a pending exception during load
487 if (self->IsExceptionPending()) {
488 // TODO: free native allocations in klass
489 return NULL;
490 }
491 {
492 ObjectLock lock(klass);
Carl Shapirob5573532011-07-12 18:22:59 -0700493 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700494 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700495 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700496 if (!success) {
497 // We may fail to insert if we raced with another thread.
498 klass->clinit_thread_id_ = 0;
499 // TODO: free native allocations in klass
500 klass = LookupClass(descriptor, class_loader);
501 CHECK(klass != NULL);
502 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700503 // Finish loading (if necessary) by finding parents
504 if (!klass->IsLoaded() && !LoadSuperAndInterfaces(klass, dex_file)) {
505 // Loading failed.
506 // TODO: CHECK(self->IsExceptionPending());
507 lock.NotifyAll();
508 return NULL;
509 }
510 CHECK(klass->IsLoaded());
511 // Link the class (if necessary)
512 if (!klass->IsLinked() && !LinkClass(klass, dex_file)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700513 // Linking failed.
514 // TODO: CHECK(self->IsExceptionPending());
515 lock.NotifyAll();
516 return NULL;
517 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700518 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700519 }
520 }
521 }
522 // Link the class if it has not already been linked.
523 if (!klass->IsLinked() && !klass->IsErroneous()) {
524 ObjectLock lock(klass);
525 // Check for circular dependencies between classes.
Carl Shapirob5573532011-07-12 18:22:59 -0700526 if (!klass->IsLinked() && klass->clinit_thread_id_ == self->GetId()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700527 LG << "Recursive link"; // TODO: ClassCircularityError
528 return NULL;
529 }
530 // Wait for the pending initialization to complete.
531 while (!klass->IsLinked() && !klass->IsErroneous()) {
532 lock.Wait();
533 }
534 }
535 if (klass->IsErroneous()) {
536 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
537 return NULL;
538 }
539 // Return the loaded class. No exceptions should be pending.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700540 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700541 CHECK(!self->IsExceptionPending());
542 return klass;
543}
544
Brian Carlstromf615a612011-07-23 12:50:34 -0700545void ClassLinker::LoadClass(const DexFile& dex_file,
546 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700547 Class* klass,
548 ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700549 CHECK(klass != NULL);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700550 CHECK(klass->dex_cache_ != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700551 CHECK_EQ(Class::kStatusNotReady, klass->status_);
Brian Carlstromf615a612011-07-23 12:50:34 -0700552 const byte* class_data = dex_file.GetClassData(dex_class_def);
553 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700554
Brian Carlstromf615a612011-07-23 12:50:34 -0700555 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700556 CHECK(descriptor != NULL);
557
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700558 klass->klass_ = GetClassRoot(kJavaLangClass);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700559 klass->descriptor_ = String::AllocFromModifiedUtf8(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -0700560 klass->access_flags_ = dex_class_def.access_flags_;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700561 klass->class_loader_ = class_loader;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700562 klass->primitive_type_ = Class::kPrimNot;
563 klass->status_ = Class::kStatusIdx;
564
565 klass->super_class_ = NULL;
Brian Carlstromf615a612011-07-23 12:50:34 -0700566 klass->super_class_idx_ = dex_class_def.superclass_idx_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700567
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700568 size_t num_static_fields = header.static_fields_size_;
569 size_t num_instance_fields = header.instance_fields_size_;
570 size_t num_direct_methods = header.direct_methods_size_;
571 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700572
Brian Carlstromf615a612011-07-23 12:50:34 -0700573 klass->source_file_ = dex_file.dexGetSourceFile(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700574
575 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700576 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700577
578 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700579 DCHECK(klass->sfields_ == NULL);
580 if (num_static_fields != 0) {
Jesse Wilson35baaab2011-08-10 16:18:03 -0400581 klass->sfields_ = AllocObjectArray<Field>(num_static_fields);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700582 uint32_t last_idx = 0;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700583 for (size_t i = 0; i < klass->NumStaticFields(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700584 DexFile::Field dex_field;
585 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400586 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700587 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700588 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700589 }
590 }
591
592 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700593 DCHECK(klass->ifields_ == NULL);
594 if (num_instance_fields != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700595 // TODO: allocate on the object heap.
Jesse Wilson35baaab2011-08-10 16:18:03 -0400596 klass->ifields_ = AllocObjectArray<Field>(num_instance_fields);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700597 uint32_t last_idx = 0;
598 for (size_t i = 0; i < klass->NumInstanceFields(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700599 DexFile::Field dex_field;
600 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400601 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700602 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700603 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700604 }
605 }
606
607 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700608 DCHECK(klass->direct_methods_ == NULL);
609 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700610 // TODO: append direct methods to class object
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700611 klass->direct_methods_ = AllocObjectArray<Method>(num_direct_methods);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700612 uint32_t last_idx = 0;
613 for (size_t i = 0; i < klass->NumDirectMethods(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700614 DexFile::Method dex_method;
615 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700616 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700617 klass->SetDirectMethod(i, meth);
Brian Carlstromf615a612011-07-23 12:50:34 -0700618 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700619 // TODO: register maps
620 }
621 }
622
623 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700624 DCHECK(klass->virtual_methods_ == NULL);
625 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700626 // TODO: append virtual methods to class object
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700627 klass->virtual_methods_ = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700628 uint32_t last_idx = 0;
629 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700630 DexFile::Method dex_method;
631 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700632 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700633 klass->SetVirtualMethod(i, meth);
Brian Carlstromf615a612011-07-23 12:50:34 -0700634 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700635 // TODO: register maps
636 }
637 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700638}
639
Brian Carlstromf615a612011-07-23 12:50:34 -0700640void ClassLinker::LoadInterfaces(const DexFile& dex_file,
641 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700642 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700643 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700644 if (list != NULL) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700645 DCHECK(klass->interfaces_ == NULL);
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700646 klass->interfaces_ = AllocObjectArray<Class>(list->Size());
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700647 DCHECK(klass->interfaces_idx_ == NULL);
648 klass->interfaces_idx_ = new uint32_t[list->Size()];
Brian Carlstrom934486c2011-07-12 23:42:50 -0700649 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700650 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700651 klass->interfaces_idx_[i] = type_item.type_idx_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700652 }
653 }
654}
655
Brian Carlstromf615a612011-07-23 12:50:34 -0700656void ClassLinker::LoadField(const DexFile& dex_file,
657 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700658 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700659 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700660 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400661 dst->declaring_class_ = klass;
Jesse Wilsonfd687c52011-08-04 19:27:35 -0700662 dst->name_ = ResolveString(klass, field_id.name_idx_, dex_file);
Brian Carlstromae3ac012011-07-27 01:30:28 -0700663 dst->descriptor_.set(dex_file.dexStringByTypeIdx(field_id.type_idx_));
Jesse Wilson35baaab2011-08-10 16:18:03 -0400664 // TODO: Assign dst->type_.
Brian Carlstrom934486c2011-07-12 23:42:50 -0700665 dst->access_flags_ = src.access_flags_;
666}
667
Brian Carlstromf615a612011-07-23 12:50:34 -0700668void ClassLinker::LoadMethod(const DexFile& dex_file,
669 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700670 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700671 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700672 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400673 dst->declaring_class_ = klass;
Jesse Wilsonfd687c52011-08-04 19:27:35 -0700674 dst->name_ = ResolveString(klass, method_id.name_idx_, dex_file);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700675 {
676 int32_t utf16_length;
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700677 scoped_array<char> utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_,
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700678 &utf16_length));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700679 dst->signature_ = String::AllocFromModifiedUtf8(utf16_length, utf8.get());
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700680 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700681 dst->proto_idx_ = method_id.proto_idx_;
Shih-wei Liao2fb97532011-08-11 16:17:23 -0700682 dst->code_off_ = src.code_off_;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700683 dst->shorty_ = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700684 dst->access_flags_ = src.access_flags_;
685
686 // TODO: check for finalize method
687
Brian Carlstromf615a612011-07-23 12:50:34 -0700688 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700689 if (code_item != NULL) {
690 dst->num_registers_ = code_item->registers_size_;
691 dst->num_ins_ = code_item->ins_size_;
692 dst->num_outs_ = code_item->outs_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700693 } else {
694 uint16_t num_args = dst->NumArgRegisters();
695 if (!dst->IsStatic()) {
696 ++num_args;
697 }
698 dst->num_registers_ = dst->num_ins_ + num_args;
699 // TODO: native methods
700 }
701}
702
Brian Carlstroma663ea52011-08-19 23:33:41 -0700703void ClassLinker::AppendToBootClassPath(const DexFile* dex_file) {
Carl Shapiro2ed144c2011-07-26 16:52:08 -0700704 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700705 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
706}
707
708void ClassLinker::AppendToBootClassPath(const DexFile* dex_file, DexCache* dex_cache) {
709 CHECK(dex_file != NULL);
710 CHECK(dex_cache != NULL);
Brian Carlstromf615a612011-07-23 12:50:34 -0700711 boot_class_path_.push_back(dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700712 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700713}
714
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700715void ClassLinker::RegisterDexFile(const DexFile* dex_file) {
Carl Shapiro2ed144c2011-07-26 16:52:08 -0700716 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700717 RegisterDexFile(dex_file, AllocDexCache(dex_file));
718}
719
720void ClassLinker::RegisterDexFile(const DexFile* dex_file, DexCache* dex_cache) {
721 CHECK(dex_file != NULL);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700722 CHECK(dex_cache != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700723 dex_files_.push_back(dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700724 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700725}
726
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700727const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700728 for (size_t i = 0; i != dex_caches_.size(); ++i) {
729 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700730 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700731 }
732 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700733 CHECK(false) << "Could not find DexFile";
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700734 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700735}
736
Brian Carlstromf615a612011-07-23 12:50:34 -0700737DexCache* ClassLinker::FindDexCache(const DexFile* dex_file) const {
Brian Carlstromf615a612011-07-23 12:50:34 -0700738 for (size_t i = 0; i != dex_files_.size(); ++i) {
739 if (dex_files_[i] == dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700740 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700741 }
742 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700743 CHECK(false) << "Could not find DexCache";
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700744 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700745}
746
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700747Class* ClassLinker::CreatePrimitiveClass(const char* descriptor) {
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700748 Class* klass = AllocClass();
Carl Shapiro565f5072011-07-10 13:39:43 -0700749 CHECK(klass != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -0700750 klass->super_class_ = NULL;
Carl Shapiro565f5072011-07-10 13:39:43 -0700751 klass->access_flags_ = kAccPublic | kAccFinal | kAccAbstract;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700752 klass->descriptor_ = String::AllocFromModifiedUtf8(descriptor);
Carl Shapiro565f5072011-07-10 13:39:43 -0700753 klass->status_ = Class::kStatusInitialized;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700754 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700755 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700756 return klass;
757}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700758
Brian Carlstrombe977852011-07-19 14:54:54 -0700759// Create an array class (i.e. the class object for the array, not the
760// array itself). "descriptor" looks like "[C" or "[[[[B" or
761// "[Ljava/lang/String;".
762//
763// If "descriptor" refers to an array of primitives, look up the
764// primitive type's internally-generated class object.
765//
766// "loader" is the class loader of the class that's referring to us. It's
767// used to ensure that we're looking for the element type in the right
768// context. It does NOT become the class loader for the array class; that
769// always comes from the base element class.
770//
771// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700772Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700773 ClassLoader* class_loader)
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700774{
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700775 CHECK(descriptor[0] == '[');
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700776
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700777 // Identify the underlying element class and the array dimension depth.
778 Class* component_type_ = NULL;
779 int array_rank;
780 if (descriptor[1] == '[') {
781 // array of arrays; keep descriptor and grab stuff from parent
782 Class* outer = FindClass(descriptor.substr(1), class_loader);
783 if (outer != NULL) {
784 // want the base class, not "outer", in our component_type_
785 component_type_ = outer->component_type_;
786 array_rank = outer->array_rank_ + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700787 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700788 DCHECK(component_type_ == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700789 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700790 } else {
791 array_rank = 1;
792 if (descriptor[1] == 'L') {
793 // array of objects; strip off "[" and look up descriptor.
794 const StringPiece subDescriptor = descriptor.substr(1);
795 component_type_ = FindClass(subDescriptor, class_loader);
796 } else {
797 // array of a primitive type
798 component_type_ = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700799 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700800 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700801
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700802 if (component_type_ == NULL) {
803 // failed
804 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
805 return NULL;
806 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700807
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700808 // See if the component type is already loaded. Array classes are
809 // always associated with the class loader of their underlying
810 // element type -- an array of Strings goes with the loader for
811 // java/lang/String -- so we need to look for it there. (The
812 // caller should have checked for the existence of the class
813 // before calling here, but they did so with *their* class loader,
814 // not the component type's loader.)
815 //
816 // If we find it, the caller adds "loader" to the class' initiating
817 // loader list, which should prevent us from going through this again.
818 //
819 // This call is unnecessary if "loader" and "component_type_->class_loader_"
820 // are the same, because our caller (FindClass) just did the
821 // lookup. (Even if we get this wrong we still have correct behavior,
822 // because we effectively do this lookup again when we add the new
823 // class to the hash table --- necessary because of possible races with
824 // other threads.)
825 if (class_loader != component_type_->class_loader_) {
826 Class* new_class = LookupClass(descriptor, component_type_->class_loader_);
827 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700828 return new_class;
829 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700830 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700831
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700832 // Fill out the fields in the Class.
833 //
834 // It is possible to execute some methods against arrays, because
835 // all arrays are subclasses of java_lang_Object_, so we need to set
836 // up a vtable. We can just point at the one in java_lang_Object_.
837 //
838 // Array classes are simple enough that we don't need to do a full
839 // link step.
840
841 Class* new_class = NULL;
842 if (!init_done_) {
843 if (descriptor == "[Ljava/lang/Object;") {
844 new_class = GetClassRoot(kObjectArrayClass);
845 } else if (descriptor == "[C") {
846 new_class = GetClassRoot(kCharArrayClass);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400847 } else if (descriptor == "[I") {
848 new_class = GetClassRoot(kIntArrayClass);
849 } else if (descriptor == "[J") {
850 new_class = GetClassRoot(kLongArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700851 }
852 }
853 if (new_class == NULL) {
854 new_class = AllocClass();
855 if (new_class == NULL) {
856 return NULL;
857 }
858 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700859 new_class->descriptor_ = String::AllocFromModifiedUtf8(descriptor.ToString().c_str());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700860 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
861 new_class->super_class_ = java_lang_Object;
862 new_class->vtable_ = java_lang_Object->vtable_;
863 new_class->primitive_type_ = Class::kPrimNot;
864 new_class->component_type_ = component_type_;
865 new_class->class_loader_ = component_type_->class_loader_;
866 new_class->array_rank_ = array_rank;
867 new_class->status_ = Class::kStatusInitialized;
868 // don't need to set new_class->object_size_
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700869 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700870
871
872 // All arrays have java/lang/Cloneable and java/io/Serializable as
873 // interfaces. We need to set that up here, so that stuff like
874 // "instanceof" works right.
875 //
876 // Note: The GC could run during the call to FindSystemClass,
877 // so we need to make sure the class object is GC-valid while we're in
878 // there. Do this by clearing the interface list so the GC will just
879 // think that the entries are null.
880
881
882 // Use the single, global copies of "interfaces" and "iftable"
883 // (remember not to free them for arrays).
884 DCHECK(array_interfaces_ != NULL);
885 new_class->interfaces_ = array_interfaces_;
886 new_class->iftable_count_ = 2;
887 DCHECK(array_iftable_ != NULL);
888 new_class->iftable_ = array_iftable_;
889
890 // Inherit access flags from the component type. Arrays can't be
891 // used as a superclass or interface, so we want to add "final"
892 // and remove "interface".
893 //
894 // Don't inherit any non-standard flags (e.g., kAccFinal)
895 // from component_type_. We assume that the array class does not
896 // override finalize().
897 new_class->access_flags_ = ((new_class->component_type_->access_flags_ &
898 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask;
899
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700900 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700901 return new_class;
902 }
903 // Another thread must have loaded the class after we
904 // started but before we finished. Abandon what we've
905 // done.
906 //
907 // (Yes, this happens.)
908
909 // Grab the winning class.
910 Class* other_class = LookupClass(descriptor, component_type_->class_loader_);
911 DCHECK(other_class != NULL);
912 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700913}
914
915Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -0700916 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700917 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700918 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700919 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700920 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700921 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700922 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700923 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700924 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700925 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700926 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700927 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700928 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700929 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700930 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700931 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700932 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700933 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700934 return GetClassRoot(kPrimitiveVoid);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700935 case 'L':
936 case '[':
Elliott Hughesc7ac37f2011-08-12 12:21:58 -0700937 LOG(ERROR) << "Not a primitive type " << PrintableChar(type);
Carl Shapiro565f5072011-07-10 13:39:43 -0700938 default:
Elliott Hughesc7ac37f2011-08-12 12:21:58 -0700939 LOG(ERROR) << "Unknown primitive type " << PrintableChar(type);
Carl Shapiro744ad052011-08-06 15:53:36 -0700940 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700941 return NULL; // Not reachable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700942}
943
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700944bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
945 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700946 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700947 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700948 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700949}
950
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700951Class* ClassLinker::LookupClass(const StringPiece& descriptor, ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700952 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700953 MutexLock mu(classes_lock_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700954 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700955 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700956 Class* klass = it->second;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700957 if (klass->descriptor_->Equals(descriptor) && klass->class_loader_ == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700958 return klass;
959 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700960 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700961 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700962}
963
964bool ClassLinker::InitializeClass(Class* klass) {
965 CHECK(klass->GetStatus() == Class::kStatusResolved ||
966 klass->GetStatus() == Class::kStatusError);
967
Carl Shapirob5573532011-07-12 18:22:59 -0700968 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700969
970 {
971 ObjectLock lock(klass);
972
973 if (klass->GetStatus() < Class::kStatusVerified) {
974 if (klass->IsErroneous()) {
975 LG << "re-initializing failed class"; // TODO: throw
976 return false;
977 }
978
979 CHECK(klass->GetStatus() == Class::kStatusResolved);
980
981 klass->status_ = Class::kStatusVerifying;
982 if (!DexVerify::VerifyClass(klass)) {
983 LG << "Verification failed"; // TODO: ThrowVerifyError
984 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700985 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700986 klass->SetStatus(Class::kStatusError);
987 return false;
988 }
989
990 klass->SetStatus(Class::kStatusVerified);
991 }
992
993 if (klass->status_ == Class::kStatusInitialized) {
994 return true;
995 }
996
997 while (klass->status_ == Class::kStatusInitializing) {
998 // we caught somebody else in the act; was it us?
Carl Shapirob5573532011-07-12 18:22:59 -0700999 if (klass->clinit_thread_id_ == self->GetId()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001000 LG << "recursive <clinit>";
1001 return true;
1002 }
1003
1004 CHECK(!self->IsExceptionPending());
1005
1006 lock.Wait(); // TODO: check for interruption
1007
1008 // When we wake up, repeat the test for init-in-progress. If
1009 // there's an exception pending (only possible if
1010 // "interruptShouldThrow" was set), bail out.
1011 if (self->IsExceptionPending()) {
1012 CHECK(false);
1013 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1014 klass->SetStatus(Class::kStatusError);
1015 return false;
1016 }
1017 if (klass->GetStatus() == Class::kStatusInitializing) {
1018 continue;
1019 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001020 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001021 klass->GetStatus() == Class::kStatusError);
1022 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001023 // The caller wants an exception, but it was thrown in a
1024 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001025 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1026 return false;
1027 }
1028 return true; // otherwise, initialized
1029 }
1030
1031 // see if we failed previously
1032 if (klass->IsErroneous()) {
1033 // might be wise to unlock before throwing; depends on which class
1034 // it is that we have locked
1035
1036 // TODO: throwEarlierClassFailure(klass);
1037 return false;
1038 }
1039
1040 if (!ValidateSuperClassDescriptors(klass)) {
1041 klass->SetStatus(Class::kStatusError);
1042 return false;
1043 }
1044
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001045 DCHECK(klass->status_ < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001046
Carl Shapirob5573532011-07-12 18:22:59 -07001047 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001048 klass->status_ = Class::kStatusInitializing;
1049 }
1050
1051 if (!InitializeSuperClass(klass)) {
1052 return false;
1053 }
1054
1055 InitializeStaticFields(klass);
1056
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001057 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001058 if (clinit != NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001059 // JValue unused;
1060 // TODO: dvmCallMethod(self, method, NULL, &unused);
Elliott Hughes53b61312011-08-12 18:28:20 -07001061 // UNIMPLEMENTED(FATAL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001062 }
1063
1064 {
1065 ObjectLock lock(klass);
1066
1067 if (self->IsExceptionPending()) {
1068 klass->SetStatus(Class::kStatusError);
1069 } else {
1070 klass->SetStatus(Class::kStatusInitialized);
1071 }
1072 lock.NotifyAll();
1073 }
1074
1075 return true;
1076}
1077
1078bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1079 if (klass->IsInterface()) {
1080 return true;
1081 }
1082 // begin with the methods local to the superclass
1083 if (klass->HasSuperClass() &&
1084 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1085 const Class* super = klass->GetSuperClass();
1086 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001087 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001088 if (method != super->GetVirtualMethod(i) &&
1089 !HasSameMethodDescriptorClasses(method, super, klass)) {
1090 LG << "Classes resolve differently in superclass";
1091 return false;
1092 }
1093 }
1094 }
1095 for (size_t i = 0; i < klass->iftable_count_; ++i) {
1096 const InterfaceEntry* iftable = &klass->iftable_[i];
1097 Class* interface = iftable->GetClass();
1098 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1099 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1100 uint32_t vtable_index = iftable->method_index_array_[j];
1101 const Method* method = klass->GetVirtualMethod(vtable_index);
1102 if (!HasSameMethodDescriptorClasses(method, interface,
1103 method->GetClass())) {
1104 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1105 return false;
1106 }
1107 }
1108 }
1109 }
1110 return true;
1111}
1112
1113bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001114 const Class* klass1,
1115 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001116 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
1117 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->proto_idx_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001118 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001119 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001120 const char* descriptor = it->GetDescriptor();
1121 if (descriptor == NULL) {
1122 break;
1123 }
1124 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1125 // Found a non-primitive type.
1126 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1127 return false;
1128 }
1129 }
1130 }
1131 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001132 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001133 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1134 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1135 return false;
1136 }
1137 }
1138 return true;
1139}
1140
1141// Returns true if classes referenced by the descriptor are the
1142// same classes in klass1 as they are in klass2.
1143bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001144 const Class* klass1,
1145 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001146 CHECK(descriptor != NULL);
1147 CHECK(klass1 != NULL);
1148 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001149 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001150 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001151 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001152 // TODO: found2 == NULL
1153 // TODO: lookup found1 in initiating loader list
1154 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001155 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001156 if (found1 == found2) {
1157 return true;
1158 } else {
1159 return false;
1160 }
1161 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001162 return true;
1163}
1164
1165bool ClassLinker::InitializeSuperClass(Class* klass) {
1166 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001167 if (!klass->IsInterface() && klass->HasSuperClass()) {
1168 Class* super_class = klass->GetSuperClass();
1169 if (super_class->GetStatus() != Class::kStatusInitialized) {
1170 CHECK(!super_class->IsInterface());
1171 klass->MonitorExit();
1172 bool super_initialized = InitializeClass(super_class);
1173 klass->MonitorEnter();
1174 // TODO: check for a pending exception
1175 if (!super_initialized) {
1176 klass->SetStatus(Class::kStatusError);
1177 klass->NotifyAll();
1178 return false;
1179 }
1180 }
1181 }
1182 return true;
1183}
1184
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001185bool ClassLinker::EnsureInitialized(Class* c) {
1186 CHECK(c != NULL);
1187 if (c->IsInitialized()) {
1188 return true;
1189 }
1190
1191 c->MonitorExit();
1192 InitializeClass(c);
1193 c->MonitorEnter();
1194 return !Thread::Current()->IsExceptionPending();
1195}
1196
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001197void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001198 size_t num_static_fields = klass->NumStaticFields();
1199 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001200 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001201 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001202 DexCache* dex_cache = klass->GetDexCache();
1203 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001204 return;
1205 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001206 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001207 const DexFile& dex_file = FindDexFile(dex_cache);
1208 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001209 CHECK(dex_class_def != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001210 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001211 if (addr == NULL) {
1212 // All this class' static fields have default values.
1213 return;
1214 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001215 size_t array_size = DecodeUnsignedLeb128(&addr);
1216 for (size_t i = 0; i < array_size; ++i) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001217 Field* field = klass->GetStaticField(i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001218 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001219 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001220 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001221 case DexFile::kByte:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001222 field->SetByte(value.b);
1223 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001224 case DexFile::kShort:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001225 field->SetShort(value.s);
1226 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001227 case DexFile::kChar:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001228 field->SetChar(value.c);
1229 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001230 case DexFile::kInt:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001231 field->SetInt(value.i);
1232 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001233 case DexFile::kLong:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001234 field->SetLong(value.j);
1235 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001236 case DexFile::kFloat:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001237 field->SetFloat(value.f);
1238 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001239 case DexFile::kDouble:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001240 field->SetDouble(value.d);
1241 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001242 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001243 uint32_t string_idx = value.i;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001244 String* resolved = ResolveString(klass, string_idx, dex_file);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001245 field->SetObject(resolved);
1246 break;
1247 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001248 case DexFile::kBoolean:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001249 field->SetBoolean(value.z);
1250 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001251 case DexFile::kNull:
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001252 field->SetObject(value.l);
1253 break;
1254 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001255 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001256 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001257 }
1258}
1259
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001260bool ClassLinker::LinkClass(Class* klass, const DexFile& dex_file) {
1261 CHECK_EQ(Class::kStatusLoaded, klass->status_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001262 if (!LinkSuperClass(klass)) {
1263 return false;
1264 }
1265 if (!LinkMethods(klass)) {
1266 return false;
1267 }
Jesse Wilson7833bd22011-08-09 18:31:44 -04001268 if (!LinkStaticFields(klass)) {
1269 return false;
1270 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001271 if (!LinkInstanceFields(klass)) {
1272 return false;
1273 }
1274 CreateReferenceOffsets(klass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001275 CHECK_EQ(Class::kStatusLoaded, klass->status_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001276 klass->status_ = Class::kStatusResolved;
1277 return true;
1278}
1279
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001280bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
1281 CHECK_EQ(Class::kStatusIdx, klass->status_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001282 if (klass->super_class_idx_ != DexFile::kDexNoIndex) {
1283 Class* super_class = ResolveClass(klass, klass->super_class_idx_, dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001284 if (super_class == NULL) {
1285 LG << "Failed to resolve superclass";
1286 return false;
1287 }
1288 klass->super_class_ = super_class; // TODO: write barrier
1289 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001290 if (klass->NumInterfaces() > 0) {
1291 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1292 uint32_t idx = klass->interfaces_idx_[i];
1293 klass->SetInterface(i, ResolveClass(klass, idx, dex_file));
1294 if (klass->GetInterface(i) == NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001295 LG << "Failed to resolve interface";
1296 return false;
1297 }
1298 // Verify
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001299 if (!klass->CanAccess(klass->GetInterface(i))) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001300 LG << "Inaccessible interface";
1301 return false;
1302 }
1303 }
1304 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001305 // Mark the class as loaded.
1306 klass->status_ = Class::kStatusLoaded;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001307 return true;
1308}
1309
1310bool ClassLinker::LinkSuperClass(Class* klass) {
1311 CHECK(!klass->IsPrimitive());
1312 const Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001313 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001314 if (super != NULL) {
1315 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1316 return false;
1317 }
1318 // TODO: clear finalize attribute
1319 return true;
1320 }
1321 if (super == NULL) {
1322 LG << "No superclass defined"; // TODO: LinkageError
1323 return false;
1324 }
1325 // Verify
1326 if (super->IsFinal()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001327 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001328 return false;
1329 }
1330 if (super->IsInterface()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001331 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001332 return false;
1333 }
1334 if (!klass->CanAccess(super)) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001335 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001336 return false;
1337 }
1338 return true;
1339}
1340
1341// Populate the class vtable and itable.
1342bool ClassLinker::LinkMethods(Class* klass) {
1343 if (klass->IsInterface()) {
1344 // No vtable.
1345 size_t count = klass->NumVirtualMethods();
1346 if (!IsUint(16, count)) {
1347 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1348 return false;
1349 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001350 for (size_t i = 0; i < count; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001351 klass->GetVirtualMethod(i)->method_index_ = i;
1352 }
1353 } else {
1354 // Link virtual method tables
1355 LinkVirtualMethods(klass);
1356
1357 // Link interface method tables
1358 LinkInterfaceMethods(klass);
1359
1360 // Insert stubs.
1361 LinkAbstractMethods(klass);
1362 }
1363 return true;
1364}
1365
1366bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001367 if (klass->HasSuperClass()) {
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001368 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->vtable_->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001369 size_t actual_count = klass->GetSuperClass()->vtable_->GetLength();
1370 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001371 // TODO: do not assign to the vtable field until it is fully constructed.
1372 klass->vtable_ = klass->GetSuperClass()->vtable_->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001373 // See if any of our virtual methods override the superclass.
1374 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1375 Method* local_method = klass->GetVirtualMethod(i);
1376 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001377 for (; j < actual_count; ++j) {
1378 Method* super_method = klass->vtable_->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001379 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001380 // Verify
1381 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001382 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001383 return false;
1384 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001385 klass->vtable_->Set(j, local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001386 local_method->method_index_ = j;
1387 break;
1388 }
1389 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001390 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001391 // Not overriding, append.
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001392 klass->vtable_->Set(actual_count, local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001393 local_method->method_index_ = actual_count;
1394 actual_count += 1;
1395 }
1396 }
1397 if (!IsUint(16, actual_count)) {
1398 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1399 return false;
1400 }
1401 CHECK_LE(actual_count, max_count);
1402 if (actual_count < max_count) {
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001403 // TODO: do not assign to the vtable field until it is fully constructed.
1404 klass->vtable_ = klass->vtable_->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001405 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001406 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001407 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001408 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001409 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001410 LG << "Too many methods"; // TODO: VirtualMachineError
1411 return false;
1412 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001413 // TODO: do not assign to the vtable field until it is fully constructed.
1414 klass->vtable_ = AllocObjectArray<Method>(num_virtual_methods);
1415 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001416 klass->vtable_->Set(i, klass->GetVirtualMethod(i));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001417 klass->GetVirtualMethod(i)->method_index_ = i & 0xFFFF;
1418 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001419 }
1420 return true;
1421}
1422
1423bool ClassLinker::LinkInterfaceMethods(Class* klass) {
1424 int pool_offset = 0;
1425 int pool_size = 0;
1426 int miranda_count = 0;
1427 int miranda_alloc = 0;
1428 size_t super_ifcount;
1429 if (klass->HasSuperClass()) {
1430 super_ifcount = klass->GetSuperClass()->iftable_count_;
1431 } else {
1432 super_ifcount = 0;
1433 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001434 size_t ifcount = super_ifcount;
1435 ifcount += klass->NumInterfaces();
1436 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1437 ifcount += klass->GetInterface(i)->iftable_count_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001438 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001439 if (ifcount == 0) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001440 DCHECK(klass->iftable_count_ == 0);
1441 DCHECK(klass->iftable_ == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001442 return true;
1443 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001444 klass->iftable_ = new InterfaceEntry[ifcount * sizeof(InterfaceEntry)];
1445 memset(klass->iftable_, 0x00, sizeof(InterfaceEntry) * ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001446 if (super_ifcount != 0) {
1447 memcpy(klass->iftable_, klass->GetSuperClass()->iftable_,
1448 sizeof(InterfaceEntry) * super_ifcount);
1449 }
1450 // Flatten the interface inheritance hierarchy.
1451 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001452 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1453 Class* interf = klass->GetInterface(i);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001454 DCHECK(interf != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001455 if (!interf->IsInterface()) {
1456 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1457 return false;
1458 }
1459 klass->iftable_[idx++].SetClass(interf);
1460 for (size_t j = 0; j < interf->iftable_count_; j++) {
1461 klass->iftable_[idx++].SetClass(interf->iftable_[j].GetClass());
1462 }
1463 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001464 CHECK_EQ(idx, ifcount);
1465 klass->iftable_count_ = ifcount;
1466 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001467 return true;
1468 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001469 for (size_t i = super_ifcount; i < ifcount; i++) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001470 pool_size += klass->iftable_[i].GetClass()->NumVirtualMethods();
1471 }
1472 if (pool_size == 0) {
1473 return true;
1474 }
1475 klass->ifvi_pool_count_ = pool_size;
1476 klass->ifvi_pool_ = new uint32_t[pool_size];
1477 std::vector<Method*> miranda_list;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001478 for (size_t i = super_ifcount; i < ifcount; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001479 klass->iftable_[i].method_index_array_ = klass->ifvi_pool_ + pool_offset;
1480 Class* interface = klass->iftable_[i].GetClass();
1481 pool_offset += interface->NumVirtualMethods(); // end here
1482 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1483 Method* interface_method = interface->GetVirtualMethod(j);
1484 int k; // must be signed
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001485 for (k = klass->vtable_->GetLength() - 1; k >= 0; --k) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001486 Method* vtable_method = klass->vtable_->Get(k);
1487 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1488 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001489 LG << "Implementation not public";
1490 return false;
1491 }
1492 klass->iftable_[i].method_index_array_[j] = k;
1493 break;
1494 }
1495 }
1496 if (k < 0) {
1497 if (miranda_count == miranda_alloc) {
1498 miranda_alloc += 8;
1499 if (miranda_list.empty()) {
1500 miranda_list.resize(miranda_alloc);
1501 } else {
1502 miranda_list.resize(miranda_alloc);
1503 }
1504 }
1505 int mir;
1506 for (mir = 0; mir < miranda_count; mir++) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001507 Method* miranda_method = miranda_list[mir];
1508 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001509 break;
1510 }
1511 }
1512 // point the interface table at a phantom slot index
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001513 klass->iftable_[i].method_index_array_[j] = klass->vtable_->GetLength() + mir;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001514 if (mir == miranda_count) {
1515 miranda_list[miranda_count++] = interface_method;
1516 }
1517 }
1518 }
1519 }
1520 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001521 int old_method_count = klass->NumVirtualMethods();
1522 int new_method_count = old_method_count + miranda_count;
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001523 klass->virtual_methods_ = klass->virtual_methods_->CopyOf(new_method_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001524
1525 CHECK(klass->vtable_ != NULL);
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001526 int old_vtable_count = klass->vtable_->GetLength();
1527 int new_vtable_count = old_vtable_count + miranda_count;
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001528 // TODO: do not assign to the vtable field until it is fully constructed.
1529 klass->vtable_ = klass->vtable_->CopyOf(new_vtable_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001530
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001531 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001532 Method* meth = AllocMethod();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001533 memcpy(meth, miranda_list[i], sizeof(Method));
1534 meth->klass_ = klass;
1535 meth->access_flags_ |= kAccMiranda;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001536 meth->method_index_ = 0xFFFF & (old_vtable_count + i);
1537 klass->SetVirtualMethod(old_method_count + i, meth);
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001538 klass->vtable_->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001539 }
1540 }
1541 return true;
1542}
1543
1544void ClassLinker::LinkAbstractMethods(Class* klass) {
1545 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1546 Method* method = klass->GetVirtualMethod(i);
1547 if (method->IsAbstract()) {
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001548 LG << "AbstractMethodError";
1549 method->code_off_ = 0xFFFFFFFF;
1550 // TODO: throw AbstractMethodError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001551 }
1552 }
1553}
1554
Jesse Wilson7833bd22011-08-09 18:31:44 -04001555// Each static field will be stored in one of three arrays: static_references_,
1556// static_32bit_primitives_, or static_64bit_primitives_. This assigns each
1557// field a slot in its array and create the arrays.
1558bool ClassLinker::LinkStaticFields(Class* klass) {
1559 size_t next_reference_slot = 0;
1560 size_t next_32bit_primitive_slot = 0;
1561 size_t next_64bit_primitive_slot = 0;
1562
1563 for (size_t i = 0; i < klass->NumStaticFields(); i++) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001564 Field* field = klass->GetStaticField(i);
Jesse Wilson7833bd22011-08-09 18:31:44 -04001565 char type = field->GetType();
1566 if (type == '[' || type == 'L') {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001567 field->offset_ = next_reference_slot++;
Jesse Wilson7833bd22011-08-09 18:31:44 -04001568 } else if (type == 'J' || type == 'D') {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001569 field->offset_ = next_64bit_primitive_slot++;
Jesse Wilson7833bd22011-08-09 18:31:44 -04001570 } else {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001571 field->offset_ = next_32bit_primitive_slot++;
Jesse Wilson7833bd22011-08-09 18:31:44 -04001572 }
1573 }
1574
1575 if (next_reference_slot > 0) {
1576 Class* array_class = GetClassRoot(kObjectArrayClass);
1577 klass->static_references_ = ObjectArray<Object>::Alloc(array_class, next_reference_slot);
1578 }
1579 if (next_32bit_primitive_slot > 0) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001580 klass->static_32bit_primitives_ = IntArray::Alloc(next_32bit_primitive_slot);
Jesse Wilson7833bd22011-08-09 18:31:44 -04001581 }
1582 if (next_64bit_primitive_slot > 0) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001583 klass->static_64bit_primitives_ = LongArray::Alloc(next_64bit_primitive_slot);
Jesse Wilson7833bd22011-08-09 18:31:44 -04001584 }
1585
1586 return true;
1587}
1588
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001589bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001590 int field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001591 if (klass->GetSuperClass() != NULL) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001592 field_offset = klass->GetSuperClass()->object_size_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001593 } else {
Brian Carlstroma0808032011-07-18 00:39:23 -07001594 field_offset = OFFSETOF_MEMBER(DataObject, fields_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001595 }
1596 // Move references to the front.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001597 klass->num_reference_instance_fields_ = 0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001598 size_t i = 0;
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001599 for ( ; i < klass->NumInstanceFields(); i++) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001600 Field* pField = klass->GetInstanceField(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001601 char c = pField->GetType();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001602 if (c != '[' && c != 'L') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001603 for (size_t j = klass->NumInstanceFields() - 1; j > i; j--) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001604 Field* refField = klass->GetInstanceField(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001605 char rc = refField->GetType();
1606 if (rc == '[' || rc == 'L') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001607 klass->SetInstanceField(i, refField);
1608 klass->SetInstanceField(j, pField);
1609 pField = refField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001610 c = rc;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001611 klass->num_reference_instance_fields_++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001612 break;
1613 }
1614 }
1615 } else {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001616 klass->num_reference_instance_fields_++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001617 }
1618 if (c != '[' && c != 'L') {
1619 break;
1620 }
Brian Carlstroma0808032011-07-18 00:39:23 -07001621 pField->SetOffset(field_offset);
1622 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001623 }
1624
1625 // Now we want to pack all of the double-wide fields together. If
1626 // we're not aligned, though, we want to shuffle one 32-bit field
1627 // into place. If we can't find one, we'll have to pad it.
Brian Carlstroma0808032011-07-18 00:39:23 -07001628 if (i != klass->NumInstanceFields() && (field_offset & 0x04) != 0) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001629 Field* pField = klass->GetInstanceField(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001630 char c = pField->GetType();
1631
1632 if (c != 'J' && c != 'D') {
1633 // The field that comes next is 32-bit, so just advance past it.
Brian Carlstrombe977852011-07-19 14:54:54 -07001634 DCHECK(c != '[');
1635 DCHECK(c != 'L');
Brian Carlstroma0808032011-07-18 00:39:23 -07001636 pField->SetOffset(field_offset);
1637 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001638 i++;
1639 } else {
1640 // Next field is 64-bit, so search for a 32-bit field we can
1641 // swap into it.
1642 bool found = false;
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001643 for (size_t j = klass->NumInstanceFields() - 1; j > i; j--) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001644 Field* singleField = klass->GetInstanceField(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001645 char rc = singleField->GetType();
1646 if (rc != 'J' && rc != 'D') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001647 klass->SetInstanceField(i, singleField);
1648 klass->SetInstanceField(j, pField);
1649 pField = singleField;
Brian Carlstroma0808032011-07-18 00:39:23 -07001650 pField->SetOffset(field_offset);
1651 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001652 found = true;
1653 i++;
1654 break;
1655 }
1656 }
1657 if (!found) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001658 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001659 }
1660 }
1661 }
1662
1663 // Alignment is good, shuffle any double-wide fields forward, and
1664 // finish assigning field offsets to all fields.
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001665 DCHECK(i == klass->NumInstanceFields() || (field_offset & 0x04) == 0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001666 for ( ; i < klass->NumInstanceFields(); i++) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001667 Field* pField = klass->GetInstanceField(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001668 char c = pField->GetType();
1669 if (c != 'D' && c != 'J') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001670 for (size_t j = klass->NumInstanceFields() - 1; j > i; j--) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001671 Field* doubleField = klass->GetInstanceField(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001672 char rc = doubleField->GetType();
1673 if (rc == 'D' || rc == 'J') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001674 klass->SetInstanceField(i, doubleField);
1675 klass->SetInstanceField(j, pField);
1676 pField = doubleField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001677 c = rc;
1678 break;
1679 }
1680 }
1681 } else {
1682 // This is a double-wide field, leave it be.
1683 }
1684
Brian Carlstroma0808032011-07-18 00:39:23 -07001685 pField->SetOffset(field_offset);
1686 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001687 if (c == 'J' || c == 'D')
Brian Carlstroma0808032011-07-18 00:39:23 -07001688 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001689 }
1690
1691#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001692 // Make sure that all reference fields appear before
1693 // non-reference fields, and all double-wide fields are aligned.
1694 bool seen_non_ref = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001695 for (i = 0; i < klass->NumInstanceFields(); i++) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001696 Field *pField = klass->GetInstanceField(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001697 char c = pField->GetType();
1698
1699 if (c == 'D' || c == 'J') {
Brian Carlstrombe977852011-07-19 14:54:54 -07001700 DCHECK_EQ(0U, pField->GetOffset() & 0x07);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001701 }
1702
1703 if (c != '[' && c != 'L') {
Brian Carlstrombe977852011-07-19 14:54:54 -07001704 if (!seen_non_ref) {
1705 seen_non_ref = true;
Brian Carlstrom07d579f2011-07-27 13:31:51 -07001706 DCHECK_EQ(klass->NumReferenceInstanceFields(), i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001707 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001708 } else {
1709 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710 }
1711 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001712 if (!seen_non_ref) {
Brian Carlstrom07d579f2011-07-27 13:31:51 -07001713 DCHECK_EQ(klass->NumInstanceFields(), klass->NumReferenceInstanceFields());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001714 }
1715#endif
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001716 klass->object_size_ = field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001717 return true;
1718}
1719
1720// Set the bitmap of reference offsets, refOffsets, from the ifields
1721// list.
1722void ClassLinker::CreateReferenceOffsets(Class* klass) {
1723 uint32_t reference_offsets = 0;
1724 if (klass->HasSuperClass()) {
1725 reference_offsets = klass->GetSuperClass()->GetReferenceOffsets();
1726 }
1727 // If our superclass overflowed, we don't stand a chance.
1728 if (reference_offsets != CLASS_WALK_SUPER) {
1729 // All of the fields that contain object references are guaranteed
1730 // to be at the beginning of the ifields list.
1731 for (size_t i = 0; i < klass->NumReferenceInstanceFields(); ++i) {
1732 // Note that, per the comment on struct InstField, f->byteOffset
1733 // is the offset from the beginning of obj, not the offset into
1734 // obj->instanceData.
Jesse Wilson35baaab2011-08-10 16:18:03 -04001735 const Field* field = klass->GetInstanceField(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001736 size_t byte_offset = field->GetOffset();
1737 CHECK_GE(byte_offset, CLASS_SMALLEST_OFFSET);
Elliott Hughes1f359b02011-07-17 14:27:17 -07001738 CHECK_EQ(byte_offset & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001739 if (CLASS_CAN_ENCODE_OFFSET(byte_offset)) {
1740 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset);
Elliott Hughes1f359b02011-07-17 14:27:17 -07001741 CHECK_NE(new_bit, 0U);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001742 reference_offsets |= new_bit;
1743 } else {
1744 reference_offsets = CLASS_WALK_SUPER;
1745 break;
1746 }
1747 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001748 }
Brian Carlstromae3ac012011-07-27 01:30:28 -07001749 klass->SetReferenceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001750}
1751
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001752Class* ClassLinker::ResolveClass(const Class* referrer,
1753 uint32_t class_idx,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001754 const DexFile& dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001755 DexCache* dex_cache = referrer->GetDexCache();
1756 Class* resolved = dex_cache->GetResolvedClass(class_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001757 if (resolved != NULL) {
1758 return resolved;
1759 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001760 const char* descriptor = dex_file.dexStringByTypeIdx(class_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001761 if (descriptor[0] != '\0' && descriptor[1] == '\0') {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001762 resolved = FindPrimitiveClass(descriptor[0]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001763 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001764 resolved = FindClass(descriptor, referrer->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001765 }
1766 if (resolved != NULL) {
1767 Class* check = resolved->IsArray() ? resolved->component_type_ : resolved;
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001768 if (referrer->GetDexCache() != check->GetDexCache()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769 if (check->GetClassLoader() != NULL) {
1770 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
1771 return NULL;
1772 }
1773 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001774 dex_cache->SetResolvedClass(class_idx, resolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001775 } else {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001776 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001777 }
1778 return resolved;
1779}
1780
1781Method* ResolveMethod(const Class* referrer, uint32_t method_idx,
1782 /*MethodType*/ int method_type) {
1783 CHECK(false);
1784 return NULL;
1785}
1786
Carl Shapiro69759ea2011-07-21 18:13:35 -07001787String* ClassLinker::ResolveString(const Class* referring,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001788 uint32_t string_idx,
1789 const DexFile& dex_file) {
1790 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
1791 int32_t utf16_length = dex_file.GetStringLength(string_id);
1792 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001793 String* string = intern_table_.Intern(utf16_length, utf8_data);
1794 referring->GetDexCache()->SetResolvedString(string_idx, string);
1795 return string;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001796}
1797
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001798} // namespace art