blob: e0b55cae6b0687b9b9e1d3293b783a901d9d0c02 [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;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070033 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070034 "Z",
35 "B",
36 "C",
37 "D",
38 "F",
39 "I",
40 "J",
41 "S",
42 "V",
43 "[Z",
44 "[B",
45 "[C",
46 "[D",
47 "[F",
48 "[I",
49 "[J",
50 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070051 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070052};
53
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070054ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path, Space* space) {
Carl Shapiro61e019d2011-07-14 16:53:09 -070055 scoped_ptr<ClassLinker> class_linker(new ClassLinker);
Brian Carlstroma663ea52011-08-19 23:33:41 -070056 if (space == NULL) {
57 class_linker->Init(boot_class_path);
58 } else {
59 class_linker->Init(boot_class_path, space);
60 }
Carl Shapiro61e019d2011-07-14 16:53:09 -070061 // TODO: check for failure during initialization
62 return class_linker.release();
63}
64
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070065ClassLinker::ClassLinker()
66 : classes_lock_(Mutex::Create("ClassLinker::Lock")),
67 class_roots_(NULL),
68 init_done_(false) {
69}
Brian Carlstroma663ea52011-08-19 23:33:41 -070070
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070071void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070072 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070073
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070074 // java_lang_Class comes first, its needed for AllocClass
Brian Carlstrom4873d462011-08-21 15:23:39 -070075 Class* java_lang_Class = down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070076 CHECK(java_lang_Class != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -070077 java_lang_Class->class_size_ = sizeof(ClassClass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070078 java_lang_Class->klass_ = java_lang_Class;
79 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -070080
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070081 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -070082 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070083 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070084 // backfill Object as the super class of Class
85 java_lang_Class->super_class_ = java_lang_Object;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070086 // mark as non-primitive for object_array_class
87 java_lang_Object->primitive_type_ = Class::kPrimNot;
Brian Carlstroma0808032011-07-18 00:39:23 -070088
Elliott Hughesc1674ed2011-08-25 18:09:09 -070089 // Object[] is for DexCache and int[] is for various Class members.
Brian Carlstrom4873d462011-08-21 15:23:39 -070090 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070091 CHECK(object_array_class != NULL);
Brian Carlstromdb4d5402011-08-09 12:18:28 -070092 object_array_class->component_type_ = java_lang_Object;
Elliott Hughesc1674ed2011-08-25 18:09:09 -070093 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
94 CHECK(int_array_class != NULL);
95 IntArray::SetArrayClass(int_array_class);
Brian Carlstroma0808032011-07-18 00:39:23 -070096
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070097 // String and char[] are necessary so that FindClass can assign names to members
Brian Carlstrom4873d462011-08-21 15:23:39 -070098 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
Jesse Wilson14150742011-07-29 19:04:44 -040099 CHECK(java_lang_String != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700100 CHECK_LT(java_lang_String->object_size_, sizeof(String));
Jesse Wilson14150742011-07-29 19:04:44 -0400101 java_lang_String->object_size_ = sizeof(String);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700102 String::SetClass(java_lang_String);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700103 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Jesse Wilson8989d992011-08-02 13:39:42 -0700104 CHECK(char_array_class != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700105 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700106 // Now String::Alloc* can be used
107
108 // backfill Class descriptors missing until this point
109 java_lang_Class->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/Class;");
110 java_lang_Object->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/Object;");
111 object_array_class->descriptor_ = String::AllocFromModifiedUtf8("[Ljava/lang/Object;");
112 java_lang_String->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/String;");
113 char_array_class->descriptor_ = String::AllocFromModifiedUtf8("[C");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700114 int_array_class->descriptor_ = String::AllocFromModifiedUtf8("[I");
Jesse Wilson14150742011-07-29 19:04:44 -0400115
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700116 // Field and Method are necessary so that FindClass can link members
Brian Carlstrom4873d462011-08-21 15:23:39 -0700117 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700118 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700119 java_lang_reflect_Field->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/reflect/Field;");
Jesse Wilson35baaab2011-08-10 16:18:03 -0400120 CHECK_LT(java_lang_reflect_Field->object_size_, sizeof(Field));
121 java_lang_reflect_Field->object_size_ = sizeof(Field);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700122 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700123 java_lang_reflect_Method->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700124 CHECK(java_lang_reflect_Method != NULL);
125 CHECK_LT(java_lang_reflect_Method->object_size_, sizeof(Method));
126 java_lang_reflect_Method->object_size_ = sizeof(Method);
127
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700128 // create storage for root classes, save away our work so far
129 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700130 SetClassRoot(kJavaLangClass, java_lang_Class);
131 SetClassRoot(kJavaLangObject, java_lang_Object);
132 SetClassRoot(kObjectArrayClass, object_array_class);
133 SetClassRoot(kJavaLangString, java_lang_String);
134 SetClassRoot(kCharArrayClass, char_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700135 SetClassRoot(kIntArrayClass, int_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700136 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) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700143 const DexFile* dex_file = boot_class_path[i];
144 CHECK(dex_file != NULL);
145 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700146 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700147 // now we can use FindSystemClass, at least for non-arrays classes.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700148
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700149 // run Class, Field, and Method through FindSystemClass.
150 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700151 // we also override their object_size_ values to accommodate the extra C++ fields.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700152 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700153 CHECK_EQ(java_lang_Class, Class_class);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700154 CHECK_LT(java_lang_Class->object_size_, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700155 java_lang_Class->object_size_ = sizeof(Class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700156 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700157 CHECK_EQ(java_lang_reflect_Field, Field_class);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400158 CHECK_LT(java_lang_reflect_Field->object_size_, sizeof(Field));
159 java_lang_reflect_Field->object_size_ = sizeof(Field);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700160 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700161 CHECK_EQ(java_lang_reflect_Method, Method_class);
162 CHECK_LT(java_lang_reflect_Method->object_size_, sizeof(Method));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700163 java_lang_reflect_Method->object_size_ = sizeof(Method);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700164
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700165 // Object and String just need more minimal setup, since they do not have extra C++ fields.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700166 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700167 CHECK_EQ(java_lang_Object, Object_class);
168 CHECK_EQ(java_lang_Object->object_size_, sizeof(Object));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700169 Class* String_class = FindSystemClass("Ljava/lang/String;");
Jesse Wilsonf7e85a52011-08-01 18:45:58 -0700170 CHECK_EQ(java_lang_String, String_class);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700171 CHECK_EQ(java_lang_String->object_size_, sizeof(String));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700172
173 // Setup the ClassLoaders, adjusting the object_size_ as necessary
174 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
175 CHECK(java_lang_ClassLoader != NULL);
176 CHECK_LT(java_lang_ClassLoader->object_size_, sizeof(ClassLoader));
177 java_lang_ClassLoader->object_size_ = sizeof(ClassLoader);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700178 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700179 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
180 CHECK(dalvik_system_BaseDexClassLoader != NULL);
181 CHECK_EQ(dalvik_system_BaseDexClassLoader->object_size_, sizeof(BaseDexClassLoader));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700182 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700183 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
184 CHECK(dalvik_system_PathClassLoader != NULL);
185 CHECK_EQ(dalvik_system_PathClassLoader->object_size_, sizeof(PathClassLoader));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700186 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700187 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700188
189 // Setup a single, global copy of "interfaces" and "iftable" for
190 // reuse across array classes
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700191 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700192 CHECK(java_lang_Cloneable != NULL);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700193 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700194 CHECK(java_io_Serializable != NULL);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700195
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700196 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700197 CHECK(array_interfaces_ != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700198 array_interfaces_->Set(0, java_lang_Cloneable);
199 array_interfaces_->Set(1, java_io_Serializable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700200
201 // We assume that Cloneable/Serializable don't have superinterfaces --
202 // normally we'd have to crawl up and explicitly list all of the
203 // supers as well. These interfaces don't have any methods, so we
204 // don't have to worry about the ifviPool either.
205 array_iftable_ = new InterfaceEntry[2];
Brian Carlstrom30b94452011-08-25 21:35:26 -0700206 array_iftable_[0].SetInterface(array_interfaces_->Get(0));
207 array_iftable_[1].SetInterface(array_interfaces_->Get(1));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700208 // now FindClass can be used for non-primitive array classes
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700209
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700210 // run Object[] through FindClass to complete initialization
Jesse Wilson8989d992011-08-02 13:39:42 -0700211 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
212 CHECK_EQ(object_array_class, found_object_array_class);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700213 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
214 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700215
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700216 // Setup the primitive type classes.
Brian Carlstroma663ea52011-08-19 23:33:41 -0700217 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z"));
218 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B"));
219 SetClassRoot(kPrimitiveChar, CreatePrimitiveClass("C"));
220 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D"));
221 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F"));
222 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I"));
223 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J"));
224 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S"));
225 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V"));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700226 // now we can use FindSystemClass for anything, including for "[C"
227
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700228 // run char[] and int[] through FindClass to complete initialization
Jesse Wilson8989d992011-08-02 13:39:42 -0700229 Class* found_char_array_class = FindSystemClass("[C");
230 CHECK_EQ(char_array_class, found_char_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700231 Class* found_int_array_class = FindSystemClass("[I");
232 CHECK_EQ(int_array_class, found_int_array_class);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700233
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700234 // Initialize all the other primitive array types for PrimitiveArray::Alloc.
235 // These are easy because everything we need has already been set up.
Brian Carlstroma663ea52011-08-19 23:33:41 -0700236 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
237 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
238 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
239 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
Brian Carlstrom4873d462011-08-21 15:23:39 -0700240 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700241 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700242 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
243 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700244 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
245 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
246 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
247 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Brian Carlstrom4873d462011-08-21 15:23:39 -0700248 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700249 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700250 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700251
Brian Carlstroma663ea52011-08-19 23:33:41 -0700252 FinishInit();
253}
254
255void ClassLinker::FinishInit() {
256 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700257 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700258 ClassRoot class_root = static_cast<ClassRoot>(i);
259 Class* klass = GetClassRoot(class_root);
260 CHECK(klass != NULL);
261 DCHECK(klass->IsArray() || klass->IsPrimitive() || klass->dex_cache_ != NULL);
262 // note SetClassRoot does additional validation.
263 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700264 }
265
266 // disable the slow paths in FindClass and CreatePrimitiveClass now
267 // that Object, Class, and Object[] are setup
268 init_done_ = true;
269}
270
Brian Carlstroma663ea52011-08-19 23:33:41 -0700271struct ClassLinker::InitCallbackState {
272 ClassLinker* class_linker;
273
274 Class* class_roots[kClassRootsMax];
275
276 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
277 Table descriptor_to_class_root;
278
279 struct DexCacheHash {
280 size_t operator()(art::DexCache* const& obj) const {
281 return reinterpret_cast<size_t>(&obj);
282 }
283 };
284 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
285 Set dex_caches;
286};
287
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700288void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path, Space* space) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700289 CHECK(!init_done_);
290
291 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
292 DCHECK(heap_bitmap != NULL);
293
294 InitCallbackState state;
295 state.class_linker = this;
296 for (size_t i = 0; i < kClassRootsMax; i++) {
297 ClassRoot class_root = static_cast<ClassRoot>(i);
298 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
299 }
300
301 // reinit clases_ table
302 heap_bitmap->Walk(InitCallback, &state);
303
304 // reinit class_roots_
305 Class* object_array_class = state.class_roots[kObjectArrayClass];
306 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
307 for (size_t i = 0; i < kClassRootsMax; i++) {
308 ClassRoot class_root = static_cast<ClassRoot>(i);
309 SetClassRoot(class_root, state.class_roots[class_root]);
310 }
311
312 // reinit intern_table_
313 ObjectArray<Object>* interned_array = space->GetImageHeader().GetInternedArray();
314 for (int32_t i = 0; i < interned_array->GetLength(); i++) {
315 String* string = interned_array->Get(i)->AsString();
316 intern_table_.Register(string);
317 }
318
319 // reinit array_interfaces_ from any array class instance, they should all be ==
320 array_interfaces_ = GetClassRoot(kObjectArrayClass)->interfaces_;
321 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->interfaces_);
322
323 // build a map from location to DexCache to match up with DexFile::GetLocation
324 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
325 typedef InitCallbackState::Set::const_iterator It; // TODO: C++0x auto
326 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
327 DexCache* dex_cache = *it;
328 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
329 location_to_dex_cache[location] = dex_cache;
330 }
331
332 // reinit boot_class_path with DexFile arguments and found DexCaches
333 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700334 const DexFile* dex_file = boot_class_path[i];
335 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700336 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700337 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700338 }
339
340 String::SetClass(GetClassRoot(kJavaLangString));
341 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
342 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
343 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
344 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
345 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
346 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
347 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
348 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700349 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700350 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700351
352 FinishInit();
353}
354
Brian Carlstrom4873d462011-08-21 15:23:39 -0700355void ClassLinker::InitCallback(Object* obj, void *arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700356 DCHECK(obj != NULL);
357 DCHECK(arg != NULL);
358 InitCallbackState* state = reinterpret_cast<InitCallbackState*>(arg);
359
360 if (!obj->IsClass()) {
361 return;
362 }
363 Class* klass = obj->AsClass();
364 CHECK(klass->class_loader_ == NULL);
365
366 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
367
368 // restore class to ClassLinker::classes_ table
369 state->class_linker->InsertClass(descriptor, klass);
370
371 // note DexCache to match with DexFile later
372 DexCache* dex_cache = klass->GetDexCache();
373 if (dex_cache != NULL) {
374 state->dex_caches.insert(dex_cache);
375 } else {
376 DCHECK(klass->IsArray() || klass->IsPrimitive());
377 }
378
379 // check if this is a root, if so, register it
380 typedef InitCallbackState::Table::const_iterator It; // TODO: C++0x auto
381 It it = state->descriptor_to_class_root.find(descriptor);
382 if (it != state->descriptor_to_class_root.end()) {
383 ClassRoot class_root = it->second;
384 state->class_roots[class_root] = klass;
385 }
386}
387
388// Keep in sync with InitCallback. Anything we visit, we need to
389// reinit references to when reinitializing a ClassLinker from a
390// mapped image.
391void ClassLinker::VisitRoots(Heap::RootVistor* root_visitor, void* arg) const {
392
Brian Carlstromb88e9442011-07-28 15:15:51 -0700393 root_visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700394
395 for (size_t i = 0; i < dex_caches_.size(); i++) {
Brian Carlstromb88e9442011-07-28 15:15:51 -0700396 root_visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700397 }
398
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700399 {
400 MutexLock mu(classes_lock_);
401 typedef Table::const_iterator It; // TODO: C++0x auto
402 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
403 root_visitor(it->second, arg);
404 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700405 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700406
407 intern_table_.VisitRoots(root_visitor, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700408
Brian Carlstromb88e9442011-07-28 15:15:51 -0700409 root_visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700410}
411
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700412ClassLinker::~ClassLinker() {
413 delete classes_lock_;
414 String::ResetClass();
415 BooleanArray::ResetArrayClass();
416 ByteArray::ResetArrayClass();
417 CharArray::ResetArrayClass();
418 DoubleArray::ResetArrayClass();
419 FloatArray::ResetArrayClass();
420 IntArray::ResetArrayClass();
421 LongArray::ResetArrayClass();
422 ShortArray::ResetArrayClass();
423 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700424 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700425}
426
427DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700428 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700429 dex_cache->Init(String::AllocFromModifiedUtf8(dex_file.GetLocation().c_str()),
430 AllocObjectArray<String>(dex_file.NumStringIds()),
431 AllocObjectArray<Class>(dex_file.NumTypeIds()),
432 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700433 AllocObjectArray<Field>(dex_file.NumFieldIds()),
434 AllocCodeAndMethods(dex_file.NumMethodIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700435 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700436}
437
Brian Carlstrom83db7722011-08-26 17:32:56 -0700438CodeAndMethods* ClassLinker::AllocCodeAndMethods(size_t length) {
439 return down_cast<CodeAndMethods*>(IntArray::Alloc(CodeAndMethods::LengthAsArray(length)));
440}
441
Brian Carlstrom4873d462011-08-21 15:23:39 -0700442Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
443 DCHECK_GE(class_size, sizeof(Class));
444 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
445 klass->class_size_ = class_size;
446 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700447}
448
Brian Carlstrom4873d462011-08-21 15:23:39 -0700449Class* ClassLinker::AllocClass(size_t class_size) {
450 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700451}
452
Jesse Wilson35baaab2011-08-10 16:18:03 -0400453Field* ClassLinker::AllocField() {
454 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->NewInstance());
Brian Carlstroma0808032011-07-18 00:39:23 -0700455}
456
457Method* ClassLinker::AllocMethod() {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700458 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->NewInstance());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700459}
460
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700461ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
462 return ObjectArray<StackTraceElement>::Alloc(
463 GetClassRoot(kJavaLangStackTraceElementArrayClass),
464 length);
465}
466
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700467Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700468 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700469 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700470 if (class_loader != NULL) {
471 Class* klass = FindClass(descriptor, NULL);
472 if (klass != NULL) {
473 return klass;
474 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700475 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700476 }
477
Carl Shapirob5573532011-07-12 18:22:59 -0700478 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700479 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700480 CHECK(!self->IsExceptionPending());
481 // Find the class in the loaded classes table.
482 Class* klass = LookupClass(descriptor, class_loader);
483 if (klass == NULL) {
484 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700485 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700486 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700487 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700488 const DexFile::ClassPath& class_path = ((class_loader != NULL) ? class_loader->GetClassPath() : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700489 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700490 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700491 std::string name(PrintableString(descriptor));
492 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
493 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700494 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700495 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700496 const DexFile& dex_file = *pair.first;
497 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700498 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700499 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700500 if (!init_done_) {
501 // finish up init of hand crafted class_roots_
502 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700503 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700504 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700505 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400506 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700507 klass = GetClassRoot(kJavaLangString);
508 } else if (descriptor == "Ljava/lang/reflect/Field;") {
509 klass = GetClassRoot(kJavaLangReflectField);
510 } else if (descriptor == "Ljava/lang/reflect/Method;") {
511 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700512 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700513 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700514 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700515 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700516 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700517 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700518 klass->dex_cache_ = dex_cache;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700519 LoadClass(dex_file, dex_class_def, klass, class_loader);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700520 // Check for a pending exception during load
521 if (self->IsExceptionPending()) {
522 // TODO: free native allocations in klass
523 return NULL;
524 }
525 {
526 ObjectLock lock(klass);
Carl Shapirob5573532011-07-12 18:22:59 -0700527 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700528 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700529 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700530 if (!success) {
531 // We may fail to insert if we raced with another thread.
532 klass->clinit_thread_id_ = 0;
533 // TODO: free native allocations in klass
534 klass = LookupClass(descriptor, class_loader);
535 CHECK(klass != NULL);
536 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700537 // Finish loading (if necessary) by finding parents
538 if (!klass->IsLoaded() && !LoadSuperAndInterfaces(klass, dex_file)) {
539 // Loading failed.
540 // TODO: CHECK(self->IsExceptionPending());
541 lock.NotifyAll();
542 return NULL;
543 }
544 CHECK(klass->IsLoaded());
545 // Link the class (if necessary)
546 if (!klass->IsLinked() && !LinkClass(klass, dex_file)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700547 // Linking failed.
548 // TODO: CHECK(self->IsExceptionPending());
549 lock.NotifyAll();
550 return NULL;
551 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700552 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700553 }
554 }
555 }
556 // Link the class if it has not already been linked.
557 if (!klass->IsLinked() && !klass->IsErroneous()) {
558 ObjectLock lock(klass);
559 // Check for circular dependencies between classes.
Carl Shapirob5573532011-07-12 18:22:59 -0700560 if (!klass->IsLinked() && klass->clinit_thread_id_ == self->GetId()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700561 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700562 return NULL;
563 }
564 // Wait for the pending initialization to complete.
565 while (!klass->IsLinked() && !klass->IsErroneous()) {
566 lock.Wait();
567 }
568 }
569 if (klass->IsErroneous()) {
570 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
571 return NULL;
572 }
573 // Return the loaded class. No exceptions should be pending.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700574 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700575 CHECK(!self->IsExceptionPending());
576 return klass;
577}
578
Brian Carlstrom4873d462011-08-21 15:23:39 -0700579// Precomputes size that will be needed for Class, matching LinkStaticFields
580size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
581 const DexFile::ClassDef& dex_class_def) {
582 const byte* class_data = dex_file.GetClassData(dex_class_def);
583 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
584 size_t num_static_fields = header.static_fields_size_;
585 size_t num_ref = 0;
586 size_t num_32 = 0;
587 size_t num_64 = 0;
588 if (num_static_fields != 0) {
589 uint32_t last_idx = 0;
590 for (size_t i = 0; i < num_static_fields; ++i) {
591 DexFile::Field dex_field;
592 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
593 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
594 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
595 char c = descriptor[0];
596 if (c == 'L' || c == '[') {
597 num_ref++;
598 } else if (c == 'J' || c == 'D') {
599 num_64++;
600 } else {
601 num_32++;
602 }
603 }
604 }
605
606 // start with generic class data
607 size_t size = sizeof(Class);
608 // follow with reference fields which must be contiguous at start
609 size += (num_ref * sizeof(uint32_t));
610 // if there are 64-bit fields to add, make sure they are aligned
611 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
612 if (num_32 != 0) {
613 // use an available 32-bit field for padding
614 num_32--;
615 }
616 size += sizeof(uint32_t); // either way, we are adding a word
617 DCHECK_EQ(size, RoundUp(size, 8));
618 }
619 // tack on any 64-bit fields now that alignment is assured
620 size += (num_64 * sizeof(uint64_t));
621 // tack on any remaining 32-bit fields
622 size += (num_32 * sizeof(uint32_t));
623 return size;
624}
625
Brian Carlstromf615a612011-07-23 12:50:34 -0700626void ClassLinker::LoadClass(const DexFile& dex_file,
627 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700628 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700629 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700630 CHECK(klass != NULL);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700631 CHECK(klass->dex_cache_ != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700632 CHECK_EQ(Class::kStatusNotReady, klass->status_);
Brian Carlstromf615a612011-07-23 12:50:34 -0700633 const byte* class_data = dex_file.GetClassData(dex_class_def);
634 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700635
Brian Carlstromf615a612011-07-23 12:50:34 -0700636 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700637 CHECK(descriptor != NULL);
638
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700639 klass->klass_ = GetClassRoot(kJavaLangClass);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700640 klass->descriptor_ = String::AllocFromModifiedUtf8(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -0700641 klass->access_flags_ = dex_class_def.access_flags_;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700642 klass->class_loader_ = class_loader;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700643 klass->primitive_type_ = Class::kPrimNot;
644 klass->status_ = Class::kStatusIdx;
645
646 klass->super_class_ = NULL;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700647 klass->super_class_type_idx_ = dex_class_def.superclass_idx_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700648
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700649 size_t num_static_fields = header.static_fields_size_;
650 size_t num_instance_fields = header.instance_fields_size_;
651 size_t num_direct_methods = header.direct_methods_size_;
652 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700653
Brian Carlstromf615a612011-07-23 12:50:34 -0700654 klass->source_file_ = dex_file.dexGetSourceFile(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700655
656 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700657 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700658
659 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700660 DCHECK(klass->sfields_ == NULL);
661 if (num_static_fields != 0) {
Jesse Wilson35baaab2011-08-10 16:18:03 -0400662 klass->sfields_ = AllocObjectArray<Field>(num_static_fields);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700663 uint32_t last_idx = 0;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700664 for (size_t i = 0; i < klass->NumStaticFields(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700665 DexFile::Field dex_field;
666 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400667 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700668 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700669 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700670 }
671 }
672
673 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700674 DCHECK(klass->ifields_ == NULL);
675 if (num_instance_fields != 0) {
Jesse Wilson35baaab2011-08-10 16:18:03 -0400676 klass->ifields_ = AllocObjectArray<Field>(num_instance_fields);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700677 uint32_t last_idx = 0;
678 for (size_t i = 0; i < klass->NumInstanceFields(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700679 DexFile::Field dex_field;
680 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400681 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700682 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700683 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700684 }
685 }
686
687 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700688 DCHECK(klass->direct_methods_ == NULL);
689 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700690 // TODO: append direct methods to class object
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700691 klass->direct_methods_ = AllocObjectArray<Method>(num_direct_methods);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700692 uint32_t last_idx = 0;
693 for (size_t i = 0; i < klass->NumDirectMethods(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700694 DexFile::Method dex_method;
695 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700696 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700697 klass->SetDirectMethod(i, meth);
Brian Carlstromf615a612011-07-23 12:50:34 -0700698 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700699 // TODO: register maps
700 }
701 }
702
703 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700704 DCHECK(klass->virtual_methods_ == NULL);
705 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700706 // TODO: append virtual methods to class object
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700707 klass->virtual_methods_ = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700708 uint32_t last_idx = 0;
709 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700710 DexFile::Method dex_method;
711 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700712 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700713 klass->SetVirtualMethod(i, meth);
Brian Carlstromf615a612011-07-23 12:50:34 -0700714 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700715 // TODO: register maps
716 }
717 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700718}
719
Brian Carlstromf615a612011-07-23 12:50:34 -0700720void ClassLinker::LoadInterfaces(const DexFile& dex_file,
721 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700722 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700723 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700724 if (list != NULL) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700725 DCHECK(klass->interfaces_ == NULL);
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700726 klass->interfaces_ = AllocObjectArray<Class>(list->Size());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700727 DCHECK(klass->interfaces_type_idx_ == NULL);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700728 klass->interfaces_type_idx_ = IntArray::Alloc(list->Size());
Brian Carlstrom934486c2011-07-12 23:42:50 -0700729 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700730 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700731 klass->interfaces_type_idx_->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700732 }
733 }
734}
735
Brian Carlstromf615a612011-07-23 12:50:34 -0700736void ClassLinker::LoadField(const DexFile& dex_file,
737 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700738 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700739 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700740 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400741 dst->declaring_class_ = klass;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700742 dst->name_ = ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache());
Brian Carlstromae3ac012011-07-27 01:30:28 -0700743 dst->descriptor_.set(dex_file.dexStringByTypeIdx(field_id.type_idx_));
Jesse Wilson35baaab2011-08-10 16:18:03 -0400744 // TODO: Assign dst->type_.
Brian Carlstrom934486c2011-07-12 23:42:50 -0700745 dst->access_flags_ = src.access_flags_;
746}
747
Brian Carlstromf615a612011-07-23 12:50:34 -0700748void ClassLinker::LoadMethod(const DexFile& dex_file,
749 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700750 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700751 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700752 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400753 dst->declaring_class_ = klass;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700754 dst->name_ = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700755 {
756 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700757 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
758 dst->signature_ = String::AllocFromModifiedUtf8(utf16_length, utf8.c_str());
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700759 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700760 dst->proto_idx_ = method_id.proto_idx_;
Shih-wei Liao2fb97532011-08-11 16:17:23 -0700761 dst->code_off_ = src.code_off_;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700762 dst->shorty_ = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700763 dst->access_flags_ = src.access_flags_;
764
Brian Carlstromc4fa2c02011-08-21 03:00:12 -0700765 dst->dex_cache_strings_ = klass->dex_cache_->GetStrings();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700766 dst->dex_cache_types_ = klass->dex_cache_->GetTypes();
Brian Carlstromc4fa2c02011-08-21 03:00:12 -0700767 dst->dex_cache_methods_ = klass->dex_cache_->GetMethods();
768 dst->dex_cache_fields_ = klass->dex_cache_->GetFields();
Brian Carlstrom83db7722011-08-26 17:32:56 -0700769 dst->dex_cache_code_and_methods_ = klass->dex_cache_->GetCodeAndMethods();
Brian Carlstromc4fa2c02011-08-21 03:00:12 -0700770
Brian Carlstrom934486c2011-07-12 23:42:50 -0700771 // TODO: check for finalize method
772
Brian Carlstromf615a612011-07-23 12:50:34 -0700773 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700774 if (code_item != NULL) {
775 dst->num_registers_ = code_item->registers_size_;
776 dst->num_ins_ = code_item->ins_size_;
777 dst->num_outs_ = code_item->outs_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700778 } else {
779 uint16_t num_args = dst->NumArgRegisters();
780 if (!dst->IsStatic()) {
781 ++num_args;
782 }
783 dst->num_registers_ = dst->num_ins_ + num_args;
784 // TODO: native methods
785 }
786}
787
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700788void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700789 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
790}
791
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700792void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700793 CHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700794 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700795 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700796}
797
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700798void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700799 RegisterDexFile(dex_file, AllocDexCache(dex_file));
800}
801
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700802void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700803 CHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700804 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700805 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700806}
807
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700808const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700809 for (size_t i = 0; i != dex_caches_.size(); ++i) {
810 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700811 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700812 }
813 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700814 CHECK(false) << "Could not find DexFile";
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700815 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700816}
817
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700818DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstromf615a612011-07-23 12:50:34 -0700819 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700820 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700821 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700822 }
823 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700824 CHECK(false) << "Could not find DexCache";
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700825 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700826}
827
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700828Class* ClassLinker::CreatePrimitiveClass(const char* descriptor) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700829 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700830 CHECK(klass != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -0700831 klass->super_class_ = NULL;
Carl Shapiro565f5072011-07-10 13:39:43 -0700832 klass->access_flags_ = kAccPublic | kAccFinal | kAccAbstract;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700833 klass->descriptor_ = String::AllocFromModifiedUtf8(descriptor);
Carl Shapiro565f5072011-07-10 13:39:43 -0700834 klass->status_ = Class::kStatusInitialized;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700835 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700836 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700837 return klass;
838}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700839
Brian Carlstrombe977852011-07-19 14:54:54 -0700840// Create an array class (i.e. the class object for the array, not the
841// array itself). "descriptor" looks like "[C" or "[[[[B" or
842// "[Ljava/lang/String;".
843//
844// If "descriptor" refers to an array of primitives, look up the
845// primitive type's internally-generated class object.
846//
847// "loader" is the class loader of the class that's referring to us. It's
848// used to ensure that we're looking for the element type in the right
849// context. It does NOT become the class loader for the array class; that
850// always comes from the base element class.
851//
852// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700853Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700854 const ClassLoader* class_loader)
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700855{
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700856 CHECK(descriptor[0] == '[');
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700857
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700858 // Identify the underlying element class and the array dimension depth.
859 Class* component_type_ = NULL;
860 int array_rank;
861 if (descriptor[1] == '[') {
862 // array of arrays; keep descriptor and grab stuff from parent
863 Class* outer = FindClass(descriptor.substr(1), class_loader);
864 if (outer != NULL) {
865 // want the base class, not "outer", in our component_type_
866 component_type_ = outer->component_type_;
867 array_rank = outer->array_rank_ + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700868 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700869 DCHECK(component_type_ == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700870 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700871 } else {
872 array_rank = 1;
873 if (descriptor[1] == 'L') {
874 // array of objects; strip off "[" and look up descriptor.
875 const StringPiece subDescriptor = descriptor.substr(1);
876 component_type_ = FindClass(subDescriptor, class_loader);
877 } else {
878 // array of a primitive type
879 component_type_ = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700880 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700881 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700882
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700883 if (component_type_ == NULL) {
884 // failed
885 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
886 return NULL;
887 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700888
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700889 // See if the component type is already loaded. Array classes are
890 // always associated with the class loader of their underlying
891 // element type -- an array of Strings goes with the loader for
892 // java/lang/String -- so we need to look for it there. (The
893 // caller should have checked for the existence of the class
894 // before calling here, but they did so with *their* class loader,
895 // not the component type's loader.)
896 //
897 // If we find it, the caller adds "loader" to the class' initiating
898 // loader list, which should prevent us from going through this again.
899 //
900 // This call is unnecessary if "loader" and "component_type_->class_loader_"
901 // are the same, because our caller (FindClass) just did the
902 // lookup. (Even if we get this wrong we still have correct behavior,
903 // because we effectively do this lookup again when we add the new
904 // class to the hash table --- necessary because of possible races with
905 // other threads.)
906 if (class_loader != component_type_->class_loader_) {
907 Class* new_class = LookupClass(descriptor, component_type_->class_loader_);
908 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700909 return new_class;
910 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700911 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700912
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700913 // Fill out the fields in the Class.
914 //
915 // It is possible to execute some methods against arrays, because
916 // all arrays are subclasses of java_lang_Object_, so we need to set
917 // up a vtable. We can just point at the one in java_lang_Object_.
918 //
919 // Array classes are simple enough that we don't need to do a full
920 // link step.
921
922 Class* new_class = NULL;
923 if (!init_done_) {
924 if (descriptor == "[Ljava/lang/Object;") {
925 new_class = GetClassRoot(kObjectArrayClass);
926 } else if (descriptor == "[C") {
927 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700928 } else if (descriptor == "[I") {
929 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700930 }
931 }
932 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700933 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700934 if (new_class == NULL) {
935 return NULL;
936 }
937 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700938 new_class->descriptor_ = String::AllocFromModifiedUtf8(descriptor.ToString().c_str());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700939 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
940 new_class->super_class_ = java_lang_Object;
941 new_class->vtable_ = java_lang_Object->vtable_;
942 new_class->primitive_type_ = Class::kPrimNot;
943 new_class->component_type_ = component_type_;
944 new_class->class_loader_ = component_type_->class_loader_;
945 new_class->array_rank_ = array_rank;
946 new_class->status_ = Class::kStatusInitialized;
947 // don't need to set new_class->object_size_
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700948 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700949
950
951 // All arrays have java/lang/Cloneable and java/io/Serializable as
952 // interfaces. We need to set that up here, so that stuff like
953 // "instanceof" works right.
954 //
955 // Note: The GC could run during the call to FindSystemClass,
956 // so we need to make sure the class object is GC-valid while we're in
957 // there. Do this by clearing the interface list so the GC will just
958 // think that the entries are null.
959
960
961 // Use the single, global copies of "interfaces" and "iftable"
962 // (remember not to free them for arrays).
963 DCHECK(array_interfaces_ != NULL);
964 new_class->interfaces_ = array_interfaces_;
965 new_class->iftable_count_ = 2;
966 DCHECK(array_iftable_ != NULL);
967 new_class->iftable_ = array_iftable_;
968
969 // Inherit access flags from the component type. Arrays can't be
970 // used as a superclass or interface, so we want to add "final"
971 // and remove "interface".
972 //
973 // Don't inherit any non-standard flags (e.g., kAccFinal)
974 // from component_type_. We assume that the array class does not
975 // override finalize().
976 new_class->access_flags_ = ((new_class->component_type_->access_flags_ &
977 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask;
978
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700979 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700980 return new_class;
981 }
982 // Another thread must have loaded the class after we
983 // started but before we finished. Abandon what we've
984 // done.
985 //
986 // (Yes, this happens.)
987
988 // Grab the winning class.
989 Class* other_class = LookupClass(descriptor, component_type_->class_loader_);
990 DCHECK(other_class != NULL);
991 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700992}
993
994Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -0700995 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700996 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700997 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700998 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700999 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001000 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001001 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001002 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001003 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001004 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001005 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001006 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001007 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001008 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001009 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001010 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001011 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001012 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001013 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001014 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001015 std::string printable_type(PrintableChar(type));
1016 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1017 "Not a primitive type: %s", printable_type.c_str());
1018 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001019}
1020
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001021bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1022 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001023 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001024 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001025 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001026}
1027
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001028Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001029 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001030 MutexLock mu(classes_lock_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001031 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001032 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001033 Class* klass = it->second;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001034 if (klass->descriptor_->Equals(descriptor) && klass->class_loader_ == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001035 return klass;
1036 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001037 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001038 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001039}
1040
1041bool ClassLinker::InitializeClass(Class* klass) {
1042 CHECK(klass->GetStatus() == Class::kStatusResolved ||
1043 klass->GetStatus() == Class::kStatusError);
1044
Carl Shapirob5573532011-07-12 18:22:59 -07001045 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001046
1047 {
1048 ObjectLock lock(klass);
1049
1050 if (klass->GetStatus() < Class::kStatusVerified) {
1051 if (klass->IsErroneous()) {
1052 LG << "re-initializing failed class"; // TODO: throw
1053 return false;
1054 }
1055
1056 CHECK(klass->GetStatus() == Class::kStatusResolved);
1057
1058 klass->status_ = Class::kStatusVerifying;
1059 if (!DexVerify::VerifyClass(klass)) {
1060 LG << "Verification failed"; // TODO: ThrowVerifyError
1061 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001062 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001063 klass->SetStatus(Class::kStatusError);
1064 return false;
1065 }
1066
1067 klass->SetStatus(Class::kStatusVerified);
1068 }
1069
1070 if (klass->status_ == Class::kStatusInitialized) {
1071 return true;
1072 }
1073
1074 while (klass->status_ == Class::kStatusInitializing) {
1075 // we caught somebody else in the act; was it us?
Carl Shapirob5573532011-07-12 18:22:59 -07001076 if (klass->clinit_thread_id_ == self->GetId()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001077 LG << "recursive <clinit>";
1078 return true;
1079 }
1080
1081 CHECK(!self->IsExceptionPending());
1082
1083 lock.Wait(); // TODO: check for interruption
1084
1085 // When we wake up, repeat the test for init-in-progress. If
1086 // there's an exception pending (only possible if
1087 // "interruptShouldThrow" was set), bail out.
1088 if (self->IsExceptionPending()) {
1089 CHECK(false);
1090 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1091 klass->SetStatus(Class::kStatusError);
1092 return false;
1093 }
1094 if (klass->GetStatus() == Class::kStatusInitializing) {
1095 continue;
1096 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001097 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001098 klass->GetStatus() == Class::kStatusError);
1099 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001100 // The caller wants an exception, but it was thrown in a
1101 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001102 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1103 return false;
1104 }
1105 return true; // otherwise, initialized
1106 }
1107
1108 // see if we failed previously
1109 if (klass->IsErroneous()) {
1110 // might be wise to unlock before throwing; depends on which class
1111 // it is that we have locked
1112
1113 // TODO: throwEarlierClassFailure(klass);
1114 return false;
1115 }
1116
1117 if (!ValidateSuperClassDescriptors(klass)) {
1118 klass->SetStatus(Class::kStatusError);
1119 return false;
1120 }
1121
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001122 DCHECK(klass->status_ < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001123
Carl Shapirob5573532011-07-12 18:22:59 -07001124 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001125 klass->status_ = Class::kStatusInitializing;
1126 }
1127
1128 if (!InitializeSuperClass(klass)) {
1129 return false;
1130 }
1131
1132 InitializeStaticFields(klass);
1133
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001134 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001135 if (clinit != NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001136 // JValue unused;
1137 // TODO: dvmCallMethod(self, method, NULL, &unused);
Elliott Hughes53b61312011-08-12 18:28:20 -07001138 // UNIMPLEMENTED(FATAL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001139 }
1140
1141 {
1142 ObjectLock lock(klass);
1143
1144 if (self->IsExceptionPending()) {
1145 klass->SetStatus(Class::kStatusError);
1146 } else {
1147 klass->SetStatus(Class::kStatusInitialized);
1148 }
1149 lock.NotifyAll();
1150 }
1151
1152 return true;
1153}
1154
1155bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1156 if (klass->IsInterface()) {
1157 return true;
1158 }
1159 // begin with the methods local to the superclass
1160 if (klass->HasSuperClass() &&
1161 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1162 const Class* super = klass->GetSuperClass();
1163 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001164 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001165 if (method != super->GetVirtualMethod(i) &&
1166 !HasSameMethodDescriptorClasses(method, super, klass)) {
1167 LG << "Classes resolve differently in superclass";
1168 return false;
1169 }
1170 }
1171 }
1172 for (size_t i = 0; i < klass->iftable_count_; ++i) {
1173 const InterfaceEntry* iftable = &klass->iftable_[i];
Brian Carlstrom30b94452011-08-25 21:35:26 -07001174 Class* interface = iftable->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001175 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1176 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1177 uint32_t vtable_index = iftable->method_index_array_[j];
1178 const Method* method = klass->GetVirtualMethod(vtable_index);
1179 if (!HasSameMethodDescriptorClasses(method, interface,
1180 method->GetClass())) {
1181 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1182 return false;
1183 }
1184 }
1185 }
1186 }
1187 return true;
1188}
1189
1190bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001191 const Class* klass1,
1192 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001193 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
1194 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->proto_idx_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001195 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001196 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001197 const char* descriptor = it->GetDescriptor();
1198 if (descriptor == NULL) {
1199 break;
1200 }
1201 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1202 // Found a non-primitive type.
1203 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1204 return false;
1205 }
1206 }
1207 }
1208 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001209 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001210 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1211 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1212 return false;
1213 }
1214 }
1215 return true;
1216}
1217
1218// Returns true if classes referenced by the descriptor are the
1219// same classes in klass1 as they are in klass2.
1220bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001221 const Class* klass1,
1222 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001223 CHECK(descriptor != NULL);
1224 CHECK(klass1 != NULL);
1225 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001226 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001227 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001228 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001229 // TODO: found2 == NULL
1230 // TODO: lookup found1 in initiating loader list
1231 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001232 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001233 if (found1 == found2) {
1234 return true;
1235 } else {
1236 return false;
1237 }
1238 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001239 return true;
1240}
1241
1242bool ClassLinker::InitializeSuperClass(Class* klass) {
1243 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001244 if (!klass->IsInterface() && klass->HasSuperClass()) {
1245 Class* super_class = klass->GetSuperClass();
1246 if (super_class->GetStatus() != Class::kStatusInitialized) {
1247 CHECK(!super_class->IsInterface());
1248 klass->MonitorExit();
1249 bool super_initialized = InitializeClass(super_class);
1250 klass->MonitorEnter();
1251 // TODO: check for a pending exception
1252 if (!super_initialized) {
1253 klass->SetStatus(Class::kStatusError);
1254 klass->NotifyAll();
1255 return false;
1256 }
1257 }
1258 }
1259 return true;
1260}
1261
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001262bool ClassLinker::EnsureInitialized(Class* c) {
1263 CHECK(c != NULL);
1264 if (c->IsInitialized()) {
1265 return true;
1266 }
1267
1268 c->MonitorExit();
1269 InitializeClass(c);
1270 c->MonitorEnter();
1271 return !Thread::Current()->IsExceptionPending();
1272}
1273
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001274void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001275 size_t num_static_fields = klass->NumStaticFields();
1276 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001277 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001278 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001279 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001280 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001281 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001282 return;
1283 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001284 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001285 const DexFile& dex_file = FindDexFile(dex_cache);
1286 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001287 CHECK(dex_class_def != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001288 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001289 if (addr == NULL) {
1290 // All this class' static fields have default values.
1291 return;
1292 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001293 size_t array_size = DecodeUnsignedLeb128(&addr);
1294 for (size_t i = 0; i < array_size; ++i) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001295 Field* field = klass->GetStaticField(i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001296 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001297 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001298 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001299 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001300 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001301 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001302 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001303 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001304 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001305 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001306 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001307 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001308 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001309 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001310 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001311 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001312 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001313 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001314 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001315 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001316 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001317 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001318 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001319 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001320 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001321 uint32_t string_idx = value.i;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001322 String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001323 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001324 break;
1325 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001326 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001327 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001328 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001329 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001330 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001331 break;
1332 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001333 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001334 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001335 }
1336}
1337
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001338bool ClassLinker::LinkClass(Class* klass, const DexFile& dex_file) {
1339 CHECK_EQ(Class::kStatusLoaded, klass->status_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001340 if (!LinkSuperClass(klass)) {
1341 return false;
1342 }
1343 if (!LinkMethods(klass)) {
1344 return false;
1345 }
1346 if (!LinkInstanceFields(klass)) {
1347 return false;
1348 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001349 if (!LinkStaticFields(klass)) {
1350 return false;
1351 }
1352 CreateReferenceInstanceOffsets(klass);
1353 CreateReferenceStaticOffsets(klass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001354 CHECK_EQ(Class::kStatusLoaded, klass->status_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001355 klass->status_ = Class::kStatusResolved;
1356 return true;
1357}
1358
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001359bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
1360 CHECK_EQ(Class::kStatusIdx, klass->status_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001361 if (klass->super_class_type_idx_ != DexFile::kDexNoIndex) {
1362 Class* super_class = ResolveType(dex_file, klass->super_class_type_idx_, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001363 if (super_class == NULL) {
1364 LG << "Failed to resolve superclass";
1365 return false;
1366 }
1367 klass->super_class_ = super_class; // TODO: write barrier
1368 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001369 if (klass->NumInterfaces() > 0) {
1370 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001371 uint32_t type_idx = klass->interfaces_type_idx_->Get(i);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001372 klass->SetInterface(i, ResolveType(dex_file, type_idx, klass));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001373 if (klass->GetInterface(i) == NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001374 LG << "Failed to resolve interface";
1375 return false;
1376 }
1377 // Verify
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001378 if (!klass->CanAccess(klass->GetInterface(i))) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001379 LG << "Inaccessible interface";
1380 return false;
1381 }
1382 }
1383 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001384 // Mark the class as loaded.
1385 klass->status_ = Class::kStatusLoaded;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001386 return true;
1387}
1388
1389bool ClassLinker::LinkSuperClass(Class* klass) {
1390 CHECK(!klass->IsPrimitive());
1391 const Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001392 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001393 if (super != NULL) {
1394 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1395 return false;
1396 }
1397 // TODO: clear finalize attribute
1398 return true;
1399 }
1400 if (super == NULL) {
1401 LG << "No superclass defined"; // TODO: LinkageError
1402 return false;
1403 }
1404 // Verify
1405 if (super->IsFinal()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001406 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001407 return false;
1408 }
1409 if (super->IsInterface()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001410 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001411 return false;
1412 }
1413 if (!klass->CanAccess(super)) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001414 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001415 return false;
1416 }
1417 return true;
1418}
1419
1420// Populate the class vtable and itable.
1421bool ClassLinker::LinkMethods(Class* klass) {
1422 if (klass->IsInterface()) {
1423 // No vtable.
1424 size_t count = klass->NumVirtualMethods();
1425 if (!IsUint(16, count)) {
1426 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1427 return false;
1428 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001429 for (size_t i = 0; i < count; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001430 klass->GetVirtualMethod(i)->method_index_ = i;
1431 }
1432 } else {
1433 // Link virtual method tables
1434 LinkVirtualMethods(klass);
1435
1436 // Link interface method tables
1437 LinkInterfaceMethods(klass);
1438
1439 // Insert stubs.
1440 LinkAbstractMethods(klass);
1441 }
1442 return true;
1443}
1444
1445bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001446 if (klass->HasSuperClass()) {
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001447 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->vtable_->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001448 size_t actual_count = klass->GetSuperClass()->vtable_->GetLength();
1449 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001450 // TODO: do not assign to the vtable field until it is fully constructed.
1451 klass->vtable_ = klass->GetSuperClass()->vtable_->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001452 // See if any of our virtual methods override the superclass.
1453 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1454 Method* local_method = klass->GetVirtualMethod(i);
1455 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001456 for (; j < actual_count; ++j) {
1457 Method* super_method = klass->vtable_->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001458 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001459 // Verify
1460 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001461 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001462 return false;
1463 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001464 klass->vtable_->Set(j, local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001465 local_method->method_index_ = j;
1466 break;
1467 }
1468 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001469 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001470 // Not overriding, append.
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001471 klass->vtable_->Set(actual_count, local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001472 local_method->method_index_ = actual_count;
1473 actual_count += 1;
1474 }
1475 }
1476 if (!IsUint(16, actual_count)) {
1477 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1478 return false;
1479 }
1480 CHECK_LE(actual_count, max_count);
1481 if (actual_count < max_count) {
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001482 // TODO: do not assign to the vtable field until it is fully constructed.
1483 klass->vtable_ = klass->vtable_->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001484 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001485 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001486 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001487 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001488 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001489 LG << "Too many methods"; // TODO: VirtualMachineError
1490 return false;
1491 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001492 // TODO: do not assign to the vtable field until it is fully constructed.
1493 klass->vtable_ = AllocObjectArray<Method>(num_virtual_methods);
1494 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001495 klass->vtable_->Set(i, klass->GetVirtualMethod(i));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001496 klass->GetVirtualMethod(i)->method_index_ = i & 0xFFFF;
1497 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001498 }
1499 return true;
1500}
1501
1502bool ClassLinker::LinkInterfaceMethods(Class* klass) {
1503 int pool_offset = 0;
1504 int pool_size = 0;
1505 int miranda_count = 0;
1506 int miranda_alloc = 0;
1507 size_t super_ifcount;
1508 if (klass->HasSuperClass()) {
1509 super_ifcount = klass->GetSuperClass()->iftable_count_;
1510 } else {
1511 super_ifcount = 0;
1512 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001513 size_t ifcount = super_ifcount;
1514 ifcount += klass->NumInterfaces();
1515 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1516 ifcount += klass->GetInterface(i)->iftable_count_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001517 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001518 if (ifcount == 0) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001519 DCHECK(klass->iftable_count_ == 0);
1520 DCHECK(klass->iftable_ == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001521 return true;
1522 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001523 klass->iftable_ = new InterfaceEntry[ifcount * sizeof(InterfaceEntry)];
1524 memset(klass->iftable_, 0x00, sizeof(InterfaceEntry) * ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001525 if (super_ifcount != 0) {
1526 memcpy(klass->iftable_, klass->GetSuperClass()->iftable_,
1527 sizeof(InterfaceEntry) * super_ifcount);
1528 }
1529 // Flatten the interface inheritance hierarchy.
1530 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001531 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1532 Class* interf = klass->GetInterface(i);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001533 DCHECK(interf != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001534 if (!interf->IsInterface()) {
1535 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1536 return false;
1537 }
Brian Carlstrom30b94452011-08-25 21:35:26 -07001538 klass->iftable_[idx++].SetInterface(interf);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001539 for (size_t j = 0; j < interf->iftable_count_; j++) {
Brian Carlstrom30b94452011-08-25 21:35:26 -07001540 klass->iftable_[idx++].SetInterface(interf->iftable_[j].GetInterface());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001541 }
1542 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001543 CHECK_EQ(idx, ifcount);
1544 klass->iftable_count_ = ifcount;
1545 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001546 return true;
1547 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001548 for (size_t i = super_ifcount; i < ifcount; i++) {
Brian Carlstrom30b94452011-08-25 21:35:26 -07001549 pool_size += klass->iftable_[i].GetInterface()->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001550 }
1551 if (pool_size == 0) {
1552 return true;
1553 }
1554 klass->ifvi_pool_count_ = pool_size;
1555 klass->ifvi_pool_ = new uint32_t[pool_size];
1556 std::vector<Method*> miranda_list;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001557 for (size_t i = super_ifcount; i < ifcount; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001558 klass->iftable_[i].method_index_array_ = klass->ifvi_pool_ + pool_offset;
Brian Carlstrom30b94452011-08-25 21:35:26 -07001559 Class* interface = klass->iftable_[i].GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001560 pool_offset += interface->NumVirtualMethods(); // end here
1561 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1562 Method* interface_method = interface->GetVirtualMethod(j);
1563 int k; // must be signed
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001564 for (k = klass->vtable_->GetLength() - 1; k >= 0; --k) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001565 Method* vtable_method = klass->vtable_->Get(k);
1566 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1567 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001568 LG << "Implementation not public";
1569 return false;
1570 }
1571 klass->iftable_[i].method_index_array_[j] = k;
1572 break;
1573 }
1574 }
1575 if (k < 0) {
1576 if (miranda_count == miranda_alloc) {
1577 miranda_alloc += 8;
1578 if (miranda_list.empty()) {
1579 miranda_list.resize(miranda_alloc);
1580 } else {
1581 miranda_list.resize(miranda_alloc);
1582 }
1583 }
1584 int mir;
1585 for (mir = 0; mir < miranda_count; mir++) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001586 Method* miranda_method = miranda_list[mir];
1587 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001588 break;
1589 }
1590 }
1591 // point the interface table at a phantom slot index
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001592 klass->iftable_[i].method_index_array_[j] = klass->vtable_->GetLength() + mir;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001593 if (mir == miranda_count) {
1594 miranda_list[miranda_count++] = interface_method;
1595 }
1596 }
1597 }
1598 }
1599 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001600 int old_method_count = klass->NumVirtualMethods();
1601 int new_method_count = old_method_count + miranda_count;
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001602 klass->virtual_methods_ = klass->virtual_methods_->CopyOf(new_method_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001603
1604 CHECK(klass->vtable_ != NULL);
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001605 int old_vtable_count = klass->vtable_->GetLength();
1606 int new_vtable_count = old_vtable_count + miranda_count;
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001607 // TODO: do not assign to the vtable field until it is fully constructed.
1608 klass->vtable_ = klass->vtable_->CopyOf(new_vtable_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001609
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001610 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001611 Method* meth = AllocMethod();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001612 memcpy(meth, miranda_list[i], sizeof(Method));
1613 meth->klass_ = klass;
1614 meth->access_flags_ |= kAccMiranda;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001615 meth->method_index_ = 0xFFFF & (old_vtable_count + i);
1616 klass->SetVirtualMethod(old_method_count + i, meth);
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001617 klass->vtable_->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001618 }
1619 }
1620 return true;
1621}
1622
1623void ClassLinker::LinkAbstractMethods(Class* klass) {
1624 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1625 Method* method = klass->GetVirtualMethod(i);
1626 if (method->IsAbstract()) {
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001627 LG << "AbstractMethodError";
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001628 // TODO: throw AbstractMethodError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001629 }
1630 }
1631}
1632
1633bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001634 CHECK(klass != NULL);
1635 size_t field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001636 if (klass->GetSuperClass() != NULL) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001637 field_offset = klass->GetSuperClass()->object_size_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001638 } else {
Brian Carlstroma0808032011-07-18 00:39:23 -07001639 field_offset = OFFSETOF_MEMBER(DataObject, fields_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001641 return LinkFields(field_offset,
1642 klass->num_reference_instance_fields_,
1643 klass->NumInstanceFields(),
1644 klass->ifields_,
1645 klass->object_size_);
1646}
1647
1648bool ClassLinker::LinkStaticFields(Class* klass) {
1649 CHECK(klass != NULL);
1650 size_t allocated_class_size = klass->class_size_;
1651 size_t field_offset = OFFSETOF_MEMBER(Class, fields_);
1652 bool success = LinkFields(field_offset,
1653 klass->num_reference_static_fields_,
1654 klass->NumStaticFields(),
1655 klass->sfields_,
1656 klass->class_size_);
1657 CHECK_EQ(allocated_class_size, klass->class_size_);
1658 return success;
1659}
1660
1661bool ClassLinker::LinkFields(size_t field_offset,
1662 size_t& num_reference_fields,
1663 size_t num_fields,
1664 ObjectArray<Field>* fields,
1665 size_t& size) {
1666 CHECK((num_fields == 0) == (fields == NULL));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001667 // Move references to the front.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001668 num_reference_fields = 0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001669 size_t i = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001670 for ( ; i < num_fields; i++) {
1671 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001672 char c = pField->GetType();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001673 if (c != '[' && c != 'L') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001674 for (size_t j = num_fields - 1; j > i; j--) {
1675 Field* refField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001676 char rc = refField->GetType();
1677 if (rc == '[' || rc == 'L') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001678 fields->Set(i, refField);
1679 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001680 pField = refField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001681 c = rc;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001682 num_reference_fields++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001683 break;
1684 }
1685 }
1686 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001687 num_reference_fields++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001688 }
1689 if (c != '[' && c != 'L') {
1690 break;
1691 }
Brian Carlstroma0808032011-07-18 00:39:23 -07001692 pField->SetOffset(field_offset);
1693 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001694 }
1695
1696 // Now we want to pack all of the double-wide fields together. If
1697 // we're not aligned, though, we want to shuffle one 32-bit field
1698 // into place. If we can't find one, we'll have to pad it.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001699 if (i != num_fields && (field_offset & 0x04) != 0) {
1700 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001701 char c = pField->GetType();
1702
1703 if (c != 'J' && c != 'D') {
1704 // The field that comes next is 32-bit, so just advance past it.
Brian Carlstrombe977852011-07-19 14:54:54 -07001705 DCHECK(c != '[');
1706 DCHECK(c != 'L');
Brian Carlstroma0808032011-07-18 00:39:23 -07001707 pField->SetOffset(field_offset);
1708 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001709 i++;
1710 } else {
1711 // Next field is 64-bit, so search for a 32-bit field we can
1712 // swap into it.
1713 bool found = false;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001714 for (size_t j = num_fields - 1; j > i; j--) {
1715 Field* singleField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001716 char rc = singleField->GetType();
1717 if (rc != 'J' && rc != 'D') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001718 fields->Set(i, singleField);
1719 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001720 pField = singleField;
Brian Carlstroma0808032011-07-18 00:39:23 -07001721 pField->SetOffset(field_offset);
1722 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001723 found = true;
1724 i++;
1725 break;
1726 }
1727 }
1728 if (!found) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001729 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001730 }
1731 }
1732 }
1733
1734 // Alignment is good, shuffle any double-wide fields forward, and
1735 // finish assigning field offsets to all fields.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001736 DCHECK(i == num_fields || (field_offset & 0x04) == 0);
1737 for ( ; i < num_fields; i++) {
1738 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001739 char c = pField->GetType();
1740 if (c != 'D' && c != 'J') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001741 for (size_t j = num_fields - 1; j > i; j--) {
1742 Field* doubleField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001743 char rc = doubleField->GetType();
1744 if (rc == 'D' || rc == 'J') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001745 fields->Set(i, doubleField);
1746 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001747 pField = doubleField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001748 c = rc;
1749 break;
1750 }
1751 }
1752 } else {
1753 // This is a double-wide field, leave it be.
1754 }
1755
Brian Carlstroma0808032011-07-18 00:39:23 -07001756 pField->SetOffset(field_offset);
1757 field_offset += sizeof(uint32_t);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001758 if (c == 'J' || c == 'D') {
Brian Carlstroma0808032011-07-18 00:39:23 -07001759 field_offset += sizeof(uint32_t);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001760 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001761 }
1762
1763#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001764 // Make sure that all reference fields appear before
1765 // non-reference fields, and all double-wide fields are aligned.
1766 bool seen_non_ref = false;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001767 for (i = 0; i < num_fields; i++) {
1768 Field *pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769 char c = pField->GetType();
1770
1771 if (c == 'D' || c == 'J') {
Brian Carlstrombe977852011-07-19 14:54:54 -07001772 DCHECK_EQ(0U, pField->GetOffset() & 0x07);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001773 }
1774
1775 if (c != '[' && c != 'L') {
Brian Carlstrombe977852011-07-19 14:54:54 -07001776 if (!seen_non_ref) {
1777 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001778 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001779 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001780 } else {
1781 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001782 }
1783 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001784 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001785 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001786 }
1787#endif
Brian Carlstrom4873d462011-08-21 15:23:39 -07001788 size = field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001789 return true;
1790}
1791
1792// Set the bitmap of reference offsets, refOffsets, from the ifields
1793// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001794void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
1795 klass->reference_instance_offsets_ = 0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001796 if (klass->HasSuperClass()) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001797 klass->reference_instance_offsets_ = klass->GetSuperClass()->GetReferenceInstanceOffsets();
1798 // If our superclass overflowed, we don't stand a chance.
1799 if (klass->reference_instance_offsets_ == CLASS_WALK_SUPER) {
1800 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001801 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001802 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001803 CreateReferenceOffsets(klass->reference_instance_offsets_,
1804 klass->NumReferenceInstanceFields(),
1805 klass->ifields_);
1806}
1807
1808void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
1809 klass->reference_static_offsets_ = 0;
1810 CreateReferenceOffsets(klass->reference_static_offsets_,
1811 klass->NumReferenceStaticFields(),
1812 klass->sfields_);
1813}
1814
1815void ClassLinker::CreateReferenceOffsets(uint32_t& reference_offsets,
1816 size_t num_reference_fields,
1817 const ObjectArray<Field>* fields) {
1818 // All of the fields that contain object references are guaranteed
1819 // to be at the beginning of the fields list.
1820 for (size_t i = 0; i < num_reference_fields; ++i) {
1821 // Note that byte_offset is the offset from the beginning of
1822 // object, not the offset into instance data
1823 const Field* field = fields->Get(i);
1824 size_t byte_offset = field->GetOffset();
1825 CHECK_GE(byte_offset, CLASS_SMALLEST_OFFSET);
1826 CHECK_EQ(byte_offset & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
1827 if (CLASS_CAN_ENCODE_OFFSET(byte_offset)) {
1828 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset);
1829 CHECK_NE(new_bit, 0U);
1830 reference_offsets |= new_bit;
1831 } else {
1832 reference_offsets = CLASS_WALK_SUPER;
1833 break;
1834 }
1835 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001836}
1837
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001838String* ClassLinker::ResolveString(const DexFile& dex_file,
1839 uint32_t string_idx,
1840 DexCache* dex_cache) {
1841 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001842 if (resolved != NULL) {
1843 return resolved;
1844 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001845 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
1846 int32_t utf16_length = dex_file.GetStringLength(string_id);
1847 const char* utf8_data = dex_file.GetStringData(string_id);
1848 String* string = intern_table_.Intern(utf16_length, utf8_data);
1849 dex_cache->SetResolvedString(string_idx, string);
1850 return string;
1851}
1852
1853Class* ClassLinker::ResolveType(const DexFile& dex_file,
1854 uint32_t type_idx,
1855 DexCache* dex_cache,
1856 const ClassLoader* class_loader) {
1857 Class* resolved = dex_cache->GetResolvedType(type_idx);
1858 if (resolved != NULL) {
1859 return resolved;
1860 }
1861 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001862 if (descriptor[0] != '\0' && descriptor[1] == '\0') {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001863 resolved = FindPrimitiveClass(descriptor[0]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001864 } else {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001865 resolved = FindClass(descriptor, class_loader);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001866 }
1867 if (resolved != NULL) {
1868 Class* check = resolved->IsArray() ? resolved->component_type_ : resolved;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001869 if (dex_cache != check->GetDexCache()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001870 if (check->GetClassLoader() != NULL) {
1871 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
1872 return NULL;
1873 }
1874 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001875 dex_cache->SetResolvedType(type_idx, resolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001876 } else {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001877 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001878 }
1879 return resolved;
1880}
1881
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001882Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
1883 uint32_t method_idx,
1884 DexCache* dex_cache,
1885 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001886 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001887 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
1888 if (resolved != NULL) {
1889 return resolved;
1890 }
1891 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
1892 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
1893 if (klass == NULL) {
1894 return NULL;
1895 }
1896
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001897 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07001898 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001899 if (is_direct) {
1900 resolved = klass->FindDirectMethod(name, signature);
1901 } else {
1902 resolved = klass->FindVirtualMethod(name, signature);
1903 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001904 if (resolved != NULL) {
1905 dex_cache->SetResolvedMethod(method_idx, resolved);
1906 } else {
1907 // DCHECK(Thread::Current()->IsExceptionPending());
1908 }
1909 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001910}
1911
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001912Field* ClassLinker::ResolveField(const DexFile& dex_file,
1913 uint32_t field_idx,
1914 DexCache* dex_cache,
1915 const ClassLoader* class_loader,
1916 bool is_static) {
1917 Field* resolved = dex_cache->GetResolvedField(field_idx);
1918 if (resolved != NULL) {
1919 return resolved;
1920 }
1921 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
1922 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
1923 if (klass == NULL) {
1924 return NULL;
1925 }
1926
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001927 const char* name = dex_file.dexStringById(field_id.name_idx_);
1928 const char* type = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1929 if (is_static) {
1930 resolved = klass->FindStaticField(name, type);
1931 } else {
1932 resolved = klass->FindInstanceField(name, type);
1933 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001934 if (resolved != NULL) {
1935 dex_cache->SetResolvedfield(field_idx, resolved);
1936 } else {
1937 // DCHECK(Thread::Current()->IsExceptionPending());
1938 }
1939 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001940}
1941
Elliott Hughese27955c2011-08-26 15:21:24 -07001942size_t ClassLinker::NumLoadedClasses() const {
1943 MutexLock mu(classes_lock_);
1944 return classes_.size();
1945}
1946
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001947} // namespace art