blob: 29eac7736e9b0aa99ce150906c53dd362659e684 [file] [log] [blame]
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "object.h"
4
Ian Rogersb033c752011-07-20 12:22:35 -07005#include <string.h>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006
Ian Rogersdf20fe02011-07-20 20:34:16 -07007#include <algorithm>
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07008#include <iostream>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009#include <string>
10#include <utility>
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070011
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070012#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070013#include "class_loader.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070014#include "dex_cache.h"
15#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070016#include "globals.h"
Brian Carlstroma40f9bc2011-07-26 21:26:07 -070017#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070018#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070019#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070020#include "monitor.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070021#include "runtime.h"
Carl Shapiro3ee755d2011-06-28 12:11:04 -070022
23namespace art {
24
Elliott Hughes081be7f2011-09-18 16:50:26 -070025Object* Object::Clone() {
26 Class* c = GetClass();
27 DCHECK(!c->IsClassClass());
28
29 // Object::SizeOf gets the right size even if we're an array.
30 // Using c->AllocObject() here would be wrong.
31 size_t num_bytes = SizeOf();
32 Object* copy = Heap::AllocObject(c, num_bytes);
33 if (copy == NULL) {
34 return NULL;
35 }
36
37 // Copy instance data. We assume memcpy copies by words.
38 // TODO: expose and use move32.
39 byte* src_bytes = reinterpret_cast<byte*>(this);
40 byte* dst_bytes = reinterpret_cast<byte*>(copy);
41 size_t offset = sizeof(Object);
42 memcpy(dst_bytes + offset, src_bytes + offset, num_bytes - offset);
43
44 // TODO: Mark the clone as finalizable if appropriate.
45// if (IS_CLASS_FLAG_SET(clazz, CLASS_ISFINALIZABLE)) {
46// dvmSetFinalizable(copy);
47// }
48
49 return copy;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070050}
51
Elliott Hughes5f791332011-09-15 17:45:30 -070052uint32_t Object::GetLockOwner() {
53 return Monitor::GetLockOwner(monitor_);
54}
55
Elliott Hughes081be7f2011-09-18 16:50:26 -070056bool Object::IsString() const {
57 // TODO use "klass_ == String::GetJavaLangString()" instead?
58 return GetClass() == GetClass()->GetDescriptor()->GetClass();
59}
60
Elliott Hughes5f791332011-09-15 17:45:30 -070061void Object::MonitorEnter(Thread* thread) {
62 Monitor::MonitorEnter(thread, this);
63}
64
Ian Rogersff1ed472011-09-20 13:46:24 -070065bool Object::MonitorExit(Thread* thread) {
66 return Monitor::MonitorExit(thread, this);
Elliott Hughes5f791332011-09-15 17:45:30 -070067}
68
69void Object::Notify() {
70 Monitor::Notify(Thread::Current(), this);
71}
72
73void Object::NotifyAll() {
74 Monitor::NotifyAll(Thread::Current(), this);
75}
76
77void Object::Wait(int64_t ms, int32_t ns) {
78 Monitor::Wait(Thread::Current(), this, ms, ns, true);
79}
80
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070081// TODO: get global references for these
82Class* Field::java_lang_reflect_Field_ = NULL;
83
84void Field::SetClass(Class* java_lang_reflect_Field) {
85 CHECK(java_lang_reflect_Field_ == NULL);
86 CHECK(java_lang_reflect_Field != NULL);
87 java_lang_reflect_Field_ = java_lang_reflect_Field;
88}
89
90void Field::ResetClass() {
91 CHECK(java_lang_reflect_Field_ != NULL);
92 java_lang_reflect_Field_ = NULL;
93}
94
95void Field::SetTypeIdx(uint32_t type_idx) {
96 SetField32(OFFSET_OF_OBJECT_MEMBER(Field, type_idx_), type_idx, false);
97}
98
99Class* Field::GetTypeDuringLinking() const {
100 // We are assured that the necessary primitive types are in the dex cache
101 // early during class linking
102 return GetDeclaringClass()->GetDexCache()->GetResolvedType(GetTypeIdx());
103}
104
105Class* Field::GetType() const {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700106 // Do full linkage (which sets dex cache value to speed next call)
107 return Runtime::Current()->GetClassLinker()->ResolveType(GetTypeIdx(), this);
108}
109
Brian Carlstrom845490b2011-09-19 15:56:53 -0700110Field* Field::FindInstanceFieldFromCode(uint32_t field_idx, const Method* referrer) {
111 return FindFieldFromCode(field_idx, referrer, false);
112}
113
114Field* Field::FindStaticFieldFromCode(uint32_t field_idx, const Method* referrer) {
115 return FindFieldFromCode(field_idx, referrer, true);
116}
117
118Field* Field::FindFieldFromCode(uint32_t field_idx, const Method* referrer, bool is_static) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700119 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom845490b2011-09-19 15:56:53 -0700120 Field* f = class_linker->ResolveField(field_idx, referrer, is_static);
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700121 if (f != NULL) {
122 Class* c = f->GetDeclaringClass();
123 // If the class is already initializing, we must be inside <clinit>, or
124 // we'd still be waiting for the lock.
Brian Carlstrom25c33252011-09-18 15:58:35 -0700125 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c, true)) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700126 return f;
127 }
Brian Carlstromb63ec392011-08-27 17:38:27 -0700128 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700129 UNIMPLEMENTED(FATAL) << "throw an error and unwind";
130 return NULL;
131}
132
133uint32_t Field::Get32StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700134 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700135 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
136 return field->Get32(NULL);
137}
138void Field::Set32StaticFromCode(uint32_t field_idx, const Method* referrer, uint32_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700139 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700140 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int32_t));
141 field->Set32(NULL, new_value);
142}
143uint64_t Field::Get64StaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700144 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700145 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
146 return field->Get64(NULL);
147}
148void Field::Set64StaticFromCode(uint32_t field_idx, const Method* referrer, uint64_t new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700149 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700150 DCHECK(field->GetType()->PrimitiveSize() == sizeof(int64_t));
151 field->Set64(NULL, new_value);
152}
153Object* Field::GetObjStaticFromCode(uint32_t field_idx, const Method* referrer) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700154 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700155 DCHECK(!field->GetType()->IsPrimitive());
156 return field->GetObj(NULL);
157}
158void Field::SetObjStaticFromCode(uint32_t field_idx, const Method* referrer, Object* new_value) {
Brian Carlstrom845490b2011-09-19 15:56:53 -0700159 Field* field = FindStaticFieldFromCode(field_idx, referrer);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700160 DCHECK(!field->GetType()->IsPrimitive());
161 field->SetObj(NULL, new_value);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700162}
163
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700164uint32_t Field::Get32(const Object* object) const {
165 CHECK((object == NULL) == IsStatic());
166 if (IsStatic()) {
167 object = declaring_class_;
168 }
169 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700170}
171
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700172void Field::Set32(Object* object, uint32_t new_value) const {
173 CHECK((object == NULL) == IsStatic());
174 if (IsStatic()) {
175 object = declaring_class_;
176 }
177 object->SetField32(GetOffset(), new_value, IsVolatile());
178}
179
180uint64_t Field::Get64(const Object* object) const {
181 CHECK((object == NULL) == IsStatic());
182 if (IsStatic()) {
183 object = declaring_class_;
184 }
185 return object->GetField64(GetOffset(), IsVolatile());
186}
187
188void Field::Set64(Object* object, uint64_t new_value) const {
189 CHECK((object == NULL) == IsStatic());
190 if (IsStatic()) {
191 object = declaring_class_;
192 }
193 object->SetField64(GetOffset(), new_value, IsVolatile());
194}
195
196Object* Field::GetObj(const Object* object) const {
197 CHECK((object == NULL) == IsStatic());
198 if (IsStatic()) {
199 object = declaring_class_;
200 }
201 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
202}
203
204void Field::SetObj(Object* object, const Object* new_value) const {
205 CHECK((object == NULL) == IsStatic());
206 if (IsStatic()) {
207 object = declaring_class_;
208 }
209 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
210}
211
212bool Field::GetBoolean(const Object* object) const {
213 DCHECK(GetType()->IsPrimitiveBoolean());
214 return Get32(object);
215}
216
217void Field::SetBoolean(Object* object, bool z) const {
218 DCHECK(GetType()->IsPrimitiveBoolean());
219 Set32(object, z);
220}
221
222int8_t Field::GetByte(const Object* object) const {
223 DCHECK(GetType()->IsPrimitiveByte());
224 return Get32(object);
225}
226
227void Field::SetByte(Object* object, int8_t b) const {
228 DCHECK(GetType()->IsPrimitiveByte());
229 Set32(object, b);
230}
231
232uint16_t Field::GetChar(const Object* object) const {
233 DCHECK(GetType()->IsPrimitiveChar());
234 return Get32(object);
235}
236
237void Field::SetChar(Object* object, uint16_t c) const {
238 DCHECK(GetType()->IsPrimitiveChar());
239 Set32(object, c);
240}
241
242uint16_t Field::GetShort(const Object* object) const {
243 DCHECK(GetType()->IsPrimitiveShort());
244 return Get32(object);
245}
246
247void Field::SetShort(Object* object, uint16_t s) const {
248 DCHECK(GetType()->IsPrimitiveShort());
249 Set32(object, s);
250}
251
252int32_t Field::GetInt(const Object* object) const {
253 DCHECK(GetType()->IsPrimitiveInt());
254 return Get32(object);
255}
256
257void Field::SetInt(Object* object, int32_t i) const {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700258 DCHECK(GetType()->IsPrimitiveInt()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700259 Set32(object, i);
260}
261
262int64_t Field::GetLong(const Object* object) const {
263 DCHECK(GetType()->IsPrimitiveLong());
264 return Get64(object);
265}
266
267void Field::SetLong(Object* object, int64_t j) const {
268 DCHECK(GetType()->IsPrimitiveLong());
269 Set64(object, j);
270}
271
272float Field::GetFloat(const Object* object) const {
273 DCHECK(GetType()->IsPrimitiveFloat());
274 JValue float_bits;
275 float_bits.i = Get32(object);
276 return float_bits.f;
277}
278
279void Field::SetFloat(Object* object, float f) const {
280 DCHECK(GetType()->IsPrimitiveFloat());
281 JValue float_bits;
282 float_bits.f = f;
283 Set32(object, float_bits.i);
284}
285
286double Field::GetDouble(const Object* object) const {
287 DCHECK(GetType()->IsPrimitiveDouble());
288 JValue double_bits;
289 double_bits.j = Get64(object);
290 return double_bits.d;
291}
292
293void Field::SetDouble(Object* object, double d) const {
294 DCHECK(GetType()->IsPrimitiveDouble());
295 JValue double_bits;
296 double_bits.d = d;
297 Set64(object, double_bits.j);
298}
299
300Object* Field::GetObject(const Object* object) const {
301 CHECK(!GetType()->IsPrimitive());
302 return GetObj(object);
303}
304
305void Field::SetObject(Object* object, const Object* l) const {
306 CHECK(!GetType()->IsPrimitive());
307 SetObj(object, l);
308}
309
310// TODO: get global references for these
311Class* Method::java_lang_reflect_Method_ = NULL;
312
313void Method::SetClass(Class* java_lang_reflect_Method) {
314 CHECK(java_lang_reflect_Method_ == NULL);
315 CHECK(java_lang_reflect_Method != NULL);
316 java_lang_reflect_Method_ = java_lang_reflect_Method;
317}
318
319void Method::ResetClass() {
320 CHECK(java_lang_reflect_Method_ != NULL);
321 java_lang_reflect_Method_ = NULL;
322}
323
Elliott Hughes418d20f2011-09-22 14:00:39 -0700324Class* ExtractNextClassFromSignature(ClassLinker* class_linker, const ClassLoader* cl, const char*& p) {
325 if (*p == '[') {
326 // Something like "[[[Ljava/lang/String;".
327 const char* start = p;
328 while (*p == '[') {
329 ++p;
330 }
331 if (*p == 'L') {
332 while (*p != ';') {
333 ++p;
334 }
335 }
336 ++p; // Either the ';' or the primitive type.
337
338 StringPiece descriptor(start, (p - start));
339 return class_linker->FindClass(descriptor, cl);
340 } else if (*p == 'L') {
341 const char* start = p;
342 while (*p != ';') {
343 ++p;
344 }
345 ++p;
346 StringPiece descriptor(start, (p - start));
347 return class_linker->FindClass(descriptor, cl);
348 } else {
349 return class_linker->FindPrimitiveClass(*p++);
350 }
351}
352
353void Method::InitJavaFieldsLocked() {
354 // Create the array.
355 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
356 size_t arg_count = GetShorty()->GetLength() - 1;
357 Class* array_class = class_linker->FindSystemClass("[Ljava/lang/Class;");
358 ObjectArray<Class>* parameters = ObjectArray<Class>::Alloc(array_class, arg_count);
359 if (parameters == NULL) {
360 return;
361 }
362
363 // Parse the signature, filling the array.
364 const ClassLoader* cl = GetDeclaringClass()->GetClassLoader();
365 std::string signature(GetSignature()->ToModifiedUtf8());
366 const char* p = signature.c_str();
367 DCHECK_EQ(*p, '(');
368 ++p;
369 for (size_t i = 0; i < arg_count; ++i) {
370 Class* c = ExtractNextClassFromSignature(class_linker, cl, p);
371 if (c == NULL) {
372 return;
373 }
374 parameters->Set(i, c);
375 }
376
377 DCHECK_EQ(*p, ')');
378 ++p;
379
380 java_parameter_types_ = parameters;
381 java_return_type_ = ExtractNextClassFromSignature(class_linker, cl, p);
382}
383
384void Method::InitJavaFields() {
385 Thread* self = Thread::Current();
386 ScopedThreadStateChange tsc(self, Thread::kRunnable);
387 MonitorEnter(self);
388 if (java_parameter_types_ == NULL || java_return_type_ == NULL) {
389 InitJavaFieldsLocked();
390 }
391 MonitorExit(self);
392}
393
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700394ObjectArray<String>* Method::GetDexCacheStrings() const {
395 return GetFieldObject<ObjectArray<String>*>(
396 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
397}
398
399void Method::SetReturnTypeIdx(uint32_t new_return_type_idx) {
400 SetField32(OFFSET_OF_OBJECT_MEMBER(Method, java_return_type_idx_),
401 new_return_type_idx, false);
402}
403
404Class* Method::GetReturnType() const {
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700405 DCHECK(GetDeclaringClass()->IsResolved() || GetDeclaringClass()->IsErroneous());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406 // Short-cut
407 Class* result = GetDexCacheResolvedTypes()->Get(GetReturnTypeIdx());
408 if (result == NULL) {
409 // Do full linkage and set cache value for next call
410 result = Runtime::Current()->GetClassLinker()->ResolveType(GetReturnTypeIdx(), this);
411 }
412 CHECK(result != NULL);
413 return result;
414}
415
416void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
417 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
418 new_dex_cache_strings, false);
419}
420
421ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
422 return GetFieldObject<ObjectArray<Class>*>(
423 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
424}
425
426void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
427 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
428 new_dex_cache_classes, false);
429}
430
431ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
432 return GetFieldObject<ObjectArray<Method>*>(
433 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
434}
435
436void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
437 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
438 new_dex_cache_methods, false);
439}
440
441ObjectArray<Field>* Method::GetDexCacheResolvedFields() const {
442 return GetFieldObject<ObjectArray<Field>*>(
443 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_), false);
444}
445
446void Method::SetDexCacheResolvedFields(ObjectArray<Field>* new_dex_cache_fields) {
447 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_fields_),
448 new_dex_cache_fields, false);
449}
450
451CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
452 return GetFieldPtr<CodeAndDirectMethods*>(
453 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
454 false);
455}
456
457void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
458 SetFieldPtr<CodeAndDirectMethods*>(
459 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
460 new_value, false);
461}
462
463ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
464 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
465 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
466 false);
467}
468
469void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
470 SetFieldObject(
471 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
472 new_value, false);
473
474}
475
476size_t Method::NumArgRegisters(const StringPiece& shorty) {
477 CHECK_LE(1, shorty.length());
478 uint32_t num_registers = 0;
479 for (int i = 1; i < shorty.length(); ++i) {
480 char ch = shorty[i];
481 if (ch == 'D' || ch == 'J') {
482 num_registers += 2;
483 } else {
484 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700485 }
486 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487 return num_registers;
488}
489
490size_t Method::NumArgArrayBytes() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700491 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492 size_t num_bytes = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700493 for (int i = 1; i < shorty->GetLength(); ++i) {
494 char ch = shorty->CharAt(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700495 if (ch == 'D' || ch == 'J') {
496 num_bytes += 8;
497 } else if (ch == 'L') {
498 // Argument is a reference or an array. The shorty descriptor
499 // does not distinguish between these types.
500 num_bytes += sizeof(Object*);
501 } else {
502 num_bytes += 4;
503 }
504 }
505 return num_bytes;
506}
507
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700508size_t Method::NumArgs() const {
509 // "1 +" because the first in Args is the receiver.
510 // "- 1" because we don't count the return type.
511 return (IsStatic() ? 0 : 1) + GetShorty()->GetLength() - 1;
512}
513
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514// The number of reference arguments to this method including implicit this
515// pointer
516size_t Method::NumReferenceArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700517 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518 size_t result = IsStatic() ? 0 : 1; // The implicit this pointer.
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700519 for (int i = 1; i < shorty->GetLength(); i++) {
520 char ch = shorty->CharAt(i);
521 if ((ch == 'L') || (ch == '[')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700522 result++;
523 }
524 }
525 return result;
526}
527
528// The number of long or double arguments
529size_t Method::NumLongOrDoubleArgs() const {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700530 const String* shorty = GetShorty();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700531 size_t result = 0;
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700532 for (int i = 1; i < shorty->GetLength(); i++) {
533 char ch = shorty->CharAt(i);
534 if ((ch == 'D') || (ch == 'J')) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535 result++;
536 }
537 }
538 return result;
539}
540
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700541// Is the given method parameter a reference?
542bool Method::IsParamAReference(unsigned int param) const {
543 CHECK_LT(param, NumArgs());
544 if (IsStatic()) {
545 param++; // 0th argument must skip return value at start of the shorty
546 } else if (param == 0) {
547 return true; // this argument
548 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700549 return GetShorty()->CharAt(param) == 'L';
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550}
551
552// Is the given method parameter a long or double?
553bool Method::IsParamALongOrDouble(unsigned int param) const {
554 CHECK_LT(param, NumArgs());
555 if (IsStatic()) {
556 param++; // 0th argument must skip return value at start of the shorty
557 } else if (param == 0) {
558 return false; // this argument
559 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700560 char ch = GetShorty()->CharAt(param);
561 return (ch == 'J' || ch == 'D');
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700562}
563
564static size_t ShortyCharToSize(char x) {
565 switch (x) {
566 case 'V': return 0;
567 case '[': return kPointerSize;
568 case 'L': return kPointerSize;
569 case 'D': return 8;
570 case 'J': return 8;
571 default: return 4;
572 }
573}
574
575size_t Method::ParamSize(unsigned int param) const {
576 CHECK_LT(param, NumArgs());
577 if (IsStatic()) {
578 param++; // 0th argument must skip return value at start of the shorty
579 } else if (param == 0) {
580 return kPointerSize; // this argument
581 }
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700582 return ShortyCharToSize(GetShorty()->CharAt(param));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700583}
584
585size_t Method::ReturnSize() const {
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700586 return ShortyCharToSize(GetShorty()->CharAt(0));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587}
588
589bool Method::HasSameNameAndDescriptor(const Method* that) const {
590 return (this->GetName()->Equals(that->GetName()) &&
591 this->GetSignature()->Equals(that->GetSignature()));
592}
593
Ian Rogersbdb03912011-09-14 00:55:44 -0700594uint32_t Method::ToDexPC(const uintptr_t pc) const {
595 IntArray* mapping_table = GetMappingTable();
596 if (mapping_table == NULL) {
Ian Rogers67375ac2011-09-14 00:55:44 -0700597 DCHECK(IsNative());
598 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700599 }
600 size_t mapping_table_length = mapping_table->GetLength();
601 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(GetCode());
602 CHECK_LT(sought_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
603 uint32_t best_offset = 0;
604 uint32_t best_dex_offset = 0;
605 for (size_t i = 0; i < mapping_table_length; i += 2) {
606 uint32_t map_offset = mapping_table->Get(i);
607 uint32_t map_dex_offset = mapping_table->Get(i + 1);
608 if (map_offset == sought_offset) {
609 best_offset = map_offset;
610 best_dex_offset = map_dex_offset;
611 break;
612 }
613 if (map_offset < sought_offset && map_offset > best_offset) {
614 best_offset = map_offset;
615 best_dex_offset = map_dex_offset;
616 }
617 }
618 return best_dex_offset;
619}
620
621uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
622 IntArray* mapping_table = GetMappingTable();
623 if (mapping_table == NULL) {
624 DCHECK(dex_pc == 0);
625 return 0; // Special no mapping/pc == 0 case
626 }
627 size_t mapping_table_length = mapping_table->GetLength();
628 for (size_t i = 0; i < mapping_table_length; i += 2) {
629 uint32_t map_offset = mapping_table->Get(i);
630 uint32_t map_dex_offset = mapping_table->Get(i + 1);
631 if (map_dex_offset == dex_pc) {
632 DCHECK_LT(map_offset, static_cast<uint32_t>(GetCodeArray()->GetLength()));
633 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
634 }
635 }
636 LOG(FATAL) << "Looking up Dex PC not contained in method";
637 return 0;
638}
639
640uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
641 DexCache* dex_cache = GetDeclaringClass()->GetDexCache();
642 const ClassLoader* class_loader = GetDeclaringClass()->GetClassLoader();
643 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
644 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
645 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(GetCodeItemOffset());
646 // Iterate over the catch handlers associated with dex_pc
647 for (DexFile::CatchHandlerIterator iter = dex_file.dexFindCatchHandler(*code_item, dex_pc);
648 !iter.HasNext(); iter.Next()) {
649 uint32_t iter_type_idx = iter.Get().type_idx_;
650 // Catch all case
651 if(iter_type_idx == DexFile::kDexNoIndex) {
652 return iter.Get().address_;
653 }
654 // Does this catch exception type apply?
655 Class* iter_exception_type =
656 class_linker->ResolveType(dex_file, iter_type_idx, dex_cache, class_loader);
657 if (iter_exception_type->IsAssignableFrom(exception_type)) {
658 return iter.Get().address_;
659 }
660 }
661 // Handler not found
662 return DexFile::kDexNoIndex;
663}
664
buzbee4ef76522011-09-08 10:00:32 -0700665void Method::SetCode(ByteArray* code_array, InstructionSet instruction_set,
buzbeec41e5b52011-09-23 12:46:19 -0700666 IntArray* mapping_table, ShortArray* vmap_table) {
Elliott Hughes1240dad2011-09-09 16:24:50 -0700667 CHECK(GetCode() == NULL || IsNative());
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700668 SetFieldPtr<ByteArray*>(OFFSET_OF_OBJECT_MEMBER(Method, code_array_), code_array, false);
Ian Rogersbdb03912011-09-14 00:55:44 -0700669 SetFieldPtr<IntArray*>(OFFSET_OF_OBJECT_MEMBER(Method, mapping_table_),
buzbee4ef76522011-09-08 10:00:32 -0700670 mapping_table, false);
buzbeec41e5b52011-09-23 12:46:19 -0700671 SetFieldPtr<ShortArray*>(OFFSET_OF_OBJECT_MEMBER(Method, vmap_table_),
672 vmap_table, false);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700673 int8_t* code = code_array->GetData();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700674 uintptr_t address = reinterpret_cast<uintptr_t>(code);
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700675 if (instruction_set == kThumb2) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700676 // Set the low-order bit so a BLX will switch to Thumb mode
677 address |= 0x1;
678 }
Ian Rogersff1ed472011-09-20 13:46:24 -0700679 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, code_),
680 reinterpret_cast<const void*>(address), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700681}
682
Ian Rogersbdb03912011-09-14 00:55:44 -0700683bool Method::IsWithinCode(uintptr_t pc) const {
Ian Rogersbdb03912011-09-14 00:55:44 -0700684 if (pc == 0) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700685 // PC of 0 represents the beginning of a stack trace either a native or where we have a callee
686 // save method that has no code
687 DCHECK(IsNative() || IsPhony());
Ian Rogersbdb03912011-09-14 00:55:44 -0700688 return true;
689 } else {
Ian Rogers93dd9662011-09-17 23:21:22 -0700690#if defined(__arm__)
691 pc &= ~0x1; // clear any possible thumb instruction mode bit
692#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700693 uint32_t rel_offset = pc - reinterpret_cast<uintptr_t>(GetCodeArray()->GetData());
Ian Rogers93dd9662011-09-17 23:21:22 -0700694 // Strictly the following test should be a less-than, however, if the last
695 // instruction is a call to an exception throw we may see return addresses
696 // that are 1 beyond the end of code.
697 return rel_offset <= static_cast<uint32_t>(GetCodeArray()->GetLength());
Ian Rogersbdb03912011-09-14 00:55:44 -0700698 }
699}
700
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700701void Method::SetInvokeStub(const ByteArray* invoke_stub_array) {
702 const InvokeStub* invoke_stub = reinterpret_cast<InvokeStub*>(invoke_stub_array->GetData());
703 SetFieldPtr<const ByteArray*>(
704 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_array_), invoke_stub_array, false);
705 SetFieldPtr<const InvokeStub*>(
706 OFFSET_OF_OBJECT_MEMBER(Method, invoke_stub_), invoke_stub, false);
707}
708
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700709void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
710 // Push a transition back into managed code onto the linked list in thread.
711 CHECK_EQ(Thread::kRunnable, self->GetState());
712 NativeToManagedRecord record;
713 self->PushNativeToManagedRecord(&record);
714
715 // Call the invoke stub associated with the method.
716 // Pass everything as arguments.
717 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700718
719 bool have_executable_code = (GetCode() != NULL);
720#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700721 // Currently we can only compile non-native methods for ARM.
722 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700723#endif
724
725 if (have_executable_code && stub != NULL) {
726 LOG(INFO) << "invoking " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700727 (*stub)(this, receiver, self, args, result);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700728 LOG(INFO) << "returned " << PrettyMethod(this) << " code=" << (void*) GetCode() << " stub=" << (void*) stub;
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700729 } else {
730 LOG(WARNING) << "Not invoking method with no associated code: " << PrettyMethod(this);
731 if (result != NULL) {
732 result->j = 0;
733 }
734 }
735
736 // Pop transition.
737 self->PopNativeToManagedRecord(record);
738}
739
Brian Carlstrom16192862011-09-12 17:50:06 -0700740bool Method::IsRegistered() {
741 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
742 void* jni_stub = Runtime::Current()->GetJniStubArray()->GetData();
743 return native_method != jni_stub;
744}
745
746void Method::RegisterNative(const void* native_method) {
747 CHECK(IsNative());
748 CHECK(native_method != NULL);
749 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
750 native_method, false);
751}
752
753void Method::UnregisterNative() {
754 CHECK(IsNative());
755 // restore stub to lookup native pointer via dlsym
756 RegisterNative(Runtime::Current()->GetJniStubArray()->GetData());
757}
758
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700759void Class::SetStatus(Status new_status) {
760 CHECK(new_status > GetStatus() || new_status == kStatusError ||
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700761 !Runtime::Current()->IsStarted()) << GetDescriptor()->ToModifiedUtf8();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700762 CHECK(sizeof(Status) == sizeof(uint32_t));
763 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_),
764 new_status, false);
765}
766
767DexCache* Class::GetDexCache() const {
768 return GetFieldObject<DexCache*>(
769 OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
770}
771
772void Class::SetDexCache(DexCache* new_dex_cache) {
773 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_),
774 new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700775}
776
Brian Carlstrom1f870082011-08-23 16:02:11 -0700777Object* Class::AllocObjectFromCode(uint32_t type_idx, Method* method) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700778 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700779 if (klass == NULL) {
780 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
781 if (klass == NULL) {
782 UNIMPLEMENTED(FATAL) << "throw an error";
783 return NULL;
784 }
785 }
Brian Carlstrom1f870082011-08-23 16:02:11 -0700786 return klass->AllocObject();
787}
788
789Object* Class::AllocObject() {
790 DCHECK(!IsAbstract());
791 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700792}
793
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700794void Class::DumpClass(std::ostream& os, int flags) {
795 if ((flags & kDumpClassFullDetail) == 0) {
796 os << PrettyClass(this);
797 if ((flags & kDumpClassClassLoader) != 0) {
798 os << ' ' << GetClassLoader();
799 }
800 if ((flags & kDumpClassInitialized) != 0) {
801 os << ' ' << GetStatus();
802 }
803 os << std::endl;
804 return;
805 }
806
807 Class* super = GetSuperClass();
808 os << "----- " << (IsInterface() ? "interface" : "class") << " "
809 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
810 os << " objectSize=" << SizeOf() << " "
811 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
812 os << StringPrintf(" access=0x%04x.%04x\n",
813 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
814 if (super != NULL) {
815 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
816 }
817 if (IsArrayClass()) {
818 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
819 }
820 if (NumInterfaces() > 0) {
821 os << " interfaces (" << NumInterfaces() << "):\n";
822 for (size_t i = 0; i < NumInterfaces(); ++i) {
823 Class* interface = GetInterface(i);
824 const ClassLoader* cl = interface->GetClassLoader();
825 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
826 }
827 }
828 os << " vtable (" << NumVirtualMethods() << " entries, "
829 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
830 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
831 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethod(i)).c_str());
832 }
833 os << " direct methods (" << NumDirectMethods() << " entries):\n";
834 for (size_t i = 0; i < NumDirectMethods(); ++i) {
835 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
836 }
837 if (NumStaticFields() > 0) {
838 os << " static fields (" << NumStaticFields() << " entries):\n";
839 for (size_t i = 0; i < NumStaticFields(); ++i) {
840 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
841 }
842 }
843 if (NumInstanceFields() > 0) {
844 os << " instance fields (" << NumInstanceFields() << " entries):\n";
845 for (size_t i = 0; i < NumInstanceFields(); ++i) {
846 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
847 }
848 }
849}
850
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700851void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
852 if (new_reference_offsets != CLASS_WALK_SUPER) {
853 // Sanity check that the number of bits set in the reference offset bitmap
854 // agrees with the number of references
855 Class* cur = this;
856 size_t cnt = 0;
857 while (cur) {
858 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
859 cur = cur->GetSuperClass();
860 }
861 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
862 }
863 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
864 new_reference_offsets, false);
865}
866
867void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
868 if (new_reference_offsets != CLASS_WALK_SUPER) {
869 // Sanity check that the number of bits set in the reference offset bitmap
870 // agrees with the number of references
871 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
872 NumReferenceStaticFieldsDuringLinking());
873 }
874 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
875 new_reference_offsets, false);
876}
877
878size_t Class::PrimitiveSize() const {
879 switch (GetPrimitiveType()) {
880 case kPrimBoolean:
881 case kPrimByte:
882 case kPrimChar:
883 case kPrimShort:
884 case kPrimInt:
885 case kPrimFloat:
886 return sizeof(int32_t);
887 case kPrimLong:
888 case kPrimDouble:
889 return sizeof(int64_t);
890 default:
891 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
892 return 0;
893 }
894}
895
896size_t Class::GetTypeSize(const String* descriptor) {
897 switch (descriptor->CharAt(0)) {
898 case 'B': return 1; // byte
899 case 'C': return 2; // char
900 case 'D': return 8; // double
901 case 'F': return 4; // float
902 case 'I': return 4; // int
903 case 'J': return 8; // long
904 case 'S': return 2; // short
905 case 'Z': return 1; // boolean
906 case 'L': return sizeof(Object*);
907 case '[': return sizeof(Array*);
908 default:
909 LOG(ERROR) << "Unknown type " << descriptor;
910 return 0;
911 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700912}
913
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700914bool Class::Implements(const Class* klass) const {
915 DCHECK(klass != NULL);
916 DCHECK(klass->IsInterface());
917 // All interfaces implemented directly and by our superclass, and
918 // recursively all super-interfaces of those interfaces, are listed
919 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700920 int32_t iftable_count = GetIfTableCount();
921 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
922 for (int32_t i = 0; i < iftable_count; i++) {
923 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700924 return true;
925 }
926 }
927 return false;
928}
929
930// Determine whether "this" is assignable from "klazz", where both of these
931// are array classes.
932//
933// Consider an array class, e.g. Y[][], where Y is a subclass of X.
934// Y[][] = Y[][] --> true (identity)
935// X[][] = Y[][] --> true (element superclass)
936// Y = Y[][] --> false
937// Y[] = Y[][] --> false
938// Object = Y[][] --> true (everything is an object)
939// Object[] = Y[][] --> true
940// Object[][] = Y[][] --> true
941// Object[][][] = Y[][] --> false (too many []s)
942// Serializable = Y[][] --> true (all arrays are Serializable)
943// Serializable[] = Y[][] --> true
944// Serializable[][] = Y[][] --> false (unless Y is Serializable)
945//
946// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700947// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700948//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700949bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700950 DCHECK(IsArrayClass());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700951 DCHECK(src->IsArrayClass());
952 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700953}
954
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700955bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700956 DCHECK(!IsInterface()); // handled first in IsAssignableFrom
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700957 DCHECK(src->IsArrayClass());
Brian Carlstromb63ec392011-08-27 17:38:27 -0700958 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700959 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700960 // src's super should be java_lang_Object, since it is an array.
961 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700962 DCHECK(java_lang_Object != NULL);
963 DCHECK(java_lang_Object->GetSuperClass() == NULL);
964 return this == java_lang_Object;
965 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700966 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700967}
968
969bool Class::IsSubClass(const Class* klass) const {
970 DCHECK(!IsInterface());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700971 DCHECK(!IsArrayClass());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700972 const Class* current = this;
973 do {
974 if (current == klass) {
975 return true;
976 }
977 current = current->GetSuperClass();
978 } while (current != NULL);
979 return false;
980}
981
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700982bool Class::IsInSamePackage(const String* descriptor_string_1,
983 const String* descriptor_string_2) {
984 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
985 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
986
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700987 size_t i = 0;
988 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
989 ++i;
990 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700991 if (descriptor1.find('/', i) != StringPiece::npos ||
992 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700993 return false;
994 } else {
995 return true;
996 }
997}
998
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700999#if 0
Ian Rogersb033c752011-07-20 12:22:35 -07001000bool Class::IsInSamePackage(const StringPiece& descriptor1,
1001 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001002 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001003 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -07001004 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
1005 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001006 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
1007}
1008#endif
1009
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001010bool Class::IsInSamePackage(const Class* that) const {
1011 const Class* klass1 = this;
1012 const Class* klass2 = that;
1013 if (klass1 == klass2) {
1014 return true;
1015 }
1016 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001017 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001018 return false;
1019 }
1020 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -07001021 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001022 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001023 }
jeffhao4a801a42011-09-23 13:53:40 -07001024 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001025 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001026 }
1027 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001028 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001029}
1030
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001031const ClassLoader* Class::GetClassLoader() const {
1032 return GetFieldObject<const ClassLoader*>(
1033 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -07001034}
1035
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001036void Class::SetClassLoader(const ClassLoader* new_cl) {
1037 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
1038 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
1039 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001040}
1041
Brian Carlstrom30b94452011-08-25 21:35:26 -07001042Method* Class::FindVirtualMethodForInterface(Method* method) {
1043 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001044 DCHECK(declaring_class != NULL);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001045 DCHECK(declaring_class->IsInterface());
1046 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001047 int32_t iftable_count = GetIfTableCount();
1048 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1049 for (int32_t i = 0; i < iftable_count; i++) {
1050 InterfaceEntry* interface_entry = iftable->Get(i);
1051 if (interface_entry->GetInterface() == declaring_class) {
1052 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -07001053 }
1054 }
Brian Carlstrom16192862011-09-12 17:50:06 -07001055 UNIMPLEMENTED(FATAL) << "Need to throw an error of some kind " << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001056 return NULL;
1057}
1058
jeffhaobdb76512011-09-07 11:43:16 -07001059Method* Class::FindInterfaceMethod(const StringPiece& name,
1060 const StringPiece& signature) {
1061 // Check the current class before checking the interfaces.
1062 Method* method = FindVirtualMethod(name, signature);
1063 if (method != NULL) {
1064 return method;
1065 }
1066
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001067 int32_t iftable_count = GetIfTableCount();
1068 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1069 for (int32_t i = 0; i < iftable_count; i++) {
1070 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001071 if (method != NULL) {
1072 return method;
1073 }
1074 }
1075 return NULL;
1076}
1077
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001078Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001079 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001080 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001081 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001082 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001083 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001084 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001085 }
1086 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001087 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001088}
1089
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001090Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001091 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001092 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001093 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001094 if (method != NULL) {
1095 return method;
1096 }
1097 }
1098 return NULL;
1099}
1100
1101Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001102 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001103 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001104 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001105 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001106 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001107 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001108 }
1109 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001110 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001111}
1112
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001113Method* Class::FindVirtualMethod(const StringPiece& name,
1114 const StringPiece& descriptor) {
1115 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1116 Method* method = klass->FindDeclaredVirtualMethod(name, descriptor);
1117 if (method != NULL) {
1118 return method;
1119 }
1120 }
1121 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001122}
1123
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001124Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001125 // Is the field in this class?
1126 // Interfaces are not relevant because they can't contain instance fields.
1127 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1128 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001129 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001130 return f;
1131 }
1132 }
1133 return NULL;
1134}
1135
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001136Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001137 // Is the field in this class, or any of its superclasses?
1138 // Interfaces are not relevant because they can't contain instance fields.
1139 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001140 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001141 if (f != NULL) {
1142 return f;
1143 }
1144 }
1145 return NULL;
1146}
1147
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001148Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
1149 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -07001150 for (size_t i = 0; i < NumStaticFields(); ++i) {
1151 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001152 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001153 return f;
1154 }
1155 }
1156 return NULL;
1157}
1158
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001159Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001160 // Is the field in this class (or its interfaces), or any of its
1161 // superclasses (or their interfaces)?
1162 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1163 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001164 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001165 if (f != NULL) {
1166 return f;
1167 }
1168
1169 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001170 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1171 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1172 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001173 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001174 if (f != NULL) {
1175 return f;
1176 }
1177 }
1178 }
1179 return NULL;
1180}
1181
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001182Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001183 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001184 DCHECK_GE(component_count, 0);
1185 DCHECK(array_class->IsArrayClass());
1186 size_t size = SizeOf(component_count, component_size);
1187 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1188 if (array != NULL) {
1189 DCHECK(array->IsArrayInstance());
1190 array->SetLength(component_count);
1191 }
1192 return array;
1193}
1194
1195Array* Array::Alloc(Class* array_class, int32_t component_count) {
1196 return Alloc(array_class, component_count, array_class->GetComponentSize());
1197}
1198
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001199template<typename T>
1200PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001201 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001202 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1203 return down_cast<PrimitiveArray<T>*>(raw_array);
1204}
1205
1206template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1207
1208// Explicitly instantiate all the primitive array types.
1209template class PrimitiveArray<uint8_t>; // BooleanArray
1210template class PrimitiveArray<int8_t>; // ByteArray
1211template class PrimitiveArray<uint16_t>; // CharArray
1212template class PrimitiveArray<double>; // DoubleArray
1213template class PrimitiveArray<float>; // FloatArray
1214template class PrimitiveArray<int32_t>; // IntArray
1215template class PrimitiveArray<int64_t>; // LongArray
1216template class PrimitiveArray<int16_t>; // ShortArray
1217
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001218// TODO: get global references for these
1219Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001220
Brian Carlstroma663ea52011-08-19 23:33:41 -07001221void String::SetClass(Class* java_lang_String) {
1222 CHECK(java_lang_String_ == NULL);
1223 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001224 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001225}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001226
Brian Carlstroma663ea52011-08-19 23:33:41 -07001227void String::ResetClass() {
1228 CHECK(java_lang_String_ != NULL);
1229 java_lang_String_ = NULL;
1230}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001231
Brian Carlstromc74255f2011-09-11 22:47:39 -07001232String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001233 return Runtime::Current()->GetInternTable()->InternWeak(this);
1234}
1235
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001236int32_t String::GetHashCode() const {
1237 int32_t result = GetField32(
1238 OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1239 DCHECK(result != 0 ||
1240 ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0);
1241 return result;
1242}
1243
1244int32_t String::GetLength() const {
1245 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1246 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1247 return result;
1248}
1249
1250uint16_t String::CharAt(int32_t index) const {
1251 // TODO: do we need this? Equals is the only caller, and could
1252 // bounds check itself.
1253 if (index < 0 || index >= count_) {
1254 Thread* self = Thread::Current();
1255 self->ThrowNewException("Ljava/lang/StringIndexOutOfBoundsException;",
1256 "length=%i; index=%i", count_, index);
1257 return 0;
1258 }
1259 return GetCharArray()->Get(index + GetOffset());
1260}
1261
1262String* String::AllocFromUtf16(int32_t utf16_length,
1263 const uint16_t* utf16_data_in,
1264 int32_t hash_code) {
1265 String* string = Alloc(GetJavaLangString(), utf16_length);
1266 // TODO: use 16-bit wide memset variant
1267 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1268 for (int i = 0; i < utf16_length; i++) {
1269 array->Set(i, utf16_data_in[i]);
1270 }
1271 if (hash_code != 0) {
1272 string->SetHashCode(hash_code);
1273 } else {
1274 string->ComputeHashCode();
1275 }
1276 return string;
1277}
1278
1279String* String::AllocFromModifiedUtf8(const char* utf) {
1280 size_t char_count = CountModifiedUtf8Chars(utf);
1281 return AllocFromModifiedUtf8(char_count, utf);
1282}
1283
1284String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1285 const char* utf8_data_in) {
1286 String* string = Alloc(GetJavaLangString(), utf16_length);
1287 uint16_t* utf16_data_out =
1288 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1289 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1290 string->ComputeHashCode();
1291 return string;
1292}
1293
1294String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1295 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1296}
1297
1298String* String::Alloc(Class* java_lang_String, CharArray* array) {
1299 String* string = down_cast<String*>(java_lang_String->AllocObject());
1300 string->SetArray(array);
1301 string->SetCount(array->GetLength());
1302 return string;
1303}
1304
1305bool String::Equals(const String* that) const {
1306 if (this == that) {
1307 // Quick reference equality test
1308 return true;
1309 } else if (that == NULL) {
1310 // Null isn't an instanceof anything
1311 return false;
1312 } else if (this->GetLength() != that->GetLength()) {
1313 // Quick length inequality test
1314 return false;
1315 } else {
1316 // NB don't short circuit on hash code as we're presumably here as the
1317 // hash code was already equal
1318 for (int32_t i = 0; i < that->GetLength(); ++i) {
1319 if (this->CharAt(i) != that->CharAt(i)) {
1320 return false;
1321 }
1322 }
1323 return true;
1324 }
1325}
1326
1327bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1328 int32_t that_length) const {
1329 if (this->GetLength() != that_length) {
1330 return false;
1331 } else {
1332 for (int32_t i = 0; i < that_length; ++i) {
1333 if (this->CharAt(i) != that_chars[that_offset + i]) {
1334 return false;
1335 }
1336 }
1337 return true;
1338 }
1339}
1340
1341bool String::Equals(const char* modified_utf8) const {
1342 for (int32_t i = 0; i < GetLength(); ++i) {
1343 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1344 if (ch == '\0' || ch != CharAt(i)) {
1345 return false;
1346 }
1347 }
1348 return *modified_utf8 == '\0';
1349}
1350
1351bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001352 if (modified_utf8.size() != GetLength()) {
1353 return false;
1354 }
1355 const char* p = modified_utf8.data();
1356 for (int32_t i = 0; i < GetLength(); ++i) {
1357 uint16_t ch = GetUtf16FromUtf8(&p);
1358 if (ch != CharAt(i)) {
1359 return false;
1360 }
1361 }
1362 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001363}
1364
1365// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1366std::string String::ToModifiedUtf8() const {
1367 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1368 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1369 std::string result(byte_count, char(0));
1370 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1371 return result;
1372}
1373
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001374Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1375
1376void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1377 CHECK(java_lang_StackTraceElement_ == NULL);
1378 CHECK(java_lang_StackTraceElement != NULL);
1379 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1380}
1381
1382void StackTraceElement::ResetClass() {
1383 CHECK(java_lang_StackTraceElement_ != NULL);
1384 java_lang_StackTraceElement_ = NULL;
1385}
1386
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001387StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1388 const String* method_name,
1389 const String* file_name,
1390 int32_t line_number) {
1391 StackTraceElement* trace =
1392 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1393 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1394 const_cast<String*>(declaring_class), false);
1395 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1396 const_cast<String*>(method_name), false);
1397 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1398 const_cast<String*>(file_name), false);
1399 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1400 line_number, false);
1401 return trace;
1402}
1403
Elliott Hughes1f359b02011-07-17 14:27:17 -07001404static const char* kClassStatusNames[] = {
1405 "Error",
1406 "NotReady",
1407 "Idx",
1408 "Loaded",
1409 "Resolved",
1410 "Verifying",
1411 "Verified",
1412 "Initializing",
1413 "Initialized"
1414};
1415std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1416 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001417 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001418 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001419 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001420 }
1421 return os;
1422}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001423
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001424} // namespace art