blob: 6be1136d893813a506392060770f928ec966b0f7 [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"
Elliott Hughes68e76522011-10-05 13:22:16 -070037#include "stack.h"
Ian Rogers0571d352011-11-03 19:51:38 -070038#include "utils.h"
Carl Shapiro3ee755d2011-06-28 12:11:04 -070039
40namespace art {
41
Elliott Hughesdbb40792011-11-18 17:05:22 -080042String* Object::AsString() {
43 DCHECK(GetClass()->IsStringClass());
44 return down_cast<String*>(this);
45}
46
Elliott Hughes081be7f2011-09-18 16:50:26 -070047Object* Object::Clone() {
48 Class* c = GetClass();
49 DCHECK(!c->IsClassClass());
50
51 // Object::SizeOf gets the right size even if we're an array.
52 // Using c->AllocObject() here would be wrong.
53 size_t num_bytes = SizeOf();
Brian Carlstrom40381fb2011-10-19 14:13:40 -070054 SirtRef<Object> copy(Heap::AllocObject(c, num_bytes));
55 if (copy.get() == NULL) {
Elliott Hughes081be7f2011-09-18 16:50:26 -070056 return NULL;
57 }
58
59 // Copy instance data. We assume memcpy copies by words.
60 // TODO: expose and use move32.
61 byte* src_bytes = reinterpret_cast<byte*>(this);
Brian Carlstrom40381fb2011-10-19 14:13:40 -070062 byte* dst_bytes = reinterpret_cast<byte*>(copy.get());
Elliott Hughes081be7f2011-09-18 16:50:26 -070063 size_t offset = sizeof(Object);
64 memcpy(dst_bytes + offset, src_bytes + offset, num_bytes - offset);
65
Elliott Hughes20cde902011-10-04 17:37:27 -070066 if (c->IsFinalizable()) {
Ian Rogers5d4bdc22011-11-02 22:15:43 -070067 Heap::AddFinalizerReference(Thread::Current(), copy.get());
Elliott Hughes20cde902011-10-04 17:37:27 -070068 }
Elliott Hughes081be7f2011-09-18 16:50:26 -070069
Brian Carlstrom40381fb2011-10-19 14:13:40 -070070 return copy.get();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070071}
72
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070073uint32_t Object::GetThinLockId() {
74 return Monitor::GetThinLockId(monitor_);
Elliott Hughes5f791332011-09-15 17:45:30 -070075}
76
77void Object::MonitorEnter(Thread* thread) {
78 Monitor::MonitorEnter(thread, this);
79}
80
Ian Rogersff1ed472011-09-20 13:46:24 -070081bool Object::MonitorExit(Thread* thread) {
82 return Monitor::MonitorExit(thread, this);
Elliott Hughes5f791332011-09-15 17:45:30 -070083}
84
85void Object::Notify() {
86 Monitor::Notify(Thread::Current(), this);
87}
88
89void Object::NotifyAll() {
90 Monitor::NotifyAll(Thread::Current(), this);
91}
92
93void Object::Wait(int64_t ms, int32_t ns) {
94 Monitor::Wait(Thread::Current(), this, ms, ns, true);
95}
96
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070097// TODO: get global references for these
98Class* Field::java_lang_reflect_Field_ = NULL;
99
100void Field::SetClass(Class* java_lang_reflect_Field) {
101 CHECK(java_lang_reflect_Field_ == NULL);
102 CHECK(java_lang_reflect_Field != NULL);
103 java_lang_reflect_Field_ = java_lang_reflect_Field;
104}
105
106void Field::ResetClass() {
107 CHECK(java_lang_reflect_Field_ != NULL);
108 java_lang_reflect_Field_ = NULL;
109}
110
Ian Rogers0571d352011-11-03 19:51:38 -0700111void Field::SetOffset(MemberOffset num_bytes) {
112 DCHECK(GetDeclaringClass()->IsLoaded() || GetDeclaringClass()->IsErroneous());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800113#if 0 // TODO enable later in boot and under !NDEBUG
114 FieldHelper fh(this);
115 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Ian Rogers0571d352011-11-03 19:51:38 -0700116 if (type == Primitive::kPrimDouble || type == Primitive::kPrimLong) {
117 DCHECK_ALIGNED(num_bytes.Uint32Value(), 8);
118 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800119#endif
Ian Rogers0571d352011-11-03 19:51:38 -0700120 SetField32(OFFSET_OF_OBJECT_MEMBER(Field, offset_), num_bytes.Uint32Value(), false);
121}
122
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700123uint32_t Field::Get32(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700124 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700125 if (IsStatic()) {
126 object = declaring_class_;
127 }
128 return object->GetField32(GetOffset(), IsVolatile());
Elliott Hughes68f4fa02011-08-21 10:46:59 -0700129}
130
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700131void Field::Set32(Object* object, uint32_t new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700132 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700133 if (IsStatic()) {
134 object = declaring_class_;
135 }
136 object->SetField32(GetOffset(), new_value, IsVolatile());
137}
138
139uint64_t Field::Get64(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700140 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700141 if (IsStatic()) {
142 object = declaring_class_;
143 }
144 return object->GetField64(GetOffset(), IsVolatile());
145}
146
147void Field::Set64(Object* object, uint64_t new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700148 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700149 if (IsStatic()) {
150 object = declaring_class_;
151 }
152 object->SetField64(GetOffset(), new_value, IsVolatile());
153}
154
155Object* Field::GetObj(const Object* object) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700156 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700157 if (IsStatic()) {
158 object = declaring_class_;
159 }
160 return object->GetFieldObject<Object*>(GetOffset(), IsVolatile());
161}
162
163void Field::SetObj(Object* object, const Object* new_value) const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700164 CHECK((object == NULL) == IsStatic()) << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700165 if (IsStatic()) {
166 object = declaring_class_;
167 }
168 object->SetFieldObject(GetOffset(), new_value, IsVolatile());
169}
170
171bool Field::GetBoolean(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800172 DCHECK_EQ(Primitive::kPrimBoolean, FieldHelper(this).GetTypeAsPrimitiveType())
173 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700174 return Get32(object);
175}
176
177void Field::SetBoolean(Object* object, bool z) 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 Set32(object, z);
181}
182
183int8_t Field::GetByte(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800184 DCHECK_EQ(Primitive::kPrimByte, FieldHelper(this).GetTypeAsPrimitiveType())
185 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700186 return Get32(object);
187}
188
189void Field::SetByte(Object* object, int8_t b) 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 Set32(object, b);
193}
194
195uint16_t Field::GetChar(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800196 DCHECK_EQ(Primitive::kPrimChar, FieldHelper(this).GetTypeAsPrimitiveType())
197 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700198 return Get32(object);
199}
200
201void Field::SetChar(Object* object, uint16_t c) 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 Set32(object, c);
205}
206
Ian Rogers466bb252011-10-14 03:29:56 -0700207int16_t Field::GetShort(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800208 DCHECK_EQ(Primitive::kPrimShort, FieldHelper(this).GetTypeAsPrimitiveType())
209 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700210 return Get32(object);
211}
212
Ian Rogers466bb252011-10-14 03:29:56 -0700213void Field::SetShort(Object* object, int16_t s) 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 Set32(object, s);
217}
218
219int32_t Field::GetInt(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800220 DCHECK_EQ(Primitive::kPrimInt, FieldHelper(this).GetTypeAsPrimitiveType())
221 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700222 return Get32(object);
223}
224
225void Field::SetInt(Object* object, int32_t i) 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 Set32(object, i);
229}
230
231int64_t Field::GetLong(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800232 DCHECK_EQ(Primitive::kPrimLong, FieldHelper(this).GetTypeAsPrimitiveType())
233 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700234 return Get64(object);
235}
236
237void Field::SetLong(Object* object, int64_t j) 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 Set64(object, j);
241}
242
243float Field::GetFloat(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800244 DCHECK_EQ(Primitive::kPrimFloat, FieldHelper(this).GetTypeAsPrimitiveType())
245 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700246 JValue float_bits;
247 float_bits.i = Get32(object);
248 return float_bits.f;
249}
250
251void Field::SetFloat(Object* object, float f) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800252 DCHECK_EQ(Primitive::kPrimFloat, FieldHelper(this).GetTypeAsPrimitiveType())
253 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254 JValue float_bits;
255 float_bits.f = f;
256 Set32(object, float_bits.i);
257}
258
259double Field::GetDouble(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800260 DCHECK_EQ(Primitive::kPrimDouble, FieldHelper(this).GetTypeAsPrimitiveType())
261 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700262 JValue double_bits;
263 double_bits.j = Get64(object);
264 return double_bits.d;
265}
266
267void Field::SetDouble(Object* object, double d) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800268 DCHECK_EQ(Primitive::kPrimDouble, FieldHelper(this).GetTypeAsPrimitiveType())
269 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 JValue double_bits;
271 double_bits.d = d;
272 Set64(object, double_bits.j);
273}
274
275Object* Field::GetObject(const Object* object) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800276 DCHECK_EQ(Primitive::kPrimNot, FieldHelper(this).GetTypeAsPrimitiveType())
277 << PrettyField(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700278 return GetObj(object);
279}
280
281void Field::SetObject(Object* object, const Object* l) 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 SetObj(object, l);
285}
286
287// TODO: get global references for these
Elliott Hughes80609252011-09-23 17:24:51 -0700288Class* Method::java_lang_reflect_Constructor_ = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289Class* Method::java_lang_reflect_Method_ = NULL;
290
Elliott Hughes80609252011-09-23 17:24:51 -0700291void Method::SetClasses(Class* java_lang_reflect_Constructor, Class* java_lang_reflect_Method) {
292 CHECK(java_lang_reflect_Constructor_ == NULL);
293 CHECK(java_lang_reflect_Constructor != NULL);
294 java_lang_reflect_Constructor_ = java_lang_reflect_Constructor;
295
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700296 CHECK(java_lang_reflect_Method_ == NULL);
297 CHECK(java_lang_reflect_Method != NULL);
298 java_lang_reflect_Method_ = java_lang_reflect_Method;
299}
300
Elliott Hughes80609252011-09-23 17:24:51 -0700301void Method::ResetClasses() {
302 CHECK(java_lang_reflect_Constructor_ != NULL);
303 java_lang_reflect_Constructor_ = NULL;
304
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305 CHECK(java_lang_reflect_Method_ != NULL);
306 java_lang_reflect_Method_ = NULL;
307}
308
Elliott Hughes418d20f2011-09-22 14:00:39 -0700309Class* ExtractNextClassFromSignature(ClassLinker* class_linker, const ClassLoader* cl, const char*& p) {
310 if (*p == '[') {
311 // Something like "[[[Ljava/lang/String;".
312 const char* start = p;
313 while (*p == '[') {
314 ++p;
315 }
316 if (*p == 'L') {
317 while (*p != ';') {
318 ++p;
319 }
320 }
321 ++p; // Either the ';' or the primitive type.
322
Brian Carlstromaded5f72011-10-07 17:15:04 -0700323 std::string descriptor(start, (p - start));
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800324 return class_linker->FindClass(descriptor.c_str(), cl);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700325 } else if (*p == 'L') {
326 const char* start = p;
327 while (*p != ';') {
328 ++p;
329 }
330 ++p;
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800331 std::string descriptor(start, (p - start));
332 return class_linker->FindClass(descriptor.c_str(), cl);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700333 } else {
334 return class_linker->FindPrimitiveClass(*p++);
335 }
336}
337
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338ObjectArray<String>* Method::GetDexCacheStrings() const {
339 return GetFieldObject<ObjectArray<String>*>(
340 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_), false);
341}
342
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700343void Method::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
344 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_strings_),
345 new_dex_cache_strings, false);
346}
347
348ObjectArray<Class>* Method::GetDexCacheResolvedTypes() const {
349 return GetFieldObject<ObjectArray<Class>*>(
350 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_), false);
351}
352
353void Method::SetDexCacheResolvedTypes(ObjectArray<Class>* new_dex_cache_classes) {
354 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_types_),
355 new_dex_cache_classes, false);
356}
357
358ObjectArray<Method>* Method::GetDexCacheResolvedMethods() const {
359 return GetFieldObject<ObjectArray<Method>*>(
360 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_), false);
361}
362
363void Method::SetDexCacheResolvedMethods(ObjectArray<Method>* new_dex_cache_methods) {
364 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_resolved_methods_),
365 new_dex_cache_methods, false);
366}
367
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368CodeAndDirectMethods* Method::GetDexCacheCodeAndDirectMethods() const {
369 return GetFieldPtr<CodeAndDirectMethods*>(
370 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
371 false);
372}
373
374void Method::SetDexCacheCodeAndDirectMethods(CodeAndDirectMethods* new_value) {
375 SetFieldPtr<CodeAndDirectMethods*>(
376 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_code_and_direct_methods_),
377 new_value, false);
378}
379
380ObjectArray<StaticStorageBase>* Method::GetDexCacheInitializedStaticStorage() const {
381 return GetFieldObject<ObjectArray<StaticStorageBase>*>(
382 OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
383 false);
384}
385
386void Method::SetDexCacheInitializedStaticStorage(ObjectArray<StaticStorageBase>* new_value) {
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700387 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Method, dex_cache_initialized_static_storage_),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700388 new_value, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389}
390
391size_t Method::NumArgRegisters(const StringPiece& shorty) {
392 CHECK_LE(1, shorty.length());
393 uint32_t num_registers = 0;
394 for (int i = 1; i < shorty.length(); ++i) {
395 char ch = shorty[i];
396 if (ch == 'D' || ch == 'J') {
397 num_registers += 2;
398 } else {
399 num_registers += 1;
Brian Carlstromb63ec392011-08-27 17:38:27 -0700400 }
401 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700402 return num_registers;
403}
404
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800405bool Method::IsProxyMethod() const {
406 return GetDeclaringClass()->IsProxyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407}
408
Ian Rogers466bb252011-10-14 03:29:56 -0700409Method* Method::FindOverriddenMethod() const {
410 if (IsStatic()) {
411 return NULL;
412 }
413 Class* declaring_class = GetDeclaringClass();
414 Class* super_class = declaring_class->GetSuperClass();
415 uint16_t method_index = GetMethodIndex();
416 ObjectArray<Method>* super_class_vtable = super_class->GetVTable();
417 Method* result = NULL;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800418 // Did this method override a super class method? If so load the result from the super class'
419 // vtable
Ian Rogers466bb252011-10-14 03:29:56 -0700420 if (super_class_vtable != NULL && method_index < super_class_vtable->GetLength()) {
421 result = super_class_vtable->Get(method_index);
422 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800423 // Method didn't override superclass method so search interfaces
424 MethodHelper mh(this);
425 MethodHelper interface_mh;
426 ObjectArray<InterfaceEntry>* iftable = GetDeclaringClass()->GetIfTable();
427 for (int32_t i = 0; i < iftable->GetLength() && result == NULL; i++) {
428 InterfaceEntry* entry = iftable->Get(i);
429 Class* interface = entry->GetInterface();
430 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
431 Method* interface_method = interface->GetVirtualMethod(j);
432 interface_mh.ChangeMethod(interface_method);
433 if (mh.HasSameNameAndSignature(&interface_mh)) {
434 result = interface_method;
435 break;
436 }
437 }
Ian Rogers466bb252011-10-14 03:29:56 -0700438 }
439 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800440#ifndef NDEBUG
441 MethodHelper result_mh(result);
442 DCHECK(result == NULL || MethodHelper(this).HasSameNameAndSignature(&result_mh));
443#endif
Ian Rogers466bb252011-10-14 03:29:56 -0700444 return result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700445}
446
Ian Rogersbdb03912011-09-14 00:55:44 -0700447uint32_t Method::ToDexPC(const uintptr_t pc) const {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700448 const uint32_t* mapping_table = GetMappingTable();
Ian Rogersbdb03912011-09-14 00:55:44 -0700449 if (mapping_table == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800450 DCHECK(IsNative() || IsCalleeSaveMethod() || IsProxyMethod()) << PrettyMethod(this);
Ian Rogers67375ac2011-09-14 00:55:44 -0700451 return DexFile::kDexNoIndex; // Special no mapping case
Ian Rogersbdb03912011-09-14 00:55:44 -0700452 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700453 size_t mapping_table_length = GetMappingTableLength();
jeffhao26c0a1a2012-01-17 16:28:33 -0800454 const void* code_offset;
455 if (Runtime::Current()->IsMethodTracingActive() &&
456 Runtime::Current()->GetTracer()->GetSavedCodeFromMap(this) != NULL) {
457 code_offset = Runtime::Current()->GetTracer()->GetSavedCodeFromMap(this);
458 } else {
459 code_offset = GetCode();
460 }
jeffhaoe343b762011-12-05 16:36:44 -0800461 uint32_t sought_offset = pc - reinterpret_cast<uintptr_t>(code_offset);
Ian Rogersbdb03912011-09-14 00:55:44 -0700462 uint32_t best_offset = 0;
463 uint32_t best_dex_offset = 0;
464 for (size_t i = 0; i < mapping_table_length; i += 2) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700465 uint32_t map_offset = mapping_table[i];
466 uint32_t map_dex_offset = mapping_table[i + 1];
Ian Rogersbdb03912011-09-14 00:55:44 -0700467 if (map_offset == sought_offset) {
468 best_offset = map_offset;
469 best_dex_offset = map_dex_offset;
470 break;
471 }
472 if (map_offset < sought_offset && map_offset > best_offset) {
473 best_offset = map_offset;
474 best_dex_offset = map_dex_offset;
475 }
476 }
477 return best_dex_offset;
478}
479
480uintptr_t Method::ToNativePC(const uint32_t dex_pc) const {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700481 const uint32_t* mapping_table = GetMappingTable();
Ian Rogersbdb03912011-09-14 00:55:44 -0700482 if (mapping_table == NULL) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700483 DCHECK_EQ(dex_pc, 0U);
Ian Rogersbdb03912011-09-14 00:55:44 -0700484 return 0; // Special no mapping/pc == 0 case
485 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700486 size_t mapping_table_length = GetMappingTableLength();
Ian Rogersbdb03912011-09-14 00:55:44 -0700487 for (size_t i = 0; i < mapping_table_length; i += 2) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700488 uint32_t map_offset = mapping_table[i];
489 uint32_t map_dex_offset = mapping_table[i + 1];
Ian Rogersbdb03912011-09-14 00:55:44 -0700490 if (map_dex_offset == dex_pc) {
jeffhao2692b572011-12-16 15:42:28 -0800491 if (Runtime::Current()->IsMethodTracingActive()) {
492 Trace* tracer = Runtime::Current()->GetTracer();
493 return reinterpret_cast<uintptr_t>(tracer->GetSavedCodeFromMap(this)) + map_offset;
jeffhaoe343b762011-12-05 16:36:44 -0800494 } else {
495 return reinterpret_cast<uintptr_t>(GetCode()) + map_offset;
496 }
Ian Rogersbdb03912011-09-14 00:55:44 -0700497 }
498 }
499 LOG(FATAL) << "Looking up Dex PC not contained in method";
500 return 0;
501}
502
503uint32_t Method::FindCatchBlock(Class* exception_type, uint32_t dex_pc) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800504 MethodHelper mh(this);
505 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Ian Rogersbdb03912011-09-14 00:55:44 -0700506 // Iterate over the catch handlers associated with dex_pc
Ian Rogers0571d352011-11-03 19:51:38 -0700507 for (CatchHandlerIterator it(*code_item, dex_pc); it.HasNext(); it.Next()) {
508 uint16_t iter_type_idx = it.GetHandlerTypeIndex();
Ian Rogersbdb03912011-09-14 00:55:44 -0700509 // Catch all case
Ian Rogers0571d352011-11-03 19:51:38 -0700510 if (iter_type_idx == DexFile::kDexNoIndex16) {
511 return it.GetHandlerAddress();
Ian Rogersbdb03912011-09-14 00:55:44 -0700512 }
513 // Does this catch exception type apply?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800514 Class* iter_exception_type = mh.GetDexCacheResolvedType(iter_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -0700515 if (iter_exception_type == NULL) {
516 // The verifier should take care of resolving all exception classes early
517 LOG(WARNING) << "Unresolved exception class when finding catch block: "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800518 << mh.GetTypeDescriptorFromTypeIdx(iter_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -0700519 } else if (iter_exception_type->IsAssignableFrom(exception_type)) {
Ian Rogers0571d352011-11-03 19:51:38 -0700520 return it.GetHandlerAddress();
Ian Rogersbdb03912011-09-14 00:55:44 -0700521 }
522 }
523 // Handler not found
524 return DexFile::kDexNoIndex;
525}
526
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700527void Method::Invoke(Thread* self, Object* receiver, byte* args, JValue* result) const {
528 // Push a transition back into managed code onto the linked list in thread.
529 CHECK_EQ(Thread::kRunnable, self->GetState());
530 NativeToManagedRecord record;
531 self->PushNativeToManagedRecord(&record);
532
533 // Call the invoke stub associated with the method.
534 // Pass everything as arguments.
535 const Method::InvokeStub* stub = GetInvokeStub();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700536
537 bool have_executable_code = (GetCode() != NULL);
538#if !defined(__arm__)
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700539 // Currently we can only compile non-native methods for ARM.
540 have_executable_code = IsNative();
Elliott Hughes1240dad2011-09-09 16:24:50 -0700541#endif
542
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500543 if (Runtime::Current()->IsStarted() && have_executable_code && stub != NULL) {
Elliott Hughes9f865372011-10-11 15:04:19 -0700544 bool log = false;
545 if (log) {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800546 LOG(INFO) << StringPrintf("invoking %s code=%p stub=%p",
547 PrettyMethod(this).c_str(), GetCode(), stub);
Elliott Hughes9f865372011-10-11 15:04:19 -0700548 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700549 (*stub)(this, receiver, self, args, result);
Elliott Hughes9f865372011-10-11 15:04:19 -0700550 if (log) {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800551 LOG(INFO) << StringPrintf("returned %s code=%p stub=%p",
552 PrettyMethod(this).c_str(), GetCode(), stub);
Elliott Hughes9f865372011-10-11 15:04:19 -0700553 }
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700554 } else {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800555 LOG(INFO) << StringPrintf("not invoking %s code=%p stub=%p started=%s",
556 PrettyMethod(this).c_str(), GetCode(), stub,
557 Runtime::Current()->IsStarted() ? "true" : "false");
Elliott Hughesf5ecf062011-09-06 17:37:59 -0700558 if (result != NULL) {
559 result->j = 0;
560 }
561 }
562
563 // Pop transition.
564 self->PopNativeToManagedRecord(record);
565}
566
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700567bool Method::IsRegistered() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700568 void* native_method = GetFieldPtr<void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_), false);
Ian Rogers169c9a72011-11-13 20:13:17 -0800569 void* jni_stub = Runtime::Current()->GetJniDlsymLookupStub()->GetData();
Brian Carlstrom16192862011-09-12 17:50:06 -0700570 return native_method != jni_stub;
571}
572
573void Method::RegisterNative(const void* native_method) {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700574 CHECK(IsNative()) << PrettyMethod(this);
575 CHECK(native_method != NULL) << PrettyMethod(this);
Brian Carlstrom16192862011-09-12 17:50:06 -0700576 SetFieldPtr<const void*>(OFFSET_OF_OBJECT_MEMBER(Method, native_method_),
577 native_method, false);
578}
579
580void Method::UnregisterNative() {
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700581 CHECK(IsNative()) << PrettyMethod(this);
Brian Carlstrom16192862011-09-12 17:50:06 -0700582 // restore stub to lookup native pointer via dlsym
Ian Rogers169c9a72011-11-13 20:13:17 -0800583 RegisterNative(Runtime::Current()->GetJniDlsymLookupStub()->GetData());
Brian Carlstrom16192862011-09-12 17:50:06 -0700584}
585
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700586void Class::SetStatus(Status new_status) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700587 CHECK(new_status > GetStatus() || new_status == kStatusError || !Runtime::Current()->IsStarted())
588 << PrettyClass(this) << " " << GetStatus() << " -> " << new_status;
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700589 CHECK(sizeof(Status) == sizeof(uint32_t)) << PrettyClass(this);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -0800590 if (new_status == kStatusError) {
591 CHECK_NE(GetStatus(), kStatusError) << PrettyClass(this);
592
593 // stash current exception
594 Thread* self = Thread::Current();
595 SirtRef<Throwable> exception(self->GetException());
596 CHECK(exception.get() != NULL);
597
598 // clear exception to call FindSystemClass
599 self->ClearException();
600 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
601 Class* eiie_class = class_linker->FindSystemClass("Ljava/lang/ExceptionInInitializerError;");
602 CHECK(!self->IsExceptionPending());
603
604 // only verification errors, not initialization problems, should set a verify error.
605 // this is to ensure that ThrowEarlierClassFailure will throw NoClassDefFoundError in that case.
606 Class* exception_class = exception->GetClass();
607 if (!eiie_class->IsAssignableFrom(exception_class)) {
608 SetVerifyErrorClass(exception_class);
609 }
610
611 // restore exception
612 self->SetException(exception.get());
613 }
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700614 return SetField32(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status, false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700615}
616
617DexCache* Class::GetDexCache() const {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700618 return GetFieldObject<DexCache*>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), false);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700619}
620
621void Class::SetDexCache(DexCache* new_dex_cache) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700622 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache, false);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700623}
624
Brian Carlstrom1f870082011-08-23 16:02:11 -0700625Object* Class::AllocObject() {
Brian Carlstrom96a253a2011-10-27 18:38:10 -0700626 DCHECK(!IsArrayClass()) << PrettyClass(this);
Ian Rogers28ad40d2011-10-27 15:19:26 -0700627 DCHECK(IsInstantiable()) << PrettyClass(this);
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500628 // TODO: decide whether we want this check. It currently fails during bootstrap.
629 // DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
Brian Carlstrom96a253a2011-10-27 18:38:10 -0700630 DCHECK_GE(this->object_size_, sizeof(Object));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700631 return Heap::AllocObject(this, this->object_size_);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700632}
633
Ian Rogers0571d352011-11-03 19:51:38 -0700634void Class::SetClassSize(size_t new_class_size) {
635 DCHECK_GE(new_class_size, GetClassSize()) << " class=" << PrettyTypeOf(this);
636 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size, false);
637}
638
Ian Rogersd418eda2012-01-30 12:14:28 -0800639// Return the class' name. The exact format is bizarre, but it's the specified behavior for
640// Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
641// but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
642// slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
643String* Class::ComputeName() {
644 String* name = GetName();
645 if (name != NULL) {
646 return name;
647 }
648 std::string descriptor(ClassHelper(this).GetDescriptor());
649 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
650 // The descriptor indicates that this is the class for
651 // a primitive type; special-case the return value.
652 const char* c_name = NULL;
653 switch (descriptor[0]) {
654 case 'Z': c_name = "boolean"; break;
655 case 'B': c_name = "byte"; break;
656 case 'C': c_name = "char"; break;
657 case 'S': c_name = "short"; break;
658 case 'I': c_name = "int"; break;
659 case 'J': c_name = "long"; break;
660 case 'F': c_name = "float"; break;
661 case 'D': c_name = "double"; break;
662 case 'V': c_name = "void"; break;
663 default:
664 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
665 }
666 name = String::AllocFromModifiedUtf8(c_name);
667 } else {
668 // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
669 // components.
670 if (descriptor.size() > 2 && descriptor[0] == 'L' && descriptor[descriptor.size() - 1] == ';') {
671 descriptor.erase(0, 1);
672 descriptor.erase(descriptor.size() - 1);
673 }
674 std::replace(descriptor.begin(), descriptor.end(), '/', '.');
675 name = String::AllocFromModifiedUtf8(descriptor.c_str());
676 }
677 SetName(name);
678 return name;
679}
680
Elliott Hughes4681c802011-09-25 18:04:37 -0700681void Class::DumpClass(std::ostream& os, int flags) const {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700682 if ((flags & kDumpClassFullDetail) == 0) {
683 os << PrettyClass(this);
684 if ((flags & kDumpClassClassLoader) != 0) {
685 os << ' ' << GetClassLoader();
686 }
687 if ((flags & kDumpClassInitialized) != 0) {
688 os << ' ' << GetStatus();
689 }
Elliott Hughese0918552011-10-28 17:18:29 -0700690 os << "\n";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700691 return;
692 }
693
694 Class* super = GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800695 ClassHelper kh(this);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700696 os << "----- " << (IsInterface() ? "interface" : "class") << " "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800697 << "'" << kh.GetDescriptor() << "' cl=" << GetClassLoader() << " -----\n",
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700698 os << " objectSize=" << SizeOf() << " "
699 << "(" << (super != NULL ? super->SizeOf() : -1) << " from super)\n",
700 os << StringPrintf(" access=0x%04x.%04x\n",
701 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
702 if (super != NULL) {
703 os << " super='" << PrettyClass(super) << "' (cl=" << super->GetClassLoader() << ")\n";
704 }
705 if (IsArrayClass()) {
706 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
707 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800708 if (kh.NumInterfaces() > 0) {
709 os << " interfaces (" << kh.NumInterfaces() << "):\n";
710 for (size_t i = 0; i < kh.NumInterfaces(); ++i) {
711 Class* interface = kh.GetInterface(i);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700712 const ClassLoader* cl = interface->GetClassLoader();
Elliott Hughese689d512012-01-18 23:39:47 -0800713 os << StringPrintf(" %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700714 }
715 }
716 os << " vtable (" << NumVirtualMethods() << " entries, "
717 << (super != NULL ? super->NumVirtualMethods() : 0) << " in super):\n";
718 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Elliott Hughese689d512012-01-18 23:39:47 -0800719 os << StringPrintf(" %2zd: %s\n", i, PrettyMethod(GetVirtualMethodDuringLinking(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700720 }
721 os << " direct methods (" << NumDirectMethods() << " entries):\n";
722 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Elliott Hughese689d512012-01-18 23:39:47 -0800723 os << StringPrintf(" %2zd: %s\n", i, PrettyMethod(GetDirectMethod(i)).c_str());
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700724 }
725 if (NumStaticFields() > 0) {
726 os << " static fields (" << NumStaticFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700727 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700728 for (size_t i = 0; i < NumStaticFields(); ++i) {
Elliott Hughese689d512012-01-18 23:39:47 -0800729 os << StringPrintf(" %2zd: %s\n", i, PrettyField(GetStaticField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700730 }
731 } else {
732 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700733 }
734 }
735 if (NumInstanceFields() > 0) {
736 os << " instance fields (" << NumInstanceFields() << " entries):\n";
Elliott Hughes03f03492011-09-26 13:38:08 -0700737 if (IsResolved() || IsErroneous()) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700738 for (size_t i = 0; i < NumInstanceFields(); ++i) {
Elliott Hughese689d512012-01-18 23:39:47 -0800739 os << StringPrintf(" %2zd: %s\n", i, PrettyField(GetInstanceField(i)).c_str());
Elliott Hughes4681c802011-09-25 18:04:37 -0700740 }
741 } else {
742 os << " <not yet available>";
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700743 }
744 }
745}
746
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700747void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
748 if (new_reference_offsets != CLASS_WALK_SUPER) {
749 // Sanity check that the number of bits set in the reference offset bitmap
750 // agrees with the number of references
Elliott Hughescccd84f2011-12-05 16:51:54 -0800751 size_t count = 0;
752 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
753 count += c->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700754 }
Elliott Hughescccd84f2011-12-05 16:51:54 -0800755 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets), count);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700756 }
757 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
758 new_reference_offsets, false);
759}
760
761void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
762 if (new_reference_offsets != CLASS_WALK_SUPER) {
763 // Sanity check that the number of bits set in the reference offset bitmap
764 // agrees with the number of references
765 CHECK_EQ((size_t)__builtin_popcount(new_reference_offsets),
766 NumReferenceStaticFieldsDuringLinking());
767 }
768 SetField32(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
769 new_reference_offsets, false);
770}
771
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700772bool Class::Implements(const Class* klass) const {
773 DCHECK(klass != NULL);
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700774 DCHECK(klass->IsInterface()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700775 // All interfaces implemented directly and by our superclass, and
776 // recursively all super-interfaces of those interfaces, are listed
777 // in iftable_, so we can just do a linear scan through that.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700778 int32_t iftable_count = GetIfTableCount();
779 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
780 for (int32_t i = 0; i < iftable_count; i++) {
781 if (iftable->Get(i)->GetInterface() == klass) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700782 return true;
783 }
784 }
785 return false;
786}
787
788// Determine whether "this" is assignable from "klazz", where both of these
789// are array classes.
790//
791// Consider an array class, e.g. Y[][], where Y is a subclass of X.
792// Y[][] = Y[][] --> true (identity)
793// X[][] = Y[][] --> true (element superclass)
794// Y = Y[][] --> false
795// Y[] = Y[][] --> false
796// Object = Y[][] --> true (everything is an object)
797// Object[] = Y[][] --> true
798// Object[][] = Y[][] --> true
799// Object[][][] = Y[][] --> false (too many []s)
800// Serializable = Y[][] --> true (all arrays are Serializable)
801// Serializable[] = Y[][] --> true
802// Serializable[][] = Y[][] --> false (unless Y is Serializable)
803//
804// Don't forget about primitive types.
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700805// Object[] = int[] --> false
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700806//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700807bool Class::IsArrayAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700808 DCHECK(IsArrayClass()) << PrettyClass(this);
809 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700810 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700811}
812
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700813bool Class::IsAssignableFromArray(const Class* src) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700814 DCHECK(!IsInterface()) << PrettyClass(this); // handled first in IsAssignableFrom
815 DCHECK(src->IsArrayClass()) << PrettyClass(src);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700816 if (!IsArrayClass()) {
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700817 // If "this" is not also an array, it must be Object.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700818 // src's super should be java_lang_Object, since it is an array.
819 Class* java_lang_Object = src->GetSuperClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700820 DCHECK(java_lang_Object != NULL) << PrettyClass(src);
821 DCHECK(java_lang_Object->GetSuperClass() == NULL) << PrettyClass(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700822 return this == java_lang_Object;
823 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700824 return IsArrayAssignableFromArray(src);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700825}
826
827bool Class::IsSubClass(const Class* klass) const {
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700828 DCHECK(!IsInterface()) << PrettyClass(this);
829 DCHECK(!IsArrayClass()) << PrettyClass(this);
Brian Carlstromf7ed11a2011-08-09 17:55:51 -0700830 const Class* current = this;
831 do {
832 if (current == klass) {
833 return true;
834 }
835 current = current->GetSuperClass();
836 } while (current != NULL);
837 return false;
838}
839
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800840bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700841 size_t i = 0;
842 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
843 ++i;
844 }
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700845 if (descriptor1.find('/', i) != StringPiece::npos ||
846 descriptor2.find('/', i) != StringPiece::npos) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700847 return false;
848 } else {
849 return true;
850 }
851}
852
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700853#if 0
Ian Rogersb033c752011-07-20 12:22:35 -0700854bool Class::IsInSamePackage(const StringPiece& descriptor1,
855 const StringPiece& descriptor2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700856 size_t size = std::min(descriptor1.size(), descriptor2.size());
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700857 std::pair<StringPiece::const_iterator, StringPiece::const_iterator> pos;
Ian Rogersb033c752011-07-20 12:22:35 -0700858 pos = std::mismatch(descriptor1.begin(), descriptor1.begin() + size,
859 descriptor2.begin());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700860 return !(*(pos.second).rfind('/') != npos && descriptor2.rfind('/') != npos);
861}
862#endif
863
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700864bool Class::IsInSamePackage(const Class* that) const {
865 const Class* klass1 = this;
866 const Class* klass2 = that;
867 if (klass1 == klass2) {
868 return true;
869 }
870 // Class loaders must match.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700871 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700872 return false;
873 }
874 // Arrays are in the same package when their element classes are.
jeffhao4a801a42011-09-23 13:53:40 -0700875 while (klass1->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700876 klass1 = klass1->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700877 }
jeffhao4a801a42011-09-23 13:53:40 -0700878 while (klass2->IsArrayClass()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700879 klass2 = klass2->GetComponentType();
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700880 }
881 // Compare the package part of the descriptor string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800882 ClassHelper kh(klass1);
Elliott Hughes95572412011-12-13 18:14:20 -0800883 std::string descriptor1(kh.GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800884 kh.ChangeClass(klass2);
Elliott Hughes95572412011-12-13 18:14:20 -0800885 std::string descriptor2(kh.GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800886 return IsInSamePackage(descriptor1, descriptor2);
Carl Shapiro894d0fa2011-06-30 14:48:49 -0700887}
888
Elliott Hughesdbb40792011-11-18 17:05:22 -0800889bool Class::IsClassClass() const {
890 Class* java_lang_Class = GetClass()->GetClass();
891 return this == java_lang_Class;
892}
893
894bool Class::IsStringClass() const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800895 return this == String::GetJavaLangString();
Elliott Hughesdbb40792011-11-18 17:05:22 -0800896}
897
Ian Rogers6f1dfe42011-12-08 17:28:34 -0800898bool Class::IsThrowableClass() const {
899 Class* throwable = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Throwable;");
900 return throwable->IsAssignableFrom(this);
901}
902
Elliott Hughes1bba14f2011-12-01 18:00:36 -0800903ClassLoader* Class::GetClassLoader() const {
904 return GetFieldObject<ClassLoader*>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), false);
Brian Carlstromb9edb842011-08-28 16:31:06 -0700905}
906
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700907void Class::SetClassLoader(const ClassLoader* new_cl) {
908 ClassLoader* new_class_loader = const_cast<ClassLoader*>(new_cl);
Ian Rogersd81871c2011-10-03 13:57:23 -0700909 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader, false);
Carl Shapiro8860c0e2011-08-04 17:36:16 -0700910}
911
Ian Rogersb04f69f2011-10-17 00:40:54 -0700912Method* Class::FindVirtualMethodForInterface(Method* method, bool can_throw) {
Brian Carlstrom30b94452011-08-25 21:35:26 -0700913 Class* declaring_class = method->GetDeclaringClass();
Brian Carlstrom65ca0772011-09-24 16:03:08 -0700914 DCHECK(declaring_class != NULL) << PrettyClass(this);
915 DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
Brian Carlstrom30b94452011-08-25 21:35:26 -0700916 // TODO cache to improve lookup speed
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700917 int32_t iftable_count = GetIfTableCount();
918 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
919 for (int32_t i = 0; i < iftable_count; i++) {
920 InterfaceEntry* interface_entry = iftable->Get(i);
921 if (interface_entry->GetInterface() == declaring_class) {
922 return interface_entry->GetMethodArray()->Get(method->GetMethodIndex());
Brian Carlstrom30b94452011-08-25 21:35:26 -0700923 }
924 }
Ian Rogersb04f69f2011-10-17 00:40:54 -0700925 if (can_throw) {
926 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
927 "Class %s does not implement interface %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800928 PrettyDescriptor(this).c_str(), PrettyDescriptor(declaring_class).c_str());
Ian Rogersb04f69f2011-10-17 00:40:54 -0700929 }
Brian Carlstrom30b94452011-08-25 21:35:26 -0700930 return NULL;
931}
932
Ian Rogers466bb252011-10-14 03:29:56 -0700933Method* Class::FindInterfaceMethod(const StringPiece& name, const StringPiece& signature) const {
jeffhaobdb76512011-09-07 11:43:16 -0700934 // Check the current class before checking the interfaces.
Ian Rogers94c0e332012-01-18 22:11:47 -0800935 Method* method = FindDeclaredVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -0700936 if (method != NULL) {
937 return method;
938 }
939
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700940 int32_t iftable_count = GetIfTableCount();
941 ObjectArray<InterfaceEntry>* iftable = GetIfTable();
942 for (int32_t i = 0; i < iftable_count; i++) {
943 method = iftable->Get(i)->GetInterface()->FindVirtualMethod(name, signature);
jeffhaobdb76512011-09-07 11:43:16 -0700944 if (method != NULL) {
945 return method;
946 }
947 }
948 return NULL;
949}
950
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700951Method* Class::FindDeclaredDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700952 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800953 MethodHelper mh;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700954 for (size_t i = 0; i < NumDirectMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -0700955 Method* method = GetDirectMethod(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800956 mh.ChangeMethod(method);
957 if (name == mh.GetName() && signature == mh.GetSignature()) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700958 return method;
Ian Rogersb033c752011-07-20 12:22:35 -0700959 }
960 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700961 return NULL;
Ian Rogersb033c752011-07-20 12:22:35 -0700962}
963
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700964Method* Class::FindDirectMethod(const StringPiece& name,
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700965 const StringPiece& signature) {
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700966 for (Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700967 Method* method = klass->FindDeclaredDirectMethod(name, signature);
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700968 if (method != NULL) {
969 return method;
970 }
971 }
972 return NULL;
973}
974
975Method* Class::FindDeclaredVirtualMethod(const StringPiece& name,
Ian Rogers466bb252011-10-14 03:29:56 -0700976 const StringPiece& signature) const {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800977 MethodHelper mh;
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700978 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
Ian Rogersb033c752011-07-20 12:22:35 -0700979 Method* method = GetVirtualMethod(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800980 mh.ChangeMethod(method);
981 if (name == mh.GetName() && signature == mh.GetSignature()) {
Ian Rogers466bb252011-10-14 03:29:56 -0700982 return method;
Ian Rogers466bb252011-10-14 03:29:56 -0700983 }
984 }
985 return NULL;
986}
987
988Method* Class::FindVirtualMethod(const StringPiece& name, const StringPiece& signature) const {
989 for (const Class* klass = this; klass != NULL; klass = klass->GetSuperClass()) {
990 Method* method = klass->FindDeclaredVirtualMethod(name, signature);
991 if (method != NULL) {
992 return method;
993 }
994 }
995 return NULL;
996}
997
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700998Field* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
Elliott Hughescdf53122011-08-19 15:46:09 -0700999 // Is the field in this class?
1000 // Interfaces are not relevant because they can't contain instance fields.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001001 FieldHelper fh;
Elliott Hughescdf53122011-08-19 15:46:09 -07001002 for (size_t i = 0; i < NumInstanceFields(); ++i) {
1003 Field* f = GetInstanceField(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001004 fh.ChangeField(f);
1005 if (name == fh.GetName() && type == fh.GetTypeDescriptor()) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001006 return f;
1007 }
1008 }
1009 return NULL;
1010}
1011
1012Field* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
Elliott Hughescdf53122011-08-19 15:46:09 -07001013 // Is the field in this class, or any of its superclasses?
1014 // Interfaces are not relevant because they can't contain instance fields.
1015 for (Class* c = this; c != NULL; c = c->GetSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001016 Field* f = c->FindDeclaredInstanceField(name, type);
Elliott Hughescdf53122011-08-19 15:46:09 -07001017 if (f != NULL) {
1018 return f;
1019 }
1020 }
1021 return NULL;
1022}
1023
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001024Field* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
1025 DCHECK(type != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001026 FieldHelper fh;
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001027 for (size_t i = 0; i < NumStaticFields(); ++i) {
1028 Field* f = GetStaticField(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001029 fh.ChangeField(f);
1030 if (name == fh.GetName() && type == fh.GetTypeDescriptor()) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001031 return f;
1032 }
1033 }
1034 return NULL;
1035}
1036
1037Field* Class::FindStaticField(const StringPiece& name, const StringPiece& type) {
1038 // Is the field in this class (or its interfaces), or any of its
1039 // superclasses (or their interfaces)?
Ian Rogersb067ac22011-12-13 18:05:09 -08001040 ClassHelper kh;
1041 for (Class* k = this; k != NULL; k = k->GetSuperClass()) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001042 // Is the field in this class?
Ian Rogersb067ac22011-12-13 18:05:09 -08001043 Field* f = k->FindDeclaredStaticField(name, type);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001044 if (f != NULL) {
1045 return f;
1046 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001047 // Is this field in any of this class' interfaces?
Ian Rogersb067ac22011-12-13 18:05:09 -08001048 kh.ChangeClass(k);
1049 for (uint32_t i = 0; i < kh.NumInterfaces(); ++i) {
1050 Class* interface = kh.GetInterface(i);
1051 f = interface->FindDeclaredStaticField(name, type);
1052 if (f != NULL) {
1053 return f;
1054 }
1055 }
1056 }
1057 return NULL;
1058}
1059
1060Field* Class::FindField(const StringPiece& name, const StringPiece& type) {
1061 // Find a field using the JLS field resolution order
1062 ClassHelper kh;
1063 for (Class* k = this; k != NULL; k = k->GetSuperClass()) {
1064 // Is the field in this class?
1065 Field* f = k->FindDeclaredInstanceField(name, type);
1066 if (f != NULL) {
1067 return f;
1068 }
1069 f = k->FindDeclaredStaticField(name, type);
1070 if (f != NULL) {
1071 return f;
1072 }
1073 // Is this field in any of this class' interfaces?
1074 kh.ChangeClass(k);
1075 for (uint32_t i = 0; i < kh.NumInterfaces(); ++i) {
1076 Class* interface = kh.GetInterface(i);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001077 f = interface->FindDeclaredStaticField(name, type);
1078 if (f != NULL) {
1079 return f;
1080 }
1081 }
1082 }
1083 return NULL;
1084}
1085
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001086Array* Array::Alloc(Class* array_class, int32_t component_count, size_t component_size) {
Elliott Hughes0f4c41d2011-09-04 14:58:03 -07001087 DCHECK(array_class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001088 DCHECK_GE(component_count, 0);
1089 DCHECK(array_class->IsArrayClass());
Elliott Hughesb408de72011-10-04 14:35:05 -07001090
1091 size_t header_size = sizeof(Array);
1092 size_t data_size = component_count * component_size;
1093 size_t size = header_size + data_size;
1094
1095 // Check for overflow and throw OutOfMemoryError if this was an unreasonable request.
1096 size_t component_shift = sizeof(size_t) * 8 - 1 - CLZ(component_size);
1097 if (data_size >> component_shift != size_t(component_count) || size < data_size) {
1098 Thread::Current()->ThrowNewExceptionF("Ljava/lang/OutOfMemoryError;",
Elliott Hughese689d512012-01-18 23:39:47 -08001099 "%s of length %d exceeds the VM limit",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001100 PrettyDescriptor(array_class).c_str(), component_count);
Elliott Hughesb408de72011-10-04 14:35:05 -07001101 return NULL;
1102 }
1103
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001104 Array* array = down_cast<Array*>(Heap::AllocObject(array_class, size));
1105 if (array != NULL) {
1106 DCHECK(array->IsArrayInstance());
1107 array->SetLength(component_count);
1108 }
1109 return array;
1110}
1111
1112Array* Array::Alloc(Class* array_class, int32_t component_count) {
1113 return Alloc(array_class, component_count, array_class->GetComponentSize());
1114}
1115
Elliott Hughes80609252011-09-23 17:24:51 -07001116bool Array::ThrowArrayIndexOutOfBoundsException(int32_t index) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001117 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001118 "length=%i; index=%i", length_, index);
1119 return false;
1120}
1121
1122bool Array::ThrowArrayStoreException(Object* object) const {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001123 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Elliott Hughes80609252011-09-23 17:24:51 -07001124 "Can't store an element of type %s into an array of type %s",
1125 PrettyTypeOf(object).c_str(), PrettyTypeOf(this).c_str());
1126 return false;
1127}
1128
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001129template<typename T>
1130PrimitiveArray<T>* PrimitiveArray<T>::Alloc(size_t length) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001131 DCHECK(array_class_ != NULL);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001132 Array* raw_array = Array::Alloc(array_class_, length, sizeof(T));
1133 return down_cast<PrimitiveArray<T>*>(raw_array);
1134}
1135
1136template <typename T> Class* PrimitiveArray<T>::array_class_ = NULL;
1137
1138// Explicitly instantiate all the primitive array types.
1139template class PrimitiveArray<uint8_t>; // BooleanArray
1140template class PrimitiveArray<int8_t>; // ByteArray
1141template class PrimitiveArray<uint16_t>; // CharArray
1142template class PrimitiveArray<double>; // DoubleArray
1143template class PrimitiveArray<float>; // FloatArray
1144template class PrimitiveArray<int32_t>; // IntArray
1145template class PrimitiveArray<int64_t>; // LongArray
1146template class PrimitiveArray<int16_t>; // ShortArray
1147
Ian Rogers466bb252011-10-14 03:29:56 -07001148// Explicitly instantiate Class[][]
1149template class ObjectArray<ObjectArray<Class> >;
1150
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001151// TODO: get global references for these
1152Class* String::java_lang_String_ = NULL;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001153
Brian Carlstroma663ea52011-08-19 23:33:41 -07001154void String::SetClass(Class* java_lang_String) {
1155 CHECK(java_lang_String_ == NULL);
1156 CHECK(java_lang_String != NULL);
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001157 java_lang_String_ = java_lang_String;
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001158}
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001159
Brian Carlstroma663ea52011-08-19 23:33:41 -07001160void String::ResetClass() {
1161 CHECK(java_lang_String_ != NULL);
1162 java_lang_String_ = NULL;
1163}
Jesse Wilsonf7e85a52011-08-01 18:45:58 -07001164
Brian Carlstromc74255f2011-09-11 22:47:39 -07001165String* String::Intern() {
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001166 return Runtime::Current()->GetInternTable()->InternWeak(this);
1167}
1168
Brian Carlstrom395520e2011-09-25 19:35:00 -07001169int32_t String::GetHashCode() {
1170 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1171 if (result == 0) {
1172 ComputeHashCode();
1173 }
1174 result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, hash_code_), false);
1175 DCHECK(result != 0 || ComputeUtf16Hash(GetCharArray(), GetOffset(), GetLength()) == 0)
1176 << ToModifiedUtf8() << " " << result;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001177 return result;
1178}
1179
1180int32_t String::GetLength() const {
1181 int32_t result = GetField32(OFFSET_OF_OBJECT_MEMBER(String, count_), false);
1182 DCHECK(result >= 0 && result <= GetCharArray()->GetLength());
1183 return result;
1184}
1185
1186uint16_t String::CharAt(int32_t index) const {
1187 // TODO: do we need this? Equals is the only caller, and could
1188 // bounds check itself.
1189 if (index < 0 || index >= count_) {
1190 Thread* self = Thread::Current();
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001191 self->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;",
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001192 "length=%i; index=%i", count_, index);
1193 return 0;
1194 }
1195 return GetCharArray()->Get(index + GetOffset());
1196}
1197
1198String* String::AllocFromUtf16(int32_t utf16_length,
1199 const uint16_t* utf16_data_in,
1200 int32_t hash_code) {
Jesse Wilson25e79a52011-11-18 15:31:58 -05001201 CHECK(utf16_data_in != NULL || utf16_length == 0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001202 String* string = Alloc(GetJavaLangString(), utf16_length);
Elliott Hughesb51036c2011-10-12 23:49:11 -07001203 if (string == NULL) {
1204 return NULL;
1205 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001206 // TODO: use 16-bit wide memset variant
1207 CharArray* array = const_cast<CharArray*>(string->GetCharArray());
Elliott Hughesb51036c2011-10-12 23:49:11 -07001208 if (array == NULL) {
1209 return NULL;
1210 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001211 for (int i = 0; i < utf16_length; i++) {
1212 array->Set(i, utf16_data_in[i]);
1213 }
1214 if (hash_code != 0) {
1215 string->SetHashCode(hash_code);
1216 } else {
1217 string->ComputeHashCode();
1218 }
1219 return string;
1220}
1221
1222String* String::AllocFromModifiedUtf8(const char* utf) {
Ian Rogers48601312011-12-07 16:45:19 -08001223 if (utf == NULL) {
1224 return NULL;
1225 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001226 size_t char_count = CountModifiedUtf8Chars(utf);
1227 return AllocFromModifiedUtf8(char_count, utf);
1228}
1229
1230String* String::AllocFromModifiedUtf8(int32_t utf16_length,
1231 const char* utf8_data_in) {
1232 String* string = Alloc(GetJavaLangString(), utf16_length);
Elliott Hughesb51036c2011-10-12 23:49:11 -07001233 if (string == NULL) {
1234 return NULL;
1235 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001236 uint16_t* utf16_data_out =
1237 const_cast<uint16_t*>(string->GetCharArray()->GetData());
1238 ConvertModifiedUtf8ToUtf16(utf16_data_out, utf8_data_in);
1239 string->ComputeHashCode();
1240 return string;
1241}
1242
1243String* String::Alloc(Class* java_lang_String, int32_t utf16_length) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001244 SirtRef<CharArray> array(CharArray::Alloc(utf16_length));
1245 if (array.get() == NULL) {
Elliott Hughesb51036c2011-10-12 23:49:11 -07001246 return NULL;
1247 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001248 return Alloc(java_lang_String, array.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001249}
1250
1251String* String::Alloc(Class* java_lang_String, CharArray* array) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001252 SirtRef<CharArray> array_ref(array); // hold reference in case AllocObject causes GC
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001253 String* string = down_cast<String*>(java_lang_String->AllocObject());
Elliott Hughesb51036c2011-10-12 23:49:11 -07001254 if (string == NULL) {
1255 return NULL;
1256 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001257 string->SetArray(array);
1258 string->SetCount(array->GetLength());
1259 return string;
1260}
1261
1262bool String::Equals(const String* that) const {
1263 if (this == that) {
1264 // Quick reference equality test
1265 return true;
1266 } else if (that == NULL) {
1267 // Null isn't an instanceof anything
1268 return false;
1269 } else if (this->GetLength() != that->GetLength()) {
1270 // Quick length inequality test
1271 return false;
1272 } else {
Elliott Hughes20cde902011-10-04 17:37:27 -07001273 // Note: don't short circuit on hash code as we're presumably here as the
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001274 // hash code was already equal
1275 for (int32_t i = 0; i < that->GetLength(); ++i) {
1276 if (this->CharAt(i) != that->CharAt(i)) {
1277 return false;
1278 }
1279 }
1280 return true;
1281 }
1282}
1283
Elliott Hughes5d78d392011-12-13 16:53:05 -08001284bool String::Equals(const uint16_t* that_chars, int32_t that_offset, int32_t that_length) const {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001285 if (this->GetLength() != that_length) {
1286 return false;
1287 } else {
1288 for (int32_t i = 0; i < that_length; ++i) {
1289 if (this->CharAt(i) != that_chars[that_offset + i]) {
1290 return false;
1291 }
1292 }
1293 return true;
1294 }
1295}
1296
1297bool String::Equals(const char* modified_utf8) const {
1298 for (int32_t i = 0; i < GetLength(); ++i) {
1299 uint16_t ch = GetUtf16FromUtf8(&modified_utf8);
1300 if (ch == '\0' || ch != CharAt(i)) {
1301 return false;
1302 }
1303 }
1304 return *modified_utf8 == '\0';
1305}
1306
1307bool String::Equals(const StringPiece& modified_utf8) const {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001308 if (modified_utf8.size() != GetLength()) {
1309 return false;
1310 }
1311 const char* p = modified_utf8.data();
1312 for (int32_t i = 0; i < GetLength(); ++i) {
1313 uint16_t ch = GetUtf16FromUtf8(&p);
1314 if (ch != CharAt(i)) {
1315 return false;
1316 }
1317 }
1318 return true;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001319}
1320
1321// Create a modified UTF-8 encoded std::string from a java/lang/String object.
1322std::string String::ToModifiedUtf8() const {
1323 const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
1324 size_t byte_count(CountUtf8Bytes(chars, GetLength()));
1325 std::string result(byte_count, char(0));
1326 ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
1327 return result;
1328}
1329
Ian Rogers1c5eb702012-02-01 09:18:34 -08001330void Throwable::SetCause(Throwable* cause) {
1331 CHECK(cause != NULL);
1332 CHECK(cause != this);
1333 CHECK(GetFieldObject<Throwable*>(OFFSET_OF_OBJECT_MEMBER(Throwable, cause_), false) == NULL);
1334 SetFieldObject(OFFSET_OF_OBJECT_MEMBER(Throwable, cause_), cause, false);
1335}
1336
Ian Rogers466bb252011-10-14 03:29:56 -07001337bool Throwable::IsCheckedException() const {
1338 Class* error = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/Error;");
1339 if (InstanceOf(error)) {
1340 return false;
1341 }
1342 Class* jlre = Runtime::Current()->GetClassLinker()->FindSystemClass("Ljava/lang/RuntimeException;");
1343 return !InstanceOf(jlre);
1344}
1345
Ian Rogers9074b992011-10-26 17:41:55 -07001346std::string Throwable::Dump() const {
Ian Rogers09f6b562012-01-31 21:58:52 -08001347 std::string result(PrettyTypeOf(this));
1348 result += ": ";
1349 String* msg = GetFieldObject<String*>(OFFSET_OF_OBJECT_MEMBER(Throwable, detail_message_), false);
1350 if (msg != NULL) {
1351 result += msg->ToModifiedUtf8();
Ian Rogers9074b992011-10-26 17:41:55 -07001352 }
Ian Rogers09f6b562012-01-31 21:58:52 -08001353 result += "\n";
1354 Object* stack_state = GetStackState();
1355 // check stack state isn't missing or corrupt
1356 if (stack_state != NULL && stack_state->IsObjectArray()) {
1357 // Decode the internal stack trace into the depth and method trace
1358 ObjectArray<Object>* method_trace = down_cast<ObjectArray<Object>*>(stack_state);
1359 int32_t depth = method_trace->GetLength() - 1;
1360 for (int32_t i = 0; i < depth; ++i) {
1361 Method* method = down_cast<Method*>(method_trace->Get(i));
1362 result += " at ";
1363 result += PrettyMethod(method, true);
1364 result += "\n";
1365 }
Ian Rogers9074b992011-10-26 17:41:55 -07001366 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08001367 Throwable* cause = GetFieldObject<Throwable*>(OFFSET_OF_OBJECT_MEMBER(Throwable, cause_), false);
1368 if (cause != NULL) {
1369 result += "Caused by: ";
1370 result += cause->Dump();
1371 }
Ian Rogers9074b992011-10-26 17:41:55 -07001372 return result;
1373}
1374
Ian Rogers5167c972012-02-03 10:41:20 -08001375
1376Class* Throwable::java_lang_Throwable_ = NULL;
1377
1378void Throwable::SetClass(Class* java_lang_Throwable) {
1379 CHECK(java_lang_Throwable_ == NULL);
1380 CHECK(java_lang_Throwable != NULL);
1381 java_lang_Throwable_ = java_lang_Throwable;
1382}
1383
1384void Throwable::ResetClass() {
1385 CHECK(java_lang_Throwable_ != NULL);
1386 java_lang_Throwable_ = NULL;
1387}
1388
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001389Class* StackTraceElement::java_lang_StackTraceElement_ = NULL;
1390
1391void StackTraceElement::SetClass(Class* java_lang_StackTraceElement) {
1392 CHECK(java_lang_StackTraceElement_ == NULL);
1393 CHECK(java_lang_StackTraceElement != NULL);
1394 java_lang_StackTraceElement_ = java_lang_StackTraceElement;
1395}
1396
1397void StackTraceElement::ResetClass() {
1398 CHECK(java_lang_StackTraceElement_ != NULL);
1399 java_lang_StackTraceElement_ = NULL;
1400}
1401
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001402StackTraceElement* StackTraceElement::Alloc(String* declaring_class,
1403 String* method_name,
1404 String* file_name,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001405 int32_t line_number) {
1406 StackTraceElement* trace =
1407 down_cast<StackTraceElement*>(GetStackTraceElement()->AllocObject());
1408 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, declaring_class_),
1409 const_cast<String*>(declaring_class), false);
1410 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, method_name_),
1411 const_cast<String*>(method_name), false);
1412 trace->SetFieldObject(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, file_name_),
1413 const_cast<String*>(file_name), false);
1414 trace->SetField32(OFFSET_OF_OBJECT_MEMBER(StackTraceElement, line_number_),
1415 line_number, false);
1416 return trace;
1417}
1418
Elliott Hughes1f359b02011-07-17 14:27:17 -07001419static const char* kClassStatusNames[] = {
1420 "Error",
1421 "NotReady",
1422 "Idx",
1423 "Loaded",
1424 "Resolved",
1425 "Verifying",
1426 "Verified",
1427 "Initializing",
1428 "Initialized"
1429};
1430std::ostream& operator<<(std::ostream& os, const Class::Status& rhs) {
1431 if (rhs >= Class::kStatusError && rhs <= Class::kStatusInitialized) {
Brian Carlstromae3ac012011-07-27 01:30:28 -07001432 os << kClassStatusNames[rhs + 1];
Elliott Hughes1f359b02011-07-17 14:27:17 -07001433 } else {
Ian Rogersb033c752011-07-20 12:22:35 -07001434 os << "Class::Status[" << static_cast<int>(rhs) << "]";
Elliott Hughes1f359b02011-07-17 14:27:17 -07001435 }
1436 return os;
1437}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001438
Carl Shapiro3ee755d2011-06-28 12:11:04 -07001439} // namespace art