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.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: 48 explicit CopyReferenceFieldsWithReadBarrierVisitor(ObjPtr<Object> dest_obj) 49 : dest_obj_(dest_obj) {} 50 51 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 60 void operator()(ObjPtr<mirror::Class> klass, 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. 69 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) 70 const {} 71 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {} 72 73 private: 74 ObjPtr<Object> const dest_obj_; 75 }; 76 77 Object* Object::CopyObject(ObjPtr<mirror::Object> dest, 78 ObjPtr<mirror::Object> src, 79 size_t num_bytes) { 80 // Copy instance data. Don't assume memcpy copies by words (b/32012820). 81 { 82 const size_t offset = sizeof(Object); 83 uint8_t* src_bytes = reinterpret_cast<uint8_t*>(src.Ptr()) + offset; 84 uint8_t* dst_bytes = reinterpret_cast<uint8_t*>(dest.Ptr()) + offset; 85 num_bytes -= offset; 86 DCHECK_ALIGNED(src_bytes, sizeof(uintptr_t)); 87 DCHECK_ALIGNED(dst_bytes, sizeof(uintptr_t)); 88 // Use word sized copies to begin. 89 while (num_bytes >= sizeof(uintptr_t)) { 90 reinterpret_cast<Atomic<uintptr_t>*>(dst_bytes)->StoreRelaxed( 91 reinterpret_cast<Atomic<uintptr_t>*>(src_bytes)->LoadRelaxed()); 92 src_bytes += sizeof(uintptr_t); 93 dst_bytes += sizeof(uintptr_t); 94 num_bytes -= sizeof(uintptr_t); 95 } 96 // Copy possible 32 bit word. 97 if (sizeof(uintptr_t) != sizeof(uint32_t) && num_bytes >= sizeof(uint32_t)) { 98 reinterpret_cast<Atomic<uint32_t>*>(dst_bytes)->StoreRelaxed( 99 reinterpret_cast<Atomic<uint32_t>*>(src_bytes)->LoadRelaxed()); 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)->StoreRelaxed( 108 reinterpret_cast<Atomic<uint8_t>*>(src_bytes)->LoadRelaxed()); 109 src_bytes += sizeof(uint8_t); 110 dst_bytes += sizeof(uint8_t); 111 num_bytes -= sizeof(uint8_t); 112 } 113 } 114 115 if (kUseReadBarrier) { 116 // We need a RB here. After copying the whole object above, copy references fields one by one 117 // again with a RB to make sure there are no from space refs. TODO: Optimize this later? 118 CopyReferenceFieldsWithReadBarrierVisitor visitor(dest); 119 src->VisitReferences(visitor, visitor); 120 } 121 gc::Heap* heap = Runtime::Current()->GetHeap(); 122 // Perform write barriers on copied object references. 123 ObjPtr<Class> c = src->GetClass(); 124 if (c->IsArrayClass()) { 125 if (!c->GetComponentType()->IsPrimitive()) { 126 ObjectArray<Object>* array = dest->AsObjectArray<Object>(); 127 heap->WriteBarrierArray(dest, 0, array->GetLength()); 128 } 129 } else { 130 heap->WriteBarrierEveryFieldOf(dest); 131 } 132 return dest.Ptr(); 133 } 134 135 // An allocation pre-fence visitor that copies the object. 136 class CopyObjectVisitor { 137 public: 138 CopyObjectVisitor(Handle<Object>* orig, size_t num_bytes) 139 : orig_(orig), num_bytes_(num_bytes) {} 140 141 void operator()(ObjPtr<Object> obj, size_t usable_size ATTRIBUTE_UNUSED) const 142 REQUIRES_SHARED(Locks::mutator_lock_) { 143 Object::CopyObject(obj, orig_->Get(), num_bytes_); 144 } 145 146 private: 147 Handle<Object>* const orig_; 148 const size_t num_bytes_; 149 DISALLOW_COPY_AND_ASSIGN(CopyObjectVisitor); 150 }; 151 152 Object* Object::Clone(Thread* self) { 153 CHECK(!IsClass()) << "Can't clone classes."; 154 // Object::SizeOf gets the right size even if we're an array. Using c->AllocObject() here would 155 // be wrong. 156 gc::Heap* heap = Runtime::Current()->GetHeap(); 157 size_t num_bytes = SizeOf(); 158 StackHandleScope<1> hs(self); 159 Handle<Object> this_object(hs.NewHandle(this)); 160 ObjPtr<Object> copy; 161 CopyObjectVisitor visitor(&this_object, num_bytes); 162 if (heap->IsMovableObject(this)) { 163 copy = heap->AllocObject<true>(self, GetClass(), num_bytes, visitor); 164 } else { 165 copy = heap->AllocNonMovableObject<true>(self, GetClass(), num_bytes, visitor); 166 } 167 if (this_object->GetClass()->IsFinalizable()) { 168 heap->AddFinalizerReference(self, ©); 169 } 170 return copy.Ptr(); 171 } 172 173 uint32_t Object::GenerateIdentityHashCode() { 174 uint32_t expected_value, new_value; 175 do { 176 expected_value = hash_code_seed.LoadRelaxed(); 177 new_value = expected_value * 1103515245 + 12345; 178 } while (!hash_code_seed.CompareAndSetWeakRelaxed(expected_value, new_value) || 179 (expected_value & LockWord::kHashMask) == 0); 180 return expected_value & LockWord::kHashMask; 181 } 182 183 void Object::SetHashCodeSeed(uint32_t new_seed) { 184 hash_code_seed.StoreRelaxed(new_seed); 185 } 186 187 int32_t Object::IdentityHashCode() { 188 ObjPtr<Object> current_this = this; // The this pointer may get invalidated by thread suspension. 189 while (true) { 190 LockWord lw = current_this->GetLockWord(false); 191 switch (lw.GetState()) { 192 case LockWord::kUnlocked: { 193 // Try to compare and swap in a new hash, if we succeed we will return the hash on the next 194 // loop iteration. 195 LockWord hash_word = LockWord::FromHashCode(GenerateIdentityHashCode(), lw.GCState()); 196 DCHECK_EQ(hash_word.GetState(), LockWord::kHashCode); 197 if (current_this->CasLockWordWeakRelaxed(lw, hash_word)) { 198 return hash_word.GetHashCode(); 199 } 200 break; 201 } 202 case LockWord::kThinLocked: { 203 // Inflate the thin lock to a monitor and stick the hash code inside of the monitor. May 204 // fail spuriously. 205 Thread* self = Thread::Current(); 206 StackHandleScope<1> hs(self); 207 Handle<mirror::Object> h_this(hs.NewHandle(current_this)); 208 Monitor::InflateThinLocked(self, h_this, lw, GenerateIdentityHashCode()); 209 // A GC may have occurred when we switched to kBlocked. 210 current_this = h_this.Get(); 211 break; 212 } 213 case LockWord::kFatLocked: { 214 // Already inflated, return the hash stored in the monitor. 215 Monitor* monitor = lw.FatLockMonitor(); 216 DCHECK(monitor != nullptr); 217 return monitor->GetHashCode(); 218 } 219 case LockWord::kHashCode: { 220 return lw.GetHashCode(); 221 } 222 default: { 223 LOG(FATAL) << "Invalid state during hashcode " << lw.GetState(); 224 break; 225 } 226 } 227 } 228 UNREACHABLE(); 229 } 230 231 void Object::CheckFieldAssignmentImpl(MemberOffset field_offset, ObjPtr<Object> new_value) { 232 ObjPtr<Class> c = GetClass(); 233 Runtime* runtime = Runtime::Current(); 234 if (runtime->GetClassLinker() == nullptr || !runtime->IsStarted() || 235 !runtime->GetHeap()->IsObjectValidationEnabled() || !c->IsResolved()) { 236 return; 237 } 238 for (ObjPtr<Class> cur = c; cur != nullptr; cur = cur->GetSuperClass()) { 239 for (ArtField& field : cur->GetIFields()) { 240 if (field.GetOffset().Int32Value() == field_offset.Int32Value()) { 241 CHECK_NE(field.GetTypeAsPrimitiveType(), Primitive::kPrimNot); 242 // TODO: resolve the field type for moving GC. 243 ObjPtr<mirror::Class> field_type = 244 kMovingCollector ? field.LookupResolvedType() : field.ResolveType(); 245 if (field_type != nullptr) { 246 CHECK(field_type->IsAssignableFrom(new_value->GetClass())); 247 } 248 return; 249 } 250 } 251 } 252 if (c->IsArrayClass()) { 253 // Bounds and assign-ability done in the array setter. 254 return; 255 } 256 if (IsClass()) { 257 for (ArtField& field : AsClass()->GetSFields()) { 258 if (field.GetOffset().Int32Value() == field_offset.Int32Value()) { 259 CHECK_NE(field.GetTypeAsPrimitiveType(), Primitive::kPrimNot); 260 // TODO: resolve the field type for moving GC. 261 ObjPtr<mirror::Class> field_type = 262 kMovingCollector ? field.LookupResolvedType() : field.ResolveType(); 263 if (field_type != nullptr) { 264 CHECK(field_type->IsAssignableFrom(new_value->GetClass())); 265 } 266 return; 267 } 268 } 269 } 270 LOG(FATAL) << "Failed to find field for assignment to " << reinterpret_cast<void*>(this) 271 << " of type " << c->PrettyDescriptor() << " at offset " << field_offset; 272 UNREACHABLE(); 273 } 274 275 ArtField* Object::FindFieldByOffset(MemberOffset offset) { 276 return IsClass() ? ArtField::FindStaticFieldWithOffset(AsClass(), offset.Uint32Value()) 277 : ArtField::FindInstanceFieldWithOffset(GetClass(), offset.Uint32Value()); 278 } 279 280 std::string Object::PrettyTypeOf(ObjPtr<mirror::Object> obj) { 281 if (obj == nullptr) { 282 return "null"; 283 } 284 return obj->PrettyTypeOf(); 285 } 286 287 std::string Object::PrettyTypeOf() { 288 // From-space version is the same as the to-space version since the dex file never changes. 289 // Avoiding the read barrier here is important to prevent recursive AssertToSpaceInvariant 290 // issues. 291 ObjPtr<mirror::Class> klass = GetClass<kDefaultVerifyFlags, kWithoutReadBarrier>(); 292 if (klass == nullptr) { 293 return "(raw)"; 294 } 295 std::string temp; 296 std::string result(PrettyDescriptor(klass->GetDescriptor(&temp))); 297 if (klass->IsClassClass()) { 298 result += "<" + PrettyDescriptor(AsClass()->GetDescriptor(&temp)) + ">"; 299 } 300 return result; 301 } 302 303 } // namespace mirror 304 } // namespace art 305