• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 {
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 ATTRIBUTE_UNUSED) const69   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
70       const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const71   void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) 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 ATTRIBUTE_UNUSED) const147   void operator()(ObjPtr<Object> obj, size_t usable_size ATTRIBUTE_UNUSED) 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 
IdentityHashCode()188 int32_t Object::IdentityHashCode() {
189   ObjPtr<Object> current_this = this;  // The this pointer may get invalidated by thread suspension.
190   while (true) {
191     LockWord lw = current_this->GetLockWord(false);
192     switch (lw.GetState()) {
193       case LockWord::kUnlocked: {
194         // Try to compare and swap in a new hash, if we succeed we will return the hash on the next
195         // loop iteration.
196         LockWord hash_word = LockWord::FromHashCode(GenerateIdentityHashCode(), lw.GCState());
197         DCHECK_EQ(hash_word.GetState(), LockWord::kHashCode);
198         // Use a strong CAS to prevent spurious failures since these can make the boot image
199         // non-deterministic.
200         if (current_this->CasLockWord(lw, hash_word, CASMode::kStrong, std::memory_order_relaxed)) {
201           return hash_word.GetHashCode();
202         }
203         break;
204       }
205       case LockWord::kThinLocked: {
206         // Inflate the thin lock to a monitor and stick the hash code inside of the monitor. May
207         // fail spuriously.
208         Thread* self = Thread::Current();
209         StackHandleScope<1> hs(self);
210         Handle<mirror::Object> h_this(hs.NewHandle(current_this));
211         Monitor::InflateThinLocked(self, h_this, lw, GenerateIdentityHashCode());
212         // A GC may have occurred when we switched to kBlocked.
213         current_this = h_this.Get();
214         break;
215       }
216       case LockWord::kFatLocked: {
217         // Already inflated, return the hash stored in the monitor.
218         Monitor* monitor = lw.FatLockMonitor();
219         DCHECK(monitor != nullptr);
220         return monitor->GetHashCode();
221       }
222       case LockWord::kHashCode: {
223         return lw.GetHashCode();
224       }
225       default: {
226         LOG(FATAL) << "Invalid state during hashcode " << lw.GetState();
227         UNREACHABLE();
228       }
229     }
230   }
231 }
232 
CheckFieldAssignmentImpl(MemberOffset field_offset,ObjPtr<Object> new_value)233 void Object::CheckFieldAssignmentImpl(MemberOffset field_offset, ObjPtr<Object> new_value) {
234   ObjPtr<Class> c = GetClass();
235   Runtime* runtime = Runtime::Current();
236   if (runtime->GetClassLinker() == nullptr || !runtime->IsStarted() ||
237       !runtime->GetHeap()->IsObjectValidationEnabled() || !c->IsResolved()) {
238     return;
239   }
240   for (ObjPtr<Class> cur = c; cur != nullptr; cur = cur->GetSuperClass()) {
241     for (ArtField& field : cur->GetIFields()) {
242       if (field.GetOffset().Int32Value() == field_offset.Int32Value()) {
243         CHECK_NE(field.GetTypeAsPrimitiveType(), Primitive::kPrimNot);
244         // TODO: resolve the field type for moving GC.
245         ObjPtr<mirror::Class> field_type =
246             kMovingCollector ? field.LookupResolvedType() : field.ResolveType();
247         if (field_type != nullptr) {
248           CHECK(field_type->IsAssignableFrom(new_value->GetClass()));
249         }
250         return;
251       }
252     }
253   }
254   if (c->IsArrayClass()) {
255     // Bounds and assign-ability done in the array setter.
256     return;
257   }
258   if (IsClass()) {
259     for (ArtField& field : AsClass()->GetSFields()) {
260       if (field.GetOffset().Int32Value() == field_offset.Int32Value()) {
261         CHECK_NE(field.GetTypeAsPrimitiveType(), Primitive::kPrimNot);
262         // TODO: resolve the field type for moving GC.
263         ObjPtr<mirror::Class> field_type =
264             kMovingCollector ? field.LookupResolvedType() : field.ResolveType();
265         if (field_type != nullptr) {
266           CHECK(field_type->IsAssignableFrom(new_value->GetClass()));
267         }
268         return;
269       }
270     }
271   }
272   LOG(FATAL) << "Failed to find field for assignment to " << reinterpret_cast<void*>(this)
273              << " of type " << c->PrettyDescriptor() << " at offset " << field_offset;
274   UNREACHABLE();
275 }
276 
FindFieldByOffset(MemberOffset offset)277 ArtField* Object::FindFieldByOffset(MemberOffset offset) {
278   return IsClass() ? ArtField::FindStaticFieldWithOffset(AsClass(), offset.Uint32Value())
279       : ArtField::FindInstanceFieldWithOffset(GetClass(), offset.Uint32Value());
280 }
281 
PrettyTypeOf(ObjPtr<mirror::Object> obj)282 std::string Object::PrettyTypeOf(ObjPtr<mirror::Object> obj) {
283   return (obj == nullptr) ? "null" : obj->PrettyTypeOf();
284 }
285 
PrettyTypeOf()286 std::string Object::PrettyTypeOf() {
287   // From-space version is the same as the to-space version since the dex file never changes.
288   // Avoiding the read barrier here is important to prevent recursive AssertToSpaceInvariant
289   // issues.
290   ObjPtr<mirror::Class> klass = GetClass<kDefaultVerifyFlags, kWithoutReadBarrier>();
291   if (klass == nullptr) {
292     return "(raw)";
293   }
294   std::string temp;
295   std::string result(PrettyDescriptor(klass->GetDescriptor(&temp)));
296   if (klass->IsClassClass()) {
297     result += "<" + PrettyDescriptor(AsClass()->GetDescriptor(&temp)) + ">";
298   }
299   return result;
300 }
301 
302 }  // namespace mirror
303 }  // namespace art
304