blob: b94d39275d884cb84a9ae181afb186c145f842db [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
65void Object::MonitorExit(Thread* thread) {
66 Monitor::MonitorExit(thread, this);
67}
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
buzbee34cd9e52011-09-08 14:31:52 -0700110Field* Field::FindFieldFromCode(uint32_t field_idx, const Method* referrer) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700111 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
112 Field* f = class_linker->ResolveField(field_idx, referrer);
113 if (f != NULL) {
114 Class* c = f->GetDeclaringClass();
115 // If the class is already initializing, we must be inside <clinit>, or
116 // we'd still be waiting for the lock.
Brian Carlstrom25c33252011-09-18 15:58:35 -0700117 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c, true)) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700118 return f;
119 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700120 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700121 UNIMPLEMENTED(FATAL) << "throw an error and unwind";
122 return NULL;
123}
124
125uint32_t Field::Get32StaticFromCode(uint32_t field_idx, const Method* referrer) {
126 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700127 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
128 return field->Get32(NULL);
129}
130void Field::Set32StaticFromCode(uint32_t field_idx, const Method* referrer, uint32_t new_value) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700131 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700132 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
133 field->Set32(NULL, new_value);
134}
135uint64_t Field::Get64StaticFromCode(uint32_t field_idx, const Method* referrer) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700136 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700137 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
138 return field->Get64(NULL);
139}
140void Field::Set64StaticFromCode(uint32_t field_idx, const Method* referrer, uint64_t new_value) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700141 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700142 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
143 field->Set64(NULL, new_value);
144}
145Object* Field::GetObjStaticFromCode(uint32_t field_idx, const Method* referrer) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700146 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700147 DCHECK(!field->GetType()->IsPrimitive());
148 return field->GetObj(NULL);
149}
150void Field::SetObjStaticFromCode(uint32_t field_idx, const Method* referrer, Object* new_value) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700151 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700152 DCHECK(!field->GetType()->IsPrimitive());
153 field->SetObj(NULL, new_value);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700154}
155
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700156uint32_t Field::Get32(const Object* object) const {
157 CHECK((object == NULL) == IsStatic());
158 if (IsStatic()) {
159 object = declaring_class_;
160 }
161 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700162}
163
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700164void Field::Set32(Object* object, uint32_t new_value) const {
165 CHECK((object == NULL) == IsStatic());
166 if (IsStatic()) {
167 object = declaring_class_;
168 }
169 object->SetField32(GetOffset(), new_value, IsVolatile());
170}
171
172uint64_t Field::Get64(const Object* object) const {
173 CHECK((object == NULL) == IsStatic());
174 if (IsStatic()) {
175 object = declaring_class_;
176 }
177 return object->GetField64(GetOffset(), IsVolatile());
178}
179
180void Field::Set64(Object* object, uint64_t new_value) const {
181 CHECK((object == NULL) == IsStatic());
182 if (IsStatic()) {
183 object = declaring_class_;
184 }
185 object->SetField64(GetOffset(), new_value, IsVolatile());
186}
187
188Object* Field::GetObj(const Object* object) const {
189 CHECK((object == NULL) == IsStatic());
190 if (IsStatic()) {
191 object = declaring_class_;
192 }
193 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
194}
195
196void Field::SetObj(Object* object, const Object* new_value) const {
197 CHECK((object == NULL) == IsStatic());
198 if (IsStatic()) {
199 object = declaring_class_;
200 }
201 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
202}
203
204bool Field::GetBoolean(const Object* object) const {
205 DCHECK(GetType()->IsPrimitiveBoolean());
206 return Get32(object);
207}
208
209void Field::SetBoolean(Object* object, bool z) const {
210 DCHECK(GetType()->IsPrimitiveBoolean());
211 Set32(object, z);
212}
213
214int8_t Field::GetByte(const Object* object) const {
215 DCHECK(GetType()->IsPrimitiveByte());
216 return Get32(object);
217}
218
219void Field::SetByte(Object* object, int8_t b) const {
220 DCHECK(GetType()->IsPrimitiveByte());
221 Set32(object, b);
222}
223
224uint16_t Field::GetChar(const Object* object) const {
225 DCHECK(GetType()->IsPrimitiveChar());
226 return Get32(object);
227}
228
229void Field::SetChar(Object* object, uint16_t c) const {
230 DCHECK(GetType()->IsPrimitiveChar());
231 Set32(object, c);
232}
233
234uint16_t Field::GetShort(const Object* object) const {
235 DCHECK(GetType()->IsPrimitiveShort());
236 return Get32(object);
237}
238
239void Field::SetShort(Object* object, uint16_t s) const {
240 DCHECK(GetType()->IsPrimitiveShort());
241 Set32(object, s);
242}
243
244int32_t Field::GetInt(const Object* object) const {
245 DCHECK(GetType()->IsPrimitiveInt());
246 return Get32(object);
247}
248
249void Field::SetInt(Object* object, int32_t i) const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700250 DCHECK(GetType()->IsPrimitiveInt()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700251 Set32(object, i);
252}
253
254int64_t Field::GetLong(const Object* object) const {
255 DCHECK(GetType()->IsPrimitiveLong());
256 return Get64(object);
257}
258
259void Field::SetLong(Object* object, int64_t j) const {
260 DCHECK(GetType()->IsPrimitiveLong());
261 Set64(object, j);
262}
263
264float Field::GetFloat(const Object* object) const {
265 DCHECK(GetType()->IsPrimitiveFloat());
266 JValue float_bits;
267 float_bits.i = Get32(object);
268 return float_bits.f;
269}
270
271void Field::SetFloat(Object* object, float f) const {
272 DCHECK(GetType()->IsPrimitiveFloat());
273 JValue float_bits;
274 float_bits.f = f;
275 Set32(object, float_bits.i);
276}
277
278double Field::GetDouble(const Object* object) const {
279 DCHECK(GetType()->IsPrimitiveDouble());
280 JValue double_bits;
281 double_bits.j = Get64(object);
282 return double_bits.d;
283}
284
285void Field::SetDouble(Object* object, double d) const {
286 DCHECK(GetType()->IsPrimitiveDouble());
287 JValue double_bits;
288 double_bits.d = d;
289 Set64(object, double_bits.j);
290}
291
292Object* Field::GetObject(const Object* object) const {
293 CHECK(!GetType()->IsPrimitive());
294 return GetObj(object);
295}
296
297void Field::SetObject(Object* object, const Object* l) const {
298 CHECK(!GetType()->IsPrimitive());
299 SetObj(object, l);
300}
301
302// TODO: get global references for these
303Class* Method::java_lang_reflect_Method_ = NULL;
304
305void Method::SetClass(Class* java_lang_reflect_Method) {
306 CHECK(java_lang_reflect_Method_ == NULL);
307 CHECK(java_lang_reflect_Method != NULL);
308 java_lang_reflect_Method_ = java_lang_reflect_Method;
309}
310
311void Method::ResetClass() {
312 CHECK(java_lang_reflect_Method_ != NULL);
313 java_lang_reflect_Method_ = NULL;
314}
315
316ObjectArray<String>* Method::GetDexCacheStrings() const {
317 return GetFieldObject<ObjectArray<String>*>(
318 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
319}
320
321void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
322 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
323 new_return_type_idx, false);
324}
325
326Class* Method::GetReturnType() const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700327 DCHECK(GetDeclaringClass()->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700328 // Short-cut
329 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
330 if (result == NULL) {
331 // Do full linkage and set cache value for next call
332 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
333 }
334 CHECK(result != NULL);
335 return result;
336}
337
338void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
339 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
340 new_dex_cache_strings, false);
341}
342
343ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
344 return GetFieldObject<ObjectArray<Class>*>(
345 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
346}
347
348void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
349 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
350 new_dex_cache_classes, false);
351}
352
353ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
354 return GetFieldObject<ObjectArray<Method>*>(
355 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
356}
357
358void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
359 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
360 new_dex_cache_methods, false);
361}
362
363ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
364 return GetFieldObject<ObjectArray<Field>*>(
365 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
366}
367
368void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
369 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
370 new_dex_cache_fields, false);
371}
372
373CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
374 return GetFieldPtr<CodeAndDirectMethods*>(
375 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
376 false);
377}
378
379void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
380 SetFieldPtr<CodeAndDirectMethods*>(
381 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
382 new_value, false);
383}
384
385ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
386 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
387 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
388 false);
389}
390
391void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
392 SetFieldObject(
393 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
394 new_value, false);
395
396}
397
398size_t Method::NumArgRegisters(const StringPiece& shorty) {
399 CHECK_LE(1, shorty.length());
400 uint32_t num_registers = 0;
401 for (int i = 1; i < shorty.length(); ++i) {
402 char ch = shorty[i];
403 if (ch == 'D' || ch == 'J') {
404 num_registers += 2;
405 } else {
406 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700407 }
408 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409 return num_registers;
410}
411
412size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700413 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700415 for (int i = 1; i < shorty->GetLength(); ++i) {
416 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700417 if (ch == 'D' || ch == 'J') {
418 num_bytes += 8;
419 } else if (ch == 'L') {
420 // Argument is a reference or an array. The shorty descriptor
421 // does not distinguish between these types.
422 num_bytes += sizeof(Object*);
423 } else {
424 num_bytes += 4;
425 }
426 }
427 return num_bytes;
428}
429
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700430size_t Method::NumArgs() const {
431 // "1 +" because the first in Args is the receiver.
432 // "- 1" because we don't count the return type.
433 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
434}
435
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436// The number of reference arguments to this method including implicit this
437// pointer
438size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700439 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700441 for (int i = 1; i < shorty->GetLength(); i++) {
442 char ch = shorty->CharAt(i);
443 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444 result++;
445 }
446 }
447 return result;
448}
449
450// The number of long or double arguments
451size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700452 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700453 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700454 for (int i = 1; i < shorty->GetLength(); i++) {
455 char ch = shorty->CharAt(i);
456 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457 result++;
458 }
459 }
460 return result;
461}
462
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463// Is the given method parameter a reference?
464bool Method::IsParamAReference(unsigned int param) const {
465 CHECK_LT(param, NumArgs());
466 if (IsStatic()) {
467 param++; // 0th argument must skip return value at start of the shorty
468 } else if (param == 0) {
469 return true; // this argument
470 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700471 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700472}
473
474// Is the given method parameter a long or double?
475bool Method::IsParamALongOrDouble(unsigned int param) const {
476 CHECK_LT(param, NumArgs());
477 if (IsStatic()) {
478 param++; // 0th argument must skip return value at start of the shorty
479 } else if (param == 0) {
480 return false; // this argument
481 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700482 char ch = GetShorty()->CharAt(param);
483 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700484}
485
486static size_t ShortyCharToSize(char x) {
487 switch (x) {
488 case 'V': return 0;
489 case '[': return kPointerSize;
490 case 'L': return kPointerSize;
491 case 'D': return 8;
492 case 'J': return 8;
493 default: return 4;
494 }
495}
496
497size_t Method::ParamSize(unsigned int param) const {
498 CHECK_LT(param, NumArgs());
499 if (IsStatic()) {
500 param++; // 0th argument must skip return value at start of the shorty
501 } else if (param == 0) {
502 return kPointerSize; // this argument
503 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700504 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700505}
506
507size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700508 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509}
510
511bool Method::HasSameNameAndDescriptor(const Method* that) const {
512 return (this->GetName()->Equals(that->GetName()) &&
513 this->GetSignature()->Equals(that->GetSignature()));
514}
515
Ian Rogersbdb03912011-09-14 00:55:44 -0700516uint32_t Method::ToDexPC(const uintptr_t pc) const {
517 IntArray* mapping_table = GetMappingTable();
518 if (mapping_table == NULL) {
Ian Rogers67375ac2011-09-14 00:55:44 -0700519 DCHECK(IsNative());
520 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700521 }
522 size_t mapping_table_length = mapping_table->GetLength();
523 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
524 CHECK_LT(sought_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
525 uint32_t best_offset = 0;
526 uint32_t best_dex_offset = 0;
527 for (size_t i = 0; i < mapping_table_length; i += 2) {
528 uint32_t map_offset = mapping_table->Get(i);
529 uint32_t map_dex_offset = mapping_table->Get(i + 1);
530 if (map_offset == sought_offset) {
531 best_offset = map_offset;
532 best_dex_offset = map_dex_offset;
533 break;
534 }
535 if (map_offset < sought_offset && map_offset > best_offset) {
536 best_offset = map_offset;
537 best_dex_offset = map_dex_offset;
538 }
539 }
540 return best_dex_offset;
541}
542
543uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
544 IntArray* mapping_table = GetMappingTable();
545 if (mapping_table == NULL) {
546 DCHECK(dex_pc == 0);
547 return 0; // Special no mapping/pc == 0 case
548 }
549 size_t mapping_table_length = mapping_table->GetLength();
550 for (size_t i = 0; i < mapping_table_length; i += 2) {
551 uint32_t map_offset = mapping_table->Get(i);
552 uint32_t map_dex_offset = mapping_table->Get(i + 1);
553 if (map_dex_offset == dex_pc) {
554 DCHECK_LT(map_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
555 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
556 }
557 }
558 LOG(FATAL) << "Looking up Dex PC not contained in method";
559 return 0;
560}
561
562uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
563 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
564 const ClassLoader* class_loader = GetDeclaringClass()->GetClassLoader();
565 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
566 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
567 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
568 // Iterate over the catch handlers associated with dex_pc
569 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
570 !iter.HasNext(); iter.Next()) {
571 uint32_t iter_type_idx = iter.Get().type_idx_;
572 // Catch all case
573 if(iter_type_idx == DexFile::kDexNoIndex) {
574 return iter.Get().address_;
575 }
576 // Does this catch exception type apply?
577 Class* iter_exception_type =
578 class_linker->ResolveType(dex_file, iter_type_idx, dex_cache, class_loader);
579 if (iter_exception_type->IsAssignableFrom(exception_type)) {
580 return iter.Get().address_;
581 }
582 }
583 // Handler not found
584 return DexFile::kDexNoIndex;
585}
586
buzbee4ef76522011-09-08 10:00:32 -0700587void Method::SetCode(ByteArray* code_array, InstructionSet instruction_set,
Ian Rogersbdb03912011-09-14 00:55:44 -0700588 IntArray* mapping_table) {
Elliott Hughes1240dad2011-09-09 16:24:50 -0700589 CHECK(GetCode() == NULL || IsNative());
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700590 SetFieldPtr<ByteArray*>(OFFSET_OF_OBJECT_MEMBER(Method, code_array_), code_array, false);
Ian Rogersbdb03912011-09-14 00:55:44 -0700591 SetFieldPtr<IntArray*>(OFFSET_OF_OBJECT_MEMBER(Method, mapping_table_),
buzbee4ef76522011-09-08 10:00:32 -0700592 mapping_table, false);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700593 int8_t* code = code_array->GetData();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700594 uintptr_t address = reinterpret_cast<uintptr_t>(code);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700595 if (instruction_set == kThumb2) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700596 // Set the low-order bit so a BLX will switch to Thumb mode
597 address |= 0x1;
598 }
Elliott Hughes5ea047b2011-09-13 14:38:18 -0700599 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, code_), reinterpret_cast<const void*>(address), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700600}
601
Ian Rogersbdb03912011-09-14 00:55:44 -0700602bool Method::IsWithinCode(uintptr_t pc) const {
603 if (GetCode() == NULL) {
604 return false;
605 }
606 if (pc == 0) {
607 // assume that this is some initial value that will always lie in code
608 return true;
609 } else {
Ian Rogers93dd9662011-09-17 23:21:22 -0700610#if defined(__arm__)
611 pc &= ~0x1; // clear any possible thumb instruction mode bit
612#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700613 uint32_t rel_offset = pc - reinterpret_cast<uintptr_t>(GetCodeArray()->GetData());
Ian Rogers93dd9662011-09-17 23:21:22 -0700614 // Strictly the following test should be a less-than, however, if the last
615 // instruction is a call to an exception throw we may see return addresses
616 // that are 1 beyond the end of code.
617 return rel_offset <= static_cast<uint32_t>(GetCodeArray()->GetLength());
Ian Rogersbdb03912011-09-14 00:55:44 -0700618 }
619}
620
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700621void Method::SetInvokeStub(const ByteArray* invoke_stub_array) {
622 const InvokeStub* invoke_stub = reinterpret_cast<InvokeStub*>(invoke_stub_array->GetData());
623 SetFieldPtr<const ByteArray*>(
624 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_array_), invoke_stub_array, false);
625 SetFieldPtr<const InvokeStub*>(
626 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_), invoke_stub, false);
627}
628
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700629void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
630 // Push a transition back into managed code onto the linked list in thread.
631 CHECK_EQ(Thread::kRunnable, self->GetState());
632 NativeToManagedRecord record;
633 self->PushNativeToManagedRecord(&record);
634
635 // Call the invoke stub associated with the method.
636 // Pass everything as arguments.
637 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700638
639 bool have_executable_code = (GetCode() != NULL);
640#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700641 // Currently we can only compile non-native methods for ARM.
642 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700643#endif
644
645 if (have_executable_code && stub != NULL) {
646 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700647 (*stub)(this, receiver, self, args, result);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700648 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700649 } else {
650 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
651 if (result != NULL) {
652 result->j = 0;
653 }
654 }
655
656 // Pop transition.
657 self->PopNativeToManagedRecord(record);
658}
659
Brian Carlstrom16192862011-09-12 17:50:06 -0700660bool Method::IsRegistered() {
661 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
662 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
663 return native_method != jni_stub;
664}
665
666void Method::RegisterNative(const void* native_method) {
667 CHECK(IsNative());
668 CHECK(native_method != NULL);
669 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
670 native_method, false);
671}
672
673void Method::UnregisterNative() {
674 CHECK(IsNative());
675 // restore stub to lookup native pointer via dlsym
676 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
677}
678
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700679void Class::SetStatus(Status new_status) {
680 CHECK(new_status > GetStatus() || new_status == kStatusError ||
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700681 !Runtime::Current()->IsStarted()) << GetDescriptor()->ToModifiedUtf8();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700682 CHECK(sizeof(Status) == sizeof(uint32_t));
683 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_),
684 new_status, false);
685}
686
687DexCache* Class::GetDexCache() const {
688 return GetFieldObject<DexCache*>(
689 OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
690}
691
692void Class::SetDexCache(DexCache* new_dex_cache) {
693 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_),
694 new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700695}
696
Brian Carlstrom1f870082011-08-23 16:02:11 -0700697Object* Class::AllocObjectFromCode(uint32_t type_idx, Method* method) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700698 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700699 if (klass == NULL) {
700 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
701 if (klass == NULL) {
702 UNIMPLEMENTED(FATAL) << "throw an error";
703 return NULL;
704 }
705 }
Brian Carlstrom1f870082011-08-23 16:02:11 -0700706 return klass->AllocObject();
707}
708
709Object* Class::AllocObject() {
710 DCHECK(!IsAbstract());
711 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700712}
713
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700714void Class::DumpClass(std::ostream& os, int flags) {
715 if ((flags & kDumpClassFullDetail) == 0) {
716 os << PrettyClass(this);
717 if ((flags & kDumpClassClassLoader) != 0) {
718 os << ' ' << GetClassLoader();
719 }
720 if ((flags & kDumpClassInitialized) != 0) {
721 os << ' ' << GetStatus();
722 }
723 os << std::endl;
724 return;
725 }
726
727 Class* super = GetSuperClass();
728 os << "----- " << (IsInterface() ? "interface" : "class") << " "
729 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
730 os << " objectSize=" << SizeOf() << " "
731 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
732 os << StringPrintf(" access=0x%04x.%04x\n",
733 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
734 if (super != NULL) {
735 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
736 }
737 if (IsArrayClass()) {
738 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
739 }
740 if (NumInterfaces() > 0) {
741 os << " interfaces (" << NumInterfaces() << "):\n";
742 for (size_t i = 0; i < NumInterfaces(); ++i) {
743 Class* interface = GetInterface(i);
744 const ClassLoader* cl = interface->GetClassLoader();
745 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
746 }
747 }
748 os << " vtable (" << NumVirtualMethods() << " entries, "
749 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
750 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
751 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethod(i)).c_str());
752 }
753 os << " direct methods (" << NumDirectMethods() << " entries):\n";
754 for (size_t i = 0; i < NumDirectMethods(); ++i) {
755 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
756 }
757 if (NumStaticFields() > 0) {
758 os << " static fields (" << NumStaticFields() << " entries):\n";
759 for (size_t i = 0; i < NumStaticFields(); ++i) {
760 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
761 }
762 }
763 if (NumInstanceFields() > 0) {
764 os << " instance fields (" << NumInstanceFields() << " entries):\n";
765 for (size_t i = 0; i < NumInstanceFields(); ++i) {
766 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
767 }
768 }
769}
770
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700771void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
772 if (new_reference_offsets != CLASS_WALK_SUPER) {
773 // Sanity check that the number of bits set in the reference offset bitmap
774 // agrees with the number of references
775 Class* cur = this;
776 size_t cnt = 0;
777 while (cur) {
778 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
779 cur = cur->GetSuperClass();
780 }
781 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
782 }
783 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
784 new_reference_offsets, false);
785}
786
787void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
788 if (new_reference_offsets != CLASS_WALK_SUPER) {
789 // Sanity check that the number of bits set in the reference offset bitmap
790 // agrees with the number of references
791 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
792 NumReferenceStaticFieldsDuringLinking());
793 }
794 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
795 new_reference_offsets, false);
796}
797
798size_t Class::PrimitiveSize() const {
799 switch (GetPrimitiveType()) {
800 case kPrimBoolean:
801 case kPrimByte:
802 case kPrimChar:
803 case kPrimShort:
804 case kPrimInt:
805 case kPrimFloat:
806 return sizeof(int32_t);
807 case kPrimLong:
808 case kPrimDouble:
809 return sizeof(int64_t);
810 default:
811 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
812 return 0;
813 }
814}
815
816size_t Class::GetTypeSize(const String* descriptor) {
817 switch (descriptor->CharAt(0)) {
818 case 'B': return 1; // byte
819 case 'C': return 2; // char
820 case 'D': return 8; // double
821 case 'F': return 4; // float
822 case 'I': return 4; // int
823 case 'J': return 8; // long
824 case 'S': return 2; // short
825 case 'Z': return 1; // boolean
826 case 'L': return sizeof(Object*);
827 case '[': return sizeof(Array*);
828 default:
829 LOG(ERROR) << "Unknown type " << descriptor;
830 return 0;
831 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700832}
833
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700834bool Class::Implements(const Class* klass) const {
835 DCHECK(klass != NULL);
836 DCHECK(klass->IsInterface());
837 // All interfaces implemented directly and by our superclass, and
838 // recursively all super-interfaces of those interfaces, are listed
839 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700840 int32_t iftable_count = GetIfTableCount();
841 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
842 for (int32_t i = 0; i < iftable_count; i++) {
843 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700844 return true;
845 }
846 }
847 return false;
848}
849
buzbee9a195c92011-09-16 13:26:02 -0700850void Class::CanPutArrayElementFromCode(const Object* element, const Class* array_class) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700851 DCHECK(array_class != NULL);
buzbee9a195c92011-09-16 13:26:02 -0700852 if (element == NULL) {
853 return;
854 }
Brian Carlstrom25c33252011-09-18 15:58:35 -0700855 if (!array_class->GetComponentType()->IsAssignableFrom(element->GetClass())) {
buzbee9a195c92011-09-16 13:26:02 -0700856 LOG(ERROR) << "Can't put a " << PrettyClass(element->GetClass())
Elliott Hughes54e7df12011-09-16 11:47:04 -0700857 << " into a " << PrettyClass(array_class);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700858 UNIMPLEMENTED(FATAL) << "need to throw ArrayStoreException and unwind stack";
859 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700860}
861
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700862// Determine whether "this" is assignable from "klazz", where both of these
863// are array classes.
864//
865// Consider an array class, e.g. Y[][], where Y is a subclass of X.
866// Y[][] = Y[][] --> true (identity)
867// X[][] = Y[][] --> true (element superclass)
868// Y = Y[][] --> false
869// Y[] = Y[][] --> false
870// Object = Y[][] --> true (everything is an object)
871// Object[] = Y[][] --> true
872// Object[][] = Y[][] --> true
873// Object[][][] = Y[][] --> false (too many []s)
874// Serializable = Y[][] --> true (all arrays are Serializable)
875// Serializable[] = Y[][] --> true
876// Serializable[][] = Y[][] --> false (unless Y is Serializable)
877//
878// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700879// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700880//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700881bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700882 DCHECK(IsArrayClass());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700883 DCHECK(src->IsArrayClass());
884 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700885}
886
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700887bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700888 DCHECK(!IsInterface()); // handled first in IsAssignableFrom
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700889 DCHECK(src->IsArrayClass());
Brian Carlstromb63ec392011-08-27 17:38:27 -0700890 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700891 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700892 // src's super should be java_lang_Object, since it is an array.
893 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700894 DCHECK(java_lang_Object != NULL);
895 DCHECK(java_lang_Object->GetSuperClass() == NULL);
896 return this == java_lang_Object;
897 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700898 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700899}
900
901bool Class::IsSubClass(const Class* klass) const {
902 DCHECK(!IsInterface());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700903 DCHECK(!IsArrayClass());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700904 const Class* current = this;
905 do {
906 if (current == klass) {
907 return true;
908 }
909 current = current->GetSuperClass();
910 } while (current != NULL);
911 return false;
912}
913
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700914bool Class::IsInSamePackage(const String* descriptor_string_1,
915 const String* descriptor_string_2) {
916 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
917 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
918
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700919 size_t i = 0;
920 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
921 ++i;
922 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700923 if (descriptor1.find('/', i) != StringPiece::npos ||
924 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700925 return false;
926 } else {
927 return true;
928 }
929}
930
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700931#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700932bool Class::IsInSamePackage(const StringPiece& descriptor1,
933 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700934 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700935 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700936 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
937 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700938 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
939}
940#endif
941
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700942bool Class::IsInSamePackage(const Class* that) const {
943 const Class* klass1 = this;
944 const Class* klass2 = that;
945 if (klass1 == klass2) {
946 return true;
947 }
948 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700949 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700950 return false;
951 }
952 // Arrays are in the same package when their element classes are.
Brian Carlstromb63ec392011-08-27 17:38:27 -0700953 if (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700954 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700955 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700956 if (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700957 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700958 }
959 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700960 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700961}
962
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700963const ClassLoader* Class::GetClassLoader() const {
964 return GetFieldObject<const ClassLoader*>(
965 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -0700966}
967
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700968void Class::SetClassLoader(const ClassLoader* new_cl) {
969 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
970 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
971 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700972}
973
Brian Carlstrom30b94452011-08-25 21:35:26 -0700974Method* Class::FindVirtualMethodForInterface(Method* method) {
975 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700976 DCHECK(declaring_class != NULL);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700977 DCHECK(declaring_class->IsInterface());
978 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700979 int32_t iftable_count = GetIfTableCount();
980 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
981 for (int32_t i = 0; i < iftable_count; i++) {
982 InterfaceEntry* interface_entry = iftable->Get(i);
983 if (interface_entry->GetInterface() == declaring_class) {
984 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -0700985 }
986 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700987 UNIMPLEMENTED(FATAL) << "Need to throw an error of some kind " << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700988 return NULL;
989}
990
jeffhaobdb76512011-09-07 11:43:16 -0700991Method* Class::FindInterfaceMethod(const StringPiece& name,
992 const StringPiece& signature) {
993 // Check the current class before checking the interfaces.
994 Method* method = FindVirtualMethod(name, signature);
995 if (method != NULL) {
996 return method;
997 }
998
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700999 int32_t iftable_count = GetIfTableCount();
1000 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1001 for (int32_t i = 0; i < iftable_count; i++) {
1002 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001003 if (method != NULL) {
1004 return method;
1005 }
1006 }
1007 return NULL;
1008}
1009
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001010Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001011 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001012 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001013 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001014 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001015 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001016 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001017 }
1018 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001019 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001020}
1021
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001022Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001023 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001024 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001025 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001026 if (method != NULL) {
1027 return method;
1028 }
1029 }
1030 return NULL;
1031}
1032
1033Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001034 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001035 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001036 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001037 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001038 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001039 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001040 }
1041 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001042 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001043}
1044
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001045Method* Class::FindVirtualMethod(const StringPiece& name,
1046 const StringPiece& descriptor) {
1047 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1048 Method* method = klass->FindDeclaredVirtualMethod(name, descriptor);
1049 if (method != NULL) {
1050 return method;
1051 }
1052 }
1053 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001054}
1055
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001056Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001057 // Is the field in this class?
1058 // Interfaces are not relevant because they can't contain instance fields.
1059 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1060 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001061 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001062 return f;
1063 }
1064 }
1065 return NULL;
1066}
1067
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001068Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001069 // Is the field in this class, or any of its superclasses?
1070 // Interfaces are not relevant because they can't contain instance fields.
1071 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001072 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001073 if (f != NULL) {
1074 return f;
1075 }
1076 }
1077 return NULL;
1078}
1079
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001080Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
1081 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -07001082 for (size_t i = 0; i < NumStaticFields(); ++i) {
1083 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001084 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001085 return f;
1086 }
1087 }
1088 return NULL;
1089}
1090
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001091Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001092 // Is the field in this class (or its interfaces), or any of its
1093 // superclasses (or their interfaces)?
1094 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1095 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001096 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001097 if (f != NULL) {
1098 return f;
1099 }
1100
1101 // Is this field in any of this class' interfaces?
1102 for (size_t i = 0; i < c->NumInterfaces(); ++i) {
1103 Class* interface = c->GetInterface(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001104 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001105 if (f != NULL) {
1106 return f;
1107 }
1108 }
1109 }
1110 return NULL;
1111}
1112
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001113Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001114 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001115 DCHECK_GE(component_count, 0);
1116 DCHECK(array_class->IsArrayClass());
1117 size_t size = SizeOf(component_count, component_size);
1118 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1119 if (array != NULL) {
1120 DCHECK(array->IsArrayInstance());
1121 array->SetLength(component_count);
1122 }
1123 return array;
1124}
1125
1126Array* Array::Alloc(Class* array_class, int32_t component_count) {
1127 return Alloc(array_class, component_count, array_class->GetComponentSize());
1128}
1129
1130Array* Array::AllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
1131 // TODO: throw on negative component_count
1132 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
1133 if (klass == NULL) {
1134 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
1135 if (klass == NULL || !klass->IsArrayClass()) {
1136 UNIMPLEMENTED(FATAL) << "throw an error";
1137 return NULL;
1138 }
1139 }
1140 return Array::Alloc(klass, component_count);
1141}
1142
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001143template<typename T>
1144PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001145 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001146 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1147 return down_cast<PrimitiveArray<T>*>(raw_array);
1148}
1149
1150template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1151
1152// Explicitly instantiate all the primitive array types.
1153template class PrimitiveArray<uint8_t>; // BooleanArray
1154template class PrimitiveArray<int8_t>; // ByteArray
1155template class PrimitiveArray<uint16_t>; // CharArray
1156template class PrimitiveArray<double>; // DoubleArray
1157template class PrimitiveArray<float>; // FloatArray
1158template class PrimitiveArray<int32_t>; // IntArray
1159template class PrimitiveArray<int64_t>; // LongArray
1160template class PrimitiveArray<int16_t>; // ShortArray
1161
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001162// TODO: get global references for these
1163Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001164
Brian Carlstroma663ea52011-08-19 23:33:41 -07001165void String::SetClass(Class* java_lang_String) {
1166 CHECK(java_lang_String_ == NULL);
1167 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001168 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001169}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001170
Brian Carlstroma663ea52011-08-19 23:33:41 -07001171void String::ResetClass() {
1172 CHECK(java_lang_String_ != NULL);
1173 java_lang_String_ = NULL;
1174}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001175
Brian Carlstromc74255f2011-09-11 22:47:39 -07001176String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001177 return Runtime::Current()->GetInternTable()->InternWeak(this);
1178}
1179
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001180int32_t String::GetHashCode() const {
1181 int32_t result = GetField32(
1182 OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1183 DCHECK(result != 0 ||
1184 ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0);
1185 return result;
1186}
1187
1188int32_t String::GetLength() const {
1189 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1190 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1191 return result;
1192}
1193
1194uint16_t String::CharAt(int32_t index) const {
1195 // TODO: do we need this? Equals is the only caller, and could
1196 // bounds check itself.
1197 if (index < 0 || index >= count_) {
1198 Thread* self = Thread::Current();
1199 self->ThrowNewException("Ljava/lang/StringIndexOutOfBoundsException;",
1200 "length=%i; index=%i", count_, index);
1201 return 0;
1202 }
1203 return GetCharArray()->Get(index + GetOffset());
1204}
1205
1206String* String::AllocFromUtf16(int32_t utf16_length,
1207 const uint16_t* utf16_data_in,
1208 int32_t hash_code) {
1209 String* string = Alloc(GetJavaLangString(), utf16_length);
1210 // TODO: use 16-bit wide memset variant
1211 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1212 for (int i = 0; i < utf16_length; i++) {
1213 array->Set(i, utf16_data_in[i]);
1214 }
1215 if (hash_code != 0) {
1216 string->SetHashCode(hash_code);
1217 } else {
1218 string->ComputeHashCode();
1219 }
1220 return string;
1221}
1222
1223String* String::AllocFromModifiedUtf8(const char* utf) {
1224 size_t char_count = CountModifiedUtf8Chars(utf);
1225 return AllocFromModifiedUtf8(char_count, utf);
1226}
1227
1228String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1229 const char* utf8_data_in) {
1230 String* string = Alloc(GetJavaLangString(), utf16_length);
1231 uint16_t* utf16_data_out =
1232 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1233 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1234 string->ComputeHashCode();
1235 return string;
1236}
1237
1238String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1239 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1240}
1241
1242String* String::Alloc(Class* java_lang_String, CharArray* array) {
1243 String* string = down_cast<String*>(java_lang_String->AllocObject());
1244 string->SetArray(array);
1245 string->SetCount(array->GetLength());
1246 return string;
1247}
1248
1249bool String::Equals(const String* that) const {
1250 if (this == that) {
1251 // Quick reference equality test
1252 return true;
1253 } else if (that == NULL) {
1254 // Null isn't an instanceof anything
1255 return false;
1256 } else if (this->GetLength() != that->GetLength()) {
1257 // Quick length inequality test
1258 return false;
1259 } else {
1260 // NB don't short circuit on hash code as we're presumably here as the
1261 // hash code was already equal
1262 for (int32_t i = 0; i < that->GetLength(); ++i) {
1263 if (this->CharAt(i) != that->CharAt(i)) {
1264 return false;
1265 }
1266 }
1267 return true;
1268 }
1269}
1270
1271bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1272 int32_t that_length) const {
1273 if (this->GetLength() != that_length) {
1274 return false;
1275 } else {
1276 for (int32_t i = 0; i < that_length; ++i) {
1277 if (this->CharAt(i) != that_chars[that_offset + i]) {
1278 return false;
1279 }
1280 }
1281 return true;
1282 }
1283}
1284
1285bool String::Equals(const char* modified_utf8) const {
1286 for (int32_t i = 0; i < GetLength(); ++i) {
1287 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1288 if (ch == '\0' || ch != CharAt(i)) {
1289 return false;
1290 }
1291 }
1292 return *modified_utf8 == '\0';
1293}
1294
1295bool String::Equals(const StringPiece& modified_utf8) const {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001296 // TODO: do not assume C-string representation. For now DCHECK.
1297 DCHECK_EQ(modified_utf8.data()[modified_utf8.size()], 0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001298 return Equals(modified_utf8.data());
1299}
1300
1301// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1302std::string String::ToModifiedUtf8() const {
1303 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1304 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1305 std::string result(byte_count, char(0));
1306 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1307 return result;
1308}
1309
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001310Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1311
1312void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1313 CHECK(java_lang_StackTraceElement_ == NULL);
1314 CHECK(java_lang_StackTraceElement != NULL);
1315 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1316}
1317
1318void StackTraceElement::ResetClass() {
1319 CHECK(java_lang_StackTraceElement_ != NULL);
1320 java_lang_StackTraceElement_ = NULL;
1321}
1322
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001323StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1324 const String* method_name,
1325 const String* file_name,
1326 int32_t line_number) {
1327 StackTraceElement* trace =
1328 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1329 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1330 const_cast<String*>(declaring_class), false);
1331 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1332 const_cast<String*>(method_name), false);
1333 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1334 const_cast<String*>(file_name), false);
1335 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1336 line_number, false);
1337 return trace;
1338}
1339
Elliott Hughes1f359b02011-07-17 14:27:17 -07001340static const char* kClassStatusNames[] = {
1341 "Error",
1342 "NotReady",
1343 "Idx",
1344 "Loaded",
1345 "Resolved",
1346 "Verifying",
1347 "Verified",
1348 "Initializing",
1349 "Initialized"
1350};
1351std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1352 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001353 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001354 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001355 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001356 }
1357 return os;
1358}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001359
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001360} // namespace art