heap-inl.h revision 1febddf359ae500ef1bb01ab4883b076fcb56440
1/*
2 * Copyright (C) 2013 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#ifndef ART_RUNTIME_GC_HEAP_INL_H_
18#define ART_RUNTIME_GC_HEAP_INL_H_
19
20#include "heap.h"
21
22#include "debugger.h"
23#include "gc/space/bump_pointer_space-inl.h"
24#include "gc/space/dlmalloc_space-inl.h"
25#include "gc/space/large_object_space.h"
26#include "gc/space/rosalloc_space-inl.h"
27#include "object_utils.h"
28#include "runtime.h"
29#include "thread.h"
30#include "thread-inl.h"
31
32namespace art {
33namespace gc {
34
35template <bool kInstrumented, typename PreFenceVisitor>
36inline mirror::Object* Heap::AllocObjectWithAllocator(Thread* self, mirror::Class* klass,
37                                                      size_t byte_count, AllocatorType allocator,
38                                                      const PreFenceVisitor& pre_fence_visitor) {
39  DebugCheckPreconditionsForAllocObject(klass, byte_count);
40  // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
41  // done in the runnable state where suspension is expected.
42  DCHECK_EQ(self->GetState(), kRunnable);
43  self->AssertThreadSuspensionIsAllowable();
44  mirror::Object* obj;
45  size_t bytes_allocated;
46  AllocationTimer alloc_timer(this, &obj);
47  if (UNLIKELY(ShouldAllocLargeObject(klass, byte_count))) {
48    obj = TryToAllocate<kInstrumented>(self, kAllocatorTypeLOS, byte_count, false,
49                                       &bytes_allocated);
50    allocator = kAllocatorTypeLOS;
51  } else {
52    obj = TryToAllocate<kInstrumented>(self, allocator, byte_count, false, &bytes_allocated);
53  }
54
55  if (UNLIKELY(obj == nullptr)) {
56    SirtRef<mirror::Class> sirt_c(self, klass);
57    obj = AllocateInternalWithGc(self, allocator, byte_count, &bytes_allocated);
58    if (obj == nullptr) {
59      return nullptr;
60    } else {
61      klass = sirt_c.get();
62    }
63  }
64  obj->SetClass(klass);
65  pre_fence_visitor(obj);
66  DCHECK_GT(bytes_allocated, 0u);
67  const size_t new_num_bytes_allocated =
68      static_cast<size_t>(num_bytes_allocated_.fetch_add(bytes_allocated)) + bytes_allocated;
69  // TODO: Deprecate.
70  if (kInstrumented) {
71    if (Runtime::Current()->HasStatsEnabled()) {
72      RuntimeStats* thread_stats = self->GetStats();
73      ++thread_stats->allocated_objects;
74      thread_stats->allocated_bytes += bytes_allocated;
75      RuntimeStats* global_stats = Runtime::Current()->GetStats();
76      ++global_stats->allocated_objects;
77      global_stats->allocated_bytes += bytes_allocated;
78    }
79  } else {
80    DCHECK(!Runtime::Current()->HasStatsEnabled());
81  }
82  if (AllocatorHasAllocationStack(allocator)) {
83    // This is safe to do since the GC will never free objects which are neither in the allocation
84    // stack or the live bitmap.
85    while (!allocation_stack_->AtomicPushBack(obj)) {
86      CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
87    }
88  }
89  if (kInstrumented) {
90    if (Dbg::IsAllocTrackingEnabled()) {
91      Dbg::RecordAllocation(klass, bytes_allocated);
92    }
93  } else {
94    DCHECK(!Dbg::IsAllocTrackingEnabled());
95  }
96  if (AllocatorHasConcurrentGC(allocator)) {
97    CheckConcurrentGC(self, new_num_bytes_allocated, obj);
98  }
99  if (kIsDebugBuild) {
100    if (kDesiredHeapVerification > kNoHeapVerification) {
101      VerifyObject(obj);
102    }
103    self->VerifyStack();
104  }
105  return obj;
106}
107
108template <const bool kInstrumented>
109inline mirror::Object* Heap::TryToAllocate(Thread* self, AllocatorType allocator_type,
110                                           size_t alloc_size, bool grow,
111                                           size_t* bytes_allocated) {
112  if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
113    return nullptr;
114  }
115  if (kInstrumented) {
116    if (UNLIKELY(running_on_valgrind_ && allocator_type == kAllocatorTypeFreeList)) {
117      return non_moving_space_->Alloc(self, alloc_size, bytes_allocated);
118    }
119  }
120  mirror::Object* ret;
121  switch (allocator_type) {
122    case kAllocatorTypeBumpPointer: {
123      DCHECK(bump_pointer_space_ != nullptr);
124      alloc_size = RoundUp(alloc_size, space::BumpPointerSpace::kAlignment);
125      ret = bump_pointer_space_->AllocNonvirtual(alloc_size);
126      if (LIKELY(ret != nullptr)) {
127        *bytes_allocated = alloc_size;
128      }
129      break;
130    }
131    case kAllocatorTypeFreeList: {
132      if (kUseRosAlloc) {
133        ret = reinterpret_cast<space::RosAllocSpace*>(non_moving_space_)->AllocNonvirtual(
134            self, alloc_size, bytes_allocated);
135      } else {
136        ret = reinterpret_cast<space::DlMallocSpace*>(non_moving_space_)->AllocNonvirtual(
137            self, alloc_size, bytes_allocated);
138      }
139      break;
140    }
141    case kAllocatorTypeLOS: {
142      ret = large_object_space_->Alloc(self, alloc_size, bytes_allocated);
143      // Make sure that our large object didn't get placed anywhere within the space interval or
144      // else it breaks the immune range.
145      DCHECK(ret == nullptr ||
146             reinterpret_cast<byte*>(ret) < continuous_spaces_.front()->Begin() ||
147             reinterpret_cast<byte*>(ret) >= continuous_spaces_.back()->End());
148      break;
149    }
150    default: {
151      LOG(FATAL) << "Invalid allocator type";
152      ret = nullptr;
153    }
154  }
155  return ret;
156}
157
158inline void Heap::DebugCheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
159  DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
160         (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
161         strlen(ClassHelper(c).GetDescriptor()) == 0);
162  DCHECK_GE(byte_count, sizeof(mirror::Object));
163}
164
165inline Heap::AllocationTimer::AllocationTimer(Heap* heap, mirror::Object** allocated_obj_ptr)
166    : heap_(heap), allocated_obj_ptr_(allocated_obj_ptr) {
167  if (kMeasureAllocationTime) {
168    allocation_start_time_ = NanoTime() / kTimeAdjust;
169  }
170}
171
172inline Heap::AllocationTimer::~AllocationTimer() {
173  if (kMeasureAllocationTime) {
174    mirror::Object* allocated_obj = *allocated_obj_ptr_;
175    // Only if the allocation succeeded, record the time.
176    if (allocated_obj != nullptr) {
177      uint64_t allocation_end_time = NanoTime() / kTimeAdjust;
178      heap_->total_allocation_time_.fetch_add(allocation_end_time - allocation_start_time_);
179    }
180  }
181};
182
183inline bool Heap::ShouldAllocLargeObject(mirror::Class* c, size_t byte_count) const {
184  // We need to have a zygote space or else our newly allocated large object can end up in the
185  // Zygote resulting in it being prematurely freed.
186  // We can only do this for primitive objects since large objects will not be within the card table
187  // range. This also means that we rely on SetClass not dirtying the object's card.
188  return byte_count >= kLargeObjectThreshold && have_zygote_space_ && c->IsPrimitiveArray();
189}
190
191inline bool Heap::IsOutOfMemoryOnAllocation(size_t alloc_size, bool grow) {
192  size_t new_footprint = num_bytes_allocated_ + alloc_size;
193  if (UNLIKELY(new_footprint > max_allowed_footprint_)) {
194    if (UNLIKELY(new_footprint > growth_limit_)) {
195      return true;
196    }
197    if (!concurrent_gc_) {
198      if (!grow) {
199        return true;
200      } else {
201        max_allowed_footprint_ = new_footprint;
202      }
203    }
204  }
205  return false;
206}
207
208inline void Heap::CheckConcurrentGC(Thread* self, size_t new_num_bytes_allocated,
209                                    mirror::Object* obj) {
210  if (UNLIKELY(new_num_bytes_allocated >= concurrent_start_bytes_)) {
211    // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
212    SirtRef<mirror::Object> ref(self, obj);
213    RequestConcurrentGC(self);
214  }
215}
216
217}  // namespace gc
218}  // namespace art
219
220#endif  // ART_RUNTIME_GC_HEAP_INL_H_
221