blob: ece99209cac4e9b9a8e234267a3e573133c76dfb [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 Chartier0418ae22013-07-31 13:35:46 -070063static const bool kGCALotMode = false;
64static const size_t kGcAlotInterval = KB;
Mathieu Chartier65db8802012-11-20 12:36:46 -080065static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070066// Minimum amount of remaining bytes before a concurrent GC is triggered.
67static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070068const double Heap::kDefaultTargetUtilization = 0.5;
69
Mathieu Chartier0051be62012-10-12 17:47:11 -070070Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
71 double target_utilization, size_t capacity,
Mathieu Chartier63a54342013-07-23 13:17:59 -070072 const std::string& original_image_file_name, bool concurrent_gc, size_t num_gc_threads)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070073 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080074 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070075 concurrent_gc_(concurrent_gc),
Mathieu Chartier63a54342013-07-23 13:17:59 -070076 num_gc_threads_(num_gc_threads),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070077 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070078 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080079 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070080 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070081 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080082 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070083 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070084 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070085 native_footprint_gc_watermark_(initial_size),
86 native_footprint_limit_(2 * initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -070087 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
88 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -070089 total_bytes_freed_ever_(0),
90 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070091 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080092 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070093 native_bytes_allocated_(0),
Mathieu Chartier82353312013-07-18 10:47:51 -070094 process_state_(PROCESS_STATE_TOP),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -070095 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -070096 verify_missing_card_marks_(false),
97 verify_system_weaks_(false),
98 verify_pre_gc_heap_(false),
99 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700100 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700101 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700102 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700103 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800104 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700105 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
106 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
107 * verification is enabled, we limit the size of allocation stacks to speed up their
108 * searching.
109 */
110 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
111 : (kDesiredHeapVerification > kNoHeapVerification) ? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800112 reference_referent_offset_(0),
113 reference_queue_offset_(0),
114 reference_queueNext_offset_(0),
115 reference_pendingNext_offset_(0),
116 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700117 min_free_(min_free),
118 max_free_(max_free),
119 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700120 total_wait_time_(0),
121 measure_allocation_time_(false),
122 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700123 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800124 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800125 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700126 }
127
Ian Rogers1d54e732013-05-02 21:10:01 -0700128 live_bitmap_.reset(new accounting::HeapBitmap(this));
129 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700130
Ian Rogers30fab402012-01-23 15:43:46 -0800131 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700132 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800133 std::string image_file_name(original_image_file_name);
134 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700135 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
136 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700137 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800138 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
139 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800140 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
141 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700142 if (oat_file_end_addr > requested_alloc_space_begin) {
143 requested_alloc_space_begin =
144 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
145 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700146 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700147 }
148
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700149 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700150 const bool kUseFreeListSpaceForLOS = false;
151 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700152 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700153 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700154 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700155 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700156 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
157 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700158
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700159 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700160 initial_size,
161 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700162 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700163 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700164 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700165 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700166
Ian Rogers1d54e732013-05-02 21:10:01 -0700167 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
168 byte* heap_begin = continuous_spaces_.front()->Begin();
169 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
170 if (continuous_spaces_.back()->IsDlMallocSpace()) {
171 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700172 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700173
Ian Rogers30fab402012-01-23 15:43:46 -0800174 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700175 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700176 typedef std::vector<space::ContinuousSpace*>::iterator It;
177 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
178 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800179 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700180 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700181 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800182 }
183 }
184
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800185 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700186 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700187 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700188
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700189 image_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Ian Rogers1d54e732013-05-02 21:10:01 -0700190 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700191
Ian Rogers1d54e732013-05-02 21:10:01 -0700192 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700193 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700194
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700195 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700196 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700197
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800198 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700199 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700200 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
201 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
202 max_allocation_stack_size_));
203 live_stack_.reset(accounting::ObjectStack::Create("live stack",
204 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700205
Mathieu Chartier65db8802012-11-20 12:36:46 -0800206 // It's still too early to take a lock because there are no threads yet, but we can create locks
207 // now. We don't create it earlier to make it clear that you can't use locks during heap
208 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700209 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700210 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
211 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700212
Mathieu Chartier63a54342013-07-23 13:17:59 -0700213 // Create the reference queue lock, this is required so for parallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700214 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700215
Ian Rogers1d54e732013-05-02 21:10:01 -0700216 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800217 last_gc_size_ = GetBytesAllocated();
218
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800219 // Create our garbage collectors.
220 for (size_t i = 0; i < 2; ++i) {
221 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700222 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
223 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
224 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700225 }
226
Brian Carlstrom42748892013-07-18 18:04:08 -0700227 CHECK_NE(max_allowed_footprint_, 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800228 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800229 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700230 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700231}
232
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700233void Heap::CreateThreadPool() {
Mathieu Chartier63a54342013-07-23 13:17:59 -0700234 thread_pool_.reset(new ThreadPool(num_gc_threads_));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700235}
236
237void Heap::DeleteThreadPool() {
238 thread_pool_.reset(NULL);
239}
240
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700241// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700242struct ContinuousSpaceSorter {
Brian Carlstromdf629502013-07-17 22:39:56 -0700243 bool operator()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700244 return a->Begin() < b->Begin();
245 }
246};
247
Mathieu Chartier82353312013-07-18 10:47:51 -0700248void Heap::UpdateProcessState(ProcessState process_state) {
249 process_state_ = process_state;
250}
251
Ian Rogers1d54e732013-05-02 21:10:01 -0700252void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700253 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700254 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700255 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700256 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700257 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700258 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
259 continuous_spaces_.push_back(space);
260 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
261 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700262 }
263
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700264 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700265 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700266
267 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
268 // avoid redundant marking.
269 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700270 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
271 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
272 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700273 if (space->IsImageSpace()) {
274 DCHECK(!seen_zygote);
275 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700276 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700277 DCHECK(!seen_alloc);
278 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700279 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700280 seen_alloc = true;
281 }
282 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800283}
284
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700285void Heap::RegisterGCAllocation(size_t bytes) {
286 if (this != NULL) {
287 gc_memory_overhead_.fetch_add(bytes);
288 }
289}
290
291void Heap::RegisterGCDeAllocation(size_t bytes) {
292 if (this != NULL) {
293 gc_memory_overhead_.fetch_sub(bytes);
294 }
295}
296
Ian Rogers1d54e732013-05-02 21:10:01 -0700297void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
298 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
299 DCHECK(space != NULL);
300 DCHECK(space->GetLiveObjects() != NULL);
301 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
302 DCHECK(space->GetMarkObjects() != NULL);
303 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
304 discontinuous_spaces_.push_back(space);
305}
306
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700307void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700308 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700309 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700310 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800311
312 // Dump cumulative loggers for each GC type.
313 // TODO: C++0x
314 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700315 typedef std::vector<collector::MarkSweep*>::const_iterator It;
316 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800317 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700318 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800319 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800320 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700321 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800322 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700323 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800324 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
325 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
326 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700327 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
328 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
329 << collector->GetName() << " freed: " << freed_objects
330 << " objects with total size " << PrettySize(freed_bytes) << "\n"
331 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
332 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800333 total_duration += total_ns;
334 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700335 }
336 }
337 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700338 size_t total_objects_allocated = GetObjectsAllocatedEver();
339 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700340 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700341 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700342 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
343 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700344 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700345 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700346 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700347 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700348 os << "Total number of allocations: " << total_objects_allocated << "\n";
349 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700350 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700351 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
352 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
353 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700354 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700355 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
356 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700357 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700358}
359
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800360Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700361 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700362 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700363 }
364
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800365 STLDeleteElements(&mark_sweep_collectors_);
366
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700367 // If we don't reset then the mark stack complains in it's destructor.
368 allocation_stack_->Reset();
369 live_stack_->Reset();
370
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800371 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800372 // We can't take the heap lock here because there might be a daemon thread suspended with the
373 // heap lock held. We know though that no non-daemon threads are executing, and we know that
374 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
375 // 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 -0700376 STLDeleteElements(&continuous_spaces_);
377 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700378 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700379 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700380}
381
Ian Rogers1d54e732013-05-02 21:10:01 -0700382space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
383 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700384 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700385 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
386 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700387 if ((*it)->Contains(obj)) {
388 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700389 }
390 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700391 if (!fail_ok) {
392 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
393 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700394 return NULL;
395}
396
Ian Rogers1d54e732013-05-02 21:10:01 -0700397space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
398 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700399 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700400 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
401 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
402 if ((*it)->Contains(obj)) {
403 return *it;
404 }
405 }
406 if (!fail_ok) {
407 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
408 }
409 return NULL;
410}
411
412space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
413 space::Space* result = FindContinuousSpaceFromObject(obj, true);
414 if (result != NULL) {
415 return result;
416 }
417 return FindDiscontinuousSpaceFromObject(obj, true);
418}
419
420space::ImageSpace* Heap::GetImageSpace() const {
421 // TODO: C++0x auto
422 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
423 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700424 if ((*it)->IsImageSpace()) {
425 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700426 }
427 }
428 return NULL;
429}
430
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700431static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700432 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700433 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700434 size_t chunk_free_bytes = chunk_size - used_bytes;
435 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
436 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700437 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700438}
439
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800440mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
441 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
443 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800444 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700445
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800446 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700447 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700448 uint64_t allocation_start = 0;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700449 if (UNLIKELY(measure_allocation_time_)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700450 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700451 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700452
453 // We need to have a zygote space or else our newly allocated large object can end up in the
454 // Zygote resulting in it being prematurely freed.
455 // We can only do this for primive objects since large objects will not be within the card table
456 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers333cf1b2013-07-24 11:57:02 -0700457 bool large_object_allocation =
458 byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
459 if (UNLIKELY(large_object_allocation)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700460 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700461 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700462 // Make sure that our large object didn't get placed anywhere within the space interval or else
463 // it breaks the immune range.
464 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700465 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
466 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700467 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700468 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700469
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700470 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700471 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700472 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700473 }
474
Mathieu Chartier037813d2012-08-23 16:44:59 -0700475 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700477
478 // Record allocation after since we want to use the atomic add for the atomic fence to guard
479 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700480 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700481
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 if (Dbg::IsAllocTrackingEnabled()) {
483 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700484 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700485 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700486 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800487 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700488 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489 }
490 VerifyObject(obj);
491
Ian Rogers333cf1b2013-07-24 11:57:02 -0700492 if (UNLIKELY(measure_allocation_time_)) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700493 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700494 }
495
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496 return obj;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700497 } else {
498 std::ostringstream oss;
499 int64_t total_bytes_free = GetFreeMemory();
500 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
501 << " free bytes";
502 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
503 if (!large_object_allocation && total_bytes_free >= byte_count) {
504 size_t max_contiguous_allocation = 0;
505 // TODO: C++0x auto
506 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
507 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
508 space::ContinuousSpace* space = *it;
509 if (space->IsDlMallocSpace()) {
510 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
511 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800512 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700513 oss << "; failed due to fragmentation (largest possible contiguous allocation "
514 << max_contiguous_allocation << " bytes)";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700515 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700516 self->ThrowOutOfMemoryError(oss.str().c_str());
517 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700518 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700519}
520
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800521bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700522 // Note: we deliberately don't take the lock here, and mustn't test anything that would
523 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700524 if (obj == NULL) {
525 return true;
526 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700527 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700528 return false;
529 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700530 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700531}
532
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800533bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700534 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700535 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700536 return false;
537 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700538 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
539 space::DiscontinuousSpace* d_space = NULL;
540 if (c_space != NULL) {
541 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700542 return true;
543 }
544 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700545 d_space = FindDiscontinuousSpaceFromObject(obj, true);
546 if (d_space != NULL) {
547 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700548 return true;
549 }
550 }
551 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700552 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Ian Rogers1d54e732013-05-02 21:10:01 -0700553 for (size_t i = 0; i < 5; ++i) {
554 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
555 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
556 return true;
557 }
558 NanoSleep(MsToNs(10));
559 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700560 // We need to check the bitmaps again since there is a race where we mark something as live and
561 // then clear the stack containing it.
562 if (c_space != NULL) {
563 if (c_space->GetLiveBitmap()->Test(obj)) {
564 return true;
565 }
566 } else {
567 d_space = FindDiscontinuousSpaceFromObject(obj, true);
568 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
569 return true;
570 }
571 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700572 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700573}
574
Ian Rogers04d7aa92013-03-16 14:29:17 -0700575void Heap::VerifyObjectImpl(const mirror::Object* obj) {
576 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700577 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700578 return;
579 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700580 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700581}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700582
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700583void Heap::DumpSpaces() {
584 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700585 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
586 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
587 space::ContinuousSpace* space = *it;
588 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
589 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700590 LOG(INFO) << space << " " << *space << "\n"
591 << live_bitmap << " " << *live_bitmap << "\n"
592 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700593 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700594 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
595 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
596 space::DiscontinuousSpace* space = *it;
597 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700598 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700599}
600
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800601void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800602 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700603 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700604 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800605 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
606 return;
607 }
608 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
609 mirror::Object::ClassOffset().Int32Value();
610 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
611 if (UNLIKELY(c == NULL)) {
612 LOG(FATAL) << "Null class in object: " << obj;
613 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
614 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
615 }
616 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
617 // Note: we don't use the accessors here as they have internal sanity checks
618 // that we don't want to run
619 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
620 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
621 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
622 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
623 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700624
Ian Rogers62d6c772013-02-27 08:32:07 -0800625 if (verify_object_mode_ != kVerifyAllFast) {
626 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
627 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700628 if (!IsLiveObjectLocked(obj)) {
629 DumpSpaces();
630 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700631 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700632 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700633 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
634 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700635 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700636}
637
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800638void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700639 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700640 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700641}
642
643void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700644 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700645 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700646}
647
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800648void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700649 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700650 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700651 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700652
653 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700654 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700655 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700656 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700657
658 // TODO: Update these atomically.
659 RuntimeStats* global_stats = Runtime::Current()->GetStats();
660 ++global_stats->allocated_objects;
661 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700662 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700663
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700664 // This is safe to do since the GC will never free objects which are neither in the allocation
665 // stack or the live bitmap.
666 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700667 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700668 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700669}
670
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700672 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700673 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700674
675 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700676 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700677 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700678 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700679
680 // TODO: Do this concurrently.
681 RuntimeStats* global_stats = Runtime::Current()->GetStats();
682 global_stats->freed_objects += freed_objects;
683 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700684 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700685}
686
Ian Rogers1d54e732013-05-02 21:10:01 -0700687mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
688 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700689 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800690 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
691 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
692 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
693 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700694 return NULL;
695 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700696 }
697
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700698 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700699}
700
Ian Rogers1d54e732013-05-02 21:10:01 -0700701mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700702 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
703 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700704 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700705 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700706
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800707 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700708 if (ptr != NULL) {
709 return ptr;
710 }
711
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700712 // The allocation failed. If the GC is running, block until it completes, and then retry the
713 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700714 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
715 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700716 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700717 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700718 if (ptr != NULL) {
719 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700720 }
721 }
722
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700723 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700724 for (size_t i = static_cast<size_t>(last_gc) + 1;
725 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700726 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700727 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700728 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700729 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700730 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700731 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
732 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700733 break;
734 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700735 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700736 run_gc = have_zygote_space_;
737 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700738 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700739 run_gc = true;
740 break;
741 default:
742 break;
743 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700744
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700745 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700746 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700747 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800748 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700749 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700750
751 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700752 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700753 if (ptr != NULL) {
754 return ptr;
755 }
756 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700757 }
758
759 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700760 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700761 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700762 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700763 return ptr;
764 }
765
Elliott Hughes81ff3182012-03-23 20:35:56 -0700766 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
767 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
768 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700769
Elliott Hughes418dfe72011-10-06 18:56:27 -0700770 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700771 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
772 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700773
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700774 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700775 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700776 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700777}
778
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700779void Heap::SetTargetHeapUtilization(float target) {
780 DCHECK_GT(target, 0.0f); // asserted in Java code
781 DCHECK_LT(target, 1.0f);
782 target_utilization_ = target;
783}
784
Ian Rogers1d54e732013-05-02 21:10:01 -0700785size_t Heap::GetObjectsAllocated() const {
786 size_t total = 0;
787 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
788 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
789 space::ContinuousSpace* space = *it;
790 if (space->IsDlMallocSpace()) {
791 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700792 }
793 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700794 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
795 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
796 space::DiscontinuousSpace* space = *it;
797 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
798 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700799 return total;
800}
801
Ian Rogers1d54e732013-05-02 21:10:01 -0700802size_t Heap::GetObjectsAllocatedEver() const {
803 size_t total = 0;
804 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
805 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
806 space::ContinuousSpace* space = *it;
807 if (space->IsDlMallocSpace()) {
808 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700809 }
810 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700811 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
812 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
813 space::DiscontinuousSpace* space = *it;
814 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
815 }
816 return total;
817}
818
819size_t Heap::GetBytesAllocatedEver() const {
820 size_t total = 0;
821 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
822 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
823 space::ContinuousSpace* space = *it;
824 if (space->IsDlMallocSpace()) {
825 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
826 }
827 }
828 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
829 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
830 space::DiscontinuousSpace* space = *it;
831 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
832 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700833 return total;
834}
835
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700836class InstanceCounter {
837 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800838 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700839 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800840 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700841 }
842
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800843 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800844 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800845 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800846 if (use_is_assignable_from_) {
847 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
848 ++counts_[i];
849 }
850 } else {
851 if (instance_class == classes_[i]) {
852 ++counts_[i];
853 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700854 }
855 }
856 }
857
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700858 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800859 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800860 bool use_is_assignable_from_;
861 uint64_t* const counts_;
862
863 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700864};
865
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800866void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800867 uint64_t* counts) {
868 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
869 // is empty, so the live bitmap is the only place we need to look.
870 Thread* self = Thread::Current();
871 self->TransitionFromRunnableToSuspended(kNative);
872 CollectGarbage(false);
873 self->TransitionFromSuspendedToRunnable();
874
875 InstanceCounter counter(classes, use_is_assignable_from, counts);
876 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700877 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700878}
879
Elliott Hughes3b78c942013-01-15 17:35:41 -0800880class InstanceCollector {
881 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800882 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800883 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
884 : class_(c), max_count_(max_count), instances_(instances) {
885 }
886
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800887 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
888 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800889 if (instance_class == class_) {
890 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800891 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800892 }
893 }
894 }
895
896 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800897 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800898 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800899 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800900
901 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
902};
903
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800904void Heap::GetInstances(mirror::Class* c, int32_t max_count,
905 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800906 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
907 // is empty, so the live bitmap is the only place we need to look.
908 Thread* self = Thread::Current();
909 self->TransitionFromRunnableToSuspended(kNative);
910 CollectGarbage(false);
911 self->TransitionFromSuspendedToRunnable();
912
913 InstanceCollector collector(c, max_count, instances);
914 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
915 GetLiveBitmap()->Visit(collector);
916}
917
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800918class ReferringObjectsFinder {
919 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800920 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
921 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800922 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
923 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
924 }
925
926 // For bitmap Visit.
927 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
928 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800929 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -0700930 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800931 }
932
933 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -0700934 void operator()(const mirror::Object* referrer, const mirror::Object* object,
935 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800936 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800937 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800938 }
939 }
940
941 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800942 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800943 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800944 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800945
946 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
947};
948
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800949void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
950 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800951 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
952 // is empty, so the live bitmap is the only place we need to look.
953 Thread* self = Thread::Current();
954 self->TransitionFromRunnableToSuspended(kNative);
955 CollectGarbage(false);
956 self->TransitionFromSuspendedToRunnable();
957
958 ReferringObjectsFinder finder(o, max_count, referring_objects);
959 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
960 GetLiveBitmap()->Visit(finder);
961}
962
Ian Rogers30fab402012-01-23 15:43:46 -0800963void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700964 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
965 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700966 Thread* self = Thread::Current();
967 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700968 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700969}
970
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700971void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700972 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800973 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
974 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700975 Thread* self = Thread::Current();
976 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700977
978 // Try to see if we have any Zygote spaces.
979 if (have_zygote_space_) {
980 return;
981 }
982
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700983 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
984
985 {
986 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700987 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700988 FlushAllocStack();
989 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700990
Ian Rogers1d54e732013-05-02 21:10:01 -0700991 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
992 // of the remaining available heap memory.
993 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700994 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -0700995 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700996
Ian Rogers1d54e732013-05-02 21:10:01 -0700997 // Change the GC retention policy of the zygote space to only collect when full.
998 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
999 AddContinuousSpace(alloc_space_);
1000 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001001
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001002 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001003 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001004 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1005 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1006 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001007 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001008 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001009}
1010
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001011void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001012 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1013 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001014 allocation_stack_->Reset();
1015}
1016
Ian Rogers1d54e732013-05-02 21:10:01 -07001017void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1018 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001019 mirror::Object** limit = stack->End();
1020 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1021 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001022 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001023 if (LIKELY(bitmap->HasAddress(obj))) {
1024 bitmap->Set(obj);
1025 } else {
1026 large_objects->Set(obj);
1027 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001028 }
1029}
1030
Ian Rogers1d54e732013-05-02 21:10:01 -07001031void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1032 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001033 mirror::Object** limit = stack->End();
1034 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1035 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001036 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001037 if (LIKELY(bitmap->HasAddress(obj))) {
1038 bitmap->Clear(obj);
1039 } else {
1040 large_objects->Clear(obj);
1041 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001042 }
1043}
1044
Ian Rogers1d54e732013-05-02 21:10:01 -07001045collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1046 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001047 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001048
1049 switch (gc_cause) {
1050 case kGcCauseForAlloc:
1051 ATRACE_BEGIN("GC (alloc)");
1052 break;
1053 case kGcCauseBackground:
1054 ATRACE_BEGIN("GC (background)");
1055 break;
1056 case kGcCauseExplicit:
1057 ATRACE_BEGIN("GC (explicit)");
1058 break;
1059 }
1060
Mathieu Chartier65db8802012-11-20 12:36:46 -08001061 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001062 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001063
Ian Rogers120f1c72012-09-28 17:17:10 -07001064 if (self->IsHandlingStackOverflow()) {
1065 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1066 }
1067
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001068 // Ensure there is only one GC at a time.
1069 bool start_collect = false;
1070 while (!start_collect) {
1071 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001072 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001073 if (!is_gc_running_) {
1074 is_gc_running_ = true;
1075 start_collect = true;
1076 }
1077 }
1078 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001079 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001080 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1081 // Not doing at the moment to ensure soft references are cleared.
1082 }
1083 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001084 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001085
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001086 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1087 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1088 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1089 }
1090
Ian Rogers1d54e732013-05-02 21:10:01 -07001091 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001092 uint64_t gc_start_size = GetBytesAllocated();
1093 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001094 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001095 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1096 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001097 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001098 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001099 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001100 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1101 }
1102
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001103 if (gc_type == collector::kGcTypeSticky &&
1104 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1105 gc_type = collector::kGcTypePartial;
1106 }
1107
Ian Rogers1d54e732013-05-02 21:10:01 -07001108 DCHECK_LT(gc_type, collector::kGcTypeMax);
1109 DCHECK_NE(gc_type, collector::kGcTypeNone);
1110 collector::MarkSweep* collector = NULL;
1111 typedef std::vector<collector::MarkSweep*>::iterator It;
1112 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1113 it != end; ++it) {
1114 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001115 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1116 collector = cur_collector;
1117 break;
1118 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001119 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001120 CHECK(collector != NULL)
1121 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1122 << " and type=" << gc_type;
1123 collector->clear_soft_references_ = clear_soft_references;
1124 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001125 total_objects_freed_ever_ += collector->GetFreedObjects();
1126 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001127
Ian Rogers1d54e732013-05-02 21:10:01 -07001128 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001129 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1130 bool was_slow = duration > kSlowGcThreshold ||
1131 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1132 for (size_t i = 0; i < pauses.size(); ++i) {
1133 if (pauses[i] > kLongGcPauseThreshold) {
1134 was_slow = true;
1135 }
1136 }
1137
1138 if (was_slow) {
1139 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001140 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001141 const size_t total_memory = GetTotalMemory();
1142 std::ostringstream pause_string;
1143 for (size_t i = 0; i < pauses.size(); ++i) {
1144 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1145 << ((i != pauses.size() - 1) ? ", " : "");
1146 }
1147 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001148 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1149 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1150 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1151 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001152 if (VLOG_IS_ON(heap)) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001153 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001154 }
1155 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001156
Ian Rogers15bf2d32012-08-28 17:33:04 -07001157 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001158 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001159 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001160 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001161 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001162 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001163 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001164
Ian Rogers15bf2d32012-08-28 17:33:04 -07001165 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001166 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001167 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001168 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001169}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001170
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001171void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
Ian Rogers1d54e732013-05-02 21:10:01 -07001172 collector::GcType gc_type) {
1173 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001174 // 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 -07001175 // cards.
1176 return;
1177 }
1178
1179 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001180 if (gc_type == collector::kGcTypePartial) {
1181 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001182 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001183
Ian Rogers1d54e732013-05-02 21:10:01 -07001184 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001185 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001186 }
1187
1188 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001189 timings.NewSplit("UpdateModUnionTable");
1190 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001191
1192 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001193 timings.NewSplit("MarkImageToAllocSpaceReferences");
1194 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001195}
1196
Ian Rogers1d54e732013-05-02 21:10:01 -07001197static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001198 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001199 if (root == obj) {
1200 LOG(INFO) << "Object " << obj << " is a root";
1201 }
1202}
1203
1204class ScanVisitor {
1205 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001206 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001207 LOG(INFO) << "Would have rescanned object " << obj;
1208 }
1209};
1210
Ian Rogers1d54e732013-05-02 21:10:01 -07001211// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001212class VerifyReferenceVisitor {
1213 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001214 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001215 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001216 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001217
1218 bool Failed() const {
1219 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001220 }
1221
1222 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001223 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001224 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1225 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001226 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001227 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001228 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1229 accounting::CardTable* card_table = heap_->GetCardTable();
1230 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1231 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001232
Ian Rogers1d54e732013-05-02 21:10:01 -07001233 if (obj != NULL) {
1234 byte* card_addr = card_table->CardFromAddr(obj);
1235 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1236 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1237 << "\nObj type " << PrettyTypeOf(obj)
1238 << "\nRef type " << PrettyTypeOf(ref);
1239 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1240 void* cover_begin = card_table->AddrFromCard(card_addr);
1241 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1242 accounting::CardTable::kCardSize);
1243 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1244 << "-" << cover_end;
1245 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001246
Ian Rogers1d54e732013-05-02 21:10:01 -07001247 // Print out how the object is live.
1248 if (bitmap != NULL && bitmap->Test(obj)) {
1249 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1250 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001251 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001252 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1253 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001254 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001255 LOG(ERROR) << "Object " << obj << " found in live stack";
1256 }
1257 // Attempt to see if the card table missed the reference.
1258 ScanVisitor scan_visitor;
1259 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1260 card_table->Scan(bitmap, byte_cover_begin,
1261 byte_cover_begin + accounting::CardTable::kCardSize,
1262 scan_visitor, VoidFunctor());
1263
1264 // Search to see if any of the roots reference our object.
1265 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1266 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1267
1268 // Search to see if any of the roots reference our reference.
1269 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1270 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1271 } else {
1272 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001273 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001274 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001275 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001276 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001277 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001278 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001279 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001280 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1281 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1282 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001283 }
1284 }
1285
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001286 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001287 return heap_->IsLiveObjectLocked(obj);
1288 }
1289
1290 static void VerifyRoots(const mirror::Object* root, void* arg) {
1291 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1292 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001293 }
1294
1295 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001296 Heap* const heap_;
1297 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001298};
1299
Ian Rogers1d54e732013-05-02 21:10:01 -07001300// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001301class VerifyObjectVisitor {
1302 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001303 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001304
Brian Carlstromdf629502013-07-17 22:39:56 -07001305 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001306 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001307 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1308 // be live or else how did we find it in the live bitmap?
1309 VerifyReferenceVisitor visitor(heap_);
1310 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1311 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001312 }
1313
1314 bool Failed() const {
1315 return failed_;
1316 }
1317
1318 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001319 Heap* const heap_;
1320 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001321};
1322
1323// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001324bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001325 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001326 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001327 allocation_stack_->Sort();
1328 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001329 // Perform the verification.
1330 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001331 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001332 GetLiveBitmap()->Visit(visitor);
1333 // We don't want to verify the objects in the allocation stack since they themselves may be
1334 // pointing to dead objects if they are not reachable.
1335 if (visitor.Failed()) {
1336 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001337 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001338 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001339 return true;
1340}
1341
1342class VerifyReferenceCardVisitor {
1343 public:
1344 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1345 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1346 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001347 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001348 }
1349
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001350 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1351 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001352 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1353 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001354 // Filter out class references since changing an object's class does not mark the card as dirty.
1355 // Also handles large objects, since the only reference they hold is a class reference.
1356 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001357 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001358 // If the object is not dirty and it is referencing something in the live stack other than
1359 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001360 if (!card_table->AddrIsInCardTable(obj)) {
1361 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1362 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001363 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001364 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1365 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001366 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001367 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1368 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001369 LOG(ERROR) << "Object " << obj << " found in live stack";
1370 }
1371 if (heap_->GetLiveBitmap()->Test(obj)) {
1372 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1373 }
1374 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1375 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1376
1377 // Print which field of the object is dead.
1378 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001379 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001380 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001381 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1382 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001383 CHECK(fields != NULL);
1384 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001385 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001386 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1387 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1388 << PrettyField(cur);
1389 break;
1390 }
1391 }
1392 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001393 const mirror::ObjectArray<mirror::Object>* object_array =
1394 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001395 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1396 if (object_array->Get(i) == ref) {
1397 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1398 }
1399 }
1400 }
1401
1402 *failed_ = true;
1403 }
1404 }
1405 }
1406 }
1407
1408 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001409 Heap* const heap_;
1410 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001411};
1412
1413class VerifyLiveStackReferences {
1414 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001415 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001416 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001417 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001418
Brian Carlstromdf629502013-07-17 22:39:56 -07001419 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001420 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1421 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001422 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001423 }
1424
1425 bool Failed() const {
1426 return failed_;
1427 }
1428
1429 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001430 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001431 bool failed_;
1432};
1433
1434bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001435 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001436
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001437 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001438 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001439 VerifyLiveStackReferences visitor(this);
1440 GetLiveBitmap()->Visit(visitor);
1441
1442 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001443 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001444 visitor(*it);
1445 }
1446
1447 if (visitor.Failed()) {
1448 DumpSpaces();
1449 return false;
1450 }
1451 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001452}
1453
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001454void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001455 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001456
1457 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001458 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001459 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001460 }
1461}
1462
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001463void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001464 // Clear cards and keep track of cards cleared in the mod-union table.
1465 typedef std::vector<space::ContinuousSpace*>::iterator It;
1466 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1467 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001468 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001469 timings.NewSplit("ModUnionClearCards");
1470 image_mod_union_table_->ClearCards(space);
1471 } else if (space->IsZygoteSpace()) {
1472 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001473 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001474 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001475 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1476 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001477 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001478 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001479 }
1480 }
1481}
1482
Ian Rogers1d54e732013-05-02 21:10:01 -07001483void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001484 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1485 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001486
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001487 if (verify_pre_gc_heap_) {
1488 thread_list->SuspendAll();
1489 {
1490 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1491 if (!VerifyHeapReferences()) {
1492 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1493 }
1494 }
1495 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001496 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001497
1498 // Check that all objects which reference things in the live stack are on dirty cards.
1499 if (verify_missing_card_marks_) {
1500 thread_list->SuspendAll();
1501 {
1502 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1503 SwapStacks();
1504 // Sort the live stack so that we can quickly binary search it later.
1505 if (!VerifyMissingCardMarks()) {
1506 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1507 }
1508 SwapStacks();
1509 }
1510 thread_list->ResumeAll();
1511 }
1512
1513 if (verify_mod_union_table_) {
1514 thread_list->SuspendAll();
1515 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1516 zygote_mod_union_table_->Update();
1517 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001518 image_mod_union_table_->Update();
1519 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001520 thread_list->ResumeAll();
1521 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001522}
1523
Ian Rogers1d54e732013-05-02 21:10:01 -07001524void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001526
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001527 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1528 // reachable objects.
1529 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001530 Thread* self = Thread::Current();
1531 CHECK_NE(self->GetState(), kRunnable);
1532 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001534 {
1535 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1536 // Swapping bound bitmaps does nothing.
1537 gc->SwapBitmaps();
1538 if (!VerifyHeapReferences()) {
1539 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1540 }
1541 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001542 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001543 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001544 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001546}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547
Ian Rogers1d54e732013-05-02 21:10:01 -07001548void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001549 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001550
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001551 if (verify_system_weaks_) {
1552 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001553 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001554 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001555 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001556}
1557
Ian Rogers1d54e732013-05-02 21:10:01 -07001558collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1559 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001560 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001561 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001562 bool do_wait;
1563 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564 {
1565 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001566 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001567 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001568 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001569 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001570 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001571 // We must wait, change thread state then sleep on gc_complete_cond_;
1572 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1573 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001574 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001575 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001576 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001577 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001578 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001579 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001580 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001581 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001582 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1584 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001585 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001586 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001587 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001588 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001589}
1590
Elliott Hughesc967f782012-04-16 10:23:15 -07001591void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001592 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001593 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001594 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001595}
1596
1597size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001598 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001599}
1600
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001601void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001602 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001603 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001604 << PrettySize(GetMaxMemory());
1605 max_allowed_footprint = GetMaxMemory();
1606 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001607 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001608}
1609
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001610void Heap::UpdateMaxNativeFootprint() {
1611 size_t native_size = native_bytes_allocated_;
1612 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1613 size_t target_size = native_size / GetTargetHeapUtilization();
1614 if (target_size > native_size + max_free_) {
1615 target_size = native_size + max_free_;
1616 } else if (target_size < native_size + min_free_) {
1617 target_size = native_size + min_free_;
1618 }
1619 native_footprint_gc_watermark_ = target_size;
1620 native_footprint_limit_ = 2 * target_size - native_size;
1621}
1622
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001623void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001624 // We know what our utilization is at this moment.
1625 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001626 const size_t bytes_allocated = GetBytesAllocated();
1627 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001628 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001629
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001630 size_t target_size;
1631 if (gc_type != collector::kGcTypeSticky) {
1632 // Grow the heap for non sticky GC.
1633 target_size = bytes_allocated / GetTargetHeapUtilization();
1634 if (target_size > bytes_allocated + max_free_) {
1635 target_size = bytes_allocated + max_free_;
1636 } else if (target_size < bytes_allocated + min_free_) {
1637 target_size = bytes_allocated + min_free_;
1638 }
1639 next_gc_type_ = collector::kGcTypeSticky;
1640 } else {
1641 // Based on how close the current heap size is to the target size, decide
1642 // whether or not to do a partial or sticky GC next.
1643 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1644 next_gc_type_ = collector::kGcTypeSticky;
1645 } else {
1646 next_gc_type_ = collector::kGcTypePartial;
1647 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001648
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001649 // If we have freed enough memory, shrink the heap back down.
1650 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1651 target_size = bytes_allocated + max_free_;
1652 } else {
1653 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1654 }
1655 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001656 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001657
Ian Rogers1d54e732013-05-02 21:10:01 -07001658 // Calculate when to perform the next ConcurrentGC.
1659 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001660 // Calculate the estimated GC duration.
1661 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1662 // Estimate how many remaining bytes we will have when we need to start the next GC.
1663 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001664 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1665 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1666 // A never going to happen situation that from the estimated allocation rate we will exceed
1667 // the applications entire footprint with the given estimated allocation rate. Schedule
1668 // another GC straight away.
1669 concurrent_start_bytes_ = bytes_allocated;
1670 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001671 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1672 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1673 // right away.
1674 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001675 }
1676 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1677 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1678 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001679
1680 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001681}
1682
jeffhaoc1160702011-10-27 15:48:45 -07001683void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001684 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001685 alloc_space_->ClearGrowthLimit();
1686}
1687
Elliott Hughesadb460d2011-10-05 17:02:34 -07001688void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001689 MemberOffset reference_queue_offset,
1690 MemberOffset reference_queueNext_offset,
1691 MemberOffset reference_pendingNext_offset,
1692 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001693 reference_referent_offset_ = reference_referent_offset;
1694 reference_queue_offset_ = reference_queue_offset;
1695 reference_queueNext_offset_ = reference_queueNext_offset;
1696 reference_pendingNext_offset_ = reference_pendingNext_offset;
1697 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1698 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1699 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1700 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1701 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1702 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1703}
1704
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001705mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001706 DCHECK(reference != NULL);
1707 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001708 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001709}
1710
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001711void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001712 DCHECK(reference != NULL);
1713 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1714 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1715}
1716
1717// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001718bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001719 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001720 const mirror::Object* queue =
1721 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1722 const mirror::Object* queue_next =
1723 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001724 return (queue != NULL) && (queue_next == NULL);
1725}
1726
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001727void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001728 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001729 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1730 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001731 EnqueuePendingReference(ref, cleared_reference_list);
1732}
1733
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001734void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001735 DCHECK(ref != NULL);
1736 DCHECK(list != NULL);
1737
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001738 // TODO: Remove this lock, use atomic stacks for storing references.
1739 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001740 if (*list == NULL) {
1741 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1742 *list = ref;
1743 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001744 mirror::Object* head =
1745 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001746 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1747 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1748 }
1749}
1750
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001751mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001752 DCHECK(list != NULL);
1753 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001754 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1755 false);
1756 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001757
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001758 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1759 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001760 if (*list == head) {
1761 ref = *list;
1762 *list = NULL;
1763 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001764 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1765 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001766 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1767 ref = head;
1768 }
1769 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1770 return ref;
1771}
1772
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001773void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001774 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001775 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001776 ArgArray arg_array(NULL, 0);
1777 arg_array.Append(reinterpret_cast<uint32_t>(object));
1778 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001779 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001780}
1781
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001782void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001783 DCHECK(cleared != NULL);
1784 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001785 // When a runtime isn't started there are no reference queues to care about so ignore.
1786 if (LIKELY(Runtime::Current()->IsStarted())) {
1787 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001788 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001789 ArgArray arg_array(NULL, 0);
1790 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1791 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001792 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001793 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001794 *cleared = NULL;
1795 }
1796}
1797
Ian Rogers1f539342012-10-03 21:09:42 -07001798void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001799 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001800 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001801 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001802 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001803 !runtime->IsConcurrentGcEnabled()) {
1804 return;
1805 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001806 {
1807 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1808 if (runtime->IsShuttingDown()) {
1809 return;
1810 }
1811 }
1812 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001813 return;
1814 }
1815
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001816 // We already have a request pending, no reason to start more until we update
1817 // concurrent_start_bytes_.
1818 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1819
Ian Rogers120f1c72012-09-28 17:17:10 -07001820 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001821 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1822 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001823 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1824 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001825 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001826}
1827
Ian Rogers81d425b2012-09-27 16:03:43 -07001828void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001829 {
1830 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001831 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001832 return;
1833 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001834 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001835
Mathieu Chartier65db8802012-11-20 12:36:46 -08001836 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001837 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001838 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001839 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001840}
1841
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001842void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001843 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1844 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1845 // a space it will hold its lock and can become a cause of jank.
1846 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1847 // forking.
1848
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001849 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1850 // because that only marks object heads, so a large array looks like lots of empty space. We
1851 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1852 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1853 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1854 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001855 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001856 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001857 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1858 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001859 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1860 // heap trim occurred in the last two seconds.
1861 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001862 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001863
1864 Thread* self = Thread::Current();
1865 {
1866 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1867 Runtime* runtime = Runtime::Current();
1868 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1869 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1870 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1871 // as we don't hold the lock while requesting the trim).
1872 return;
1873 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001874 }
Ian Rogers48931882013-01-22 14:35:16 -08001875
1876 SchedPolicy policy;
1877 get_sched_policy(self->GetTid(), &policy);
1878 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1879 // Don't trim the heap if we are a foreground or audio app.
1880 return;
1881 }
1882
Ian Rogers1d54e732013-05-02 21:10:01 -07001883 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001884 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001885 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1886 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001887 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1888 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001889 CHECK(!env->ExceptionCheck());
1890}
1891
Ian Rogers48931882013-01-22 14:35:16 -08001892size_t Heap::Trim() {
1893 // Handle a requested heap trim on a thread outside of the main GC thread.
1894 return alloc_space_->Trim();
1895}
1896
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001897bool Heap::IsGCRequestPending() const {
1898 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
1899}
1900
1901void Heap::RegisterNativeAllocation(int bytes) {
1902 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001903 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001904 Thread* self = Thread::Current();
1905 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
1906 // The second watermark is higher than the gc watermark. If you hit this it means you are
1907 // allocating native objects faster than the GC can keep up with.
1908 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1909 JNIEnv* env = self->GetJniEnv();
1910 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
1911 // point.
1912 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
1913 DCHECK(WellKnownClasses::java_lang_System != NULL);
1914 WellKnownClasses::java_lang_System_runFinalization =
1915 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
1916 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
1917 }
1918 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
1919 // Just finished a GC, attempt to run finalizers.
1920 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1921 WellKnownClasses::java_lang_System_runFinalization);
1922 CHECK(!env->ExceptionCheck());
1923 }
1924
1925 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
1926 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1927 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
1928 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1929 WellKnownClasses::java_lang_System_runFinalization);
1930 CHECK(!env->ExceptionCheck());
1931 }
1932 // We have just run finalizers, update the native watermark since it is very likely that
1933 // finalizers released native managed allocations.
1934 UpdateMaxNativeFootprint();
1935 } else {
1936 if (!IsGCRequestPending()) {
1937 RequestConcurrentGC(self);
1938 }
1939 }
1940 }
1941}
1942
1943void Heap::RegisterNativeFree(int bytes) {
1944 int expected_size, new_size;
1945 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001946 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001947 new_size = expected_size - bytes;
1948 if (new_size < 0) {
1949 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
1950 bytes, expected_size);
1951 break;
1952 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001953 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001954}
1955
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001956int64_t Heap::GetTotalMemory() const {
1957 int64_t ret = 0;
1958 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1959 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1960 space::ContinuousSpace* space = *it;
1961 if (space->IsImageSpace()) {
1962 // Currently don't include the image space.
1963 } else if (space->IsDlMallocSpace()) {
1964 // Zygote or alloc space
1965 ret += space->AsDlMallocSpace()->GetFootprint();
1966 }
1967 }
1968 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
1969 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
1970 space::DiscontinuousSpace* space = *it;
1971 if (space->IsLargeObjectSpace()) {
1972 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
1973 }
1974 }
1975 return ret;
1976}
1977
Ian Rogers1d54e732013-05-02 21:10:01 -07001978} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001979} // namespace art