blob: 668ff1db6b657a32ad6269228cf6f4ffd48601b6 [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>
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070024#include <valgrind.h>
Carl Shapiro58551df2011-07-24 03:09:51 -070025
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070027#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080028#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070029#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070030#include "gc/accounting/atomic_stack.h"
31#include "gc/accounting/card_table-inl.h"
32#include "gc/accounting/heap_bitmap-inl.h"
33#include "gc/accounting/mod_union_table-inl.h"
34#include "gc/accounting/space_bitmap-inl.h"
35#include "gc/collector/mark_sweep-inl.h"
36#include "gc/collector/partial_mark_sweep.h"
37#include "gc/collector/sticky_mark_sweep.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070038#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/image_space.h"
40#include "gc/space/large_object_space.h"
41#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070042#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080043#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/class-inl.h"
45#include "mirror/field-inl.h"
46#include "mirror/object.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080049#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080050#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070051#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070052#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070053#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070054#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070055#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
58namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070059namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070060
Ian Rogers1d54e732013-05-02 21:10:01 -070061// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080062static const uint64_t kSlowGcThreshold = MsToNs(100);
Mathieu Chartier82353312013-07-18 10:47:51 -070063// When to create a log message about a long pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080064static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier0418ae22013-07-31 13:35:46 -070065static const bool kGCALotMode = false;
66static const size_t kGcAlotInterval = KB;
Mathieu Chartier65db8802012-11-20 12:36:46 -080067static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070068// Minimum amount of remaining bytes before a concurrent GC is triggered.
69static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070070const double Heap::kDefaultTargetUtilization = 0.5;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070071// If true, measure the total allocation time.
72static const bool kMeasureAllocationTime = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070073
Mathieu Chartier0051be62012-10-12 17:47:11 -070074Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
75 double target_utilization, size_t capacity,
Mathieu Chartier63a54342013-07-23 13:17:59 -070076 const std::string& original_image_file_name, bool concurrent_gc, size_t num_gc_threads)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070077 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080078 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070079 concurrent_gc_(concurrent_gc),
Mathieu Chartier63a54342013-07-23 13:17:59 -070080 num_gc_threads_(num_gc_threads),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070081 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070082 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080083 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070084 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070085 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080086 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070087 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070088 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070089 native_footprint_gc_watermark_(initial_size),
90 native_footprint_limit_(2 * initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -070091 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
92 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -070093 total_bytes_freed_ever_(0),
94 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070095 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080096 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070097 native_bytes_allocated_(0),
Mathieu Chartier82353312013-07-18 10:47:51 -070098 process_state_(PROCESS_STATE_TOP),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -070099 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700100 verify_missing_card_marks_(false),
101 verify_system_weaks_(false),
102 verify_pre_gc_heap_(false),
103 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700104 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700105 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700106 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700107 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800108 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700109 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
110 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
111 * verification is enabled, we limit the size of allocation stacks to speed up their
112 * searching.
113 */
114 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
115 : (kDesiredHeapVerification > kNoHeapVerification) ? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800116 reference_referent_offset_(0),
117 reference_queue_offset_(0),
118 reference_queueNext_offset_(0),
119 reference_pendingNext_offset_(0),
120 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700121 min_free_(min_free),
122 max_free_(max_free),
123 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700124 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700125 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700126 verify_object_mode_(kHeapVerificationNotPermitted),
127 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800128 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800129 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700130 }
131
Ian Rogers1d54e732013-05-02 21:10:01 -0700132 live_bitmap_.reset(new accounting::HeapBitmap(this));
133 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700134
Ian Rogers30fab402012-01-23 15:43:46 -0800135 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700136 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800137 std::string image_file_name(original_image_file_name);
138 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700139 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
140 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700141 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800142 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
143 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800144 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
145 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700146 if (oat_file_end_addr > requested_alloc_space_begin) {
147 requested_alloc_space_begin =
148 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
149 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700150 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700151 }
152
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700153 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700154 initial_size,
155 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700156 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700157 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700158 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700159 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700160
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700161 // Allocate the large object space.
162 const bool kUseFreeListSpaceForLOS = false;
163 if (kUseFreeListSpaceForLOS) {
164 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
165 } else {
166 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
167 }
168 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
169 AddDiscontinuousSpace(large_object_space_);
170
Ian Rogers1d54e732013-05-02 21:10:01 -0700171 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
172 byte* heap_begin = continuous_spaces_.front()->Begin();
173 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
174 if (continuous_spaces_.back()->IsDlMallocSpace()) {
175 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700176 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700177
Ian Rogers30fab402012-01-23 15:43:46 -0800178 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700179 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700180 typedef std::vector<space::ContinuousSpace*>::iterator It;
181 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
182 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800183 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700184 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700185 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800186 }
187 }
188
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800189 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700190 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700191 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700192
Mathieu Chartier161a8e02013-08-01 19:12:52 -0700193 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
Ian Rogers1d54e732013-05-02 21:10:01 -0700194 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700195
Ian Rogers1d54e732013-05-02 21:10:01 -0700196 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700197 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700198
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700199 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700200 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700201
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800202 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700203 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700204 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
205 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
206 max_allocation_stack_size_));
207 live_stack_.reset(accounting::ObjectStack::Create("live stack",
208 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700209
Mathieu Chartier65db8802012-11-20 12:36:46 -0800210 // It's still too early to take a lock because there are no threads yet, but we can create locks
211 // now. We don't create it earlier to make it clear that you can't use locks during heap
212 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700213 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700214 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
215 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700216
Mathieu Chartier63a54342013-07-23 13:17:59 -0700217 // Create the reference queue lock, this is required so for parallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700218 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700219
Ian Rogers1d54e732013-05-02 21:10:01 -0700220 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800221 last_gc_size_ = GetBytesAllocated();
222
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800223 // Create our garbage collectors.
224 for (size_t i = 0; i < 2; ++i) {
225 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700226 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
227 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
228 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700229 }
230
Brian Carlstrom42748892013-07-18 18:04:08 -0700231 CHECK_NE(max_allowed_footprint_, 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800232 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800233 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700234 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700235}
236
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700237void Heap::CreateThreadPool() {
Mathieu Chartier63a54342013-07-23 13:17:59 -0700238 thread_pool_.reset(new ThreadPool(num_gc_threads_));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700239}
240
241void Heap::DeleteThreadPool() {
242 thread_pool_.reset(NULL);
243}
244
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700245// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700246struct ContinuousSpaceSorter {
Brian Carlstromdf629502013-07-17 22:39:56 -0700247 bool operator()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700248 return a->Begin() < b->Begin();
249 }
250};
251
Mathieu Chartier82353312013-07-18 10:47:51 -0700252void Heap::UpdateProcessState(ProcessState process_state) {
253 process_state_ = process_state;
254}
255
Ian Rogers1d54e732013-05-02 21:10:01 -0700256void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700257 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700258 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700259 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700260 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700261 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700262 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
263 continuous_spaces_.push_back(space);
264 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
265 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700266 }
267
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700268 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700269 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700270
271 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
272 // avoid redundant marking.
273 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700274 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
275 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
276 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700277 if (space->IsImageSpace()) {
278 DCHECK(!seen_zygote);
279 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700280 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700281 DCHECK(!seen_alloc);
282 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700283 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700284 seen_alloc = true;
285 }
286 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800287}
288
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700289void Heap::RegisterGCAllocation(size_t bytes) {
290 if (this != NULL) {
291 gc_memory_overhead_.fetch_add(bytes);
292 }
293}
294
295void Heap::RegisterGCDeAllocation(size_t bytes) {
296 if (this != NULL) {
297 gc_memory_overhead_.fetch_sub(bytes);
298 }
299}
300
Ian Rogers1d54e732013-05-02 21:10:01 -0700301void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
302 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
303 DCHECK(space != NULL);
304 DCHECK(space->GetLiveObjects() != NULL);
305 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
306 DCHECK(space->GetMarkObjects() != NULL);
307 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
308 discontinuous_spaces_.push_back(space);
309}
310
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700311void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700312 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700313 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700314 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800315
316 // Dump cumulative loggers for each GC type.
317 // TODO: C++0x
318 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700319 typedef std::vector<collector::MarkSweep*>::const_iterator It;
320 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800321 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700322 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800323 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800324 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700325 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800326 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700327 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800328 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
329 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
330 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700331 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
332 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
333 << collector->GetName() << " freed: " << freed_objects
334 << " objects with total size " << PrettySize(freed_bytes) << "\n"
335 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
336 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800337 total_duration += total_ns;
338 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700339 }
340 }
341 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700342 size_t total_objects_allocated = GetObjectsAllocatedEver();
343 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700344 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700345 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700346 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
347 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700348 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700349 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700350 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700351 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700352 os << "Total number of allocations: " << total_objects_allocated << "\n";
353 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700354 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700355 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
356 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
357 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700358 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700359 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
360 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700361 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700362}
363
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800364Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700365 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700366 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700367 }
368
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800369 STLDeleteElements(&mark_sweep_collectors_);
370
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700371 // If we don't reset then the mark stack complains in it's destructor.
372 allocation_stack_->Reset();
373 live_stack_->Reset();
374
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800375 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800376 // We can't take the heap lock here because there might be a daemon thread suspended with the
377 // heap lock held. We know though that no non-daemon threads are executing, and we know that
378 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
379 // 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 -0700380 STLDeleteElements(&continuous_spaces_);
381 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700383 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700384}
385
Ian Rogers1d54e732013-05-02 21:10:01 -0700386space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
387 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700388 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700389 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
390 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700391 if ((*it)->Contains(obj)) {
392 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700393 }
394 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700395 if (!fail_ok) {
396 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
397 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700398 return NULL;
399}
400
Ian Rogers1d54e732013-05-02 21:10:01 -0700401space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
402 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700403 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700404 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
405 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
406 if ((*it)->Contains(obj)) {
407 return *it;
408 }
409 }
410 if (!fail_ok) {
411 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
412 }
413 return NULL;
414}
415
416space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
417 space::Space* result = FindContinuousSpaceFromObject(obj, true);
418 if (result != NULL) {
419 return result;
420 }
421 return FindDiscontinuousSpaceFromObject(obj, true);
422}
423
424space::ImageSpace* Heap::GetImageSpace() const {
425 // TODO: C++0x auto
426 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
427 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700428 if ((*it)->IsImageSpace()) {
429 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700430 }
431 }
432 return NULL;
433}
434
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700435static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700436 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700437 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700438 size_t chunk_free_bytes = chunk_size - used_bytes;
439 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
440 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700441 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700442}
443
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800444mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
445 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700446 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
447 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800448 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700449
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800450 mirror::Object* obj = NULL;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700451 size_t bytes_allocated = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700452 uint64_t allocation_start = 0;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700453 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700454 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700455 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700456
457 // We need to have a zygote space or else our newly allocated large object can end up in the
458 // Zygote resulting in it being prematurely freed.
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700459 // We can only do this for primitive objects since large objects will not be within the card table
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700460 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers333cf1b2013-07-24 11:57:02 -0700461 bool large_object_allocation =
462 byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
463 if (UNLIKELY(large_object_allocation)) {
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700464 obj = Allocate(self, large_object_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700465 // Make sure that our large object didn't get placed anywhere within the space interval or else
466 // it breaks the immune range.
467 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700468 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
469 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700470 } else {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700471 obj = Allocate(self, alloc_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700472 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700473 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700474 }
475
Mathieu Chartier037813d2012-08-23 16:44:59 -0700476 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700478
479 // Record allocation after since we want to use the atomic add for the atomic fence to guard
480 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700481 RecordAllocation(bytes_allocated, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700482
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700483 if (Dbg::IsAllocTrackingEnabled()) {
484 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700485 }
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700486 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800488 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700489 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700490 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700491 if (kDesiredHeapVerification > kNoHeapVerification) {
492 VerifyObject(obj);
493 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700494
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700495 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700496 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700497 }
498
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499 return obj;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700500 } else {
501 std::ostringstream oss;
502 int64_t total_bytes_free = GetFreeMemory();
503 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
504 << " free bytes";
505 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
506 if (!large_object_allocation && total_bytes_free >= byte_count) {
507 size_t max_contiguous_allocation = 0;
508 // TODO: C++0x auto
509 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
510 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
511 space::ContinuousSpace* space = *it;
512 if (space->IsDlMallocSpace()) {
513 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
514 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800515 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700516 oss << "; failed due to fragmentation (largest possible contiguous allocation "
517 << max_contiguous_allocation << " bytes)";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700518 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700519 self->ThrowOutOfMemoryError(oss.str().c_str());
520 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700521 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700522}
523
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800524bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700525 // Note: we deliberately don't take the lock here, and mustn't test anything that would
526 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700527 if (obj == NULL) {
528 return true;
529 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700530 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700531 return false;
532 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700533 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700534}
535
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800536bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700537 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700538 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700539 return false;
540 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700541 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
542 space::DiscontinuousSpace* d_space = NULL;
543 if (c_space != NULL) {
544 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700545 return true;
546 }
547 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700548 d_space = FindDiscontinuousSpaceFromObject(obj, true);
549 if (d_space != NULL) {
550 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700551 return true;
552 }
553 }
554 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700555 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Ian Rogers1d54e732013-05-02 21:10:01 -0700556 for (size_t i = 0; i < 5; ++i) {
557 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
558 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
559 return true;
560 }
561 NanoSleep(MsToNs(10));
562 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700563 // We need to check the bitmaps again since there is a race where we mark something as live and
564 // then clear the stack containing it.
565 if (c_space != NULL) {
566 if (c_space->GetLiveBitmap()->Test(obj)) {
567 return true;
568 }
569 } else {
570 d_space = FindDiscontinuousSpaceFromObject(obj, true);
571 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
572 return true;
573 }
574 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700575 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700576}
577
Ian Rogers04d7aa92013-03-16 14:29:17 -0700578void Heap::VerifyObjectImpl(const mirror::Object* obj) {
579 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700580 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700581 return;
582 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700583 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700584}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700585
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700586void Heap::DumpSpaces() {
587 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700588 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
589 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
590 space::ContinuousSpace* space = *it;
591 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
592 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700593 LOG(INFO) << space << " " << *space << "\n"
594 << live_bitmap << " " << *live_bitmap << "\n"
595 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700596 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700597 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
598 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
599 space::DiscontinuousSpace* space = *it;
600 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700601 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700602}
603
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800604void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800605 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700606 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700607 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800608 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
609 return;
610 }
611 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
612 mirror::Object::ClassOffset().Int32Value();
613 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
614 if (UNLIKELY(c == NULL)) {
615 LOG(FATAL) << "Null class in object: " << obj;
616 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
617 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
618 }
619 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
620 // Note: we don't use the accessors here as they have internal sanity checks
621 // that we don't want to run
622 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
623 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
624 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
625 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
626 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700627
Ian Rogers62d6c772013-02-27 08:32:07 -0800628 if (verify_object_mode_ != kVerifyAllFast) {
629 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
630 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700631 if (!IsLiveObjectLocked(obj)) {
632 DumpSpaces();
633 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700634 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700635 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700636 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
637 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700638 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700639}
640
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800641void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700642 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700643 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700644}
645
646void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700647 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700648 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649}
650
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700651inline void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700652 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700653 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700654 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700655
656 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700657 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700658 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700659 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700660
661 // TODO: Update these atomically.
662 RuntimeStats* global_stats = Runtime::Current()->GetStats();
663 ++global_stats->allocated_objects;
664 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700665 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700666
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700667 // This is safe to do since the GC will never free objects which are neither in the allocation
668 // stack or the live bitmap.
669 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700670 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700671 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700672}
673
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700674void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700675 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700676 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700677
678 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700679 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700680 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700681 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700682
683 // TODO: Do this concurrently.
684 RuntimeStats* global_stats = Runtime::Current()->GetStats();
685 global_stats->freed_objects += freed_objects;
686 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700687 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700688}
689
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700690inline bool Heap::IsOutOfMemoryOnAllocation(size_t alloc_size) {
691 return num_bytes_allocated_ + alloc_size > growth_limit_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700692}
693
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700694inline mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
695 bool grow, size_t* bytes_allocated) {
696 if (IsOutOfMemoryOnAllocation(alloc_size)) {
697 return NULL;
698 }
699 return space->Alloc(self, alloc_size, bytes_allocated);
700}
701
702// DlMallocSpace-specific version.
703inline mirror::Object* Heap::TryToAllocate(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
704 bool grow, size_t* bytes_allocated) {
705 if (IsOutOfMemoryOnAllocation(alloc_size)) {
706 return NULL;
707 }
708 if (!running_on_valgrind_) {
709 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
710 } else {
711 return space->Alloc(self, alloc_size, bytes_allocated);
712 }
713}
714
715template <class T>
716inline mirror::Object* Heap::Allocate(Thread* self, T* space, size_t alloc_size, size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700717 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
718 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700719 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700720 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700721
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700722 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700723 if (ptr != NULL) {
724 return ptr;
725 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700726 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
727}
728
729mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space, size_t alloc_size,
730 size_t* bytes_allocated) {
731 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700732
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700733 // The allocation failed. If the GC is running, block until it completes, and then retry the
734 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700735 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
736 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700737 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700738 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700739 if (ptr != NULL) {
740 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700741 }
742 }
743
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700744 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700745 for (size_t i = static_cast<size_t>(last_gc) + 1;
746 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700747 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700748 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700749 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700750 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700751 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700752 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
753 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700754 break;
755 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700756 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700757 run_gc = have_zygote_space_;
758 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700759 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700760 run_gc = true;
761 break;
762 default:
763 break;
764 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700765
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700766 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700767 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700768 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800769 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700770 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700771
772 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700773 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700774 if (ptr != NULL) {
775 return ptr;
776 }
777 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700778 }
779
780 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700781 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700782 ptr = TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700783 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700784 return ptr;
785 }
786
Elliott Hughes81ff3182012-03-23 20:35:56 -0700787 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
788 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
789 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700790
Elliott Hughes418dfe72011-10-06 18:56:27 -0700791 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700792 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
793 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700794
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700795 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700796 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700797 return TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700798}
799
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700800void Heap::SetTargetHeapUtilization(float target) {
801 DCHECK_GT(target, 0.0f); // asserted in Java code
802 DCHECK_LT(target, 1.0f);
803 target_utilization_ = target;
804}
805
Ian Rogers1d54e732013-05-02 21:10:01 -0700806size_t Heap::GetObjectsAllocated() const {
807 size_t total = 0;
808 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
809 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
810 space::ContinuousSpace* space = *it;
811 if (space->IsDlMallocSpace()) {
812 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700813 }
814 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700815 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
816 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
817 space::DiscontinuousSpace* space = *it;
818 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
819 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700820 return total;
821}
822
Ian Rogers1d54e732013-05-02 21:10:01 -0700823size_t Heap::GetObjectsAllocatedEver() const {
824 size_t total = 0;
825 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
826 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
827 space::ContinuousSpace* space = *it;
828 if (space->IsDlMallocSpace()) {
829 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700830 }
831 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700832 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
833 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
834 space::DiscontinuousSpace* space = *it;
835 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
836 }
837 return total;
838}
839
840size_t Heap::GetBytesAllocatedEver() const {
841 size_t total = 0;
842 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
843 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
844 space::ContinuousSpace* space = *it;
845 if (space->IsDlMallocSpace()) {
846 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
847 }
848 }
849 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
850 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
851 space::DiscontinuousSpace* space = *it;
852 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
853 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700854 return total;
855}
856
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700857class InstanceCounter {
858 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800859 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700860 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800861 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700862 }
863
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800864 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800865 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800866 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800867 if (use_is_assignable_from_) {
868 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
869 ++counts_[i];
870 }
871 } else {
872 if (instance_class == classes_[i]) {
873 ++counts_[i];
874 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700875 }
876 }
877 }
878
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700879 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800880 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800881 bool use_is_assignable_from_;
882 uint64_t* const counts_;
883
884 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700885};
886
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800887void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800888 uint64_t* counts) {
889 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
890 // is empty, so the live bitmap is the only place we need to look.
891 Thread* self = Thread::Current();
892 self->TransitionFromRunnableToSuspended(kNative);
893 CollectGarbage(false);
894 self->TransitionFromSuspendedToRunnable();
895
896 InstanceCounter counter(classes, use_is_assignable_from, counts);
897 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700898 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700899}
900
Elliott Hughes3b78c942013-01-15 17:35:41 -0800901class InstanceCollector {
902 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800903 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800904 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
905 : class_(c), max_count_(max_count), instances_(instances) {
906 }
907
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800908 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
909 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800910 if (instance_class == class_) {
911 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800912 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800913 }
914 }
915 }
916
917 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800918 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800919 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800920 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800921
922 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
923};
924
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800925void Heap::GetInstances(mirror::Class* c, int32_t max_count,
926 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800927 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
928 // is empty, so the live bitmap is the only place we need to look.
929 Thread* self = Thread::Current();
930 self->TransitionFromRunnableToSuspended(kNative);
931 CollectGarbage(false);
932 self->TransitionFromSuspendedToRunnable();
933
934 InstanceCollector collector(c, max_count, instances);
935 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
936 GetLiveBitmap()->Visit(collector);
937}
938
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800939class ReferringObjectsFinder {
940 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800941 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
942 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800943 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
944 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
945 }
946
947 // For bitmap Visit.
948 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
949 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800950 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -0700951 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800952 }
953
954 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -0700955 void operator()(const mirror::Object* referrer, const mirror::Object* object,
956 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800957 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800958 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800959 }
960 }
961
962 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800963 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800964 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800965 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800966
967 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
968};
969
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800970void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
971 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800972 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
973 // is empty, so the live bitmap is the only place we need to look.
974 Thread* self = Thread::Current();
975 self->TransitionFromRunnableToSuspended(kNative);
976 CollectGarbage(false);
977 self->TransitionFromSuspendedToRunnable();
978
979 ReferringObjectsFinder finder(o, max_count, referring_objects);
980 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
981 GetLiveBitmap()->Visit(finder);
982}
983
Ian Rogers30fab402012-01-23 15:43:46 -0800984void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700985 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
986 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700987 Thread* self = Thread::Current();
988 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700989 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700990}
991
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700992void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700993 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800994 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
995 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -0700996 Thread* self = Thread::Current();
997 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700998
999 // Try to see if we have any Zygote spaces.
1000 if (have_zygote_space_) {
1001 return;
1002 }
1003
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001004 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1005
1006 {
1007 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001008 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001009 FlushAllocStack();
1010 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001011
Ian Rogers1d54e732013-05-02 21:10:01 -07001012 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1013 // of the remaining available heap memory.
1014 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001015 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -07001016 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001017
Ian Rogers1d54e732013-05-02 21:10:01 -07001018 // Change the GC retention policy of the zygote space to only collect when full.
1019 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1020 AddContinuousSpace(alloc_space_);
1021 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001022
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001023 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001024 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001025 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1026 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1027 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001028 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001029 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001030}
1031
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001032void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001033 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1034 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001035 allocation_stack_->Reset();
1036}
1037
Ian Rogers1d54e732013-05-02 21:10:01 -07001038void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1039 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001040 mirror::Object** limit = stack->End();
1041 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1042 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001043 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001044 if (LIKELY(bitmap->HasAddress(obj))) {
1045 bitmap->Set(obj);
1046 } else {
1047 large_objects->Set(obj);
1048 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001049 }
1050}
1051
Ian Rogers1d54e732013-05-02 21:10:01 -07001052collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1053 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001054 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001055
1056 switch (gc_cause) {
1057 case kGcCauseForAlloc:
1058 ATRACE_BEGIN("GC (alloc)");
1059 break;
1060 case kGcCauseBackground:
1061 ATRACE_BEGIN("GC (background)");
1062 break;
1063 case kGcCauseExplicit:
1064 ATRACE_BEGIN("GC (explicit)");
1065 break;
1066 }
1067
Mathieu Chartier65db8802012-11-20 12:36:46 -08001068 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001069 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001070
Ian Rogers120f1c72012-09-28 17:17:10 -07001071 if (self->IsHandlingStackOverflow()) {
1072 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1073 }
1074
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001075 // Ensure there is only one GC at a time.
1076 bool start_collect = false;
1077 while (!start_collect) {
1078 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001079 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001080 if (!is_gc_running_) {
1081 is_gc_running_ = true;
1082 start_collect = true;
1083 }
1084 }
1085 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001086 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001087 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1088 // Not doing at the moment to ensure soft references are cleared.
1089 }
1090 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001091 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001093 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1094 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1095 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1096 }
1097
Ian Rogers1d54e732013-05-02 21:10:01 -07001098 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001099 uint64_t gc_start_size = GetBytesAllocated();
1100 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001101 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001102 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1103 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001104 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001105 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001106 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001107 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1108 }
1109
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001110 if (gc_type == collector::kGcTypeSticky &&
1111 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1112 gc_type = collector::kGcTypePartial;
1113 }
1114
Ian Rogers1d54e732013-05-02 21:10:01 -07001115 DCHECK_LT(gc_type, collector::kGcTypeMax);
1116 DCHECK_NE(gc_type, collector::kGcTypeNone);
1117 collector::MarkSweep* collector = NULL;
1118 typedef std::vector<collector::MarkSweep*>::iterator It;
1119 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1120 it != end; ++it) {
1121 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001122 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1123 collector = cur_collector;
1124 break;
1125 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001126 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001127 CHECK(collector != NULL)
1128 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1129 << " and type=" << gc_type;
1130 collector->clear_soft_references_ = clear_soft_references;
1131 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001132 total_objects_freed_ever_ += collector->GetFreedObjects();
1133 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001134
Ian Rogers1d54e732013-05-02 21:10:01 -07001135 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001136 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1137 bool was_slow = duration > kSlowGcThreshold ||
1138 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1139 for (size_t i = 0; i < pauses.size(); ++i) {
1140 if (pauses[i] > kLongGcPauseThreshold) {
1141 was_slow = true;
1142 }
1143 }
1144
1145 if (was_slow) {
1146 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001147 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001148 const size_t total_memory = GetTotalMemory();
1149 std::ostringstream pause_string;
1150 for (size_t i = 0; i < pauses.size(); ++i) {
1151 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1152 << ((i != pauses.size() - 1) ? ", " : "");
1153 }
1154 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001155 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1156 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1157 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1158 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001159 if (VLOG_IS_ON(heap)) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001160 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001161 }
1162 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001163
Ian Rogers15bf2d32012-08-28 17:33:04 -07001164 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001165 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001166 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001167 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001168 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001169 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001170 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001171
Ian Rogers15bf2d32012-08-28 17:33:04 -07001172 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001173 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001174 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001175 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001176}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001177
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001178void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
Ian Rogers1d54e732013-05-02 21:10:01 -07001179 collector::GcType gc_type) {
1180 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001181 // 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 -07001182 // cards.
1183 return;
1184 }
1185
1186 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001187 if (gc_type == collector::kGcTypePartial) {
1188 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001189 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001190
Ian Rogers1d54e732013-05-02 21:10:01 -07001191 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001192 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001193 }
1194
1195 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001196 timings.NewSplit("UpdateModUnionTable");
1197 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001198
1199 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001200 timings.NewSplit("MarkImageToAllocSpaceReferences");
1201 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001202}
1203
Ian Rogers1d54e732013-05-02 21:10:01 -07001204static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001205 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001206 if (root == obj) {
1207 LOG(INFO) << "Object " << obj << " is a root";
1208 }
1209}
1210
1211class ScanVisitor {
1212 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001213 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001214 LOG(INFO) << "Would have rescanned object " << obj;
1215 }
1216};
1217
Ian Rogers1d54e732013-05-02 21:10:01 -07001218// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001219class VerifyReferenceVisitor {
1220 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001221 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001222 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001223 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001224
1225 bool Failed() const {
1226 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001227 }
1228
1229 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001230 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001231 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1232 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001233 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001234 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001235 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1236 accounting::CardTable* card_table = heap_->GetCardTable();
1237 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1238 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001239
Ian Rogers1d54e732013-05-02 21:10:01 -07001240 if (obj != NULL) {
1241 byte* card_addr = card_table->CardFromAddr(obj);
1242 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1243 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1244 << "\nObj type " << PrettyTypeOf(obj)
1245 << "\nRef type " << PrettyTypeOf(ref);
1246 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1247 void* cover_begin = card_table->AddrFromCard(card_addr);
1248 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1249 accounting::CardTable::kCardSize);
1250 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1251 << "-" << cover_end;
1252 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001253
Ian Rogers1d54e732013-05-02 21:10:01 -07001254 // Print out how the object is live.
1255 if (bitmap != NULL && bitmap->Test(obj)) {
1256 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1257 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001258 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001259 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1260 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001261 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001262 LOG(ERROR) << "Object " << obj << " found in live stack";
1263 }
1264 // Attempt to see if the card table missed the reference.
1265 ScanVisitor scan_visitor;
1266 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1267 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001268 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001269
1270 // Search to see if any of the roots reference our object.
1271 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1272 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1273
1274 // Search to see if any of the roots reference our reference.
1275 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1276 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1277 } else {
1278 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001279 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001280 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001281 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001282 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001283 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001284 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001285 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001286 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1287 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1288 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001289 }
1290 }
1291
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001292 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001293 return heap_->IsLiveObjectLocked(obj);
1294 }
1295
1296 static void VerifyRoots(const mirror::Object* root, void* arg) {
1297 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1298 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001299 }
1300
1301 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001302 Heap* const heap_;
1303 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001304};
1305
Ian Rogers1d54e732013-05-02 21:10:01 -07001306// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001307class VerifyObjectVisitor {
1308 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001309 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001310
Brian Carlstromdf629502013-07-17 22:39:56 -07001311 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001312 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001313 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1314 // be live or else how did we find it in the live bitmap?
1315 VerifyReferenceVisitor visitor(heap_);
1316 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1317 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001318 }
1319
1320 bool Failed() const {
1321 return failed_;
1322 }
1323
1324 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001325 Heap* const heap_;
1326 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001327};
1328
1329// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001330bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001331 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001332 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001333 allocation_stack_->Sort();
1334 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001335 // Perform the verification.
1336 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001337 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001338 GetLiveBitmap()->Visit(visitor);
1339 // We don't want to verify the objects in the allocation stack since they themselves may be
1340 // pointing to dead objects if they are not reachable.
1341 if (visitor.Failed()) {
1342 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001343 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001344 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001345 return true;
1346}
1347
1348class VerifyReferenceCardVisitor {
1349 public:
1350 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1351 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1352 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001353 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001354 }
1355
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001356 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1357 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001358 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1359 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001360 // Filter out class references since changing an object's class does not mark the card as dirty.
1361 // Also handles large objects, since the only reference they hold is a class reference.
1362 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001363 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001364 // If the object is not dirty and it is referencing something in the live stack other than
1365 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001366 if (!card_table->AddrIsInCardTable(obj)) {
1367 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1368 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001369 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001370 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1371 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001372 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001373 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1374 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001375 LOG(ERROR) << "Object " << obj << " found in live stack";
1376 }
1377 if (heap_->GetLiveBitmap()->Test(obj)) {
1378 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1379 }
1380 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1381 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1382
1383 // Print which field of the object is dead.
1384 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001385 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001386 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001387 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1388 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001389 CHECK(fields != NULL);
1390 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001391 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001392 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1393 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1394 << PrettyField(cur);
1395 break;
1396 }
1397 }
1398 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001399 const mirror::ObjectArray<mirror::Object>* object_array =
1400 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001401 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1402 if (object_array->Get(i) == ref) {
1403 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1404 }
1405 }
1406 }
1407
1408 *failed_ = true;
1409 }
1410 }
1411 }
1412 }
1413
1414 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001415 Heap* const heap_;
1416 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001417};
1418
1419class VerifyLiveStackReferences {
1420 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001421 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001422 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001423 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001424
Brian Carlstromdf629502013-07-17 22:39:56 -07001425 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001426 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1427 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001428 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001429 }
1430
1431 bool Failed() const {
1432 return failed_;
1433 }
1434
1435 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001436 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001437 bool failed_;
1438};
1439
1440bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001441 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001442
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001443 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001444 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001445 VerifyLiveStackReferences visitor(this);
1446 GetLiveBitmap()->Visit(visitor);
1447
1448 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001449 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001450 visitor(*it);
1451 }
1452
1453 if (visitor.Failed()) {
1454 DumpSpaces();
1455 return false;
1456 }
1457 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001458}
1459
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001460void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001461 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001462
1463 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001464 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001465 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001466 }
1467}
1468
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001469void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001470 // Clear cards and keep track of cards cleared in the mod-union table.
1471 typedef std::vector<space::ContinuousSpace*>::iterator It;
1472 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1473 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001474 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001475 timings.NewSplit("ModUnionClearCards");
1476 image_mod_union_table_->ClearCards(space);
1477 } else if (space->IsZygoteSpace()) {
1478 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001479 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001480 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001481 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1482 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001483 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001484 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001485 }
1486 }
1487}
1488
Ian Rogers1d54e732013-05-02 21:10:01 -07001489void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001490 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1491 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001492
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001493 if (verify_pre_gc_heap_) {
1494 thread_list->SuspendAll();
1495 {
1496 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1497 if (!VerifyHeapReferences()) {
1498 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1499 }
1500 }
1501 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001502 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001503
1504 // Check that all objects which reference things in the live stack are on dirty cards.
1505 if (verify_missing_card_marks_) {
1506 thread_list->SuspendAll();
1507 {
1508 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1509 SwapStacks();
1510 // Sort the live stack so that we can quickly binary search it later.
1511 if (!VerifyMissingCardMarks()) {
1512 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1513 }
1514 SwapStacks();
1515 }
1516 thread_list->ResumeAll();
1517 }
1518
1519 if (verify_mod_union_table_) {
1520 thread_list->SuspendAll();
1521 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1522 zygote_mod_union_table_->Update();
1523 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001524 image_mod_union_table_->Update();
1525 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001526 thread_list->ResumeAll();
1527 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001528}
1529
Ian Rogers1d54e732013-05-02 21:10:01 -07001530void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001531 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001533 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1534 // reachable objects.
1535 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001536 Thread* self = Thread::Current();
1537 CHECK_NE(self->GetState(), kRunnable);
1538 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001539 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001540 {
1541 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1542 // Swapping bound bitmaps does nothing.
1543 gc->SwapBitmaps();
1544 if (!VerifyHeapReferences()) {
1545 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1546 }
1547 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001548 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001549 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001550 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001551 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001552}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001553
Ian Rogers1d54e732013-05-02 21:10:01 -07001554void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001555 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001556
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001557 if (verify_system_weaks_) {
1558 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001559 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001560 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001561 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001562}
1563
Ian Rogers1d54e732013-05-02 21:10:01 -07001564collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1565 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001566 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001567 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001568 bool do_wait;
1569 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001570 {
1571 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001572 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001573 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001574 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001575 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001576 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001577 // We must wait, change thread state then sleep on gc_complete_cond_;
1578 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1579 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001580 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001581 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001582 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001584 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001585 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001586 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001587 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001588 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001589 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1590 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001591 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001592 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001593 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001594 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001595}
1596
Elliott Hughesc967f782012-04-16 10:23:15 -07001597void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001598 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001599 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001600 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001601}
1602
1603size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001604 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001605}
1606
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001607void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001608 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001609 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001610 << PrettySize(GetMaxMemory());
1611 max_allowed_footprint = GetMaxMemory();
1612 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001613 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001614}
1615
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001616void Heap::UpdateMaxNativeFootprint() {
1617 size_t native_size = native_bytes_allocated_;
1618 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1619 size_t target_size = native_size / GetTargetHeapUtilization();
1620 if (target_size > native_size + max_free_) {
1621 target_size = native_size + max_free_;
1622 } else if (target_size < native_size + min_free_) {
1623 target_size = native_size + min_free_;
1624 }
1625 native_footprint_gc_watermark_ = target_size;
1626 native_footprint_limit_ = 2 * target_size - native_size;
1627}
1628
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001629void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001630 // We know what our utilization is at this moment.
1631 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001632 const size_t bytes_allocated = GetBytesAllocated();
1633 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001634 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001635
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001636 size_t target_size;
1637 if (gc_type != collector::kGcTypeSticky) {
1638 // Grow the heap for non sticky GC.
1639 target_size = bytes_allocated / GetTargetHeapUtilization();
1640 if (target_size > bytes_allocated + max_free_) {
1641 target_size = bytes_allocated + max_free_;
1642 } else if (target_size < bytes_allocated + min_free_) {
1643 target_size = bytes_allocated + min_free_;
1644 }
1645 next_gc_type_ = collector::kGcTypeSticky;
1646 } else {
1647 // Based on how close the current heap size is to the target size, decide
1648 // whether or not to do a partial or sticky GC next.
1649 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1650 next_gc_type_ = collector::kGcTypeSticky;
1651 } else {
1652 next_gc_type_ = collector::kGcTypePartial;
1653 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001654
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001655 // If we have freed enough memory, shrink the heap back down.
1656 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1657 target_size = bytes_allocated + max_free_;
1658 } else {
1659 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1660 }
1661 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001662 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001663
Ian Rogers1d54e732013-05-02 21:10:01 -07001664 // Calculate when to perform the next ConcurrentGC.
1665 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001666 // Calculate the estimated GC duration.
1667 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1668 // Estimate how many remaining bytes we will have when we need to start the next GC.
1669 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001670 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1671 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1672 // A never going to happen situation that from the estimated allocation rate we will exceed
1673 // the applications entire footprint with the given estimated allocation rate. Schedule
1674 // another GC straight away.
1675 concurrent_start_bytes_ = bytes_allocated;
1676 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001677 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1678 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1679 // right away.
1680 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001681 }
1682 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1683 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1684 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001685
1686 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001687}
1688
jeffhaoc1160702011-10-27 15:48:45 -07001689void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001690 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001691 alloc_space_->ClearGrowthLimit();
1692}
1693
Elliott Hughesadb460d2011-10-05 17:02:34 -07001694void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001695 MemberOffset reference_queue_offset,
1696 MemberOffset reference_queueNext_offset,
1697 MemberOffset reference_pendingNext_offset,
1698 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001699 reference_referent_offset_ = reference_referent_offset;
1700 reference_queue_offset_ = reference_queue_offset;
1701 reference_queueNext_offset_ = reference_queueNext_offset;
1702 reference_pendingNext_offset_ = reference_pendingNext_offset;
1703 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1704 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1705 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1706 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1707 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1708 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1709}
1710
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001711mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001712 DCHECK(reference != NULL);
1713 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001714 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001715}
1716
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001717void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001718 DCHECK(reference != NULL);
1719 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1720 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1721}
1722
1723// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001724bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001725 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001726 const mirror::Object* queue =
1727 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1728 const mirror::Object* queue_next =
1729 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001730 return (queue != NULL) && (queue_next == NULL);
1731}
1732
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001733void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001734 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001735 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1736 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001737 EnqueuePendingReference(ref, cleared_reference_list);
1738}
1739
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001740void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001741 DCHECK(ref != NULL);
1742 DCHECK(list != NULL);
1743
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001744 // TODO: Remove this lock, use atomic stacks for storing references.
1745 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001746 if (*list == NULL) {
1747 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1748 *list = ref;
1749 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001750 mirror::Object* head =
1751 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001752 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1753 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1754 }
1755}
1756
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001757mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001758 DCHECK(list != NULL);
1759 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001760 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1761 false);
1762 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001763
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001764 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1765 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001766 if (*list == head) {
1767 ref = *list;
1768 *list = NULL;
1769 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001770 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1771 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001772 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1773 ref = head;
1774 }
1775 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1776 return ref;
1777}
1778
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001779void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001780 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001781 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001782 ArgArray arg_array(NULL, 0);
1783 arg_array.Append(reinterpret_cast<uint32_t>(object));
1784 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001785 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001786}
1787
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001788void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001789 DCHECK(cleared != NULL);
1790 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001791 // When a runtime isn't started there are no reference queues to care about so ignore.
1792 if (LIKELY(Runtime::Current()->IsStarted())) {
1793 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001794 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001795 ArgArray arg_array(NULL, 0);
1796 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1797 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001798 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001799 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001800 *cleared = NULL;
1801 }
1802}
1803
Ian Rogers1f539342012-10-03 21:09:42 -07001804void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001805 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001806 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001807 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001808 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001809 !runtime->IsConcurrentGcEnabled()) {
1810 return;
1811 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001812 {
1813 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1814 if (runtime->IsShuttingDown()) {
1815 return;
1816 }
1817 }
1818 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001819 return;
1820 }
1821
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001822 // We already have a request pending, no reason to start more until we update
1823 // concurrent_start_bytes_.
1824 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1825
Ian Rogers120f1c72012-09-28 17:17:10 -07001826 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001827 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1828 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001829 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1830 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001831 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001832}
1833
Ian Rogers81d425b2012-09-27 16:03:43 -07001834void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001835 {
1836 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001837 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001838 return;
1839 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001840 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001841
Mathieu Chartier65db8802012-11-20 12:36:46 -08001842 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001843 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001844 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001845 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001846}
1847
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001848void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001849 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1850 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1851 // a space it will hold its lock and can become a cause of jank.
1852 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1853 // forking.
1854
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001855 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1856 // because that only marks object heads, so a large array looks like lots of empty space. We
1857 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1858 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1859 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1860 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001861 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001862 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001863 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1864 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001865 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1866 // heap trim occurred in the last two seconds.
1867 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001868 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001869
1870 Thread* self = Thread::Current();
1871 {
1872 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1873 Runtime* runtime = Runtime::Current();
1874 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1875 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1876 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1877 // as we don't hold the lock while requesting the trim).
1878 return;
1879 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001880 }
Ian Rogers48931882013-01-22 14:35:16 -08001881
1882 SchedPolicy policy;
1883 get_sched_policy(self->GetTid(), &policy);
1884 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1885 // Don't trim the heap if we are a foreground or audio app.
1886 return;
1887 }
1888
Ian Rogers1d54e732013-05-02 21:10:01 -07001889 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001890 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001891 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1892 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001893 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1894 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001895 CHECK(!env->ExceptionCheck());
1896}
1897
Ian Rogers48931882013-01-22 14:35:16 -08001898size_t Heap::Trim() {
1899 // Handle a requested heap trim on a thread outside of the main GC thread.
1900 return alloc_space_->Trim();
1901}
1902
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001903bool Heap::IsGCRequestPending() const {
1904 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
1905}
1906
1907void Heap::RegisterNativeAllocation(int bytes) {
1908 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001909 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001910 Thread* self = Thread::Current();
1911 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
1912 // The second watermark is higher than the gc watermark. If you hit this it means you are
1913 // allocating native objects faster than the GC can keep up with.
1914 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1915 JNIEnv* env = self->GetJniEnv();
1916 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
1917 // point.
1918 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
1919 DCHECK(WellKnownClasses::java_lang_System != NULL);
1920 WellKnownClasses::java_lang_System_runFinalization =
1921 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
1922 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
1923 }
1924 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
1925 // Just finished a GC, attempt to run finalizers.
1926 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1927 WellKnownClasses::java_lang_System_runFinalization);
1928 CHECK(!env->ExceptionCheck());
1929 }
1930
1931 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
1932 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1933 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
1934 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1935 WellKnownClasses::java_lang_System_runFinalization);
1936 CHECK(!env->ExceptionCheck());
1937 }
1938 // We have just run finalizers, update the native watermark since it is very likely that
1939 // finalizers released native managed allocations.
1940 UpdateMaxNativeFootprint();
1941 } else {
1942 if (!IsGCRequestPending()) {
1943 RequestConcurrentGC(self);
1944 }
1945 }
1946 }
1947}
1948
1949void Heap::RegisterNativeFree(int bytes) {
1950 int expected_size, new_size;
1951 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001952 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001953 new_size = expected_size - bytes;
1954 if (new_size < 0) {
1955 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
1956 bytes, expected_size);
1957 break;
1958 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001959 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001960}
1961
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001962int64_t Heap::GetTotalMemory() const {
1963 int64_t ret = 0;
1964 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1965 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1966 space::ContinuousSpace* space = *it;
1967 if (space->IsImageSpace()) {
1968 // Currently don't include the image space.
1969 } else if (space->IsDlMallocSpace()) {
1970 // Zygote or alloc space
1971 ret += space->AsDlMallocSpace()->GetFootprint();
1972 }
1973 }
1974 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
1975 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
1976 space::DiscontinuousSpace* space = *it;
1977 if (space->IsLargeObjectSpace()) {
1978 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
1979 }
1980 }
1981 return ret;
1982}
1983
Ian Rogers1d54e732013-05-02 21:10:01 -07001984} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001985} // namespace art