blob: c43fe49c64fbcb3ad0644eab9e54d3623a5c683c [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();
33 Object* copy = Heap::AllocObject(c, num_bytes);
34 if (copy == NULL) {
35 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);
41 byte* dst_bytes = reinterpret_cast<byte*>(copy);
42 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()) {
Elliott Hughesadb460d2011-10-05 17:02:34 -070046 Heap::AddFinalizerReference(copy);
Elliott Hughes20cde902011-10-04 17:37:27 -070047 }
Elliott Hughes081be7f2011-09-18 16:50:26 -070048
49 return copy;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070050}
51
Elliott Hughes5f791332011-09-15 17:45:30 -070052uint32_t Object::GetLockOwner() {
53 return Monitor::GetLockOwner(monitor_);
54}
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
105Class* Field::GetType() const {
Elliott Hughes80609252011-09-23 17:24:51 -0700106 if (type_ == NULL) {
107 type_ = Runtime::Current()->GetClassLinker()->ResolveType(GetTypeIdx(), this);
108 }
109 return type_;
110}
111
112void Field::InitJavaFields() {
113 Thread* self = Thread::Current();
114 ScopedThreadStateChange tsc(self, Thread::kRunnable);
115 MonitorEnter(self);
116 if (type_ == NULL) {
117 InitJavaFieldsLocked();
118 }
119 MonitorExit(self);
120}
121
122void Field::InitJavaFieldsLocked() {
123 GetType(); // Sets type_ as a side-effect. May throw.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700124}
125
Brian Carlstrom845490b2011-09-19 15:56:53 -0700126Field* Field::FindInstanceFieldFromCode(uint32_t field_idx, const Method* referrer) {
127 return FindFieldFromCode(field_idx, referrer, false);
128}
129
130Field* Field::FindStaticFieldFromCode(uint32_t field_idx, const Method* referrer) {
131 return FindFieldFromCode(field_idx, referrer, true);
132}
133
134Field* Field::FindFieldFromCode(uint32_t field_idx, const Method* referrer, bool is_static) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700135 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom845490b2011-09-19 15:56:53 -0700136 Field* f = class_linker->ResolveField(field_idx, referrer, is_static);
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700137 if (f != NULL) {
138 Class* c = f->GetDeclaringClass();
139 // If the class is already initializing, we must be inside <clinit>, or
140 // we'd still be waiting for the lock.
Brian Carlstrom25c33252011-09-18 15:58:35 -0700141 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c, true)) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700142 return f;
143 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700144 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700145 UNIMPLEMENTED(FATAL) << "throw an error and unwind";
146 return NULL;
147}
148
149uint32_t Field::Get32StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700150 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700151 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
152 return field->Get32(NULL);
153}
154void Field::Set32StaticFromCode(uint32_t field_idx, const Method* referrer, uint32_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700155 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700156 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
157 field->Set32(NULL, new_value);
158}
159uint64_t Field::Get64StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700160 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700161 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
162 return field->Get64(NULL);
163}
164void Field::Set64StaticFromCode(uint32_t field_idx, const Method* referrer, uint64_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700165 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700166 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
167 field->Set64(NULL, new_value);
168}
169Object* Field::GetObjStaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700170 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700171 DCHECK(!field->GetType()->IsPrimitive());
172 return field->GetObj(NULL);
173}
174void Field::SetObjStaticFromCode(uint32_t field_idx, const Method* referrer, Object* new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700175 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700176 DCHECK(!field->GetType()->IsPrimitive());
177 field->SetObj(NULL, new_value);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700178}
179
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700180uint32_t Field::Get32(const Object* object) const {
181 CHECK((object == NULL) == IsStatic());
182 if (IsStatic()) {
183 object = declaring_class_;
184 }
185 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700186}
187
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700188void Field::Set32(Object* object, uint32_t new_value) const {
189 CHECK((object == NULL) == IsStatic());
190 if (IsStatic()) {
191 object = declaring_class_;
192 }
193 object->SetField32(GetOffset(), new_value, IsVolatile());
194}
195
196uint64_t Field::Get64(const Object* object) const {
197 CHECK((object == NULL) == IsStatic());
198 if (IsStatic()) {
199 object = declaring_class_;
200 }
201 return object->GetField64(GetOffset(), IsVolatile());
202}
203
204void Field::Set64(Object* object, uint64_t new_value) const {
205 CHECK((object == NULL) == IsStatic());
206 if (IsStatic()) {
207 object = declaring_class_;
208 }
209 object->SetField64(GetOffset(), new_value, IsVolatile());
210}
211
212Object* Field::GetObj(const Object* object) const {
213 CHECK((object == NULL) == IsStatic());
214 if (IsStatic()) {
215 object = declaring_class_;
216 }
217 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
218}
219
220void Field::SetObj(Object* object, const Object* new_value) const {
221 CHECK((object == NULL) == IsStatic());
222 if (IsStatic()) {
223 object = declaring_class_;
224 }
225 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
226}
227
228bool Field::GetBoolean(const Object* object) const {
229 DCHECK(GetType()->IsPrimitiveBoolean());
230 return Get32(object);
231}
232
233void Field::SetBoolean(Object* object, bool z) const {
234 DCHECK(GetType()->IsPrimitiveBoolean());
235 Set32(object, z);
236}
237
238int8_t Field::GetByte(const Object* object) const {
239 DCHECK(GetType()->IsPrimitiveByte());
240 return Get32(object);
241}
242
243void Field::SetByte(Object* object, int8_t b) const {
244 DCHECK(GetType()->IsPrimitiveByte());
245 Set32(object, b);
246}
247
248uint16_t Field::GetChar(const Object* object) const {
249 DCHECK(GetType()->IsPrimitiveChar());
250 return Get32(object);
251}
252
253void Field::SetChar(Object* object, uint16_t c) const {
254 DCHECK(GetType()->IsPrimitiveChar());
255 Set32(object, c);
256}
257
258uint16_t Field::GetShort(const Object* object) const {
259 DCHECK(GetType()->IsPrimitiveShort());
260 return Get32(object);
261}
262
263void Field::SetShort(Object* object, uint16_t s) const {
264 DCHECK(GetType()->IsPrimitiveShort());
265 Set32(object, s);
266}
267
268int32_t Field::GetInt(const Object* object) const {
269 DCHECK(GetType()->IsPrimitiveInt());
270 return Get32(object);
271}
272
273void Field::SetInt(Object* object, int32_t i) const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700274 DCHECK(GetType()->IsPrimitiveInt()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275 Set32(object, i);
276}
277
278int64_t Field::GetLong(const Object* object) const {
279 DCHECK(GetType()->IsPrimitiveLong());
280 return Get64(object);
281}
282
283void Field::SetLong(Object* object, int64_t j) const {
284 DCHECK(GetType()->IsPrimitiveLong());
285 Set64(object, j);
286}
287
288float Field::GetFloat(const Object* object) const {
289 DCHECK(GetType()->IsPrimitiveFloat());
290 JValue float_bits;
291 float_bits.i = Get32(object);
292 return float_bits.f;
293}
294
295void Field::SetFloat(Object* object, float f) const {
296 DCHECK(GetType()->IsPrimitiveFloat());
297 JValue float_bits;
298 float_bits.f = f;
299 Set32(object, float_bits.i);
300}
301
302double Field::GetDouble(const Object* object) const {
303 DCHECK(GetType()->IsPrimitiveDouble());
304 JValue double_bits;
305 double_bits.j = Get64(object);
306 return double_bits.d;
307}
308
309void Field::SetDouble(Object* object, double d) const {
310 DCHECK(GetType()->IsPrimitiveDouble());
311 JValue double_bits;
312 double_bits.d = d;
313 Set64(object, double_bits.j);
314}
315
316Object* Field::GetObject(const Object* object) const {
317 CHECK(!GetType()->IsPrimitive());
318 return GetObj(object);
319}
320
321void Field::SetObject(Object* object, const Object* l) const {
322 CHECK(!GetType()->IsPrimitive());
323 SetObj(object, l);
324}
325
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700326bool Method::IsClassInitializer() const {
327 return IsStatic() && GetName()->Equals("<clinit>");
328}
329
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700330// TODO: get global references for these
Elliott Hughes80609252011-09-23 17:24:51 -0700331Class* Method::java_lang_reflect_Constructor_ = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332Class* Method::java_lang_reflect_Method_ = NULL;
333
Elliott Hughes80609252011-09-23 17:24:51 -0700334void Method::SetClasses(Class* java_lang_reflect_Constructor, Class* java_lang_reflect_Method) {
335 CHECK(java_lang_reflect_Constructor_ == NULL);
336 CHECK(java_lang_reflect_Constructor != NULL);
337 java_lang_reflect_Constructor_ = java_lang_reflect_Constructor;
338
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339 CHECK(java_lang_reflect_Method_ == NULL);
340 CHECK(java_lang_reflect_Method != NULL);
341 java_lang_reflect_Method_ = java_lang_reflect_Method;
342}
343
Elliott Hughes80609252011-09-23 17:24:51 -0700344void Method::ResetClasses() {
345 CHECK(java_lang_reflect_Constructor_ != NULL);
346 java_lang_reflect_Constructor_ = NULL;
347
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348 CHECK(java_lang_reflect_Method_ != NULL);
349 java_lang_reflect_Method_ = NULL;
350}
351
Elliott Hughes418d20f2011-09-22 14:00:39 -0700352Class* ExtractNextClassFromSignature(ClassLinker* class_linker, const ClassLoader* cl, const char*& p) {
353 if (*p == '[') {
354 // Something like "[[[Ljava/lang/String;".
355 const char* start = p;
356 while (*p == '[') {
357 ++p;
358 }
359 if (*p == 'L') {
360 while (*p != ';') {
361 ++p;
362 }
363 }
364 ++p; // Either the ';' or the primitive type.
365
366 StringPiece descriptor(start, (p - start));
367 return class_linker->FindClass(descriptor, cl);
368 } else if (*p == 'L') {
369 const char* start = p;
370 while (*p != ';') {
371 ++p;
372 }
373 ++p;
374 StringPiece descriptor(start, (p - start));
375 return class_linker->FindClass(descriptor, cl);
376 } else {
377 return class_linker->FindPrimitiveClass(*p++);
378 }
379}
380
381void Method::InitJavaFieldsLocked() {
382 // Create the array.
383 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
384 size_t arg_count = GetShorty()->GetLength() - 1;
385 Class* array_class = class_linker->FindSystemClass("[Ljava/lang/Class;");
386 ObjectArray<Class>* parameters = ObjectArray<Class>::Alloc(array_class, arg_count);
387 if (parameters == NULL) {
388 return;
389 }
390
391 // Parse the signature, filling the array.
392 const ClassLoader* cl = GetDeclaringClass()->GetClassLoader();
393 std::string signature(GetSignature()->ToModifiedUtf8());
394 const char* p = signature.c_str();
395 DCHECK_EQ(*p, '(');
396 ++p;
397 for (size_t i = 0; i < arg_count; ++i) {
398 Class* c = ExtractNextClassFromSignature(class_linker, cl, p);
399 if (c == NULL) {
400 return;
401 }
402 parameters->Set(i, c);
403 }
404
405 DCHECK_EQ(*p, ')');
406 ++p;
407
408 java_parameter_types_ = parameters;
409 java_return_type_ = ExtractNextClassFromSignature(class_linker, cl, p);
410}
411
412void Method::InitJavaFields() {
413 Thread* self = Thread::Current();
414 ScopedThreadStateChange tsc(self, Thread::kRunnable);
415 MonitorEnter(self);
416 if (java_parameter_types_ == NULL || java_return_type_ == NULL) {
417 InitJavaFieldsLocked();
418 }
419 MonitorExit(self);
420}
421
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422ObjectArray<String>* Method::GetDexCacheStrings() const {
423 return GetFieldObject<ObjectArray<String>*>(
424 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
425}
426
427void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
428 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
429 new_return_type_idx, false);
430}
431
432Class* Method::GetReturnType() const {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700433 DCHECK(GetDeclaringClass()->IsResolved() || GetDeclaringClass()->IsErroneous());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700434 // Short-cut
435 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
436 if (result == NULL) {
437 // Do full linkage and set cache value for next call
438 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
439 }
Elliott Hughes14134a12011-09-30 16:55:51 -0700440 CHECK(result != NULL) << PrettyMethod(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441 return result;
442}
443
444void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
445 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
446 new_dex_cache_strings, false);
447}
448
449ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
450 return GetFieldObject<ObjectArray<Class>*>(
451 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
452}
453
454void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
455 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
456 new_dex_cache_classes, false);
457}
458
459ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
460 return GetFieldObject<ObjectArray<Method>*>(
461 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
462}
463
464void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
465 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
466 new_dex_cache_methods, false);
467}
468
469ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
470 return GetFieldObject<ObjectArray<Field>*>(
471 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
472}
473
474void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
475 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
476 new_dex_cache_fields, false);
477}
478
479CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
480 return GetFieldPtr<CodeAndDirectMethods*>(
481 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
482 false);
483}
484
485void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
486 SetFieldPtr<CodeAndDirectMethods*>(
487 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
488 new_value, false);
489}
490
491ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
492 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
493 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
494 false);
495}
496
497void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
498 SetFieldObject(
499 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
500 new_value, false);
501
502}
503
504size_t Method::NumArgRegisters(const StringPiece& shorty) {
505 CHECK_LE(1, shorty.length());
506 uint32_t num_registers = 0;
507 for (int i = 1; i < shorty.length(); ++i) {
508 char ch = shorty[i];
509 if (ch == 'D' || ch == 'J') {
510 num_registers += 2;
511 } else {
512 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700513 }
514 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515 return num_registers;
516}
517
518size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700519 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700520 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700521 for (int i = 1; i < shorty->GetLength(); ++i) {
522 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700523 if (ch == 'D' || ch == 'J') {
524 num_bytes += 8;
525 } else if (ch == 'L') {
526 // Argument is a reference or an array. The shorty descriptor
527 // does not distinguish between these types.
528 num_bytes += sizeof(Object*);
529 } else {
530 num_bytes += 4;
531 }
532 }
533 return num_bytes;
534}
535
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700536size_t Method::NumArgs() const {
537 // "1 +" because the first in Args is the receiver.
538 // "- 1" because we don't count the return type.
539 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
540}
541
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542// The number of reference arguments to this method including implicit this
543// pointer
544size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700545 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700546 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700547 for (int i = 1; i < shorty->GetLength(); i++) {
548 char ch = shorty->CharAt(i);
549 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550 result++;
551 }
552 }
553 return result;
554}
555
556// The number of long or double arguments
557size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700558 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700560 for (int i = 1; i < shorty->GetLength(); i++) {
561 char ch = shorty->CharAt(i);
562 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700563 result++;
564 }
565 }
566 return result;
567}
568
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700569// Is the given method parameter a reference?
570bool Method::IsParamAReference(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 true; // this argument
576 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700577 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700578}
579
580// Is the given method parameter a long or double?
581bool Method::IsParamALongOrDouble(unsigned int param) const {
582 CHECK_LT(param, NumArgs());
583 if (IsStatic()) {
584 param++; // 0th argument must skip return value at start of the shorty
585 } else if (param == 0) {
586 return false; // this argument
587 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700588 char ch = GetShorty()->CharAt(param);
589 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700590}
591
592static size_t ShortyCharToSize(char x) {
593 switch (x) {
594 case 'V': return 0;
595 case '[': return kPointerSize;
596 case 'L': return kPointerSize;
597 case 'D': return 8;
598 case 'J': return 8;
599 default: return 4;
600 }
601}
602
603size_t Method::ParamSize(unsigned int param) const {
604 CHECK_LT(param, NumArgs());
605 if (IsStatic()) {
606 param++; // 0th argument must skip return value at start of the shorty
607 } else if (param == 0) {
608 return kPointerSize; // this argument
609 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700610 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700611}
612
613size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700614 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700615}
616
617bool Method::HasSameNameAndDescriptor(const Method* that) const {
618 return (this->GetName()->Equals(that->GetName()) &&
619 this->GetSignature()->Equals(that->GetSignature()));
620}
621
Ian Rogersbdb03912011-09-14 00:55:44 -0700622uint32_t Method::ToDexPC(const uintptr_t pc) const {
623 IntArray* mapping_table = GetMappingTable();
624 if (mapping_table == NULL) {
Ian Rogers67375ac2011-09-14 00:55:44 -0700625 DCHECK(IsNative());
626 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700627 }
628 size_t mapping_table_length = mapping_table->GetLength();
629 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700630 if (GetCodeArray() != NULL) {
631 CHECK_LT(sought_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
632 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700633 uint32_t best_offset = 0;
634 uint32_t best_dex_offset = 0;
635 for (size_t i = 0; i < mapping_table_length; i += 2) {
636 uint32_t map_offset = mapping_table->Get(i);
637 uint32_t map_dex_offset = mapping_table->Get(i + 1);
638 if (map_offset == sought_offset) {
639 best_offset = map_offset;
640 best_dex_offset = map_dex_offset;
641 break;
642 }
643 if (map_offset < sought_offset && map_offset > best_offset) {
644 best_offset = map_offset;
645 best_dex_offset = map_dex_offset;
646 }
647 }
648 return best_dex_offset;
649}
650
651uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
652 IntArray* mapping_table = GetMappingTable();
653 if (mapping_table == NULL) {
654 DCHECK(dex_pc == 0);
655 return 0; // Special no mapping/pc == 0 case
656 }
657 size_t mapping_table_length = mapping_table->GetLength();
658 for (size_t i = 0; i < mapping_table_length; i += 2) {
659 uint32_t map_offset = mapping_table->Get(i);
660 uint32_t map_dex_offset = mapping_table->Get(i + 1);
661 if (map_dex_offset == dex_pc) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700662 if (GetCodeArray() != NULL) {
663 DCHECK_LT(map_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
664 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700665 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
666 }
667 }
668 LOG(FATAL) << "Looking up Dex PC not contained in method";
669 return 0;
670}
671
672uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
673 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
674 const ClassLoader* class_loader = GetDeclaringClass()->GetClassLoader();
675 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
676 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
677 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
678 // Iterate over the catch handlers associated with dex_pc
679 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
680 !iter.HasNext(); iter.Next()) {
681 uint32_t iter_type_idx = iter.Get().type_idx_;
682 // Catch all case
Elliott Hughes80609252011-09-23 17:24:51 -0700683 if (iter_type_idx == DexFile::kDexNoIndex) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700684 return iter.Get().address_;
685 }
686 // Does this catch exception type apply?
687 Class* iter_exception_type =
688 class_linker->ResolveType(dex_file, iter_type_idx, dex_cache, class_loader);
689 if (iter_exception_type->IsAssignableFrom(exception_type)) {
690 return iter.Get().address_;
691 }
692 }
693 // Handler not found
694 return DexFile::kDexNoIndex;
695}
696
Brian Carlstrome24fa612011-09-29 00:53:55 -0700697void Method::SetCodeArray(ByteArray* code_array, InstructionSet instruction_set) {
698// TODO: restore this check or warning when compile time code storage is moved out of Method
Elliott Hughes4681c802011-09-25 18:04:37 -0700699// CHECK(GetCode() == NULL || IsNative()) << PrettyMethod(this);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700700// if (GetCode() != NULL && !IsNative()) {
701// LOG(WARNING) << "Calling SetCode more than once for " << PrettyMethod(this);
702// }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700703 SetFieldPtr<ByteArray*>(OFFSET_OF_OBJECT_MEMBER(Method, code_array_), code_array, false);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700704
705 void* code;
706 if (code_array != NULL) {
707 code = code_array->GetData();
708 if (instruction_set == kThumb2) {
709 uintptr_t address = reinterpret_cast<uintptr_t>(code);
710 // Set the low-order bit so a BLX will switch to Thumb mode
711 address |= 0x1;
712 code = reinterpret_cast<void*>(address);
713 }
714 } else {
715 code = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700716 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700717 SetCode(code);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700718}
719
Ian Rogersbdb03912011-09-14 00:55:44 -0700720bool Method::IsWithinCode(uintptr_t pc) const {
Ian Rogersbdb03912011-09-14 00:55:44 -0700721 if (pc == 0) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700722 // PC of 0 represents the beginning of a stack trace either a native or where we have a callee
723 // save method that has no code
724 DCHECK(IsNative() || IsPhony());
Ian Rogersbdb03912011-09-14 00:55:44 -0700725 return true;
726 } else {
Ian Rogers93dd9662011-09-17 23:21:22 -0700727#if defined(__arm__)
728 pc &= ~0x1; // clear any possible thumb instruction mode bit
729#endif
Brian Carlstrome24fa612011-09-29 00:53:55 -0700730 if (GetCodeArray() == NULL) {
731 return true;
732 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700733 uint32_t rel_offset = pc - reinterpret_cast<uintptr_t>(GetCodeArray()->GetData());
Ian Rogers93dd9662011-09-17 23:21:22 -0700734 // Strictly the following test should be a less-than, however, if the last
735 // instruction is a call to an exception throw we may see return addresses
736 // that are 1 beyond the end of code.
737 return rel_offset <= static_cast<uint32_t>(GetCodeArray()->GetLength());
Ian Rogersbdb03912011-09-14 00:55:44 -0700738 }
739}
740
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700741void Method::SetInvokeStub(const ByteArray* invoke_stub_array) {
742 const InvokeStub* invoke_stub = reinterpret_cast<InvokeStub*>(invoke_stub_array->GetData());
743 SetFieldPtr<const ByteArray*>(
744 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_array_), invoke_stub_array, false);
745 SetFieldPtr<const InvokeStub*>(
746 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_), invoke_stub, false);
747}
748
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700749void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
750 // Push a transition back into managed code onto the linked list in thread.
751 CHECK_EQ(Thread::kRunnable, self->GetState());
752 NativeToManagedRecord record;
753 self->PushNativeToManagedRecord(&record);
754
755 // Call the invoke stub associated with the method.
756 // Pass everything as arguments.
757 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700758
759 bool have_executable_code = (GetCode() != NULL);
760#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700761 // Currently we can only compile non-native methods for ARM.
762 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700763#endif
764
765 if (have_executable_code && stub != NULL) {
766 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700767 (*stub)(this, receiver, self, args, result);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700768 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700769 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700770 if (Runtime::Current()->IsStarted()) {
771 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
772 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700773 if (result != NULL) {
774 result->j = 0;
775 }
776 }
777
778 // Pop transition.
779 self->PopNativeToManagedRecord(record);
780}
781
Brian Carlstrom16192862011-09-12 17:50:06 -0700782bool Method::IsRegistered() {
783 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
784 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
785 return native_method != jni_stub;
786}
787
788void Method::RegisterNative(const void* native_method) {
789 CHECK(IsNative());
790 CHECK(native_method != NULL);
791 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
792 native_method, false);
793}
794
795void Method::UnregisterNative() {
796 CHECK(IsNative());
797 // restore stub to lookup native pointer via dlsym
798 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
799}
800
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700801void Class::SetStatus(Status new_status) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700802 CHECK(new_status > GetStatus() || new_status == kStatusError || !Runtime::Current()->IsStarted())
803 << PrettyClass(this) << " " << GetStatus() << " -> " << new_status;
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700804 CHECK(sizeof(Status) == sizeof(uint32_t)) << PrettyClass(this);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700805 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700806}
807
808DexCache* Class::GetDexCache() const {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700809 return GetFieldObject<DexCache*>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700810}
811
812void Class::SetDexCache(DexCache* new_dex_cache) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700813 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700814}
815
Brian Carlstrom1f870082011-08-23 16:02:11 -0700816Object* Class::AllocObject() {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700817 DCHECK(!IsAbstract()) << PrettyClass(this);
818 DCHECK(!IsInterface()) << PrettyClass(this);
819 DCHECK(!IsPrimitive()) << PrettyClass(this);
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700820 DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700821 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700822}
823
Elliott Hughes4681c802011-09-25 18:04:37 -0700824void Class::DumpClass(std::ostream& os, int flags) const {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700825 if ((flags & kDumpClassFullDetail) == 0) {
826 os << PrettyClass(this);
827 if ((flags & kDumpClassClassLoader) != 0) {
828 os << ' ' << GetClassLoader();
829 }
830 if ((flags & kDumpClassInitialized) != 0) {
831 os << ' ' << GetStatus();
832 }
833 os << std::endl;
834 return;
835 }
836
837 Class* super = GetSuperClass();
838 os << "----- " << (IsInterface() ? "interface" : "class") << " "
839 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
840 os << " objectSize=" << SizeOf() << " "
841 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
842 os << StringPrintf(" access=0x%04x.%04x\n",
843 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
844 if (super != NULL) {
845 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
846 }
847 if (IsArrayClass()) {
848 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
849 }
850 if (NumInterfaces() > 0) {
851 os << " interfaces (" << NumInterfaces() << "):\n";
852 for (size_t i = 0; i < NumInterfaces(); ++i) {
853 Class* interface = GetInterface(i);
854 const ClassLoader* cl = interface->GetClassLoader();
855 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
856 }
857 }
858 os << " vtable (" << NumVirtualMethods() << " entries, "
859 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
860 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700861 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethodDuringLinking(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700862 }
863 os << " direct methods (" << NumDirectMethods() << " entries):\n";
864 for (size_t i = 0; i < NumDirectMethods(); ++i) {
865 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
866 }
867 if (NumStaticFields() > 0) {
868 os << " static fields (" << NumStaticFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700869 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700870 for (size_t i = 0; i < NumStaticFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700871 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700872 }
873 } else {
874 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700875 }
876 }
877 if (NumInstanceFields() > 0) {
878 os << " instance fields (" << NumInstanceFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700879 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700880 for (size_t i = 0; i < NumInstanceFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700881 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700882 }
883 } else {
884 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700885 }
886 }
887}
888
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700889void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
890 if (new_reference_offsets != CLASS_WALK_SUPER) {
891 // Sanity check that the number of bits set in the reference offset bitmap
892 // agrees with the number of references
893 Class* cur = this;
894 size_t cnt = 0;
895 while (cur) {
896 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
897 cur = cur->GetSuperClass();
898 }
899 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
900 }
901 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
902 new_reference_offsets, false);
903}
904
905void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
906 if (new_reference_offsets != CLASS_WALK_SUPER) {
907 // Sanity check that the number of bits set in the reference offset bitmap
908 // agrees with the number of references
909 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
910 NumReferenceStaticFieldsDuringLinking());
911 }
912 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
913 new_reference_offsets, false);
914}
915
916size_t Class::PrimitiveSize() const {
917 switch (GetPrimitiveType()) {
918 case kPrimBoolean:
919 case kPrimByte:
920 case kPrimChar:
921 case kPrimShort:
922 case kPrimInt:
923 case kPrimFloat:
924 return sizeof(int32_t);
925 case kPrimLong:
926 case kPrimDouble:
927 return sizeof(int64_t);
928 default:
929 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
930 return 0;
931 }
932}
933
934size_t Class::GetTypeSize(const String* descriptor) {
935 switch (descriptor->CharAt(0)) {
936 case 'B': return 1; // byte
937 case 'C': return 2; // char
938 case 'D': return 8; // double
939 case 'F': return 4; // float
940 case 'I': return 4; // int
941 case 'J': return 8; // long
942 case 'S': return 2; // short
943 case 'Z': return 1; // boolean
944 case 'L': return sizeof(Object*);
945 case '[': return sizeof(Array*);
946 default:
947 LOG(ERROR) << "Unknown type " << descriptor;
948 return 0;
949 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700950}
951
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700952bool Class::Implements(const Class* klass) const {
953 DCHECK(klass != NULL);
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700954 DCHECK(klass->IsInterface()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700955 // All interfaces implemented directly and by our superclass, and
956 // recursively all super-interfaces of those interfaces, are listed
957 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700958 int32_t iftable_count = GetIfTableCount();
959 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
960 for (int32_t i = 0; i < iftable_count; i++) {
961 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700962 return true;
963 }
964 }
965 return false;
966}
967
968// Determine whether "this" is assignable from "klazz", where both of these
969// are array classes.
970//
971// Consider an array class, e.g. Y[][], where Y is a subclass of X.
972// Y[][] = Y[][] --> true (identity)
973// X[][] = Y[][] --> true (element superclass)
974// Y = Y[][] --> false
975// Y[] = Y[][] --> false
976// Object = Y[][] --> true (everything is an object)
977// Object[] = Y[][] --> true
978// Object[][] = Y[][] --> true
979// Object[][][] = Y[][] --> false (too many []s)
980// Serializable = Y[][] --> true (all arrays are Serializable)
981// Serializable[] = Y[][] --> true
982// Serializable[][] = Y[][] --> false (unless Y is Serializable)
983//
984// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700985// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700986//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700987bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700988 DCHECK(IsArrayClass()) << PrettyClass(this);
989 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700990 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700991}
992
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700993bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700994 DCHECK(!IsInterface()) << PrettyClass(this); // handled first in IsAssignableFrom
995 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700996 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700997 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700998 // src's super should be java_lang_Object, since it is an array.
999 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001000 DCHECK(java_lang_Object != NULL) << PrettyClass(src);
1001 DCHECK(java_lang_Object->GetSuperClass() == NULL) << PrettyClass(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001002 return this == java_lang_Object;
1003 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001004 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001005}
1006
1007bool Class::IsSubClass(const Class* klass) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001008 DCHECK(!IsInterface()) << PrettyClass(this);
1009 DCHECK(!IsArrayClass()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001010 const Class* current = this;
1011 do {
1012 if (current == klass) {
1013 return true;
1014 }
1015 current = current->GetSuperClass();
1016 } while (current != NULL);
1017 return false;
1018}
1019
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001020bool Class::IsInSamePackage(const String* descriptor_string_1,
1021 const String* descriptor_string_2) {
1022 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
1023 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
1024
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001025 size_t i = 0;
1026 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
1027 ++i;
1028 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001029 if (descriptor1.find('/', i) != StringPiece::npos ||
1030 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001031 return false;
1032 } else {
1033 return true;
1034 }
1035}
1036
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001037#if 0
Ian Rogersb033c752011-07-20 12:22:35 -07001038bool Class::IsInSamePackage(const StringPiece& descriptor1,
1039 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001040 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001041 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -07001042 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
1043 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001044 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
1045}
1046#endif
1047
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001048bool Class::IsInSamePackage(const Class* that) const {
1049 const Class* klass1 = this;
1050 const Class* klass2 = that;
1051 if (klass1 == klass2) {
1052 return true;
1053 }
1054 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001055 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001056 return false;
1057 }
1058 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -07001059 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001060 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001061 }
jeffhao4a801a42011-09-23 13:53:40 -07001062 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001063 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001064 }
1065 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001066 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001067}
1068
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001069const ClassLoader* Class::GetClassLoader() const {
1070 return GetFieldObject<const ClassLoader*>(
1071 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -07001072}
1073
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001074void Class::SetClassLoader(const ClassLoader* new_cl) {
1075 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
1076 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
1077 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001078}
1079
Brian Carlstrom30b94452011-08-25 21:35:26 -07001080Method* Class::FindVirtualMethodForInterface(Method* method) {
1081 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001082 DCHECK(declaring_class != NULL) << PrettyClass(this);
1083 DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001084 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001085 int32_t iftable_count = GetIfTableCount();
1086 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1087 for (int32_t i = 0; i < iftable_count; i++) {
1088 InterfaceEntry* interface_entry = iftable->Get(i);
1089 if (interface_entry->GetInterface() == declaring_class) {
1090 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -07001091 }
1092 }
Elliott Hughesefdbac52011-10-06 15:06:18 -07001093 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
1094 "Class %s does not implement interface %s",
1095 PrettyDescriptor(GetDescriptor()).c_str(),
1096 PrettyDescriptor(declaring_class->GetDescriptor()).c_str());
Brian Carlstrom30b94452011-08-25 21:35:26 -07001097 return NULL;
1098}
1099
jeffhaobdb76512011-09-07 11:43:16 -07001100Method* Class::FindInterfaceMethod(const StringPiece& name,
1101 const StringPiece& signature) {
1102 // Check the current class before checking the interfaces.
1103 Method* method = FindVirtualMethod(name, signature);
1104 if (method != NULL) {
1105 return method;
1106 }
1107
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001108 int32_t iftable_count = GetIfTableCount();
1109 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1110 for (int32_t i = 0; i < iftable_count; i++) {
1111 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001112 if (method != NULL) {
1113 return method;
1114 }
1115 }
1116 return NULL;
1117}
1118
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001119Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001120 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001121 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001122 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001123 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001124 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001125 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001126 }
1127 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001128 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001129}
1130
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001131Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001132 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001133 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001134 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001135 if (method != NULL) {
1136 return method;
1137 }
1138 }
1139 return NULL;
1140}
1141
1142Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001143 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001144 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001145 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001146 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001147 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001148 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001149 }
1150 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001151 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001152}
1153
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001154Method* Class::FindVirtualMethod(const StringPiece& name,
Elliott Hughescc5f9a92011-09-28 19:17:29 -07001155 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001156 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07001157 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001158 if (method != NULL) {
1159 return method;
1160 }
1161 }
1162 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001163}
1164
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001165Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001166 // Is the field in this class?
1167 // Interfaces are not relevant because they can't contain instance fields.
1168 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1169 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001170 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001171 return f;
1172 }
1173 }
1174 return NULL;
1175}
1176
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001177Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001178 // Is the field in this class, or any of its superclasses?
1179 // Interfaces are not relevant because they can't contain instance fields.
1180 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001181 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001182 if (f != NULL) {
1183 return f;
1184 }
1185 }
1186 return NULL;
1187}
1188
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001189Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
1190 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -07001191 for (size_t i = 0; i < NumStaticFields(); ++i) {
1192 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001193 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001194 return f;
1195 }
1196 }
1197 return NULL;
1198}
1199
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001200Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001201 // Is the field in this class (or its interfaces), or any of its
1202 // superclasses (or their interfaces)?
1203 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1204 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001205 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001206 if (f != NULL) {
1207 return f;
1208 }
1209
1210 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001211 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1212 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1213 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001214 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001215 if (f != NULL) {
1216 return f;
1217 }
1218 }
1219 }
1220 return NULL;
1221}
1222
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001223Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001224 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001225 DCHECK_GE(component_count, 0);
1226 DCHECK(array_class->IsArrayClass());
Elliott Hughesb408de72011-10-04 14:35:05 -07001227
1228 size_t header_size = sizeof(Array);
1229 size_t data_size = component_count * component_size;
1230 size_t size = header_size + data_size;
1231
1232 // Check for overflow and throw OutOfMemoryError if this was an unreasonable request.
1233 size_t component_shift = sizeof(size_t) * 8 - 1 - CLZ(component_size);
1234 if (data_size >> component_shift != size_t(component_count) || size < data_size) {
1235 Thread::Current()->ThrowNewExceptionF("Ljava/lang/OutOfMemoryError;",
1236 "%s of length %zd exceeds the VM limit",
1237 PrettyDescriptor(array_class->GetDescriptor()).c_str(), component_count);
1238 return NULL;
1239 }
1240
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001241 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1242 if (array != NULL) {
1243 DCHECK(array->IsArrayInstance());
1244 array->SetLength(component_count);
1245 }
1246 return array;
1247}
1248
1249Array* Array::Alloc(Class* array_class, int32_t component_count) {
1250 return Alloc(array_class, component_count, array_class->GetComponentSize());
1251}
1252
Elliott Hughes80609252011-09-23 17:24:51 -07001253bool Array::ThrowArrayIndexOutOfBoundsException(int32_t index) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001254 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001255 "length=%i; index=%i", length_, index);
1256 return false;
1257}
1258
1259bool Array::ThrowArrayStoreException(Object* object) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001260 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001261 "Can't store an element of type %s into an array of type %s",
1262 PrettyTypeOf(object).c_str(), PrettyTypeOf(this).c_str());
1263 return false;
1264}
1265
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001266template<typename T>
1267PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001268 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001269 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1270 return down_cast<PrimitiveArray<T>*>(raw_array);
1271}
1272
1273template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1274
1275// Explicitly instantiate all the primitive array types.
1276template class PrimitiveArray<uint8_t>; // BooleanArray
1277template class PrimitiveArray<int8_t>; // ByteArray
1278template class PrimitiveArray<uint16_t>; // CharArray
1279template class PrimitiveArray<double>; // DoubleArray
1280template class PrimitiveArray<float>; // FloatArray
1281template class PrimitiveArray<int32_t>; // IntArray
1282template class PrimitiveArray<int64_t>; // LongArray
1283template class PrimitiveArray<int16_t>; // ShortArray
1284
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001285// TODO: get global references for these
1286Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001287
Brian Carlstroma663ea52011-08-19 23:33:41 -07001288void String::SetClass(Class* java_lang_String) {
1289 CHECK(java_lang_String_ == NULL);
1290 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001291 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001292}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001293
Brian Carlstroma663ea52011-08-19 23:33:41 -07001294void String::ResetClass() {
1295 CHECK(java_lang_String_ != NULL);
1296 java_lang_String_ = NULL;
1297}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001298
Brian Carlstromc74255f2011-09-11 22:47:39 -07001299String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001300 return Runtime::Current()->GetInternTable()->InternWeak(this);
1301}
1302
Brian Carlstrom395520e2011-09-25 19:35:00 -07001303int32_t String::GetHashCode() {
1304 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1305 if (result == 0) {
1306 ComputeHashCode();
1307 }
1308 result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1309 DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
1310 << ToModifiedUtf8() << " " << result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001311 return result;
1312}
1313
1314int32_t String::GetLength() const {
1315 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1316 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1317 return result;
1318}
1319
1320uint16_t String::CharAt(int32_t index) const {
1321 // TODO: do we need this? Equals is the only caller, and could
1322 // bounds check itself.
1323 if (index < 0 || index >= count_) {
1324 Thread* self = Thread::Current();
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001325 self->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;",
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001326 "length=%i; index=%i", count_, index);
1327 return 0;
1328 }
1329 return GetCharArray()->Get(index + GetOffset());
1330}
1331
1332String* String::AllocFromUtf16(int32_t utf16_length,
1333 const uint16_t* utf16_data_in,
1334 int32_t hash_code) {
1335 String* string = Alloc(GetJavaLangString(), utf16_length);
1336 // TODO: use 16-bit wide memset variant
1337 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1338 for (int i = 0; i < utf16_length; i++) {
1339 array->Set(i, utf16_data_in[i]);
1340 }
1341 if (hash_code != 0) {
1342 string->SetHashCode(hash_code);
1343 } else {
1344 string->ComputeHashCode();
1345 }
1346 return string;
1347}
1348
1349String* String::AllocFromModifiedUtf8(const char* utf) {
1350 size_t char_count = CountModifiedUtf8Chars(utf);
1351 return AllocFromModifiedUtf8(char_count, utf);
1352}
1353
1354String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1355 const char* utf8_data_in) {
1356 String* string = Alloc(GetJavaLangString(), utf16_length);
1357 uint16_t* utf16_data_out =
1358 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1359 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1360 string->ComputeHashCode();
1361 return string;
1362}
1363
1364String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1365 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1366}
1367
1368String* String::Alloc(Class* java_lang_String, CharArray* array) {
1369 String* string = down_cast<String*>(java_lang_String->AllocObject());
1370 string->SetArray(array);
1371 string->SetCount(array->GetLength());
1372 return string;
1373}
1374
1375bool String::Equals(const String* that) const {
1376 if (this == that) {
1377 // Quick reference equality test
1378 return true;
1379 } else if (that == NULL) {
1380 // Null isn't an instanceof anything
1381 return false;
1382 } else if (this->GetLength() != that->GetLength()) {
1383 // Quick length inequality test
1384 return false;
1385 } else {
Elliott Hughes20cde902011-10-04 17:37:27 -07001386 // Note: don't short circuit on hash code as we're presumably here as the
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001387 // hash code was already equal
1388 for (int32_t i = 0; i < that->GetLength(); ++i) {
1389 if (this->CharAt(i) != that->CharAt(i)) {
1390 return false;
1391 }
1392 }
1393 return true;
1394 }
1395}
1396
1397bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1398 int32_t that_length) const {
1399 if (this->GetLength() != that_length) {
1400 return false;
1401 } else {
1402 for (int32_t i = 0; i < that_length; ++i) {
1403 if (this->CharAt(i) != that_chars[that_offset + i]) {
1404 return false;
1405 }
1406 }
1407 return true;
1408 }
1409}
1410
1411bool String::Equals(const char* modified_utf8) const {
1412 for (int32_t i = 0; i < GetLength(); ++i) {
1413 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1414 if (ch == '\0' || ch != CharAt(i)) {
1415 return false;
1416 }
1417 }
1418 return *modified_utf8 == '\0';
1419}
1420
1421bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001422 if (modified_utf8.size() != GetLength()) {
1423 return false;
1424 }
1425 const char* p = modified_utf8.data();
1426 for (int32_t i = 0; i < GetLength(); ++i) {
1427 uint16_t ch = GetUtf16FromUtf8(&p);
1428 if (ch != CharAt(i)) {
1429 return false;
1430 }
1431 }
1432 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001433}
1434
1435// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1436std::string String::ToModifiedUtf8() const {
1437 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1438 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1439 std::string result(byte_count, char(0));
1440 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1441 return result;
1442}
1443
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001444Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1445
1446void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1447 CHECK(java_lang_StackTraceElement_ == NULL);
1448 CHECK(java_lang_StackTraceElement != NULL);
1449 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1450}
1451
1452void StackTraceElement::ResetClass() {
1453 CHECK(java_lang_StackTraceElement_ != NULL);
1454 java_lang_StackTraceElement_ = NULL;
1455}
1456
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001457StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1458 const String* method_name,
1459 const String* file_name,
1460 int32_t line_number) {
1461 StackTraceElement* trace =
1462 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1463 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1464 const_cast<String*>(declaring_class), false);
1465 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1466 const_cast<String*>(method_name), false);
1467 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1468 const_cast<String*>(file_name), false);
1469 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1470 line_number, false);
1471 return trace;
1472}
1473
Elliott Hughes1f359b02011-07-17 14:27:17 -07001474static const char* kClassStatusNames[] = {
1475 "Error",
1476 "NotReady",
1477 "Idx",
1478 "Loaded",
1479 "Resolved",
1480 "Verifying",
1481 "Verified",
1482 "Initializing",
1483 "Initialized"
1484};
1485std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1486 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001487 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001488 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001489 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001490 }
1491 return os;
1492}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001493
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001494} // namespace art