blob: 74f7b1b75573a7a21566c857e5e7baa474551b04 [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
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700153 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700154 const bool kUseFreeListSpaceForLOS = false;
155 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700156 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700157 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700158 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700159 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700160 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
161 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700162
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700163 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700164 initial_size,
165 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700166 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700167 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700168 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700169 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700170
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 Chartiere0f0cb32012-08-28 11:26:00 -0700451 size_t size = 0;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700452 size_t bytes_allocated;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700453 uint64_t allocation_start = 0;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700454 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700455 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700456 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700457
458 // We need to have a zygote space or else our newly allocated large object can end up in the
459 // Zygote resulting in it being prematurely freed.
460 // We can only do this for primive objects since large objects will not be within the card table
461 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers333cf1b2013-07-24 11:57:02 -0700462 bool large_object_allocation =
463 byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
464 if (UNLIKELY(large_object_allocation)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700465 size = RoundUp(byte_count, kPageSize);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700466 obj = Allocate(self, large_object_space_, size, &bytes_allocated);
467 DCHECK(obj == NULL || size == bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700468 // Make sure that our large object didn't get placed anywhere within the space interval or else
469 // it breaks the immune range.
470 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700471 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
472 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700473 } else {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700474 obj = Allocate(self, alloc_space_, byte_count, &bytes_allocated);
475 DCHECK(obj == NULL || size <= bytes_allocated);
476 size = bytes_allocated;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700477
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700478 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700479 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700480 }
481
Mathieu Chartier037813d2012-08-23 16:44:59 -0700482 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700483 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700484
485 // Record allocation after since we want to use the atomic add for the atomic fence to guard
486 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700487 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700488
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489 if (Dbg::IsAllocTrackingEnabled()) {
490 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700491 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700492 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700493 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800494 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700495 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700497 if (kDesiredHeapVerification > kNoHeapVerification) {
498 VerifyObject(obj);
499 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700501 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700502 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700503 }
504
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700505 return obj;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700506 } else {
507 std::ostringstream oss;
508 int64_t total_bytes_free = GetFreeMemory();
509 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
510 << " free bytes";
511 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
512 if (!large_object_allocation && total_bytes_free >= byte_count) {
513 size_t max_contiguous_allocation = 0;
514 // TODO: C++0x auto
515 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
516 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
517 space::ContinuousSpace* space = *it;
518 if (space->IsDlMallocSpace()) {
519 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
520 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800521 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700522 oss << "; failed due to fragmentation (largest possible contiguous allocation "
523 << max_contiguous_allocation << " bytes)";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700524 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700525 self->ThrowOutOfMemoryError(oss.str().c_str());
526 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700527 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700528}
529
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800530bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700531 // Note: we deliberately don't take the lock here, and mustn't test anything that would
532 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700533 if (obj == NULL) {
534 return true;
535 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700536 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700537 return false;
538 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700539 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700540}
541
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800542bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700543 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700544 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700545 return false;
546 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700547 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
548 space::DiscontinuousSpace* d_space = NULL;
549 if (c_space != NULL) {
550 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700551 return true;
552 }
553 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700554 d_space = FindDiscontinuousSpaceFromObject(obj, true);
555 if (d_space != NULL) {
556 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700557 return true;
558 }
559 }
560 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700561 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Ian Rogers1d54e732013-05-02 21:10:01 -0700562 for (size_t i = 0; i < 5; ++i) {
563 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
564 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
565 return true;
566 }
567 NanoSleep(MsToNs(10));
568 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700569 // We need to check the bitmaps again since there is a race where we mark something as live and
570 // then clear the stack containing it.
571 if (c_space != NULL) {
572 if (c_space->GetLiveBitmap()->Test(obj)) {
573 return true;
574 }
575 } else {
576 d_space = FindDiscontinuousSpaceFromObject(obj, true);
577 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
578 return true;
579 }
580 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700581 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700582}
583
Ian Rogers04d7aa92013-03-16 14:29:17 -0700584void Heap::VerifyObjectImpl(const mirror::Object* obj) {
585 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700586 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700587 return;
588 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700589 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700590}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700591
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700592void Heap::DumpSpaces() {
593 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700594 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
595 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
596 space::ContinuousSpace* space = *it;
597 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
598 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700599 LOG(INFO) << space << " " << *space << "\n"
600 << live_bitmap << " " << *live_bitmap << "\n"
601 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700602 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700603 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
604 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
605 space::DiscontinuousSpace* space = *it;
606 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700607 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700608}
609
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800610void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800611 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700612 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700613 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800614 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
615 return;
616 }
617 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
618 mirror::Object::ClassOffset().Int32Value();
619 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
620 if (UNLIKELY(c == NULL)) {
621 LOG(FATAL) << "Null class in object: " << obj;
622 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
623 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
624 }
625 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
626 // Note: we don't use the accessors here as they have internal sanity checks
627 // that we don't want to run
628 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
629 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
630 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
631 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
632 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700633
Ian Rogers62d6c772013-02-27 08:32:07 -0800634 if (verify_object_mode_ != kVerifyAllFast) {
635 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
636 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700637 if (!IsLiveObjectLocked(obj)) {
638 DumpSpaces();
639 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700640 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700641 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700642 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
643 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700644 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700645}
646
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800647void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700648 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700649 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700650}
651
652void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700653 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700654 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700655}
656
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700657inline void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700658 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700659 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700660 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700661
662 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700663 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700664 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700665 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700666
667 // TODO: Update these atomically.
668 RuntimeStats* global_stats = Runtime::Current()->GetStats();
669 ++global_stats->allocated_objects;
670 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700671 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700672
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700673 // This is safe to do since the GC will never free objects which are neither in the allocation
674 // stack or the live bitmap.
675 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700676 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700677 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700678}
679
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700680void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700681 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700682 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700683
684 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700685 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700686 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700687 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700688
689 // TODO: Do this concurrently.
690 RuntimeStats* global_stats = Runtime::Current()->GetStats();
691 global_stats->freed_objects += freed_objects;
692 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700693 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700694}
695
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700696inline bool Heap::IsOutOfMemoryOnAllocation(size_t alloc_size) {
697 return num_bytes_allocated_ + alloc_size > growth_limit_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700698}
699
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700700inline mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
701 bool grow, size_t* bytes_allocated) {
702 if (IsOutOfMemoryOnAllocation(alloc_size)) {
703 return NULL;
704 }
705 return space->Alloc(self, alloc_size, bytes_allocated);
706}
707
708// DlMallocSpace-specific version.
709inline mirror::Object* Heap::TryToAllocate(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
710 bool grow, size_t* bytes_allocated) {
711 if (IsOutOfMemoryOnAllocation(alloc_size)) {
712 return NULL;
713 }
714 if (!running_on_valgrind_) {
715 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
716 } else {
717 return space->Alloc(self, alloc_size, bytes_allocated);
718 }
719}
720
721template <class T>
722inline mirror::Object* Heap::Allocate(Thread* self, T* space, size_t alloc_size, size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700723 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
724 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700725 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700726 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700727
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700728 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700729 if (ptr != NULL) {
730 return ptr;
731 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700732 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
733}
734
735mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space, size_t alloc_size,
736 size_t* bytes_allocated) {
737 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700738
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700739 // The allocation failed. If the GC is running, block until it completes, and then retry the
740 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700741 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
742 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700743 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700744 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700745 if (ptr != NULL) {
746 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700747 }
748 }
749
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700750 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700751 for (size_t i = static_cast<size_t>(last_gc) + 1;
752 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700753 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700754 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700755 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700756 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700757 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700758 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
759 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700760 break;
761 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700762 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700763 run_gc = have_zygote_space_;
764 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700765 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700766 run_gc = true;
767 break;
768 default:
769 break;
770 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700771
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700772 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700773 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700774 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800775 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700776 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700777
778 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700779 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700780 if (ptr != NULL) {
781 return ptr;
782 }
783 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700784 }
785
786 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700787 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700788 ptr = TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700789 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700790 return ptr;
791 }
792
Elliott Hughes81ff3182012-03-23 20:35:56 -0700793 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
794 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
795 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700796
Elliott Hughes418dfe72011-10-06 18:56:27 -0700797 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700798 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
799 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700800
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700801 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700802 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700803 return TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700804}
805
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700806void Heap::SetTargetHeapUtilization(float target) {
807 DCHECK_GT(target, 0.0f); // asserted in Java code
808 DCHECK_LT(target, 1.0f);
809 target_utilization_ = target;
810}
811
Ian Rogers1d54e732013-05-02 21:10:01 -0700812size_t Heap::GetObjectsAllocated() const {
813 size_t total = 0;
814 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
815 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
816 space::ContinuousSpace* space = *it;
817 if (space->IsDlMallocSpace()) {
818 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700819 }
820 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700821 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
822 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
823 space::DiscontinuousSpace* space = *it;
824 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
825 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700826 return total;
827}
828
Ian Rogers1d54e732013-05-02 21:10:01 -0700829size_t Heap::GetObjectsAllocatedEver() const {
830 size_t total = 0;
831 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
832 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
833 space::ContinuousSpace* space = *it;
834 if (space->IsDlMallocSpace()) {
835 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700836 }
837 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700838 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
839 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
840 space::DiscontinuousSpace* space = *it;
841 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
842 }
843 return total;
844}
845
846size_t Heap::GetBytesAllocatedEver() const {
847 size_t total = 0;
848 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
849 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
850 space::ContinuousSpace* space = *it;
851 if (space->IsDlMallocSpace()) {
852 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
853 }
854 }
855 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
856 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
857 space::DiscontinuousSpace* space = *it;
858 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
859 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700860 return total;
861}
862
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700863class InstanceCounter {
864 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800865 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700866 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800867 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700868 }
869
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800870 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800871 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800872 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800873 if (use_is_assignable_from_) {
874 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
875 ++counts_[i];
876 }
877 } else {
878 if (instance_class == classes_[i]) {
879 ++counts_[i];
880 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700881 }
882 }
883 }
884
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700885 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800886 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800887 bool use_is_assignable_from_;
888 uint64_t* const counts_;
889
890 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700891};
892
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800893void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800894 uint64_t* counts) {
895 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
896 // is empty, so the live bitmap is the only place we need to look.
897 Thread* self = Thread::Current();
898 self->TransitionFromRunnableToSuspended(kNative);
899 CollectGarbage(false);
900 self->TransitionFromSuspendedToRunnable();
901
902 InstanceCounter counter(classes, use_is_assignable_from, counts);
903 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700904 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700905}
906
Elliott Hughes3b78c942013-01-15 17:35:41 -0800907class InstanceCollector {
908 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800909 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800910 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
911 : class_(c), max_count_(max_count), instances_(instances) {
912 }
913
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800914 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
915 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800916 if (instance_class == class_) {
917 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800918 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800919 }
920 }
921 }
922
923 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800924 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800925 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800926 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800927
928 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
929};
930
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800931void Heap::GetInstances(mirror::Class* c, int32_t max_count,
932 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800933 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
934 // is empty, so the live bitmap is the only place we need to look.
935 Thread* self = Thread::Current();
936 self->TransitionFromRunnableToSuspended(kNative);
937 CollectGarbage(false);
938 self->TransitionFromSuspendedToRunnable();
939
940 InstanceCollector collector(c, max_count, instances);
941 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
942 GetLiveBitmap()->Visit(collector);
943}
944
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800945class ReferringObjectsFinder {
946 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800947 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
948 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800949 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
950 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
951 }
952
953 // For bitmap Visit.
954 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
955 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800956 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -0700957 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800958 }
959
960 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -0700961 void operator()(const mirror::Object* referrer, const mirror::Object* object,
962 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800963 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800964 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800965 }
966 }
967
968 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800969 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800970 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800971 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800972
973 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
974};
975
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800976void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
977 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800978 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
979 // is empty, so the live bitmap is the only place we need to look.
980 Thread* self = Thread::Current();
981 self->TransitionFromRunnableToSuspended(kNative);
982 CollectGarbage(false);
983 self->TransitionFromSuspendedToRunnable();
984
985 ReferringObjectsFinder finder(o, max_count, referring_objects);
986 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
987 GetLiveBitmap()->Visit(finder);
988}
989
Ian Rogers30fab402012-01-23 15:43:46 -0800990void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700991 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
992 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700993 Thread* self = Thread::Current();
994 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700995 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700996}
997
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700998void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700999 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001000 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1001 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001002 Thread* self = Thread::Current();
1003 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001004
1005 // Try to see if we have any Zygote spaces.
1006 if (have_zygote_space_) {
1007 return;
1008 }
1009
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001010 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1011
1012 {
1013 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001014 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001015 FlushAllocStack();
1016 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001017
Ian Rogers1d54e732013-05-02 21:10:01 -07001018 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1019 // of the remaining available heap memory.
1020 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001021 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -07001022 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001023
Ian Rogers1d54e732013-05-02 21:10:01 -07001024 // Change the GC retention policy of the zygote space to only collect when full.
1025 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1026 AddContinuousSpace(alloc_space_);
1027 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001028
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001029 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001030 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001031 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1032 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1033 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001034 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001035 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001036}
1037
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001039 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1040 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001041 allocation_stack_->Reset();
1042}
1043
Ian Rogers1d54e732013-05-02 21:10:01 -07001044void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1045 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001046 mirror::Object** limit = stack->End();
1047 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1048 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001049 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001050 if (LIKELY(bitmap->HasAddress(obj))) {
1051 bitmap->Set(obj);
1052 } else {
1053 large_objects->Set(obj);
1054 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001055 }
1056}
1057
Ian Rogers1d54e732013-05-02 21:10:01 -07001058collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1059 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001060 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001061
1062 switch (gc_cause) {
1063 case kGcCauseForAlloc:
1064 ATRACE_BEGIN("GC (alloc)");
1065 break;
1066 case kGcCauseBackground:
1067 ATRACE_BEGIN("GC (background)");
1068 break;
1069 case kGcCauseExplicit:
1070 ATRACE_BEGIN("GC (explicit)");
1071 break;
1072 }
1073
Mathieu Chartier65db8802012-11-20 12:36:46 -08001074 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001075 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001076
Ian Rogers120f1c72012-09-28 17:17:10 -07001077 if (self->IsHandlingStackOverflow()) {
1078 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1079 }
1080
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001081 // Ensure there is only one GC at a time.
1082 bool start_collect = false;
1083 while (!start_collect) {
1084 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001085 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001086 if (!is_gc_running_) {
1087 is_gc_running_ = true;
1088 start_collect = true;
1089 }
1090 }
1091 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001092 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001093 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1094 // Not doing at the moment to ensure soft references are cleared.
1095 }
1096 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001097 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001098
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001099 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1100 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1101 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1102 }
1103
Ian Rogers1d54e732013-05-02 21:10:01 -07001104 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001105 uint64_t gc_start_size = GetBytesAllocated();
1106 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001107 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001108 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1109 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001110 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001111 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001112 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001113 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1114 }
1115
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001116 if (gc_type == collector::kGcTypeSticky &&
1117 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1118 gc_type = collector::kGcTypePartial;
1119 }
1120
Ian Rogers1d54e732013-05-02 21:10:01 -07001121 DCHECK_LT(gc_type, collector::kGcTypeMax);
1122 DCHECK_NE(gc_type, collector::kGcTypeNone);
1123 collector::MarkSweep* collector = NULL;
1124 typedef std::vector<collector::MarkSweep*>::iterator It;
1125 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1126 it != end; ++it) {
1127 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001128 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1129 collector = cur_collector;
1130 break;
1131 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001132 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001133 CHECK(collector != NULL)
1134 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1135 << " and type=" << gc_type;
1136 collector->clear_soft_references_ = clear_soft_references;
1137 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001138 total_objects_freed_ever_ += collector->GetFreedObjects();
1139 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001140
Ian Rogers1d54e732013-05-02 21:10:01 -07001141 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001142 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1143 bool was_slow = duration > kSlowGcThreshold ||
1144 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1145 for (size_t i = 0; i < pauses.size(); ++i) {
1146 if (pauses[i] > kLongGcPauseThreshold) {
1147 was_slow = true;
1148 }
1149 }
1150
1151 if (was_slow) {
1152 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001153 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001154 const size_t total_memory = GetTotalMemory();
1155 std::ostringstream pause_string;
1156 for (size_t i = 0; i < pauses.size(); ++i) {
1157 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1158 << ((i != pauses.size() - 1) ? ", " : "");
1159 }
1160 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001161 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1162 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1163 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1164 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001165 if (VLOG_IS_ON(heap)) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001166 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001167 }
1168 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001169
Ian Rogers15bf2d32012-08-28 17:33:04 -07001170 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001171 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001172 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001173 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001174 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001175 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001176 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001177
Ian Rogers15bf2d32012-08-28 17:33:04 -07001178 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001179 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001180 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001181 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001182}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001183
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001184void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
Ian Rogers1d54e732013-05-02 21:10:01 -07001185 collector::GcType gc_type) {
1186 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001187 // 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 -07001188 // cards.
1189 return;
1190 }
1191
1192 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001193 if (gc_type == collector::kGcTypePartial) {
1194 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001195 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001196
Ian Rogers1d54e732013-05-02 21:10:01 -07001197 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001198 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001199 }
1200
1201 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001202 timings.NewSplit("UpdateModUnionTable");
1203 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001204
1205 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001206 timings.NewSplit("MarkImageToAllocSpaceReferences");
1207 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001208}
1209
Ian Rogers1d54e732013-05-02 21:10:01 -07001210static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001211 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001212 if (root == obj) {
1213 LOG(INFO) << "Object " << obj << " is a root";
1214 }
1215}
1216
1217class ScanVisitor {
1218 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001219 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001220 LOG(INFO) << "Would have rescanned object " << obj;
1221 }
1222};
1223
Ian Rogers1d54e732013-05-02 21:10:01 -07001224// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001225class VerifyReferenceVisitor {
1226 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001227 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001228 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001229 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001230
1231 bool Failed() const {
1232 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001233 }
1234
1235 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001236 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001237 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1238 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001239 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001241 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1242 accounting::CardTable* card_table = heap_->GetCardTable();
1243 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1244 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001245
Ian Rogers1d54e732013-05-02 21:10:01 -07001246 if (obj != NULL) {
1247 byte* card_addr = card_table->CardFromAddr(obj);
1248 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1249 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1250 << "\nObj type " << PrettyTypeOf(obj)
1251 << "\nRef type " << PrettyTypeOf(ref);
1252 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1253 void* cover_begin = card_table->AddrFromCard(card_addr);
1254 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1255 accounting::CardTable::kCardSize);
1256 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1257 << "-" << cover_end;
1258 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001259
Ian Rogers1d54e732013-05-02 21:10:01 -07001260 // Print out how the object is live.
1261 if (bitmap != NULL && bitmap->Test(obj)) {
1262 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1263 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001264 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001265 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1266 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001267 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001268 LOG(ERROR) << "Object " << obj << " found in live stack";
1269 }
1270 // Attempt to see if the card table missed the reference.
1271 ScanVisitor scan_visitor;
1272 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1273 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001274 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001275
1276 // Search to see if any of the roots reference our object.
1277 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1278 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1279
1280 // Search to see if any of the roots reference our reference.
1281 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1282 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1283 } else {
1284 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001285 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001286 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001287 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001288 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001289 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001290 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001291 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001292 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1293 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1294 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001295 }
1296 }
1297
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001298 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001299 return heap_->IsLiveObjectLocked(obj);
1300 }
1301
1302 static void VerifyRoots(const mirror::Object* root, void* arg) {
1303 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1304 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001305 }
1306
1307 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001308 Heap* const heap_;
1309 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001310};
1311
Ian Rogers1d54e732013-05-02 21:10:01 -07001312// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001313class VerifyObjectVisitor {
1314 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001315 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001316
Brian Carlstromdf629502013-07-17 22:39:56 -07001317 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001318 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001319 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1320 // be live or else how did we find it in the live bitmap?
1321 VerifyReferenceVisitor visitor(heap_);
1322 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1323 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001324 }
1325
1326 bool Failed() const {
1327 return failed_;
1328 }
1329
1330 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001331 Heap* const heap_;
1332 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001333};
1334
1335// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001336bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001337 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001338 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001339 allocation_stack_->Sort();
1340 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001341 // Perform the verification.
1342 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001343 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001344 GetLiveBitmap()->Visit(visitor);
1345 // We don't want to verify the objects in the allocation stack since they themselves may be
1346 // pointing to dead objects if they are not reachable.
1347 if (visitor.Failed()) {
1348 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001349 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001350 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001351 return true;
1352}
1353
1354class VerifyReferenceCardVisitor {
1355 public:
1356 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1357 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1358 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001359 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001360 }
1361
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001362 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1363 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001364 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1365 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001366 // Filter out class references since changing an object's class does not mark the card as dirty.
1367 // Also handles large objects, since the only reference they hold is a class reference.
1368 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001369 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001370 // If the object is not dirty and it is referencing something in the live stack other than
1371 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001372 if (!card_table->AddrIsInCardTable(obj)) {
1373 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1374 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001375 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001376 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1377 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001378 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001379 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1380 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001381 LOG(ERROR) << "Object " << obj << " found in live stack";
1382 }
1383 if (heap_->GetLiveBitmap()->Test(obj)) {
1384 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1385 }
1386 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1387 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1388
1389 // Print which field of the object is dead.
1390 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001391 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001392 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001393 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1394 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001395 CHECK(fields != NULL);
1396 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001397 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001398 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1399 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1400 << PrettyField(cur);
1401 break;
1402 }
1403 }
1404 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001405 const mirror::ObjectArray<mirror::Object>* object_array =
1406 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001407 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1408 if (object_array->Get(i) == ref) {
1409 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1410 }
1411 }
1412 }
1413
1414 *failed_ = true;
1415 }
1416 }
1417 }
1418 }
1419
1420 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001421 Heap* const heap_;
1422 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001423};
1424
1425class VerifyLiveStackReferences {
1426 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001427 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001428 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001429 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001430
Brian Carlstromdf629502013-07-17 22:39:56 -07001431 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001432 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1433 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001434 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001435 }
1436
1437 bool Failed() const {
1438 return failed_;
1439 }
1440
1441 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001442 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001443 bool failed_;
1444};
1445
1446bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001447 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001448
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001449 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001450 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001451 VerifyLiveStackReferences visitor(this);
1452 GetLiveBitmap()->Visit(visitor);
1453
1454 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001455 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001456 visitor(*it);
1457 }
1458
1459 if (visitor.Failed()) {
1460 DumpSpaces();
1461 return false;
1462 }
1463 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001464}
1465
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001466void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001467 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001468
1469 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001470 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001471 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001472 }
1473}
1474
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001475void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001476 // Clear cards and keep track of cards cleared in the mod-union table.
1477 typedef std::vector<space::ContinuousSpace*>::iterator It;
1478 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1479 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001480 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001481 timings.NewSplit("ModUnionClearCards");
1482 image_mod_union_table_->ClearCards(space);
1483 } else if (space->IsZygoteSpace()) {
1484 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001485 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001486 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001487 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1488 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001489 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001490 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001491 }
1492 }
1493}
1494
Ian Rogers1d54e732013-05-02 21:10:01 -07001495void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001496 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1497 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001498
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001499 if (verify_pre_gc_heap_) {
1500 thread_list->SuspendAll();
1501 {
1502 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1503 if (!VerifyHeapReferences()) {
1504 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1505 }
1506 }
1507 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001508 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001509
1510 // Check that all objects which reference things in the live stack are on dirty cards.
1511 if (verify_missing_card_marks_) {
1512 thread_list->SuspendAll();
1513 {
1514 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1515 SwapStacks();
1516 // Sort the live stack so that we can quickly binary search it later.
1517 if (!VerifyMissingCardMarks()) {
1518 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1519 }
1520 SwapStacks();
1521 }
1522 thread_list->ResumeAll();
1523 }
1524
1525 if (verify_mod_union_table_) {
1526 thread_list->SuspendAll();
1527 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1528 zygote_mod_union_table_->Update();
1529 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001530 image_mod_union_table_->Update();
1531 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001532 thread_list->ResumeAll();
1533 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001534}
1535
Ian Rogers1d54e732013-05-02 21:10:01 -07001536void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001537 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001538
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001539 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1540 // reachable objects.
1541 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001542 Thread* self = Thread::Current();
1543 CHECK_NE(self->GetState(), kRunnable);
1544 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001546 {
1547 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1548 // Swapping bound bitmaps does nothing.
1549 gc->SwapBitmaps();
1550 if (!VerifyHeapReferences()) {
1551 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1552 }
1553 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001554 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001555 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001556 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001558}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001559
Ian Rogers1d54e732013-05-02 21:10:01 -07001560void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001561 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001562
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001563 if (verify_system_weaks_) {
1564 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001565 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001566 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001567 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001568}
1569
Ian Rogers1d54e732013-05-02 21:10:01 -07001570collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1571 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001572 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001573 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001574 bool do_wait;
1575 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001576 {
1577 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001578 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001579 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001580 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001581 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001582 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001583 // We must wait, change thread state then sleep on gc_complete_cond_;
1584 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1585 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001586 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001587 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001588 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001589 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001590 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001591 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001592 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001593 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001594 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001595 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1596 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001597 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001598 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001599 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001600 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001601}
1602
Elliott Hughesc967f782012-04-16 10:23:15 -07001603void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001604 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001605 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001606 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001607}
1608
1609size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001610 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001611}
1612
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001613void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001614 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001615 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001616 << PrettySize(GetMaxMemory());
1617 max_allowed_footprint = GetMaxMemory();
1618 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001619 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001620}
1621
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001622void Heap::UpdateMaxNativeFootprint() {
1623 size_t native_size = native_bytes_allocated_;
1624 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1625 size_t target_size = native_size / GetTargetHeapUtilization();
1626 if (target_size > native_size + max_free_) {
1627 target_size = native_size + max_free_;
1628 } else if (target_size < native_size + min_free_) {
1629 target_size = native_size + min_free_;
1630 }
1631 native_footprint_gc_watermark_ = target_size;
1632 native_footprint_limit_ = 2 * target_size - native_size;
1633}
1634
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001635void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001636 // We know what our utilization is at this moment.
1637 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001638 const size_t bytes_allocated = GetBytesAllocated();
1639 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001640 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001641
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001642 size_t target_size;
1643 if (gc_type != collector::kGcTypeSticky) {
1644 // Grow the heap for non sticky GC.
1645 target_size = bytes_allocated / GetTargetHeapUtilization();
1646 if (target_size > bytes_allocated + max_free_) {
1647 target_size = bytes_allocated + max_free_;
1648 } else if (target_size < bytes_allocated + min_free_) {
1649 target_size = bytes_allocated + min_free_;
1650 }
1651 next_gc_type_ = collector::kGcTypeSticky;
1652 } else {
1653 // Based on how close the current heap size is to the target size, decide
1654 // whether or not to do a partial or sticky GC next.
1655 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1656 next_gc_type_ = collector::kGcTypeSticky;
1657 } else {
1658 next_gc_type_ = collector::kGcTypePartial;
1659 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001660
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001661 // If we have freed enough memory, shrink the heap back down.
1662 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1663 target_size = bytes_allocated + max_free_;
1664 } else {
1665 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1666 }
1667 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001668 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001669
Ian Rogers1d54e732013-05-02 21:10:01 -07001670 // Calculate when to perform the next ConcurrentGC.
1671 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001672 // Calculate the estimated GC duration.
1673 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1674 // Estimate how many remaining bytes we will have when we need to start the next GC.
1675 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001676 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1677 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1678 // A never going to happen situation that from the estimated allocation rate we will exceed
1679 // the applications entire footprint with the given estimated allocation rate. Schedule
1680 // another GC straight away.
1681 concurrent_start_bytes_ = bytes_allocated;
1682 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001683 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1684 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1685 // right away.
1686 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001687 }
1688 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1689 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1690 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001691
1692 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001693}
1694
jeffhaoc1160702011-10-27 15:48:45 -07001695void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001696 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001697 alloc_space_->ClearGrowthLimit();
1698}
1699
Elliott Hughesadb460d2011-10-05 17:02:34 -07001700void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001701 MemberOffset reference_queue_offset,
1702 MemberOffset reference_queueNext_offset,
1703 MemberOffset reference_pendingNext_offset,
1704 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001705 reference_referent_offset_ = reference_referent_offset;
1706 reference_queue_offset_ = reference_queue_offset;
1707 reference_queueNext_offset_ = reference_queueNext_offset;
1708 reference_pendingNext_offset_ = reference_pendingNext_offset;
1709 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1710 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1711 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1712 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1713 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1714 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1715}
1716
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001717mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001718 DCHECK(reference != NULL);
1719 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001720 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001721}
1722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001723void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001724 DCHECK(reference != NULL);
1725 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1726 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1727}
1728
1729// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001730bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001731 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001732 const mirror::Object* queue =
1733 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1734 const mirror::Object* queue_next =
1735 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001736 return (queue != NULL) && (queue_next == NULL);
1737}
1738
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001739void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001740 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001741 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1742 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001743 EnqueuePendingReference(ref, cleared_reference_list);
1744}
1745
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001746void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001747 DCHECK(ref != NULL);
1748 DCHECK(list != NULL);
1749
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001750 // TODO: Remove this lock, use atomic stacks for storing references.
1751 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001752 if (*list == NULL) {
1753 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1754 *list = ref;
1755 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001756 mirror::Object* head =
1757 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001758 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1759 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1760 }
1761}
1762
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001763mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001764 DCHECK(list != NULL);
1765 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001766 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1767 false);
1768 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001769
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001770 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1771 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001772 if (*list == head) {
1773 ref = *list;
1774 *list = NULL;
1775 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001776 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1777 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001778 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1779 ref = head;
1780 }
1781 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1782 return ref;
1783}
1784
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001785void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001786 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001787 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001788 ArgArray arg_array(NULL, 0);
1789 arg_array.Append(reinterpret_cast<uint32_t>(object));
1790 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001791 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001792}
1793
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001794void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001795 DCHECK(cleared != NULL);
1796 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001797 // When a runtime isn't started there are no reference queues to care about so ignore.
1798 if (LIKELY(Runtime::Current()->IsStarted())) {
1799 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001800 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001801 ArgArray arg_array(NULL, 0);
1802 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1803 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001804 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001805 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001806 *cleared = NULL;
1807 }
1808}
1809
Ian Rogers1f539342012-10-03 21:09:42 -07001810void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001811 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001812 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001813 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001814 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001815 !runtime->IsConcurrentGcEnabled()) {
1816 return;
1817 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001818 {
1819 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1820 if (runtime->IsShuttingDown()) {
1821 return;
1822 }
1823 }
1824 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001825 return;
1826 }
1827
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001828 // We already have a request pending, no reason to start more until we update
1829 // concurrent_start_bytes_.
1830 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1831
Ian Rogers120f1c72012-09-28 17:17:10 -07001832 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001833 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1834 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001835 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1836 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001837 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001838}
1839
Ian Rogers81d425b2012-09-27 16:03:43 -07001840void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001841 {
1842 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001843 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001844 return;
1845 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001846 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001847
Mathieu Chartier65db8802012-11-20 12:36:46 -08001848 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001849 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001850 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001851 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001852}
1853
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001854void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001855 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1856 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1857 // a space it will hold its lock and can become a cause of jank.
1858 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1859 // forking.
1860
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001861 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1862 // because that only marks object heads, so a large array looks like lots of empty space. We
1863 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1864 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1865 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1866 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001867 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001868 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001869 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1870 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001871 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1872 // heap trim occurred in the last two seconds.
1873 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001874 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001875
1876 Thread* self = Thread::Current();
1877 {
1878 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1879 Runtime* runtime = Runtime::Current();
1880 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1881 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1882 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1883 // as we don't hold the lock while requesting the trim).
1884 return;
1885 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001886 }
Ian Rogers48931882013-01-22 14:35:16 -08001887
1888 SchedPolicy policy;
1889 get_sched_policy(self->GetTid(), &policy);
1890 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1891 // Don't trim the heap if we are a foreground or audio app.
1892 return;
1893 }
1894
Ian Rogers1d54e732013-05-02 21:10:01 -07001895 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001896 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001897 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1898 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001899 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1900 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001901 CHECK(!env->ExceptionCheck());
1902}
1903
Ian Rogers48931882013-01-22 14:35:16 -08001904size_t Heap::Trim() {
1905 // Handle a requested heap trim on a thread outside of the main GC thread.
1906 return alloc_space_->Trim();
1907}
1908
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001909bool Heap::IsGCRequestPending() const {
1910 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
1911}
1912
1913void Heap::RegisterNativeAllocation(int bytes) {
1914 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001915 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001916 Thread* self = Thread::Current();
1917 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
1918 // The second watermark is higher than the gc watermark. If you hit this it means you are
1919 // allocating native objects faster than the GC can keep up with.
1920 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1921 JNIEnv* env = self->GetJniEnv();
1922 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
1923 // point.
1924 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
1925 DCHECK(WellKnownClasses::java_lang_System != NULL);
1926 WellKnownClasses::java_lang_System_runFinalization =
1927 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
1928 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
1929 }
1930 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
1931 // Just finished a GC, attempt to run finalizers.
1932 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1933 WellKnownClasses::java_lang_System_runFinalization);
1934 CHECK(!env->ExceptionCheck());
1935 }
1936
1937 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
1938 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1939 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
1940 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
1941 WellKnownClasses::java_lang_System_runFinalization);
1942 CHECK(!env->ExceptionCheck());
1943 }
1944 // We have just run finalizers, update the native watermark since it is very likely that
1945 // finalizers released native managed allocations.
1946 UpdateMaxNativeFootprint();
1947 } else {
1948 if (!IsGCRequestPending()) {
1949 RequestConcurrentGC(self);
1950 }
1951 }
1952 }
1953}
1954
1955void Heap::RegisterNativeFree(int bytes) {
1956 int expected_size, new_size;
1957 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001958 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001959 new_size = expected_size - bytes;
1960 if (new_size < 0) {
1961 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
1962 bytes, expected_size);
1963 break;
1964 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001965 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001966}
1967
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001968int64_t Heap::GetTotalMemory() const {
1969 int64_t ret = 0;
1970 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1971 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1972 space::ContinuousSpace* space = *it;
1973 if (space->IsImageSpace()) {
1974 // Currently don't include the image space.
1975 } else if (space->IsDlMallocSpace()) {
1976 // Zygote or alloc space
1977 ret += space->AsDlMallocSpace()->GetFootprint();
1978 }
1979 }
1980 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
1981 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
1982 space::DiscontinuousSpace* space = *it;
1983 if (space->IsLargeObjectSpace()) {
1984 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
1985 }
1986 }
1987 return ret;
1988}
1989
Ian Rogers1d54e732013-05-02 21:10:01 -07001990} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001991} // namespace art