blob: cf15a6489bef06639793c16349ad4eaa953f3f8f [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro3ee755d2011-06-28 12:11:04 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "object.h"
18
Ian Rogersb033c752011-07-20 12:22:35 -070019#include <string.h>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070020
Ian Rogersdf20fe02011-07-20 20:34:16 -070021#include <algorithm>
Elliott Hughes9d5ccec2011-09-19 13:19:50 -070022#include <iostream>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
24#include <utility>
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070026#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070027#include "class_loader.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070028#include "dex_cache.h"
29#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070030#include "globals.h"
Brian Carlstroma40f9bc2011-07-26 21:26:07 -070031#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070032#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070034#include "monitor.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080035#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070036#include "runtime.h"
Ian Rogers60db5ab2012-02-20 17:02:00 -080037#include "runtime_support.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070038#include "stack.h"
Ian Rogers0571d352011-11-03 19:51:38 -070039#include "utils.h"
Carl Shapiro3ee755d2011-06-28 12:11:04 -070040
Logan Chienfca7e872011-12-20 20:08:22 +080041#if defined(ART_USE_LLVM_COMPILER)
42#include "compiler_llvm/inferred_reg_category_map.h"
43using art::compiler_llvm::InferredRegCategoryMap;
44#endif
45
Carl Shapiro3ee755d2011-06-28 12:11:04 -070046namespace art {
47
Elliott Hughesdbb40792011-11-18 17:05:22 -080048String* Object::AsString() {
49 DCHECK(GetClass()->IsStringClass());
50 return down_cast<String*>(this);
51}
52
Elliott Hughes081be7f2011-09-18 16:50:26 -070053Object* Object::Clone() {
54 Class* c = GetClass();
55 DCHECK(!c->IsClassClass());
56
57 // Object::SizeOf gets the right size even if we're an array.
58 // Using c->AllocObject() here would be wrong.
59 size_t num_bytes = SizeOf();
Brian Carlstrom40381fb2011-10-19 14:13:40 -070060 SirtRef<Object> copy(Heap::AllocObject(c, num_bytes));
61 if (copy.get() == NULL) {
Elliott Hughes081be7f2011-09-18 16:50:26 -070062 return NULL;
63 }
64
65 // Copy instance data. We assume memcpy copies by words.
66 // TODO: expose and use move32.
67 byte* src_bytes = reinterpret_cast<byte*>(this);
Brian Carlstrom40381fb2011-10-19 14:13:40 -070068 byte* dst_bytes = reinterpret_cast<byte*>(copy.get());
Elliott Hughes081be7f2011-09-18 16:50:26 -070069 size_t offset = sizeof(Object);
70 memcpy(dst_bytes + offset, src_bytes + offset, num_bytes - offset);
71
Elliott Hughes20cde902011-10-04 17:37:27 -070072 if (c->IsFinalizable()) {
Ian Rogers5d4bdc22011-11-02 22:15:43 -070073 Heap::AddFinalizerReference(Thread::Current(), copy.get());
Elliott Hughes20cde902011-10-04 17:37:27 -070074 }
Elliott Hughes081be7f2011-09-18 16:50:26 -070075
Brian Carlstrom40381fb2011-10-19 14:13:40 -070076 return copy.get();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070077}
78
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070079uint32_t Object::GetThinLockId() {
80 return Monitor::GetThinLockId(monitor_);
Elliott Hughes5f791332011-09-15 17:45:30 -070081}
82
83void Object::MonitorEnter(Thread* thread) {
84 Monitor::MonitorEnter(thread, this);
85}
86
Ian Rogersff1ed472011-09-20 13:46:24 -070087bool Object::MonitorExit(Thread* thread) {
88 return Monitor::MonitorExit(thread, this);
Elliott Hughes5f791332011-09-15 17:45:30 -070089}
90
91void Object::Notify() {
92 Monitor::Notify(Thread::Current(), this);
93}
94
95void Object::NotifyAll() {
96 Monitor::NotifyAll(Thread::Current(), this);
97}
98
99void Object::Wait(int64_t ms, int32_t ns) {
100 Monitor::Wait(Thread::Current(), this, ms, ns, true);
101}
102
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700103// TODO: get global references for these
104Class* Field::java_lang_reflect_Field_ = NULL;
105
106void Field::SetClass(Class* java_lang_reflect_Field) {
107 CHECK(java_lang_reflect_Field_ == NULL);
108 CHECK(java_lang_reflect_Field != NULL);
109 java_lang_reflect_Field_ = java_lang_reflect_Field;
110}
111
112void Field::ResetClass() {
113 CHECK(java_lang_reflect_Field_ != NULL);
114 java_lang_reflect_Field_ = NULL;
115}
116
Ian Rogers0571d352011-11-03 19:51:38 -0700117void Field::SetOffset(MemberOffset num_bytes) {
118 DCHECK(GetDeclaringClass()->IsLoaded() || GetDeclaringClass()->IsErroneous());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800119#if 0 // TODO enable later in boot and under !NDEBUG
120 FieldHelper fh(this);
121 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Ian Rogers0571d352011-11-03 19:51:38 -0700122 if (type == Primitive::kPrimDouble || type == Primitive::kPrimLong) {
123 DCHECK_ALIGNED(num_bytes.Uint32Value(), 8);
124 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800125#endif
Ian Rogers0571d352011-11-03 19:51:38 -0700126 SetField32(OFFSET_OF_OBJECT_MEMBER(Field, offset_), num_bytes.Uint32Value(), false);
127}
128
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700129uint32_t Field::Get32(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700130 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700131 if (IsStatic()) {
132 object = declaring_class_;
133 }
134 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700135}
136
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700137void Field::Set32(Object* object, uint32_t new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700138 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700139 if (IsStatic()) {
140 object = declaring_class_;
141 }
142 object->SetField32(GetOffset(), new_value, IsVolatile());
143}
144
145uint64_t Field::Get64(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700146 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700147 if (IsStatic()) {
148 object = declaring_class_;
149 }
150 return object->GetField64(GetOffset(), IsVolatile());
151}
152
153void Field::Set64(Object* object, uint64_t new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700154 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700155 if (IsStatic()) {
156 object = declaring_class_;
157 }
158 object->SetField64(GetOffset(), new_value, IsVolatile());
159}
160
161Object* Field::GetObj(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700162 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700163 if (IsStatic()) {
164 object = declaring_class_;
165 }
166 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
167}
168
169void Field::SetObj(Object* object, const Object* new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700170 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700171 if (IsStatic()) {
172 object = declaring_class_;
173 }
174 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
175}
176
177bool Field::GetBoolean(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800178 DCHECK_EQ(Primitive::kPrimBoolean, FieldHelper(this).GetTypeAsPrimitiveType())
179 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700180 return Get32(object);
181}
182
183void Field::SetBoolean(Object* object, bool z) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800184 DCHECK_EQ(Primitive::kPrimBoolean, FieldHelper(this).GetTypeAsPrimitiveType())
185 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700186 Set32(object, z);
187}
188
189int8_t Field::GetByte(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800190 DCHECK_EQ(Primitive::kPrimByte, FieldHelper(this).GetTypeAsPrimitiveType())
191 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700192 return Get32(object);
193}
194
195void Field::SetByte(Object* object, int8_t b) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800196 DCHECK_EQ(Primitive::kPrimByte, FieldHelper(this).GetTypeAsPrimitiveType())
197 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700198 Set32(object, b);
199}
200
201uint16_t Field::GetChar(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800202 DCHECK_EQ(Primitive::kPrimChar, FieldHelper(this).GetTypeAsPrimitiveType())
203 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700204 return Get32(object);
205}
206
207void Field::SetChar(Object* object, uint16_t c) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800208 DCHECK_EQ(Primitive::kPrimChar, FieldHelper(this).GetTypeAsPrimitiveType())
209 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700210 Set32(object, c);
211}
212
Ian Rogers466bb252011-10-14 03:29:56 -0700213int16_t Field::GetShort(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800214 DCHECK_EQ(Primitive::kPrimShort, FieldHelper(this).GetTypeAsPrimitiveType())
215 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700216 return Get32(object);
217}
218
Ian Rogers466bb252011-10-14 03:29:56 -0700219void Field::SetShort(Object* object, int16_t s) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800220 DCHECK_EQ(Primitive::kPrimShort, FieldHelper(this).GetTypeAsPrimitiveType())
221 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700222 Set32(object, s);
223}
224
225int32_t Field::GetInt(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800226 DCHECK_EQ(Primitive::kPrimInt, FieldHelper(this).GetTypeAsPrimitiveType())
227 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700228 return Get32(object);
229}
230
231void Field::SetInt(Object* object, int32_t i) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800232 DCHECK_EQ(Primitive::kPrimInt, FieldHelper(this).GetTypeAsPrimitiveType())
233 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700234 Set32(object, i);
235}
236
237int64_t Field::GetLong(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800238 DCHECK_EQ(Primitive::kPrimLong, FieldHelper(this).GetTypeAsPrimitiveType())
239 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700240 return Get64(object);
241}
242
243void Field::SetLong(Object* object, int64_t j) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800244 DCHECK_EQ(Primitive::kPrimLong, FieldHelper(this).GetTypeAsPrimitiveType())
245 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700246 Set64(object, j);
247}
248
249float Field::GetFloat(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800250 DCHECK_EQ(Primitive::kPrimFloat, FieldHelper(this).GetTypeAsPrimitiveType())
251 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700252 JValue float_bits;
253 float_bits.i = Get32(object);
254 return float_bits.f;
255}
256
257void Field::SetFloat(Object* object, float f) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800258 DCHECK_EQ(Primitive::kPrimFloat, FieldHelper(this).GetTypeAsPrimitiveType())
259 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700260 JValue float_bits;
261 float_bits.f = f;
262 Set32(object, float_bits.i);
263}
264
265double Field::GetDouble(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800266 DCHECK_EQ(Primitive::kPrimDouble, FieldHelper(this).GetTypeAsPrimitiveType())
267 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700268 JValue double_bits;
269 double_bits.j = Get64(object);
270 return double_bits.d;
271}
272
273void Field::SetDouble(Object* object, double d) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800274 DCHECK_EQ(Primitive::kPrimDouble, FieldHelper(this).GetTypeAsPrimitiveType())
275 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700276 JValue double_bits;
277 double_bits.d = d;
278 Set64(object, double_bits.j);
279}
280
281Object* Field::GetObject(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800282 DCHECK_EQ(Primitive::kPrimNot, FieldHelper(this).GetTypeAsPrimitiveType())
283 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 return GetObj(object);
285}
286
287void Field::SetObject(Object* object, const Object* l) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800288 DCHECK_EQ(Primitive::kPrimNot, FieldHelper(this).GetTypeAsPrimitiveType())
289 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700290 SetObj(object, l);
291}
292
293// TODO: get global references for these
Elliott Hughes80609252011-09-23 17:24:51 -0700294Class* Method::java_lang_reflect_Constructor_ = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295Class* Method::java_lang_reflect_Method_ = NULL;
296
Elliott Hughes80609252011-09-23 17:24:51 -0700297void Method::SetClasses(Class* java_lang_reflect_Constructor, Class* java_lang_reflect_Method) {
298 CHECK(java_lang_reflect_Constructor_ == NULL);
299 CHECK(java_lang_reflect_Constructor != NULL);
300 java_lang_reflect_Constructor_ = java_lang_reflect_Constructor;
301
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302 CHECK(java_lang_reflect_Method_ == NULL);
303 CHECK(java_lang_reflect_Method != NULL);
304 java_lang_reflect_Method_ = java_lang_reflect_Method;
305}
306
Elliott Hughes80609252011-09-23 17:24:51 -0700307void Method::ResetClasses() {
308 CHECK(java_lang_reflect_Constructor_ != NULL);
309 java_lang_reflect_Constructor_ = NULL;
310
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700311 CHECK(java_lang_reflect_Method_ != NULL);
312 java_lang_reflect_Method_ = NULL;
313}
314
Elliott Hughes418d20f2011-09-22 14:00:39 -0700315Class* ExtractNextClassFromSignature(ClassLinker* class_linker, const ClassLoader* cl, const char*& p) {
316 if (*p == '[') {
317 // Something like "[[[Ljava/lang/String;".
318 const char* start = p;
319 while (*p == '[') {
320 ++p;
321 }
322 if (*p == 'L') {
323 while (*p != ';') {
324 ++p;
325 }
326 }
327 ++p; // Either the ';' or the primitive type.
328
Brian Carlstromaded5f72011-10-07 17:15:04 -0700329 std::string descriptor(start, (p - start));
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800330 return class_linker->FindClass(descriptor.c_str(), cl);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700331 } else if (*p == 'L') {
332 const char* start = p;
333 while (*p != ';') {
334 ++p;
335 }
336 ++p;
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800337 std::string descriptor(start, (p - start));
338 return class_linker->FindClass(descriptor.c_str(), cl);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700339 } else {
340 return class_linker->FindPrimitiveClass(*p++);
341 }
342}
343
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344ObjectArray<String>* Method::GetDexCacheStrings() const {
345 return GetFieldObject<ObjectArray<String>*>(
346 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
347}
348
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
350 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
351 new_dex_cache_strings, false);
352}
353
354ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
355 return GetFieldObject<ObjectArray<Class>*>(
356 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
357}
358
359void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
360 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
361 new_dex_cache_classes, false);
362}
363
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
365 return GetFieldPtr<CodeAndDirectMethods*>(
366 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
367 false);
368}
369
370void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
371 SetFieldPtr<CodeAndDirectMethods*>(
372 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
373 new_value, false);
374}
375
376ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
377 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
378 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
379 false);
380}
381
382void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700383 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384 new_value, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385}
386
Logan Chienfca7e872011-12-20 20:08:22 +0800387#if defined(ART_USE_LLVM_COMPILER)
388
389const InferredRegCategoryMap* Method::GetInferredRegCategoryMap() const {
390 const InferredRegCategoryMap* map = GetFieldPtr<const InferredRegCategoryMap*>(
391 OFFSET_OF_OBJECT_MEMBER(Method, gc_map_), false);
392 DCHECK(map != NULL) << PrettyMethod(this);
393 return map;
394}
395
396void Method::SetInferredRegCategoryMap(const InferredRegCategoryMap* map) {
Logan Chiena1854662012-02-17 09:52:18 +0800397 const InferredRegCategoryMap* existing_map = GetFieldPtr<const InferredRegCategoryMap*>(
398 OFFSET_OF_OBJECT_MEMBER(Method, gc_map_), false);
Logan Chienfca7e872011-12-20 20:08:22 +0800399
400 DCHECK(existing_map == NULL) << PrettyMethod(this);
401 DCHECK(map != NULL) << PrettyMethod(this);
402
403 // TODO: Remove if we won't find any use of InferredRegCategoryMap at runtime.
404 SetFieldPtr<const InferredRegCategoryMap*>(
405 OFFSET_OF_OBJECT_MEMBER(Method, gc_map_), map, false);
406}
407
408void Method::ResetInferredRegCategoryMap() {
409 delete GetInferredRegCategoryMap();
410 SetFieldPtr<const InferredRegCategoryMap*>(
Logan Chiena1854662012-02-17 09:52:18 +0800411 OFFSET_OF_OBJECT_MEMBER(Method, gc_map_), NULL, false);
Logan Chienfca7e872011-12-20 20:08:22 +0800412}
413
414#endif
415
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416size_t Method::NumArgRegisters(const StringPiece& shorty) {
417 CHECK_LE(1, shorty.length());
418 uint32_t num_registers = 0;
419 for (int i = 1; i < shorty.length(); ++i) {
420 char ch = shorty[i];
421 if (ch == 'D' || ch == 'J') {
422 num_registers += 2;
423 } else {
424 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700425 }
426 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427 return num_registers;
428}
429
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800430bool Method::IsProxyMethod() const {
431 return GetDeclaringClass()->IsProxyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700432}
433
Ian Rogers466bb252011-10-14 03:29:56 -0700434Method* Method::FindOverriddenMethod() const {
435 if (IsStatic()) {
436 return NULL;
437 }
438 Class* declaring_class = GetDeclaringClass();
439 Class* super_class = declaring_class->GetSuperClass();
440 uint16_t method_index = GetMethodIndex();
441 ObjectArray<Method>* super_class_vtable = super_class->GetVTable();
442 Method* result = NULL;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800443 // Did this method override a super class method? If so load the result from the super class'
444 // vtable
Ian Rogers466bb252011-10-14 03:29:56 -0700445 if (super_class_vtable != NULL && method_index < super_class_vtable->GetLength()) {
446 result = super_class_vtable->Get(method_index);
447 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800448 // Method didn't override superclass method so search interfaces
Ian Rogers16f93672012-02-14 12:29:06 -0800449 if (IsProxyMethod()) {
450 result = Runtime::Current()->GetClassLinker()->FindMethodForProxy(GetDeclaringClass(), this);
451 } else {
452 MethodHelper mh(this);
453 MethodHelper interface_mh;
454 ObjectArray<InterfaceEntry>* iftable = GetDeclaringClass()->GetIfTable();
455 for (int32_t i = 0; i < iftable->GetLength() && result == NULL; i++) {
456 InterfaceEntry* entry = iftable->Get(i);
457 Class* interface = entry->GetInterface();
458 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
459 Method* interface_method = interface->GetVirtualMethod(j);
460 interface_mh.ChangeMethod(interface_method);
461 if (mh.HasSameNameAndSignature(&interface_mh)) {
462 result = interface_method;
463 break;
464 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800465 }
466 }
Ian Rogers466bb252011-10-14 03:29:56 -0700467 }
468 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800469#ifndef NDEBUG
470 MethodHelper result_mh(result);
471 DCHECK(result == NULL || MethodHelper(this).HasSameNameAndSignature(&result_mh));
472#endif
Ian Rogers466bb252011-10-14 03:29:56 -0700473 return result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700474}
475
Ian Rogersbdb03912011-09-14 00:55:44 -0700476uint32_t Method::ToDexPC(const uintptr_t pc) const {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700477 const uint32_t* mapping_table = GetMappingTable();
Ian Rogersbdb03912011-09-14 00:55:44 -0700478 if (mapping_table == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800479 DCHECK(IsNative() || IsCalleeSaveMethod() || IsProxyMethod()) << PrettyMethod(this);
Ian Rogers67375ac2011-09-14 00:55:44 -0700480 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700481 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700482 size_t mapping_table_length = GetMappingTableLength();
jeffhao26c0a1a2012-01-17 16:28:33 -0800483 const void* code_offset;
484 if (Runtime::Current()->IsMethodTracingActive() &&
485 Runtime::Current()->GetTracer()->GetSavedCodeFromMap(this) != NULL) {
486 code_offset = Runtime::Current()->GetTracer()->GetSavedCodeFromMap(this);
487 } else {
488 code_offset = GetCode();
489 }
jeffhaoe343b762011-12-05 16:36:44 -0800490 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(code_offset);
Ian Rogersbdb03912011-09-14 00:55:44 -0700491 uint32_t best_offset = 0;
492 uint32_t best_dex_offset = 0;
493 for (size_t i = 0; i < mapping_table_length; i += 2) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700494 uint32_t map_offset = mapping_table[i];
495 uint32_t map_dex_offset = mapping_table[i + 1];
Ian Rogersbdb03912011-09-14 00:55:44 -0700496 if (map_offset == sought_offset) {
497 best_offset = map_offset;
498 best_dex_offset = map_dex_offset;
499 break;
500 }
501 if (map_offset < sought_offset && map_offset > best_offset) {
502 best_offset = map_offset;
503 best_dex_offset = map_dex_offset;
504 }
505 }
506 return best_dex_offset;
507}
508
509uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700510 const uint32_t* mapping_table = GetMappingTable();
Ian Rogersbdb03912011-09-14 00:55:44 -0700511 if (mapping_table == NULL) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700512 DCHECK_EQ(dex_pc, 0U);
Ian Rogersbdb03912011-09-14 00:55:44 -0700513 return 0; // Special no mapping/pc == 0 case
514 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700515 size_t mapping_table_length = GetMappingTableLength();
Ian Rogersbdb03912011-09-14 00:55:44 -0700516 for (size_t i = 0; i < mapping_table_length; i += 2) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700517 uint32_t map_offset = mapping_table[i];
518 uint32_t map_dex_offset = mapping_table[i + 1];
Ian Rogersbdb03912011-09-14 00:55:44 -0700519 if (map_dex_offset == dex_pc) {
jeffhao2692b572011-12-16 15:42:28 -0800520 if (Runtime::Current()->IsMethodTracingActive()) {
521 Trace* tracer = Runtime::Current()->GetTracer();
522 return reinterpret_cast<uintptr_t>(tracer->GetSavedCodeFromMap(this)) + map_offset;
jeffhaoe343b762011-12-05 16:36:44 -0800523 } else {
524 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
525 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700526 }
527 }
528 LOG(FATAL) << "Looking up Dex PC not contained in method";
529 return 0;
530}
531
532uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800533 MethodHelper mh(this);
534 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Ian Rogersbdb03912011-09-14 00:55:44 -0700535 // Iterate over the catch handlers associated with dex_pc
Ian Rogers0571d352011-11-03 19:51:38 -0700536 for (CatchHandlerIterator it(*code_item, dex_pc); it.HasNext(); it.Next()) {
537 uint16_t iter_type_idx = it.GetHandlerTypeIndex();
Ian Rogersbdb03912011-09-14 00:55:44 -0700538 // Catch all case
Ian Rogers0571d352011-11-03 19:51:38 -0700539 if (iter_type_idx == DexFile::kDexNoIndex16) {
540 return it.GetHandlerAddress();
Ian Rogersbdb03912011-09-14 00:55:44 -0700541 }
542 // Does this catch exception type apply?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800543 Class* iter_exception_type = mh.GetDexCacheResolvedType(iter_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -0700544 if (iter_exception_type == NULL) {
545 // The verifier should take care of resolving all exception classes early
546 LOG(WARNING) << "Unresolved exception class when finding catch block: "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800547 << mh.GetTypeDescriptorFromTypeIdx(iter_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -0700548 } else if (iter_exception_type->IsAssignableFrom(exception_type)) {
Ian Rogers0571d352011-11-03 19:51:38 -0700549 return it.GetHandlerAddress();
Ian Rogersbdb03912011-09-14 00:55:44 -0700550 }
551 }
552 // Handler not found
553 return DexFile::kDexNoIndex;
554}
555
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700556void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
557 // Push a transition back into managed code onto the linked list in thread.
558 CHECK_EQ(Thread::kRunnable, self->GetState());
559 NativeToManagedRecord record;
560 self->PushNativeToManagedRecord(&record);
561
562 // Call the invoke stub associated with the method.
563 // Pass everything as arguments.
564 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700565
566 bool have_executable_code = (GetCode() != NULL);
567#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700568 // Currently we can only compile non-native methods for ARM.
569 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700570#endif
571
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500572 if (Runtime::Current()->IsStarted() && have_executable_code && stub != NULL) {
Elliott Hughes9f865372011-10-11 15:04:19 -0700573 bool log = false;
574 if (log) {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800575 LOG(INFO) << StringPrintf("invoking %s code=%p stub=%p",
576 PrettyMethod(this).c_str(), GetCode(), stub);
Elliott Hughes9f865372011-10-11 15:04:19 -0700577 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700578 (*stub)(this, receiver, self, args, result);
Elliott Hughes9f865372011-10-11 15:04:19 -0700579 if (log) {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800580 LOG(INFO) << StringPrintf("returned %s code=%p stub=%p",
581 PrettyMethod(this).c_str(), GetCode(), stub);
Elliott Hughes9f865372011-10-11 15:04:19 -0700582 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700583 } else {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800584 LOG(INFO) << StringPrintf("not invoking %s code=%p stub=%p started=%s",
585 PrettyMethod(this).c_str(), GetCode(), stub,
586 Runtime::Current()->IsStarted() ? "true" : "false");
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700587 if (result != NULL) {
588 result->j = 0;
589 }
590 }
591
592 // Pop transition.
593 self->PopNativeToManagedRecord(record);
594}
595
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700596bool Method::IsRegistered() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700597 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
Ian Rogers169c9a72011-11-13 20:13:17 -0800598 void* jni_stub = Runtime::Current()->GetJniDlsymLookupStub()->GetData();
Brian Carlstrom16192862011-09-12 17:50:06 -0700599 return native_method != jni_stub;
600}
601
Ian Rogers60db5ab2012-02-20 17:02:00 -0800602void Method::RegisterNative(Thread* self, const void* native_method) {
603 DCHECK(Thread::Current() == self);
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700604 CHECK(IsNative()) << PrettyMethod(this);
605 CHECK(native_method != NULL) << PrettyMethod(this);
Ian Rogers60db5ab2012-02-20 17:02:00 -0800606 if (!self->GetJniEnv()->vm->work_around_app_jni_bugs) {
607 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
608 native_method, false);
609 } else {
610 // We've been asked to associate this method with the given native method but are working
611 // around JNI bugs, that include not giving Object** SIRT references to native methods. Direct
612 // the native method to runtime support and store the target somewhere runtime support will
613 // find it.
614#if defined(__arm__)
615 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
616 reinterpret_cast<const void*>(art_work_around_app_jni_bugs), false);
617#else
618 UNIMPLEMENTED(FATAL);
619#endif
620 SetFieldPtr<const uint8_t*>(OFFSET_OF_OBJECT_MEMBER(Method, gc_map_),
621 reinterpret_cast<const uint8_t*>(native_method), false);
622 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700623}
624
625void Method::UnregisterNative() {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700626 CHECK(IsNative()) << PrettyMethod(this);
Brian Carlstrom16192862011-09-12 17:50:06 -0700627 // restore stub to lookup native pointer via dlsym
Ian Rogers60db5ab2012-02-20 17:02:00 -0800628 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
629 Runtime::Current()->GetJniDlsymLookupStub()->GetData(), false);
Brian Carlstrom16192862011-09-12 17:50:06 -0700630}
631
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700632void Class::SetStatus(Status new_status) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700633 CHECK(new_status > GetStatus() || new_status == kStatusError || !Runtime::Current()->IsStarted())
634 << PrettyClass(this) << " " << GetStatus() << " -> " << new_status;
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700635 CHECK(sizeof(Status) == sizeof(uint32_t)) << PrettyClass(this);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -0800636 if (new_status == kStatusError) {
637 CHECK_NE(GetStatus(), kStatusError) << PrettyClass(this);
638
639 // stash current exception
640 Thread* self = Thread::Current();
641 SirtRef<Throwable> exception(self->GetException());
642 CHECK(exception.get() != NULL);
643
644 // clear exception to call FindSystemClass
645 self->ClearException();
646 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
647 Class* eiie_class = class_linker->FindSystemClass("Ljava/lang/ExceptionInInitializerError;");
648 CHECK(!self->IsExceptionPending());
649
650 // only verification errors, not initialization problems, should set a verify error.
651 // this is to ensure that ThrowEarlierClassFailure will throw NoClassDefFoundError in that case.
652 Class* exception_class = exception->GetClass();
653 if (!eiie_class->IsAssignableFrom(exception_class)) {
654 SetVerifyErrorClass(exception_class);
655 }
656
657 // restore exception
658 self->SetException(exception.get());
659 }
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700660 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700661}
662
663DexCache* Class::GetDexCache() const {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700664 return GetFieldObject<DexCache*>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700665}
666
667void Class::SetDexCache(DexCache* new_dex_cache) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700668 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700669}
670
Brian Carlstrom1f870082011-08-23 16:02:11 -0700671Object* Class::AllocObject() {
Brian Carlstrom96a253a2011-10-27 18:38:10 -0700672 DCHECK(!IsArrayClass()) << PrettyClass(this);
Ian Rogers28ad40d2011-10-27 15:19:26 -0700673 DCHECK(IsInstantiable()) << PrettyClass(this);
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500674 // TODO: decide whether we want this check. It currently fails during bootstrap.
675 // DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
Brian Carlstrom96a253a2011-10-27 18:38:10 -0700676 DCHECK_GE(this->object_size_, sizeof(Object));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700677 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700678}
679
Ian Rogers0571d352011-11-03 19:51:38 -0700680void Class::SetClassSize(size_t new_class_size) {
681 DCHECK_GE(new_class_size, GetClassSize()) << " class=" << PrettyTypeOf(this);
682 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size, false);
683}
684
Ian Rogersd418eda2012-01-30 12:14:28 -0800685// Return the class' name. The exact format is bizarre, but it's the specified behavior for
686// Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
687// but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
688// slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
689String* Class::ComputeName() {
690 String* name = GetName();
691 if (name != NULL) {
692 return name;
693 }
694 std::string descriptor(ClassHelper(this).GetDescriptor());
695 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
696 // The descriptor indicates that this is the class for
697 // a primitive type; special-case the return value.
698 const char* c_name = NULL;
699 switch (descriptor[0]) {
700 case 'Z': c_name = "boolean"; break;
701 case 'B': c_name = "byte"; break;
702 case 'C': c_name = "char"; break;
703 case 'S': c_name = "short"; break;
704 case 'I': c_name = "int"; break;
705 case 'J': c_name = "long"; break;
706 case 'F': c_name = "float"; break;
707 case 'D': c_name = "double"; break;
708 case 'V': c_name = "void"; break;
709 default:
710 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
711 }
712 name = String::AllocFromModifiedUtf8(c_name);
713 } else {
714 // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
715 // components.
716 if (descriptor.size() > 2 && descriptor[0] == 'L' && descriptor[descriptor.size() - 1] == ';') {
717 descriptor.erase(0, 1);
718 descriptor.erase(descriptor.size() - 1);
719 }
720 std::replace(descriptor.begin(), descriptor.end(), '/', '.');
721 name = String::AllocFromModifiedUtf8(descriptor.c_str());
722 }
723 SetName(name);
724 return name;
725}
726
Elliott Hughes4681c802011-09-25 18:04:37 -0700727void Class::DumpClass(std::ostream& os, int flags) const {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700728 if ((flags & kDumpClassFullDetail) == 0) {
729 os << PrettyClass(this);
730 if ((flags & kDumpClassClassLoader) != 0) {
731 os << ' ' << GetClassLoader();
732 }
733 if ((flags & kDumpClassInitialized) != 0) {
734 os << ' ' << GetStatus();
735 }
Elliott Hughese0918552011-10-28 17:18:29 -0700736 os << "\n";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700737 return;
738 }
739
740 Class* super = GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800741 ClassHelper kh(this);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700742 os << "----- " << (IsInterface() ? "interface" : "class") << " "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800743 << "'" << kh.GetDescriptor() << "' cl=" << GetClassLoader() << " -----\n",
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700744 os << " objectSize=" << SizeOf() << " "
745 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
746 os << StringPrintf(" access=0x%04x.%04x\n",
747 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
748 if (super != NULL) {
749 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
750 }
751 if (IsArrayClass()) {
752 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
753 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800754 if (kh.NumInterfaces() > 0) {
755 os << " interfaces (" << kh.NumInterfaces() << "):\n";
756 for (size_t i = 0; i < kh.NumInterfaces(); ++i) {
757 Class* interface = kh.GetInterface(i);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700758 const ClassLoader* cl = interface->GetClassLoader();
Elliott Hughese689d512012-01-18 23:39:47 -0800759 os << StringPrintf(" %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700760 }
761 }
762 os << " vtable (" << NumVirtualMethods() << " entries, "
763 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
764 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Elliott Hughese689d512012-01-18 23:39:47 -0800765 os << StringPrintf(" %2zd: %s\n", i, PrettyMethod(GetVirtualMethodDuringLinking(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700766 }
767 os << " direct methods (" << NumDirectMethods() << " entries):\n";
768 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Elliott Hughese689d512012-01-18 23:39:47 -0800769 os << StringPrintf(" %2zd: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700770 }
771 if (NumStaticFields() > 0) {
772 os << " static fields (" << NumStaticFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700773 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700774 for (size_t i = 0; i < NumStaticFields(); ++i) {
Elliott Hughese689d512012-01-18 23:39:47 -0800775 os << StringPrintf(" %2zd: %s\n", i, PrettyField(GetStaticField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700776 }
777 } else {
778 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700779 }
780 }
781 if (NumInstanceFields() > 0) {
782 os << " instance fields (" << NumInstanceFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700783 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700784 for (size_t i = 0; i < NumInstanceFields(); ++i) {
Elliott Hughese689d512012-01-18 23:39:47 -0800785 os << StringPrintf(" %2zd: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700786 }
787 } else {
788 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700789 }
790 }
791}
792
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700793void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
794 if (new_reference_offsets != CLASS_WALK_SUPER) {
795 // Sanity check that the number of bits set in the reference offset bitmap
796 // agrees with the number of references
Elliott Hughescccd84f2011-12-05 16:51:54 -0800797 size_t count = 0;
798 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
799 count += c->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700800 }
Elliott Hughescccd84f2011-12-05 16:51:54 -0800801 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), count);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700802 }
803 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
804 new_reference_offsets, false);
805}
806
807void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
808 if (new_reference_offsets != CLASS_WALK_SUPER) {
809 // Sanity check that the number of bits set in the reference offset bitmap
810 // agrees with the number of references
811 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
812 NumReferenceStaticFieldsDuringLinking());
813 }
814 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
815 new_reference_offsets, false);
816}
817
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700818bool Class::Implements(const Class* klass) const {
819 DCHECK(klass != NULL);
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700820 DCHECK(klass->IsInterface()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700821 // All interfaces implemented directly and by our superclass, and
822 // recursively all super-interfaces of those interfaces, are listed
823 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700824 int32_t iftable_count = GetIfTableCount();
825 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
826 for (int32_t i = 0; i < iftable_count; i++) {
827 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700828 return true;
829 }
830 }
831 return false;
832}
833
834// Determine whether "this" is assignable from "klazz", where both of these
835// are array classes.
836//
837// Consider an array class, e.g. Y[][], where Y is a subclass of X.
838// Y[][] = Y[][] --> true (identity)
839// X[][] = Y[][] --> true (element superclass)
840// Y = Y[][] --> false
841// Y[] = Y[][] --> false
842// Object = Y[][] --> true (everything is an object)
843// Object[] = Y[][] --> true
844// Object[][] = Y[][] --> true
845// Object[][][] = Y[][] --> false (too many []s)
846// Serializable = Y[][] --> true (all arrays are Serializable)
847// Serializable[] = Y[][] --> true
848// Serializable[][] = Y[][] --> false (unless Y is Serializable)
849//
850// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700851// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700852//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700853bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700854 DCHECK(IsArrayClass()) << PrettyClass(this);
855 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700856 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700857}
858
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700859bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700860 DCHECK(!IsInterface()) << PrettyClass(this); // handled first in IsAssignableFrom
861 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700862 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700863 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700864 // src's super should be java_lang_Object, since it is an array.
865 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700866 DCHECK(java_lang_Object != NULL) << PrettyClass(src);
867 DCHECK(java_lang_Object->GetSuperClass() == NULL) << PrettyClass(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700868 return this == java_lang_Object;
869 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700870 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700871}
872
873bool Class::IsSubClass(const Class* klass) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700874 DCHECK(!IsInterface()) << PrettyClass(this);
875 DCHECK(!IsArrayClass()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700876 const Class* current = this;
877 do {
878 if (current == klass) {
879 return true;
880 }
881 current = current->GetSuperClass();
882 } while (current != NULL);
883 return false;
884}
885
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800886bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700887 size_t i = 0;
888 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
889 ++i;
890 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700891 if (descriptor1.find('/', i) != StringPiece::npos ||
892 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700893 return false;
894 } else {
895 return true;
896 }
897}
898
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700899#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700900bool Class::IsInSamePackage(const StringPiece& descriptor1,
901 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700902 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700903 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700904 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
905 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700906 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
907}
908#endif
909
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700910bool Class::IsInSamePackage(const Class* that) const {
911 const Class* klass1 = this;
912 const Class* klass2 = that;
913 if (klass1 == klass2) {
914 return true;
915 }
916 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700917 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700918 return false;
919 }
920 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -0700921 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700922 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700923 }
jeffhao4a801a42011-09-23 13:53:40 -0700924 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700925 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700926 }
927 // Compare the package part of the descriptor string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800928 ClassHelper kh(klass1);
Elliott Hughes95572412011-12-13 18:14:20 -0800929 std::string descriptor1(kh.GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800930 kh.ChangeClass(klass2);
Elliott Hughes95572412011-12-13 18:14:20 -0800931 std::string descriptor2(kh.GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800932 return IsInSamePackage(descriptor1, descriptor2);
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700933}
934
Elliott Hughesdbb40792011-11-18 17:05:22 -0800935bool Class::IsClassClass() const {
936 Class* java_lang_Class = GetClass()->GetClass();
937 return this == java_lang_Class;
938}
939
940bool Class::IsStringClass() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800941 return this == String::GetJavaLangString();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800942}
943
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800944bool Class::IsThrowableClass() const {
945 Class* throwable = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Throwable;");
946 return throwable->IsAssignableFrom(this);
947}
948
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800949ClassLoader* Class::GetClassLoader() const {
950 return GetFieldObject<ClassLoader*>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -0700951}
952
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700953void Class::SetClassLoader(const ClassLoader* new_cl) {
954 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
Ian Rogersd81871c2011-10-03 13:57:23 -0700955 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700956}
957
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800958Method* Class::FindVirtualMethodForInterface(Method* method) {
Brian Carlstrom30b94452011-08-25 21:35:26 -0700959 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700960 DCHECK(declaring_class != NULL) << PrettyClass(this);
961 DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700962 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700963 int32_t iftable_count = GetIfTableCount();
964 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
965 for (int32_t i = 0; i < iftable_count; i++) {
966 InterfaceEntry* interface_entry = iftable->Get(i);
967 if (interface_entry->GetInterface() == declaring_class) {
968 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -0700969 }
970 }
Brian Carlstrom30b94452011-08-25 21:35:26 -0700971 return NULL;
972}
973
Ian Rogers466bb252011-10-14 03:29:56 -0700974Method* Class::FindInterfaceMethod(const StringPiece& name, const StringPiece& signature) const {
jeffhaobdb76512011-09-07 11:43:16 -0700975 // Check the current class before checking the interfaces.
Ian Rogers94c0e332012-01-18 22:11:47 -0800976 Method* method = FindDeclaredVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -0700977 if (method != NULL) {
978 return method;
979 }
980
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700981 int32_t iftable_count = GetIfTableCount();
982 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
983 for (int32_t i = 0; i < iftable_count; i++) {
984 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -0700985 if (method != NULL) {
986 return method;
987 }
988 }
989 return NULL;
990}
991
Ian Rogers7b0c5b42012-02-16 15:29:07 -0800992Method* Class::FindInterfaceMethod(const DexCache* dex_cache, uint32_t dex_method_idx) const {
993 // Check the current class before checking the interfaces.
994 Method* method = FindDeclaredVirtualMethod(dex_cache, dex_method_idx);
995 if (method != NULL) {
996 return method;
997 }
998
999 int32_t iftable_count = GetIfTableCount();
1000 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
1001 for (int32_t i = 0; i < iftable_count; i++) {
1002 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(dex_cache, dex_method_idx);
1003 if (method != NULL) {
1004 return method;
1005 }
1006 }
1007 return NULL;
1008}
1009
1010
1011Method* Class::FindDeclaredDirectMethod(const StringPiece& name, const StringPiece& signature) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001012 MethodHelper mh;
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001013 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001014 Method* method = GetDirectMethod(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001015 mh.ChangeMethod(method);
1016 if (name == mh.GetName() && signature == mh.GetSignature()) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001017 return method;
Ian Rogersb033c752011-07-20 12:22:35 -07001018 }
1019 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001020 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -07001021}
1022
Ian Rogers7b0c5b42012-02-16 15:29:07 -08001023Method* Class::FindDeclaredDirectMethod(const DexCache* dex_cache, uint32_t dex_method_idx) const {
1024 if (GetDexCache() == dex_cache) {
1025 for (size_t i = 0; i < NumDirectMethods(); ++i) {
1026 Method* method = GetDirectMethod(i);
1027 if (method->GetDexMethodIndex() == dex_method_idx) {
1028 return method;
1029 }
1030 }
1031 }
1032 return NULL;
1033}
1034
1035Method* Class::FindDirectMethod(const StringPiece& name, const StringPiece& signature) const {
1036 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001037 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001038 if (method != NULL) {
1039 return method;
1040 }
1041 }
1042 return NULL;
1043}
1044
Ian Rogers7b0c5b42012-02-16 15:29:07 -08001045Method* Class::FindDirectMethod(const DexCache* dex_cache, uint32_t dex_method_idx) const {
1046 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1047 Method* method = klass->FindDeclaredDirectMethod(dex_cache, dex_method_idx);
1048 if (method != NULL) {
1049 return method;
1050 }
1051 }
1052 return NULL;
1053}
1054
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001055Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Ian Rogers466bb252011-10-14 03:29:56 -07001056 const StringPiece& signature) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001057 MethodHelper mh;
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001058 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -07001059 Method* method = GetVirtualMethod(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001060 mh.ChangeMethod(method);
1061 if (name == mh.GetName() && signature == mh.GetSignature()) {
Ian Rogers466bb252011-10-14 03:29:56 -07001062 return method;
Ian Rogers466bb252011-10-14 03:29:56 -07001063 }
1064 }
1065 return NULL;
1066}
1067
Ian Rogers7b0c5b42012-02-16 15:29:07 -08001068Method* Class::FindDeclaredVirtualMethod(const DexCache* dex_cache, uint32_t dex_method_idx) const {
1069 if (GetDexCache() == dex_cache) {
1070 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
1071 Method* method = GetVirtualMethod(i);
1072 if (method->GetDexMethodIndex() == dex_method_idx) {
1073 return method;
1074 }
1075 }
1076 }
1077 return NULL;
1078}
1079
Ian Rogers466bb252011-10-14 03:29:56 -07001080Method* Class::FindVirtualMethod(const StringPiece& name, const StringPiece& signature) const {
1081 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1082 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
1083 if (method != NULL) {
1084 return method;
1085 }
1086 }
1087 return NULL;
1088}
1089
Ian Rogers7b0c5b42012-02-16 15:29:07 -08001090Method* Class::FindVirtualMethod(const DexCache* dex_cache, uint32_t dex_method_idx) const {
1091 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
1092 Method* method = klass->FindDeclaredVirtualMethod(dex_cache, dex_method_idx);
1093 if (method != NULL) {
1094 return method;
1095 }
1096 }
1097 return NULL;
1098}
1099
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001100Field* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001101 // Is the field in this class?
1102 // Interfaces are not relevant because they can't contain instance fields.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001103 FieldHelper fh;
Elliott Hughescdf53122011-08-19 15:46:09 -07001104 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1105 Field* f = GetInstanceField(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001106 fh.ChangeField(f);
1107 if (name == fh.GetName() && type == fh.GetTypeDescriptor()) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001108 return f;
1109 }
1110 }
1111 return NULL;
1112}
1113
Ian Rogers7b0c5b42012-02-16 15:29:07 -08001114Field* Class::FindDeclaredInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) {
1115 if (GetDexCache() == dex_cache) {
1116 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1117 Field* f = GetInstanceField(i);
1118 if (f->GetDexFieldIndex() == dex_field_idx) {
1119 return f;
1120 }
1121 }
1122 }
1123 return NULL;
1124}
1125
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001126Field* Class::FindInstanceField(const StringPiece& name, const StringPiece& 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 Rogers7b0c5b42012-02-16 15:29:07 -08001138Field* Class::FindInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) {
1139 // Is the field in this class, or any of its superclasses?
1140 // Interfaces are not relevant because they can't contain instance fields.
1141 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
1142 Field* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
1143 if (f != NULL) {
1144 return f;
1145 }
1146 }
1147 return NULL;
1148}
1149
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001150Field* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
1151 DCHECK(type != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001152 FieldHelper fh;
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001153 for (size_t i = 0; i < NumStaticFields(); ++i) {
1154 Field* f = GetStaticField(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001155 fh.ChangeField(f);
1156 if (name == fh.GetName() && type == fh.GetTypeDescriptor()) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001157 return f;
1158 }
1159 }
1160 return NULL;
1161}
1162
Ian Rogers7b0c5b42012-02-16 15:29:07 -08001163Field* Class::FindDeclaredStaticField(const DexCache* dex_cache, uint32_t dex_field_idx) {
1164 if (dex_cache == GetDexCache()) {
1165 for (size_t i = 0; i < NumStaticFields(); ++i) {
1166 Field* f = GetStaticField(i);
1167 if (f->GetDexFieldIndex() == dex_field_idx) {
1168 return f;
1169 }
1170 }
1171 }
1172 return NULL;
1173}
1174
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001175Field* Class::FindStaticField(const StringPiece& name, const StringPiece& type) {
1176 // Is the field in this class (or its interfaces), or any of its
1177 // superclasses (or their interfaces)?
Ian Rogersb067ac22011-12-13 18:05:09 -08001178 ClassHelper kh;
1179 for (Class* k = this; k != NULL; k = k->GetSuperClass()) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001180 // Is the field in this class?
Ian Rogersb067ac22011-12-13 18:05:09 -08001181 Field* f = k->FindDeclaredStaticField(name, type);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001182 if (f != NULL) {
1183 return f;
1184 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001185 // Is this field in any of this class' interfaces?
Ian Rogersb067ac22011-12-13 18:05:09 -08001186 kh.ChangeClass(k);
1187 for (uint32_t i = 0; i < kh.NumInterfaces(); ++i) {
1188 Class* interface = kh.GetInterface(i);
1189 f = interface->FindDeclaredStaticField(name, type);
1190 if (f != NULL) {
1191 return f;
1192 }
1193 }
1194 }
1195 return NULL;
1196}
1197
Ian Rogers7b0c5b42012-02-16 15:29:07 -08001198Field* Class::FindStaticField(const DexCache* dex_cache, uint32_t dex_field_idx) {
1199 ClassHelper kh;
1200 for (Class* k = this; k != NULL; k = k->GetSuperClass()) {
1201 // Is the field in this class?
1202 Field* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
1203 if (f != NULL) {
1204 return f;
1205 }
1206 // Is this field in any of this class' interfaces?
1207 kh.ChangeClass(k);
1208 for (uint32_t i = 0; i < kh.NumInterfaces(); ++i) {
1209 Class* interface = kh.GetInterface(i);
1210 f = interface->FindDeclaredStaticField(dex_cache, dex_field_idx);
1211 if (f != NULL) {
1212 return f;
1213 }
1214 }
1215 }
1216 return NULL;
1217}
1218
Ian Rogersb067ac22011-12-13 18:05:09 -08001219Field* Class::FindField(const StringPiece& name, const StringPiece& type) {
1220 // Find a field using the JLS field resolution order
1221 ClassHelper kh;
1222 for (Class* k = this; k != NULL; k = k->GetSuperClass()) {
1223 // Is the field in this class?
1224 Field* f = k->FindDeclaredInstanceField(name, type);
1225 if (f != NULL) {
1226 return f;
1227 }
1228 f = k->FindDeclaredStaticField(name, type);
1229 if (f != NULL) {
1230 return f;
1231 }
1232 // Is this field in any of this class' interfaces?
1233 kh.ChangeClass(k);
1234 for (uint32_t i = 0; i < kh.NumInterfaces(); ++i) {
1235 Class* interface = kh.GetInterface(i);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001236 f = interface->FindDeclaredStaticField(name, type);
1237 if (f != NULL) {
1238 return f;
1239 }
1240 }
1241 }
1242 return NULL;
1243}
1244
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001245Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001246 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001247 DCHECK_GE(component_count, 0);
1248 DCHECK(array_class->IsArrayClass());
Elliott Hughesb408de72011-10-04 14:35:05 -07001249
1250 size_t header_size = sizeof(Array);
1251 size_t data_size = component_count * component_size;
1252 size_t size = header_size + data_size;
1253
1254 // Check for overflow and throw OutOfMemoryError if this was an unreasonable request.
1255 size_t component_shift = sizeof(size_t) * 8 - 1 - CLZ(component_size);
1256 if (data_size >> component_shift != size_t(component_count) || size < data_size) {
1257 Thread::Current()->ThrowNewExceptionF("Ljava/lang/OutOfMemoryError;",
Elliott Hughese689d512012-01-18 23:39:47 -08001258 "%s of length %d exceeds the VM limit",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001259 PrettyDescriptor(array_class).c_str(), component_count);
Elliott Hughesb408de72011-10-04 14:35:05 -07001260 return NULL;
1261 }
1262
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001263 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1264 if (array != NULL) {
1265 DCHECK(array->IsArrayInstance());
1266 array->SetLength(component_count);
1267 }
1268 return array;
1269}
1270
1271Array* Array::Alloc(Class* array_class, int32_t component_count) {
1272 return Alloc(array_class, component_count, array_class->GetComponentSize());
1273}
1274
Elliott Hughes80609252011-09-23 17:24:51 -07001275bool Array::ThrowArrayIndexOutOfBoundsException(int32_t index) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001276 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001277 "length=%i; index=%i", length_, index);
1278 return false;
1279}
1280
1281bool Array::ThrowArrayStoreException(Object* object) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001282 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001283 "Can't store an element of type %s into an array of type %s",
1284 PrettyTypeOf(object).c_str(), PrettyTypeOf(this).c_str());
1285 return false;
1286}
1287
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001288template<typename T>
1289PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001290 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001291 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1292 return down_cast<PrimitiveArray<T>*>(raw_array);
1293}
1294
1295template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1296
1297// Explicitly instantiate all the primitive array types.
1298template class PrimitiveArray<uint8_t>; // BooleanArray
1299template class PrimitiveArray<int8_t>; // ByteArray
1300template class PrimitiveArray<uint16_t>; // CharArray
1301template class PrimitiveArray<double>; // DoubleArray
1302template class PrimitiveArray<float>; // FloatArray
1303template class PrimitiveArray<int32_t>; // IntArray
1304template class PrimitiveArray<int64_t>; // LongArray
1305template class PrimitiveArray<int16_t>; // ShortArray
1306
Ian Rogers466bb252011-10-14 03:29:56 -07001307// Explicitly instantiate Class[][]
1308template class ObjectArray<ObjectArray<Class> >;
1309
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001310// TODO: get global references for these
1311Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001312
Brian Carlstroma663ea52011-08-19 23:33:41 -07001313void String::SetClass(Class* java_lang_String) {
1314 CHECK(java_lang_String_ == NULL);
1315 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001316 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001317}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001318
Brian Carlstroma663ea52011-08-19 23:33:41 -07001319void String::ResetClass() {
1320 CHECK(java_lang_String_ != NULL);
1321 java_lang_String_ = NULL;
1322}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001323
Brian Carlstromc74255f2011-09-11 22:47:39 -07001324String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001325 return Runtime::Current()->GetInternTable()->InternWeak(this);
1326}
1327
Brian Carlstrom395520e2011-09-25 19:35:00 -07001328int32_t String::GetHashCode() {
1329 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1330 if (result == 0) {
1331 ComputeHashCode();
1332 }
1333 result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1334 DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
1335 << ToModifiedUtf8() << " " << result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001336 return result;
1337}
1338
1339int32_t String::GetLength() const {
1340 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1341 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1342 return result;
1343}
1344
1345uint16_t String::CharAt(int32_t index) const {
1346 // TODO: do we need this? Equals is the only caller, and could
1347 // bounds check itself.
1348 if (index < 0 || index >= count_) {
1349 Thread* self = Thread::Current();
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001350 self->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;",
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001351 "length=%i; index=%i", count_, index);
1352 return 0;
1353 }
1354 return GetCharArray()->Get(index + GetOffset());
1355}
1356
1357String* String::AllocFromUtf16(int32_t utf16_length,
1358 const uint16_t* utf16_data_in,
1359 int32_t hash_code) {
Jesse Wilson25e79a52011-11-18 15:31:58 -05001360 CHECK(utf16_data_in != NULL || utf16_length == 0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001361 String* string = Alloc(GetJavaLangString(), utf16_length);
Elliott Hughesb51036c2011-10-12 23:49:11 -07001362 if (string == NULL) {
1363 return NULL;
1364 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001365 // TODO: use 16-bit wide memset variant
1366 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
Elliott Hughesb51036c2011-10-12 23:49:11 -07001367 if (array == NULL) {
1368 return NULL;
1369 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001370 for (int i = 0; i < utf16_length; i++) {
1371 array->Set(i, utf16_data_in[i]);
1372 }
1373 if (hash_code != 0) {
1374 string->SetHashCode(hash_code);
1375 } else {
1376 string->ComputeHashCode();
1377 }
1378 return string;
1379}
1380
1381String* String::AllocFromModifiedUtf8(const char* utf) {
Ian Rogers48601312011-12-07 16:45:19 -08001382 if (utf == NULL) {
1383 return NULL;
1384 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001385 size_t char_count = CountModifiedUtf8Chars(utf);
1386 return AllocFromModifiedUtf8(char_count, utf);
1387}
1388
1389String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1390 const char* utf8_data_in) {
1391 String* string = Alloc(GetJavaLangString(), utf16_length);
Elliott Hughesb51036c2011-10-12 23:49:11 -07001392 if (string == NULL) {
1393 return NULL;
1394 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001395 uint16_t* utf16_data_out =
1396 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1397 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1398 string->ComputeHashCode();
1399 return string;
1400}
1401
1402String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001403 SirtRef<CharArray> array(CharArray::Alloc(utf16_length));
1404 if (array.get() == NULL) {
Elliott Hughesb51036c2011-10-12 23:49:11 -07001405 return NULL;
1406 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001407 return Alloc(java_lang_String, array.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001408}
1409
1410String* String::Alloc(Class* java_lang_String, CharArray* array) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001411 SirtRef<CharArray> array_ref(array); // hold reference in case AllocObject causes GC
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001412 String* string = down_cast<String*>(java_lang_String->AllocObject());
Elliott Hughesb51036c2011-10-12 23:49:11 -07001413 if (string == NULL) {
1414 return NULL;
1415 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001416 string->SetArray(array);
1417 string->SetCount(array->GetLength());
1418 return string;
1419}
1420
1421bool String::Equals(const String* that) const {
1422 if (this == that) {
1423 // Quick reference equality test
1424 return true;
1425 } else if (that == NULL) {
1426 // Null isn't an instanceof anything
1427 return false;
1428 } else if (this->GetLength() != that->GetLength()) {
1429 // Quick length inequality test
1430 return false;
1431 } else {
Elliott Hughes20cde902011-10-04 17:37:27 -07001432 // Note: don't short circuit on hash code as we're presumably here as the
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001433 // hash code was already equal
1434 for (int32_t i = 0; i < that->GetLength(); ++i) {
1435 if (this->CharAt(i) != that->CharAt(i)) {
1436 return false;
1437 }
1438 }
1439 return true;
1440 }
1441}
1442
Elliott Hughes5d78d392011-12-13 16:53:05 -08001443bool String::Equals(const uint16_t* that_chars, int32_t that_offset, int32_t that_length) const {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001444 if (this->GetLength() != that_length) {
1445 return false;
1446 } else {
1447 for (int32_t i = 0; i < that_length; ++i) {
1448 if (this->CharAt(i) != that_chars[that_offset + i]) {
1449 return false;
1450 }
1451 }
1452 return true;
1453 }
1454}
1455
1456bool String::Equals(const char* modified_utf8) const {
1457 for (int32_t i = 0; i < GetLength(); ++i) {
1458 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1459 if (ch == '\0' || ch != CharAt(i)) {
1460 return false;
1461 }
1462 }
1463 return *modified_utf8 == '\0';
1464}
1465
1466bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001467 if (modified_utf8.size() != GetLength()) {
1468 return false;
1469 }
1470 const char* p = modified_utf8.data();
1471 for (int32_t i = 0; i < GetLength(); ++i) {
1472 uint16_t ch = GetUtf16FromUtf8(&p);
1473 if (ch != CharAt(i)) {
1474 return false;
1475 }
1476 }
1477 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001478}
1479
1480// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1481std::string String::ToModifiedUtf8() const {
1482 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1483 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1484 std::string result(byte_count, char(0));
1485 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1486 return result;
1487}
1488
Ian Rogers1c5eb702012-02-01 09:18:34 -08001489void Throwable::SetCause(Throwable* cause) {
1490 CHECK(cause != NULL);
1491 CHECK(cause != this);
1492 CHECK(GetFieldObject<Throwable*>(OFFSET_OF_OBJECT_MEMBER(Throwable, cause_), false) == NULL);
1493 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Throwable, cause_), cause, false);
1494}
1495
Ian Rogers466bb252011-10-14 03:29:56 -07001496bool Throwable::IsCheckedException() const {
1497 Class* error = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Error;");
1498 if (InstanceOf(error)) {
1499 return false;
1500 }
1501 Class* jlre = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/RuntimeException;");
1502 return !InstanceOf(jlre);
1503}
1504
Ian Rogers9074b992011-10-26 17:41:55 -07001505std::string Throwable::Dump() const {
Ian Rogers09f6b562012-01-31 21:58:52 -08001506 std::string result(PrettyTypeOf(this));
1507 result += ": ";
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001508 String* msg = GetDetailMessage();
Ian Rogers09f6b562012-01-31 21:58:52 -08001509 if (msg != NULL) {
1510 result += msg->ToModifiedUtf8();
Ian Rogers9074b992011-10-26 17:41:55 -07001511 }
Ian Rogers09f6b562012-01-31 21:58:52 -08001512 result += "\n";
1513 Object* stack_state = GetStackState();
1514 // check stack state isn't missing or corrupt
1515 if (stack_state != NULL && stack_state->IsObjectArray()) {
1516 // Decode the internal stack trace into the depth and method trace
1517 ObjectArray<Object>* method_trace = down_cast<ObjectArray<Object>*>(stack_state);
1518 int32_t depth = method_trace->GetLength() - 1;
1519 for (int32_t i = 0; i < depth; ++i) {
1520 Method* method = down_cast<Method*>(method_trace->Get(i));
1521 result += " at ";
1522 result += PrettyMethod(method, true);
1523 result += "\n";
1524 }
Ian Rogers9074b992011-10-26 17:41:55 -07001525 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08001526 Throwable* cause = GetFieldObject<Throwable*>(OFFSET_OF_OBJECT_MEMBER(Throwable, cause_), false);
Ian Rogersc8b306f2012-02-17 21:34:44 -08001527 if (cause != NULL && cause != this) { // Constructor makes cause == this by default.
Ian Rogers1c5eb702012-02-01 09:18:34 -08001528 result += "Caused by: ";
1529 result += cause->Dump();
1530 }
Ian Rogers9074b992011-10-26 17:41:55 -07001531 return result;
1532}
1533
Ian Rogers5167c972012-02-03 10:41:20 -08001534
1535Class* Throwable::java_lang_Throwable_ = NULL;
1536
1537void Throwable::SetClass(Class* java_lang_Throwable) {
1538 CHECK(java_lang_Throwable_ == NULL);
1539 CHECK(java_lang_Throwable != NULL);
1540 java_lang_Throwable_ = java_lang_Throwable;
1541}
1542
1543void Throwable::ResetClass() {
1544 CHECK(java_lang_Throwable_ != NULL);
1545 java_lang_Throwable_ = NULL;
1546}
1547
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001548Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1549
1550void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1551 CHECK(java_lang_StackTraceElement_ == NULL);
1552 CHECK(java_lang_StackTraceElement != NULL);
1553 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1554}
1555
1556void StackTraceElement::ResetClass() {
1557 CHECK(java_lang_StackTraceElement_ != NULL);
1558 java_lang_StackTraceElement_ = NULL;
1559}
1560
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001561StackTraceElement* StackTraceElement::Alloc(String* declaring_class,
1562 String* method_name,
1563 String* file_name,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001564 int32_t line_number) {
1565 StackTraceElement* trace =
1566 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1567 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1568 const_cast<String*>(declaring_class), false);
1569 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1570 const_cast<String*>(method_name), false);
1571 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1572 const_cast<String*>(file_name), false);
1573 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1574 line_number, false);
1575 return trace;
1576}
1577
Elliott Hughes1f359b02011-07-17 14:27:17 -07001578static const char* kClassStatusNames[] = {
1579 "Error",
1580 "NotReady",
1581 "Idx",
1582 "Loaded",
1583 "Resolved",
1584 "Verifying",
1585 "Verified",
1586 "Initializing",
1587 "Initialized"
1588};
1589std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1590 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001591 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001592 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001593 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001594 }
1595 return os;
1596}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001597
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001598} // namespace art