blob: 91328aaccb0b5aa8e963da13bacab8a782d6749a [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 Rogers0cfe1fb2011-08-26 03:29:44 -0700130Class* Field::GetType() const {
Elliott Hughes80609252011-09-23 17:24:51 -0700131 if (type_ == NULL) {
132 type_ = Runtime::Current()->GetClassLinker()->ResolveType(GetTypeIdx(), this);
133 }
134 return type_;
135}
136
137void Field::InitJavaFields() {
138 Thread* self = Thread::Current();
139 ScopedThreadStateChange tsc(self, Thread::kRunnable);
140 MonitorEnter(self);
141 if (type_ == NULL) {
142 InitJavaFieldsLocked();
143 }
144 MonitorExit(self);
145}
146
147void Field::InitJavaFieldsLocked() {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700148 GetType(); // Resolves type as a side-effect. May throw.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700149}
150
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700151uint32_t Field::Get32(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700152 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700153 if (IsStatic()) {
154 object = declaring_class_;
155 }
156 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700157}
158
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700159void Field::Set32(Object* object, uint32_t new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700160 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700161 if (IsStatic()) {
162 object = declaring_class_;
163 }
164 object->SetField32(GetOffset(), new_value, IsVolatile());
165}
166
167uint64_t Field::Get64(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700168 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700169 if (IsStatic()) {
170 object = declaring_class_;
171 }
172 return object->GetField64(GetOffset(), IsVolatile());
173}
174
175void Field::Set64(Object* object, uint64_t new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700176 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700177 if (IsStatic()) {
178 object = declaring_class_;
179 }
180 object->SetField64(GetOffset(), new_value, IsVolatile());
181}
182
183Object* Field::GetObj(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700184 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700185 if (IsStatic()) {
186 object = declaring_class_;
187 }
188 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
189}
190
191void Field::SetObj(Object* object, const Object* new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700192 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700193 if (IsStatic()) {
194 object = declaring_class_;
195 }
196 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
197}
198
199bool Field::GetBoolean(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700200 DCHECK(GetPrimitiveType() == Primitive::kPrimBoolean) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700201 return Get32(object);
202}
203
204void Field::SetBoolean(Object* object, bool z) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700205 DCHECK(GetPrimitiveType() == Primitive::kPrimBoolean) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700206 Set32(object, z);
207}
208
209int8_t Field::GetByte(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700210 DCHECK(GetPrimitiveType() == Primitive::kPrimByte) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700211 return Get32(object);
212}
213
214void Field::SetByte(Object* object, int8_t b) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700215 DCHECK(GetPrimitiveType() == Primitive::kPrimByte) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700216 Set32(object, b);
217}
218
219uint16_t Field::GetChar(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700220 DCHECK(GetPrimitiveType() == Primitive::kPrimChar) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700221 return Get32(object);
222}
223
224void Field::SetChar(Object* object, uint16_t c) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700225 DCHECK(GetPrimitiveType() == Primitive::kPrimChar) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700226 Set32(object, c);
227}
228
Ian Rogers466bb252011-10-14 03:29:56 -0700229int16_t Field::GetShort(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700230 DCHECK(GetPrimitiveType() == Primitive::kPrimShort) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700231 return Get32(object);
232}
233
Ian Rogers466bb252011-10-14 03:29:56 -0700234void Field::SetShort(Object* object, int16_t s) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700235 DCHECK(GetPrimitiveType() == Primitive::kPrimShort) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700236 Set32(object, s);
237}
238
239int32_t Field::GetInt(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700240 DCHECK(GetPrimitiveType() == Primitive::kPrimInt) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700241 return Get32(object);
242}
243
244void Field::SetInt(Object* object, int32_t i) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700245 DCHECK(GetPrimitiveType() == Primitive::kPrimInt) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700246 Set32(object, i);
247}
248
249int64_t Field::GetLong(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700250 DCHECK(GetPrimitiveType() == Primitive::kPrimLong) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700251 return Get64(object);
252}
253
254void Field::SetLong(Object* object, int64_t j) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700255 DCHECK(GetPrimitiveType() == Primitive::kPrimLong) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700256 Set64(object, j);
257}
258
259float Field::GetFloat(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700260 DCHECK(GetPrimitiveType() == Primitive::kPrimFloat) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700261 JValue float_bits;
262 float_bits.i = Get32(object);
263 return float_bits.f;
264}
265
266void Field::SetFloat(Object* object, float f) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700267 DCHECK(GetPrimitiveType() == Primitive::kPrimFloat) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700268 JValue float_bits;
269 float_bits.f = f;
270 Set32(object, float_bits.i);
271}
272
273double Field::GetDouble(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700274 DCHECK(GetPrimitiveType() == Primitive::kPrimDouble) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275 JValue double_bits;
276 double_bits.j = Get64(object);
277 return double_bits.d;
278}
279
280void Field::SetDouble(Object* object, double d) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700281 DCHECK(GetPrimitiveType() == Primitive::kPrimDouble) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700282 JValue double_bits;
283 double_bits.d = d;
284 Set64(object, double_bits.j);
285}
286
287Object* Field::GetObject(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700288 CHECK(GetPrimitiveType() == Primitive::kPrimNot) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289 return GetObj(object);
290}
291
292void Field::SetObject(Object* object, const Object* l) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700293 CHECK(GetPrimitiveType() == Primitive::kPrimNot) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294 SetObj(object, l);
295}
296
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700297bool Method::IsClassInitializer() const {
298 return IsStatic() && GetName()->Equals("<clinit>");
299}
300
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301// TODO: get global references for these
Elliott Hughes80609252011-09-23 17:24:51 -0700302Class* Method::java_lang_reflect_Constructor_ = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303Class* Method::java_lang_reflect_Method_ = NULL;
304
Elliott Hughes80609252011-09-23 17:24:51 -0700305void Method::SetClasses(Class* java_lang_reflect_Constructor, Class* java_lang_reflect_Method) {
306 CHECK(java_lang_reflect_Constructor_ == NULL);
307 CHECK(java_lang_reflect_Constructor != NULL);
308 java_lang_reflect_Constructor_ = java_lang_reflect_Constructor;
309
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700310 CHECK(java_lang_reflect_Method_ == NULL);
311 CHECK(java_lang_reflect_Method != NULL);
312 java_lang_reflect_Method_ = java_lang_reflect_Method;
313}
314
Elliott Hughes80609252011-09-23 17:24:51 -0700315void Method::ResetClasses() {
316 CHECK(java_lang_reflect_Constructor_ != NULL);
317 java_lang_reflect_Constructor_ = NULL;
318
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700319 CHECK(java_lang_reflect_Method_ != NULL);
320 java_lang_reflect_Method_ = NULL;
321}
322
Elliott Hughes418d20f2011-09-22 14:00:39 -0700323Class* ExtractNextClassFromSignature(ClassLinker* class_linker, const ClassLoader* cl, const char*& p) {
324 if (*p == '[') {
325 // Something like "[[[Ljava/lang/String;".
326 const char* start = p;
327 while (*p == '[') {
328 ++p;
329 }
330 if (*p == 'L') {
331 while (*p != ';') {
332 ++p;
333 }
334 }
335 ++p; // Either the ';' or the primitive type.
336
Brian Carlstromaded5f72011-10-07 17:15:04 -0700337 std::string descriptor(start, (p - start));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700338 return class_linker->FindClass(descriptor, cl);
339 } else if (*p == 'L') {
340 const char* start = p;
341 while (*p != ';') {
342 ++p;
343 }
344 ++p;
345 StringPiece descriptor(start, (p - start));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700346 return class_linker->FindClass(descriptor.ToString(), cl);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700347 } else {
348 return class_linker->FindPrimitiveClass(*p++);
349 }
350}
351
352void Method::InitJavaFieldsLocked() {
353 // Create the array.
354 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
355 size_t arg_count = GetShorty()->GetLength() - 1;
356 Class* array_class = class_linker->FindSystemClass("[Ljava/lang/Class;");
357 ObjectArray<Class>* parameters = ObjectArray<Class>::Alloc(array_class, arg_count);
358 if (parameters == NULL) {
359 return;
360 }
361
362 // Parse the signature, filling the array.
363 const ClassLoader* cl = GetDeclaringClass()->GetClassLoader();
364 std::string signature(GetSignature()->ToModifiedUtf8());
365 const char* p = signature.c_str();
366 DCHECK_EQ(*p, '(');
367 ++p;
368 for (size_t i = 0; i < arg_count; ++i) {
369 Class* c = ExtractNextClassFromSignature(class_linker, cl, p);
370 if (c == NULL) {
371 return;
372 }
373 parameters->Set(i, c);
374 }
375
376 DCHECK_EQ(*p, ')');
377 ++p;
378
379 java_parameter_types_ = parameters;
380 java_return_type_ = ExtractNextClassFromSignature(class_linker, cl, p);
381}
382
383void Method::InitJavaFields() {
384 Thread* self = Thread::Current();
385 ScopedThreadStateChange tsc(self, Thread::kRunnable);
386 MonitorEnter(self);
387 if (java_parameter_types_ == NULL || java_return_type_ == NULL) {
388 InitJavaFieldsLocked();
389 }
390 MonitorExit(self);
391}
392
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393ObjectArray<String>* Method::GetDexCacheStrings() const {
394 return GetFieldObject<ObjectArray<String>*>(
395 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
396}
397
398void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
399 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
400 new_return_type_idx, false);
401}
402
403Class* Method::GetReturnType() const {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700404 DCHECK(GetDeclaringClass()->IsResolved() || GetDeclaringClass()->IsErroneous())
405 << PrettyMethod(this);
Jesse Wilsond81cdcc2011-10-17 14:36:48 -0400406 Class* java_return_type = java_return_type_;
407 if (java_return_type != NULL) {
408 return java_return_type;
409 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410 // Short-cut
411 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
412 if (result == NULL) {
413 // Do full linkage and set cache value for next call
414 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
415 }
Elliott Hughes14134a12011-09-30 16:55:51 -0700416 CHECK(result != NULL) << PrettyMethod(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700417 return result;
418}
419
420void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
421 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
422 new_dex_cache_strings, false);
423}
424
425ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
426 return GetFieldObject<ObjectArray<Class>*>(
427 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
428}
429
430void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
431 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
432 new_dex_cache_classes, false);
433}
434
435ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
436 return GetFieldObject<ObjectArray<Method>*>(
437 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
438}
439
440void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
441 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
442 new_dex_cache_methods, false);
443}
444
445ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
446 return GetFieldObject<ObjectArray<Field>*>(
447 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
448}
449
450void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
451 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
452 new_dex_cache_fields, false);
453}
454
455CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
456 return GetFieldPtr<CodeAndDirectMethods*>(
457 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
458 false);
459}
460
461void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
462 SetFieldPtr<CodeAndDirectMethods*>(
463 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
464 new_value, false);
465}
466
467ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
468 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
469 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
470 false);
471}
472
473void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700474 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475 new_value, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476}
477
478size_t Method::NumArgRegisters(const StringPiece& shorty) {
479 CHECK_LE(1, shorty.length());
480 uint32_t num_registers = 0;
481 for (int i = 1; i < shorty.length(); ++i) {
482 char ch = shorty[i];
483 if (ch == 'D' || ch == 'J') {
484 num_registers += 2;
485 } else {
486 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700487 }
488 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700489 return num_registers;
490}
491
492size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700493 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700494 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700495 for (int i = 1; i < shorty->GetLength(); ++i) {
496 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700497 if (ch == 'D' || ch == 'J') {
498 num_bytes += 8;
499 } else if (ch == 'L') {
500 // Argument is a reference or an array. The shorty descriptor
501 // does not distinguish between these types.
502 num_bytes += sizeof(Object*);
503 } else {
504 num_bytes += 4;
505 }
506 }
507 return num_bytes;
508}
509
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700510size_t Method::NumArgs() const {
511 // "1 +" because the first in Args is the receiver.
512 // "- 1" because we don't count the return type.
513 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
514}
515
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516// The number of reference arguments to this method including implicit this
517// pointer
518size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700519 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700520 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700521 for (int i = 1; i < shorty->GetLength(); i++) {
522 char ch = shorty->CharAt(i);
523 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700524 result++;
525 }
526 }
527 return result;
528}
529
530// The number of long or double arguments
531size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700532 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700533 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700534 for (int i = 1; i < shorty->GetLength(); i++) {
535 char ch = shorty->CharAt(i);
536 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700537 result++;
538 }
539 }
540 return result;
541}
542
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700543// Is the given method parameter a reference?
544bool Method::IsParamAReference(unsigned int param) const {
545 CHECK_LT(param, NumArgs());
546 if (IsStatic()) {
547 param++; // 0th argument must skip return value at start of the shorty
548 } else if (param == 0) {
549 return true; // this argument
550 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700551 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700552}
553
554// Is the given method parameter a long or double?
555bool Method::IsParamALongOrDouble(unsigned int param) const {
556 CHECK_LT(param, NumArgs());
557 if (IsStatic()) {
558 param++; // 0th argument must skip return value at start of the shorty
559 } else if (param == 0) {
560 return false; // this argument
561 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700562 char ch = GetShorty()->CharAt(param);
563 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700564}
565
566static size_t ShortyCharToSize(char x) {
567 switch (x) {
568 case 'V': return 0;
569 case '[': return kPointerSize;
570 case 'L': return kPointerSize;
571 case 'D': return 8;
572 case 'J': return 8;
573 default: return 4;
574 }
575}
576
577size_t Method::ParamSize(unsigned int param) const {
578 CHECK_LT(param, NumArgs());
579 if (IsStatic()) {
580 param++; // 0th argument must skip return value at start of the shorty
581 } else if (param == 0) {
582 return kPointerSize; // this argument
583 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700584 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700585}
586
587size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700588 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700589}
590
Ian Rogers466bb252011-10-14 03:29:56 -0700591Method* Method::FindOverriddenMethod() const {
592 if (IsStatic()) {
593 return NULL;
594 }
595 Class* declaring_class = GetDeclaringClass();
596 Class* super_class = declaring_class->GetSuperClass();
597 uint16_t method_index = GetMethodIndex();
598 ObjectArray<Method>* super_class_vtable = super_class->GetVTable();
599 Method* result = NULL;
600 if (super_class_vtable != NULL && method_index < super_class_vtable->GetLength()) {
601 result = super_class_vtable->Get(method_index);
602 } else {
603 ObjectArray<Class>* interfaces = declaring_class->GetInterfaces();
604 String* name = GetName();
605 String* signature = GetSignature();
606 for (int32_t i = 0; i < interfaces->GetLength() && result == NULL; i++) {
607 Class* interface = interfaces->Get(i);
608 result = interface->FindInterfaceMethod(name, signature);
609 }
610 }
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700611 DCHECK(result == NULL || HasSameNameAndSignature(result));
Ian Rogers466bb252011-10-14 03:29:56 -0700612 return result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700613}
614
Ian Rogersbdb03912011-09-14 00:55:44 -0700615uint32_t Method::ToDexPC(const uintptr_t pc) const {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700616 const uint32_t* mapping_table = GetMappingTable();
Ian Rogersbdb03912011-09-14 00:55:44 -0700617 if (mapping_table == NULL) {
Brian Carlstrom26c935a2011-10-16 14:52:35 -0700618 DCHECK(IsNative() || IsCalleeSaveMethod()) << PrettyMethod(this);
Ian Rogers67375ac2011-09-14 00:55:44 -0700619 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700620 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700621 size_t mapping_table_length = GetMappingTableLength();
Ian Rogersbdb03912011-09-14 00:55:44 -0700622 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
Ian Rogersbdb03912011-09-14 00:55:44 -0700623 uint32_t best_offset = 0;
624 uint32_t best_dex_offset = 0;
625 for (size_t i = 0; i < mapping_table_length; i += 2) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700626 uint32_t map_offset = mapping_table[i];
627 uint32_t map_dex_offset = mapping_table[i + 1];
Ian Rogersbdb03912011-09-14 00:55:44 -0700628 if (map_offset == sought_offset) {
629 best_offset = map_offset;
630 best_dex_offset = map_dex_offset;
631 break;
632 }
633 if (map_offset < sought_offset && map_offset > best_offset) {
634 best_offset = map_offset;
635 best_dex_offset = map_dex_offset;
636 }
637 }
638 return best_dex_offset;
639}
640
641uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700642 const uint32_t* mapping_table = GetMappingTable();
Ian Rogersbdb03912011-09-14 00:55:44 -0700643 if (mapping_table == NULL) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700644 DCHECK_EQ(dex_pc, 0U);
Ian Rogersbdb03912011-09-14 00:55:44 -0700645 return 0; // Special no mapping/pc == 0 case
646 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700647 size_t mapping_table_length = GetMappingTableLength();
Ian Rogersbdb03912011-09-14 00:55:44 -0700648 for (size_t i = 0; i < mapping_table_length; i += 2) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700649 uint32_t map_offset = mapping_table[i];
650 uint32_t map_dex_offset = mapping_table[i + 1];
Ian Rogersbdb03912011-09-14 00:55:44 -0700651 if (map_dex_offset == dex_pc) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700652 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
653 }
654 }
655 LOG(FATAL) << "Looking up Dex PC not contained in method";
656 return 0;
657}
658
659uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
660 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
661 const ClassLoader* class_loader = GetDeclaringClass()->GetClassLoader();
662 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
663 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
664 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
665 // Iterate over the catch handlers associated with dex_pc
666 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
667 !iter.HasNext(); iter.Next()) {
668 uint32_t iter_type_idx = iter.Get().type_idx_;
669 // Catch all case
Elliott Hughes80609252011-09-23 17:24:51 -0700670 if (iter_type_idx == DexFile::kDexNoIndex) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700671 return iter.Get().address_;
672 }
673 // Does this catch exception type apply?
674 Class* iter_exception_type =
675 class_linker->ResolveType(dex_file, iter_type_idx, dex_cache, class_loader);
676 if (iter_exception_type->IsAssignableFrom(exception_type)) {
677 return iter.Get().address_;
678 }
679 }
680 // Handler not found
681 return DexFile::kDexNoIndex;
682}
683
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700684void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
685 // Push a transition back into managed code onto the linked list in thread.
686 CHECK_EQ(Thread::kRunnable, self->GetState());
687 NativeToManagedRecord record;
688 self->PushNativeToManagedRecord(&record);
689
690 // Call the invoke stub associated with the method.
691 // Pass everything as arguments.
692 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700693
694 bool have_executable_code = (GetCode() != NULL);
695#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700696 // Currently we can only compile non-native methods for ARM.
697 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700698#endif
699
700 if (have_executable_code && stub != NULL) {
Elliott Hughes9f865372011-10-11 15:04:19 -0700701 bool log = false;
702 if (log) {
703 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
704 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700705 (*stub)(this, receiver, self, args, result);
Elliott Hughes9f865372011-10-11 15:04:19 -0700706 if (log) {
707 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
708 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700709 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700710 if (Runtime::Current()->IsStarted()) {
711 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
712 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700713 if (result != NULL) {
714 result->j = 0;
715 }
716 }
717
718 // Pop transition.
719 self->PopNativeToManagedRecord(record);
720}
721
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700722bool Method::IsRegistered() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700723 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
724 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
725 return native_method != jni_stub;
726}
727
728void Method::RegisterNative(const void* native_method) {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700729 CHECK(IsNative()) << PrettyMethod(this);
730 CHECK(native_method != NULL) << PrettyMethod(this);
Brian Carlstrom16192862011-09-12 17:50:06 -0700731 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
732 native_method, false);
733}
734
735void Method::UnregisterNative() {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700736 CHECK(IsNative()) << PrettyMethod(this);
Brian Carlstrom16192862011-09-12 17:50:06 -0700737 // restore stub to lookup native pointer via dlsym
738 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
739}
740
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700741void Class::SetStatus(Status new_status) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700742 CHECK(new_status > GetStatus() || new_status == kStatusError || !Runtime::Current()->IsStarted())
743 << PrettyClass(this) << " " << GetStatus() << " -> " << new_status;
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700744 CHECK(sizeof(Status) == sizeof(uint32_t)) << PrettyClass(this);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700745 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700746}
747
748DexCache* Class::GetDexCache() const {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700749 return GetFieldObject<DexCache*>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700750}
751
752void Class::SetDexCache(DexCache* new_dex_cache) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700753 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700754}
755
Brian Carlstrom1f870082011-08-23 16:02:11 -0700756Object* Class::AllocObject() {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700757 DCHECK(!IsAbstract()) << PrettyClass(this);
758 DCHECK(!IsInterface()) << PrettyClass(this);
759 DCHECK(!IsPrimitive()) << PrettyClass(this);
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700760 DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700761 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700762}
763
Elliott Hughes4681c802011-09-25 18:04:37 -0700764void Class::DumpClass(std::ostream& os, int flags) const {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700765 if ((flags & kDumpClassFullDetail) == 0) {
766 os << PrettyClass(this);
767 if ((flags & kDumpClassClassLoader) != 0) {
768 os << ' ' << GetClassLoader();
769 }
770 if ((flags & kDumpClassInitialized) != 0) {
771 os << ' ' << GetStatus();
772 }
773 os << std::endl;
774 return;
775 }
776
777 Class* super = GetSuperClass();
778 os << "----- " << (IsInterface() ? "interface" : "class") << " "
779 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
780 os << " objectSize=" << SizeOf() << " "
781 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
782 os << StringPrintf(" access=0x%04x.%04x\n",
783 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
784 if (super != NULL) {
785 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
786 }
787 if (IsArrayClass()) {
788 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
789 }
790 if (NumInterfaces() > 0) {
791 os << " interfaces (" << NumInterfaces() << "):\n";
792 for (size_t i = 0; i < NumInterfaces(); ++i) {
793 Class* interface = GetInterface(i);
794 const ClassLoader* cl = interface->GetClassLoader();
795 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
796 }
797 }
798 os << " vtable (" << NumVirtualMethods() << " entries, "
799 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
800 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700801 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethodDuringLinking(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700802 }
803 os << " direct methods (" << NumDirectMethods() << " entries):\n";
804 for (size_t i = 0; i < NumDirectMethods(); ++i) {
805 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
806 }
807 if (NumStaticFields() > 0) {
808 os << " static fields (" << NumStaticFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700809 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700810 for (size_t i = 0; i < NumStaticFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700811 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700812 }
813 } else {
814 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700815 }
816 }
817 if (NumInstanceFields() > 0) {
818 os << " instance fields (" << NumInstanceFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700819 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700820 for (size_t i = 0; i < NumInstanceFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700821 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700822 }
823 } else {
824 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700825 }
826 }
827}
828
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700829void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
830 if (new_reference_offsets != CLASS_WALK_SUPER) {
831 // Sanity check that the number of bits set in the reference offset bitmap
832 // agrees with the number of references
833 Class* cur = this;
834 size_t cnt = 0;
835 while (cur) {
836 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
837 cur = cur->GetSuperClass();
838 }
839 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
840 }
841 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
842 new_reference_offsets, false);
843}
844
845void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
846 if (new_reference_offsets != CLASS_WALK_SUPER) {
847 // Sanity check that the number of bits set in the reference offset bitmap
848 // agrees with the number of references
849 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
850 NumReferenceStaticFieldsDuringLinking());
851 }
852 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
853 new_reference_offsets, false);
854}
855
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700856bool Class::Implements(const Class* klass) const {
857 DCHECK(klass != NULL);
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700858 DCHECK(klass->IsInterface()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700859 // All interfaces implemented directly and by our superclass, and
860 // recursively all super-interfaces of those interfaces, are listed
861 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700862 int32_t iftable_count = GetIfTableCount();
863 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
864 for (int32_t i = 0; i < iftable_count; i++) {
865 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700866 return true;
867 }
868 }
869 return false;
870}
871
872// Determine whether "this" is assignable from "klazz", where both of these
873// are array classes.
874//
875// Consider an array class, e.g. Y[][], where Y is a subclass of X.
876// Y[][] = Y[][] --> true (identity)
877// X[][] = Y[][] --> true (element superclass)
878// Y = Y[][] --> false
879// Y[] = Y[][] --> false
880// Object = Y[][] --> true (everything is an object)
881// Object[] = Y[][] --> true
882// Object[][] = Y[][] --> true
883// Object[][][] = Y[][] --> false (too many []s)
884// Serializable = Y[][] --> true (all arrays are Serializable)
885// Serializable[] = Y[][] --> true
886// Serializable[][] = Y[][] --> false (unless Y is Serializable)
887//
888// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700889// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700890//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700891bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700892 DCHECK(IsArrayClass()) << PrettyClass(this);
893 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700894 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700895}
896
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700897bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700898 DCHECK(!IsInterface()) << PrettyClass(this); // handled first in IsAssignableFrom
899 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700900 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700901 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700902 // src's super should be java_lang_Object, since it is an array.
903 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700904 DCHECK(java_lang_Object != NULL) << PrettyClass(src);
905 DCHECK(java_lang_Object->GetSuperClass() == NULL) << PrettyClass(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700906 return this == java_lang_Object;
907 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700908 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700909}
910
911bool Class::IsSubClass(const Class* klass) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700912 DCHECK(!IsInterface()) << PrettyClass(this);
913 DCHECK(!IsArrayClass()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700914 const Class* current = this;
915 do {
916 if (current == klass) {
917 return true;
918 }
919 current = current->GetSuperClass();
920 } while (current != NULL);
921 return false;
922}
923
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700924bool Class::IsInSamePackage(const String* descriptor_string_1,
925 const String* descriptor_string_2) {
926 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
927 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
928
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700929 size_t i = 0;
930 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
931 ++i;
932 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700933 if (descriptor1.find('/', i) != StringPiece::npos ||
934 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700935 return false;
936 } else {
937 return true;
938 }
939}
940
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700941#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700942bool Class::IsInSamePackage(const StringPiece& descriptor1,
943 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700944 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700945 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700946 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
947 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700948 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
949}
950#endif
951
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700952bool Class::IsInSamePackage(const Class* that) const {
953 const Class* klass1 = this;
954 const Class* klass2 = that;
955 if (klass1 == klass2) {
956 return true;
957 }
958 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700959 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700960 return false;
961 }
962 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -0700963 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700964 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700965 }
jeffhao4a801a42011-09-23 13:53:40 -0700966 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700967 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700968 }
969 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700970 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700971}
972
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700973const ClassLoader* Class::GetClassLoader() const {
Ian Rogersd81871c2011-10-03 13:57:23 -0700974 return GetFieldObject<const ClassLoader*>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -0700975}
976
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700977void Class::SetClassLoader(const ClassLoader* new_cl) {
978 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
Ian Rogersd81871c2011-10-03 13:57:23 -0700979 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700980}
981
Ian Rogersb04f69f2011-10-17 00:40:54 -0700982Method* Class::FindVirtualMethodForInterface(Method* method, bool can_throw) {
Brian Carlstrom30b94452011-08-25 21:35:26 -0700983 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700984 DCHECK(declaring_class != NULL) << PrettyClass(this);
985 DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700986 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700987 int32_t iftable_count = GetIfTableCount();
988 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
989 for (int32_t i = 0; i < iftable_count; i++) {
990 InterfaceEntry* interface_entry = iftable->Get(i);
991 if (interface_entry->GetInterface() == declaring_class) {
992 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -0700993 }
994 }
Ian Rogersb04f69f2011-10-17 00:40:54 -0700995 if (can_throw) {
996 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
997 "Class %s does not implement interface %s",
998 PrettyDescriptor(GetDescriptor()).c_str(),
999 PrettyDescriptor(declaring_class->GetDescriptor()).c_str());
1000 }
Brian Carlstrom30b94452011-08-25 21:35:26 -07001001 return NULL;
1002}
1003
Ian Rogers466bb252011-10-14 03:29:56 -07001004Method* Class::FindInterfaceMethod(const StringPiece& name, const StringPiece& signature) const {
jeffhaobdb76512011-09-07 11:43:16 -07001005 // Check the current class before checking the interfaces.
1006 Method* method = FindVirtualMethod(name, signature);
1007 if (method != NULL) {
1008 return method;
1009 }
1010
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001011 int32_t iftable_count = GetIfTableCount();
1012 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1013 for (int32_t i = 0; i < iftable_count; i++) {
1014 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001015 if (method != NULL) {
1016 return method;
1017 }
1018 }
1019 return NULL;
1020}
1021
Ian Rogers466bb252011-10-14 03:29:56 -07001022Method* Class::FindInterfaceMethod(String* name, String* signature) const {
1023 // Check the current class before checking the interfaces.
1024 Method* method = FindVirtualMethod(name, signature);
1025 if (method != NULL) {
1026 return method;
1027 }
1028 int32_t iftable_count = GetIfTableCount();
1029 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1030 for (int32_t i = 0; i < iftable_count; i++) {
1031 Class* interface = iftable->Get(i)->GetInterface();
1032 method = interface->FindVirtualMethod(name, signature);
1033 if (method != NULL) {
1034 return method;
1035 }
1036 }
1037 return NULL;
1038}
1039
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001040Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001041 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001042 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001043 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001044 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001045 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001046 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001047 }
1048 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001049 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001050}
1051
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001052Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001053 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001054 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001055 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001056 if (method != NULL) {
1057 return method;
1058 }
1059 }
1060 return NULL;
1061}
1062
1063Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Ian Rogers466bb252011-10-14 03:29:56 -07001064 const StringPiece& signature) const {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001065 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001066 Method* method = GetVirtualMethod(i);
Ian Rogers466bb252011-10-14 03:29:56 -07001067 if (method->GetName()->Equals(name) && method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001068 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001069 }
1070 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001071 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001072}
1073
Ian Rogers466bb252011-10-14 03:29:56 -07001074Method* Class::FindDeclaredVirtualMethod(String* name, String* signature) const {
1075 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
1076 Method* method = GetVirtualMethod(i);
1077 if (method->GetName() == name && method->GetSignature() == signature) {
1078 return method;
Ian Rogers466bb252011-10-14 03:29:56 -07001079 }
1080 }
1081 return NULL;
1082}
1083
1084Method* Class::FindVirtualMethod(const StringPiece& name, const StringPiece& signature) const {
1085 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1086 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
1087 if (method != NULL) {
1088 return method;
1089 }
1090 }
1091 return NULL;
1092}
1093
1094Method* Class::FindVirtualMethod(String* name, String* signature) const {
1095 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07001096 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001097 if (method != NULL) {
1098 return method;
1099 }
1100 }
1101 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001102}
1103
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001104Field* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001105 // Is the field in this class?
1106 // Interfaces are not relevant because they can't contain instance fields.
1107 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1108 Field* f = GetInstanceField(i);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001109 if (f->GetName()->Equals(name) &&
1110 StringPiece(f->GetTypeDescriptor()) == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001111 return f;
1112 }
1113 }
1114 return NULL;
1115}
1116
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001117Field* Class::FindDeclaredInstanceField(String* name, String* type) {
1118 // Is the field in this class?
1119 // Interfaces are not relevant because they can't contain instance fields.
1120 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1121 Field* f = GetInstanceField(i);
1122 if (f->GetName() == name && type->Equals(f->GetTypeDescriptor())) {
1123 return f;
1124 }
1125 }
1126 return NULL;
1127}
1128
1129Field* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001130 // Is the field in this class, or any of its superclasses?
1131 // Interfaces are not relevant because they can't contain instance fields.
1132 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001133 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001134 if (f != NULL) {
1135 return f;
1136 }
1137 }
1138 return NULL;
1139}
1140
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001141Field* Class::FindInstanceField(String* name, String* type) {
1142 // Is the field in this class, or any of its superclasses?
1143 // Interfaces are not relevant because they can't contain instance fields.
1144 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1145 Field* f = c->FindDeclaredInstanceField(name, type);
1146 if (f != NULL) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001147 return f;
1148 }
1149 }
1150 return NULL;
1151}
1152
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001153Field* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
1154 DCHECK(type != NULL);
1155 for (size_t i = 0; i < NumStaticFields(); ++i) {
1156 Field* f = GetStaticField(i);
1157 if (f->GetName()->Equals(name) && StringPiece(f->GetTypeDescriptor()) == type) {
1158 return f;
1159 }
1160 }
1161 return NULL;
1162}
1163
1164Field* Class::FindDeclaredStaticField(String* name, String* type) {
1165 DCHECK(type != NULL);
1166 for (size_t i = 0; i < NumStaticFields(); ++i) {
1167 Field* f = GetStaticField(i);
1168 if (f->GetName() == name && type->Equals(f->GetTypeDescriptor())) {
1169 return f;
1170 }
1171 }
1172 return NULL;
1173}
1174
1175Field* Class::FindStaticField(const StringPiece& name, const StringPiece& type) {
1176 // Is the field in this class (or its interfaces), or any of its
1177 // superclasses (or their interfaces)?
1178 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1179 // Is the field in this class?
1180 Field* f = c->FindDeclaredStaticField(name, type);
1181 if (f != NULL) {
1182 return f;
1183 }
1184
1185 // Is this field in any of this class' interfaces?
1186 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1187 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1188 Class* interface = interface_entry->GetInterface();
1189 f = interface->FindDeclaredStaticField(name, type);
1190 if (f != NULL) {
1191 return f;
1192 }
1193 }
1194 }
1195 return NULL;
1196}
1197
1198Field* Class::FindStaticField(String* name, String* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001199 // Is the field in this class (or its interfaces), or any of its
1200 // superclasses (or their interfaces)?
1201 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1202 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001203 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001204 if (f != NULL) {
1205 return f;
1206 }
1207
1208 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001209 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1210 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1211 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001212 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001213 if (f != NULL) {
1214 return f;
1215 }
1216 }
1217 }
1218 return NULL;
1219}
1220
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001221Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001222 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001223 DCHECK_GE(component_count, 0);
1224 DCHECK(array_class->IsArrayClass());
Elliott Hughesb408de72011-10-04 14:35:05 -07001225
1226 size_t header_size = sizeof(Array);
1227 size_t data_size = component_count * component_size;
1228 size_t size = header_size + data_size;
1229
1230 // Check for overflow and throw OutOfMemoryError if this was an unreasonable request.
1231 size_t component_shift = sizeof(size_t) * 8 - 1 - CLZ(component_size);
1232 if (data_size >> component_shift != size_t(component_count) || size < data_size) {
1233 Thread::Current()->ThrowNewExceptionF("Ljava/lang/OutOfMemoryError;",
1234 "%s of length %zd exceeds the VM limit",
1235 PrettyDescriptor(array_class->GetDescriptor()).c_str(), component_count);
1236 return NULL;
1237 }
1238
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001239 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1240 if (array != NULL) {
1241 DCHECK(array->IsArrayInstance());
1242 array->SetLength(component_count);
1243 }
1244 return array;
1245}
1246
1247Array* Array::Alloc(Class* array_class, int32_t component_count) {
1248 return Alloc(array_class, component_count, array_class->GetComponentSize());
1249}
1250
Elliott Hughes80609252011-09-23 17:24:51 -07001251bool Array::ThrowArrayIndexOutOfBoundsException(int32_t index) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001252 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001253 "length=%i; index=%i", length_, index);
1254 return false;
1255}
1256
1257bool Array::ThrowArrayStoreException(Object* object) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001258 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001259 "Can't store an element of type %s into an array of type %s",
1260 PrettyTypeOf(object).c_str(), PrettyTypeOf(this).c_str());
1261 return false;
1262}
1263
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001264template<typename T>
1265PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001266 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001267 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1268 return down_cast<PrimitiveArray<T>*>(raw_array);
1269}
1270
1271template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1272
1273// Explicitly instantiate all the primitive array types.
1274template class PrimitiveArray<uint8_t>; // BooleanArray
1275template class PrimitiveArray<int8_t>; // ByteArray
1276template class PrimitiveArray<uint16_t>; // CharArray
1277template class PrimitiveArray<double>; // DoubleArray
1278template class PrimitiveArray<float>; // FloatArray
1279template class PrimitiveArray<int32_t>; // IntArray
1280template class PrimitiveArray<int64_t>; // LongArray
1281template class PrimitiveArray<int16_t>; // ShortArray
1282
Ian Rogers466bb252011-10-14 03:29:56 -07001283// Explicitly instantiate Class[][]
1284template class ObjectArray<ObjectArray<Class> >;
1285
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001286// TODO: get global references for these
1287Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001288
Brian Carlstroma663ea52011-08-19 23:33:41 -07001289void String::SetClass(Class* java_lang_String) {
1290 CHECK(java_lang_String_ == NULL);
1291 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001292 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001293}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001294
Brian Carlstroma663ea52011-08-19 23:33:41 -07001295void String::ResetClass() {
1296 CHECK(java_lang_String_ != NULL);
1297 java_lang_String_ = NULL;
1298}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001299
Brian Carlstromc74255f2011-09-11 22:47:39 -07001300String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001301 return Runtime::Current()->GetInternTable()->InternWeak(this);
1302}
1303
Brian Carlstrom395520e2011-09-25 19:35:00 -07001304int32_t String::GetHashCode() {
1305 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1306 if (result == 0) {
1307 ComputeHashCode();
1308 }
1309 result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1310 DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
1311 << ToModifiedUtf8() << " " << result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001312 return result;
1313}
1314
1315int32_t String::GetLength() const {
1316 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1317 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1318 return result;
1319}
1320
1321uint16_t String::CharAt(int32_t index) const {
1322 // TODO: do we need this? Equals is the only caller, and could
1323 // bounds check itself.
1324 if (index < 0 || index >= count_) {
1325 Thread* self = Thread::Current();
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001326 self->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;",
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001327 "length=%i; index=%i", count_, index);
1328 return 0;
1329 }
1330 return GetCharArray()->Get(index + GetOffset());
1331}
1332
1333String* String::AllocFromUtf16(int32_t utf16_length,
1334 const uint16_t* utf16_data_in,
1335 int32_t hash_code) {
1336 String* string = Alloc(GetJavaLangString(), utf16_length);
Elliott Hughesb51036c2011-10-12 23:49:11 -07001337 if (string == NULL) {
1338 return NULL;
1339 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001340 // TODO: use 16-bit wide memset variant
1341 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
Elliott Hughesb51036c2011-10-12 23:49:11 -07001342 if (array == NULL) {
1343 return NULL;
1344 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001345 for (int i = 0; i < utf16_length; i++) {
1346 array->Set(i, utf16_data_in[i]);
1347 }
1348 if (hash_code != 0) {
1349 string->SetHashCode(hash_code);
1350 } else {
1351 string->ComputeHashCode();
1352 }
1353 return string;
1354}
1355
1356String* String::AllocFromModifiedUtf8(const char* utf) {
1357 size_t char_count = CountModifiedUtf8Chars(utf);
1358 return AllocFromModifiedUtf8(char_count, utf);
1359}
1360
1361String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1362 const char* utf8_data_in) {
1363 String* string = Alloc(GetJavaLangString(), utf16_length);
Elliott Hughesb51036c2011-10-12 23:49:11 -07001364 if (string == NULL) {
1365 return NULL;
1366 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001367 uint16_t* utf16_data_out =
1368 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1369 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1370 string->ComputeHashCode();
1371 return string;
1372}
1373
1374String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001375 SirtRef<CharArray> array(CharArray::Alloc(utf16_length));
1376 if (array.get() == NULL) {
Elliott Hughesb51036c2011-10-12 23:49:11 -07001377 return NULL;
1378 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001379 return Alloc(java_lang_String, array.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001380}
1381
1382String* String::Alloc(Class* java_lang_String, CharArray* array) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001383 SirtRef<CharArray> array_ref(array); // hold reference in case AllocObject causes GC
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001384 String* string = down_cast<String*>(java_lang_String->AllocObject());
Elliott Hughesb51036c2011-10-12 23:49:11 -07001385 if (string == NULL) {
1386 return NULL;
1387 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001388 string->SetArray(array);
1389 string->SetCount(array->GetLength());
1390 return string;
1391}
1392
1393bool String::Equals(const String* that) const {
1394 if (this == that) {
1395 // Quick reference equality test
1396 return true;
1397 } else if (that == NULL) {
1398 // Null isn't an instanceof anything
1399 return false;
1400 } else if (this->GetLength() != that->GetLength()) {
1401 // Quick length inequality test
1402 return false;
1403 } else {
Elliott Hughes20cde902011-10-04 17:37:27 -07001404 // Note: don't short circuit on hash code as we're presumably here as the
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001405 // hash code was already equal
1406 for (int32_t i = 0; i < that->GetLength(); ++i) {
1407 if (this->CharAt(i) != that->CharAt(i)) {
1408 return false;
1409 }
1410 }
1411 return true;
1412 }
1413}
1414
1415bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1416 int32_t that_length) const {
1417 if (this->GetLength() != that_length) {
1418 return false;
1419 } else {
1420 for (int32_t i = 0; i < that_length; ++i) {
1421 if (this->CharAt(i) != that_chars[that_offset + i]) {
1422 return false;
1423 }
1424 }
1425 return true;
1426 }
1427}
1428
1429bool String::Equals(const char* modified_utf8) const {
1430 for (int32_t i = 0; i < GetLength(); ++i) {
1431 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1432 if (ch == '\0' || ch != CharAt(i)) {
1433 return false;
1434 }
1435 }
1436 return *modified_utf8 == '\0';
1437}
1438
1439bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001440 if (modified_utf8.size() != GetLength()) {
1441 return false;
1442 }
1443 const char* p = modified_utf8.data();
1444 for (int32_t i = 0; i < GetLength(); ++i) {
1445 uint16_t ch = GetUtf16FromUtf8(&p);
1446 if (ch != CharAt(i)) {
1447 return false;
1448 }
1449 }
1450 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001451}
1452
1453// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1454std::string String::ToModifiedUtf8() const {
1455 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1456 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1457 std::string result(byte_count, char(0));
1458 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1459 return result;
1460}
1461
Ian Rogers466bb252011-10-14 03:29:56 -07001462bool Throwable::IsCheckedException() const {
1463 Class* error = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Error;");
1464 if (InstanceOf(error)) {
1465 return false;
1466 }
1467 Class* jlre = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/RuntimeException;");
1468 return !InstanceOf(jlre);
1469}
1470
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001471Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1472
1473void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1474 CHECK(java_lang_StackTraceElement_ == NULL);
1475 CHECK(java_lang_StackTraceElement != NULL);
1476 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1477}
1478
1479void StackTraceElement::ResetClass() {
1480 CHECK(java_lang_StackTraceElement_ != NULL);
1481 java_lang_StackTraceElement_ = NULL;
1482}
1483
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001484StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1485 const String* method_name,
1486 const String* file_name,
1487 int32_t line_number) {
1488 StackTraceElement* trace =
1489 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1490 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1491 const_cast<String*>(declaring_class), false);
1492 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1493 const_cast<String*>(method_name), false);
1494 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1495 const_cast<String*>(file_name), false);
1496 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1497 line_number, false);
1498 return trace;
1499}
1500
Elliott Hughes1f359b02011-07-17 14:27:17 -07001501static const char* kClassStatusNames[] = {
1502 "Error",
1503 "NotReady",
1504 "Idx",
1505 "Loaded",
1506 "Resolved",
1507 "Verifying",
1508 "Verified",
1509 "Initializing",
1510 "Initialized"
1511};
1512std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1513 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001514 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001515 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001516 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001517 }
1518 return os;
1519}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001520
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001521} // namespace art