blob: 2bb6d2d405ee82ea28a9650f25f71219b000d3c8 [file] [log] [blame]
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "object.h"
4
Ian Rogersb033c752011-07-20 12:22:35 -07005#include <string.h>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006
Ian Rogersdf20fe02011-07-20 20:34:16 -07007#include <algorithm>
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07008#include <iostream>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009#include <string>
10#include <utility>
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070011
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070012#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070013#include "class_loader.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070014#include "dex_cache.h"
15#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070016#include "globals.h"
Brian Carlstroma40f9bc2011-07-26 21:26:07 -070017#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070018#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070019#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070020#include "monitor.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070021#include "runtime.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070022#include "stack.h"
Carl Shapiro3ee755d2011-06-28 12:11:04 -070023
24namespace art {
25
Elliott Hughes081be7f2011-09-18 16:50:26 -070026Object* Object::Clone() {
27 Class* c = GetClass();
28 DCHECK(!c->IsClassClass());
29
30 // Object::SizeOf gets the right size even if we're an array.
31 // Using c->AllocObject() here would be wrong.
32 size_t num_bytes = SizeOf();
Brian Carlstrom40381fb2011-10-19 14:13:40 -070033 SirtRef<Object> copy(Heap::AllocObject(c, num_bytes));
34 if (copy.get() == NULL) {
Elliott Hughes081be7f2011-09-18 16:50:26 -070035 return NULL;
36 }
37
38 // Copy instance data. We assume memcpy copies by words.
39 // TODO: expose and use move32.
40 byte* src_bytes = reinterpret_cast<byte*>(this);
Brian Carlstrom40381fb2011-10-19 14:13:40 -070041 byte* dst_bytes = reinterpret_cast<byte*>(copy.get());
Elliott Hughes081be7f2011-09-18 16:50:26 -070042 size_t offset = sizeof(Object);
43 memcpy(dst_bytes + offset, src_bytes + offset, num_bytes - offset);
44
Elliott Hughes20cde902011-10-04 17:37:27 -070045 if (c->IsFinalizable()) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -070046 Heap::AddFinalizerReference(copy.get());
Elliott Hughes20cde902011-10-04 17:37:27 -070047 }
Elliott Hughes081be7f2011-09-18 16:50:26 -070048
Brian Carlstrom40381fb2011-10-19 14:13:40 -070049 return copy.get();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070050}
51
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070052uint32_t Object::GetThinLockId() {
53 return Monitor::GetThinLockId(monitor_);
Elliott Hughes5f791332011-09-15 17:45:30 -070054}
55
Elliott Hughes081be7f2011-09-18 16:50:26 -070056bool Object::IsString() const {
57 // TODO use "klass_ == String::GetJavaLangString()" instead?
58 return GetClass() == GetClass()->GetDescriptor()->GetClass();
59}
60
Elliott Hughes5f791332011-09-15 17:45:30 -070061void Object::MonitorEnter(Thread* thread) {
62 Monitor::MonitorEnter(thread, this);
63}
64
Ian Rogersff1ed472011-09-20 13:46:24 -070065bool Object::MonitorExit(Thread* thread) {
66 return Monitor::MonitorExit(thread, this);
Elliott Hughes5f791332011-09-15 17:45:30 -070067}
68
69void Object::Notify() {
70 Monitor::Notify(Thread::Current(), this);
71}
72
73void Object::NotifyAll() {
74 Monitor::NotifyAll(Thread::Current(), this);
75}
76
77void Object::Wait(int64_t ms, int32_t ns) {
78 Monitor::Wait(Thread::Current(), this, ms, ns, true);
79}
80
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070081// TODO: get global references for these
82Class* Field::java_lang_reflect_Field_ = NULL;
83
84void Field::SetClass(Class* java_lang_reflect_Field) {
85 CHECK(java_lang_reflect_Field_ == NULL);
86 CHECK(java_lang_reflect_Field != NULL);
87 java_lang_reflect_Field_ = java_lang_reflect_Field;
88}
89
90void Field::ResetClass() {
91 CHECK(java_lang_reflect_Field_ != NULL);
92 java_lang_reflect_Field_ = NULL;
93}
94
95void Field::SetTypeIdx(uint32_t type_idx) {
96 SetField32(OFFSET_OF_OBJECT_MEMBER(Field, type_idx_), type_idx, false);
97}
98
99Class* Field::GetTypeDuringLinking() const {
100 // We are assured that the necessary primitive types are in the dex cache
101 // early during class linking
102 return GetDeclaringClass()->GetDexCache()->GetResolvedType(GetTypeIdx());
103}
104
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700105bool Field::IsPrimitiveType() const {
106 Class* type = GetTypeDuringLinking();
107 return (type == NULL || type->IsPrimitive());
108}
109
110Primitive::Type Field::GetPrimitiveType() const {
111 Class* type = GetTypeDuringLinking();
112 if (type == NULL) {
113 return Primitive::kPrimNot;
114 }
115 return type->GetPrimitiveType();
116}
117
118size_t Field::PrimitiveSize() const {
119 return Primitive::FieldSize(GetPrimitiveType());
120}
121
122const char* Field::GetTypeDescriptor() const {
123 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
124 const DexFile& dex_file = class_linker->FindDexFile(GetDeclaringClass()->GetDexCache());
125 const char* descriptor = dex_file.dexStringByTypeIdx(GetTypeIdx());
126 DCHECK(descriptor != NULL);
127 return descriptor;
128}
129
Ian Rogers5d76c432011-10-31 21:42:49 -0700130Class* Field::GetType() {
131 Class* type = GetFieldObject<Class*>(OFFSET_OF_OBJECT_MEMBER(Field, type_), false);
132 if (type == NULL) {
133 type = Runtime::Current()->GetClassLinker()->ResolveType(GetTypeIdx(), this);
134 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Field, type_), type, false);
Elliott Hughes80609252011-09-23 17:24:51 -0700135 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700136 return type;
Elliott Hughes80609252011-09-23 17:24:51 -0700137}
138
139void Field::InitJavaFields() {
140 Thread* self = Thread::Current();
141 ScopedThreadStateChange tsc(self, Thread::kRunnable);
142 MonitorEnter(self);
143 if (type_ == NULL) {
144 InitJavaFieldsLocked();
145 }
146 MonitorExit(self);
147}
148
149void Field::InitJavaFieldsLocked() {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700150 GetType(); // Resolves type as a side-effect. May throw.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700151}
152
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700153uint32_t Field::Get32(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700154 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700155 if (IsStatic()) {
156 object = declaring_class_;
157 }
158 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700159}
160
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700161void Field::Set32(Object* object, uint32_t new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700162 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700163 if (IsStatic()) {
164 object = declaring_class_;
165 }
166 object->SetField32(GetOffset(), new_value, IsVolatile());
167}
168
169uint64_t Field::Get64(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700170 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700171 if (IsStatic()) {
172 object = declaring_class_;
173 }
174 return object->GetField64(GetOffset(), IsVolatile());
175}
176
177void Field::Set64(Object* object, uint64_t new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700178 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700179 if (IsStatic()) {
180 object = declaring_class_;
181 }
182 object->SetField64(GetOffset(), new_value, IsVolatile());
183}
184
185Object* Field::GetObj(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700186 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700187 if (IsStatic()) {
188 object = declaring_class_;
189 }
190 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
191}
192
193void Field::SetObj(Object* object, const Object* new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700194 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700195 if (IsStatic()) {
196 object = declaring_class_;
197 }
198 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
199}
200
201bool Field::GetBoolean(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700202 DCHECK(GetPrimitiveType() == Primitive::kPrimBoolean) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700203 return Get32(object);
204}
205
206void Field::SetBoolean(Object* object, bool z) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700207 DCHECK(GetPrimitiveType() == Primitive::kPrimBoolean) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700208 Set32(object, z);
209}
210
211int8_t Field::GetByte(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700212 DCHECK(GetPrimitiveType() == Primitive::kPrimByte) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700213 return Get32(object);
214}
215
216void Field::SetByte(Object* object, int8_t b) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700217 DCHECK(GetPrimitiveType() == Primitive::kPrimByte) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700218 Set32(object, b);
219}
220
221uint16_t Field::GetChar(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700222 DCHECK(GetPrimitiveType() == Primitive::kPrimChar) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700223 return Get32(object);
224}
225
226void Field::SetChar(Object* object, uint16_t c) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700227 DCHECK(GetPrimitiveType() == Primitive::kPrimChar) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700228 Set32(object, c);
229}
230
Ian Rogers466bb252011-10-14 03:29:56 -0700231int16_t Field::GetShort(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700232 DCHECK(GetPrimitiveType() == Primitive::kPrimShort) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700233 return Get32(object);
234}
235
Ian Rogers466bb252011-10-14 03:29:56 -0700236void Field::SetShort(Object* object, int16_t s) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700237 DCHECK(GetPrimitiveType() == Primitive::kPrimShort) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700238 Set32(object, s);
239}
240
241int32_t Field::GetInt(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700242 DCHECK(GetPrimitiveType() == Primitive::kPrimInt) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700243 return Get32(object);
244}
245
246void Field::SetInt(Object* object, int32_t i) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700247 DCHECK(GetPrimitiveType() == Primitive::kPrimInt) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700248 Set32(object, i);
249}
250
251int64_t Field::GetLong(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700252 DCHECK(GetPrimitiveType() == Primitive::kPrimLong) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700253 return Get64(object);
254}
255
256void Field::SetLong(Object* object, int64_t j) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700257 DCHECK(GetPrimitiveType() == Primitive::kPrimLong) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258 Set64(object, j);
259}
260
261float Field::GetFloat(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700262 DCHECK(GetPrimitiveType() == Primitive::kPrimFloat) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263 JValue float_bits;
264 float_bits.i = Get32(object);
265 return float_bits.f;
266}
267
268void Field::SetFloat(Object* object, float f) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700269 DCHECK(GetPrimitiveType() == Primitive::kPrimFloat) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 JValue float_bits;
271 float_bits.f = f;
272 Set32(object, float_bits.i);
273}
274
275double Field::GetDouble(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700276 DCHECK(GetPrimitiveType() == Primitive::kPrimDouble) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700277 JValue double_bits;
278 double_bits.j = Get64(object);
279 return double_bits.d;
280}
281
282void Field::SetDouble(Object* object, double d) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700283 DCHECK(GetPrimitiveType() == Primitive::kPrimDouble) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 JValue double_bits;
285 double_bits.d = d;
286 Set64(object, double_bits.j);
287}
288
289Object* Field::GetObject(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700290 CHECK(GetPrimitiveType() == Primitive::kPrimNot) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700291 return GetObj(object);
292}
293
294void Field::SetObject(Object* object, const Object* l) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700295 CHECK(GetPrimitiveType() == Primitive::kPrimNot) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700296 SetObj(object, l);
297}
298
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700299bool Method::IsClassInitializer() const {
300 return IsStatic() && GetName()->Equals("<clinit>");
301}
302
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303// TODO: get global references for these
Elliott Hughes80609252011-09-23 17:24:51 -0700304Class* Method::java_lang_reflect_Constructor_ = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305Class* Method::java_lang_reflect_Method_ = NULL;
306
Elliott Hughes80609252011-09-23 17:24:51 -0700307void Method::SetClasses(Class* java_lang_reflect_Constructor, Class* java_lang_reflect_Method) {
308 CHECK(java_lang_reflect_Constructor_ == NULL);
309 CHECK(java_lang_reflect_Constructor != NULL);
310 java_lang_reflect_Constructor_ = java_lang_reflect_Constructor;
311
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700312 CHECK(java_lang_reflect_Method_ == NULL);
313 CHECK(java_lang_reflect_Method != NULL);
314 java_lang_reflect_Method_ = java_lang_reflect_Method;
315}
316
Elliott Hughes80609252011-09-23 17:24:51 -0700317void Method::ResetClasses() {
318 CHECK(java_lang_reflect_Constructor_ != NULL);
319 java_lang_reflect_Constructor_ = NULL;
320
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700321 CHECK(java_lang_reflect_Method_ != NULL);
322 java_lang_reflect_Method_ = NULL;
323}
324
Elliott Hughes418d20f2011-09-22 14:00:39 -0700325Class* ExtractNextClassFromSignature(ClassLinker* class_linker, const ClassLoader* cl, const char*& p) {
326 if (*p == '[') {
327 // Something like "[[[Ljava/lang/String;".
328 const char* start = p;
329 while (*p == '[') {
330 ++p;
331 }
332 if (*p == 'L') {
333 while (*p != ';') {
334 ++p;
335 }
336 }
337 ++p; // Either the ';' or the primitive type.
338
Brian Carlstromaded5f72011-10-07 17:15:04 -0700339 std::string descriptor(start, (p - start));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700340 return class_linker->FindClass(descriptor, cl);
341 } else if (*p == 'L') {
342 const char* start = p;
343 while (*p != ';') {
344 ++p;
345 }
346 ++p;
347 StringPiece descriptor(start, (p - start));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700348 return class_linker->FindClass(descriptor.ToString(), cl);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700349 } else {
350 return class_linker->FindPrimitiveClass(*p++);
351 }
352}
353
354void Method::InitJavaFieldsLocked() {
355 // Create the array.
356 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
357 size_t arg_count = GetShorty()->GetLength() - 1;
358 Class* array_class = class_linker->FindSystemClass("[Ljava/lang/Class;");
359 ObjectArray<Class>* parameters = ObjectArray<Class>::Alloc(array_class, arg_count);
360 if (parameters == NULL) {
361 return;
362 }
363
364 // Parse the signature, filling the array.
365 const ClassLoader* cl = GetDeclaringClass()->GetClassLoader();
366 std::string signature(GetSignature()->ToModifiedUtf8());
367 const char* p = signature.c_str();
368 DCHECK_EQ(*p, '(');
369 ++p;
370 for (size_t i = 0; i < arg_count; ++i) {
371 Class* c = ExtractNextClassFromSignature(class_linker, cl, p);
372 if (c == NULL) {
373 return;
374 }
375 parameters->Set(i, c);
376 }
377
378 DCHECK_EQ(*p, ')');
379 ++p;
380
Ian Rogers5d76c432011-10-31 21:42:49 -0700381 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, java_parameter_types_),
382 parameters, false);
383 Class* java_return_type = ExtractNextClassFromSignature(class_linker, cl, p);
384 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_),
385 java_return_type, false);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700386}
387
388void Method::InitJavaFields() {
389 Thread* self = Thread::Current();
390 ScopedThreadStateChange tsc(self, Thread::kRunnable);
391 MonitorEnter(self);
392 if (java_parameter_types_ == NULL || java_return_type_ == NULL) {
393 InitJavaFieldsLocked();
394 }
395 MonitorExit(self);
396}
397
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398ObjectArray<String>* Method::GetDexCacheStrings() const {
399 return GetFieldObject<ObjectArray<String>*>(
400 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
401}
402
403void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
404 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
405 new_return_type_idx, false);
406}
407
Ian Rogers9074b992011-10-26 17:41:55 -0700408const char* Method::GetReturnTypeDescriptor() const {
409 Class* declaring_class = GetDeclaringClass();
410 DexCache* dex_cache = declaring_class->GetDexCache();
411 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
412 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
413 const char* descriptor = dex_file.dexStringByTypeIdx(GetReturnTypeIdx());
414 DCHECK(descriptor != NULL);
415 return descriptor;
416}
417
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418Class* Method::GetReturnType() const {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700419 DCHECK(GetDeclaringClass()->IsResolved() || GetDeclaringClass()->IsErroneous())
420 << PrettyMethod(this);
Jesse Wilsond81cdcc2011-10-17 14:36:48 -0400421 Class* java_return_type = java_return_type_;
422 if (java_return_type != NULL) {
423 return java_return_type;
424 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425 // Short-cut
426 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
427 if (result == NULL) {
428 // Do full linkage and set cache value for next call
429 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
430 }
Elliott Hughes14134a12011-09-30 16:55:51 -0700431 CHECK(result != NULL) << PrettyMethod(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700432 return result;
433}
434
435void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
436 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
437 new_dex_cache_strings, false);
438}
439
440ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
441 return GetFieldObject<ObjectArray<Class>*>(
442 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
443}
444
445void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
446 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
447 new_dex_cache_classes, false);
448}
449
450ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
451 return GetFieldObject<ObjectArray<Method>*>(
452 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
453}
454
455void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
456 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
457 new_dex_cache_methods, false);
458}
459
460ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
461 return GetFieldObject<ObjectArray<Field>*>(
462 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
463}
464
465void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
466 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
467 new_dex_cache_fields, false);
468}
469
470CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
471 return GetFieldPtr<CodeAndDirectMethods*>(
472 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
473 false);
474}
475
476void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
477 SetFieldPtr<CodeAndDirectMethods*>(
478 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
479 new_value, false);
480}
481
482ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
483 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
484 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
485 false);
486}
487
488void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700489 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700490 new_value, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700491}
492
493size_t Method::NumArgRegisters(const StringPiece& shorty) {
494 CHECK_LE(1, shorty.length());
495 uint32_t num_registers = 0;
496 for (int i = 1; i < shorty.length(); ++i) {
497 char ch = shorty[i];
498 if (ch == 'D' || ch == 'J') {
499 num_registers += 2;
500 } else {
501 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700502 }
503 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700504 return num_registers;
505}
506
507size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700508 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700510 for (int i = 1; i < shorty->GetLength(); ++i) {
511 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700512 if (ch == 'D' || ch == 'J') {
513 num_bytes += 8;
514 } else if (ch == 'L') {
515 // Argument is a reference or an array. The shorty descriptor
516 // does not distinguish between these types.
517 num_bytes += sizeof(Object*);
518 } else {
519 num_bytes += 4;
520 }
521 }
522 return num_bytes;
523}
524
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700525size_t Method::NumArgs() const {
526 // "1 +" because the first in Args is the receiver.
527 // "- 1" because we don't count the return type.
528 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
529}
530
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700531// The number of reference arguments to this method including implicit this
532// pointer
533size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700534 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700536 for (int i = 1; i < shorty->GetLength(); i++) {
537 char ch = shorty->CharAt(i);
538 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700539 result++;
540 }
541 }
542 return result;
543}
544
545// The number of long or double arguments
546size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700547 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700548 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700549 for (int i = 1; i < shorty->GetLength(); i++) {
550 char ch = shorty->CharAt(i);
551 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700552 result++;
553 }
554 }
555 return result;
556}
557
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558// Is the given method parameter a reference?
559bool Method::IsParamAReference(unsigned int param) const {
560 CHECK_LT(param, NumArgs());
561 if (IsStatic()) {
562 param++; // 0th argument must skip return value at start of the shorty
563 } else if (param == 0) {
564 return true; // this argument
565 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700566 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567}
568
569// Is the given method parameter a long or double?
570bool Method::IsParamALongOrDouble(unsigned int param) const {
571 CHECK_LT(param, NumArgs());
572 if (IsStatic()) {
573 param++; // 0th argument must skip return value at start of the shorty
574 } else if (param == 0) {
575 return false; // this argument
576 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700577 char ch = GetShorty()->CharAt(param);
578 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700579}
580
581static size_t ShortyCharToSize(char x) {
582 switch (x) {
583 case 'V': return 0;
584 case '[': return kPointerSize;
585 case 'L': return kPointerSize;
586 case 'D': return 8;
587 case 'J': return 8;
588 default: return 4;
589 }
590}
591
592size_t Method::ParamSize(unsigned int param) const {
593 CHECK_LT(param, NumArgs());
594 if (IsStatic()) {
595 param++; // 0th argument must skip return value at start of the shorty
596 } else if (param == 0) {
597 return kPointerSize; // this argument
598 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700599 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700600}
601
602size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700603 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700604}
605
Ian Rogers466bb252011-10-14 03:29:56 -0700606Method* Method::FindOverriddenMethod() const {
607 if (IsStatic()) {
608 return NULL;
609 }
610 Class* declaring_class = GetDeclaringClass();
611 Class* super_class = declaring_class->GetSuperClass();
612 uint16_t method_index = GetMethodIndex();
613 ObjectArray<Method>* super_class_vtable = super_class->GetVTable();
614 Method* result = NULL;
615 if (super_class_vtable != NULL && method_index < super_class_vtable->GetLength()) {
616 result = super_class_vtable->Get(method_index);
617 } else {
618 ObjectArray<Class>* interfaces = declaring_class->GetInterfaces();
619 String* name = GetName();
620 String* signature = GetSignature();
621 for (int32_t i = 0; i < interfaces->GetLength() && result == NULL; i++) {
622 Class* interface = interfaces->Get(i);
623 result = interface->FindInterfaceMethod(name, signature);
624 }
625 }
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700626 DCHECK(result == NULL || HasSameNameAndSignature(result));
Ian Rogers466bb252011-10-14 03:29:56 -0700627 return result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700628}
629
Ian Rogersbdb03912011-09-14 00:55:44 -0700630uint32_t Method::ToDexPC(const uintptr_t pc) const {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700631 const uint32_t* mapping_table = GetMappingTable();
Ian Rogersbdb03912011-09-14 00:55:44 -0700632 if (mapping_table == NULL) {
Brian Carlstrom26c935a2011-10-16 14:52:35 -0700633 DCHECK(IsNative() || IsCalleeSaveMethod()) << PrettyMethod(this);
Ian Rogers67375ac2011-09-14 00:55:44 -0700634 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700635 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700636 size_t mapping_table_length = GetMappingTableLength();
Ian Rogersbdb03912011-09-14 00:55:44 -0700637 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
Ian Rogersbdb03912011-09-14 00:55:44 -0700638 uint32_t best_offset = 0;
639 uint32_t best_dex_offset = 0;
640 for (size_t i = 0; i < mapping_table_length; i += 2) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700641 uint32_t map_offset = mapping_table[i];
642 uint32_t map_dex_offset = mapping_table[i + 1];
Ian Rogersbdb03912011-09-14 00:55:44 -0700643 if (map_offset == sought_offset) {
644 best_offset = map_offset;
645 best_dex_offset = map_dex_offset;
646 break;
647 }
648 if (map_offset < sought_offset && map_offset > best_offset) {
649 best_offset = map_offset;
650 best_dex_offset = map_dex_offset;
651 }
652 }
653 return best_dex_offset;
654}
655
656uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700657 const uint32_t* mapping_table = GetMappingTable();
Ian Rogersbdb03912011-09-14 00:55:44 -0700658 if (mapping_table == NULL) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700659 DCHECK_EQ(dex_pc, 0U);
Ian Rogersbdb03912011-09-14 00:55:44 -0700660 return 0; // Special no mapping/pc == 0 case
661 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700662 size_t mapping_table_length = GetMappingTableLength();
Ian Rogersbdb03912011-09-14 00:55:44 -0700663 for (size_t i = 0; i < mapping_table_length; i += 2) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700664 uint32_t map_offset = mapping_table[i];
665 uint32_t map_dex_offset = mapping_table[i + 1];
Ian Rogersbdb03912011-09-14 00:55:44 -0700666 if (map_dex_offset == dex_pc) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700667 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
668 }
669 }
670 LOG(FATAL) << "Looking up Dex PC not contained in method";
671 return 0;
672}
673
674uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
675 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
Ian Rogersbdb03912011-09-14 00:55:44 -0700676 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
677 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
678 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
679 // Iterate over the catch handlers associated with dex_pc
680 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
681 !iter.HasNext(); iter.Next()) {
682 uint32_t iter_type_idx = iter.Get().type_idx_;
683 // Catch all case
Elliott Hughes80609252011-09-23 17:24:51 -0700684 if (iter_type_idx == DexFile::kDexNoIndex) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700685 return iter.Get().address_;
686 }
687 // Does this catch exception type apply?
Ian Rogers28ad40d2011-10-27 15:19:26 -0700688 Class* iter_exception_type = dex_cache->GetResolvedType(iter_type_idx);
689 if (iter_exception_type == NULL) {
690 // The verifier should take care of resolving all exception classes early
691 LOG(WARNING) << "Unresolved exception class when finding catch block: "
692 << dex_file.GetTypeDescriptor(dex_file.GetTypeId(iter_type_idx));
693 } else if (iter_exception_type->IsAssignableFrom(exception_type)) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700694 return iter.Get().address_;
695 }
696 }
697 // Handler not found
698 return DexFile::kDexNoIndex;
699}
700
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700701void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
702 // Push a transition back into managed code onto the linked list in thread.
703 CHECK_EQ(Thread::kRunnable, self->GetState());
704 NativeToManagedRecord record;
705 self->PushNativeToManagedRecord(&record);
706
707 // Call the invoke stub associated with the method.
708 // Pass everything as arguments.
709 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700710
711 bool have_executable_code = (GetCode() != NULL);
712#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700713 // Currently we can only compile non-native methods for ARM.
714 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700715#endif
716
717 if (have_executable_code && stub != NULL) {
Elliott Hughes9f865372011-10-11 15:04:19 -0700718 bool log = false;
719 if (log) {
720 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
721 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700722 (*stub)(this, receiver, self, args, result);
Elliott Hughes9f865372011-10-11 15:04:19 -0700723 if (log) {
724 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
725 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700726 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700727 if (Runtime::Current()->IsStarted()) {
728 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
729 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700730 if (result != NULL) {
731 result->j = 0;
732 }
733 }
734
735 // Pop transition.
736 self->PopNativeToManagedRecord(record);
737}
738
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700739bool Method::IsRegistered() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700740 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
741 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
742 return native_method != jni_stub;
743}
744
745void Method::RegisterNative(const void* native_method) {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700746 CHECK(IsNative()) << PrettyMethod(this);
747 CHECK(native_method != NULL) << PrettyMethod(this);
Brian Carlstrom16192862011-09-12 17:50:06 -0700748 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
749 native_method, false);
750}
751
752void Method::UnregisterNative() {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700753 CHECK(IsNative()) << PrettyMethod(this);
Brian Carlstrom16192862011-09-12 17:50:06 -0700754 // restore stub to lookup native pointer via dlsym
755 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
756}
757
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700758void Class::SetStatus(Status new_status) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700759 CHECK(new_status > GetStatus() || new_status == kStatusError || !Runtime::Current()->IsStarted())
760 << PrettyClass(this) << " " << GetStatus() << " -> " << new_status;
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700761 CHECK(sizeof(Status) == sizeof(uint32_t)) << PrettyClass(this);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700762 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700763}
764
765DexCache* Class::GetDexCache() const {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700766 return GetFieldObject<DexCache*>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700767}
768
769void Class::SetDexCache(DexCache* new_dex_cache) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700770 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700771}
772
Brian Carlstrom1f870082011-08-23 16:02:11 -0700773Object* Class::AllocObject() {
Brian Carlstrom96a253a2011-10-27 18:38:10 -0700774 DCHECK(!IsArrayClass()) << PrettyClass(this);
Ian Rogers28ad40d2011-10-27 15:19:26 -0700775 DCHECK(IsInstantiable()) << PrettyClass(this);
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700776 DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
Brian Carlstrom96a253a2011-10-27 18:38:10 -0700777 DCHECK_GE(this->object_size_, sizeof(Object));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700778 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700779}
780
Elliott Hughes4681c802011-09-25 18:04:37 -0700781void Class::DumpClass(std::ostream& os, int flags) const {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700782 if ((flags & kDumpClassFullDetail) == 0) {
783 os << PrettyClass(this);
784 if ((flags & kDumpClassClassLoader) != 0) {
785 os << ' ' << GetClassLoader();
786 }
787 if ((flags & kDumpClassInitialized) != 0) {
788 os << ' ' << GetStatus();
789 }
Elliott Hughese0918552011-10-28 17:18:29 -0700790 os << "\n";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700791 return;
792 }
793
794 Class* super = GetSuperClass();
795 os << "----- " << (IsInterface() ? "interface" : "class") << " "
796 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
797 os << " objectSize=" << SizeOf() << " "
798 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
799 os << StringPrintf(" access=0x%04x.%04x\n",
800 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
801 if (super != NULL) {
802 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
803 }
804 if (IsArrayClass()) {
805 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
806 }
807 if (NumInterfaces() > 0) {
808 os << " interfaces (" << NumInterfaces() << "):\n";
809 for (size_t i = 0; i < NumInterfaces(); ++i) {
810 Class* interface = GetInterface(i);
811 const ClassLoader* cl = interface->GetClassLoader();
812 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
813 }
814 }
815 os << " vtable (" << NumVirtualMethods() << " entries, "
816 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
817 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700818 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethodDuringLinking(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700819 }
820 os << " direct methods (" << NumDirectMethods() << " entries):\n";
821 for (size_t i = 0; i < NumDirectMethods(); ++i) {
822 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
823 }
824 if (NumStaticFields() > 0) {
825 os << " static fields (" << NumStaticFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700826 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700827 for (size_t i = 0; i < NumStaticFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700828 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700829 }
830 } else {
831 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700832 }
833 }
834 if (NumInstanceFields() > 0) {
835 os << " instance fields (" << NumInstanceFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700836 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700837 for (size_t i = 0; i < NumInstanceFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700838 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700839 }
840 } else {
841 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700842 }
843 }
844}
845
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700846void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
847 if (new_reference_offsets != CLASS_WALK_SUPER) {
848 // Sanity check that the number of bits set in the reference offset bitmap
849 // agrees with the number of references
850 Class* cur = this;
851 size_t cnt = 0;
852 while (cur) {
853 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
854 cur = cur->GetSuperClass();
855 }
856 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
857 }
858 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
859 new_reference_offsets, false);
860}
861
862void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
863 if (new_reference_offsets != CLASS_WALK_SUPER) {
864 // Sanity check that the number of bits set in the reference offset bitmap
865 // agrees with the number of references
866 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
867 NumReferenceStaticFieldsDuringLinking());
868 }
869 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
870 new_reference_offsets, false);
871}
872
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700873bool Class::Implements(const Class* klass) const {
874 DCHECK(klass != NULL);
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700875 DCHECK(klass->IsInterface()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700876 // All interfaces implemented directly and by our superclass, and
877 // recursively all super-interfaces of those interfaces, are listed
878 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700879 int32_t iftable_count = GetIfTableCount();
880 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
881 for (int32_t i = 0; i < iftable_count; i++) {
882 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700883 return true;
884 }
885 }
886 return false;
887}
888
889// Determine whether "this" is assignable from "klazz", where both of these
890// are array classes.
891//
892// Consider an array class, e.g. Y[][], where Y is a subclass of X.
893// Y[][] = Y[][] --> true (identity)
894// X[][] = Y[][] --> true (element superclass)
895// Y = Y[][] --> false
896// Y[] = Y[][] --> false
897// Object = Y[][] --> true (everything is an object)
898// Object[] = Y[][] --> true
899// Object[][] = Y[][] --> true
900// Object[][][] = Y[][] --> false (too many []s)
901// Serializable = Y[][] --> true (all arrays are Serializable)
902// Serializable[] = Y[][] --> true
903// Serializable[][] = Y[][] --> false (unless Y is Serializable)
904//
905// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700906// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700907//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700908bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700909 DCHECK(IsArrayClass()) << PrettyClass(this);
910 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700911 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700912}
913
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700914bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700915 DCHECK(!IsInterface()) << PrettyClass(this); // handled first in IsAssignableFrom
916 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700917 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700918 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700919 // src's super should be java_lang_Object, since it is an array.
920 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700921 DCHECK(java_lang_Object != NULL) << PrettyClass(src);
922 DCHECK(java_lang_Object->GetSuperClass() == NULL) << PrettyClass(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700923 return this == java_lang_Object;
924 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700925 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700926}
927
928bool Class::IsSubClass(const Class* klass) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700929 DCHECK(!IsInterface()) << PrettyClass(this);
930 DCHECK(!IsArrayClass()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700931 const Class* current = this;
932 do {
933 if (current == klass) {
934 return true;
935 }
936 current = current->GetSuperClass();
937 } while (current != NULL);
938 return false;
939}
940
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700941bool Class::IsInSamePackage(const String* descriptor_string_1,
942 const String* descriptor_string_2) {
943 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
944 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
945
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700946 size_t i = 0;
947 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
948 ++i;
949 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700950 if (descriptor1.find('/', i) != StringPiece::npos ||
951 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700952 return false;
953 } else {
954 return true;
955 }
956}
957
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700958#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700959bool Class::IsInSamePackage(const StringPiece& descriptor1,
960 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700961 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700962 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700963 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
964 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700965 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
966}
967#endif
968
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700969bool Class::IsInSamePackage(const Class* that) const {
970 const Class* klass1 = this;
971 const Class* klass2 = that;
972 if (klass1 == klass2) {
973 return true;
974 }
975 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700976 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700977 return false;
978 }
979 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -0700980 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700981 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700982 }
jeffhao4a801a42011-09-23 13:53:40 -0700983 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700984 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700985 }
986 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700987 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700988}
989
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700990const ClassLoader* Class::GetClassLoader() const {
Ian Rogersd81871c2011-10-03 13:57:23 -0700991 return GetFieldObject<const ClassLoader*>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -0700992}
993
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700994void Class::SetClassLoader(const ClassLoader* new_cl) {
995 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
Ian Rogersd81871c2011-10-03 13:57:23 -0700996 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700997}
998
Ian Rogersb04f69f2011-10-17 00:40:54 -0700999Method* Class::FindVirtualMethodForInterface(Method* method, bool can_throw) {
Brian Carlstrom30b94452011-08-25 21:35:26 -07001000 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001001 DCHECK(declaring_class != NULL) << PrettyClass(this);
1002 DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001003 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001004 int32_t iftable_count = GetIfTableCount();
1005 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1006 for (int32_t i = 0; i < iftable_count; i++) {
1007 InterfaceEntry* interface_entry = iftable->Get(i);
1008 if (interface_entry->GetInterface() == declaring_class) {
1009 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -07001010 }
1011 }
Ian Rogersb04f69f2011-10-17 00:40:54 -07001012 if (can_throw) {
1013 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
1014 "Class %s does not implement interface %s",
1015 PrettyDescriptor(GetDescriptor()).c_str(),
1016 PrettyDescriptor(declaring_class->GetDescriptor()).c_str());
1017 }
Brian Carlstrom30b94452011-08-25 21:35:26 -07001018 return NULL;
1019}
1020
Ian Rogers466bb252011-10-14 03:29:56 -07001021Method* Class::FindInterfaceMethod(const StringPiece& name, const StringPiece& signature) const {
jeffhaobdb76512011-09-07 11:43:16 -07001022 // Check the current class before checking the interfaces.
1023 Method* method = FindVirtualMethod(name, signature);
1024 if (method != NULL) {
1025 return method;
1026 }
1027
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001028 int32_t iftable_count = GetIfTableCount();
1029 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1030 for (int32_t i = 0; i < iftable_count; i++) {
1031 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001032 if (method != NULL) {
1033 return method;
1034 }
1035 }
1036 return NULL;
1037}
1038
Ian Rogers466bb252011-10-14 03:29:56 -07001039Method* Class::FindInterfaceMethod(String* name, String* signature) const {
1040 // Check the current class before checking the interfaces.
1041 Method* method = FindVirtualMethod(name, signature);
1042 if (method != NULL) {
1043 return method;
1044 }
1045 int32_t iftable_count = GetIfTableCount();
1046 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1047 for (int32_t i = 0; i < iftable_count; i++) {
1048 Class* interface = iftable->Get(i)->GetInterface();
1049 method = interface->FindVirtualMethod(name, signature);
1050 if (method != NULL) {
1051 return method;
1052 }
1053 }
1054 return NULL;
1055}
1056
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001057Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001058 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001059 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001060 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001061 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001062 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001063 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001064 }
1065 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001066 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001067}
1068
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001069Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001070 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001071 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001072 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001073 if (method != NULL) {
1074 return method;
1075 }
1076 }
1077 return NULL;
1078}
1079
1080Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Ian Rogers466bb252011-10-14 03:29:56 -07001081 const StringPiece& signature) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001082 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001083 Method* method = GetVirtualMethod(i);
Ian Rogers466bb252011-10-14 03:29:56 -07001084 if (method->GetName()->Equals(name) && method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001085 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001086 }
1087 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001088 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001089}
1090
Ian Rogers466bb252011-10-14 03:29:56 -07001091Method* Class::FindDeclaredVirtualMethod(String* name, String* signature) const {
1092 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
1093 Method* method = GetVirtualMethod(i);
1094 if (method->GetName() == name && method->GetSignature() == signature) {
1095 return method;
Ian Rogers466bb252011-10-14 03:29:56 -07001096 }
1097 }
1098 return NULL;
1099}
1100
1101Method* Class::FindVirtualMethod(const StringPiece& name, const StringPiece& signature) const {
1102 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1103 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
1104 if (method != NULL) {
1105 return method;
1106 }
1107 }
1108 return NULL;
1109}
1110
1111Method* Class::FindVirtualMethod(String* name, String* signature) const {
1112 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07001113 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001114 if (method != NULL) {
1115 return method;
1116 }
1117 }
1118 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001119}
1120
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001121Field* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001122 // Is the field in this class?
1123 // Interfaces are not relevant because they can't contain instance fields.
1124 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1125 Field* f = GetInstanceField(i);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001126 if (f->GetName()->Equals(name) &&
1127 StringPiece(f->GetTypeDescriptor()) == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001128 return f;
1129 }
1130 }
1131 return NULL;
1132}
1133
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001134Field* Class::FindDeclaredInstanceField(String* name, String* type) {
1135 // Is the field in this class?
1136 // Interfaces are not relevant because they can't contain instance fields.
1137 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1138 Field* f = GetInstanceField(i);
1139 if (f->GetName() == name && type->Equals(f->GetTypeDescriptor())) {
1140 return f;
1141 }
1142 }
1143 return NULL;
1144}
1145
1146Field* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001147 // Is the field in this class, or any of its superclasses?
1148 // Interfaces are not relevant because they can't contain instance fields.
1149 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001150 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001151 if (f != NULL) {
1152 return f;
1153 }
1154 }
1155 return NULL;
1156}
1157
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001158Field* Class::FindInstanceField(String* name, String* type) {
1159 // Is the field in this class, or any of its superclasses?
1160 // Interfaces are not relevant because they can't contain instance fields.
1161 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1162 Field* f = c->FindDeclaredInstanceField(name, type);
1163 if (f != NULL) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001164 return f;
1165 }
1166 }
1167 return NULL;
1168}
1169
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001170Field* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
1171 DCHECK(type != NULL);
1172 for (size_t i = 0; i < NumStaticFields(); ++i) {
1173 Field* f = GetStaticField(i);
1174 if (f->GetName()->Equals(name) && StringPiece(f->GetTypeDescriptor()) == type) {
1175 return f;
1176 }
1177 }
1178 return NULL;
1179}
1180
1181Field* Class::FindDeclaredStaticField(String* name, String* type) {
1182 DCHECK(type != NULL);
1183 for (size_t i = 0; i < NumStaticFields(); ++i) {
1184 Field* f = GetStaticField(i);
1185 if (f->GetName() == name && type->Equals(f->GetTypeDescriptor())) {
1186 return f;
1187 }
1188 }
1189 return NULL;
1190}
1191
1192Field* Class::FindStaticField(const StringPiece& name, const StringPiece& type) {
1193 // Is the field in this class (or its interfaces), or any of its
1194 // superclasses (or their interfaces)?
1195 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1196 // Is the field in this class?
1197 Field* f = c->FindDeclaredStaticField(name, type);
1198 if (f != NULL) {
1199 return f;
1200 }
1201
1202 // Is this field in any of this class' interfaces?
1203 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1204 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1205 Class* interface = interface_entry->GetInterface();
1206 f = interface->FindDeclaredStaticField(name, type);
1207 if (f != NULL) {
1208 return f;
1209 }
1210 }
1211 }
1212 return NULL;
1213}
1214
1215Field* Class::FindStaticField(String* name, String* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001216 // Is the field in this class (or its interfaces), or any of its
1217 // superclasses (or their interfaces)?
1218 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1219 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001220 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001221 if (f != NULL) {
1222 return f;
1223 }
1224
1225 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001226 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1227 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1228 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001229 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001230 if (f != NULL) {
1231 return f;
1232 }
1233 }
1234 }
1235 return NULL;
1236}
1237
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001238Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001239 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001240 DCHECK_GE(component_count, 0);
1241 DCHECK(array_class->IsArrayClass());
Elliott Hughesb408de72011-10-04 14:35:05 -07001242
1243 size_t header_size = sizeof(Array);
1244 size_t data_size = component_count * component_size;
1245 size_t size = header_size + data_size;
1246
1247 // Check for overflow and throw OutOfMemoryError if this was an unreasonable request.
1248 size_t component_shift = sizeof(size_t) * 8 - 1 - CLZ(component_size);
1249 if (data_size >> component_shift != size_t(component_count) || size < data_size) {
1250 Thread::Current()->ThrowNewExceptionF("Ljava/lang/OutOfMemoryError;",
1251 "%s of length %zd exceeds the VM limit",
1252 PrettyDescriptor(array_class->GetDescriptor()).c_str(), component_count);
1253 return NULL;
1254 }
1255
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001256 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1257 if (array != NULL) {
1258 DCHECK(array->IsArrayInstance());
1259 array->SetLength(component_count);
1260 }
1261 return array;
1262}
1263
1264Array* Array::Alloc(Class* array_class, int32_t component_count) {
1265 return Alloc(array_class, component_count, array_class->GetComponentSize());
1266}
1267
Elliott Hughes80609252011-09-23 17:24:51 -07001268bool Array::ThrowArrayIndexOutOfBoundsException(int32_t index) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001269 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001270 "length=%i; index=%i", length_, index);
1271 return false;
1272}
1273
1274bool Array::ThrowArrayStoreException(Object* object) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001275 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001276 "Can't store an element of type %s into an array of type %s",
1277 PrettyTypeOf(object).c_str(), PrettyTypeOf(this).c_str());
1278 return false;
1279}
1280
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001281template<typename T>
1282PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001283 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001284 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1285 return down_cast<PrimitiveArray<T>*>(raw_array);
1286}
1287
1288template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1289
1290// Explicitly instantiate all the primitive array types.
1291template class PrimitiveArray<uint8_t>; // BooleanArray
1292template class PrimitiveArray<int8_t>; // ByteArray
1293template class PrimitiveArray<uint16_t>; // CharArray
1294template class PrimitiveArray<double>; // DoubleArray
1295template class PrimitiveArray<float>; // FloatArray
1296template class PrimitiveArray<int32_t>; // IntArray
1297template class PrimitiveArray<int64_t>; // LongArray
1298template class PrimitiveArray<int16_t>; // ShortArray
1299
Ian Rogers466bb252011-10-14 03:29:56 -07001300// Explicitly instantiate Class[][]
1301template class ObjectArray<ObjectArray<Class> >;
1302
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001303// TODO: get global references for these
1304Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001305
Brian Carlstroma663ea52011-08-19 23:33:41 -07001306void String::SetClass(Class* java_lang_String) {
1307 CHECK(java_lang_String_ == NULL);
1308 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001309 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001310}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001311
Brian Carlstroma663ea52011-08-19 23:33:41 -07001312void String::ResetClass() {
1313 CHECK(java_lang_String_ != NULL);
1314 java_lang_String_ = NULL;
1315}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001316
Brian Carlstromc74255f2011-09-11 22:47:39 -07001317String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001318 return Runtime::Current()->GetInternTable()->InternWeak(this);
1319}
1320
Brian Carlstrom395520e2011-09-25 19:35:00 -07001321int32_t String::GetHashCode() {
1322 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1323 if (result == 0) {
1324 ComputeHashCode();
1325 }
1326 result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1327 DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
1328 << ToModifiedUtf8() << " " << result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001329 return result;
1330}
1331
1332int32_t String::GetLength() const {
1333 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1334 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1335 return result;
1336}
1337
1338uint16_t String::CharAt(int32_t index) const {
1339 // TODO: do we need this? Equals is the only caller, and could
1340 // bounds check itself.
1341 if (index < 0 || index >= count_) {
1342 Thread* self = Thread::Current();
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001343 self->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;",
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001344 "length=%i; index=%i", count_, index);
1345 return 0;
1346 }
1347 return GetCharArray()->Get(index + GetOffset());
1348}
1349
1350String* String::AllocFromUtf16(int32_t utf16_length,
1351 const uint16_t* utf16_data_in,
1352 int32_t hash_code) {
1353 String* string = Alloc(GetJavaLangString(), utf16_length);
Elliott Hughesb51036c2011-10-12 23:49:11 -07001354 if (string == NULL) {
1355 return NULL;
1356 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001357 // TODO: use 16-bit wide memset variant
1358 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
Elliott Hughesb51036c2011-10-12 23:49:11 -07001359 if (array == NULL) {
1360 return NULL;
1361 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001362 for (int i = 0; i < utf16_length; i++) {
1363 array->Set(i, utf16_data_in[i]);
1364 }
1365 if (hash_code != 0) {
1366 string->SetHashCode(hash_code);
1367 } else {
1368 string->ComputeHashCode();
1369 }
1370 return string;
1371}
1372
1373String* String::AllocFromModifiedUtf8(const char* utf) {
1374 size_t char_count = CountModifiedUtf8Chars(utf);
1375 return AllocFromModifiedUtf8(char_count, utf);
1376}
1377
1378String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1379 const char* utf8_data_in) {
1380 String* string = Alloc(GetJavaLangString(), utf16_length);
Elliott Hughesb51036c2011-10-12 23:49:11 -07001381 if (string == NULL) {
1382 return NULL;
1383 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001384 uint16_t* utf16_data_out =
1385 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1386 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1387 string->ComputeHashCode();
1388 return string;
1389}
1390
1391String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001392 SirtRef<CharArray> array(CharArray::Alloc(utf16_length));
1393 if (array.get() == NULL) {
Elliott Hughesb51036c2011-10-12 23:49:11 -07001394 return NULL;
1395 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001396 return Alloc(java_lang_String, array.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001397}
1398
1399String* String::Alloc(Class* java_lang_String, CharArray* array) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001400 SirtRef<CharArray> array_ref(array); // hold reference in case AllocObject causes GC
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001401 String* string = down_cast<String*>(java_lang_String->AllocObject());
Elliott Hughesb51036c2011-10-12 23:49:11 -07001402 if (string == NULL) {
1403 return NULL;
1404 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001405 string->SetArray(array);
1406 string->SetCount(array->GetLength());
1407 return string;
1408}
1409
1410bool String::Equals(const String* that) const {
1411 if (this == that) {
1412 // Quick reference equality test
1413 return true;
1414 } else if (that == NULL) {
1415 // Null isn't an instanceof anything
1416 return false;
1417 } else if (this->GetLength() != that->GetLength()) {
1418 // Quick length inequality test
1419 return false;
1420 } else {
Elliott Hughes20cde902011-10-04 17:37:27 -07001421 // Note: don't short circuit on hash code as we're presumably here as the
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001422 // hash code was already equal
1423 for (int32_t i = 0; i < that->GetLength(); ++i) {
1424 if (this->CharAt(i) != that->CharAt(i)) {
1425 return false;
1426 }
1427 }
1428 return true;
1429 }
1430}
1431
1432bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1433 int32_t that_length) const {
1434 if (this->GetLength() != that_length) {
1435 return false;
1436 } else {
1437 for (int32_t i = 0; i < that_length; ++i) {
1438 if (this->CharAt(i) != that_chars[that_offset + i]) {
1439 return false;
1440 }
1441 }
1442 return true;
1443 }
1444}
1445
1446bool String::Equals(const char* modified_utf8) const {
1447 for (int32_t i = 0; i < GetLength(); ++i) {
1448 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1449 if (ch == '\0' || ch != CharAt(i)) {
1450 return false;
1451 }
1452 }
1453 return *modified_utf8 == '\0';
1454}
1455
1456bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001457 if (modified_utf8.size() != GetLength()) {
1458 return false;
1459 }
1460 const char* p = modified_utf8.data();
1461 for (int32_t i = 0; i < GetLength(); ++i) {
1462 uint16_t ch = GetUtf16FromUtf8(&p);
1463 if (ch != CharAt(i)) {
1464 return false;
1465 }
1466 }
1467 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001468}
1469
1470// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1471std::string String::ToModifiedUtf8() const {
1472 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1473 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1474 std::string result(byte_count, char(0));
1475 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1476 return result;
1477}
1478
Ian Rogers466bb252011-10-14 03:29:56 -07001479bool Throwable::IsCheckedException() const {
1480 Class* error = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Error;");
1481 if (InstanceOf(error)) {
1482 return false;
1483 }
1484 Class* jlre = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/RuntimeException;");
1485 return !InstanceOf(jlre);
1486}
1487
Ian Rogers9074b992011-10-26 17:41:55 -07001488std::string Throwable::Dump() const {
1489 Object* stack_state = GetStackState();
1490 if (stack_state == NULL || !stack_state->IsObjectArray()) {
1491 // missing or corrupt stack state
1492 return "";
1493 }
1494 // Decode the internal stack trace into the depth and method trace
1495 ObjectArray<Object>* method_trace = down_cast<ObjectArray<Object>*>(stack_state);
1496 int32_t depth = method_trace->GetLength() - 1;
1497 std::string result;
1498 for (int32_t i = 0; i < depth; ++i) {
1499 Method* method = down_cast<Method*>(method_trace->Get(i));
1500 result += " at ";
1501 result += PrettyMethod(method, true);
1502 result += "\n";
1503 }
1504 return result;
1505}
1506
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001507Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1508
1509void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1510 CHECK(java_lang_StackTraceElement_ == NULL);
1511 CHECK(java_lang_StackTraceElement != NULL);
1512 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1513}
1514
1515void StackTraceElement::ResetClass() {
1516 CHECK(java_lang_StackTraceElement_ != NULL);
1517 java_lang_StackTraceElement_ = NULL;
1518}
1519
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001520StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1521 const String* method_name,
1522 const String* file_name,
1523 int32_t line_number) {
1524 StackTraceElement* trace =
1525 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1526 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1527 const_cast<String*>(declaring_class), false);
1528 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1529 const_cast<String*>(method_name), false);
1530 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1531 const_cast<String*>(file_name), false);
1532 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1533 line_number, false);
1534 return trace;
1535}
1536
Elliott Hughes1f359b02011-07-17 14:27:17 -07001537static const char* kClassStatusNames[] = {
1538 "Error",
1539 "NotReady",
1540 "Idx",
1541 "Loaded",
1542 "Resolved",
1543 "Verifying",
1544 "Verified",
1545 "Initializing",
1546 "Initialized"
1547};
1548std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1549 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001550 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001551 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001552 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001553 }
1554 return os;
1555}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001556
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001557} // namespace art