blob: 5c4fa5c0305451c62a052192de8ca2750062ed28 [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2// Author: cshapiro@google.com (Carl Shapiro)
3
4#include "src/class_linker.h"
5
6#include <vector>
7#include <utility>
8
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009#include "src/casts.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010#include "src/dex_verifier.h"
Carl Shapiro5fafe2b2011-07-09 15:34:41 -070011#include "src/heap.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070012#include "src/logging.h"
13#include "src/monitor.h"
14#include "src/object.h"
15#include "src/raw_dex_file.h"
16#include "src/scoped_ptr.h"
17#include "src/thread.h"
18#include "src/utils.h"
19
20namespace art {
21
Carl Shapiro61e019d2011-07-14 16:53:09 -070022ClassLinker* ClassLinker::Create() {
23 scoped_ptr<ClassLinker> class_linker(new ClassLinker);
24 class_linker->Init();
25 // TODO: check for failure during initialization
26 return class_linker.release();
27}
28
Carl Shapiro565f5072011-07-10 13:39:43 -070029void ClassLinker::Init() {
Brian Carlstroma0808032011-07-18 00:39:23 -070030 // Allocate and partially initialize the Class, Object, Field, Method classes.
Brian Carlstrom934486c2011-07-12 23:42:50 -070031 // Initialization will be completed when the definitions are loaded.
Brian Carlstroma0808032011-07-18 00:39:23 -070032 java_lang_Class_ = reinterpret_cast<Class*>(Heap::AllocRaw(sizeof(Class), NULL));
Brian Carlstroma331b3c2011-07-18 17:47:56 -070033 CHECK(java_lang_Class_ != NULL);
Carl Shapiro565f5072011-07-10 13:39:43 -070034 java_lang_Class_->descriptor_ = "Ljava/lang/Class;";
Brian Carlstroma0808032011-07-18 00:39:23 -070035 java_lang_Class_->object_size_ = sizeof(Class);
36 java_lang_Class_->klass_ = java_lang_Class_;
37
38 java_lang_Object_ = AllocClass(NULL);
Brian Carlstroma331b3c2011-07-18 17:47:56 -070039 CHECK(java_lang_Object_ != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -070040 java_lang_Object_->descriptor_ = "Ljava/lang/Object;";
41
42 java_lang_Class_->super_class_ = java_lang_Object_;
43
44 java_lang_ref_Field_ = AllocClass(NULL);
Brian Carlstroma331b3c2011-07-18 17:47:56 -070045 CHECK(java_lang_ref_Field_ != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -070046 java_lang_ref_Field_->descriptor_ = "Ljava/lang/ref/Field;";
47
48 java_lang_ref_Method_ = AllocClass(NULL);
Brian Carlstroma331b3c2011-07-18 17:47:56 -070049 CHECK(java_lang_ref_Method_ != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -070050 java_lang_ref_Method_->descriptor_ = "Ljava/lang/Method;";
Carl Shapiro565f5072011-07-10 13:39:43 -070051
Brian Carlstroma331b3c2011-07-18 17:47:56 -070052 java_lang_Cloneable_ = AllocClass(NULL);
53 CHECK(java_lang_Cloneable_ != NULL);
54 java_lang_Cloneable_->descriptor_ = "Ljava/lang/Cloneable;";
Brian Carlstroma0808032011-07-18 00:39:23 -070055
Brian Carlstroma331b3c2011-07-18 17:47:56 -070056 java_io_Serializable_ = AllocClass(NULL);
57 CHECK(java_io_Serializable_ != NULL);
58 java_io_Serializable_->descriptor_ = "Ljava/io/Serializable;";
59
60 java_lang_String_ = AllocClass(NULL);
61 CHECK(java_lang_String_ != NULL);
62 java_lang_String_->descriptor_ = "Ljava/lang/String;";
63
64 // Allocate and initialize the primitive type classes.
65 primitive_byte_ = CreatePrimitiveClass("B");
66 primitive_char_ = CreatePrimitiveClass("C");
67 primitive_double_ = CreatePrimitiveClass("D");
68 primitive_float_ = CreatePrimitiveClass("F");
69 primitive_int_ = CreatePrimitiveClass("I");
70 primitive_long_ = CreatePrimitiveClass("J");
71 primitive_short_ = CreatePrimitiveClass("S");
72 primitive_boolean_ = CreatePrimitiveClass("Z");
73 primitive_void_ = CreatePrimitiveClass("V");
74
75 char_array_class_ = FindSystemClass("[C");
76 CHECK(char_array_class_ != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -070077}
78
79Class* ClassLinker::AllocClass(DexFile* dex_file) {
80 Class* klass = reinterpret_cast<Class*>(Heap::AllocObject(java_lang_Class_));
81 klass->dex_file_ = dex_file;
82 return klass;
83}
84
85StaticField* ClassLinker::AllocStaticField() {
86 return reinterpret_cast<StaticField*>(Heap::AllocRaw(sizeof(StaticField), java_lang_ref_Field_));
87}
88
89InstanceField* ClassLinker::AllocInstanceField() {
90 return reinterpret_cast<InstanceField*>(Heap::AllocRaw(sizeof(InstanceField), java_lang_ref_Field_));
91}
92
93Method* ClassLinker::AllocMethod() {
94 return reinterpret_cast<Method*>(Heap::AllocRaw(sizeof(Method), java_lang_ref_Method_));
Carl Shapiro565f5072011-07-10 13:39:43 -070095}
96
Brian Carlstrom6cc18452011-07-18 15:10:33 -070097Class* ClassLinker::FindClass(const StringPiece& descriptor,
98 Object* class_loader) {
Carl Shapirob5573532011-07-12 18:22:59 -070099 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700100 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700101 CHECK(!self->IsExceptionPending());
102 // Find the class in the loaded classes table.
103 Class* klass = LookupClass(descriptor, class_loader);
104 if (klass == NULL) {
105 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700106 if (descriptor[0] == '[') {
107 return CreateArrayClass(descriptor, class_loader);
108 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700109 ClassPathEntry pair = FindInClassPath(descriptor);
110 if (pair.first == NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700111 LG << "Class " << descriptor << " not found"; // TODO: NoClassDefFoundError
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700112 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700113 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700114 DexFile* dex_file = pair.first;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700115 const RawDexFile::ClassDef* class_def = pair.second;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700116 // Load the class from the dex file.
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700117 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700118 klass = java_lang_Object_;
119 klass->dex_file_ = dex_file;
Brian Carlstroma0808032011-07-18 00:39:23 -0700120 klass->object_size_ = sizeof(Object);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700121 char_array_class_->super_class_idx_ = class_def->class_idx_;
122 } else if (descriptor == "Ljava/lang/Class;") {
Carl Shapiro565f5072011-07-10 13:39:43 -0700123 klass = java_lang_Class_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700124 klass->dex_file_ = dex_file;
Brian Carlstroma0808032011-07-18 00:39:23 -0700125 klass->object_size_ = sizeof(Class);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700126 } else if (descriptor == "Ljava/lang/ref/Field;") {
Brian Carlstroma0808032011-07-18 00:39:23 -0700127 klass = java_lang_ref_Field_;
128 klass->dex_file_ = dex_file;
129 klass->object_size_ = sizeof(Field);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700130 } else if (descriptor == "Ljava/lang/ref/Method;") {
Brian Carlstroma0808032011-07-18 00:39:23 -0700131 klass = java_lang_ref_Method_;
132 klass->dex_file_ = dex_file;
133 klass->object_size_ = sizeof(Method);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700134 } else if (descriptor == "Ljava/lang/Cloneable;") {
135 klass = java_lang_Cloneable_;
136 klass->dex_file_ = dex_file;
137 } else if (descriptor == "Ljava/io/Serializable;") {
138 klass = java_io_Serializable_;
139 klass->dex_file_ = dex_file;
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700140 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstroma0808032011-07-18 00:39:23 -0700141 klass = java_lang_String_;
142 klass->dex_file_ = dex_file;
143 klass->object_size_ = sizeof(String);
Carl Shapiro565f5072011-07-10 13:39:43 -0700144 } else {
Brian Carlstroma0808032011-07-18 00:39:23 -0700145 klass = AllocClass(dex_file);
Carl Shapiro565f5072011-07-10 13:39:43 -0700146 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700147 LoadClass(*class_def, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700148 // Check for a pending exception during load
149 if (self->IsExceptionPending()) {
150 // TODO: free native allocations in klass
151 return NULL;
152 }
153 {
154 ObjectLock lock(klass);
Carl Shapirob5573532011-07-12 18:22:59 -0700155 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700156 // Add the newly loaded class to the loaded classes table.
157 bool success = InsertClass(klass);
158 if (!success) {
159 // We may fail to insert if we raced with another thread.
160 klass->clinit_thread_id_ = 0;
161 // TODO: free native allocations in klass
162 klass = LookupClass(descriptor, class_loader);
163 CHECK(klass != NULL);
164 } else {
165 // Link the class.
166 if (!LinkClass(klass)) {
167 // Linking failed.
168 // TODO: CHECK(self->IsExceptionPending());
169 lock.NotifyAll();
170 return NULL;
171 }
172 }
173 }
174 }
175 // Link the class if it has not already been linked.
176 if (!klass->IsLinked() && !klass->IsErroneous()) {
177 ObjectLock lock(klass);
178 // Check for circular dependencies between classes.
Carl Shapirob5573532011-07-12 18:22:59 -0700179 if (!klass->IsLinked() && klass->clinit_thread_id_ == self->GetId()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700180 LG << "Recursive link"; // TODO: ClassCircularityError
181 return NULL;
182 }
183 // Wait for the pending initialization to complete.
184 while (!klass->IsLinked() && !klass->IsErroneous()) {
185 lock.Wait();
186 }
187 }
188 if (klass->IsErroneous()) {
189 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
190 return NULL;
191 }
192 // Return the loaded class. No exceptions should be pending.
193 CHECK(!self->IsExceptionPending());
194 return klass;
195}
196
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700197void ClassLinker::LoadClass(const RawDexFile::ClassDef& class_def, Class* klass) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700198 CHECK(klass != NULL);
199 CHECK(klass->dex_file_ != NULL);
200 const RawDexFile* raw = klass->GetDexFile()->GetRaw();
201 const byte* class_data = raw->GetClassData(class_def);
202 RawDexFile::ClassDataHeader header = raw->ReadClassDataHeader(&class_data);
203
204 const char* descriptor = raw->GetClassDescriptor(class_def);
205 CHECK(descriptor != NULL);
206
207 klass->klass_ = java_lang_Class_;
208 klass->descriptor_.set(descriptor);
209 klass->descriptor_alloc_ = NULL;
210 klass->access_flags_ = class_def.access_flags_;
211 klass->class_loader_ = NULL; // TODO
212 klass->primitive_type_ = Class::kPrimNot;
213 klass->status_ = Class::kStatusIdx;
214
215 klass->super_class_ = NULL;
216 klass->super_class_idx_ = class_def.superclass_idx_;
217
218 klass->num_sfields_ = header.static_fields_size_;
219 klass->num_ifields_ = header.instance_fields_size_;
220 klass->num_direct_methods_ = header.direct_methods_size_;
221 klass->num_virtual_methods_ = header.virtual_methods_size_;
222
223 klass->source_file_ = raw->dexGetSourceFile(class_def);
224
225 // Load class interfaces.
226 LoadInterfaces(class_def, klass);
227
228 // Load static fields.
229 if (klass->num_sfields_ != 0) {
230 // TODO: allocate on the object heap.
Brian Carlstroma7f4f482011-07-17 17:01:34 -0700231 klass->sfields_ = new StaticField*[klass->NumStaticFields()]();
Brian Carlstrom934486c2011-07-12 23:42:50 -0700232 uint32_t last_idx = 0;
233 for (size_t i = 0; i < klass->num_sfields_; ++i) {
234 RawDexFile::Field raw_field;
235 raw->dexReadClassDataField(&class_data, &raw_field, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700236 StaticField* sfield = AllocStaticField();
Brian Carlstroma7f4f482011-07-17 17:01:34 -0700237 klass->sfields_[i] = sfield;
238 LoadField(klass, raw_field, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700239 }
240 }
241
242 // Load instance fields.
243 if (klass->NumInstanceFields() != 0) {
244 // TODO: allocate on the object heap.
Brian Carlstroma7f4f482011-07-17 17:01:34 -0700245 klass->ifields_ = new InstanceField*[klass->NumInstanceFields()]();
Brian Carlstrom934486c2011-07-12 23:42:50 -0700246 uint32_t last_idx = 0;
247 for (size_t i = 0; i < klass->NumInstanceFields(); ++i) {
248 RawDexFile::Field raw_field;
249 raw->dexReadClassDataField(&class_data, &raw_field, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700250 InstanceField* ifield = AllocInstanceField();
Brian Carlstroma7f4f482011-07-17 17:01:34 -0700251 klass->ifields_[i] = ifield;
252 LoadField(klass, raw_field, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700253 }
254 }
255
256 // Load direct methods.
257 if (klass->NumDirectMethods() != 0) {
258 // TODO: append direct methods to class object
Brian Carlstroma7f4f482011-07-17 17:01:34 -0700259 klass->direct_methods_ = new Method*[klass->NumDirectMethods()]();
Brian Carlstrom934486c2011-07-12 23:42:50 -0700260 uint32_t last_idx = 0;
261 for (size_t i = 0; i < klass->NumDirectMethods(); ++i) {
262 RawDexFile::Method raw_method;
263 raw->dexReadClassDataMethod(&class_data, &raw_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700264 Method* meth = AllocMethod();
Brian Carlstroma7f4f482011-07-17 17:01:34 -0700265 klass->direct_methods_[i] = meth;
266 LoadMethod(klass, raw_method, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700267 // TODO: register maps
268 }
269 }
270
271 // Load virtual methods.
272 if (klass->NumVirtualMethods() != 0) {
273 // TODO: append virtual methods to class object
Brian Carlstroma7f4f482011-07-17 17:01:34 -0700274 klass->virtual_methods_ = new Method*[klass->NumVirtualMethods()]();
Brian Carlstrom934486c2011-07-12 23:42:50 -0700275 uint32_t last_idx = 0;
276 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
277 RawDexFile::Method raw_method;
278 raw->dexReadClassDataMethod(&class_data, &raw_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700279 Method* meth = AllocMethod();
Brian Carlstroma7f4f482011-07-17 17:01:34 -0700280 klass->virtual_methods_[i] = meth;
281 LoadMethod(klass, raw_method, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700282 // TODO: register maps
283 }
284 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700285}
286
287void ClassLinker::LoadInterfaces(const RawDexFile::ClassDef& class_def,
288 Class* klass) {
289 const RawDexFile* raw = klass->GetDexFile()->GetRaw();
290 const RawDexFile::TypeList* list = raw->GetInterfacesList(class_def);
291 if (list != NULL) {
292 klass->interface_count_ = list->Size();
293 // TODO: allocate the interfaces array on the object heap.
294 klass->interfaces_ = new Class*[list->Size()]();
295 for (size_t i = 0; i < list->Size(); ++i) {
296 const RawDexFile::TypeItem& type_item = list->GetTypeItem(i);
297 klass->interfaces_[i] = reinterpret_cast<Class*>(type_item.type_idx_);
298 }
299 }
300}
301
302void ClassLinker::LoadField(Class* klass, const RawDexFile::Field& src,
303 Field* dst) {
304 const RawDexFile* raw = klass->GetDexFile()->GetRaw();
305 const RawDexFile::FieldId& field_id = raw->GetFieldId(src.field_idx_);
306 dst->klass_ = klass;
307 dst->name_ = raw->dexStringById(field_id.name_idx_);
308 dst->signature_ = raw->dexStringByTypeIdx(field_id.type_idx_);
309 dst->access_flags_ = src.access_flags_;
310}
311
312void ClassLinker::LoadMethod(Class* klass, const RawDexFile::Method& src,
313 Method* dst) {
314 const RawDexFile* raw = klass->GetDexFile()->GetRaw();
315 const RawDexFile::MethodId& method_id = raw->GetMethodId(src.method_idx_);
316 dst->klass_ = klass;
317 dst->name_.set(raw->dexStringById(method_id.name_idx_));
318 dst->proto_idx_ = method_id.proto_idx_;
319 dst->shorty_.set(raw->GetShorty(method_id.proto_idx_));
320 dst->access_flags_ = src.access_flags_;
321
322 // TODO: check for finalize method
323
324 const RawDexFile::CodeItem* code_item = raw->GetCodeItem(src);
325 if (code_item != NULL) {
326 dst->num_registers_ = code_item->registers_size_;
327 dst->num_ins_ = code_item->ins_size_;
328 dst->num_outs_ = code_item->outs_size_;
329 dst->insns_ = code_item->insns_;
330 } else {
331 uint16_t num_args = dst->NumArgRegisters();
332 if (!dst->IsStatic()) {
333 ++num_args;
334 }
335 dst->num_registers_ = dst->num_ins_ + num_args;
336 // TODO: native methods
337 }
338}
339
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700340ClassLinker::ClassPathEntry ClassLinker::FindInClassPath(const StringPiece& descriptor) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700341 for (size_t i = 0; i != class_path_.size(); ++i) {
342 DexFile* dex_file = class_path_[i];
Brian Carlstroma0808032011-07-18 00:39:23 -0700343 const RawDexFile::ClassDef* class_def = dex_file->GetRaw()->FindClassDef(descriptor);
344 if (class_def != NULL) {
345 return ClassPathEntry(dex_file, class_def);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700346 }
347 }
Brian Carlstroma0808032011-07-18 00:39:23 -0700348 return ClassPathEntry(NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700349}
350
351void ClassLinker::AppendToClassPath(DexFile* dex_file) {
352 class_path_.push_back(dex_file);
353}
354
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700355Class* ClassLinker::CreatePrimitiveClass(const StringPiece& descriptor) {
Brian Carlstroma0808032011-07-18 00:39:23 -0700356 Class* klass = AllocClass(NULL);
Carl Shapiro565f5072011-07-10 13:39:43 -0700357 CHECK(klass != NULL);
Brian Carlstroma0808032011-07-18 00:39:23 -0700358 klass->super_class_ = NULL;
Carl Shapiro565f5072011-07-10 13:39:43 -0700359 klass->access_flags_ = kAccPublic | kAccFinal | kAccAbstract;
360 klass->descriptor_ = descriptor;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700361 klass->descriptor_alloc_ = NULL;
Carl Shapiro565f5072011-07-10 13:39:43 -0700362 klass->status_ = Class::kStatusInitialized;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700363 bool success = InsertClass(klass);
364 CHECK(success);
Carl Shapiro565f5072011-07-10 13:39:43 -0700365 return klass;
366}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700367
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700368/*
369 * Create an array class (i.e. the class object for the array, not the
370 * array itself). "descriptor" looks like "[C" or "[[[[B" or
371 * "[Ljava/lang/String;".
372 *
373 * If "descriptor" refers to an array of primitives, look up the
374 * primitive type's internally-generated class object.
375 *
376 * "loader" is the class loader of the class that's referring to us. It's
377 * used to ensure that we're looking for the element type in the right
378 * context. It does NOT become the class loader for the array class; that
379 * always comes from the base element class.
380 *
381 * Returns NULL with an exception raised on failure.
382 */
383Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor, Object* class_loader)
384{
385 CHECK(descriptor[0] == '[');
386 DCHECK(java_lang_Class_ != NULL);
387 DCHECK(java_lang_Object_ != NULL);
388
389 /*
390 * Identify the underlying element class and the array dimension depth.
391 */
392 Class* component_type_ = NULL;
393 int array_rank;
394 if (descriptor[1] == '[') {
395 /* array of arrays; keep descriptor and grab stuff from parent */
396 Class* outer = FindClass(descriptor.substr(1), class_loader);
397 if (outer != NULL) {
398 /* want the base class, not "outer", in our component_type_ */
399 component_type_ = outer->component_type_;
400 array_rank = outer->array_rank_ + 1;
401 } else {
402 DCHECK(component_type_ == NULL); /* make sure we fail */
403 }
404 } else {
405 array_rank = 1;
406 if (descriptor[1] == 'L') {
407 /* array of objects; strip off "[" and look up descriptor. */
408 const StringPiece subDescriptor = descriptor.substr(1);
409 LG << "searching for element class '" << subDescriptor << "'";
410 component_type_ = FindClass(subDescriptor, class_loader); // TODO FindClassNoInit
411 } else {
412 /* array of a primitive type */
413 component_type_ = FindPrimitiveClass(descriptor[1]);
414 }
415 }
416
417 if (component_type_ == NULL) {
418 /* failed */
419 DCHECK(Thread::Current()->IsExceptionPending());
420 return NULL;
421 }
422
423 /*
424 * See if the component type is already loaded. Array classes are
425 * always associated with the class loader of their underlying
426 * element type -- an array of Strings goes with the loader for
427 * java/lang/String -- so we need to look for it there. (The
428 * caller should have checked for the existence of the class
429 * before calling here, but they did so with *their* class loader,
430 * not the component type's loader.)
431 *
432 * If we find it, the caller adds "loader" to the class' initiating
433 * loader list, which should prevent us from going through this again.
434 *
435 * This call is unnecessary if "loader" and "component_type_->class_loader_"
436 * are the same, because our caller (FindClass) just did the
437 * lookup. (Even if we get this wrong we still have correct behavior,
438 * because we effectively do this lookup again when we add the new
439 * class to the hash table --- necessary because of possible races with
440 * other threads.)
441 */
442 if (class_loader != component_type_->class_loader_) {
443 Class* new_class = LookupClass(descriptor, component_type_->class_loader_);
444 if (new_class != NULL) {
445 return new_class;
446 }
447 }
448
449 /*
450 * Fill out the fields in the Class.
451 *
452 * It is possible to execute some methods against arrays, because
453 * all arrays are subclasses of java_lang_Object_, so we need to set
454 * up a vtable. We can just point at the one in java_lang_Object_.
455 *
456 * Array classes are simple enough that we don't need to do a full
457 * link step.
458 */
459 Class* new_class = AllocClass(NULL);
460 if (new_class == NULL) {
461 return NULL;
462 }
463 new_class->descriptor_alloc_ = new std::string(descriptor.data(),
464 descriptor.size());
465 new_class->descriptor_.set(new_class->descriptor_alloc_->data(),
466 new_class->descriptor_alloc_->size());
467 new_class->super_class_ = java_lang_Object_;
468 new_class->vtable_count_ = java_lang_Object_->vtable_count_;
469 new_class->vtable_ = java_lang_Object_->vtable_;
470 new_class->primitive_type_ = Class::kPrimNot;
471 new_class->component_type_ = component_type_;
472 new_class->class_loader_ = component_type_->class_loader_;
473 new_class->array_rank_ = array_rank;
474 new_class->status_ = Class::kStatusInitialized;
475
476 /* don't need to set new_class->object_size_ */
477
478 /*
479 * All arrays have java/lang/Cloneable and java/io/Serializable as
480 * interfaces. We need to set that up here, so that stuff like
481 * "instanceof" works right.
482 *
483 * Note: The GC could run during the call to FindSystemClassNoInit(),
484 * so we need to make sure the class object is GC-valid while we're in
485 * there. Do this by clearing the interface list so the GC will just
486 * think that the entries are null.
487 *
488 * TODO?
489 * We may want to create a single, global copy of "interfaces" and
490 * "iftable" somewhere near the start and just point to those (and
491 * remember not to free them for arrays).
492 */
493 new_class->interface_count_ = 2;
494 new_class->interfaces_ = new Class*[2];
495 memset(new_class->interfaces_, 0, sizeof(Class*) * 2);
496 new_class->interfaces_[0] = java_lang_Cloneable_;
497 new_class->interfaces_[1] = java_io_Serializable_;
498 /*
499 * We assume that Cloneable/Serializable don't have superinterfaces --
500 * normally we'd have to crawl up and explicitly list all of the
501 * supers as well. These interfaces don't have any methods, so we
502 * don't have to worry about the ifviPool either.
503 */
504 new_class->iftable_count_ = 2;
505 new_class->iftable_ = new InterfaceEntry[2];
506 memset(new_class->iftable_, 0, sizeof(InterfaceEntry) * 2);
507 new_class->iftable_[0].SetClass(new_class->interfaces_[0]);
508 new_class->iftable_[1].SetClass(new_class->interfaces_[1]);
509
510 /*
511 * Inherit access flags from the component type. Arrays can't be
512 * used as a superclass or interface, so we want to add "final"
513 * and remove "interface".
514 *
515 * Don't inherit any non-standard flags (e.g., kAccFinal)
516 * from component_type_. We assume that the array class does not
517 * override finalize().
518 */
519 new_class->access_flags_ = ((new_class->component_type_->access_flags_ &
520 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask;
521
522 if (InsertClass(new_class)) {
523 return new_class;
524 }
525 /*
526 * Another thread must have loaded the class after we
527 * started but before we finished. Abandon what we've
528 * done.
529 *
530 * (Yes, this happens.)
531 */
532
533 /* Grab the winning class.
534 */
535 Class* other_class = LookupClass(descriptor, component_type_->class_loader_);
536 DCHECK(other_class != NULL);
537 return other_class;
538}
539
540Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -0700541 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700542 case 'B':
Carl Shapiro565f5072011-07-10 13:39:43 -0700543 CHECK(primitive_byte_ != NULL);
544 return primitive_byte_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700545 case 'C':
Carl Shapiro565f5072011-07-10 13:39:43 -0700546 CHECK(primitive_char_ != NULL);
547 return primitive_char_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700548 case 'D':
Carl Shapiro565f5072011-07-10 13:39:43 -0700549 CHECK(primitive_double_ != NULL);
550 return primitive_double_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700551 case 'F':
Carl Shapiro565f5072011-07-10 13:39:43 -0700552 CHECK(primitive_float_ != NULL);
553 return primitive_float_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700554 case 'I':
Carl Shapiro565f5072011-07-10 13:39:43 -0700555 CHECK(primitive_int_ != NULL);
556 return primitive_int_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700557 case 'J':
Carl Shapiro565f5072011-07-10 13:39:43 -0700558 CHECK(primitive_long_ != NULL);
559 return primitive_long_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700560 case 'S':
Carl Shapiro565f5072011-07-10 13:39:43 -0700561 CHECK(primitive_short_ != NULL);
562 return primitive_short_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700563 case 'Z':
Carl Shapiro565f5072011-07-10 13:39:43 -0700564 CHECK(primitive_boolean_ != NULL);
565 return primitive_boolean_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700566 case 'V':
Carl Shapiro565f5072011-07-10 13:39:43 -0700567 CHECK(primitive_void_ != NULL);
568 return primitive_void_;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700569 case 'L':
570 case '[':
571 LOG(ERROR) << "Not a primitive type " << static_cast<int>(type);
Carl Shapiro565f5072011-07-10 13:39:43 -0700572 default:
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700573 LOG(ERROR) << "Unknown primitive type " << static_cast<int>(type);
Carl Shapiro565f5072011-07-10 13:39:43 -0700574 };
575 return NULL; // Not reachable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700576}
577
578bool ClassLinker::InsertClass(Class* klass) {
579 // TODO: acquire classes_lock_
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700580 const StringPiece& key = klass->GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700581 bool success = classes_.insert(std::make_pair(key, klass)).second;
582 // TODO: release classes_lock_
583 return success;
584}
585
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700586Class* ClassLinker::LookupClass(const StringPiece& descriptor, Object* class_loader) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700587 // TODO: acquire classes_lock_
588 Table::iterator it = classes_.find(descriptor);
589 // TODO: release classes_lock_
590 if (it == classes_.end()) {
591 return NULL;
592 } else {
593 return (*it).second;
594 }
595}
596
597bool ClassLinker::InitializeClass(Class* klass) {
598 CHECK(klass->GetStatus() == Class::kStatusResolved ||
599 klass->GetStatus() == Class::kStatusError);
600
Carl Shapirob5573532011-07-12 18:22:59 -0700601 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700602
603 {
604 ObjectLock lock(klass);
605
606 if (klass->GetStatus() < Class::kStatusVerified) {
607 if (klass->IsErroneous()) {
608 LG << "re-initializing failed class"; // TODO: throw
609 return false;
610 }
611
612 CHECK(klass->GetStatus() == Class::kStatusResolved);
613
614 klass->status_ = Class::kStatusVerifying;
615 if (!DexVerify::VerifyClass(klass)) {
616 LG << "Verification failed"; // TODO: ThrowVerifyError
617 Object* exception = self->GetException();
618 klass->SetObjectAt(OFFSETOF_MEMBER(Class, verify_error_class_),
619 exception->GetClass());
620 klass->SetStatus(Class::kStatusError);
621 return false;
622 }
623
624 klass->SetStatus(Class::kStatusVerified);
625 }
626
627 if (klass->status_ == Class::kStatusInitialized) {
628 return true;
629 }
630
631 while (klass->status_ == Class::kStatusInitializing) {
632 // we caught somebody else in the act; was it us?
Carl Shapirob5573532011-07-12 18:22:59 -0700633 if (klass->clinit_thread_id_ == self->GetId()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700634 LG << "recursive <clinit>";
635 return true;
636 }
637
638 CHECK(!self->IsExceptionPending());
639
640 lock.Wait(); // TODO: check for interruption
641
642 // When we wake up, repeat the test for init-in-progress. If
643 // there's an exception pending (only possible if
644 // "interruptShouldThrow" was set), bail out.
645 if (self->IsExceptionPending()) {
646 CHECK(false);
647 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
648 klass->SetStatus(Class::kStatusError);
649 return false;
650 }
651 if (klass->GetStatus() == Class::kStatusInitializing) {
652 continue;
653 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700654 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700655 klass->GetStatus() == Class::kStatusError);
656 if (klass->IsErroneous()) {
657 /*
658 * The caller wants an exception, but it was thrown in a
659 * different thread. Synthesize one here.
660 */
661 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
662 return false;
663 }
664 return true; // otherwise, initialized
665 }
666
667 // see if we failed previously
668 if (klass->IsErroneous()) {
669 // might be wise to unlock before throwing; depends on which class
670 // it is that we have locked
671
672 // TODO: throwEarlierClassFailure(klass);
673 return false;
674 }
675
676 if (!ValidateSuperClassDescriptors(klass)) {
677 klass->SetStatus(Class::kStatusError);
678 return false;
679 }
680
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700681 DCHECK(klass->status_ < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700682
Carl Shapirob5573532011-07-12 18:22:59 -0700683 klass->clinit_thread_id_ = self->GetId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700684 klass->status_ = Class::kStatusInitializing;
685 }
686
687 if (!InitializeSuperClass(klass)) {
688 return false;
689 }
690
691 InitializeStaticFields(klass);
692
693 Method* clinit = klass->FindDirectMethodLocally("<clinit>", "()V");
694 if (clinit != NULL) {
695 } else {
696 // JValue unused;
697 // TODO: dvmCallMethod(self, method, NULL, &unused);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -0700698 //CHECK(!"unimplemented");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700699 }
700
701 {
702 ObjectLock lock(klass);
703
704 if (self->IsExceptionPending()) {
705 klass->SetStatus(Class::kStatusError);
706 } else {
707 klass->SetStatus(Class::kStatusInitialized);
708 }
709 lock.NotifyAll();
710 }
711
712 return true;
713}
714
715bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
716 if (klass->IsInterface()) {
717 return true;
718 }
719 // begin with the methods local to the superclass
720 if (klass->HasSuperClass() &&
721 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
722 const Class* super = klass->GetSuperClass();
723 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
724 const Method* method = klass->GetVirtualMethod(i);
725 if (method != super->GetVirtualMethod(i) &&
726 !HasSameMethodDescriptorClasses(method, super, klass)) {
727 LG << "Classes resolve differently in superclass";
728 return false;
729 }
730 }
731 }
732 for (size_t i = 0; i < klass->iftable_count_; ++i) {
733 const InterfaceEntry* iftable = &klass->iftable_[i];
734 Class* interface = iftable->GetClass();
735 if (klass->GetClassLoader() != interface->GetClassLoader()) {
736 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
737 uint32_t vtable_index = iftable->method_index_array_[j];
738 const Method* method = klass->GetVirtualMethod(vtable_index);
739 if (!HasSameMethodDescriptorClasses(method, interface,
740 method->GetClass())) {
741 LG << "Classes resolve differently in interface"; // TODO: LinkageError
742 return false;
743 }
744 }
745 }
746 }
747 return true;
748}
749
750bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700751 const Class* klass1,
752 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700753 const RawDexFile* raw = method->GetClass()->GetDexFile()->GetRaw();
754 const RawDexFile::ProtoId& proto_id = raw->GetProtoId(method->proto_idx_);
755 RawDexFile::ParameterIterator *it;
756 for (it = raw->GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
757 const char* descriptor = it->GetDescriptor();
758 if (descriptor == NULL) {
759 break;
760 }
761 if (descriptor[0] == 'L' || descriptor[0] == '[') {
762 // Found a non-primitive type.
763 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
764 return false;
765 }
766 }
767 }
768 // Check the return type
769 const char* descriptor = raw->GetReturnTypeDescriptor(proto_id);
770 if (descriptor[0] == 'L' || descriptor[0] == '[') {
771 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
772 return false;
773 }
774 }
775 return true;
776}
777
778// Returns true if classes referenced by the descriptor are the
779// same classes in klass1 as they are in klass2.
780bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700781 const Class* klass1,
782 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700783 CHECK(descriptor != NULL);
784 CHECK(klass1 != NULL);
785 CHECK(klass2 != NULL);
786#if 0
787 Class* found1 = FindClassNoInit(descriptor, klass1->GetClassLoader());
788 // TODO: found1 == NULL
789 Class* found2 = FindClassNoInit(descriptor, klass2->GetClassLoader());
790 // TODO: found2 == NULL
791 // TODO: lookup found1 in initiating loader list
792 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -0700793 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700794 if (found1 == found2) {
795 return true;
796 } else {
797 return false;
798 }
799 }
800#endif
801 return true;
802}
803
804bool ClassLinker::InitializeSuperClass(Class* klass) {
805 CHECK(klass != NULL);
806 // TODO: assert klass lock is acquired
807 if (!klass->IsInterface() && klass->HasSuperClass()) {
808 Class* super_class = klass->GetSuperClass();
809 if (super_class->GetStatus() != Class::kStatusInitialized) {
810 CHECK(!super_class->IsInterface());
811 klass->MonitorExit();
812 bool super_initialized = InitializeClass(super_class);
813 klass->MonitorEnter();
814 // TODO: check for a pending exception
815 if (!super_initialized) {
816 klass->SetStatus(Class::kStatusError);
817 klass->NotifyAll();
818 return false;
819 }
820 }
821 }
822 return true;
823}
824
825void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -0700826 size_t num_static_fields = klass->NumStaticFields();
827 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700828 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -0700829 }
830 DexFile* dex_file = klass->GetDexFile();
831 if (dex_file == NULL) {
832 return;
833 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700834 const StringPiece& descriptor = klass->GetDescriptor();
Brian Carlstrom934486c2011-07-12 23:42:50 -0700835 const RawDexFile* raw = dex_file->GetRaw();
Carl Shapiro5fafe2b2011-07-09 15:34:41 -0700836 const RawDexFile::ClassDef* class_def = raw->FindClassDef(descriptor);
837 CHECK(class_def != NULL);
838 const byte* addr = raw->GetEncodedArray(*class_def);
839 size_t array_size = DecodeUnsignedLeb128(&addr);
840 for (size_t i = 0; i < array_size; ++i) {
841 StaticField* field = klass->GetStaticField(i);
842 JValue value;
843 RawDexFile::ValueType type = raw->ReadEncodedValue(&addr, &value);
844 switch (type) {
845 case RawDexFile::kByte:
846 field->SetByte(value.b);
847 break;
848 case RawDexFile::kShort:
849 field->SetShort(value.s);
850 break;
851 case RawDexFile::kChar:
852 field->SetChar(value.c);
853 break;
854 case RawDexFile::kInt:
855 field->SetInt(value.i);
856 break;
857 case RawDexFile::kLong:
858 field->SetLong(value.j);
859 break;
860 case RawDexFile::kFloat:
861 field->SetFloat(value.f);
862 break;
863 case RawDexFile::kDouble:
864 field->SetDouble(value.d);
865 break;
866 case RawDexFile::kString: {
867 uint32_t string_idx = value.i;
868 String* resolved = ResolveString(klass, string_idx);
869 field->SetObject(resolved);
870 break;
871 }
872 case RawDexFile::kBoolean:
873 field->SetBoolean(value.z);
874 break;
875 case RawDexFile::kNull:
876 field->SetObject(value.l);
877 break;
878 default:
Carl Shapiro606258b2011-07-09 16:09:09 -0700879 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -0700880 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700881 }
882}
883
884bool ClassLinker::LinkClass(Class* klass) {
885 CHECK(klass->status_ == Class::kStatusIdx ||
886 klass->status_ == Class::kStatusLoaded);
887 if (klass->status_ == Class::kStatusIdx) {
888 if (!LinkInterfaces(klass)) {
889 return false;
890 }
891 }
892 if (!LinkSuperClass(klass)) {
893 return false;
894 }
895 if (!LinkMethods(klass)) {
896 return false;
897 }
898 if (!LinkInstanceFields(klass)) {
899 return false;
900 }
901 CreateReferenceOffsets(klass);
902 CHECK_EQ(klass->status_, Class::kStatusLoaded);
903 klass->status_ = Class::kStatusResolved;
904 return true;
905}
906
907bool ClassLinker::LinkInterfaces(Class* klass) {
908 scoped_array<uint32_t> interfaces_idx;
909 // TODO: store interfaces_idx in the Class object
910 // TODO: move this outside of link interfaces
911 if (klass->interface_count_ > 0) {
Carl Shapiro565f5072011-07-10 13:39:43 -0700912 size_t length = klass->interface_count_ * sizeof(klass->interfaces_[0]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700913 interfaces_idx.reset(new uint32_t[klass->interface_count_]);
Carl Shapiro565f5072011-07-10 13:39:43 -0700914 memcpy(interfaces_idx.get(), klass->interfaces_, length);
915 memset(klass->interfaces_, 0xFF, length);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700916 }
917 // Mark the class as loaded.
918 klass->status_ = Class::kStatusLoaded;
919 if (klass->super_class_idx_ != RawDexFile::kDexNoIndex) {
920 Class* super_class = ResolveClass(klass, klass->super_class_idx_);
921 if (super_class == NULL) {
922 LG << "Failed to resolve superclass";
923 return false;
924 }
925 klass->super_class_ = super_class; // TODO: write barrier
926 }
927 if (klass->interface_count_ > 0) {
928 for (size_t i = 0; i < klass->interface_count_; ++i) {
929 uint32_t idx = interfaces_idx[i];
930 klass->interfaces_[i] = ResolveClass(klass, idx);
931 if (klass->interfaces_[i] == NULL) {
932 LG << "Failed to resolve interface";
933 return false;
934 }
935 // Verify
936 if (!klass->CanAccess(klass->interfaces_[i])) {
937 LG << "Inaccessible interface";
938 return false;
939 }
940 }
941 }
942 return true;
943}
944
945bool ClassLinker::LinkSuperClass(Class* klass) {
946 CHECK(!klass->IsPrimitive());
947 const Class* super = klass->GetSuperClass();
948 if (klass->GetDescriptor() == "Ljava/lang/Object;") {
949 if (super != NULL) {
950 LG << "Superclass must not be defined"; // TODO: ClassFormatError
951 return false;
952 }
953 // TODO: clear finalize attribute
954 return true;
955 }
956 if (super == NULL) {
957 LG << "No superclass defined"; // TODO: LinkageError
958 return false;
959 }
960 // Verify
961 if (super->IsFinal()) {
962 LG << "Superclass is declared final"; // TODO: IncompatibleClassChangeError
963 return false;
964 }
965 if (super->IsInterface()) {
966 LG << "Superclass is an interface"; // TODO: IncompatibleClassChangeError
967 return false;
968 }
969 if (!klass->CanAccess(super)) {
970 LG << "Superclass is inaccessible"; // TODO: IllegalAccessError
971 return false;
972 }
973 return true;
974}
975
976// Populate the class vtable and itable.
977bool ClassLinker::LinkMethods(Class* klass) {
978 if (klass->IsInterface()) {
979 // No vtable.
980 size_t count = klass->NumVirtualMethods();
981 if (!IsUint(16, count)) {
982 LG << "Too many methods on interface"; // TODO: VirtualMachineError
983 return false;
984 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700985 for (size_t i = 0; i < count; ++i) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700986 klass->GetVirtualMethod(i)->method_index_ = i;
987 }
988 } else {
989 // Link virtual method tables
990 LinkVirtualMethods(klass);
991
992 // Link interface method tables
993 LinkInterfaceMethods(klass);
994
995 // Insert stubs.
996 LinkAbstractMethods(klass);
997 }
998 return true;
999}
1000
1001bool ClassLinker::LinkVirtualMethods(Class* klass) {
1002 uint32_t max_count = klass->NumVirtualMethods();
1003 if (klass->GetSuperClass() != NULL) {
1004 max_count += klass->GetSuperClass()->NumVirtualMethods();
1005 } else {
1006 CHECK(klass->GetDescriptor() == "Ljava/lang/Object;");
1007 }
1008 // TODO: do not assign to the vtable field until it is fully constructed.
1009 // TODO: make this a vector<Method*> instead?
1010 klass->vtable_ = new Method*[max_count];
1011 if (klass->HasSuperClass()) {
1012 memcpy(klass->vtable_,
1013 klass->GetSuperClass()->vtable_,
1014 klass->GetSuperClass()->vtable_count_ * sizeof(Method*));
1015 size_t actual_count = klass->GetSuperClass()->vtable_count_;
1016 // See if any of our virtual methods override the superclass.
1017 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1018 Method* local_method = klass->GetVirtualMethod(i);
1019 size_t j = 0;
1020 for (; j < klass->GetSuperClass()->vtable_count_; ++j) {
1021 const Method* super_method = klass->vtable_[j];
1022 if (local_method->HasSameNameAndPrototype(super_method)) {
1023 // Verify
1024 if (super_method->IsFinal()) {
1025 LG << "Method overrides final method"; // TODO: VirtualMachineError
1026 return false;
1027 }
1028 klass->vtable_[j] = local_method;
1029 local_method->method_index_ = j;
1030 break;
1031 }
1032 }
1033 if (j == klass->GetSuperClass()->vtable_count_) {
1034 // Not overriding, append.
1035 klass->vtable_[actual_count] = local_method;
1036 local_method->method_index_ = actual_count;
1037 actual_count += 1;
1038 }
1039 }
1040 if (!IsUint(16, actual_count)) {
1041 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1042 return false;
1043 }
1044 CHECK_LE(actual_count, max_count);
1045 if (actual_count < max_count) {
1046 Method** new_vtable = new Method*[actual_count];
1047 memcpy(new_vtable, klass->vtable_, actual_count * sizeof(Method*));
Carl Shapiro565f5072011-07-10 13:39:43 -07001048 delete[] klass->vtable_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001049 klass->vtable_ = new_vtable;
1050 LG << "shrunk vtable: "
1051 << "was " << max_count << ", "
1052 << "now " << actual_count;
1053 }
1054 klass->vtable_count_ = actual_count;
1055 } else {
1056 CHECK(klass->GetDescriptor() == "Ljava/lang/Object;");
1057 if (!IsUint(16, klass->NumVirtualMethods())) {
1058 LG << "Too many methods"; // TODO: VirtualMachineError
1059 return false;
1060 }
1061 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1062 klass->vtable_[i] = klass->GetVirtualMethod(i);
1063 klass->GetVirtualMethod(i)->method_index_ = i & 0xFFFF;
1064 }
1065 klass->vtable_count_ = klass->NumVirtualMethods();
1066 }
1067 return true;
1068}
1069
1070bool ClassLinker::LinkInterfaceMethods(Class* klass) {
1071 int pool_offset = 0;
1072 int pool_size = 0;
1073 int miranda_count = 0;
1074 int miranda_alloc = 0;
1075 size_t super_ifcount;
1076 if (klass->HasSuperClass()) {
1077 super_ifcount = klass->GetSuperClass()->iftable_count_;
1078 } else {
1079 super_ifcount = 0;
1080 }
1081 size_t ifCount = super_ifcount;
1082 ifCount += klass->interface_count_;
1083 for (size_t i = 0; i < klass->interface_count_; i++) {
1084 ifCount += klass->interfaces_[i]->iftable_count_;
1085 }
1086 if (ifCount == 0) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001087 DCHECK(klass->iftable_count_ == 0);
1088 DCHECK(klass->iftable_ == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001089 return true;
1090 }
1091 klass->iftable_ = new InterfaceEntry[ifCount * sizeof(InterfaceEntry)];
1092 memset(klass->iftable_, 0x00, sizeof(InterfaceEntry) * ifCount);
1093 if (super_ifcount != 0) {
1094 memcpy(klass->iftable_, klass->GetSuperClass()->iftable_,
1095 sizeof(InterfaceEntry) * super_ifcount);
1096 }
1097 // Flatten the interface inheritance hierarchy.
1098 size_t idx = super_ifcount;
1099 for (size_t i = 0; i < klass->interface_count_; i++) {
1100 Class* interf = klass->interfaces_[i];
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001101 DCHECK(interf != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001102 if (!interf->IsInterface()) {
1103 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1104 return false;
1105 }
1106 klass->iftable_[idx++].SetClass(interf);
1107 for (size_t j = 0; j < interf->iftable_count_; j++) {
1108 klass->iftable_[idx++].SetClass(interf->iftable_[j].GetClass());
1109 }
1110 }
1111 CHECK_EQ(idx, ifCount);
1112 klass->iftable_count_ = ifCount;
1113 if (klass->IsInterface() || super_ifcount == ifCount) {
1114 return true;
1115 }
1116 for (size_t i = super_ifcount; i < ifCount; i++) {
1117 pool_size += klass->iftable_[i].GetClass()->NumVirtualMethods();
1118 }
1119 if (pool_size == 0) {
1120 return true;
1121 }
1122 klass->ifvi_pool_count_ = pool_size;
1123 klass->ifvi_pool_ = new uint32_t[pool_size];
1124 std::vector<Method*> miranda_list;
1125 for (size_t i = super_ifcount; i < ifCount; ++i) {
1126 klass->iftable_[i].method_index_array_ = klass->ifvi_pool_ + pool_offset;
1127 Class* interface = klass->iftable_[i].GetClass();
1128 pool_offset += interface->NumVirtualMethods(); // end here
1129 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1130 Method* interface_method = interface->GetVirtualMethod(j);
1131 int k; // must be signed
1132 for (k = klass->vtable_count_ - 1; k >= 0; --k) {
1133 if (interface_method->HasSameNameAndPrototype(klass->vtable_[k])) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001134 if (!klass->vtable_[k]->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001135 LG << "Implementation not public";
1136 return false;
1137 }
1138 klass->iftable_[i].method_index_array_[j] = k;
1139 break;
1140 }
1141 }
1142 if (k < 0) {
1143 if (miranda_count == miranda_alloc) {
1144 miranda_alloc += 8;
1145 if (miranda_list.empty()) {
1146 miranda_list.resize(miranda_alloc);
1147 } else {
1148 miranda_list.resize(miranda_alloc);
1149 }
1150 }
1151 int mir;
1152 for (mir = 0; mir < miranda_count; mir++) {
1153 if (miranda_list[mir]->HasSameNameAndPrototype(interface_method)) {
1154 break;
1155 }
1156 }
1157 // point the interface table at a phantom slot index
1158 klass->iftable_[i].method_index_array_[j] = klass->vtable_count_ + mir;
1159 if (mir == miranda_count) {
1160 miranda_list[miranda_count++] = interface_method;
1161 }
1162 }
1163 }
1164 }
1165 if (miranda_count != 0) {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001166 int oldMethodCount = klass->NumVirtualMethods();
1167 int newMethodCount = oldMethodCount + miranda_count;
1168 Method** newVirtualMethods = new Method*[newMethodCount];
1169 if (klass->virtual_methods_ != NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001170 memcpy(newVirtualMethods,
1171 klass->virtual_methods_,
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001172 klass->NumVirtualMethods() * sizeof(Method*));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001173 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001174 klass->virtual_methods_ = newVirtualMethods;
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001175 klass->num_virtual_methods_ = newMethodCount;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001176
1177 CHECK(klass->vtable_ != NULL);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001178 int oldVtableCount = klass->vtable_count_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001179 klass->vtable_count_ += miranda_count;
1180
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001181 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001182 Method* meth = AllocMethod();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001183 memcpy(meth, miranda_list[i], sizeof(Method));
1184 meth->klass_ = klass;
1185 meth->access_flags_ |= kAccMiranda;
1186 meth->method_index_ = 0xFFFF & (oldVtableCount + i);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001187 klass->virtual_methods_[oldMethodCount+i] = meth;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001188 klass->vtable_[oldVtableCount + i] = meth;
1189 }
1190 }
1191 return true;
1192}
1193
1194void ClassLinker::LinkAbstractMethods(Class* klass) {
1195 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
1196 Method* method = klass->GetVirtualMethod(i);
1197 if (method->IsAbstract()) {
1198 method->insns_ = reinterpret_cast<uint16_t*>(0xFFFFFFFF); // TODO: AbstractMethodError
1199 }
1200 }
1201}
1202
1203bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001204 int field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001205 if (klass->GetSuperClass() != NULL) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001206 field_offset = klass->GetSuperClass()->object_size_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001207 } else {
Brian Carlstroma0808032011-07-18 00:39:23 -07001208 field_offset = OFFSETOF_MEMBER(DataObject, fields_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001209 }
1210 // Move references to the front.
1211 klass->num_reference_ifields_ = 0;
1212 size_t i = 0;
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001213 for ( ; i < klass->NumInstanceFields(); i++) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001214 InstanceField* pField = klass->GetInstanceField(i);
1215 char c = pField->GetType();
1216
1217 if (c != '[' && c != 'L') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001218 for (size_t j = klass->NumInstanceFields() - 1; j > i; j--) {
1219 InstanceField* refField = klass->GetInstanceField(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001220 char rc = refField->GetType();
1221 if (rc == '[' || rc == 'L') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001222 klass->SetInstanceField(i, refField);
1223 klass->SetInstanceField(j, pField);
1224 pField = refField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001225 c = rc;
1226 klass->num_reference_ifields_++;
1227 break;
1228 }
1229 }
1230 } else {
1231 klass->num_reference_ifields_++;
1232 }
1233 if (c != '[' && c != 'L') {
1234 break;
1235 }
Brian Carlstroma0808032011-07-18 00:39:23 -07001236 pField->SetOffset(field_offset);
1237 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001238 }
1239
1240 // Now we want to pack all of the double-wide fields together. If
1241 // we're not aligned, though, we want to shuffle one 32-bit field
1242 // into place. If we can't find one, we'll have to pad it.
Brian Carlstroma0808032011-07-18 00:39:23 -07001243 if (i != klass->NumInstanceFields() && (field_offset & 0x04) != 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001244 InstanceField* pField = klass->GetInstanceField(i);
1245 char c = pField->GetType();
1246
1247 if (c != 'J' && c != 'D') {
1248 // The field that comes next is 32-bit, so just advance past it.
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001249 DCHECK(c != '[' && c != 'L');
Brian Carlstroma0808032011-07-18 00:39:23 -07001250 pField->SetOffset(field_offset);
1251 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001252 i++;
1253 } else {
1254 // Next field is 64-bit, so search for a 32-bit field we can
1255 // swap into it.
1256 bool found = false;
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001257 for (size_t j = klass->NumInstanceFields() - 1; j > i; j--) {
1258 InstanceField* singleField = klass->GetInstanceField(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001259 char rc = singleField->GetType();
1260 if (rc != 'J' && rc != 'D') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001261 klass->SetInstanceField(i, singleField);
1262 klass->SetInstanceField(j, pField);
1263 pField = singleField;
Brian Carlstroma0808032011-07-18 00:39:23 -07001264 pField->SetOffset(field_offset);
1265 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001266 found = true;
1267 i++;
1268 break;
1269 }
1270 }
1271 if (!found) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001272 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001273 }
1274 }
1275 }
1276
1277 // Alignment is good, shuffle any double-wide fields forward, and
1278 // finish assigning field offsets to all fields.
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001279 DCHECK(i == klass->NumInstanceFields() || (field_offset & 0x04) == 0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001280 for ( ; i < klass->NumInstanceFields(); i++) {
1281 InstanceField* pField = klass->GetInstanceField(i);
1282 char c = pField->GetType();
1283 if (c != 'D' && c != 'J') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001284 for (size_t j = klass->NumInstanceFields() - 1; j > i; j--) {
1285 InstanceField* doubleField = klass->GetInstanceField(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001286 char rc = doubleField->GetType();
1287 if (rc == 'D' || rc == 'J') {
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001288 klass->SetInstanceField(i, doubleField);
1289 klass->SetInstanceField(j, pField);
1290 pField = doubleField;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001291 c = rc;
1292 break;
1293 }
1294 }
1295 } else {
1296 // This is a double-wide field, leave it be.
1297 }
1298
Brian Carlstroma0808032011-07-18 00:39:23 -07001299 pField->SetOffset(field_offset);
1300 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001301 if (c == 'J' || c == 'D')
Brian Carlstroma0808032011-07-18 00:39:23 -07001302 field_offset += sizeof(uint32_t);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001303 }
1304
1305#ifndef NDEBUG
1306 /* Make sure that all reference fields appear before
1307 * non-reference fields, and all double-wide fields are aligned.
1308 */
1309 j = 0; // seen non-ref
1310 for (i = 0; i < klass->NumInstanceFields(); i++) {
1311 InstanceField *pField = &klass->ifields[i];
1312 char c = pField->GetType();
1313
1314 if (c == 'D' || c == 'J') {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001315 DCHECK((pField->offset_ & 0x07) == 0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001316 }
1317
1318 if (c != '[' && c != 'L') {
1319 if (!j) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001320 DCHECK(i == klass->num_reference_ifields_);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001321 j = 1;
1322 }
1323 } else if (j) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001324 DCHECK(false);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001325 }
1326 }
1327 if (!j) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001328 DCHECK(klass->num_reference_ifields_ == klass->NumInstanceFields());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001329 }
1330#endif
1331
Brian Carlstroma0808032011-07-18 00:39:23 -07001332 klass->object_size_ = field_offset;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001333 return true;
1334}
1335
1336// Set the bitmap of reference offsets, refOffsets, from the ifields
1337// list.
1338void ClassLinker::CreateReferenceOffsets(Class* klass) {
1339 uint32_t reference_offsets = 0;
1340 if (klass->HasSuperClass()) {
1341 reference_offsets = klass->GetSuperClass()->GetReferenceOffsets();
1342 }
1343 // If our superclass overflowed, we don't stand a chance.
1344 if (reference_offsets != CLASS_WALK_SUPER) {
1345 // All of the fields that contain object references are guaranteed
1346 // to be at the beginning of the ifields list.
1347 for (size_t i = 0; i < klass->NumReferenceInstanceFields(); ++i) {
1348 // Note that, per the comment on struct InstField, f->byteOffset
1349 // is the offset from the beginning of obj, not the offset into
1350 // obj->instanceData.
1351 const InstanceField* field = klass->GetInstanceField(i);
1352 size_t byte_offset = field->GetOffset();
1353 CHECK_GE(byte_offset, CLASS_SMALLEST_OFFSET);
Elliott Hughes1f359b02011-07-17 14:27:17 -07001354 CHECK_EQ(byte_offset & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001355 if (CLASS_CAN_ENCODE_OFFSET(byte_offset)) {
1356 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset);
Elliott Hughes1f359b02011-07-17 14:27:17 -07001357 CHECK_NE(new_bit, 0U);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001358 reference_offsets |= new_bit;
1359 } else {
1360 reference_offsets = CLASS_WALK_SUPER;
1361 break;
1362 }
1363 }
1364 klass->SetReferenceOffsets(reference_offsets);
1365 }
1366}
1367
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001368Class* ClassLinker::ResolveClass(const Class* referrer, uint32_t class_idx) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001369 DexFile* dex_file = referrer->GetDexFile();
1370 Class* resolved = dex_file->GetResolvedClass(class_idx);
1371 if (resolved != NULL) {
1372 return resolved;
1373 }
1374 const char* descriptor = dex_file->GetRaw()->dexStringByTypeIdx(class_idx);
1375 if (descriptor[0] != '\0' && descriptor[1] == '\0') {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001376 resolved = FindPrimitiveClass(descriptor[0]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001377 } else {
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001378 resolved = FindClass(descriptor, referrer->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001379 }
1380 if (resolved != NULL) {
1381 Class* check = resolved->IsArray() ? resolved->component_type_ : resolved;
1382 if (referrer->GetDexFile() != check->GetDexFile()) {
1383 if (check->GetClassLoader() != NULL) {
1384 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
1385 return NULL;
1386 }
1387 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001388 dex_file->SetResolvedClass(resolved, class_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001389 } else {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001390 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001391 }
1392 return resolved;
1393}
1394
1395Method* ResolveMethod(const Class* referrer, uint32_t method_idx,
1396 /*MethodType*/ int method_type) {
1397 CHECK(false);
1398 return NULL;
1399}
1400
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001401String* ClassLinker::ResolveString(const Class* referring, uint32_t string_idx) {
1402 const RawDexFile* raw = referring->GetDexFile()->GetRaw();
1403 const RawDexFile::StringId& string_id = raw->GetStringId(string_idx);
1404 const char* string_data = raw->GetStringData(string_id);
Brian Carlstroma0808032011-07-18 00:39:23 -07001405 String* new_string = Heap::AllocStringFromModifiedUtf8(java_lang_String_, char_array_class_, string_data);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001406 // TODO: intern the new string
1407 referring->GetDexFile()->SetResolvedString(new_string, string_idx);
1408 return new_string;
1409}
1410
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001411} // namespace art