blob: 00f7e5b57f117469733de1547462560ebd420aa6 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Mathieu Chartier752a0e62013-06-27 11:03:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
Brian Carlstrom5643b782012-02-05 12:32:53 -080021
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
24
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070026#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080027#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070028#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/accounting/atomic_stack.h"
30#include "gc/accounting/card_table-inl.h"
31#include "gc/accounting/heap_bitmap-inl.h"
32#include "gc/accounting/mod_union_table-inl.h"
33#include "gc/accounting/space_bitmap-inl.h"
34#include "gc/collector/mark_sweep-inl.h"
35#include "gc/collector/partial_mark_sweep.h"
36#include "gc/collector/sticky_mark_sweep.h"
37#include "gc/space/image_space.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070040#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080041#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/class-inl.h"
43#include "mirror/field-inl.h"
44#include "mirror/object.h"
45#include "mirror/object-inl.h"
46#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080047#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080048#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070049#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070050#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070051#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070052#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070053#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070055
56namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070057namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070058
Ian Rogers1d54e732013-05-02 21:10:01 -070059// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080060static const uint64_t kSlowGcThreshold = MsToNs(100);
Mathieu Chartier82353312013-07-18 10:47:51 -070061// When to create a log message about a long pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080062static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080063static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070064// Minimum amount of remaining bytes before a concurrent GC is triggered.
65static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070066const double Heap::kDefaultTargetUtilization = 0.5;
67
Mathieu Chartier0051be62012-10-12 17:47:11 -070068Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
69 double target_utilization, size_t capacity,
Mathieu Chartier63a54342013-07-23 13:17:59 -070070 const std::string& original_image_file_name, bool concurrent_gc, size_t num_gc_threads)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070071 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080072 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070073 concurrent_gc_(concurrent_gc),
Mathieu Chartier63a54342013-07-23 13:17:59 -070074 num_gc_threads_(num_gc_threads),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070075 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070076 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080077 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070078 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070079 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080080 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070081 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070082 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070083 native_footprint_gc_watermark_(initial_size),
84 native_footprint_limit_(2 * initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -070085 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
86 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -070087 total_bytes_freed_ever_(0),
88 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070089 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080090 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070091 native_bytes_allocated_(0),
Mathieu Chartier82353312013-07-18 10:47:51 -070092 process_state_(PROCESS_STATE_TOP),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -070093 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -070094 verify_missing_card_marks_(false),
95 verify_system_weaks_(false),
96 verify_pre_gc_heap_(false),
97 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -070098 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070099 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700100 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700101 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800102 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700103 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800104 reference_referent_offset_(0),
105 reference_queue_offset_(0),
106 reference_queueNext_offset_(0),
107 reference_pendingNext_offset_(0),
108 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700109 min_free_(min_free),
110 max_free_(max_free),
111 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700112 total_wait_time_(0),
113 measure_allocation_time_(false),
114 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700115 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800116 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800117 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700118 }
119
Ian Rogers1d54e732013-05-02 21:10:01 -0700120 live_bitmap_.reset(new accounting::HeapBitmap(this));
121 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700122
Ian Rogers30fab402012-01-23 15:43:46 -0800123 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700124 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800125 std::string image_file_name(original_image_file_name);
126 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700127 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
128 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700129 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800130 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
131 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800132 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
133 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700134 if (oat_file_end_addr > requested_alloc_space_begin) {
135 requested_alloc_space_begin =
136 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
137 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700138 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700139 }
140
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700141 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700142 const bool kUseFreeListSpaceForLOS = false;
143 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700144 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700145 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700146 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700147 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700148 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
149 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700150
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700151 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700152 initial_size,
153 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700154 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700155 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700156 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700157 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700158
Ian Rogers1d54e732013-05-02 21:10:01 -0700159 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
160 byte* heap_begin = continuous_spaces_.front()->Begin();
161 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
162 if (continuous_spaces_.back()->IsDlMallocSpace()) {
163 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700164 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700165
Ian Rogers30fab402012-01-23 15:43:46 -0800166 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700167 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700168 typedef std::vector<space::ContinuousSpace*>::iterator It;
169 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
170 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800171 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700172 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700173 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800174 }
175 }
176
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800177 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700178 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700179 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700180
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700181 image_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Ian Rogers1d54e732013-05-02 21:10:01 -0700182 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700183
Ian Rogers1d54e732013-05-02 21:10:01 -0700184 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700185 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700186
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700187 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700188 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700189
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800190 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700191 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700192 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
193 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
194 max_allocation_stack_size_));
195 live_stack_.reset(accounting::ObjectStack::Create("live stack",
196 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700197
Mathieu Chartier65db8802012-11-20 12:36:46 -0800198 // It's still too early to take a lock because there are no threads yet, but we can create locks
199 // now. We don't create it earlier to make it clear that you can't use locks during heap
200 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700201 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700202 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
203 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700204
Mathieu Chartier63a54342013-07-23 13:17:59 -0700205 // Create the reference queue lock, this is required so for parallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700206 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700207
Ian Rogers1d54e732013-05-02 21:10:01 -0700208 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800209 last_gc_size_ = GetBytesAllocated();
210
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800211 // Create our garbage collectors.
212 for (size_t i = 0; i < 2; ++i) {
213 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700214 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
215 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
216 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700217 }
218
Brian Carlstrom42748892013-07-18 18:04:08 -0700219 CHECK_NE(max_allowed_footprint_, 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800220 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800221 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700222 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700223}
224
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700225void Heap::CreateThreadPool() {
Mathieu Chartier63a54342013-07-23 13:17:59 -0700226 thread_pool_.reset(new ThreadPool(num_gc_threads_));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700227}
228
229void Heap::DeleteThreadPool() {
230 thread_pool_.reset(NULL);
231}
232
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700233// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700234struct ContinuousSpaceSorter {
Brian Carlstromdf629502013-07-17 22:39:56 -0700235 bool operator()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700236 return a->Begin() < b->Begin();
237 }
238};
239
Mathieu Chartier82353312013-07-18 10:47:51 -0700240void Heap::UpdateProcessState(ProcessState process_state) {
241 process_state_ = process_state;
242}
243
Ian Rogers1d54e732013-05-02 21:10:01 -0700244void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700245 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700246 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700247 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700248 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700249 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700250 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
251 continuous_spaces_.push_back(space);
252 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
253 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700254 }
255
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700256 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700257 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700258
259 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
260 // avoid redundant marking.
261 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700262 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
263 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
264 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700265 if (space->IsImageSpace()) {
266 DCHECK(!seen_zygote);
267 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700268 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700269 DCHECK(!seen_alloc);
270 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700271 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700272 seen_alloc = true;
273 }
274 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800275}
276
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700277void Heap::RegisterGCAllocation(size_t bytes) {
278 if (this != NULL) {
279 gc_memory_overhead_.fetch_add(bytes);
280 }
281}
282
283void Heap::RegisterGCDeAllocation(size_t bytes) {
284 if (this != NULL) {
285 gc_memory_overhead_.fetch_sub(bytes);
286 }
287}
288
Ian Rogers1d54e732013-05-02 21:10:01 -0700289void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
290 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
291 DCHECK(space != NULL);
292 DCHECK(space->GetLiveObjects() != NULL);
293 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
294 DCHECK(space->GetMarkObjects() != NULL);
295 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
296 discontinuous_spaces_.push_back(space);
297}
298
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700299void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700300 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700301 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700302 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800303
304 // Dump cumulative loggers for each GC type.
305 // TODO: C++0x
306 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700307 typedef std::vector<collector::MarkSweep*>::const_iterator It;
308 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800309 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700310 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800311 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800312 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700313 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800314 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700315 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800316 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
317 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
318 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700319 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
320 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
321 << collector->GetName() << " freed: " << freed_objects
322 << " objects with total size " << PrettySize(freed_bytes) << "\n"
323 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
324 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800325 total_duration += total_ns;
326 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700327 }
328 }
329 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700330 size_t total_objects_allocated = GetObjectsAllocatedEver();
331 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700332 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700333 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700334 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
335 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700336 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700337 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700338 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700339 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700340 os << "Total number of allocations: " << total_objects_allocated << "\n";
341 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700342 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700343 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
344 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
345 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700346 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700347 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
348 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700349 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700350}
351
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800352Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700353 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700354 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700355 }
356
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800357 STLDeleteElements(&mark_sweep_collectors_);
358
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700359 // If we don't reset then the mark stack complains in it's destructor.
360 allocation_stack_->Reset();
361 live_stack_->Reset();
362
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800363 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800364 // We can't take the heap lock here because there might be a daemon thread suspended with the
365 // heap lock held. We know though that no non-daemon threads are executing, and we know that
366 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
367 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Ian Rogers1d54e732013-05-02 21:10:01 -0700368 STLDeleteElements(&continuous_spaces_);
369 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700370 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700371 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700372}
373
Ian Rogers1d54e732013-05-02 21:10:01 -0700374space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
375 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700376 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700377 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
378 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700379 if ((*it)->Contains(obj)) {
380 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700381 }
382 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700383 if (!fail_ok) {
384 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
385 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700386 return NULL;
387}
388
Ian Rogers1d54e732013-05-02 21:10:01 -0700389space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
390 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700391 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700392 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
393 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
394 if ((*it)->Contains(obj)) {
395 return *it;
396 }
397 }
398 if (!fail_ok) {
399 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
400 }
401 return NULL;
402}
403
404space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
405 space::Space* result = FindContinuousSpaceFromObject(obj, true);
406 if (result != NULL) {
407 return result;
408 }
409 return FindDiscontinuousSpaceFromObject(obj, true);
410}
411
412space::ImageSpace* Heap::GetImageSpace() const {
413 // TODO: C++0x auto
414 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
415 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700416 if ((*it)->IsImageSpace()) {
417 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700418 }
419 }
420 return NULL;
421}
422
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700423static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700424 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700425 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700426 size_t chunk_free_bytes = chunk_size - used_bytes;
427 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
428 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700429 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700430}
431
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800432mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
433 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700434 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
435 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800436 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700437
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800438 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700439 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700440 uint64_t allocation_start = 0;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700441 if (UNLIKELY(measure_allocation_time_)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700442 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700443 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700444
445 // We need to have a zygote space or else our newly allocated large object can end up in the
446 // Zygote resulting in it being prematurely freed.
447 // We can only do this for primive objects since large objects will not be within the card table
448 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers333cf1b2013-07-24 11:57:02 -0700449 bool large_object_allocation =
450 byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
451 if (UNLIKELY(large_object_allocation)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700452 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700453 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700454 // Make sure that our large object didn't get placed anywhere within the space interval or else
455 // it breaks the immune range.
456 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700457 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
458 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700459 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700460 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700461
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700462 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700463 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700464 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700465 }
466
Mathieu Chartier037813d2012-08-23 16:44:59 -0700467 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700469
470 // Record allocation after since we want to use the atomic add for the atomic fence to guard
471 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700472 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700473
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700474 if (Dbg::IsAllocTrackingEnabled()) {
475 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700476 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700477 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800479 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700480 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 }
482 VerifyObject(obj);
483
Ian Rogers333cf1b2013-07-24 11:57:02 -0700484 if (UNLIKELY(measure_allocation_time_)) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700485 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700486 }
487
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 return obj;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700489 } else {
490 std::ostringstream oss;
491 int64_t total_bytes_free = GetFreeMemory();
492 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
493 << " free bytes";
494 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
495 if (!large_object_allocation && total_bytes_free >= byte_count) {
496 size_t max_contiguous_allocation = 0;
497 // TODO: C++0x auto
498 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
499 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
500 space::ContinuousSpace* space = *it;
501 if (space->IsDlMallocSpace()) {
502 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
503 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800504 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700505 oss << "; failed due to fragmentation (largest possible contiguous allocation "
506 << max_contiguous_allocation << " bytes)";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700507 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700508 self->ThrowOutOfMemoryError(oss.str().c_str());
509 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700510 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700511}
512
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800513bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700514 // Note: we deliberately don't take the lock here, and mustn't test anything that would
515 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700516 if (obj == NULL) {
517 return true;
518 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700519 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700520 return false;
521 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700522 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700523}
524
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800525bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700526 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700527 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700528 return false;
529 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700530 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
531 space::DiscontinuousSpace* d_space = NULL;
532 if (c_space != NULL) {
533 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700534 return true;
535 }
536 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700537 d_space = FindDiscontinuousSpaceFromObject(obj, true);
538 if (d_space != NULL) {
539 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700540 return true;
541 }
542 }
543 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700544 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Ian Rogers1d54e732013-05-02 21:10:01 -0700545 for (size_t i = 0; i < 5; ++i) {
546 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
547 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
548 return true;
549 }
550 NanoSleep(MsToNs(10));
551 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700552 // We need to check the bitmaps again since there is a race where we mark something as live and
553 // then clear the stack containing it.
554 if (c_space != NULL) {
555 if (c_space->GetLiveBitmap()->Test(obj)) {
556 return true;
557 }
558 } else {
559 d_space = FindDiscontinuousSpaceFromObject(obj, true);
560 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
561 return true;
562 }
563 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700564 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700565}
566
Ian Rogers04d7aa92013-03-16 14:29:17 -0700567void Heap::VerifyObjectImpl(const mirror::Object* obj) {
568 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700569 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700570 return;
571 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700572 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700573}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700574
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700575void Heap::DumpSpaces() {
576 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700577 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
578 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
579 space::ContinuousSpace* space = *it;
580 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
581 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700582 LOG(INFO) << space << " " << *space << "\n"
583 << live_bitmap << " " << *live_bitmap << "\n"
584 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700585 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700586 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
587 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
588 space::DiscontinuousSpace* space = *it;
589 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700590 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700591}
592
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800593void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800594 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700595 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700596 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800597 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
598 return;
599 }
600 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
601 mirror::Object::ClassOffset().Int32Value();
602 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
603 if (UNLIKELY(c == NULL)) {
604 LOG(FATAL) << "Null class in object: " << obj;
605 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
606 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
607 }
608 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
609 // Note: we don't use the accessors here as they have internal sanity checks
610 // that we don't want to run
611 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
612 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
613 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
614 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
615 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700616
Ian Rogers62d6c772013-02-27 08:32:07 -0800617 if (verify_object_mode_ != kVerifyAllFast) {
618 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
619 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700620 if (!IsLiveObjectLocked(obj)) {
621 DumpSpaces();
622 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700623 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700624 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700625 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
626 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700627 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700628}
629
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800630void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700631 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700632 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700633}
634
635void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700636 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700637 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700638}
639
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800640void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700641 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700642 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700643 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700644
645 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700646 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700647 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700648 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700649
650 // TODO: Update these atomically.
651 RuntimeStats* global_stats = Runtime::Current()->GetStats();
652 ++global_stats->allocated_objects;
653 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700654 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700655
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700656 // This is safe to do since the GC will never free objects which are neither in the allocation
657 // stack or the live bitmap.
658 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700659 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700660 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700661}
662
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700663void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700664 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700665 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700666
667 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700668 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700669 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700670 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700671
672 // TODO: Do this concurrently.
673 RuntimeStats* global_stats = Runtime::Current()->GetStats();
674 global_stats->freed_objects += freed_objects;
675 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700676 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700677}
678
Ian Rogers1d54e732013-05-02 21:10:01 -0700679mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
680 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700681 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800682 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
683 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
684 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
685 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700686 return NULL;
687 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700688 }
689
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700690 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700691}
692
Ian Rogers1d54e732013-05-02 21:10:01 -0700693mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700694 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
695 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700696 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700697 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700698
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800699 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700700 if (ptr != NULL) {
701 return ptr;
702 }
703
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700704 // The allocation failed. If the GC is running, block until it completes, and then retry the
705 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700706 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
707 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700708 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700709 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700710 if (ptr != NULL) {
711 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700712 }
713 }
714
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700715 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700716 for (size_t i = static_cast<size_t>(last_gc) + 1;
717 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700718 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700719 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700720 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700721 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700722 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700723 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
724 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700725 break;
726 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700727 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700728 run_gc = have_zygote_space_;
729 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700730 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700731 run_gc = true;
732 break;
733 default:
734 break;
735 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700736
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700737 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700738 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700739 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800740 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700741 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700742
743 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700744 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700745 if (ptr != NULL) {
746 return ptr;
747 }
748 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700749 }
750
751 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700752 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700753 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700754 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700755 return ptr;
756 }
757
Elliott Hughes81ff3182012-03-23 20:35:56 -0700758 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
759 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
760 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700761
Elliott Hughes418dfe72011-10-06 18:56:27 -0700762 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700763 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
764 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700765
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700766 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700767 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700768 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700769}
770
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700771void Heap::SetTargetHeapUtilization(float target) {
772 DCHECK_GT(target, 0.0f); // asserted in Java code
773 DCHECK_LT(target, 1.0f);
774 target_utilization_ = target;
775}
776
Ian Rogers1d54e732013-05-02 21:10:01 -0700777size_t Heap::GetObjectsAllocated() const {
778 size_t total = 0;
779 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
780 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
781 space::ContinuousSpace* space = *it;
782 if (space->IsDlMallocSpace()) {
783 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700784 }
785 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700786 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
787 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
788 space::DiscontinuousSpace* space = *it;
789 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
790 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700791 return total;
792}
793
Ian Rogers1d54e732013-05-02 21:10:01 -0700794size_t Heap::GetObjectsAllocatedEver() const {
795 size_t total = 0;
796 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
797 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
798 space::ContinuousSpace* space = *it;
799 if (space->IsDlMallocSpace()) {
800 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700801 }
802 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700803 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
804 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
805 space::DiscontinuousSpace* space = *it;
806 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
807 }
808 return total;
809}
810
811size_t Heap::GetBytesAllocatedEver() const {
812 size_t total = 0;
813 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
814 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
815 space::ContinuousSpace* space = *it;
816 if (space->IsDlMallocSpace()) {
817 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
818 }
819 }
820 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
821 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
822 space::DiscontinuousSpace* space = *it;
823 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
824 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700825 return total;
826}
827
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700828class InstanceCounter {
829 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800830 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700831 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800832 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700833 }
834
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800835 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800836 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800837 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800838 if (use_is_assignable_from_) {
839 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
840 ++counts_[i];
841 }
842 } else {
843 if (instance_class == classes_[i]) {
844 ++counts_[i];
845 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700846 }
847 }
848 }
849
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700850 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800852 bool use_is_assignable_from_;
853 uint64_t* const counts_;
854
855 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700856};
857
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800858void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800859 uint64_t* counts) {
860 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
861 // is empty, so the live bitmap is the only place we need to look.
862 Thread* self = Thread::Current();
863 self->TransitionFromRunnableToSuspended(kNative);
864 CollectGarbage(false);
865 self->TransitionFromSuspendedToRunnable();
866
867 InstanceCounter counter(classes, use_is_assignable_from, counts);
868 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700869 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700870}
871
Elliott Hughes3b78c942013-01-15 17:35:41 -0800872class InstanceCollector {
873 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800874 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800875 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
876 : class_(c), max_count_(max_count), instances_(instances) {
877 }
878
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800879 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
880 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800881 if (instance_class == class_) {
882 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800883 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800884 }
885 }
886 }
887
888 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800889 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800890 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800891 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800892
893 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
894};
895
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800896void Heap::GetInstances(mirror::Class* c, int32_t max_count,
897 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800898 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
899 // is empty, so the live bitmap is the only place we need to look.
900 Thread* self = Thread::Current();
901 self->TransitionFromRunnableToSuspended(kNative);
902 CollectGarbage(false);
903 self->TransitionFromSuspendedToRunnable();
904
905 InstanceCollector collector(c, max_count, instances);
906 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
907 GetLiveBitmap()->Visit(collector);
908}
909
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800910class ReferringObjectsFinder {
911 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800912 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
913 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800914 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
915 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
916 }
917
918 // For bitmap Visit.
919 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
920 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800921 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -0700922 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800923 }
924
925 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -0700926 void operator()(const mirror::Object* referrer, const mirror::Object* object,
927 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800928 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800929 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800930 }
931 }
932
933 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800934 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800935 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800936 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800937
938 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
939};
940
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800941void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
942 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800943 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
944 // is empty, so the live bitmap is the only place we need to look.
945 Thread* self = Thread::Current();
946 self->TransitionFromRunnableToSuspended(kNative);
947 CollectGarbage(false);
948 self->TransitionFromSuspendedToRunnable();
949
950 ReferringObjectsFinder finder(o, max_count, referring_objects);
951 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
952 GetLiveBitmap()->Visit(finder);
953}
954
Ian Rogers30fab402012-01-23 15:43:46 -0800955void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700956 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
957 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700958 Thread* self = Thread::Current();
959 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700960 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700961}
962
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700963void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700964 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800965 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
966 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700967 Thread* self = Thread::Current();
968 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700969
970 // Try to see if we have any Zygote spaces.
971 if (have_zygote_space_) {
972 return;
973 }
974
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700975 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
976
977 {
978 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700979 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700980 FlushAllocStack();
981 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700982
Ian Rogers1d54e732013-05-02 21:10:01 -0700983 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
984 // of the remaining available heap memory.
985 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700986 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -0700987 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700988
Ian Rogers1d54e732013-05-02 21:10:01 -0700989 // Change the GC retention policy of the zygote space to only collect when full.
990 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
991 AddContinuousSpace(alloc_space_);
992 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700993
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700994 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700995 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700996 typedef std::vector<collector::MarkSweep*>::const_iterator It;
997 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
998 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800999 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001000 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001001}
1002
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001003void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001004 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1005 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001006 allocation_stack_->Reset();
1007}
1008
Ian Rogers1d54e732013-05-02 21:10:01 -07001009void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1010 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001011 mirror::Object** limit = stack->End();
1012 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1013 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001014 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001015 if (LIKELY(bitmap->HasAddress(obj))) {
1016 bitmap->Set(obj);
1017 } else {
1018 large_objects->Set(obj);
1019 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001020 }
1021}
1022
Ian Rogers1d54e732013-05-02 21:10:01 -07001023void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1024 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001025 mirror::Object** limit = stack->End();
1026 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1027 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001028 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001029 if (LIKELY(bitmap->HasAddress(obj))) {
1030 bitmap->Clear(obj);
1031 } else {
1032 large_objects->Clear(obj);
1033 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001034 }
1035}
1036
Ian Rogers1d54e732013-05-02 21:10:01 -07001037collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1038 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001039 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001040
1041 switch (gc_cause) {
1042 case kGcCauseForAlloc:
1043 ATRACE_BEGIN("GC (alloc)");
1044 break;
1045 case kGcCauseBackground:
1046 ATRACE_BEGIN("GC (background)");
1047 break;
1048 case kGcCauseExplicit:
1049 ATRACE_BEGIN("GC (explicit)");
1050 break;
1051 }
1052
Mathieu Chartier65db8802012-11-20 12:36:46 -08001053 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001054 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001055
Ian Rogers120f1c72012-09-28 17:17:10 -07001056 if (self->IsHandlingStackOverflow()) {
1057 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1058 }
1059
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001060 // Ensure there is only one GC at a time.
1061 bool start_collect = false;
1062 while (!start_collect) {
1063 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001064 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001065 if (!is_gc_running_) {
1066 is_gc_running_ = true;
1067 start_collect = true;
1068 }
1069 }
1070 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001071 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001072 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1073 // Not doing at the moment to ensure soft references are cleared.
1074 }
1075 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001076 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001077
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001078 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1079 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1080 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1081 }
1082
Ian Rogers1d54e732013-05-02 21:10:01 -07001083 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001084 uint64_t gc_start_size = GetBytesAllocated();
1085 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001086 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001087 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1088 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001089 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001090 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001091 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001092 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1093 }
1094
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001095 if (gc_type == collector::kGcTypeSticky &&
1096 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1097 gc_type = collector::kGcTypePartial;
1098 }
1099
Ian Rogers1d54e732013-05-02 21:10:01 -07001100 DCHECK_LT(gc_type, collector::kGcTypeMax);
1101 DCHECK_NE(gc_type, collector::kGcTypeNone);
1102 collector::MarkSweep* collector = NULL;
1103 typedef std::vector<collector::MarkSweep*>::iterator It;
1104 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1105 it != end; ++it) {
1106 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001107 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1108 collector = cur_collector;
1109 break;
1110 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001111 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001112 CHECK(collector != NULL)
1113 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1114 << " and type=" << gc_type;
1115 collector->clear_soft_references_ = clear_soft_references;
1116 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001117 total_objects_freed_ever_ += collector->GetFreedObjects();
1118 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001119
Ian Rogers1d54e732013-05-02 21:10:01 -07001120 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001121 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1122 bool was_slow = duration > kSlowGcThreshold ||
1123 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1124 for (size_t i = 0; i < pauses.size(); ++i) {
1125 if (pauses[i] > kLongGcPauseThreshold) {
1126 was_slow = true;
1127 }
1128 }
1129
1130 if (was_slow) {
1131 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001132 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001133 const size_t total_memory = GetTotalMemory();
1134 std::ostringstream pause_string;
1135 for (size_t i = 0; i < pauses.size(); ++i) {
1136 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1137 << ((i != pauses.size() - 1) ? ", " : "");
1138 }
1139 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001140 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1141 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1142 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1143 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001144 if (VLOG_IS_ON(heap)) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001145 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001146 }
1147 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001148
Ian Rogers15bf2d32012-08-28 17:33:04 -07001149 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001150 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001151 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001152 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001153 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001154 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001155 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001156
Ian Rogers15bf2d32012-08-28 17:33:04 -07001157 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001158 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001159 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001160 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001161}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001162
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001163void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
Ian Rogers1d54e732013-05-02 21:10:01 -07001164 collector::GcType gc_type) {
1165 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001166 // Don't need to do anything for mod union table in this case since we are only scanning dirty
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001167 // cards.
1168 return;
1169 }
1170
1171 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001172 if (gc_type == collector::kGcTypePartial) {
1173 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001174 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001175
Ian Rogers1d54e732013-05-02 21:10:01 -07001176 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001177 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001178 }
1179
1180 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001181 timings.NewSplit("UpdateModUnionTable");
1182 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001183
1184 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001185 timings.NewSplit("MarkImageToAllocSpaceReferences");
1186 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001187}
1188
Ian Rogers1d54e732013-05-02 21:10:01 -07001189static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001190 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001191 if (root == obj) {
1192 LOG(INFO) << "Object " << obj << " is a root";
1193 }
1194}
1195
1196class ScanVisitor {
1197 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001198 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001199 LOG(INFO) << "Would have rescanned object " << obj;
1200 }
1201};
1202
Ian Rogers1d54e732013-05-02 21:10:01 -07001203// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001204class VerifyReferenceVisitor {
1205 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001206 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001207 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001208 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001209
1210 bool Failed() const {
1211 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001212 }
1213
1214 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001215 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001216 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1217 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001218 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001219 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001220 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1221 accounting::CardTable* card_table = heap_->GetCardTable();
1222 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1223 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001224
Ian Rogers1d54e732013-05-02 21:10:01 -07001225 if (obj != NULL) {
1226 byte* card_addr = card_table->CardFromAddr(obj);
1227 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1228 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1229 << "\nObj type " << PrettyTypeOf(obj)
1230 << "\nRef type " << PrettyTypeOf(ref);
1231 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1232 void* cover_begin = card_table->AddrFromCard(card_addr);
1233 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1234 accounting::CardTable::kCardSize);
1235 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1236 << "-" << cover_end;
1237 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001238
Ian Rogers1d54e732013-05-02 21:10:01 -07001239 // Print out how the object is live.
1240 if (bitmap != NULL && bitmap->Test(obj)) {
1241 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1242 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001243 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001244 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1245 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001246 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001247 LOG(ERROR) << "Object " << obj << " found in live stack";
1248 }
1249 // Attempt to see if the card table missed the reference.
1250 ScanVisitor scan_visitor;
1251 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1252 card_table->Scan(bitmap, byte_cover_begin,
1253 byte_cover_begin + accounting::CardTable::kCardSize,
1254 scan_visitor, VoidFunctor());
1255
1256 // Search to see if any of the roots reference our object.
1257 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1258 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1259
1260 // Search to see if any of the roots reference our reference.
1261 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1262 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1263 } else {
1264 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001265 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001266 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001267 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001268 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001269 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001270 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001271 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001272 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1273 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1274 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001275 }
1276 }
1277
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001278 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001279 return heap_->IsLiveObjectLocked(obj);
1280 }
1281
1282 static void VerifyRoots(const mirror::Object* root, void* arg) {
1283 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1284 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001285 }
1286
1287 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001288 Heap* const heap_;
1289 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001290};
1291
Ian Rogers1d54e732013-05-02 21:10:01 -07001292// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001293class VerifyObjectVisitor {
1294 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001295 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001296
Brian Carlstromdf629502013-07-17 22:39:56 -07001297 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001298 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001299 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1300 // be live or else how did we find it in the live bitmap?
1301 VerifyReferenceVisitor visitor(heap_);
1302 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1303 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001304 }
1305
1306 bool Failed() const {
1307 return failed_;
1308 }
1309
1310 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001311 Heap* const heap_;
1312 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001313};
1314
1315// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001316bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001317 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001318 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001319 allocation_stack_->Sort();
1320 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001321 // Perform the verification.
1322 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001323 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001324 GetLiveBitmap()->Visit(visitor);
1325 // We don't want to verify the objects in the allocation stack since they themselves may be
1326 // pointing to dead objects if they are not reachable.
1327 if (visitor.Failed()) {
1328 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001329 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001330 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001331 return true;
1332}
1333
1334class VerifyReferenceCardVisitor {
1335 public:
1336 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1337 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1338 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001339 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001340 }
1341
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001342 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1343 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001344 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1345 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001346 // Filter out class references since changing an object's class does not mark the card as dirty.
1347 // Also handles large objects, since the only reference they hold is a class reference.
1348 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001349 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001350 // If the object is not dirty and it is referencing something in the live stack other than
1351 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001352 if (!card_table->AddrIsInCardTable(obj)) {
1353 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1354 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001355 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001356 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1357 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001358 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001359 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1360 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001361 LOG(ERROR) << "Object " << obj << " found in live stack";
1362 }
1363 if (heap_->GetLiveBitmap()->Test(obj)) {
1364 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1365 }
1366 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1367 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1368
1369 // Print which field of the object is dead.
1370 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001371 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001372 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001373 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1374 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001375 CHECK(fields != NULL);
1376 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001377 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001378 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1379 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1380 << PrettyField(cur);
1381 break;
1382 }
1383 }
1384 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001385 const mirror::ObjectArray<mirror::Object>* object_array =
1386 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001387 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1388 if (object_array->Get(i) == ref) {
1389 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1390 }
1391 }
1392 }
1393
1394 *failed_ = true;
1395 }
1396 }
1397 }
1398 }
1399
1400 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001401 Heap* const heap_;
1402 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001403};
1404
1405class VerifyLiveStackReferences {
1406 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001407 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001408 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001409 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001410
Brian Carlstromdf629502013-07-17 22:39:56 -07001411 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001412 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1413 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001414 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001415 }
1416
1417 bool Failed() const {
1418 return failed_;
1419 }
1420
1421 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001422 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001423 bool failed_;
1424};
1425
1426bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001427 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001428
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001429 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001430 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001431 VerifyLiveStackReferences visitor(this);
1432 GetLiveBitmap()->Visit(visitor);
1433
1434 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001435 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001436 visitor(*it);
1437 }
1438
1439 if (visitor.Failed()) {
1440 DumpSpaces();
1441 return false;
1442 }
1443 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001444}
1445
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001446void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001447 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001448
1449 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001450 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001451 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001452 }
1453}
1454
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001455void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001456 // Clear cards and keep track of cards cleared in the mod-union table.
1457 typedef std::vector<space::ContinuousSpace*>::iterator It;
1458 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1459 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001460 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001461 timings.NewSplit("ModUnionClearCards");
1462 image_mod_union_table_->ClearCards(space);
1463 } else if (space->IsZygoteSpace()) {
1464 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001465 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001466 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001467 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1468 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001469 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001470 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001471 }
1472 }
1473}
1474
Ian Rogers1d54e732013-05-02 21:10:01 -07001475void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001476 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1477 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001478
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001479 if (verify_pre_gc_heap_) {
1480 thread_list->SuspendAll();
1481 {
1482 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1483 if (!VerifyHeapReferences()) {
1484 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1485 }
1486 }
1487 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001488 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001489
1490 // Check that all objects which reference things in the live stack are on dirty cards.
1491 if (verify_missing_card_marks_) {
1492 thread_list->SuspendAll();
1493 {
1494 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1495 SwapStacks();
1496 // Sort the live stack so that we can quickly binary search it later.
1497 if (!VerifyMissingCardMarks()) {
1498 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1499 }
1500 SwapStacks();
1501 }
1502 thread_list->ResumeAll();
1503 }
1504
1505 if (verify_mod_union_table_) {
1506 thread_list->SuspendAll();
1507 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1508 zygote_mod_union_table_->Update();
1509 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001510 image_mod_union_table_->Update();
1511 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001512 thread_list->ResumeAll();
1513 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001514}
1515
Ian Rogers1d54e732013-05-02 21:10:01 -07001516void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001517 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001518
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001519 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1520 // reachable objects.
1521 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001522 Thread* self = Thread::Current();
1523 CHECK_NE(self->GetState(), kRunnable);
1524 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001526 {
1527 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1528 // Swapping bound bitmaps does nothing.
1529 gc->SwapBitmaps();
1530 if (!VerifyHeapReferences()) {
1531 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1532 }
1533 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001534 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001535 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001536 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001537 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001538}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001539
Ian Rogers1d54e732013-05-02 21:10:01 -07001540void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001541 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001542
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001543 if (verify_system_weaks_) {
1544 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001545 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001546 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001548}
1549
Ian Rogers1d54e732013-05-02 21:10:01 -07001550collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1551 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001552 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001553 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001554 bool do_wait;
1555 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556 {
1557 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001558 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001559 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001560 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001561 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001562 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001563 // We must wait, change thread state then sleep on gc_complete_cond_;
1564 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1565 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001566 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001567 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001568 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001569 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001570 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001571 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001572 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001573 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001574 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001575 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1576 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001577 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001578 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001579 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001580 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001581}
1582
Elliott Hughesc967f782012-04-16 10:23:15 -07001583void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001584 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001585 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001586 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001587}
1588
1589size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001590 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001591}
1592
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001593void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001594 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001595 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001596 << PrettySize(GetMaxMemory());
1597 max_allowed_footprint = GetMaxMemory();
1598 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001599 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001600}
1601
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001602void Heap::UpdateMaxNativeFootprint() {
1603 size_t native_size = native_bytes_allocated_;
1604 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1605 size_t target_size = native_size / GetTargetHeapUtilization();
1606 if (target_size > native_size + max_free_) {
1607 target_size = native_size + max_free_;
1608 } else if (target_size < native_size + min_free_) {
1609 target_size = native_size + min_free_;
1610 }
1611 native_footprint_gc_watermark_ = target_size;
1612 native_footprint_limit_ = 2 * target_size - native_size;
1613}
1614
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001615void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001616 // We know what our utilization is at this moment.
1617 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001618 const size_t bytes_allocated = GetBytesAllocated();
1619 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001620 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001621
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001622 size_t target_size;
1623 if (gc_type != collector::kGcTypeSticky) {
1624 // Grow the heap for non sticky GC.
1625 target_size = bytes_allocated / GetTargetHeapUtilization();
1626 if (target_size > bytes_allocated + max_free_) {
1627 target_size = bytes_allocated + max_free_;
1628 } else if (target_size < bytes_allocated + min_free_) {
1629 target_size = bytes_allocated + min_free_;
1630 }
1631 next_gc_type_ = collector::kGcTypeSticky;
1632 } else {
1633 // Based on how close the current heap size is to the target size, decide
1634 // whether or not to do a partial or sticky GC next.
1635 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1636 next_gc_type_ = collector::kGcTypeSticky;
1637 } else {
1638 next_gc_type_ = collector::kGcTypePartial;
1639 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001640
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001641 // If we have freed enough memory, shrink the heap back down.
1642 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1643 target_size = bytes_allocated + max_free_;
1644 } else {
1645 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1646 }
1647 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001648 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001649
Ian Rogers1d54e732013-05-02 21:10:01 -07001650 // Calculate when to perform the next ConcurrentGC.
1651 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001652 // Calculate the estimated GC duration.
1653 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1654 // Estimate how many remaining bytes we will have when we need to start the next GC.
1655 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001656 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1657 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1658 // A never going to happen situation that from the estimated allocation rate we will exceed
1659 // the applications entire footprint with the given estimated allocation rate. Schedule
1660 // another GC straight away.
1661 concurrent_start_bytes_ = bytes_allocated;
1662 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001663 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1664 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1665 // right away.
1666 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001667 }
1668 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1669 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1670 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001671
1672 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001673}
1674
jeffhaoc1160702011-10-27 15:48:45 -07001675void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001676 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001677 alloc_space_->ClearGrowthLimit();
1678}
1679
Elliott Hughesadb460d2011-10-05 17:02:34 -07001680void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001681 MemberOffset reference_queue_offset,
1682 MemberOffset reference_queueNext_offset,
1683 MemberOffset reference_pendingNext_offset,
1684 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001685 reference_referent_offset_ = reference_referent_offset;
1686 reference_queue_offset_ = reference_queue_offset;
1687 reference_queueNext_offset_ = reference_queueNext_offset;
1688 reference_pendingNext_offset_ = reference_pendingNext_offset;
1689 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1690 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1691 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1692 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1693 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1694 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1695}
1696
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001697mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001698 DCHECK(reference != NULL);
1699 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001700 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001701}
1702
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001703void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001704 DCHECK(reference != NULL);
1705 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1706 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1707}
1708
1709// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001710bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001711 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001712 const mirror::Object* queue =
1713 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1714 const mirror::Object* queue_next =
1715 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001716 return (queue != NULL) && (queue_next == NULL);
1717}
1718
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001719void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001720 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001721 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1722 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001723 EnqueuePendingReference(ref, cleared_reference_list);
1724}
1725
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001726void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001727 DCHECK(ref != NULL);
1728 DCHECK(list != NULL);
1729
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001730 // TODO: Remove this lock, use atomic stacks for storing references.
1731 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001732 if (*list == NULL) {
1733 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1734 *list = ref;
1735 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001736 mirror::Object* head =
1737 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001738 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1739 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1740 }
1741}
1742
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001743mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001744 DCHECK(list != NULL);
1745 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001746 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1747 false);
1748 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001749
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001750 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1751 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001752 if (*list == head) {
1753 ref = *list;
1754 *list = NULL;
1755 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001756 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1757 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001758 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1759 ref = head;
1760 }
1761 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1762 return ref;
1763}
1764
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001765void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001766 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001767 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001768 ArgArray arg_array(NULL, 0);
1769 arg_array.Append(reinterpret_cast<uint32_t>(object));
1770 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001771 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001772}
1773
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001774void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001775 DCHECK(cleared != NULL);
1776 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001777 // When a runtime isn't started there are no reference queues to care about so ignore.
1778 if (LIKELY(Runtime::Current()->IsStarted())) {
1779 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001780 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001781 ArgArray arg_array(NULL, 0);
1782 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1783 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001784 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001785 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001786 *cleared = NULL;
1787 }
1788}
1789
Ian Rogers1f539342012-10-03 21:09:42 -07001790void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001791 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001792 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001793 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001794 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001795 !runtime->IsConcurrentGcEnabled()) {
1796 return;
1797 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001798 {
1799 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1800 if (runtime->IsShuttingDown()) {
1801 return;
1802 }
1803 }
1804 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001805 return;
1806 }
1807
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001808 // We already have a request pending, no reason to start more until we update
1809 // concurrent_start_bytes_.
1810 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1811
Ian Rogers120f1c72012-09-28 17:17:10 -07001812 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001813 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1814 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001815 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1816 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001817 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001818}
1819
Ian Rogers81d425b2012-09-27 16:03:43 -07001820void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001821 {
1822 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001823 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001824 return;
1825 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001826 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001827
Mathieu Chartier65db8802012-11-20 12:36:46 -08001828 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001829 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001830 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001831 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001832}
1833
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001834void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001835 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1836 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1837 // a space it will hold its lock and can become a cause of jank.
1838 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1839 // forking.
1840
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001841 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1842 // because that only marks object heads, so a large array looks like lots of empty space. We
1843 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1844 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1845 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1846 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001847 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001848 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001849 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1850 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001851 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1852 // heap trim occurred in the last two seconds.
1853 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001854 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001855
1856 Thread* self = Thread::Current();
1857 {
1858 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1859 Runtime* runtime = Runtime::Current();
1860 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1861 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1862 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1863 // as we don't hold the lock while requesting the trim).
1864 return;
1865 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001866 }
Ian Rogers48931882013-01-22 14:35:16 -08001867
1868 SchedPolicy policy;
1869 get_sched_policy(self->GetTid(), &policy);
1870 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1871 // Don't trim the heap if we are a foreground or audio app.
1872 return;
1873 }
1874
Ian Rogers1d54e732013-05-02 21:10:01 -07001875 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001876 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001877 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1878 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001879 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1880 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001881 CHECK(!env->ExceptionCheck());
1882}
1883
Ian Rogers48931882013-01-22 14:35:16 -08001884size_t Heap::Trim() {
1885 // Handle a requested heap trim on a thread outside of the main GC thread.
1886 return alloc_space_->Trim();
1887}
1888
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001889bool Heap::IsGCRequestPending() const {
1890 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
1891}
1892
1893void Heap::RegisterNativeAllocation(int bytes) {
1894 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001895 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001896 Thread* self = Thread::Current();
1897 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
1898 // The second watermark is higher than the gc watermark. If you hit this it means you are
1899 // allocating native objects faster than the GC can keep up with.
1900 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1901 JNIEnv* env = self->GetJniEnv();
1902 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
1903 // point.
1904 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
1905 DCHECK(WellKnownClasses::java_lang_System != NULL);
1906 WellKnownClasses::java_lang_System_runFinalization =
1907 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
1908 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
1909 }
1910 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
1911 // Just finished a GC, attempt to run finalizers.
1912 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1913 WellKnownClasses::java_lang_System_runFinalization);
1914 CHECK(!env->ExceptionCheck());
1915 }
1916
1917 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
1918 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1919 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
1920 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1921 WellKnownClasses::java_lang_System_runFinalization);
1922 CHECK(!env->ExceptionCheck());
1923 }
1924 // We have just run finalizers, update the native watermark since it is very likely that
1925 // finalizers released native managed allocations.
1926 UpdateMaxNativeFootprint();
1927 } else {
1928 if (!IsGCRequestPending()) {
1929 RequestConcurrentGC(self);
1930 }
1931 }
1932 }
1933}
1934
1935void Heap::RegisterNativeFree(int bytes) {
1936 int expected_size, new_size;
1937 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001938 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001939 new_size = expected_size - bytes;
1940 if (new_size < 0) {
1941 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
1942 bytes, expected_size);
1943 break;
1944 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001945 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001946}
1947
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001948int64_t Heap::GetTotalMemory() const {
1949 int64_t ret = 0;
1950 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1951 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1952 space::ContinuousSpace* space = *it;
1953 if (space->IsImageSpace()) {
1954 // Currently don't include the image space.
1955 } else if (space->IsDlMallocSpace()) {
1956 // Zygote or alloc space
1957 ret += space->AsDlMallocSpace()->GetFootprint();
1958 }
1959 }
1960 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
1961 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
1962 space::DiscontinuousSpace* space = *it;
1963 if (space->IsLargeObjectSpace()) {
1964 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
1965 }
1966 }
1967 return ret;
1968}
1969
Ian Rogers1d54e732013-05-02 21:10:01 -07001970} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001971} // namespace art