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 <ctime>
18
19 #include "object.h"
20
21 #include "art_field.h"
22 #include "art_field-inl.h"
23 #include "array-inl.h"
24 #include "class.h"
25 #include "class-inl.h"
26 #include "class_linker-inl.h"
27 #include "field_helper.h"
28 #include "gc/accounting/card_table-inl.h"
29 #include "gc/heap.h"
30 #include "iftable-inl.h"
31 #include "monitor.h"
32 #include "object-inl.h"
33 #include "object_array-inl.h"
34 #include "runtime.h"
35 #include "handle_scope-inl.h"
36 #include "throwable.h"
37 #include "well_known_classes.h"
38
39 namespace art {
40 namespace mirror {
41
42 Atomic<uint32_t> Object::hash_code_seed(987654321U + std::time(nullptr));
43
44 class CopyReferenceFieldsWithReadBarrierVisitor {
45 public:
CopyReferenceFieldsWithReadBarrierVisitor(Object * dest_obj)46 explicit CopyReferenceFieldsWithReadBarrierVisitor(Object* dest_obj)
47 : dest_obj_(dest_obj) {}
48
operator ()(Object * obj,MemberOffset offset,bool) const49 void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const
50 ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
51 // GetFieldObject() contains a RB.
52 Object* ref = obj->GetFieldObject<Object>(offset);
53 // No WB here as a large object space does not have a card table
54 // coverage. Instead, cards will be marked separately.
55 dest_obj_->SetFieldObjectWithoutWriteBarrier<false, false>(offset, ref);
56 }
57
operator ()(mirror::Class * klass,mirror::Reference * ref) const58 void operator()(mirror::Class* klass, mirror::Reference* ref) const
59 ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
60 // Copy java.lang.ref.Reference.referent which isn't visited in
61 // Object::VisitReferences().
62 DCHECK(klass->IsTypeOfReferenceClass());
63 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
64 }
65
66 private:
67 Object* const dest_obj_;
68 };
69
CopyObject(Thread * self,mirror::Object * dest,mirror::Object * src,size_t num_bytes)70 Object* Object::CopyObject(Thread* self, mirror::Object* dest, mirror::Object* src,
71 size_t num_bytes) {
72 // Copy instance data. We assume memcpy copies by words.
73 // TODO: expose and use move32.
74 byte* src_bytes = reinterpret_cast<byte*>(src);
75 byte* dst_bytes = reinterpret_cast<byte*>(dest);
76 size_t offset = sizeof(Object);
77 memcpy(dst_bytes + offset, src_bytes + offset, num_bytes - offset);
78 if (kUseBakerOrBrooksReadBarrier) {
79 // We need a RB here. After the memcpy that covers the whole
80 // object above, copy references fields one by one again with a
81 // RB. TODO: Optimize this later?
82 CopyReferenceFieldsWithReadBarrierVisitor visitor(dest);
83 src->VisitReferences<true>(visitor, visitor);
84 }
85 gc::Heap* heap = Runtime::Current()->GetHeap();
86 // Perform write barriers on copied object references.
87 Class* c = src->GetClass();
88 if (c->IsArrayClass()) {
89 if (!c->GetComponentType()->IsPrimitive()) {
90 ObjectArray<Object>* array = dest->AsObjectArray<Object>();
91 heap->WriteBarrierArray(dest, 0, array->GetLength());
92 }
93 } else {
94 heap->WriteBarrierEveryFieldOf(dest);
95 }
96 if (c->IsFinalizable()) {
97 heap->AddFinalizerReference(self, &dest);
98 }
99 return dest;
100 }
101
102 // An allocation pre-fence visitor that copies the object.
103 class CopyObjectVisitor {
104 public:
CopyObjectVisitor(Thread * self,Handle<Object> * orig,size_t num_bytes)105 explicit CopyObjectVisitor(Thread* self, Handle<Object>* orig, size_t num_bytes)
106 : self_(self), orig_(orig), num_bytes_(num_bytes) {
107 }
108
operator ()(Object * obj,size_t usable_size) const109 void operator()(Object* obj, size_t usable_size) const
110 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
111 UNUSED(usable_size);
112 Object::CopyObject(self_, obj, orig_->Get(), num_bytes_);
113 }
114
115 private:
116 Thread* const self_;
117 Handle<Object>* const orig_;
118 const size_t num_bytes_;
119 DISALLOW_COPY_AND_ASSIGN(CopyObjectVisitor);
120 };
121
Clone(Thread * self)122 Object* Object::Clone(Thread* self) {
123 CHECK(!IsClass()) << "Can't clone classes.";
124 // Object::SizeOf gets the right size even if we're an array. Using c->AllocObject() here would
125 // be wrong.
126 gc::Heap* heap = Runtime::Current()->GetHeap();
127 size_t num_bytes = SizeOf();
128 StackHandleScope<1> hs(self);
129 Handle<Object> this_object(hs.NewHandle(this));
130 Object* copy;
131 CopyObjectVisitor visitor(self, &this_object, num_bytes);
132 if (heap->IsMovableObject(this)) {
133 copy = heap->AllocObject<true>(self, GetClass(), num_bytes, visitor);
134 } else {
135 copy = heap->AllocNonMovableObject<true>(self, GetClass(), num_bytes, visitor);
136 }
137 return copy;
138 }
139
GenerateIdentityHashCode()140 uint32_t Object::GenerateIdentityHashCode() {
141 uint32_t expected_value, new_value;
142 do {
143 expected_value = hash_code_seed.LoadRelaxed();
144 new_value = expected_value * 1103515245 + 12345;
145 } while (!hash_code_seed.CompareExchangeWeakRelaxed(expected_value, new_value) ||
146 (expected_value & LockWord::kHashMask) == 0);
147 return expected_value & LockWord::kHashMask;
148 }
149
SetHashCodeSeed(uint32_t new_seed)150 void Object::SetHashCodeSeed(uint32_t new_seed) {
151 hash_code_seed.StoreRelaxed(new_seed);
152 }
153
IdentityHashCode() const154 int32_t Object::IdentityHashCode() const {
155 mirror::Object* current_this = const_cast<mirror::Object*>(this);
156 while (true) {
157 LockWord lw = current_this->GetLockWord(false);
158 switch (lw.GetState()) {
159 case LockWord::kUnlocked: {
160 // Try to compare and swap in a new hash, if we succeed we will return the hash on the next
161 // loop iteration.
162 LockWord hash_word(LockWord::FromHashCode(GenerateIdentityHashCode()));
163 DCHECK_EQ(hash_word.GetState(), LockWord::kHashCode);
164 if (const_cast<Object*>(this)->CasLockWordWeakRelaxed(lw, hash_word)) {
165 return hash_word.GetHashCode();
166 }
167 break;
168 }
169 case LockWord::kThinLocked: {
170 // Inflate the thin lock to a monitor and stick the hash code inside of the monitor. May
171 // fail spuriously.
172 Thread* self = Thread::Current();
173 StackHandleScope<1> hs(self);
174 Handle<mirror::Object> h_this(hs.NewHandle(current_this));
175 Monitor::InflateThinLocked(self, h_this, lw, GenerateIdentityHashCode());
176 // A GC may have occurred when we switched to kBlocked.
177 current_this = h_this.Get();
178 break;
179 }
180 case LockWord::kFatLocked: {
181 // Already inflated, return the has stored in the monitor.
182 Monitor* monitor = lw.FatLockMonitor();
183 DCHECK(monitor != nullptr);
184 return monitor->GetHashCode();
185 }
186 case LockWord::kHashCode: {
187 return lw.GetHashCode();
188 }
189 default: {
190 LOG(FATAL) << "Invalid state during hashcode " << lw.GetState();
191 break;
192 }
193 }
194 }
195 LOG(FATAL) << "Unreachable";
196 return 0;
197 }
198
CheckFieldAssignmentImpl(MemberOffset field_offset,Object * new_value)199 void Object::CheckFieldAssignmentImpl(MemberOffset field_offset, Object* new_value) {
200 Class* c = GetClass();
201 Runtime* runtime = Runtime::Current();
202 if (runtime->GetClassLinker() == nullptr || !runtime->IsStarted() ||
203 !runtime->GetHeap()->IsObjectValidationEnabled() || !c->IsResolved()) {
204 return;
205 }
206 for (Class* cur = c; cur != NULL; cur = cur->GetSuperClass()) {
207 ObjectArray<ArtField>* fields = cur->GetIFields();
208 if (fields != NULL) {
209 size_t num_ifields = fields->GetLength();
210 for (size_t i = 0; i < num_ifields; ++i) {
211 ArtField* field = fields->Get(i);
212 if (field->GetOffset().Int32Value() == field_offset.Int32Value()) {
213 CHECK_NE(field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
214 StackHandleScope<1> hs(Thread::Current());
215 FieldHelper fh(hs.NewHandle(field));
216 CHECK(fh.GetType()->IsAssignableFrom(new_value->GetClass()));
217 return;
218 }
219 }
220 }
221 }
222 if (c->IsArrayClass()) {
223 // Bounds and assign-ability done in the array setter.
224 return;
225 }
226 if (IsClass()) {
227 ObjectArray<ArtField>* fields = AsClass()->GetSFields();
228 if (fields != NULL) {
229 size_t num_sfields = fields->GetLength();
230 for (size_t i = 0; i < num_sfields; ++i) {
231 ArtField* field = fields->Get(i);
232 if (field->GetOffset().Int32Value() == field_offset.Int32Value()) {
233 CHECK_NE(field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
234 StackHandleScope<1> hs(Thread::Current());
235 FieldHelper fh(hs.NewHandle(field));
236 CHECK(fh.GetType()->IsAssignableFrom(new_value->GetClass()));
237 return;
238 }
239 }
240 }
241 }
242 LOG(FATAL) << "Failed to find field for assignment to " << reinterpret_cast<void*>(this)
243 << " of type " << PrettyDescriptor(c) << " at offset " << field_offset;
244 }
245
246 } // namespace mirror
247 } // namespace art
248