blob: c31e3e982b21c45dc6d069c57aebcbd7028d4c9a [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"
Mathieu Chartier590fee92013-09-13 13:46:47 -070033#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070034#include "gc/accounting/mod_union_table-inl.h"
35#include "gc/accounting/space_bitmap-inl.h"
36#include "gc/collector/mark_sweep-inl.h"
37#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070038#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070040#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070041#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070042#include "gc/space/image_space.h"
43#include "gc/space/large_object_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070044#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070045#include "gc/space/space-inl.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070046#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070047#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080048#include "invoke_arg_array_builder.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070049#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "mirror/object.h"
52#include "mirror/object-inl.h"
53#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080054#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080055#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070056#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070057#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070058#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070059#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070060#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070061#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070062
63namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070064namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070065
Mathieu Chartier720ef762013-08-17 14:46:54 -070066static constexpr bool kGCALotMode = false;
67static constexpr size_t kGcAlotInterval = KB;
68static constexpr bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070069// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070070static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070071
Mathieu Chartier0051be62012-10-12 17:47:11 -070072Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Ian Rogers8d31bbd2013-10-13 10:44:14 -070073 double target_utilization, size_t capacity, const std::string& image_file_name,
Mathieu Chartier2775ee42013-08-20 17:43:47 -070074 bool concurrent_gc, size_t parallel_gc_threads, size_t conc_gc_threads,
75 bool low_memory_mode, size_t long_pause_log_threshold, size_t long_gc_log_threshold,
76 bool ignore_max_footprint)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -080077 : non_moving_space_(nullptr),
Mathieu Chartier590fee92013-09-13 13:46:47 -070078 concurrent_gc_(!kMovingCollector && concurrent_gc),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070079 parallel_gc_threads_(parallel_gc_threads),
80 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070081 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070082 long_pause_log_threshold_(long_pause_log_threshold),
83 long_gc_log_threshold_(long_gc_log_threshold),
84 ignore_max_footprint_(ignore_max_footprint),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085 have_zygote_space_(false),
Mathieu Chartier39e32612013-11-12 16:28:05 -080086 soft_reference_queue_(this),
87 weak_reference_queue_(this),
88 finalizer_reference_queue_(this),
89 phantom_reference_queue_(this),
90 cleared_references_(this),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080091 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070092 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070093 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080094 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070095 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070096 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070097 native_footprint_gc_watermark_(initial_size),
98 native_footprint_limit_(2 * initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -070099 native_need_to_run_finalization_(false),
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700100 activity_thread_class_(NULL),
101 application_thread_class_(NULL),
102 activity_thread_(NULL),
103 application_thread_(NULL),
104 last_process_state_id_(NULL),
105 // Initially care about pauses in case we never get notified of process states, or if the JNI
106 // code becomes broken.
107 care_about_pause_times_(true),
Mathieu Chartier720ef762013-08-17 14:46:54 -0700108 concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
109 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700110 total_bytes_freed_ever_(0),
111 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800112 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700113 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700114 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700115 verify_missing_card_marks_(false),
116 verify_system_weaks_(false),
117 verify_pre_gc_heap_(false),
118 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700119 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700120 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700121 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700122 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800123 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700124 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
125 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
126 * verification is enabled, we limit the size of allocation stacks to speed up their
127 * searching.
128 */
129 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
Mathieu Chartier590fee92013-09-13 13:46:47 -0700130 : (kDesiredHeapVerification > kVerifyAllFast) ? KB : MB),
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800131 current_allocator_(kMovingCollector ? kAllocatorTypeBumpPointer : kAllocatorTypeFreeList),
132 current_non_moving_allocator_(kAllocatorTypeFreeList),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700133 bump_pointer_space_(nullptr),
134 temp_space_(nullptr),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800135 reference_referent_offset_(0),
136 reference_queue_offset_(0),
137 reference_queueNext_offset_(0),
138 reference_pendingNext_offset_(0),
139 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700140 min_free_(min_free),
141 max_free_(max_free),
142 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700143 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700144 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700145 verify_object_mode_(kHeapVerificationNotPermitted),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700146 gc_disable_count_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700147 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800148 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800149 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700150 }
151
Ian Rogers1d54e732013-05-02 21:10:01 -0700152 live_bitmap_.reset(new accounting::HeapBitmap(this));
153 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700154
Ian Rogers30fab402012-01-23 15:43:46 -0800155 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700156 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800157 if (!image_file_name.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700158 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700159 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700160 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800161 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
162 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800163 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
164 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700165 if (oat_file_end_addr > requested_alloc_space_begin) {
166 requested_alloc_space_begin =
167 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
168 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700169 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700170 }
171
Mathieu Chartier590fee92013-09-13 13:46:47 -0700172 const char* name = Runtime::Current()->IsZygote() ? "zygote space" : "alloc space";
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700173 if (!kUseRosAlloc) {
174 non_moving_space_ = space::DlMallocSpace::Create(name, initial_size, growth_limit, capacity,
175 requested_alloc_space_begin);
176 } else {
177 non_moving_space_ = space::RosAllocSpace::Create(name, initial_size, growth_limit, capacity,
178 requested_alloc_space_begin);
179 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700180 if (kMovingCollector) {
181 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
182 // TODO: Having 3+ spaces as big as the large heap size can cause virtual memory fragmentation
183 // issues.
184 const size_t bump_pointer_space_size = std::min(non_moving_space_->Capacity(), 128 * MB);
185 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space",
186 bump_pointer_space_size, nullptr);
187 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
188 AddSpace(bump_pointer_space_);
189 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2", bump_pointer_space_size,
190 nullptr);
191 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
192 AddSpace(temp_space_);
193 }
194
195 CHECK(non_moving_space_ != NULL) << "Failed to create non-moving space";
196 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
197 AddSpace(non_moving_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700198
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700199 // Allocate the large object space.
200 const bool kUseFreeListSpaceForLOS = false;
201 if (kUseFreeListSpaceForLOS) {
202 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
203 } else {
204 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
205 }
206 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700207 AddSpace(large_object_space_);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700208
Ian Rogers1d54e732013-05-02 21:10:01 -0700209 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700210 CHECK(!continuous_spaces_.empty());
211 // Relies on the spaces being sorted.
Ian Rogers1d54e732013-05-02 21:10:01 -0700212 byte* heap_begin = continuous_spaces_.front()->Begin();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700213 byte* heap_end = continuous_spaces_.back()->Limit();
214 size_t heap_capacity = heap_end - heap_begin;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700215
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800216 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700217 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700218 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700219
Mathieu Chartier590fee92013-09-13 13:46:47 -0700220 // Card cache for now since it makes it easier for us to update the references to the copying
221 // spaces.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700222 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier590fee92013-09-13 13:46:47 -0700223 new accounting::ModUnionTableCardCache("Image mod-union table", this, GetImageSpace());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700224 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
225 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700226
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700227 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700228 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700229
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800230 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700231 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700232 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
233 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
234 max_allocation_stack_size_));
235 live_stack_.reset(accounting::ObjectStack::Create("live stack",
236 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700237
Mathieu Chartier65db8802012-11-20 12:36:46 -0800238 // It's still too early to take a lock because there are no threads yet, but we can create locks
239 // now. We don't create it earlier to make it clear that you can't use locks during heap
240 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700241 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700242 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
243 *gc_complete_lock_));
Ian Rogers1d54e732013-05-02 21:10:01 -0700244 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800245 last_gc_size_ = GetBytesAllocated();
246
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700247 if (ignore_max_footprint_) {
248 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700249 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700250 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700251 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700252
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800253 // Create our garbage collectors.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700254 if (!kMovingCollector) {
255 for (size_t i = 0; i < 2; ++i) {
256 const bool concurrent = i != 0;
257 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
258 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
259 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
260 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800261 gc_plan_.push_back(collector::kGcTypeSticky);
262 gc_plan_.push_back(collector::kGcTypePartial);
263 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700264 } else {
265 semi_space_collector_ = new collector::SemiSpace(this);
266 garbage_collectors_.push_back(semi_space_collector_);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800267 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700268 }
269
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700270 if (running_on_valgrind_) {
Ian Rogersfa824272013-11-05 16:12:57 -0800271 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700272 }
273
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800274 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800275 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700276 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700277}
278
Mathieu Chartier590fee92013-09-13 13:46:47 -0700279bool Heap::IsCompilingBoot() const {
280 for (const auto& space : continuous_spaces_) {
281 if (space->IsImageSpace()) {
282 return false;
283 } else if (space->IsZygoteSpace()) {
284 return false;
285 }
286 }
287 return true;
288}
289
290bool Heap::HasImageSpace() const {
291 for (const auto& space : continuous_spaces_) {
292 if (space->IsImageSpace()) {
293 return true;
294 }
295 }
296 return false;
297}
298
299void Heap::IncrementDisableGC(Thread* self) {
300 // Need to do this holding the lock to prevent races where the GC is about to run / running when
301 // we attempt to disable it.
302 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
303 MutexLock mu(self, *gc_complete_lock_);
304 WaitForGcToCompleteLocked(self);
305 ++gc_disable_count_;
306}
307
308void Heap::DecrementDisableGC(Thread* self) {
309 MutexLock mu(self, *gc_complete_lock_);
310 CHECK_GE(gc_disable_count_, 0U);
311 --gc_disable_count_;
312}
313
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700314void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700315 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
316 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800317 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700318 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700319}
320
Mathieu Chartier590fee92013-09-13 13:46:47 -0700321void Heap::VisitObjects(ObjectVisitorCallback callback, void* arg) {
322 // Visit objects in bump pointer space.
323 Thread* self = Thread::Current();
324 // TODO: Use reference block.
325 std::vector<SirtRef<mirror::Object>*> saved_refs;
326 if (bump_pointer_space_ != nullptr) {
327 // Need to put all these in sirts since the callback may trigger a GC. TODO: Use a better data
328 // structure.
329 mirror::Object* obj = reinterpret_cast<mirror::Object*>(bump_pointer_space_->Begin());
330 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(
331 bump_pointer_space_->End());
332 while (obj < end) {
333 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
334 obj = space::BumpPointerSpace::GetNextObject(obj);
335 }
336 }
337 // TODO: Switch to standard begin and end to use ranged a based loop.
338 for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
339 it < end; ++it) {
340 mirror::Object* obj = *it;
341 // Objects in the allocation stack might be in a movable space.
342 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
343 }
344 GetLiveBitmap()->Walk(callback, arg);
345 for (const auto& ref : saved_refs) {
346 callback(ref->get(), arg);
347 }
348 // Need to free the sirts in reverse order they were allocated.
349 for (size_t i = saved_refs.size(); i != 0; --i) {
350 delete saved_refs[i - 1];
351 }
352}
353
354void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
355 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(), stack);
356}
357
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700358void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700359 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700360}
361
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700362static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700363 DCHECK(out_value != NULL);
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700364 jfieldID field = env->GetStaticFieldID(clz, name, "I");
365 if (field == NULL) {
366 env->ExceptionClear();
367 return false;
368 }
369 *out_value = env->GetStaticIntField(clz, field);
370 return true;
371}
372
373void Heap::ListenForProcessStateChange() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700374 VLOG(heap) << "Heap notified of process state change";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700375
376 Thread* self = Thread::Current();
377 JNIEnvExt* env = self->GetJniEnv();
378
379 if (!have_zygote_space_) {
380 return;
381 }
382
383 if (activity_thread_class_ == NULL) {
384 jclass clz = env->FindClass("android/app/ActivityThread");
385 if (clz == NULL) {
386 env->ExceptionClear();
387 LOG(WARNING) << "Could not find activity thread class in process state change";
388 return;
389 }
390 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
391 }
392
393 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
394 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
395 "currentActivityThread",
396 "()Landroid/app/ActivityThread;");
397 if (current_activity_method == NULL) {
398 env->ExceptionClear();
399 LOG(WARNING) << "Could not get method for currentActivityThread";
400 return;
401 }
402
403 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
404 if (obj == NULL) {
405 env->ExceptionClear();
406 LOG(WARNING) << "Could not get current activity";
407 return;
408 }
409 activity_thread_ = env->NewGlobalRef(obj);
410 }
411
412 if (process_state_cares_about_pause_time_.empty()) {
413 // Just attempt to do this the first time.
414 jclass clz = env->FindClass("android/app/ActivityManager");
415 if (clz == NULL) {
416 LOG(WARNING) << "Activity manager class is null";
417 return;
418 }
419 ScopedLocalRef<jclass> activity_manager(env, clz);
420 std::vector<const char*> care_about_pauses;
421 care_about_pauses.push_back("PROCESS_STATE_TOP");
422 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
423 // Attempt to read the constants and classify them as whether or not we care about pause times.
424 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
425 int process_state = 0;
426 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
427 process_state_cares_about_pause_time_.insert(process_state);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700428 VLOG(heap) << "Adding process state " << process_state
429 << " to set of states which care about pause time";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700430 }
431 }
432 }
433
434 if (application_thread_class_ == NULL) {
435 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
436 if (clz == NULL) {
437 env->ExceptionClear();
438 LOG(WARNING) << "Could not get application thread class";
439 return;
440 }
441 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
442 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
443 if (last_process_state_id_ == NULL) {
444 env->ExceptionClear();
445 LOG(WARNING) << "Could not get last process state member";
446 return;
447 }
448 }
449
450 if (application_thread_class_ != NULL && application_thread_ == NULL) {
451 jmethodID get_application_thread =
452 env->GetMethodID(activity_thread_class_, "getApplicationThread",
453 "()Landroid/app/ActivityThread$ApplicationThread;");
454 if (get_application_thread == NULL) {
455 LOG(WARNING) << "Could not get method ID for get application thread";
456 return;
457 }
458
459 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
460 if (obj == NULL) {
461 LOG(WARNING) << "Could not get application thread";
462 return;
463 }
464
465 application_thread_ = env->NewGlobalRef(obj);
466 }
467
468 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
469 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
470 env->ExceptionClear();
471
472 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
473 process_state_cares_about_pause_time_.end();
474
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700475 VLOG(heap) << "New process state " << process_state
476 << " care about pauses " << care_about_pause_times_;
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700477 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700478}
479
Mathieu Chartier590fee92013-09-13 13:46:47 -0700480void Heap::AddSpace(space::Space* space) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700481 DCHECK(space != NULL);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700482 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
483 if (space->IsContinuousSpace()) {
484 DCHECK(!space->IsDiscontinuousSpace());
485 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
486 // Continuous spaces don't necessarily have bitmaps.
487 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
488 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
489 if (live_bitmap != nullptr) {
490 DCHECK(mark_bitmap != nullptr);
491 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
492 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700493 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700494
495 continuous_spaces_.push_back(continuous_space);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700496 if (continuous_space->IsMallocSpace()) {
497 non_moving_space_ = continuous_space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700498 }
499
500 // Ensure that spaces remain sorted in increasing order of start address.
501 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
502 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
503 return a->Begin() < b->Begin();
504 });
505 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
506 // avoid redundant marking.
507 bool seen_zygote = false, seen_alloc = false;
508 for (const auto& space : continuous_spaces_) {
509 if (space->IsImageSpace()) {
510 CHECK(!seen_zygote);
511 CHECK(!seen_alloc);
512 } else if (space->IsZygoteSpace()) {
513 CHECK(!seen_alloc);
514 seen_zygote = true;
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700515 } else if (space->IsMallocSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700516 seen_alloc = true;
517 }
518 }
519 } else {
520 DCHECK(space->IsDiscontinuousSpace());
521 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
522 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
523 live_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
524 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
525 mark_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
526 discontinuous_spaces_.push_back(discontinuous_space);
527 }
528 if (space->IsAllocSpace()) {
529 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700530 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800531}
532
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700533void Heap::RegisterGCAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700534 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700535 gc_memory_overhead_.fetch_add(bytes);
536 }
537}
538
539void Heap::RegisterGCDeAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700540 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700541 gc_memory_overhead_.fetch_sub(bytes);
542 }
543}
544
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700545void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700546 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700547 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700548 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800549
550 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800551 uint64_t total_paused_time = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700552 for (const auto& collector : garbage_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800553 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800554 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700555 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800556 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700557 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800558 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
559 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
560 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700561 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
562 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
563 << collector->GetName() << " freed: " << freed_objects
564 << " objects with total size " << PrettySize(freed_bytes) << "\n"
565 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
566 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800567 total_duration += total_ns;
568 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700569 }
570 }
571 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700572 size_t total_objects_allocated = GetObjectsAllocatedEver();
573 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700574 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700575 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700576 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
577 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700578 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700579 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700580 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700581 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700582 os << "Total number of allocations: " << total_objects_allocated << "\n";
583 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700584 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700585 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
586 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
587 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700588 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700589 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
590 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700591 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700592}
593
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800594Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700595 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700596 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700597 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700598 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700599 STLDeleteElements(&garbage_collectors_);
600 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700601 allocation_stack_->Reset();
602 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700603 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700604 STLDeleteElements(&continuous_spaces_);
605 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606 delete gc_complete_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700607 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700608}
609
Ian Rogers1d54e732013-05-02 21:10:01 -0700610space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
611 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700612 for (const auto& space : continuous_spaces_) {
613 if (space->Contains(obj)) {
614 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700615 }
616 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700617 if (!fail_ok) {
618 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
619 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700620 return NULL;
621}
622
Ian Rogers1d54e732013-05-02 21:10:01 -0700623space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
624 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700625 for (const auto& space : discontinuous_spaces_) {
626 if (space->Contains(obj)) {
627 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700628 }
629 }
630 if (!fail_ok) {
631 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
632 }
633 return NULL;
634}
635
636space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
637 space::Space* result = FindContinuousSpaceFromObject(obj, true);
638 if (result != NULL) {
639 return result;
640 }
641 return FindDiscontinuousSpaceFromObject(obj, true);
642}
643
Mathieu Chartier39e32612013-11-12 16:28:05 -0800644struct SoftReferenceArgs {
645 RootVisitor* is_marked_callback_;
646 RootVisitor* recursive_mark_callback_;
647 void* arg_;
648};
649
650mirror::Object* Heap::PreserveSoftReferenceCallback(mirror::Object* obj, void* arg) {
651 SoftReferenceArgs* args = reinterpret_cast<SoftReferenceArgs*>(arg);
652 // TODO: Not preserve all soft references.
653 return args->recursive_mark_callback_(obj, args->arg_);
654}
655
656// Process reference class instances and schedule finalizations.
657void Heap::ProcessReferences(TimingLogger& timings, bool clear_soft,
658 RootVisitor* is_marked_callback,
659 RootVisitor* recursive_mark_object_callback, void* arg) {
660 // Unless we are in the zygote or required to clear soft references with white references,
661 // preserve some white referents.
662 if (!clear_soft && !Runtime::Current()->IsZygote()) {
663 SoftReferenceArgs soft_reference_args;
664 soft_reference_args.is_marked_callback_ = is_marked_callback;
665 soft_reference_args.recursive_mark_callback_ = recursive_mark_object_callback;
666 soft_reference_args.arg_ = arg;
667 soft_reference_queue_.PreserveSomeSoftReferences(&PreserveSoftReferenceCallback,
668 &soft_reference_args);
669 }
670 timings.StartSplit("ProcessReferences");
671 // Clear all remaining soft and weak references with white referents.
672 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
673 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
674 timings.EndSplit();
675 // Preserve all white objects with finalize methods and schedule them for finalization.
676 timings.StartSplit("EnqueueFinalizerReferences");
677 finalizer_reference_queue_.EnqueueFinalizerReferences(cleared_references_, is_marked_callback,
678 recursive_mark_object_callback, arg);
679 timings.EndSplit();
680 timings.StartSplit("ProcessReferences");
681 // Clear all f-reachable soft and weak references with white referents.
682 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
683 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
684 // Clear all phantom references with white referents.
685 phantom_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
686 // At this point all reference queues other than the cleared references should be empty.
687 DCHECK(soft_reference_queue_.IsEmpty());
688 DCHECK(weak_reference_queue_.IsEmpty());
689 DCHECK(finalizer_reference_queue_.IsEmpty());
690 DCHECK(phantom_reference_queue_.IsEmpty());
691 timings.EndSplit();
692}
693
694bool Heap::IsEnqueued(mirror::Object* ref) const {
695 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
696 // will always be non-null.
697 return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
698}
699
700bool Heap::IsEnqueuable(const mirror::Object* ref) const {
701 DCHECK(ref != nullptr);
702 const mirror::Object* queue =
703 ref->GetFieldObject<mirror::Object*>(GetReferenceQueueOffset(), false);
704 const mirror::Object* queue_next =
705 ref->GetFieldObject<mirror::Object*>(GetReferenceQueueNextOffset(), false);
706 return queue != nullptr && queue_next == nullptr;
707}
708
709// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
710// marked, put it on the appropriate list in the heap for later processing.
711void Heap::DelayReferenceReferent(mirror::Class* klass, mirror::Object* obj,
712 RootVisitor mark_visitor, void* arg) {
713 DCHECK(klass != nullptr);
714 DCHECK(klass->IsReferenceClass());
715 DCHECK(obj != nullptr);
716 mirror::Object* referent = GetReferenceReferent(obj);
717 if (referent != nullptr) {
718 mirror::Object* forward_address = mark_visitor(referent, arg);
719 // Null means that the object is not currently marked.
720 if (forward_address == nullptr) {
721 Thread* self = Thread::Current();
722 // TODO: Remove these locks, and use atomic stacks for storing references?
723 // We need to check that the references haven't already been enqueued since we can end up
724 // scanning the same reference multiple times due to dirty cards.
725 if (klass->IsSoftReferenceClass()) {
726 soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
727 } else if (klass->IsWeakReferenceClass()) {
728 weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
729 } else if (klass->IsFinalizerReferenceClass()) {
730 finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
731 } else if (klass->IsPhantomReferenceClass()) {
732 phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
733 } else {
734 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
735 << klass->GetAccessFlags();
736 }
737 } else if (referent != forward_address) {
738 // Referent is already marked and we need to update it.
739 SetReferenceReferent(obj, forward_address);
740 }
741 }
742}
743
Ian Rogers1d54e732013-05-02 21:10:01 -0700744space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700745 for (const auto& space : continuous_spaces_) {
746 if (space->IsImageSpace()) {
747 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700748 }
749 }
750 return NULL;
751}
752
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700753static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700754 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700755 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700756 size_t chunk_free_bytes = chunk_size - used_bytes;
757 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
758 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700759 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700760}
761
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700762void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
763 std::ostringstream oss;
764 int64_t total_bytes_free = GetFreeMemory();
765 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
766 << " free bytes";
767 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
768 if (!large_object_allocation && total_bytes_free >= byte_count) {
769 size_t max_contiguous_allocation = 0;
770 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700771 if (space->IsMallocSpace()) {
772 // To allow the Walk/InspectAll() to exclusively-lock the mutator
773 // lock, temporarily release the shared access to the mutator
774 // lock here by transitioning to the suspended state.
775 Locks::mutator_lock_->AssertSharedHeld(self);
776 self->TransitionFromRunnableToSuspended(kSuspended);
777 space->AsMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
778 self->TransitionFromSuspendedToRunnable();
779 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700780 }
781 }
782 oss << "; failed due to fragmentation (largest possible contiguous allocation "
783 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700784 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700785 self->ThrowOutOfMemoryError(oss.str().c_str());
786}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700787
Mathieu Chartier590fee92013-09-13 13:46:47 -0700788void Heap::Trim() {
789 uint64_t start_ns = NanoTime();
790 // Trim the managed spaces.
791 uint64_t total_alloc_space_allocated = 0;
792 uint64_t total_alloc_space_size = 0;
793 uint64_t managed_reclaimed = 0;
794 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700795 if (space->IsMallocSpace() && !space->IsZygoteSpace()) {
796 gc::space::MallocSpace* alloc_space = space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700797 total_alloc_space_size += alloc_space->Size();
798 managed_reclaimed += alloc_space->Trim();
799 }
800 }
801 total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated() -
802 bump_pointer_space_->GetBytesAllocated();
803 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
804 static_cast<float>(total_alloc_space_size);
805 uint64_t gc_heap_end_ns = NanoTime();
806 // Trim the native heap.
807 dlmalloc_trim(0);
808 size_t native_reclaimed = 0;
809 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
810 uint64_t end_ns = NanoTime();
811 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
812 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
813 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
814 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
815 << "%.";
816}
817
818bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
819 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
820 // taking the lock.
821 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -0700822 return true;
823 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700824 return IsAligned<kObjectAlignment>(obj) && IsHeapAddress(obj);
825}
826
827bool Heap::IsHeapAddress(const mirror::Object* obj) const {
828 if (kMovingCollector && bump_pointer_space_->HasAddress(obj)) {
829 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700830 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700831 // TODO: This probably doesn't work for large objects.
832 return FindSpaceFromObject(obj, true) != nullptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700833}
834
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700835bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
836 bool search_live_stack, bool sorted) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700837 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700838 if (obj == nullptr || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700839 return false;
840 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700841 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
842 space::DiscontinuousSpace* d_space = NULL;
843 if (c_space != NULL) {
844 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700845 return true;
846 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700847 } else if (bump_pointer_space_->Contains(obj) || temp_space_->Contains(obj)) {
848 return true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700849 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700850 d_space = FindDiscontinuousSpaceFromObject(obj, true);
851 if (d_space != NULL) {
852 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700853 return true;
854 }
855 }
856 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700857 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700858 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
859 if (i > 0) {
860 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -0700861 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700862 if (search_allocation_stack) {
863 if (sorted) {
864 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
865 return true;
866 }
867 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
868 return true;
869 }
870 }
871
872 if (search_live_stack) {
873 if (sorted) {
874 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
875 return true;
876 }
877 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
878 return true;
879 }
880 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700881 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700882 // We need to check the bitmaps again since there is a race where we mark something as live and
883 // then clear the stack containing it.
884 if (c_space != NULL) {
885 if (c_space->GetLiveBitmap()->Test(obj)) {
886 return true;
887 }
888 } else {
889 d_space = FindDiscontinuousSpaceFromObject(obj, true);
890 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
891 return true;
892 }
893 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700894 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700895}
896
Ian Rogers04d7aa92013-03-16 14:29:17 -0700897void Heap::VerifyObjectImpl(const mirror::Object* obj) {
898 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700899 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700900 return;
901 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700902 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700903}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700904
Mathieu Chartier590fee92013-09-13 13:46:47 -0700905void Heap::DumpSpaces(std::ostream& stream) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700906 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700907 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
908 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700909 stream << space << " " << *space << "\n";
910 if (live_bitmap != nullptr) {
911 stream << live_bitmap << " " << *live_bitmap << "\n";
912 }
913 if (mark_bitmap != nullptr) {
914 stream << mark_bitmap << " " << *mark_bitmap << "\n";
915 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700916 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700917 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700918 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700919 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700920}
921
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800922void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700923 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
924 // Ignore early dawn of the universe verifications.
925 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800926 return;
927 }
928 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
929 mirror::Object::ClassOffset().Int32Value();
930 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
931 if (UNLIKELY(c == NULL)) {
932 LOG(FATAL) << "Null class in object: " << obj;
933 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
934 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
935 }
936 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
937 // Note: we don't use the accessors here as they have internal sanity checks
938 // that we don't want to run
939 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
940 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
941 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
942 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
943 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700944
Mathieu Chartier590fee92013-09-13 13:46:47 -0700945 if (verify_object_mode_ > kVerifyAllFast) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800946 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
947 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700948 if (!IsLiveObjectLocked(obj)) {
949 DumpSpaces();
950 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700951 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700952 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700953 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
954 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700955 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700956}
957
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800958void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700959 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700960 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700961}
962
963void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700964 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700965 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700966}
967
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700968void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700969 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700970 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700971
972 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700973 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700974 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700975 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700976
977 // TODO: Do this concurrently.
978 RuntimeStats* global_stats = Runtime::Current()->GetStats();
979 global_stats->freed_objects += freed_objects;
980 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700981 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700982}
983
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800984mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
Mathieu Chartier720ef762013-08-17 14:46:54 -0700985 size_t alloc_size, size_t* bytes_allocated) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800986 mirror::Object* ptr = nullptr;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700987 // The allocation failed. If the GC is running, block until it completes, and then retry the
988 // allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700989 collector::GcType last_gc = WaitForGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700990 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700991 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800992 ptr = TryToAllocate<true>(self, allocator, alloc_size, false, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700993 }
994
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700995 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800996 for (collector::GcType gc_type : gc_plan_) {
997 if (ptr != nullptr) {
998 break;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700999 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001000 // Attempt to run the collector, if we succeed, re-try the allocation.
1001 if (CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001002 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001003 ptr = TryToAllocate<true>(self, allocator, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001004 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001005 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001006 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001007 if (ptr == nullptr) {
1008 // Try harder, growing the heap if necessary.
1009 ptr = TryToAllocate<true>(self, allocator, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001010 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001011 if (ptr == nullptr) {
1012 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1013 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1014 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1015 // OOME.
1016 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1017 << " allocation";
1018 // TODO: Run finalization, but this may cause more allocations to occur.
1019 // We don't need a WaitForGcToComplete here either.
1020 DCHECK(!gc_plan_.empty());
1021 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1022 ptr = TryToAllocate<true>(self, allocator, alloc_size, true, bytes_allocated);
1023 if (ptr == nullptr) {
1024 ThrowOutOfMemoryError(self, alloc_size, false);
1025 }
1026 }
1027 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001028}
1029
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001030void Heap::SetTargetHeapUtilization(float target) {
1031 DCHECK_GT(target, 0.0f); // asserted in Java code
1032 DCHECK_LT(target, 1.0f);
1033 target_utilization_ = target;
1034}
1035
Ian Rogers1d54e732013-05-02 21:10:01 -07001036size_t Heap::GetObjectsAllocated() const {
1037 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001038 for (space::AllocSpace* space : alloc_spaces_) {
1039 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001040 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001041 return total;
1042}
1043
Ian Rogers1d54e732013-05-02 21:10:01 -07001044size_t Heap::GetObjectsAllocatedEver() const {
1045 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001046 for (space::AllocSpace* space : alloc_spaces_) {
1047 total += space->GetTotalObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001048 }
1049 return total;
1050}
1051
1052size_t Heap::GetBytesAllocatedEver() const {
1053 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001054 for (space::AllocSpace* space : alloc_spaces_) {
1055 total += space->GetTotalBytesAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001056 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001057 return total;
1058}
1059
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001060class InstanceCounter {
1061 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001062 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001063 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001064 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001065 }
1066
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001067 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001068 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001069 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001070 if (use_is_assignable_from_) {
1071 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
1072 ++counts_[i];
1073 }
1074 } else {
1075 if (instance_class == classes_[i]) {
1076 ++counts_[i];
1077 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001078 }
1079 }
1080 }
1081
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001082 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001083 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001084 bool use_is_assignable_from_;
1085 uint64_t* const counts_;
1086
1087 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001088};
1089
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001090void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001091 uint64_t* counts) {
1092 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1093 // is empty, so the live bitmap is the only place we need to look.
1094 Thread* self = Thread::Current();
1095 self->TransitionFromRunnableToSuspended(kNative);
1096 CollectGarbage(false);
1097 self->TransitionFromSuspendedToRunnable();
1098
1099 InstanceCounter counter(classes, use_is_assignable_from, counts);
1100 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001101 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001102}
1103
Elliott Hughes3b78c942013-01-15 17:35:41 -08001104class InstanceCollector {
1105 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001106 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001107 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1108 : class_(c), max_count_(max_count), instances_(instances) {
1109 }
1110
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001111 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1112 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001113 if (instance_class == class_) {
1114 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001115 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001116 }
1117 }
1118 }
1119
1120 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001121 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001122 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001123 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001124
1125 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1126};
1127
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001128void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1129 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001130 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1131 // is empty, so the live bitmap is the only place we need to look.
1132 Thread* self = Thread::Current();
1133 self->TransitionFromRunnableToSuspended(kNative);
1134 CollectGarbage(false);
1135 self->TransitionFromSuspendedToRunnable();
1136
1137 InstanceCollector collector(c, max_count, instances);
1138 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1139 GetLiveBitmap()->Visit(collector);
1140}
1141
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001142class ReferringObjectsFinder {
1143 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001144 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1145 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001146 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1147 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1148 }
1149
1150 // For bitmap Visit.
1151 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1152 // annotalysis on visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001153 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1154 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(o), *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001155 }
1156
1157 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001158 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001159 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001160 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001161 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001162 }
1163 }
1164
1165 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001166 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001167 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001168 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001169
1170 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1171};
1172
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001173void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1174 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001175 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1176 // is empty, so the live bitmap is the only place we need to look.
1177 Thread* self = Thread::Current();
1178 self->TransitionFromRunnableToSuspended(kNative);
1179 CollectGarbage(false);
1180 self->TransitionFromSuspendedToRunnable();
1181
1182 ReferringObjectsFinder finder(o, max_count, referring_objects);
1183 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1184 GetLiveBitmap()->Visit(finder);
1185}
1186
Ian Rogers30fab402012-01-23 15:43:46 -08001187void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001188 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1189 // last GC will not have necessarily been cleared.
Ian Rogers1d54e732013-05-02 21:10:01 -07001190 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001191}
1192
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001193void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001194 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -07001195 Thread* self = Thread::Current();
1196 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001197 // Try to see if we have any Zygote spaces.
1198 if (have_zygote_space_) {
1199 return;
1200 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001201 VLOG(heap) << "Starting PreZygoteFork";
1202 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1203 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
1204 // Trim the pages at the end of the non moving space.
1205 non_moving_space_->Trim();
1206 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1207 // Create a new bump pointer space which we will compact into.
1208 if (semi_space_collector_ != nullptr) {
1209 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1210 non_moving_space_->Limit());
1211 // Compact the bump pointer space to a new zygote bump pointer space.
1212 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1213 Compact(&target_space, bump_pointer_space_);
1214 CHECK_EQ(temp_space_->GetBytesAllocated(), 0U);
1215 total_objects_freed_ever_ += semi_space_collector_->GetFreedObjects();
1216 total_bytes_freed_ever_ += semi_space_collector_->GetFreedBytes();
1217 // Update the end and write out image.
1218 non_moving_space_->SetEnd(target_space.End());
1219 non_moving_space_->SetLimit(target_space.Limit());
1220 accounting::SpaceBitmap* bitmap = non_moving_space_->GetLiveBitmap();
1221 // Record the allocations in the bitmap.
1222 VLOG(heap) << "Recording zygote allocations";
1223 mirror::Object* obj = reinterpret_cast<mirror::Object*>(target_space.Begin());
1224 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(target_space.End());
1225 while (obj < end) {
1226 bitmap->Set(obj);
1227 obj = space::BumpPointerSpace::GetNextObject(obj);
1228 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001229 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001230 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
1231 // the remaining available heap memory.
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001232 space::MallocSpace* zygote_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001233 non_moving_space_ = zygote_space->CreateZygoteSpace("alloc space");
1234 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -07001235 // Change the GC retention policy of the zygote space to only collect when full.
1236 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001237 AddSpace(non_moving_space_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001238 have_zygote_space_ = true;
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001239 zygote_space->InvalidateAllocator();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001240 // Create the zygote space mod union table.
1241 accounting::ModUnionTable* mod_union_table =
1242 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1243 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1244 AddModUnionTable(mod_union_table);
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001245 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001246 for (const auto& collector : garbage_collectors_) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001247 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001248 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001249}
1250
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001251void Heap::FlushAllocStack() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001252 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001253 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001254 allocation_stack_->Reset();
1255}
1256
Ian Rogers1d54e732013-05-02 21:10:01 -07001257void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1258 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001259 mirror::Object** limit = stack->End();
1260 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1261 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001262 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001263 if (LIKELY(bitmap->HasAddress(obj))) {
1264 bitmap->Set(obj);
1265 } else {
1266 large_objects->Set(obj);
1267 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001268 }
1269}
1270
Mathieu Chartier590fee92013-09-13 13:46:47 -07001271const char* PrettyCause(GcCause cause) {
1272 switch (cause) {
1273 case kGcCauseForAlloc: return "Alloc";
1274 case kGcCauseBackground: return "Background";
1275 case kGcCauseExplicit: return "Explicit";
1276 default:
1277 LOG(FATAL) << "Unreachable";
1278 }
1279 return "";
1280}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001281
Mathieu Chartier590fee92013-09-13 13:46:47 -07001282void Heap::SwapSemiSpaces() {
1283 // Swap the spaces so we allocate into the space which we just evacuated.
1284 std::swap(bump_pointer_space_, temp_space_);
1285}
1286
1287void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
1288 space::ContinuousMemMapAllocSpace* source_space) {
1289 CHECK(kMovingCollector);
1290 CHECK_NE(target_space, source_space) << "In-place compaction unsupported";
1291 if (target_space != source_space) {
1292 semi_space_collector_->SetFromSpace(source_space);
1293 semi_space_collector_->SetToSpace(target_space);
1294 semi_space_collector_->Run(false);
1295 }
1296}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001297
Ian Rogers1d54e732013-05-02 21:10:01 -07001298collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1299 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001300 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001301 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001302 // If the heap can't run the GC, silently fail and return that no GC was run.
1303 switch (gc_type) {
1304 case collector::kGcTypeSticky: {
1305 const size_t alloc_space_size = non_moving_space_->Size();
1306 if (alloc_space_size < min_alloc_space_size_for_sticky_gc_ ||
1307 non_moving_space_->Capacity() - alloc_space_size < min_remaining_space_for_sticky_gc_) {
1308 return collector::kGcTypeNone;
1309 }
1310 break;
1311 }
1312 case collector::kGcTypePartial: {
1313 if (!have_zygote_space_) {
1314 return collector::kGcTypeNone;
1315 }
1316 break;
1317 }
1318 default: {
1319 // Other GC types don't have any special cases which makes them not runnable. The main case
1320 // here is full GC.
1321 }
1322 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001323 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001324 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001325 if (self->IsHandlingStackOverflow()) {
1326 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1327 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001328 {
1329 gc_complete_lock_->AssertNotHeld(self);
1330 MutexLock mu(self, *gc_complete_lock_);
1331 // Ensure there is only one GC at a time.
1332 WaitForGcToCompleteLocked(self);
1333 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1334 // Not doing at the moment to ensure soft references are cleared.
1335 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
1336 if (gc_disable_count_ != 0) {
1337 LOG(WARNING) << "Skipping GC due to disable count " << gc_disable_count_;
1338 return collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001339 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001340 is_gc_running_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001341 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001342 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
1343 ++runtime->GetStats()->gc_for_alloc_count;
1344 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001345 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001346 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001347 uint64_t gc_start_size = GetBytesAllocated();
1348 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001349 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001350 // Back to back GCs can cause 0 ms of wait time in between GC invocations.
1351 if (LIKELY(ms_delta != 0)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001352 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001353 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1354 }
1355
Ian Rogers1d54e732013-05-02 21:10:01 -07001356 DCHECK_LT(gc_type, collector::kGcTypeMax);
1357 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001358
Mathieu Chartier590fee92013-09-13 13:46:47 -07001359 collector::GarbageCollector* collector = nullptr;
1360 if (kMovingCollector) {
1361 gc_type = semi_space_collector_->GetGcType();
1362 CHECK_EQ(temp_space_->GetObjectsAllocated(), 0U);
1363 semi_space_collector_->SetFromSpace(bump_pointer_space_);
1364 semi_space_collector_->SetToSpace(temp_space_);
1365 mprotect(temp_space_->Begin(), temp_space_->Capacity(), PROT_READ | PROT_WRITE);
1366 }
1367 for (const auto& cur_collector : garbage_collectors_) {
1368 if (cur_collector->IsConcurrent() == concurrent_gc_ &&
1369 cur_collector->GetGcType() == gc_type) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001370 collector = cur_collector;
1371 break;
1372 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001373 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001374 if (kMovingCollector) {
1375 gc_type = collector::kGcTypeFull;
1376 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001377 CHECK(collector != NULL)
1378 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1379 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001380
Mathieu Chartier590fee92013-09-13 13:46:47 -07001381 ATRACE_BEGIN(StringPrintf("%s %s GC", PrettyCause(gc_cause), collector->GetName()).c_str());
1382
1383 collector->Run(clear_soft_references);
Ian Rogers1d54e732013-05-02 21:10:01 -07001384 total_objects_freed_ever_ += collector->GetFreedObjects();
1385 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001386
Mathieu Chartier39e32612013-11-12 16:28:05 -08001387 // Enqueue cleared references.
1388 EnqueueClearedReferences();
1389
Mathieu Chartier590fee92013-09-13 13:46:47 -07001390 // Grow the heap so that we know when to perform the next GC.
1391 GrowForUtilization(gc_type, collector->GetDurationNs());
1392
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001393 if (care_about_pause_times_) {
1394 const size_t duration = collector->GetDurationNs();
1395 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1396 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001397 bool was_slow = duration > long_gc_log_threshold_ ||
1398 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001399 if (!was_slow) {
1400 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001401 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001402 }
1403 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001404 if (was_slow) {
1405 const size_t percent_free = GetPercentFree();
1406 const size_t current_heap_size = GetBytesAllocated();
1407 const size_t total_memory = GetTotalMemory();
1408 std::ostringstream pause_string;
1409 for (size_t i = 0; i < pauses.size(); ++i) {
1410 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1411 << ((i != pauses.size() - 1) ? ", " : "");
1412 }
1413 LOG(INFO) << gc_cause << " " << collector->GetName()
1414 << " GC freed " << collector->GetFreedObjects() << "("
1415 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1416 << collector->GetFreedLargeObjects() << "("
1417 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1418 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1419 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1420 << " total " << PrettyDuration((duration / 1000) * 1000);
1421 if (VLOG_IS_ON(heap)) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001422 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001423 }
1424 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001425 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001426
Ian Rogers15bf2d32012-08-28 17:33:04 -07001427 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001428 MutexLock mu(self, *gc_complete_lock_);
1429 is_gc_running_ = false;
1430 last_gc_type_ = gc_type;
1431 // Wake anyone who may have been waiting for the GC to complete.
1432 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001433 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001434
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001435 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001436
1437 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001438 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001439 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001440}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001441
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001442static mirror::Object* RootMatchesObjectVisitor(mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001443 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001444 if (root == obj) {
1445 LOG(INFO) << "Object " << obj << " is a root";
1446 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001447 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001448}
1449
1450class ScanVisitor {
1451 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001452 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001453 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001454 }
1455};
1456
Ian Rogers1d54e732013-05-02 21:10:01 -07001457// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001458class VerifyReferenceVisitor {
1459 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001460 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001461 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001462 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001463
1464 bool Failed() const {
1465 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001466 }
1467
1468 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001469 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001470 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1471 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001472 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001473 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001474 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1475 accounting::CardTable* card_table = heap_->GetCardTable();
1476 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1477 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001478 if (!failed_) {
1479 // Print message on only on first failure to prevent spam.
1480 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1481 failed_ = true;
1482 }
1483 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001484 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001485 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1486 << offset << "\n card value = " << static_cast<int>(*card_addr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001487 if (heap_->IsValidObjectAddress(obj->GetClass())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001488 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1489 } else {
1490 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
1491 }
1492
1493 // Attmept to find the class inside of the recently freed objects.
1494 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001495 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
1496 space::MallocSpace* space = ref_space->AsMallocSpace();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001497 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1498 if (ref_class != nullptr) {
1499 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1500 << PrettyClass(ref_class);
1501 } else {
1502 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
1503 }
1504 }
1505
Mathieu Chartier590fee92013-09-13 13:46:47 -07001506 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001507 ref->GetClass()->IsClass()) {
1508 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1509 } else {
1510 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1511 << ") is not a valid heap address";
1512 }
1513
Ian Rogers1d54e732013-05-02 21:10:01 -07001514 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1515 void* cover_begin = card_table->AddrFromCard(card_addr);
1516 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1517 accounting::CardTable::kCardSize);
1518 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1519 << "-" << cover_end;
1520 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001521
Ian Rogers1d54e732013-05-02 21:10:01 -07001522 // Print out how the object is live.
1523 if (bitmap != NULL && bitmap->Test(obj)) {
1524 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1525 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001526 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001527 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1528 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001529 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001530 LOG(ERROR) << "Object " << obj << " found in live stack";
1531 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001532 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1533 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1534 }
1535 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1536 LOG(ERROR) << "Ref " << ref << " found in live stack";
1537 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001538 // Attempt to see if the card table missed the reference.
1539 ScanVisitor scan_visitor;
1540 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1541 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001542 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001543
1544 // Search to see if any of the roots reference our object.
1545 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1546 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1547
1548 // Search to see if any of the roots reference our reference.
1549 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1550 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1551 } else {
1552 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001553 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001554 }
1555 }
1556
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001557 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001558 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001559 }
1560
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001561 static mirror::Object* VerifyRoots(mirror::Object* root, void* arg) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001562 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001563 (*visitor)(nullptr, root, MemberOffset(0), true);
1564 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001565 }
1566
1567 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001568 Heap* const heap_;
1569 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001570};
1571
Ian Rogers1d54e732013-05-02 21:10:01 -07001572// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001573class VerifyObjectVisitor {
1574 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001575 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001576
Mathieu Chartier590fee92013-09-13 13:46:47 -07001577 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001578 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001579 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1580 // be live or else how did we find it in the live bitmap?
1581 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001582 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001583 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
1584 if (obj->GetClass()->IsReferenceClass()) {
1585 visitor(obj, heap_->GetReferenceReferent(obj), MemberOffset(0), false);
1586 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001587 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001588 }
1589
Mathieu Chartier590fee92013-09-13 13:46:47 -07001590 static void VisitCallback(mirror::Object* obj, void* arg)
1591 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1592 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
1593 visitor->operator()(obj);
1594 }
1595
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001596 bool Failed() const {
1597 return failed_;
1598 }
1599
1600 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001601 Heap* const heap_;
1602 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001603};
1604
1605// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001606bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001607 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001608 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001609 allocation_stack_->Sort();
1610 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001611 VerifyObjectVisitor visitor(this);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001612 // Verify objects in the allocation stack since these will be objects which were:
1613 // 1. Allocated prior to the GC (pre GC verification).
1614 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001615 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001616 // pointing to dead objects if they are not reachable.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001617 VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
1618 // Verify the roots:
1619 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001620 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001621 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001622 for (const auto& table_pair : mod_union_tables_) {
1623 accounting::ModUnionTable* mod_union_table = table_pair.second;
1624 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
1625 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001626 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001627 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001628 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001629 return true;
1630}
1631
1632class VerifyReferenceCardVisitor {
1633 public:
1634 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1635 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1636 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001637 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001638 }
1639
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001640 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1641 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001642 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1643 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001644 // Filter out class references since changing an object's class does not mark the card as dirty.
1645 // Also handles large objects, since the only reference they hold is a class reference.
1646 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001647 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001648 // If the object is not dirty and it is referencing something in the live stack other than
1649 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001650 if (!card_table->AddrIsInCardTable(obj)) {
1651 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1652 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001653 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001654 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1655 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001656 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001657 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1658 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001659 LOG(ERROR) << "Object " << obj << " found in live stack";
1660 }
1661 if (heap_->GetLiveBitmap()->Test(obj)) {
1662 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1663 }
1664 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1665 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1666
1667 // Print which field of the object is dead.
1668 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001669 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001670 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001671 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1672 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001673 CHECK(fields != NULL);
1674 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001675 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001676 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1677 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1678 << PrettyField(cur);
1679 break;
1680 }
1681 }
1682 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001683 const mirror::ObjectArray<mirror::Object>* object_array =
1684 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001685 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1686 if (object_array->Get(i) == ref) {
1687 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1688 }
1689 }
1690 }
1691
1692 *failed_ = true;
1693 }
1694 }
1695 }
1696 }
1697
1698 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001699 Heap* const heap_;
1700 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001701};
1702
1703class VerifyLiveStackReferences {
1704 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001705 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001706 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001707 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001708
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001709 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001710 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1711 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001712 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001713 }
1714
1715 bool Failed() const {
1716 return failed_;
1717 }
1718
1719 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001720 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001721 bool failed_;
1722};
1723
1724bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001725 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001726
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001727 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001728 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001729 VerifyLiveStackReferences visitor(this);
1730 GetLiveBitmap()->Visit(visitor);
1731
1732 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001733 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001734 visitor(*it);
1735 }
1736
1737 if (visitor.Failed()) {
1738 DumpSpaces();
1739 return false;
1740 }
1741 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001742}
1743
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001744void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001745 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001746}
1747
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001748accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
1749 auto it = mod_union_tables_.find(space);
1750 if (it == mod_union_tables_.end()) {
1751 return nullptr;
1752 }
1753 return it->second;
1754}
1755
Ian Rogers5fe9af72013-11-14 00:17:20 -08001756void Heap::ProcessCards(TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001757 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001758 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001759 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
1760 if (table != nullptr) {
1761 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
1762 "ImageModUnionClearCards";
Ian Rogers5fe9af72013-11-14 00:17:20 -08001763 TimingLogger::ScopedSplit split(name, &timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001764 table->ClearCards();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001765 } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001766 TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001767 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1768 // were dirty before the GC started.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001769 // TODO: Don't need to use atomic.
1770 // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
1771 // roots and then we scan / update mod union tables after. We will always scan either card.//
1772 // If we end up with the non aged card, we scan it it in the pause.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001773 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001774 }
1775 }
1776}
1777
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001778static mirror::Object* IdentityCallback(mirror::Object* obj, void*) {
1779 return obj;
1780}
1781
Ian Rogers1d54e732013-05-02 21:10:01 -07001782void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001783 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1784 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001785
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001786 if (verify_pre_gc_heap_) {
1787 thread_list->SuspendAll();
1788 {
1789 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1790 if (!VerifyHeapReferences()) {
1791 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1792 }
1793 }
1794 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001795 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001796
1797 // Check that all objects which reference things in the live stack are on dirty cards.
1798 if (verify_missing_card_marks_) {
1799 thread_list->SuspendAll();
1800 {
1801 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1802 SwapStacks();
1803 // Sort the live stack so that we can quickly binary search it later.
1804 if (!VerifyMissingCardMarks()) {
1805 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1806 }
1807 SwapStacks();
1808 }
1809 thread_list->ResumeAll();
1810 }
1811
1812 if (verify_mod_union_table_) {
1813 thread_list->SuspendAll();
1814 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001815 for (const auto& table_pair : mod_union_tables_) {
1816 accounting::ModUnionTable* mod_union_table = table_pair.second;
1817 mod_union_table->UpdateAndMarkReferences(IdentityCallback, nullptr);
1818 mod_union_table->Verify();
1819 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001820 thread_list->ResumeAll();
1821 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001822}
1823
Ian Rogers1d54e732013-05-02 21:10:01 -07001824void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001825 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1826 // reachable objects.
1827 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001828 Thread* self = Thread::Current();
1829 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07001830 {
1831 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1832 // Swapping bound bitmaps does nothing.
1833 gc->SwapBitmaps();
1834 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001835 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07001836 }
1837 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001838 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001839 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001840}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001841
Ian Rogers1d54e732013-05-02 21:10:01 -07001842void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001843 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001844 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001845 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001846 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001847 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001848 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001849}
1850
Mathieu Chartier590fee92013-09-13 13:46:47 -07001851collector::GcType Heap::WaitForGcToComplete(Thread* self) {
1852 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1853 MutexLock mu(self, *gc_complete_lock_);
1854 return WaitForGcToCompleteLocked(self);
1855}
1856
1857collector::GcType Heap::WaitForGcToCompleteLocked(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001858 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001859 uint64_t wait_start = NanoTime();
1860 while (is_gc_running_) {
1861 ATRACE_BEGIN("GC: Wait For Completion");
1862 // We must wait, change thread state then sleep on gc_complete_cond_;
1863 gc_complete_cond_->Wait(self);
1864 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001865 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001866 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001867 uint64_t wait_time = NanoTime() - wait_start;
1868 total_wait_time_ += wait_time;
1869 if (wait_time > long_pause_log_threshold_) {
1870 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time);
1871 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001872 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001873}
1874
Elliott Hughesc967f782012-04-16 10:23:15 -07001875void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001876 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001877 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001878 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001879}
1880
1881size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001882 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001883}
1884
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001885void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001886 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001887 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001888 << PrettySize(GetMaxMemory());
1889 max_allowed_footprint = GetMaxMemory();
1890 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001891 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001892}
1893
Mathieu Chartier590fee92013-09-13 13:46:47 -07001894bool Heap::IsMovableObject(const mirror::Object* obj) const {
1895 if (kMovingCollector) {
1896 DCHECK(!IsInTempSpace(obj));
1897 if (bump_pointer_space_->HasAddress(obj)) {
1898 return true;
1899 }
1900 }
1901 return false;
1902}
1903
1904bool Heap::IsInTempSpace(const mirror::Object* obj) const {
1905 if (temp_space_->HasAddress(obj) && !temp_space_->Contains(obj)) {
1906 return true;
1907 }
1908 return false;
1909}
1910
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001911void Heap::UpdateMaxNativeFootprint() {
1912 size_t native_size = native_bytes_allocated_;
1913 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1914 size_t target_size = native_size / GetTargetHeapUtilization();
1915 if (target_size > native_size + max_free_) {
1916 target_size = native_size + max_free_;
1917 } else if (target_size < native_size + min_free_) {
1918 target_size = native_size + min_free_;
1919 }
1920 native_footprint_gc_watermark_ = target_size;
1921 native_footprint_limit_ = 2 * target_size - native_size;
1922}
1923
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001924void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001925 // We know what our utilization is at this moment.
1926 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001927 const size_t bytes_allocated = GetBytesAllocated();
1928 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001929 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001930
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001931 size_t target_size;
1932 if (gc_type != collector::kGcTypeSticky) {
1933 // Grow the heap for non sticky GC.
1934 target_size = bytes_allocated / GetTargetHeapUtilization();
1935 if (target_size > bytes_allocated + max_free_) {
1936 target_size = bytes_allocated + max_free_;
1937 } else if (target_size < bytes_allocated + min_free_) {
1938 target_size = bytes_allocated + min_free_;
1939 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001940 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001941 next_gc_type_ = collector::kGcTypeSticky;
1942 } else {
1943 // Based on how close the current heap size is to the target size, decide
1944 // whether or not to do a partial or sticky GC next.
1945 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1946 next_gc_type_ = collector::kGcTypeSticky;
1947 } else {
1948 next_gc_type_ = collector::kGcTypePartial;
1949 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001950
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001951 // If we have freed enough memory, shrink the heap back down.
1952 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1953 target_size = bytes_allocated + max_free_;
1954 } else {
1955 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1956 }
1957 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001958
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001959 if (!ignore_max_footprint_) {
1960 SetIdealFootprint(target_size);
1961
1962 if (concurrent_gc_) {
1963 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001964 // Calculate the estimated GC duration.
1965 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1966 // Estimate how many remaining bytes we will have when we need to start the next GC.
1967 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1968 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1969 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1970 // A never going to happen situation that from the estimated allocation rate we will exceed
1971 // the applications entire footprint with the given estimated allocation rate. Schedule
1972 // another GC straight away.
1973 concurrent_start_bytes_ = bytes_allocated;
1974 } else {
1975 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1976 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1977 // right away.
1978 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1979 }
1980 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1981 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001982 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001983 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001984}
1985
jeffhaoc1160702011-10-27 15:48:45 -07001986void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001987 growth_limit_ = capacity_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001988 non_moving_space_->ClearGrowthLimit();
jeffhaoc1160702011-10-27 15:48:45 -07001989}
1990
Elliott Hughesadb460d2011-10-05 17:02:34 -07001991void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001992 MemberOffset reference_queue_offset,
1993 MemberOffset reference_queueNext_offset,
1994 MemberOffset reference_pendingNext_offset,
1995 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001996 reference_referent_offset_ = reference_referent_offset;
1997 reference_queue_offset_ = reference_queue_offset;
1998 reference_queueNext_offset_ = reference_queueNext_offset;
1999 reference_pendingNext_offset_ = reference_pendingNext_offset;
2000 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
2001 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2002 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
2003 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
2004 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
2005 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
2006}
2007
Mathieu Chartier590fee92013-09-13 13:46:47 -07002008void Heap::SetReferenceReferent(mirror::Object* reference, mirror::Object* referent) {
2009 DCHECK(reference != NULL);
2010 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2011 reference->SetFieldObject(reference_referent_offset_, referent, true);
2012}
2013
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002014mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002015 DCHECK(reference != NULL);
2016 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002017 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002018}
2019
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002020void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002021 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08002022 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08002023 ArgArray arg_array(NULL, 0);
2024 arg_array.Append(reinterpret_cast<uint32_t>(object));
2025 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07002026 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002027}
2028
Mathieu Chartier590fee92013-09-13 13:46:47 -07002029void Heap::PrintReferenceQueue(std::ostream& os, mirror::Object** queue) {
2030 os << "Refernece queue " << queue << "\n";
2031 if (queue != nullptr) {
2032 mirror::Object* list = *queue;
2033 if (list != nullptr) {
2034 mirror::Object* cur = list;
2035 do {
2036 mirror::Object* pending_next =
2037 cur->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
2038 os << "PendingNext=" << pending_next;
2039 if (cur->GetClass()->IsFinalizerReferenceClass()) {
2040 os << " Zombie=" <<
2041 cur->GetFieldObject<mirror::Object*>(finalizer_reference_zombie_offset_, false);
2042 }
2043 os << "\n";
2044 cur = pending_next;
2045 } while (cur != list);
2046 }
2047 }
2048}
2049
Mathieu Chartier39e32612013-11-12 16:28:05 -08002050void Heap::EnqueueClearedReferences() {
2051 if (!cleared_references_.IsEmpty()) {
Ian Rogers64b6d142012-10-29 16:34:15 -07002052 // When a runtime isn't started there are no reference queues to care about so ignore.
2053 if (LIKELY(Runtime::Current()->IsStarted())) {
2054 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08002055 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08002056 ArgArray arg_array(NULL, 0);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002057 arg_array.Append(reinterpret_cast<uint32_t>(cleared_references_.GetList()));
Jeff Hao5d917302013-02-27 17:57:33 -08002058 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07002059 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07002060 }
Mathieu Chartier39e32612013-11-12 16:28:05 -08002061 cleared_references_.Clear();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002062 }
2063}
2064
Ian Rogers1f539342012-10-03 21:09:42 -07002065void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07002066 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002067 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08002068 DCHECK(concurrent_gc_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002069 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2070 self->IsHandlingStackOverflow()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002071 return;
2072 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002073 // We already have a request pending, no reason to start more until we update
2074 // concurrent_start_bytes_.
2075 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers120f1c72012-09-28 17:17:10 -07002076 JNIEnv* env = self->GetJniEnv();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002077 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2078 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002079 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2080 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002081 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002082}
2083
Ian Rogers81d425b2012-09-27 16:03:43 -07002084void Heap::ConcurrentGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002085 if (Runtime::Current()->IsShuttingDown(self)) {
2086 return;
Mathieu Chartier2542d662012-06-21 17:14:11 -07002087 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002088 // Wait for any GCs currently running to finish.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002089 if (WaitForGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002090 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002091 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002092}
2093
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002094void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08002095 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
2096 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
2097 // a space it will hold its lock and can become a cause of jank.
2098 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
2099 // forking.
2100
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002101 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2102 // because that only marks object heads, so a large array looks like lots of empty space. We
2103 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2104 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2105 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2106 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08002107 uint64_t ms_time = MilliTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002108 // Don't bother trimming the alloc space if a heap trim occurred in the last two seconds.
2109 if (ms_time - last_trim_time_ms_ < 2 * 1000) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002110 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002111 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002112
2113 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002114 Runtime* runtime = Runtime::Current();
2115 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
2116 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2117 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2118 // as we don't hold the lock while requesting the trim).
2119 return;
Ian Rogerse1d490c2012-02-03 09:09:07 -08002120 }
Ian Rogers48931882013-01-22 14:35:16 -08002121
Ian Rogers1d54e732013-05-02 21:10:01 -07002122 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002123 ListenForProcessStateChange();
2124
2125 // Trim only if we do not currently care about pause times.
2126 if (!care_about_pause_times_) {
2127 JNIEnv* env = self->GetJniEnv();
2128 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2129 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2130 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2131 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2132 CHECK(!env->ExceptionCheck());
2133 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002134}
2135
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002136void Heap::RevokeThreadLocalBuffers(Thread* thread) {
2137 non_moving_space_->RevokeThreadLocalBuffers(thread);
2138}
2139
2140void Heap::RevokeAllThreadLocalBuffers() {
2141 non_moving_space_->RevokeAllThreadLocalBuffers();
2142}
2143
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002144bool Heap::IsGCRequestPending() const {
2145 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2146}
2147
Mathieu Chartier590fee92013-09-13 13:46:47 -07002148void Heap::RunFinalization(JNIEnv* env) {
2149 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
2150 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
2151 CHECK(WellKnownClasses::java_lang_System != nullptr);
2152 WellKnownClasses::java_lang_System_runFinalization =
2153 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2154 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
2155 }
2156 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2157 WellKnownClasses::java_lang_System_runFinalization);
2158}
2159
Ian Rogers1eb512d2013-10-18 15:42:20 -07002160void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002161 Thread* self = ThreadForEnv(env);
2162 if (native_need_to_run_finalization_) {
2163 RunFinalization(env);
2164 UpdateMaxNativeFootprint();
2165 native_need_to_run_finalization_ = false;
2166 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002167 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002168 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002169 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002170 collector::GcType gc_type = have_zygote_space_ ? collector::kGcTypePartial :
2171 collector::kGcTypeFull;
2172
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002173 // The second watermark is higher than the gc watermark. If you hit this it means you are
2174 // allocating native objects faster than the GC can keep up with.
2175 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002176 if (WaitForGcToComplete(self) != collector::kGcTypeNone) {
2177 // Just finished a GC, attempt to run finalizers.
2178 RunFinalization(env);
2179 CHECK(!env->ExceptionCheck());
2180 }
2181 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2182 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002183 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002184 RunFinalization(env);
2185 native_need_to_run_finalization_ = false;
2186 CHECK(!env->ExceptionCheck());
2187 }
2188 // We have just run finalizers, update the native watermark since it is very likely that
2189 // finalizers released native managed allocations.
2190 UpdateMaxNativeFootprint();
2191 } else if (!IsGCRequestPending()) {
2192 if (concurrent_gc_) {
2193 RequestConcurrentGC(self);
2194 } else {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002195 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002196 }
2197 }
2198 }
2199}
2200
Ian Rogers1eb512d2013-10-18 15:42:20 -07002201void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002202 int expected_size, new_size;
2203 do {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002204 expected_size = native_bytes_allocated_.load();
2205 new_size = expected_size - bytes;
2206 if (UNLIKELY(new_size < 0)) {
2207 ScopedObjectAccess soa(env);
2208 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2209 StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2210 "registered as allocated", bytes, expected_size).c_str());
2211 break;
2212 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002213 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002214}
2215
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002216int64_t Heap::GetTotalMemory() const {
2217 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002218 for (const auto& space : continuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002219 // Currently don't include the image space.
2220 if (!space->IsImageSpace()) {
2221 ret += space->Size();
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002222 }
2223 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002224 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002225 if (space->IsLargeObjectSpace()) {
2226 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2227 }
2228 }
2229 return ret;
2230}
2231
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002232void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2233 DCHECK(mod_union_table != nullptr);
2234 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2235}
2236
Ian Rogers1d54e732013-05-02 21:10:01 -07002237} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002238} // namespace art