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 "array-inl.h"
22 #include "art_field-inl.h"
23 #include "art_field.h"
24 #include "class-inl.h"
25 #include "class.h"
26 #include "class_linker-inl.h"
27 #include "dex/descriptors_names.h"
28 #include "dex/dex_file-inl.h"
29 #include "gc/accounting/card_table-inl.h"
30 #include "gc/heap-inl.h"
31 #include "handle_scope-inl.h"
32 #include "iftable-inl.h"
33 #include "monitor.h"
34 #include "object-inl.h"
35 #include "object-refvisitor-inl.h"
36 #include "object_array-inl.h"
37 #include "runtime.h"
38 #include "throwable.h"
39 #include "well_known_classes.h"
40 
41 namespace art HIDDEN {
42 namespace mirror {
43 
44 Atomic<uint32_t> Object::hash_code_seed(987654321U + std::time(nullptr));
45 
46 class CopyReferenceFieldsWithReadBarrierVisitor {
47  public:
CopyReferenceFieldsWithReadBarrierVisitor(ObjPtr<Object> dest_obj)48   explicit CopyReferenceFieldsWithReadBarrierVisitor(ObjPtr<Object> dest_obj)
49       : dest_obj_(dest_obj) {}
50 
operator ()(ObjPtr<Object> obj,MemberOffset offset,bool) const51   void operator()(ObjPtr<Object> obj, MemberOffset offset, bool /* is_static */) const
52       ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_) {
53     // GetFieldObject() contains a RB.
54     ObjPtr<Object> ref = obj->GetFieldObject<Object>(offset);
55     // No WB here as a large object space does not have a card table
56     // coverage. Instead, cards will be marked separately.
57     dest_obj_->SetFieldObjectWithoutWriteBarrier<false, false>(offset, ref);
58   }
59 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const60   void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
61       ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_) {
62     // Copy java.lang.ref.Reference.referent which isn't visited in
63     // Object::VisitReferences().
64     DCHECK(klass->IsTypeOfReferenceClass());
65     this->operator()(ref, mirror::Reference::ReferentOffset(), false);
66   }
67 
68   // Unused since we don't copy class native roots.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const69   void VisitRootIfNonNull(
70       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const71   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
72 
73  private:
74   const ObjPtr<Object> dest_obj_;
75 };
76 
CopyRawObjectData(uint8_t * dst_bytes,ObjPtr<mirror::Object> src,size_t num_bytes)77 void Object::CopyRawObjectData(uint8_t* dst_bytes,
78                                ObjPtr<mirror::Object> src,
79                                size_t num_bytes) {
80   // Copy instance data.  Don't assume memcpy copies by words (b/32012820).
81   const size_t offset = sizeof(Object);
82   uint8_t* src_bytes = reinterpret_cast<uint8_t*>(src.Ptr()) + offset;
83   dst_bytes += offset;
84   DCHECK_ALIGNED(src_bytes, sizeof(uintptr_t));
85   DCHECK_ALIGNED(dst_bytes, sizeof(uintptr_t));
86   // Use word sized copies to begin.
87   while (num_bytes >= sizeof(uintptr_t)) {
88     reinterpret_cast<Atomic<uintptr_t>*>(dst_bytes)->store(
89         reinterpret_cast<Atomic<uintptr_t>*>(src_bytes)->load(std::memory_order_relaxed),
90         std::memory_order_relaxed);
91     src_bytes += sizeof(uintptr_t);
92     dst_bytes += sizeof(uintptr_t);
93     num_bytes -= sizeof(uintptr_t);
94   }
95   // Copy possible 32 bit word.
96   if (sizeof(uintptr_t) != sizeof(uint32_t) && num_bytes >= sizeof(uint32_t)) {
97     reinterpret_cast<Atomic<uint32_t>*>(dst_bytes)->store(
98         reinterpret_cast<Atomic<uint32_t>*>(src_bytes)->load(std::memory_order_relaxed),
99         std::memory_order_relaxed);
100     src_bytes += sizeof(uint32_t);
101     dst_bytes += sizeof(uint32_t);
102     num_bytes -= sizeof(uint32_t);
103   }
104   // Copy remaining bytes, avoid going past the end of num_bytes since there may be a redzone
105   // there.
106   while (num_bytes > 0) {
107     reinterpret_cast<Atomic<uint8_t>*>(dst_bytes)->store(
108         reinterpret_cast<Atomic<uint8_t>*>(src_bytes)->load(std::memory_order_relaxed),
109         std::memory_order_relaxed);
110     src_bytes += sizeof(uint8_t);
111     dst_bytes += sizeof(uint8_t);
112     num_bytes -= sizeof(uint8_t);
113   }
114 }
115 
CopyObject(ObjPtr<mirror::Object> dest,ObjPtr<mirror::Object> src,size_t num_bytes)116 ObjPtr<Object> Object::CopyObject(ObjPtr<mirror::Object> dest,
117                                   ObjPtr<mirror::Object> src,
118                                   size_t num_bytes) {
119   // Copy everything but the header.
120   CopyRawObjectData(reinterpret_cast<uint8_t*>(dest.Ptr()), src, num_bytes - sizeof(Object));
121 
122   if (gUseReadBarrier) {
123     // We need a RB here. After copying the whole object above, copy references fields one by one
124     // again with a RB to make sure there are no from space refs. TODO: Optimize this later?
125     CopyReferenceFieldsWithReadBarrierVisitor visitor(dest);
126     src->VisitReferences(visitor, visitor);
127   }
128   // Perform write barriers on copied object references.
129   ObjPtr<Class> c = src->GetClass();
130   if (c->IsArrayClass()) {
131     if (!c->GetComponentType()->IsPrimitive()) {
132       ObjPtr<ObjectArray<Object>> array = dest->AsObjectArray<Object>();
133       WriteBarrier::ForArrayWrite(dest, 0, array->GetLength());
134     }
135   } else {
136     WriteBarrier::ForEveryFieldWrite(dest);
137   }
138   return dest;
139 }
140 
141 // An allocation pre-fence visitor that copies the object.
142 class CopyObjectVisitor {
143  public:
CopyObjectVisitor(Handle<Object> * orig,size_t num_bytes)144   CopyObjectVisitor(Handle<Object>* orig, size_t num_bytes)
145       : orig_(orig), num_bytes_(num_bytes) {}
146 
operator ()(ObjPtr<Object> obj,size_t usable_size) const147   void operator()(ObjPtr<Object> obj, [[maybe_unused]] size_t usable_size) const
148       REQUIRES_SHARED(Locks::mutator_lock_) {
149     Object::CopyObject(obj, orig_->Get(), num_bytes_);
150   }
151 
152  private:
153   Handle<Object>* const orig_;
154   const size_t num_bytes_;
155   DISALLOW_COPY_AND_ASSIGN(CopyObjectVisitor);
156 };
157 
Clone(Handle<Object> h_this,Thread * self)158 ObjPtr<Object> Object::Clone(Handle<Object> h_this, Thread* self) {
159   CHECK(!h_this->IsClass()) << "Can't clone classes.";
160   // Object::SizeOf gets the right size even if we're an array. Using c->AllocObject() here would
161   // be wrong.
162   gc::Heap* heap = Runtime::Current()->GetHeap();
163   size_t num_bytes = h_this->SizeOf();
164   CopyObjectVisitor visitor(&h_this, num_bytes);
165   ObjPtr<Object> copy = heap->IsMovableObject(h_this.Get())
166       ? heap->AllocObject(self, h_this->GetClass(), num_bytes, visitor)
167       : heap->AllocNonMovableObject(self, h_this->GetClass(), num_bytes, visitor);
168   if (h_this->GetClass()->IsFinalizable()) {
169     heap->AddFinalizerReference(self, &copy);
170   }
171   return copy;
172 }
173 
GenerateIdentityHashCode()174 uint32_t Object::GenerateIdentityHashCode() {
175   uint32_t expected_value, new_value;
176   do {
177     expected_value = hash_code_seed.load(std::memory_order_relaxed);
178     new_value = expected_value * 1103515245 + 12345;
179   } while (!hash_code_seed.CompareAndSetWeakRelaxed(expected_value, new_value) ||
180       (expected_value & LockWord::kHashMask) == 0);
181   return expected_value & LockWord::kHashMask;
182 }
183 
SetHashCodeSeed(uint32_t new_seed)184 void Object::SetHashCodeSeed(uint32_t new_seed) {
185   hash_code_seed.store(new_seed, std::memory_order_relaxed);
186 }
187 
188 template <bool kAllowInflation>
IdentityHashCodeHelper()189 int32_t Object::IdentityHashCodeHelper() {
190   ObjPtr<Object> current_this = this;  // The this pointer may get invalidated by thread suspension.
191   while (true) {
192     LockWord lw = current_this->GetLockWord(false);
193     switch (lw.GetState()) {
194       case LockWord::kUnlocked: {
195         // Try to compare and swap in a new hash, if we succeed we will return the hash on the next
196         // loop iteration.
197         LockWord hash_word = LockWord::FromHashCode(GenerateIdentityHashCode(), lw.GCState());
198         DCHECK_EQ(hash_word.GetState(), LockWord::kHashCode);
199         // Use a strong CAS to prevent spurious failures since these can make the boot image
200         // non-deterministic.
201         if (current_this->CasLockWord(lw, hash_word, CASMode::kStrong, std::memory_order_relaxed)) {
202           return hash_word.GetHashCode();
203         }
204         break;
205       }
206       case LockWord::kThinLocked: {
207         if (!kAllowInflation) {
208           return 0;
209         }
210         // Inflate the thin lock to a monitor and stick the hash code inside of the monitor. May
211         // fail spuriously.
212         Thread* self = Thread::Current();
213         StackHandleScope<1> hs(self);
214         Handle<mirror::Object> h_this(hs.NewHandle(current_this));
215         Monitor::InflateThinLocked(self, h_this, lw, GenerateIdentityHashCode());
216         // A GC may have occurred when we switched to kBlocked.
217         current_this = h_this.Get();
218         break;
219       }
220       case LockWord::kFatLocked: {
221         // Already inflated, return the hash stored in the monitor.
222         Monitor* monitor = lw.FatLockMonitor();
223         DCHECK(monitor != nullptr);
224         return monitor->GetHashCode();
225       }
226       case LockWord::kHashCode: {
227         return lw.GetHashCode();
228       }
229       default: {
230         LOG(FATAL) << "Invalid state during hashcode " << lw.GetState();
231         UNREACHABLE();
232       }
233     }
234   }
235 }
236 
IdentityHashCode()237 int32_t Object::IdentityHashCode() { return IdentityHashCodeHelper</* kAllowInflation= */ true>(); }
238 
IdentityHashCodeNoInflation()239 int32_t Object::IdentityHashCodeNoInflation() {
240   return IdentityHashCodeHelper</* kAllowInflation= */ false>();
241 }
242 
CheckFieldAssignmentImpl(MemberOffset field_offset,ObjPtr<Object> new_value)243 void Object::CheckFieldAssignmentImpl(MemberOffset field_offset, ObjPtr<Object> new_value) {
244   ObjPtr<Class> c = GetClass();
245   Runtime* runtime = Runtime::Current();
246   if (runtime->GetClassLinker() == nullptr || !runtime->IsStarted() ||
247       !runtime->GetHeap()->IsObjectValidationEnabled() || !c->IsResolved()) {
248     return;
249   }
250   for (ObjPtr<Class> cur = c; cur != nullptr; cur = cur->GetSuperClass()) {
251     for (ArtField& field : cur->GetIFields()) {
252       if (field.GetOffset().Int32Value() == field_offset.Int32Value()) {
253         CHECK_NE(field.GetTypeAsPrimitiveType(), Primitive::kPrimNot);
254         // TODO: resolve the field type for moving GC.
255         ObjPtr<mirror::Class> field_type =
256             kMovingCollector ? field.LookupResolvedType() : field.ResolveType();
257         if (field_type != nullptr) {
258           CHECK(field_type->IsAssignableFrom(new_value->GetClass()));
259         }
260         return;
261       }
262     }
263   }
264   if (c->IsArrayClass()) {
265     // Bounds and assign-ability done in the array setter.
266     return;
267   }
268   if (IsClass()) {
269     for (ArtField& field : AsClass()->GetSFields()) {
270       if (field.GetOffset().Int32Value() == field_offset.Int32Value()) {
271         CHECK_NE(field.GetTypeAsPrimitiveType(), Primitive::kPrimNot);
272         // TODO: resolve the field type for moving GC.
273         ObjPtr<mirror::Class> field_type =
274             kMovingCollector ? field.LookupResolvedType() : field.ResolveType();
275         if (field_type != nullptr) {
276           CHECK(field_type->IsAssignableFrom(new_value->GetClass()));
277         }
278         return;
279       }
280     }
281   }
282   LOG(FATAL) << "Failed to find field for assignment to " << reinterpret_cast<void*>(this)
283              << " of type " << c->PrettyDescriptor() << " at offset " << field_offset;
284   UNREACHABLE();
285 }
286 
FindFieldByOffset(MemberOffset offset)287 ArtField* Object::FindFieldByOffset(MemberOffset offset) {
288   return IsClass() ? ArtField::FindStaticFieldWithOffset(AsClass(), offset.Uint32Value())
289       : ArtField::FindInstanceFieldWithOffset(GetClass(), offset.Uint32Value());
290 }
291 
PrettyTypeOf(ObjPtr<mirror::Object> obj)292 std::string Object::PrettyTypeOf(ObjPtr<mirror::Object> obj) {
293   return (obj == nullptr) ? "null" : obj->PrettyTypeOf();
294 }
295 
PrettyTypeOf()296 std::string Object::PrettyTypeOf() {
297   // From-space version is the same as the to-space version since the dex file never changes.
298   // Avoiding the read barrier here is important to prevent recursive AssertToSpaceInvariant
299   // issues.
300   ObjPtr<mirror::Class> klass = GetClass<kDefaultVerifyFlags, kWithoutReadBarrier>();
301   if (klass == nullptr) {
302     return "(raw)";
303   }
304   std::string temp;
305   std::string result(PrettyDescriptor(klass->GetDescriptor(&temp)));
306   if (klass->IsClassClass()) {
307     result += "<" + PrettyDescriptor(AsClass()->GetDescriptor(&temp)) + ">";
308   }
309   return result;
310 }
311 
312 }  // namespace mirror
313 }  // namespace art
314