blob: 6490797c4c4832429a89188c0fcf7a6df1e029b6 [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>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008#include <string>
9#include <utility>
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070011#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070012#include "class_loader.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070013#include "dex_cache.h"
14#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070015#include "globals.h"
Brian Carlstroma40f9bc2011-07-26 21:26:07 -070016#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070017#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070019#include "monitor.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include "runtime.h"
Carl Shapiro3ee755d2011-06-28 12:11:04 -070021
22namespace art {
23
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070024bool Object::IsString() const {
25 // TODO use "klass_ == String::GetJavaLangString()" instead?
26 return GetClass() == GetClass()->GetDescriptor()->GetClass();
27}
28
Elliott Hughes5f791332011-09-15 17:45:30 -070029uint32_t Object::GetLockOwner() {
30 return Monitor::GetLockOwner(monitor_);
31}
32
33void Object::MonitorEnter(Thread* thread) {
34 Monitor::MonitorEnter(thread, this);
35}
36
37void Object::MonitorExit(Thread* thread) {
38 Monitor::MonitorExit(thread, this);
39}
40
41void Object::Notify() {
42 Monitor::Notify(Thread::Current(), this);
43}
44
45void Object::NotifyAll() {
46 Monitor::NotifyAll(Thread::Current(), this);
47}
48
49void Object::Wait(int64_t ms, int32_t ns) {
50 Monitor::Wait(Thread::Current(), this, ms, ns, true);
51}
52
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070053// TODO: get global references for these
54Class* Field::java_lang_reflect_Field_ = NULL;
55
56void Field::SetClass(Class* java_lang_reflect_Field) {
57 CHECK(java_lang_reflect_Field_ == NULL);
58 CHECK(java_lang_reflect_Field != NULL);
59 java_lang_reflect_Field_ = java_lang_reflect_Field;
60}
61
62void Field::ResetClass() {
63 CHECK(java_lang_reflect_Field_ != NULL);
64 java_lang_reflect_Field_ = NULL;
65}
66
67void Field::SetTypeIdx(uint32_t type_idx) {
68 SetField32(OFFSET_OF_OBJECT_MEMBER(Field, type_idx_), type_idx, false);
69}
70
71Class* Field::GetTypeDuringLinking() const {
72 // We are assured that the necessary primitive types are in the dex cache
73 // early during class linking
74 return GetDeclaringClass()->GetDexCache()->GetResolvedType(GetTypeIdx());
75}
76
77Class* Field::GetType() const {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070078 // Do full linkage (which sets dex cache value to speed next call)
79 return Runtime::Current()->GetClassLinker()->ResolveType(GetTypeIdx(), this);
80}
81
buzbee34cd9e52011-09-08 14:31:52 -070082Field* Field::FindFieldFromCode(uint32_t field_idx, const Method* referrer) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -070083 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
84 Field* f = class_linker->ResolveField(field_idx, referrer);
85 if (f != NULL) {
86 Class* c = f->GetDeclaringClass();
87 // If the class is already initializing, we must be inside <clinit>, or
88 // we'd still be waiting for the lock.
89 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c)) {
90 return f;
91 }
Brian Carlstromb63ec392011-08-27 17:38:27 -070092 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -070093 UNIMPLEMENTED(FATAL) << "throw an error and unwind";
94 return NULL;
95}
96
97uint32_t Field::Get32StaticFromCode(uint32_t field_idx, const Method* referrer) {
98 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070099 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
100 return field->Get32(NULL);
101}
102void Field::Set32StaticFromCode(uint32_t field_idx, const Method* referrer, uint32_t new_value) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700103 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700104 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
105 field->Set32(NULL, new_value);
106}
107uint64_t Field::Get64StaticFromCode(uint32_t field_idx, const Method* referrer) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700108 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700109 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
110 return field->Get64(NULL);
111}
112void Field::Set64StaticFromCode(uint32_t field_idx, const Method* referrer, uint64_t new_value) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700113 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700114 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
115 field->Set64(NULL, new_value);
116}
117Object* Field::GetObjStaticFromCode(uint32_t field_idx, const Method* referrer) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700118 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700119 DCHECK(!field->GetType()->IsPrimitive());
120 return field->GetObj(NULL);
121}
122void Field::SetObjStaticFromCode(uint32_t field_idx, const Method* referrer, Object* new_value) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700123 Field* field = FindFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700124 DCHECK(!field->GetType()->IsPrimitive());
125 field->SetObj(NULL, new_value);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700126}
127
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700128uint32_t Field::Get32(const Object* object) const {
129 CHECK((object == NULL) == IsStatic());
130 if (IsStatic()) {
131 object = declaring_class_;
132 }
133 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700134}
135
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700136void Field::Set32(Object* object, uint32_t new_value) const {
137 CHECK((object == NULL) == IsStatic());
138 if (IsStatic()) {
139 object = declaring_class_;
140 }
141 object->SetField32(GetOffset(), new_value, IsVolatile());
142}
143
144uint64_t Field::Get64(const Object* object) const {
145 CHECK((object == NULL) == IsStatic());
146 if (IsStatic()) {
147 object = declaring_class_;
148 }
149 return object->GetField64(GetOffset(), IsVolatile());
150}
151
152void Field::Set64(Object* object, uint64_t new_value) const {
153 CHECK((object == NULL) == IsStatic());
154 if (IsStatic()) {
155 object = declaring_class_;
156 }
157 object->SetField64(GetOffset(), new_value, IsVolatile());
158}
159
160Object* Field::GetObj(const Object* object) const {
161 CHECK((object == NULL) == IsStatic());
162 if (IsStatic()) {
163 object = declaring_class_;
164 }
165 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
166}
167
168void Field::SetObj(Object* object, const Object* new_value) const {
169 CHECK((object == NULL) == IsStatic());
170 if (IsStatic()) {
171 object = declaring_class_;
172 }
173 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
174}
175
176bool Field::GetBoolean(const Object* object) const {
177 DCHECK(GetType()->IsPrimitiveBoolean());
178 return Get32(object);
179}
180
181void Field::SetBoolean(Object* object, bool z) const {
182 DCHECK(GetType()->IsPrimitiveBoolean());
183 Set32(object, z);
184}
185
186int8_t Field::GetByte(const Object* object) const {
187 DCHECK(GetType()->IsPrimitiveByte());
188 return Get32(object);
189}
190
191void Field::SetByte(Object* object, int8_t b) const {
192 DCHECK(GetType()->IsPrimitiveByte());
193 Set32(object, b);
194}
195
196uint16_t Field::GetChar(const Object* object) const {
197 DCHECK(GetType()->IsPrimitiveChar());
198 return Get32(object);
199}
200
201void Field::SetChar(Object* object, uint16_t c) const {
202 DCHECK(GetType()->IsPrimitiveChar());
203 Set32(object, c);
204}
205
206uint16_t Field::GetShort(const Object* object) const {
207 DCHECK(GetType()->IsPrimitiveShort());
208 return Get32(object);
209}
210
211void Field::SetShort(Object* object, uint16_t s) const {
212 DCHECK(GetType()->IsPrimitiveShort());
213 Set32(object, s);
214}
215
216int32_t Field::GetInt(const Object* object) const {
217 DCHECK(GetType()->IsPrimitiveInt());
218 return Get32(object);
219}
220
221void Field::SetInt(Object* object, int32_t i) const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700222 DCHECK(GetType()->IsPrimitiveInt()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700223 Set32(object, i);
224}
225
226int64_t Field::GetLong(const Object* object) const {
227 DCHECK(GetType()->IsPrimitiveLong());
228 return Get64(object);
229}
230
231void Field::SetLong(Object* object, int64_t j) const {
232 DCHECK(GetType()->IsPrimitiveLong());
233 Set64(object, j);
234}
235
236float Field::GetFloat(const Object* object) const {
237 DCHECK(GetType()->IsPrimitiveFloat());
238 JValue float_bits;
239 float_bits.i = Get32(object);
240 return float_bits.f;
241}
242
243void Field::SetFloat(Object* object, float f) const {
244 DCHECK(GetType()->IsPrimitiveFloat());
245 JValue float_bits;
246 float_bits.f = f;
247 Set32(object, float_bits.i);
248}
249
250double Field::GetDouble(const Object* object) const {
251 DCHECK(GetType()->IsPrimitiveDouble());
252 JValue double_bits;
253 double_bits.j = Get64(object);
254 return double_bits.d;
255}
256
257void Field::SetDouble(Object* object, double d) const {
258 DCHECK(GetType()->IsPrimitiveDouble());
259 JValue double_bits;
260 double_bits.d = d;
261 Set64(object, double_bits.j);
262}
263
264Object* Field::GetObject(const Object* object) const {
265 CHECK(!GetType()->IsPrimitive());
266 return GetObj(object);
267}
268
269void Field::SetObject(Object* object, const Object* l) const {
270 CHECK(!GetType()->IsPrimitive());
271 SetObj(object, l);
272}
273
274// TODO: get global references for these
275Class* Method::java_lang_reflect_Method_ = NULL;
276
277void Method::SetClass(Class* java_lang_reflect_Method) {
278 CHECK(java_lang_reflect_Method_ == NULL);
279 CHECK(java_lang_reflect_Method != NULL);
280 java_lang_reflect_Method_ = java_lang_reflect_Method;
281}
282
283void Method::ResetClass() {
284 CHECK(java_lang_reflect_Method_ != NULL);
285 java_lang_reflect_Method_ = NULL;
286}
287
288ObjectArray<String>* Method::GetDexCacheStrings() const {
289 return GetFieldObject<ObjectArray<String>*>(
290 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
291}
292
293void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
294 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
295 new_return_type_idx, false);
296}
297
298Class* Method::GetReturnType() const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700299 DCHECK(GetDeclaringClass()->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300 // Short-cut
301 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
302 if (result == NULL) {
303 // Do full linkage and set cache value for next call
304 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
305 }
306 CHECK(result != NULL);
307 return result;
308}
309
310void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
311 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
312 new_dex_cache_strings, false);
313}
314
315ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
316 return GetFieldObject<ObjectArray<Class>*>(
317 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
318}
319
320void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
321 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
322 new_dex_cache_classes, false);
323}
324
325ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
326 return GetFieldObject<ObjectArray<Method>*>(
327 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
328}
329
330void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
331 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
332 new_dex_cache_methods, false);
333}
334
335ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
336 return GetFieldObject<ObjectArray<Field>*>(
337 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
338}
339
340void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
341 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
342 new_dex_cache_fields, false);
343}
344
345CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
346 return GetFieldPtr<CodeAndDirectMethods*>(
347 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
348 false);
349}
350
351void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
352 SetFieldPtr<CodeAndDirectMethods*>(
353 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
354 new_value, false);
355}
356
357ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
358 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
359 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
360 false);
361}
362
363void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
364 SetFieldObject(
365 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
366 new_value, false);
367
368}
369
370size_t Method::NumArgRegisters(const StringPiece& shorty) {
371 CHECK_LE(1, shorty.length());
372 uint32_t num_registers = 0;
373 for (int i = 1; i < shorty.length(); ++i) {
374 char ch = shorty[i];
375 if (ch == 'D' || ch == 'J') {
376 num_registers += 2;
377 } else {
378 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700379 }
380 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381 return num_registers;
382}
383
384size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700385 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700387 for (int i = 1; i < shorty->GetLength(); ++i) {
388 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389 if (ch == 'D' || ch == 'J') {
390 num_bytes += 8;
391 } else if (ch == 'L') {
392 // Argument is a reference or an array. The shorty descriptor
393 // does not distinguish between these types.
394 num_bytes += sizeof(Object*);
395 } else {
396 num_bytes += 4;
397 }
398 }
399 return num_bytes;
400}
401
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700402size_t Method::NumArgs() const {
403 // "1 +" because the first in Args is the receiver.
404 // "- 1" because we don't count the return type.
405 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
406}
407
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700408// The number of reference arguments to this method including implicit this
409// pointer
410size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700411 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700412 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700413 for (int i = 1; i < shorty->GetLength(); i++) {
414 char ch = shorty->CharAt(i);
415 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416 result++;
417 }
418 }
419 return result;
420}
421
422// The number of long or double arguments
423size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700424 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700426 for (int i = 1; i < shorty->GetLength(); i++) {
427 char ch = shorty->CharAt(i);
428 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700429 result++;
430 }
431 }
432 return result;
433}
434
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435// Is the given method parameter a reference?
436bool Method::IsParamAReference(unsigned int param) const {
437 CHECK_LT(param, NumArgs());
438 if (IsStatic()) {
439 param++; // 0th argument must skip return value at start of the shorty
440 } else if (param == 0) {
441 return true; // this argument
442 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700443 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444}
445
446// Is the given method parameter a long or double?
447bool Method::IsParamALongOrDouble(unsigned int param) const {
448 CHECK_LT(param, NumArgs());
449 if (IsStatic()) {
450 param++; // 0th argument must skip return value at start of the shorty
451 } else if (param == 0) {
452 return false; // this argument
453 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700454 char ch = GetShorty()->CharAt(param);
455 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700456}
457
458static size_t ShortyCharToSize(char x) {
459 switch (x) {
460 case 'V': return 0;
461 case '[': return kPointerSize;
462 case 'L': return kPointerSize;
463 case 'D': return 8;
464 case 'J': return 8;
465 default: return 4;
466 }
467}
468
469size_t Method::ParamSize(unsigned int param) const {
470 CHECK_LT(param, NumArgs());
471 if (IsStatic()) {
472 param++; // 0th argument must skip return value at start of the shorty
473 } else if (param == 0) {
474 return kPointerSize; // this argument
475 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700476 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477}
478
479size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700480 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700481}
482
483bool Method::HasSameNameAndDescriptor(const Method* that) const {
484 return (this->GetName()->Equals(that->GetName()) &&
485 this->GetSignature()->Equals(that->GetSignature()));
486}
487
Ian Rogersbdb03912011-09-14 00:55:44 -0700488uint32_t Method::ToDexPC(const uintptr_t pc) const {
489 IntArray* mapping_table = GetMappingTable();
490 if (mapping_table == NULL) {
Ian Rogers67375ac2011-09-14 00:55:44 -0700491 DCHECK(IsNative());
492 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700493 }
494 size_t mapping_table_length = mapping_table->GetLength();
495 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
496 CHECK_LT(sought_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
497 uint32_t best_offset = 0;
498 uint32_t best_dex_offset = 0;
499 for (size_t i = 0; i < mapping_table_length; i += 2) {
500 uint32_t map_offset = mapping_table->Get(i);
501 uint32_t map_dex_offset = mapping_table->Get(i + 1);
502 if (map_offset == sought_offset) {
503 best_offset = map_offset;
504 best_dex_offset = map_dex_offset;
505 break;
506 }
507 if (map_offset < sought_offset && map_offset > best_offset) {
508 best_offset = map_offset;
509 best_dex_offset = map_dex_offset;
510 }
511 }
512 return best_dex_offset;
513}
514
515uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
516 IntArray* mapping_table = GetMappingTable();
517 if (mapping_table == NULL) {
518 DCHECK(dex_pc == 0);
519 return 0; // Special no mapping/pc == 0 case
520 }
521 size_t mapping_table_length = mapping_table->GetLength();
522 for (size_t i = 0; i < mapping_table_length; i += 2) {
523 uint32_t map_offset = mapping_table->Get(i);
524 uint32_t map_dex_offset = mapping_table->Get(i + 1);
525 if (map_dex_offset == dex_pc) {
526 DCHECK_LT(map_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
527 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
528 }
529 }
530 LOG(FATAL) << "Looking up Dex PC not contained in method";
531 return 0;
532}
533
534uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
535 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
536 const ClassLoader* class_loader = GetDeclaringClass()->GetClassLoader();
537 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
538 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
539 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
540 // Iterate over the catch handlers associated with dex_pc
541 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
542 !iter.HasNext(); iter.Next()) {
543 uint32_t iter_type_idx = iter.Get().type_idx_;
544 // Catch all case
545 if(iter_type_idx == DexFile::kDexNoIndex) {
546 return iter.Get().address_;
547 }
548 // Does this catch exception type apply?
549 Class* iter_exception_type =
550 class_linker->ResolveType(dex_file, iter_type_idx, dex_cache, class_loader);
551 if (iter_exception_type->IsAssignableFrom(exception_type)) {
552 return iter.Get().address_;
553 }
554 }
555 // Handler not found
556 return DexFile::kDexNoIndex;
557}
558
buzbee4ef76522011-09-08 10:00:32 -0700559void Method::SetCode(ByteArray* code_array, InstructionSet instruction_set,
Ian Rogersbdb03912011-09-14 00:55:44 -0700560 IntArray* mapping_table) {
Elliott Hughes1240dad2011-09-09 16:24:50 -0700561 CHECK(GetCode() == NULL || IsNative());
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700562 SetFieldPtr<ByteArray*>(OFFSET_OF_OBJECT_MEMBER(Method, code_array_), code_array, false);
Ian Rogersbdb03912011-09-14 00:55:44 -0700563 SetFieldPtr<IntArray*>(OFFSET_OF_OBJECT_MEMBER(Method, mapping_table_),
buzbee4ef76522011-09-08 10:00:32 -0700564 mapping_table, false);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700565 int8_t* code = code_array->GetData();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566 uintptr_t address = reinterpret_cast<uintptr_t>(code);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700567 if (instruction_set == kThumb2) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568 // Set the low-order bit so a BLX will switch to Thumb mode
569 address |= 0x1;
570 }
Elliott Hughes5ea047b2011-09-13 14:38:18 -0700571 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, code_), reinterpret_cast<const void*>(address), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572}
573
Ian Rogersbdb03912011-09-14 00:55:44 -0700574bool Method::IsWithinCode(uintptr_t pc) const {
575 if (GetCode() == NULL) {
576 return false;
577 }
578 if (pc == 0) {
579 // assume that this is some initial value that will always lie in code
580 return true;
581 } else {
582 uint32_t rel_offset = pc - reinterpret_cast<uintptr_t>(GetCodeArray()->GetData());
583 return rel_offset < static_cast<uint32_t>(GetCodeArray()->GetLength());
584 }
585}
586
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700587void Method::SetInvokeStub(const ByteArray* invoke_stub_array) {
588 const InvokeStub* invoke_stub = reinterpret_cast<InvokeStub*>(invoke_stub_array->GetData());
589 SetFieldPtr<const ByteArray*>(
590 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_array_), invoke_stub_array, false);
591 SetFieldPtr<const InvokeStub*>(
592 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_), invoke_stub, false);
593}
594
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700595void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
596 // Push a transition back into managed code onto the linked list in thread.
597 CHECK_EQ(Thread::kRunnable, self->GetState());
598 NativeToManagedRecord record;
599 self->PushNativeToManagedRecord(&record);
600
601 // Call the invoke stub associated with the method.
602 // Pass everything as arguments.
603 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700604
605 bool have_executable_code = (GetCode() != NULL);
606#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700607 // Currently we can only compile non-native methods for ARM.
608 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700609#endif
610
611 if (have_executable_code && stub != NULL) {
612 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700613 (*stub)(this, receiver, self, args, result);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700614 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700615 } else {
616 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
617 if (result != NULL) {
618 result->j = 0;
619 }
620 }
621
622 // Pop transition.
623 self->PopNativeToManagedRecord(record);
624}
625
Brian Carlstrom16192862011-09-12 17:50:06 -0700626bool Method::IsRegistered() {
627 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
628 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
629 return native_method != jni_stub;
630}
631
632void Method::RegisterNative(const void* native_method) {
633 CHECK(IsNative());
634 CHECK(native_method != NULL);
635 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
636 native_method, false);
637}
638
639void Method::UnregisterNative() {
640 CHECK(IsNative());
641 // restore stub to lookup native pointer via dlsym
642 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
643}
644
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700645void Class::SetStatus(Status new_status) {
646 CHECK(new_status > GetStatus() || new_status == kStatusError ||
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700647 !Runtime::Current()->IsStarted()) << GetDescriptor()->ToModifiedUtf8();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700648 CHECK(sizeof(Status) == sizeof(uint32_t));
649 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_),
650 new_status, false);
651}
652
653DexCache* Class::GetDexCache() const {
654 return GetFieldObject<DexCache*>(
655 OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
656}
657
658void Class::SetDexCache(DexCache* new_dex_cache) {
659 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_),
660 new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700661}
662
Brian Carlstrom1f870082011-08-23 16:02:11 -0700663Object* Class::AllocObjectFromCode(uint32_t type_idx, Method* method) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700664 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700665 if (klass == NULL) {
666 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
667 if (klass == NULL) {
668 UNIMPLEMENTED(FATAL) << "throw an error";
669 return NULL;
670 }
671 }
Brian Carlstrom1f870082011-08-23 16:02:11 -0700672 return klass->AllocObject();
673}
674
675Object* Class::AllocObject() {
676 DCHECK(!IsAbstract());
677 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700678}
679
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700680void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
681 if (new_reference_offsets != CLASS_WALK_SUPER) {
682 // Sanity check that the number of bits set in the reference offset bitmap
683 // agrees with the number of references
684 Class* cur = this;
685 size_t cnt = 0;
686 while (cur) {
687 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
688 cur = cur->GetSuperClass();
689 }
690 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
691 }
692 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
693 new_reference_offsets, false);
694}
695
696void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
697 if (new_reference_offsets != CLASS_WALK_SUPER) {
698 // Sanity check that the number of bits set in the reference offset bitmap
699 // agrees with the number of references
700 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
701 NumReferenceStaticFieldsDuringLinking());
702 }
703 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
704 new_reference_offsets, false);
705}
706
707size_t Class::PrimitiveSize() const {
708 switch (GetPrimitiveType()) {
709 case kPrimBoolean:
710 case kPrimByte:
711 case kPrimChar:
712 case kPrimShort:
713 case kPrimInt:
714 case kPrimFloat:
715 return sizeof(int32_t);
716 case kPrimLong:
717 case kPrimDouble:
718 return sizeof(int64_t);
719 default:
720 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
721 return 0;
722 }
723}
724
725size_t Class::GetTypeSize(const String* descriptor) {
726 switch (descriptor->CharAt(0)) {
727 case 'B': return 1; // byte
728 case 'C': return 2; // char
729 case 'D': return 8; // double
730 case 'F': return 4; // float
731 case 'I': return 4; // int
732 case 'J': return 8; // long
733 case 'S': return 2; // short
734 case 'Z': return 1; // boolean
735 case 'L': return sizeof(Object*);
736 case '[': return sizeof(Array*);
737 default:
738 LOG(ERROR) << "Unknown type " << descriptor;
739 return 0;
740 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700741}
742
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700743bool Class::Implements(const Class* klass) const {
744 DCHECK(klass != NULL);
745 DCHECK(klass->IsInterface());
746 // All interfaces implemented directly and by our superclass, and
747 // recursively all super-interfaces of those interfaces, are listed
748 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700749 int32_t iftable_count = GetIfTableCount();
750 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
751 for (int32_t i = 0; i < iftable_count; i++) {
752 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700753 return true;
754 }
755 }
756 return false;
757}
758
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700759bool Class::CanPutArrayElement(const Class* object_class, const Class* array_class) {
760 if (object_class->IsArrayClass()) {
761 return array_class->IsArrayAssignableFromArray(object_class);
762 } else {
763 return array_class->GetComponentType()->IsAssignableFrom(object_class);
764 }
765}
766
buzbee9a195c92011-09-16 13:26:02 -0700767void Class::CanPutArrayElementFromCode(const Object* element, const Class* array_class) {
768 if (element == NULL) {
769 return;
770 }
771 if (!CanPutArrayElement(element->GetClass(), array_class)) {
772 LOG(ERROR) << "Can't put a " << PrettyClass(element->GetClass())
Elliott Hughes54e7df12011-09-16 11:47:04 -0700773 << " into a " << PrettyClass(array_class);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700774 UNIMPLEMENTED(FATAL) << "need to throw ArrayStoreException and unwind stack";
775 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700776}
777
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700778// Determine whether "this" is assignable from "klazz", where both of these
779// are array classes.
780//
781// Consider an array class, e.g. Y[][], where Y is a subclass of X.
782// Y[][] = Y[][] --> true (identity)
783// X[][] = Y[][] --> true (element superclass)
784// Y = Y[][] --> false
785// Y[] = Y[][] --> false
786// Object = Y[][] --> true (everything is an object)
787// Object[] = Y[][] --> true
788// Object[][] = Y[][] --> true
789// Object[][][] = Y[][] --> false (too many []s)
790// Serializable = Y[][] --> true (all arrays are Serializable)
791// Serializable[] = Y[][] --> true
792// Serializable[][] = Y[][] --> false (unless Y is Serializable)
793//
794// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700795// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700796//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700797bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700798 DCHECK(IsArrayClass());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700799 DCHECK(src->IsArrayClass());
800 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700801}
802
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700803bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700804 DCHECK(!IsInterface()); // handled first in IsAssignableFrom
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700805 DCHECK(src->IsArrayClass());
Brian Carlstromb63ec392011-08-27 17:38:27 -0700806 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700807 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700808 // src's super should be java_lang_Object, since it is an array.
809 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700810 DCHECK(java_lang_Object != NULL);
811 DCHECK(java_lang_Object->GetSuperClass() == NULL);
812 return this == java_lang_Object;
813 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700814 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700815}
816
817bool Class::IsSubClass(const Class* klass) const {
818 DCHECK(!IsInterface());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700819 DCHECK(!IsArrayClass());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700820 const Class* current = this;
821 do {
822 if (current == klass) {
823 return true;
824 }
825 current = current->GetSuperClass();
826 } while (current != NULL);
827 return false;
828}
829
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700830bool Class::IsInSamePackage(const String* descriptor_string_1,
831 const String* descriptor_string_2) {
832 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
833 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
834
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700835 size_t i = 0;
836 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
837 ++i;
838 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700839 if (descriptor1.find('/', i) != StringPiece::npos ||
840 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700841 return false;
842 } else {
843 return true;
844 }
845}
846
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700847#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700848bool Class::IsInSamePackage(const StringPiece& descriptor1,
849 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700850 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700851 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700852 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
853 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700854 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
855}
856#endif
857
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700858bool Class::IsInSamePackage(const Class* that) const {
859 const Class* klass1 = this;
860 const Class* klass2 = that;
861 if (klass1 == klass2) {
862 return true;
863 }
864 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700865 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700866 return false;
867 }
868 // Arrays are in the same package when their element classes are.
Brian Carlstromb63ec392011-08-27 17:38:27 -0700869 if (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700870 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700871 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700872 if (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700873 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700874 }
875 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700876 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700877}
878
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700879const ClassLoader* Class::GetClassLoader() const {
880 return GetFieldObject<const ClassLoader*>(
881 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -0700882}
883
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700884void Class::SetClassLoader(const ClassLoader* new_cl) {
885 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
886 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
887 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700888}
889
Brian Carlstrom30b94452011-08-25 21:35:26 -0700890Method* Class::FindVirtualMethodForInterface(Method* method) {
891 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700892 DCHECK(declaring_class != NULL);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700893 DCHECK(declaring_class->IsInterface());
894 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700895 int32_t iftable_count = GetIfTableCount();
896 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
897 for (int32_t i = 0; i < iftable_count; i++) {
898 InterfaceEntry* interface_entry = iftable->Get(i);
899 if (interface_entry->GetInterface() == declaring_class) {
900 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -0700901 }
902 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700903 UNIMPLEMENTED(FATAL) << "Need to throw an error of some kind " << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700904 return NULL;
905}
906
jeffhaobdb76512011-09-07 11:43:16 -0700907Method* Class::FindInterfaceMethod(const StringPiece& name,
908 const StringPiece& signature) {
909 // Check the current class before checking the interfaces.
910 Method* method = FindVirtualMethod(name, signature);
911 if (method != NULL) {
912 return method;
913 }
914
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700915 int32_t iftable_count = GetIfTableCount();
916 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
917 for (int32_t i = 0; i < iftable_count; i++) {
918 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -0700919 if (method != NULL) {
920 return method;
921 }
922 }
923 return NULL;
924}
925
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700926Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700927 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700928 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -0700929 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700930 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700931 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700932 return method;
Ian Rogersb033c752011-07-20 12:22:35 -0700933 }
934 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700935 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -0700936}
937
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700938Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700939 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700940 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700941 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700942 if (method != NULL) {
943 return method;
944 }
945 }
946 return NULL;
947}
948
949Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700950 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700951 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -0700952 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700953 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700954 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700955 return method;
Ian Rogersb033c752011-07-20 12:22:35 -0700956 }
957 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700958 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -0700959}
960
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700961Method* Class::FindVirtualMethod(const StringPiece& name,
962 const StringPiece& descriptor) {
963 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
964 Method* method = klass->FindDeclaredVirtualMethod(name, descriptor);
965 if (method != NULL) {
966 return method;
967 }
968 }
969 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700970}
971
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700972Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -0700973 // Is the field in this class?
974 // Interfaces are not relevant because they can't contain instance fields.
975 for (size_t i = 0; i < NumInstanceFields(); ++i) {
976 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700977 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -0700978 return f;
979 }
980 }
981 return NULL;
982}
983
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700984Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -0700985 // Is the field in this class, or any of its superclasses?
986 // Interfaces are not relevant because they can't contain instance fields.
987 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700988 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -0700989 if (f != NULL) {
990 return f;
991 }
992 }
993 return NULL;
994}
995
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700996Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
997 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -0700998 for (size_t i = 0; i < NumStaticFields(); ++i) {
999 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001000 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001001 return f;
1002 }
1003 }
1004 return NULL;
1005}
1006
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001007Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001008 // Is the field in this class (or its interfaces), or any of its
1009 // superclasses (or their interfaces)?
1010 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1011 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001012 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001013 if (f != NULL) {
1014 return f;
1015 }
1016
1017 // Is this field in any of this class' interfaces?
1018 for (size_t i = 0; i < c->NumInterfaces(); ++i) {
1019 Class* interface = c->GetInterface(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001020 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001021 if (f != NULL) {
1022 return f;
1023 }
1024 }
1025 }
1026 return NULL;
1027}
1028
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001029Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001030 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001031 DCHECK_GE(component_count, 0);
1032 DCHECK(array_class->IsArrayClass());
1033 size_t size = SizeOf(component_count, component_size);
1034 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1035 if (array != NULL) {
1036 DCHECK(array->IsArrayInstance());
1037 array->SetLength(component_count);
1038 }
1039 return array;
1040}
1041
1042Array* Array::Alloc(Class* array_class, int32_t component_count) {
1043 return Alloc(array_class, component_count, array_class->GetComponentSize());
1044}
1045
1046Array* Array::AllocFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
1047 // TODO: throw on negative component_count
1048 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
1049 if (klass == NULL) {
1050 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
1051 if (klass == NULL || !klass->IsArrayClass()) {
1052 UNIMPLEMENTED(FATAL) << "throw an error";
1053 return NULL;
1054 }
1055 }
1056 return Array::Alloc(klass, component_count);
1057}
1058
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001059template<typename T>
1060PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001061 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001062 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1063 return down_cast<PrimitiveArray<T>*>(raw_array);
1064}
1065
1066template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1067
1068// Explicitly instantiate all the primitive array types.
1069template class PrimitiveArray<uint8_t>; // BooleanArray
1070template class PrimitiveArray<int8_t>; // ByteArray
1071template class PrimitiveArray<uint16_t>; // CharArray
1072template class PrimitiveArray<double>; // DoubleArray
1073template class PrimitiveArray<float>; // FloatArray
1074template class PrimitiveArray<int32_t>; // IntArray
1075template class PrimitiveArray<int64_t>; // LongArray
1076template class PrimitiveArray<int16_t>; // ShortArray
1077
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001078// TODO: get global references for these
1079Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001080
Brian Carlstroma663ea52011-08-19 23:33:41 -07001081void String::SetClass(Class* java_lang_String) {
1082 CHECK(java_lang_String_ == NULL);
1083 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001084 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001085}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001086
Brian Carlstroma663ea52011-08-19 23:33:41 -07001087void String::ResetClass() {
1088 CHECK(java_lang_String_ != NULL);
1089 java_lang_String_ = NULL;
1090}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001091
Brian Carlstromc74255f2011-09-11 22:47:39 -07001092String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001093 return Runtime::Current()->GetInternTable()->InternWeak(this);
1094}
1095
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001096int32_t String::GetHashCode() const {
1097 int32_t result = GetField32(
1098 OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1099 DCHECK(result != 0 ||
1100 ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0);
1101 return result;
1102}
1103
1104int32_t String::GetLength() const {
1105 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1106 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1107 return result;
1108}
1109
1110uint16_t String::CharAt(int32_t index) const {
1111 // TODO: do we need this? Equals is the only caller, and could
1112 // bounds check itself.
1113 if (index < 0 || index >= count_) {
1114 Thread* self = Thread::Current();
1115 self->ThrowNewException("Ljava/lang/StringIndexOutOfBoundsException;",
1116 "length=%i; index=%i", count_, index);
1117 return 0;
1118 }
1119 return GetCharArray()->Get(index + GetOffset());
1120}
1121
1122String* String::AllocFromUtf16(int32_t utf16_length,
1123 const uint16_t* utf16_data_in,
1124 int32_t hash_code) {
1125 String* string = Alloc(GetJavaLangString(), utf16_length);
1126 // TODO: use 16-bit wide memset variant
1127 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1128 for (int i = 0; i < utf16_length; i++) {
1129 array->Set(i, utf16_data_in[i]);
1130 }
1131 if (hash_code != 0) {
1132 string->SetHashCode(hash_code);
1133 } else {
1134 string->ComputeHashCode();
1135 }
1136 return string;
1137}
1138
1139String* String::AllocFromModifiedUtf8(const char* utf) {
1140 size_t char_count = CountModifiedUtf8Chars(utf);
1141 return AllocFromModifiedUtf8(char_count, utf);
1142}
1143
1144String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1145 const char* utf8_data_in) {
1146 String* string = Alloc(GetJavaLangString(), utf16_length);
1147 uint16_t* utf16_data_out =
1148 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1149 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1150 string->ComputeHashCode();
1151 return string;
1152}
1153
1154String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1155 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1156}
1157
1158String* String::Alloc(Class* java_lang_String, CharArray* array) {
1159 String* string = down_cast<String*>(java_lang_String->AllocObject());
1160 string->SetArray(array);
1161 string->SetCount(array->GetLength());
1162 return string;
1163}
1164
1165bool String::Equals(const String* that) const {
1166 if (this == that) {
1167 // Quick reference equality test
1168 return true;
1169 } else if (that == NULL) {
1170 // Null isn't an instanceof anything
1171 return false;
1172 } else if (this->GetLength() != that->GetLength()) {
1173 // Quick length inequality test
1174 return false;
1175 } else {
1176 // NB don't short circuit on hash code as we're presumably here as the
1177 // hash code was already equal
1178 for (int32_t i = 0; i < that->GetLength(); ++i) {
1179 if (this->CharAt(i) != that->CharAt(i)) {
1180 return false;
1181 }
1182 }
1183 return true;
1184 }
1185}
1186
1187bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1188 int32_t that_length) const {
1189 if (this->GetLength() != that_length) {
1190 return false;
1191 } else {
1192 for (int32_t i = 0; i < that_length; ++i) {
1193 if (this->CharAt(i) != that_chars[that_offset + i]) {
1194 return false;
1195 }
1196 }
1197 return true;
1198 }
1199}
1200
1201bool String::Equals(const char* modified_utf8) const {
1202 for (int32_t i = 0; i < GetLength(); ++i) {
1203 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1204 if (ch == '\0' || ch != CharAt(i)) {
1205 return false;
1206 }
1207 }
1208 return *modified_utf8 == '\0';
1209}
1210
1211bool String::Equals(const StringPiece& modified_utf8) const {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001212 // TODO: do not assume C-string representation. For now DCHECK.
1213 DCHECK_EQ(modified_utf8.data()[modified_utf8.size()], 0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001214 return Equals(modified_utf8.data());
1215}
1216
1217// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1218std::string String::ToModifiedUtf8() const {
1219 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1220 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1221 std::string result(byte_count, char(0));
1222 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1223 return result;
1224}
1225
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001226Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1227
1228void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1229 CHECK(java_lang_StackTraceElement_ == NULL);
1230 CHECK(java_lang_StackTraceElement != NULL);
1231 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1232}
1233
1234void StackTraceElement::ResetClass() {
1235 CHECK(java_lang_StackTraceElement_ != NULL);
1236 java_lang_StackTraceElement_ = NULL;
1237}
1238
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001239StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1240 const String* method_name,
1241 const String* file_name,
1242 int32_t line_number) {
1243 StackTraceElement* trace =
1244 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1245 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1246 const_cast<String*>(declaring_class), false);
1247 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1248 const_cast<String*>(method_name), false);
1249 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1250 const_cast<String*>(file_name), false);
1251 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1252 line_number, false);
1253 return trace;
1254}
1255
Elliott Hughes1f359b02011-07-17 14:27:17 -07001256static const char* kClassStatusNames[] = {
1257 "Error",
1258 "NotReady",
1259 "Idx",
1260 "Loaded",
1261 "Resolved",
1262 "Verifying",
1263 "Verified",
1264 "Initializing",
1265 "Initialized"
1266};
1267std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1268 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001269 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001270 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001271 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001272 }
1273 return os;
1274}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001275
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001276} // namespace art