blob: a42ab72b3bab74a51b7adf96317d030eb089946c [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 Carlstromb63ec392011-08-27 17:38:27 -070092 object_array_class->array_rank_ = 1;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070093 object_array_class->component_type_ = java_lang_Object;
Elliott Hughesc1674ed2011-08-25 18:09:09 -070094 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
95 CHECK(int_array_class != NULL);
Brian Carlstromb63ec392011-08-27 17:38:27 -070096 int_array_class->array_rank_ = 1;
Elliott Hughesc1674ed2011-08-25 18:09:09 -070097 IntArray::SetArrayClass(int_array_class);
Brian Carlstroma0808032011-07-18 00:39:23 -070098
Brian Carlstrom74eb46a2011-08-02 20:10:14 -070099 // String and char[] are necessary so that FindClass can assign names to members
Brian Carlstrom4873d462011-08-21 15:23:39 -0700100 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
Jesse Wilson14150742011-07-29 19:04:44 -0400101 CHECK(java_lang_String != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700102 CHECK_LT(java_lang_String->object_size_, sizeof(String));
Jesse Wilson14150742011-07-29 19:04:44 -0400103 java_lang_String->object_size_ = sizeof(String);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700104 String::SetClass(java_lang_String);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700105 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Jesse Wilson8989d992011-08-02 13:39:42 -0700106 CHECK(char_array_class != NULL);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700107 char_array_class->array_rank_ = 1;
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700108 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700109 // Now String::Alloc* can be used
110
111 // backfill Class descriptors missing until this point
112 java_lang_Class->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/Class;");
113 java_lang_Object->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/Object;");
114 object_array_class->descriptor_ = String::AllocFromModifiedUtf8("[Ljava/lang/Object;");
115 java_lang_String->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/String;");
116 char_array_class->descriptor_ = String::AllocFromModifiedUtf8("[C");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700117 int_array_class->descriptor_ = String::AllocFromModifiedUtf8("[I");
Jesse Wilson14150742011-07-29 19:04:44 -0400118
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700119 // Field and Method are necessary so that FindClass can link members
Brian Carlstrom4873d462011-08-21 15:23:39 -0700120 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700121 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700122 java_lang_reflect_Field->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/reflect/Field;");
Jesse Wilson35baaab2011-08-10 16:18:03 -0400123 CHECK_LT(java_lang_reflect_Field->object_size_, sizeof(Field));
124 java_lang_reflect_Field->object_size_ = sizeof(Field);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700125 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700126 java_lang_reflect_Method->descriptor_ = String::AllocFromModifiedUtf8("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700127 CHECK(java_lang_reflect_Method != NULL);
128 CHECK_LT(java_lang_reflect_Method->object_size_, sizeof(Method));
129 java_lang_reflect_Method->object_size_ = sizeof(Method);
130
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700131 // create storage for root classes, save away our work so far
132 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700133 SetClassRoot(kJavaLangClass, java_lang_Class);
134 SetClassRoot(kJavaLangObject, java_lang_Object);
135 SetClassRoot(kObjectArrayClass, object_array_class);
136 SetClassRoot(kJavaLangString, java_lang_String);
137 SetClassRoot(kCharArrayClass, char_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700138 SetClassRoot(kIntArrayClass, int_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700139 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
140 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700141 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700142
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700143 // setup boot_class_path_ now that we can use AllocObjectArray to
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700144 // create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700145 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700146 const DexFile* dex_file = boot_class_path[i];
147 CHECK(dex_file != NULL);
148 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700149 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700150 // now we can use FindSystemClass, at least for non-arrays classes.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700151
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700152 // run Class, Field, and Method through FindSystemClass.
153 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700154 // we also override their object_size_ values to accommodate the extra C++ fields.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700155 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700156 CHECK_EQ(java_lang_Class, Class_class);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700157 CHECK_LT(java_lang_Class->object_size_, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700158 java_lang_Class->object_size_ = sizeof(Class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700159 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700160 CHECK_EQ(java_lang_reflect_Field, Field_class);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400161 CHECK_LT(java_lang_reflect_Field->object_size_, sizeof(Field));
162 java_lang_reflect_Field->object_size_ = sizeof(Field);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700163 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700164 CHECK_EQ(java_lang_reflect_Method, Method_class);
165 CHECK_LT(java_lang_reflect_Method->object_size_, sizeof(Method));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700166 java_lang_reflect_Method->object_size_ = sizeof(Method);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700167
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700168 // Object and String just need more minimal setup, since they do not have extra C++ fields.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700169 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700170 CHECK_EQ(java_lang_Object, Object_class);
171 CHECK_EQ(java_lang_Object->object_size_, sizeof(Object));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700172 Class* String_class = FindSystemClass("Ljava/lang/String;");
Jesse Wilsonf7e85a52011-08-01 18:45:58 -0700173 CHECK_EQ(java_lang_String, String_class);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700174 CHECK_EQ(java_lang_String->object_size_, sizeof(String));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700175
176 // Setup the ClassLoaders, adjusting the object_size_ as necessary
177 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
178 CHECK(java_lang_ClassLoader != NULL);
179 CHECK_LT(java_lang_ClassLoader->object_size_, sizeof(ClassLoader));
180 java_lang_ClassLoader->object_size_ = sizeof(ClassLoader);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700181 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700182 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
183 CHECK(dalvik_system_BaseDexClassLoader != NULL);
184 CHECK_EQ(dalvik_system_BaseDexClassLoader->object_size_, sizeof(BaseDexClassLoader));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700185 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700186 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
187 CHECK(dalvik_system_PathClassLoader != NULL);
188 CHECK_EQ(dalvik_system_PathClassLoader->object_size_, sizeof(PathClassLoader));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700189 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700190 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700191
192 // Setup a single, global copy of "interfaces" and "iftable" for
193 // reuse across array classes
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700194 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700195 CHECK(java_lang_Cloneable != NULL);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700196 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700197 CHECK(java_io_Serializable != NULL);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700198
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700199 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700200 CHECK(array_interfaces_ != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700201 array_interfaces_->Set(0, java_lang_Cloneable);
202 array_interfaces_->Set(1, java_io_Serializable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700203
204 // We assume that Cloneable/Serializable don't have superinterfaces --
205 // normally we'd have to crawl up and explicitly list all of the
206 // supers as well. These interfaces don't have any methods, so we
207 // don't have to worry about the ifviPool either.
208 array_iftable_ = new InterfaceEntry[2];
Brian Carlstrom30b94452011-08-25 21:35:26 -0700209 array_iftable_[0].SetInterface(array_interfaces_->Get(0));
210 array_iftable_[1].SetInterface(array_interfaces_->Get(1));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700211 // now FindClass can be used for non-primitive array classes
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700212
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700213 // run Object[] through FindClass to complete initialization
Jesse Wilson8989d992011-08-02 13:39:42 -0700214 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
215 CHECK_EQ(object_array_class, found_object_array_class);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700216 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
217 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700218
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700219 // Setup the primitive type classes.
Brian Carlstroma663ea52011-08-19 23:33:41 -0700220 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z"));
221 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B"));
222 SetClassRoot(kPrimitiveChar, CreatePrimitiveClass("C"));
223 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D"));
224 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F"));
225 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I"));
226 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J"));
227 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S"));
228 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V"));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700229 // now we can use FindSystemClass for anything, including for "[C"
230
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700231 // run char[] and int[] through FindClass to complete initialization
Jesse Wilson8989d992011-08-02 13:39:42 -0700232 Class* found_char_array_class = FindSystemClass("[C");
233 CHECK_EQ(char_array_class, found_char_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700234 Class* found_int_array_class = FindSystemClass("[I");
235 CHECK_EQ(int_array_class, found_int_array_class);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700236
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700237 // Initialize all the other primitive array types for PrimitiveArray::Alloc.
238 // These are easy because everything we need has already been set up.
Brian Carlstroma663ea52011-08-19 23:33:41 -0700239 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
240 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
241 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
242 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
Brian Carlstrom4873d462011-08-21 15:23:39 -0700243 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700244 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700245 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
246 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700247 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
248 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
249 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
250 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Brian Carlstrom4873d462011-08-21 15:23:39 -0700251 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700252 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700253 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700254
Brian Carlstroma663ea52011-08-19 23:33:41 -0700255 FinishInit();
256}
257
258void ClassLinker::FinishInit() {
259 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700260 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700261 ClassRoot class_root = static_cast<ClassRoot>(i);
262 Class* klass = GetClassRoot(class_root);
263 CHECK(klass != NULL);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700264 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->dex_cache_ != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700265 // note SetClassRoot does additional validation.
266 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700267 }
268
269 // disable the slow paths in FindClass and CreatePrimitiveClass now
270 // that Object, Class, and Object[] are setup
271 init_done_ = true;
272}
273
Brian Carlstroma663ea52011-08-19 23:33:41 -0700274struct ClassLinker::InitCallbackState {
275 ClassLinker* class_linker;
276
277 Class* class_roots[kClassRootsMax];
278
279 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
280 Table descriptor_to_class_root;
281
282 struct DexCacheHash {
283 size_t operator()(art::DexCache* const& obj) const {
284 return reinterpret_cast<size_t>(&obj);
285 }
286 };
287 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
288 Set dex_caches;
289};
290
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700291void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path, Space* space) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700292 CHECK(!init_done_);
293
294 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
295 DCHECK(heap_bitmap != NULL);
296
297 InitCallbackState state;
298 state.class_linker = this;
299 for (size_t i = 0; i < kClassRootsMax; i++) {
300 ClassRoot class_root = static_cast<ClassRoot>(i);
301 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
302 }
303
304 // reinit clases_ table
305 heap_bitmap->Walk(InitCallback, &state);
306
307 // reinit class_roots_
308 Class* object_array_class = state.class_roots[kObjectArrayClass];
309 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
310 for (size_t i = 0; i < kClassRootsMax; i++) {
311 ClassRoot class_root = static_cast<ClassRoot>(i);
312 SetClassRoot(class_root, state.class_roots[class_root]);
313 }
314
315 // reinit intern_table_
316 ObjectArray<Object>* interned_array = space->GetImageHeader().GetInternedArray();
317 for (int32_t i = 0; i < interned_array->GetLength(); i++) {
318 String* string = interned_array->Get(i)->AsString();
319 intern_table_.Register(string);
320 }
321
322 // reinit array_interfaces_ from any array class instance, they should all be ==
323 array_interfaces_ = GetClassRoot(kObjectArrayClass)->interfaces_;
324 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->interfaces_);
325
326 // build a map from location to DexCache to match up with DexFile::GetLocation
327 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
328 typedef InitCallbackState::Set::const_iterator It; // TODO: C++0x auto
329 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
330 DexCache* dex_cache = *it;
331 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
332 location_to_dex_cache[location] = dex_cache;
333 }
334
335 // reinit boot_class_path with DexFile arguments and found DexCaches
336 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700337 const DexFile* dex_file = boot_class_path[i];
338 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700339 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700340 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700341 }
342
343 String::SetClass(GetClassRoot(kJavaLangString));
344 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
345 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
346 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
347 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
348 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
349 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
350 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
351 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700352 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700353 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700354
355 FinishInit();
356}
357
Brian Carlstrom4873d462011-08-21 15:23:39 -0700358void ClassLinker::InitCallback(Object* obj, void *arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700359 DCHECK(obj != NULL);
360 DCHECK(arg != NULL);
361 InitCallbackState* state = reinterpret_cast<InitCallbackState*>(arg);
362
363 if (!obj->IsClass()) {
364 return;
365 }
366 Class* klass = obj->AsClass();
367 CHECK(klass->class_loader_ == NULL);
368
369 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
370
371 // restore class to ClassLinker::classes_ table
372 state->class_linker->InsertClass(descriptor, klass);
373
374 // note DexCache to match with DexFile later
375 DexCache* dex_cache = klass->GetDexCache();
376 if (dex_cache != NULL) {
377 state->dex_caches.insert(dex_cache);
378 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700379 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700380 }
381
382 // check if this is a root, if so, register it
383 typedef InitCallbackState::Table::const_iterator It; // TODO: C++0x auto
384 It it = state->descriptor_to_class_root.find(descriptor);
385 if (it != state->descriptor_to_class_root.end()) {
386 ClassRoot class_root = it->second;
387 state->class_roots[class_root] = klass;
388 }
389}
390
391// Keep in sync with InitCallback. Anything we visit, we need to
392// reinit references to when reinitializing a ClassLinker from a
393// mapped image.
394void ClassLinker::VisitRoots(Heap::RootVistor* root_visitor, void* arg) const {
395
Brian Carlstromb88e9442011-07-28 15:15:51 -0700396 root_visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700397
398 for (size_t i = 0; i < dex_caches_.size(); i++) {
Brian Carlstromb88e9442011-07-28 15:15:51 -0700399 root_visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700400 }
401
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700402 {
403 MutexLock mu(classes_lock_);
404 typedef Table::const_iterator It; // TODO: C++0x auto
405 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
406 root_visitor(it->second, arg);
407 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700408 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700409
410 intern_table_.VisitRoots(root_visitor, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700411
Brian Carlstromb88e9442011-07-28 15:15:51 -0700412 root_visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700413}
414
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700415ClassLinker::~ClassLinker() {
416 delete classes_lock_;
417 String::ResetClass();
418 BooleanArray::ResetArrayClass();
419 ByteArray::ResetArrayClass();
420 CharArray::ResetArrayClass();
421 DoubleArray::ResetArrayClass();
422 FloatArray::ResetArrayClass();
423 IntArray::ResetArrayClass();
424 LongArray::ResetArrayClass();
425 ShortArray::ResetArrayClass();
426 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700427 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700428}
429
430DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700431 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700432 dex_cache->Init(String::AllocFromModifiedUtf8(dex_file.GetLocation().c_str()),
433 AllocObjectArray<String>(dex_file.NumStringIds()),
434 AllocObjectArray<Class>(dex_file.NumTypeIds()),
435 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700436 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700437 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
438 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700439 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700440}
441
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700442CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
443 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700444}
445
Brian Carlstrom4873d462011-08-21 15:23:39 -0700446Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
447 DCHECK_GE(class_size, sizeof(Class));
448 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
449 klass->class_size_ = class_size;
450 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700451}
452
Brian Carlstrom4873d462011-08-21 15:23:39 -0700453Class* ClassLinker::AllocClass(size_t class_size) {
454 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700455}
456
Jesse Wilson35baaab2011-08-10 16:18:03 -0400457Field* ClassLinker::AllocField() {
458 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->NewInstance());
Brian Carlstroma0808032011-07-18 00:39:23 -0700459}
460
461Method* ClassLinker::AllocMethod() {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700462 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->NewInstance());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700463}
464
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700465ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
466 return ObjectArray<StackTraceElement>::Alloc(
467 GetClassRoot(kJavaLangStackTraceElementArrayClass),
468 length);
469}
470
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700471Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700472 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700473 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700474 if (class_loader != NULL) {
475 Class* klass = FindClass(descriptor, NULL);
476 if (klass != NULL) {
477 return klass;
478 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700479 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700480 }
481
Carl Shapirob5573532011-07-12 18:22:59 -0700482 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700483 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700484 CHECK(!self->IsExceptionPending());
485 // Find the class in the loaded classes table.
486 Class* klass = LookupClass(descriptor, class_loader);
487 if (klass == NULL) {
488 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700489 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700490 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700491 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700492 const DexFile::ClassPath& class_path = ((class_loader != NULL) ? class_loader->GetClassPath() : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700493 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700494 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700495 std::string name(PrintableString(descriptor));
496 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
497 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700498 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700499 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700500 const DexFile& dex_file = *pair.first;
501 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700502 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700503 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700504 if (!init_done_) {
505 // finish up init of hand crafted class_roots_
506 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700507 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700508 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700509 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400510 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700511 klass = GetClassRoot(kJavaLangString);
512 } else if (descriptor == "Ljava/lang/reflect/Field;") {
513 klass = GetClassRoot(kJavaLangReflectField);
514 } else if (descriptor == "Ljava/lang/reflect/Method;") {
515 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700516 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700517 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700518 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700519 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700520 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700521 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700522 klass->dex_cache_ = dex_cache;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700523 LoadClass(dex_file, dex_class_def, klass, class_loader);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700524 // Check for a pending exception during load
525 if (self->IsExceptionPending()) {
526 // TODO: free native allocations in klass
527 return NULL;
528 }
529 {
530 ObjectLock lock(klass);
Carl Shapirob5573532011-07-12 18:22:59 -0700531 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700532 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700533 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700534 if (!success) {
535 // We may fail to insert if we raced with another thread.
536 klass->clinit_thread_id_ = 0;
537 // TODO: free native allocations in klass
538 klass = LookupClass(descriptor, class_loader);
539 CHECK(klass != NULL);
540 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700541 // Finish loading (if necessary) by finding parents
542 if (!klass->IsLoaded() && !LoadSuperAndInterfaces(klass, dex_file)) {
543 // Loading failed.
544 // TODO: CHECK(self->IsExceptionPending());
545 lock.NotifyAll();
546 return NULL;
547 }
548 CHECK(klass->IsLoaded());
549 // Link the class (if necessary)
550 if (!klass->IsLinked() && !LinkClass(klass, dex_file)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700551 // Linking failed.
552 // TODO: CHECK(self->IsExceptionPending());
553 lock.NotifyAll();
554 return NULL;
555 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700556 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700557 }
558 }
559 }
560 // Link the class if it has not already been linked.
561 if (!klass->IsLinked() && !klass->IsErroneous()) {
562 ObjectLock lock(klass);
563 // Check for circular dependencies between classes.
Carl Shapirob5573532011-07-12 18:22:59 -0700564 if (!klass->IsLinked() && klass->clinit_thread_id_ == self->GetId()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700565 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700566 return NULL;
567 }
568 // Wait for the pending initialization to complete.
569 while (!klass->IsLinked() && !klass->IsErroneous()) {
570 lock.Wait();
571 }
572 }
573 if (klass->IsErroneous()) {
574 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
575 return NULL;
576 }
577 // Return the loaded class. No exceptions should be pending.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700578 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700579 CHECK(!self->IsExceptionPending());
580 return klass;
581}
582
Brian Carlstrom4873d462011-08-21 15:23:39 -0700583// Precomputes size that will be needed for Class, matching LinkStaticFields
584size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
585 const DexFile::ClassDef& dex_class_def) {
586 const byte* class_data = dex_file.GetClassData(dex_class_def);
587 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
588 size_t num_static_fields = header.static_fields_size_;
589 size_t num_ref = 0;
590 size_t num_32 = 0;
591 size_t num_64 = 0;
592 if (num_static_fields != 0) {
593 uint32_t last_idx = 0;
594 for (size_t i = 0; i < num_static_fields; ++i) {
595 DexFile::Field dex_field;
596 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
597 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
598 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
599 char c = descriptor[0];
600 if (c == 'L' || c == '[') {
601 num_ref++;
602 } else if (c == 'J' || c == 'D') {
603 num_64++;
604 } else {
605 num_32++;
606 }
607 }
608 }
609
610 // start with generic class data
611 size_t size = sizeof(Class);
612 // follow with reference fields which must be contiguous at start
613 size += (num_ref * sizeof(uint32_t));
614 // if there are 64-bit fields to add, make sure they are aligned
615 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
616 if (num_32 != 0) {
617 // use an available 32-bit field for padding
618 num_32--;
619 }
620 size += sizeof(uint32_t); // either way, we are adding a word
621 DCHECK_EQ(size, RoundUp(size, 8));
622 }
623 // tack on any 64-bit fields now that alignment is assured
624 size += (num_64 * sizeof(uint64_t));
625 // tack on any remaining 32-bit fields
626 size += (num_32 * sizeof(uint32_t));
627 return size;
628}
629
Brian Carlstromf615a612011-07-23 12:50:34 -0700630void ClassLinker::LoadClass(const DexFile& dex_file,
631 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700632 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700633 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700634 CHECK(klass != NULL);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700635 CHECK(klass->dex_cache_ != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700636 CHECK_EQ(Class::kStatusNotReady, klass->status_);
Brian Carlstromf615a612011-07-23 12:50:34 -0700637 const byte* class_data = dex_file.GetClassData(dex_class_def);
638 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700639
Brian Carlstromf615a612011-07-23 12:50:34 -0700640 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700641 CHECK(descriptor != NULL);
642
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700643 klass->klass_ = GetClassRoot(kJavaLangClass);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700644 klass->descriptor_ = String::AllocFromModifiedUtf8(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -0700645 klass->access_flags_ = dex_class_def.access_flags_;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700646 klass->class_loader_ = class_loader;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700647 klass->primitive_type_ = Class::kPrimNot;
648 klass->status_ = Class::kStatusIdx;
649
650 klass->super_class_ = NULL;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700651 klass->super_class_type_idx_ = dex_class_def.superclass_idx_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700652
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700653 size_t num_static_fields = header.static_fields_size_;
654 size_t num_instance_fields = header.instance_fields_size_;
655 size_t num_direct_methods = header.direct_methods_size_;
656 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700657
Brian Carlstromf615a612011-07-23 12:50:34 -0700658 klass->source_file_ = dex_file.dexGetSourceFile(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700659
660 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700661 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700662
663 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700664 DCHECK(klass->sfields_ == NULL);
665 if (num_static_fields != 0) {
Jesse Wilson35baaab2011-08-10 16:18:03 -0400666 klass->sfields_ = AllocObjectArray<Field>(num_static_fields);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700667 uint32_t last_idx = 0;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700668 for (size_t i = 0; i < klass->NumStaticFields(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700669 DexFile::Field dex_field;
670 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400671 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700672 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700673 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700674 }
675 }
676
677 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700678 DCHECK(klass->ifields_ == NULL);
679 if (num_instance_fields != 0) {
Jesse Wilson35baaab2011-08-10 16:18:03 -0400680 klass->ifields_ = AllocObjectArray<Field>(num_instance_fields);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700681 uint32_t last_idx = 0;
682 for (size_t i = 0; i < klass->NumInstanceFields(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700683 DexFile::Field dex_field;
684 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400685 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700686 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700687 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700688 }
689 }
690
691 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700692 DCHECK(klass->direct_methods_ == NULL);
693 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700694 // TODO: append direct methods to class object
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700695 klass->direct_methods_ = AllocObjectArray<Method>(num_direct_methods);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700696 uint32_t last_idx = 0;
697 for (size_t i = 0; i < klass->NumDirectMethods(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700698 DexFile::Method dex_method;
699 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700700 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700701 klass->SetDirectMethod(i, meth);
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700702 LoadMethod(dex_file, dex_method, klass, meth, true);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700703 // TODO: register maps
704 }
705 }
706
707 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700708 DCHECK(klass->virtual_methods_ == NULL);
709 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700710 // TODO: append virtual methods to class object
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700711 klass->virtual_methods_ = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700712 uint32_t last_idx = 0;
713 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700714 DexFile::Method dex_method;
715 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700716 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700717 klass->SetVirtualMethod(i, meth);
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700718 LoadMethod(dex_file, dex_method, klass, meth, false);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700719 // TODO: register maps
720 }
721 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700722}
723
Brian Carlstromf615a612011-07-23 12:50:34 -0700724void ClassLinker::LoadInterfaces(const DexFile& dex_file,
725 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700726 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700727 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700728 if (list != NULL) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700729 DCHECK(klass->interfaces_ == NULL);
Brian Carlstrom4a96b602011-07-26 16:40:23 -0700730 klass->interfaces_ = AllocObjectArray<Class>(list->Size());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700731 DCHECK(klass->interfaces_type_idx_ == NULL);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700732 klass->interfaces_type_idx_ = IntArray::Alloc(list->Size());
Brian Carlstrom934486c2011-07-12 23:42:50 -0700733 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700734 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700735 klass->interfaces_type_idx_->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700736 }
737 }
738}
739
Brian Carlstromf615a612011-07-23 12:50:34 -0700740void ClassLinker::LoadField(const DexFile& dex_file,
741 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700742 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700743 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700744 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400745 dst->declaring_class_ = klass;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700746 dst->name_ = ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache());
Brian Carlstromae3ac012011-07-27 01:30:28 -0700747 dst->descriptor_.set(dex_file.dexStringByTypeIdx(field_id.type_idx_));
Jesse Wilson35baaab2011-08-10 16:18:03 -0400748 // TODO: Assign dst->type_.
Brian Carlstrom934486c2011-07-12 23:42:50 -0700749 dst->access_flags_ = src.access_flags_;
750}
751
Brian Carlstromf615a612011-07-23 12:50:34 -0700752void ClassLinker::LoadMethod(const DexFile& dex_file,
753 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700754 Class* klass,
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700755 Method* dst,
756 bool is_direct) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700757 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Jesse Wilson7833bd22011-08-09 18:31:44 -0400758 dst->declaring_class_ = klass;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700759 dst->name_ = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700760 {
761 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700762 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
763 dst->signature_ = String::AllocFromModifiedUtf8(utf16_length, utf8.c_str());
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700764 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700765 dst->proto_idx_ = method_id.proto_idx_;
Shih-wei Liao2fb97532011-08-11 16:17:23 -0700766 dst->code_off_ = src.code_off_;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700767 dst->shorty_ = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700768 dst->access_flags_ = src.access_flags_;
769
Brian Carlstromc4fa2c02011-08-21 03:00:12 -0700770 dst->dex_cache_strings_ = klass->dex_cache_->GetStrings();
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700771 dst->dex_cache_resolved_types_ = klass->dex_cache_->GetResolvedTypes();
772 dst->dex_cache_resolved_methods_ = klass->dex_cache_->GetResolvedMethods();
773 dst->dex_cache_resolved_fields_ = klass->dex_cache_->GetResolvedFields();
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700774 dst->dex_cache_code_and_direct_methods_ = klass->dex_cache_->GetCodeAndDirectMethods();
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700775 dst->dex_cache_initialized_static_storage_ = klass->dex_cache_->GetInitializedStaticStorage();
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700776
777 dst->is_direct_ = is_direct;
Brian Carlstromc4fa2c02011-08-21 03:00:12 -0700778
Brian Carlstrom934486c2011-07-12 23:42:50 -0700779 // TODO: check for finalize method
780
Brian Carlstromf615a612011-07-23 12:50:34 -0700781 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700782 if (code_item != NULL) {
783 dst->num_registers_ = code_item->registers_size_;
784 dst->num_ins_ = code_item->ins_size_;
785 dst->num_outs_ = code_item->outs_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700786 } else {
787 uint16_t num_args = dst->NumArgRegisters();
788 if (!dst->IsStatic()) {
789 ++num_args;
790 }
791 dst->num_registers_ = dst->num_ins_ + num_args;
792 // TODO: native methods
793 }
794}
795
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700796void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700797 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
798}
799
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700800void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700801 CHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700802 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700803 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700804}
805
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700806void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700807 RegisterDexFile(dex_file, AllocDexCache(dex_file));
808}
809
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700810void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700811 CHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700812 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700813 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700814}
815
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700816const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700817 for (size_t i = 0; i != dex_caches_.size(); ++i) {
818 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700819 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700820 }
821 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700822 CHECK(false) << "Could not find DexFile";
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700823 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700824}
825
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700826DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstromf615a612011-07-23 12:50:34 -0700827 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700828 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700829 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700830 }
831 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700832 CHECK(false) << "Could not find DexCache";
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700833 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700834}
835
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700836Class* ClassLinker::CreatePrimitiveClass(const char* descriptor) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700837 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700838 CHECK(klass != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -0700839 klass->super_class_ = NULL;
Carl Shapiro565f5072011-07-10 13:39:43 -0700840 klass->access_flags_ = kAccPublic | kAccFinal | kAccAbstract;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700841 klass->descriptor_ = String::AllocFromModifiedUtf8(descriptor);
Carl Shapiro565f5072011-07-10 13:39:43 -0700842 klass->status_ = Class::kStatusInitialized;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700843 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700844 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700845 return klass;
846}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700847
Brian Carlstrombe977852011-07-19 14:54:54 -0700848// Create an array class (i.e. the class object for the array, not the
849// array itself). "descriptor" looks like "[C" or "[[[[B" or
850// "[Ljava/lang/String;".
851//
852// If "descriptor" refers to an array of primitives, look up the
853// primitive type's internally-generated class object.
854//
855// "loader" is the class loader of the class that's referring to us. It's
856// used to ensure that we're looking for the element type in the right
857// context. It does NOT become the class loader for the array class; that
858// always comes from the base element class.
859//
860// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700861Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700862 const ClassLoader* class_loader)
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700863{
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700864 CHECK(descriptor[0] == '[');
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700865
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700866 // Identify the underlying element class and the array dimension depth.
867 Class* component_type_ = NULL;
868 int array_rank;
869 if (descriptor[1] == '[') {
870 // array of arrays; keep descriptor and grab stuff from parent
871 Class* outer = FindClass(descriptor.substr(1), class_loader);
872 if (outer != NULL) {
873 // want the base class, not "outer", in our component_type_
874 component_type_ = outer->component_type_;
875 array_rank = outer->array_rank_ + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700876 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700877 DCHECK(component_type_ == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700878 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700879 } else {
880 array_rank = 1;
881 if (descriptor[1] == 'L') {
882 // array of objects; strip off "[" and look up descriptor.
883 const StringPiece subDescriptor = descriptor.substr(1);
884 component_type_ = FindClass(subDescriptor, class_loader);
885 } else {
886 // array of a primitive type
887 component_type_ = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700888 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700889 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700890
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700891 if (component_type_ == NULL) {
892 // failed
893 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
894 return NULL;
895 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700896
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700897 // See if the component type is already loaded. Array classes are
898 // always associated with the class loader of their underlying
899 // element type -- an array of Strings goes with the loader for
900 // java/lang/String -- so we need to look for it there. (The
901 // caller should have checked for the existence of the class
902 // before calling here, but they did so with *their* class loader,
903 // not the component type's loader.)
904 //
905 // If we find it, the caller adds "loader" to the class' initiating
906 // loader list, which should prevent us from going through this again.
907 //
908 // This call is unnecessary if "loader" and "component_type_->class_loader_"
909 // are the same, because our caller (FindClass) just did the
910 // lookup. (Even if we get this wrong we still have correct behavior,
911 // because we effectively do this lookup again when we add the new
912 // class to the hash table --- necessary because of possible races with
913 // other threads.)
914 if (class_loader != component_type_->class_loader_) {
915 Class* new_class = LookupClass(descriptor, component_type_->class_loader_);
916 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700917 return new_class;
918 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700919 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700920
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700921 // Fill out the fields in the Class.
922 //
923 // It is possible to execute some methods against arrays, because
924 // all arrays are subclasses of java_lang_Object_, so we need to set
925 // up a vtable. We can just point at the one in java_lang_Object_.
926 //
927 // Array classes are simple enough that we don't need to do a full
928 // link step.
929
930 Class* new_class = NULL;
931 if (!init_done_) {
932 if (descriptor == "[Ljava/lang/Object;") {
933 new_class = GetClassRoot(kObjectArrayClass);
934 } else if (descriptor == "[C") {
935 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700936 } else if (descriptor == "[I") {
937 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700938 }
939 }
940 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700941 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700942 if (new_class == NULL) {
943 return NULL;
944 }
945 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700946 new_class->descriptor_ = String::AllocFromModifiedUtf8(descriptor.ToString().c_str());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700947 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
948 new_class->super_class_ = java_lang_Object;
949 new_class->vtable_ = java_lang_Object->vtable_;
950 new_class->primitive_type_ = Class::kPrimNot;
951 new_class->component_type_ = component_type_;
952 new_class->class_loader_ = component_type_->class_loader_;
953 new_class->array_rank_ = array_rank;
954 new_class->status_ = Class::kStatusInitialized;
955 // don't need to set new_class->object_size_
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700956 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700957
958
959 // All arrays have java/lang/Cloneable and java/io/Serializable as
960 // interfaces. We need to set that up here, so that stuff like
961 // "instanceof" works right.
962 //
963 // Note: The GC could run during the call to FindSystemClass,
964 // so we need to make sure the class object is GC-valid while we're in
965 // there. Do this by clearing the interface list so the GC will just
966 // think that the entries are null.
967
968
969 // Use the single, global copies of "interfaces" and "iftable"
970 // (remember not to free them for arrays).
971 DCHECK(array_interfaces_ != NULL);
972 new_class->interfaces_ = array_interfaces_;
973 new_class->iftable_count_ = 2;
974 DCHECK(array_iftable_ != NULL);
975 new_class->iftable_ = array_iftable_;
976
977 // Inherit access flags from the component type. Arrays can't be
978 // used as a superclass or interface, so we want to add "final"
979 // and remove "interface".
980 //
981 // Don't inherit any non-standard flags (e.g., kAccFinal)
982 // from component_type_. We assume that the array class does not
983 // override finalize().
984 new_class->access_flags_ = ((new_class->component_type_->access_flags_ &
985 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask;
986
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700987 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700988 return new_class;
989 }
990 // Another thread must have loaded the class after we
991 // started but before we finished. Abandon what we've
992 // done.
993 //
994 // (Yes, this happens.)
995
996 // Grab the winning class.
997 Class* other_class = LookupClass(descriptor, component_type_->class_loader_);
998 DCHECK(other_class != NULL);
999 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001000}
1001
1002Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001003 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001004 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001005 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001006 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001007 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001008 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001009 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001010 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001011 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001012 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001013 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001014 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001015 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001016 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001017 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001018 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001019 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001020 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001021 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001022 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001023 std::string printable_type(PrintableChar(type));
1024 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1025 "Not a primitive type: %s", printable_type.c_str());
1026 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001027}
1028
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001029bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1030 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001031 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001032 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001033 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001034}
1035
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001036Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001037 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001038 MutexLock mu(classes_lock_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001039 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001040 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001041 Class* klass = it->second;
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001042 if (klass->descriptor_->Equals(descriptor) && klass->class_loader_ == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001043 return klass;
1044 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001045 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001046 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001047}
1048
1049bool ClassLinker::InitializeClass(Class* klass) {
1050 CHECK(klass->GetStatus() == Class::kStatusResolved ||
1051 klass->GetStatus() == Class::kStatusError);
1052
Carl Shapirob5573532011-07-12 18:22:59 -07001053 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001054
1055 {
1056 ObjectLock lock(klass);
1057
1058 if (klass->GetStatus() < Class::kStatusVerified) {
1059 if (klass->IsErroneous()) {
1060 LG << "re-initializing failed class"; // TODO: throw
1061 return false;
1062 }
1063
1064 CHECK(klass->GetStatus() == Class::kStatusResolved);
1065
1066 klass->status_ = Class::kStatusVerifying;
1067 if (!DexVerify::VerifyClass(klass)) {
1068 LG << "Verification failed"; // TODO: ThrowVerifyError
1069 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001070 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001071 klass->SetStatus(Class::kStatusError);
1072 return false;
1073 }
1074
1075 klass->SetStatus(Class::kStatusVerified);
1076 }
1077
1078 if (klass->status_ == Class::kStatusInitialized) {
1079 return true;
1080 }
1081
1082 while (klass->status_ == Class::kStatusInitializing) {
1083 // we caught somebody else in the act; was it us?
Carl Shapirob5573532011-07-12 18:22:59 -07001084 if (klass->clinit_thread_id_ == self->GetId()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001085 LG << "recursive <clinit>";
1086 return true;
1087 }
1088
1089 CHECK(!self->IsExceptionPending());
1090
1091 lock.Wait(); // TODO: check for interruption
1092
1093 // When we wake up, repeat the test for init-in-progress. If
1094 // there's an exception pending (only possible if
1095 // "interruptShouldThrow" was set), bail out.
1096 if (self->IsExceptionPending()) {
1097 CHECK(false);
1098 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1099 klass->SetStatus(Class::kStatusError);
1100 return false;
1101 }
1102 if (klass->GetStatus() == Class::kStatusInitializing) {
1103 continue;
1104 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001105 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001106 klass->GetStatus() == Class::kStatusError);
1107 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001108 // The caller wants an exception, but it was thrown in a
1109 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001110 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1111 return false;
1112 }
1113 return true; // otherwise, initialized
1114 }
1115
1116 // see if we failed previously
1117 if (klass->IsErroneous()) {
1118 // might be wise to unlock before throwing; depends on which class
1119 // it is that we have locked
1120
1121 // TODO: throwEarlierClassFailure(klass);
1122 return false;
1123 }
1124
1125 if (!ValidateSuperClassDescriptors(klass)) {
1126 klass->SetStatus(Class::kStatusError);
1127 return false;
1128 }
1129
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001130 DCHECK(klass->status_ < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001131
Carl Shapirob5573532011-07-12 18:22:59 -07001132 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001133 klass->status_ = Class::kStatusInitializing;
1134 }
1135
1136 if (!InitializeSuperClass(klass)) {
1137 return false;
1138 }
1139
1140 InitializeStaticFields(klass);
1141
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001142 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001143 if (clinit != NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001144 // JValue unused;
1145 // TODO: dvmCallMethod(self, method, NULL, &unused);
Elliott Hughes53b61312011-08-12 18:28:20 -07001146 // UNIMPLEMENTED(FATAL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001147 }
1148
1149 {
1150 ObjectLock lock(klass);
1151
1152 if (self->IsExceptionPending()) {
1153 klass->SetStatus(Class::kStatusError);
1154 } else {
1155 klass->SetStatus(Class::kStatusInitialized);
1156 }
1157 lock.NotifyAll();
1158 }
1159
1160 return true;
1161}
1162
1163bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1164 if (klass->IsInterface()) {
1165 return true;
1166 }
1167 // begin with the methods local to the superclass
1168 if (klass->HasSuperClass() &&
1169 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1170 const Class* super = klass->GetSuperClass();
1171 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001172 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001173 if (method != super->GetVirtualMethod(i) &&
1174 !HasSameMethodDescriptorClasses(method, super, klass)) {
1175 LG << "Classes resolve differently in superclass";
1176 return false;
1177 }
1178 }
1179 }
1180 for (size_t i = 0; i < klass->iftable_count_; ++i) {
1181 const InterfaceEntry* iftable = &klass->iftable_[i];
Brian Carlstrom30b94452011-08-25 21:35:26 -07001182 Class* interface = iftable->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001183 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1184 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1185 uint32_t vtable_index = iftable->method_index_array_[j];
1186 const Method* method = klass->GetVirtualMethod(vtable_index);
1187 if (!HasSameMethodDescriptorClasses(method, interface,
1188 method->GetClass())) {
1189 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1190 return false;
1191 }
1192 }
1193 }
1194 }
1195 return true;
1196}
1197
1198bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001199 const Class* klass1,
1200 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001201 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
1202 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->proto_idx_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001203 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001204 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001205 const char* descriptor = it->GetDescriptor();
1206 if (descriptor == NULL) {
1207 break;
1208 }
1209 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1210 // Found a non-primitive type.
1211 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1212 return false;
1213 }
1214 }
1215 }
1216 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001217 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001218 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1219 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1220 return false;
1221 }
1222 }
1223 return true;
1224}
1225
1226// Returns true if classes referenced by the descriptor are the
1227// same classes in klass1 as they are in klass2.
1228bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001229 const Class* klass1,
1230 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001231 CHECK(descriptor != NULL);
1232 CHECK(klass1 != NULL);
1233 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001234 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001235 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001236 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001237 // TODO: found2 == NULL
1238 // TODO: lookup found1 in initiating loader list
1239 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001240 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001241 if (found1 == found2) {
1242 return true;
1243 } else {
1244 return false;
1245 }
1246 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001247 return true;
1248}
1249
1250bool ClassLinker::InitializeSuperClass(Class* klass) {
1251 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001252 if (!klass->IsInterface() && klass->HasSuperClass()) {
1253 Class* super_class = klass->GetSuperClass();
1254 if (super_class->GetStatus() != Class::kStatusInitialized) {
1255 CHECK(!super_class->IsInterface());
1256 klass->MonitorExit();
1257 bool super_initialized = InitializeClass(super_class);
1258 klass->MonitorEnter();
1259 // TODO: check for a pending exception
1260 if (!super_initialized) {
1261 klass->SetStatus(Class::kStatusError);
1262 klass->NotifyAll();
1263 return false;
1264 }
1265 }
1266 }
1267 return true;
1268}
1269
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001270bool ClassLinker::EnsureInitialized(Class* c) {
1271 CHECK(c != NULL);
1272 if (c->IsInitialized()) {
1273 return true;
1274 }
1275
1276 c->MonitorExit();
1277 InitializeClass(c);
1278 c->MonitorEnter();
1279 return !Thread::Current()->IsExceptionPending();
1280}
1281
Brian Carlstromb9edb842011-08-28 16:31:06 -07001282StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1283 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001284 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1285 Class* klass = class_linker->ResolveType(type_idx, referrer);
1286 if (klass == NULL) {
1287 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1288 }
1289 if (!class_linker->EnsureInitialized(klass)) {
1290 CHECK(Thread::Current()->IsExceptionPending());
1291 UNIMPLEMENTED(FATAL) << "throw exception due to class initializtion problem";
1292 }
1293 return klass;
1294}
1295
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001296void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001297 size_t num_static_fields = klass->NumStaticFields();
1298 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001299 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001300 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001301 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001302 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001303 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001304 return;
1305 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001306 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001307 const DexFile& dex_file = FindDexFile(dex_cache);
1308 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001309 CHECK(dex_class_def != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001310 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001311 if (addr == NULL) {
1312 // All this class' static fields have default values.
1313 return;
1314 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001315 size_t array_size = DecodeUnsignedLeb128(&addr);
1316 for (size_t i = 0; i < array_size; ++i) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001317 Field* field = klass->GetStaticField(i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001318 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001319 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001320 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001321 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001322 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001323 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001324 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001325 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001326 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001327 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001328 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001329 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001330 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001331 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001332 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001333 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001334 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001335 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001336 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001337 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001338 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001339 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001340 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001341 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001342 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001343 uint32_t string_idx = value.i;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001344 String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001345 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001346 break;
1347 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001348 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001349 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001350 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001351 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001352 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001353 break;
1354 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001355 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001356 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001357 }
1358}
1359
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001360bool ClassLinker::LinkClass(Class* klass, const DexFile& dex_file) {
1361 CHECK_EQ(Class::kStatusLoaded, klass->status_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001362 if (!LinkSuperClass(klass)) {
1363 return false;
1364 }
1365 if (!LinkMethods(klass)) {
1366 return false;
1367 }
1368 if (!LinkInstanceFields(klass)) {
1369 return false;
1370 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001371 if (!LinkStaticFields(klass)) {
1372 return false;
1373 }
1374 CreateReferenceInstanceOffsets(klass);
1375 CreateReferenceStaticOffsets(klass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001376 CHECK_EQ(Class::kStatusLoaded, klass->status_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001377 klass->status_ = Class::kStatusResolved;
1378 return true;
1379}
1380
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001381bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
1382 CHECK_EQ(Class::kStatusIdx, klass->status_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001383 if (klass->super_class_type_idx_ != DexFile::kDexNoIndex) {
1384 Class* super_class = ResolveType(dex_file, klass->super_class_type_idx_, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001385 if (super_class == NULL) {
1386 LG << "Failed to resolve superclass";
1387 return false;
1388 }
1389 klass->super_class_ = super_class; // TODO: write barrier
1390 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001391 if (klass->NumInterfaces() > 0) {
1392 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001393 uint32_t type_idx = klass->interfaces_type_idx_->Get(i);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001394 klass->SetInterface(i, ResolveType(dex_file, type_idx, klass));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001395 if (klass->GetInterface(i) == NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001396 LG << "Failed to resolve interface";
1397 return false;
1398 }
1399 // Verify
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001400 if (!klass->CanAccess(klass->GetInterface(i))) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001401 LG << "Inaccessible interface";
1402 return false;
1403 }
1404 }
1405 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001406 // Mark the class as loaded.
1407 klass->status_ = Class::kStatusLoaded;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001408 return true;
1409}
1410
1411bool ClassLinker::LinkSuperClass(Class* klass) {
1412 CHECK(!klass->IsPrimitive());
1413 const Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001414 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001415 if (super != NULL) {
1416 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1417 return false;
1418 }
1419 // TODO: clear finalize attribute
1420 return true;
1421 }
1422 if (super == NULL) {
1423 LG << "No superclass defined"; // TODO: LinkageError
1424 return false;
1425 }
1426 // Verify
1427 if (super->IsFinal()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001428 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001429 return false;
1430 }
1431 if (super->IsInterface()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001432 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001433 return false;
1434 }
1435 if (!klass->CanAccess(super)) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001436 LG << "Superclass " << super->descriptor_->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001437 return false;
1438 }
1439 return true;
1440}
1441
1442// Populate the class vtable and itable.
1443bool ClassLinker::LinkMethods(Class* klass) {
1444 if (klass->IsInterface()) {
1445 // No vtable.
1446 size_t count = klass->NumVirtualMethods();
1447 if (!IsUint(16, count)) {
1448 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1449 return false;
1450 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001451 for (size_t i = 0; i < count; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001452 klass->GetVirtualMethod(i)->method_index_ = i;
1453 }
1454 } else {
1455 // Link virtual method tables
1456 LinkVirtualMethods(klass);
1457
1458 // Link interface method tables
1459 LinkInterfaceMethods(klass);
1460
1461 // Insert stubs.
1462 LinkAbstractMethods(klass);
1463 }
1464 return true;
1465}
1466
1467bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001468 if (klass->HasSuperClass()) {
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001469 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->vtable_->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001470 size_t actual_count = klass->GetSuperClass()->vtable_->GetLength();
1471 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001472 // TODO: do not assign to the vtable field until it is fully constructed.
1473 klass->vtable_ = klass->GetSuperClass()->vtable_->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001474 // See if any of our virtual methods override the superclass.
1475 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1476 Method* local_method = klass->GetVirtualMethod(i);
1477 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001478 for (; j < actual_count; ++j) {
1479 Method* super_method = klass->vtable_->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001480 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001481 // Verify
1482 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001483 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001484 return false;
1485 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001486 klass->vtable_->Set(j, local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001487 local_method->method_index_ = j;
1488 break;
1489 }
1490 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001491 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001492 // Not overriding, append.
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001493 klass->vtable_->Set(actual_count, local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001494 local_method->method_index_ = actual_count;
1495 actual_count += 1;
1496 }
1497 }
1498 if (!IsUint(16, actual_count)) {
1499 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1500 return false;
1501 }
1502 CHECK_LE(actual_count, max_count);
1503 if (actual_count < max_count) {
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001504 // TODO: do not assign to the vtable field until it is fully constructed.
1505 klass->vtable_ = klass->vtable_->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001506 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001507 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001508 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001509 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001510 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001511 LG << "Too many methods"; // TODO: VirtualMachineError
1512 return false;
1513 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001514 // TODO: do not assign to the vtable field until it is fully constructed.
1515 klass->vtable_ = AllocObjectArray<Method>(num_virtual_methods);
1516 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001517 klass->vtable_->Set(i, klass->GetVirtualMethod(i));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001518 klass->GetVirtualMethod(i)->method_index_ = i & 0xFFFF;
1519 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001520 }
1521 return true;
1522}
1523
1524bool ClassLinker::LinkInterfaceMethods(Class* klass) {
1525 int pool_offset = 0;
1526 int pool_size = 0;
1527 int miranda_count = 0;
1528 int miranda_alloc = 0;
1529 size_t super_ifcount;
1530 if (klass->HasSuperClass()) {
1531 super_ifcount = klass->GetSuperClass()->iftable_count_;
1532 } else {
1533 super_ifcount = 0;
1534 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001535 size_t ifcount = super_ifcount;
1536 ifcount += klass->NumInterfaces();
1537 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1538 ifcount += klass->GetInterface(i)->iftable_count_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001539 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001540 if (ifcount == 0) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001541 DCHECK(klass->iftable_count_ == 0);
1542 DCHECK(klass->iftable_ == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001543 return true;
1544 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001545 klass->iftable_ = new InterfaceEntry[ifcount * sizeof(InterfaceEntry)];
1546 memset(klass->iftable_, 0x00, sizeof(InterfaceEntry) * ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001547 if (super_ifcount != 0) {
1548 memcpy(klass->iftable_, klass->GetSuperClass()->iftable_,
1549 sizeof(InterfaceEntry) * super_ifcount);
1550 }
1551 // Flatten the interface inheritance hierarchy.
1552 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001553 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1554 Class* interf = klass->GetInterface(i);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001555 DCHECK(interf != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001556 if (!interf->IsInterface()) {
1557 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1558 return false;
1559 }
Brian Carlstrom30b94452011-08-25 21:35:26 -07001560 klass->iftable_[idx++].SetInterface(interf);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001561 for (size_t j = 0; j < interf->iftable_count_; j++) {
Brian Carlstrom30b94452011-08-25 21:35:26 -07001562 klass->iftable_[idx++].SetInterface(interf->iftable_[j].GetInterface());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001563 }
1564 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001565 CHECK_EQ(idx, ifcount);
1566 klass->iftable_count_ = ifcount;
1567 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001568 return true;
1569 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001570 for (size_t i = super_ifcount; i < ifcount; i++) {
Brian Carlstrom30b94452011-08-25 21:35:26 -07001571 pool_size += klass->iftable_[i].GetInterface()->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001572 }
1573 if (pool_size == 0) {
1574 return true;
1575 }
1576 klass->ifvi_pool_count_ = pool_size;
1577 klass->ifvi_pool_ = new uint32_t[pool_size];
1578 std::vector<Method*> miranda_list;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001579 for (size_t i = super_ifcount; i < ifcount; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001580 klass->iftable_[i].method_index_array_ = klass->ifvi_pool_ + pool_offset;
Brian Carlstrom30b94452011-08-25 21:35:26 -07001581 Class* interface = klass->iftable_[i].GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001582 pool_offset += interface->NumVirtualMethods(); // end here
1583 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1584 Method* interface_method = interface->GetVirtualMethod(j);
1585 int k; // must be signed
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001586 for (k = klass->vtable_->GetLength() - 1; k >= 0; --k) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001587 Method* vtable_method = klass->vtable_->Get(k);
1588 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1589 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001590 LG << "Implementation not public";
1591 return false;
1592 }
1593 klass->iftable_[i].method_index_array_[j] = k;
1594 break;
1595 }
1596 }
1597 if (k < 0) {
1598 if (miranda_count == miranda_alloc) {
1599 miranda_alloc += 8;
1600 if (miranda_list.empty()) {
1601 miranda_list.resize(miranda_alloc);
1602 } else {
1603 miranda_list.resize(miranda_alloc);
1604 }
1605 }
1606 int mir;
1607 for (mir = 0; mir < miranda_count; mir++) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001608 Method* miranda_method = miranda_list[mir];
1609 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001610 break;
1611 }
1612 }
1613 // point the interface table at a phantom slot index
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001614 klass->iftable_[i].method_index_array_[j] = klass->vtable_->GetLength() + mir;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001615 if (mir == miranda_count) {
1616 miranda_list[miranda_count++] = interface_method;
1617 }
1618 }
1619 }
1620 }
1621 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001622 int old_method_count = klass->NumVirtualMethods();
1623 int new_method_count = old_method_count + miranda_count;
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001624 klass->virtual_methods_ = klass->virtual_methods_->CopyOf(new_method_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001625
1626 CHECK(klass->vtable_ != NULL);
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001627 int old_vtable_count = klass->vtable_->GetLength();
1628 int new_vtable_count = old_vtable_count + miranda_count;
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001629 // TODO: do not assign to the vtable field until it is fully constructed.
1630 klass->vtable_ = klass->vtable_->CopyOf(new_vtable_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001631
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001632 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001633 Method* meth = AllocMethod();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001634 memcpy(meth, miranda_list[i], sizeof(Method));
1635 meth->klass_ = klass;
1636 meth->access_flags_ |= kAccMiranda;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001637 meth->method_index_ = 0xFFFF & (old_vtable_count + i);
1638 klass->SetVirtualMethod(old_method_count + i, meth);
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001639 klass->vtable_->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640 }
1641 }
1642 return true;
1643}
1644
1645void ClassLinker::LinkAbstractMethods(Class* klass) {
1646 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1647 Method* method = klass->GetVirtualMethod(i);
1648 if (method->IsAbstract()) {
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001649 LG << "AbstractMethodError";
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001650 // TODO: throw AbstractMethodError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001651 }
1652 }
1653}
1654
1655bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001656 CHECK(klass != NULL);
1657 size_t field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001658 if (klass->GetSuperClass() != NULL) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001659 field_offset = klass->GetSuperClass()->object_size_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001660 } else {
Brian Carlstroma0808032011-07-18 00:39:23 -07001661 field_offset = OFFSETOF_MEMBER(DataObject, fields_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001662 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001663 return LinkFields(field_offset,
1664 klass->num_reference_instance_fields_,
1665 klass->NumInstanceFields(),
1666 klass->ifields_,
1667 klass->object_size_);
1668}
1669
1670bool ClassLinker::LinkStaticFields(Class* klass) {
1671 CHECK(klass != NULL);
1672 size_t allocated_class_size = klass->class_size_;
1673 size_t field_offset = OFFSETOF_MEMBER(Class, fields_);
1674 bool success = LinkFields(field_offset,
1675 klass->num_reference_static_fields_,
1676 klass->NumStaticFields(),
1677 klass->sfields_,
1678 klass->class_size_);
1679 CHECK_EQ(allocated_class_size, klass->class_size_);
1680 return success;
1681}
1682
1683bool ClassLinker::LinkFields(size_t field_offset,
1684 size_t& num_reference_fields,
1685 size_t num_fields,
1686 ObjectArray<Field>* fields,
1687 size_t& size) {
1688 CHECK((num_fields == 0) == (fields == NULL));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001689 // Move references to the front.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001690 num_reference_fields = 0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001691 size_t i = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001692 for ( ; i < num_fields; i++) {
1693 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001694 char c = pField->GetType();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001695 if (c != '[' && c != 'L') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001696 for (size_t j = num_fields - 1; j > i; j--) {
1697 Field* refField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001698 char rc = refField->GetType();
1699 if (rc == '[' || rc == 'L') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001700 fields->Set(i, refField);
1701 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001702 pField = refField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001703 c = rc;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001704 num_reference_fields++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001705 break;
1706 }
1707 }
1708 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001709 num_reference_fields++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710 }
1711 if (c != '[' && c != 'L') {
1712 break;
1713 }
Brian Carlstroma0808032011-07-18 00:39:23 -07001714 pField->SetOffset(field_offset);
1715 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001716 }
1717
1718 // Now we want to pack all of the double-wide fields together. If
1719 // we're not aligned, though, we want to shuffle one 32-bit field
1720 // into place. If we can't find one, we'll have to pad it.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001721 if (i != num_fields && (field_offset & 0x04) != 0) {
1722 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001723 char c = pField->GetType();
1724
1725 if (c != 'J' && c != 'D') {
1726 // The field that comes next is 32-bit, so just advance past it.
Brian Carlstrombe977852011-07-19 14:54:54 -07001727 DCHECK(c != '[');
1728 DCHECK(c != 'L');
Brian Carlstroma0808032011-07-18 00:39:23 -07001729 pField->SetOffset(field_offset);
1730 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001731 i++;
1732 } else {
1733 // Next field is 64-bit, so search for a 32-bit field we can
1734 // swap into it.
1735 bool found = false;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001736 for (size_t j = num_fields - 1; j > i; j--) {
1737 Field* singleField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001738 char rc = singleField->GetType();
1739 if (rc != 'J' && rc != 'D') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001740 fields->Set(i, singleField);
1741 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001742 pField = singleField;
Brian Carlstroma0808032011-07-18 00:39:23 -07001743 pField->SetOffset(field_offset);
1744 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001745 found = true;
1746 i++;
1747 break;
1748 }
1749 }
1750 if (!found) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001751 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001752 }
1753 }
1754 }
1755
1756 // Alignment is good, shuffle any double-wide fields forward, and
1757 // finish assigning field offsets to all fields.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001758 DCHECK(i == num_fields || (field_offset & 0x04) == 0);
1759 for ( ; i < num_fields; i++) {
1760 Field* pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001761 char c = pField->GetType();
1762 if (c != 'D' && c != 'J') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001763 for (size_t j = num_fields - 1; j > i; j--) {
1764 Field* doubleField = fields->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001765 char rc = doubleField->GetType();
1766 if (rc == 'D' || rc == 'J') {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001767 fields->Set(i, doubleField);
1768 fields->Set(j, pField);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001769 pField = doubleField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001770 c = rc;
1771 break;
1772 }
1773 }
1774 } else {
1775 // This is a double-wide field, leave it be.
1776 }
1777
Brian Carlstroma0808032011-07-18 00:39:23 -07001778 pField->SetOffset(field_offset);
1779 field_offset += sizeof(uint32_t);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001780 if (c == 'J' || c == 'D') {
Brian Carlstroma0808032011-07-18 00:39:23 -07001781 field_offset += sizeof(uint32_t);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001782 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001783 }
1784
1785#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001786 // Make sure that all reference fields appear before
1787 // non-reference fields, and all double-wide fields are aligned.
1788 bool seen_non_ref = false;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001789 for (i = 0; i < num_fields; i++) {
1790 Field *pField = fields->Get(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001791 char c = pField->GetType();
1792
1793 if (c == 'D' || c == 'J') {
Brian Carlstrombe977852011-07-19 14:54:54 -07001794 DCHECK_EQ(0U, pField->GetOffset() & 0x07);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795 }
1796
1797 if (c != '[' && c != 'L') {
Brian Carlstrombe977852011-07-19 14:54:54 -07001798 if (!seen_non_ref) {
1799 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001800 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001801 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001802 } else {
1803 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001804 }
1805 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001806 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001807 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001808 }
1809#endif
Brian Carlstrom4873d462011-08-21 15:23:39 -07001810 size = field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001811 return true;
1812}
1813
1814// Set the bitmap of reference offsets, refOffsets, from the ifields
1815// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001816void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
1817 klass->reference_instance_offsets_ = 0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001818 if (klass->HasSuperClass()) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001819 klass->reference_instance_offsets_ = klass->GetSuperClass()->GetReferenceInstanceOffsets();
1820 // If our superclass overflowed, we don't stand a chance.
1821 if (klass->reference_instance_offsets_ == CLASS_WALK_SUPER) {
1822 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001823 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001824 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001825 CreateReferenceOffsets(klass->reference_instance_offsets_,
1826 klass->NumReferenceInstanceFields(),
1827 klass->ifields_);
1828}
1829
1830void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
1831 klass->reference_static_offsets_ = 0;
1832 CreateReferenceOffsets(klass->reference_static_offsets_,
1833 klass->NumReferenceStaticFields(),
1834 klass->sfields_);
1835}
1836
1837void ClassLinker::CreateReferenceOffsets(uint32_t& reference_offsets,
1838 size_t num_reference_fields,
1839 const ObjectArray<Field>* fields) {
1840 // All of the fields that contain object references are guaranteed
1841 // to be at the beginning of the fields list.
1842 for (size_t i = 0; i < num_reference_fields; ++i) {
1843 // Note that byte_offset is the offset from the beginning of
1844 // object, not the offset into instance data
1845 const Field* field = fields->Get(i);
1846 size_t byte_offset = field->GetOffset();
1847 CHECK_GE(byte_offset, CLASS_SMALLEST_OFFSET);
1848 CHECK_EQ(byte_offset & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
1849 if (CLASS_CAN_ENCODE_OFFSET(byte_offset)) {
1850 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset);
1851 CHECK_NE(new_bit, 0U);
1852 reference_offsets |= new_bit;
1853 } else {
1854 reference_offsets = CLASS_WALK_SUPER;
1855 break;
1856 }
1857 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001858}
1859
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001860String* ClassLinker::ResolveString(const DexFile& dex_file,
1861 uint32_t string_idx,
1862 DexCache* dex_cache) {
1863 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001864 if (resolved != NULL) {
1865 return resolved;
1866 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001867 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
1868 int32_t utf16_length = dex_file.GetStringLength(string_id);
1869 const char* utf8_data = dex_file.GetStringData(string_id);
1870 String* string = intern_table_.Intern(utf16_length, utf8_data);
1871 dex_cache->SetResolvedString(string_idx, string);
1872 return string;
1873}
1874
1875Class* ClassLinker::ResolveType(const DexFile& dex_file,
1876 uint32_t type_idx,
1877 DexCache* dex_cache,
1878 const ClassLoader* class_loader) {
1879 Class* resolved = dex_cache->GetResolvedType(type_idx);
1880 if (resolved != NULL) {
1881 return resolved;
1882 }
1883 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001884 if (descriptor[0] != '\0' && descriptor[1] == '\0') {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001885 resolved = FindPrimitiveClass(descriptor[0]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001886 } else {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001887 resolved = FindClass(descriptor, class_loader);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001888 }
1889 if (resolved != NULL) {
Brian Carlstromb63ec392011-08-27 17:38:27 -07001890 Class* check = resolved->IsArrayClass() ? resolved->component_type_ : resolved;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001891 if (dex_cache != check->GetDexCache()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001892 if (check->GetClassLoader() != NULL) {
1893 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
1894 return NULL;
1895 }
1896 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001897 dex_cache->SetResolvedType(type_idx, resolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001898 } else {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001899 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001900 }
1901 return resolved;
1902}
1903
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001904Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
1905 uint32_t method_idx,
1906 DexCache* dex_cache,
1907 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001908 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001909 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
1910 if (resolved != NULL) {
1911 return resolved;
1912 }
1913 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
1914 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
1915 if (klass == NULL) {
1916 return NULL;
1917 }
1918
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001919 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07001920 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001921 if (is_direct) {
1922 resolved = klass->FindDirectMethod(name, signature);
1923 } else {
1924 resolved = klass->FindVirtualMethod(name, signature);
1925 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001926 if (resolved != NULL) {
1927 dex_cache->SetResolvedMethod(method_idx, resolved);
1928 } else {
1929 // DCHECK(Thread::Current()->IsExceptionPending());
1930 }
1931 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001932}
1933
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001934Field* ClassLinker::ResolveField(const DexFile& dex_file,
1935 uint32_t field_idx,
1936 DexCache* dex_cache,
1937 const ClassLoader* class_loader,
1938 bool is_static) {
1939 Field* resolved = dex_cache->GetResolvedField(field_idx);
1940 if (resolved != NULL) {
1941 return resolved;
1942 }
1943 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
1944 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
1945 if (klass == NULL) {
1946 return NULL;
1947 }
1948
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07001949 const char* name = dex_file.dexStringById(field_id.name_idx_);
1950 const char* type = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1951 if (is_static) {
1952 resolved = klass->FindStaticField(name, type);
1953 } else {
1954 resolved = klass->FindInstanceField(name, type);
1955 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001956 if (resolved != NULL) {
1957 dex_cache->SetResolvedfield(field_idx, resolved);
1958 } else {
1959 // DCHECK(Thread::Current()->IsExceptionPending());
1960 }
1961 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001962}
1963
Elliott Hughese27955c2011-08-26 15:21:24 -07001964size_t ClassLinker::NumLoadedClasses() const {
1965 MutexLock mu(classes_lock_);
1966 return classes_.size();
1967}
1968
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001969} // namespace art