blob: 4950077a5bf05040c148ee94765374ce9e303700 [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"
Carl Shapiro3ee755d2011-06-28 12:11:04 -070022
23namespace art {
24
Elliott Hughes20cde902011-10-04 17:37:27 -070025void Object::AddFinalizerReference() {
26 Thread* self = Thread::Current();
27
28 // TODO: cache these somewhere.
29 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
30 Class* java_lang_ref_FinalizerReference = class_linker->FindSystemClass("Ljava/lang/ref/FinalizerReference;");
31 CHECK(java_lang_ref_FinalizerReference != NULL);
32 Method* m = java_lang_ref_FinalizerReference->FindDirectMethod("add", "(Ljava/lang/Object;)V");
33 CHECK(m != NULL);
34
35 LOG(INFO) << "Object::AddFinalizerReference invoking FinalizerReference.add for " << (void*) this;
36 m->Invoke(self, NULL, reinterpret_cast<byte*>(this), NULL);
37}
38
Elliott Hughes081be7f2011-09-18 16:50:26 -070039Object* Object::Clone() {
40 Class* c = GetClass();
41 DCHECK(!c->IsClassClass());
42
43 // Object::SizeOf gets the right size even if we're an array.
44 // Using c->AllocObject() here would be wrong.
45 size_t num_bytes = SizeOf();
46 Object* copy = Heap::AllocObject(c, num_bytes);
47 if (copy == NULL) {
48 return NULL;
49 }
50
51 // Copy instance data. We assume memcpy copies by words.
52 // TODO: expose and use move32.
53 byte* src_bytes = reinterpret_cast<byte*>(this);
54 byte* dst_bytes = reinterpret_cast<byte*>(copy);
55 size_t offset = sizeof(Object);
56 memcpy(dst_bytes + offset, src_bytes + offset, num_bytes - offset);
57
Elliott Hughes20cde902011-10-04 17:37:27 -070058 if (c->IsFinalizable()) {
59 copy->AddFinalizerReference();
60 }
Elliott Hughes081be7f2011-09-18 16:50:26 -070061
62 return copy;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070063}
64
Elliott Hughes5f791332011-09-15 17:45:30 -070065uint32_t Object::GetLockOwner() {
66 return Monitor::GetLockOwner(monitor_);
67}
68
Elliott Hughes081be7f2011-09-18 16:50:26 -070069bool Object::IsString() const {
70 // TODO use "klass_ == String::GetJavaLangString()" instead?
71 return GetClass() == GetClass()->GetDescriptor()->GetClass();
72}
73
Elliott Hughes5f791332011-09-15 17:45:30 -070074void Object::MonitorEnter(Thread* thread) {
75 Monitor::MonitorEnter(thread, this);
76}
77
Ian Rogersff1ed472011-09-20 13:46:24 -070078bool Object::MonitorExit(Thread* thread) {
79 return Monitor::MonitorExit(thread, this);
Elliott Hughes5f791332011-09-15 17:45:30 -070080}
81
82void Object::Notify() {
83 Monitor::Notify(Thread::Current(), this);
84}
85
86void Object::NotifyAll() {
87 Monitor::NotifyAll(Thread::Current(), this);
88}
89
90void Object::Wait(int64_t ms, int32_t ns) {
91 Monitor::Wait(Thread::Current(), this, ms, ns, true);
92}
93
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070094// TODO: get global references for these
95Class* Field::java_lang_reflect_Field_ = NULL;
96
97void Field::SetClass(Class* java_lang_reflect_Field) {
98 CHECK(java_lang_reflect_Field_ == NULL);
99 CHECK(java_lang_reflect_Field != NULL);
100 java_lang_reflect_Field_ = java_lang_reflect_Field;
101}
102
103void Field::ResetClass() {
104 CHECK(java_lang_reflect_Field_ != NULL);
105 java_lang_reflect_Field_ = NULL;
106}
107
108void Field::SetTypeIdx(uint32_t type_idx) {
109 SetField32(OFFSET_OF_OBJECT_MEMBER(Field, type_idx_), type_idx, false);
110}
111
112Class* Field::GetTypeDuringLinking() const {
113 // We are assured that the necessary primitive types are in the dex cache
114 // early during class linking
115 return GetDeclaringClass()->GetDexCache()->GetResolvedType(GetTypeIdx());
116}
117
118Class* Field::GetType() const {
Elliott Hughes80609252011-09-23 17:24:51 -0700119 if (type_ == NULL) {
120 type_ = Runtime::Current()->GetClassLinker()->ResolveType(GetTypeIdx(), this);
121 }
122 return type_;
123}
124
125void Field::InitJavaFields() {
126 Thread* self = Thread::Current();
127 ScopedThreadStateChange tsc(self, Thread::kRunnable);
128 MonitorEnter(self);
129 if (type_ == NULL) {
130 InitJavaFieldsLocked();
131 }
132 MonitorExit(self);
133}
134
135void Field::InitJavaFieldsLocked() {
136 GetType(); // Sets type_ as a side-effect. May throw.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700137}
138
Brian Carlstrom845490b2011-09-19 15:56:53 -0700139Field* Field::FindInstanceFieldFromCode(uint32_t field_idx, const Method* referrer) {
140 return FindFieldFromCode(field_idx, referrer, false);
141}
142
143Field* Field::FindStaticFieldFromCode(uint32_t field_idx, const Method* referrer) {
144 return FindFieldFromCode(field_idx, referrer, true);
145}
146
147Field* Field::FindFieldFromCode(uint32_t field_idx, const Method* referrer, bool is_static) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700148 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom845490b2011-09-19 15:56:53 -0700149 Field* f = class_linker->ResolveField(field_idx, referrer, is_static);
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700150 if (f != NULL) {
151 Class* c = f->GetDeclaringClass();
152 // If the class is already initializing, we must be inside <clinit>, or
153 // we'd still be waiting for the lock.
Brian Carlstrom25c33252011-09-18 15:58:35 -0700154 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c, true)) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700155 return f;
156 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700157 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700158 UNIMPLEMENTED(FATAL) << "throw an error and unwind";
159 return NULL;
160}
161
162uint32_t Field::Get32StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700163 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700164 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
165 return field->Get32(NULL);
166}
167void Field::Set32StaticFromCode(uint32_t field_idx, const Method* referrer, uint32_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700168 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700169 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
170 field->Set32(NULL, new_value);
171}
172uint64_t Field::Get64StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700173 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700174 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
175 return field->Get64(NULL);
176}
177void Field::Set64StaticFromCode(uint32_t field_idx, const Method* referrer, uint64_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700178 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700179 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
180 field->Set64(NULL, new_value);
181}
182Object* Field::GetObjStaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700183 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700184 DCHECK(!field->GetType()->IsPrimitive());
185 return field->GetObj(NULL);
186}
187void Field::SetObjStaticFromCode(uint32_t field_idx, const Method* referrer, Object* new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700188 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700189 DCHECK(!field->GetType()->IsPrimitive());
190 field->SetObj(NULL, new_value);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700191}
192
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700193uint32_t Field::Get32(const Object* object) const {
194 CHECK((object == NULL) == IsStatic());
195 if (IsStatic()) {
196 object = declaring_class_;
197 }
198 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700199}
200
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700201void Field::Set32(Object* object, uint32_t new_value) const {
202 CHECK((object == NULL) == IsStatic());
203 if (IsStatic()) {
204 object = declaring_class_;
205 }
206 object->SetField32(GetOffset(), new_value, IsVolatile());
207}
208
209uint64_t Field::Get64(const Object* object) const {
210 CHECK((object == NULL) == IsStatic());
211 if (IsStatic()) {
212 object = declaring_class_;
213 }
214 return object->GetField64(GetOffset(), IsVolatile());
215}
216
217void Field::Set64(Object* object, uint64_t new_value) const {
218 CHECK((object == NULL) == IsStatic());
219 if (IsStatic()) {
220 object = declaring_class_;
221 }
222 object->SetField64(GetOffset(), new_value, IsVolatile());
223}
224
225Object* Field::GetObj(const Object* object) const {
226 CHECK((object == NULL) == IsStatic());
227 if (IsStatic()) {
228 object = declaring_class_;
229 }
230 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
231}
232
233void Field::SetObj(Object* object, const Object* new_value) const {
234 CHECK((object == NULL) == IsStatic());
235 if (IsStatic()) {
236 object = declaring_class_;
237 }
238 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
239}
240
241bool Field::GetBoolean(const Object* object) const {
242 DCHECK(GetType()->IsPrimitiveBoolean());
243 return Get32(object);
244}
245
246void Field::SetBoolean(Object* object, bool z) const {
247 DCHECK(GetType()->IsPrimitiveBoolean());
248 Set32(object, z);
249}
250
251int8_t Field::GetByte(const Object* object) const {
252 DCHECK(GetType()->IsPrimitiveByte());
253 return Get32(object);
254}
255
256void Field::SetByte(Object* object, int8_t b) const {
257 DCHECK(GetType()->IsPrimitiveByte());
258 Set32(object, b);
259}
260
261uint16_t Field::GetChar(const Object* object) const {
262 DCHECK(GetType()->IsPrimitiveChar());
263 return Get32(object);
264}
265
266void Field::SetChar(Object* object, uint16_t c) const {
267 DCHECK(GetType()->IsPrimitiveChar());
268 Set32(object, c);
269}
270
271uint16_t Field::GetShort(const Object* object) const {
272 DCHECK(GetType()->IsPrimitiveShort());
273 return Get32(object);
274}
275
276void Field::SetShort(Object* object, uint16_t s) const {
277 DCHECK(GetType()->IsPrimitiveShort());
278 Set32(object, s);
279}
280
281int32_t Field::GetInt(const Object* object) const {
282 DCHECK(GetType()->IsPrimitiveInt());
283 return Get32(object);
284}
285
286void Field::SetInt(Object* object, int32_t i) const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700287 DCHECK(GetType()->IsPrimitiveInt()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288 Set32(object, i);
289}
290
291int64_t Field::GetLong(const Object* object) const {
292 DCHECK(GetType()->IsPrimitiveLong());
293 return Get64(object);
294}
295
296void Field::SetLong(Object* object, int64_t j) const {
297 DCHECK(GetType()->IsPrimitiveLong());
298 Set64(object, j);
299}
300
301float Field::GetFloat(const Object* object) const {
302 DCHECK(GetType()->IsPrimitiveFloat());
303 JValue float_bits;
304 float_bits.i = Get32(object);
305 return float_bits.f;
306}
307
308void Field::SetFloat(Object* object, float f) const {
309 DCHECK(GetType()->IsPrimitiveFloat());
310 JValue float_bits;
311 float_bits.f = f;
312 Set32(object, float_bits.i);
313}
314
315double Field::GetDouble(const Object* object) const {
316 DCHECK(GetType()->IsPrimitiveDouble());
317 JValue double_bits;
318 double_bits.j = Get64(object);
319 return double_bits.d;
320}
321
322void Field::SetDouble(Object* object, double d) const {
323 DCHECK(GetType()->IsPrimitiveDouble());
324 JValue double_bits;
325 double_bits.d = d;
326 Set64(object, double_bits.j);
327}
328
329Object* Field::GetObject(const Object* object) const {
330 CHECK(!GetType()->IsPrimitive());
331 return GetObj(object);
332}
333
334void Field::SetObject(Object* object, const Object* l) const {
335 CHECK(!GetType()->IsPrimitive());
336 SetObj(object, l);
337}
338
339// TODO: get global references for these
Elliott Hughes80609252011-09-23 17:24:51 -0700340Class* Method::java_lang_reflect_Constructor_ = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341Class* Method::java_lang_reflect_Method_ = NULL;
342
Elliott Hughes80609252011-09-23 17:24:51 -0700343void Method::SetClasses(Class* java_lang_reflect_Constructor, Class* java_lang_reflect_Method) {
344 CHECK(java_lang_reflect_Constructor_ == NULL);
345 CHECK(java_lang_reflect_Constructor != NULL);
346 java_lang_reflect_Constructor_ = java_lang_reflect_Constructor;
347
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348 CHECK(java_lang_reflect_Method_ == NULL);
349 CHECK(java_lang_reflect_Method != NULL);
350 java_lang_reflect_Method_ = java_lang_reflect_Method;
351}
352
Elliott Hughes80609252011-09-23 17:24:51 -0700353void Method::ResetClasses() {
354 CHECK(java_lang_reflect_Constructor_ != NULL);
355 java_lang_reflect_Constructor_ = NULL;
356
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 CHECK(java_lang_reflect_Method_ != NULL);
358 java_lang_reflect_Method_ = NULL;
359}
360
Elliott Hughes418d20f2011-09-22 14:00:39 -0700361Class* ExtractNextClassFromSignature(ClassLinker* class_linker, const ClassLoader* cl, const char*& p) {
362 if (*p == '[') {
363 // Something like "[[[Ljava/lang/String;".
364 const char* start = p;
365 while (*p == '[') {
366 ++p;
367 }
368 if (*p == 'L') {
369 while (*p != ';') {
370 ++p;
371 }
372 }
373 ++p; // Either the ';' or the primitive type.
374
375 StringPiece descriptor(start, (p - start));
376 return class_linker->FindClass(descriptor, cl);
377 } else if (*p == 'L') {
378 const char* start = p;
379 while (*p != ';') {
380 ++p;
381 }
382 ++p;
383 StringPiece descriptor(start, (p - start));
384 return class_linker->FindClass(descriptor, cl);
385 } else {
386 return class_linker->FindPrimitiveClass(*p++);
387 }
388}
389
390void Method::InitJavaFieldsLocked() {
391 // Create the array.
392 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
393 size_t arg_count = GetShorty()->GetLength() - 1;
394 Class* array_class = class_linker->FindSystemClass("[Ljava/lang/Class;");
395 ObjectArray<Class>* parameters = ObjectArray<Class>::Alloc(array_class, arg_count);
396 if (parameters == NULL) {
397 return;
398 }
399
400 // Parse the signature, filling the array.
401 const ClassLoader* cl = GetDeclaringClass()->GetClassLoader();
402 std::string signature(GetSignature()->ToModifiedUtf8());
403 const char* p = signature.c_str();
404 DCHECK_EQ(*p, '(');
405 ++p;
406 for (size_t i = 0; i < arg_count; ++i) {
407 Class* c = ExtractNextClassFromSignature(class_linker, cl, p);
408 if (c == NULL) {
409 return;
410 }
411 parameters->Set(i, c);
412 }
413
414 DCHECK_EQ(*p, ')');
415 ++p;
416
417 java_parameter_types_ = parameters;
418 java_return_type_ = ExtractNextClassFromSignature(class_linker, cl, p);
419}
420
421void Method::InitJavaFields() {
422 Thread* self = Thread::Current();
423 ScopedThreadStateChange tsc(self, Thread::kRunnable);
424 MonitorEnter(self);
425 if (java_parameter_types_ == NULL || java_return_type_ == NULL) {
426 InitJavaFieldsLocked();
427 }
428 MonitorExit(self);
429}
430
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700431ObjectArray<String>* Method::GetDexCacheStrings() const {
432 return GetFieldObject<ObjectArray<String>*>(
433 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
434}
435
436void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
437 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
438 new_return_type_idx, false);
439}
440
441Class* Method::GetReturnType() const {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700442 DCHECK(GetDeclaringClass()->IsResolved() || GetDeclaringClass()->IsErroneous());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700443 // Short-cut
444 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
445 if (result == NULL) {
446 // Do full linkage and set cache value for next call
447 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
448 }
Elliott Hughes14134a12011-09-30 16:55:51 -0700449 CHECK(result != NULL) << PrettyMethod(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700450 return result;
451}
452
453void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
454 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
455 new_dex_cache_strings, false);
456}
457
458ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
459 return GetFieldObject<ObjectArray<Class>*>(
460 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
461}
462
463void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
464 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
465 new_dex_cache_classes, false);
466}
467
468ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
469 return GetFieldObject<ObjectArray<Method>*>(
470 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
471}
472
473void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
474 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
475 new_dex_cache_methods, false);
476}
477
478ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
479 return GetFieldObject<ObjectArray<Field>*>(
480 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
481}
482
483void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
484 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
485 new_dex_cache_fields, false);
486}
487
488CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
489 return GetFieldPtr<CodeAndDirectMethods*>(
490 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
491 false);
492}
493
494void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
495 SetFieldPtr<CodeAndDirectMethods*>(
496 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
497 new_value, false);
498}
499
500ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
501 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
502 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
503 false);
504}
505
506void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
507 SetFieldObject(
508 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
509 new_value, false);
510
511}
512
513size_t Method::NumArgRegisters(const StringPiece& shorty) {
514 CHECK_LE(1, shorty.length());
515 uint32_t num_registers = 0;
516 for (int i = 1; i < shorty.length(); ++i) {
517 char ch = shorty[i];
518 if (ch == 'D' || ch == 'J') {
519 num_registers += 2;
520 } else {
521 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700522 }
523 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700524 return num_registers;
525}
526
527size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700528 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700530 for (int i = 1; i < shorty->GetLength(); ++i) {
531 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700532 if (ch == 'D' || ch == 'J') {
533 num_bytes += 8;
534 } else if (ch == 'L') {
535 // Argument is a reference or an array. The shorty descriptor
536 // does not distinguish between these types.
537 num_bytes += sizeof(Object*);
538 } else {
539 num_bytes += 4;
540 }
541 }
542 return num_bytes;
543}
544
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700545size_t Method::NumArgs() const {
546 // "1 +" because the first in Args is the receiver.
547 // "- 1" because we don't count the return type.
548 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
549}
550
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700551// The number of reference arguments to this method including implicit this
552// pointer
553size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700554 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700556 for (int i = 1; i < shorty->GetLength(); i++) {
557 char ch = shorty->CharAt(i);
558 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 result++;
560 }
561 }
562 return result;
563}
564
565// The number of long or double arguments
566size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700567 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700569 for (int i = 1; i < shorty->GetLength(); i++) {
570 char ch = shorty->CharAt(i);
571 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572 result++;
573 }
574 }
575 return result;
576}
577
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700578// Is the given method parameter a reference?
579bool Method::IsParamAReference(unsigned int param) const {
580 CHECK_LT(param, NumArgs());
581 if (IsStatic()) {
582 param++; // 0th argument must skip return value at start of the shorty
583 } else if (param == 0) {
584 return true; // this argument
585 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700586 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587}
588
589// Is the given method parameter a long or double?
590bool Method::IsParamALongOrDouble(unsigned int param) const {
591 CHECK_LT(param, NumArgs());
592 if (IsStatic()) {
593 param++; // 0th argument must skip return value at start of the shorty
594 } else if (param == 0) {
595 return false; // this argument
596 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700597 char ch = GetShorty()->CharAt(param);
598 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700599}
600
601static size_t ShortyCharToSize(char x) {
602 switch (x) {
603 case 'V': return 0;
604 case '[': return kPointerSize;
605 case 'L': return kPointerSize;
606 case 'D': return 8;
607 case 'J': return 8;
608 default: return 4;
609 }
610}
611
612size_t Method::ParamSize(unsigned int param) const {
613 CHECK_LT(param, NumArgs());
614 if (IsStatic()) {
615 param++; // 0th argument must skip return value at start of the shorty
616 } else if (param == 0) {
617 return kPointerSize; // this argument
618 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700619 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700620}
621
622size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700623 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700624}
625
626bool Method::HasSameNameAndDescriptor(const Method* that) const {
627 return (this->GetName()->Equals(that->GetName()) &&
628 this->GetSignature()->Equals(that->GetSignature()));
629}
630
Ian Rogersbdb03912011-09-14 00:55:44 -0700631uint32_t Method::ToDexPC(const uintptr_t pc) const {
632 IntArray* mapping_table = GetMappingTable();
633 if (mapping_table == NULL) {
Ian Rogers67375ac2011-09-14 00:55:44 -0700634 DCHECK(IsNative());
635 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700636 }
637 size_t mapping_table_length = mapping_table->GetLength();
638 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700639 if (GetCodeArray() != NULL) {
640 CHECK_LT(sought_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
641 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700642 uint32_t best_offset = 0;
643 uint32_t best_dex_offset = 0;
644 for (size_t i = 0; i < mapping_table_length; i += 2) {
645 uint32_t map_offset = mapping_table->Get(i);
646 uint32_t map_dex_offset = mapping_table->Get(i + 1);
647 if (map_offset == sought_offset) {
648 best_offset = map_offset;
649 best_dex_offset = map_dex_offset;
650 break;
651 }
652 if (map_offset < sought_offset && map_offset > best_offset) {
653 best_offset = map_offset;
654 best_dex_offset = map_dex_offset;
655 }
656 }
657 return best_dex_offset;
658}
659
660uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
661 IntArray* mapping_table = GetMappingTable();
662 if (mapping_table == NULL) {
663 DCHECK(dex_pc == 0);
664 return 0; // Special no mapping/pc == 0 case
665 }
666 size_t mapping_table_length = mapping_table->GetLength();
667 for (size_t i = 0; i < mapping_table_length; i += 2) {
668 uint32_t map_offset = mapping_table->Get(i);
669 uint32_t map_dex_offset = mapping_table->Get(i + 1);
670 if (map_dex_offset == dex_pc) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700671 if (GetCodeArray() != NULL) {
672 DCHECK_LT(map_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
673 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700674 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
675 }
676 }
677 LOG(FATAL) << "Looking up Dex PC not contained in method";
678 return 0;
679}
680
681uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
682 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
683 const ClassLoader* class_loader = GetDeclaringClass()->GetClassLoader();
684 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
685 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
686 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
687 // Iterate over the catch handlers associated with dex_pc
688 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
689 !iter.HasNext(); iter.Next()) {
690 uint32_t iter_type_idx = iter.Get().type_idx_;
691 // Catch all case
Elliott Hughes80609252011-09-23 17:24:51 -0700692 if (iter_type_idx == DexFile::kDexNoIndex) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700693 return iter.Get().address_;
694 }
695 // Does this catch exception type apply?
696 Class* iter_exception_type =
697 class_linker->ResolveType(dex_file, iter_type_idx, dex_cache, class_loader);
698 if (iter_exception_type->IsAssignableFrom(exception_type)) {
699 return iter.Get().address_;
700 }
701 }
702 // Handler not found
703 return DexFile::kDexNoIndex;
704}
705
Brian Carlstrome24fa612011-09-29 00:53:55 -0700706void Method::SetCodeArray(ByteArray* code_array, InstructionSet instruction_set) {
707// TODO: restore this check or warning when compile time code storage is moved out of Method
Elliott Hughes4681c802011-09-25 18:04:37 -0700708// CHECK(GetCode() == NULL || IsNative()) << PrettyMethod(this);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700709// if (GetCode() != NULL && !IsNative()) {
710// LOG(WARNING) << "Calling SetCode more than once for " << PrettyMethod(this);
711// }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700712 SetFieldPtr<ByteArray*>(OFFSET_OF_OBJECT_MEMBER(Method, code_array_), code_array, false);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700713
714 void* code;
715 if (code_array != NULL) {
716 code = code_array->GetData();
717 if (instruction_set == kThumb2) {
718 uintptr_t address = reinterpret_cast<uintptr_t>(code);
719 // Set the low-order bit so a BLX will switch to Thumb mode
720 address |= 0x1;
721 code = reinterpret_cast<void*>(address);
722 }
723 } else {
724 code = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700725 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700726 SetCode(code);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700727}
728
Ian Rogersbdb03912011-09-14 00:55:44 -0700729bool Method::IsWithinCode(uintptr_t pc) const {
Ian Rogersbdb03912011-09-14 00:55:44 -0700730 if (pc == 0) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700731 // PC of 0 represents the beginning of a stack trace either a native or where we have a callee
732 // save method that has no code
733 DCHECK(IsNative() || IsPhony());
Ian Rogersbdb03912011-09-14 00:55:44 -0700734 return true;
735 } else {
Ian Rogers93dd9662011-09-17 23:21:22 -0700736#if defined(__arm__)
737 pc &= ~0x1; // clear any possible thumb instruction mode bit
738#endif
Brian Carlstrome24fa612011-09-29 00:53:55 -0700739 if (GetCodeArray() == NULL) {
740 return true;
741 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700742 uint32_t rel_offset = pc - reinterpret_cast<uintptr_t>(GetCodeArray()->GetData());
Ian Rogers93dd9662011-09-17 23:21:22 -0700743 // Strictly the following test should be a less-than, however, if the last
744 // instruction is a call to an exception throw we may see return addresses
745 // that are 1 beyond the end of code.
746 return rel_offset <= static_cast<uint32_t>(GetCodeArray()->GetLength());
Ian Rogersbdb03912011-09-14 00:55:44 -0700747 }
748}
749
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700750void Method::SetInvokeStub(const ByteArray* invoke_stub_array) {
751 const InvokeStub* invoke_stub = reinterpret_cast<InvokeStub*>(invoke_stub_array->GetData());
752 SetFieldPtr<const ByteArray*>(
753 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_array_), invoke_stub_array, false);
754 SetFieldPtr<const InvokeStub*>(
755 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_), invoke_stub, false);
756}
757
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700758void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
759 // Push a transition back into managed code onto the linked list in thread.
760 CHECK_EQ(Thread::kRunnable, self->GetState());
761 NativeToManagedRecord record;
762 self->PushNativeToManagedRecord(&record);
763
764 // Call the invoke stub associated with the method.
765 // Pass everything as arguments.
766 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700767
768 bool have_executable_code = (GetCode() != NULL);
769#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700770 // Currently we can only compile non-native methods for ARM.
771 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700772#endif
773
774 if (have_executable_code && stub != NULL) {
775 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700776 (*stub)(this, receiver, self, args, result);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700777 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700778 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700779 if (Runtime::Current()->IsStarted()) {
780 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
781 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700782 if (result != NULL) {
783 result->j = 0;
784 }
785 }
786
787 // Pop transition.
788 self->PopNativeToManagedRecord(record);
789}
790
Brian Carlstrom16192862011-09-12 17:50:06 -0700791bool Method::IsRegistered() {
792 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
793 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
794 return native_method != jni_stub;
795}
796
797void Method::RegisterNative(const void* native_method) {
798 CHECK(IsNative());
799 CHECK(native_method != NULL);
800 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
801 native_method, false);
802}
803
804void Method::UnregisterNative() {
805 CHECK(IsNative());
806 // restore stub to lookup native pointer via dlsym
807 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
808}
809
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700810void Class::SetStatus(Status new_status) {
811 CHECK(new_status > GetStatus() || new_status == kStatusError ||
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700812 !Runtime::Current()->IsStarted()) << PrettyClass(this);
813 CHECK(sizeof(Status) == sizeof(uint32_t)) << PrettyClass(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700814 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_),
815 new_status, false);
816}
817
818DexCache* Class::GetDexCache() const {
819 return GetFieldObject<DexCache*>(
820 OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
821}
822
823void Class::SetDexCache(DexCache* new_dex_cache) {
824 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_),
825 new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700826}
827
Brian Carlstrom1f870082011-08-23 16:02:11 -0700828Object* Class::AllocObject() {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700829 DCHECK(!IsAbstract()) << PrettyClass(this);
830 DCHECK(!IsInterface()) << PrettyClass(this);
831 DCHECK(!IsPrimitive()) << PrettyClass(this);
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700832 DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700833 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700834}
835
Elliott Hughes4681c802011-09-25 18:04:37 -0700836void Class::DumpClass(std::ostream& os, int flags) const {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700837 if ((flags & kDumpClassFullDetail) == 0) {
838 os << PrettyClass(this);
839 if ((flags & kDumpClassClassLoader) != 0) {
840 os << ' ' << GetClassLoader();
841 }
842 if ((flags & kDumpClassInitialized) != 0) {
843 os << ' ' << GetStatus();
844 }
845 os << std::endl;
846 return;
847 }
848
849 Class* super = GetSuperClass();
850 os << "----- " << (IsInterface() ? "interface" : "class") << " "
851 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
852 os << " objectSize=" << SizeOf() << " "
853 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
854 os << StringPrintf(" access=0x%04x.%04x\n",
855 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
856 if (super != NULL) {
857 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
858 }
859 if (IsArrayClass()) {
860 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
861 }
862 if (NumInterfaces() > 0) {
863 os << " interfaces (" << NumInterfaces() << "):\n";
864 for (size_t i = 0; i < NumInterfaces(); ++i) {
865 Class* interface = GetInterface(i);
866 const ClassLoader* cl = interface->GetClassLoader();
867 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
868 }
869 }
870 os << " vtable (" << NumVirtualMethods() << " entries, "
871 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
872 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700873 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethodDuringLinking(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700874 }
875 os << " direct methods (" << NumDirectMethods() << " entries):\n";
876 for (size_t i = 0; i < NumDirectMethods(); ++i) {
877 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
878 }
879 if (NumStaticFields() > 0) {
880 os << " static fields (" << NumStaticFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700881 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700882 for (size_t i = 0; i < NumStaticFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700883 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700884 }
885 } else {
886 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700887 }
888 }
889 if (NumInstanceFields() > 0) {
890 os << " instance fields (" << NumInstanceFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700891 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700892 for (size_t i = 0; i < NumInstanceFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700893 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700894 }
895 } else {
896 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700897 }
898 }
899}
900
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700901void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
902 if (new_reference_offsets != CLASS_WALK_SUPER) {
903 // Sanity check that the number of bits set in the reference offset bitmap
904 // agrees with the number of references
905 Class* cur = this;
906 size_t cnt = 0;
907 while (cur) {
908 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
909 cur = cur->GetSuperClass();
910 }
911 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
912 }
913 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
914 new_reference_offsets, false);
915}
916
917void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
918 if (new_reference_offsets != CLASS_WALK_SUPER) {
919 // Sanity check that the number of bits set in the reference offset bitmap
920 // agrees with the number of references
921 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
922 NumReferenceStaticFieldsDuringLinking());
923 }
924 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
925 new_reference_offsets, false);
926}
927
928size_t Class::PrimitiveSize() const {
929 switch (GetPrimitiveType()) {
930 case kPrimBoolean:
931 case kPrimByte:
932 case kPrimChar:
933 case kPrimShort:
934 case kPrimInt:
935 case kPrimFloat:
936 return sizeof(int32_t);
937 case kPrimLong:
938 case kPrimDouble:
939 return sizeof(int64_t);
940 default:
941 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
942 return 0;
943 }
944}
945
946size_t Class::GetTypeSize(const String* descriptor) {
947 switch (descriptor->CharAt(0)) {
948 case 'B': return 1; // byte
949 case 'C': return 2; // char
950 case 'D': return 8; // double
951 case 'F': return 4; // float
952 case 'I': return 4; // int
953 case 'J': return 8; // long
954 case 'S': return 2; // short
955 case 'Z': return 1; // boolean
956 case 'L': return sizeof(Object*);
957 case '[': return sizeof(Array*);
958 default:
959 LOG(ERROR) << "Unknown type " << descriptor;
960 return 0;
961 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700962}
963
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700964bool Class::Implements(const Class* klass) const {
965 DCHECK(klass != NULL);
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700966 DCHECK(klass->IsInterface()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700967 // All interfaces implemented directly and by our superclass, and
968 // recursively all super-interfaces of those interfaces, are listed
969 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700970 int32_t iftable_count = GetIfTableCount();
971 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
972 for (int32_t i = 0; i < iftable_count; i++) {
973 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700974 return true;
975 }
976 }
977 return false;
978}
979
980// Determine whether "this" is assignable from "klazz", where both of these
981// are array classes.
982//
983// Consider an array class, e.g. Y[][], where Y is a subclass of X.
984// Y[][] = Y[][] --> true (identity)
985// X[][] = Y[][] --> true (element superclass)
986// Y = Y[][] --> false
987// Y[] = Y[][] --> false
988// Object = Y[][] --> true (everything is an object)
989// Object[] = Y[][] --> true
990// Object[][] = Y[][] --> true
991// Object[][][] = Y[][] --> false (too many []s)
992// Serializable = Y[][] --> true (all arrays are Serializable)
993// Serializable[] = Y[][] --> true
994// Serializable[][] = Y[][] --> false (unless Y is Serializable)
995//
996// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700997// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700998//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700999bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001000 DCHECK(IsArrayClass()) << PrettyClass(this);
1001 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001002 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001003}
1004
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001005bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001006 DCHECK(!IsInterface()) << PrettyClass(this); // handled first in IsAssignableFrom
1007 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstromb63ec392011-08-27 17:38:27 -07001008 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001009 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001010 // src's super should be java_lang_Object, since it is an array.
1011 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001012 DCHECK(java_lang_Object != NULL) << PrettyClass(src);
1013 DCHECK(java_lang_Object->GetSuperClass() == NULL) << PrettyClass(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001014 return this == java_lang_Object;
1015 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001016 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001017}
1018
1019bool Class::IsSubClass(const Class* klass) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001020 DCHECK(!IsInterface()) << PrettyClass(this);
1021 DCHECK(!IsArrayClass()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001022 const Class* current = this;
1023 do {
1024 if (current == klass) {
1025 return true;
1026 }
1027 current = current->GetSuperClass();
1028 } while (current != NULL);
1029 return false;
1030}
1031
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001032bool Class::IsInSamePackage(const String* descriptor_string_1,
1033 const String* descriptor_string_2) {
1034 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
1035 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
1036
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001037 size_t i = 0;
1038 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
1039 ++i;
1040 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001041 if (descriptor1.find('/', i) != StringPiece::npos ||
1042 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001043 return false;
1044 } else {
1045 return true;
1046 }
1047}
1048
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001049#if 0
Ian Rogersb033c752011-07-20 12:22:35 -07001050bool Class::IsInSamePackage(const StringPiece& descriptor1,
1051 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001052 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001053 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -07001054 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
1055 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001056 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
1057}
1058#endif
1059
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001060bool Class::IsInSamePackage(const Class* that) const {
1061 const Class* klass1 = this;
1062 const Class* klass2 = that;
1063 if (klass1 == klass2) {
1064 return true;
1065 }
1066 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001067 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001068 return false;
1069 }
1070 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -07001071 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001072 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001073 }
jeffhao4a801a42011-09-23 13:53:40 -07001074 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001075 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001076 }
1077 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001078 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001079}
1080
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001081const ClassLoader* Class::GetClassLoader() const {
1082 return GetFieldObject<const ClassLoader*>(
1083 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -07001084}
1085
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001086void Class::SetClassLoader(const ClassLoader* new_cl) {
1087 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
1088 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
1089 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001090}
1091
Brian Carlstrom30b94452011-08-25 21:35:26 -07001092Method* Class::FindVirtualMethodForInterface(Method* method) {
1093 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001094 DCHECK(declaring_class != NULL) << PrettyClass(this);
1095 DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001096 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001097 int32_t iftable_count = GetIfTableCount();
1098 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1099 for (int32_t i = 0; i < iftable_count; i++) {
1100 InterfaceEntry* interface_entry = iftable->Get(i);
1101 if (interface_entry->GetInterface() == declaring_class) {
1102 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -07001103 }
1104 }
Brian Carlstrom16192862011-09-12 17:50:06 -07001105 UNIMPLEMENTED(FATAL) << "Need to throw an error of some kind " << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001106 return NULL;
1107}
1108
jeffhaobdb76512011-09-07 11:43:16 -07001109Method* Class::FindInterfaceMethod(const StringPiece& name,
1110 const StringPiece& signature) {
1111 // Check the current class before checking the interfaces.
1112 Method* method = FindVirtualMethod(name, signature);
1113 if (method != NULL) {
1114 return method;
1115 }
1116
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001117 int32_t iftable_count = GetIfTableCount();
1118 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1119 for (int32_t i = 0; i < iftable_count; i++) {
1120 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001121 if (method != NULL) {
1122 return method;
1123 }
1124 }
1125 return NULL;
1126}
1127
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001128Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001129 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001130 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001131 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001132 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001133 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001134 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001135 }
1136 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001137 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001138}
1139
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001140Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001141 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001142 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001143 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001144 if (method != NULL) {
1145 return method;
1146 }
1147 }
1148 return NULL;
1149}
1150
1151Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001152 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001153 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001154 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001155 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001156 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001157 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001158 }
1159 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001160 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001161}
1162
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001163Method* Class::FindVirtualMethod(const StringPiece& name,
Elliott Hughescc5f9a92011-09-28 19:17:29 -07001164 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001165 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07001166 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001167 if (method != NULL) {
1168 return method;
1169 }
1170 }
1171 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001172}
1173
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001174Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001175 // Is the field in this class?
1176 // Interfaces are not relevant because they can't contain instance fields.
1177 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1178 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001179 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001180 return f;
1181 }
1182 }
1183 return NULL;
1184}
1185
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001186Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001187 // Is the field in this class, or any of its superclasses?
1188 // Interfaces are not relevant because they can't contain instance fields.
1189 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001190 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001191 if (f != NULL) {
1192 return f;
1193 }
1194 }
1195 return NULL;
1196}
1197
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001198Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
1199 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -07001200 for (size_t i = 0; i < NumStaticFields(); ++i) {
1201 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001202 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001203 return f;
1204 }
1205 }
1206 return NULL;
1207}
1208
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001209Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001210 // Is the field in this class (or its interfaces), or any of its
1211 // superclasses (or their interfaces)?
1212 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1213 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001214 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001215 if (f != NULL) {
1216 return f;
1217 }
1218
1219 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001220 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1221 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1222 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001223 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001224 if (f != NULL) {
1225 return f;
1226 }
1227 }
1228 }
1229 return NULL;
1230}
1231
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001232Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001233 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001234 DCHECK_GE(component_count, 0);
1235 DCHECK(array_class->IsArrayClass());
Elliott Hughesb408de72011-10-04 14:35:05 -07001236
1237 size_t header_size = sizeof(Array);
1238 size_t data_size = component_count * component_size;
1239 size_t size = header_size + data_size;
1240
1241 // Check for overflow and throw OutOfMemoryError if this was an unreasonable request.
1242 size_t component_shift = sizeof(size_t) * 8 - 1 - CLZ(component_size);
1243 if (data_size >> component_shift != size_t(component_count) || size < data_size) {
1244 Thread::Current()->ThrowNewExceptionF("Ljava/lang/OutOfMemoryError;",
1245 "%s of length %zd exceeds the VM limit",
1246 PrettyDescriptor(array_class->GetDescriptor()).c_str(), component_count);
1247 return NULL;
1248 }
1249
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001250 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1251 if (array != NULL) {
1252 DCHECK(array->IsArrayInstance());
1253 array->SetLength(component_count);
1254 }
Elliott Hughesb408de72011-10-04 14:35:05 -07001255
1256 // TODO: throw OutOfMemoryError. (here or in Heap::AllocObject?)
1257 CHECK(array != NULL) << PrettyClass(array_class)
1258 << " component_count=" << component_count
1259 << " component_size=" << component_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001260 return array;
1261}
1262
1263Array* Array::Alloc(Class* array_class, int32_t component_count) {
1264 return Alloc(array_class, component_count, array_class->GetComponentSize());
1265}
1266
Elliott Hughes80609252011-09-23 17:24:51 -07001267bool Array::ThrowArrayIndexOutOfBoundsException(int32_t index) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001268 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001269 "length=%i; index=%i", length_, index);
1270 return false;
1271}
1272
1273bool Array::ThrowArrayStoreException(Object* object) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001274 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001275 "Can't store an element of type %s into an array of type %s",
1276 PrettyTypeOf(object).c_str(), PrettyTypeOf(this).c_str());
1277 return false;
1278}
1279
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001280template<typename T>
1281PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001282 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001283 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1284 return down_cast<PrimitiveArray<T>*>(raw_array);
1285}
1286
1287template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1288
1289// Explicitly instantiate all the primitive array types.
1290template class PrimitiveArray<uint8_t>; // BooleanArray
1291template class PrimitiveArray<int8_t>; // ByteArray
1292template class PrimitiveArray<uint16_t>; // CharArray
1293template class PrimitiveArray<double>; // DoubleArray
1294template class PrimitiveArray<float>; // FloatArray
1295template class PrimitiveArray<int32_t>; // IntArray
1296template class PrimitiveArray<int64_t>; // LongArray
1297template class PrimitiveArray<int16_t>; // ShortArray
1298
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001299// TODO: get global references for these
1300Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001301
Brian Carlstroma663ea52011-08-19 23:33:41 -07001302void String::SetClass(Class* java_lang_String) {
1303 CHECK(java_lang_String_ == NULL);
1304 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001305 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001306}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001307
Brian Carlstroma663ea52011-08-19 23:33:41 -07001308void String::ResetClass() {
1309 CHECK(java_lang_String_ != NULL);
1310 java_lang_String_ = NULL;
1311}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001312
Brian Carlstromc74255f2011-09-11 22:47:39 -07001313String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001314 return Runtime::Current()->GetInternTable()->InternWeak(this);
1315}
1316
Brian Carlstrom395520e2011-09-25 19:35:00 -07001317int32_t String::GetHashCode() {
1318 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1319 if (result == 0) {
1320 ComputeHashCode();
1321 }
1322 result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1323 DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
1324 << ToModifiedUtf8() << " " << result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001325 return result;
1326}
1327
1328int32_t String::GetLength() const {
1329 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1330 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1331 return result;
1332}
1333
1334uint16_t String::CharAt(int32_t index) const {
1335 // TODO: do we need this? Equals is the only caller, and could
1336 // bounds check itself.
1337 if (index < 0 || index >= count_) {
1338 Thread* self = Thread::Current();
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001339 self->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;",
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001340 "length=%i; index=%i", count_, index);
1341 return 0;
1342 }
1343 return GetCharArray()->Get(index + GetOffset());
1344}
1345
1346String* String::AllocFromUtf16(int32_t utf16_length,
1347 const uint16_t* utf16_data_in,
1348 int32_t hash_code) {
1349 String* string = Alloc(GetJavaLangString(), utf16_length);
1350 // TODO: use 16-bit wide memset variant
1351 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1352 for (int i = 0; i < utf16_length; i++) {
1353 array->Set(i, utf16_data_in[i]);
1354 }
1355 if (hash_code != 0) {
1356 string->SetHashCode(hash_code);
1357 } else {
1358 string->ComputeHashCode();
1359 }
1360 return string;
1361}
1362
1363String* String::AllocFromModifiedUtf8(const char* utf) {
1364 size_t char_count = CountModifiedUtf8Chars(utf);
1365 return AllocFromModifiedUtf8(char_count, utf);
1366}
1367
1368String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1369 const char* utf8_data_in) {
1370 String* string = Alloc(GetJavaLangString(), utf16_length);
1371 uint16_t* utf16_data_out =
1372 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1373 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1374 string->ComputeHashCode();
1375 return string;
1376}
1377
1378String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1379 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1380}
1381
1382String* String::Alloc(Class* java_lang_String, CharArray* array) {
1383 String* string = down_cast<String*>(java_lang_String->AllocObject());
1384 string->SetArray(array);
1385 string->SetCount(array->GetLength());
1386 return string;
1387}
1388
1389bool String::Equals(const String* that) const {
1390 if (this == that) {
1391 // Quick reference equality test
1392 return true;
1393 } else if (that == NULL) {
1394 // Null isn't an instanceof anything
1395 return false;
1396 } else if (this->GetLength() != that->GetLength()) {
1397 // Quick length inequality test
1398 return false;
1399 } else {
Elliott Hughes20cde902011-10-04 17:37:27 -07001400 // Note: don't short circuit on hash code as we're presumably here as the
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001401 // hash code was already equal
1402 for (int32_t i = 0; i < that->GetLength(); ++i) {
1403 if (this->CharAt(i) != that->CharAt(i)) {
1404 return false;
1405 }
1406 }
1407 return true;
1408 }
1409}
1410
1411bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1412 int32_t that_length) const {
1413 if (this->GetLength() != that_length) {
1414 return false;
1415 } else {
1416 for (int32_t i = 0; i < that_length; ++i) {
1417 if (this->CharAt(i) != that_chars[that_offset + i]) {
1418 return false;
1419 }
1420 }
1421 return true;
1422 }
1423}
1424
1425bool String::Equals(const char* modified_utf8) const {
1426 for (int32_t i = 0; i < GetLength(); ++i) {
1427 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1428 if (ch == '\0' || ch != CharAt(i)) {
1429 return false;
1430 }
1431 }
1432 return *modified_utf8 == '\0';
1433}
1434
1435bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001436 if (modified_utf8.size() != GetLength()) {
1437 return false;
1438 }
1439 const char* p = modified_utf8.data();
1440 for (int32_t i = 0; i < GetLength(); ++i) {
1441 uint16_t ch = GetUtf16FromUtf8(&p);
1442 if (ch != CharAt(i)) {
1443 return false;
1444 }
1445 }
1446 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001447}
1448
1449// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1450std::string String::ToModifiedUtf8() const {
1451 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1452 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1453 std::string result(byte_count, char(0));
1454 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1455 return result;
1456}
1457
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001458Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1459
1460void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1461 CHECK(java_lang_StackTraceElement_ == NULL);
1462 CHECK(java_lang_StackTraceElement != NULL);
1463 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1464}
1465
1466void StackTraceElement::ResetClass() {
1467 CHECK(java_lang_StackTraceElement_ != NULL);
1468 java_lang_StackTraceElement_ = NULL;
1469}
1470
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001471StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1472 const String* method_name,
1473 const String* file_name,
1474 int32_t line_number) {
1475 StackTraceElement* trace =
1476 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1477 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1478 const_cast<String*>(declaring_class), false);
1479 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1480 const_cast<String*>(method_name), false);
1481 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1482 const_cast<String*>(file_name), false);
1483 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1484 line_number, false);
1485 return trace;
1486}
1487
Elliott Hughes1f359b02011-07-17 14:27:17 -07001488static const char* kClassStatusNames[] = {
1489 "Error",
1490 "NotReady",
1491 "Idx",
1492 "Loaded",
1493 "Resolved",
1494 "Verifying",
1495 "Verified",
1496 "Initializing",
1497 "Initialized"
1498};
1499std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1500 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001501 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001502 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001503 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001504 }
1505 return os;
1506}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001507
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001508} // namespace art