blob: 12cd68d604fde35536981390352278a06e642f20 [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 Hughes081be7f2011-09-18 16:50:26 -070025Object* Object::Clone() {
26 Class* c = GetClass();
27 DCHECK(!c->IsClassClass());
28
29 // Object::SizeOf gets the right size even if we're an array.
30 // Using c->AllocObject() here would be wrong.
31 size_t num_bytes = SizeOf();
32 Object* copy = Heap::AllocObject(c, num_bytes);
33 if (copy == NULL) {
34 return NULL;
35 }
36
37 // Copy instance data. We assume memcpy copies by words.
38 // TODO: expose and use move32.
39 byte* src_bytes = reinterpret_cast<byte*>(this);
40 byte* dst_bytes = reinterpret_cast<byte*>(copy);
41 size_t offset = sizeof(Object);
42 memcpy(dst_bytes + offset, src_bytes + offset, num_bytes - offset);
43
44 // TODO: Mark the clone as finalizable if appropriate.
45// if (IS_CLASS_FLAG_SET(clazz, CLASS_ISFINALIZABLE)) {
46// dvmSetFinalizable(copy);
47// }
48
49 return copy;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070050}
51
Elliott Hughes5f791332011-09-15 17:45:30 -070052uint32_t Object::GetLockOwner() {
53 return Monitor::GetLockOwner(monitor_);
54}
55
Elliott Hughes081be7f2011-09-18 16:50:26 -070056bool Object::IsString() const {
57 // TODO use "klass_ == String::GetJavaLangString()" instead?
58 return GetClass() == GetClass()->GetDescriptor()->GetClass();
59}
60
Elliott Hughes5f791332011-09-15 17:45:30 -070061void Object::MonitorEnter(Thread* thread) {
62 Monitor::MonitorEnter(thread, this);
63}
64
Ian Rogersff1ed472011-09-20 13:46:24 -070065bool Object::MonitorExit(Thread* thread) {
66 return Monitor::MonitorExit(thread, this);
Elliott Hughes5f791332011-09-15 17:45:30 -070067}
68
69void Object::Notify() {
70 Monitor::Notify(Thread::Current(), this);
71}
72
73void Object::NotifyAll() {
74 Monitor::NotifyAll(Thread::Current(), this);
75}
76
77void Object::Wait(int64_t ms, int32_t ns) {
78 Monitor::Wait(Thread::Current(), this, ms, ns, true);
79}
80
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070081// TODO: get global references for these
82Class* Field::java_lang_reflect_Field_ = NULL;
83
84void Field::SetClass(Class* java_lang_reflect_Field) {
85 CHECK(java_lang_reflect_Field_ == NULL);
86 CHECK(java_lang_reflect_Field != NULL);
87 java_lang_reflect_Field_ = java_lang_reflect_Field;
88}
89
90void Field::ResetClass() {
91 CHECK(java_lang_reflect_Field_ != NULL);
92 java_lang_reflect_Field_ = NULL;
93}
94
95void Field::SetTypeIdx(uint32_t type_idx) {
96 SetField32(OFFSET_OF_OBJECT_MEMBER(Field, type_idx_), type_idx, false);
97}
98
99Class* Field::GetTypeDuringLinking() const {
100 // We are assured that the necessary primitive types are in the dex cache
101 // early during class linking
102 return GetDeclaringClass()->GetDexCache()->GetResolvedType(GetTypeIdx());
103}
104
105Class* Field::GetType() const {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700106 // Do full linkage (which sets dex cache value to speed next call)
107 return Runtime::Current()->GetClassLinker()->ResolveType(GetTypeIdx(), this);
108}
109
Brian Carlstrom845490b2011-09-19 15:56:53 -0700110Field* Field::FindInstanceFieldFromCode(uint32_t field_idx, const Method* referrer) {
111 return FindFieldFromCode(field_idx, referrer, false);
112}
113
114Field* Field::FindStaticFieldFromCode(uint32_t field_idx, const Method* referrer) {
115 return FindFieldFromCode(field_idx, referrer, true);
116}
117
118Field* Field::FindFieldFromCode(uint32_t field_idx, const Method* referrer, bool is_static) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700119 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom845490b2011-09-19 15:56:53 -0700120 Field* f = class_linker->ResolveField(field_idx, referrer, is_static);
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700121 if (f != NULL) {
122 Class* c = f->GetDeclaringClass();
123 // If the class is already initializing, we must be inside <clinit>, or
124 // we'd still be waiting for the lock.
Brian Carlstrom25c33252011-09-18 15:58:35 -0700125 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c, true)) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700126 return f;
127 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700128 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700129 UNIMPLEMENTED(FATAL) << "throw an error and unwind";
130 return NULL;
131}
132
133uint32_t Field::Get32StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700134 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700135 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
136 return field->Get32(NULL);
137}
138void Field::Set32StaticFromCode(uint32_t field_idx, const Method* referrer, uint32_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700139 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700140 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
141 field->Set32(NULL, new_value);
142}
143uint64_t Field::Get64StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700144 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700145 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
146 return field->Get64(NULL);
147}
148void Field::Set64StaticFromCode(uint32_t field_idx, const Method* referrer, uint64_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700149 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700150 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
151 field->Set64(NULL, new_value);
152}
153Object* Field::GetObjStaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700154 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700155 DCHECK(!field->GetType()->IsPrimitive());
156 return field->GetObj(NULL);
157}
158void Field::SetObjStaticFromCode(uint32_t field_idx, const Method* referrer, Object* new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700159 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700160 DCHECK(!field->GetType()->IsPrimitive());
161 field->SetObj(NULL, new_value);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700162}
163
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700164uint32_t Field::Get32(const Object* object) const {
165 CHECK((object == NULL) == IsStatic());
166 if (IsStatic()) {
167 object = declaring_class_;
168 }
169 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700170}
171
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700172void Field::Set32(Object* object, uint32_t new_value) const {
173 CHECK((object == NULL) == IsStatic());
174 if (IsStatic()) {
175 object = declaring_class_;
176 }
177 object->SetField32(GetOffset(), new_value, IsVolatile());
178}
179
180uint64_t Field::Get64(const Object* object) const {
181 CHECK((object == NULL) == IsStatic());
182 if (IsStatic()) {
183 object = declaring_class_;
184 }
185 return object->GetField64(GetOffset(), IsVolatile());
186}
187
188void Field::Set64(Object* object, uint64_t new_value) const {
189 CHECK((object == NULL) == IsStatic());
190 if (IsStatic()) {
191 object = declaring_class_;
192 }
193 object->SetField64(GetOffset(), new_value, IsVolatile());
194}
195
196Object* Field::GetObj(const Object* object) const {
197 CHECK((object == NULL) == IsStatic());
198 if (IsStatic()) {
199 object = declaring_class_;
200 }
201 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
202}
203
204void Field::SetObj(Object* object, const Object* new_value) const {
205 CHECK((object == NULL) == IsStatic());
206 if (IsStatic()) {
207 object = declaring_class_;
208 }
209 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
210}
211
212bool Field::GetBoolean(const Object* object) const {
213 DCHECK(GetType()->IsPrimitiveBoolean());
214 return Get32(object);
215}
216
217void Field::SetBoolean(Object* object, bool z) const {
218 DCHECK(GetType()->IsPrimitiveBoolean());
219 Set32(object, z);
220}
221
222int8_t Field::GetByte(const Object* object) const {
223 DCHECK(GetType()->IsPrimitiveByte());
224 return Get32(object);
225}
226
227void Field::SetByte(Object* object, int8_t b) const {
228 DCHECK(GetType()->IsPrimitiveByte());
229 Set32(object, b);
230}
231
232uint16_t Field::GetChar(const Object* object) const {
233 DCHECK(GetType()->IsPrimitiveChar());
234 return Get32(object);
235}
236
237void Field::SetChar(Object* object, uint16_t c) const {
238 DCHECK(GetType()->IsPrimitiveChar());
239 Set32(object, c);
240}
241
242uint16_t Field::GetShort(const Object* object) const {
243 DCHECK(GetType()->IsPrimitiveShort());
244 return Get32(object);
245}
246
247void Field::SetShort(Object* object, uint16_t s) const {
248 DCHECK(GetType()->IsPrimitiveShort());
249 Set32(object, s);
250}
251
252int32_t Field::GetInt(const Object* object) const {
253 DCHECK(GetType()->IsPrimitiveInt());
254 return Get32(object);
255}
256
257void Field::SetInt(Object* object, int32_t i) const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700258 DCHECK(GetType()->IsPrimitiveInt()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700259 Set32(object, i);
260}
261
262int64_t Field::GetLong(const Object* object) const {
263 DCHECK(GetType()->IsPrimitiveLong());
264 return Get64(object);
265}
266
267void Field::SetLong(Object* object, int64_t j) const {
268 DCHECK(GetType()->IsPrimitiveLong());
269 Set64(object, j);
270}
271
272float Field::GetFloat(const Object* object) const {
273 DCHECK(GetType()->IsPrimitiveFloat());
274 JValue float_bits;
275 float_bits.i = Get32(object);
276 return float_bits.f;
277}
278
279void Field::SetFloat(Object* object, float f) const {
280 DCHECK(GetType()->IsPrimitiveFloat());
281 JValue float_bits;
282 float_bits.f = f;
283 Set32(object, float_bits.i);
284}
285
286double Field::GetDouble(const Object* object) const {
287 DCHECK(GetType()->IsPrimitiveDouble());
288 JValue double_bits;
289 double_bits.j = Get64(object);
290 return double_bits.d;
291}
292
293void Field::SetDouble(Object* object, double d) const {
294 DCHECK(GetType()->IsPrimitiveDouble());
295 JValue double_bits;
296 double_bits.d = d;
297 Set64(object, double_bits.j);
298}
299
300Object* Field::GetObject(const Object* object) const {
301 CHECK(!GetType()->IsPrimitive());
302 return GetObj(object);
303}
304
305void Field::SetObject(Object* object, const Object* l) const {
306 CHECK(!GetType()->IsPrimitive());
307 SetObj(object, l);
308}
309
310// TODO: get global references for these
311Class* Method::java_lang_reflect_Method_ = NULL;
312
313void Method::SetClass(Class* java_lang_reflect_Method) {
314 CHECK(java_lang_reflect_Method_ == NULL);
315 CHECK(java_lang_reflect_Method != NULL);
316 java_lang_reflect_Method_ = java_lang_reflect_Method;
317}
318
319void Method::ResetClass() {
320 CHECK(java_lang_reflect_Method_ != NULL);
321 java_lang_reflect_Method_ = NULL;
322}
323
324ObjectArray<String>* Method::GetDexCacheStrings() const {
325 return GetFieldObject<ObjectArray<String>*>(
326 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
327}
328
329void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
330 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
331 new_return_type_idx, false);
332}
333
334Class* Method::GetReturnType() const {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700335 DCHECK(GetDeclaringClass()->IsResolved() || GetDeclaringClass()->IsErroneous());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700336 // Short-cut
337 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
338 if (result == NULL) {
339 // Do full linkage and set cache value for next call
340 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
341 }
342 CHECK(result != NULL);
343 return result;
344}
345
346void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
347 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
348 new_dex_cache_strings, false);
349}
350
351ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
352 return GetFieldObject<ObjectArray<Class>*>(
353 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
354}
355
356void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
357 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
358 new_dex_cache_classes, false);
359}
360
361ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
362 return GetFieldObject<ObjectArray<Method>*>(
363 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
364}
365
366void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
367 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
368 new_dex_cache_methods, false);
369}
370
371ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
372 return GetFieldObject<ObjectArray<Field>*>(
373 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
374}
375
376void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
377 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
378 new_dex_cache_fields, false);
379}
380
381CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
382 return GetFieldPtr<CodeAndDirectMethods*>(
383 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
384 false);
385}
386
387void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
388 SetFieldPtr<CodeAndDirectMethods*>(
389 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
390 new_value, false);
391}
392
393ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
394 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
395 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
396 false);
397}
398
399void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
400 SetFieldObject(
401 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
402 new_value, false);
403
404}
405
406size_t Method::NumArgRegisters(const StringPiece& shorty) {
407 CHECK_LE(1, shorty.length());
408 uint32_t num_registers = 0;
409 for (int i = 1; i < shorty.length(); ++i) {
410 char ch = shorty[i];
411 if (ch == 'D' || ch == 'J') {
412 num_registers += 2;
413 } else {
414 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700415 }
416 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700417 return num_registers;
418}
419
420size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700421 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700423 for (int i = 1; i < shorty->GetLength(); ++i) {
424 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425 if (ch == 'D' || ch == 'J') {
426 num_bytes += 8;
427 } else if (ch == 'L') {
428 // Argument is a reference or an array. The shorty descriptor
429 // does not distinguish between these types.
430 num_bytes += sizeof(Object*);
431 } else {
432 num_bytes += 4;
433 }
434 }
435 return num_bytes;
436}
437
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700438size_t Method::NumArgs() const {
439 // "1 +" because the first in Args is the receiver.
440 // "- 1" because we don't count the return type.
441 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
442}
443
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444// The number of reference arguments to this method including implicit this
445// pointer
446size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700447 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700448 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700449 for (int i = 1; i < shorty->GetLength(); i++) {
450 char ch = shorty->CharAt(i);
451 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452 result++;
453 }
454 }
455 return result;
456}
457
458// The number of long or double arguments
459size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700460 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700462 for (int i = 1; i < shorty->GetLength(); i++) {
463 char ch = shorty->CharAt(i);
464 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700465 result++;
466 }
467 }
468 return result;
469}
470
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471// Is the given method parameter a reference?
472bool Method::IsParamAReference(unsigned int param) const {
473 CHECK_LT(param, NumArgs());
474 if (IsStatic()) {
475 param++; // 0th argument must skip return value at start of the shorty
476 } else if (param == 0) {
477 return true; // this argument
478 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700479 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700480}
481
482// Is the given method parameter a long or double?
483bool Method::IsParamALongOrDouble(unsigned int param) const {
484 CHECK_LT(param, NumArgs());
485 if (IsStatic()) {
486 param++; // 0th argument must skip return value at start of the shorty
487 } else if (param == 0) {
488 return false; // this argument
489 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700490 char ch = GetShorty()->CharAt(param);
491 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492}
493
494static size_t ShortyCharToSize(char x) {
495 switch (x) {
496 case 'V': return 0;
497 case '[': return kPointerSize;
498 case 'L': return kPointerSize;
499 case 'D': return 8;
500 case 'J': return 8;
501 default: return 4;
502 }
503}
504
505size_t Method::ParamSize(unsigned int param) const {
506 CHECK_LT(param, NumArgs());
507 if (IsStatic()) {
508 param++; // 0th argument must skip return value at start of the shorty
509 } else if (param == 0) {
510 return kPointerSize; // this argument
511 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700512 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700513}
514
515size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700516 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517}
518
519bool Method::HasSameNameAndDescriptor(const Method* that) const {
520 return (this->GetName()->Equals(that->GetName()) &&
521 this->GetSignature()->Equals(that->GetSignature()));
522}
523
Ian Rogersbdb03912011-09-14 00:55:44 -0700524uint32_t Method::ToDexPC(const uintptr_t pc) const {
525 IntArray* mapping_table = GetMappingTable();
526 if (mapping_table == NULL) {
Ian Rogers67375ac2011-09-14 00:55:44 -0700527 DCHECK(IsNative());
528 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700529 }
530 size_t mapping_table_length = mapping_table->GetLength();
531 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
532 CHECK_LT(sought_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
533 uint32_t best_offset = 0;
534 uint32_t best_dex_offset = 0;
535 for (size_t i = 0; i < mapping_table_length; i += 2) {
536 uint32_t map_offset = mapping_table->Get(i);
537 uint32_t map_dex_offset = mapping_table->Get(i + 1);
538 if (map_offset == sought_offset) {
539 best_offset = map_offset;
540 best_dex_offset = map_dex_offset;
541 break;
542 }
543 if (map_offset < sought_offset && map_offset > best_offset) {
544 best_offset = map_offset;
545 best_dex_offset = map_dex_offset;
546 }
547 }
548 return best_dex_offset;
549}
550
551uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
552 IntArray* mapping_table = GetMappingTable();
553 if (mapping_table == NULL) {
554 DCHECK(dex_pc == 0);
555 return 0; // Special no mapping/pc == 0 case
556 }
557 size_t mapping_table_length = mapping_table->GetLength();
558 for (size_t i = 0; i < mapping_table_length; i += 2) {
559 uint32_t map_offset = mapping_table->Get(i);
560 uint32_t map_dex_offset = mapping_table->Get(i + 1);
561 if (map_dex_offset == dex_pc) {
562 DCHECK_LT(map_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
563 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
564 }
565 }
566 LOG(FATAL) << "Looking up Dex PC not contained in method";
567 return 0;
568}
569
570uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
571 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
572 const ClassLoader* class_loader = GetDeclaringClass()->GetClassLoader();
573 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
574 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
575 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
576 // Iterate over the catch handlers associated with dex_pc
577 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
578 !iter.HasNext(); iter.Next()) {
579 uint32_t iter_type_idx = iter.Get().type_idx_;
580 // Catch all case
581 if(iter_type_idx == DexFile::kDexNoIndex) {
582 return iter.Get().address_;
583 }
584 // Does this catch exception type apply?
585 Class* iter_exception_type =
586 class_linker->ResolveType(dex_file, iter_type_idx, dex_cache, class_loader);
587 if (iter_exception_type->IsAssignableFrom(exception_type)) {
588 return iter.Get().address_;
589 }
590 }
591 // Handler not found
592 return DexFile::kDexNoIndex;
593}
594
buzbee4ef76522011-09-08 10:00:32 -0700595void Method::SetCode(ByteArray* code_array, InstructionSet instruction_set,
buzbeec41e5b52011-09-23 12:46:19 -0700596 IntArray* mapping_table, ShortArray* vmap_table) {
Elliott Hughes1240dad2011-09-09 16:24:50 -0700597 CHECK(GetCode() == NULL || IsNative());
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700598 SetFieldPtr<ByteArray*>(OFFSET_OF_OBJECT_MEMBER(Method, code_array_), code_array, false);
Ian Rogersbdb03912011-09-14 00:55:44 -0700599 SetFieldPtr<IntArray*>(OFFSET_OF_OBJECT_MEMBER(Method, mapping_table_),
buzbee4ef76522011-09-08 10:00:32 -0700600 mapping_table, false);
buzbeec41e5b52011-09-23 12:46:19 -0700601 SetFieldPtr<ShortArray*>(OFFSET_OF_OBJECT_MEMBER(Method, vmap_table_),
602 vmap_table, false);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700603 int8_t* code = code_array->GetData();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700604 uintptr_t address = reinterpret_cast<uintptr_t>(code);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700605 if (instruction_set == kThumb2) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700606 // Set the low-order bit so a BLX will switch to Thumb mode
607 address |= 0x1;
608 }
Ian Rogersff1ed472011-09-20 13:46:24 -0700609 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, code_),
610 reinterpret_cast<const void*>(address), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700611}
612
Ian Rogersbdb03912011-09-14 00:55:44 -0700613bool Method::IsWithinCode(uintptr_t pc) const {
Ian Rogersbdb03912011-09-14 00:55:44 -0700614 if (pc == 0) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700615 // PC of 0 represents the beginning of a stack trace either a native or where we have a callee
616 // save method that has no code
617 DCHECK(IsNative() || IsPhony());
Ian Rogersbdb03912011-09-14 00:55:44 -0700618 return true;
619 } else {
Ian Rogers93dd9662011-09-17 23:21:22 -0700620#if defined(__arm__)
621 pc &= ~0x1; // clear any possible thumb instruction mode bit
622#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700623 uint32_t rel_offset = pc - reinterpret_cast<uintptr_t>(GetCodeArray()->GetData());
Ian Rogers93dd9662011-09-17 23:21:22 -0700624 // Strictly the following test should be a less-than, however, if the last
625 // instruction is a call to an exception throw we may see return addresses
626 // that are 1 beyond the end of code.
627 return rel_offset <= static_cast<uint32_t>(GetCodeArray()->GetLength());
Ian Rogersbdb03912011-09-14 00:55:44 -0700628 }
629}
630
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700631void Method::SetInvokeStub(const ByteArray* invoke_stub_array) {
632 const InvokeStub* invoke_stub = reinterpret_cast<InvokeStub*>(invoke_stub_array->GetData());
633 SetFieldPtr<const ByteArray*>(
634 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_array_), invoke_stub_array, false);
635 SetFieldPtr<const InvokeStub*>(
636 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_), invoke_stub, false);
637}
638
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700639void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
640 // Push a transition back into managed code onto the linked list in thread.
641 CHECK_EQ(Thread::kRunnable, self->GetState());
642 NativeToManagedRecord record;
643 self->PushNativeToManagedRecord(&record);
644
645 // Call the invoke stub associated with the method.
646 // Pass everything as arguments.
647 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700648
649 bool have_executable_code = (GetCode() != NULL);
650#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700651 // Currently we can only compile non-native methods for ARM.
652 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700653#endif
654
655 if (have_executable_code && stub != NULL) {
656 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700657 (*stub)(this, receiver, self, args, result);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700658 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700659 } else {
660 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
661 if (result != NULL) {
662 result->j = 0;
663 }
664 }
665
666 // Pop transition.
667 self->PopNativeToManagedRecord(record);
668}
669
Brian Carlstrom16192862011-09-12 17:50:06 -0700670bool Method::IsRegistered() {
671 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
672 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
673 return native_method != jni_stub;
674}
675
676void Method::RegisterNative(const void* native_method) {
677 CHECK(IsNative());
678 CHECK(native_method != NULL);
679 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
680 native_method, false);
681}
682
683void Method::UnregisterNative() {
684 CHECK(IsNative());
685 // restore stub to lookup native pointer via dlsym
686 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
687}
688
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700689void Class::SetStatus(Status new_status) {
690 CHECK(new_status > GetStatus() || new_status == kStatusError ||
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700691 !Runtime::Current()->IsStarted()) << GetDescriptor()->ToModifiedUtf8();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700692 CHECK(sizeof(Status) == sizeof(uint32_t));
693 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_),
694 new_status, false);
695}
696
697DexCache* Class::GetDexCache() const {
698 return GetFieldObject<DexCache*>(
699 OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
700}
701
702void Class::SetDexCache(DexCache* new_dex_cache) {
703 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_),
704 new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700705}
706
Brian Carlstrom1f870082011-08-23 16:02:11 -0700707Object* Class::AllocObjectFromCode(uint32_t type_idx, Method* method) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700708 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700709 if (klass == NULL) {
710 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
711 if (klass == NULL) {
712 UNIMPLEMENTED(FATAL) << "throw an error";
713 return NULL;
714 }
715 }
Brian Carlstrom1f870082011-08-23 16:02:11 -0700716 return klass->AllocObject();
717}
718
719Object* Class::AllocObject() {
720 DCHECK(!IsAbstract());
721 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700722}
723
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700724void Class::DumpClass(std::ostream& os, int flags) {
725 if ((flags & kDumpClassFullDetail) == 0) {
726 os << PrettyClass(this);
727 if ((flags & kDumpClassClassLoader) != 0) {
728 os << ' ' << GetClassLoader();
729 }
730 if ((flags & kDumpClassInitialized) != 0) {
731 os << ' ' << GetStatus();
732 }
733 os << std::endl;
734 return;
735 }
736
737 Class* super = GetSuperClass();
738 os << "----- " << (IsInterface() ? "interface" : "class") << " "
739 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
740 os << " objectSize=" << SizeOf() << " "
741 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
742 os << StringPrintf(" access=0x%04x.%04x\n",
743 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
744 if (super != NULL) {
745 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
746 }
747 if (IsArrayClass()) {
748 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
749 }
750 if (NumInterfaces() > 0) {
751 os << " interfaces (" << NumInterfaces() << "):\n";
752 for (size_t i = 0; i < NumInterfaces(); ++i) {
753 Class* interface = GetInterface(i);
754 const ClassLoader* cl = interface->GetClassLoader();
755 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
756 }
757 }
758 os << " vtable (" << NumVirtualMethods() << " entries, "
759 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
760 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
761 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethod(i)).c_str());
762 }
763 os << " direct methods (" << NumDirectMethods() << " entries):\n";
764 for (size_t i = 0; i < NumDirectMethods(); ++i) {
765 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
766 }
767 if (NumStaticFields() > 0) {
768 os << " static fields (" << NumStaticFields() << " entries):\n";
769 for (size_t i = 0; i < NumStaticFields(); ++i) {
770 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
771 }
772 }
773 if (NumInstanceFields() > 0) {
774 os << " instance fields (" << NumInstanceFields() << " entries):\n";
775 for (size_t i = 0; i < NumInstanceFields(); ++i) {
776 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
777 }
778 }
779}
780
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700781void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
782 if (new_reference_offsets != CLASS_WALK_SUPER) {
783 // Sanity check that the number of bits set in the reference offset bitmap
784 // agrees with the number of references
785 Class* cur = this;
786 size_t cnt = 0;
787 while (cur) {
788 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
789 cur = cur->GetSuperClass();
790 }
791 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
792 }
793 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
794 new_reference_offsets, false);
795}
796
797void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
798 if (new_reference_offsets != CLASS_WALK_SUPER) {
799 // Sanity check that the number of bits set in the reference offset bitmap
800 // agrees with the number of references
801 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
802 NumReferenceStaticFieldsDuringLinking());
803 }
804 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
805 new_reference_offsets, false);
806}
807
808size_t Class::PrimitiveSize() const {
809 switch (GetPrimitiveType()) {
810 case kPrimBoolean:
811 case kPrimByte:
812 case kPrimChar:
813 case kPrimShort:
814 case kPrimInt:
815 case kPrimFloat:
816 return sizeof(int32_t);
817 case kPrimLong:
818 case kPrimDouble:
819 return sizeof(int64_t);
820 default:
821 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
822 return 0;
823 }
824}
825
826size_t Class::GetTypeSize(const String* descriptor) {
827 switch (descriptor->CharAt(0)) {
828 case 'B': return 1; // byte
829 case 'C': return 2; // char
830 case 'D': return 8; // double
831 case 'F': return 4; // float
832 case 'I': return 4; // int
833 case 'J': return 8; // long
834 case 'S': return 2; // short
835 case 'Z': return 1; // boolean
836 case 'L': return sizeof(Object*);
837 case '[': return sizeof(Array*);
838 default:
839 LOG(ERROR) << "Unknown type " << descriptor;
840 return 0;
841 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700842}
843
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700844bool Class::Implements(const Class* klass) const {
845 DCHECK(klass != NULL);
846 DCHECK(klass->IsInterface());
847 // All interfaces implemented directly and by our superclass, and
848 // recursively all super-interfaces of those interfaces, are listed
849 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700850 int32_t iftable_count = GetIfTableCount();
851 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
852 for (int32_t i = 0; i < iftable_count; i++) {
853 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700854 return true;
855 }
856 }
857 return false;
858}
859
buzbee9a195c92011-09-16 13:26:02 -0700860void Class::CanPutArrayElementFromCode(const Object* element, const Class* array_class) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700861 DCHECK(array_class != NULL);
buzbee9a195c92011-09-16 13:26:02 -0700862 if (element == NULL) {
863 return;
864 }
Brian Carlstrom25c33252011-09-18 15:58:35 -0700865 if (!array_class->GetComponentType()->IsAssignableFrom(element->GetClass())) {
buzbee9a195c92011-09-16 13:26:02 -0700866 LOG(ERROR) << "Can't put a " << PrettyClass(element->GetClass())
Elliott Hughes54e7df12011-09-16 11:47:04 -0700867 << " into a " << PrettyClass(array_class);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700868 UNIMPLEMENTED(FATAL) << "need to throw ArrayStoreException and unwind stack";
869 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700870}
871
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700872// Determine whether "this" is assignable from "klazz", where both of these
873// are array classes.
874//
875// Consider an array class, e.g. Y[][], where Y is a subclass of X.
876// Y[][] = Y[][] --> true (identity)
877// X[][] = Y[][] --> true (element superclass)
878// Y = Y[][] --> false
879// Y[] = Y[][] --> false
880// Object = Y[][] --> true (everything is an object)
881// Object[] = Y[][] --> true
882// Object[][] = Y[][] --> true
883// Object[][][] = Y[][] --> false (too many []s)
884// Serializable = Y[][] --> true (all arrays are Serializable)
885// Serializable[] = Y[][] --> true
886// Serializable[][] = Y[][] --> false (unless Y is Serializable)
887//
888// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700889// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700890//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700891bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700892 DCHECK(IsArrayClass());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700893 DCHECK(src->IsArrayClass());
894 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700895}
896
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700897bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700898 DCHECK(!IsInterface()); // handled first in IsAssignableFrom
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700899 DCHECK(src->IsArrayClass());
Brian Carlstromb63ec392011-08-27 17:38:27 -0700900 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700901 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700902 // src's super should be java_lang_Object, since it is an array.
903 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700904 DCHECK(java_lang_Object != NULL);
905 DCHECK(java_lang_Object->GetSuperClass() == NULL);
906 return this == java_lang_Object;
907 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700908 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700909}
910
911bool Class::IsSubClass(const Class* klass) const {
912 DCHECK(!IsInterface());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700913 DCHECK(!IsArrayClass());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700914 const Class* current = this;
915 do {
916 if (current == klass) {
917 return true;
918 }
919 current = current->GetSuperClass();
920 } while (current != NULL);
921 return false;
922}
923
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700924bool Class::IsInSamePackage(const String* descriptor_string_1,
925 const String* descriptor_string_2) {
926 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
927 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
928
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700929 size_t i = 0;
930 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
931 ++i;
932 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700933 if (descriptor1.find('/', i) != StringPiece::npos ||
934 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700935 return false;
936 } else {
937 return true;
938 }
939}
940
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700941#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700942bool Class::IsInSamePackage(const StringPiece& descriptor1,
943 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700944 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700945 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700946 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
947 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700948 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
949}
950#endif
951
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700952bool Class::IsInSamePackage(const Class* that) const {
953 const Class* klass1 = this;
954 const Class* klass2 = that;
955 if (klass1 == klass2) {
956 return true;
957 }
958 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700959 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700960 return false;
961 }
962 // Arrays are in the same package when their element classes are.
Brian Carlstromb63ec392011-08-27 17:38:27 -0700963 if (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700964 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700965 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700966 if (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700967 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700968 }
969 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700970 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700971}
972
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700973const ClassLoader* Class::GetClassLoader() const {
974 return GetFieldObject<const ClassLoader*>(
975 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -0700976}
977
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700978void Class::SetClassLoader(const ClassLoader* new_cl) {
979 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
980 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
981 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700982}
983
Brian Carlstrom30b94452011-08-25 21:35:26 -0700984Method* Class::FindVirtualMethodForInterface(Method* method) {
985 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700986 DCHECK(declaring_class != NULL);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700987 DCHECK(declaring_class->IsInterface());
988 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700989 int32_t iftable_count = GetIfTableCount();
990 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
991 for (int32_t i = 0; i < iftable_count; i++) {
992 InterfaceEntry* interface_entry = iftable->Get(i);
993 if (interface_entry->GetInterface() == declaring_class) {
994 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -0700995 }
996 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700997 UNIMPLEMENTED(FATAL) << "Need to throw an error of some kind " << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700998 return NULL;
999}
1000
jeffhaobdb76512011-09-07 11:43:16 -07001001Method* Class::FindInterfaceMethod(const StringPiece& name,
1002 const StringPiece& signature) {
1003 // Check the current class before checking the interfaces.
1004 Method* method = FindVirtualMethod(name, signature);
1005 if (method != NULL) {
1006 return method;
1007 }
1008
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001009 int32_t iftable_count = GetIfTableCount();
1010 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1011 for (int32_t i = 0; i < iftable_count; i++) {
1012 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001013 if (method != NULL) {
1014 return method;
1015 }
1016 }
1017 return NULL;
1018}
1019
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001020Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001021 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001022 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001023 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001024 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001025 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001026 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001027 }
1028 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001029 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001030}
1031
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001032Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001033 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001034 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001035 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001036 if (method != NULL) {
1037 return method;
1038 }
1039 }
1040 return NULL;
1041}
1042
1043Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001044 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001045 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001046 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001047 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001048 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001049 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001050 }
1051 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001052 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001053}
1054
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001055Method* Class::FindVirtualMethod(const StringPiece& name,
1056 const StringPiece& descriptor) {
1057 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1058 Method* method = klass->FindDeclaredVirtualMethod(name, descriptor);
1059 if (method != NULL) {
1060 return method;
1061 }
1062 }
1063 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001064}
1065
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001066Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001067 // Is the field in this class?
1068 // Interfaces are not relevant because they can't contain instance fields.
1069 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1070 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001071 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001072 return f;
1073 }
1074 }
1075 return NULL;
1076}
1077
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001078Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001079 // Is the field in this class, or any of its superclasses?
1080 // Interfaces are not relevant because they can't contain instance fields.
1081 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001082 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001083 if (f != NULL) {
1084 return f;
1085 }
1086 }
1087 return NULL;
1088}
1089
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001090Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
1091 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -07001092 for (size_t i = 0; i < NumStaticFields(); ++i) {
1093 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001094 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001095 return f;
1096 }
1097 }
1098 return NULL;
1099}
1100
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001101Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001102 // Is the field in this class (or its interfaces), or any of its
1103 // superclasses (or their interfaces)?
1104 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1105 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001106 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001107 if (f != NULL) {
1108 return f;
1109 }
1110
1111 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001112 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1113 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1114 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001115 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001116 if (f != NULL) {
1117 return f;
1118 }
1119 }
1120 }
1121 return NULL;
1122}
1123
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001124Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001125 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001126 DCHECK_GE(component_count, 0);
1127 DCHECK(array_class->IsArrayClass());
1128 size_t size = SizeOf(component_count, component_size);
1129 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1130 if (array != NULL) {
1131 DCHECK(array->IsArrayInstance());
1132 array->SetLength(component_count);
1133 }
1134 return array;
1135}
1136
1137Array* Array::Alloc(Class* array_class, int32_t component_count) {
1138 return Alloc(array_class, component_count, array_class->GetComponentSize());
1139}
1140
1141Array* Array::AllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
1142 // TODO: throw on negative component_count
1143 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
1144 if (klass == NULL) {
1145 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
1146 if (klass == NULL || !klass->IsArrayClass()) {
1147 UNIMPLEMENTED(FATAL) << "throw an error";
1148 return NULL;
1149 }
1150 }
1151 return Array::Alloc(klass, component_count);
1152}
1153
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001154template<typename T>
1155PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001156 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001157 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1158 return down_cast<PrimitiveArray<T>*>(raw_array);
1159}
1160
1161template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1162
1163// Explicitly instantiate all the primitive array types.
1164template class PrimitiveArray<uint8_t>; // BooleanArray
1165template class PrimitiveArray<int8_t>; // ByteArray
1166template class PrimitiveArray<uint16_t>; // CharArray
1167template class PrimitiveArray<double>; // DoubleArray
1168template class PrimitiveArray<float>; // FloatArray
1169template class PrimitiveArray<int32_t>; // IntArray
1170template class PrimitiveArray<int64_t>; // LongArray
1171template class PrimitiveArray<int16_t>; // ShortArray
1172
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001173// TODO: get global references for these
1174Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001175
Brian Carlstroma663ea52011-08-19 23:33:41 -07001176void String::SetClass(Class* java_lang_String) {
1177 CHECK(java_lang_String_ == NULL);
1178 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001179 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001180}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001181
Brian Carlstroma663ea52011-08-19 23:33:41 -07001182void String::ResetClass() {
1183 CHECK(java_lang_String_ != NULL);
1184 java_lang_String_ = NULL;
1185}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001186
Brian Carlstromc74255f2011-09-11 22:47:39 -07001187String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001188 return Runtime::Current()->GetInternTable()->InternWeak(this);
1189}
1190
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001191int32_t String::GetHashCode() const {
1192 int32_t result = GetField32(
1193 OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1194 DCHECK(result != 0 ||
1195 ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0);
1196 return result;
1197}
1198
1199int32_t String::GetLength() const {
1200 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1201 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1202 return result;
1203}
1204
1205uint16_t String::CharAt(int32_t index) const {
1206 // TODO: do we need this? Equals is the only caller, and could
1207 // bounds check itself.
1208 if (index < 0 || index >= count_) {
1209 Thread* self = Thread::Current();
1210 self->ThrowNewException("Ljava/lang/StringIndexOutOfBoundsException;",
1211 "length=%i; index=%i", count_, index);
1212 return 0;
1213 }
1214 return GetCharArray()->Get(index + GetOffset());
1215}
1216
1217String* String::AllocFromUtf16(int32_t utf16_length,
1218 const uint16_t* utf16_data_in,
1219 int32_t hash_code) {
1220 String* string = Alloc(GetJavaLangString(), utf16_length);
1221 // TODO: use 16-bit wide memset variant
1222 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1223 for (int i = 0; i < utf16_length; i++) {
1224 array->Set(i, utf16_data_in[i]);
1225 }
1226 if (hash_code != 0) {
1227 string->SetHashCode(hash_code);
1228 } else {
1229 string->ComputeHashCode();
1230 }
1231 return string;
1232}
1233
1234String* String::AllocFromModifiedUtf8(const char* utf) {
1235 size_t char_count = CountModifiedUtf8Chars(utf);
1236 return AllocFromModifiedUtf8(char_count, utf);
1237}
1238
1239String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1240 const char* utf8_data_in) {
1241 String* string = Alloc(GetJavaLangString(), utf16_length);
1242 uint16_t* utf16_data_out =
1243 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1244 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1245 string->ComputeHashCode();
1246 return string;
1247}
1248
1249String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1250 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1251}
1252
1253String* String::Alloc(Class* java_lang_String, CharArray* array) {
1254 String* string = down_cast<String*>(java_lang_String->AllocObject());
1255 string->SetArray(array);
1256 string->SetCount(array->GetLength());
1257 return string;
1258}
1259
1260bool String::Equals(const String* that) const {
1261 if (this == that) {
1262 // Quick reference equality test
1263 return true;
1264 } else if (that == NULL) {
1265 // Null isn't an instanceof anything
1266 return false;
1267 } else if (this->GetLength() != that->GetLength()) {
1268 // Quick length inequality test
1269 return false;
1270 } else {
1271 // NB don't short circuit on hash code as we're presumably here as the
1272 // hash code was already equal
1273 for (int32_t i = 0; i < that->GetLength(); ++i) {
1274 if (this->CharAt(i) != that->CharAt(i)) {
1275 return false;
1276 }
1277 }
1278 return true;
1279 }
1280}
1281
1282bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1283 int32_t that_length) const {
1284 if (this->GetLength() != that_length) {
1285 return false;
1286 } else {
1287 for (int32_t i = 0; i < that_length; ++i) {
1288 if (this->CharAt(i) != that_chars[that_offset + i]) {
1289 return false;
1290 }
1291 }
1292 return true;
1293 }
1294}
1295
1296bool String::Equals(const char* modified_utf8) const {
1297 for (int32_t i = 0; i < GetLength(); ++i) {
1298 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1299 if (ch == '\0' || ch != CharAt(i)) {
1300 return false;
1301 }
1302 }
1303 return *modified_utf8 == '\0';
1304}
1305
1306bool String::Equals(const StringPiece& modified_utf8) const {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001307 // TODO: do not assume C-string representation. For now DCHECK.
1308 DCHECK_EQ(modified_utf8.data()[modified_utf8.size()], 0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001309 return Equals(modified_utf8.data());
1310}
1311
1312// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1313std::string String::ToModifiedUtf8() const {
1314 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1315 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1316 std::string result(byte_count, char(0));
1317 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1318 return result;
1319}
1320
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001321Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1322
1323void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1324 CHECK(java_lang_StackTraceElement_ == NULL);
1325 CHECK(java_lang_StackTraceElement != NULL);
1326 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1327}
1328
1329void StackTraceElement::ResetClass() {
1330 CHECK(java_lang_StackTraceElement_ != NULL);
1331 java_lang_StackTraceElement_ = NULL;
1332}
1333
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001334StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1335 const String* method_name,
1336 const String* file_name,
1337 int32_t line_number) {
1338 StackTraceElement* trace =
1339 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1340 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1341 const_cast<String*>(declaring_class), false);
1342 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1343 const_cast<String*>(method_name), false);
1344 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1345 const_cast<String*>(file_name), false);
1346 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1347 line_number, false);
1348 return trace;
1349}
1350
Elliott Hughes1f359b02011-07-17 14:27:17 -07001351static const char* kClassStatusNames[] = {
1352 "Error",
1353 "NotReady",
1354 "Idx",
1355 "Loaded",
1356 "Resolved",
1357 "Verifying",
1358 "Verified",
1359 "Initializing",
1360 "Initialized"
1361};
1362std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1363 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001364 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001365 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001366 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001367 }
1368 return os;
1369}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001370
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001371} // namespace art