blob: 1af840f3d2dedf783d6a5ed0f39be39ebe6de109 [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,
Ian Rogersbdb03912011-09-14 00:55:44 -0700596 IntArray* mapping_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);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700601 int8_t* code = code_array->GetData();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700602 uintptr_t address = reinterpret_cast<uintptr_t>(code);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700603 if (instruction_set == kThumb2) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700604 // Set the low-order bit so a BLX will switch to Thumb mode
605 address |= 0x1;
606 }
Ian Rogersff1ed472011-09-20 13:46:24 -0700607 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, code_),
608 reinterpret_cast<const void*>(address), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700609}
610
Ian Rogersbdb03912011-09-14 00:55:44 -0700611bool Method::IsWithinCode(uintptr_t pc) const {
Ian Rogersbdb03912011-09-14 00:55:44 -0700612 if (pc == 0) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700613 // PC of 0 represents the beginning of a stack trace either a native or where we have a callee
614 // save method that has no code
615 DCHECK(IsNative() || IsPhony());
Ian Rogersbdb03912011-09-14 00:55:44 -0700616 return true;
617 } else {
Ian Rogers93dd9662011-09-17 23:21:22 -0700618#if defined(__arm__)
619 pc &= ~0x1; // clear any possible thumb instruction mode bit
620#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700621 uint32_t rel_offset = pc - reinterpret_cast<uintptr_t>(GetCodeArray()->GetData());
Ian Rogers93dd9662011-09-17 23:21:22 -0700622 // Strictly the following test should be a less-than, however, if the last
623 // instruction is a call to an exception throw we may see return addresses
624 // that are 1 beyond the end of code.
625 return rel_offset <= static_cast<uint32_t>(GetCodeArray()->GetLength());
Ian Rogersbdb03912011-09-14 00:55:44 -0700626 }
627}
628
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700629void Method::SetInvokeStub(const ByteArray* invoke_stub_array) {
630 const InvokeStub* invoke_stub = reinterpret_cast<InvokeStub*>(invoke_stub_array->GetData());
631 SetFieldPtr<const ByteArray*>(
632 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_array_), invoke_stub_array, false);
633 SetFieldPtr<const InvokeStub*>(
634 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_), invoke_stub, false);
635}
636
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700637void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
638 // Push a transition back into managed code onto the linked list in thread.
639 CHECK_EQ(Thread::kRunnable, self->GetState());
640 NativeToManagedRecord record;
641 self->PushNativeToManagedRecord(&record);
642
643 // Call the invoke stub associated with the method.
644 // Pass everything as arguments.
645 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700646
647 bool have_executable_code = (GetCode() != NULL);
648#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700649 // Currently we can only compile non-native methods for ARM.
650 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700651#endif
652
653 if (have_executable_code && stub != NULL) {
654 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700655 (*stub)(this, receiver, self, args, result);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700656 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700657 } else {
658 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
659 if (result != NULL) {
660 result->j = 0;
661 }
662 }
663
664 // Pop transition.
665 self->PopNativeToManagedRecord(record);
666}
667
Brian Carlstrom16192862011-09-12 17:50:06 -0700668bool Method::IsRegistered() {
669 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
670 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
671 return native_method != jni_stub;
672}
673
674void Method::RegisterNative(const void* native_method) {
675 CHECK(IsNative());
676 CHECK(native_method != NULL);
677 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
678 native_method, false);
679}
680
681void Method::UnregisterNative() {
682 CHECK(IsNative());
683 // restore stub to lookup native pointer via dlsym
684 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
685}
686
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700687void Class::SetStatus(Status new_status) {
688 CHECK(new_status > GetStatus() || new_status == kStatusError ||
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700689 !Runtime::Current()->IsStarted()) << GetDescriptor()->ToModifiedUtf8();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700690 CHECK(sizeof(Status) == sizeof(uint32_t));
691 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_),
692 new_status, false);
693}
694
695DexCache* Class::GetDexCache() const {
696 return GetFieldObject<DexCache*>(
697 OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
698}
699
700void Class::SetDexCache(DexCache* new_dex_cache) {
701 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_),
702 new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700703}
704
Brian Carlstrom1f870082011-08-23 16:02:11 -0700705Object* Class::AllocObjectFromCode(uint32_t type_idx, Method* method) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700706 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700707 if (klass == NULL) {
708 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
709 if (klass == NULL) {
710 UNIMPLEMENTED(FATAL) << "throw an error";
711 return NULL;
712 }
713 }
Brian Carlstrom1f870082011-08-23 16:02:11 -0700714 return klass->AllocObject();
715}
716
717Object* Class::AllocObject() {
718 DCHECK(!IsAbstract());
719 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700720}
721
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700722void Class::DumpClass(std::ostream& os, int flags) {
723 if ((flags & kDumpClassFullDetail) == 0) {
724 os << PrettyClass(this);
725 if ((flags & kDumpClassClassLoader) != 0) {
726 os << ' ' << GetClassLoader();
727 }
728 if ((flags & kDumpClassInitialized) != 0) {
729 os << ' ' << GetStatus();
730 }
731 os << std::endl;
732 return;
733 }
734
735 Class* super = GetSuperClass();
736 os << "----- " << (IsInterface() ? "interface" : "class") << " "
737 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
738 os << " objectSize=" << SizeOf() << " "
739 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
740 os << StringPrintf(" access=0x%04x.%04x\n",
741 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
742 if (super != NULL) {
743 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
744 }
745 if (IsArrayClass()) {
746 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
747 }
748 if (NumInterfaces() > 0) {
749 os << " interfaces (" << NumInterfaces() << "):\n";
750 for (size_t i = 0; i < NumInterfaces(); ++i) {
751 Class* interface = GetInterface(i);
752 const ClassLoader* cl = interface->GetClassLoader();
753 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
754 }
755 }
756 os << " vtable (" << NumVirtualMethods() << " entries, "
757 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
758 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
759 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethod(i)).c_str());
760 }
761 os << " direct methods (" << NumDirectMethods() << " entries):\n";
762 for (size_t i = 0; i < NumDirectMethods(); ++i) {
763 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
764 }
765 if (NumStaticFields() > 0) {
766 os << " static fields (" << NumStaticFields() << " entries):\n";
767 for (size_t i = 0; i < NumStaticFields(); ++i) {
768 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
769 }
770 }
771 if (NumInstanceFields() > 0) {
772 os << " instance fields (" << NumInstanceFields() << " entries):\n";
773 for (size_t i = 0; i < NumInstanceFields(); ++i) {
774 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
775 }
776 }
777}
778
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700779void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
780 if (new_reference_offsets != CLASS_WALK_SUPER) {
781 // Sanity check that the number of bits set in the reference offset bitmap
782 // agrees with the number of references
783 Class* cur = this;
784 size_t cnt = 0;
785 while (cur) {
786 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
787 cur = cur->GetSuperClass();
788 }
789 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
790 }
791 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
792 new_reference_offsets, false);
793}
794
795void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
796 if (new_reference_offsets != CLASS_WALK_SUPER) {
797 // Sanity check that the number of bits set in the reference offset bitmap
798 // agrees with the number of references
799 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
800 NumReferenceStaticFieldsDuringLinking());
801 }
802 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
803 new_reference_offsets, false);
804}
805
806size_t Class::PrimitiveSize() const {
807 switch (GetPrimitiveType()) {
808 case kPrimBoolean:
809 case kPrimByte:
810 case kPrimChar:
811 case kPrimShort:
812 case kPrimInt:
813 case kPrimFloat:
814 return sizeof(int32_t);
815 case kPrimLong:
816 case kPrimDouble:
817 return sizeof(int64_t);
818 default:
819 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
820 return 0;
821 }
822}
823
824size_t Class::GetTypeSize(const String* descriptor) {
825 switch (descriptor->CharAt(0)) {
826 case 'B': return 1; // byte
827 case 'C': return 2; // char
828 case 'D': return 8; // double
829 case 'F': return 4; // float
830 case 'I': return 4; // int
831 case 'J': return 8; // long
832 case 'S': return 2; // short
833 case 'Z': return 1; // boolean
834 case 'L': return sizeof(Object*);
835 case '[': return sizeof(Array*);
836 default:
837 LOG(ERROR) << "Unknown type " << descriptor;
838 return 0;
839 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700840}
841
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700842bool Class::Implements(const Class* klass) const {
843 DCHECK(klass != NULL);
844 DCHECK(klass->IsInterface());
845 // All interfaces implemented directly and by our superclass, and
846 // recursively all super-interfaces of those interfaces, are listed
847 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700848 int32_t iftable_count = GetIfTableCount();
849 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
850 for (int32_t i = 0; i < iftable_count; i++) {
851 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700852 return true;
853 }
854 }
855 return false;
856}
857
buzbee9a195c92011-09-16 13:26:02 -0700858void Class::CanPutArrayElementFromCode(const Object* element, const Class* array_class) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700859 DCHECK(array_class != NULL);
buzbee9a195c92011-09-16 13:26:02 -0700860 if (element == NULL) {
861 return;
862 }
Brian Carlstrom25c33252011-09-18 15:58:35 -0700863 if (!array_class->GetComponentType()->IsAssignableFrom(element->GetClass())) {
buzbee9a195c92011-09-16 13:26:02 -0700864 LOG(ERROR) << "Can't put a " << PrettyClass(element->GetClass())
Elliott Hughes54e7df12011-09-16 11:47:04 -0700865 << " into a " << PrettyClass(array_class);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700866 UNIMPLEMENTED(FATAL) << "need to throw ArrayStoreException and unwind stack";
867 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700868}
869
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700870// Determine whether "this" is assignable from "klazz", where both of these
871// are array classes.
872//
873// Consider an array class, e.g. Y[][], where Y is a subclass of X.
874// Y[][] = Y[][] --> true (identity)
875// X[][] = Y[][] --> true (element superclass)
876// Y = Y[][] --> false
877// Y[] = Y[][] --> false
878// Object = Y[][] --> true (everything is an object)
879// Object[] = Y[][] --> true
880// Object[][] = Y[][] --> true
881// Object[][][] = Y[][] --> false (too many []s)
882// Serializable = Y[][] --> true (all arrays are Serializable)
883// Serializable[] = Y[][] --> true
884// Serializable[][] = Y[][] --> false (unless Y is Serializable)
885//
886// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700887// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700888//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700889bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700890 DCHECK(IsArrayClass());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700891 DCHECK(src->IsArrayClass());
892 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700893}
894
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700895bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700896 DCHECK(!IsInterface()); // handled first in IsAssignableFrom
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700897 DCHECK(src->IsArrayClass());
Brian Carlstromb63ec392011-08-27 17:38:27 -0700898 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700899 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700900 // src's super should be java_lang_Object, since it is an array.
901 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700902 DCHECK(java_lang_Object != NULL);
903 DCHECK(java_lang_Object->GetSuperClass() == NULL);
904 return this == java_lang_Object;
905 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700906 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700907}
908
909bool Class::IsSubClass(const Class* klass) const {
910 DCHECK(!IsInterface());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700911 DCHECK(!IsArrayClass());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700912 const Class* current = this;
913 do {
914 if (current == klass) {
915 return true;
916 }
917 current = current->GetSuperClass();
918 } while (current != NULL);
919 return false;
920}
921
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700922bool Class::IsInSamePackage(const String* descriptor_string_1,
923 const String* descriptor_string_2) {
924 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
925 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
926
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700927 size_t i = 0;
928 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
929 ++i;
930 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700931 if (descriptor1.find('/', i) != StringPiece::npos ||
932 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700933 return false;
934 } else {
935 return true;
936 }
937}
938
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700939#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700940bool Class::IsInSamePackage(const StringPiece& descriptor1,
941 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700942 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700943 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700944 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
945 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700946 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
947}
948#endif
949
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700950bool Class::IsInSamePackage(const Class* that) const {
951 const Class* klass1 = this;
952 const Class* klass2 = that;
953 if (klass1 == klass2) {
954 return true;
955 }
956 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700957 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700958 return false;
959 }
960 // Arrays are in the same package when their element classes are.
Brian Carlstromb63ec392011-08-27 17:38:27 -0700961 if (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700962 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700963 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700964 if (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700965 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700966 }
967 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700968 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700969}
970
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700971const ClassLoader* Class::GetClassLoader() const {
972 return GetFieldObject<const ClassLoader*>(
973 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -0700974}
975
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700976void Class::SetClassLoader(const ClassLoader* new_cl) {
977 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
978 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
979 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700980}
981
Brian Carlstrom30b94452011-08-25 21:35:26 -0700982Method* Class::FindVirtualMethodForInterface(Method* method) {
983 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700984 DCHECK(declaring_class != NULL);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700985 DCHECK(declaring_class->IsInterface());
986 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700987 int32_t iftable_count = GetIfTableCount();
988 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
989 for (int32_t i = 0; i < iftable_count; i++) {
990 InterfaceEntry* interface_entry = iftable->Get(i);
991 if (interface_entry->GetInterface() == declaring_class) {
992 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -0700993 }
994 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700995 UNIMPLEMENTED(FATAL) << "Need to throw an error of some kind " << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700996 return NULL;
997}
998
jeffhaobdb76512011-09-07 11:43:16 -0700999Method* Class::FindInterfaceMethod(const StringPiece& name,
1000 const StringPiece& signature) {
1001 // Check the current class before checking the interfaces.
1002 Method* method = FindVirtualMethod(name, signature);
1003 if (method != NULL) {
1004 return method;
1005 }
1006
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001007 int32_t iftable_count = GetIfTableCount();
1008 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1009 for (int32_t i = 0; i < iftable_count; i++) {
1010 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001011 if (method != NULL) {
1012 return method;
1013 }
1014 }
1015 return NULL;
1016}
1017
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001018Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001019 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001020 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001021 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001022 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001023 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001024 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001025 }
1026 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001027 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001028}
1029
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001030Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001031 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001032 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001033 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001034 if (method != NULL) {
1035 return method;
1036 }
1037 }
1038 return NULL;
1039}
1040
1041Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001042 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001043 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001044 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001045 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001046 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001047 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001048 }
1049 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001050 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001051}
1052
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001053Method* Class::FindVirtualMethod(const StringPiece& name,
1054 const StringPiece& descriptor) {
1055 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1056 Method* method = klass->FindDeclaredVirtualMethod(name, descriptor);
1057 if (method != NULL) {
1058 return method;
1059 }
1060 }
1061 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001062}
1063
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001064Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001065 // Is the field in this class?
1066 // Interfaces are not relevant because they can't contain instance fields.
1067 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1068 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001069 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001070 return f;
1071 }
1072 }
1073 return NULL;
1074}
1075
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001076Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001077 // Is the field in this class, or any of its superclasses?
1078 // Interfaces are not relevant because they can't contain instance fields.
1079 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001080 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001081 if (f != NULL) {
1082 return f;
1083 }
1084 }
1085 return NULL;
1086}
1087
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001088Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
1089 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -07001090 for (size_t i = 0; i < NumStaticFields(); ++i) {
1091 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001092 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001093 return f;
1094 }
1095 }
1096 return NULL;
1097}
1098
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001099Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001100 // Is the field in this class (or its interfaces), or any of its
1101 // superclasses (or their interfaces)?
1102 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1103 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001104 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001105 if (f != NULL) {
1106 return f;
1107 }
1108
1109 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001110 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1111 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1112 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001113 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001114 if (f != NULL) {
1115 return f;
1116 }
1117 }
1118 }
1119 return NULL;
1120}
1121
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001122Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001123 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001124 DCHECK_GE(component_count, 0);
1125 DCHECK(array_class->IsArrayClass());
1126 size_t size = SizeOf(component_count, component_size);
1127 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1128 if (array != NULL) {
1129 DCHECK(array->IsArrayInstance());
1130 array->SetLength(component_count);
1131 }
1132 return array;
1133}
1134
1135Array* Array::Alloc(Class* array_class, int32_t component_count) {
1136 return Alloc(array_class, component_count, array_class->GetComponentSize());
1137}
1138
1139Array* Array::AllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
1140 // TODO: throw on negative component_count
1141 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
1142 if (klass == NULL) {
1143 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
1144 if (klass == NULL || !klass->IsArrayClass()) {
1145 UNIMPLEMENTED(FATAL) << "throw an error";
1146 return NULL;
1147 }
1148 }
1149 return Array::Alloc(klass, component_count);
1150}
1151
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001152template<typename T>
1153PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001154 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001155 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1156 return down_cast<PrimitiveArray<T>*>(raw_array);
1157}
1158
1159template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1160
1161// Explicitly instantiate all the primitive array types.
1162template class PrimitiveArray<uint8_t>; // BooleanArray
1163template class PrimitiveArray<int8_t>; // ByteArray
1164template class PrimitiveArray<uint16_t>; // CharArray
1165template class PrimitiveArray<double>; // DoubleArray
1166template class PrimitiveArray<float>; // FloatArray
1167template class PrimitiveArray<int32_t>; // IntArray
1168template class PrimitiveArray<int64_t>; // LongArray
1169template class PrimitiveArray<int16_t>; // ShortArray
1170
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001171// TODO: get global references for these
1172Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001173
Brian Carlstroma663ea52011-08-19 23:33:41 -07001174void String::SetClass(Class* java_lang_String) {
1175 CHECK(java_lang_String_ == NULL);
1176 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001177 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001178}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001179
Brian Carlstroma663ea52011-08-19 23:33:41 -07001180void String::ResetClass() {
1181 CHECK(java_lang_String_ != NULL);
1182 java_lang_String_ = NULL;
1183}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001184
Brian Carlstromc74255f2011-09-11 22:47:39 -07001185String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001186 return Runtime::Current()->GetInternTable()->InternWeak(this);
1187}
1188
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001189int32_t String::GetHashCode() const {
1190 int32_t result = GetField32(
1191 OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1192 DCHECK(result != 0 ||
1193 ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0);
1194 return result;
1195}
1196
1197int32_t String::GetLength() const {
1198 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1199 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1200 return result;
1201}
1202
1203uint16_t String::CharAt(int32_t index) const {
1204 // TODO: do we need this? Equals is the only caller, and could
1205 // bounds check itself.
1206 if (index < 0 || index >= count_) {
1207 Thread* self = Thread::Current();
1208 self->ThrowNewException("Ljava/lang/StringIndexOutOfBoundsException;",
1209 "length=%i; index=%i", count_, index);
1210 return 0;
1211 }
1212 return GetCharArray()->Get(index + GetOffset());
1213}
1214
1215String* String::AllocFromUtf16(int32_t utf16_length,
1216 const uint16_t* utf16_data_in,
1217 int32_t hash_code) {
1218 String* string = Alloc(GetJavaLangString(), utf16_length);
1219 // TODO: use 16-bit wide memset variant
1220 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1221 for (int i = 0; i < utf16_length; i++) {
1222 array->Set(i, utf16_data_in[i]);
1223 }
1224 if (hash_code != 0) {
1225 string->SetHashCode(hash_code);
1226 } else {
1227 string->ComputeHashCode();
1228 }
1229 return string;
1230}
1231
1232String* String::AllocFromModifiedUtf8(const char* utf) {
1233 size_t char_count = CountModifiedUtf8Chars(utf);
1234 return AllocFromModifiedUtf8(char_count, utf);
1235}
1236
1237String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1238 const char* utf8_data_in) {
1239 String* string = Alloc(GetJavaLangString(), utf16_length);
1240 uint16_t* utf16_data_out =
1241 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1242 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1243 string->ComputeHashCode();
1244 return string;
1245}
1246
1247String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1248 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1249}
1250
1251String* String::Alloc(Class* java_lang_String, CharArray* array) {
1252 String* string = down_cast<String*>(java_lang_String->AllocObject());
1253 string->SetArray(array);
1254 string->SetCount(array->GetLength());
1255 return string;
1256}
1257
1258bool String::Equals(const String* that) const {
1259 if (this == that) {
1260 // Quick reference equality test
1261 return true;
1262 } else if (that == NULL) {
1263 // Null isn't an instanceof anything
1264 return false;
1265 } else if (this->GetLength() != that->GetLength()) {
1266 // Quick length inequality test
1267 return false;
1268 } else {
1269 // NB don't short circuit on hash code as we're presumably here as the
1270 // hash code was already equal
1271 for (int32_t i = 0; i < that->GetLength(); ++i) {
1272 if (this->CharAt(i) != that->CharAt(i)) {
1273 return false;
1274 }
1275 }
1276 return true;
1277 }
1278}
1279
1280bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1281 int32_t that_length) const {
1282 if (this->GetLength() != that_length) {
1283 return false;
1284 } else {
1285 for (int32_t i = 0; i < that_length; ++i) {
1286 if (this->CharAt(i) != that_chars[that_offset + i]) {
1287 return false;
1288 }
1289 }
1290 return true;
1291 }
1292}
1293
1294bool String::Equals(const char* modified_utf8) const {
1295 for (int32_t i = 0; i < GetLength(); ++i) {
1296 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1297 if (ch == '\0' || ch != CharAt(i)) {
1298 return false;
1299 }
1300 }
1301 return *modified_utf8 == '\0';
1302}
1303
1304bool String::Equals(const StringPiece& modified_utf8) const {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001305 // TODO: do not assume C-string representation. For now DCHECK.
1306 DCHECK_EQ(modified_utf8.data()[modified_utf8.size()], 0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001307 return Equals(modified_utf8.data());
1308}
1309
1310// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1311std::string String::ToModifiedUtf8() const {
1312 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1313 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1314 std::string result(byte_count, char(0));
1315 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1316 return result;
1317}
1318
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001319Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1320
1321void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1322 CHECK(java_lang_StackTraceElement_ == NULL);
1323 CHECK(java_lang_StackTraceElement != NULL);
1324 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1325}
1326
1327void StackTraceElement::ResetClass() {
1328 CHECK(java_lang_StackTraceElement_ != NULL);
1329 java_lang_StackTraceElement_ = NULL;
1330}
1331
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001332StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1333 const String* method_name,
1334 const String* file_name,
1335 int32_t line_number) {
1336 StackTraceElement* trace =
1337 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1338 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1339 const_cast<String*>(declaring_class), false);
1340 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1341 const_cast<String*>(method_name), false);
1342 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1343 const_cast<String*>(file_name), false);
1344 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1345 line_number, false);
1346 return trace;
1347}
1348
Elliott Hughes1f359b02011-07-17 14:27:17 -07001349static const char* kClassStatusNames[] = {
1350 "Error",
1351 "NotReady",
1352 "Idx",
1353 "Loaded",
1354 "Resolved",
1355 "Verifying",
1356 "Verified",
1357 "Initializing",
1358 "Initialized"
1359};
1360std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1361 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001362 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001363 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001364 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001365 }
1366 return os;
1367}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001368
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001369} // namespace art