blob: ce37470045329fd46fad71746466ac3253a1e66a [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 Hughes20cde902011-10-04 17:37:27 -070026void Object::AddFinalizerReference() {
27 Thread* self = Thread::Current();
28
29 // TODO: cache these somewhere.
30 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
31 Class* java_lang_ref_FinalizerReference = class_linker->FindSystemClass("Ljava/lang/ref/FinalizerReference;");
32 CHECK(java_lang_ref_FinalizerReference != NULL);
33 Method* m = java_lang_ref_FinalizerReference->FindDirectMethod("add", "(Ljava/lang/Object;)V");
34 CHECK(m != NULL);
35
36 LOG(INFO) << "Object::AddFinalizerReference invoking FinalizerReference.add for " << (void*) this;
37 m->Invoke(self, NULL, reinterpret_cast<byte*>(this), NULL);
38}
39
Elliott Hughes081be7f2011-09-18 16:50:26 -070040Object* Object::Clone() {
41 Class* c = GetClass();
42 DCHECK(!c->IsClassClass());
43
44 // Object::SizeOf gets the right size even if we're an array.
45 // Using c->AllocObject() here would be wrong.
46 size_t num_bytes = SizeOf();
47 Object* copy = Heap::AllocObject(c, num_bytes);
48 if (copy == NULL) {
49 return NULL;
50 }
51
52 // Copy instance data. We assume memcpy copies by words.
53 // TODO: expose and use move32.
54 byte* src_bytes = reinterpret_cast<byte*>(this);
55 byte* dst_bytes = reinterpret_cast<byte*>(copy);
56 size_t offset = sizeof(Object);
57 memcpy(dst_bytes + offset, src_bytes + offset, num_bytes - offset);
58
Elliott Hughes20cde902011-10-04 17:37:27 -070059 if (c->IsFinalizable()) {
60 copy->AddFinalizerReference();
61 }
Elliott Hughes081be7f2011-09-18 16:50:26 -070062
63 return copy;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070064}
65
Elliott Hughes5f791332011-09-15 17:45:30 -070066uint32_t Object::GetLockOwner() {
67 return Monitor::GetLockOwner(monitor_);
68}
69
Elliott Hughes081be7f2011-09-18 16:50:26 -070070bool Object::IsString() const {
71 // TODO use "klass_ == String::GetJavaLangString()" instead?
72 return GetClass() == GetClass()->GetDescriptor()->GetClass();
73}
74
Elliott Hughes5f791332011-09-15 17:45:30 -070075void Object::MonitorEnter(Thread* thread) {
76 Monitor::MonitorEnter(thread, this);
77}
78
Ian Rogersff1ed472011-09-20 13:46:24 -070079bool Object::MonitorExit(Thread* thread) {
80 return Monitor::MonitorExit(thread, this);
Elliott Hughes5f791332011-09-15 17:45:30 -070081}
82
83void Object::Notify() {
84 Monitor::Notify(Thread::Current(), this);
85}
86
87void Object::NotifyAll() {
88 Monitor::NotifyAll(Thread::Current(), this);
89}
90
91void Object::Wait(int64_t ms, int32_t ns) {
92 Monitor::Wait(Thread::Current(), this, ms, ns, true);
93}
94
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070095// TODO: get global references for these
96Class* Field::java_lang_reflect_Field_ = NULL;
97
98void Field::SetClass(Class* java_lang_reflect_Field) {
99 CHECK(java_lang_reflect_Field_ == NULL);
100 CHECK(java_lang_reflect_Field != NULL);
101 java_lang_reflect_Field_ = java_lang_reflect_Field;
102}
103
104void Field::ResetClass() {
105 CHECK(java_lang_reflect_Field_ != NULL);
106 java_lang_reflect_Field_ = NULL;
107}
108
109void Field::SetTypeIdx(uint32_t type_idx) {
110 SetField32(OFFSET_OF_OBJECT_MEMBER(Field, type_idx_), type_idx, false);
111}
112
113Class* Field::GetTypeDuringLinking() const {
114 // We are assured that the necessary primitive types are in the dex cache
115 // early during class linking
116 return GetDeclaringClass()->GetDexCache()->GetResolvedType(GetTypeIdx());
117}
118
119Class* Field::GetType() const {
Elliott Hughes80609252011-09-23 17:24:51 -0700120 if (type_ == NULL) {
121 type_ = Runtime::Current()->GetClassLinker()->ResolveType(GetTypeIdx(), this);
122 }
123 return type_;
124}
125
126void Field::InitJavaFields() {
127 Thread* self = Thread::Current();
128 ScopedThreadStateChange tsc(self, Thread::kRunnable);
129 MonitorEnter(self);
130 if (type_ == NULL) {
131 InitJavaFieldsLocked();
132 }
133 MonitorExit(self);
134}
135
136void Field::InitJavaFieldsLocked() {
137 GetType(); // Sets type_ as a side-effect. May throw.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700138}
139
Brian Carlstrom845490b2011-09-19 15:56:53 -0700140Field* Field::FindInstanceFieldFromCode(uint32_t field_idx, const Method* referrer) {
141 return FindFieldFromCode(field_idx, referrer, false);
142}
143
144Field* Field::FindStaticFieldFromCode(uint32_t field_idx, const Method* referrer) {
145 return FindFieldFromCode(field_idx, referrer, true);
146}
147
148Field* Field::FindFieldFromCode(uint32_t field_idx, const Method* referrer, bool is_static) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700149 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom845490b2011-09-19 15:56:53 -0700150 Field* f = class_linker->ResolveField(field_idx, referrer, is_static);
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700151 if (f != NULL) {
152 Class* c = f->GetDeclaringClass();
153 // If the class is already initializing, we must be inside <clinit>, or
154 // we'd still be waiting for the lock.
Brian Carlstrom25c33252011-09-18 15:58:35 -0700155 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c, true)) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700156 return f;
157 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700158 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700159 UNIMPLEMENTED(FATAL) << "throw an error and unwind";
160 return NULL;
161}
162
163uint32_t Field::Get32StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700164 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700165 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
166 return field->Get32(NULL);
167}
168void Field::Set32StaticFromCode(uint32_t field_idx, const Method* referrer, uint32_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700169 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700170 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
171 field->Set32(NULL, new_value);
172}
173uint64_t Field::Get64StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700174 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700175 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
176 return field->Get64(NULL);
177}
178void Field::Set64StaticFromCode(uint32_t field_idx, const Method* referrer, uint64_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700179 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700180 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
181 field->Set64(NULL, new_value);
182}
183Object* Field::GetObjStaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700184 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700185 DCHECK(!field->GetType()->IsPrimitive());
186 return field->GetObj(NULL);
187}
188void Field::SetObjStaticFromCode(uint32_t field_idx, const Method* referrer, Object* new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700189 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700190 DCHECK(!field->GetType()->IsPrimitive());
191 field->SetObj(NULL, new_value);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700192}
193
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700194uint32_t Field::Get32(const Object* object) const {
195 CHECK((object == NULL) == IsStatic());
196 if (IsStatic()) {
197 object = declaring_class_;
198 }
199 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700200}
201
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700202void Field::Set32(Object* object, uint32_t new_value) const {
203 CHECK((object == NULL) == IsStatic());
204 if (IsStatic()) {
205 object = declaring_class_;
206 }
207 object->SetField32(GetOffset(), new_value, IsVolatile());
208}
209
210uint64_t Field::Get64(const Object* object) const {
211 CHECK((object == NULL) == IsStatic());
212 if (IsStatic()) {
213 object = declaring_class_;
214 }
215 return object->GetField64(GetOffset(), IsVolatile());
216}
217
218void Field::Set64(Object* object, uint64_t new_value) const {
219 CHECK((object == NULL) == IsStatic());
220 if (IsStatic()) {
221 object = declaring_class_;
222 }
223 object->SetField64(GetOffset(), new_value, IsVolatile());
224}
225
226Object* Field::GetObj(const Object* object) const {
227 CHECK((object == NULL) == IsStatic());
228 if (IsStatic()) {
229 object = declaring_class_;
230 }
231 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
232}
233
234void Field::SetObj(Object* object, const Object* new_value) const {
235 CHECK((object == NULL) == IsStatic());
236 if (IsStatic()) {
237 object = declaring_class_;
238 }
239 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
240}
241
242bool Field::GetBoolean(const Object* object) const {
243 DCHECK(GetType()->IsPrimitiveBoolean());
244 return Get32(object);
245}
246
247void Field::SetBoolean(Object* object, bool z) const {
248 DCHECK(GetType()->IsPrimitiveBoolean());
249 Set32(object, z);
250}
251
252int8_t Field::GetByte(const Object* object) const {
253 DCHECK(GetType()->IsPrimitiveByte());
254 return Get32(object);
255}
256
257void Field::SetByte(Object* object, int8_t b) const {
258 DCHECK(GetType()->IsPrimitiveByte());
259 Set32(object, b);
260}
261
262uint16_t Field::GetChar(const Object* object) const {
263 DCHECK(GetType()->IsPrimitiveChar());
264 return Get32(object);
265}
266
267void Field::SetChar(Object* object, uint16_t c) const {
268 DCHECK(GetType()->IsPrimitiveChar());
269 Set32(object, c);
270}
271
272uint16_t Field::GetShort(const Object* object) const {
273 DCHECK(GetType()->IsPrimitiveShort());
274 return Get32(object);
275}
276
277void Field::SetShort(Object* object, uint16_t s) const {
278 DCHECK(GetType()->IsPrimitiveShort());
279 Set32(object, s);
280}
281
282int32_t Field::GetInt(const Object* object) const {
283 DCHECK(GetType()->IsPrimitiveInt());
284 return Get32(object);
285}
286
287void Field::SetInt(Object* object, int32_t i) const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700288 DCHECK(GetType()->IsPrimitiveInt()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289 Set32(object, i);
290}
291
292int64_t Field::GetLong(const Object* object) const {
293 DCHECK(GetType()->IsPrimitiveLong());
294 return Get64(object);
295}
296
297void Field::SetLong(Object* object, int64_t j) const {
298 DCHECK(GetType()->IsPrimitiveLong());
299 Set64(object, j);
300}
301
302float Field::GetFloat(const Object* object) const {
303 DCHECK(GetType()->IsPrimitiveFloat());
304 JValue float_bits;
305 float_bits.i = Get32(object);
306 return float_bits.f;
307}
308
309void Field::SetFloat(Object* object, float f) const {
310 DCHECK(GetType()->IsPrimitiveFloat());
311 JValue float_bits;
312 float_bits.f = f;
313 Set32(object, float_bits.i);
314}
315
316double Field::GetDouble(const Object* object) const {
317 DCHECK(GetType()->IsPrimitiveDouble());
318 JValue double_bits;
319 double_bits.j = Get64(object);
320 return double_bits.d;
321}
322
323void Field::SetDouble(Object* object, double d) const {
324 DCHECK(GetType()->IsPrimitiveDouble());
325 JValue double_bits;
326 double_bits.d = d;
327 Set64(object, double_bits.j);
328}
329
330Object* Field::GetObject(const Object* object) const {
331 CHECK(!GetType()->IsPrimitive());
332 return GetObj(object);
333}
334
335void Field::SetObject(Object* object, const Object* l) const {
336 CHECK(!GetType()->IsPrimitive());
337 SetObj(object, l);
338}
339
340// TODO: get global references for these
Elliott Hughes80609252011-09-23 17:24:51 -0700341Class* Method::java_lang_reflect_Constructor_ = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342Class* Method::java_lang_reflect_Method_ = NULL;
343
Elliott Hughes80609252011-09-23 17:24:51 -0700344void Method::SetClasses(Class* java_lang_reflect_Constructor, Class* java_lang_reflect_Method) {
345 CHECK(java_lang_reflect_Constructor_ == NULL);
346 CHECK(java_lang_reflect_Constructor != NULL);
347 java_lang_reflect_Constructor_ = java_lang_reflect_Constructor;
348
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349 CHECK(java_lang_reflect_Method_ == NULL);
350 CHECK(java_lang_reflect_Method != NULL);
351 java_lang_reflect_Method_ = java_lang_reflect_Method;
352}
353
Elliott Hughes80609252011-09-23 17:24:51 -0700354void Method::ResetClasses() {
355 CHECK(java_lang_reflect_Constructor_ != NULL);
356 java_lang_reflect_Constructor_ = NULL;
357
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358 CHECK(java_lang_reflect_Method_ != NULL);
359 java_lang_reflect_Method_ = NULL;
360}
361
Elliott Hughes418d20f2011-09-22 14:00:39 -0700362Class* ExtractNextClassFromSignature(ClassLinker* class_linker, const ClassLoader* cl, const char*& p) {
363 if (*p == '[') {
364 // Something like "[[[Ljava/lang/String;".
365 const char* start = p;
366 while (*p == '[') {
367 ++p;
368 }
369 if (*p == 'L') {
370 while (*p != ';') {
371 ++p;
372 }
373 }
374 ++p; // Either the ';' or the primitive type.
375
376 StringPiece descriptor(start, (p - start));
377 return class_linker->FindClass(descriptor, cl);
378 } else if (*p == 'L') {
379 const char* start = p;
380 while (*p != ';') {
381 ++p;
382 }
383 ++p;
384 StringPiece descriptor(start, (p - start));
385 return class_linker->FindClass(descriptor, cl);
386 } else {
387 return class_linker->FindPrimitiveClass(*p++);
388 }
389}
390
391void Method::InitJavaFieldsLocked() {
392 // Create the array.
393 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
394 size_t arg_count = GetShorty()->GetLength() - 1;
395 Class* array_class = class_linker->FindSystemClass("[Ljava/lang/Class;");
396 ObjectArray<Class>* parameters = ObjectArray<Class>::Alloc(array_class, arg_count);
397 if (parameters == NULL) {
398 return;
399 }
400
401 // Parse the signature, filling the array.
402 const ClassLoader* cl = GetDeclaringClass()->GetClassLoader();
403 std::string signature(GetSignature()->ToModifiedUtf8());
404 const char* p = signature.c_str();
405 DCHECK_EQ(*p, '(');
406 ++p;
407 for (size_t i = 0; i < arg_count; ++i) {
408 Class* c = ExtractNextClassFromSignature(class_linker, cl, p);
409 if (c == NULL) {
410 return;
411 }
412 parameters->Set(i, c);
413 }
414
415 DCHECK_EQ(*p, ')');
416 ++p;
417
418 java_parameter_types_ = parameters;
419 java_return_type_ = ExtractNextClassFromSignature(class_linker, cl, p);
420}
421
422void Method::InitJavaFields() {
423 Thread* self = Thread::Current();
424 ScopedThreadStateChange tsc(self, Thread::kRunnable);
425 MonitorEnter(self);
426 if (java_parameter_types_ == NULL || java_return_type_ == NULL) {
427 InitJavaFieldsLocked();
428 }
429 MonitorExit(self);
430}
431
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700432ObjectArray<String>* Method::GetDexCacheStrings() const {
433 return GetFieldObject<ObjectArray<String>*>(
434 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
435}
436
437void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
438 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
439 new_return_type_idx, false);
440}
441
442Class* Method::GetReturnType() const {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700443 DCHECK(GetDeclaringClass()->IsResolved() || GetDeclaringClass()->IsErroneous());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444 // Short-cut
445 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
446 if (result == NULL) {
447 // Do full linkage and set cache value for next call
448 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
449 }
Elliott Hughes14134a12011-09-30 16:55:51 -0700450 CHECK(result != NULL) << PrettyMethod(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700451 return result;
452}
453
454void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
455 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
456 new_dex_cache_strings, false);
457}
458
459ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
460 return GetFieldObject<ObjectArray<Class>*>(
461 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
462}
463
464void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
465 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
466 new_dex_cache_classes, false);
467}
468
469ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
470 return GetFieldObject<ObjectArray<Method>*>(
471 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
472}
473
474void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
475 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
476 new_dex_cache_methods, false);
477}
478
479ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
480 return GetFieldObject<ObjectArray<Field>*>(
481 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
482}
483
484void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
485 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
486 new_dex_cache_fields, false);
487}
488
489CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
490 return GetFieldPtr<CodeAndDirectMethods*>(
491 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
492 false);
493}
494
495void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
496 SetFieldPtr<CodeAndDirectMethods*>(
497 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
498 new_value, false);
499}
500
501ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
502 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
503 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
504 false);
505}
506
507void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
508 SetFieldObject(
509 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
510 new_value, false);
511
512}
513
514size_t Method::NumArgRegisters(const StringPiece& shorty) {
515 CHECK_LE(1, shorty.length());
516 uint32_t num_registers = 0;
517 for (int i = 1; i < shorty.length(); ++i) {
518 char ch = shorty[i];
519 if (ch == 'D' || ch == 'J') {
520 num_registers += 2;
521 } else {
522 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700523 }
524 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525 return num_registers;
526}
527
528size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700529 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700530 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700531 for (int i = 1; i < shorty->GetLength(); ++i) {
532 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700533 if (ch == 'D' || ch == 'J') {
534 num_bytes += 8;
535 } else if (ch == 'L') {
536 // Argument is a reference or an array. The shorty descriptor
537 // does not distinguish between these types.
538 num_bytes += sizeof(Object*);
539 } else {
540 num_bytes += 4;
541 }
542 }
543 return num_bytes;
544}
545
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700546size_t Method::NumArgs() const {
547 // "1 +" because the first in Args is the receiver.
548 // "- 1" because we don't count the return type.
549 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
550}
551
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700552// The number of reference arguments to this method including implicit this
553// pointer
554size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700555 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700556 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700557 for (int i = 1; i < shorty->GetLength(); i++) {
558 char ch = shorty->CharAt(i);
559 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700560 result++;
561 }
562 }
563 return result;
564}
565
566// The number of long or double arguments
567size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700568 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700569 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700570 for (int i = 1; i < shorty->GetLength(); i++) {
571 char ch = shorty->CharAt(i);
572 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700573 result++;
574 }
575 }
576 return result;
577}
578
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700579// Is the given method parameter a reference?
580bool Method::IsParamAReference(unsigned int param) const {
581 CHECK_LT(param, NumArgs());
582 if (IsStatic()) {
583 param++; // 0th argument must skip return value at start of the shorty
584 } else if (param == 0) {
585 return true; // this argument
586 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700587 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700588}
589
590// Is the given method parameter a long or double?
591bool Method::IsParamALongOrDouble(unsigned int param) const {
592 CHECK_LT(param, NumArgs());
593 if (IsStatic()) {
594 param++; // 0th argument must skip return value at start of the shorty
595 } else if (param == 0) {
596 return false; // this argument
597 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700598 char ch = GetShorty()->CharAt(param);
599 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700600}
601
602static size_t ShortyCharToSize(char x) {
603 switch (x) {
604 case 'V': return 0;
605 case '[': return kPointerSize;
606 case 'L': return kPointerSize;
607 case 'D': return 8;
608 case 'J': return 8;
609 default: return 4;
610 }
611}
612
613size_t Method::ParamSize(unsigned int param) const {
614 CHECK_LT(param, NumArgs());
615 if (IsStatic()) {
616 param++; // 0th argument must skip return value at start of the shorty
617 } else if (param == 0) {
618 return kPointerSize; // this argument
619 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700620 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700621}
622
623size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700624 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700625}
626
627bool Method::HasSameNameAndDescriptor(const Method* that) const {
628 return (this->GetName()->Equals(that->GetName()) &&
629 this->GetSignature()->Equals(that->GetSignature()));
630}
631
Ian Rogersbdb03912011-09-14 00:55:44 -0700632uint32_t Method::ToDexPC(const uintptr_t pc) const {
633 IntArray* mapping_table = GetMappingTable();
634 if (mapping_table == NULL) {
Ian Rogers67375ac2011-09-14 00:55:44 -0700635 DCHECK(IsNative());
636 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700637 }
638 size_t mapping_table_length = mapping_table->GetLength();
639 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700640 if (GetCodeArray() != NULL) {
641 CHECK_LT(sought_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
642 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700643 uint32_t best_offset = 0;
644 uint32_t best_dex_offset = 0;
645 for (size_t i = 0; i < mapping_table_length; i += 2) {
646 uint32_t map_offset = mapping_table->Get(i);
647 uint32_t map_dex_offset = mapping_table->Get(i + 1);
648 if (map_offset == sought_offset) {
649 best_offset = map_offset;
650 best_dex_offset = map_dex_offset;
651 break;
652 }
653 if (map_offset < sought_offset && map_offset > best_offset) {
654 best_offset = map_offset;
655 best_dex_offset = map_dex_offset;
656 }
657 }
658 return best_dex_offset;
659}
660
661uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
662 IntArray* mapping_table = GetMappingTable();
663 if (mapping_table == NULL) {
664 DCHECK(dex_pc == 0);
665 return 0; // Special no mapping/pc == 0 case
666 }
667 size_t mapping_table_length = mapping_table->GetLength();
668 for (size_t i = 0; i < mapping_table_length; i += 2) {
669 uint32_t map_offset = mapping_table->Get(i);
670 uint32_t map_dex_offset = mapping_table->Get(i + 1);
671 if (map_dex_offset == dex_pc) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700672 if (GetCodeArray() != NULL) {
673 DCHECK_LT(map_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
674 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700675 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
676 }
677 }
678 LOG(FATAL) << "Looking up Dex PC not contained in method";
679 return 0;
680}
681
682uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
683 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
684 const ClassLoader* class_loader = GetDeclaringClass()->GetClassLoader();
685 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
686 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
687 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
688 // Iterate over the catch handlers associated with dex_pc
689 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
690 !iter.HasNext(); iter.Next()) {
691 uint32_t iter_type_idx = iter.Get().type_idx_;
692 // Catch all case
Elliott Hughes80609252011-09-23 17:24:51 -0700693 if (iter_type_idx == DexFile::kDexNoIndex) {
Ian Rogersbdb03912011-09-14 00:55:44 -0700694 return iter.Get().address_;
695 }
696 // Does this catch exception type apply?
697 Class* iter_exception_type =
698 class_linker->ResolveType(dex_file, iter_type_idx, dex_cache, class_loader);
699 if (iter_exception_type->IsAssignableFrom(exception_type)) {
700 return iter.Get().address_;
701 }
702 }
703 // Handler not found
704 return DexFile::kDexNoIndex;
705}
706
Brian Carlstrome24fa612011-09-29 00:53:55 -0700707void Method::SetCodeArray(ByteArray* code_array, InstructionSet instruction_set) {
708// TODO: restore this check or warning when compile time code storage is moved out of Method
Elliott Hughes4681c802011-09-25 18:04:37 -0700709// CHECK(GetCode() == NULL || IsNative()) << PrettyMethod(this);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700710// if (GetCode() != NULL && !IsNative()) {
711// LOG(WARNING) << "Calling SetCode more than once for " << PrettyMethod(this);
712// }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700713 SetFieldPtr<ByteArray*>(OFFSET_OF_OBJECT_MEMBER(Method, code_array_), code_array, false);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700714
715 void* code;
716 if (code_array != NULL) {
717 code = code_array->GetData();
718 if (instruction_set == kThumb2) {
719 uintptr_t address = reinterpret_cast<uintptr_t>(code);
720 // Set the low-order bit so a BLX will switch to Thumb mode
721 address |= 0x1;
722 code = reinterpret_cast<void*>(address);
723 }
724 } else {
725 code = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700726 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700727 SetCode(code);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700728}
729
Ian Rogersbdb03912011-09-14 00:55:44 -0700730bool Method::IsWithinCode(uintptr_t pc) const {
Ian Rogersbdb03912011-09-14 00:55:44 -0700731 if (pc == 0) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700732 // PC of 0 represents the beginning of a stack trace either a native or where we have a callee
733 // save method that has no code
734 DCHECK(IsNative() || IsPhony());
Ian Rogersbdb03912011-09-14 00:55:44 -0700735 return true;
736 } else {
Ian Rogers93dd9662011-09-17 23:21:22 -0700737#if defined(__arm__)
738 pc &= ~0x1; // clear any possible thumb instruction mode bit
739#endif
Brian Carlstrome24fa612011-09-29 00:53:55 -0700740 if (GetCodeArray() == NULL) {
741 return true;
742 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700743 uint32_t rel_offset = pc - reinterpret_cast<uintptr_t>(GetCodeArray()->GetData());
Ian Rogers93dd9662011-09-17 23:21:22 -0700744 // Strictly the following test should be a less-than, however, if the last
745 // instruction is a call to an exception throw we may see return addresses
746 // that are 1 beyond the end of code.
747 return rel_offset <= static_cast<uint32_t>(GetCodeArray()->GetLength());
Ian Rogersbdb03912011-09-14 00:55:44 -0700748 }
749}
750
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700751void Method::SetInvokeStub(const ByteArray* invoke_stub_array) {
752 const InvokeStub* invoke_stub = reinterpret_cast<InvokeStub*>(invoke_stub_array->GetData());
753 SetFieldPtr<const ByteArray*>(
754 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_array_), invoke_stub_array, false);
755 SetFieldPtr<const InvokeStub*>(
756 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_), invoke_stub, false);
757}
758
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700759void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
760 // Push a transition back into managed code onto the linked list in thread.
761 CHECK_EQ(Thread::kRunnable, self->GetState());
762 NativeToManagedRecord record;
763 self->PushNativeToManagedRecord(&record);
764
765 // Call the invoke stub associated with the method.
766 // Pass everything as arguments.
767 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700768
769 bool have_executable_code = (GetCode() != NULL);
770#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700771 // Currently we can only compile non-native methods for ARM.
772 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700773#endif
774
775 if (have_executable_code && stub != NULL) {
776 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700777 (*stub)(this, receiver, self, args, result);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700778 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700779 } else {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700780 if (Runtime::Current()->IsStarted()) {
781 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
782 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700783 if (result != NULL) {
784 result->j = 0;
785 }
786 }
787
788 // Pop transition.
789 self->PopNativeToManagedRecord(record);
790}
791
Brian Carlstrom16192862011-09-12 17:50:06 -0700792bool Method::IsRegistered() {
793 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
794 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
795 return native_method != jni_stub;
796}
797
798void Method::RegisterNative(const void* native_method) {
799 CHECK(IsNative());
800 CHECK(native_method != NULL);
801 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
802 native_method, false);
803}
804
805void Method::UnregisterNative() {
806 CHECK(IsNative());
807 // restore stub to lookup native pointer via dlsym
808 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
809}
810
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700811void Class::SetStatus(Status new_status) {
812 CHECK(new_status > GetStatus() || new_status == kStatusError ||
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700813 !Runtime::Current()->IsStarted()) << PrettyClass(this);
814 CHECK(sizeof(Status) == sizeof(uint32_t)) << PrettyClass(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700815 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_),
816 new_status, false);
817}
818
819DexCache* Class::GetDexCache() const {
820 return GetFieldObject<DexCache*>(
821 OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
822}
823
824void Class::SetDexCache(DexCache* new_dex_cache) {
825 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_),
826 new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700827}
828
Brian Carlstrom1f870082011-08-23 16:02:11 -0700829Object* Class::AllocObject() {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700830 DCHECK(!IsAbstract()) << PrettyClass(this);
831 DCHECK(!IsInterface()) << PrettyClass(this);
832 DCHECK(!IsPrimitive()) << PrettyClass(this);
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700833 DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700834 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700835}
836
Elliott Hughes4681c802011-09-25 18:04:37 -0700837void Class::DumpClass(std::ostream& os, int flags) const {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700838 if ((flags & kDumpClassFullDetail) == 0) {
839 os << PrettyClass(this);
840 if ((flags & kDumpClassClassLoader) != 0) {
841 os << ' ' << GetClassLoader();
842 }
843 if ((flags & kDumpClassInitialized) != 0) {
844 os << ' ' << GetStatus();
845 }
846 os << std::endl;
847 return;
848 }
849
850 Class* super = GetSuperClass();
851 os << "----- " << (IsInterface() ? "interface" : "class") << " "
852 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
853 os << " objectSize=" << SizeOf() << " "
854 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
855 os << StringPrintf(" access=0x%04x.%04x\n",
856 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
857 if (super != NULL) {
858 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
859 }
860 if (IsArrayClass()) {
861 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
862 }
863 if (NumInterfaces() > 0) {
864 os << " interfaces (" << NumInterfaces() << "):\n";
865 for (size_t i = 0; i < NumInterfaces(); ++i) {
866 Class* interface = GetInterface(i);
867 const ClassLoader* cl = interface->GetClassLoader();
868 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
869 }
870 }
871 os << " vtable (" << NumVirtualMethods() << " entries, "
872 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
873 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700874 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethodDuringLinking(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700875 }
876 os << " direct methods (" << NumDirectMethods() << " entries):\n";
877 for (size_t i = 0; i < NumDirectMethods(); ++i) {
878 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
879 }
880 if (NumStaticFields() > 0) {
881 os << " static fields (" << NumStaticFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700882 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700883 for (size_t i = 0; i < NumStaticFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700884 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700885 }
886 } else {
887 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700888 }
889 }
890 if (NumInstanceFields() > 0) {
891 os << " instance fields (" << NumInstanceFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700892 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700893 for (size_t i = 0; i < NumInstanceFields(); ++i) {
Elliott Hughes03f03492011-09-26 13:38:08 -0700894 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700895 }
896 } else {
897 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700898 }
899 }
900}
901
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700902void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
903 if (new_reference_offsets != CLASS_WALK_SUPER) {
904 // Sanity check that the number of bits set in the reference offset bitmap
905 // agrees with the number of references
906 Class* cur = this;
907 size_t cnt = 0;
908 while (cur) {
909 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
910 cur = cur->GetSuperClass();
911 }
912 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
913 }
914 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
915 new_reference_offsets, false);
916}
917
918void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
919 if (new_reference_offsets != CLASS_WALK_SUPER) {
920 // Sanity check that the number of bits set in the reference offset bitmap
921 // agrees with the number of references
922 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
923 NumReferenceStaticFieldsDuringLinking());
924 }
925 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
926 new_reference_offsets, false);
927}
928
929size_t Class::PrimitiveSize() const {
930 switch (GetPrimitiveType()) {
931 case kPrimBoolean:
932 case kPrimByte:
933 case kPrimChar:
934 case kPrimShort:
935 case kPrimInt:
936 case kPrimFloat:
937 return sizeof(int32_t);
938 case kPrimLong:
939 case kPrimDouble:
940 return sizeof(int64_t);
941 default:
942 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
943 return 0;
944 }
945}
946
947size_t Class::GetTypeSize(const String* descriptor) {
948 switch (descriptor->CharAt(0)) {
949 case 'B': return 1; // byte
950 case 'C': return 2; // char
951 case 'D': return 8; // double
952 case 'F': return 4; // float
953 case 'I': return 4; // int
954 case 'J': return 8; // long
955 case 'S': return 2; // short
956 case 'Z': return 1; // boolean
957 case 'L': return sizeof(Object*);
958 case '[': return sizeof(Array*);
959 default:
960 LOG(ERROR) << "Unknown type " << descriptor;
961 return 0;
962 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700963}
964
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700965bool Class::Implements(const Class* klass) const {
966 DCHECK(klass != NULL);
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700967 DCHECK(klass->IsInterface()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700968 // All interfaces implemented directly and by our superclass, and
969 // recursively all super-interfaces of those interfaces, are listed
970 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700971 int32_t iftable_count = GetIfTableCount();
972 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
973 for (int32_t i = 0; i < iftable_count; i++) {
974 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700975 return true;
976 }
977 }
978 return false;
979}
980
981// Determine whether "this" is assignable from "klazz", where both of these
982// are array classes.
983//
984// Consider an array class, e.g. Y[][], where Y is a subclass of X.
985// Y[][] = Y[][] --> true (identity)
986// X[][] = Y[][] --> true (element superclass)
987// Y = Y[][] --> false
988// Y[] = Y[][] --> false
989// Object = Y[][] --> true (everything is an object)
990// Object[] = Y[][] --> true
991// Object[][] = Y[][] --> true
992// Object[][][] = Y[][] --> false (too many []s)
993// Serializable = Y[][] --> true (all arrays are Serializable)
994// Serializable[] = Y[][] --> true
995// Serializable[][] = Y[][] --> false (unless Y is Serializable)
996//
997// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700998// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700999//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001000bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001001 DCHECK(IsArrayClass()) << PrettyClass(this);
1002 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001003 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001004}
1005
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001006bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001007 DCHECK(!IsInterface()) << PrettyClass(this); // handled first in IsAssignableFrom
1008 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstromb63ec392011-08-27 17:38:27 -07001009 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001010 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001011 // src's super should be java_lang_Object, since it is an array.
1012 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001013 DCHECK(java_lang_Object != NULL) << PrettyClass(src);
1014 DCHECK(java_lang_Object->GetSuperClass() == NULL) << PrettyClass(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001015 return this == java_lang_Object;
1016 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001017 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001018}
1019
1020bool Class::IsSubClass(const Class* klass) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001021 DCHECK(!IsInterface()) << PrettyClass(this);
1022 DCHECK(!IsArrayClass()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001023 const Class* current = this;
1024 do {
1025 if (current == klass) {
1026 return true;
1027 }
1028 current = current->GetSuperClass();
1029 } while (current != NULL);
1030 return false;
1031}
1032
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001033bool Class::IsInSamePackage(const String* descriptor_string_1,
1034 const String* descriptor_string_2) {
1035 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
1036 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
1037
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001038 size_t i = 0;
1039 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
1040 ++i;
1041 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001042 if (descriptor1.find('/', i) != StringPiece::npos ||
1043 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001044 return false;
1045 } else {
1046 return true;
1047 }
1048}
1049
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001050#if 0
Ian Rogersb033c752011-07-20 12:22:35 -07001051bool Class::IsInSamePackage(const StringPiece& descriptor1,
1052 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001053 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001054 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -07001055 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
1056 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001057 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
1058}
1059#endif
1060
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001061bool Class::IsInSamePackage(const Class* that) const {
1062 const Class* klass1 = this;
1063 const Class* klass2 = that;
1064 if (klass1 == klass2) {
1065 return true;
1066 }
1067 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001068 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001069 return false;
1070 }
1071 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -07001072 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001073 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001074 }
jeffhao4a801a42011-09-23 13:53:40 -07001075 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001076 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001077 }
1078 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001079 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001080}
1081
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001082const ClassLoader* Class::GetClassLoader() const {
1083 return GetFieldObject<const ClassLoader*>(
1084 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -07001085}
1086
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001087void Class::SetClassLoader(const ClassLoader* new_cl) {
1088 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
1089 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
1090 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001091}
1092
Brian Carlstrom30b94452011-08-25 21:35:26 -07001093Method* Class::FindVirtualMethodForInterface(Method* method) {
1094 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001095 DCHECK(declaring_class != NULL) << PrettyClass(this);
1096 DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001097 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001098 int32_t iftable_count = GetIfTableCount();
1099 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1100 for (int32_t i = 0; i < iftable_count; i++) {
1101 InterfaceEntry* interface_entry = iftable->Get(i);
1102 if (interface_entry->GetInterface() == declaring_class) {
1103 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -07001104 }
1105 }
Brian Carlstrom16192862011-09-12 17:50:06 -07001106 UNIMPLEMENTED(FATAL) << "Need to throw an error of some kind " << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001107 return NULL;
1108}
1109
jeffhaobdb76512011-09-07 11:43:16 -07001110Method* Class::FindInterfaceMethod(const StringPiece& name,
1111 const StringPiece& signature) {
1112 // Check the current class before checking the interfaces.
1113 Method* method = FindVirtualMethod(name, signature);
1114 if (method != NULL) {
1115 return method;
1116 }
1117
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001118 int32_t iftable_count = GetIfTableCount();
1119 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1120 for (int32_t i = 0; i < iftable_count; i++) {
1121 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001122 if (method != NULL) {
1123 return method;
1124 }
1125 }
1126 return NULL;
1127}
1128
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001129Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001130 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001131 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001132 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001133 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001134 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001135 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001136 }
1137 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001138 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001139}
1140
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001141Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001142 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001143 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001144 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001145 if (method != NULL) {
1146 return method;
1147 }
1148 }
1149 return NULL;
1150}
1151
1152Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001153 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001154 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001155 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001156 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001157 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001158 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001159 }
1160 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001161 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001162}
1163
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001164Method* Class::FindVirtualMethod(const StringPiece& name,
Elliott Hughescc5f9a92011-09-28 19:17:29 -07001165 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001166 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07001167 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001168 if (method != NULL) {
1169 return method;
1170 }
1171 }
1172 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001173}
1174
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001175Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001176 // Is the field in this class?
1177 // Interfaces are not relevant because they can't contain instance fields.
1178 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1179 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001180 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001181 return f;
1182 }
1183 }
1184 return NULL;
1185}
1186
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001187Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001188 // Is the field in this class, or any of its superclasses?
1189 // Interfaces are not relevant because they can't contain instance fields.
1190 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001191 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001192 if (f != NULL) {
1193 return f;
1194 }
1195 }
1196 return NULL;
1197}
1198
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001199Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
1200 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -07001201 for (size_t i = 0; i < NumStaticFields(); ++i) {
1202 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001203 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001204 return f;
1205 }
1206 }
1207 return NULL;
1208}
1209
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001210Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001211 // Is the field in this class (or its interfaces), or any of its
1212 // superclasses (or their interfaces)?
1213 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1214 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001215 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001216 if (f != NULL) {
1217 return f;
1218 }
1219
1220 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001221 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1222 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1223 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001224 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001225 if (f != NULL) {
1226 return f;
1227 }
1228 }
1229 }
1230 return NULL;
1231}
1232
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001233Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001234 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001235 DCHECK_GE(component_count, 0);
1236 DCHECK(array_class->IsArrayClass());
Elliott Hughesb408de72011-10-04 14:35:05 -07001237
1238 size_t header_size = sizeof(Array);
1239 size_t data_size = component_count * component_size;
1240 size_t size = header_size + data_size;
1241
1242 // Check for overflow and throw OutOfMemoryError if this was an unreasonable request.
1243 size_t component_shift = sizeof(size_t) * 8 - 1 - CLZ(component_size);
1244 if (data_size >> component_shift != size_t(component_count) || size < data_size) {
1245 Thread::Current()->ThrowNewExceptionF("Ljava/lang/OutOfMemoryError;",
1246 "%s of length %zd exceeds the VM limit",
1247 PrettyDescriptor(array_class->GetDescriptor()).c_str(), component_count);
1248 return NULL;
1249 }
1250
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001251 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1252 if (array != NULL) {
1253 DCHECK(array->IsArrayInstance());
1254 array->SetLength(component_count);
1255 }
Elliott Hughesb408de72011-10-04 14:35:05 -07001256
1257 // TODO: throw OutOfMemoryError. (here or in Heap::AllocObject?)
1258 CHECK(array != NULL) << PrettyClass(array_class)
1259 << " component_count=" << component_count
1260 << " component_size=" << component_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001261 return array;
1262}
1263
1264Array* Array::Alloc(Class* array_class, int32_t component_count) {
1265 return Alloc(array_class, component_count, array_class->GetComponentSize());
1266}
1267
Elliott Hughes80609252011-09-23 17:24:51 -07001268bool Array::ThrowArrayIndexOutOfBoundsException(int32_t index) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001269 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001270 "length=%i; index=%i", length_, index);
1271 return false;
1272}
1273
1274bool Array::ThrowArrayStoreException(Object* object) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001275 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001276 "Can't store an element of type %s into an array of type %s",
1277 PrettyTypeOf(object).c_str(), PrettyTypeOf(this).c_str());
1278 return false;
1279}
1280
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001281template<typename T>
1282PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001283 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001284 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1285 return down_cast<PrimitiveArray<T>*>(raw_array);
1286}
1287
1288template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1289
1290// Explicitly instantiate all the primitive array types.
1291template class PrimitiveArray<uint8_t>; // BooleanArray
1292template class PrimitiveArray<int8_t>; // ByteArray
1293template class PrimitiveArray<uint16_t>; // CharArray
1294template class PrimitiveArray<double>; // DoubleArray
1295template class PrimitiveArray<float>; // FloatArray
1296template class PrimitiveArray<int32_t>; // IntArray
1297template class PrimitiveArray<int64_t>; // LongArray
1298template class PrimitiveArray<int16_t>; // ShortArray
1299
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001300// TODO: get global references for these
1301Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001302
Brian Carlstroma663ea52011-08-19 23:33:41 -07001303void String::SetClass(Class* java_lang_String) {
1304 CHECK(java_lang_String_ == NULL);
1305 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001306 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001307}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001308
Brian Carlstroma663ea52011-08-19 23:33:41 -07001309void String::ResetClass() {
1310 CHECK(java_lang_String_ != NULL);
1311 java_lang_String_ = NULL;
1312}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001313
Brian Carlstromc74255f2011-09-11 22:47:39 -07001314String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001315 return Runtime::Current()->GetInternTable()->InternWeak(this);
1316}
1317
Brian Carlstrom395520e2011-09-25 19:35:00 -07001318int32_t String::GetHashCode() {
1319 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1320 if (result == 0) {
1321 ComputeHashCode();
1322 }
1323 result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1324 DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
1325 << ToModifiedUtf8() << " " << result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001326 return result;
1327}
1328
1329int32_t String::GetLength() const {
1330 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1331 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1332 return result;
1333}
1334
1335uint16_t String::CharAt(int32_t index) const {
1336 // TODO: do we need this? Equals is the only caller, and could
1337 // bounds check itself.
1338 if (index < 0 || index >= count_) {
1339 Thread* self = Thread::Current();
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001340 self->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;",
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001341 "length=%i; index=%i", count_, index);
1342 return 0;
1343 }
1344 return GetCharArray()->Get(index + GetOffset());
1345}
1346
1347String* String::AllocFromUtf16(int32_t utf16_length,
1348 const uint16_t* utf16_data_in,
1349 int32_t hash_code) {
1350 String* string = Alloc(GetJavaLangString(), utf16_length);
1351 // TODO: use 16-bit wide memset variant
1352 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1353 for (int i = 0; i < utf16_length; i++) {
1354 array->Set(i, utf16_data_in[i]);
1355 }
1356 if (hash_code != 0) {
1357 string->SetHashCode(hash_code);
1358 } else {
1359 string->ComputeHashCode();
1360 }
1361 return string;
1362}
1363
1364String* String::AllocFromModifiedUtf8(const char* utf) {
1365 size_t char_count = CountModifiedUtf8Chars(utf);
1366 return AllocFromModifiedUtf8(char_count, utf);
1367}
1368
1369String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1370 const char* utf8_data_in) {
1371 String* string = Alloc(GetJavaLangString(), utf16_length);
1372 uint16_t* utf16_data_out =
1373 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1374 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1375 string->ComputeHashCode();
1376 return string;
1377}
1378
1379String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1380 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1381}
1382
1383String* String::Alloc(Class* java_lang_String, CharArray* array) {
1384 String* string = down_cast<String*>(java_lang_String->AllocObject());
1385 string->SetArray(array);
1386 string->SetCount(array->GetLength());
1387 return string;
1388}
1389
1390bool String::Equals(const String* that) const {
1391 if (this == that) {
1392 // Quick reference equality test
1393 return true;
1394 } else if (that == NULL) {
1395 // Null isn't an instanceof anything
1396 return false;
1397 } else if (this->GetLength() != that->GetLength()) {
1398 // Quick length inequality test
1399 return false;
1400 } else {
Elliott Hughes20cde902011-10-04 17:37:27 -07001401 // Note: don't short circuit on hash code as we're presumably here as the
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001402 // hash code was already equal
1403 for (int32_t i = 0; i < that->GetLength(); ++i) {
1404 if (this->CharAt(i) != that->CharAt(i)) {
1405 return false;
1406 }
1407 }
1408 return true;
1409 }
1410}
1411
1412bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1413 int32_t that_length) const {
1414 if (this->GetLength() != that_length) {
1415 return false;
1416 } else {
1417 for (int32_t i = 0; i < that_length; ++i) {
1418 if (this->CharAt(i) != that_chars[that_offset + i]) {
1419 return false;
1420 }
1421 }
1422 return true;
1423 }
1424}
1425
1426bool String::Equals(const char* modified_utf8) const {
1427 for (int32_t i = 0; i < GetLength(); ++i) {
1428 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1429 if (ch == '\0' || ch != CharAt(i)) {
1430 return false;
1431 }
1432 }
1433 return *modified_utf8 == '\0';
1434}
1435
1436bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001437 if (modified_utf8.size() != GetLength()) {
1438 return false;
1439 }
1440 const char* p = modified_utf8.data();
1441 for (int32_t i = 0; i < GetLength(); ++i) {
1442 uint16_t ch = GetUtf16FromUtf8(&p);
1443 if (ch != CharAt(i)) {
1444 return false;
1445 }
1446 }
1447 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001448}
1449
1450// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1451std::string String::ToModifiedUtf8() const {
1452 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1453 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1454 std::string result(byte_count, char(0));
1455 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1456 return result;
1457}
1458
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001459Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1460
1461void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1462 CHECK(java_lang_StackTraceElement_ == NULL);
1463 CHECK(java_lang_StackTraceElement != NULL);
1464 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1465}
1466
1467void StackTraceElement::ResetClass() {
1468 CHECK(java_lang_StackTraceElement_ != NULL);
1469 java_lang_StackTraceElement_ = NULL;
1470}
1471
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001472StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1473 const String* method_name,
1474 const String* file_name,
1475 int32_t line_number) {
1476 StackTraceElement* trace =
1477 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1478 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1479 const_cast<String*>(declaring_class), false);
1480 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1481 const_cast<String*>(method_name), false);
1482 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1483 const_cast<String*>(file_name), false);
1484 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1485 line_number, false);
1486 return trace;
1487}
1488
Elliott Hughes1f359b02011-07-17 14:27:17 -07001489static const char* kClassStatusNames[] = {
1490 "Error",
1491 "NotReady",
1492 "Idx",
1493 "Loaded",
1494 "Resolved",
1495 "Verifying",
1496 "Verified",
1497 "Initializing",
1498 "Initialized"
1499};
1500std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1501 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001502 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001503 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001504 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001505 }
1506 return os;
1507}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001508
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001509} // namespace art