blob: 7b47d9f80f2a1bb98063000423fd41b82deae794 [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::AllocObject() {
778 DCHECK(!IsAbstract());
Ian Rogers21d9e832011-09-23 17:05:09 -0700779 DCHECK(!IsInterface());
780 DCHECK(!IsPrimitive());
Brian Carlstrom1f870082011-08-23 16:02:11 -0700781 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700782}
783
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700784void Class::DumpClass(std::ostream& os, int flags) {
785 if ((flags & kDumpClassFullDetail) == 0) {
786 os << PrettyClass(this);
787 if ((flags & kDumpClassClassLoader) != 0) {
788 os << ' ' << GetClassLoader();
789 }
790 if ((flags & kDumpClassInitialized) != 0) {
791 os << ' ' << GetStatus();
792 }
793 os << std::endl;
794 return;
795 }
796
797 Class* super = GetSuperClass();
798 os << "----- " << (IsInterface() ? "interface" : "class") << " "
799 << "'" << GetDescriptor()->ToModifiedUtf8() << "' cl=" << GetClassLoader() << " -----\n",
800 os << " objectSize=" << SizeOf() << " "
801 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
802 os << StringPrintf(" access=0x%04x.%04x\n",
803 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
804 if (super != NULL) {
805 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
806 }
807 if (IsArrayClass()) {
808 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
809 }
810 if (NumInterfaces() > 0) {
811 os << " interfaces (" << NumInterfaces() << "):\n";
812 for (size_t i = 0; i < NumInterfaces(); ++i) {
813 Class* interface = GetInterface(i);
814 const ClassLoader* cl = interface->GetClassLoader();
815 os << StringPrintf(" %2d: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
816 }
817 }
818 os << " vtable (" << NumVirtualMethods() << " entries, "
819 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
820 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
821 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetVirtualMethod(i)).c_str());
822 }
823 os << " direct methods (" << NumDirectMethods() << " entries):\n";
824 for (size_t i = 0; i < NumDirectMethods(); ++i) {
825 os << StringPrintf(" %2d: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
826 }
827 if (NumStaticFields() > 0) {
828 os << " static fields (" << NumStaticFields() << " entries):\n";
829 for (size_t i = 0; i < NumStaticFields(); ++i) {
830 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetStaticField(i)).c_str());
831 }
832 }
833 if (NumInstanceFields() > 0) {
834 os << " instance fields (" << NumInstanceFields() << " entries):\n";
835 for (size_t i = 0; i < NumInstanceFields(); ++i) {
836 os << StringPrintf(" %2d: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
837 }
838 }
839}
840
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700841void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
842 if (new_reference_offsets != CLASS_WALK_SUPER) {
843 // Sanity check that the number of bits set in the reference offset bitmap
844 // agrees with the number of references
845 Class* cur = this;
846 size_t cnt = 0;
847 while (cur) {
848 cnt += cur->NumReferenceInstanceFieldsDuringLinking();
849 cur = cur->GetSuperClass();
850 }
851 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), cnt);
852 }
853 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
854 new_reference_offsets, false);
855}
856
857void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
858 if (new_reference_offsets != CLASS_WALK_SUPER) {
859 // Sanity check that the number of bits set in the reference offset bitmap
860 // agrees with the number of references
861 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
862 NumReferenceStaticFieldsDuringLinking());
863 }
864 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
865 new_reference_offsets, false);
866}
867
868size_t Class::PrimitiveSize() const {
869 switch (GetPrimitiveType()) {
870 case kPrimBoolean:
871 case kPrimByte:
872 case kPrimChar:
873 case kPrimShort:
874 case kPrimInt:
875 case kPrimFloat:
876 return sizeof(int32_t);
877 case kPrimLong:
878 case kPrimDouble:
879 return sizeof(int64_t);
880 default:
881 LOG(FATAL) << "Primitive type size calculation on invalid type " << this;
882 return 0;
883 }
884}
885
886size_t Class::GetTypeSize(const String* descriptor) {
887 switch (descriptor->CharAt(0)) {
888 case 'B': return 1; // byte
889 case 'C': return 2; // char
890 case 'D': return 8; // double
891 case 'F': return 4; // float
892 case 'I': return 4; // int
893 case 'J': return 8; // long
894 case 'S': return 2; // short
895 case 'Z': return 1; // boolean
896 case 'L': return sizeof(Object*);
897 case '[': return sizeof(Array*);
898 default:
899 LOG(ERROR) << "Unknown type " << descriptor;
900 return 0;
901 }
Elliott Hughesbf86d042011-08-31 17:53:14 -0700902}
903
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700904bool Class::Implements(const Class* klass) const {
905 DCHECK(klass != NULL);
906 DCHECK(klass->IsInterface());
907 // All interfaces implemented directly and by our superclass, and
908 // recursively all super-interfaces of those interfaces, are listed
909 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700910 int32_t iftable_count = GetIfTableCount();
911 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
912 for (int32_t i = 0; i < iftable_count; i++) {
913 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700914 return true;
915 }
916 }
917 return false;
918}
919
920// Determine whether "this" is assignable from "klazz", where both of these
921// are array classes.
922//
923// Consider an array class, e.g. Y[][], where Y is a subclass of X.
924// Y[][] = Y[][] --> true (identity)
925// X[][] = Y[][] --> true (element superclass)
926// Y = Y[][] --> false
927// Y[] = Y[][] --> false
928// Object = Y[][] --> true (everything is an object)
929// Object[] = Y[][] --> true
930// Object[][] = Y[][] --> true
931// Object[][][] = Y[][] --> false (too many []s)
932// Serializable = Y[][] --> true (all arrays are Serializable)
933// Serializable[] = Y[][] --> true
934// Serializable[][] = Y[][] --> false (unless Y is Serializable)
935//
936// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700937// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700938//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700939bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700940 DCHECK(IsArrayClass());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700941 DCHECK(src->IsArrayClass());
942 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700943}
944
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700945bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700946 DCHECK(!IsInterface()); // handled first in IsAssignableFrom
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700947 DCHECK(src->IsArrayClass());
Brian Carlstromb63ec392011-08-27 17:38:27 -0700948 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700949 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700950 // src's super should be java_lang_Object, since it is an array.
951 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700952 DCHECK(java_lang_Object != NULL);
953 DCHECK(java_lang_Object->GetSuperClass() == NULL);
954 return this == java_lang_Object;
955 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700956 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700957}
958
959bool Class::IsSubClass(const Class* klass) const {
960 DCHECK(!IsInterface());
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700961 DCHECK(!IsArrayClass());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700962 const Class* current = this;
963 do {
964 if (current == klass) {
965 return true;
966 }
967 current = current->GetSuperClass();
968 } while (current != NULL);
969 return false;
970}
971
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700972bool Class::IsInSamePackage(const String* descriptor_string_1,
973 const String* descriptor_string_2) {
974 const std::string descriptor1(descriptor_string_1->ToModifiedUtf8());
975 const std::string descriptor2(descriptor_string_2->ToModifiedUtf8());
976
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700977 size_t i = 0;
978 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
979 ++i;
980 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700981 if (descriptor1.find('/', i) != StringPiece::npos ||
982 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700983 return false;
984 } else {
985 return true;
986 }
987}
988
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700989#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700990bool Class::IsInSamePackage(const StringPiece& descriptor1,
991 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700992 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700993 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700994 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
995 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700996 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
997}
998#endif
999
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001000bool Class::IsInSamePackage(const Class* that) const {
1001 const Class* klass1 = this;
1002 const Class* klass2 = that;
1003 if (klass1 == klass2) {
1004 return true;
1005 }
1006 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001007 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001008 return false;
1009 }
1010 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -07001011 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001012 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001013 }
jeffhao4a801a42011-09-23 13:53:40 -07001014 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001015 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001016 }
1017 // Compare the package part of the descriptor string.
Brian Carlstrom6cc18452011-07-18 15:10:33 -07001018 return IsInSamePackage(klass1->descriptor_, klass2->descriptor_);
Carl Shapiro894d0fa2011-06-30 14:48:49 -07001019}
1020
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001021const ClassLoader* Class::GetClassLoader() const {
1022 return GetFieldObject<const ClassLoader*>(
1023 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -07001024}
1025
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001026void Class::SetClassLoader(const ClassLoader* new_cl) {
1027 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
1028 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_),
1029 new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001030}
1031
Brian Carlstrom30b94452011-08-25 21:35:26 -07001032Method* Class::FindVirtualMethodForInterface(Method* method) {
1033 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001034 DCHECK(declaring_class != NULL);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001035 DCHECK(declaring_class->IsInterface());
1036 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001037 int32_t iftable_count = GetIfTableCount();
1038 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1039 for (int32_t i = 0; i < iftable_count; i++) {
1040 InterfaceEntry* interface_entry = iftable->Get(i);
1041 if (interface_entry->GetInterface() == declaring_class) {
1042 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -07001043 }
1044 }
Brian Carlstrom16192862011-09-12 17:50:06 -07001045 UNIMPLEMENTED(FATAL) << "Need to throw an error of some kind " << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -07001046 return NULL;
1047}
1048
jeffhaobdb76512011-09-07 11:43:16 -07001049Method* Class::FindInterfaceMethod(const StringPiece& name,
1050 const StringPiece& signature) {
1051 // Check the current class before checking the interfaces.
1052 Method* method = FindVirtualMethod(name, signature);
1053 if (method != NULL) {
1054 return method;
1055 }
1056
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001057 int32_t iftable_count = GetIfTableCount();
1058 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1059 for (int32_t i = 0; i < iftable_count; i++) {
1060 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -07001061 if (method != NULL) {
1062 return method;
1063 }
1064 }
1065 return NULL;
1066}
1067
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001068Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001069 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001070 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001071 Method* method = GetDirectMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001072 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001073 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001074 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001075 }
1076 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001077 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001078}
1079
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001080Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001081 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001082 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001083 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001084 if (method != NULL) {
1085 return method;
1086 }
1087 }
1088 return NULL;
1089}
1090
1091Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001092 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001093 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001094 Method* method = GetVirtualMethod(i);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001095 if (method->GetName()->Equals(name) &&
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001096 method->GetSignature()->Equals(signature)) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001097 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001098 }
1099 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001100 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001101}
1102
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001103Method* Class::FindVirtualMethod(const StringPiece& name,
1104 const StringPiece& descriptor) {
1105 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1106 Method* method = klass->FindDeclaredVirtualMethod(name, descriptor);
1107 if (method != NULL) {
1108 return method;
1109 }
1110 }
1111 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001112}
1113
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001114Field* Class::FindDeclaredInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001115 // Is the field in this class?
1116 // Interfaces are not relevant because they can't contain instance fields.
1117 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1118 Field* f = GetInstanceField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001119 if (f->GetName()->Equals(name) && type == f->GetType()) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001120 return f;
1121 }
1122 }
1123 return NULL;
1124}
1125
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001126Field* Class::FindInstanceField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001127 // Is the field in this class, or any of its superclasses?
1128 // Interfaces are not relevant because they can't contain instance fields.
1129 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001130 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001131 if (f != NULL) {
1132 return f;
1133 }
1134 }
1135 return NULL;
1136}
1137
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001138Field* Class::FindDeclaredStaticField(const StringPiece& name, Class* type) {
1139 DCHECK(type != NULL);
Elliott Hughescdf53122011-08-19 15:46:09 -07001140 for (size_t i = 0; i < NumStaticFields(); ++i) {
1141 Field* f = GetStaticField(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001142 if (f->GetName()->Equals(name) && f->GetType() == type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001143 return f;
1144 }
1145 }
1146 return NULL;
1147}
1148
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001149Field* Class::FindStaticField(const StringPiece& name, Class* type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001150 // Is the field in this class (or its interfaces), or any of its
1151 // superclasses (or their interfaces)?
1152 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1153 // Is the field in this class?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001154 Field* f = c->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001155 if (f != NULL) {
1156 return f;
1157 }
1158
1159 // Is this field in any of this class' interfaces?
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001160 for (int32_t i = 0; i < c->GetIfTableCount(); ++i) {
1161 InterfaceEntry* interface_entry = c->GetIfTable()->Get(i);
1162 Class* interface = interface_entry->GetInterface();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001163 f = interface->FindDeclaredStaticField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001164 if (f != NULL) {
1165 return f;
1166 }
1167 }
1168 }
1169 return NULL;
1170}
1171
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001172Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001173 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001174 DCHECK_GE(component_count, 0);
1175 DCHECK(array_class->IsArrayClass());
1176 size_t size = SizeOf(component_count, component_size);
1177 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1178 if (array != NULL) {
1179 DCHECK(array->IsArrayInstance());
1180 array->SetLength(component_count);
1181 }
1182 return array;
1183}
1184
1185Array* Array::Alloc(Class* array_class, int32_t component_count) {
1186 return Alloc(array_class, component_count, array_class->GetComponentSize());
1187}
1188
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001189template<typename T>
1190PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001191 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001192 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1193 return down_cast<PrimitiveArray<T>*>(raw_array);
1194}
1195
1196template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1197
1198// Explicitly instantiate all the primitive array types.
1199template class PrimitiveArray<uint8_t>; // BooleanArray
1200template class PrimitiveArray<int8_t>; // ByteArray
1201template class PrimitiveArray<uint16_t>; // CharArray
1202template class PrimitiveArray<double>; // DoubleArray
1203template class PrimitiveArray<float>; // FloatArray
1204template class PrimitiveArray<int32_t>; // IntArray
1205template class PrimitiveArray<int64_t>; // LongArray
1206template class PrimitiveArray<int16_t>; // ShortArray
1207
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001208// TODO: get global references for these
1209Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001210
Brian Carlstroma663ea52011-08-19 23:33:41 -07001211void String::SetClass(Class* java_lang_String) {
1212 CHECK(java_lang_String_ == NULL);
1213 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001214 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001215}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001216
Brian Carlstroma663ea52011-08-19 23:33:41 -07001217void String::ResetClass() {
1218 CHECK(java_lang_String_ != NULL);
1219 java_lang_String_ = NULL;
1220}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001221
Brian Carlstromc74255f2011-09-11 22:47:39 -07001222String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001223 return Runtime::Current()->GetInternTable()->InternWeak(this);
1224}
1225
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001226int32_t String::GetHashCode() const {
1227 int32_t result = GetField32(
1228 OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1229 DCHECK(result != 0 ||
1230 ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0);
1231 return result;
1232}
1233
1234int32_t String::GetLength() const {
1235 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1236 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1237 return result;
1238}
1239
1240uint16_t String::CharAt(int32_t index) const {
1241 // TODO: do we need this? Equals is the only caller, and could
1242 // bounds check itself.
1243 if (index < 0 || index >= count_) {
1244 Thread* self = Thread::Current();
1245 self->ThrowNewException("Ljava/lang/StringIndexOutOfBoundsException;",
1246 "length=%i; index=%i", count_, index);
1247 return 0;
1248 }
1249 return GetCharArray()->Get(index + GetOffset());
1250}
1251
1252String* String::AllocFromUtf16(int32_t utf16_length,
1253 const uint16_t* utf16_data_in,
1254 int32_t hash_code) {
1255 String* string = Alloc(GetJavaLangString(), utf16_length);
1256 // TODO: use 16-bit wide memset variant
1257 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
1258 for (int i = 0; i < utf16_length; i++) {
1259 array->Set(i, utf16_data_in[i]);
1260 }
1261 if (hash_code != 0) {
1262 string->SetHashCode(hash_code);
1263 } else {
1264 string->ComputeHashCode();
1265 }
1266 return string;
1267}
1268
1269String* String::AllocFromModifiedUtf8(const char* utf) {
1270 size_t char_count = CountModifiedUtf8Chars(utf);
1271 return AllocFromModifiedUtf8(char_count, utf);
1272}
1273
1274String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1275 const char* utf8_data_in) {
1276 String* string = Alloc(GetJavaLangString(), utf16_length);
1277 uint16_t* utf16_data_out =
1278 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1279 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1280 string->ComputeHashCode();
1281 return string;
1282}
1283
1284String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
1285 return Alloc(java_lang_String, CharArray::Alloc(utf16_length));
1286}
1287
1288String* String::Alloc(Class* java_lang_String, CharArray* array) {
1289 String* string = down_cast<String*>(java_lang_String->AllocObject());
1290 string->SetArray(array);
1291 string->SetCount(array->GetLength());
1292 return string;
1293}
1294
1295bool String::Equals(const String* that) const {
1296 if (this == that) {
1297 // Quick reference equality test
1298 return true;
1299 } else if (that == NULL) {
1300 // Null isn't an instanceof anything
1301 return false;
1302 } else if (this->GetLength() != that->GetLength()) {
1303 // Quick length inequality test
1304 return false;
1305 } else {
1306 // NB don't short circuit on hash code as we're presumably here as the
1307 // hash code was already equal
1308 for (int32_t i = 0; i < that->GetLength(); ++i) {
1309 if (this->CharAt(i) != that->CharAt(i)) {
1310 return false;
1311 }
1312 }
1313 return true;
1314 }
1315}
1316
1317bool String::Equals(const uint16_t* that_chars, int32_t that_offset,
1318 int32_t that_length) const {
1319 if (this->GetLength() != that_length) {
1320 return false;
1321 } else {
1322 for (int32_t i = 0; i < that_length; ++i) {
1323 if (this->CharAt(i) != that_chars[that_offset + i]) {
1324 return false;
1325 }
1326 }
1327 return true;
1328 }
1329}
1330
1331bool String::Equals(const char* modified_utf8) const {
1332 for (int32_t i = 0; i < GetLength(); ++i) {
1333 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1334 if (ch == '\0' || ch != CharAt(i)) {
1335 return false;
1336 }
1337 }
1338 return *modified_utf8 == '\0';
1339}
1340
1341bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001342 if (modified_utf8.size() != GetLength()) {
1343 return false;
1344 }
1345 const char* p = modified_utf8.data();
1346 for (int32_t i = 0; i < GetLength(); ++i) {
1347 uint16_t ch = GetUtf16FromUtf8(&p);
1348 if (ch != CharAt(i)) {
1349 return false;
1350 }
1351 }
1352 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001353}
1354
1355// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1356std::string String::ToModifiedUtf8() const {
1357 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1358 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1359 std::string result(byte_count, char(0));
1360 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1361 return result;
1362}
1363
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001364Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1365
1366void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1367 CHECK(java_lang_StackTraceElement_ == NULL);
1368 CHECK(java_lang_StackTraceElement != NULL);
1369 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1370}
1371
1372void StackTraceElement::ResetClass() {
1373 CHECK(java_lang_StackTraceElement_ != NULL);
1374 java_lang_StackTraceElement_ = NULL;
1375}
1376
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001377StackTraceElement* StackTraceElement::Alloc(const String* declaring_class,
1378 const String* method_name,
1379 const String* file_name,
1380 int32_t line_number) {
1381 StackTraceElement* trace =
1382 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1383 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1384 const_cast<String*>(declaring_class), false);
1385 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1386 const_cast<String*>(method_name), false);
1387 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1388 const_cast<String*>(file_name), false);
1389 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1390 line_number, false);
1391 return trace;
1392}
1393
Elliott Hughes1f359b02011-07-17 14:27:17 -07001394static const char* kClassStatusNames[] = {
1395 "Error",
1396 "NotReady",
1397 "Idx",
1398 "Loaded",
1399 "Resolved",
1400 "Verifying",
1401 "Verified",
1402 "Initializing",
1403 "Initialized"
1404};
1405std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1406 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001407 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001408 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001409 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001410 }
1411 return os;
1412}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001413
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001414} // namespace art