1 /*
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  */
16 
17 #include "object.h"
18 
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <memory>
22 
23 #include "array-inl.h"
24 #include "art_field-inl.h"
25 #include "art_method-inl.h"
26 #include "asm_support.h"
27 #include "class-inl.h"
28 #include "class_linker.h"
29 #include "class_linker-inl.h"
30 #include "common_runtime_test.h"
31 #include "dex_file.h"
32 #include "entrypoints/entrypoint_utils-inl.h"
33 #include "gc/accounting/card_table-inl.h"
34 #include "gc/heap.h"
35 #include "handle_scope-inl.h"
36 #include "iftable-inl.h"
37 #include "method_helper-inl.h"
38 #include "object-inl.h"
39 #include "object_array-inl.h"
40 #include "scoped_thread_state_change.h"
41 #include "string-inl.h"
42 
43 namespace art {
44 namespace mirror {
45 
46 class ObjectTest : public CommonRuntimeTest {
47  protected:
AssertString(int32_t expected_utf16_length,const char * utf8_in,const char * utf16_expected_le,int32_t expected_hash)48   void AssertString(int32_t expected_utf16_length,
49                     const char* utf8_in,
50                     const char* utf16_expected_le,
51                     int32_t expected_hash)
52       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
53     std::unique_ptr<uint16_t[]> utf16_expected(new uint16_t[expected_utf16_length]);
54     for (int32_t i = 0; i < expected_utf16_length; i++) {
55       uint16_t ch = (((utf16_expected_le[i*2 + 0] & 0xff) << 8) |
56                      ((utf16_expected_le[i*2 + 1] & 0xff) << 0));
57       utf16_expected[i] = ch;
58     }
59 
60     Thread* self = Thread::Current();
61     StackHandleScope<1> hs(self);
62     Handle<String> string(
63         hs.NewHandle(String::AllocFromModifiedUtf8(self, expected_utf16_length, utf8_in)));
64     ASSERT_EQ(expected_utf16_length, string->GetLength());
65     ASSERT_TRUE(string->GetCharArray() != NULL);
66     ASSERT_TRUE(string->GetCharArray()->GetData() != NULL);
67     // strlen is necessary because the 1-character string "\x00\x00" is interpreted as ""
68     ASSERT_TRUE(string->Equals(utf8_in) || (expected_utf16_length == 1 && strlen(utf8_in) == 0));
69     ASSERT_TRUE(string->Equals(StringPiece(utf8_in)) || (expected_utf16_length == 1 && strlen(utf8_in) == 0));
70     for (int32_t i = 0; i < expected_utf16_length; i++) {
71       EXPECT_EQ(utf16_expected[i], string->CharAt(i));
72     }
73     EXPECT_EQ(expected_hash, string->GetHashCode());
74   }
75 };
76 
77 // Keep the assembly code in sync
TEST_F(ObjectTest,AsmConstants)78 TEST_F(ObjectTest, AsmConstants) {
79   EXPECT_EQ(CLASS_OFFSET, Object::ClassOffset().Int32Value());
80   EXPECT_EQ(LOCK_WORD_OFFSET, Object::MonitorOffset().Int32Value());
81 
82   EXPECT_EQ(CLASS_COMPONENT_TYPE_OFFSET, Class::ComponentTypeOffset().Int32Value());
83 
84   EXPECT_EQ(ARRAY_LENGTH_OFFSET, Array::LengthOffset().Int32Value());
85   EXPECT_EQ(OBJECT_ARRAY_DATA_OFFSET, Array::DataOffset(sizeof(HeapReference<Object>)).Int32Value());
86 
87   EXPECT_EQ(STRING_VALUE_OFFSET, String::ValueOffset().Int32Value());
88   EXPECT_EQ(STRING_COUNT_OFFSET, String::CountOffset().Int32Value());
89   EXPECT_EQ(STRING_OFFSET_OFFSET, String::OffsetOffset().Int32Value());
90   EXPECT_EQ(STRING_DATA_OFFSET, Array::DataOffset(sizeof(uint16_t)).Int32Value());
91 
92   EXPECT_EQ(METHOD_DEX_CACHE_METHODS_OFFSET,
93             ArtMethod::DexCacheResolvedMethodsOffset().Int32Value());
94 #if defined(ART_USE_PORTABLE_COMPILER)
95   EXPECT_EQ(METHOD_PORTABLE_CODE_OFFSET_32,
96             ArtMethod::EntryPointFromPortableCompiledCodeOffset(4).Int32Value());
97   EXPECT_EQ(METHOD_PORTABLE_CODE_OFFSET_64,
98             ArtMethod::EntryPointFromPortableCompiledCodeOffset(8).Int32Value());
99 #endif
100   EXPECT_EQ(METHOD_QUICK_CODE_OFFSET_32,
101             ArtMethod::EntryPointFromQuickCompiledCodeOffset(4).Int32Value());
102   EXPECT_EQ(METHOD_QUICK_CODE_OFFSET_64,
103             ArtMethod::EntryPointFromQuickCompiledCodeOffset(8).Int32Value());
104 }
105 
TEST_F(ObjectTest,IsInSamePackage)106 TEST_F(ObjectTest, IsInSamePackage) {
107   // Matches
108   EXPECT_TRUE(Class::IsInSamePackage("Ljava/lang/Object;", "Ljava/lang/Class;"));
109   EXPECT_TRUE(Class::IsInSamePackage("LFoo;", "LBar;"));
110 
111   // Mismatches
112   EXPECT_FALSE(Class::IsInSamePackage("Ljava/lang/Object;", "Ljava/io/File;"));
113   EXPECT_FALSE(Class::IsInSamePackage("Ljava/lang/Object;", "Ljava/lang/reflect/Method;"));
114 }
115 
TEST_F(ObjectTest,Clone)116 TEST_F(ObjectTest, Clone) {
117   ScopedObjectAccess soa(Thread::Current());
118   StackHandleScope<2> hs(soa.Self());
119   Handle<ObjectArray<Object>> a1(
120       hs.NewHandle(class_linker_->AllocObjectArray<Object>(soa.Self(), 256)));
121   size_t s1 = a1->SizeOf();
122   Object* clone = a1->Clone(soa.Self());
123   EXPECT_EQ(s1, clone->SizeOf());
124   EXPECT_TRUE(clone->GetClass() == a1->GetClass());
125 }
126 
TEST_F(ObjectTest,AllocObjectArray)127 TEST_F(ObjectTest, AllocObjectArray) {
128   ScopedObjectAccess soa(Thread::Current());
129   StackHandleScope<2> hs(soa.Self());
130   Handle<ObjectArray<Object>> oa(
131       hs.NewHandle(class_linker_->AllocObjectArray<Object>(soa.Self(), 2)));
132   EXPECT_EQ(2, oa->GetLength());
133   EXPECT_TRUE(oa->Get(0) == NULL);
134   EXPECT_TRUE(oa->Get(1) == NULL);
135   oa->Set<false>(0, oa.Get());
136   EXPECT_TRUE(oa->Get(0) == oa.Get());
137   EXPECT_TRUE(oa->Get(1) == NULL);
138   oa->Set<false>(1, oa.Get());
139   EXPECT_TRUE(oa->Get(0) == oa.Get());
140   EXPECT_TRUE(oa->Get(1) == oa.Get());
141 
142   Class* aioobe = class_linker_->FindSystemClass(soa.Self(),
143                                                  "Ljava/lang/ArrayIndexOutOfBoundsException;");
144 
145   EXPECT_TRUE(oa->Get(-1) == NULL);
146   EXPECT_TRUE(soa.Self()->IsExceptionPending());
147   EXPECT_EQ(aioobe, soa.Self()->GetException(NULL)->GetClass());
148   soa.Self()->ClearException();
149 
150   EXPECT_TRUE(oa->Get(2) == NULL);
151   EXPECT_TRUE(soa.Self()->IsExceptionPending());
152   EXPECT_EQ(aioobe, soa.Self()->GetException(NULL)->GetClass());
153   soa.Self()->ClearException();
154 
155   ASSERT_TRUE(oa->GetClass() != NULL);
156   Handle<mirror::Class> klass(hs.NewHandle(oa->GetClass()));
157   ASSERT_EQ(2U, klass->NumDirectInterfaces());
158   EXPECT_EQ(class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Cloneable;"),
159             mirror::Class::GetDirectInterface(soa.Self(), klass, 0));
160   EXPECT_EQ(class_linker_->FindSystemClass(soa.Self(), "Ljava/io/Serializable;"),
161             mirror::Class::GetDirectInterface(soa.Self(), klass, 1));
162 }
163 
TEST_F(ObjectTest,AllocArray)164 TEST_F(ObjectTest, AllocArray) {
165   ScopedObjectAccess soa(Thread::Current());
166   Class* c = class_linker_->FindSystemClass(soa.Self(), "[I");
167   StackHandleScope<1> hs(soa.Self());
168   Handle<Array> a(
169       hs.NewHandle(Array::Alloc<true>(soa.Self(), c, 1, c->GetComponentSize(),
170                                       Runtime::Current()->GetHeap()->GetCurrentAllocator())));
171   EXPECT_TRUE(c == a->GetClass());
172   EXPECT_EQ(1, a->GetLength());
173 
174   c = class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/Object;");
175   a.Assign(Array::Alloc<true>(soa.Self(), c, 1, c->GetComponentSize(),
176                               Runtime::Current()->GetHeap()->GetCurrentAllocator()));
177   EXPECT_TRUE(c == a->GetClass());
178   EXPECT_EQ(1, a->GetLength());
179 
180   c = class_linker_->FindSystemClass(soa.Self(), "[[Ljava/lang/Object;");
181   a.Assign(Array::Alloc<true>(soa.Self(), c, 1, c->GetComponentSize(),
182                               Runtime::Current()->GetHeap()->GetCurrentAllocator()));
183   EXPECT_TRUE(c == a->GetClass());
184   EXPECT_EQ(1, a->GetLength());
185 }
186 
TEST_F(ObjectTest,AllocArray_FillUsable)187 TEST_F(ObjectTest, AllocArray_FillUsable) {
188   ScopedObjectAccess soa(Thread::Current());
189   Class* c = class_linker_->FindSystemClass(soa.Self(), "[B");
190   StackHandleScope<1> hs(soa.Self());
191   Handle<Array> a(
192       hs.NewHandle(Array::Alloc<true>(soa.Self(), c, 1, c->GetComponentSize(),
193                                       Runtime::Current()->GetHeap()->GetCurrentAllocator(), true)));
194   EXPECT_TRUE(c == a->GetClass());
195   EXPECT_LE(1, a->GetLength());
196 
197   c = class_linker_->FindSystemClass(soa.Self(), "[I");
198   a.Assign(Array::Alloc<true>(soa.Self(), c, 2, c->GetComponentSize(),
199                               Runtime::Current()->GetHeap()->GetCurrentAllocator(), true));
200   EXPECT_TRUE(c == a->GetClass());
201   EXPECT_LE(2, a->GetLength());
202 
203   c = class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/Object;");
204   a.Assign(Array::Alloc<true>(soa.Self(), c, 2, c->GetComponentSize(),
205                               Runtime::Current()->GetHeap()->GetCurrentAllocator(), true));
206   EXPECT_TRUE(c == a->GetClass());
207   EXPECT_LE(2, a->GetLength());
208 
209   c = class_linker_->FindSystemClass(soa.Self(), "[[Ljava/lang/Object;");
210   a.Assign(Array::Alloc<true>(soa.Self(), c, 2, c->GetComponentSize(),
211                              Runtime::Current()->GetHeap()->GetCurrentAllocator(), true));
212   EXPECT_TRUE(c == a->GetClass());
213   EXPECT_LE(2, a->GetLength());
214 }
215 
216 template<typename ArrayT>
TestPrimitiveArray(ClassLinker * cl)217 void TestPrimitiveArray(ClassLinker* cl) {
218   ScopedObjectAccess soa(Thread::Current());
219   typedef typename ArrayT::ElementType T;
220 
221   ArrayT* a = ArrayT::Alloc(soa.Self(), 2);
222   EXPECT_EQ(2, a->GetLength());
223   EXPECT_EQ(0, a->Get(0));
224   EXPECT_EQ(0, a->Get(1));
225   a->Set(0, T(123));
226   EXPECT_EQ(T(123), a->Get(0));
227   EXPECT_EQ(0, a->Get(1));
228   a->Set(1, T(321));
229   EXPECT_EQ(T(123), a->Get(0));
230   EXPECT_EQ(T(321), a->Get(1));
231 
232   Class* aioobe = cl->FindSystemClass(soa.Self(), "Ljava/lang/ArrayIndexOutOfBoundsException;");
233 
234   EXPECT_EQ(0, a->Get(-1));
235   EXPECT_TRUE(soa.Self()->IsExceptionPending());
236   EXPECT_EQ(aioobe, soa.Self()->GetException(NULL)->GetClass());
237   soa.Self()->ClearException();
238 
239   EXPECT_EQ(0, a->Get(2));
240   EXPECT_TRUE(soa.Self()->IsExceptionPending());
241   EXPECT_EQ(aioobe, soa.Self()->GetException(NULL)->GetClass());
242   soa.Self()->ClearException();
243 }
244 
TEST_F(ObjectTest,PrimitiveArray_Boolean_Alloc)245 TEST_F(ObjectTest, PrimitiveArray_Boolean_Alloc) {
246   TestPrimitiveArray<BooleanArray>(class_linker_);
247 }
TEST_F(ObjectTest,PrimitiveArray_Byte_Alloc)248 TEST_F(ObjectTest, PrimitiveArray_Byte_Alloc) {
249   TestPrimitiveArray<ByteArray>(class_linker_);
250 }
TEST_F(ObjectTest,PrimitiveArray_Char_Alloc)251 TEST_F(ObjectTest, PrimitiveArray_Char_Alloc) {
252   TestPrimitiveArray<CharArray>(class_linker_);
253 }
TEST_F(ObjectTest,PrimitiveArray_Double_Alloc)254 TEST_F(ObjectTest, PrimitiveArray_Double_Alloc) {
255   TestPrimitiveArray<DoubleArray>(class_linker_);
256 }
TEST_F(ObjectTest,PrimitiveArray_Float_Alloc)257 TEST_F(ObjectTest, PrimitiveArray_Float_Alloc) {
258   TestPrimitiveArray<FloatArray>(class_linker_);
259 }
TEST_F(ObjectTest,PrimitiveArray_Int_Alloc)260 TEST_F(ObjectTest, PrimitiveArray_Int_Alloc) {
261   TestPrimitiveArray<IntArray>(class_linker_);
262 }
TEST_F(ObjectTest,PrimitiveArray_Long_Alloc)263 TEST_F(ObjectTest, PrimitiveArray_Long_Alloc) {
264   TestPrimitiveArray<LongArray>(class_linker_);
265 }
TEST_F(ObjectTest,PrimitiveArray_Short_Alloc)266 TEST_F(ObjectTest, PrimitiveArray_Short_Alloc) {
267   TestPrimitiveArray<ShortArray>(class_linker_);
268 }
269 
TEST_F(ObjectTest,CheckAndAllocArrayFromCode)270 TEST_F(ObjectTest, CheckAndAllocArrayFromCode) {
271   // pretend we are trying to call 'new char[3]' from String.toCharArray
272   ScopedObjectAccess soa(Thread::Current());
273   Class* java_util_Arrays = class_linker_->FindSystemClass(soa.Self(), "Ljava/util/Arrays;");
274   ArtMethod* sort = java_util_Arrays->FindDirectMethod("sort", "([I)V");
275   const DexFile::StringId* string_id = java_lang_dex_file_->FindStringId("[I");
276   ASSERT_TRUE(string_id != NULL);
277   const DexFile::TypeId* type_id = java_lang_dex_file_->FindTypeId(
278       java_lang_dex_file_->GetIndexForStringId(*string_id));
279   ASSERT_TRUE(type_id != NULL);
280   uint32_t type_idx = java_lang_dex_file_->GetIndexForTypeId(*type_id);
281   Object* array = CheckAndAllocArrayFromCodeInstrumented(type_idx, sort, 3, Thread::Current(), false,
282                                                          Runtime::Current()->GetHeap()->GetCurrentAllocator());
283   EXPECT_TRUE(array->IsArrayInstance());
284   EXPECT_EQ(3, array->AsArray()->GetLength());
285   EXPECT_TRUE(array->GetClass()->IsArrayClass());
286   EXPECT_TRUE(array->GetClass()->GetComponentType()->IsPrimitive());
287 }
288 
TEST_F(ObjectTest,CreateMultiArray)289 TEST_F(ObjectTest, CreateMultiArray) {
290   ScopedObjectAccess soa(Thread::Current());
291 
292   StackHandleScope<2> hs(soa.Self());
293   Handle<Class> c(hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "I")));
294   Handle<IntArray> dims(hs.NewHandle(IntArray::Alloc(soa.Self(), 1)));
295   dims->Set<false>(0, 1);
296   Array* multi = Array::CreateMultiArray(soa.Self(), c, dims);
297   EXPECT_TRUE(multi->GetClass() == class_linker_->FindSystemClass(soa.Self(), "[I"));
298   EXPECT_EQ(1, multi->GetLength());
299 
300   dims->Set<false>(0, -1);
301   multi = Array::CreateMultiArray(soa.Self(), c, dims);
302   EXPECT_TRUE(soa.Self()->IsExceptionPending());
303   EXPECT_EQ(PrettyDescriptor(soa.Self()->GetException(NULL)->GetClass()),
304             "java.lang.NegativeArraySizeException");
305   soa.Self()->ClearException();
306 
307   dims.Assign(IntArray::Alloc(soa.Self(), 2));
308   for (int i = 1; i < 20; ++i) {
309     for (int j = 0; j < 20; ++j) {
310       dims->Set<false>(0, i);
311       dims->Set<false>(1, j);
312       multi = Array::CreateMultiArray(soa.Self(), c, dims);
313       EXPECT_TRUE(multi->GetClass() == class_linker_->FindSystemClass(soa.Self(), "[[I"));
314       EXPECT_EQ(i, multi->GetLength());
315       for (int k = 0; k < i; ++k) {
316         Array* outer = multi->AsObjectArray<Array>()->Get(k);
317         EXPECT_TRUE(outer->GetClass() == class_linker_->FindSystemClass(soa.Self(), "[I"));
318         EXPECT_EQ(j, outer->GetLength());
319       }
320     }
321   }
322 }
323 
TEST_F(ObjectTest,StaticFieldFromCode)324 TEST_F(ObjectTest, StaticFieldFromCode) {
325   // pretend we are trying to access 'Static.s0' from StaticsFromCode.<clinit>
326   ScopedObjectAccess soa(Thread::Current());
327   jobject class_loader = LoadDex("StaticsFromCode");
328   const DexFile* dex_file = Runtime::Current()->GetCompileTimeClassPath(class_loader)[0];
329   CHECK(dex_file != NULL);
330 
331   StackHandleScope<2> hs(soa.Self());
332   Handle<mirror::ClassLoader> loader(hs.NewHandle(soa.Decode<ClassLoader*>(class_loader)));
333   Class* klass = class_linker_->FindClass(soa.Self(), "LStaticsFromCode;", loader);
334   ArtMethod* clinit = klass->FindClassInitializer();
335   const DexFile::StringId* klass_string_id = dex_file->FindStringId("LStaticsFromCode;");
336   ASSERT_TRUE(klass_string_id != NULL);
337   const DexFile::TypeId* klass_type_id = dex_file->FindTypeId(
338       dex_file->GetIndexForStringId(*klass_string_id));
339   ASSERT_TRUE(klass_type_id != NULL);
340 
341   const DexFile::StringId* type_string_id = dex_file->FindStringId("Ljava/lang/Object;");
342   ASSERT_TRUE(type_string_id != NULL);
343   const DexFile::TypeId* type_type_id = dex_file->FindTypeId(
344       dex_file->GetIndexForStringId(*type_string_id));
345   ASSERT_TRUE(type_type_id != NULL);
346 
347   const DexFile::StringId* name_str_id = dex_file->FindStringId("s0");
348   ASSERT_TRUE(name_str_id != NULL);
349 
350   const DexFile::FieldId* field_id = dex_file->FindFieldId(
351       *klass_type_id, *name_str_id, *type_type_id);
352   ASSERT_TRUE(field_id != NULL);
353   uint32_t field_idx = dex_file->GetIndexForFieldId(*field_id);
354 
355   ArtField* field = FindFieldFromCode<StaticObjectRead, true>(field_idx, clinit, Thread::Current(),
356                                                               sizeof(HeapReference<Object>));
357   Object* s0 = field->GetObj(klass);
358   EXPECT_TRUE(s0 != NULL);
359 
360   Handle<CharArray> char_array(hs.NewHandle(CharArray::Alloc(soa.Self(), 0)));
361   field->SetObj<false>(field->GetDeclaringClass(), char_array.Get());
362   EXPECT_EQ(char_array.Get(), field->GetObj(klass));
363 
364   field->SetObj<false>(field->GetDeclaringClass(), NULL);
365   EXPECT_EQ(NULL, field->GetObj(klass));
366 
367   // TODO: more exhaustive tests of all 6 cases of ArtField::*FromCode
368 }
369 
TEST_F(ObjectTest,String)370 TEST_F(ObjectTest, String) {
371   ScopedObjectAccess soa(Thread::Current());
372   // Test the empty string.
373   AssertString(0, "",     "", 0);
374 
375   // Test one-byte characters.
376   AssertString(1, " ",    "\x00\x20",         0x20);
377   AssertString(1, "",     "\x00\x00",         0);
378   AssertString(1, "\x7f", "\x00\x7f",         0x7f);
379   AssertString(2, "hi",   "\x00\x68\x00\x69", (31 * 0x68) + 0x69);
380 
381   // Test two-byte characters.
382   AssertString(1, "\xc2\x80",   "\x00\x80",                 0x80);
383   AssertString(1, "\xd9\xa6",   "\x06\x66",                 0x0666);
384   AssertString(1, "\xdf\xbf",   "\x07\xff",                 0x07ff);
385   AssertString(3, "h\xd9\xa6i", "\x00\x68\x06\x66\x00\x69", (31 * ((31 * 0x68) + 0x0666)) + 0x69);
386 
387   // Test three-byte characters.
388   AssertString(1, "\xe0\xa0\x80",   "\x08\x00",                 0x0800);
389   AssertString(1, "\xe1\x88\xb4",   "\x12\x34",                 0x1234);
390   AssertString(1, "\xef\xbf\xbf",   "\xff\xff",                 0xffff);
391   AssertString(3, "h\xe1\x88\xb4i", "\x00\x68\x12\x34\x00\x69", (31 * ((31 * 0x68) + 0x1234)) + 0x69);
392 }
393 
TEST_F(ObjectTest,StringEqualsUtf8)394 TEST_F(ObjectTest, StringEqualsUtf8) {
395   ScopedObjectAccess soa(Thread::Current());
396   StackHandleScope<2> hs(soa.Self());
397   Handle<String> string(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "android")));
398   EXPECT_TRUE(string->Equals("android"));
399   EXPECT_FALSE(string->Equals("Android"));
400   EXPECT_FALSE(string->Equals("ANDROID"));
401   EXPECT_FALSE(string->Equals(""));
402   EXPECT_FALSE(string->Equals("and"));
403   EXPECT_FALSE(string->Equals("androids"));
404 
405   Handle<String> empty(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "")));
406   EXPECT_TRUE(empty->Equals(""));
407   EXPECT_FALSE(empty->Equals("a"));
408 }
409 
TEST_F(ObjectTest,StringEquals)410 TEST_F(ObjectTest, StringEquals) {
411   ScopedObjectAccess soa(Thread::Current());
412   StackHandleScope<3> hs(soa.Self());
413   Handle<String> string(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "android")));
414   Handle<String> string_2(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "android")));
415   EXPECT_TRUE(string->Equals(string_2.Get()));
416   EXPECT_FALSE(string->Equals("Android"));
417   EXPECT_FALSE(string->Equals("ANDROID"));
418   EXPECT_FALSE(string->Equals(""));
419   EXPECT_FALSE(string->Equals("and"));
420   EXPECT_FALSE(string->Equals("androids"));
421 
422   Handle<String> empty(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "")));
423   EXPECT_TRUE(empty->Equals(""));
424   EXPECT_FALSE(empty->Equals("a"));
425 }
426 
TEST_F(ObjectTest,StringCompareTo)427 TEST_F(ObjectTest, StringCompareTo) {
428   ScopedObjectAccess soa(Thread::Current());
429   StackHandleScope<5> hs(soa.Self());
430   Handle<String> string(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "android")));
431   Handle<String> string_2(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "android")));
432   Handle<String> string_3(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "Android")));
433   Handle<String> string_4(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "and")));
434   Handle<String> string_5(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "")));
435   EXPECT_EQ(0, string->CompareTo(string_2.Get()));
436   EXPECT_LT(0, string->CompareTo(string_3.Get()));
437   EXPECT_GT(0, string_3->CompareTo(string.Get()));
438   EXPECT_LT(0, string->CompareTo(string_4.Get()));
439   EXPECT_GT(0, string_4->CompareTo(string.Get()));
440   EXPECT_LT(0, string->CompareTo(string_5.Get()));
441   EXPECT_GT(0, string_5->CompareTo(string.Get()));
442 }
443 
TEST_F(ObjectTest,StringLength)444 TEST_F(ObjectTest, StringLength) {
445   ScopedObjectAccess soa(Thread::Current());
446   StackHandleScope<1> hs(soa.Self());
447   Handle<String> string(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "android")));
448   EXPECT_EQ(string->GetLength(), 7);
449   EXPECT_EQ(string->GetUtfLength(), 7);
450 
451   string->SetOffset(2);
452   string->SetCount(5);
453   EXPECT_TRUE(string->Equals("droid"));
454   EXPECT_EQ(string->GetLength(), 5);
455   EXPECT_EQ(string->GetUtfLength(), 5);
456 }
457 
TEST_F(ObjectTest,DescriptorCompare)458 TEST_F(ObjectTest, DescriptorCompare) {
459   // Two classloaders conflicts in compile_time_class_paths_.
460   ScopedObjectAccess soa(Thread::Current());
461   ClassLinker* linker = class_linker_;
462 
463   jobject jclass_loader_1 = LoadDex("ProtoCompare");
464   jobject jclass_loader_2 = LoadDex("ProtoCompare2");
465   StackHandleScope<4> hs(soa.Self());
466   Handle<ClassLoader> class_loader_1(hs.NewHandle(soa.Decode<ClassLoader*>(jclass_loader_1)));
467   Handle<ClassLoader> class_loader_2(hs.NewHandle(soa.Decode<ClassLoader*>(jclass_loader_2)));
468 
469   Class* klass1 = linker->FindClass(soa.Self(), "LProtoCompare;", class_loader_1);
470   ASSERT_TRUE(klass1 != NULL);
471   Class* klass2 = linker->FindClass(soa.Self(), "LProtoCompare2;", class_loader_2);
472   ASSERT_TRUE(klass2 != NULL);
473 
474   ArtMethod* m1_1 = klass1->GetVirtualMethod(0);
475   EXPECT_STREQ(m1_1->GetName(), "m1");
476   ArtMethod* m2_1 = klass1->GetVirtualMethod(1);
477   EXPECT_STREQ(m2_1->GetName(), "m2");
478   ArtMethod* m3_1 = klass1->GetVirtualMethod(2);
479   EXPECT_STREQ(m3_1->GetName(), "m3");
480   ArtMethod* m4_1 = klass1->GetVirtualMethod(3);
481   EXPECT_STREQ(m4_1->GetName(), "m4");
482 
483   ArtMethod* m1_2 = klass2->GetVirtualMethod(0);
484   EXPECT_STREQ(m1_2->GetName(), "m1");
485   ArtMethod* m2_2 = klass2->GetVirtualMethod(1);
486   EXPECT_STREQ(m2_2->GetName(), "m2");
487   ArtMethod* m3_2 = klass2->GetVirtualMethod(2);
488   EXPECT_STREQ(m3_2->GetName(), "m3");
489   ArtMethod* m4_2 = klass2->GetVirtualMethod(3);
490   EXPECT_STREQ(m4_2->GetName(), "m4");
491 
492   MethodHelper mh(hs.NewHandle(m1_1));
493   MethodHelper mh2(hs.NewHandle(m1_2));
494   EXPECT_TRUE(mh.HasSameNameAndSignature(&mh2));
495   EXPECT_TRUE(mh2.HasSameNameAndSignature(&mh));
496 
497   mh.ChangeMethod(m2_1);
498   mh2.ChangeMethod(m2_2);
499   EXPECT_TRUE(mh.HasSameNameAndSignature(&mh2));
500   EXPECT_TRUE(mh2.HasSameNameAndSignature(&mh));
501 
502   mh.ChangeMethod(m3_1);
503   mh2.ChangeMethod(m3_2);
504   EXPECT_TRUE(mh.HasSameNameAndSignature(&mh2));
505   EXPECT_TRUE(mh2.HasSameNameAndSignature(&mh));
506 
507   mh.ChangeMethod(m4_1);
508   mh2.ChangeMethod(m4_2);
509   EXPECT_TRUE(mh.HasSameNameAndSignature(&mh2));
510   EXPECT_TRUE(mh2.HasSameNameAndSignature(&mh));
511 }
512 
TEST_F(ObjectTest,StringHashCode)513 TEST_F(ObjectTest, StringHashCode) {
514   ScopedObjectAccess soa(Thread::Current());
515   StackHandleScope<3> hs(soa.Self());
516   Handle<String> empty(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "")));
517   Handle<String> A(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "A")));
518   Handle<String> ABC(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "ABC")));
519 
520   EXPECT_EQ(0, empty->GetHashCode());
521   EXPECT_EQ(65, A->GetHashCode());
522   EXPECT_EQ(64578, ABC->GetHashCode());
523 }
524 
TEST_F(ObjectTest,InstanceOf)525 TEST_F(ObjectTest, InstanceOf) {
526   ScopedObjectAccess soa(Thread::Current());
527   jobject jclass_loader = LoadDex("XandY");
528   StackHandleScope<3> hs(soa.Self());
529   Handle<ClassLoader> class_loader(hs.NewHandle(soa.Decode<ClassLoader*>(jclass_loader)));
530 
531   Class* X = class_linker_->FindClass(soa.Self(), "LX;", class_loader);
532   Class* Y = class_linker_->FindClass(soa.Self(), "LY;", class_loader);
533   ASSERT_TRUE(X != NULL);
534   ASSERT_TRUE(Y != NULL);
535 
536   Handle<Object> x(hs.NewHandle(X->AllocObject(soa.Self())));
537   Handle<Object> y(hs.NewHandle(Y->AllocObject(soa.Self())));
538   ASSERT_TRUE(x.Get() != NULL);
539   ASSERT_TRUE(y.Get() != NULL);
540 
541   EXPECT_TRUE(x->InstanceOf(X));
542   EXPECT_FALSE(x->InstanceOf(Y));
543   EXPECT_TRUE(y->InstanceOf(X));
544   EXPECT_TRUE(y->InstanceOf(Y));
545 
546   Class* java_lang_Class = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Class;");
547   Class* Object_array_class = class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/Object;");
548 
549   EXPECT_FALSE(java_lang_Class->InstanceOf(Object_array_class));
550   EXPECT_TRUE(Object_array_class->InstanceOf(java_lang_Class));
551 
552   // All array classes implement Cloneable and Serializable.
553   Object* array = ObjectArray<Object>::Alloc(soa.Self(), Object_array_class, 1);
554   Class* java_lang_Cloneable = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Cloneable;");
555   Class* java_io_Serializable = class_linker_->FindSystemClass(soa.Self(), "Ljava/io/Serializable;");
556   EXPECT_TRUE(array->InstanceOf(java_lang_Cloneable));
557   EXPECT_TRUE(array->InstanceOf(java_io_Serializable));
558 }
559 
TEST_F(ObjectTest,IsAssignableFrom)560 TEST_F(ObjectTest, IsAssignableFrom) {
561   ScopedObjectAccess soa(Thread::Current());
562   jobject jclass_loader = LoadDex("XandY");
563   StackHandleScope<1> hs(soa.Self());
564   Handle<ClassLoader> class_loader(hs.NewHandle(soa.Decode<ClassLoader*>(jclass_loader)));
565   Class* X = class_linker_->FindClass(soa.Self(), "LX;", class_loader);
566   Class* Y = class_linker_->FindClass(soa.Self(), "LY;", class_loader);
567 
568   EXPECT_TRUE(X->IsAssignableFrom(X));
569   EXPECT_TRUE(X->IsAssignableFrom(Y));
570   EXPECT_FALSE(Y->IsAssignableFrom(X));
571   EXPECT_TRUE(Y->IsAssignableFrom(Y));
572 
573   // class final String implements CharSequence, ..
574   Class* string = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/String;");
575   Class* charseq = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/CharSequence;");
576   // Can String be assigned to CharSequence without a cast?
577   EXPECT_TRUE(charseq->IsAssignableFrom(string));
578   // Can CharSequence be assigned to String without a cast?
579   EXPECT_FALSE(string->IsAssignableFrom(charseq));
580 
581   // Primitive types are only assignable to themselves
582   const char* prims = "ZBCSIJFD";
583   Class* prim_types[strlen(prims)];
584   for (size_t i = 0; i < strlen(prims); i++) {
585     prim_types[i] = class_linker_->FindPrimitiveClass(prims[i]);
586   }
587   for (size_t i = 0; i < strlen(prims); i++) {
588     for (size_t j = 0; i < strlen(prims); i++) {
589       if (i == j) {
590         EXPECT_TRUE(prim_types[i]->IsAssignableFrom(prim_types[j]));
591       } else {
592         EXPECT_FALSE(prim_types[i]->IsAssignableFrom(prim_types[j]));
593       }
594     }
595   }
596 }
597 
TEST_F(ObjectTest,IsAssignableFromArray)598 TEST_F(ObjectTest, IsAssignableFromArray) {
599   ScopedObjectAccess soa(Thread::Current());
600   jobject jclass_loader = LoadDex("XandY");
601   StackHandleScope<1> hs(soa.Self());
602   Handle<ClassLoader> class_loader(hs.NewHandle(soa.Decode<ClassLoader*>(jclass_loader)));
603   Class* X = class_linker_->FindClass(soa.Self(), "LX;", class_loader);
604   Class* Y = class_linker_->FindClass(soa.Self(), "LY;", class_loader);
605   ASSERT_TRUE(X != NULL);
606   ASSERT_TRUE(Y != NULL);
607 
608   Class* YA = class_linker_->FindClass(soa.Self(), "[LY;", class_loader);
609   Class* YAA = class_linker_->FindClass(soa.Self(), "[[LY;", class_loader);
610   ASSERT_TRUE(YA != NULL);
611   ASSERT_TRUE(YAA != NULL);
612 
613   Class* XAA = class_linker_->FindClass(soa.Self(), "[[LX;", class_loader);
614   ASSERT_TRUE(XAA != NULL);
615 
616   Class* O = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;");
617   Class* OA = class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/Object;");
618   Class* OAA = class_linker_->FindSystemClass(soa.Self(), "[[Ljava/lang/Object;");
619   Class* OAAA = class_linker_->FindSystemClass(soa.Self(), "[[[Ljava/lang/Object;");
620   ASSERT_TRUE(O != NULL);
621   ASSERT_TRUE(OA != NULL);
622   ASSERT_TRUE(OAA != NULL);
623   ASSERT_TRUE(OAAA != NULL);
624 
625   Class* S = class_linker_->FindSystemClass(soa.Self(), "Ljava/io/Serializable;");
626   Class* SA = class_linker_->FindSystemClass(soa.Self(), "[Ljava/io/Serializable;");
627   Class* SAA = class_linker_->FindSystemClass(soa.Self(), "[[Ljava/io/Serializable;");
628   ASSERT_TRUE(S != NULL);
629   ASSERT_TRUE(SA != NULL);
630   ASSERT_TRUE(SAA != NULL);
631 
632   Class* IA = class_linker_->FindSystemClass(soa.Self(), "[I");
633   ASSERT_TRUE(IA != NULL);
634 
635   EXPECT_TRUE(YAA->IsAssignableFrom(YAA));  // identity
636   EXPECT_TRUE(XAA->IsAssignableFrom(YAA));  // element superclass
637   EXPECT_FALSE(YAA->IsAssignableFrom(XAA));
638   EXPECT_FALSE(Y->IsAssignableFrom(YAA));
639   EXPECT_FALSE(YA->IsAssignableFrom(YAA));
640   EXPECT_TRUE(O->IsAssignableFrom(YAA));  // everything is an Object
641   EXPECT_TRUE(OA->IsAssignableFrom(YAA));
642   EXPECT_TRUE(OAA->IsAssignableFrom(YAA));
643   EXPECT_TRUE(S->IsAssignableFrom(YAA));  // all arrays are Serializable
644   EXPECT_TRUE(SA->IsAssignableFrom(YAA));
645   EXPECT_FALSE(SAA->IsAssignableFrom(YAA));  // unless Y was Serializable
646 
647   EXPECT_FALSE(IA->IsAssignableFrom(OA));
648   EXPECT_FALSE(OA->IsAssignableFrom(IA));
649   EXPECT_TRUE(O->IsAssignableFrom(IA));
650 }
651 
TEST_F(ObjectTest,FindInstanceField)652 TEST_F(ObjectTest, FindInstanceField) {
653   ScopedObjectAccess soa(Thread::Current());
654   StackHandleScope<1> hs(soa.Self());
655   Handle<String> s(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "ABC")));
656   ASSERT_TRUE(s.Get() != NULL);
657   Class* c = s->GetClass();
658   ASSERT_TRUE(c != NULL);
659 
660   // Wrong type.
661   EXPECT_TRUE(c->FindDeclaredInstanceField("count", "J") == NULL);
662   EXPECT_TRUE(c->FindInstanceField("count", "J") == NULL);
663 
664   // Wrong name.
665   EXPECT_TRUE(c->FindDeclaredInstanceField("Count", "I") == NULL);
666   EXPECT_TRUE(c->FindInstanceField("Count", "I") == NULL);
667 
668   // Right name and type.
669   ArtField* f1 = c->FindDeclaredInstanceField("count", "I");
670   ArtField* f2 = c->FindInstanceField("count", "I");
671   EXPECT_TRUE(f1 != NULL);
672   EXPECT_TRUE(f2 != NULL);
673   EXPECT_EQ(f1, f2);
674 
675   // TODO: check that s.count == 3.
676 
677   // Ensure that we handle superclass fields correctly...
678   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/StringBuilder;");
679   ASSERT_TRUE(c != NULL);
680   // No StringBuilder.count...
681   EXPECT_TRUE(c->FindDeclaredInstanceField("count", "I") == NULL);
682   // ...but there is an AbstractStringBuilder.count.
683   EXPECT_TRUE(c->FindInstanceField("count", "I") != NULL);
684 }
685 
TEST_F(ObjectTest,FindStaticField)686 TEST_F(ObjectTest, FindStaticField) {
687   ScopedObjectAccess soa(Thread::Current());
688   StackHandleScope<4> hs(soa.Self());
689   Handle<String> s(hs.NewHandle(String::AllocFromModifiedUtf8(soa.Self(), "ABC")));
690   ASSERT_TRUE(s.Get() != NULL);
691   Handle<Class> c(hs.NewHandle(s->GetClass()));
692   ASSERT_TRUE(c.Get() != NULL);
693 
694   // Wrong type.
695   EXPECT_TRUE(c->FindDeclaredStaticField("CASE_INSENSITIVE_ORDER", "I") == NULL);
696   EXPECT_TRUE(mirror::Class::FindStaticField(soa.Self(), c, "CASE_INSENSITIVE_ORDER", "I") == NULL);
697 
698   // Wrong name.
699   EXPECT_TRUE(c->FindDeclaredStaticField("cASE_INSENSITIVE_ORDER", "Ljava/util/Comparator;") == NULL);
700   EXPECT_TRUE(
701       mirror::Class::FindStaticField(soa.Self(), c, "cASE_INSENSITIVE_ORDER",
702                                      "Ljava/util/Comparator;") == NULL);
703 
704   // Right name and type.
705   Handle<ArtField> f1(hs.NewHandle(
706       c->FindDeclaredStaticField("CASE_INSENSITIVE_ORDER", "Ljava/util/Comparator;")));
707   Handle<ArtField> f2(hs.NewHandle(
708       mirror::Class::FindStaticField(soa.Self(), c, "CASE_INSENSITIVE_ORDER",
709                                      "Ljava/util/Comparator;")));
710   EXPECT_TRUE(f1.Get() != NULL);
711   EXPECT_TRUE(f2.Get() != NULL);
712   EXPECT_EQ(f1.Get(), f2.Get());
713 
714   // TODO: test static fields via superclasses.
715   // TODO: test static fields via interfaces.
716   // TODO: test that interfaces trump superclasses.
717 }
718 
TEST_F(ObjectTest,IdentityHashCode)719 TEST_F(ObjectTest, IdentityHashCode) {
720   // Regression test for b/19046417 which had an infinite loop if the
721   // (seed & LockWord::kHashMask) == 0. seed 0 triggered the infinite loop since we did the check
722   // before the CAS which resulted in the same seed the next loop iteration.
723   mirror::Object::SetHashCodeSeed(0);
724   int32_t hash_code = mirror::Object::GenerateIdentityHashCode();
725   EXPECT_NE(hash_code, 0);
726 }
727 
728 }  // namespace mirror
729 }  // namespace art
730